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 ImplicitParams, TypeSynonymInstances, FlexibleInstances, ConstrainedClassMethods #-} -- Similar to tc024, but cross module module TcRun025_B where import Data.List( sort ) -- This class has no tyvars in its class op context -- One uses a newtype, the other a data type class C1 a where fc1 :: (?p :: String) => a; class C2 a where fc2 :: (?p :: String) => a; opc :: a instance C1 String where fc1 = ?p; instance C2 String where fc2 = ?p; opc = "x" -- This class constrains no new type variables in -- its class op context class D1 a where fd1 :: (Ord a) => [a] -> [a] class D2 a where fd2 :: (Ord a) => [a] -> [a] opd :: a instance D1 (Maybe a) where fd1 xs = sort xs instance D2 (Maybe a) where fd2 xs = sort xs opd = Nothing
ezyang/ghc
testsuite/tests/typecheck/should_run/TcRun025_B.hs
bsd-3-clause
998
0
9
406
232
131
101
23
0
{-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fwarn-duplicate-exports #-} module T2436( C(..), T(..), module T2436a, S(..) ) where import T2436a class C a where data T a instance C Int where data T Int = TInt Int data instance S Int = SInt
snoyberg/ghc
testsuite/tests/rename/should_compile/T2436.hs
bsd-3-clause
250
0
7
51
82
49
33
9
0
module T10233 where import T10233a( Constraint, Int )
urbanslug/ghc
testsuite/tests/module/T10233.hs
bsd-3-clause
54
0
5
8
15
10
5
2
0
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -ddump-splices #-} module T3600 where import T3600a $(test)
siddhanathan/ghc
testsuite/tests/th/T3600.hs
bsd-3-clause
109
0
6
14
16
10
6
5
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | Futhark prettyprinter. This module defines 'Pretty' instances -- for the AST defined in "Language.Futhark.Syntax". module Language.Futhark.Pretty ( pretty, prettyTuple, leadingOperator, IsName (..), prettyName, Annot (..), ) where import Control.Monad import Data.Array import Data.Char (chr) import Data.Functor import Data.List (intersperse) import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as M import Data.Maybe import Data.Monoid hiding (Sum) import Data.Ord import Data.Word import Futhark.Util import Futhark.Util.Pretty import Language.Futhark.Prop import Language.Futhark.Syntax import Prelude -- | A class for types that are variable names in the Futhark source -- language. This is used instead of a mere 'Pretty' instance because -- in the compiler frontend we want to print VNames differently -- depending on whether the FUTHARK_COMPILER_DEBUGGING environment -- variable is set, yet in the backend we want to always print VNames -- with the tag. To avoid erroneously using the 'Pretty' instance for -- VNames, we in fact only define it inside the modules for the core -- language (as an orphan instance). class IsName v where pprName :: v -> Doc -- | Depending on the environment variable FUTHARK_COMPILER_DEBUGGING, -- VNames are printed as either the name with an internal tag, or just -- the base name. instance IsName VName where pprName | isEnvVarAtLeast "FUTHARK_COMPILER_DEBUGGING" 1 = \(VName vn i) -> ppr vn <> text "_" <> text (show i) | otherwise = ppr . baseName instance IsName Name where pprName = ppr -- | Prettyprint a name to a string. prettyName :: IsName v => v -> String prettyName = prettyDoc 80 . pprName -- | Class for type constructors that represent annotations. Used in -- the prettyprinter to either print the original AST, or the computed -- decoration. class Annot f where -- | Extract value, if any. unAnnot :: f a -> Maybe a instance Annot NoInfo where unAnnot = const Nothing instance Annot Info where unAnnot = Just . unInfo pprAnnot :: (Annot f, Pretty a, Pretty b) => a -> f b -> Doc pprAnnot a b = maybe (ppr a) ppr $ unAnnot b instance Pretty Value where ppr (PrimValue bv) = ppr bv ppr (ArrayValue a t) | [] <- elems a = text "empty" <> parens (ppr t) | Array {} <- t = brackets $ commastack $ map ppr $ elems a | otherwise = brackets $ commasep $ map ppr $ elems a instance Pretty PrimValue where ppr (UnsignedValue (Int8Value v)) = text (show (fromIntegral v :: Word8)) <> text "u8" ppr (UnsignedValue (Int16Value v)) = text (show (fromIntegral v :: Word16)) <> text "u16" ppr (UnsignedValue (Int32Value v)) = text (show (fromIntegral v :: Word32)) <> text "u32" ppr (UnsignedValue (Int64Value v)) = text (show (fromIntegral v :: Word64)) <> text "u64" ppr (SignedValue v) = ppr v ppr (BoolValue True) = text "true" ppr (BoolValue False) = text "false" ppr (FloatValue v) = ppr v instance IsName vn => Pretty (DimDecl vn) where ppr (AnyDim Nothing) = mempty ppr (AnyDim (Just v)) = text "?" <> pprName v ppr (NamedDim v) = ppr v ppr (ConstDim n) = ppr n instance IsName vn => Pretty (DimExp vn) where ppr DimExpAny = mempty ppr (DimExpNamed v _) = ppr v ppr (DimExpConst n _) = ppr n instance IsName vn => Pretty (ShapeDecl (DimDecl vn)) where ppr (ShapeDecl ds) = mconcat (map (brackets . ppr) ds) instance Pretty (ShapeDecl ()) where ppr (ShapeDecl ds) = mconcat $ replicate (length ds) $ text "[]" instance Pretty (ShapeDecl Int64) where ppr (ShapeDecl ds) = mconcat (map (brackets . ppr) ds) instance Pretty (ShapeDecl Bool) where ppr (ShapeDecl ds) = mconcat (map (brackets . ppr) ds) instance Pretty (ShapeDecl dim) => Pretty (RetTypeBase dim as) where ppr = pprPrec 0 pprPrec p (RetType [] t) = pprPrec p t pprPrec _ (RetType dims t) = text "?" <> mconcat (map (brackets . pprName) dims) <> text "." <> ppr t instance Pretty (ShapeDecl dim) => Pretty (ScalarTypeBase dim as) where ppr = pprPrec 0 pprPrec _ (Prim et) = ppr et pprPrec p (TypeVar _ u et targs) = parensIf (not (null targs) && p > 3) $ ppr u <> ppr (qualNameFromTypeName et) <+> spread (map (pprPrec 3) targs) pprPrec _ (Record fs) | Just ts <- areTupleFields fs = oneLine (parens $ commasep $ map ppr ts) <|> parens (align $ mconcat $ punctuate (text "," <> line) $ map ppr ts) | otherwise = oneLine (braces $ commasep fs') <|> braces (align $ mconcat $ punctuate (text "," <> line) fs') where ppField (name, t) = text (nameToString name) <> colon <+> align (ppr t) fs' = map ppField $ M.toList fs pprPrec p (Arrow _ (Named v) t1 t2) = parensIf (p > 1) $ parens (pprName v <> colon <+> align (ppr t1)) <+/> text "->" <+> pprPrec 1 t2 pprPrec p (Arrow _ Unnamed t1 t2) = parensIf (p > 1) $ pprPrec 2 t1 <+/> text "->" <+> pprPrec 1 t2 pprPrec p (Sum cs) = parensIf (p > 0) $ oneLine (mconcat $ punctuate (text " | ") cs') <|> align (mconcat $ punctuate (text " |" <> line) cs') where ppConstr (name, fs) = sep $ (text "#" <> ppr name) : map (pprPrec 2) fs cs' = map ppConstr $ M.toList cs instance Pretty (ShapeDecl dim) => Pretty (TypeBase dim as) where ppr = pprPrec 0 pprPrec _ (Array _ u at shape) = ppr u <> ppr shape <> align (pprPrec 1 at) pprPrec p (Scalar t) = pprPrec p t instance Pretty (ShapeDecl dim) => Pretty (TypeArg dim) where ppr = pprPrec 0 pprPrec _ (TypeArgDim d _) = ppr $ ShapeDecl [d] pprPrec p (TypeArgType t _) = pprPrec p t instance (Eq vn, IsName vn) => Pretty (TypeExp vn) where ppr (TEUnique t _) = text "*" <> ppr t ppr (TEArray at d _) = brackets (ppr d) <> ppr at ppr (TETuple ts _) = parens $ commasep $ map ppr ts ppr (TERecord fs _) = braces $ commasep $ map ppField fs where ppField (name, t) = text (nameToString name) <> colon <+> ppr t ppr (TEVar name _) = ppr name ppr (TEApply t arg _) = ppr t <+> ppr arg ppr (TEArrow (Just v) t1 t2 _) = parens v' <+> text "->" <+> ppr t2 where v' = pprName v <> colon <+> ppr t1 ppr (TEArrow Nothing t1 t2 _) = ppr t1 <+> text "->" <+> ppr t2 ppr (TESum cs _) = align $ cat $ punctuate (text " |" <> softline) $ map ppConstr cs where ppConstr (name, fs) = text "#" <> ppr name <+> sep (map ppr fs) ppr (TEDim dims te _) = text "?" <> mconcat (map (brackets . pprName) dims) <> text "." <> ppr te instance (Eq vn, IsName vn) => Pretty (TypeArgExp vn) where ppr (TypeArgExpDim d _) = brackets $ ppr d ppr (TypeArgExpType t) = ppr t instance (Eq vn, IsName vn, Annot f) => Pretty (TypeDeclBase f vn) where ppr x = pprAnnot (declaredType x) (expandedType x) instance IsName vn => Pretty (QualName vn) where ppr (QualName names name) = mconcat $ punctuate (text ".") $ map pprName names ++ [pprName name] instance IsName vn => Pretty (IdentBase f vn) where ppr = pprName . identName hasArrayLit :: ExpBase ty vn -> Bool hasArrayLit ArrayLit {} = True hasArrayLit (TupLit es2 _) = any hasArrayLit es2 hasArrayLit _ = False instance (Eq vn, IsName vn, Annot f) => Pretty (DimIndexBase f vn) where ppr (DimFix e) = ppr e ppr (DimSlice i j (Just s)) = maybe mempty ppr i <> text ":" <> maybe mempty ppr j <> text ":" <> ppr s ppr (DimSlice i (Just j) s) = maybe mempty ppr i <> text ":" <> ppr j <> maybe mempty ((text ":" <>) . ppr) s ppr (DimSlice i Nothing Nothing) = maybe mempty ppr i <> text ":" instance IsName vn => Pretty (SizeBinder vn) where ppr (SizeBinder v _) = brackets $ pprName v letBody :: (Eq vn, IsName vn, Annot f) => ExpBase f vn -> Doc letBody body@(AppExp LetPat {} _) = ppr body letBody body@(AppExp LetFun {} _) = ppr body letBody body = text "in" <+> align (ppr body) instance (Eq vn, IsName vn, Annot f) => Pretty (AppExpBase f vn) where ppr = pprPrec (-1) pprPrec p (Coerce e t _) = parensIf (p /= -1) $ pprPrec 0 e <+> text ":>" <+> align (pprPrec 0 t) pprPrec p (BinOp (bop, _) _ (x, _) (y, _) _) = prettyBinOp p bop x y pprPrec _ (Match e cs _) = text "match" <+> ppr e </> (stack . map ppr) (NE.toList cs) pprPrec _ (DoLoop sizeparams pat initexp form loopbody _) = text "loop" <+> align ( spread (map (brackets . pprName) sizeparams) <+/> ppr pat <+> equals <+/> ppr initexp <+/> ppr form <+> text "do" ) </> indent 2 (ppr loopbody) pprPrec _ (Index e idxs _) = pprPrec 9 e <> brackets (commasep (map ppr idxs)) pprPrec p (LetPat sizes pat e body _) = parensIf (p /= -1) $ align $ text "let" <+> spread (map ppr sizes) <+> align (ppr pat) <+> ( if linebreak then equals </> indent 2 (ppr e) else equals <+> align (ppr e) ) </> letBody body where linebreak = case e of AppExp {} -> True Attr {} -> True ArrayLit {} -> False _ -> hasArrayLit e pprPrec _ (LetFun fname (tparams, params, retdecl, rettype, e) body _) = text "let" <+> pprName fname <+> spread (map ppr tparams ++ map ppr params) <> retdecl' <+> equals </> indent 2 (ppr e) </> letBody body where retdecl' = case (ppr <$> unAnnot rettype) `mplus` (ppr <$> retdecl) of Just rettype' -> colon <+> align rettype' Nothing -> mempty pprPrec _ (LetWith dest src idxs ve body _) | dest == src = text "let" <+> ppr dest <> list (map ppr idxs) <+> equals <+> align (ppr ve) </> letBody body | otherwise = text "let" <+> ppr dest <+> equals <+> ppr src <+> text "with" <+> brackets (commasep (map ppr idxs)) <+> text "=" <+> align (ppr ve) </> letBody body pprPrec p (Range start maybe_step end _) = parensIf (p /= -1) $ ppr start <> maybe mempty ((text ".." <>) . ppr) maybe_step <> case end of DownToExclusive end' -> text "..>" <> ppr end' ToInclusive end' -> text "..." <> ppr end' UpToExclusive end' -> text "..<" <> ppr end' pprPrec _ (If c t f _) = text "if" <+> ppr c </> text "then" <+> align (ppr t) </> text "else" <+> align (ppr f) pprPrec p (Apply f arg _ _) = parensIf (p >= 10) $ pprPrec 0 f <+/> pprPrec 10 arg instance (Eq vn, IsName vn, Annot f) => Pretty (ExpBase f vn) where ppr = pprPrec (-1) pprPrec _ (Var name t _) = ppr name <> inst where inst = case unAnnot t of Just t' | isEnvVarAtLeast "FUTHARK_COMPILER_DEBUGGING" 2 -> text "@" <> parens (align $ ppr t') _ -> mempty pprPrec _ (Parens e _) = align $ parens $ ppr e pprPrec _ (QualParens (v, _) e _) = ppr v <> text "." <> align (parens $ ppr e) pprPrec p (Ascript e t _) = parensIf (p /= -1) $ pprPrec 0 e <+> text ":" <+> align (pprPrec 0 t) pprPrec _ (Literal v _) = ppr v pprPrec _ (IntLit v _ _) = ppr v pprPrec _ (FloatLit v _ _) = ppr v pprPrec _ (TupLit es _) | any hasArrayLit es = parens $ commastack $ map ppr es | otherwise = parens $ commasep $ map ppr es pprPrec _ (RecordLit fs _) | any fieldArray fs = braces $ commastack $ map ppr fs | otherwise = braces $ commasep $ map ppr fs where fieldArray (RecordFieldExplicit _ e _) = hasArrayLit e fieldArray RecordFieldImplicit {} = False pprPrec _ (ArrayLit es info _) = brackets (commasep $ map ppr es) <> info' where info' = case unAnnot info of Just t | isEnvVarAtLeast "FUTHARK_COMPILER_DEBUGGING" 2 -> text "@" <> parens (align $ ppr t) _ -> mempty pprPrec _ (StringLit s _) = text $ show $ map (chr . fromIntegral) s pprPrec _ (Project k e _ _) = ppr e <> text "." <> ppr k pprPrec _ (Negate e _) = text "-" <> ppr e pprPrec _ (Not e _) = text "-" <> ppr e pprPrec _ (Update src idxs ve _) = ppr src <+> text "with" <+> brackets (commasep (map ppr idxs)) <+> text "=" <+> align (ppr ve) pprPrec _ (RecordUpdate src fs ve _ _) = ppr src <+> text "with" <+> mconcat (intersperse (text ".") (map ppr fs)) <+> text "=" <+> align (ppr ve) pprPrec _ (Assert e1 e2 _ _) = text "assert" <+> pprPrec 10 e1 <+> pprPrec 10 e2 pprPrec p (Lambda params body rettype _ _) = parensIf (p /= -1) $ text "\\" <> spread (map ppr params) <> ppAscription rettype <+> text "->" </> indent 2 (ppr body) pprPrec _ (OpSection binop _ _) = parens $ ppr binop pprPrec _ (OpSectionLeft binop _ x _ _ _) = parens $ ppr x <+> ppBinOp binop pprPrec _ (OpSectionRight binop _ x _ _ _) = parens $ ppBinOp binop <+> ppr x pprPrec _ (ProjectSection fields _ _) = parens $ mconcat $ map p fields where p name = text "." <> ppr name pprPrec _ (IndexSection idxs _ _) = parens $ text "." <> brackets (commasep (map ppr idxs)) pprPrec _ (Constr n cs _ _) = text "#" <> ppr n <+> sep (map ppr cs) pprPrec _ (Attr attr e _) = text "#[" <> ppr attr <> text "]" </> pprPrec (-1) e pprPrec i (AppExp e _) = pprPrec i e instance IsName vn => Pretty (AttrAtom vn) where ppr (AtomName v) = ppr v ppr (AtomInt x) = ppr x instance IsName vn => Pretty (AttrInfo vn) where ppr (AttrAtom attr _) = ppr attr ppr (AttrComp f attrs _) = ppr f <> parens (commasep $ map ppr attrs) instance (Eq vn, IsName vn, Annot f) => Pretty (FieldBase f vn) where ppr (RecordFieldExplicit name e _) = ppr name <> equals <> ppr e ppr (RecordFieldImplicit name _ _) = pprName name instance (Eq vn, IsName vn, Annot f) => Pretty (CaseBase f vn) where ppr (CasePat p e _) = text "case" <+> ppr p <+> text "->" </> indent 2 (ppr e) instance (Eq vn, IsName vn, Annot f) => Pretty (LoopFormBase f vn) where ppr (For i ubound) = text "for" <+> ppr i <+> text "<" <+> align (ppr ubound) ppr (ForIn x e) = text "for" <+> ppr x <+> text "in" <+> ppr e ppr (While cond) = text "while" <+> ppr cond instance Pretty PatLit where ppr (PatLitInt x) = ppr x ppr (PatLitFloat f) = ppr f ppr (PatLitPrim v) = ppr v instance (Eq vn, IsName vn, Annot f) => Pretty (PatBase f vn) where ppr (PatAscription p t _) = ppr p <> colon <+> align (ppr t) ppr (PatParens p _) = parens $ ppr p ppr (Id v t _) = case unAnnot t of Just t' -> parens $ pprName v <> colon <+> align (ppr t') Nothing -> pprName v ppr (TuplePat pats _) = parens $ commasep $ map ppr pats ppr (RecordPat fs _) = braces $ commasep $ map ppField fs where ppField (name, t) = text (nameToString name) <> equals <> ppr t ppr (Wildcard t _) = case unAnnot t of Just t' -> parens $ text "_" <> colon <+> ppr t' Nothing -> text "_" ppr (PatLit e _ _) = ppr e ppr (PatConstr n _ ps _) = text "#" <> ppr n <+> sep (map ppr ps) ppr (PatAttr attr p _) = text "#[" <> ppr attr <> text "]" <+/> ppr p ppAscription :: Pretty t => Maybe t -> Doc ppAscription Nothing = mempty ppAscription (Just t) = colon <> align (ppr t) instance (Eq vn, IsName vn, Annot f) => Pretty (ProgBase f vn) where ppr = stack . punctuate line . map ppr . progDecs instance (Eq vn, IsName vn, Annot f) => Pretty (DecBase f vn) where ppr (ValDec dec) = ppr dec ppr (TypeDec dec) = ppr dec ppr (SigDec sig) = ppr sig ppr (ModDec sd) = ppr sd ppr (OpenDec x _) = text "open" <+> ppr x ppr (LocalDec dec _) = text "local" <+> ppr dec ppr (ImportDec x _ _) = text "import" <+> ppr x instance (Eq vn, IsName vn, Annot f) => Pretty (ModExpBase f vn) where ppr (ModVar v _) = ppr v ppr (ModParens e _) = parens $ ppr e ppr (ModImport v _ _) = text "import" <+> ppr (show v) ppr (ModDecs ds _) = nestedBlock "{" "}" (stack $ punctuate line $ map ppr ds) ppr (ModApply f a _ _ _) = parens $ ppr f <+> parens (ppr a) ppr (ModAscript me se _ _) = ppr me <> colon <+> ppr se ppr (ModLambda param maybe_sig body _) = text "\\" <> ppr param <> maybe_sig' <+> text "->" </> indent 2 (ppr body) where maybe_sig' = case maybe_sig of Nothing -> mempty Just (sig, _) -> colon <+> ppr sig instance Pretty Liftedness where ppr Unlifted = text "" ppr SizeLifted = text "~" ppr Lifted = text "^" instance (Eq vn, IsName vn, Annot f) => Pretty (TypeBindBase f vn) where ppr (TypeBind name l params te rt _ _) = text "type" <> ppr l <+> pprName name <+> spread (map ppr params) <+> equals <+> maybe (ppr te) ppr (unAnnot rt) instance (Eq vn, IsName vn) => Pretty (TypeParamBase vn) where ppr (TypeParamDim name _) = brackets $ pprName name ppr (TypeParamType l name _) = text "'" <> ppr l <> pprName name instance (Eq vn, IsName vn, Annot f) => Pretty (ValBindBase f vn) where ppr (ValBind entry name retdecl rettype tparams args body _ attrs _) = mconcat (map ((<> line) . ppr) attrs) <> text fun <+> pprName name <+> align (sep (map ppr tparams ++ map ppr args)) <> retdecl' <> text " =" </> indent 2 (ppr body) where fun | isJust entry = "entry" | otherwise = "let" retdecl' = case (ppr <$> unAnnot rettype) `mplus` (ppr <$> retdecl) of Just rettype' -> colon <+> align rettype' Nothing -> mempty instance (Eq vn, IsName vn, Annot f) => Pretty (SpecBase f vn) where ppr (TypeAbbrSpec tpsig) = ppr tpsig ppr (TypeSpec l name ps _ _) = text "type" <> ppr l <+> pprName name <+> spread (map ppr ps) ppr (ValSpec name tparams vtype _ _) = text "val" <+> pprName name <+> spread (map ppr tparams) <> colon <+> ppr vtype ppr (ModSpec name sig _ _) = text "module" <+> pprName name <> colon <+> ppr sig ppr (IncludeSpec e _) = text "include" <+> ppr e instance (Eq vn, IsName vn, Annot f) => Pretty (SigExpBase f vn) where ppr (SigVar v _ _) = ppr v ppr (SigParens e _) = parens $ ppr e ppr (SigSpecs ss _) = nestedBlock "{" "}" (stack $ punctuate line $ map ppr ss) ppr (SigWith s (TypeRef v ps td _) _) = ppr s <+> text "with" <+> ppr v <+> spread (map ppr ps) <> text " =" <+> ppr td ppr (SigArrow (Just v) e1 e2 _) = parens (pprName v <> colon <+> ppr e1) <+> text "->" <+> ppr e2 ppr (SigArrow Nothing e1 e2 _) = ppr e1 <+> text "->" <+> ppr e2 instance (Eq vn, IsName vn, Annot f) => Pretty (SigBindBase f vn) where ppr (SigBind name e _ _) = text "module type" <+> pprName name <+> equals <+> ppr e instance (Eq vn, IsName vn, Annot f) => Pretty (ModParamBase f vn) where ppr (ModParam pname psig _ _) = parens (pprName pname <> colon <+> ppr psig) instance (Eq vn, IsName vn, Annot f) => Pretty (ModBindBase f vn) where ppr (ModBind name ps sig e _ _) = text "module" <+> pprName name <+> spread (map ppr ps) <+> sig' <> text " =" <+> ppr e where sig' = case sig of Nothing -> mempty Just (s, _) -> colon <+> ppr s <> text " " ppBinOp :: IsName v => QualName v -> Doc ppBinOp bop = case leading of Backtick -> text "`" <> ppr bop <> text "`" _ -> ppr bop where leading = leadingOperator $ nameFromString $ pretty $ pprName $ qualLeaf bop prettyBinOp :: (Eq vn, IsName vn, Annot f) => Int -> QualName vn -> ExpBase f vn -> ExpBase f vn -> Doc prettyBinOp p bop x y = parensIf (p > symPrecedence) $ pprPrec symPrecedence x <+/> bop' <+> pprPrec symRPrecedence y where bop' = case leading of Backtick -> text "`" <> ppr bop <> text "`" _ -> ppr bop leading = leadingOperator $ nameFromString $ pretty $ pprName $ qualLeaf bop symPrecedence = precedence leading symRPrecedence = rprecedence leading precedence PipeRight = -1 precedence PipeLeft = -1 precedence LogAnd = 0 precedence LogOr = 0 precedence Band = 1 precedence Bor = 1 precedence Xor = 1 precedence Equal = 2 precedence NotEqual = 2 precedence Less = 2 precedence Leq = 2 precedence Greater = 2 precedence Geq = 2 precedence ShiftL = 3 precedence ShiftR = 3 precedence Plus = 4 precedence Minus = 4 precedence Times = 5 precedence Divide = 5 precedence Mod = 5 precedence Quot = 5 precedence Rem = 5 precedence Pow = 6 precedence Backtick = 9 rprecedence Minus = 10 rprecedence Divide = 10 rprecedence op = precedence op
HIPERFIT/futhark
src/Language/Futhark/Pretty.hs
isc
20,531
0
19
5,439
9,125
4,415
4,710
474
27
module RK4 where data State = S { x :: Float, v :: Float } deriving (Show, Eq) data Deriv = D { dx :: Float, dv :: Float } deriving (Show, Eq) type Accel = State -> Float type Integrator = Accel -> Float -> State -> State euler :: Integrator euler af dt s0 = s' where s' = S x' v' x' = x s0 + dt * v s0 v' = v s0 + dt * af s0 rk4 :: Integrator rk4 af dt s0 = s' where evaluateHere = evaluate af s0 a = evaluateHere (D 0 0) 0 b = evaluateHere a (dt*0.5) c = evaluateHere b (dt*0.5) d = evaluateHere c dt dxdt = 1.0/6.0 * (dx a + 2.0*(dx b + dx c) + dx d) dvdt = 1.0/6.0 * (dv a + 2.0*(dv b + dv c) + dv d) d' = D dxdt dvdt x' = x s0 + dt * dx d' v' = v s0 + dt * dv d' s' = S x' v' evaluate af s d dt = D (v se) (af se) where se = S (x s + dt * dx d) (v s + dt * dv d) runIntegrator ig af s dt steps = foldr (.) id (replicate steps (ig af dt)) $ s scanIntegrator ig af s dt steps = scanl (\s igC -> igC s) s (replicate steps (ig af dt)) carAf s = 1.0 springAf k b s = -k*(x s) - b*(v s) carExample ig = runIntegrator ig carAf (S 0 0) 0.5 100 springExample ig = runIntegrator ig (springAf 10 1) (S 1 1) 0.5 100
RichardBarrell/snippets
RK4.hs
isc
1,221
0
13
392
688
350
338
32
1
module Language.Tiger.AST ( module AST) where import Language.Tiger.AST.Declaration as AST
zeling/tiger
src/Language/Tiger/AST.hs
mit
99
0
4
18
22
16
6
3
0
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SubtleCrypto (js_encrypt, encrypt, js_decrypt, decrypt, js_sign, sign, js_verify, verify, js_digest, digest, js_generateKey, generateKey, js_importKey, importKey, js_exportKey, exportKey, js_wrapKey, wrapKey, js_unwrapKey, unwrapKey, SubtleCrypto, castToSubtleCrypto, gTypeSubtleCrypto) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"encrypt\"]($2, $3, $4)" js_encrypt :: JSRef SubtleCrypto -> JSString -> JSRef CryptoKey -> JSRef [Maybe data'] -> IO (JSRef Promise) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.encrypt Mozilla WebKitSubtleCrypto.encrypt documentation> encrypt :: (MonadIO m, ToJSString algorithm, IsCryptoOperationData data') => SubtleCrypto -> algorithm -> Maybe CryptoKey -> [Maybe data'] -> m (Maybe Promise) encrypt self algorithm key data' = liftIO ((toJSRef data' >>= \ data'' -> js_encrypt (unSubtleCrypto self) (toJSString algorithm) (maybe jsNull pToJSRef key) data'') >>= fromJSRef) foreign import javascript unsafe "$1[\"decrypt\"]($2, $3, $4)" js_decrypt :: JSRef SubtleCrypto -> JSString -> JSRef CryptoKey -> JSRef [Maybe data'] -> IO (JSRef Promise) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.decrypt Mozilla WebKitSubtleCrypto.decrypt documentation> decrypt :: (MonadIO m, ToJSString algorithm, IsCryptoOperationData data') => SubtleCrypto -> algorithm -> Maybe CryptoKey -> [Maybe data'] -> m (Maybe Promise) decrypt self algorithm key data' = liftIO ((toJSRef data' >>= \ data'' -> js_decrypt (unSubtleCrypto self) (toJSString algorithm) (maybe jsNull pToJSRef key) data'') >>= fromJSRef) foreign import javascript unsafe "$1[\"sign\"]($2, $3, $4)" js_sign :: JSRef SubtleCrypto -> JSString -> JSRef CryptoKey -> JSRef [Maybe data'] -> IO (JSRef Promise) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.sign Mozilla WebKitSubtleCrypto.sign documentation> sign :: (MonadIO m, ToJSString algorithm, IsCryptoOperationData data') => SubtleCrypto -> algorithm -> Maybe CryptoKey -> [Maybe data'] -> m (Maybe Promise) sign self algorithm key data' = liftIO ((toJSRef data' >>= \ data'' -> js_sign (unSubtleCrypto self) (toJSString algorithm) (maybe jsNull pToJSRef key) data'') >>= fromJSRef) foreign import javascript unsafe "$1[\"verify\"]($2, $3, $4, $5)" js_verify :: JSRef SubtleCrypto -> JSString -> JSRef CryptoKey -> JSRef CryptoOperationData -> JSRef [Maybe data'] -> IO (JSRef Promise) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.verify Mozilla WebKitSubtleCrypto.verify documentation> verify :: (MonadIO m, ToJSString algorithm, IsCryptoOperationData signature, IsCryptoOperationData data') => SubtleCrypto -> algorithm -> Maybe CryptoKey -> Maybe signature -> [Maybe data'] -> m (Maybe Promise) verify self algorithm key signature data' = liftIO ((toJSRef data' >>= \ data'' -> js_verify (unSubtleCrypto self) (toJSString algorithm) (maybe jsNull pToJSRef key) (maybe jsNull (unCryptoOperationData . toCryptoOperationData) signature) data'') >>= fromJSRef) foreign import javascript unsafe "$1[\"digest\"]($2, $3)" js_digest :: JSRef SubtleCrypto -> JSString -> JSRef [Maybe data'] -> IO (JSRef Promise) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.digest Mozilla WebKitSubtleCrypto.digest documentation> digest :: (MonadIO m, ToJSString algorithm, IsCryptoOperationData data') => SubtleCrypto -> algorithm -> [Maybe data'] -> m (Maybe Promise) digest self algorithm data' = liftIO ((toJSRef data' >>= \ data'' -> js_digest (unSubtleCrypto self) (toJSString algorithm) data'') >>= fromJSRef) foreign import javascript unsafe "$1[\"generateKey\"]($2, $3, $4)" js_generateKey :: JSRef SubtleCrypto -> JSString -> Bool -> JSRef [KeyUsage] -> IO (JSRef Promise) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.generateKey Mozilla WebKitSubtleCrypto.generateKey documentation> generateKey :: (MonadIO m, ToJSString algorithm) => SubtleCrypto -> algorithm -> Bool -> [KeyUsage] -> m (Maybe Promise) generateKey self algorithm extractable keyUsages = liftIO ((toJSRef keyUsages >>= \ keyUsages' -> js_generateKey (unSubtleCrypto self) (toJSString algorithm) extractable keyUsages') >>= fromJSRef) foreign import javascript unsafe "$1[\"importKey\"]($2, $3, $4, $5,\n$6)" js_importKey :: JSRef SubtleCrypto -> JSString -> JSRef CryptoOperationData -> JSString -> Bool -> JSRef [KeyUsage] -> IO (JSRef Promise) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.importKey Mozilla WebKitSubtleCrypto.importKey documentation> importKey :: (MonadIO m, ToJSString format, IsCryptoOperationData keyData, ToJSString algorithm) => SubtleCrypto -> format -> Maybe keyData -> algorithm -> Bool -> [KeyUsage] -> m (Maybe Promise) importKey self format keyData algorithm extractable keyUsages = liftIO ((toJSRef keyUsages >>= \ keyUsages' -> js_importKey (unSubtleCrypto self) (toJSString format) (maybe jsNull (unCryptoOperationData . toCryptoOperationData) keyData) (toJSString algorithm) extractable keyUsages') >>= fromJSRef) foreign import javascript unsafe "$1[\"exportKey\"]($2, $3)" js_exportKey :: JSRef SubtleCrypto -> JSString -> JSRef CryptoKey -> IO (JSRef Promise) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.exportKey Mozilla WebKitSubtleCrypto.exportKey documentation> exportKey :: (MonadIO m, ToJSString format) => SubtleCrypto -> format -> Maybe CryptoKey -> m (Maybe Promise) exportKey self format key = liftIO ((js_exportKey (unSubtleCrypto self) (toJSString format) (maybe jsNull pToJSRef key)) >>= fromJSRef) foreign import javascript unsafe "$1[\"wrapKey\"]($2, $3, $4, $5)" js_wrapKey :: JSRef SubtleCrypto -> JSString -> JSRef CryptoKey -> JSRef CryptoKey -> JSString -> IO (JSRef Promise) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.wrapKey Mozilla WebKitSubtleCrypto.wrapKey documentation> wrapKey :: (MonadIO m, ToJSString format, ToJSString wrapAlgorithm) => SubtleCrypto -> format -> Maybe CryptoKey -> Maybe CryptoKey -> wrapAlgorithm -> m (Maybe Promise) wrapKey self format key wrappingKey wrapAlgorithm = liftIO ((js_wrapKey (unSubtleCrypto self) (toJSString format) (maybe jsNull pToJSRef key) (maybe jsNull pToJSRef wrappingKey) (toJSString wrapAlgorithm)) >>= fromJSRef) foreign import javascript unsafe "$1[\"unwrapKey\"]($2, $3, $4, $5,\n$6, $7, $8)" js_unwrapKey :: JSRef SubtleCrypto -> JSString -> JSRef CryptoOperationData -> JSRef CryptoKey -> JSString -> JSString -> Bool -> JSRef [KeyUsage] -> IO (JSRef Promise) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.unwrapKey Mozilla WebKitSubtleCrypto.unwrapKey documentation> unwrapKey :: (MonadIO m, ToJSString format, IsCryptoOperationData wrappedKey, ToJSString unwrapAlgorithm, ToJSString unwrappedKeyAlgorithm) => SubtleCrypto -> format -> Maybe wrappedKey -> Maybe CryptoKey -> unwrapAlgorithm -> unwrappedKeyAlgorithm -> Bool -> [KeyUsage] -> m (Maybe Promise) unwrapKey self format wrappedKey unwrappingKey unwrapAlgorithm unwrappedKeyAlgorithm extractable keyUsages = liftIO ((toJSRef keyUsages >>= \ keyUsages' -> js_unwrapKey (unSubtleCrypto self) (toJSString format) (maybe jsNull (unCryptoOperationData . toCryptoOperationData) wrappedKey) (maybe jsNull pToJSRef unwrappingKey) (toJSString unwrapAlgorithm) (toJSString unwrappedKeyAlgorithm) extractable keyUsages') >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/SubtleCrypto.hs
mit
9,991
132
15
2,662
2,236
1,190
1,046
209
1
import Control.Monad filter' _ [] = [-1] filter' _ (_:xs) = xs main = do n <- readLn :: IO Int replicateM_ n $ do line <- getLine arrLine <- getLine let k = read (words line !! 1) :: Int let arr = map (\x -> read x :: Int) (words arrLine) putStrLn $ unwords (map show (filter' k arr))
ahavrylyuk/hackerrank
haskell/filter-elements.hs
mit
312
0
16
88
167
81
86
11
1
{-# LANGUAGE GeneralizedNewtypeDeriving, TemplateHaskell #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-} module IRC.Types where import Control.Lens import CAH.Cards.Types import Data.Set (Set) import Data.Map (Map) import Data.Bimap (Bimap) import qualified IRC.Raw.Types as Raw import IRC.Raw.Monad import Common.Types import CAH.Cards.Types import Data.ByteString (ByteString) import Data.Monoid import Data.Dynamic import Data.Text (Text) import Control.Applicative import System.Random import Control.Monad.Trans.Class import qualified Control.Monad.Ether.State.Strict as ES import qualified Control.Monad.Ether.Reader as ER import Control.Ether.TH ethereal "GameState" "gameState" ethereal "CardSet" "cardSet" ethereal "Tracker" "nickTracker" ethereal "GameInfoT" "gameInfo" type TrackerMonad = ES.MonadState Tracker NickTracker type GameMonad r m = (ES.MonadState GameState (GS r) m, ER.MonadReader CardSet [Pack] m, ER.MonadReader GameInfoT GameInfo m, Applicative m) data Cmd = N Int | S ByteString deriving (Show,Eq,Ord) -- used by IRC.Commands data User = User Nick Ident Host deriving (Show,Eq) newtype UID = UID Integer deriving (Show,Eq,Ord) data TrackEvent = Login Nick Account | Logout Nick | NickChange Nick Nick deriving (Show,Eq, Typeable) data NickTracker = Tracker !UID -- ^ next uid to use !(Bimap Nick UID) -- ^ bimap keeping the mapping from nicks to UIDs !(Map UID Account) -- ^ maps from user IDs to textual "user account", missing key means the user doesn't have a registered account deriving (Show,Eq) data Players a = Players (Bimap UID Account) (Map Account a) deriving (Show,Eq) userNick :: User -> Nick userNick (User n _ _) = n newtype Channel = Channel Text deriving (Show,Eq) newtype Nick = Nick Text deriving (Show,Eq,Ord) newtype Message = Message Text deriving (Show,Eq,Monoid) newtype Target = Target Text deriving (Show,Eq) newtype Account = Account Text deriving (Show,Eq,Ord) type Ident = Text type Host = Text data Mode = Plus Char | Minus Char deriving (Show,Eq) data CMode = CMode Nick Mode deriving (Show,Eq) data SASLCfg = SASLCfg { sasl_username :: String ,sasl_password :: String } deriving (Show,Eq) data ChannelCfg = ChannelCfg { channel_name :: Channel ,channel_password :: Maybe String } deriving (Show,Eq) data IRCConfig = IRCConfig { config_network :: String ,config_port :: Int ,config_nick :: Nick ,config_sasl :: Maybe SASLCfg ,config_channels :: [ChannelCfg] } deriving (Show,Eq) type Player = Account data NatN = Nat_Zero | Nat_Succ NatN data T_GameState {-(p :: NatN)-} a = T_NoGameBeingPlayed | T_WaitingFor a deriving (Typeable) data T_Waiting = T_Players | T_Czar deriving (Typeable) type family ToLogicTag (x :: *) :: T_GameState T_Waiting where ToLogicTag NoGame = T_NoGameBeingPlayed ToLogicTag (Current WFCzar) = T_WaitingFor T_Czar ToLogicTag (Current WFPlayers) = T_WaitingFor T_Players data LogicCommand st where PlayerJoin :: Nick -> Account -> LogicCommand a PlayerLeave :: Nick -> Account -> LogicCommand a StartGame :: Nick -> Account -> LogicCommand T_NoGameBeingPlayed PlayerPick :: Nick -> Account -> [WhiteCard] -> LogicCommand (T_WaitingFor T_Players) CzarPick :: Nick -> Account -> ChoiceN -> LogicCommand (T_WaitingFor T_Czar) ShowTable :: LogicCommand (T_WaitingFor a) ShowCards :: Nick -> Account -> LogicCommand (T_WaitingFor a) data TextMessage = NoError | UserNotPlaying Nick | UserNotIdentified Nick | NotEnoughPlayers Integer | AlreadyPlaying Nick | GameStarted [Nick] | GameAlreadyBeingPlayed | JoinPlayer Nick | LeavePlayer Nick | AlreadyPlayed Nick | ReplacingOld Nick Nick -- the first nick is the "old" one | MustPickNCards Nick Integer | PlayersWin [Nick] Points | CzarPicked Nick Nick BlackCard [WhiteCard] Points -- first is czar | CzarDoesn'tPlay Nick | YourCardsAre Nick [(Integer, WhiteCard)] | TheCardsAre | CardsPicked Nick Integer BlackCard [WhiteCard] | PlayersList [Nick] | CzarLeft Nick | Table Nick BlackCard | StatusWaitingCzar Nick | StatusWaitPlayers Nick [Nick] -- first is czar | Debug Text newtype ChoiceN = ChoiceN Integer deriving (Show,Eq,Ord) newtype Points = Points Integer deriving (Show,Eq,Ord,Num) type Game r m = ES.StateT GameState (GS r) ( ES.StateT EventsTag Events ( ES.StateT Tracker NickTracker ( ER.ReaderT CardSet [Pack] ( ER.ReaderT GameInfoT GameInfo (IRC m))))) data GameInfo = GameInfo { _gameChannel :: Channel ,_botNick :: Nick } deriving (Show) data GS a = GS { _stdGen :: StdGen ,_whiteCards :: Set WhiteCard ,_blackCards :: Set BlackCard ,_players :: Players (Set WhiteCard) -- ^ current players (and their cards) ,_current :: a } deriving (Show,Functor) changing :: Monad m => (GS r -> GS r') -> Game r' m a -> Game r m a changing f gs = do x <- ES.get gameState lift $ ES.evalStateT gameState gs (f x) data NoGame = NoGame deriving (Show) data Current w = Current { _points :: Map Player Points ,_czar :: Player ,_blackCard :: BlackCard ,_currentB :: w } deriving (Show,Functor) data WFCzar = WFCzar { _picks :: Map Integer (Player, [WhiteCard]) } deriving (Show) data WFPlayers = WFPlayers { _waitingFor :: Set Player -- ^ players we're waiting for ,_alreadyPlayed :: Map Player [WhiteCard] -- ^ players with their picks } deriving (Show) makeLenses ''GS makeLenses ''Current makeLenses ''WFCzar makeLenses ''WFPlayers makeLenses ''GameInfo
EXio4/ircah
src/IRC/Types.hs
mit
6,577
0
15
2,044
1,702
953
749
-1
-1
{-# LANGUAGE TemplateHaskell , TypeFamilies, OverloadedStrings #-} module Main where import System.Environment import Generics.BiGUL.TH import GHC.Generics import Data.Aeson import Data.Text import Control.Applicative import Control.Monad import qualified Data.ByteString.Lazy as B import SourceModel import qualified AutoScalingBX as ASBX import qualified FirewallBX as FWBX import qualified RedundancyBX as REDBX import qualified ExecutionBX as EXBX import qualified AutoScalingModel as ASV import qualified FirewallModel as FWV import qualified RedundancyModel as REDV import qualified ExecutionModel as EXV import qualified AutoscalingFailureModel as ASFV import qualified AutoscalingFailureBX as ASFBX import qualified FailureModel as FAV import qualified FailureBX as FABX doGet bx source param = case bx of "autoscalingFailure" -> case result of Just res -> encode res where result = (ASFBX.get (ASFBX.autoscalingFailureUpd param) source) "redundancy" -> case result of Just res -> encode res where result = (REDBX.get REDBX.redundancyUpd source) "firewall" -> case result of Just res -> encode res where result = (FWBX.get FWBX.firewallUpd source) "execution" -> encode (EXBX.getExecution source) doGet' bx source = case bx of "failure" -> case result of Just res -> encode res where result = (FABX.get FABX.failureUpd source) "autoScaling" -> case result of Just res -> encode res where result = (ASBX.get ASBX.autoScalingUpd source) doASPut source view = case result of Just res -> encode res where result = (ASBX.put ASBX.autoScalingUpd source view) doREDPut source view = case result of Just res -> encode res where result = (REDBX.put REDBX.redundancyUpd source view) doFWPut source view = case result of Just res -> encode res where result = (FWBX.put FWBX.firewallUpd source view) doEXPut source view = case result of Just res -> encode res where result = (EXBX.put EXBX.executionUpd source view) doASFPut source view param = case result of Just res -> encode res where result = (ASFBX.put (ASFBX.autoscalingFailureUpd param) source view) doFAPut source view = case result of Just res -> encode res where result = (FABX.put FABX.failureUpd source view) -- arguments are: -- dir: the direction, either get or put -- bx: the name of the transformation -- param: a parameter to pass to the bx (not all BX need this) -- Example: ./Main get autoScaling as.json main :: IO () main = do [dir, bx, param] <- getArgs putStrLn "Starting" case bx of "autoscalingFailure" -> do doAutoscalingFailure dir param "autoScaling" -> do doAutoScaling dir "failure" -> do doFailure dir "execution" -> do doExecution dir "firewall" -> do doFirewall dir doExecution dir = do src <- (eitherDecode <$> (B.readFile "source.json")) :: IO (Either String Model) case src of Left err -> putStrLn err Right source -> case dir of "get" -> do B.writeFile "execution.json" (doGet "execution" source "") "put" -> do v <- (eitherDecode <$> (B.readFile "execution.json")) :: IO (Either String EXV.View) case v of Left err -> do putStrLn "Error parse execution.json" putStrLn err Right vw -> B.writeFile "source.json" (doEXPut source vw) doAutoscalingFailure dir param = do src <- (eitherDecode <$> (B.readFile "source.json")) :: IO (Either String Model) case src of Left err -> putStrLn err Right source -> case dir of "get" -> do B.writeFile "autoscalingFailure.json" (doGet "autoscalingFailure" source param) "put" -> do v <- (eitherDecode <$> (B.readFile "autoscalingFailure.json")) :: IO (Either String ASFV.AutoscalingFailure) case v of Left err -> do putStrLn "Error parse autoscalingFailure.json" putStrLn err Right vw -> B.writeFile "source.json" (doASFPut source vw param) doAutoScaling dir = do src <- (eitherDecode <$> (B.readFile "autoscalingFailure.json")) :: IO (Either String ASFV.AutoscalingFailure) case src of Left err -> putStrLn err Right source -> case dir of "get" -> do B.writeFile "autoScaling.json" (doGet' "autoScaling" source) "put" -> do v <- (eitherDecode <$> (B.readFile "autoScaling.json")) :: IO (Either String ASV.View) case v of Left err -> do putStrLn "Error parse autoScaling.json" putStrLn err Right vw -> B.writeFile "autoscalingFailure.json" (doASPut source vw) doFailure dir = do src <- (eitherDecode <$> (B.readFile "autoscalingFailure.json")) :: IO (Either String ASFV.AutoscalingFailure) case src of Left err -> putStrLn err Right source -> case dir of "get" -> do B.writeFile "failure.json" (doGet' "failure" source) "put" -> do v <- (eitherDecode <$> (B.readFile "failure.json")) :: IO (Either String FAV.FailureView) case v of Left err -> do putStrLn "Error parse failure.json" putStrLn err Right vw -> B.writeFile "autoscalingFailure.json" (doFAPut source vw) doFirewall dir = do src <- (eitherDecode <$> (B.readFile "source.json")) :: IO (Either String Model) case src of Left err -> putStrLn err Right source -> case dir of "get" -> do B.writeFile "firewall.json" (doGet "firewall" source "") "put" -> do v <- (eitherDecode <$> (B.readFile "firewall.json")) :: IO (Either String FWV.View) case v of Left err -> do putStrLn "Error parse firewall.json" putStrLn err Right vw -> B.writeFile "source.json" (doFWPut source vw) {- Zhenjiang: the following two functions can be used to generate the Haskell representations from the JSON representation of soruce/view for simple testing of FirewallBX.hs. -} jsonSource2Haskell :: IO () jsonSource2Haskell = do src <- (eitherDecode <$> B.readFile "source.json") :: IO (Either String Model) case src of Right s -> putStrLn (show s) Left _ -> putStrLn "JSON parse error (source)" jsonFirewallView2Haskell :: IO () jsonFirewallView2Haskell = do view <- (eitherDecode <$> B.readFile "firewall.json") :: IO (Either String FWV.View) case view of Right v -> putStrLn (show v) Left _ -> putStrLn "JSON parse error (firewall)"
prl-tokyo/MAPE-knowledge-base
Haskell/Main.hs
mit
6,424
0
20
1,488
1,951
960
991
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} module Main where import Data.Int (Int32) import Database.HDBC.PostgreSQL (Connection) import Database.HDBC.Session (handleSqlError', withConnectionIO) import HRR.Commands (Command (..), Flag (..), runAndPrintCommand) import HRR.DataSource (connect') import System.Console.GetOpt (ArgDescr (..), ArgOrder (..), OptDescr (..), getOpt, usageInfo) import System.Environment (getArgs) import System.Exit (ExitCode (..), exitSuccess, exitWith) import System.IO (hPutStrLn, stderr) -------------------------------------------------------------------------------- -- | Flags with their corresponding description flags :: [OptDescr Flag] flags = [ Option ['d'] ["due-by"] (ReqArg DueBy "DATE") "Get todos due by a certain date" , Option ['l'] ["late"] (NoArg Late) "Get todos that are late" , Option ['w'] ["with-hashtags"] (NoArg WithHashtags) "Get todos with the associated hashtags" , Option ['h'] ["hashtags"] (ReqArg SearchHashtag "HASHTAGS") "Get todos for a certain hashtag" , Option ['o'] ["order-by-priority"] (NoArg OrderByPriority) "Get todos ordered by priority" , Option ['p'] ["priority"] (ReqArg SetPriority "PRIORITY") "When adding a todo, you can set its priority" , Option ['d'] ["debug"] (NoArg Debug) "Debug sql executed" , Option ['h'] ["help"] (NoArg Help) "Show help menu" , Option ['v'] ["version"] (NoArg Version) "Show version" ] header :: String header = "todos <command> [options]\n\n\ \Available commands: find, add, complete, list\n" -------------------------------------------------------------------------------- -- | Parse the command and the corresponding flags (if any) parse :: [String] -> Either String (Command, [Flag]) -- | Simple parsing of commands parse [] = Left "Wrong number of arguments." parse ("-h":_) = Left (usageInfo header flags) parse ("--help":_) = Left (usageInfo header flags) parse ("-v":_) = Left "0.1.0.0" parse ("--version":_) = Left "0.1.0.0" parse args = case args of ("find":x:argv) -> makeCommand (Find (read x :: Int32)) argv ("add":x:argv) -> makeCommand (Add x) argv ("complete":x:_) -> makeCommand (Complete (read x :: Int32)) [] ("list":argv) -> makeCommand List argv ("report":_) -> makeCommand Reports [] _ -> Left "Unrecognized command or wrong \ \number of arguments." makeCommand :: Command -> [String] -> Either String (Command, [Flag]) makeCommand c argv = case getOpt Permute flags argv of (args', _, []) -> Right(c, args') (_, _, errs) -> Left (concat errs) -------------------------------------------------------------------------------- -- | Gets the results of a command and its corresponding flags getResults :: Connection -> Either String (Command, [Flag]) -> IO () -- | An error happened getResults _ (Left s) = hPutStrLn stderr s >> exitWith (ExitFailure 1) -- | We have an appropriate command and its results getResults conn (Right (c, flags')) = runAndPrintCommand conn c flags' >> exitSuccess main :: IO () main = handleSqlError' $ withConnectionIO connect' $ \conn -> do parsed <- fmap parse getArgs getResults conn parsed
charlydagos/haskell-sql-edsl-demo
code/hrr/src/Main.hs
mit
3,975
0
12
1,310
951
520
431
61
6
import Data.Array.IArray import Data.Char import Data.Maybe import Data.List -------------------------------------------------------------------------------- data Cell = Value Int | Values (Array Int Bool) Int deriving Show isCellSet :: Cell -> Bool isCellSet (Value _) = True isCellSet (Values _ _) = False -------------------------------------------------------------------------------- type Coord = (Int, Int) next :: Coord -> Coord next (8, 8) = (0, 0) next (i, 8) = (i+1, 0) next (i, j) = (i, j+1) linkedWith (i, j) = [(i , j' ) | j' <- [0..8]] ++ [(i' , j ) | i' <- [0..8]] ++ [(i0 + i', j0 + j') | let i0 = 3 * (div i 3), let j0 = 3 * (div j 3), i' <- [0..2], j' <- [0..2]] -------------------------------------------------------------------------------- type Board = Array Coord Cell -------------------------------------------------------------------------------- set :: Board -> Coord -> Int -> Maybe Board set board coord val = case (board ! coord) of Value v -> if (v == val) then Just board else Nothing Values arr len -> if (arr ! val) then board' else Nothing where board' = unset (board // [(coord, Value val)]) (linkedWith coord) unset :: Board -> [Coord] -> Maybe Board unset b [] = (Just b) unset b (c:cs) | c == coord = unset b cs | otherwise = case (b ! c) of Value v -> if v == val then Nothing else unset b cs Values arr len -> let arr' = arr // [(val, False)] b' = set b c (fst $ head $ filter snd $ assocs (arr')) in case () of _| not (arr ! val) -> unset b cs | len == 1 -> Nothing | len == 2 -> case b' of Just b'' -> unset b'' cs Nothing -> Nothing | otherwise -> unset (b // [(c, Values arr' (len-1))]) cs -------------------------------------------------------------------------------- fork :: Board -> [Board] fork board = map fromJust $ filter isJust $ map (\val -> set board pivot val) values where candidates = [(coord, len) | (coord, Values _ len) <- assocs board] pivot = pivot' (9, 9) 10 candidates where pivot' coord len [] = coord pivot' coord len ((coord', len'):ls) | len' == 2 = coord' | len' < len = pivot' coord' len' ls | otherwise = pivot' coord len ls Values arr _ = board ! pivot values = map fst $ filter snd $ assocs arr -------------------------------------------------------------------------------- isDone :: Board -> Bool isDone board = all isCellSet $ elems board -------------------------------------------------------------------------------- solve :: Board -> [Board] solve board = if isDone board then [board] else concat $ map solve $ fork board -------------------------------------------------------------------------------- mkBoard :: [Int] -> Maybe Board mkBoard ns | length ns == 81 = fst $ foldl' setter (Just nullBoard, (0, 0)) ns | otherwise = error ("mkBoard: wrong input list length: " ++ show ns) where setter :: (Maybe Board, Coord) -> Int -> (Maybe Board, Coord) setter (Nothing, _) _ = (Nothing, (0, 0)) setter (Just board, coord) val | val == 0 = (Just board, next coord) | 1 <= val && val <= 9 = ((set board coord val), next coord) | otherwise = error ("mkBoard: wrong input value '" ++ show (val) ++ "' at " ++ show (coord)) nullBoard = listArray ((0, 0), (8, 8)) (replicate 81 nullCell) nullCell = Values (listArray (1, 9) (replicate 9 True)) 9 -------------------------------------------------------------------------------- convert :: String -> [Maybe Board] convert str = convert' $ filter (\s -> head s /= 'G') $ (lines str) where convert' :: [String] -> [Maybe Board] convert' [] = [] convert' strs = let (h, t) = (splitAt 9 strs) in (mkBoard $ map digitToInt $ concat h) : convert' t -------------------------------------------------------------------------------- euler :: [Board] -> Int euler boards = foldl' (\acc board -> euler1 board + acc) 0 boards where euler1 :: Board -> Int euler1 board = 100 * val1 + 10 * val2 + val3 where Value val1 = board!(0, 0) Value val2 = board!(0, 1) Value val3 = board!(0, 2) -------------------------------------------------------------------------------- main = do file <- readFile "z:/euler/euler_0096.txt" putStrLn $ show $ euler $ concat $ map solve $ map fromJust $ filter isJust $ convert file -------------------------------------------------------------------------------- -- Debugging functions -------------------------------------------------------------------------------- showBoard :: (Array Coord String) -> String showBoard board = concat [concat [(board ! (i, j)) ++ (if j == 8 then "\n" else " ") | j <- [0..8]] | i <- [0..8]] showBoard' :: Maybe Board -> String showBoard' Nothing = "Nothing\n" showBoard' (Just board) = showBoard $ amap showCell board showCell :: Cell -> String showCell (Value v) = show v showCell (Values _ _) = "." showFree :: Cell -> String showFree (Value v) = "*" showFree (Values _ len) = show len --------------------------------------------------------------------------------
dpieroux/euler
0/0096_array.hs
mit
5,755
0
24
1,692
2,005
1,043
962
-1
-1
module SyntaxParser where import LexicalParser import Text.Parsec import Text.Parsec.String import Data.List data CompilationUnit = PackageDecl TypeName | ImportDecls [ImportDecl] | TypeDecls [TypeDecl] deriving (Eq,Ord,Show) data ImportDecl = ImportDecl TypeName deriving (Eq,Ord,Show) data TypeDecl = ClassDecl ClassDeclaration | EnumDecl EnumDeclaration deriving (Eq,Ord,Show) data ClassDeclaration = ClassDeclaration [ClassModifier] Ident [TypeParameter] SuperClass [SuperInterface] ClassBody deriving (Eq,Ord,Show) data EnumDeclaration = EnumDeclaration String -- TODO deriving (Eq, Ord, Show) data TypeName = TypeName String deriving (Eq,Ord,Show) data ClassModifier = ClassModifier String deriving (Eq, Ord, Show) data Ident = Ident InputElement deriving (Eq, Ord, Show) data TypeParameter = TypeParameter String deriving (Eq, Ord, Show) data SuperClass = SuperClass ClassType deriving (Eq, Ord, Show) data SuperInterface = SuperInterface ClassType deriving (Eq, Ord, Show) data ClassType = ClassType Ident [TypeParameter] deriving (Eq, Ord, Show) data ClassBody = ClassBody [InputElement] -- TODO deriving (Eq, Ord, Show) type JParser = GenParser InputElement () satisfy' p = tokenPrim showTok nextPos testTok where showTok t = show t testTok t = if p t then Just t else Nothing nextPos pos t ts = incSourceColumn pos 1 anyElement :: Monad m => ParsecT [InputElement] u m InputElement anyElement = satisfy' p <?> "input element" where p el = True keyword :: Monad m => String -> ParsecT [InputElement] u m InputElement keyword kw = satisfy' p <?> ("keyword " ++ kw) where p el = case el of T (Keyword keyword) -> keyword == kw _ -> False identifier :: Monad m => ParsecT [InputElement] u m InputElement identifier = satisfy' p <?> "identifier" where p el = case el of T (Identifier _) -> True _ -> False separator :: Monad m => String -> ParsecT [InputElement] u m InputElement separator s = satisfy' p <?> ("separator '" ++ s ++ "'") where p el = case el of T (Separator sep) -> sep == s _ -> False -- compilationUnit :: Parser CompilationUnit -- compilationUnit = packageDeclaration <|> (many importDeclaration) <|> (many typeDeclaration) packageDeclaration :: JParser CompilationUnit packageDeclaration = do keyword "package" result <- typeName separator ";" return $ PackageDecl result importDeclaration :: JParser ImportDecl importDeclaration = do keyword "import" result <- typeName separator ";" return $ ImportDecl result typeDeclaration :: JParser TypeDecl typeDeclaration = classDeclaration <|> interfaceDeclaration typeName :: JParser TypeName typeName = do result <- identifier `sepBy` (separator ".") let nameParts = map (\(T (Identifier x)) -> x) result return $ TypeName (intercalate "." nameParts) classDeclaration :: JParser TypeDecl classDeclaration = normalClass <|> enumClass interfaceDeclaration = undefined normalClass :: JParser TypeDecl normalClass = do modifiers <- many classModifier keyword "class" name <- identifier typeParams <- classTypeParams superClass <- (try $ keyword "extends") >> classType superInterfaces <- (try $ keyword "implements") >> (classType `sepBy` (separator ",")) separator "{" classBody <- many anyElement separator "}" let classDecl = ClassDeclaration modifiers (Ident name) typeParams (SuperClass superClass) (map (\x -> SuperInterface x ) superInterfaces) (ClassBody classBody) return $ ClassDecl classDecl classModifier :: JParser ClassModifier classModifier = undefined classTypeParams :: JParser [TypeParameter] classTypeParams = undefined classType :: JParser ClassType classType = undefined enumClass :: JParser TypeDecl enumClass = undefined -- parseSyntax :: String -> Either ParseError CompilationUnit -- parseSyntax input = parse compilationUnit "unknown" input parseJava input = parse elements "unknown" input parseSyntax input = parse importDeclaration "" tokens where tokens = case (parseJava input) of Right toks -> filter (not . isWhitespace) toks _ -> [] isWhitespace t = case t of Whitespace -> True _ -> False
dimsuz/java-ast
src/SyntaxParser.hs
mit
4,581
0
16
1,157
1,321
673
648
108
3
module FieldMarshal.Marshal where import qualified FieldMarshal.CSharp as CSharp import qualified FieldMarshal.Cpp as Cpp data MarshalType = MarshalDefault Cpp.Type CSharp.Type | MarshalAs Cpp.Type CSharp.Type UnmanagedType | MarshalWrap Cpp.Type CSharp.Type [CppTypeWrapper] | MarshalPlatform Cpp.Type CSharp.Type [(Platform, CppTypeWrapper)] deriving (Eq, Show) newtype UnmanagedType = UnmanagedType String deriving (Eq, Show) data Platform = Microsoft | Mono deriving (Eq, Show) data ConversionCode = ConversionCode UnmanagedType Cpp.Type [String] [String] deriving (Eq, Show) data CppTypeWrapper = WrapToCppOwned ConversionCode | WrapToCppUnowned ConversionCode | WrapToCSharpOwned ConversionCode | WrapToCSharpUnowned ConversionCode deriving (Eq, Show)
scott-fleischman/field-marshal
FieldMarshal.Marshal.hs
mit
793
0
8
118
208
121
87
21
0
module Handler.Frontend where import Import -- will redirect to login page if not authenticated getFrontendR :: [Text] -> Handler Html getFrontendR _ = do _ <- requireAuth defaultLayout $ do setTitle "happy scheduler" $(widgetFile "frontend")
frt/happyscheduler
Handler/Frontend.hs
mit
269
0
12
61
63
31
32
8
1
module Data.NGH.Formats.FastQ ( fastQConduit , fastQparse , fastQread , fastQwrite ) where import Data.Word import qualified Data.ByteString as B import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Char8 as L8 import Data.NGH.FastQ import Data.Conduit import Control.Monad import qualified Data.Conduit.Binary as CB -- | fastQConduit is a Conduit from B.ByteString to DNAwQuality fastQConduit :: (Monad m) => Word8 -> Conduit B.ByteString m DNAwQuality fastQConduit q = CB.lines =$= fastQConduit' q fastQConduit' :: (Monad m) => Word8 -> Conduit B.ByteString m DNAwQuality fastQConduit' qualN = read1 >>= maybe (return ()) (\s -> yield s >> fastQConduit' qualN) where read1 = await >>= maybe (return Nothing) (\h -> do Just sq <- await void await Just qs <- await return . Just $ DNAwQuality { dna_seq = sq, header = h, qualities = B.map (flip (-) qualN) qs }) -- | fastQparse read a list of lines and returns a lazy list of DNAwQuality fastQparse :: Word8 -> [B.ByteString] -> [DNAwQuality] fastQparse _ [] = [] fastQparse qualN (h:sq:_:qs:rest) = (first:fastQparse qualN rest) where first = DNAwQuality { dna_seq=sq, header=h, qualities=B.map (flip (-) qualN) qs } fastQparse _ _ = error "Data.NGH.FastQ.fastQparse: incomplete record" fastQread :: Word8 -> L.ByteString -> [DNAwQuality] fastQread qualN = fastQparse qualN . map (S.concat . L.toChunks) . L8.lines -- | fastQwrite is to write in FastQ format. It does no IO, but formats it as a string fastQwrite :: Word8 -> DNAwQuality -> L.ByteString fastQwrite qualN DNAwQuality {header=h,dna_seq=s,qualities=qs} = L.fromChunks [h ,S8.pack "\n" ,s ,S8.pack "\n+\n" ,S.map (+ qualN) qs ,S8.pack "\n"]
luispedro/NGH
Data/NGH/Formats/FastQ.hs
mit
1,996
0
18
494
598
333
265
40
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} module PresentDrop ( initialModel , update , view ) where import Control.Distributed.Process import Control.Lens (at, ix, makeLenses, over, set, toListOf) import qualified Control.Lens as Lens import Data.Aeson import Data.Aeson.Casing import Data.Binary import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Text (Text) import GHC.Generics import Network.GameEngine import System.Random data Coords = Coords { _x :: Double , _y :: Double } deriving (Show, Eq, Binary, Generic) data Player = Player { _position :: Coords , _score :: Integer , _name :: Text , _color :: Text } deriving (Show, Eq, Binary, Generic) data Gps = Gps { _gpsPosition :: Coords , _variance :: Double } deriving (Show, Eq, Binary, Generic) data Model = Model { _players :: Map SendPortId Player , _gpss :: [Gps] , _present :: Coords , _rng :: StdGen } deriving (Show) makeLenses ''Coords makeLenses ''Player makeLenses ''Gps makeLenses ''Model instance FromJSON Coords where parseJSON = genericParseJSON $ aesonDrop 1 camelCase instance ToJSON Coords where toJSON = genericToJSON $ aesonDrop 1 camelCase instance ToJSON Player where toJSON = genericToJSON $ aesonDrop 1 camelCase data View = View { viewPlayers :: [Player] , viewGpss :: [ViewGps] , viewSampleCommands :: [Msg] } deriving (Show, Eq, Binary, Generic) data ViewGps = ViewGps { viewGpsPosition :: Coords , viewGpsDistance :: Double } deriving (Show, Eq, Binary, Generic) instance ToJSON View where toJSON = genericToJSON $ aesonPrefix camelCase instance ToJSON ViewGps where toJSON = genericToJSON $ aesonDrop 7 camelCase ------------------------------------------------------------ hypotenuse :: Floating r => r -> r -> r hypotenuse dx dy = sqrt $ (dx ^ (2 :: Int)) + (dy ^ (2 :: Int)) normalise :: (Floating r, Ord r) => (r, r) -> (r, r) normalise (dx, dy) = if h <= 1 then (dx, dy) else (dx / h, dy / h) where h = hypotenuse dx dy distanceBetween :: Coords -> Coords -> Double distanceBetween a b = hypotenuse dx dy where dx = Lens.view x a - Lens.view x b dy = Lens.view y a - Lens.view y b randomPair :: (RandomGen g, Random a) => (a, a) -> g -> ((a, a), g) randomPair range stdGen = ((a, b), stdGen'') where (a, stdGen') = randomR range stdGen (b, stdGen'') = randomR range stdGen' ------------------------------------------------------------ initialModel :: StdGen -> Model initialModel stdGen = Model { _players = Map.empty , _gpss = [ Gps { _gpsPosition = Coords (-10) (-8) , _variance = 0 } , Gps { _gpsPosition = Coords 12 (-5) , _variance = 0 } , Gps { _gpsPosition = Coords (-4) 9 , _variance = 0 } ] , _present = Coords 5 3 , _rng = stdGen } newPlayer :: Player newPlayer = Player { _name = "<Your Name Here>" , _score = 0 , _position = Coords 0 0 , _color = "white" } data Msg = SetName Text | SetColor Text | Move Coords deriving (Show, Eq, Binary, Generic, FromJSON, ToJSON) update :: EngineMsg Msg -> Model -> Model update msg = handleWin . handleMsg msg handleWin :: Model -> Model handleWin model = if null overlappingPlayers then model else let withIncrementedScores aModel = Map.foldlWithKey (\aModel' portId _ -> over (players . ix portId . score) (+ 1) aModel') aModel overlappingPlayers in movePresent . withIncrementedScores $ model where overlappingPlayers :: Map SendPortId Player overlappingPlayers = Map.filter inRange (Lens.view players model) inRange :: Player -> Bool inRange player = distanceBetween (Lens.view present model) (Lens.view position player) < 1 movePresent :: Model -> Model movePresent model = set rng newRng $ set present (Coords newX newY) model where ((newX, newY), newRng) = randomPair (-10, 10) $ Lens.view rng model handleMsg :: EngineMsg Msg -> Model -> Model handleMsg (Join playerId) = set (players . at playerId) (Just newPlayer) handleMsg (Leave playerId) = set (players . at playerId) Nothing handleMsg (GameMsg playerId (SetName newName)) = set (players . ix playerId . name) newName handleMsg (GameMsg playerId (SetColor text)) = set (players . ix playerId . color) text handleMsg (GameMsg playerId (Move moveTo)) = over (players . ix playerId . position) updatePosition where updatePosition = over x (dx +) . over y (dy +) (dx, dy) = normalise (Lens.view x moveTo, Lens.view y moveTo) view :: Model -> View view model = View { viewPlayers = toListOf (players . traverse) model , viewGpss = viewGps (Lens.view present model) <$> Lens.view gpss model , viewSampleCommands = [SetName "Kris", SetColor "#ff0000", Move $ Coords 1.0 (-2.0)] } viewGps :: Coords -> Gps -> ViewGps viewGps presentPosition gps = ViewGps { viewGpsPosition = Lens.view gpsPosition gps , viewGpsDistance = distanceBetween presentPosition (Lens.view gpsPosition gps) + Lens.view variance gps }
topliceanu/learn
elm/Cloud-Haskell-Game/server/src/PresentDrop.hs
mit
5,315
0
17
1,215
1,828
996
832
161
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Preprocessor (PreprocessorState, preprocessProg, resolveExpr) where import Expr import Program import Control.Monad.State import Text.Printf (printf) import qualified Data.Map.Strict as Map type Offset = Int type ConstExprMap = Map.Map String Expr data PreprocessorState = PreprocessorState {currOffset :: Offset ,constexprs :: ConstExprMap} deriving (Show) initialPreprocessorState :: PreprocessorState initialPreprocessorState = PreprocessorState {currOffset = 0 ,constexprs = Map.empty} newtype Preprocessor a = Preprocessor {runPreprocessor :: State PreprocessorState a} deriving (Functor,Applicative,Monad,MonadState PreprocessorState) incrOffset :: Int -> Preprocessor () incrOffset n = modify $ \s -> s {currOffset = (currOffset s) + 1} modifyConstExprs :: (ConstExprMap -> ConstExprMap) -> Preprocessor () modifyConstExprs f = modify $ \s -> s {constexprs = f (constexprs s)} insertConstExpr :: String -> Expr -> Preprocessor () insertConstExpr n e = modifyConstExprs $ Map.insert n e preprocessStmt :: Stmt -> Preprocessor () preprocessStmt (StInsn _) = incrOffset 1 preprocessStmt (StLabel name) = do coff <- gets currOffset insertConstExpr name (ExprInteger (toInteger coff)) preprocessStmt (StConstExpr name expr) = insertConstExpr name expr execPreprocessor :: Preprocessor a -> PreprocessorState execPreprocessor m = execState (runPreprocessor m) initialPreprocessorState preprocessProg :: Program -> Either String PreprocessorState preprocessProg prog = Right $ execPreprocessor $ mapM_ preprocessStmt prog resolveExpr :: PreprocessorState -> Expr -> Either String Expr resolveExpr p (ExprRef n) = let ces = constexprs p lu = Map.lookup n ces in case lu of Nothing -> Left $ printf "Failed to resolve constexpr ref \"%s\"" n Just e -> resolveExpr p e resolveExpr _ e | (resolved e) = Right e | otherwise = Left $ printf "failed to resolve constexpr: %s" (show e)
nyaxt/dmix
nkmd/as/Preprocessor.hs
mit
2,042
0
11
374
607
316
291
51
2
module PlasmaCutter where import BasicTypes import LineSintaticScanner import BoolExprSintaticScanner extractCode :: [String] -> Environment -> [String] extractCode [] _ = [] extractCode (x:xs) env = extr ++ (extractCode xs newEnv) where extr = [snd $ extractLine (parseLine x) env] newEnv = fst $ extractLine (parseLine x) env extractLine :: Line -> Environment -> (Environment, String) extractLine (Condition line) (var,st) = ((var, newSt), []) where evRes = evaluateCondition line var newSt = [evRes] ++ st extractLine (EndCondition) (var,st) = ((var, tail st), []) extractLine (CodeLine line) env@(_,st) = if head st then (env, line) else (env, []) evaluateCondition :: String -> Variables -> Bool evaluateCondition fun env = evalFunction env $ parseFunction fun evalFunction :: Variables -> Expression -> Bool evalFunction env (And lhs rhs) = (evalFunction env lhs) && (evalFunction env rhs) evalFunction env (Or lhs rhs) = (evalFunction env lhs) || (evalFunction env rhs) evalFunction env (Not exp) = not (evalFunction env exp) evalFunction env (ExpId var) = let exp = [snd x | x <- env, var == fst x] in case exp of [] -> error (var ++ " not in scope.") [x] -> x
hephaestus-pl/hephaestus
willian/hephaestus-parser-only/PlasmaCutter.hs
mit
1,212
0
12
230
517
275
242
26
2
module Chapter5 where import Chapter4 (rjustify) -- 5.1.3 binom :: Int -> Int -> Int binom n k | n < 0 = 0 | k == 0 = 1 | otherwise = binom (n - 1) k + binom (n - 1) (k - 1) binomSum :: Int -> Int binomSum n = sum [binom n k | k <- [0..n]] pascal :: Int -> [[Int]] pascal x = [map (uncurry binom) xs | xs <- xss] where elemCount = x + 1 xss = [take elemCount (drop n elems) | n <- [0, elemCount..(length elems - elemCount)]] elems = [(a, b) | a <- [0..x], b <- [0..x]] printPascal :: Int -> IO() printPascal x = mapM_ putStr table where pascalTriangle = pascal x table = header ++ ["\n"] ++ divisor ++ ["\n"] ++ content justification = 1 + (longestDigit pascalTriangle) divisor = take (2 + (length pascalTriangle + 1) * justification) (repeat "-") content = map row (zip pascalTriangle [0..length pascalTriangle]) row (r, idx) = rowIndex idx ++ rowContent (rjustify justification) r rowIndex idx = (rjustify justification (show idx)) ++ " |" header = [" " ++ rjustify justification "|"] ++ map ((rjustify justification) . show) [0..length pascalTriangle - 1] rowContent rjustified xs = foldr ((++) . rjustified . showNonZero) "\n" xs showNonZero y = if y > 0 then show y else " " longestDigit :: [[Int]] -> Int longestDigit = -- maximum . concat . map (map digits) maximum . map localLongestDigit localLongestDigit :: [Int] -> Int localLongestDigit = maximum . map digitCount digitCount :: Integral a => Int -> a digitCount n = floor $ logBase 10.0 (fromIntegral n) + 1 (!) :: [a] -> Int -> a (!) [] _ = error "empty list" (!) (x:xs) i | i == 0 = x | otherwise = xs ! (i - 1) takewhile :: (a -> Bool) -> [a] -> [a] takewhile _ [] = [] takewhile p (x:xs) | p x = x : takewhile p xs | otherwise = [] dropwhile :: (a -> Bool) -> [a] -> [a] dropwhile _ [] = [] dropwhile p ys@(x:xs) | p x = dropwhile p xs | otherwise = ys inits :: [a] -> [[a]] inits [] = [[]] inits (x:xs) = [[]] ++ map (x:) (inits xs) subs :: [a] -> [[a]] subs [] = [[]] subs (x:xs) = subs' ++ map (x:) subs' where subs' = subs xs intersperse :: a -> [a] -> [[a]] intersperse x [] = [[x]] intersperse x (y:ys) = [x:y:ys] ++ map (y:) (intersperse x ys) perms :: [a] -> [[a]] perms [] = [[]] perms (x:xs) = concat . map (intersperse x) $ perms xs perms' :: [a] -> [[a]] perms' [] = [[]] perms' (x:xs) = [zs | ys <- perms xs, zs <- intersperse x ys] -- 5.6.1 -- length segs = sum [1..length xs] + 1 segs :: [a] -> [[a]] segs [] = [[]] segs (x:xs) = segs xs ++ map (x:) (inits xs) segs' :: [a] -> [[a]] segs' xs = segstr xs [[]] -- segstr xs [] where segstr [] acc = acc -- [[]] ++ acc segstr (y:ys) acc = segstr ys (map (y:) (inits ys) ++ acc) -- 5.6.2 -- length (choose k xs) == binom (length xs) k choose :: Int -> [a] -> [[a]] choose _ [] = [[]] choose 0 _ = [[]] choose k xs@(y:ys) | length xs == k = [xs] | otherwise = choose k ys ++ map (y:) (choose (k - 1) ys)
futtetennista/IntroductionToFunctionalProgramming
itfp/src/Chapter5.hs
mit
3,207
0
13
969
1,616
855
761
127
2
module Language.Tiny.Analysis.Grammar where data Program = Program [Declaration] deriving (Eq, Show) data Declaration = FunctionDeclaration Annotation String [Parameter] Block | VariableDeclaration Variable deriving (Eq, Show) data Variable = Variable Annotation String deriving (Eq, Show) data Parameter = Parameter Annotation String deriving (Eq, Show) data Annotation = IntAnnotation | CharAnnotation | ArrayAnnotation Annotation Expression deriving (Eq, Ord, Show) data Block = Block [Variable] [Statement] deriving (Eq, Show) data Statement = Conditional Expression Statement | Alternative Expression Statement Statement | Loop Expression Statement | Statements Block | Assignment Lefthand Expression | ArrayAssignment Lefthand Expression | ReturnStatement Expression | VoidCall String [Expression] | Output Expression | Input Lefthand | Nop deriving (Eq, Show) data Lefthand = ScalarAccess String | ArrayAccess Lefthand Expression deriving (Eq, Ord, Show) data Expression = Lefthand Lefthand | Add Expression Expression | Subtract Expression Expression | Multiply Expression Expression | Divide Expression Expression | Equality Expression Expression | Inequality Expression Expression | GreaterThan Expression Expression | LessThan Expression Expression | Negate Expression | Not Expression | IntValue Int | Call String [Expression] | CharValue Char | ArrayLength Lefthand deriving (Eq, Ord, Show)
dmeysman/tiny-compiler
src/Language/Tiny/Analysis/Grammar.hs
mit
1,505
0
7
284
400
228
172
56
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagrequest.html module Stratosphere.ResourceProperties.EC2EC2FleetTagRequest where import Stratosphere.ResourceImports -- | Full data type definition for EC2EC2FleetTagRequest. See -- 'ec2EC2FleetTagRequest' for a more convenient constructor. data EC2EC2FleetTagRequest = EC2EC2FleetTagRequest { _eC2EC2FleetTagRequestKey :: Maybe (Val Text) , _eC2EC2FleetTagRequestValue :: Maybe (Val Text) } deriving (Show, Eq) instance ToJSON EC2EC2FleetTagRequest where toJSON EC2EC2FleetTagRequest{..} = object $ catMaybes [ fmap (("Key",) . toJSON) _eC2EC2FleetTagRequestKey , fmap (("Value",) . toJSON) _eC2EC2FleetTagRequestValue ] -- | Constructor for 'EC2EC2FleetTagRequest' containing required fields as -- arguments. ec2EC2FleetTagRequest :: EC2EC2FleetTagRequest ec2EC2FleetTagRequest = EC2EC2FleetTagRequest { _eC2EC2FleetTagRequestKey = Nothing , _eC2EC2FleetTagRequestValue = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagrequest.html#cfn-ec2-ec2fleet-tagrequest-key ececftrKey :: Lens' EC2EC2FleetTagRequest (Maybe (Val Text)) ececftrKey = lens _eC2EC2FleetTagRequestKey (\s a -> s { _eC2EC2FleetTagRequestKey = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagrequest.html#cfn-ec2-ec2fleet-tagrequest-value ececftrValue :: Lens' EC2EC2FleetTagRequest (Maybe (Val Text)) ececftrValue = lens _eC2EC2FleetTagRequestValue (\s a -> s { _eC2EC2FleetTagRequestValue = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/EC2EC2FleetTagRequest.hs
mit
1,756
0
12
205
264
151
113
27
1
{-# LANGUAGE OverloadedStrings #-} {- Custom prettyprinter for JMacro AST - uses the jmacro prettyprinter for most of the work - fixme: need a better way to make a customized prettyprinter, without duplicating 5 cases -} module Gen2.Printer where import Data.Char (isAlpha, isDigit) import qualified Data.Map as M import qualified Data.Text.Lazy as TL import qualified Data.Text as T import Prelude import Text.PrettyPrint.Leijen.Text (Doc, align, char, comma, fillSep, hcat, nest, parens, punctuate, text, vcat, (<+>)) import qualified Text.PrettyPrint.Leijen.Text as PP import Compiler.JMacro (Ident, JExpr(..), JStat(..), JOp(..), JVal(..), jsToDocR, RenderJs(..), defaultRenderJs) pretty :: JStat -> Doc pretty = jsToDocR ghcjsRenderJs ghcjsRenderJs :: RenderJs ghcjsRenderJs = defaultRenderJs { renderJsV = ghcjsRenderJsV , renderJsS = ghcjsRenderJsS } -- attempt to resugar some of the common constructs ghcjsRenderJsS :: RenderJs -> JStat -> Doc ghcjsRenderJsS r (BlockStat xs) = prettyBlock r (flattenBlocks xs) ghcjsRenderJsS r s = renderJsS defaultRenderJs r s -- don't quote keys in our object literals, so closure compiler works ghcjsRenderJsV :: RenderJs -> JVal -> Doc ghcjsRenderJsV r (JHash m) | M.null m = text "{}" | otherwise = braceNest . fillSep . punctuate comma . map (\(x,y) -> quoteIfRequired x <> PP.colon <+> jsToDocR r y) $ M.toList m where quoteIfRequired x | isUnquotedKey x = text (TL.fromStrict x) | otherwise = PP.squotes (text (TL.fromStrict x)) isUnquotedKey x | T.null x = False | T.all isDigit x = True | otherwise = validFirstIdent (T.head x) && T.all validOtherIdent (T.tail x) -- fixme, this will quote some idents that don't really need to be quoted validFirstIdent c = c == '_' || c == '$' || isAlpha c validOtherIdent c = isAlpha c || isDigit c ghcjsRenderJsV r v = renderJsV defaultRenderJs r v prettyBlock :: RenderJs -> [JStat] -> Doc prettyBlock r xs = vcat $ map addSemi (prettyBlock' r xs) -- recognize common patterns in a block and convert them to more idiomatic/concise javascript prettyBlock' :: RenderJs -> [JStat] -> [Doc] -- resugar for loops with/without var declaration prettyBlock' r ( (DeclStat i) : (AssignStat (ValExpr (JVar i')) v0) : (WhileStat False p (BlockStat bs)) : xs ) | i == i' && not (null flat) && isForUpdStat (last flat) = mkFor r True i v0 p (last flat) (init flat) : prettyBlock' r xs where flat = flattenBlocks bs prettyBlock' r ( (AssignStat (ValExpr (JVar i)) v0) : (WhileStat False p (BlockStat bs)) : xs ) | not (null flat) && isForUpdStat (last flat) = mkFor r False i v0 p (last flat) (init flat) : prettyBlock' r xs where flat = flattenBlocks bs -- global function (does not preserve semantics but works for GHCJS) prettyBlock' r ( (DeclStat i) : (AssignStat (ValExpr (JVar i')) (ValExpr (JFunc is b))) : xs ) | i == i' = (text "function" <+> jsToDocR r i <> parens (fillSep . punctuate comma . map (jsToDocR r) $ is) $$ braceNest' (jsToDocR r b) ) : prettyBlock' r xs -- declare/assign prettyBlock' r ( (DeclStat i) : (AssignStat (ValExpr (JVar i')) v) : xs ) | i == i' = (text "var" <+> jsToDocR r i <+> char '=' <+> jsToDocR r v) : prettyBlock' r xs -- modify/assign operators (fixme this should be more general, but beware of side effects like PPostExpr) prettyBlock' r ( (AssignStat (ValExpr (JVar i)) (InfixExpr AddOp (ValExpr (JVar i')) (ValExpr (JInt 1)))) : xs ) | i == i' = ("++" <> jsToDocR r i) : prettyBlock' r xs prettyBlock' r ( (AssignStat (ValExpr (JVar i)) (InfixExpr SubOp (ValExpr (JVar i')) (ValExpr (JInt 1)))) : xs ) | i == i' = ("--" <> jsToDocR r i) : prettyBlock' r xs prettyBlock' r ( (AssignStat (ValExpr (JVar i)) (InfixExpr AddOp (ValExpr (JVar i')) e)) : xs ) | i == i' = (jsToDocR r i <+> text "+=" <+> jsToDocR r e) : prettyBlock' r xs prettyBlock' r ( (AssignStat (ValExpr (JVar i)) (InfixExpr SubOp (ValExpr (JVar i')) e)) : xs ) | i == i' = (jsToDocR r i <+> text "-=" <+> jsToDocR r e) : prettyBlock' r xs prettyBlock' r (x:xs) = jsToDocR r x : prettyBlock' r xs prettyBlock' _ [] = [] -- build the for block mkFor :: RenderJs -> Bool -> Ident -> JExpr -> JExpr -> JStat -> [JStat] -> Doc mkFor r decl i v0 p s1 sb = text "for" <> forCond <+> braceNest'' (jsToDocR r $ BlockStat sb) where c0 | decl = text "var" <+> jsToDocR r i <+> char '=' <+> jsToDocR r v0 | otherwise = jsToDocR r i <+> char '=' <+> jsToDocR r v0 forCond = parens $ hcat $ interSemi [ c0 , jsToDocR r p , parens (jsToDocR r s1) ] -- check if a statement is suitable to be converted to something in the for(;;x) position isForUpdStat :: JStat -> Bool isForUpdStat UOpStat {} = True isForUpdStat AssignStat {} = True isForUpdStat ApplStat {} = True isForUpdStat _ = False interSemi :: [Doc] -> [Doc] interSemi [] = [PP.empty] interSemi [s] = [s] interSemi (x:xs) = x <> text ";" : interSemi xs addSemi :: Doc -> Doc addSemi x = x <> text ";" -- stuff below is from jmacro infixl 5 $$, $+$ ($+$), ($$), ($$$) :: Doc -> Doc -> Doc x $+$ y = x PP.<$> y x $$ y = align (x $+$ y) x $$$ y = align (nest 2 $ x $+$ y) flattenBlocks :: [JStat] -> [JStat] flattenBlocks (BlockStat y:ys) = flattenBlocks y ++ flattenBlocks ys flattenBlocks (y:ys) = y : flattenBlocks ys flattenBlocks [] = [] braceNest :: Doc -> Doc braceNest x = char '{' <+> nest 2 x $$ char '}' braceNest' :: Doc -> Doc braceNest' x = nest 2 (char '{' $+$ x) $$ char '}' -- somewhat more compact (egyptian style) braces braceNest'' :: Doc -> Doc braceNest'' x = nest 2 (char '{' PP.<$> x) PP.<$> char '}'
ghcjs/ghcjs
src/Gen2/Printer.hs
mit
6,578
0
16
2,109
2,245
1,138
1,107
110
1
import Data.List import Data.Function import Control.Applicative import Control.Monad import Control.Arrow getGrid :: String -> IO [[Float]] getGrid filename = map (map read . filter ((>0) . length) . filter (',' `notElem`) . groupBy ((==) `on` (== ','))) . lines <$> readFile filename getMod3 :: Int -> [a] -> [a] getMod3 res xs = map fst $ filter ((== res) . (`mod` 3) . snd) $ zip xs [0..] zipCoords :: [[a]] -> [[((Int,Int),a)]] zipCoords xss = zipWith (\r xs -> zipWith (\c x -> ((r,c),x)) [0..] xs) [0..] xss mod3Sum :: Int -> Int -> [[Float]] -> Float mod3Sum rm cm = sum . concat . getMod3 rm . map (getMod3 cm) mod3Slant s (r,c) = ((r-c+s+1) `mod` 3, (r+c+2) `mod` 3) -- second coord: (r+c+2) or (s-r+2) or (2-c-s) mod3SlantSum :: Int -> Int -> Int -> [[Float]] -> Float mod3SlantSum s rm cm = sum . map snd . filter ((== (rm,cm)) . fst) . map (mod3Slant s *** id) . concat . zipCoords dumpGrid :: Int -> IO () dumpGrid n = do g <- getGrid ("s" ++ show n ++ ".txt") putStrLn $ "== " ++ show n ++ " ==" forM_ [0..2] (\rm -> putStrLn $ intercalate "\t" $ map (\cm -> show $ mod3SlantSum n rm cm g) [0..2]) main = mapM_ dumpGrid [3..25]
betaveros/probabilistic-poliwraths
mod3.hs
mit
1,156
2
15
233
647
351
296
23
1
module WordNumber where import Data.List (intersperse, intercalate) digitToWord :: Int -> String digitToWord n | n == 1 = "one" | n == 2 = "two" | n == 3 = "three" | n == 4 = "four" | n == 5 = "five" | n == 6 = "six" | n == 7 = "seven" | n == 8 = "eight" | n == 9 = "nine" digits :: Int -> [Int] {- digits n = go n where leng = length (show n) divider = (^) 10 (leng -1) go n = divider -} -- (mod n 10) - retrieve the last digit -- (div n 10) - retrieve remaining digits minus the last one digits n = go n [] where go n result | ((div n 10) > 0) = go (div n 10) ((mod n 10) : result) | otherwise = n : result wordNumber :: Int -> String wordNumber n = concat (intersperse "-" (map digitToWord (digits n)))
Numberartificial/workflow
haskell-first-principles/haskell-from-first-principles-master/08/08.06.05-numbers-into-words.hs
mit
781
0
13
239
294
146
148
20
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module ExportSpec where import Data.Char import Data.Int import Data.Map import Data.Monoid import Data.Proxy import Data.Text hiding (unlines) import Data.Time import Elm import GHC.Generics import Test.Hspec hiding (Spec) import Test.Hspec as Hspec import Text.Printf -- Debugging hint: -- ghci> import GHC.Generics -- ghci> :kind! Rep Post -- ... data Post = Post { id :: Int , name :: String , age :: Maybe Double , comments :: [Comment] , promoted :: Maybe Comment , author :: Maybe String } deriving (Generic, ElmType) data Comment = Comment { postId :: Int , text :: Text , mainCategories :: (String, String) , published :: Bool , created :: UTCTime , tags :: Map String Int } deriving (Generic, ElmType) data Position = Beginning | Middle | End deriving (Generic,ElmType) data Timing = Start | Continue Double | Stop deriving (Generic,ElmType) newtype Useless = Useless () deriving (Generic, ElmType) newtype FavoritePlaces = FavoritePlaces {positionsByUser :: Map String [Position]} deriving (Generic,ElmType) -- | We don't actually use this type, we just need to see that it compiles. data LotsOfInts = LotsOfInts { intA :: Int8 , intB :: Int16 , intC :: Int32 , intD :: Int64 } deriving (Generic, ElmType) spec :: Hspec.Spec spec = do toElmTypeSpec toElmDecoderSpec toElmEncoderSpec toElmTypeSpec :: Hspec.Spec toElmTypeSpec = describe "Convert to Elm types." $ do it "toElmTypeSource Post" $ shouldMatchTypeSource (unlines ["module PostType exposing (..)" ,"" ,"import CommentType exposing (..)" ,"" ,"" ,"%s"]) defaultOptions (Proxy :: Proxy Post) "test/PostType.elm" it "toElmTypeSource Comment" $ shouldMatchTypeSource (unlines ["module CommentType exposing (..)" ,"" ,"import Date exposing (Date)" ,"import Dict exposing (Dict)" ,"" ,"" ,"%s"]) defaultOptions (Proxy :: Proxy Comment) "test/CommentType.elm" it "toElmTypeSource Position" $ shouldMatchTypeSource (unlines ["module PositionType exposing (..)","","","%s"]) defaultOptions (Proxy :: Proxy Position) "test/PositionType.elm" it "toElmTypeSource Timing" $ shouldMatchTypeSource (unlines ["module TimingType exposing (..)","","","%s"]) defaultOptions (Proxy :: Proxy Timing) "test/TimingType.elm" it "toElmTypeSource Useless" $ shouldMatchTypeSource (unlines ["module UselessType exposing (..)","","","%s"]) defaultOptions (Proxy :: Proxy Useless) "test/UselessType.elm" it "toElmTypeSource FavoritePlaces" $ shouldMatchTypeSource (unlines ["module FavoritePlacesType exposing (..)" ,"" ,"import PositionType exposing (..)" ,"" ,"" ,"%s"]) defaultOptions (Proxy :: Proxy FavoritePlaces) "test/FavoritePlacesType.elm" it "toElmTypeSourceWithOptions Post" $ shouldMatchTypeSource (unlines ["module PostTypeWithOptions exposing (..)" ,"" ,"import CommentType exposing (..)" ,"" ,"" ,"%s"]) (defaultOptions {fieldLabelModifier = withPrefix "post"}) (Proxy :: Proxy Post) "test/PostTypeWithOptions.elm" it "toElmTypeSourceWithOptions Comment" $ shouldMatchTypeSource (unlines ["module CommentTypeWithOptions exposing (..)" ,"" ,"import Date exposing (Date)" ,"import Dict exposing (Dict)" ,"" ,"" ,"%s"]) (defaultOptions {fieldLabelModifier = withPrefix "comment"}) (Proxy :: Proxy Comment) "test/CommentTypeWithOptions.elm" describe "Convert to Elm type references." $ do it "toElmTypeRef Post" $ toElmTypeRef (Proxy :: Proxy Post) `shouldBe` "Post" it "toElmTypeRef [Comment]" $ toElmTypeRef (Proxy :: Proxy [Comment]) `shouldBe` "List (Comment)" it "toElmTypeRef String" $ toElmTypeRef (Proxy :: Proxy String) `shouldBe` "String" it "toElmTypeRef (Maybe String)" $ toElmTypeRef (Proxy :: Proxy (Maybe String)) `shouldBe` "Maybe (String)" it "toElmTypeRef [Maybe String]" $ toElmTypeRef (Proxy :: Proxy [Maybe String]) `shouldBe` "List (Maybe (String))" it "toElmTypeRef (Map String (Maybe String))" $ toElmTypeRef (Proxy :: Proxy (Map String (Maybe String))) `shouldBe` "Dict (String) (Maybe (String))" toElmDecoderSpec :: Hspec.Spec toElmDecoderSpec = describe "Convert to Elm decoders." $ do it "toElmDecoderSource Comment" $ shouldMatchDecoderSource (unlines ["module CommentDecoder exposing (..)" ,"" ,"import CommentType exposing (..)" ,"import Date" ,"import Dict" ,"import Json.Decode exposing (..)" ,"import Json.Decode.Pipeline exposing (..)" ,"" ,"" ,"%s"]) defaultOptions (Proxy :: Proxy Comment) "test/CommentDecoder.elm" it "toElmDecoderSource Post" $ shouldMatchDecoderSource (unlines ["module PostDecoder exposing (..)" ,"" ,"import CommentDecoder exposing (..)" ,"import Json.Decode exposing (..)" ,"import Json.Decode.Pipeline exposing (..)" ,"import PostType exposing (..)" ,"" ,"" ,"%s"]) defaultOptions (Proxy :: Proxy Post) "test/PostDecoder.elm" it "toElmDecoderSourceWithOptions Post" $ shouldMatchDecoderSource (unlines ["module PostDecoderWithOptions exposing (..)" ,"" ,"import CommentDecoder exposing (..)" ,"import Json.Decode exposing (..)" ,"import Json.Decode.Pipeline exposing (..)" ,"import PostType exposing (..)" ,"" ,"" ,"%s"]) (defaultOptions {fieldLabelModifier = withPrefix "post"}) (Proxy :: Proxy Post) "test/PostDecoderWithOptions.elm" it "toElmDecoderSourceWithOptions Comment" $ shouldMatchDecoderSource (unlines ["module CommentDecoderWithOptions exposing (..)" ,"" ,"import CommentType exposing (..)" ,"import Date" ,"import Dict" ,"import Json.Decode exposing (..)" ,"import Json.Decode.Pipeline exposing (..)" ,"" ,"" ,"%s"]) (defaultOptions {fieldLabelModifier = withPrefix "comment"}) (Proxy :: Proxy Comment) "test/CommentDecoderWithOptions.elm" describe "Convert to Elm decoder references." $ do it "toElmDecoderRef Post" $ toElmDecoderRef (Proxy :: Proxy Post) `shouldBe` "decodePost" it "toElmDecoderRef [Comment]" $ toElmDecoderRef (Proxy :: Proxy [Comment]) `shouldBe` "(list decodeComment)" it "toElmDecoderRef String" $ toElmDecoderRef (Proxy :: Proxy String) `shouldBe` "string" it "toElmDecoderRef (Maybe String)" $ toElmDecoderRef (Proxy :: Proxy (Maybe String)) `shouldBe` "(maybe string)" it "toElmDecoderRef [Maybe String]" $ toElmDecoderRef (Proxy :: Proxy [Maybe String]) `shouldBe` "(list (maybe string))" it "toElmDecoderRef (Map String (Maybe String))" $ toElmDecoderRef (Proxy :: Proxy (Map String (Maybe String))) `shouldBe` "(map Dict.fromList (list (tuple2 (,) string (maybe string))))" toElmEncoderSpec :: Hspec.Spec toElmEncoderSpec = describe "Convert to Elm encoders." $ do it "toElmEncoderSource Comment" $ shouldMatchEncoderSource (unlines ["module CommentEncoder exposing (..)" ,"" ,"import CommentType exposing (..)" ,"import Exts.Date exposing (..)" ,"import Exts.Json.Encode exposing (..)" ,"import Json.Encode" ,"" ,"" ,"%s"]) defaultOptions (Proxy :: Proxy Comment) "test/CommentEncoder.elm" it "toElmEncoderSource Post" $ shouldMatchEncoderSource (unlines ["module PostEncoder exposing (..)" ,"" ,"import CommentEncoder exposing (..)" ,"import Json.Encode" ,"import PostType exposing (..)" ,"" ,"" ,"%s"]) defaultOptions (Proxy :: Proxy Post) "test/PostEncoder.elm" it "toElmEncoderSourceWithOptions Comment" $ shouldMatchEncoderSource (unlines ["module CommentEncoderWithOptions exposing (..)" ,"" ,"import CommentType exposing (..)" ,"import Exts.Date exposing (..)" ,"import Exts.Json.Encode exposing (..)" ,"import Json.Encode" ,"" ,"" ,"%s"]) (defaultOptions {fieldLabelModifier = withPrefix "comment"}) (Proxy :: Proxy Comment) "test/CommentEncoderWithOptions.elm" it "toElmEncoderSourceWithOptions Post" $ shouldMatchEncoderSource (unlines ["module PostEncoderWithOptions exposing (..)" ,"" ,"import CommentEncoder exposing (..)" ,"import Json.Encode" ,"import PostType exposing (..)" ,"" ,"" ,"%s"]) (defaultOptions {fieldLabelModifier = withPrefix "post"}) (Proxy :: Proxy Post) "test/PostEncoderWithOptions.elm" describe "Convert to Elm encoder references." $ do it "toElmEncoderRef Post" $ toElmEncoderRef (Proxy :: Proxy Post) `shouldBe` "encodePost" it "toElmEncoderRef [Comment]" $ toElmEncoderRef (Proxy :: Proxy [Comment]) `shouldBe` "(Json.Encode.list << List.map encodeComment)" it "toElmEncoderRef String" $ toElmEncoderRef (Proxy :: Proxy String) `shouldBe` "Json.Encode.string" it "toElmEncoderRef (Maybe String)" $ toElmEncoderRef (Proxy :: Proxy (Maybe String)) `shouldBe` "(Maybe.withDefault Json.Encode.null << Maybe.map Json.Encode.string)" it "toElmEncoderRef [Maybe String]" $ toElmEncoderRef (Proxy :: Proxy [Maybe String]) `shouldBe` "(Json.Encode.list << List.map (Maybe.withDefault Json.Encode.null << Maybe.map Json.Encode.string))" it "toElmEncoderRef (Map String (Maybe String))" $ toElmEncoderRef (Proxy :: Proxy (Map String (Maybe String))) `shouldBe` "(dict Json.Encode.string (Maybe.withDefault Json.Encode.null << Maybe.map Json.Encode.string))" shouldMatchTypeSource :: ElmType a => String -> Options -> a -> FilePath -> IO () shouldMatchTypeSource wrapping options x = shouldMatchFile . printf wrapping $ toElmTypeSourceWith options x shouldMatchDecoderSource :: ElmType a => String -> Options -> a -> FilePath -> IO () shouldMatchDecoderSource wrapping options x = shouldMatchFile . printf wrapping $ toElmDecoderSourceWith options x shouldMatchEncoderSource :: ElmType a => String -> Options -> a -> FilePath -> IO () shouldMatchEncoderSource wrapping options x = shouldMatchFile . printf wrapping $ toElmEncoderSourceWith options x shouldMatchFile :: String -> FilePath -> IO () shouldMatchFile actual fileExpected = do source <- readFile fileExpected actual `shouldBe` source initCap :: Text -> Text initCap t = case uncons t of Nothing -> t Just (c, cs) -> cons (Data.Char.toUpper c) cs withPrefix :: Text -> Text -> Text withPrefix prefix s = prefix <> ( initCap s)
InfernalKnight/elm-export
test/ExportSpec.hs
epl-1.0
13,066
0
19
4,554
2,363
1,266
1,097
338
2
module Primes where import Factor primes :: [Integer] primes = sieve [2..] where sieve (p:xs) = p : sieve [ x | x <- xs, x `rem` p /= 0] isPrime :: Integer -> Bool isPrime n = all (\p -> n `rem` p /= 0) [2.. sq n] where sq = ceiling . sqrt . fromInteger -- [primes.tex] primeFactorisation :: Integer -> [Integer] primeFactorisation n = go primes n where go :: [Integer] -> Integer -> [Integer] go _ 1 = [] go (p:ps) n | p `isFactorOf` n = p : go (p:ps) (n `div` p) | otherwise = go ps n
NorfairKing/project-euler
lib/haskell/Primes.hs
gpl-2.0
551
0
12
168
265
143
122
14
2
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} module Graph.Nachbar where -- $Id$ import Graph.Util import Graph.Iso import Autolib.Graph.Basic import Autolib.Graph.Ops import Autolib.Graph.Kneser ( petersen ) import Inter.Types import Autolib.Reporter import Autolib.Util.Teilfolgen import qualified Challenger as C import Autolib.Dot ( peng ) import Data.Typeable import Data.List ( partition ) data Nachbar = Nachbar deriving ( Eq, Ord, Show, Read, Typeable ) instance C.Partial Nachbar () ( Graph Int ) where describe p _ = vcat [ text "Gesucht ist ein Graph G mit der Eigenschaft:" , nest 4 $ vcat [ text "Für alle Knoten x, y gilt:" , text "Wenn x und y nicht benachbart sind," , text "dann besteht ihre gemeinsame Nachbarschaft" , text "aus genau einem Knoten." ] , text $ "Der Graph soll keine der folgenden Formen haben:" , nest 4 $ vcat [ text "C_5" , text "Petersen-Graph" , text "es gibt einen Knoten, der zu allen anderen benachbart ist" , text "K_x mit Dach" ] ] initial p _ = circle [ 1 .. 6 ] partial p _ g = do inform $ vcat [ text "Der Graph ist" , nest 4 $ toDoc g ] peng g validate g check_not_iso (circle [1 :: Int .. 5]) g check_not_iso petersen g check_not_dominated g nicht $ kx_mit_dach g total p _ g = do check_nach g {- make :: Make make = direct Nachbar () -} ---------------------------------------------------------------------------- check_nach :: GraphC a => Graph a -> Reporter () check_nach g = silent $ mapM_ ( check_paar g ) $ paare $ lknoten g paare :: [a] -> [(a,a)] paare (x : ys) = map ( (,) x ) ys ++ paare ys paare _ = [] check_paar :: GraphC a => Graph a -> (a, a) -> Reporter () check_paar g (x, y) = when ( not $ kante x y `elementOf` kanten g ) $ do let n = intersect (nachbarn g x) (nachbarn g y) when (1 /= cardinality n) $ reject $ fsep [ text "die Knoten", toDoc x, text "und", toDoc y , text "sind nicht benachbart" , text "und haben die gemeinsamen Nachbarn", toDoc n ] check_not_dominated g = do let dom = do x <- lknoten g guard $ degree g x == pred (cardinality $ knoten g) return x when ( not $ null dom ) $ reject $ vcat [ text "Diese Knoten sind zu allen anderen benachbart:" , nest 4 $ toDoc dom ] kx_mit_dach g = do inform $ text "hat der Graph die Form K_x mit Dach?" let (x, r) = divMod (cardinality $ knoten g) 2 assert ( 1 == r ) $ text "ist die Knotenanzahl ungerade?" inform $ fsep [ text "vielleicht für x = ", toDoc x ] let xs = sfilter ( \ v -> 2 == degree g v ) $ knoten g assert ( x == cardinality xs ) $ text "gibt es genau x Knoten vom Grad 2?" assert ( is_independent g xs ) $ text "bilden diese eine unabhängige Menge?" let g' = restrict (minusSet (knoten g) xs) g inform $ text "G' := G ohne diese Menge." let (ys, zs) = Data.List.partition ( \ v -> 0 < degree g' v ) $ lknoten g' assert ( 1 == length zs ) $ text "gibt es in G' genau eine Knoten vom Grad 0?" assert ( is_clique g' $ mkSet ys ) $ text "bilden die anderen Knoten in G' eine Clique?" --------------------------------------------------------------- -- | dreht ergebnis (ablehnen\/akzeptieren) um -- TODO: move to Reporter.Type nicht :: Reporter () -> Reporter () nicht r = do mx <- wrap r case mx of Nothing -> return () Just _ -> reject $ text "(nicht)"
Erdwolf/autotool-bonn
src/Graph/Nachbar.hs
gpl-2.0
3,611
83
15
999
1,105
577
528
87
2
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-} module Code.Burrows_Wheeler.Data where import Autolib.Reader import Autolib.ToDoc import Autolib.Size import Data.Typeable data Burrows_Wheeler = Burrows_Wheeler deriving ( Eq, Ord, Typeable ) $(derives [makeReader, makeToDoc] [''Burrows_Wheeler]) -- Local variables: -- mode: haskell -- End:
Erdwolf/autotool-bonn
src/Code/Burrows_Wheeler/Data.hs
gpl-2.0
354
0
9
46
76
45
31
8
0
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Hoodle.Coroutine.Select.ManipulateImage -- Copyright : (c) 2013 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <[email protected]> -- Stability : experimental -- Portability : GHC -- -- Manipulate Image in selection -- ----------------------------------------------------------------------------- module Hoodle.Coroutine.Select.ManipulateImage where import Control.Lens (set, view, _2) import Control.Monad (guard, when) import Control.Monad.Trans (liftIO) import Control.Monad.State (get) import Data.ByteString.Base64 (encode) import Data.Foldable (forM_) import Data.Monoid ((<>)) import Data.Time import qualified Graphics.GD.ByteString as G import Graphics.Rendering.Cairo -- import Data.Hoodle.BBox import Data.Hoodle.Simple import Graphics.Hoodle.Render.Item import Graphics.Hoodle.Render.Util.HitTest (isBBox2InBBox1) -- import Hoodle.Accessor import Hoodle.Coroutine.Commit import Hoodle.Coroutine.Draw import Hoodle.Coroutine.Pen import Hoodle.Device import Hoodle.ModelAction.Page import Hoodle.ModelAction.Pen import Hoodle.ModelAction.Select import Hoodle.ModelAction.Select.Transform import qualified Hoodle.Type.Alias as A import Hoodle.Type.Canvas import Hoodle.Type.Coroutine import Hoodle.Type.Enum import Hoodle.Type.Event import Hoodle.Type.HoodleState import Hoodle.Type.PageArrangement import Hoodle.View.Coordinate import Hoodle.View.Draw -- cropImage :: BBoxed Image -> MainCoroutine () cropImage imgbbx = do liftIO $ putStrLn "cropImage called" xst <- get let (cid,cinfobox) = view currentCanvas xst hdlmodst = view hoodleModeState xst epage = forBoth' unboxBiAct (flip getCurrentPageEitherFromHoodleModeState hdlmodst) cinfobox case hdlmodst of ViewAppendState _ -> return () SelectState thdl -> do case epage of Left _ -> return () Right tpage -> initCropImage cid (thdl,tpage) where initCropImage cid (thdl,tpage) = do r <- waitSomeEvent (\case PenDown _ _ _ -> True; _ -> False) case r of PenDown cid' pbtn pcoord -> do if (cid == cid') then startCropRect cid imgbbx (thdl,tpage) pcoord else return () _ -> return () startCropRect :: CanvasId -> BBoxed Image -> (A.Hoodle A.SelectMode,A.Page A.SelectMode) -> PointerCoord -> MainCoroutine () startCropRect cid imgbbx (thdl,tpage) pcoord0 = do xst <- get geometry <- liftIO $ getGeometry4CurrCvs xst forM_ ((desktop2Page geometry . device2Desktop geometry) pcoord0) $ \(p0,c0) -> do tsel <- createTempRender geometry (p0, BBox (unPageCoord c0) (unPageCoord c0)) ctime <- liftIO $ getCurrentTime nbbox <- newCropRect cid geometry tsel (unPageCoord c0) (unPageCoord c0,ctime) surfaceFinish (tempSurfaceSrc tsel) surfaceFinish (tempSurfaceTgt tsel) let pnum = (fst . tempInfo) tsel let BBox (x0,y0) (x1,y1) = nbbox img = bbxed_content imgbbx obbox = getBBox imgbbx when (isBBox2InBBox1 obbox nbbox) $ do mimg' <- liftIO $ createCroppedImage img obbox nbbox -- let (xo,yo) = img_pos img -- img' = img { img_pos = (x0,y0), img_dim = Dim (x1-x0) (y1-y0) } forM_ mimg' $ \img' -> do rimg' <- liftIO $ cnstrctRItem (ItemImage img') let ntpage = replaceSelection rimg' tpage nthdl <- liftIO $ updateTempHoodleSelectIO thdl ntpage (unPageNum pnum) commit . set hoodleModeState (SelectState nthdl) =<< (liftIO (updatePageAll (SelectState nthdl) xst)) invalidateAllInBBox Nothing Efficient return () -- | start making a new crop rectangle newCropRect :: CanvasId -> CanvasGeometry -> TempRender (PageNum,BBox) -> (Double,Double) -> ((Double,Double),UTCTime) -> MainCoroutine BBox newCropRect cid geometry tsel orig (prev,otime) = do let pnum = (fst . tempInfo) tsel r <- nextevent penMoveAndUpOnly r pnum geometry defact moveact upact where defact = newCropRect cid geometry tsel orig (prev,otime) -- moveact (pcoord,(x,y)) = do (willUpdate,(ncoord,ntime)) <- liftIO $ getNewCoordTime (prev,otime) (x,y) if willUpdate then do let oinfo@(_,BBox xy0 _) = tempInfo tsel nbbox = BBox xy0 (x,y) ninfo = set _2 nbbox oinfo invalidateTemp cid (tempSurfaceSrc tsel) (renderBoxSelection nbbox) newCropRect cid geometry tsel {tempInfo = ninfo} orig (ncoord,ntime) else defact -- upact pcoord = (return . snd . tempInfo) tsel createCroppedImage :: Image -> BBox -> BBox -> IO (Maybe Image) createCroppedImage img obbox@(BBox (xo0,yo0) (xo1,yo1)) nbbox@(BBox (xn0,yn0) (xn1,yn1)) = do let src = img_src img embed = getByteStringIfEmbeddedPNG src case embed of Nothing -> return Nothing Just bstr -> do gdimg <- G.loadPngByteString bstr (w,h) <- G.imageSize gdimg let w' = floor $ (fromIntegral w) * (xn1-xn0) / (xo1-xo0) h' = floor $ (fromIntegral h) * (yn1-yn0) / (yo1-yo0) x1 = floor $ (fromIntegral w) * (xn0-xo0) / (xo1-xo0) y1 = floor $ (fromIntegral h) * (yn0-yo0) / (yo1-yo0) ngdimg <- G.newImage (w',h') G.copyRegion (x1,y1) (w',h') gdimg (0,0) ngdimg nbstr <- G.savePngByteString ngdimg let nb64str = encode nbstr nebdsrc = "data:image/png;base64," <> nb64str return . Just $ Image nebdsrc (xn0,yn0) (Dim (xn1-xn0) (yn1-yn0)) rotateImage :: RotateDir -> BBoxed Image -> MainCoroutine () rotateImage dir imgbbx = do xst <- get let (cid,cinfobox) = view currentCanvas xst hdlmodst = view hoodleModeState xst pnum = (PageNum . forBoth' unboxBiAct (view currentPageNum)) cinfobox epage = forBoth' unboxBiAct (flip getCurrentPageEitherFromHoodleModeState hdlmodst) cinfobox case hdlmodst of ViewAppendState _ -> return () SelectState thdl -> do case epage of Left _ -> return () Right tpage -> do let img = bbxed_content imgbbx mimg' <- liftIO (createRotatedImage dir img (getBBox imgbbx)) forM_ mimg' $ \img' -> do rimg' <- liftIO $ cnstrctRItem (ItemImage img') let ntpage = replaceSelection rimg' tpage nthdl <- liftIO $ updateTempHoodleSelectIO thdl ntpage (unPageNum pnum) commit . set hoodleModeState (SelectState nthdl) =<< (liftIO (updatePageAll (SelectState nthdl) xst)) invalidateAllInBBox Nothing Efficient return () createRotatedImage :: RotateDir -> Image -> BBox -> IO (Maybe Image) createRotatedImage dir img (BBox (x0,y0) (x1,y1)) = do let src = img_src img embed = getByteStringIfEmbeddedPNG src case embed of Nothing -> return Nothing Just bstr -> do gdimg <- G.loadPngByteString bstr (w,h) <- G.imageSize gdimg ngdimg <- G.rotateImage (case dir of CW -> 3 ; CCW -> 1) gdimg nbstr <- G.savePngByteString ngdimg let nb64str = encode nbstr nebdsrc = "data:image/png;base64," <> nb64str return . Just $ Image nebdsrc (x0,y0) (Dim (y1-y0) (x1-x0))
wavewave/hoodle-core
src/Hoodle/Coroutine/Select/ManipulateImage.hs
gpl-3.0
7,842
0
27
2,220
2,398
1,235
1,163
158
6
sayMe :: (Integral a) => a -> String sayMe 1 = "One!" sayMe 2 = "Two!" sayMe 3 = "Three!" sayMe 4 = "Four!" sayMe 5 = "Five!" sayMe x = "Not between 1 and 5" factorial :: (Integral a) => a -> a factorial 0 = 1 factorial n = n * factorial (n - 1) head' :: [a] -> a head' [] = error "Cannot call head on an empty list, sir." head' (x:_) = x length' :: (Num b) => [a] -> b length' [] = 0 length' (_:xs) = 1 + length' xs capital :: String -> String capital "" = "Empty string, sir" capital all@(x:xs) = "The first chaarcter of " ++ all ++ " is " ++ [x] bmiTell :: (RealFloat a) => a -> String bmiTell bmi | (bmi <= 18.5) = "You're underweight, you emo, you!" | (bmi <= 25.0) = "You're supposedly normal. Pffft, I bet you're ugly!" | (bmi <= 30.0) = "You're fat! Lose some weight, fatty!" | otherwise = "You're a whale, congratulations!" max' :: (Ord a) => a -> a -> a max' a b | a > b = a | otherwise = b -- max' :: (Ord a) => a -> a -> a -- max' a b | a > b = a | otherwise = b bmiTell' :: (RealFloat a) => a -> a -> String bmiTell' weight height | bmi <= skinny = "You're underweight, you emo, you!" | bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!" | bmi <= fat = "You're fat! Lose some weight, fatty!" | otherwise = "You're a whale, congratulations!" where bmi = weight / height ^ 2 (skinny, normal, fat) = (18.5, 25.0, 30.0) calcBmis :: (RealFloat a) => [(a, a)] -> [a] calcBmis xs = [bmi w h | (w, h) <- xs] where bmi weight height = weight / height ^ 2 cylinder :: (RealFloat a) => a -> a -> a cylinder r h = let sideArea = (2 * pi * r * h) topArea = (pi * r ^2) in (sideArea + 2 * topArea) describeList :: [a] -> String describeList xs = "The list is " ++ case xs of [] -> "empty." [x] -> "a singleton list." xs -> "a longer list." describeList' :: [a] -> String describeList' xs = "The list is " ++ what xs where what [] = "empty." what [x] = "a singleton list." what xs = "a longer list."
yumerov/haskell-study
learnyouahaskell/02-function-syntax/pattern.hs
gpl-3.0
2,095
0
12
597
781
408
373
54
3
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-} module Main where import Data.Aeson import Data.ByteString.Lazy import GHC.Generics main = Data.ByteString.Lazy.putStr $ encode $ hanoi 3 data Rod = A | B | C deriving Show type Move = String type Level = Int data History = Branch Level History Move History | Leaf deriving Show instance ToJSON History where toJSON (Branch l h1 m h2) = object ["name" .= m , "children" .= [toJSON h1, toJSON h2]] toJSON Leaf = object ["name" .= ("leaf"::String)] hanoi :: Int -> History hanoi = h A B C where h :: Rod -> Rod -> Rod -> Int -> History h a b c 0 = Leaf h a b c n = Branch n (h a c b (n-1)) ("move size " ++ show n ++ " disc from " ++ show a ++ " to " ++ show b ++ "\n") (h c b a (n-1))
rfrankel/Sorting-Visualization
hanoijson.hs
gpl-3.0
836
0
15
254
326
175
151
22
2
{-# LANGUAGE OverloadedStrings #-} import Codec.Picture import Codec.Picture.RGBA8 (fromDynamicImage) import System.Environment (getArgs) insertSpaces :: Image PixelRGBA8 -> Int -> Image PixelRGBA8 insertSpaces image spaceHeight = generateImage (imageSpacer image spaceHeight) width height where width = imageWidth image baseHeight = imageHeight image extraHeight = baseHeight `mod` spaceHeight height = (baseHeight - extraHeight) * 2 + extraHeight imageSpacer :: Image PixelRGBA8 -> Int -> Int -> Int -> PixelRGBA8 imageSpacer baseImage spaceHeight x y | ifFromRaw = pixelAt baseImage x realY | otherwise = PixelRGBA8 0 0 0 0 where ifFromRaw = y `div` spaceHeight `mod` 2 == 0 realY = (y `div` (2 * spaceHeight)) * spaceHeight + y `mod` spaceHeight main = do args <- getArgs let inName = args !! 0 let spaceHeight = read $ args !! 1 let outName = inName ++ "-spaced.png" rawImage <- readPng (head args) case rawImage of Left errorMsg -> putStrLn errorMsg Right rawImage -> do putStrLn "Image Loaded..." let spacedImg = insertSpaces (fromDynamicImage rawImage) spaceHeight writePng outName spacedImg putStrLn "Spaces Added"
mfilmer/figuredoublespace
main.hs
gpl-3.0
1,214
0
17
258
387
193
194
29
2
{- Ðóêîâîäñòâî ôèíàíñîâîé ïèðàìèäû ðåøèëî ïðèñâîèòü ÷èñëîâîé ðåéòèíã êàæäîìó èç ó÷àñòíèêîâ ïèðàìèäû. Åñëè ó÷àñòíèê äî ñèõ ïîð íèêîãî íå ïðèâåë â ïèðàìèäó, òî åãî ðåéòèíã ðàâíÿåòñÿ 1. Åñëè ó ó÷àñòíèêà óæå åñòü ïîä÷èíåííûå ó÷àñòíèêè, òî åãî ðåéòèíã ðàâíÿåòñÿ 1 + ñóììà ðåéòèíãîâ åãî ïðÿìûõ ïîä÷èíåííûõ. Çàäà÷à: íàéòè ñóììó ðåéòèíãîâ âñåõ ó÷àñòíèêîâ ôèíàíñîâîé ïèðàìèäû. Èñõîäíûå äàííûå ïîäàþòñÿ â âèäå ìàññèâà èç n ñòðîê, ãäå êàæäàÿ ñòðîêà ñîäåðæèò n ñèìâîëîâ. Êàæäûé ñèìâîë — ëèáî '0', ëèáî '1'. j-é ñèìâîë i-é ñòðîêè óêàçûâàåò íà òî, ÿâëÿåòñÿ ëè ó÷àñòíèê ïîä íîìåðîì j ïðÿìûì ïîä÷èíåííûì ó÷àñòíèêà i. j-é ñèìâîë j-é ñòðîêè âñåãäà ðàâåí '0'. Äåðåâî ó÷àñòíèêîâ íèêîãäà íå èìååò öèêëîâ. Êàæäûé ó÷àñòíèê âñåãäà ÿâëÿåòñÿ ïðÿìûì ïîä÷èíåííûì ìàêñèìóì îäíîãî äðóãîãî ó÷àñòíèêà. Ó äåðåâà ó÷àñòíèêîâ âñåãäà òîëüêî îäèí êîðíåâîé ó÷àñòíèê. Ïðèìåð èñõîäíûõ äàííûõ: "0110" "0000" "0001" "0000" Êîðíåâûì ýëåìåíòîì â äàííîì ñëó÷àå ÿâëÿåòñÿ ó÷àñòíèê 0. Ó íåãî äâîå ïîä÷èíåííûõ: ó÷àñòíèêè 1 è 2. Ó 1 ïîä÷èíåííûõ íåò, ó 2 åñòü ïîä÷èíåííûé ó÷àñòíèê 3. Ðåéòèíã 3-ãî: 1. Ðåéòèíã 1-ãî: 1. Ðåéòèíã 2-ãî: 1 + 1 = 2. Ðåéòèíã 0-ãî: 1 + 1 + 2 = 4. Ðåçóëüòàòîì ðàáîòû êîäà äîëæíà ÿâëÿòüñÿ ñóììà ðåéòèíãîâ âñåõ ó÷àñòíèêîâ, â äàííîì ñëó÷àå ýòî: 1 + 1 + 2 + 4 = 8. -} import Data.List treeData = [ "0110", "0000", "0001", "0000" ] employeeSubs = elemIndices '1' employees = map employeeSubs treeData calcEmpl d n = foldr (\x -> (+) (calcEmpl d x)) 1 (d !! n) calcAll = map (calcEmpl employees) [0..(length employees) - 1] main = putStrLn . show . sum $ calcAll
graninas/Haskell-Algorithms
Tests/FinanceTree.hs
gpl-3.0
1,595
10
10
319
145
78
67
11
1
(mu . bimap mu id)((x, y), z)
hmemcpy/milewski-ctfp-pdf
src/content/3.6/code/haskell/snippet09.hs
gpl-3.0
29
0
8
6
31
16
15
-1
-1
{-# language LambdaCase, ScopedTypeVariables #-} {-# language OverloadedStrings #-} module HFish.Main where import Control.Lens import Control.Monad import Control.Monad.IO.Class import Control.Monad.State.Class import Control.Monad.State import Control.Monad.Reader.Class import qualified Data.Sequence as Seq import Data.Semigroup import qualified Data.List as L import qualified Data.Set as S import qualified Data.Text as T import HFish.Interpreter.Interpreter import HFish.Interpreter.Scope import HFish.Interpreter.Core import HFish.Interpreter.Init import HFish.Interpreter.Parsing import HFish.Interpreter.Var import HFish.Interpreter.IO (echo) import HFish.Main.Interactive import HFish.Main.NonInteractive import HFish.Types import HFish.Debug import HFish.Dispatch import HFish.Startup (doStartup,setFileErrorK) import qualified HFish.Interpreter.Str as Str import Fish.Lang import Fish.Lang.Unit import Fish.Lang.Base import Fish.Lang.Pretty import System.Console.Haskeline import qualified Text.PrettyPrint.GenericPretty as GP import qualified Text.PrettyPrint.ANSI.Leijen as PP hfishMain :: NoExecute -> ShowAst -> IsCommand -> FishCompat -> [Debug] -> [String] -> IO () hfishMain (NoExecute noExecute) showAst (IsCommand isCommand) (fishCompat@(FishCompat fcompat)) dflags args | noExecute = execute args ( const $ pure () ) | ShowAst b <- showAst = execute args (printAST b) | NoAst <- showAst = do r <- mkInitialFishReader atBreakpoint fcompat s <- mkInitialFishState flip evalDispatch ( DispatchState r s Nothing fishCompat mempty ) ( dispatch isCommand dflags args ) where execute :: [String] -> (Prog T.Text () -> IO a) -> IO () execute | isCommand = exDirect fcompat . mkCommand | otherwise = exPaths exPaths xs = forM_ xs . flip (exPath fcompat) atBreakpoint :: Fish () atBreakpoint = do r <- ask s <- get let fishCompat = FishCompat $ r ^. fishCompatible liftIO $ flip evalDispatch ( DispatchState r s Nothing fishCompat mempty ) ( runInterpreterLoop $ IsBreakPoint True ) mkCommand :: [String] -> String mkCommand args = L.unwords args <> "\n" dispatch :: Bool -> [Debug] -> [String] -> Dispatch () dispatch isCommand dflags args = do setDebugFlags dflags fishCompat@(FishCompat fcompat) <- use dCompat case isCommand of True -> do let cmd = mkCommand args doStartup setCmdErrorK cmd exDirect fcompat cmd runProgram False -> case args of [] -> do setInteractive doStartup runInterpreterLoop $ IsBreakPoint False path:args' -> do doStartup injectArgs $ map Str.fromString args' setFileErrorK path exPath fcompat path runProgram setCmdErrorK :: String -> Dispatch () setCmdErrorK cmd = dOnError .= Just handle where handle :: String -> Fish () handle e = echo . show $ showErr e <> PP.hardline <> PP.magenta "~> Ocurred in command: " <> PP.string cmd <> PP.hardline showErr e = PP.hang 2 $ PP.vsep [ PP.magenta "~> Error:" , (PP.red . PP.string) e ] exDirect :: MonadIO io => Bool -> String -> ( Prog T.Text () -> io a ) -> io () exDirect fcompat cmd = do withProg' $ parseInteractive fcompat cmd exPath :: MonadIO io => Bool -> FilePath -> ( Prog T.Text () -> io a ) -> io () exPath fcompat path f = do res <- parseFile fcompat path withProg' res f setInteractive :: Dispatch () setInteractive = modify $ dReader . interactive .~ True setDebugFlags :: [Debug] -> Dispatch () setDebugFlags = mapM_ setDFlag where setDFlag :: Debug -> Dispatch () setDFlag dflag | DebugLib d <- dflag = dReader . debugFlags %= S.insert d | DebugMain d <- dflag = dDebug %= S.insert d injectArgs :: [Str.Str] -> Dispatch () injectArgs xs = do s <- liftIO =<< ( runFish inj <$> use dReader <*> use dState ) dState .= s where inj = setVar FLocalScope "argv" ( mkVar $ Seq.fromList xs ) printAST :: Bool -> Prog T.Text () -> IO () printAST full = print . if full then GP.doc else GP.doc . toBase
xaverdh/hfish
HFish/Main.hs
gpl-3.0
4,157
0
17
933
1,380
703
677
-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.FireStore.Projects.Databases.CollectionGroups.Indexes.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets a composite index. -- -- /See:/ <https://cloud.google.com/firestore Cloud Firestore API Reference> for @firestore.projects.databases.collectionGroups.indexes.get@. module Network.Google.Resource.FireStore.Projects.Databases.CollectionGroups.Indexes.Get ( -- * REST Resource ProjectsDatabasesCollectionGroupsIndexesGetResource -- * Creating a Request , projectsDatabasesCollectionGroupsIndexesGet , ProjectsDatabasesCollectionGroupsIndexesGet -- * Request Lenses , pdcgigXgafv , pdcgigUploadProtocol , pdcgigAccessToken , pdcgigUploadType , pdcgigName , pdcgigCallback ) where import Network.Google.FireStore.Types import Network.Google.Prelude -- | A resource alias for @firestore.projects.databases.collectionGroups.indexes.get@ method which the -- 'ProjectsDatabasesCollectionGroupsIndexesGet' request conforms to. type ProjectsDatabasesCollectionGroupsIndexesGetResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] GoogleFirestoreAdminV1Index -- | Gets a composite index. -- -- /See:/ 'projectsDatabasesCollectionGroupsIndexesGet' smart constructor. data ProjectsDatabasesCollectionGroupsIndexesGet = ProjectsDatabasesCollectionGroupsIndexesGet' { _pdcgigXgafv :: !(Maybe Xgafv) , _pdcgigUploadProtocol :: !(Maybe Text) , _pdcgigAccessToken :: !(Maybe Text) , _pdcgigUploadType :: !(Maybe Text) , _pdcgigName :: !Text , _pdcgigCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsDatabasesCollectionGroupsIndexesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pdcgigXgafv' -- -- * 'pdcgigUploadProtocol' -- -- * 'pdcgigAccessToken' -- -- * 'pdcgigUploadType' -- -- * 'pdcgigName' -- -- * 'pdcgigCallback' projectsDatabasesCollectionGroupsIndexesGet :: Text -- ^ 'pdcgigName' -> ProjectsDatabasesCollectionGroupsIndexesGet projectsDatabasesCollectionGroupsIndexesGet pPdcgigName_ = ProjectsDatabasesCollectionGroupsIndexesGet' { _pdcgigXgafv = Nothing , _pdcgigUploadProtocol = Nothing , _pdcgigAccessToken = Nothing , _pdcgigUploadType = Nothing , _pdcgigName = pPdcgigName_ , _pdcgigCallback = Nothing } -- | V1 error format. pdcgigXgafv :: Lens' ProjectsDatabasesCollectionGroupsIndexesGet (Maybe Xgafv) pdcgigXgafv = lens _pdcgigXgafv (\ s a -> s{_pdcgigXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pdcgigUploadProtocol :: Lens' ProjectsDatabasesCollectionGroupsIndexesGet (Maybe Text) pdcgigUploadProtocol = lens _pdcgigUploadProtocol (\ s a -> s{_pdcgigUploadProtocol = a}) -- | OAuth access token. pdcgigAccessToken :: Lens' ProjectsDatabasesCollectionGroupsIndexesGet (Maybe Text) pdcgigAccessToken = lens _pdcgigAccessToken (\ s a -> s{_pdcgigAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pdcgigUploadType :: Lens' ProjectsDatabasesCollectionGroupsIndexesGet (Maybe Text) pdcgigUploadType = lens _pdcgigUploadType (\ s a -> s{_pdcgigUploadType = a}) -- | Required. A name of the form -- \`projects\/{project_id}\/databases\/{database_id}\/collectionGroups\/{collection_id}\/indexes\/{index_id}\` pdcgigName :: Lens' ProjectsDatabasesCollectionGroupsIndexesGet Text pdcgigName = lens _pdcgigName (\ s a -> s{_pdcgigName = a}) -- | JSONP pdcgigCallback :: Lens' ProjectsDatabasesCollectionGroupsIndexesGet (Maybe Text) pdcgigCallback = lens _pdcgigCallback (\ s a -> s{_pdcgigCallback = a}) instance GoogleRequest ProjectsDatabasesCollectionGroupsIndexesGet where type Rs ProjectsDatabasesCollectionGroupsIndexesGet = GoogleFirestoreAdminV1Index type Scopes ProjectsDatabasesCollectionGroupsIndexesGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/datastore"] requestClient ProjectsDatabasesCollectionGroupsIndexesGet'{..} = go _pdcgigName _pdcgigXgafv _pdcgigUploadProtocol _pdcgigAccessToken _pdcgigUploadType _pdcgigCallback (Just AltJSON) fireStoreService where go = buildClient (Proxy :: Proxy ProjectsDatabasesCollectionGroupsIndexesGetResource) mempty
brendanhay/gogol
gogol-firestore/gen/Network/Google/Resource/FireStore/Projects/Databases/CollectionGroups/Indexes/Get.hs
mpl-2.0
5,656
0
15
1,197
701
411
290
111
1
{- This file is part of Tractor. Tractor is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Tractor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Tractor. If not, see <http://www.gnu.org/licenses/>. -} {- | Module : NetService.HomePage Description : Home page of this application front end Copyright : (c) 2016 Akihiro Yamamoto License : AGPLv3 Maintainer : https://github.com/ak1211 Stability : unstable Portability : POSIX ホームページです -} {-# LANGUAGE OverloadedStrings #-} module NetService.HomePage ( HomePage(..) ) where import qualified Data.Text as T import Lucid import qualified Servant.Docs -- | -- アプリケーションのホームページ data HomePage = HomePage instance Lucid.ToHtml HomePage where -- -- toHtml _ = do doctype_ html_ [lang_ "ja", class_ "has-navbar-fixed-top"] $ do head_ $ do meta_ [charset_ "utf-8"] meta_ [name_ "viewport", content_ "width=device-width, initial-scale=1"] title_ $ Lucid.toHtmlRaw ("Dashboard &#8212; TRACTOR" :: T.Text) link_ [rel_ "icon", href_"public/favicon.ico"] link_ [rel_ "stylesheet", href_ "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css" ] link_ [rel_ "stylesheet", href_ "https://use.fontawesome.com/releases/v5.5.0/css/all.css", integrity_ "sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU", crossorigin_ "anonymous"] link_ [rel_ "stylesheet", href_ "https://fonts.googleapis.com/css?family=Gugi"] body_ $ do script_ [src_ "public/app.js"] T.empty toHtmlRaw = Lucid.toHtml instance Servant.Docs.ToSample HomePage where toSamples _ = Servant.Docs.singleSample HomePage
ak1211/tractor
src/NetService/HomePage.hs
agpl-3.0
2,342
0
17
552
285
144
141
24
0
{-# LANGUAGE BangPatterns, OverloadedStrings #-} module Data.HBCI.Gen where import Data.Monoid ((<>)) import qualified Data.Text.Encoding as E import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as C8 import Data.HBCI.Types gen :: MSGValue -> BS.ByteString gen segs = let res = BS.intercalate "'" (map genSEG segs) in if (BS.null res) then res else res <> "'" genSEG :: SEGValue -> BS.ByteString genSEG seg = BS.intercalate "+" $ map genDEG seg genDEG :: DEGValue -> BS.ByteString genDEG deg = BS.intercalate ":" $ map genDE deg genDE :: DEValue -> BS.ByteString genDE (DEStr t) = E.encodeUtf8 t -- FIXME: This should really be latin1 genDE (DEBinary bs) = C8.singleton '@' <> (C8.pack $ show $ BS.length bs) <> C8.singleton '@' <> bs
paulkoerbitz/hsbci
src/Data/HBCI/Gen.hs
agpl-3.0
802
0
11
159
268
145
123
17
2
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-} module Language.C.Obfuscate.CPS where import Data.Char import Data.List (nubBy) import Data.Maybe import qualified Data.Map as M import qualified Data.Set as S import qualified Language.C.Syntax.AST as AST import qualified Language.C.Data.Node as N import Language.C.Syntax.Constants import Language.C.Data.Ident import Language.C.Obfuscate.Var import Language.C.Obfuscate.ASTUtils import Language.C.Obfuscate.CFG import Language.C.Obfuscate.SSA -- import for testing import Language.C (parseCFile, parseCFilePre) import Language.C.System.GCC (newGCC) import Language.C.Pretty (pretty) import Text.PrettyPrint.HughesPJ (render, text, (<+>), hsep) import System.IO.Unsafe (unsafePerformIO) -- TODO LIST: testCPS = do { let opts = [] ; ast <- errorOnLeftM "Parse Error" $ parseCFile (newGCC "gcc") Nothing opts "test/sort.c" -- -} "test/fibiter.c" ; case ast of { AST.CTranslUnit (AST.CFDefExt fundef:_) nodeInfo -> case runCFG fundef of { CFGOk (_, state) -> do { -- putStrLn $ show $ buildDTree (cfg state) ; -- putStrLn $ show $ buildDF (cfg state) ; let (SSA scopedDecls labelledBlocks sdom _ _) = buildSSA (cfg state) (formalArgs state) -- ; putStrLn $ show $ visitors -- ; putStrLn $ show $ exits ; let cps = ssa2cps fundef (buildSSA (cfg state) (formalArgs state)) ; putStrLn $ prettyCPS $ cps ; -- putStrLn $ render $ pretty (cps_ctxt cps) ; -- mapM_ (\d -> putStrLn $ render $ pretty d) (cps_funcsigs cps) ; -- mapM_ (\f -> putStrLn $ render $ pretty f) ((cps_funcs cps) ++ [cps_main cps]) } ; CFGError s -> error s } ; _ -> error "not fundec" } } prettyCPS :: CPS -> String prettyCPS cps = let declExts = map (\d -> AST.CDeclExt d) ([(cps_ctxt cps)] ++ (cps_typedefs cps) ++ (cps_funcsigs cps)) funDeclExts = map (\f -> AST.CFDefExt f) ((cps_funcs cps) ++ [cps_main cps]) in render $ pretty (AST.CTranslUnit (declExts ++ funDeclExts) N.undefNode) -- ^ a CPS function declaration AST data CPS = CPS { cps_decls :: [AST.CCompoundBlockItem N.NodeInfo] -- ^ main function decls , cps_stmts :: [AST.CCompoundBlockItem N.NodeInfo] -- ^ main function stmts , cps_funcsigs :: [AST.CDeclaration N.NodeInfo] -- ^ the signatures decls of the auxillary functions , cps_funcs :: [AST.CFunctionDef N.NodeInfo] -- ^ the auxillary functions , cps_ctxt :: AST.CDeclaration N.NodeInfo -- ^ the context for the closure , cps_typedefs :: [AST.CDeclaration N.NodeInfo] -- ^ type defs , cps_main :: AST.CFunctionDef N.NodeInfo -- ^ the main function } deriving Show -- global (parameter) name prefices bindName = "bind" bindPushName = "bind_push" bindPeekMName = "bind_peek_m" bindPeekFName = "bind_peek_f" bindPopName = "bind_pop" lambdaBindName = "lambda_bind" ifcCondName = "ifcCond" ifcTrName = "ifcTr" ifcFlName = "ifcFl" ifcName = "ifc" ifcPushName = "ifc_push" ifcPeekCName = "ifc_peek_c" ifcPeekTrName = "ifc_peek_tr" ifcPeekFlName = "ifc_peek_fl" ifcPopName = "ifc_pop" lambdaIfcName = "lambda_ifc" loopCondName = "loopcCond" loopVisitName = "loopcVisit" loopExitName = "loopcExit" loopName = "loopc" loopPushName = "loopc_push" loopPeekCName = "loopc_peek_c" loopPeekVName = "loopc_peek_v" loopPeekEName = "loopc_peek_e" loopPopName = "loopc_pop" lambdaLoopName = "lambda_loopc" kPeekName = "k_peek" kPopName = "k_pop" kPushName = "k_push" retName = "ret" idName = "id" ctxt_arr_bool = "ctxt_arr_bool" ctxt_arr_void = "ctxt_arr_void" ctxtParamName = "ctxtParam" kParamName = "kParam" mParamName = "mParam" fParamName = "fParam" condParamName = "condParam" visitorParamName = "visitorParam" exitParamName = "exitParam" trueParamName = "trueParam" falseParamName = "falseParam" kStackTop = "k_stack_top" loopStackTop = "loop_stack_top" ifcStackTop = "ifc_stack_top" bindStackTop = "bind_stack_top" kStackName = "k_stack" loopStackCName = "loopc_stack_c" loopStackVName = "loopc_stack_v" loopStackEName = "loopc_stack_e" ifcStackCName = "ifc_stack_c" ifcStackTrName = "ifc_stack_tr" ifcStackFlName = "ifc_stack_fl" bindStackFName = "bind_stack_f" bindStackMName = "bind_stack_m" {- class CPSize ssa cps where cps_trans :: ssa -> cps instance CPSize a b => CPSize [a] [b] where cps_trans as = map cps_trans as instance CPSize (Ident, LabeledBlock) (AST.CFunctionDef N.NodeInfo) where cps_trans (label, lb) = undefined {- translation d => D t => T x => X ---------------------- t x => T X -} instance CPSize (AST.CDeclaration N.NodeInfo) (AST.CDeclaration N.NodeInfo) where cps_trans decl = case decl of { AST.CDecl tyspec tripls nodeInfo -> let tyspec' = cps_trans tyspec tripls' = map (\(mb_decltr, mb_init, mb_size) -> let mb_decltr' = case mb_decltr of { Nothing -> Nothing ; Just decltr -> Just decltr -- todo } mb_init' = case mb_init of { Nothing -> Nothing ; Just init -> Just init -- todo } mb_size' = case mb_size of { Nothing -> Nothing ; Just size -> Just size -- todo } in (mb_decltr', mb_init', mb_size') ) tripls in AST.CDecl tyspec' tripls' nodeInfo -- ; AST.CStaticAssert e lit nodeInfo -> undefined } -} {- translation t => T ----------- int => int ----------- bool => bool t => t ------------- t* => T* t => T ------------ t[] => T* ------------- void => void -} {- data CDeclarationSpecifier a = CStorageSpec (CStorageSpecifier a) -- ^ storage-class specifier or typedef | CTypeSpec (CTypeSpecifier a) -- ^ type name | CTypeQual (CTypeQualifier a) -- ^ type qualifier | CFunSpec (CFunctionSpecifier a) -- ^ function specifier | CAlignSpec (CAlignmentSpecifier a) -- ^ alignment specifier deriving (Show, Data,Typeable {-! ,CNode ,Functor, Annotated !-}) -} {- --------- (Var) x => X -} -- fn, K, \bar{\Delta} |- \bar{b} => \bar{P} --translating the labeled blocks to function decls {- fn, K, \bar{\Delta}, \bar{b} |- b_i => P_i --------------------------------------------- fn, K, \bar{\Delta} |- \bar{b} => \bar{P} -} type ContextName = String type Visitors = M.Map Ident Ident -- ^ last label of the visitor -> label of the loop type Exits = M.Map Ident Ident -- ^ label of the exit -> label of the loop -- CL_cps cps_trans_lb :: Bool -> -- ^ is return void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ top level function name -- Ident -> -- ^ label for the current block M.Map Ident LabeledBlock -> -- ^ KEnv SSA -> -- ^ functions as the cfg ([AST.CFunctionDef N.NodeInfo], AST.CExpression N.NodeInfo) cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_i kenv cfg = case adjacent cfg l_i of { [ l_j ] -> {- -- in target langauge CL_cps l_i kenv cfg | \exists l_j: (l_i,l_j) \in cfg /\ \not (\exists l_k : l_j \= l_k /\ (l_i, l_k) \in cfg) = (D::\overline{D}, bind(f_i,E)) where (\overline{D}, E) = CL_cps l_j kenv cfg (\overline{phi}, s) = kenv l_i k is a fresh variable S = CS_cps s kenv l_i k D = (void => void) => void f_i = (void => void k) => { S } -- in c CL_cps l_i kenv cfg | \exists l_j: (l_i,l_j) \in cfg /\ \not (\exists l_k : l_j \= l_k /\ (l_i, l_k) \in cfg) = (D::Bind_i::\overline{D}, bind_i) where (\overline{D}, E) = CL_cps l_j kenv cfg (\overline{phi}, s) = kenv l_i k is a fresh variable S = CS_cps s kenv l_i k D = void f_i (ctxt* c) { S } Bind_i = void bind_i (ctxt* c) { bind_push(&f_i, &E, c); lambda_bind(c); } -} let f_iname = fname `app` l_i tyVoid = [AST.CTypeSpec (AST.CVoidType N.undefNode)] tyCtxt = [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] paramCtxt = (iid ctxtParamName) .::*. tyCtxt -- ctxt* ctxt k = iid kParamName lb = fromJust (M.lookup l_i kenv) stmts' = cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k kenv l_i (lb_stmts lb) f_iD = fun tyVoid f_iname [paramCtxt] stmts' (ds,e) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_j kenv cfg -- NOTE: each bind, loop and ifc, ret operators need to be "qualified" by the function name bind = fname `app` iid bindName bindpush = fname `app` iid bindPushName lambdabind = fname `app` iid lambdaBindName bind_i = bind `app` l_i bindPush = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar bindpush) [ (adr $ cvar f_iname), (adr e),(cvar $ iid ctxtParamName)] N.undefNode)) N.undefNode) -- bind_push(&f_i, &e, ctxt) lambdaBindApp = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar lambdabind) [(cvar $ iid ctxtParamName)] N.undefNode)) N.undefNode) -- lambdaBind(ctxt) bindStmts = [ bindPush, lambdaBindApp] bind_iD = fun tyVoid bind_i [paramCtxt] bindStmts in (f_iD:bind_iD:ds, cvar bind_i) ; [ l_j, l_k ] | pathExists cfg l_j l_i && pathExists cfg l_k l_i -> error ("syntactic non-terminating loop" ++ (show (M.lookup l_i kenv))) ; [ l_j, l_k ] | pathExists cfg l_j l_i -> {- -- in target langauge CL_cps l_i kenv cfg | \exists l_j, l_k: l_j \= l_k /\ (l_i,l_j) \in cfg /\ (l_i, l_k) \in cfg /\ \exists l' : (l_j, l', l_i) \in cfg /\ \not (\exists l'' : (l_k, l'', l_i) \in cfg) = (\overline{D_j} ++ \overline{D_k}, loop( () => { return E}, E_j,E_k )) where (\overline{\phi}, if e { goto l_j; } else { goto l_k; }) = kenv(l_i) (\overline{D_j}, E_j) = CL_cps l_j kenv (cfg - last(l_j, \overline{l'}, l_i)) (\overline{D_k}, E_k) = CL_cps l_k kenv cfg E = CE_cps e -- in c CL_cps l_i kenv cfg | \exists l_j, l_k: l_j \= l_k /\ (l_i,l_j) \in cfg /\ (l_i, l_k) \in cfg /\ \exists l' : (l_j, l', l_i) \in cfg /\ \not (\exists l'' : (l_k, l'', l_i) \in cfg) = (\overline{D_j} ++ \overline{D_k}, loop( () => { return E}, E_j,E_k )) where (\overline{\phi}, if e { goto l_j; } else { goto l_k; }) = kenv(l_i) (\overline{D_j}, E_j) = CL_cps l_j kenv (cfg - last(l_j, \overline{l'}, l_i)) (\overline{D_k}, E_k) = CL_cps l_k kenv cfg E = CE_cps e LoopCond_i = int loopCond_i (ctxt* c) { return E;} LoopVisit_i = void loopExit_i (ctxt* c) { (CF_cps l_i l_j); return E_j(ctxt); } LoopExit_i = void loopExit_i (ctxt* c) { (CF_cps l_i l_k); return E_k(ctxt); } Loop_i = void loop_i (ctxt* c) { loop_push(&loopCind_i, &loopVisit_i, &Loop_Exit_i, c); lambda_loop(c); } -} case M.lookup l_i kenv of { Just n -> case lb_stmts n of { [ AST.CBlockStmt (AST.CIf exp trueStmt@(AST.CGoto l_j _) (Just falseStmt@(AST.CGoto l_k _)) nodeInfo) ] -> let (d_j,e_j) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_j kenv (removeEdges cfg l_j l_i) -- we need to remove all edges (d_k,e_k) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_k kenv cfg exp' = cps_trans_exp localVars fargs ctxtName exp tyVoid = [AST.CTypeSpec (AST.CVoidType N.undefNode)] tyInt = [AST.CTypeSpec (AST.CIntType N.undefNode)] tyCtxt = [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] paramCtxt = (iid ctxtParamName) .::*. tyCtxt -- ctxt* ctxt loopCond = fname `app` iid loopCondName loopCond_i = loopCond `app` l_i loopCondStmts = [AST.CBlockStmt (AST.CReturn (Just exp') N.undefNode)] loopCond_iD = fun tyInt loopCond_i [paramCtxt] loopCondStmts loopVisit = fname `app` iid loopVisitName loopVisit_i = loopVisit `app` l_i loopVisitPhis = case M.lookup l_j kenv of { Nothing -> [] ; Just n -> cps_trans_phis ctxtName l_i l_j (lb_phis n) } loopVisitStmts = loopVisitPhis ++ [AST.CBlockStmt (AST.CExpr (Just (funCall e_j [ cvar $ iid ctxtParamName])) N.undefNode)] loopVisit_iD = fun tyVoid loopVisit_i [paramCtxt] loopVisitStmts loopExit = fname `app` iid loopExitName loopExit_i = loopExit `app` l_i loopExitPhis = case M.lookup l_k kenv of { Nothing -> [] ; Just n -> cps_trans_phis ctxtName l_i l_k (lb_phis n) } loopExitStmts = loopExitPhis ++ [AST.CBlockStmt (AST.CExpr (Just (funCall e_k [ cvar $ iid ctxtParamName])) N.undefNode)] loopExit_iD = fun tyVoid loopExit_i [paramCtxt] loopExitStmts loop = fname `app` iid loopName loop_i = loop `app` l_i loopPush = fname `app` iid loopPushName lambdaloop = fname `app` iid lambdaLoopName loopStmts = [ AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar loopPush) [ (adr (cvar loopCond_i)), (adr (cvar loopVisit_i)), (adr (cvar loopExit_i)), (cvar $ iid ctxtParamName) ] N.undefNode)) N.undefNode) , (AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar lambdaloop) [ (cvar $ iid ctxtParamName) ] N.undefNode)) N.undefNode)) ] loop_iD = fun tyVoid loop_i [paramCtxt] loopStmts in ([loopCond_iD, loopVisit_iD, loopExit_iD, loop_iD] ++ d_j ++ d_k, cvar loop_i) ; _ -> error "not possible" } ; _ -> error "not possible" } ; [ l_j, l_k ] | pathExists cfg l_k l_i -> -- same as the above case, just swapping k and j case M.lookup l_i kenv of { Just n -> case lb_stmts n of { [ AST.CBlockStmt (AST.CIf exp trueStmt@(AST.CGoto l_j _) (Just falseStmt@(AST.CGoto l_k _)) nodeInfo) ] -> let (d_j,e_j) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_j kenv cfg (d_k,e_k) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_k kenv (removeEdges cfg l_k l_i) exp' = cps_trans_exp localVars fargs ctxtName exp tyVoid = [AST.CTypeSpec (AST.CVoidType N.undefNode)] tyInt = [AST.CTypeSpec (AST.CIntType N.undefNode)] tyCtxt = [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] paramCtxt = (iid ctxtParamName) .::*. tyCtxt -- ctxt* ctxt loopCond = fname `app` iid loopCondName loopCond_i = loopCond `app` l_i loopCondStmts = [AST.CBlockStmt (AST.CReturn (Just exp') N.undefNode)] loopCond_iD = fun tyInt loopCond_i [paramCtxt] loopCondStmts loopVisit = fname `app` iid loopVisitName loopVisit_i = loopVisit `app` l_i loopVisitPhis = case M.lookup l_k kenv of { Nothing -> [] ; Just n -> cps_trans_phis ctxtName l_i l_k (lb_phis n) } loopVisitStmts = loopVisitPhis ++ [AST.CBlockStmt (AST.CExpr (Just (funCall e_k [ cvar $ iid ctxtParamName])) N.undefNode)] loopVisit_iD = fun tyVoid loopVisit_i [paramCtxt] loopVisitStmts loopExit = fname `app` iid loopExitName loopExit_i = loopExit `app` l_i loopExitPhis = case M.lookup l_j kenv of { Nothing -> [] ; Just n -> cps_trans_phis ctxtName l_i l_j (lb_phis n) } loopExitStmts = loopExitPhis ++ [AST.CBlockStmt (AST.CExpr (Just (funCall e_j [ cvar $ iid ctxtParamName])) N.undefNode)] loopExit_iD = fun tyVoid loopExit_i [paramCtxt] loopExitStmts loop = fname `app` iid loopName loop_i = loop `app` l_i loopPush = fname `app` iid loopPushName lambdaloop = fname `app` iid lambdaLoopName loopStmts = [ AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar loopPush) [ (adr (cvar loopCond_i)), (adr (cvar loopVisit_i)), (adr (cvar loopExit_i)), (cvar $ iid ctxtParamName) ] N.undefNode)) N.undefNode) , (AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar lambdaloop) [ (cvar $ iid ctxtParamName) ] N.undefNode)) N.undefNode)) ] loop_iD = fun tyVoid loop_i [paramCtxt] loopStmts in ([loopCond_iD, loopVisit_iD, loopExit_iD, loop_iD] ++ d_j ++ d_k, cvar loop_i) ; _ -> error "not possible" } ; _ -> error "not possible" } ; [ l_j, l_k ] | otherwise -> {- -- in target langauge CL_cps l_i kenv cfg | \exists l_j, l_k: l_j \= l_k /\ (l_i,l_j) \in cfg /\ (l_i, l_k) \in cfg /\ \not (\exists l' : (l_j, l', l_i) \in cfg \/ (l_k, l', l_i) \in cfg) = (\overline{D_j} ++ \overline{D_k}, ifc( () => { return E}, E_j,E_k )) where (\overline{\phi}, if e { goto l_j; } else { goto l_k; }) = kenv(l_i) (\overline{D_j}, E_j) = CL_cps l_j kenv cfg (\overline{D_k}, E_k) = CL_cps l_k kenv cfg E = CE_cps e -- in c CL_cps l_i kenv cfg | \exists l_j, l_k: l_j \= l_k /\ (l_i,l_j) \in cfg /\ (l_i, l_k) \in cfg /\ \not (\exists l' : (l_j, l', l_i) \in cfg \/ (l_k, l', l_i) \in cfg) = (Ifc_i::IfTr_i::IfFl_i::\overline{D_j} ++ \overline{D_k}, Ifc_i) where (\overline{\phi}, if e { goto l_j; } else { goto l_k; }) = kenv(l_i) (\overline{D_j}, E_j) = CL_cps l_j kenv cfg (\overline{D_k}, E_k) = CL_cps l_k kenv cfg E = CE_cps e IfCond_i = int ifcond_i (ctxt* c) { return E; } IfTr_i = void iftr_i (ctxt* c) { (CF_cps l_i l_j); return E_j(ctxt); } IfFl_i = void iffl_i (ctxt* c) { (CF_cps l_i l_k); return E_k(ctxt); } Ifc_i = void ifc_i (ctxt* c) { ifc_push(&ifcond_i, &iftr_i, &iftf_i,c); lambda_ifc(c); } -} case M.lookup l_i kenv of { Just n -> case lb_stmts n of { [ AST.CBlockStmt (AST.CIf exp trueStmt@(AST.CGoto l_j _) (Just falseStmt@(AST.CGoto l_k _)) nodeInfo) ] -> let (d_j,e_j) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_j kenv cfg (d_k,e_k) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_k kenv cfg exp' = cps_trans_exp localVars fargs ctxtName exp tyVoid = [AST.CTypeSpec (AST.CVoidType N.undefNode)] tyInt = [AST.CTypeSpec (AST.CIntType N.undefNode)] tyCtxt = [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] paramCtxt = (iid ctxtParamName) .::*. tyCtxt -- ctxt* ctxt ifcCond = fname `app` iid ifcCondName ifcCond_i = ifcCond `app` l_i ifcCondStmts = [AST.CBlockStmt (AST.CReturn (Just exp') N.undefNode)] ifcCond_iD = fun tyInt ifcCond_i [paramCtxt] ifcCondStmts ifcTrue = fname `app` iid ifcTrName ifcTrue_i = ifcTrue `app` l_i ifcTruePhis = case M.lookup l_j kenv of { Nothing -> [] ; Just n -> cps_trans_phis ctxtName l_i l_j (lb_phis n) } ifcTrueStmts = ifcTruePhis ++ [AST.CBlockStmt (AST.CExpr (Just (funCall e_j [ cvar $ iid ctxtParamName])) N.undefNode)] ifcTrue_iD = fun tyVoid ifcTrue_i [paramCtxt] ifcTrueStmts ifcFalse = fname `app` iid ifcFlName ifcFalse_i = ifcFalse `app` l_i ifcFalsePhis = case M.lookup l_k kenv of { Nothing -> [] ; Just n -> cps_trans_phis ctxtName l_i l_k (lb_phis n) } ifcFalseStmts = ifcFalsePhis ++ [AST.CBlockStmt (AST.CExpr (Just (funCall e_k [ cvar $ iid ctxtParamName])) N.undefNode)] ifcFalse_iD = fun tyVoid ifcFalse_i [paramCtxt] ifcFalseStmts ifc = fname `app` iid ifcName ifc_i = ifc `app` l_i ifcPush = fname `app` iid ifcPushName lambdaifc = fname `app` iid lambdaIfcName ifcStmts = [ AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar ifcPush) [ (adr (cvar ifcCond_i)), (adr (cvar ifcTrue_i)), (adr (cvar ifcFalse_i)), (cvar $ iid ctxtParamName) ] N.undefNode)) N.undefNode) , (AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar lambdaifc) [ (cvar $ iid ctxtParamName) ] N.undefNode)) N.undefNode)) ] ifc_iD = fun tyVoid ifc_i [paramCtxt]ifcStmts in ([ifcCond_iD, ifcTrue_iD, ifcFalse_iD, ifc_iD] ++ d_j ++ d_k, cvar ifc_i) ; _ -> error "not possible" } ; _ -> error "not possible" } ; [] -> {- -- in target langauge CL_cps l_i kenv cfg | \not (\exists l_j : (l_i,l_j) \in cfg) = ([D], bind( f_i, () => { return ret()}) where (\overline{\phi}, s) = kenv(l_i) k is fresh S = CS_cps s kenv l_i k D = (void => void) => void f_i = (void => void k) = { S } -- in c CL_cps l_i kenv cfg | \not (\exists l_j : (l_i,l_j) \in cfg) = ([D], bind( f_i, () => { return ret()}) where (\overline{\phi}, s) = kenv(l_i) k is fresh S = CS_cps s kenv l_i k D = void f_i = (ctxt* c) = { S } Bind_i = void bind_i (ctxt* c) { bind_push(&f_i, &ret, c); lambda_bind(c); } -} let f_iname = fname `app` l_i tyVoid = [AST.CTypeSpec (AST.CVoidType N.undefNode)] paramCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just (iid ctxtParamName)) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode k = iid kParamName lb = fromJust (M.lookup l_i kenv) stmts' = cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k kenv l_i (lb_stmts lb) f_iD = fun tyVoid f_iname [paramCtxt] stmts' bind = fname `app` iid bindName -- todo need to add fname prefix? bindpush = fname `app` iid bindPushName lambdabind = fname `app` iid lambdaBindName id = fname `app` iid idName -- id is ret bind_i = bind `app` l_i bindPush = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar bindpush) [ (adr $ cvar f_iname), (adr $ cvar id), (cvar $ iid ctxtParamName)] N.undefNode)) N.undefNode) -- bind_push(&f_i, &e, ctxt) lambdaBindApp = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar lambdabind) [(cvar $ iid ctxtParamName)] N.undefNode)) N.undefNode) -- lambdaBind(ctxt) bindStmts = [ bindPush, lambdaBindApp] bind_iD = fun tyVoid bind_i [paramCtxt] bindStmts in (f_iD:bind_iD:[], cvar bind_i) ; unhandled_cases -> error ("unhandle case " ++ (show unhandled_cases) ++ " " ++ (show (M.lookup l_i kenv))) } cps_trans_stmts :: Bool -> -- ^ is return type void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ fname Ident -> -- ^ K -- ^ \bar{\Delta} become part of the labelled block flag (loop) M.Map Ident LabeledBlock -> -- ^ \bar{b} kenv Ident -> -- ^ label for the current block [AST.CCompoundBlockItem N.NodeInfo] -> -- ^ stmts [AST.CCompoundBlockItem N.NodeInfo] cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k kenv l_i stmts = -- todo: maybe pattern match the CCompound constructor here? concatMap (\stmt -> cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_i stmt) stmts -- fn, K, \bar{\Delta}, \bar{b} |-_l s => S cps_trans_stmt :: Bool -> -- ^ is return type void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ fname Ident -> -- ^ K -- ^ \bar{\Delta} become part of the labelled block flag (loop) M.Map Ident LabeledBlock -> -- ^ \bar{b} kenv Ident -> -- ^ label for the current block AST.CCompoundBlockItem N.NodeInfo -> [AST.CCompoundBlockItem N.NodeInfo] {- -- in target language CS_cps (goto l_i) kenv l_j k = \overline{X = E}; return k(); where (\overline{\phi}, s) = kenv l_i \overline{(X,E)} = CF_cps \overline{\phi} l_j -- in C CS_cps (goto l_i) kenv l_j k = \overline{X = E}; ctxt_arr_void k = kpeek(ctxt); kpop(ctxt); return (*k)(ctxt); where (\overline{\phi}, s) = kenv l_i \overline{(X,E)} = CF_cps \overline{\phi} l_j -} -- note that our target is C, hence besides k, the function call include argument such as context cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_j (AST.CBlockStmt (AST.CGoto l_i nodeInfo)) = case M.lookup l_i kenv of { Just lb -> let asgmts = cps_trans_phis ctxtName l_j l_i (lb_phis lb) peek_ty = [AST.CTypeSpec (AST.CTypeDef (fname `app` (iid ctxt_arr_void)) N.undefNode)] peek_var = Just (AST.CDeclr (Just (fname `app` k)) [] Nothing [] N.undefNode) peek_rhs = Just (AST.CInitExpr (AST.CCall (cvar (fname `app` (iid kPeekName))) [cvar $ iid ctxtParamName] N.undefNode) N.undefNode) peek = AST.CBlockDecl (AST.CDecl peek_ty [(peek_var, peek_rhs, Nothing)] N.undefNode) pop = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid kPopName))) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode) kApp = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (ind $ cvar (fname `app` k)) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode) -- (*k)(ctxt) in asgmts ++ [ peek, pop, kApp ] ; Nothing -> error "cps_trans_stmt failed at a non existent label." } cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_j (AST.CBlockStmt (AST.CExpr (Just e) nodeInfo)) = -- exp let e' = cps_trans_exp localVars fargs ctxtName e in [AST.CBlockStmt (AST.CExpr (Just e') nodeInfo)] {- -- target language CS_cps (return e) kenv l_j k = res = E; return k(); where E = CE_cps e -- c language -- CS_cps (return e) kenv l_j k = res = E; ctxt_arr_void k = kpeek(ctxt); kpop(ctxt); return (*k)(ctxt); CS_cps (return e) kenv l_j k = res = E; ret(ctxt); -} cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_i (AST.CBlockStmt (AST.CReturn Nothing nodeInfo)) = let {- peek_ty = [AST.CTypeSpec (AST.CTypeDef (fname `app` (iid ctxt_arr_void)) N.undefNode)] peek_var = Just (AST.CDeclr (Just (fname `app` k)) [] Nothing [] N.undefNode) peek_rhs = Just (AST.CInitExpr (AST.CCall (cvar (fname `app` (iid kPeekName))) [cvar $ iid ctxtParamName] N.undefNode) N.undefNode) peek = AST.CBlockDecl (AST.CDecl peek_ty [(peek_var, peek_rhs, Nothing)] N.undefNode) pop = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid kPopName))) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode) kApp = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (ind $ cvar (fname `app` k)) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode) -- (*k)(ctxt) in [ peek, pop, kApp ] -} retApp = AST.CBlockStmt (AST.CExpr (Just (funCall (cvar (fname `app` iid retName)) [cvar $ iid ctxtParamName])) N.undefNode) in [ retApp ] cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_i (AST.CBlockStmt (AST.CReturn (Just e) nodeInfo)) = let {- peek_ty = [AST.CTypeSpec (AST.CTypeDef (fname `app` (iid ctxt_arr_void)) N.undefNode)] peek_var = Just (AST.CDeclr (Just (fname `app` k)) [] Nothing [] N.undefNode) peek_rhs = Just (AST.CInitExpr (AST.CCall (cvar (fname `app` (iid kPeekName))) [cvar $ iid ctxtParamName] N.undefNode) N.undefNode) peek = AST.CBlockDecl (AST.CDecl peek_ty [(peek_var, peek_rhs, Nothing)] N.undefNode) pop = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid kPopName))) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode) kApp = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (ind $ cvar (fname `app` k)) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode) -- (*k)(ctxt) -} e' = cps_trans_exp localVars fargs ctxtName e assign_or_e | isReturnVoid = e' | otherwise = ((cvar (iid ctxtParamName)) .->. (iid "func_result")) .=. e' stmt = AST.CBlockStmt (AST.CExpr (Just assign_or_e) N.undefNode) retApp = AST.CBlockStmt (AST.CExpr (Just (funCall (cvar (fname `app` iid retName)) [cvar $ iid ctxtParamName])) N.undefNode) -- in [ stmt, peek, pop, kApp ] in[ stmt, retApp] cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_i (AST.CBlockStmt (AST.CCompound ids stmts nodeInfo)) = -- todo: do we need to do anything with the ids (local labels)? let stmts' = cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k kenv l_i stmts in [AST.CBlockStmt (AST.CCompound ids stmts' nodeInfo)] cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_i stmt = error ("cps_trans_stmt error: unhandled case" ++ (show stmt)) -- (render $ pretty stmt)) cps_trans_phis :: ContextName -> Ident -> -- ^ source block label (where goto is invoked) Ident -> -- ^ destination block label (where goto is jumping to) [( Ident -- ^ var being redefined , [(Ident, Maybe Ident)])] -> -- ^ incoming block x renamed variables [AST.CCompoundBlockItem N.NodeInfo] cps_trans_phis ctxtName src_lb dest_lb ps = map (cps_trans_phi ctxtName src_lb dest_lb) ps {- --------------------------------------- l_s, l_d |- \bar{i} => \bar{x = e} -} cps_trans_phi :: ContextName -> Ident -> -- ^ source block label (where goto is invoked) Ident -> -- ^ destination block label (where goto is jumping to) (Ident, [(Ident, Maybe Ident)]) -> AST.CCompoundBlockItem N.NodeInfo cps_trans_phi ctxtName src_lb dest_lb (var, pairs) = case lookup src_lb pairs of -- look for the matching label according to the source label { Nothing -> error "cps_trans_phi failed: can't find the source label from the incoming block labels." ; Just redefined_lb -> -- lbl in which the var is redefined (it could be the precedence of src_lb) let lhs = (cvar (iid ctxtParamName)) .->. (var `app` dest_lb) rhs = (cvar (iid ctxtParamName)) .->. case redefined_lb of { Just l -> (var `app` l) ; Nothing -> var } in AST.CBlockStmt (AST.CExpr (Just (lhs .=. rhs)) N.undefNode) -- todo check var has been renamed with label } -- e => E {- --------- (ExpVal) v => V e => E, e_i => E_i -------------------------- (ExpApp) e(\bar{e}) => E(\bar{E}) -} -- it seems just to be identical -- for C target, we need to rename x to ctxt->x cps_trans_exp :: S.Set Ident -> S.Set Ident -> ContextName -> AST.CExpression N.NodeInfo -> AST.CExpression N.NodeInfo cps_trans_exp localVars fargs ctxtName (AST.CAssign op lhs rhs nodeInfo) = AST.CAssign op (cps_trans_exp localVars fargs ctxtName lhs) (cps_trans_exp localVars fargs ctxtName rhs) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CComma es nodeInfo) = AST.CComma (map (cps_trans_exp localVars fargs ctxtName) es) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CCond e1 Nothing e3 nodeInfo) = AST.CCond (cps_trans_exp localVars fargs ctxtName e1) Nothing (cps_trans_exp localVars fargs ctxtName e3) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CCond e1 (Just e2) e3 nodeInfo) = AST.CCond (cps_trans_exp localVars fargs ctxtName e1) (Just $ cps_trans_exp localVars fargs ctxtName e2) (cps_trans_exp localVars fargs ctxtName e3) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CBinary op e1 e2 nodeInfo) = AST.CBinary op (cps_trans_exp localVars fargs ctxtName e1) (cps_trans_exp localVars fargs ctxtName e2) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CCast decl e nodeInfo) = AST.CCast decl (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CUnary op e nodeInfo) = AST.CUnary op (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CSizeofExpr e nodeInfo) = AST.CSizeofExpr (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CSizeofType decl nodeInfo) = AST.CSizeofType decl nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CAlignofExpr e nodeInfo) = AST.CAlignofExpr (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CAlignofType decl nodeInfo) = AST.CAlignofType decl nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CComplexReal e nodeInfo) = AST.CComplexReal (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CComplexImag e nodeInfo) = AST.CComplexImag (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CIndex arr idx nodeInfo) = AST.CIndex (cps_trans_exp localVars fargs ctxtName arr) (cps_trans_exp localVars fargs ctxtName idx) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CCall f args nodeInfo) = AST.CCall (cps_trans_exp localVars fargs ctxtName f) (map (cps_trans_exp localVars fargs ctxtName) args) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CMember e ident deref nodeInfo) = AST.CMember (cps_trans_exp localVars fargs ctxtName e) ident deref nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CVar id _) = case unApp id of { Nothing -> cvar id ; Just id' | id' `S.member` (localVars `S.union` fargs) -> -- let io = unsafePerformIO $ print (localVars `S.union` fargs) >> print id' -- in io `seq` (cvar (iid ctxtParamName)) .->. id | otherwise -> cvar id -- global } cps_trans_exp localVars fargs ctxtName (AST.CConst c) = AST.CConst c cps_trans_exp localVars fargs ctxtName (AST.CCompoundLit decl initList nodeInfo) = AST.CCompoundLit decl initList nodeInfo -- todo check this cps_trans_exp localVars fargs ctxtName (AST.CStatExpr stmt nodeInfo ) = AST.CStatExpr stmt nodeInfo -- todo GNU C compount statement as expr cps_trans_exp localVars fargs ctxtName (AST.CLabAddrExpr ident nodeInfo ) = AST.CLabAddrExpr ident nodeInfo -- todo cps_trans_exp localVars fargs ctxtName (AST.CBuiltinExpr builtin ) = AST.CBuiltinExpr builtin -- todo build in expression {- top level translation p => P CP_cps (t' f (t x) { \overline{d}; \overline{b} }) = T' F (T X) { \overline{D''}; T' res; void ign ; ign = E(id) ; return res; } where T' = t' F = f T = t X = x \overline{D} = CD_cps \overline{d} (kenv, l_entry) = B_ssa \overline{b} (\overline{D'}, E) = CL_cps l_entry kenv G(kenv) \overline{D''} = \overline{D}; loopDelc; idDecl; seqDelc; condDecl; retDecl; \overline{D'} -} -- our target language C differs from the above specification. -- 1. the top function's type signature is not captured within SSA -- 2. \Delta is captured as the loop flag in LabaledBlock -- 3. there is no lambda expression, closure needs to be created as a context -- aux function that has type (void => void) => void should be in fact -- (void => void, ctxt*) => void -- 4. \bar{D} should be the context malloc and initialization -- 5. all the formal args should be copied to context ssa2cps :: (AST.CFunctionDef N.NodeInfo) -> SSA -> CPS ssa2cps fundef ssa@(SSA scopedDecls labelledBlocks sdom local_decl_vars fargs) = let -- scraping the information from the top level function under obfuscation funName = case getFunName fundef of { Just s -> s ; Nothing -> "unanmed" } formalArgDecls :: [AST.CDeclaration N.NodeInfo] formalArgDecls = getFormalArgs fundef formalArgIds :: [Ident] formalArgIds = concatMap (\declaration -> getFormalArgIds declaration) formalArgDecls (returnTy,ptrArrs) = getFunReturnTy fundef isReturnVoid = isVoidDeclSpec returnTy ctxtStructName = funName ++ "Ctxt" -- the context struct declaration context = mkContext ctxtStructName labelledBlocks formalArgDecls scopedDecls returnTy ptrArrs local_decl_vars fargs ctxtName = map toLower ctxtStructName -- alias name is inlower case and will be used in the the rest of the code -- loop_cps, loop_lambda, id and pop and push loop_cps = loopCPS ctxtName funName lambda_loop_cps = lambdaLoopCPS ctxtName funName loop_push_cps = loopPushCPS ctxtName funName loop_pop_cps = loopPopCPS ctxtName funName loop_peek_c_cps = loopPeekCCPS ctxtName funName loop_peek_v_cps = loopPeekVCPS ctxtName funName loop_peek_e_cps = loopPeekECPS ctxtName funName bind_cps = bindCPS ctxtName funName lambda_bind_cps = lambdaBindCPS ctxtName funName bind_push_cps = bindPushCPS ctxtName funName bind_pop_cps = bindPopCPS ctxtName funName bind_peek_m_cps = bindPeekMCPS ctxtName funName bind_peek_f_cps = bindPeekFCPS ctxtName funName ifc_cps = ifcCPS ctxtName funName lambda_ifc_cps = lambdaIfcCPS ctxtName funName ifc_push_cps = ifcPushCPS ctxtName funName ifc_pop_cps = ifcPopCPS ctxtName funName ifc_peek_c_cps = ifcPeekCCPS ctxtName funName ifc_peek_tr_cps = ifcPeekTrCPS ctxtName funName ifc_peek_fl_cps = ifcPeekFlCPS ctxtName funName id_cps = idCPS ctxtName funName ret_cps = retCPS ctxtName funName k_push_cps = kPushCPS ctxtName funName k_peek_cps = kPeekCPS ctxtName funName k_pop_cps = kPopCPS ctxtName funName combinators = [loop_cps, lambda_loop_cps, loop_push_cps, loop_pop_cps, loop_peek_c_cps, loop_peek_v_cps, loop_peek_e_cps, bind_cps, lambda_bind_cps, bind_push_cps, bind_pop_cps, bind_peek_m_cps, bind_peek_f_cps, ifc_cps, lambda_ifc_cps, ifc_push_cps,ifc_pop_cps, ifc_peek_c_cps, ifc_peek_tr_cps, ifc_peek_fl_cps, id_cps, ret_cps, k_push_cps, k_peek_cps,k_pop_cps] -- all the "nested/helper" function declarations -- todo: packing all the variable into a record l_0 = iid (labPref ++ "0" ) (ps,entryExp) = cps_trans_lb isReturnVoid local_decl_vars fargs ctxtName (iid funName) l_0 labelledBlocks ssa -- remove duplication functioni defintions in ps (caused by multiple blocks merge blocks) ps' = nubBy (\p1 p2 -> let n1 = getFunName p1 n2 = getFunName p2 in (isJust n1) && (isJust n2) && (n1 == n2)) ps -- all function signatures funcSignatures = map funSig (ps' ++ combinators ++ [fundef]) -- include the source func, in case of recursion main_decls = -- 1. malloc the context obj in the main func -- ctxtTy * ctxt = (ctxtTy *) malloc(sizeof(ctxtTy)); [ AST.CBlockDecl (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr (Just (iid ctxtParamName)) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode), Just (AST.CInitExpr (AST.CCast (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode) (AST.CCall (AST.CVar (iid "malloc") N.undefNode) [AST.CSizeofType (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [] N.undefNode) N.undefNode] N.undefNode) N.undefNode) N.undefNode),Nothing)] N.undefNode) ] main_stmts = -- 2. initialize the counter-part in the context of the formal args -- forall arg. ctxt->arg_label0 = arg [ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (arg `app` (iid $ labPref ++ "0" ))) .=. (AST.CVar arg N.undefNode))) N.undefNode) | arg <- formalArgIds] ++ -- 3. initialize the collection which are the local vars, e.g. a locally declared array -- int a[3]; -- will be reinitialized as ctxt->a_0 = (int *)malloc(sizeof(int)*3); [ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (var `app` (iid $ labPref ++ "0" ))) .=. rhs)) N.undefNode) | scopedDecl <- scopedDecls , isJust (containerDeclToInit scopedDecl) , let (Just (var,rhs)) = containerDeclToInit $ dropStorageQual $ dropConstTyQual scopedDecl ] ++ -- need to drop storage qualifier see test/arrayinitlist.c -- 4. initialize the context->stack_top = 0; [ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (iid stackTop) .=. (AST.CConst (AST.CIntConst (cInteger 0) N.undefNode))))) N.undefNode) | stackTop <- [ kStackTop,loopStackTop, ifcStackTop, bindStackTop ] ] ++ -- 5. calling entry expression [ AST.CBlockStmt (AST.CExpr (Just (funCall entryExp [ cvar (iid ctxtParamName) ])) N.undefNode) , if isReturnVoid then AST.CBlockStmt (AST.CReturn Nothing N.undefNode) else AST.CBlockStmt (AST.CReturn (Just $ (cvar (iid ctxtParamName)) .->. (iid "func_result")) N.undefNode) ] main_func = case fundef of { AST.CFunDef tySpecfs declarator decls _ nodeInfo -> AST.CFunDef tySpecfs declarator decls (AST.CCompound [] (main_decls ++ main_stmts) N.undefNode) nodeInfo } typedefs = [ ctxt_arr_voidDecl ctxtName funName, ctxt_arr_boolDecl ctxtName funName] in CPS main_decls main_stmts funcSignatures (ps' ++ combinators) context typedefs main_func -- ^ turn a scope declaration into a rhs initalization. -- ^ refer to local_array.c containerDeclToInit :: AST.CDeclaration N.NodeInfo -> Maybe (Ident, AST.CExpression N.NodeInfo) containerDeclToInit (AST.CDecl typespecs tripls nodeInfo0) = case tripls of { (Just decl@(AST.CDeclr (Just arrName) [arrDecl] _ _ _), mb_init, _):_ -> case arrDecl of { AST.CArrDeclr _ (AST.CArrSize _ size) _ -> let ptrToTy = AST.CDecl typespecs [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode malloc = AST.CCall (AST.CVar (iid "malloc") N.undefNode) [AST.CBinary AST.CMulOp (AST.CSizeofType (AST.CDecl typespecs [] N.undefNode) N.undefNode) size N.undefNode] N.undefNode cast = AST.CCast ptrToTy malloc N.undefNode in Just (arrName, cast) {- not needed, the size is recovered during the construction of SSA, see Var.hs splitDecl ; AST.CArrDeclr _ (AST.CNoArrSize _) _ -> -- no size of the array, derive from the init list case mb_init of { Just (AST.CInitList l _) -> let size = AST.CConst (AST.CIntConst (cInteger (fromIntegral $ length l)) N.undefNode) ptrToTy = AST.CDecl typespecs [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode malloc = AST.CCall (AST.CVar (iid "malloc") N.undefNode) [AST.CBinary AST.CMulOp (AST.CSizeofType (AST.CDecl typespecs [] N.undefNode) N.undefNode) size N.undefNode] N.undefNode cast = AST.CCast ptrToTy malloc N.undefNode in Just (arrName, cast) ; Nothing -> Nothing } -} ; _ -> Nothing } ; _ -> Nothing } -- ^ push {- void loop_push(ctxt_arr_bool cond, ctxt_arr_void visitor, ctxt_arr_void exit, ctxt *ctxt) { ctxt->loop_c[ctxt->curr_stack_size] = cond; ctxt->loop_v[ctxt->curr_stack_size] = visitor; ctxt->loop_e[ctxt->curr_stack_size] = exit; ctxt->loop_stack_top = ctxt->curr_stack_size + 1; } -} genPushCPS :: ContextName -> String -> -- function name prefix String -> -- operator name (loop or ifc) String -> -- stackTop name String -> -- fst para name (cond) String -> -- snd para name (visitor or tr) String -> -- third para name (exit or fl) String -> -- stack fst name String -> -- stack snd name String -> -- stack third name AST.CFunctionDef N.NodeInfo genPushCPS ctxtName fname operatorName stackTop condParaName sndParamName thirdParamName stackCName stackSndName stackThirdName = let cond = iid condParaName formalArgCond = AST.CDecl [AST.CTypeSpec intTy] -- int (*cond)(ctxt *) [(Just (AST.CDeclr (Just cond) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*x)(ctxt *) [(Just (AST.CDeclr (Just x) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode second = iid sndParamName formalArgSecond = formalArgX second third = iid thirdParamName formalArgThird = formalArgX third ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid operatorName) [formalArgCond, formalArgSecond, formalArgThird, formalArgCtxt] [ AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid stackCName)) .!!. (cvar ctxt .->. (iid stackTop))) .=. (cvar cond))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid stackSndName)) .!!. (cvar ctxt .->. (iid stackTop))) .=. (cvar second))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid stackThirdName)) .!!. (cvar ctxt .->. (iid stackTop))) .=. (cvar third))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just ((cvar ctxt .->. (iid stackTop)) .=. (AST.CBinary AST.CAddOp (cvar ctxt .->. (iid stackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode))) N.undefNode) ] loopPushCPS :: ContextName -> String -> -- function name prefix AST.CFunctionDef N.NodeInfo loopPushCPS ctxtName fname = genPushCPS ctxtName fname loopPushName loopStackTop condParamName visitorParamName exitParamName loopStackCName loopStackVName loopStackEName ifcPushCPS :: ContextName -> String -> -- function name prefix AST.CFunctionDef N.NodeInfo ifcPushCPS ctxtName fname = genPushCPS ctxtName fname ifcPushName ifcStackTop condParamName trueParamName falseParamName ifcStackCName ifcStackTrName ifcStackFlName {- void pop(sortctxt *ctxt) { ctxt->curr_stack_size = ctxt->curr_stack_size - 1; } -} genPopCPS :: ContextName -> String -> -- ^ function name prefix String -> -- ^ operator name String -> -- ^ stackTop AST.CFunctionDef N.NodeInfo genPopCPS ctxtName fname operatorName stackTop = let ctxt = iid ctxtParamName tyCtxt = [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] formalArgCtxt = ctxt .::*. tyCtxt in fun [AST.CTypeSpec voidTy] (iid fname `app` iid operatorName) [formalArgCtxt] [ AST.CBlockStmt (AST.CExpr (Just ((cvar ctxt .->. (iid stackTop)) .=. (AST.CBinary AST.CSubOp (cvar ctxt .->. (iid stackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode))) N.undefNode) ] kPopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo kPopCPS ctxtName fname = genPopCPS ctxtName fname kPopName kStackTop loopPopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo loopPopCPS ctxtName fname = genPopCPS ctxtName fname loopPopName loopStackTop ifcPopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo ifcPopCPS ctxtName fname = genPopCPS ctxtName fname ifcPopName ifcStackTop bindPopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo bindPopCPS ctxtName fname = genPopCPS ctxtName fname bindPopName bindStackTop -- ^ loop_cps {- void loop_cps(int (*cond)(sortctxt*), void (*visitor)(sortctxt*), void (*exit)(sortctxt*), sortctxt* ctxt) { if ((*cond)(ctxt)) { k_push(&lambda_loop_cps, ctxt); (*visitor)(ctxt); } else { loop_pop(c); (*exit)(ctxt); } } -} loopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo loopCPS ctxtName fname = let cond = iid condParamName formalArgCond = AST.CDecl [AST.CTypeSpec intTy] -- int (*cond)(ctxt *) [(Just (AST.CDeclr (Just cond) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*x)(ctxt *) [(Just (AST.CDeclr (Just x) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode visitor = iid visitorParamName formalArgVisitor = formalArgX visitor exit = iid exitParamName formalArgExit = formalArgX exit -- k = iid kParamName ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid loopName) [formalArgCond, formalArgVisitor, formalArgExit, formalArgCtxt] [ AST.CBlockStmt (AST.CIf (funCall (ind (cvar cond)) [(cvar ctxt)]) (AST.CCompound [] [ AST.CBlockStmt (AST.CExpr (Just $ funCall (cvar $ (iid fname) `app` (iid kPushName)) [adr (cvar (iid fname `app` iid lambdaLoopName)) , cvar ctxt ]) N.undefNode ) , AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar visitor)) [ cvar ctxt ]) N.undefNode ) ] N.undefNode) (Just (AST.CCompound [] [ AST.CBlockStmt ( AST.CExpr (Just $ funCall (cvar $ (iid fname ) `app` (iid loopPopName)) [ cvar ctxt ]) N.undefNode ) , AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar exit)) [ cvar ctxt ]) N.undefNode) ] N.undefNode)) N.undefNode) ] {- void lambda_loop_cps(sortctxt* c) { ctxt_arr_bool cc = loop_peek_cond(c); ctxt_arr_void v = loop_peek_v(c); ctxt_arr_void e = loop_peek_e(c); return loop_cps(cc,v,e,c);} -} lambdaLoopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo lambdaLoopCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode ty_ctxt_arr_bool = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_bool)) N.undefNode)] cc = iid fname `app` iid "cc" cc_var = Just (AST.CDeclr (Just cc) [] Nothing [] N.undefNode) cc_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid loopPeekCName))) [cvar $ iid ctxtParamName]) N.undefNode) ccDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_bool [(cc_var, cc_rhs, Nothing)] N.undefNode) ty_ctxt_arr_void = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)] v = iid fname `app` iid "v" v_var = Just (AST.CDeclr (Just v) [] Nothing [] N.undefNode) v_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid loopPeekVName))) [cvar $ iid ctxtParamName]) N.undefNode) vDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(v_var, v_rhs, Nothing)] N.undefNode) e = iid fname `app` iid "e" e_var = Just (AST.CDeclr (Just e) [] Nothing [] N.undefNode) e_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid loopPeekEName))) [cvar $ iid ctxtParamName]) N.undefNode) eDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(e_var, e_rhs, Nothing)] N.undefNode) in fun [AST.CTypeSpec voidTy] (iid fname `app` iid lambdaLoopName) [formalArgCtxt] [ ccDecl, vDecl, eDecl, AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (iid fname `app` iid loopName)) [ cvar cc, cvar v, cvar e , (cvar ctxt) ] N.undefNode)) N.undefNode) ] {- void id(sortctxt *ctxt) { ctxt_arr_void k = k_peek(ctxt); k_pop(ctxt); return (*k)(ctxt); } -} idCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo idCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode ty_ctxt_arr_void = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)] k = iid fname `app` iid "k" k_var = Just (AST.CDeclr (Just k) [] Nothing [] N.undefNode) k_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid kPeekName))) [cvar $ iid ctxtParamName]) N.undefNode) kDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(k_var, k_rhs, Nothing)] N.undefNode) in fun [AST.CTypeSpec voidTy] (iid fname `app` iid idName ) [formalArgCtxt] [ kDecl , AST.CBlockStmt (AST.CExpr (Just (funCall (cvar (iid fname `app` iid kPopName)) [ cvar ctxt ])) N.undefNode) , AST.CBlockStmt (AST.CReturn (Just (funCall (ind (cvar k)) [ cvar ctxt ])) N.undefNode) ] {- void ret(sortctxt *c) { return; } -} -- ^ abort the context retCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo retCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid retName ) [formalArgCtxt] [ AST.CBlockStmt (AST.CReturn Nothing N.undefNode) ] {- ctxt_arr_bool loop_peek_cond(sortctxt* c) { return c->loop_c[c->loop_stack_top-1]; } -} loopPeekCCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo loopPeekCCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_bool)) N.undefNode)] exp = ((cvar ctxt) .->. (iid loopStackCName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid loopStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode) in fun return_ty (iid fname `app` iid loopPeekCName ) [ formalArgCtxt ] [ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ] {- ctxt_arr_void loop_peek_v(sortctxt* c) { return c->loop_v[c->loop_stack_top-1]; } -} loopPeekVCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo loopPeekVCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)] exp = ((cvar ctxt) .->. (iid loopStackVName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid loopStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode) in fun return_ty (iid fname `app` iid loopPeekVName ) [ formalArgCtxt ] [ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ] {- ctxt_arr_void loop_peek_e(sortctxt* c) { return c->loop_e[c->loop_stack_top-1]; } -} loopPeekECPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo loopPeekECPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)] exp = ((cvar ctxt) .->. (iid loopStackEName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid loopStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode) in fun return_ty (iid fname `app` iid loopPeekEName ) [ formalArgCtxt ] [ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ] {- void lambda_bind_cps(sortctxt* c) { ctxt_arr_void m = bind_peek_m(c); ctxt_arr_void f = bind_peek_f(c); bind_pop(c); return bind_cps(m,f,c); } -} lambdaBindCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo lambdaBindCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode ty_ctxt_arr_void = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)] m = iid fname `app` iid "m" m_var = Just (AST.CDeclr (Just m) [] Nothing [] N.undefNode) m_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid bindPeekMName))) [cvar $ iid ctxtParamName]) N.undefNode) mDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(m_var, m_rhs, Nothing)] N.undefNode) f = iid fname `app` iid "f" f_var = Just (AST.CDeclr (Just f) [] Nothing [] N.undefNode) f_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid bindPeekFName))) [cvar $ iid ctxtParamName]) N.undefNode) fDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(f_var, f_rhs, Nothing)] N.undefNode) in fun [AST.CTypeSpec voidTy] (iid fname `app` iid lambdaBindName) [formalArgCtxt] [ mDecl, fDecl, AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (iid fname `app` iid bindPopName)) [ cvar ctxt ] N.undefNode)) N.undefNode), AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (iid fname `app` iid bindName)) [ cvar m, cvar f , (cvar ctxt) ] N.undefNode)) N.undefNode) ] {- void bind_cps(ctxt_arr_void m, ctxt_arr_void f, sortctxt* c) { k_push(f,c); return (*m)(c); } -} bindCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo bindCPS ctxtName fname = let cond = iid condParamName formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*x)(ctxt *) --todo: ctxt_arr_void x [(Just (AST.CDeclr (Just x) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode m = iid mParamName formalArgM = formalArgX m f = iid fParamName formalArgF = formalArgX f ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid bindName) [formalArgM, formalArgF, formalArgCtxt] [ AST.CBlockStmt (AST.CExpr (Just $ funCall (cvar $ (iid fname) `app` (iid kPushName)) [ cvar f , cvar ctxt ]) N.undefNode ) , AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar m)) [ cvar ctxt ]) N.undefNode ) ] {- void bind_push(ctxt_arr_void m, ctxt_arr_void f, sortctxt* c) { c->bind_m[c->bind_stack_top] = m; c->bind_f[c->bind_stack_top] = f; c->bind_stack_top +=1; return; } -} bindPushCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo bindPushCPS ctxtName fname = let formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*x)(ctxt *) [(Just (AST.CDeclr (Just x) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode second = iid mParamName formalArgSecond = formalArgX second third = iid fParamName formalArgThird = formalArgX third ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid bindPushName) [formalArgSecond, formalArgThird, formalArgCtxt] [ AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid bindStackMName)) .!!. (cvar ctxt .->. (iid bindStackTop))) .=. (cvar second))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid bindStackFName)) .!!. (cvar ctxt .->. (iid bindStackTop))) .=. (cvar third))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just ((cvar ctxt .->. (iid bindStackTop)) .=. (AST.CBinary AST.CAddOp (cvar ctxt .->. (iid bindStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode))) N.undefNode) ] {- ctxt_arr_void bind_peek_m(sortctxt* c) { return c->bind_m[c->bind_stack_top-1]; } ctxt_arr_void bind_peek_f(sortctxt* c) { return c->bind_f[c->bind_stack_top-1]; } -} bindPeekMCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo bindPeekMCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)] exp = ((cvar ctxt) .->. (iid bindStackMName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid bindStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode) in fun return_ty (iid fname `app` iid bindPeekMName ) [ formalArgCtxt ] [ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ] bindPeekFCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo bindPeekFCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)] exp = ((cvar ctxt) .->. (iid bindStackFName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid bindStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode) in fun return_ty (iid fname `app` iid bindPeekFName ) [ formalArgCtxt ] [ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ] {- void ifc_cps(ctxt_arr_bool cond, ctxt_arr_void t, ctxt_arr_void f, sortctxt* c) { ifc_pop(c); if ((*cond)(c)) { return (*t)(c); } else { return (*f)(c); } } -} ifcCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo ifcCPS ctxtName fname = let cond = iid condParamName formalArgCond = AST.CDecl [AST.CTypeSpec intTy] -- int (*cond)(ctxt *) -- todo change to ctxt_arr_bool cond [(Just (AST.CDeclr (Just cond) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*x)(ctxt *) [(Just (AST.CDeclr (Just x) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode tr = iid trueParamName formalArgTr = formalArgX tr fl = iid falseParamName formalArgFl = formalArgX fl -- k = iid kParamName ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid ifcName) [formalArgCond, formalArgTr, formalArgFl, formalArgCtxt] [ AST.CBlockStmt ( AST.CExpr (Just $ funCall (cvar $ (iid fname ) `app` (iid ifcPopName)) [ cvar ctxt ]) N.undefNode ) ,AST.CBlockStmt (AST.CIf (funCall (ind (cvar cond)) [(cvar ctxt)]) (AST.CCompound [] [AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar tr)) [ cvar ctxt ]) N.undefNode ) ] N.undefNode) (Just (AST.CCompound [] [AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar fl)) [ cvar ctxt ]) N.undefNode) ] N.undefNode)) N.undefNode) ] {- void lambda_ifc_cps(sortctxt* c) { ctxt_arr_bool cc = ifc_peek_c(c); ctxt_arr_void tr = ifc_peek_tr(c); ctxt_arr_void fl = ifc_peek_fl(c); return ifc_cps(cc,tr,fl,c); } -} lambdaIfcCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo lambdaIfcCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode ty_ctxt_arr_bool = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_bool)) N.undefNode)] cc = iid fname `app` iid "cc" cc_var = Just (AST.CDeclr (Just cc) [] Nothing [] N.undefNode) cc_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid ifcPeekCName))) [cvar $ iid ctxtParamName]) N.undefNode) ccDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_bool [(cc_var, cc_rhs, Nothing)] N.undefNode) ty_ctxt_arr_void = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)] tr = iid fname `app` iid "tr" tr_var = Just (AST.CDeclr (Just tr) [] Nothing [] N.undefNode) tr_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid ifcPeekTrName))) [cvar $ iid ctxtParamName]) N.undefNode) trDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(tr_var, tr_rhs, Nothing)] N.undefNode) fl = iid fname `app` iid "fl" fl_var = Just (AST.CDeclr (Just fl) [] Nothing [] N.undefNode) fl_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid ifcPeekFlName))) [cvar $ iid ctxtParamName]) N.undefNode) flDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(fl_var, fl_rhs, Nothing)] N.undefNode) in fun [AST.CTypeSpec voidTy] (iid fname `app` iid lambdaIfcName) [formalArgCtxt] [ ccDecl, trDecl, flDecl, AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (iid fname `app` iid ifcName)) [ cvar cc, cvar tr, cvar fl , (cvar ctxt) ] N.undefNode)) N.undefNode) ] {- ctxt_arr_bool ifc_peek_c(sortctxt* c) { return c->ifc_c[c->ifc_stack_top-1]; } -} ifcPeekCCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo ifcPeekCCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_bool)) N.undefNode)] exp = ((cvar ctxt) .->. (iid ifcStackCName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid ifcStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode) in fun return_ty (iid fname `app` iid ifcPeekCName ) [ formalArgCtxt ] [ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ] {- ctxt_arr_void ifc_peek_tr(sortctxt* c) { return c->ifc_tr[c->ifc_stack_top-1]; } -} ifcPeekTrCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo ifcPeekTrCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)] exp = ((cvar ctxt) .->. (iid ifcStackTrName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid ifcStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode) in fun return_ty (iid fname `app` iid ifcPeekTrName ) [ formalArgCtxt ] [ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ] {- ctxt_arr_void ifc_peek_fl(sortctxt* c) { return c->ifc_fl[c->ifc_stack_top-1]; } -} ifcPeekFlCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo ifcPeekFlCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)] exp = ((cvar ctxt) .->. (iid ifcStackFlName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid ifcStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode) in fun return_ty (iid fname `app` iid ifcPeekFlName ) [ formalArgCtxt ] [ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ] {- void k_push(ctxt_arr_void k, sortctxt* c) { c->k[c->k_stack_top] = k; c->k_stack_top +=1; return; } -} kPushCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo kPushCPS ctxtName fname = let formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*x)(ctxt *) [(Just (AST.CDeclr (Just x) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode k = iid kParamName formalArgK = formalArgX k ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid kPushName) [formalArgK, formalArgCtxt] [ AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid kStackName)) .!!. (cvar ctxt .->. (iid kStackTop))) .=. (cvar k))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just ((cvar ctxt .->. (iid kStackTop)) .=. (AST.CBinary AST.CAddOp (cvar ctxt .->. (iid kStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode))) N.undefNode) ] {- ctxt_arr_void k_peek(sortctxt* c) { return c->k[c->k_stack_top-1]; } -} kPeekCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo kPeekCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)] exp = ((cvar ctxt) .->. (iid kStackName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid kStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode) in fun return_ty (iid fname `app` iid kPeekName ) [ formalArgCtxt ] [ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ] -- ^ generate function signature declaration from function definition funSig :: AST.CFunctionDef N.NodeInfo -> AST.CDeclaration N.NodeInfo funSig (AST.CFunDef tySpecfs declarator op_decls stmt nodeInfo) = AST.CDecl tySpecfs [(Just declarator, Nothing, Nothing)] N.undefNode -- ^ making the context struct declaration mkContext :: String -> -- ^ context name M.Map Ident LabeledBlock -> -- ^ labeled blocks [AST.CDeclaration N.NodeInfo] -> -- ^ formal arguments [AST.CDeclaration N.NodeInfo] -> -- ^ local variable declarations [AST.CDeclarationSpecifier N.NodeInfo] -> -- ^ return Type [AST.CDerivedDeclarator N.NodeInfo] -> -- ^ the pointer or array postfix S.Set Ident -> S.Set Ident -> AST.CDeclaration N.NodeInfo mkContext name labeledBlocks formal_arg_decls local_var_decls returnType ptrArrs local_decl_vars fargs = let structName = iid name ctxtAlias = AST.CDeclr (Just (internalIdent (map toLower name))) [] Nothing [] N.undefNode attrs = [] stackSize = 20 isReturnVoid = isVoidDeclSpec returnType unaryFuncStack ty fname = AST.CDecl [AST.CTypeSpec ty] -- void (*loop_ks[2])(struct FuncCtxt*); -- todo : these are horrible to read, can be simplified via some combinators [(Just (AST.CDeclr (Just $ iid fname) [ AST.CArrDeclr [] (AST.CArrSize False (AST.CConst (AST.CIntConst (cInteger stackSize) N.undefNode))) N.undefNode , AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CSUType (AST.CStruct AST.CStructTag (Just structName) Nothing [] N.undefNode) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode],False)) [] N.undefNode] Nothing [] N.undefNode) ,Nothing,Nothing)] N.undefNode kStack = unaryFuncStack voidTy kStackName loopCStack = unaryFuncStack intTy loopStackCName loopVStack = unaryFuncStack voidTy loopStackVName loopEStack = unaryFuncStack voidTy loopStackEName ifcCStatck = unaryFuncStack intTy ifcStackCName ifcTrStack = unaryFuncStack voidTy ifcStackTrName ifcFlStack = unaryFuncStack voidTy ifcStackFlName bindMStack = unaryFuncStack voidTy bindStackMName bindFStack = unaryFuncStack voidTy bindStackFName stackTop name = AST.CDecl [AST.CTypeSpec intTy] [(Just (AST.CDeclr (Just $ iid name) [] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode kTop = stackTop kStackTop loopTop = stackTop loopStackTop ifcTop = stackTop ifcStackTop bindTop = stackTop bindStackTop funcResult | isReturnVoid = [] | otherwise = [AST.CDecl returnType [(Just (AST.CDeclr (Just $ iid "func_result") ptrArrs Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode] decls' = -- formal_arg_decls ++ -- note: we remove local decl duplicate, maybe we should let different label block to have different type decl in the ctxt, see test/scoped_dup_var.c concatMap (\d -> renameDeclWithLabeledBlocks d labeledBlocks local_decl_vars fargs) (nubBy declLHSEq $ map (cps_trans_declaration . dropConstTyQual . dropStorageQual) (formal_arg_decls ++ local_var_decls)) ++ [kStack, loopCStack, loopVStack, loopEStack, ifcCStatck, ifcTrStack, ifcFlStack, bindMStack, bindFStack, kTop, loopTop, ifcTop, bindTop ] ++ funcResult tyDef = AST.CStorageSpec (AST.CTypedef N.undefNode) structDef = AST.CTypeSpec (AST.CSUType (AST.CStruct AST.CStructTag (Just structName) (Just decls') attrs N.undefNode) N.undefNode) in AST.CDecl [tyDef, structDef] [(Just ctxtAlias, Nothing, Nothing)] N.undefNode ctxt_arr_voidDecl :: String -> -- ^ context name String -> -- ^ function name AST.CDeclaration N.NodeInfo ctxt_arr_voidDecl ctxtName fname = let tyDef = AST.CStorageSpec (AST.CTypedef N.undefNode) voidTyDef = AST.CTypeSpec voidTy def = AST.CDeclr (Just (iid fname `app` iid ctxt_arr_void)) [AST.CPtrDeclr [] N.undefNode, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode],False)) [] N.undefNode] Nothing [] N.undefNode in AST.CDecl [tyDef, voidTyDef] [(Just def, Nothing, Nothing)] N.undefNode ctxt_arr_boolDecl :: String -> -- ^ context name String -> -- ^ function name AST.CDeclaration N.NodeInfo ctxt_arr_boolDecl ctxtName fname = let tyDef = AST.CStorageSpec (AST.CTypedef N.undefNode) intTyDef = AST.CTypeSpec intTy def = AST.CDeclr (Just (iid fname `app` iid ctxt_arr_bool)) [AST.CPtrDeclr [] N.undefNode, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode],False)) [] N.undefNode] Nothing [] N.undefNode in AST.CDecl [tyDef, intTyDef] [(Just def, Nothing, Nothing)] N.undefNode -- eq for the declaration nub, see the above declLHSEq (AST.CDecl declSpecifiers1 trips1 _) (AST.CDecl declSpecifiers2 trips2 _) = let getIds trips = map (\(mb_decl, mb_init, mb_size) -> case mb_decl of { Just (AST.CDeclr mb_id derivedDeclarators mb_strLit attrs nInfo) -> mb_id ; Nothing -> Nothing }) trips in (getIds trips1) == (getIds trips2) -- we need to drop the constant type specifier since we need to initialize them in block 0, see test/const.c dropConstTyQual :: AST.CDeclaration N.NodeInfo -> AST.CDeclaration N.NodeInfo dropConstTyQual decl = case decl of { AST.CDecl declSpecifiers trips ni -> AST.CDecl (filter (not . isConst) declSpecifiers) trips ni } where isConst (AST.CTypeQual (AST.CConstQual _)) = True isConst _ = False -- we need to drop the static storage specifier since we need to initialize them in block 0, see test/arrayinitlist.c dropStorageQual :: AST.CDeclaration N.NodeInfo -> AST.CDeclaration N.NodeInfo dropStorageQual decl = case decl of { AST.CDecl declSpecifiers trips ni -> AST.CDecl (filter (not . isStorageQual) declSpecifiers) trips ni } -- renameDeclWithLabels :: AST.CDeclaration N.NodeInfo -> [Ident] -> [AST.CDeclaration N.NodeInfo] -- renameDeclWithLabels decl labels = map (renameDeclWithLabel decl) labels renameDeclWithLabeledBlocks :: AST.CDeclaration N.NodeInfo -> M.Map Ident LabeledBlock -> S.Set Ident -> S.Set Ident -> [AST.CDeclaration N.NodeInfo] renameDeclWithLabeledBlocks decl labeledBlocks local_decl_vars fargs = let idents = getFormalArgIds decl in do { ident <- idents ; (lb,blk) <- M.toList labeledBlocks ; if (null (lb_preds blk)) || -- it's the entry block (ident `elem` (lb_lvars blk)) || -- the var is in the lvars (ident `elem` (map fst (lb_phis blk))) || -- the var is in the phi (ident `elem` (lb_containers blk)) -- the var is one of the lhs container ids such as array or members then return (renameDeclWithLabel decl lb local_decl_vars fargs) else [] } renameDeclWithLabel decl label local_decl_vars fargs = let rnState = RSt label M.empty [] [] local_decl_vars fargs in case renamePure rnState decl of { (decl', rstate', containers) -> decl' } {- translation t => T ----------- int => int ----------- bool => bool t => t ------------- t* => T* t => T ------------ t[] => T* ------------- void => void -} cps_trans_declaration :: AST.CDeclaration N.NodeInfo -> AST.CDeclaration N.NodeInfo cps_trans_declaration (AST.CDecl declSpecifiers trips ni) = AST.CDecl (map cps_trans_declspec declSpecifiers) (map (\(mb_decl, mb_init, mb_size) -> let mb_decl' = case mb_decl of { Nothing -> Nothing ; Just decl -> Just (cps_trans_decltr decl) } in (mb_decl', mb_init, mb_size)) trips) ni -- lhs of a declaration cps_trans_declspec :: AST.CDeclarationSpecifier N.NodeInfo -> AST.CDeclarationSpecifier N.NodeInfo cps_trans_declspec (AST.CStorageSpec storageSpec) = AST.CStorageSpec storageSpec -- auto, register, static, extern etc cps_trans_declspec (AST.CTypeSpec tySpec) = AST.CTypeSpec tySpec -- simple type, void, int, bool etc cps_trans_declspec (AST.CTypeQual tyQual) = AST.CTypeQual tyQual -- qual, CTypeQual, CVolatQual, etc -- cps_trans_declspec (AST.CFunSpec funSpec) = AST.CFunSpec funSpec -- todo -- cps_trans_declspec (AST.CAlignSpec alignSpec) = AST.CAlignSpec alignSpec -- todo -- rhs (after the variable) cps_trans_decltr :: AST.CDeclarator N.NodeInfo -> AST.CDeclarator N.NodeInfo cps_trans_decltr (AST.CDeclr mb_id derivedDeclarators mb_strLit attrs nInfo) = AST.CDeclr mb_id (map cps_trans_derived_decltr derivedDeclarators) mb_strLit attrs nInfo cps_trans_derived_decltr :: AST.CDerivedDeclarator N.NodeInfo -> AST.CDerivedDeclarator N.NodeInfo cps_trans_derived_decltr (AST.CPtrDeclr tyQuals ni) = AST.CPtrDeclr tyQuals ni cps_trans_derived_decltr (AST.CArrDeclr tyQuals arrSize ni) = AST.CPtrDeclr tyQuals ni cps_trans_derived_decltr (AST.CFunDeclr either_id_decls attrs ni) = AST.CFunDeclr either_id_decls attrs ni {- data CDeclarationSpecifier a = CStorageSpec (CStorageSpecifier a) -- ^ storage-class specifier or typedef | CTypeSpec (CTypeSpecifier a) -- ^ type name | CTypeQual (CTypeQualifier a) -- ^ type qualifier | CFunSpec (CFunctionSpecifier a) -- ^ function specifier | CAlignSpec (CAlignmentSpecifier a) -- ^ alignment specifier deriving (Show, Data,Typeable {-! ,CNode ,Functor, Annotated !-}) -}
luzhuomi/cpp-obs
Language/C/Obfuscate/CPS.hs
apache-2.0
92,814
9
31
28,042
23,363
12,203
11,160
937
19
module Main ( main ) where import Protolude import Test.Tasty (defaultMain, testGroup) import qualified Spake2 import qualified Groups import qualified Integration main :: IO () main = sequence tests >>= defaultMain . testGroup "Spake2" where tests = [ Spake2.tests , Groups.tests , Integration.tests ]
jml/haskell-spake2
tests/Tasty.hs
apache-2.0
341
0
8
82
88
52
36
13
1
-- | Domain of terms. module Akarui.FOL.Domain where import Data.Set (Set) import Akarui.Parser import Text.Parsec import Text.Parsec.String (Parser) import qualified Data.Set as Set -- | Domain of variables and constants. data Domain = Any | Interval Double Double | Finite (Set String) -- | Parse a clause (a disjunction of positive and negative literals). -- -- @ -- dom1={1, 2, 3, 4} -- person = { Elaine, George, Jerry, Cosmo, Newman } -- @ parseDomain :: String -> Either ParseError (String, Set String) parseDomain = parse (contents parseDs) "<stdin>" parseDs :: Parser (String, Set String) parseDs = do n <- identifier reservedOp "=" reservedOp "{" elems <- commaSep identifier reservedOp "}" return (n, Set.fromList elems)
PhDP/Manticore
Akarui/FOL/Domain.hs
apache-2.0
763
0
10
146
192
105
87
20
1
module Reddit.Routes.Search where import Reddit.Types.Options import Reddit.Types.Post import Reddit.Types.Subreddit import qualified Reddit.Types.SearchOptions as Search import Data.Maybe import Data.Text (Text) import Network.API.Builder.Routes searchRoute :: Maybe SubredditName -> Options PostID -> Search.Order -> Maybe Text -> Text -> Route searchRoute r opts sorder engine q = Route (path r) [ "after" =. after opts , "before" =. before opts , "restrict_sr" =. isJust r , "sort" =. sorder , "syntax" =. engine , "limit" =. limit opts , "q" =. Just q ] "GET" where path (Just (R sub)) = [ "r", sub, "search" ] path Nothing = [ "search" ]
intolerable/reddit
src/Reddit/Routes/Search.hs
bsd-2-clause
723
0
11
178
227
125
102
21
2
{-# LANGUAGE FlexibleContexts #-} module Application.DiagramDrawer.Coroutine where import Control.Monad.Coroutine import Control.Monad.State import Control.Monad.Coroutine.SuspensionFunctors import Data.IORef import Application.DiagramDrawer.Type bouncecallback :: IORef (Await DiagramEvent (Iteratee DiagramEvent DiagramStateIO ())) -> IORef DiagramState -> DiagramEvent -> IO () bouncecallback tref sref input = do Await cont <- readIORef tref st <- readIORef sref (nr,st') <- runStateT (resume (cont input)) st case nr of Left naw -> do writeIORef tref naw writeIORef sref st' Right val -> do putStrLn $ show val writeIORef tref (Await (\_ -> return ())) writeIORef sref st' putStrLn "one step" return ()
wavewave/diagdrawer
lib/Application/DiagramDrawer/Coroutine.hs
bsd-2-clause
852
0
18
236
251
121
130
23
2
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QFileInfo.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:31 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Core.QFileInfo ( QqFileInfo(..) ,QqFileInfo_nf(..) ,absoluteDir ,baseName ,bundleName ,caching ,canonicalFilePath ,completeBaseName ,completeSuffix ,created ,dir ,groupId ,isBundle ,ownerId ,permission ,setCaching ,qFileInfo_delete ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.QFile import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core class QqFileInfo x1 where qFileInfo :: x1 -> IO (QFileInfo ()) instance QqFileInfo (()) where qFileInfo () = withQFileInfoResult $ qtc_QFileInfo foreign import ccall "qtc_QFileInfo" qtc_QFileInfo :: IO (Ptr (TQFileInfo ())) instance QqFileInfo ((QFile t1)) where qFileInfo (x1) = withQFileInfoResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QFileInfo1 cobj_x1 foreign import ccall "qtc_QFileInfo1" qtc_QFileInfo1 :: Ptr (TQFile t1) -> IO (Ptr (TQFileInfo ())) instance QqFileInfo ((QFileInfo t1)) where qFileInfo (x1) = withQFileInfoResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QFileInfo2 cobj_x1 foreign import ccall "qtc_QFileInfo2" qtc_QFileInfo2 :: Ptr (TQFileInfo t1) -> IO (Ptr (TQFileInfo ())) instance QqFileInfo ((String)) where qFileInfo (x1) = withQFileInfoResult $ withCWString x1 $ \cstr_x1 -> qtc_QFileInfo3 cstr_x1 foreign import ccall "qtc_QFileInfo3" qtc_QFileInfo3 :: CWString -> IO (Ptr (TQFileInfo ())) instance QqFileInfo ((QDir t1, String)) where qFileInfo (x1, x2) = withQFileInfoResult $ withObjectPtr x1 $ \cobj_x1 -> withCWString x2 $ \cstr_x2 -> qtc_QFileInfo4 cobj_x1 cstr_x2 foreign import ccall "qtc_QFileInfo4" qtc_QFileInfo4 :: Ptr (TQDir t1) -> CWString -> IO (Ptr (TQFileInfo ())) class QqFileInfo_nf x1 where qFileInfo_nf :: x1 -> IO (QFileInfo ()) instance QqFileInfo_nf (()) where qFileInfo_nf () = withObjectRefResult $ qtc_QFileInfo instance QqFileInfo_nf ((QFile t1)) where qFileInfo_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QFileInfo1 cobj_x1 instance QqFileInfo_nf ((QFileInfo t1)) where qFileInfo_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QFileInfo2 cobj_x1 instance QqFileInfo_nf ((String)) where qFileInfo_nf (x1) = withObjectRefResult $ withCWString x1 $ \cstr_x1 -> qtc_QFileInfo3 cstr_x1 instance QqFileInfo_nf ((QDir t1, String)) where qFileInfo_nf (x1, x2) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withCWString x2 $ \cstr_x2 -> qtc_QFileInfo4 cobj_x1 cstr_x2 absoluteDir :: QFileInfo a -> (()) -> IO (QDir ()) absoluteDir x0 () = withQDirResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_absoluteDir cobj_x0 foreign import ccall "qtc_QFileInfo_absoluteDir" qtc_QFileInfo_absoluteDir :: Ptr (TQFileInfo a) -> IO (Ptr (TQDir ())) instance QabsoluteFilePath (QFileInfo a) (()) where absoluteFilePath x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_absoluteFilePath cobj_x0 foreign import ccall "qtc_QFileInfo_absoluteFilePath" qtc_QFileInfo_absoluteFilePath :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) instance QabsolutePath (QFileInfo a) (()) where absolutePath x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_absolutePath cobj_x0 foreign import ccall "qtc_QFileInfo_absolutePath" qtc_QFileInfo_absolutePath :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) baseName :: QFileInfo a -> (()) -> IO (String) baseName x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_baseName cobj_x0 foreign import ccall "qtc_QFileInfo_baseName" qtc_QFileInfo_baseName :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) bundleName :: QFileInfo a -> (()) -> IO (String) bundleName x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_bundleName cobj_x0 foreign import ccall "qtc_QFileInfo_bundleName" qtc_QFileInfo_bundleName :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) caching :: QFileInfo a -> (()) -> IO (Bool) caching x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_caching cobj_x0 foreign import ccall "qtc_QFileInfo_caching" qtc_QFileInfo_caching :: Ptr (TQFileInfo a) -> IO CBool canonicalFilePath :: QFileInfo a -> (()) -> IO (String) canonicalFilePath x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_canonicalFilePath cobj_x0 foreign import ccall "qtc_QFileInfo_canonicalFilePath" qtc_QFileInfo_canonicalFilePath :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) instance QcanonicalPath (QFileInfo a) (()) where canonicalPath x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_canonicalPath cobj_x0 foreign import ccall "qtc_QFileInfo_canonicalPath" qtc_QFileInfo_canonicalPath :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) completeBaseName :: QFileInfo a -> (()) -> IO (String) completeBaseName x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_completeBaseName cobj_x0 foreign import ccall "qtc_QFileInfo_completeBaseName" qtc_QFileInfo_completeBaseName :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) completeSuffix :: QFileInfo a -> (()) -> IO (String) completeSuffix x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_completeSuffix cobj_x0 foreign import ccall "qtc_QFileInfo_completeSuffix" qtc_QFileInfo_completeSuffix :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) created :: QFileInfo a -> (()) -> IO (QDateTime ()) created x0 () = withQDateTimeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_created cobj_x0 foreign import ccall "qtc_QFileInfo_created" qtc_QFileInfo_created :: Ptr (TQFileInfo a) -> IO (Ptr (TQDateTime ())) instance Qdetach (QFileInfo a) (()) where detach x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_detach cobj_x0 foreign import ccall "qtc_QFileInfo_detach" qtc_QFileInfo_detach :: Ptr (TQFileInfo a) -> IO () dir :: QFileInfo a -> (()) -> IO (QDir ()) dir x0 () = withQDirResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_dir cobj_x0 foreign import ccall "qtc_QFileInfo_dir" qtc_QFileInfo_dir :: Ptr (TQFileInfo a) -> IO (Ptr (TQDir ())) instance Qexists (QFileInfo a) (()) where exists x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_exists cobj_x0 foreign import ccall "qtc_QFileInfo_exists" qtc_QFileInfo_exists :: Ptr (TQFileInfo a) -> IO CBool instance QfileName (QFileInfo a) (()) where fileName x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_fileName cobj_x0 foreign import ccall "qtc_QFileInfo_fileName" qtc_QFileInfo_fileName :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) instance QfilePath (QFileInfo a) (()) where filePath x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_filePath cobj_x0 foreign import ccall "qtc_QFileInfo_filePath" qtc_QFileInfo_filePath :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) instance Qgroup (QFileInfo a) (()) (IO (String)) where group x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_group cobj_x0 foreign import ccall "qtc_QFileInfo_group" qtc_QFileInfo_group :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) groupId :: QFileInfo a -> (()) -> IO (Int) groupId x0 () = withUnsignedIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_groupId cobj_x0 foreign import ccall "qtc_QFileInfo_groupId" qtc_QFileInfo_groupId :: Ptr (TQFileInfo a) -> IO CUInt instance QisAbsolute (QFileInfo a) (()) where isAbsolute x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_isAbsolute cobj_x0 foreign import ccall "qtc_QFileInfo_isAbsolute" qtc_QFileInfo_isAbsolute :: Ptr (TQFileInfo a) -> IO CBool isBundle :: QFileInfo a -> (()) -> IO (Bool) isBundle x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_isBundle cobj_x0 foreign import ccall "qtc_QFileInfo_isBundle" qtc_QFileInfo_isBundle :: Ptr (TQFileInfo a) -> IO CBool instance QisDir (QFileInfo a) (()) where isDir x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_isDir cobj_x0 foreign import ccall "qtc_QFileInfo_isDir" qtc_QFileInfo_isDir :: Ptr (TQFileInfo a) -> IO CBool instance QisExecutable (QFileInfo a) (()) where isExecutable x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_isExecutable cobj_x0 foreign import ccall "qtc_QFileInfo_isExecutable" qtc_QFileInfo_isExecutable :: Ptr (TQFileInfo a) -> IO CBool instance QisFile (QFileInfo a) (()) where isFile x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_isFile cobj_x0 foreign import ccall "qtc_QFileInfo_isFile" qtc_QFileInfo_isFile :: Ptr (TQFileInfo a) -> IO CBool instance QisHidden (QFileInfo a) (()) where isHidden x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_isHidden cobj_x0 foreign import ccall "qtc_QFileInfo_isHidden" qtc_QFileInfo_isHidden :: Ptr (TQFileInfo a) -> IO CBool instance QisReadable (QFileInfo a) (()) where isReadable x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_isReadable cobj_x0 foreign import ccall "qtc_QFileInfo_isReadable" qtc_QFileInfo_isReadable :: Ptr (TQFileInfo a) -> IO CBool instance QisRelative (QFileInfo a) (()) where isRelative x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_isRelative cobj_x0 foreign import ccall "qtc_QFileInfo_isRelative" qtc_QFileInfo_isRelative :: Ptr (TQFileInfo a) -> IO CBool instance QisRoot (QFileInfo a) (()) where isRoot x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_isRoot cobj_x0 foreign import ccall "qtc_QFileInfo_isRoot" qtc_QFileInfo_isRoot :: Ptr (TQFileInfo a) -> IO CBool instance QisSymLink (QFileInfo a) (()) where isSymLink x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_isSymLink cobj_x0 foreign import ccall "qtc_QFileInfo_isSymLink" qtc_QFileInfo_isSymLink :: Ptr (TQFileInfo a) -> IO CBool instance QisWritable (QFileInfo a) (()) where isWritable x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_isWritable cobj_x0 foreign import ccall "qtc_QFileInfo_isWritable" qtc_QFileInfo_isWritable :: Ptr (TQFileInfo a) -> IO CBool instance QlastModified (QFileInfo a) (()) where lastModified x0 () = withQDateTimeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_lastModified cobj_x0 foreign import ccall "qtc_QFileInfo_lastModified" qtc_QFileInfo_lastModified :: Ptr (TQFileInfo a) -> IO (Ptr (TQDateTime ())) instance QlastRead (QFileInfo a) (()) where lastRead x0 () = withQDateTimeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_lastRead cobj_x0 foreign import ccall "qtc_QFileInfo_lastRead" qtc_QFileInfo_lastRead :: Ptr (TQFileInfo a) -> IO (Ptr (TQDateTime ())) instance QmakeAbsolute (QFileInfo a) (()) where makeAbsolute x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_makeAbsolute cobj_x0 foreign import ccall "qtc_QFileInfo_makeAbsolute" qtc_QFileInfo_makeAbsolute :: Ptr (TQFileInfo a) -> IO CBool instance Qowner (QFileInfo a) (()) where owner x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_owner cobj_x0 foreign import ccall "qtc_QFileInfo_owner" qtc_QFileInfo_owner :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) ownerId :: QFileInfo a -> (()) -> IO (Int) ownerId x0 () = withUnsignedIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_ownerId cobj_x0 foreign import ccall "qtc_QFileInfo_ownerId" qtc_QFileInfo_ownerId :: Ptr (TQFileInfo a) -> IO CUInt instance Qpath (QFileInfo a) (()) (IO (String)) where path x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_path cobj_x0 foreign import ccall "qtc_QFileInfo_path" qtc_QFileInfo_path :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) permission :: QFileInfo a -> ((Permissions)) -> IO (Bool) permission x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_permission cobj_x0 (toCLong $ qFlags_toInt x1) foreign import ccall "qtc_QFileInfo_permission" qtc_QFileInfo_permission :: Ptr (TQFileInfo a) -> CLong -> IO CBool instance Qpermissions (QFileInfo a) (()) (IO (Permissions)) where permissions x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_permissions cobj_x0 foreign import ccall "qtc_QFileInfo_permissions" qtc_QFileInfo_permissions :: Ptr (TQFileInfo a) -> IO CLong instance QreadLink (QFileInfo a) (()) where readLink x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_readLink cobj_x0 foreign import ccall "qtc_QFileInfo_readLink" qtc_QFileInfo_readLink :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) instance Qrefresh (QFileInfo a) (()) where refresh x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_refresh cobj_x0 foreign import ccall "qtc_QFileInfo_refresh" qtc_QFileInfo_refresh :: Ptr (TQFileInfo a) -> IO () setCaching :: QFileInfo a -> ((Bool)) -> IO () setCaching x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_setCaching cobj_x0 (toCBool x1) foreign import ccall "qtc_QFileInfo_setCaching" qtc_QFileInfo_setCaching :: Ptr (TQFileInfo a) -> CBool -> IO () instance QsetFile (QFileInfo a) ((QDir t1, String)) where setFile x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCWString x2 $ \cstr_x2 -> qtc_QFileInfo_setFile2 cobj_x0 cobj_x1 cstr_x2 foreign import ccall "qtc_QFileInfo_setFile2" qtc_QFileInfo_setFile2 :: Ptr (TQFileInfo a) -> Ptr (TQDir t1) -> CWString -> IO () instance QsetFile (QFileInfo a) ((QFile t1)) where setFile x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFileInfo_setFile1 cobj_x0 cobj_x1 foreign import ccall "qtc_QFileInfo_setFile1" qtc_QFileInfo_setFile1 :: Ptr (TQFileInfo a) -> Ptr (TQFile t1) -> IO () instance QsetFile (QFileInfo a) ((String)) where setFile x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFileInfo_setFile cobj_x0 cstr_x1 foreign import ccall "qtc_QFileInfo_setFile" qtc_QFileInfo_setFile :: Ptr (TQFileInfo a) -> CWString -> IO () instance Qqsize (QFileInfo a) (()) (IO (Int)) where qsize x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_size cobj_x0 foreign import ccall "qtc_QFileInfo_size" qtc_QFileInfo_size :: Ptr (TQFileInfo a) -> IO CLLong instance Qsuffix (QFileInfo a) (()) where suffix x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_suffix cobj_x0 foreign import ccall "qtc_QFileInfo_suffix" qtc_QFileInfo_suffix :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) instance QsymLinkTarget (QFileInfo a) (()) where symLinkTarget x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_symLinkTarget cobj_x0 foreign import ccall "qtc_QFileInfo_symLinkTarget" qtc_QFileInfo_symLinkTarget :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ())) qFileInfo_delete :: QFileInfo a -> IO () qFileInfo_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QFileInfo_delete cobj_x0 foreign import ccall "qtc_QFileInfo_delete" qtc_QFileInfo_delete :: Ptr (TQFileInfo a) -> IO ()
keera-studios/hsQt
Qtc/Core/QFileInfo.hs
bsd-2-clause
15,873
0
13
2,716
5,155
2,612
2,543
-1
-1
module Main (main) where import Paths_eclogues_impl (getDataFileName) import Language.Haskell.HLint (hlint) import System.Exit (exitFailure, exitSuccess) paths :: [String] paths = [ "app" , "test" ] arguments :: IO [String] arguments = go <$> getDataFileName "HLint.hints" where go p = ("--hint=" ++ p) : paths main :: IO () main = do hints <- hlint =<< arguments if null hints then exitSuccess else exitFailure
futufeld/eclogues
eclogues-impl/test/HLint.hs
bsd-3-clause
442
0
9
92
144
81
63
15
2
module Database.Riak ( M.RiakException(..), M.VClock(..), M.BucketName(..), M.Key(..), M.ClientId(..), M.Quorum(..), B.Riak, B.Basic(..), B.Pong(..), B.ping, B.getClientId, B.setClientId, B.getServerInfo, B.get, B.put, B.delete, B.listBuckets, B.listKeys, B.getBucket, B.setBucket, B.mapReduce, B.indexQuery, B.searchQuery, B.runRiak, numFound, maxScore, documents, start, sort, rows, query, presort, operation, fieldsLimit, searchFilter, df, returnHead, returnBody, ifNotModified, ifNoneMatch, response, phase, request, buckets, tag, rangeMin, rangeMax, qtype, serverVersion, node, unchanged, notFoundOk, ifModified, onlyHead, deletedVClock, basicQuorum, errorMessage, errorCode, rw, vTag, userMeta, links, lastModUsecs, lastMod, indexes, deleted, contentEncoding, charset, nVal, allowMult, r, pr, keys, contentType, done, value, w, pw, dw, vClock, key, content, indexValue, bucket, clientId, props, L.HasR, L.HasPR, L.HasKeys, L.HasContentType, L.HasDone, L.HasValue, L.HasW, L.HasPW, L.HasDW, L.HasVClock, L.HasKey, L.HasContent, L.HasIndex, L.HasBucket, L.HasClientId, L.HasProps, BucketProps, Content, DeleteRequest, ErrorResponse, GetBucketRequest, GetBucketResponse, GetClientIDResponse, GetRequest, GetResponse, GetServerInfoResponse, IndexRequest, IndexQueryType, IndexResponse, Link, ListBucketsResponse, ListKeysRequest, ListKeysResponse, MapReduceRequest, MapReduceResponse, Pair, PutRequest, PutResponse, SearchDocument, SearchQueryRequest, SearchQueryResponse, SetBucketRequest, SetClientIDRequest, module Database.Riak.Connection ) where import qualified Control.Lens as Lens import Data.ByteString.Lazy (ByteString) import Data.Sequence (Seq) import Data.Word import qualified Database.Riak.Basic as B import Database.Riak.Connection import qualified Database.Riak.Messages as M import qualified Database.Riak.Lens as L import Database.Riak.Protocol.BucketProps (BucketProps) import Database.Riak.Protocol.Content (Content) import Database.Riak.Protocol.DeleteRequest (DeleteRequest) import Database.Riak.Protocol.ErrorResponse (ErrorResponse) import Database.Riak.Protocol.GetBucketRequest (GetBucketRequest) import Database.Riak.Protocol.GetBucketResponse (GetBucketResponse) import Database.Riak.Protocol.GetClientIDResponse (GetClientIDResponse) import Database.Riak.Protocol.GetRequest (GetRequest) import Database.Riak.Protocol.GetResponse (GetResponse) import Database.Riak.Protocol.GetServerInfoResponse (GetServerInfoResponse) import Database.Riak.Protocol.IndexRequest (IndexRequest) import Database.Riak.Protocol.IndexRequest.IndexQueryType (IndexQueryType) import Database.Riak.Protocol.IndexResponse (IndexResponse) import Database.Riak.Protocol.Link (Link) import Database.Riak.Protocol.ListBucketsResponse (ListBucketsResponse) import Database.Riak.Protocol.ListKeysRequest (ListKeysRequest) import Database.Riak.Protocol.ListKeysResponse (ListKeysResponse) import Database.Riak.Protocol.MapReduceRequest (MapReduceRequest) import Database.Riak.Protocol.MapReduceResponse (MapReduceResponse) import Database.Riak.Protocol.Pair (Pair) import Database.Riak.Protocol.PutRequest (PutRequest) import Database.Riak.Protocol.PutResponse (PutResponse) import Database.Riak.Protocol.SearchDocument (SearchDocument) import Database.Riak.Protocol.SearchQueryRequest (SearchQueryRequest) import Database.Riak.Protocol.SearchQueryResponse (SearchQueryResponse) import Database.Riak.Protocol.SetBucketRequest (SetBucketRequest) import Database.Riak.Protocol.SetClientIDRequest (SetClientIDRequest) numFound :: Lens.Simple Lens.Lens SearchQueryResponse (Maybe Word32) numFound = L.numFound maxScore :: Lens.Simple Lens.Lens SearchQueryResponse (Maybe Float) maxScore = L.maxScore documents :: Lens.Simple Lens.Lens SearchQueryResponse (Seq SearchDocument) documents = L.documents start :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe Word32) start = L.start sort :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe ByteString) sort = L.sort rows :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe Word32) rows = L.rows query :: Lens.Simple Lens.Lens SearchQueryRequest ByteString query = L.searchQuery presort :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe ByteString) presort = L.presort operation :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe ByteString) operation = L.operation fieldsLimit :: Lens.Simple Lens.Lens SearchQueryRequest (Seq ByteString) fieldsLimit = L.fieldsLimit searchFilter :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe ByteString) searchFilter = L.searchFilter df :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe ByteString) df = L.df returnHead :: Lens.Simple Lens.Lens PutRequest (Maybe Bool) returnHead = L.returnHead returnBody :: Lens.Simple Lens.Lens PutRequest (Maybe Bool) returnBody = L.returnBody ifNotModified :: Lens.Simple Lens.Lens PutRequest (Maybe Bool) ifNotModified = L.ifNotModified ifNoneMatch :: Lens.Simple Lens.Lens PutRequest (Maybe Bool) ifNoneMatch = L.ifNoneMatch response :: Lens.Simple Lens.Lens MapReduceResponse (Maybe ByteString) response = L.response phase :: Lens.Simple Lens.Lens MapReduceResponse (Maybe Word32) phase = L.phase request :: Lens.Simple Lens.Lens MapReduceRequest ByteString request = L.request buckets :: Lens.Simple Lens.Lens ListBucketsResponse (Seq ByteString) buckets = L.buckets tag :: Lens.Simple Lens.Lens Link (Maybe ByteString) tag = L.tag rangeMin :: Lens.Simple Lens.Lens IndexRequest (Maybe ByteString) rangeMin = L.rangeMin rangeMax :: Lens.Simple Lens.Lens IndexRequest (Maybe ByteString) rangeMax = L.rangeMax qtype :: Lens.Simple Lens.Lens IndexRequest IndexQueryType qtype = L.qtype serverVersion :: Lens.Simple Lens.Lens GetServerInfoResponse (Maybe ByteString) serverVersion = L.serverVersion node :: Lens.Simple Lens.Lens GetServerInfoResponse (Maybe ByteString) node = L.node unchanged :: Lens.Simple Lens.Lens GetResponse (Maybe Bool) unchanged = L.unchanged notFoundOk :: Lens.Simple Lens.Lens GetRequest (Maybe Bool) notFoundOk = L.notfoundOk ifModified :: Lens.Simple Lens.Lens GetRequest (Maybe ByteString) ifModified = L.ifModified onlyHead :: Lens.Simple Lens.Lens GetRequest (Maybe Bool) onlyHead = L.onlyHead deletedVClock :: Lens.Simple Lens.Lens GetRequest (Maybe Bool) deletedVClock = L.deletedVClock basicQuorum :: Lens.Simple Lens.Lens GetRequest (Maybe Bool) basicQuorum = L.basicQuorum errorMessage :: Lens.Simple Lens.Lens ErrorResponse ByteString errorMessage = L.errmsg errorCode :: Lens.Simple Lens.Lens ErrorResponse Word32 errorCode = L.errcode rw :: Lens.Simple Lens.Lens DeleteRequest (Maybe Word32) rw = L.rw vTag :: Lens.Simple Lens.Lens Content (Maybe ByteString) vTag = L.vtag userMeta :: Lens.Simple Lens.Lens Content (Seq Pair) userMeta = L.usermeta links :: Lens.Simple Lens.Lens Content (Seq Link) links = L.links lastModUsecs :: Lens.Simple Lens.Lens Content (Maybe Word32) lastModUsecs = L.lastModUsecs lastMod :: Lens.Simple Lens.Lens Content (Maybe Word32) lastMod = L.lastMod indexes :: Lens.Simple Lens.Lens Content (Seq Pair) indexes = L.indexes deleted :: Lens.Simple Lens.Lens Content (Maybe Bool) deleted = L.deleted contentEncoding :: Lens.Simple Lens.Lens Content (Maybe ByteString) contentEncoding = L.contentEncoding charset :: Lens.Simple Lens.Lens Content (Maybe ByteString) charset = L.charset nVal :: Lens.Simple Lens.Lens BucketProps (Maybe Word32) nVal = L.nVal allowMult :: Lens.Simple Lens.Lens BucketProps (Maybe Bool) allowMult = L.allowMult r :: L.HasR a => Lens.Simple Lens.Lens a (Maybe M.Quorum) r = L.r pr :: L.HasPR a => Lens.Simple Lens.Lens a (Maybe M.Quorum) pr = L.pr keys :: L.HasKeys a => Lens.Simple Lens.Lens a (Seq ByteString) keys = L.keys contentType :: L.HasContentType a => Lens.Simple Lens.Lens a (L.ContentTypeValue a) contentType = L.contentType done :: L.HasDone a => Lens.Simple Lens.Lens a (Maybe Bool) done = L.done value :: L.HasValue a => Lens.Simple Lens.Lens a (L.Value a) value = L.value w :: L.HasW a => Lens.Simple Lens.Lens a (Maybe M.Quorum) w = L.w pw :: L.HasPW a => Lens.Simple Lens.Lens a (Maybe M.Quorum) pw = L.pw dw :: L.HasDW a => Lens.Simple Lens.Lens a (Maybe M.Quorum) dw = L.dw vClock :: L.HasVClock a => Lens.Simple Lens.Lens a (Maybe ByteString) vClock = L.vclock key :: L.HasKey a => Lens.Simple Lens.Lens a (L.KeyValue a) key = L.key content :: L.HasContent a => Lens.Simple Lens.Lens a (L.ContentValue a) content = L.content indexValue :: L.HasIndex a => Lens.Simple Lens.Lens a ByteString indexValue = L.index bucket :: L.HasBucket a => Lens.Simple Lens.Lens a (L.BucketValue a) bucket = L.bucket clientId :: L.HasClientId a => Lens.Simple Lens.Lens a ByteString clientId = L.clientId props :: L.HasProps a => Lens.Simple Lens.Lens a BucketProps props = L.props
iand675/hiker
Database/Riak.hs
bsd-3-clause
9,059
298
9
1,267
3,118
1,725
1,393
290
1
{-# LANGUAGE TypeFamilies #-} -- | Number representations that are not part of the grammar. -- -- To convert these types to 'Penny.Decimal.Decimal' and the like, -- functions are available in "Penny.Copper.Decopperize". module Penny.Rep where import qualified Control.Lens as Lens import qualified Control.Lens.Extras as Lens (is) import Data.Coerce (coerce) import Data.Monoid ((<>)) import Data.Sequence (Seq, (<|)) import qualified Data.Sequence as Seq import qualified Data.Sequence.NonEmpty as NE import Penny.Copper.Types import Penny.Copper.Terminalizers import Penny.Polar -- | Qty representations with a comma radix that may be either nil -- or brim. Stored along with the side if the number is non-nil. type RepRadCom = Moderated (NilRadCom Char ()) (BrimRadCom Char ()) -- | Qty representations with a period radix that may be either nil -- or brim. Stored along with the side if the number is non-nil. type RepRadPer = Moderated (NilRadPer Char ()) (BrimRadPer Char ()) -- | Qty representations that may be neutral or non-neutral and that -- have a period or comma radix. Stored along with the side if the -- number is non-nil. type RepAnyRadix = Either RepRadCom RepRadPer oppositeRepAnyRadix :: RepAnyRadix -> RepAnyRadix oppositeRepAnyRadix = Lens.over Lens._Left oppositeModerated . Lens.over Lens._Right oppositeModerated -- | True if the 'RepAnyRadix' is zero. repAnyRadixIsZero :: RepAnyRadix -> Bool repAnyRadixIsZero rar = Lens.is (Lens._Left . _Moderate) rar || Lens.is (Lens._Right . _Moderate) rar -- | A non-neutral representation that does not include a side. type BrimAnyRadix = Either (BrimRadCom Char ()) (BrimRadPer Char ()) -- | A neutral representation of any radix. type NilAnyRadix = Either (NilRadCom Char ()) (NilRadPer Char ()) -- | Number representation that may be neutral or non-neutral, with -- either a period or comma radix. Does not have a polarity. type NilOrBrimAnyRadix = Either (NilOrBrimRadCom Char ()) (NilOrBrimRadPer Char ()) c'RepAnyRadix'BrimAnyRadix :: Pole -- ^ Use this side -> BrimAnyRadix -> RepAnyRadix c'RepAnyRadix'BrimAnyRadix pole b = case b of Left brc -> Left . Extreme $ Polarized brc pole Right brp -> Right . Extreme $ Polarized brp pole t'NilOrBrimAnyRadix :: NilOrBrimAnyRadix -> Seq Char t'NilOrBrimAnyRadix = NE.nonEmptySeqToSeq . fmap fst . either t'NilOrBrimRadCom t'NilOrBrimRadPer splitNilOrBrimAnyRadix :: NilOrBrimAnyRadix -> Either NilAnyRadix BrimAnyRadix splitNilOrBrimAnyRadix x = case x of Left nobCom -> case nobCom of NilOrBrimRadCom'NilRadCom nilCom -> Left (Left nilCom) NilOrBrimRadCom'BrimRadCom brimCom -> Right (Left brimCom) Right nobPer -> case nobPer of NilOrBrimRadPer'NilRadPer nilPer -> Left (Right nilPer) NilOrBrimRadPer'BrimRadPer brimPer -> Right (Right brimPer) groupers'DigitGroupRadCom'Star :: DigitGroupRadCom'Star t a -> Seq (GrpRadCom t a) groupers'DigitGroupRadCom'Star = fmap _r'DigitGroupRadCom'0'GrpRadCom . coerce groupers'DigitGroupRadPer'Star :: DigitGroupRadPer'Star t a -> Seq (GrpRadPer t a) groupers'DigitGroupRadPer'Star = fmap _r'DigitGroupRadPer'0'GrpRadPer . coerce groupers'BG7RadCom :: BG7RadCom t a -> Seq (GrpRadCom t a) groupers'BG7RadCom (BG7ZeroesRadCom _ _ b8) = groupers'BG8RadCom b8 groupers'BG7RadCom (BG7NovemRadCom _ _ digs) = groupers'DigitGroupRadCom'Star digs groupers'BG8RadCom :: BG8RadCom t a -> Seq (GrpRadCom t a) groupers'BG8RadCom (BG8NovemRadCom _ _ digs) = groupers'DigitGroupRadCom'Star digs groupers'BG8RadCom (BG8GroupRadCom grpr b7) = grpr <| groupers'BG7RadCom b7 groupers'BG7RadPer :: BG7RadPer t a -> Seq (GrpRadPer t a) groupers'BG7RadPer (BG7ZeroesRadPer _ _ b8) = groupers'BG8RadPer b8 groupers'BG7RadPer (BG7NovemRadPer _ _ digs) = groupers'DigitGroupRadPer'Star digs groupers'BG8RadPer :: BG8RadPer t a -> Seq (GrpRadPer t a) groupers'BG8RadPer (BG8NovemRadPer _ _ digs) = groupers'DigitGroupRadPer'Star digs groupers'BG8RadPer (BG8GroupRadPer grpr b7) = grpr <| groupers'BG7RadPer b7 groupers'BG6RadCom :: BG6RadCom t a -> Seq (GrpRadCom t a) groupers'BG6RadCom (BG6NovemRadCom _ _ g1 _ _ gs) = g1 <| groupers'DigitGroupRadCom'Star gs groupers'BG6RadCom (BG6GroupRadCom g1 b7) = g1 <| groupers'BG7RadCom b7 groupers'BG6RadPer :: BG6RadPer t a -> Seq (GrpRadPer t a) groupers'BG6RadPer (BG6NovemRadPer _ _ g1 _ _ gs) = g1 <| groupers'DigitGroupRadPer'Star gs groupers'BG6RadPer (BG6GroupRadPer g1 b7) = g1 <| groupers'BG7RadPer b7 groupers'BG5RadCom :: BG5RadCom t a -> Seq (GrpRadCom t a) groupers'BG5RadCom (BG5NovemRadCom _ _ g1 _ _ gs) = g1 <| groupers'DigitGroupRadCom'Star gs groupers'BG5RadCom (BG5ZeroRadCom _ _ b6) = groupers'BG6RadCom b6 groupers'BG5RadPer :: BG5RadPer t a -> Seq (GrpRadPer t a) groupers'BG5RadPer (BG5NovemRadPer _ _ g1 _ _ gs) = g1 <| groupers'DigitGroupRadPer'Star gs groupers'BG5RadPer (BG5ZeroRadPer _ _ b6) = groupers'BG6RadPer b6 groupers'BG4RadCom :: BG4RadCom t a -> Seq (GrpRadCom t a) groupers'BG4RadCom (BG4DigitRadCom _ _ digs) = groupers'DigitGroupRadCom'Star digs groupers'BG4RadCom BG4NilRadCom = Seq.empty groupers'BG4RadPer :: BG4RadPer t a -> Seq (GrpRadPer t a) groupers'BG4RadPer (BG4DigitRadPer _ _ digs) = groupers'DigitGroupRadPer'Star digs groupers'BG4RadPer BG4NilRadPer = Seq.empty groupers'BG3RadCom :: BG3RadCom t a -> Seq (GrpRadCom t a) groupers'BG3RadCom (BG3RadixRadCom _ b4) = groupers'BG4RadCom b4 groupers'BG3RadCom BG3NilRadCom = Seq.empty groupers'BG3RadPer :: BG3RadPer t a -> Seq (GrpRadPer t a) groupers'BG3RadPer (BG3RadixRadPer _ b4) = groupers'BG4RadPer b4 groupers'BG3RadPer BG3NilRadPer = Seq.empty groupers'BG1RadCom :: BG1RadCom t a -> Seq (GrpRadCom t a) groupers'BG1RadCom (BG1GroupOnLeftRadCom g1 _ _ digs b3) = g1 <| groupers'DigitGroupRadCom'Star digs <> groupers'BG3RadCom b3 groupers'BG1RadCom (BG1GroupOnRightRadCom _ _ _ g1 _ _ digs) = g1 <| groupers'DigitGroupRadCom'Star digs groupers'BG1RadPer :: BG1RadPer t a -> Seq (GrpRadPer t a) groupers'BG1RadPer (BG1GroupOnLeftRadPer g1 _ _ digs b3) = g1 <| groupers'DigitGroupRadPer'Star digs <> groupers'BG3RadPer b3 groupers'BG1RadPer (BG1GroupOnRightRadPer _ _ _ g1 _ _ digs) = g1 <| groupers'DigitGroupRadPer'Star digs groupers'BrimGroupedRadCom :: BrimGroupedRadCom t a -> Seq (GrpRadCom t a) groupers'BrimGroupedRadCom (BGGreaterThanOneRadCom _ _ bg1) = groupers'BG1RadCom bg1 groupers'BrimGroupedRadCom (BGLessThanOneRadCom _ _ b5) = groupers'BG5RadCom b5 groupers'BrimGroupedRadPer :: BrimGroupedRadPer t a -> Seq (GrpRadPer t a) groupers'BrimGroupedRadPer (BGGreaterThanOneRadPer _ _ bg1) = groupers'BG1RadPer bg1 groupers'BrimGroupedRadPer (BGLessThanOneRadPer _ _ b5) = groupers'BG5RadPer b5 groupers'ZeroGroupRadCom :: ZeroGroupRadCom t a -> Seq (GrpRadCom t a) groupers'ZeroGroupRadCom (ZeroGroupRadCom g _ _) = Seq.singleton g groupers'ZeroGroupRadPer :: ZeroGroupRadPer t a -> Seq (GrpRadPer t a) groupers'ZeroGroupRadPer (ZeroGroupRadPer g _ _) = Seq.singleton g groupers'NilGroupedRadCom :: NilGroupedRadCom t a -> Seq (GrpRadCom t a) groupers'NilGroupedRadCom (NilGroupedRadCom _ _ _ _ (ZeroGroupRadCom'Plus (NE.NonEmptySeq g1 gs))) = addGroup g1 (foldr addGroup Seq.empty gs) where addGroup g acc = groupers'ZeroGroupRadCom g <> acc groupers'NilGroupedRadPer :: NilGroupedRadPer t a -> Seq (GrpRadPer t a) groupers'NilGroupedRadPer (NilGroupedRadPer _ _ _ _ (ZeroGroupRadPer'Plus (NE.NonEmptySeq g1 gs))) = addGroup g1 (foldr addGroup Seq.empty gs) where addGroup g acc = groupers'ZeroGroupRadPer g <> acc groupers'NilRadCom :: NilRadCom t a -> Seq (GrpRadCom t a) groupers'NilRadCom (NilRadCom'NilUngroupedRadCom _) = Seq.empty groupers'NilRadCom (NilRadCom'NilGroupedRadCom x) = groupers'NilGroupedRadCom x groupers'NilRadPer :: NilRadPer t a -> Seq (GrpRadPer t a) groupers'NilRadPer (NilRadPer'NilUngroupedRadPer _) = Seq.empty groupers'NilRadPer (NilRadPer'NilGroupedRadPer x) = groupers'NilGroupedRadPer x groupers'BrimRadCom :: BrimRadCom t a -> Seq (GrpRadCom t a) groupers'BrimRadCom (BrimRadCom'BrimUngroupedRadCom _) = Seq.empty groupers'BrimRadCom (BrimRadCom'BrimGroupedRadCom b) = groupers'BrimGroupedRadCom b groupers'BrimRadPer :: BrimRadPer t a -> Seq (GrpRadPer t a) groupers'BrimRadPer (BrimRadPer'BrimUngroupedRadPer _) = Seq.empty groupers'BrimRadPer (BrimRadPer'BrimGroupedRadPer b) = groupers'BrimGroupedRadPer b groupers'RepRadCom :: RepRadCom -> Seq (GrpRadCom Char ()) groupers'RepRadCom x = case x of Moderate n -> groupers'NilRadCom n Extreme (Polarized o _) -> groupers'BrimRadCom o groupers'RepRadPer :: RepRadPer -> Seq (GrpRadPer Char ()) groupers'RepRadPer x = case x of Moderate n -> groupers'NilRadPer n Extreme (Polarized o _) -> groupers'BrimRadPer o groupers'RepAnyRadix :: RepAnyRadix -> Either (Seq (GrpRadCom Char ())) (Seq (GrpRadPer Char ())) groupers'RepAnyRadix = either (Left . groupers'RepRadCom) (Right . groupers'RepRadPer) groupers'BrimAnyRadix :: BrimAnyRadix -> Either (Seq (GrpRadCom Char ())) (Seq (GrpRadPer Char ())) groupers'BrimAnyRadix = either (Left . groupers'BrimRadCom) (Right . groupers'BrimRadPer) -- | Removes the 'Side' from a 'RepAnyRadix'. c'NilOrBrimAnyRadix'RepAnyRadix :: RepAnyRadix -> NilOrBrimAnyRadix c'NilOrBrimAnyRadix'RepAnyRadix ei = case ei of Left rc -> Left $ case rc of Moderate n -> NilOrBrimRadCom'NilRadCom n Extreme (Polarized c _) -> NilOrBrimRadCom'BrimRadCom c Right rp -> Right $ case rp of Moderate n -> NilOrBrimRadPer'NilRadPer n Extreme (Polarized c _) -> NilOrBrimRadPer'BrimRadPer c -- | Removes the 'Side' from a 'RepAnyRadix' and returns either Nil -- or a Brim with the side. splitRepAnyRadix :: RepAnyRadix -> Either NilAnyRadix (BrimAnyRadix, Pole) splitRepAnyRadix ei = case ei of Left rc -> case rc of Moderate n -> Left . Left $ n Extreme (Polarized brim pole) -> Right (Left brim, pole) Right rp -> case rp of Moderate n -> Left . Right $ n Extreme (Polarized brim pole) -> Right (Right brim, pole) c'NilOrBrimAnyRadix'BrimAnyRadix :: BrimAnyRadix -> NilOrBrimAnyRadix c'NilOrBrimAnyRadix'BrimAnyRadix brim = case brim of Left brc -> Left (NilOrBrimRadCom'BrimRadCom brc) Right brp -> Right (NilOrBrimRadPer'BrimRadPer brp) c'NilOrBrimAnyRadix'NilAnyRadix :: NilAnyRadix -> NilOrBrimAnyRadix c'NilOrBrimAnyRadix'NilAnyRadix nil = case nil of Left nrc -> Left (NilOrBrimRadCom'NilRadCom nrc) Right nrp -> Right (NilOrBrimRadPer'NilRadPer nrp) -- # Poles pole'RepRadCom :: RepRadCom -> Maybe Pole pole'RepRadCom = pole'Moderated pole'RepRadPer :: RepRadPer -> Maybe Pole pole'RepRadPer = pole'Moderated pole'RepAnyRadix :: RepAnyRadix -> Maybe Pole pole'RepAnyRadix = either pole'RepRadCom pole'RepRadPer
massysett/penny
penny/lib/Penny/Rep.hs
bsd-3-clause
10,925
0
14
1,787
3,043
1,504
1,539
277
4
test_disassembler :: IO () test_disassembler = let table = [ (Mov (Register 12) (Register 14), "\xce\x2c"), (Cli, "\xf8\x94"), (Sei, "\x78\x94"), (Clc, "\x88\x94"), (Clh, "\xd8\x94"), (Cln, "\xa8\x94"), (Cls, "\xc8\x94"), (Clv, "\xb8\x94"), (Clz, "\x98\x94"), (Clt, "\xe8\x94"), (Sec, "\x08\x94"), (Seh, "\x58\x94"), (Sen, "\x28\x94"), (Ses, "\x48\x94"), (Sev, "\x38\x94"), (Sez, "\x18\x94"), (Set, "\x68\x94"), (Jmp 50, "\x0c\x94\x19\x00"), (Ijmp, "\x09\x94"), (Rjmp 50, "\x19\xc0"), (Add 10 15, "\xaf\x0c"), (Adc 10 15, "\xaf\x1c"), (Sub 10 15, "\x05\x18"), (Sbc 10 15, "\x05\x08"), (Andi 10 5, "\xa5\x70"), (Ldi 10 5, "\xa5\xe0"), (Cpi 10 5, "\xa5\x30"), (Ori 10 5, "\xa5\x60"), (Subi 10 5, "\xa0\x50"), (Sbci 10 5, "\xa5\x40"), (In 15 5, "\xf5\xb0"), (Out 5 15, "\xf5\xb8"), (Sbi 15 3, "\x03\x9a"), (Cbi 15 3, "\x03\x98"), (Sbic 15 3, "\x03\x99"), (Sbis 15 3, "\x03\x9b"), (Sbrc 15 3, "\xf3\xfc"), (Sbrs 15 3, "\xf3\xfe"), (Cpse 15 20, "\xf4\x12"), (Bld 15 3, "\x53\xf8"), (Bst 15 3, "\x53\xfa"), (Adiw (Reg16 RX), "\xd2\x96"), (Sbiw (mkReg16 24), "\x06\x97"), (Movw (mkReg16 16), "\x80\x01"), (Push 15, "\xff\x92"), (Pop 15, "\xff\x90"), (Brcc 50, "\xc8\xf4"), (Brcs 50, "\xc8\xf0"), (Brtc 50, "\xce\xf4"), (Brts 50, "\xce\xf0"), (Breq 50, "\xc9\xf0"), (Brne 50, "\xc9\xf4"), (Brlt 50, "\xcc\xf0"), (Brge 50, "\xcc\xf4"), (Brpl 50, "\xca\xf4"), (Brmi 50, "\xca\xf0"), (Cp 15 20, "\xf4\x16"), (Cpc 15 20, "\xf4\x06"), (Inc 15, "\xf3\x94"), (Dec 15, "\xfa\x94"), (Ldxp 15, "\xfd\x90"), (Ldxm 15, "\xfc\x90"), (Ldyp 15, "\xf9\x90"), (Ldym 15, "\xf8\x80"), (Ldzp 15, "\xf1\x90"), (Ldzm 15, "\xf0\x80"), (Lds 15 20, "\xf0\x90\x14\x00"), (Lddx 15 3, "\xfb\x80"), (Lddy 15 3, "\xfb\x80"), (Stxp 15, "\xfd\x92"), (Stxm 15, "\xfc\x92"), (Styp 15, "\xf9\x92"), (Sts 20 15, "\xf0\x92\x14\x00"), (Stdz 41 15, "\x01\xa7"), (Lpmzp 15, "\x05\x90"), (Call 1234, "\x0e\x94\x69\x02"), (Rcall 50, "\x0e\x94\x19\x00"), (Icall, "\x09\x95"), (Ret, "\x08\x95"), (Com 15, "\xf0\x94"), (Neg 15, "\xf1\x94"), (And 15 16, "\xf0\x22"), (Eor 15 16, "\xf0\x26"), (Or 15 16, "\xf0\x2a"), (Ror 15, "\xf7\x94"), (Lsr 15, "\xf6\x94"), (Lsl 15, "\x0f\x0c"), (Swap 15, "\xf2\x94"), (Mul 8 16, "\x80\x9e"), (Break, "\x98\x95"), (Reti, "\x18\x95"), (Nop, "\x00\x00") ) main :: IO () main = putStrLn "Test suite not yet implemented"
MichaelBurge/stockfighter-jailbreak
test/Spec.hs
bsd-3-clause
3,047
1
8
1,063
1,157
686
471
-1
-1
{-# LANGUAGE MagicHash #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DisambiguateRecordFields, NamedFieldPuns #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE CPP #-} -- | This module contains types and functions that are mostly -- intended for the test suite, and should be considered internal -- for all other purposes module Text.Xml.Tiny.Internal ( -- * XML Nodes Node(..), Attribute(..) -- * ParseDetails , ParseDetails(..), AttributeParseDetails(..) -- * Slices , Slice(..) , fromOpen, fromOpenClose, fromIndexPtr , empty , start, end , take, drop, null , vector, render, toList -- * Errors , SrcLoc(..), Error(..), ErrorType(..) ) where import Control.Exception import Data.ByteString.Char8 (ByteString) import Data.ByteString.Internal (ByteString(..)) import Data.List (genericTake) import Data.Vector.Storable (Vector, (!)) import qualified Data.Vector.Storable as V import Data.Word import GHC.Stack hiding (SrcLoc) import Foreign.ForeignPtr (ForeignPtr) import Foreign import Prelude hiding (length, null, take, drop) import Text.Printf import Config -- A subset of a vector defined by an offset and length data Slice = Slice { offset, length :: !Int32 } deriving (Eq,Ord,Show) sInt :: Int sInt = sizeOf(0::Int32) instance Storable Slice where sizeOf _ = sInt * 2 alignment _ = alignment (0 :: Int64) peek p = Slice <$> peekByteOff p 0 <*> peekByteOff p sInt poke p Slice{..} = pokeByteOff p 0 offset >> pokeByteOff p sInt length {-# INLINE empty #-} empty :: Slice empty = Slice 0 0 fromOpen:: Config => Integral a => a -> Slice fromOpen o = Slice (fromIntegral o) 0 {-# INLINE fromOpenClose #-} fromOpenClose :: Config => (Integral a1, Integral a) => a -> a1 -> Slice fromOpenClose (fromIntegral->open) (fromIntegral->close) = Slice open (close-open) {-# INLINE null #-} null :: Config => Slice -> Bool null (Slice _ l) = l == 0 {-# INLINE take #-} take :: Config => Integral a => a -> Slice -> Slice take !(fromIntegral -> i) (Slice o l) = assert (l>=i) $ Slice o i {-# INLINE drop #-} drop :: Config => Integral t => t -> Slice -> Slice drop !(fromIntegral -> i) (Slice o l) = assert (l>=i || error(printf "drop %d (Slice %d %d)" i o l)) $ Slice (o+i) (l-i) -- | Inclusive start :: Config => Slice -> Int32 start = offset -- | Non inclusive end :: Config => Slice -> Int32 end (Slice o l) = o + l -- | Returns a list of indexes toList :: Config => Slice -> [Int] toList (Slice o l) = genericTake l [ fromIntegral o ..] {-# INLINE fromIndexPtr #-} -- | Apply a slice to a foreign ptr of word characters and wrap as a bytestring fromIndexPtr :: Config => Slice -> ForeignPtr Word8 -> ByteString fromIndexPtr (Slice o l) fptr = PS fptr (fromIntegral o) (fromIntegral l) -- | Apply a slice to a bytestring render :: Config => Slice -> ByteString -> ByteString render(Slice o l) _ | trace (printf "Render slice %d %d" o l) False = undefined render(Slice o l) _ | assert (o >= 0 && l >= 0) False = undefined render(Slice o l) (PS fptr _ _) = PS fptr (fromIntegral o) (fromIntegral l) -- | Apply a slice to a vector vector :: Config => Storable a => Slice -> Vector a -> [a] vector s v = [ v ! i | i <- toList s , assert (i < V.length v) True ] -- * XML Nodes -- | A parsed XML node data Node = Node{ attributesV :: !(Vector AttributeParseDetails) -- ^ All the attributes in the document , nodesV :: !(Vector ParseDetails) -- ^ All the nodes in the document , source :: !ByteString -- ^ The document bytes , slices :: !ParseDetails -- ^ Details for this node } -- | A parsed XML attribute data Attribute = Attribute { attributeName, attributeValue :: !ByteString } deriving (Eq, Show) data ParseDetails = ParseDetails { name :: {-# UNPACK #-} !Slice -- ^ bytestring slice , inner :: {-# UNPACK #-} !Slice -- ^ bytestring slice , outer :: {-# UNPACK #-} !Slice -- ^ bytestring slice , attributes :: {-# UNPACK #-} !Slice -- ^ ParseDetailsAttribute slice , nodeContents :: {-# UNPACK #-} !Slice -- ^ ParseDetails slice of children } -- | An incompletely defined set of parse details | ProtoParseDetails { name, attributes :: !Slice, innerStart, outerStart :: !Int32 } deriving (Show) -- | Assumes that a name can never be the empty slice instance Storable ParseDetails where sizeOf _ = sizeOf empty * 5 alignment _ = alignment(0::Int) poke !q (ParseDetails a b c d e) = let p = castPtr q in pokeElemOff p 0 a >> pokeElemOff p 1 b >> pokeElemOff p 2 c >> pokeElemOff p 3 d >> pokeElemOff p 4 e poke !q (ProtoParseDetails (Slice no nl) (Slice ao al) i o) = do let !p = castPtr q pokeElemOff p 0 no pokeElemOff p 1 (0::Int32) pokeElemOff p 2 nl pokeElemOff p 3 ao pokeElemOff p 4 al pokeElemOff p 5 i pokeElemOff p 6 o peek q = do let !p = castPtr q !header <- peekElemOff p 1 if header == (0::Int32) then protoNode <$> peekElemOff p 0 <*> peekElemOff p 2 <*> peekElemOff p 3 <*> peekElemOff p 4 <*> peekElemOff p 5 <*> peekElemOff p 6 else let !p = castPtr q in ParseDetails <$> peekElemOff p 0 <*> peekElemOff p 1 <*> peekElemOff p 2 <*> peekElemOff p 3 <*> peekElemOff p 4 where protoNode no nl ao al = ProtoParseDetails (Slice no nl) (Slice ao al) data AttributeParseDetails = AttributeParseDetails { nameA :: {-# UNPACK #-} !Slice, value :: {-# UNPACK #-} !Slice } deriving (Eq, Show) instance Storable AttributeParseDetails where sizeOf _ = sizeOf empty * 2 alignment _ = alignment (0 :: Int) peek !q = do let !p = castPtr q :: Ptr Slice !a <- peekElemOff p 0 !b <- peekElemOff p 1 return (AttributeParseDetails a b) poke !q (AttributeParseDetails a b)= do let !p = castPtr q :: Ptr Slice pokeElemOff p 0 a pokeElemOff p 1 b -- * Error types newtype SrcLoc = SrcLoc Int deriving Show data Error = Error ErrorType CallStack data ErrorType = UnterminatedComment SrcLoc | UnterminatedTag String SrcLoc | ClosingTagMismatch String SrcLoc | JunkAtTheEnd Slice SrcLoc | UnexpectedEndOfStream | BadAttributeForm SrcLoc | BadTagForm SrcLoc | UnfinishedComment SrcLoc | Garbage SrcLoc | InvalidNullName SrcLoc deriving Show #if __GLASGOW_HASKELL__ < 800 prettyCallStack = show #endif instance Exception Error instance Show Error where show (Error etype cs) = show etype ++ prettyCallStack cs
pepeiborra/bytestring-xml
src/Text/Xml/Tiny/Internal.hs
bsd-3-clause
6,677
0
16
1,510
2,091
1,096
995
-1
-1
module FP.Pretty.HTML where import FP.Prelude import FP.Pretty.Color import FP.Pretty.Pretty htmlFGCode :: Color -> 𝕊 -> 𝕊 htmlFGCode c s = "<span style='color:" ⧺ (htmlColorFrom256 #! c) ⧺ "'>" ⧺ s ⧺ "</span>" htmlBGCode :: Color -> 𝕊 -> 𝕊 htmlBGCode c s = "<span style='background-color:" ⧺ (htmlColorFrom256 #! c) ⧺ "'>" ⧺ s ⧺ "</span>" htmlULCode :: 𝕊 -> 𝕊 htmlULCode s = "<u>" ⧺ s ⧺ "</u>" htmlBDCode :: 𝕊 -> 𝕊 htmlBDCode s = "<b>" ⧺ s ⧺ "</b>" formatHTML :: Format -> 𝕊 -> 𝕊 formatHTML (FormatFG c) = htmlFGCode c formatHTML (FormatBG c) = htmlBGCode c formatHTML FormatUL = htmlULCode formatHTML FormatBD = htmlBDCode htmlEscapeChar ∷ ℂ → 𝕊 htmlEscapeChar c | c == '&' = "&amp;" | c == '<' = "&lt;" | c == '>' = "&gt;" | otherwise = 𝕤 $ single c htmlEscape ∷ 𝕊 → 𝕊 htmlEscape = concat ∘ map htmlEscapeChar ∘ list renderChunkHTML ∷ Chunk → 𝕊 renderChunkHTML Newline = "\n" renderChunkHTML (Text s) = htmlEscape s renderHTML ∷ PrettyOut → 𝕊 renderHTML (ChunkOut c) = renderChunkHTML c renderHTML (FormatOut f o) = compose (map formatHTML f) $ renderHTML o renderHTML NullOut = "" renderHTML (AppendOut o₁ o₂) = renderHTML o₁ ⧺ renderHTML o₂ prettyHTML ∷ (Pretty a) ⇒ a → 𝕊 prettyHTML = renderHTML ∘ renderDoc ∘ ppFinal ∘ pretty prettyHTMLStandalone ∷ (Pretty a) ⇒ a → 𝕊 prettyHTMLStandalone x = concat $ intersperse "\n" [ "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>" , "<pre>" , prettyHTML x , "</pre>" ] htmlColorFrom256 :: Color ⇰ 𝕊 htmlColorFrom256 = dict $ map (mapFst color) [ (000, "#000000") , (001, "#800000") , (002, "#008000") , (003, "#808000") , (004, "#000080") , (005, "#800080") , (006, "#008080") , (007, "#c0c0c0") , (008, "#808080") , (009, "#ff0000") , (010, "#00ff00") , (011, "#ffff00") , (012, "#0000ff") , (013, "#ff00ff") , (014, "#00ffff") , (015, "#ffffff") , (016, "#000000") , (017, "#00005f") , (018, "#000087") , (019, "#0000af") , (020, "#0000d7") , (021, "#0000ff") , (022, "#005f00") , (023, "#005f5f") , (024, "#005f87") , (025, "#005faf") , (026, "#005fd7") , (027, "#005fff") , (028, "#008700") , (029, "#00875f") , (030, "#008787") , (031, "#0087af") , (032, "#0087d7") , (033, "#0087ff") , (034, "#00af00") , (035, "#00af5f") , (036, "#00af87") , (037, "#00afaf") , (038, "#00afd7") , (039, "#00afff") , (040, "#00d700") , (041, "#00d75f") , (042, "#00d787") , (043, "#00d7af") , (044, "#00d7d7") , (045, "#00d7ff") , (046, "#00ff00") , (047, "#00ff5f") , (048, "#00ff87") , (049, "#00ffaf") , (050, "#00ffd7") , (051, "#00ffff") , (052, "#5f0000") , (053, "#5f005f") , (054, "#5f0087") , (055, "#5f00af") , (056, "#5f00d7") , (057, "#5f00ff") , (058, "#5f5f00") , (059, "#5f5f5f") , (060, "#5f5f87") , (061, "#5f5faf") , (062, "#5f5fd7") , (063, "#5f5fff") , (064, "#5f8700") , (065, "#5f875f") , (066, "#5f8787") , (067, "#5f87af") , (068, "#5f87d7") , (069, "#5f87ff") , (070, "#5faf00") , (071, "#5faf5f") , (072, "#5faf87") , (073, "#5fafaf") , (074, "#5fafd7") , (075, "#5fafff") , (076, "#5fd700") , (077, "#5fd75f") , (078, "#5fd787") , (079, "#5fd7af") , (080, "#5fd7d7") , (081, "#5fd7ff") , (082, "#5fff00") , (083, "#5fff5f") , (084, "#5fff87") , (085, "#5fffaf") , (086, "#5fffd7") , (087, "#5fffff") , (088, "#870000") , (089, "#87005f") , (090, "#870087") , (091, "#8700af") , (092, "#8700d7") , (093, "#8700ff") , (094, "#875f00") , (095, "#875f5f") , (096, "#875f87") , (097, "#875faf") , (098, "#875fd7") , (099, "#875fff") , (100, "#878700") , (101, "#87875f") , (102, "#878787") , (103, "#8787af") , (104, "#8787d7") , (105, "#8787ff") , (106, "#87af00") , (107, "#87af5f") , (108, "#87af87") , (109, "#87afaf") , (110, "#87afd7") , (111, "#87afff") , (112, "#87d700") , (113, "#87d75f") , (114, "#87d787") , (115, "#87d7af") , (116, "#87d7d7") , (117, "#87d7ff") , (118, "#87ff00") , (119, "#87ff5f") , (120, "#87ff87") , (121, "#87ffaf") , (122, "#87ffd7") , (123, "#87ffff") , (124, "#af0000") , (125, "#af005f") , (126, "#af0087") , (127, "#af00af") , (128, "#af00d7") , (129, "#af00ff") , (130, "#af5f00") , (131, "#af5f5f") , (132, "#af5f87") , (133, "#af5faf") , (134, "#af5fd7") , (135, "#af5fff") , (136, "#af8700") , (137, "#af875f") , (138, "#af8787") , (139, "#af87af") , (140, "#af87d7") , (141, "#af87ff") , (142, "#afaf00") , (143, "#afaf5f") , (144, "#afaf87") , (145, "#afafaf") , (146, "#afafd7") , (147, "#afafff") , (148, "#afd700") , (149, "#afd75f") , (150, "#afd787") , (151, "#afd7af") , (152, "#afd7d7") , (153, "#afd7ff") , (154, "#afff00") , (155, "#afff5f") , (156, "#afff87") , (157, "#afffaf") , (158, "#afffd7") , (159, "#afffff") , (160, "#d70000") , (161, "#d7005f") , (162, "#d70087") , (163, "#d700af") , (164, "#d700d7") , (165, "#d700ff") , (166, "#d75f00") , (167, "#d75f5f") , (168, "#d75f87") , (169, "#d75faf") , (170, "#d75fd7") , (171, "#d75fff") , (172, "#d78700") , (173, "#d7875f") , (174, "#d78787") , (175, "#d787af") , (176, "#d787d7") , (177, "#d787ff") , (178, "#d7af00") , (179, "#d7af5f") , (180, "#d7af87") , (181, "#d7afaf") , (182, "#d7afd7") , (183, "#d7afff") , (184, "#d7d700") , (185, "#d7d75f") , (186, "#d7d787") , (187, "#d7d7af") , (188, "#d7d7d7") , (189, "#d7d7ff") , (190, "#d7ff00") , (191, "#d7ff5f") , (192, "#d7ff87") , (193, "#d7ffaf") , (194, "#d7ffd7") , (195, "#d7ffff") , (196, "#ff0000") , (197, "#ff005f") , (198, "#ff0087") , (199, "#ff00af") , (200, "#ff00d7") , (201, "#ff00ff") , (202, "#ff5f00") , (203, "#ff5f5f") , (204, "#ff5f87") , (205, "#ff5faf") , (206, "#ff5fd7") , (207, "#ff5fff") , (208, "#ff8700") , (209, "#ff875f") , (210, "#ff8787") , (211, "#ff87af") , (212, "#ff87d7") , (213, "#ff87ff") , (214, "#ffaf00") , (215, "#ffaf5f") , (216, "#ffaf87") , (217, "#ffafaf") , (218, "#ffafd7") , (219, "#ffafff") , (220, "#ffd700") , (221, "#ffd75f") , (222, "#ffd787") , (223, "#ffd7af") , (224, "#ffd7d7") , (225, "#ffd7ff") , (226, "#ffff00") , (227, "#ffff5f") , (228, "#ffff87") , (229, "#ffffaf") , (230, "#ffffd7") , (231, "#ffffff") , (232, "#080808") , (233, "#121212") , (234, "#1c1c1c") , (235, "#262626") , (236, "#303030") , (237, "#3a3a3a") , (238, "#444444") , (239, "#4e4e4e") , (240, "#585858") , (241, "#626262") , (242, "#6c6c6c") , (243, "#767676") , (244, "#808080") , (245, "#8a8a8a") , (246, "#949494") , (247, "#9e9e9e") , (248, "#a8a8a8") , (249, "#b2b2b2") , (250, "#bcbcbc") , (251, "#c6c6c6") , (252, "#d0d0d0") , (253, "#dadada") , (254, "#e4e4e4") , (255, "#eeeeee") ]
davdar/darailude
src/FP/Pretty/HTML.hs
bsd-3-clause
7,055
84
10
1,576
2,850
1,829
1,021
-1
-1
module GL.Types ( V2FL, V3FL, Coor2(..), Coor3(..), fromDegrees ) where import Graphics.Rendering.OpenGL as GL type V2FL = Vertex2 GLfloat type V3FL = Vertex3 GLfloat data Coor2 = D2 {x,y::GLfloat} deriving Show data Coor3 = D3 {xx,yy,zz::GLfloat} deriving (Show) fromDegrees deg = deg * pi / 180
xruzzz/ax-fp-gl-haskell
src/GL/Types.hs
bsd-3-clause
346
0
8
95
119
75
44
13
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} module ZM.Types ( module Data.Model.Types , AbsTypeModel , AbsType , AbsRef(..) , absRef , AbsADT , AbsEnv , ADTRef(..) , getADTRef , toTypeRef , substAbsADT , asIdentifier , Identifier(..) , UnicodeLetter(..) , UnicodeLetterOrNumberOrLine(..) , UnicodeSymbol(..) , SHA3_256_6(..) , SHAKE128_48(..) , shake128_48 , shake128_48_BS , NonEmptyList(..) , nonEmptyList , Word7 -- * Encodings , FlatEncoding(..) , UTF8Encoding(..) , UTF16LEEncoding(..) , NoEncoding(..) -- * Exceptions and Errors , TypedDecoded , TypedDecodeException(..) , ZMError(..) -- *Other Re-exports , NFData() , Flat , ZigZag(..) , LeastSignificantFirst(..) , MostSignificantFirst(..) --, Value(..) --, Val(..) --, SpecialValue(..) -- , Binder(..) -- , Void1 ) where -- , Label(..) -- , label --, Pattern(..) --, PatternSpecial(..) import Control.DeepSeq import Control.Exception import qualified Data.ByteString as B import Data.Char import Data.Digest.Keccak import Data.Either.Validation import Flat import Data.Foldable -- import qualified Data.Map as M import Data.Model hiding ( Name ) import Data.Model.Types hiding ( Name ) import Data.Word import ZM.Model ( ) import ZM.Type.BLOB import ZM.Type.NonEmptyList import ZM.Type.Words ( LeastSignificantFirst(..) , MostSignificantFirst(..) , Word7 , ZigZag(..) ) -- |An absolute type, a type identifier that depends only on the definition of the type type AbsType = Type AbsRef -- |A reference to an absolute data type definition, in the form of a hash of the data type definition itself -- data AbsRef = AbsRef (SHA3_256_6 AbsADT) deriving (Eq, Ord, Show, NFData, Generic, Flat) newtype AbsRef = AbsRef (SHAKE128_48 AbsADT) deriving (Eq, Ord, Show, NFData, Generic, Flat) -- type AbsRef = SHAKE128_48 AbsADT -- |Return the absolute reference of the given value absRef :: AbsADT -> AbsRef absRef = AbsRef . shake128_48 -- |Return the SHAKE128_48 reference of the given value shake128_48 :: Flat a => a -> SHAKE128_48 a shake128_48 = shake128_48_BS . flat -- |Return the SHAKE128_48 reference of the given ByteString shake128_48_BS :: B.ByteString -> SHAKE128_48 a shake128_48_BS bs = case B.unpack . shake_128 6 $ bs of [w1, w2, w3, w4, w5, w6] -> SHAKE128_48 w1 w2 w3 w4 w5 w6 _ -> error "impossible" -- |A hash of a value, the first 6 bytes of the value's SHA3-256 hash data SHA3_256_6 a = SHA3_256_6 Word8 Word8 Word8 Word8 Word8 Word8 deriving (Eq, Ord, Show, NFData, Generic, Flat) -- |A hash of a value, the first 48 bits (6 bytes) of the value's SHAKE128 hash data SHAKE128_48 a = SHAKE128_48 Word8 Word8 Word8 Word8 Word8 Word8 deriving (Eq, Ord, Show, NFData, Generic, Flat) -- CHECK: Same syntax for adt and constructor names -- |An absolute data type definition, a definition that refers only to other absolute definitions type AbsADT = ADT Identifier Identifier (ADTRef AbsRef) -- |An absolute type model, an absolute type and its associated environment type AbsTypeModel = TypeModel Identifier Identifier (ADTRef AbsRef) AbsRef -- |An environments of absolute types type AbsEnv = TypeEnv Identifier Identifier (ADTRef AbsRef) AbsRef -- type ADTEnv = M.Map AbsRef AbsADT -- FIX: add a custom type for Var -- |A reference inside an ADT to another ADT data ADTRef r = Var Word8 -- ^Variable, standing for a type | Rec -- ^Recursive reference to the ADT itself | Ext r -- ^Reference to another ADT deriving (Eq, Ord, Show, NFData, Generic, Functor, Foldable, Traversable, Flat) -- |Return an external reference, if present getADTRef :: ADTRef a -> Maybe a getADTRef (Ext r) = Just r getADTRef _ = Nothing toTypeRef :: name -> ADTRef name -> TypeRef name toTypeRef _ (Var n) = TypVar n toTypeRef _ (Ext k) = TypRef k toTypeRef adtRef Rec = TypRef adtRef substAbsADT :: (AbsRef -> b) -> AbsADT -> ADT Identifier Identifier (TypeRef b) substAbsADT f adt = (f <$>) <$> (toTypeRef (absRef adt) <$> adt) -- CHECK: Is it necessary to specify a syntax for identifiers? -- |An Identifier, the name of an ADT data Identifier = Name UnicodeLetter [UnicodeLetterOrNumberOrLine] | Symbol (NonEmptyList UnicodeSymbol) deriving (Eq, Ord, Show, NFData, Generic, Flat) -- instance Flat [UnicodeLetterOrNumberOrLine] instance Convertible String Identifier where -- safeConvert = errorsToConvertResult asIdentifier safeConvert = errorsToConvertResult (validationToEither . asIdentifier) instance Convertible Identifier String where safeConvert (Name (UnicodeLetter h) t) = Right $ h : map (\(UnicodeLetterOrNumberOrLine s) -> s) t safeConvert (Symbol l) = Right $ map (\(UnicodeSymbol s) -> s) . toList $ l {-|Validate a string as an Identifier >>> asIdentifier "Id_1" Success (Name (UnicodeLetter 'I') [UnicodeLetterOrNumberOrLine 'd',UnicodeLetterOrNumberOrLine '_',UnicodeLetterOrNumberOrLine '1']) >>> asIdentifier "<>" Success (Symbol (Cons (UnicodeSymbol '<') (Elem (UnicodeSymbol '>')))) >>> asIdentifier "" Failure ["identifier cannot be empty"] >>> asIdentifier "a*^" Failure ["In a*^: '*' is not an Unicode Letter or Number or a _","In a*^: '^' is not an Unicode Letter or Number or a _"] -} asIdentifier :: String -> Validation Errors Identifier asIdentifier [] = err ["identifier cannot be empty"] asIdentifier i@(h : t) = errsInContext i $ if isLetter h then Name <$> asLetter h <*> traverse asLetterOrNumber t else Symbol . nonEmptyList <$> traverse asSymbol i -- |A character that is either a `UnicodeLetter`, a `UnicodeNumber` or the special character '_' newtype UnicodeLetterOrNumberOrLine = UnicodeLetterOrNumberOrLine Char deriving (Eq, Ord, Show, NFData, Generic, Flat) {-| A character that is included in one of the following Unicode classes: UppercaseLetter LowercaseLetter TitlecaseLetter ModifierLetter OtherLetter -} newtype UnicodeLetter = UnicodeLetter Char deriving (Eq, Ord, Show, NFData, Generic, Flat) {-| A character that is included in one of the following Unicode classes: DecimalNumber LetterNumber OtherNumber -} newtype UnicodeNumber = UnicodeNumber Char deriving (Eq, Ord, Show, NFData, Generic, Flat) {-| A character that is included in one of the following Unicode classes: MathSymbol CurrencySymbol ModifierSymbol OtherSymbol -} newtype UnicodeSymbol = UnicodeSymbol Char deriving (Eq, Ord, Show, NFData, Generic, Flat) asSymbol :: Char -> Validation Errors UnicodeSymbol asSymbol c | isSymbol c = ok $ UnicodeSymbol c | otherwise = err [show c, "is not an Unicode Symbol"] asLetter :: Char -> Validation Errors UnicodeLetter asLetter c | isLetter c = ok $ UnicodeLetter c | otherwise = err [show c, "is not an Unicode Letter"] asLetterOrNumber :: Char -> Validation Errors UnicodeLetterOrNumberOrLine asLetterOrNumber c | isLetter c || isNumber c || isAlsoOK c = ok $ UnicodeLetterOrNumberOrLine c | otherwise = err [show c, "is not an Unicode Letter or Number or a _"] ok :: a -> Validation e a ok = Success err :: [String] -> Validation Errors a err = Failure . (: []) . unwords -- CHECK: IS '_' REALLY NEEDED? isAlsoOK :: Char -> Bool isAlsoOK '_' = True isAlsoOK _ = False -- |Violations of ZM model constrains data ZMError t = UnknownType t | WrongKind { reference :: t, expectedArity, actualArity :: Int } | MutuallyRecursive [t] deriving (Show, Functor, Foldable) -- -- -- |An optionally labeled value -- data Label a label = -- Label a (Maybe label) -- deriving (Eq, Ord, Show, NFData, Generic, Flat) -- label :: (Functor f, Ord k) => M.Map k a -> (a -> l) -> f k -> f (Label k l) -- label env f o = (\ref -> Label ref (f <$> M.lookup ref env)) <$> o type TypedDecoded a = Either TypedDecodeException a -- |An exception thrown if the decoding of a type value fails data TypedDecodeException = UnknownMetaModel AbsType | WrongType { expectedType :: AbsType, actualType :: AbsType } | DecodeError DecodeException deriving (Show, Eq, Ord) instance Exception TypedDecodeException -- newtype LocalName = LocalName Identifier deriving (Eq, Ord, Show, NFData, Generic, Flat) -- Flat instances for data types in the 'model' package instance (Flat adtName, Flat consName, Flat inRef, Flat exRef, Ord exRef) => Flat (TypeModel adtName consName inRef exRef) instance (Flat a, Flat b, Flat c) => Flat (ADT a b c) instance (Flat a, Flat b) => Flat (ConTree a b) -- instance (Flat a,Flat b) => Flat [(a,Type b)] -- instance Flat a => Flat [Type a] instance Flat a => Flat (Type a) instance Flat a => Flat (TypeRef a) -- Model instances instance (Model a, Model b, Model c) => Model (ADT a b c) instance (Model a, Model b) => Model (ConTree a b) instance Model a => Model (ADTRef a) instance Model a => Model (Type a) instance Model a => Model (TypeRef a) instance (Model adtName, Model consName, Model inRef, Model exRef) => Model (TypeModel adtName consName inRef exRef) instance Model Identifier instance Model UnicodeLetter instance Model UnicodeLetterOrNumberOrLine instance Model UnicodeSymbol instance Model a => Model (SHA3_256_6 a) instance Model a => Model (SHAKE128_48 a) instance Model AbsRef instance Model a => Model (PostAligned a)
tittoassini/typed
src/ZM/Types.hs
bsd-3-clause
9,975
0
13
2,235
2,180
1,193
987
168
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Language.Sunroof.Active ( JSTime , JSDuration , reifyActive ) where import Control.Newtype ( Newtype(..) ) import Data.Active ( Clock(..), Deadline(..), Waiting(..) , Active , FractionalOf , toFractionalOf, onActive, runDynamic , start, era, end ) import Data.VectorSpace ( VectorSpace(..) ) import Data.AffineSpace ( AffineSpace(..) ) import Data.AdditiveGroup ( AdditiveGroup(..) ) import Data.Boolean ( BooleanOf, IfB(..), OrdB(..) , minB, maxB ) import Language.Sunroof.Types ( T(..) , JS, SunroofThread , JSFunction , function ) import Language.Sunroof.Classes ( Sunroof, SunroofValue(..), SunroofArgument(..) ) import Language.Sunroof.JS.Bool ( JSBool ) import Language.Sunroof.JS.Number ( JSNumber ) -- ------------------------------------------------------------- -- JSTime Type -- ------------------------------------------------------------- newtype JSTime = JSTime { unJSTime :: JSNumber } deriving ( Show ) instance Newtype JSTime JSNumber where pack = JSTime unpack = unJSTime instance AffineSpace JSTime where type Diff JSTime = JSDuration (JSTime t1) .-. (JSTime t2) = JSDuration (t1 - t2) (JSTime t) .+^ (JSDuration d) = JSTime (t + d) instance Clock JSTime where firstTime (JSTime t1) (JSTime t2) = JSTime (minB t1 t2) lastTime (JSTime t1) (JSTime t2) = JSTime (maxB t1 t2) toTime = JSTime . js . toRational fromTime = toFractionalOf instance FractionalOf JSTime JSNumber where toFractionalOf = unJSTime --instance (BooleanOf a ~ JSBool, IfB a) => Deadline JSTime a where -- choose (JSTime t1) (JSTime t2) = ifB (t1 <=* t2) instance (BooleanOf b ~ JSBool, IfB b, Deadline JSTime b) => Deadline JSTime (a -> b) where choose (JSTime t1) (JSTime t2) f1 f2 a = ifB (t1 <=* t2) (f1 a) (f2 a) instance (Sunroof a, SunroofArgument a, SunroofThread t) => Deadline JSTime (JS t a) where choose (JSTime t1) (JSTime t2) = ifB (t1 <=* t2) instance Deadline JSTime JSNumber where choose (JSTime t1) (JSTime t2) = ifB (t1 <=* t2) instance Deadline JSTime JSBool where choose (JSTime t1) (JSTime t2) = ifB (t1 <=* t2) --instance (BooleanOf a ~ JSBool, IfB a) => Deadline JSTime (f -> a) where -- choose (JSTime t1) (JSTime t2) x y c = ifB (t1 <=* t2) (x c) (y c) -- ------------------------------------------------------------- -- JSDuration Type -- ------------------------------------------------------------- newtype JSDuration = JSDuration { unJSDuration :: JSNumber } deriving ( Show, AdditiveGroup ) instance Newtype JSDuration JSNumber where pack = JSDuration unpack = unJSDuration instance VectorSpace JSDuration where type Scalar JSDuration = JSNumber s *^ (JSDuration d) = JSDuration (s * d) instance Waiting JSDuration where toDuration = JSDuration . js . toRational fromDuration = toFractionalOf instance FractionalOf JSDuration JSNumber where toFractionalOf = unJSDuration -- ------------------------------------------------------------- -- Active Combinators -- ------------------------------------------------------------- --ex1 :: Active JSTime (JS t JSNumber) --ex1 = fmap return ui reifyActive :: Active JSTime (JS A ()) -> JS A (JSNumber, JSNumber, JSFunction JSNumber ()) reifyActive = onActive (\ x -> do f <- function (\ _ -> x) return ( 0, 0, f ) ) (\ d -> do f <- function (runDynamic d . JSTime) return ( fromTime $ start $ era d , fromTime $ end $ era d , f ) ) {- compileActiveJS t :: Active JSTime (JS t JSNumber) -> String compileActiveJS t act = a ++ " ; return " ++ b where (a,b) = compileJS t $ do obj :: JSFunction JSNumber JSNumber <- function (runActive act . JSTime) apply obj 0 -}
ku-fpg/sunroof-active
Language/Sunroof/Active.hs
bsd-3-clause
4,089
13
15
801
1,047
579
468
-1
-1
module More.MonadTs where import Control.Monad.Trans.Class import Control.Monad.Trans.Reader import Control.Monad.Trans.State import Control.Monad.Trans.Maybe import Control.Monad.Identity import Control.Monad.IO.Class import Control.Monad rDec :: Num a => Reader a a rDec = ReaderT $ return . ((+) (-1)) rShow :: Show a => ReaderT a Identity String rShow = ReaderT $ Identity . show rPrintAndInc :: (Num a, Show a) => ReaderT a IO a rPrintAndInc = ReaderT $ \r -> do putStrLn $ "Hi: " ++ show r return $ r + 1 sPrintIncAccum :: (Num a, Show a) => StateT a IO String sPrintIncAccum = StateT $ \r -> do putStrLn $ "Hi: " ++ show r return $ (show r, r + 1) isValid :: String -> Bool isValid v = '!' `elem` v hungryText :: MaybeT IO String hungryText = do v <- lift getLine guard (isValid v) return v main :: IO () main = do putStrLn "say something." excite <- runMaybeT hungryText case excite of Nothing -> putStrLn "Nothing! Nothing was said!" Just e -> putStrLn ("Boom! what was said: " ++ e)
stites/composition
src/MoreReaderT.hs
bsd-3-clause
1,133
0
12
314
400
208
192
34
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. {-# LANGUAGE GADTs #-} {-# LANGUAGE NoRebindableSyntax #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Time.PT.Rules ( rules ) where import qualified Data.Text as Text import Prelude import Duckling.Dimensions.Types import Duckling.Numeral.Helpers (parseInt) import Duckling.Regex.Types import Duckling.Time.Helpers import Duckling.Time.Types (TimeData (..)) import qualified Duckling.Time.Types as TTime import qualified Duckling.TimeGrain.Types as TG import Duckling.Types ruleNamedday :: Rule ruleNamedday = Rule { name = "named-day" , pattern = [ regex "segunda((\\s|\\-)feira)?|seg\\.?" ] , prod = \_ -> tt $ dayOfWeek 1 } ruleSHourmintimeofday :: Rule ruleSHourmintimeofday = Rule { name = "às <hour-min>(time-of-day)" , pattern = [ regex "(\x00e0|a)s?" , Predicate isATimeOfDay , regex "horas?" ] , prod = \tokens -> case tokens of (_:x:_) -> Just x _ -> Nothing } ruleTheDayAfterTomorrow :: Rule ruleTheDayAfterTomorrow = Rule { name = "the day after tomorrow" , pattern = [ regex "depois de amanh(\x00e3|a)" ] , prod = \_ -> tt $ cycleNth TG.Day 2 } ruleNamedmonth12 :: Rule ruleNamedmonth12 = Rule { name = "named-month" , pattern = [ regex "dezembro|dez\\.?" ] , prod = \_ -> tt $ month 12 } ruleNamedday2 :: Rule ruleNamedday2 = Rule { name = "named-day" , pattern = [ regex "ter(\x00e7|c)a((\\s|\\-)feira)?|ter\\.?" ] , prod = \_ -> tt $ dayOfWeek 2 } ruleNatal :: Rule ruleNatal = Rule { name = "natal" , pattern = [ regex "natal" ] , prod = \_ -> tt $ monthDay 12 25 } ruleNaoDate :: Rule ruleNaoDate = Rule { name = "n[ao] <date>" , pattern = [ regex "n[ao]" , Predicate $ isGrainOfTime TG.Day ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ notLatent td _ -> Nothing } ruleIntersectByDaOrDe :: Rule ruleIntersectByDaOrDe = Rule { name = "intersect by `da` or `de`" , pattern = [ Predicate isNotLatent , regex "d[ae]" , Predicate isNotLatent ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_) -> Token Time <$> intersect td1 td2 _ -> Nothing } rulePassadosNCycle :: Rule rulePassadosNCycle = Rule { name = "passados n <cycle>" , pattern = [ regex "passad(a|o)s?" , Predicate $ isIntegerBetween 2 9999 , dimension TimeGrain ] , prod = \tokens -> case tokens of (_:token:Token TimeGrain grain:_) -> do v <- getIntValue token tt $ cycleN True grain (- v) _ -> Nothing } ruleLastTime :: Rule ruleLastTime = Rule { name = "last <time>" , pattern = [ regex "(\x00fa|u)ltim[ao]s?" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ predNth (-1) False td _ -> Nothing } ruleNamedday6 :: Rule ruleNamedday6 = Rule { name = "named-day" , pattern = [ regex "s(\x00e1|a)bado|s(\x00e1|a)b\\.?" ] , prod = \_ -> tt $ dayOfWeek 6 } ruleDatetimeDatetimeInterval :: Rule ruleDatetimeDatetimeInterval = Rule { name = "<datetime> - <datetime> (interval)" , pattern = [ Predicate isNotLatent , regex "\\-|a" , Predicate isNotLatent ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_) -> Token Time <$> interval TTime.Open td1 td2 _ -> Nothing } ruleNamedmonth7 :: Rule ruleNamedmonth7 = Rule { name = "named-month" , pattern = [ regex "julho|jul\\.?" ] , prod = \_ -> tt $ month 7 } ruleEvening :: Rule ruleEvening = Rule { name = "evening" , pattern = [ regex "noite" ] , prod = \_ -> let from = hour False 18 to = hour False 0 in Token Time . mkLatent . partOfDay <$> interval TTime.Open from to } ruleDayOfMonthSt :: Rule ruleDayOfMonthSt = Rule { name = "day of month (1st)" , pattern = [ regex "primeiro|um|1o" ] , prod = \_ -> tt $ dayOfMonth 1 } ruleNow :: Rule ruleNow = Rule { name = "now" , pattern = [ regex "(hoje)|(neste|nesse) momento" ] , prod = \_ -> tt $ cycleNth TG.Day 0 } ruleDimTimeDaMadrugada :: Rule ruleDimTimeDaMadrugada = Rule { name = "<dim time> da madrugada" , pattern = [ dimension Time , regex "(da|na|pela) madruga(da)?" ] , prod = \tokens -> case tokens of (Token Time td:_) -> do td2 <- mkLatent . partOfDay <$> interval TTime.Open (hour False 1) (hour False 4) Token Time <$> intersect td td2 _ -> Nothing } ruleHhhmmTimeofday :: Rule ruleHhhmmTimeofday = Rule { name = "hh(:|.|h)mm (time-of-day)" , pattern = [ regex "((?:[01]?\\d)|(?:2[0-3]))[:h\\.]([0-5]\\d)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (m1:m2:_)):_) -> do h <- parseInt m1 m <- parseInt m2 tt $ hourMinute True h m _ -> Nothing } ruleNamedday4 :: Rule ruleNamedday4 = Rule { name = "named-day" , pattern = [ regex "quinta((\\s|\\-)feira)?|qui\\.?" ] , prod = \_ -> tt $ dayOfWeek 4 } ruleProximoCycle :: Rule ruleProximoCycle = Rule { name = "proximo <cycle> " , pattern = [ regex "pr(\x00f3|o)xim(o|a)s?" , dimension TimeGrain ] , prod = \tokens -> case tokens of (_:Token TimeGrain grain:_) -> tt $ cycleNth grain 1 _ -> Nothing } ruleCycleAntesDeTime :: Rule ruleCycleAntesDeTime = Rule { name = "<cycle> antes de <time>" , pattern = [ dimension TimeGrain , regex "antes d[eo]" , dimension Time ] , prod = \tokens -> case tokens of (Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter False grain (-1) td _ -> Nothing } ruleEsteCycle :: Rule ruleEsteCycle = Rule { name = "este <cycle>" , pattern = [ regex "(n?es[st](es?|as?))" , dimension TimeGrain ] , prod = \tokens -> case tokens of (_:Token TimeGrain grain:_) -> tt $ cycleNth grain 0 _ -> Nothing } ruleSHourminTimeofday :: Rule ruleSHourminTimeofday = Rule { name = "às <hour-min> <time-of-day>" , pattern = [ regex "(\x00e0|a)s" , Predicate isNotLatent , regex "da" , Predicate isATimeOfDay ] , prod = \tokens -> case tokens of (_:Token Time td1:_:Token Time td2:_) -> Token Time <$> intersect td1 td2 _ -> Nothing } ruleSeason4 :: Rule ruleSeason4 = Rule { name = "season" , pattern = [ regex "primavera" ] , prod = \_ -> let from = monthDay 3 20 to = monthDay 6 21 in Token Time <$> interval TTime.Open from to } ruleYearLatent2 :: Rule ruleYearLatent2 = Rule { name = "year (latent)" , pattern = [ Predicate $ isIntegerBetween 2101 10000 ] , prod = \tokens -> case tokens of (token:_) -> do n <- getIntValue token tt . mkLatent $ year n _ -> Nothing } ruleDiaDayofmonthDeNamedmonth :: Rule ruleDiaDayofmonthDeNamedmonth = Rule { name = "dia <day-of-month> de <named-month>" , pattern = [ regex "dia" , Predicate isDOMInteger , regex "de|\\/" , Predicate isAMonth ] , prod = \tokens -> case tokens of (_:token:_:Token Time td:_) -> Token Time <$> intersectDOM td token _ -> Nothing } ruleNoon :: Rule ruleNoon = Rule { name = "noon" , pattern = [ regex "meio[\\s\\-]?dia" ] , prod = \_ -> tt $ hour False 12 } ruleProximasNCycle :: Rule ruleProximasNCycle = Rule { name = "proximas n <cycle>" , pattern = [ regex "pr(\x00f3|o)xim(o|a)s?" , Predicate $ isIntegerBetween 2 9999 , dimension TimeGrain ] , prod = \tokens -> case tokens of (_:token:Token TimeGrain grain:_) -> do v <- getIntValue token tt $ cycleN True grain v _ -> Nothing } ruleThisnextDayofweek :: Rule ruleThisnextDayofweek = Rule { name = "this|next <day-of-week>" , pattern = [ regex "es[ts][ae]|pr(\x00f3|o)xim[ao]" , Predicate isADayOfWeek ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ predNth 0 True td _ -> Nothing } ruleTheDayBeforeYesterday :: Rule ruleTheDayBeforeYesterday = Rule { name = "the day before yesterday" , pattern = [ regex "anteontem|antes de ontem" ] , prod = \_ -> tt . cycleNth TG.Day $ - 2 } ruleHourofdayIntegerAsRelativeMinutes :: Rule ruleHourofdayIntegerAsRelativeMinutes = Rule { name = "<hour-of-day> <integer> (as relative minutes)" , pattern = [ Predicate isAnHourOfDay , Predicate $ isIntegerBetween 1 59 ] , prod = \tokens -> case tokens of (Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}: token: _) -> do n <- getIntValue token tt $ hourMinute is12H hours n _ -> Nothing } ruleHourofdayAndRelativeMinutes :: Rule ruleHourofdayAndRelativeMinutes = Rule { name = "<hour-of-day> and <relative minutes>" , pattern = [ Predicate isAnHourOfDay , regex "e" , Predicate $ isIntegerBetween 1 59 ] , prod = \tokens -> case tokens of (Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}: _: token: _) -> do n <- getIntValue token tt $ hourMinute is12H hours n _ -> Nothing } ruleIntegerParaAsHourofdayAsRelativeMinutes :: Rule ruleIntegerParaAsHourofdayAsRelativeMinutes = Rule { name = "<integer> para as <hour-of-day> (as relative minutes)" , pattern = [ Predicate $ isIntegerBetween 1 59 , regex "para ((o|a|\x00e0)s?)?" , Predicate isAnHourOfDay ] , prod = \tokens -> case tokens of (token:_:Token Time td:_) -> do n <- getIntValue token t <- minutesBefore n td Just $ Token Time t _ -> Nothing } ruleHourofdayIntegerAsRelativeMinutes2 :: Rule ruleHourofdayIntegerAsRelativeMinutes2 = Rule { name = "<hour-of-day> <integer> (as relative minutes) minutos" , pattern = [ Predicate isAnHourOfDay , Predicate $ isIntegerBetween 1 59 , regex "min\\.?(uto)?s?" ] , prod = \tokens -> case tokens of (Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}: token: _) -> do n <- getIntValue token tt $ hourMinute is12H hours n _ -> Nothing } ruleHourofdayAndRelativeMinutes2 :: Rule ruleHourofdayAndRelativeMinutes2 = Rule { name = "<hour-of-day> and <relative minutes> minutos" , pattern = [ Predicate isAnHourOfDay , regex "e" , Predicate $ isIntegerBetween 1 59 , regex "min\\.?(uto)?s?" ] , prod = \tokens -> case tokens of (Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}: _: token: _) -> do n <- getIntValue token tt $ hourMinute is12H hours n _ -> Nothing } ruleIntegerParaAsHourofdayAsRelativeMinutes2 :: Rule ruleIntegerParaAsHourofdayAsRelativeMinutes2 = Rule { name = "<integer> minutos para as <hour-of-day> (as relative minutes)" , pattern = [ Predicate $ isIntegerBetween 1 59 , regex "min\\.?(uto)?s?" , regex "para ((o|a|\x00e0)s?)?" , Predicate isAnHourOfDay ] , prod = \tokens -> case tokens of (token:_:_:Token Time td:_) -> do n <- getIntValue token t <- minutesBefore n td Just $ Token Time t _ -> Nothing } ruleHourofdayQuarter :: Rule ruleHourofdayQuarter = Rule { name = "<hour-of-day> quarter (as relative minutes)" , pattern = [ Predicate isAnHourOfDay , regex "quinze" ] , prod = \tokens -> case tokens of (Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}: _) -> tt $ hourMinute is12H hours 15 _ -> Nothing } ruleHourofdayAndQuarter :: Rule ruleHourofdayAndQuarter = Rule { name = "<hour-of-day> and quinze" , pattern = [ Predicate isAnHourOfDay , regex "e quinze" ] , prod = \tokens -> case tokens of (Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}: _) -> tt $ hourMinute is12H hours 15 _ -> Nothing } ruleQuarterParaAsHourofdayAsRelativeMinutes :: Rule ruleQuarterParaAsHourofdayAsRelativeMinutes = Rule { name = "quinze para as <hour-of-day> (as relative minutes)" , pattern = [ regex "quinze para ((o|a|\x00e0)s?)?" , Predicate isAnHourOfDay ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> Token Time <$> minutesBefore 15 td _ -> Nothing } ruleHourofdayHalf :: Rule ruleHourofdayHalf = Rule { name = "<hour-of-day> half (as relative minutes)" , pattern = [ Predicate isAnHourOfDay , regex "meia|trinta" ] , prod = \tokens -> case tokens of (Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}: _) -> tt $ hourMinute is12H hours 30 _ -> Nothing } ruleHourofdayAndHalf :: Rule ruleHourofdayAndHalf = Rule { name = "<hour-of-day> and half" , pattern = [ Predicate isAnHourOfDay , regex "e (meia|trinta)" ] , prod = \tokens -> case tokens of (Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}: _) -> tt $ hourMinute is12H hours 30 _ -> Nothing } ruleHalfParaAsHourofdayAsRelativeMinutes :: Rule ruleHalfParaAsHourofdayAsRelativeMinutes = Rule { name = "half para as <hour-of-day> (as relative minutes)" , pattern = [ regex "(meia|trinta) para ((o|a|\x00e0)s?)?" , Predicate isAnHourOfDay ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> Token Time <$> minutesBefore 30 td _ -> Nothing } ruleHourofdayThreeQuarter :: Rule ruleHourofdayThreeQuarter = Rule { name = "<hour-of-day> 3/4 (as relative minutes)" , pattern = [ Predicate isAnHourOfDay , regex "quarenta e cinco" ] , prod = \tokens -> case tokens of (Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}: _) -> tt $ hourMinute is12H hours 45 _ -> Nothing } ruleHourofdayAndThreeQuarter :: Rule ruleHourofdayAndThreeQuarter = Rule { name = "<hour-of-day> and 3/4" , pattern = [ Predicate isAnHourOfDay , regex "e quarenta e cinco" ] , prod = \tokens -> case tokens of (Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}: _) -> tt $ hourMinute is12H hours 45 _ -> Nothing } ruleThreeQuarterParaAsHourofdayAsRelativeMinutes :: Rule ruleThreeQuarterParaAsHourofdayAsRelativeMinutes = Rule { name = "3/4 para as <hour-of-day> (as relative minutes)" , pattern = [ regex "quarenta e cinco para ((o|a|\x00e0)s?)?" , Predicate isAnHourOfDay ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> Token Time <$> minutesBefore 45 td _ -> Nothing } ruleNamedmonth :: Rule ruleNamedmonth = Rule { name = "named-month" , pattern = [ regex "janeiro|jan\\.?" ] , prod = \_ -> tt $ month 1 } ruleTiradentes :: Rule ruleTiradentes = Rule { name = "Tiradentes" , pattern = [ regex "tiradentes" ] , prod = \_ -> tt $ monthDay 4 21 } ruleInThePartofday :: Rule ruleInThePartofday = Rule { name = "in the <part-of-day>" , pattern = [ regex "(de|pela)" , Predicate isAPartOfDay ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ notLatent td _ -> Nothing } rulePartofdayDessaSemana :: Rule rulePartofdayDessaSemana = Rule { name = "<part-of-day> dessa semana" , pattern = [ Predicate isNotLatent , regex "(d?es[ts]a semana)|agora" ] , prod = \tokens -> case tokens of (Token Time td:_) -> Token Time . partOfDay <$> intersect (cycleNth TG.Day 0) td _ -> Nothing } ruleNamedmonth3 :: Rule ruleNamedmonth3 = Rule { name = "named-month" , pattern = [ regex "mar(\x00e7|c)o|mar\\.?" ] , prod = \_ -> tt $ month 3 } ruleDepoisDasTimeofday :: Rule ruleDepoisDasTimeofday = Rule { name = "depois das <time-of-day>" , pattern = [ regex "(depois|ap(\x00f3|o)s) d?((a|\x00e1|\x00e0)[so]?|os?)" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ withDirection TTime.After td _ -> Nothing } ruleDdmm :: Rule ruleDdmm = Rule { name = "dd[/-]mm" , pattern = [ regex "(3[01]|[12]\\d|0?[1-9])[\\/\\-](0?[1-9]|1[0-2])" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (dd:mm:_)):_) -> do m <- parseInt mm d <- parseInt dd tt $ monthDay m d _ -> Nothing } ruleEmDuration :: Rule ruleEmDuration = Rule { name = "em <duration>" , pattern = [ regex "em" , dimension Duration ] , prod = \tokens -> case tokens of (_:Token Duration dd:_) -> tt $ inDuration dd _ -> Nothing } ruleAfternoon :: Rule ruleAfternoon = Rule { name = "afternoon" , pattern = [ regex "tarde" ] , prod = \_ -> let from = hour False 12 to = hour False 19 in Token Time . mkLatent . partOfDay <$> interval TTime.Open from to } ruleNamedmonth4 :: Rule ruleNamedmonth4 = Rule { name = "named-month" , pattern = [ regex "abril|abr\\.?" ] , prod = \_ -> tt $ month 4 } ruleDimTimeDaManha :: Rule ruleDimTimeDaManha = Rule { name = "<dim time> da manha" , pattern = [ Predicate $ isGrainFinerThan TG.Year , regex "(da|na|pela) manh(\x00e3|a)" ] , prod = \tokens -> case tokens of (Token Time td:_) -> do td2 <- mkLatent . partOfDay <$> interval TTime.Open (hour False 4) (hour False 12) Token Time <$> intersect td td2 _ -> Nothing } ruleNCycleProximoqueVem :: Rule ruleNCycleProximoqueVem = Rule { name = "n <cycle> (proximo|que vem)" , pattern = [ Predicate $ isIntegerBetween 2 9999 , dimension TimeGrain , regex "(pr(\x00f3|o)xim(o|a)s?|que vem?|seguintes?)" ] , prod = \tokens -> case tokens of (token:Token TimeGrain grain:_) -> do v <- getIntValue token tt $ cycleN True grain v _ -> Nothing } ruleMidnight :: Rule ruleMidnight = Rule { name = "midnight" , pattern = [ regex "meia[\\s\\-]?noite" ] , prod = \_ -> tt $ hour False 0 } ruleNamedday5 :: Rule ruleNamedday5 = Rule { name = "named-day" , pattern = [ regex "sexta((\\s|\\-)feira)?|sex\\.?" ] , prod = \_ -> tt $ dayOfWeek 5 } ruleDdddMonthinterval :: Rule ruleDdddMonthinterval = Rule { name = "dd-dd <month>(interval)" , pattern = [ regex "(3[01]|[12]\\d|0?[1-9])" , regex "\\-|a" , regex "(3[01]|[12]\\d|0?[1-9])" , regex "de" , Predicate isAMonth ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (m1:_)): _: Token RegexMatch (GroupMatch (m2:_)): _: Token Time td: _) -> do d1 <- parseInt m1 d2 <- parseInt m2 from <- intersect (dayOfMonth d1) td to <- intersect (dayOfMonth d2) td Token Time <$> interval TTime.Closed from to _ -> Nothing } ruleTimeofdayLatent :: Rule ruleTimeofdayLatent = Rule { name = "time-of-day (latent)" , pattern = [ Predicate $ isIntegerBetween 0 23 ] , prod = \tokens -> case tokens of (token:_) -> do v <- getIntValue token tt . mkLatent $ hour True v _ -> Nothing } ruleUltimoTime :: Rule ruleUltimoTime = Rule { name = "ultimo <time>" , pattern = [ regex "(u|\x00fa)ltimo" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ predNth (-1) False td _ -> Nothing } ruleNamedmonth2 :: Rule ruleNamedmonth2 = Rule { name = "named-month" , pattern = [ regex "fevereiro|fev\\.?" ] , prod = \_ -> tt $ month 2 } ruleNamedmonthnameddayPast :: Rule ruleNamedmonthnameddayPast = Rule { name = "<named-month|named-day> past" , pattern = [ Predicate isNotLatent , regex "(da semana)? passad(o|a)" ] , prod = \tokens -> case tokens of (Token Time td:_) -> tt $ predNth (-1) False td _ -> Nothing } ruleSeason3 :: Rule ruleSeason3 = Rule { name = "season" , pattern = [ regex "inverno" ] , prod = \_ -> let from = monthDay 12 21 to = monthDay 3 20 in Token Time <$> interval TTime.Open from to } ruleSeason :: Rule ruleSeason = Rule { name = "season" , pattern = [ regex "ver(\x00e3|a)o" ] , prod = \_ -> let from = monthDay 6 21 to = monthDay 9 23 in Token Time <$> interval TTime.Open from to } ruleRightNow :: Rule ruleRightNow = Rule { name = "right now" , pattern = [ regex "agora|j(\x00e1|a)|(nesse|neste) instante" ] , prod = \_ -> tt $ cycleNth TG.Second 0 } ruleFazemDuration :: Rule ruleFazemDuration = Rule { name = "fazem <duration>" , pattern = [ regex "faz(em)?" , dimension Duration ] , prod = \tokens -> case tokens of (_:Token Duration dd:_) -> tt $ durationAgo dd _ -> Nothing } ruleAmanhPelaPartofday :: Rule ruleAmanhPelaPartofday = Rule { name = "amanhã pela <part-of-day>" , pattern = [ dimension Time , regex "(da|na|pela|a)" , Predicate isAPartOfDay ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_) -> Token Time <$> intersect td1 td2 _ -> Nothing } ruleHhmmMilitaryTimeofday :: Rule ruleHhmmMilitaryTimeofday = Rule { name = "hhmm (military time-of-day)" , pattern = [ regex "((?:[01]?\\d)|(?:2[0-3]))([0-5]\\d)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (m1:m2:_)):_) -> do h <- parseInt m1 m <- parseInt m2 tt . mkLatent $ hourMinute False h m _ -> Nothing } ruleNamedmonthnameddayNext :: Rule ruleNamedmonthnameddayNext = Rule { name = "<named-month|named-day> next" , pattern = [ dimension Time , regex "(da pr(o|\x00f3)xima semana)|(da semana)? que vem" ] , prod = \tokens -> case tokens of (Token Time td:_) -> tt $ predNth 1 False td _ -> Nothing } ruleIntersect :: Rule ruleIntersect = Rule { name = "intersect" , pattern = [ Predicate isNotLatent , Predicate isNotLatent ] , prod = \tokens -> case tokens of (Token Time td1:Token Time td2:_) -> Token Time <$> intersect td1 td2 _ -> Nothing } ruleTimeofdayPartofday :: Rule ruleTimeofdayPartofday = Rule { name = "<time-of-day> <part-of-day>" , pattern = [ dimension Time , regex "(da|na|pela)" , Predicate isAPartOfDay ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_) -> Token Time <$> intersect td1 td2 _ -> Nothing } ruleDeDatetimeDatetimeInterval :: Rule ruleDeDatetimeDatetimeInterval = Rule { name = "de <datetime> - <datetime> (interval)" , pattern = [ regex "de?" , dimension Time , regex "\\-|a" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td1:_:Token Time td2:_) -> Token Time <$> interval TTime.Open td1 td2 _ -> Nothing } ruleNamedmonth6 :: Rule ruleNamedmonth6 = Rule { name = "named-month" , pattern = [ regex "junho|jun\\.?" ] , prod = \_ -> tt $ month 6 } ruleDentroDeDuration :: Rule ruleDentroDeDuration = Rule { name = "dentro de <duration>" , pattern = [ regex "(dentro de)|em" , dimension Duration ] , prod = \tokens -> case tokens of (_:Token Duration dd:_) -> let from = cycleNth TG.Second 0 to = inDuration dd in Token Time <$> interval TTime.Open from to _ -> Nothing } ruleSTimeofday :: Rule ruleSTimeofday = Rule { name = "às <time-of-day>" , pattern = [ regex "(\x00e0|a)s?" , Predicate isATimeOfDay ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ notLatent td _ -> Nothing } ruleNamedmonth8 :: Rule ruleNamedmonth8 = Rule { name = "named-month" , pattern = [ regex "agosto|ago\\.?" ] , prod = \_ -> tt $ month 8 } ruleDimTimeDaTarde :: Rule ruleDimTimeDaTarde = Rule { name = "<dim time> da tarde" , pattern = [ dimension Time , regex "(da|na|pela) tarde" ] , prod = \tokens -> case tokens of (Token Time td:_) -> do td2 <- mkLatent . partOfDay <$> interval TTime.Open (hour False 12) (hour False 18) Token Time <$> intersect td td2 _ -> Nothing } ruleWeekend :: Rule ruleWeekend = Rule { name = "week-end" , pattern = [ regex "final de semana|fim de semana|fds" ] , prod = \_ -> do from <- intersect (dayOfWeek 5) (hour False 18) to <- intersect (dayOfWeek 1) (hour False 0) Token Time <$> interval TTime.Open from to } ruleDayofweekSHourmin :: Rule ruleDayofweekSHourmin = Rule { name = "<day-of-week> às <hour-min>" , pattern = [ Predicate isATimeOfDay , regex "(\x00e0|a)s" , Predicate isNotLatent , regex "da|pela" , Predicate isATimeOfDay ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_:Token Time td3:_) -> do td <- intersect td1 td2 Token Time <$> intersect td td3 _ -> Nothing } ruleCycleQueVem :: Rule ruleCycleQueVem = Rule { name = "<cycle> (que vem)" , pattern = [ dimension TimeGrain , regex "que vem|seguintes?" ] , prod = \tokens -> case tokens of (Token TimeGrain grain:_) -> tt $ cycleNth grain 1 _ -> Nothing } ruleAnoNovo :: Rule ruleAnoNovo = Rule { name = "ano novo" , pattern = [ regex "ano novo|reveillon" ] , prod = \_ -> tt $ monthDay 1 1 } ruleNextTime :: Rule ruleNextTime = Rule { name = "next <time>" , pattern = [ regex "(d[ao]) pr(\x00f3|o)xim[ao]s?|que vem" , Predicate isNotLatent ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ predNth 0 True td _ -> Nothing } ruleDeYear :: Rule ruleDeYear = Rule { name = "de <year>" , pattern = [ regex "de|do ano" , Predicate $ isIntegerBetween 1000 2100 ] , prod = \tokens -> case tokens of (_:token:_) -> do n <- getIntValue token tt $ year n _ -> Nothing } ruleVesperaDeAnoNovo :: Rule ruleVesperaDeAnoNovo = Rule { name = "vespera de ano novo" , pattern = [ regex "v(\x00e9|e)spera d[eo] ano[\\s\\-]novo" ] , prod = \_ -> tt $ monthDay 12 31 } ruleNPassadosCycle :: Rule ruleNPassadosCycle = Rule { name = "n passados <cycle>" , pattern = [ Predicate $ isIntegerBetween 2 9999 , regex "passad(a|o)s?" , dimension TimeGrain ] , prod = \tokens -> case tokens of (token:_:Token TimeGrain grain:_) -> do v <- getIntValue token tt $ cycleN True grain (- v) _ -> Nothing } ruleDiaDayofmonthNonOrdinal :: Rule ruleDiaDayofmonthNonOrdinal = Rule { name = "dia <day-of-month> (non ordinal)" , pattern = [ regex "dia" , Predicate isDOMInteger ] , prod = \tokens -> case tokens of (_:token:_) -> do v <- getIntValue token tt . mkLatent $ dayOfMonth v _ -> Nothing } ruleYyyymmdd :: Rule ruleYyyymmdd = Rule { name = "yyyy-mm-dd" , pattern = [ regex "(\\d{2,4})-(0?[1-9]|1[0-2])-(3[01]|[12]\\d|0?[1-9])" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (yy:mm:dd:_)):_) -> do y <- parseInt yy m <- parseInt mm d <- parseInt dd tt $ yearMonthDay y m d _ -> Nothing } ruleTimeofdayHoras :: Rule ruleTimeofdayHoras = Rule { name = "<time-of-day> horas" , pattern = [ Predicate isATimeOfDay , regex "h\\.?(ora)?s?" ] , prod = \tokens -> case tokens of (Token Time td:_) -> tt $ notLatent td _ -> Nothing } ruleTwoTimeTokensSeparatedBy :: Rule ruleTwoTimeTokensSeparatedBy = Rule { name = "two time tokens separated by \",\"" , pattern = [ Predicate isNotLatent , regex "," , Predicate isNotLatent ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_) -> Token Time <$> intersect td1 td2 _ -> Nothing } ruleTwoTimeTokensSeparatedBy2 :: Rule ruleTwoTimeTokensSeparatedBy2 = Rule { name = "two time tokens separated by \",\"2" , pattern = [ Predicate isNotLatent , regex "," , Predicate isNotLatent ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_) -> Token Time <$> intersect td2 td1 _ -> Nothing } ruleMorning :: Rule ruleMorning = Rule { name = "morning" , pattern = [ regex "manh(\x00e3|a)" ] , prod = \_ -> let from = hour False 4 to = hour False 12 in Token Time . mkLatent . partOfDay <$> interval TTime.Open from to } ruleThisPartofday :: Rule ruleThisPartofday = Rule { name = "this <part-of-day>" , pattern = [ regex "es[ts]a" , Predicate isAPartOfDay ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> Token Time . partOfDay <$> intersect (cycleNth TG.Day 0) td _ -> Nothing } ruleThisTime :: Rule ruleThisTime = Rule { name = "this <time>" , pattern = [ regex "es[ts][ae]" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ predNth 0 False td _ -> Nothing } ruleProclamaoDaRepblica :: Rule ruleProclamaoDaRepblica = Rule { name = "Proclamação da República" , pattern = [ regex "proclama(c|\x00e7)(a|\x00e3)o da rep(\x00fa|u)blica" ] , prod = \_ -> tt $ monthDay 11 15 } ruleYearLatent :: Rule ruleYearLatent = Rule { name = "year (latent)" , pattern = [ Predicate $ isIntegerBetween (- 10000) 999 ] , prod = \tokens -> case tokens of (token:_) -> do n <- getIntValue token tt . mkLatent $ year n _ -> Nothing } ruleYesterday :: Rule ruleYesterday = Rule { name = "yesterday" , pattern = [ regex "ontem" ] , prod = \_ -> tt . cycleNth TG.Day $ - 1 } ruleSeason2 :: Rule ruleSeason2 = Rule { name = "season" , pattern = [ regex "outono" ] , prod = \_ -> let from = monthDay 9 23 to = monthDay 12 21 in Token Time <$> interval TTime.Open from to } ruleDiaDoTrabalhador :: Rule ruleDiaDoTrabalhador = Rule { name = "Dia do trabalhador" , pattern = [ regex "dia do trabalh(o|ador)" ] , prod = \_ -> tt $ monthDay 5 1 } ruleNCycleAtras :: Rule ruleNCycleAtras = Rule { name = "n <cycle> atras" , pattern = [ Predicate $ isIntegerBetween 2 9999 , dimension TimeGrain , regex "atr(a|\x00e1)s" ] , prod = \tokens -> case tokens of (token:Token TimeGrain grain:_) -> do v <- getIntValue token tt $ cycleN True grain (- v) _ -> Nothing } ruleTimeofdayAmpm :: Rule ruleTimeofdayAmpm = Rule { name = "<time-of-day> am|pm" , pattern = [ Predicate isATimeOfDay , regex "([ap])\\.?m?\\.?" ] , prod = \tokens -> case tokens of (Token Time td:Token RegexMatch (GroupMatch (ap:_)):_) -> tt . timeOfDayAMPM td $ Text.toLower ap == "a" _ -> Nothing } ruleDayofmonthDeNamedmonth :: Rule ruleDayofmonthDeNamedmonth = Rule { name = "<day-of-month> de <named-month>" , pattern = [ Predicate isDOMInteger , regex "de|\\/" , Predicate isAMonth ] , prod = \tokens -> case tokens of (token:_:Token Time td:_) -> Token Time <$> intersectDOM td token _ -> Nothing } ruleEntreDatetimeEDatetimeInterval :: Rule ruleEntreDatetimeEDatetimeInterval = Rule { name = "entre <datetime> e <datetime> (interval)" , pattern = [ regex "entre" , dimension Time , regex "e" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td1:_:Token Time td2:_) -> Token Time <$> interval TTime.Open td1 td2 _ -> Nothing } ruleEntreDdEtDdMonthinterval :: Rule ruleEntreDdEtDdMonthinterval = Rule { name = "entre dd et dd <month>(interval)" , pattern = [ regex "entre" , regex "(0?[1-9]|[12]\\d|3[01])" , regex "e?" , regex "(0?[1-9]|[12]\\d|3[01])" , regex "de" , Predicate isAMonth ] , prod = \tokens -> case tokens of (_: Token RegexMatch (GroupMatch (d1:_)): _: Token RegexMatch (GroupMatch (d2:_)): _: Token Time td: _) -> do dd1 <- parseInt d1 dd2 <- parseInt d2 dom1 <- intersect (dayOfMonth dd1) td dom2 <- intersect (dayOfMonth dd2) td Token Time <$> interval TTime.Closed dom1 dom2 _ -> Nothing } ruleCyclePassado :: Rule ruleCyclePassado = Rule { name = "<cycle> passado" , pattern = [ dimension TimeGrain , regex "passad(a|o)s?" ] , prod = \tokens -> case tokens of (Token TimeGrain grain:_) -> tt . cycleNth grain $ - 1 _ -> Nothing } ruleNamedmonth5 :: Rule ruleNamedmonth5 = Rule { name = "named-month" , pattern = [ regex "maio|mai\\.?" ] , prod = \_ -> tt $ month 5 } ruleNamedday7 :: Rule ruleNamedday7 = Rule { name = "named-day" , pattern = [ regex "domingo|dom\\.?" ] , prod = \_ -> tt $ dayOfWeek 7 } ruleNossaSenhoraAparecida :: Rule ruleNossaSenhoraAparecida = Rule { name = "Nossa Senhora Aparecida" , pattern = [ regex "nossa senhora (aparecida)?" ] , prod = \_ -> tt $ monthDay 10 12 } ruleFinados :: Rule ruleFinados = Rule { name = "Finados" , pattern = [ regex "finados|dia dos mortos" ] , prod = \_ -> tt $ monthDay 11 2 } ruleYear :: Rule ruleYear = Rule { name = "year" , pattern = [ Predicate $ isIntegerBetween 1000 2100 ] , prod = \tokens -> case tokens of (token:_) -> do n <- getIntValue token tt $ year n _ -> Nothing } ruleNamedmonth10 :: Rule ruleNamedmonth10 = Rule { name = "named-month" , pattern = [ regex "outubro|out\\.?" ] , prod = \_ -> tt $ month 10 } ruleAntesDasTimeofday :: Rule ruleAntesDasTimeofday = Rule { name = "antes das <time-of-day>" , pattern = [ regex "(antes|at(e|\x00e9)|n(a|\x00e3)o mais que) (d?(o|a|\x00e0)s?)?" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ withDirection TTime.Before td _ -> Nothing } ruleNProximasCycle :: Rule ruleNProximasCycle = Rule { name = "n proximas <cycle>" , pattern = [ Predicate $ isIntegerBetween 2 9999 , regex "pr(\x00f3|o)xim(o|a)s?" , dimension TimeGrain ] , prod = \tokens -> case tokens of (token:_:Token TimeGrain grain:_) -> do v <- getIntValue token tt $ cycleN True grain v _ -> Nothing } ruleDdmmyyyy :: Rule ruleDdmmyyyy = Rule { name = "dd[/-.]mm[/-.]yyyy" , pattern = [ regex "(3[01]|[12]\\d|0?[1-9])[\\.\\/\\-](0?[1-9]|1[0-2])[\\.\\/\\-](\\d{2,4})" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (m1:m2:m3:_)):_) -> do y <- parseInt m3 m <- parseInt m2 d <- parseInt m1 tt $ yearMonthDay y m d _ -> Nothing } ruleNamedmonth11 :: Rule ruleNamedmonth11 = Rule { name = "named-month" , pattern = [ regex "novembro|nov\\.?" ] , prod = \_ -> tt $ month 11 } ruleIndependecia :: Rule ruleIndependecia = Rule { name = "Independecia" , pattern = [ regex "independ(\x00ea|e)ncia" ] , prod = \_ -> tt $ monthDay 9 7 } ruleNamedday3 :: Rule ruleNamedday3 = Rule { name = "named-day" , pattern = [ regex "quarta((\\s|\\-)feira)?|qua\\.?" ] , prod = \_ -> tt $ dayOfWeek 3 } ruleTomorrow :: Rule ruleTomorrow = Rule { name = "tomorrow" , pattern = [ regex "amanh(\x00e3|a)" ] , prod = \_ -> tt $ cycleNth TG.Day 1 } ruleNamedmonth9 :: Rule ruleNamedmonth9 = Rule { name = "named-month" , pattern = [ regex "setembro|set\\.?" ] , prod = \_ -> tt $ month 9 } ruleTimezone :: Rule ruleTimezone = Rule { name = "<time> timezone" , pattern = [ Predicate isATimeOfDay , regex "\\b(YEKT|YEKST|YAKT|YAKST|WITA|WIT|WIB|WGT|WGST|WFT|WET|WEST|WAT|WAST|VUT|VLAT|VLAST|VET|UZT|UYT|UYST|UTC|ULAT|TVT|TMT|TLT|TKT|TJT|TFT|TAHT|SST|SRT|SGT|SCT|SBT|SAST|SAMT|RET|PYT|PYST|PWT|PST|PONT|PMST|PMDT|PKT|PHT|PHOT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|NCT|MYT|MVT|MUT|MST|MSK|MSD|MMT|MHT|MDT|MAWT|MART|MAGT|MAGST|LINT|LHST|LHDT|KUYT|KST|KRAT|KRAST|KGT|JST|IST|IRST|IRKT|IRKST|IRDT|IOT|IDT|ICT|HOVT|HKT|GYT|GST|GMT|GILT|GFT|GET|GAMT|GALT|FNT|FKT|FKST|FJT|FJST|EST|EGT|EGST|EET|EEST|EDT|ECT|EAT|EAST|EASST|DAVT|ChST|CXT|CVT|CST|COT|CLT|CLST|CKT|CHAST|CHADT|CET|CEST|CDT|CCT|CAT|CAST|BTT|BST|BRT|BRST|BOT|BNT|AZT|AZST|AZOT|AZOST|AWST|AWDT|AST|ART|AQTT|ANAT|ANAST|AMT|AMST|ALMT|AKST|AKDT|AFT|AEST|AEDT|ADT|ACST|ACDT)\\b" ] , prod = \tokens -> case tokens of (Token Time td: Token RegexMatch (GroupMatch (tz:_)): _) -> Token Time <$> inTimezone tz td _ -> Nothing } rules :: [Rule] rules = [ ruleAfternoon , ruleAmanhPelaPartofday , ruleAnoNovo , ruleAntesDasTimeofday , ruleDatetimeDatetimeInterval , ruleDayOfMonthSt , ruleDayofmonthDeNamedmonth , ruleDayofweekSHourmin , ruleDdddMonthinterval , ruleDdmm , ruleDdmmyyyy , ruleDeDatetimeDatetimeInterval , ruleDeYear , ruleDentroDeDuration , ruleDepoisDasTimeofday , ruleDiaDayofmonthDeNamedmonth , ruleDiaDayofmonthNonOrdinal , ruleDiaDoTrabalhador , ruleDimTimeDaMadrugada , ruleDimTimeDaManha , ruleDimTimeDaTarde , ruleEmDuration , ruleEntreDatetimeEDatetimeInterval , ruleEntreDdEtDdMonthinterval , ruleEsteCycle , ruleEvening , ruleFazemDuration , ruleFinados , ruleHhhmmTimeofday , ruleHhmmMilitaryTimeofday , ruleHourofdayAndRelativeMinutes , ruleHourofdayAndRelativeMinutes2 , ruleHourofdayAndQuarter , ruleHourofdayAndThreeQuarter , ruleHourofdayAndHalf , ruleHourofdayIntegerAsRelativeMinutes , ruleHourofdayIntegerAsRelativeMinutes2 , ruleHourofdayQuarter , ruleHourofdayHalf , ruleHourofdayThreeQuarter , ruleInThePartofday , ruleIndependecia , ruleIntegerParaAsHourofdayAsRelativeMinutes , ruleIntegerParaAsHourofdayAsRelativeMinutes2 , ruleHalfParaAsHourofdayAsRelativeMinutes , ruleQuarterParaAsHourofdayAsRelativeMinutes , ruleThreeQuarterParaAsHourofdayAsRelativeMinutes , ruleIntersect , ruleIntersectByDaOrDe , ruleLastTime , ruleMidnight , ruleMorning , ruleNCycleAtras , ruleNCycleProximoqueVem , ruleNPassadosCycle , ruleNProximasCycle , ruleNamedday , ruleNamedday2 , ruleNamedday3 , ruleNamedday4 , ruleNamedday5 , ruleNamedday6 , ruleNamedday7 , ruleNamedmonth , ruleNamedmonth10 , ruleNamedmonth11 , ruleNamedmonth12 , ruleNamedmonth2 , ruleNamedmonth3 , ruleNamedmonth4 , ruleNamedmonth5 , ruleNamedmonth6 , ruleNamedmonth7 , ruleNamedmonth8 , ruleNamedmonth9 , ruleNamedmonthnameddayNext , ruleNamedmonthnameddayPast , ruleNaoDate , ruleNatal , ruleNextTime , ruleCycleQueVem , ruleProximoCycle , ruleNoon , ruleNossaSenhoraAparecida , ruleNow , ruleCycleAntesDeTime , ruleCyclePassado , rulePartofdayDessaSemana , rulePassadosNCycle , ruleProclamaoDaRepblica , ruleProximasNCycle , ruleRightNow , ruleSHourminTimeofday , ruleSHourmintimeofday , ruleSTimeofday , ruleSeason , ruleSeason2 , ruleSeason3 , ruleSeason4 , ruleTheDayAfterTomorrow , ruleTheDayBeforeYesterday , ruleThisPartofday , ruleThisTime , ruleThisnextDayofweek , ruleTimeofdayAmpm , ruleTimeofdayHoras , ruleTimeofdayLatent , ruleTimeofdayPartofday , ruleTiradentes , ruleTomorrow , ruleTwoTimeTokensSeparatedBy , ruleTwoTimeTokensSeparatedBy2 , ruleUltimoTime , ruleVesperaDeAnoNovo , ruleWeekend , ruleYear , ruleYearLatent , ruleYearLatent2 , ruleYesterday , ruleYyyymmdd , ruleTimezone ]
rfranek/duckling
Duckling/Time/PT/Rules.hs
bsd-3-clause
40,248
0
21
10,644
11,503
6,237
5,266
1,289
2
----------------------------------------------------------------------------- -- -- GHCi Interactive debugging commands -- -- Pepe Iborra (supported by Google SoC) 2006 -- -- ToDo: lots of violation of layering here. This module should -- decide whether it is above the GHC API (import GHC and nothing -- else) or below it. -- ----------------------------------------------------------------------------- module Debugger (pprintClosureCommand, showTerm, pprTypeAndContents) where import Linker import RtClosureInspect import GhcMonad import HscTypes import Id import Name import Var hiding ( varName ) import VarSet import UniqSupply import Type import Kind import GHC import Outputable import PprTyThing import MonadUtils import DynFlags import Exception import Control.Monad import Data.List import Data.Maybe import Data.IORef import GHC.Exts ------------------------------------- -- | The :print & friends commands ------------------------------------- pprintClosureCommand :: GhcMonad m => Bool -> Bool -> String -> m () pprintClosureCommand bindThings force str = do tythings <- (catMaybes . concat) `liftM` mapM (\w -> GHC.parseName w >>= mapM GHC.lookupName) (words str) let ids = [id | AnId id <- tythings] -- Obtain the terms and the recovered type information (subst, terms) <- mapAccumLM go emptyTvSubst ids -- Apply the substitutions obtained after recovering the types modifySession $ \hsc_env -> hsc_env{hsc_IC = substInteractiveContext (hsc_IC hsc_env) subst} -- Finally, print the Terms unqual <- GHC.getPrintUnqual docterms <- mapM showTerm terms dflags <- getDynFlags liftIO $ (printOutputForUser dflags unqual . vcat) (zipWith (\id docterm -> ppr id <+> char '=' <+> docterm) ids docterms) where -- Do the obtainTerm--bindSuspensions-computeSubstitution dance go :: GhcMonad m => TvSubst -> Id -> m (TvSubst, Term) go subst id = do let id' = id `setIdType` substTy subst (idType id) term_ <- GHC.obtainTermFromId maxBound force id' term <- tidyTermTyVars term_ term' <- if bindThings && False == isUnliftedTypeKind (termType term) then bindSuspensions term else return term -- Before leaving, we compare the type obtained to see if it's more specific -- Then, we extract a substitution, -- mapping the old tyvars to the reconstructed types. let reconstructed_type = termType term hsc_env <- getSession case (improveRTTIType hsc_env (idType id) (reconstructed_type)) of Nothing -> return (subst, term') Just subst' -> do { traceOptIf Opt_D_dump_rtti (fsep $ [text "RTTI Improvement for", ppr id, text "is the substitution:" , ppr subst']) ; return (subst `unionTvSubst` subst', term')} tidyTermTyVars :: GhcMonad m => Term -> m Term tidyTermTyVars t = withSession $ \hsc_env -> do let env_tvs = tyThingsTyVars $ ic_tythings $ hsc_IC hsc_env my_tvs = termTyVars t tvs = env_tvs `minusVarSet` my_tvs tyvarOccName = nameOccName . tyVarName tidyEnv = (initTidyOccEnv (map tyvarOccName (varSetElems tvs)) , env_tvs `intersectVarSet` my_tvs) return$ mapTermType (snd . tidyOpenType tidyEnv) t -- | Give names, and bind in the interactive environment, to all the suspensions -- included (inductively) in a term bindSuspensions :: GhcMonad m => Term -> m Term bindSuspensions t = do hsc_env <- getSession inScope <- GHC.getBindings let ictxt = hsc_IC hsc_env prefix = "_t" alreadyUsedNames = map (occNameString . nameOccName . getName) inScope availNames = map ((prefix++) . show) [(1::Int)..] \\ alreadyUsedNames availNames_var <- liftIO $ newIORef availNames (t', stuff) <- liftIO $ foldTerm (nameSuspensionsAndGetInfos availNames_var) t let (names, tys, hvals) = unzip3 stuff let ids = [ mkVanillaGlobal name ty | (name,ty) <- zip names tys] new_ic = extendInteractiveContext ictxt (map AnId ids) liftIO $ extendLinkEnv (zip names hvals) modifySession $ \_ -> hsc_env {hsc_IC = new_ic } return t' where -- Processing suspensions. Give names and recopilate info nameSuspensionsAndGetInfos :: IORef [String] -> TermFold (IO (Term, [(Name,Type,HValue)])) nameSuspensionsAndGetInfos freeNames = TermFold { fSuspension = doSuspension freeNames , fTerm = \ty dc v tt -> do tt' <- sequence tt let (terms,names) = unzip tt' return (Term ty dc v terms, concat names) , fPrim = \ty n ->return (Prim ty n,[]) , fNewtypeWrap = \ty dc t -> do (term, names) <- t return (NewtypeWrap ty dc term, names) , fRefWrap = \ty t -> do (term, names) <- t return (RefWrap ty term, names) } doSuspension freeNames ct ty hval _name = do name <- atomicModifyIORef freeNames (\x->(tail x, head x)) n <- newGrimName name return (Suspension ct ty hval (Just n), [(n,ty,hval)]) -- A custom Term printer to enable the use of Show instances showTerm :: GhcMonad m => Term -> m SDoc showTerm term = do dflags <- GHC.getSessionDynFlags if gopt Opt_PrintEvldWithShow dflags then cPprTerm (liftM2 (++) (\_y->[cPprShowable]) cPprTermBase) term else cPprTerm cPprTermBase term where cPprShowable prec t@Term{ty=ty, val=val} = if not (isFullyEvaluatedTerm t) then return Nothing else do hsc_env <- getSession dflags <- GHC.getSessionDynFlags do (new_env, bname) <- bindToFreshName hsc_env ty "showme" setSession new_env -- XXX: this tries to disable logging of errors -- does this still do what it is intended to do -- with the changed error handling and logging? let noop_log _ _ _ _ _ = return () expr = "show " ++ showPpr dflags bname _ <- GHC.setSessionDynFlags dflags{log_action=noop_log} txt_ <- withExtendedLinkEnv [(bname, val)] (GHC.compileExpr expr) let myprec = 10 -- application precedence. TODO Infix constructors let txt = unsafeCoerce# txt_ if not (null txt) then return $ Just $ cparen (prec >= myprec && needsParens txt) (text txt) else return Nothing `gfinally` do setSession hsc_env GHC.setSessionDynFlags dflags cPprShowable prec NewtypeWrap{ty=new_ty,wrapped_term=t} = cPprShowable prec t{ty=new_ty} cPprShowable _ _ = return Nothing needsParens ('"':_) = False -- some simple heuristics to see whether parens -- are redundant in an arbitrary Show output needsParens ('(':_) = False needsParens txt = ' ' `elem` txt bindToFreshName hsc_env ty userName = do name <- newGrimName userName let id = AnId $ mkVanillaGlobal name ty new_ic = extendInteractiveContext (hsc_IC hsc_env) [id] return (hsc_env {hsc_IC = new_ic }, name) -- Create new uniques and give them sequentially numbered names newGrimName :: MonadIO m => String -> m Name newGrimName userName = do us <- liftIO $ mkSplitUniqSupply 'b' let unique = uniqFromSupply us occname = mkOccName varName userName name = mkInternalName unique occname noSrcSpan return name pprTypeAndContents :: GhcMonad m => Id -> m SDoc pprTypeAndContents id = do dflags <- GHC.getSessionDynFlags let pefas = gopt Opt_PrintExplicitForalls dflags pcontents = gopt Opt_PrintBindContents dflags pprdId = (PprTyThing.pprTyThing pefas . AnId) id if pcontents then do let depthBound = 100 -- If the value is an exception, make sure we catch it and -- show the exception, rather than propagating the exception out. e_term <- gtry $ GHC.obtainTermFromId depthBound False id docs_term <- case e_term of Right term -> showTerm term Left exn -> return (text "*** Exception:" <+> text (show (exn :: SomeException))) return $ pprdId <+> equals <+> docs_term else return pprdId -------------------------------------------------------------- -- Utils traceOptIf :: GhcMonad m => DumpFlag -> SDoc -> m () traceOptIf flag doc = do dflags <- GHC.getSessionDynFlags when (dopt flag dflags) $ liftIO $ printInfoForUser dflags alwaysQualify doc
ekmett/ghc
compiler/ghci/Debugger.hs
bsd-3-clause
9,338
7
21
2,986
2,288
1,168
1,120
171
8
{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleInstances, UndecidableInstances, Rank2Types #-} module Control.Monad.Launcher ( Launcher , setVersion, checkVersion , withThreadIdDo, putThreadId, clunkTag , withFileDo, withoutFileDo, putFile, clunkFile ) where import Control.Concurrent (ThreadId) import Control.Monad.Except(throwError) import Control.Monad.State(get, put, modify) import Data.Word (Word16, Word32) import System.IO (Handle) import qualified Data.Map as M import Data.Accessor import Data.Accessor.Tuple import Control.Concurrent.MState (MState) import Network.NineP.Server.File.Internal import Network.NineP.Server.Error import Network.NineP.Server.Utils import qualified Network.NineP.Binary as B type LauncherState s = (Maybe String, M.Map Word32 (File' s), M.Map Word16 ThreadId) type Launcher s a = MState (LauncherState s) (NineP s) a setVersion :: Handle -> Word16 -> Word32 -> Launcher s (Maybe String) -> Launcher s () setVersion h tag sz f = do mver <- f case mver of Nothing -> sendRMsg h tag $ B.Rversion sz "unknown" Just ver -> do put (mver, M.empty, M.empty) sendRMsg h tag $ B.Rversion sz ver checkVersion :: Launcher s () -> Launcher s () checkVersion f = do (ver, _, _) <- get if (ver == Nothing) then throwError ErrProto else f withThreadIdDo :: Word16 -> (ThreadId -> Launcher s ()) -> Launcher s () withThreadIdDo tag f = do (_, _, mp) <- get case M.lookup tag mp of Just tid -> f tid Nothing -> throwError ErrProto putThreadId :: Word16 -> ThreadId -> Launcher s () putThreadId tag tid = modify $ third3 ^: M.insert tag tid clunkTag :: Word16 -> Launcher s () clunkTag tag = modify $ third3 ^: M.delete tag withFileDo :: Word32 -> (File' s -> Launcher s ()) -> Launcher s () withFileDo fid f = do (_, mp, _) <- get case M.lookup fid mp of Just file -> f file Nothing -> throwError ErrFidUnknown withoutFileDo :: Word32 -> (Launcher s ()) -> Launcher s () withoutFileDo fid f = do (_, mp, _) <- get case M.lookup fid mp of Just _ -> throwError ErrFidInUse Nothing -> f putFile :: Word32 -> File' s -> Launcher s () putFile fid file = modify $ second3 ^: M.insert fid file clunkFile :: Word32 -> Launcher s () clunkFile fid = modify $ second3 ^: M.delete fid
Elemir/network-ninep
src/Control/Monad/Launcher.hs
bsd-3-clause
2,446
0
14
564
881
461
420
75
2
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE MagicHash #-} module Blip.Interpreter.HashTable.IntArray ( IntArray , Elem , elemMask , primWordToElem , elemToInt , elemToInt# , newArray , readArray , writeArray , length , toPtr ) where ------------------------------------------------------------------------------ -- import Control.Monad.ST import Data.Bits import qualified Data.Primitive.ByteArray as A -- import Data.Primitive.Types (Addr (..)) import GHC.Exts import GHC.Word import Data.Word (Word8) import Prelude hiding (length) -- import Control.Monad.Primitive (RealWorld) ------------------------------------------------------------------------------ #ifdef BOUNDS_CHECKING #define BOUNDS_MSG(sz,i) concat [ "[", __FILE__, ":", \ show (__LINE__ :: Int), \ "] bounds check exceeded: ", \ "size was ", show (sz), " i was ", show (i) ] #define BOUNDS_CHECK(arr,i) let sz = (A.sizeofMutableByteArray (arr) \ `div` wordSizeInBytes) in \ if (i) < 0 || (i) >= sz \ then error (BOUNDS_MSG(sz,(i))) \ else return () #else #define BOUNDS_CHECK(arr,i) #endif ------------------------------------------------------------------------------ newtype IntArray = IA (A.MutableByteArray RealWorld) type Elem = Word16 ------------------------------------------------------------------------------ primWordToElem :: Word# -> Elem primWordToElem = W16# ------------------------------------------------------------------------------ elemToInt :: Elem -> Int elemToInt e = let !i# = elemToInt# e in (I# i#) ------------------------------------------------------------------------------ elemToInt# :: Elem -> Int# elemToInt# (W16# w#) = word2Int# w# ------------------------------------------------------------------------------ elemMask :: Int elemMask = 0xffff ------------------------------------------------------------------------------ wordSizeInBytes :: Int wordSizeInBytes = bitSize (0::Elem) `div` 8 ------------------------------------------------------------------------------ -- | Cache line size, in bytes cacheLineSize :: Int cacheLineSize = 64 ------------------------------------------------------------------------------ newArray :: Int -> IO IntArray newArray n = do let !sz = n * wordSizeInBytes !arr <- A.newAlignedPinnedByteArray sz cacheLineSize A.fillByteArray arr 0 sz 0 return $! IA arr ------------------------------------------------------------------------------ readArray :: IntArray -> Int -> IO Elem readArray (IA a) idx = do BOUNDS_CHECK(a,idx) A.readByteArray a idx ------------------------------------------------------------------------------ writeArray :: IntArray -> Int -> Elem -> IO () writeArray (IA a) idx val = do BOUNDS_CHECK(a,idx) A.writeByteArray a idx val ------------------------------------------------------------------------------ length :: IntArray -> Int length (IA a) = A.sizeofMutableByteArray a `div` wordSizeInBytes ------------------------------------------------------------------------------ toPtr :: IntArray -> Ptr Word8 toPtr (IA a) = A.mutableByteArrayContents a {- toPtr (IA a) = Ptr a# where !(Addr !a#) = A.mutableByteArrayContents a -}
bjpop/blip
blipinterpreter/src/Blip/Interpreter/HashTable/IntArray.hs
bsd-3-clause
3,680
0
10
901
516
285
231
54
1
{-| Module : Idris.IBC Description : Core representations and code to generate IBC files. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.IBC (loadIBC, loadPkgIndex, writeIBC, writePkgIndex, hasValidIBCVersion, IBCPhase(..)) where import Idris.AbsSyntax import Idris.Core.Binary import Idris.Core.CaseTree import Idris.Core.Evaluate import Idris.Core.TT import Idris.DeepSeq import Idris.Delaborate import Idris.Docstrings (Docstring) import qualified Idris.Docstrings as D import Idris.Error import Idris.Imports import Idris.Options import Idris.Output import IRTS.System (getIdrisLibDir) import Paths_idris import qualified Cheapskate.Types as CT import Codec.Archive.Zip import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict hiding (get, put) import qualified Control.Monad.State.Strict as ST import Data.Binary import Data.ByteString.Lazy as B hiding (elem, length, map) import Data.Functor import Data.List as L import Data.Maybe (catMaybes) import qualified Data.Set as S import qualified Data.Text as T import Data.Vector.Binary import Debug.Trace import System.Directory import System.FilePath ibcVersion :: Word16 ibcVersion = 162 -- | When IBC is being loaded - we'll load different things (and omit -- different structures/definitions) depending on which phase we're in. data IBCPhase = IBC_Building -- ^ when building the module tree | IBC_REPL Bool -- ^ when loading modules for the REPL Bool = True for top level module deriving (Show, Eq) data IBCFile = IBCFile { ver :: Word16 , sourcefile :: FilePath , ibc_reachablenames :: ![Name] , ibc_imports :: ![(Bool, FilePath)] , ibc_importdirs :: ![FilePath] , ibc_sourcedirs :: ![FilePath] , ibc_implicits :: ![(Name, [PArg])] , ibc_fixes :: ![FixDecl] , ibc_statics :: ![(Name, [Bool])] , ibc_interfaces :: ![(Name, InterfaceInfo)] , ibc_records :: ![(Name, RecordInfo)] , ibc_implementations :: ![(Bool, Bool, Name, Name)] , ibc_dsls :: ![(Name, DSL)] , ibc_datatypes :: ![(Name, TypeInfo)] , ibc_optimise :: ![(Name, OptInfo)] , ibc_syntax :: ![Syntax] , ibc_keywords :: ![String] , ibc_objs :: ![(Codegen, FilePath)] , ibc_libs :: ![(Codegen, String)] , ibc_cgflags :: ![(Codegen, String)] , ibc_dynamic_libs :: ![String] , ibc_hdrs :: ![(Codegen, String)] , ibc_totcheckfail :: ![(FC, String)] , ibc_flags :: ![(Name, [FnOpt])] , ibc_fninfo :: ![(Name, FnInfo)] , ibc_cg :: ![(Name, CGInfo)] , ibc_docstrings :: ![(Name, (Docstring D.DocTerm, [(Name, Docstring D.DocTerm)]))] , ibc_moduledocs :: ![(Name, Docstring D.DocTerm)] , ibc_transforms :: ![(Name, (Term, Term))] , ibc_errRev :: ![(Term, Term)] , ibc_errReduce :: ![Name] , ibc_coercions :: ![Name] , ibc_lineapps :: ![(FilePath, Int, PTerm)] , ibc_namehints :: ![(Name, Name)] , ibc_metainformation :: ![(Name, MetaInformation)] , ibc_errorhandlers :: ![Name] , ibc_function_errorhandlers :: ![(Name, Name, Name)] -- fn, arg, handler , ibc_metavars :: ![(Name, (Maybe Name, Int, [Name], Bool, Bool))] , ibc_patdefs :: ![(Name, ([([(Name, Term)], Term, Term)], [PTerm]))] , ibc_postulates :: ![Name] , ibc_externs :: ![(Name, Int)] , ibc_parsedSpan :: !(Maybe FC) , ibc_usage :: ![(Name, Int)] , ibc_exports :: ![Name] , ibc_autohints :: ![(Name, Name)] , ibc_deprecated :: ![(Name, String)] , ibc_defs :: ![(Name, Def)] , ibc_total :: ![(Name, Totality)] , ibc_injective :: ![(Name, Injectivity)] , ibc_access :: ![(Name, Accessibility)] , ibc_fragile :: ![(Name, String)] , ibc_constraints :: ![(FC, UConstraint)] } deriving Show {-! deriving instance Binary IBCFile !-} initIBC :: IBCFile initIBC = IBCFile ibcVersion "" [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] Nothing [] [] [] [] [] [] [] [] [] [] hasValidIBCVersion :: FilePath -> Idris Bool hasValidIBCVersion fp = do archiveFile <- runIO $ B.readFile fp case toArchiveOrFail archiveFile of Left _ -> return False Right archive -> do ver <- getEntry 0 "ver" archive return (ver == ibcVersion) loadIBC :: Bool -- ^ True = reexport, False = make everything private -> IBCPhase -> FilePath -> Idris () loadIBC reexport phase fp = do imps <- getImported case lookup fp imps of Nothing -> load True Just p -> if (not p && reexport) then load False else return () where load fullLoad = do logIBC 1 $ "Loading ibc " ++ fp ++ " " ++ show reexport archiveFile <- runIO $ B.readFile fp case toArchiveOrFail archiveFile of Left _ -> do ifail $ fp ++ " isn't loadable, it may have an old ibc format.\n" ++ "Please clean and rebuild it." Right archive -> do if fullLoad then process reexport phase archive fp else unhide phase fp archive addImported reexport fp -- | Load an entire package from its index file loadPkgIndex :: String -> Idris () loadPkgIndex pkg = do ddir <- runIO getIdrisLibDir addImportDir (ddir </> pkg) fp <- findPkgIndex pkg loadIBC True IBC_Building fp makeEntry :: (Binary b) => String -> [b] -> Maybe Entry makeEntry name val = if L.null val then Nothing else Just $ toEntry name 0 (encode val) entries :: IBCFile -> [Entry] entries i = catMaybes [Just $ toEntry "ver" 0 (encode $ ver i), makeEntry "sourcefile" (sourcefile i), makeEntry "ibc_imports" (ibc_imports i), makeEntry "ibc_importdirs" (ibc_importdirs i), makeEntry "ibc_sourcedirs" (ibc_sourcedirs i), makeEntry "ibc_implicits" (ibc_implicits i), makeEntry "ibc_fixes" (ibc_fixes i), makeEntry "ibc_statics" (ibc_statics i), makeEntry "ibc_interfaces" (ibc_interfaces i), makeEntry "ibc_records" (ibc_records i), makeEntry "ibc_implementations" (ibc_implementations i), makeEntry "ibc_dsls" (ibc_dsls i), makeEntry "ibc_datatypes" (ibc_datatypes i), makeEntry "ibc_optimise" (ibc_optimise i), makeEntry "ibc_syntax" (ibc_syntax i), makeEntry "ibc_keywords" (ibc_keywords i), makeEntry "ibc_objs" (ibc_objs i), makeEntry "ibc_libs" (ibc_libs i), makeEntry "ibc_cgflags" (ibc_cgflags i), makeEntry "ibc_dynamic_libs" (ibc_dynamic_libs i), makeEntry "ibc_hdrs" (ibc_hdrs i), makeEntry "ibc_totcheckfail" (ibc_totcheckfail i), makeEntry "ibc_flags" (ibc_flags i), makeEntry "ibc_fninfo" (ibc_fninfo i), makeEntry "ibc_cg" (ibc_cg i), makeEntry "ibc_docstrings" (ibc_docstrings i), makeEntry "ibc_moduledocs" (ibc_moduledocs i), makeEntry "ibc_transforms" (ibc_transforms i), makeEntry "ibc_errRev" (ibc_errRev i), makeEntry "ibc_errReduce" (ibc_errReduce i), makeEntry "ibc_coercions" (ibc_coercions i), makeEntry "ibc_lineapps" (ibc_lineapps i), makeEntry "ibc_namehints" (ibc_namehints i), makeEntry "ibc_metainformation" (ibc_metainformation i), makeEntry "ibc_errorhandlers" (ibc_errorhandlers i), makeEntry "ibc_function_errorhandlers" (ibc_function_errorhandlers i), makeEntry "ibc_metavars" (ibc_metavars i), makeEntry "ibc_patdefs" (ibc_patdefs i), makeEntry "ibc_postulates" (ibc_postulates i), makeEntry "ibc_externs" (ibc_externs i), toEntry "ibc_parsedSpan" 0 . encode <$> ibc_parsedSpan i, makeEntry "ibc_usage" (ibc_usage i), makeEntry "ibc_exports" (ibc_exports i), makeEntry "ibc_autohints" (ibc_autohints i), makeEntry "ibc_deprecated" (ibc_deprecated i), makeEntry "ibc_defs" (ibc_defs i), makeEntry "ibc_total" (ibc_total i), makeEntry "ibc_injective" (ibc_injective i), makeEntry "ibc_access" (ibc_access i), makeEntry "ibc_fragile" (ibc_fragile i)] -- TODO: Put this back in shortly after minimising/pruning constraints -- makeEntry "ibc_constraints" (ibc_constraints i)] writeArchive :: FilePath -> IBCFile -> Idris () writeArchive fp i = do let a = L.foldl (\x y -> addEntryToArchive y x) emptyArchive (entries i) runIO $ B.writeFile fp (fromArchive a) writeIBC :: FilePath -> FilePath -> Idris () writeIBC src f = do logIBC 2 $ "Writing IBC for: " ++ show f iReport 2 $ "Writing IBC for: " ++ show f i <- getIState -- case (Data.List.map fst (idris_metavars i)) \\ primDefs of -- (_:_) -> ifail "Can't write ibc when there are unsolved metavariables" -- [] -> return () resetNameIdx ibcf <- mkIBC (ibc_write i) (initIBC { sourcefile = src }) idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f) writeArchive f ibcf logIBC 2 "Written") (\c -> do logIBC 2 $ "Failed " ++ pshow i c) return () -- | Write a package index containing all the imports in the current -- IState Used for ':search' of an entire package, to ensure -- everything is loaded. writePkgIndex :: FilePath -> Idris () writePkgIndex f = do i <- getIState let imps = map (\ (x, y) -> (True, x)) $ idris_imported i logIBC 2 $ "Writing package index " ++ show f ++ " including\n" ++ show (map snd imps) resetNameIdx let ibcf = initIBC { ibc_imports = imps } idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f) writeArchive f ibcf logIBC 2 "Written") (\c -> do logIBC 2 $ "Failed " ++ pshow i c) return () mkIBC :: [IBCWrite] -> IBCFile -> Idris IBCFile mkIBC [] f = return f mkIBC (i:is) f = do ist <- getIState logIBC 5 $ show i ++ " " ++ show (L.length is) f' <- ibc ist i f mkIBC is f' ibc :: IState -> IBCWrite -> IBCFile -> Idris IBCFile ibc i (IBCFix d) f = return f { ibc_fixes = d : ibc_fixes f } ibc i (IBCImp n) f = case lookupCtxtExact n (idris_implicits i) of Just v -> return f { ibc_implicits = (n,v): ibc_implicits f } _ -> ifail "IBC write failed" ibc i (IBCStatic n) f = case lookupCtxtExact n (idris_statics i) of Just v -> return f { ibc_statics = (n,v): ibc_statics f } _ -> ifail "IBC write failed" ibc i (IBCInterface n) f = case lookupCtxtExact n (idris_interfaces i) of Just v -> return f { ibc_interfaces = (n,v): ibc_interfaces f } _ -> ifail "IBC write failed" ibc i (IBCRecord n) f = case lookupCtxtExact n (idris_records i) of Just v -> return f { ibc_records = (n,v): ibc_records f } _ -> ifail "IBC write failed" ibc i (IBCImplementation int res n ins) f = return f { ibc_implementations = (int, res, n, ins) : ibc_implementations f } ibc i (IBCDSL n) f = case lookupCtxtExact n (idris_dsls i) of Just v -> return f { ibc_dsls = (n,v): ibc_dsls f } _ -> ifail "IBC write failed" ibc i (IBCData n) f = case lookupCtxtExact n (idris_datatypes i) of Just v -> return f { ibc_datatypes = (n,v): ibc_datatypes f } _ -> ifail "IBC write failed" ibc i (IBCOpt n) f = case lookupCtxtExact n (idris_optimisation i) of Just v -> return f { ibc_optimise = (n,v): ibc_optimise f } _ -> ifail "IBC write failed" ibc i (IBCSyntax n) f = return f { ibc_syntax = n : ibc_syntax f } ibc i (IBCKeyword n) f = return f { ibc_keywords = n : ibc_keywords f } ibc i (IBCImport n) f = return f { ibc_imports = n : ibc_imports f } ibc i (IBCImportDir n) f = return f { ibc_importdirs = n : ibc_importdirs f } ibc i (IBCSourceDir n) f = return f { ibc_sourcedirs = n : ibc_sourcedirs f } ibc i (IBCObj tgt n) f = return f { ibc_objs = (tgt, n) : ibc_objs f } ibc i (IBCLib tgt n) f = return f { ibc_libs = (tgt, n) : ibc_libs f } ibc i (IBCCGFlag tgt n) f = return f { ibc_cgflags = (tgt, n) : ibc_cgflags f } ibc i (IBCDyLib n) f = return f {ibc_dynamic_libs = n : ibc_dynamic_libs f } ibc i (IBCHeader tgt n) f = return f { ibc_hdrs = (tgt, n) : ibc_hdrs f } ibc i (IBCDef n) f = do f' <- case lookupDefExact n (tt_ctxt i) of Just v -> return f { ibc_defs = (n,v) : ibc_defs f } _ -> ifail "IBC write failed" case lookupCtxtExact n (idris_patdefs i) of Just v -> return f' { ibc_patdefs = (n,v) : ibc_patdefs f } _ -> return f' -- Not a pattern definition ibc i (IBCDoc n) f = case lookupCtxtExact n (idris_docstrings i) of Just v -> return f { ibc_docstrings = (n,v) : ibc_docstrings f } _ -> ifail "IBC write failed" ibc i (IBCCG n) f = case lookupCtxtExact n (idris_callgraph i) of Just v -> return f { ibc_cg = (n,v) : ibc_cg f } _ -> ifail "IBC write failed" ibc i (IBCCoercion n) f = return f { ibc_coercions = n : ibc_coercions f } ibc i (IBCAccess n a) f = return f { ibc_access = (n,a) : ibc_access f } ibc i (IBCFlags n) f = case lookupCtxtExact n (idris_flags i) of Just a -> return f { ibc_flags = (n,a): ibc_flags f } _ -> ifail "IBC write failed" ibc i (IBCFnInfo n a) f = return f { ibc_fninfo = (n,a) : ibc_fninfo f } ibc i (IBCTotal n a) f = return f { ibc_total = (n,a) : ibc_total f } ibc i (IBCInjective n a) f = return f { ibc_injective = (n,a) : ibc_injective f } ibc i (IBCTrans n t) f = return f { ibc_transforms = (n, t) : ibc_transforms f } ibc i (IBCErrRev t) f = return f { ibc_errRev = t : ibc_errRev f } ibc i (IBCErrReduce t) f = return f { ibc_errReduce = t : ibc_errReduce f } ibc i (IBCLineApp fp l t) f = return f { ibc_lineapps = (fp,l,t) : ibc_lineapps f } ibc i (IBCNameHint (n, ty)) f = return f { ibc_namehints = (n, ty) : ibc_namehints f } ibc i (IBCMetaInformation n m) f = return f { ibc_metainformation = (n,m) : ibc_metainformation f } ibc i (IBCErrorHandler n) f = return f { ibc_errorhandlers = n : ibc_errorhandlers f } ibc i (IBCFunctionErrorHandler fn a n) f = return f { ibc_function_errorhandlers = (fn, a, n) : ibc_function_errorhandlers f } ibc i (IBCMetavar n) f = case lookup n (idris_metavars i) of Nothing -> return f Just t -> return f { ibc_metavars = (n, t) : ibc_metavars f } ibc i (IBCPostulate n) f = return f { ibc_postulates = n : ibc_postulates f } ibc i (IBCExtern n) f = return f { ibc_externs = n : ibc_externs f } ibc i (IBCTotCheckErr fc err) f = return f { ibc_totcheckfail = (fc, err) : ibc_totcheckfail f } ibc i (IBCParsedRegion fc) f = return f { ibc_parsedSpan = Just fc } ibc i (IBCModDocs n) f = case lookupCtxtExact n (idris_moduledocs i) of Just v -> return f { ibc_moduledocs = (n,v) : ibc_moduledocs f } _ -> ifail "IBC write failed" ibc i (IBCUsage n) f = return f { ibc_usage = n : ibc_usage f } ibc i (IBCExport n) f = return f { ibc_exports = n : ibc_exports f } ibc i (IBCAutoHint n h) f = return f { ibc_autohints = (n, h) : ibc_autohints f } ibc i (IBCDeprecate n r) f = return f { ibc_deprecated = (n, r) : ibc_deprecated f } ibc i (IBCFragile n r) f = return f { ibc_fragile = (n,r) : ibc_fragile f } ibc i (IBCConstraint fc u) f = return f { ibc_constraints = (fc, u) : ibc_constraints f } getEntry :: (Binary b, NFData b) => b -> FilePath -> Archive -> Idris b getEntry alt f a = case findEntryByPath f a of Nothing -> return alt Just e -> return $! (force . decode . fromEntry) e unhide :: IBCPhase -> FilePath -> Archive -> Idris () unhide phase fp ar = do processImports True phase fp ar processAccess True phase ar process :: Bool -- ^ Reexporting -> IBCPhase -> Archive -> FilePath -> Idris () process reexp phase archive fn = do ver <- getEntry 0 "ver" archive when (ver /= ibcVersion) $ do logIBC 2 "ibc out of date" let e = if ver < ibcVersion then "an earlier" else "a later" ldir <- runIO $ getIdrisLibDir let start = if ldir `L.isPrefixOf` fn then "This external module" else "This module" let end = case L.stripPrefix ldir fn of Nothing -> "Please clean and rebuild." Just ploc -> unwords ["Please reinstall:", L.head $ splitDirectories ploc] ifail $ unlines [ unwords ["Incompatible ibc version for:", show fn] , unwords [start , "was built with" , e , "version of Idris."] , end ] source <- getEntry "" "sourcefile" archive srcok <- runIO $ doesFileExist source when srcok $ timestampOlder source fn processImportDirs archive processSourceDirs archive processImports reexp phase fn archive processImplicits archive processInfix archive processStatics archive processInterfaces archive processRecords archive processImplementations archive processDSLs archive processDatatypes archive processOptimise archive processSyntax archive processKeywords archive processObjectFiles fn archive processLibs archive processCodegenFlags archive processDynamicLibs archive processHeaders archive processPatternDefs archive processFlags archive processFnInfo archive processTotalityCheckError archive processCallgraph archive processDocs archive processModuleDocs archive processCoercions archive processTransforms archive processErrRev archive processErrReduce archive processLineApps archive processNameHints archive processMetaInformation archive processErrorHandlers archive processFunctionErrorHandlers archive processMetaVars archive processPostulates archive processExterns archive processParsedSpan archive processUsage archive processExports archive processAutoHints archive processDeprecate archive processDefs archive processTotal archive processInjective archive processAccess reexp phase archive processFragile archive processConstraints archive timestampOlder :: FilePath -> FilePath -> Idris () timestampOlder src ibc = do srct <- runIO $ getModificationTime src ibct <- runIO $ getModificationTime ibc if (srct > ibct) then ifail $ unlines [ "Module needs reloading:" , unwords ["\tSRC :", show src] , unwords ["\tModified at:", show srct] , unwords ["\tIBC :", show ibc] , unwords ["\tModified at:", show ibct] ] else return () processPostulates :: Archive -> Idris () processPostulates ar = do ns <- getEntry [] "ibc_postulates" ar updateIState (\i -> i { idris_postulates = idris_postulates i `S.union` S.fromList ns }) processExterns :: Archive -> Idris () processExterns ar = do ns <- getEntry [] "ibc_externs" ar updateIState (\i -> i{ idris_externs = idris_externs i `S.union` S.fromList ns }) processParsedSpan :: Archive -> Idris () processParsedSpan ar = do fc <- getEntry Nothing "ibc_parsedSpan" ar updateIState (\i -> i { idris_parsedSpan = fc }) processUsage :: Archive -> Idris () processUsage ar = do ns <- getEntry [] "ibc_usage" ar updateIState (\i -> i { idris_erasureUsed = ns ++ idris_erasureUsed i }) processExports :: Archive -> Idris () processExports ar = do ns <- getEntry [] "ibc_exports" ar updateIState (\i -> i { idris_exports = ns ++ idris_exports i }) processAutoHints :: Archive -> Idris () processAutoHints ar = do ns <- getEntry [] "ibc_autohints" ar mapM_ (\(n,h) -> addAutoHint n h) ns processDeprecate :: Archive -> Idris () processDeprecate ar = do ns <- getEntry [] "ibc_deprecated" ar mapM_ (\(n,reason) -> addDeprecated n reason) ns processFragile :: Archive -> Idris () processFragile ar = do ns <- getEntry [] "ibc_fragile" ar mapM_ (\(n,reason) -> addFragile n reason) ns processConstraints :: Archive -> Idris () processConstraints ar = do cs <- getEntry [] "ibc_constraints" ar mapM_ (\ (fc, c) -> addConstraints fc (0, [c])) cs processImportDirs :: Archive -> Idris () processImportDirs ar = do fs <- getEntry [] "ibc_importdirs" ar mapM_ addImportDir fs processSourceDirs :: Archive -> Idris () processSourceDirs ar = do fs <- getEntry [] "ibc_sourcedirs" ar mapM_ addSourceDir fs processImports :: Bool -> IBCPhase -> FilePath -> Archive -> Idris () processImports reexp phase fname ar = do fs <- getEntry [] "ibc_imports" ar mapM_ (\(re, f) -> do i <- getIState ibcsd <- valIBCSubDir i ids <- rankedImportDirs fname putIState (i { imported = f : imported i }) let phase' = case phase of IBC_REPL _ -> IBC_REPL False p -> p fp <- findIBC ids ibcsd f case fp of Nothing -> do logIBC 2 $ "Failed to load ibc " ++ f Just fn -> do loadIBC (reexp && re) phase' fn) fs processImplicits :: Archive -> Idris () processImplicits ar = do imps <- getEntry [] "ibc_implicits" ar mapM_ (\ (n, imp) -> do i <- getIState case lookupDefAccExact n False (tt_ctxt i) of Just (n, Hidden) -> return () Just (n, Private) -> return () _ -> putIState (i { idris_implicits = addDef n imp (idris_implicits i) })) imps processInfix :: Archive -> Idris () processInfix ar = do f <- getEntry [] "ibc_fixes" ar updateIState (\i -> i { idris_infixes = sort $ f ++ idris_infixes i }) processStatics :: Archive -> Idris () processStatics ar = do ss <- getEntry [] "ibc_statics" ar mapM_ (\ (n, s) -> updateIState (\i -> i { idris_statics = addDef n s (idris_statics i) })) ss processInterfaces :: Archive -> Idris () processInterfaces ar = do cs <- getEntry [] "ibc_interfaces" ar mapM_ (\ (n, c) -> do i <- getIState -- Don't lose implementations from previous IBCs, which -- could have loaded in any order let is = case lookupCtxtExact n (idris_interfaces i) of Just ci -> interface_implementations ci _ -> [] let c' = c { interface_implementations = interface_implementations c ++ is } putIState (i { idris_interfaces = addDef n c' (idris_interfaces i) })) cs processRecords :: Archive -> Idris () processRecords ar = do rs <- getEntry [] "ibc_records" ar mapM_ (\ (n, r) -> updateIState (\i -> i { idris_records = addDef n r (idris_records i) })) rs processImplementations :: Archive -> Idris () processImplementations ar = do cs <- getEntry [] "ibc_implementations" ar mapM_ (\ (i, res, n, ins) -> addImplementation i res n ins) cs processDSLs :: Archive -> Idris () processDSLs ar = do cs <- getEntry [] "ibc_dsls" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_dsls = addDef n c (idris_dsls i) })) cs processDatatypes :: Archive -> Idris () processDatatypes ar = do cs <- getEntry [] "ibc_datatypes" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_datatypes = addDef n c (idris_datatypes i) })) cs processOptimise :: Archive -> Idris () processOptimise ar = do cs <- getEntry [] "ibc_optimise" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_optimisation = addDef n c (idris_optimisation i) })) cs processSyntax :: Archive -> Idris () processSyntax ar = do s <- getEntry [] "ibc_syntax" ar updateIState (\i -> i { syntax_rules = updateSyntaxRules s (syntax_rules i) }) processKeywords :: Archive -> Idris () processKeywords ar = do k <- getEntry [] "ibc_keywords" ar updateIState (\i -> i { syntax_keywords = k ++ syntax_keywords i }) processObjectFiles :: FilePath -> Archive -> Idris () processObjectFiles fn ar = do os <- getEntry [] "ibc_objs" ar mapM_ (\ (cg, obj) -> do dirs <- rankedImportDirs fn o <- runIO $ findInPath dirs obj addObjectFile cg o) os processLibs :: Archive -> Idris () processLibs ar = do ls <- getEntry [] "ibc_libs" ar mapM_ (uncurry addLib) ls processCodegenFlags :: Archive -> Idris () processCodegenFlags ar = do ls <- getEntry [] "ibc_cgflags" ar mapM_ (uncurry addFlag) ls processDynamicLibs :: Archive -> Idris () processDynamicLibs ar = do ls <- getEntry [] "ibc_dynamic_libs" ar res <- mapM (addDyLib . return) ls mapM_ checkLoad res where checkLoad (Left _) = return () checkLoad (Right err) = ifail err processHeaders :: Archive -> Idris () processHeaders ar = do hs <- getEntry [] "ibc_hdrs" ar mapM_ (uncurry addHdr) hs processPatternDefs :: Archive -> Idris () processPatternDefs ar = do ds <- getEntry [] "ibc_patdefs" ar mapM_ (\ (n, d) -> updateIState (\i -> i { idris_patdefs = addDef n (force d) (idris_patdefs i) })) ds processDefs :: Archive -> Idris () processDefs ar = do ds <- getEntry [] "ibc_defs" ar mapM_ (\ (n, d) -> do d' <- updateDef d case d' of TyDecl _ _ -> return () _ -> do logIBC 2 $ "SOLVING " ++ show n solveDeferred emptyFC n updateIState (\i -> i { tt_ctxt = addCtxtDef n d' (tt_ctxt i) })) ds where updateDef (CaseOp c t args o s cd) = do o' <- mapM updateOrig o cd' <- updateCD cd return $ CaseOp c t args o' s cd' updateDef t = return t updateOrig (Left t) = liftM Left (update t) updateOrig (Right (l, r)) = do l' <- update l r' <- update r return $ Right (l', r') updateCD (CaseDefs (cs, c) (rs, r)) = do c' <- updateSC c r' <- updateSC r return $ CaseDefs (cs, c') (rs, r') updateSC (Case t n alts) = do alts' <- mapM updateAlt alts return (Case t n alts') updateSC (ProjCase t alts) = do alts' <- mapM updateAlt alts return (ProjCase t alts') updateSC (STerm t) = do t' <- update t return (STerm t') updateSC c = return c updateAlt (ConCase n i ns t) = do t' <- updateSC t return (ConCase n i ns t') updateAlt (FnCase n ns t) = do t' <- updateSC t return (FnCase n ns t') updateAlt (ConstCase c t) = do t' <- updateSC t return (ConstCase c t') updateAlt (SucCase n t) = do t' <- updateSC t return (SucCase n t') updateAlt (DefaultCase t) = do t' <- updateSC t return (DefaultCase t') -- We get a lot of repetition in sub terms and can save a fair chunk -- of memory if we make sure they're shared. addTT looks for a term -- and returns it if it exists already, while also keeping stats of -- how many times a subterm is repeated. update t = do tm <- addTT t case tm of Nothing -> update' t Just t' -> return t' update' (P t n ty) = do n' <- getSymbol n return $ P t n' ty update' (App s f a) = liftM2 (App s) (update' f) (update' a) update' (Bind n b sc) = do b' <- updateB b sc' <- update sc return $ Bind n b' sc' where updateB (Let t v) = liftM2 Let (update' t) (update' v) updateB b = do ty' <- update' (binderTy b) return (b { binderTy = ty' }) update' (Proj t i) = do t' <- update' t return $ Proj t' i update' t = return t processDocs :: Archive -> Idris () processDocs ar = do ds <- getEntry [] "ibc_docstrings" ar mapM_ (\(n, a) -> addDocStr n (fst a) (snd a)) ds processModuleDocs :: Archive -> Idris () processModuleDocs ar = do ds <- getEntry [] "ibc_moduledocs" ar mapM_ (\ (n, d) -> updateIState (\i -> i { idris_moduledocs = addDef n d (idris_moduledocs i) })) ds processAccess :: Bool -- ^ Reexporting? -> IBCPhase -> Archive -> Idris () processAccess reexp phase ar = do ds <- getEntry [] "ibc_access" ar mapM_ (\ (n, a_in) -> do let a = if reexp then a_in else Hidden logIBC 3 $ "Setting " ++ show (a, n) ++ " to " ++ show a updateIState (\i -> i { tt_ctxt = setAccess n a (tt_ctxt i) }) if (not reexp) then do logIBC 2 $ "Not exporting " ++ show n setAccessibility n Hidden else logIBC 2 $ "Exporting " ++ show n -- Everything should be available at the REPL from -- things imported publicly when (phase == IBC_REPL True) $ setAccessibility n Public) ds processFlags :: Archive -> Idris () processFlags ar = do ds <- getEntry [] "ibc_flags" ar mapM_ (\ (n, a) -> setFlags n a) ds processFnInfo :: Archive -> Idris () processFnInfo ar = do ds <- getEntry [] "ibc_fninfo" ar mapM_ (\ (n, a) -> setFnInfo n a) ds processTotal :: Archive -> Idris () processTotal ar = do ds <- getEntry [] "ibc_total" ar mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setTotal n a (tt_ctxt i) })) ds processInjective :: Archive -> Idris () processInjective ar = do ds <- getEntry [] "ibc_injective" ar mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setInjective n a (tt_ctxt i) })) ds processTotalityCheckError :: Archive -> Idris () processTotalityCheckError ar = do es <- getEntry [] "ibc_totcheckfail" ar updateIState (\i -> i { idris_totcheckfail = idris_totcheckfail i ++ es }) processCallgraph :: Archive -> Idris () processCallgraph ar = do ds <- getEntry [] "ibc_cg" ar mapM_ (\ (n, a) -> addToCG n a) ds processCoercions :: Archive -> Idris () processCoercions ar = do ns <- getEntry [] "ibc_coercions" ar mapM_ (\ n -> addCoercion n) ns processTransforms :: Archive -> Idris () processTransforms ar = do ts <- getEntry [] "ibc_transforms" ar mapM_ (\ (n, t) -> addTrans n t) ts processErrRev :: Archive -> Idris () processErrRev ar = do ts <- getEntry [] "ibc_errRev" ar mapM_ addErrRev ts processErrReduce :: Archive -> Idris () processErrReduce ar = do ts <- getEntry [] "ibc_errReduce" ar mapM_ addErrReduce ts processLineApps :: Archive -> Idris () processLineApps ar = do ls <- getEntry [] "ibc_lineapps" ar mapM_ (\ (f, i, t) -> addInternalApp f i t) ls processNameHints :: Archive -> Idris () processNameHints ar = do ns <- getEntry [] "ibc_namehints" ar mapM_ (\ (n, ty) -> addNameHint n ty) ns processMetaInformation :: Archive -> Idris () processMetaInformation ar = do ds <- getEntry [] "ibc_metainformation" ar mapM_ (\ (n, m) -> updateIState (\i -> i { tt_ctxt = setMetaInformation n m (tt_ctxt i) })) ds processErrorHandlers :: Archive -> Idris () processErrorHandlers ar = do ns <- getEntry [] "ibc_errorhandlers" ar updateIState (\i -> i { idris_errorhandlers = idris_errorhandlers i ++ ns }) processFunctionErrorHandlers :: Archive -> Idris () processFunctionErrorHandlers ar = do ns <- getEntry [] "ibc_function_errorhandlers" ar mapM_ (\ (fn,arg,handler) -> addFunctionErrorHandlers fn arg [handler]) ns processMetaVars :: Archive -> Idris () processMetaVars ar = do ns <- getEntry [] "ibc_metavars" ar updateIState (\i -> i { idris_metavars = L.reverse ns ++ idris_metavars i }) ----- For Cheapskate and docstrings instance Binary a => Binary (D.Docstring a) where put (D.DocString opts lines) = do put opts ; put lines get = do opts <- get lines <- get return (D.DocString opts lines) instance Binary CT.Options where put (CT.Options x1 x2 x3 x4) = do put x1 ; put x2 ; put x3 ; put x4 get = do x1 <- get x2 <- get x3 <- get x4 <- get return (CT.Options x1 x2 x3 x4) instance Binary D.DocTerm where put D.Unchecked = putWord8 0 put (D.Checked t) = putWord8 1 >> put t put (D.Example t) = putWord8 2 >> put t put (D.Failing e) = putWord8 3 >> put e get = do i <- getWord8 case i of 0 -> return D.Unchecked 1 -> fmap D.Checked get 2 -> fmap D.Example get 3 -> fmap D.Failing get _ -> error "Corrupted binary data for DocTerm" instance Binary a => Binary (D.Block a) where put (D.Para lines) = do putWord8 0 ; put lines put (D.Header i lines) = do putWord8 1 ; put i ; put lines put (D.Blockquote bs) = do putWord8 2 ; put bs put (D.List b t xs) = do putWord8 3 ; put b ; put t ; put xs put (D.CodeBlock attr txt src) = do putWord8 4 ; put attr ; put txt ; put src put (D.HtmlBlock txt) = do putWord8 5 ; put txt put D.HRule = putWord8 6 get = do i <- getWord8 case i of 0 -> fmap D.Para get 1 -> liftM2 D.Header get get 2 -> fmap D.Blockquote get 3 -> liftM3 D.List get get get 4 -> liftM3 D.CodeBlock get get get 5 -> liftM D.HtmlBlock get 6 -> return D.HRule _ -> error "Corrupted binary data for Block" instance Binary a => Binary (D.Inline a) where put (D.Str txt) = do putWord8 0 ; put txt put D.Space = putWord8 1 put D.SoftBreak = putWord8 2 put D.LineBreak = putWord8 3 put (D.Emph xs) = putWord8 4 >> put xs put (D.Strong xs) = putWord8 5 >> put xs put (D.Code xs tm) = putWord8 6 >> put xs >> put tm put (D.Link a b c) = putWord8 7 >> put a >> put b >> put c put (D.Image a b c) = putWord8 8 >> put a >> put b >> put c put (D.Entity a) = putWord8 9 >> put a put (D.RawHtml x) = putWord8 10 >> put x get = do i <- getWord8 case i of 0 -> liftM D.Str get 1 -> return D.Space 2 -> return D.SoftBreak 3 -> return D.LineBreak 4 -> liftM D.Emph get 5 -> liftM D.Strong get 6 -> liftM2 D.Code get get 7 -> liftM3 D.Link get get get 8 -> liftM3 D.Image get get get 9 -> liftM D.Entity get 10 -> liftM D.RawHtml get _ -> error "Corrupted binary data for Inline" instance Binary CT.ListType where put (CT.Bullet c) = putWord8 0 >> put c put (CT.Numbered nw i) = putWord8 1 >> put nw >> put i get = do i <- getWord8 case i of 0 -> liftM CT.Bullet get 1 -> liftM2 CT.Numbered get get _ -> error "Corrupted binary data for ListType" instance Binary CT.CodeAttr where put (CT.CodeAttr a b) = put a >> put b get = liftM2 CT.CodeAttr get get instance Binary CT.NumWrapper where put (CT.PeriodFollowing) = putWord8 0 put (CT.ParenFollowing) = putWord8 1 get = do i <- getWord8 case i of 0 -> return CT.PeriodFollowing 1 -> return CT.ParenFollowing _ -> error "Corrupted binary data for NumWrapper" ----- Generated by 'derive' instance Binary SizeChange where put x = case x of Smaller -> putWord8 0 Same -> putWord8 1 Bigger -> putWord8 2 Unknown -> putWord8 3 get = do i <- getWord8 case i of 0 -> return Smaller 1 -> return Same 2 -> return Bigger 3 -> return Unknown _ -> error "Corrupted binary data for SizeChange" instance Binary CGInfo where put (CGInfo x1 x2 x3 x4) = do put x1 -- put x3 -- Already used SCG info for totality check put x2 put x4 get = do x1 <- get x2 <- get x3 <- get return (CGInfo x1 x2 [] x3) instance Binary CaseType where put x = case x of Updatable -> putWord8 0 Shared -> putWord8 1 get = do i <- getWord8 case i of 0 -> return Updatable 1 -> return Shared _ -> error "Corrupted binary data for CaseType" instance Binary SC where put x = case x of Case x1 x2 x3 -> do putWord8 0 put x1 put x2 put x3 ProjCase x1 x2 -> do putWord8 1 put x1 put x2 STerm x1 -> do putWord8 2 put x1 UnmatchedCase x1 -> do putWord8 3 put x1 ImpossibleCase -> do putWord8 4 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (Case x1 x2 x3) 1 -> do x1 <- get x2 <- get return (ProjCase x1 x2) 2 -> do x1 <- get return (STerm x1) 3 -> do x1 <- get return (UnmatchedCase x1) 4 -> return ImpossibleCase _ -> error "Corrupted binary data for SC" instance Binary CaseAlt where put x = {-# SCC "putCaseAlt" #-} case x of ConCase x1 x2 x3 x4 -> do putWord8 0 put x1 put x2 put x3 put x4 ConstCase x1 x2 -> do putWord8 1 put x1 put x2 DefaultCase x1 -> do putWord8 2 put x1 FnCase x1 x2 x3 -> do putWord8 3 put x1 put x2 put x3 SucCase x1 x2 -> do putWord8 4 put x1 put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (ConCase x1 x2 x3 x4) 1 -> do x1 <- get x2 <- get return (ConstCase x1 x2) 2 -> do x1 <- get return (DefaultCase x1) 3 -> do x1 <- get x2 <- get x3 <- get return (FnCase x1 x2 x3) 4 -> do x1 <- get x2 <- get return (SucCase x1 x2) _ -> error "Corrupted binary data for CaseAlt" instance Binary CaseDefs where put (CaseDefs x1 x2) = do put x1 put x2 get = do x1 <- get x2 <- get return (CaseDefs x1 x2) instance Binary CaseInfo where put x@(CaseInfo x1 x2 x3) = do put x1 put x2 put x3 get = do x1 <- get x2 <- get x3 <- get return (CaseInfo x1 x2 x3) instance Binary Def where put x = {-# SCC "putDef" #-} case x of Function x1 x2 -> do putWord8 0 put x1 put x2 TyDecl x1 x2 -> do putWord8 1 put x1 put x2 -- all primitives just get added at the start, don't write Operator x1 x2 x3 -> do return () -- no need to add/load original patterns, because they're not -- used again after totality checking CaseOp x1 x2 x3 _ _ x4 -> do putWord8 3 put x1 put x2 put x3 put x4 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (Function x1 x2) 1 -> do x1 <- get x2 <- get return (TyDecl x1 x2) -- Operator isn't written, don't read 3 -> do x1 <- get x2 <- get x3 <- get -- x4 <- get -- x3 <- get always [] x5 <- get return (CaseOp x1 x2 x3 [] [] x5) _ -> error "Corrupted binary data for Def" instance Binary Accessibility where put x = case x of Public -> putWord8 0 Frozen -> putWord8 1 Private -> putWord8 2 Hidden -> putWord8 3 get = do i <- getWord8 case i of 0 -> return Public 1 -> return Frozen 2 -> return Private 3 -> return Hidden _ -> error "Corrupted binary data for Accessibility" safeToEnum :: (Enum a, Bounded a, Integral int) => String -> int -> a safeToEnum label x' = result where x = fromIntegral x' result | x < fromEnum (minBound `asTypeOf` result) || x > fromEnum (maxBound `asTypeOf` result) = error $ label ++ ": corrupted binary representation in IBC" | otherwise = toEnum x instance Binary PReason where put x = case x of Other x1 -> do putWord8 0 put x1 Itself -> putWord8 1 NotCovering -> putWord8 2 NotPositive -> putWord8 3 Mutual x1 -> do putWord8 4 put x1 NotProductive -> putWord8 5 BelieveMe -> putWord8 6 UseUndef x1 -> do putWord8 7 put x1 ExternalIO -> putWord8 8 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Other x1) 1 -> return Itself 2 -> return NotCovering 3 -> return NotPositive 4 -> do x1 <- get return (Mutual x1) 5 -> return NotProductive 6 -> return BelieveMe 7 -> do x1 <- get return (UseUndef x1) 8 -> return ExternalIO _ -> error "Corrupted binary data for PReason" instance Binary Totality where put x = case x of Total x1 -> do putWord8 0 put x1 Partial x1 -> do putWord8 1 put x1 Unchecked -> do putWord8 2 Productive -> do putWord8 3 Generated -> do putWord8 4 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Total x1) 1 -> do x1 <- get return (Partial x1) 2 -> return Unchecked 3 -> return Productive 4 -> return Generated _ -> error "Corrupted binary data for Totality" instance Binary MetaInformation where put x = case x of EmptyMI -> do putWord8 0 DataMI x1 -> do putWord8 1 put x1 get = do i <- getWord8 case i of 0 -> return EmptyMI 1 -> do x1 <- get return (DataMI x1) _ -> error "Corrupted binary data for MetaInformation" instance Binary DataOpt where put x = case x of Codata -> putWord8 0 DefaultEliminator -> putWord8 1 DataErrRev -> putWord8 2 DefaultCaseFun -> putWord8 3 get = do i <- getWord8 case i of 0 -> return Codata 1 -> return DefaultEliminator 2 -> return DataErrRev 3 -> return DefaultCaseFun _ -> error "Corrupted binary data for DataOpt" instance Binary FnOpt where put x = case x of Inlinable -> putWord8 0 TotalFn -> putWord8 1 Dictionary -> putWord8 2 AssertTotal -> putWord8 3 Specialise x -> do putWord8 4 put x AllGuarded -> putWord8 5 PartialFn -> putWord8 6 Implicit -> putWord8 7 Reflection -> putWord8 8 ErrorHandler -> putWord8 9 ErrorReverse -> putWord8 10 CoveringFn -> putWord8 11 NoImplicit -> putWord8 12 Constructor -> putWord8 13 CExport x1 -> do putWord8 14 put x1 AutoHint -> putWord8 15 PEGenerated -> putWord8 16 StaticFn -> putWord8 17 OverlappingDictionary -> putWord8 18 ErrorReduce -> putWord8 20 get = do i <- getWord8 case i of 0 -> return Inlinable 1 -> return TotalFn 2 -> return Dictionary 3 -> return AssertTotal 4 -> do x <- get return (Specialise x) 5 -> return AllGuarded 6 -> return PartialFn 7 -> return Implicit 8 -> return Reflection 9 -> return ErrorHandler 10 -> return ErrorReverse 11 -> return CoveringFn 12 -> return NoImplicit 13 -> return Constructor 14 -> do x1 <- get return $ CExport x1 15 -> return AutoHint 16 -> return PEGenerated 17 -> return StaticFn 18 -> return OverlappingDictionary 20 -> return ErrorReduce _ -> error "Corrupted binary data for FnOpt" instance Binary Fixity where put x = case x of Infixl x1 -> do putWord8 0 put x1 Infixr x1 -> do putWord8 1 put x1 InfixN x1 -> do putWord8 2 put x1 PrefixN x1 -> do putWord8 3 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Infixl x1) 1 -> do x1 <- get return (Infixr x1) 2 -> do x1 <- get return (InfixN x1) 3 -> do x1 <- get return (PrefixN x1) _ -> error "Corrupted binary data for Fixity" instance Binary FixDecl where put (Fix x1 x2) = do put x1 put x2 get = do x1 <- get x2 <- get return (Fix x1 x2) instance Binary ArgOpt where put x = case x of HideDisplay -> putWord8 0 InaccessibleArg -> putWord8 1 AlwaysShow -> putWord8 2 UnknownImp -> putWord8 3 get = do i <- getWord8 case i of 0 -> return HideDisplay 1 -> return InaccessibleArg 2 -> return AlwaysShow 3 -> return UnknownImp _ -> error "Corrupted binary data for Static" instance Binary Static where put x = case x of Static -> putWord8 0 Dynamic -> putWord8 1 get = do i <- getWord8 case i of 0 -> return Static 1 -> return Dynamic _ -> error "Corrupted binary data for Static" instance Binary Plicity where put x = case x of Imp x1 x2 x3 x4 _ x5 -> do putWord8 0 put x1 put x2 put x3 put x4 put x5 Exp x1 x2 x3 x4 -> do putWord8 1 put x1 put x2 put x3 put x4 Constraint x1 x2 x3 -> do putWord8 2 put x1 put x2 put x3 TacImp x1 x2 x3 x4 -> do putWord8 3 put x1 put x2 put x3 put x4 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (Imp x1 x2 x3 x4 False x5) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (Exp x1 x2 x3 x4) 2 -> do x1 <- get x2 <- get x3 <- get return (Constraint x1 x2 x3) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (TacImp x1 x2 x3 x4) _ -> error "Corrupted binary data for Plicity" instance (Binary t) => Binary (PDecl' t) where put x = case x of PFix x1 x2 x3 -> do putWord8 0 put x1 put x2 put x3 PTy x1 x2 x3 x4 x5 x6 x7 x8 -> do putWord8 1 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 PClauses x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 PData x1 x2 x3 x4 x5 x6 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 put x6 PParams x1 x2 x3 -> do putWord8 4 put x1 put x2 put x3 PNamespace x1 x2 x3 -> do putWord8 5 put x1 put x2 put x3 PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 -> do putWord8 6 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 put x11 put x12 PInterface x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 -> do putWord8 7 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 put x11 put x12 PImplementation x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 -> do putWord8 8 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 put x11 put x12 put x13 put x14 put x15 PDSL x1 x2 -> do putWord8 9 put x1 put x2 PCAF x1 x2 x3 -> do putWord8 10 put x1 put x2 put x3 PMutual x1 x2 -> do putWord8 11 put x1 put x2 PPostulate x1 x2 x3 x4 x5 x6 x7 x8 -> do putWord8 12 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 PSyntax x1 x2 -> do putWord8 13 put x1 put x2 PDirective x1 -> error "Cannot serialize PDirective" PProvider x1 x2 x3 x4 x5 x6 -> do putWord8 15 put x1 put x2 put x3 put x4 put x5 put x6 PTransform x1 x2 x3 x4 -> do putWord8 16 put x1 put x2 put x3 put x4 PRunElabDecl x1 x2 x3 -> do putWord8 17 put x1 put x2 put x3 POpenInterfaces x1 x2 x3 -> do putWord8 18 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (PFix x1 x2 x3) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (PTy x1 x2 x3 x4 x5 x6 x7 x8) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PClauses x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PData x1 x2 x3 x4 x5 x6) 4 -> do x1 <- get x2 <- get x3 <- get return (PParams x1 x2 x3) 5 -> do x1 <- get x2 <- get x3 <- get return (PNamespace x1 x2 x3) 6 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get x11 <- get x12 <- get return (PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) 7 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get x11 <- get x12 <- get return (PInterface x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) 8 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get x11 <- get x12 <- get x13 <- get x14 <- get x15 <- get return (PImplementation x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15) 9 -> do x1 <- get x2 <- get return (PDSL x1 x2) 10 -> do x1 <- get x2 <- get x3 <- get return (PCAF x1 x2 x3) 11 -> do x1 <- get x2 <- get return (PMutual x1 x2) 12 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (PPostulate x1 x2 x3 x4 x5 x6 x7 x8) 13 -> do x1 <- get x2 <- get return (PSyntax x1 x2) 14 -> do error "Cannot deserialize PDirective" 15 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PProvider x1 x2 x3 x4 x5 x6) 16 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PTransform x1 x2 x3 x4) 17 -> do x1 <- get x2 <- get x3 <- get return (PRunElabDecl x1 x2 x3) 18 -> do x1 <- get x2 <- get x3 <- get return (POpenInterfaces x1 x2 x3) _ -> error "Corrupted binary data for PDecl'" instance Binary t => Binary (ProvideWhat' t) where put (ProvTerm x1 x2) = do putWord8 0 put x1 put x2 put (ProvPostulate x1) = do putWord8 1 put x1 get = do y <- getWord8 case y of 0 -> do x1 <- get x2 <- get return (ProvTerm x1 x2) 1 -> do x1 <- get return (ProvPostulate x1) _ -> error "Corrupted binary data for ProvideWhat" instance Binary Using where put (UImplicit x1 x2) = do putWord8 0; put x1; put x2 put (UConstraint x1 x2) = do putWord8 1; put x1; put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get; x2 <- get; return (UImplicit x1 x2) 1 -> do x1 <- get; x2 <- get; return (UConstraint x1 x2) _ -> error "Corrupted binary data for Using" instance Binary SyntaxInfo where put (Syn x1 x2 x3 x4 _ _ x5 x6 x7 _ _ x8 _ _ _) = do put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (Syn x1 x2 x3 x4 [] id x5 x6 x7 Nothing 0 x8 0 True True) instance (Binary t) => Binary (PClause' t) where put x = case x of PClause x1 x2 x3 x4 x5 x6 -> do putWord8 0 put x1 put x2 put x3 put x4 put x5 put x6 PWith x1 x2 x3 x4 x5 x6 x7 -> do putWord8 1 put x1 put x2 put x3 put x4 put x5 put x6 put x7 PClauseR x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 PWithR x1 x2 x3 x4 x5 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PClause x1 x2 x3 x4 x5 x6) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get return (PWith x1 x2 x3 x4 x5 x6 x7) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PClauseR x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PWithR x1 x2 x3 x4 x5) _ -> error "Corrupted binary data for PClause'" instance (Binary t) => Binary (PData' t) where put x = case x of PDatadecl x1 x2 x3 x4 -> do putWord8 0 put x1 put x2 put x3 put x4 PLaterdecl x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PDatadecl x1 x2 x3 x4) 1 -> do x1 <- get x2 <- get x3 <- get return (PLaterdecl x1 x2 x3) _ -> error "Corrupted binary data for PData'" instance Binary PunInfo where put x = case x of TypeOrTerm -> putWord8 0 IsType -> putWord8 1 IsTerm -> putWord8 2 get = do i <- getWord8 case i of 0 -> return TypeOrTerm 1 -> return IsType 2 -> return IsTerm _ -> error "Corrupted binary data for PunInfo" instance Binary PTerm where put x = case x of PQuote x1 -> do putWord8 0 put x1 PRef x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 PInferRef x1 x2 x3 -> do putWord8 2 put x1 put x2 put x3 PPatvar x1 x2 -> do putWord8 3 put x1 put x2 PLam x1 x2 x3 x4 x5 -> do putWord8 4 put x1 put x2 put x3 put x4 put x5 PPi x1 x2 x3 x4 x5 -> do putWord8 5 put x1 put x2 put x3 put x4 put x5 PLet x1 x2 x3 x4 x5 x6 -> do putWord8 6 put x1 put x2 put x3 put x4 put x5 put x6 PTyped x1 x2 -> do putWord8 7 put x1 put x2 PAppImpl x1 x2 -> error "PAppImpl in final term" PApp x1 x2 x3 -> do putWord8 8 put x1 put x2 put x3 PAppBind x1 x2 x3 -> do putWord8 9 put x1 put x2 put x3 PMatchApp x1 x2 -> do putWord8 10 put x1 put x2 PCase x1 x2 x3 -> do putWord8 11 put x1 put x2 put x3 PTrue x1 x2 -> do putWord8 12 put x1 put x2 PResolveTC x1 -> do putWord8 15 put x1 PRewrite x1 x2 x3 x4 x5 -> do putWord8 17 put x1 put x2 put x3 put x4 put x5 PPair x1 x2 x3 x4 x5 -> do putWord8 18 put x1 put x2 put x3 put x4 put x5 PDPair x1 x2 x3 x4 x5 x6 -> do putWord8 19 put x1 put x2 put x3 put x4 put x5 put x6 PAlternative x1 x2 x3 -> do putWord8 20 put x1 put x2 put x3 PHidden x1 -> do putWord8 21 put x1 PType x1 -> do putWord8 22 put x1 PGoal x1 x2 x3 x4 -> do putWord8 23 put x1 put x2 put x3 put x4 PConstant x1 x2 -> do putWord8 24 put x1 put x2 Placeholder -> putWord8 25 PDoBlock x1 -> do putWord8 26 put x1 PIdiom x1 x2 -> do putWord8 27 put x1 put x2 PMetavar x1 x2 -> do putWord8 29 put x1 put x2 PProof x1 -> do putWord8 30 put x1 PTactics x1 -> do putWord8 31 put x1 PImpossible -> putWord8 33 PCoerced x1 -> do putWord8 34 put x1 PUnifyLog x1 -> do putWord8 35 put x1 PNoImplicits x1 -> do putWord8 36 put x1 PDisamb x1 x2 -> do putWord8 37 put x1 put x2 PUniverse x1 x2 -> do putWord8 38 put x1 put x2 PRunElab x1 x2 x3 -> do putWord8 39 put x1 put x2 put x3 PAs x1 x2 x3 -> do putWord8 40 put x1 put x2 put x3 PElabError x1 -> do putWord8 41 put x1 PQuasiquote x1 x2 -> do putWord8 42 put x1 put x2 PUnquote x1 -> do putWord8 43 put x1 PQuoteName x1 x2 x3 -> do putWord8 44 put x1 put x2 put x3 PIfThenElse x1 x2 x3 x4 -> do putWord8 45 put x1 put x2 put x3 put x4 PConstSugar x1 x2 -> do putWord8 46 put x1 put x2 PWithApp x1 x2 x3 -> do putWord8 47 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get return (PQuote x1) 1 -> do x1 <- get x2 <- get x3 <- get return (PRef x1 x2 x3) 2 -> do x1 <- get x2 <- get x3 <- get return (PInferRef x1 x2 x3) 3 -> do x1 <- get x2 <- get return (PPatvar x1 x2) 4 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PLam x1 x2 x3 x4 x5) 5 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PPi x1 x2 x3 x4 x5) 6 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PLet x1 x2 x3 x4 x5 x6) 7 -> do x1 <- get x2 <- get return (PTyped x1 x2) 8 -> do x1 <- get x2 <- get x3 <- get return (PApp x1 x2 x3) 9 -> do x1 <- get x2 <- get x3 <- get return (PAppBind x1 x2 x3) 10 -> do x1 <- get x2 <- get return (PMatchApp x1 x2) 11 -> do x1 <- get x2 <- get x3 <- get return (PCase x1 x2 x3) 12 -> do x1 <- get x2 <- get return (PTrue x1 x2) 15 -> do x1 <- get return (PResolveTC x1) 17 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PRewrite x1 x2 x3 x4 x5) 18 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PPair x1 x2 x3 x4 x5) 19 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PDPair x1 x2 x3 x4 x5 x6) 20 -> do x1 <- get x2 <- get x3 <- get return (PAlternative x1 x2 x3) 21 -> do x1 <- get return (PHidden x1) 22 -> do x1 <- get return (PType x1) 23 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PGoal x1 x2 x3 x4) 24 -> do x1 <- get x2 <- get return (PConstant x1 x2) 25 -> return Placeholder 26 -> do x1 <- get return (PDoBlock x1) 27 -> do x1 <- get x2 <- get return (PIdiom x1 x2) 29 -> do x1 <- get x2 <- get return (PMetavar x1 x2) 30 -> do x1 <- get return (PProof x1) 31 -> do x1 <- get return (PTactics x1) 33 -> return PImpossible 34 -> do x1 <- get return (PCoerced x1) 35 -> do x1 <- get return (PUnifyLog x1) 36 -> do x1 <- get return (PNoImplicits x1) 37 -> do x1 <- get x2 <- get return (PDisamb x1 x2) 38 -> do x1 <- get x2 <- get return (PUniverse x1 x2) 39 -> do x1 <- get x2 <- get x3 <- get return (PRunElab x1 x2 x3) 40 -> do x1 <- get x2 <- get x3 <- get return (PAs x1 x2 x3) 41 -> do x1 <- get return (PElabError x1) 42 -> do x1 <- get x2 <- get return (PQuasiquote x1 x2) 43 -> do x1 <- get return (PUnquote x1) 44 -> do x1 <- get x2 <- get x3 <- get return (PQuoteName x1 x2 x3) 45 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PIfThenElse x1 x2 x3 x4) 46 -> do x1 <- get x2 <- get return (PConstSugar x1 x2) 47 -> do x1 <- get x2 <- get x3 <- get return (PWithApp x1 x2 x3) _ -> error "Corrupted binary data for PTerm" instance Binary PAltType where put x = case x of ExactlyOne x1 -> do putWord8 0 put x1 FirstSuccess -> putWord8 1 TryImplicit -> putWord8 2 get = do i <- getWord8 case i of 0 -> do x1 <- get return (ExactlyOne x1) 1 -> return FirstSuccess 2 -> return TryImplicit _ -> error "Corrupted binary data for PAltType" instance (Binary t) => Binary (PTactic' t) where put x = case x of Intro x1 -> do putWord8 0 put x1 Focus x1 -> do putWord8 1 put x1 Refine x1 x2 -> do putWord8 2 put x1 put x2 Rewrite x1 -> do putWord8 3 put x1 LetTac x1 x2 -> do putWord8 4 put x1 put x2 Exact x1 -> do putWord8 5 put x1 Compute -> putWord8 6 Trivial -> putWord8 7 Solve -> putWord8 8 Attack -> putWord8 9 ProofState -> putWord8 10 ProofTerm -> putWord8 11 Undo -> putWord8 12 Try x1 x2 -> do putWord8 13 put x1 put x2 TSeq x1 x2 -> do putWord8 14 put x1 put x2 Qed -> putWord8 15 ApplyTactic x1 -> do putWord8 16 put x1 Reflect x1 -> do putWord8 17 put x1 Fill x1 -> do putWord8 18 put x1 Induction x1 -> do putWord8 19 put x1 ByReflection x1 -> do putWord8 20 put x1 ProofSearch x1 x2 x3 x4 x5 x6 -> do putWord8 21 put x1 put x2 put x3 put x4 put x5 put x6 DoUnify -> putWord8 22 CaseTac x1 -> do putWord8 23 put x1 SourceFC -> putWord8 24 Intros -> putWord8 25 Equiv x1 -> do putWord8 26 put x1 Claim x1 x2 -> do putWord8 27 put x1 put x2 Unfocus -> putWord8 28 MatchRefine x1 -> do putWord8 29 put x1 LetTacTy x1 x2 x3 -> do putWord8 30 put x1 put x2 put x3 TCImplementation -> putWord8 31 GoalType x1 x2 -> do putWord8 32 put x1 put x2 TCheck x1 -> do putWord8 33 put x1 TEval x1 -> do putWord8 34 put x1 TDocStr x1 -> do putWord8 35 put x1 TSearch x1 -> do putWord8 36 put x1 Skip -> putWord8 37 TFail x1 -> do putWord8 38 put x1 Abandon -> putWord8 39 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Intro x1) 1 -> do x1 <- get return (Focus x1) 2 -> do x1 <- get x2 <- get return (Refine x1 x2) 3 -> do x1 <- get return (Rewrite x1) 4 -> do x1 <- get x2 <- get return (LetTac x1 x2) 5 -> do x1 <- get return (Exact x1) 6 -> return Compute 7 -> return Trivial 8 -> return Solve 9 -> return Attack 10 -> return ProofState 11 -> return ProofTerm 12 -> return Undo 13 -> do x1 <- get x2 <- get return (Try x1 x2) 14 -> do x1 <- get x2 <- get return (TSeq x1 x2) 15 -> return Qed 16 -> do x1 <- get return (ApplyTactic x1) 17 -> do x1 <- get return (Reflect x1) 18 -> do x1 <- get return (Fill x1) 19 -> do x1 <- get return (Induction x1) 20 -> do x1 <- get return (ByReflection x1) 21 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (ProofSearch x1 x2 x3 x4 x5 x6) 22 -> return DoUnify 23 -> do x1 <- get return (CaseTac x1) 24 -> return SourceFC 25 -> return Intros 26 -> do x1 <- get return (Equiv x1) 27 -> do x1 <- get x2 <- get return (Claim x1 x2) 28 -> return Unfocus 29 -> do x1 <- get return (MatchRefine x1) 30 -> do x1 <- get x2 <- get x3 <- get return (LetTacTy x1 x2 x3) 31 -> return TCImplementation 32 -> do x1 <- get x2 <- get return (GoalType x1 x2) 33 -> do x1 <- get return (TCheck x1) 34 -> do x1 <- get return (TEval x1) 35 -> do x1 <- get return (TDocStr x1) 36 -> do x1 <- get return (TSearch x1) 37 -> return Skip 38 -> do x1 <- get return (TFail x1) 39 -> return Abandon _ -> error "Corrupted binary data for PTactic'" instance (Binary t) => Binary (PDo' t) where put x = case x of DoExp x1 x2 -> do putWord8 0 put x1 put x2 DoBind x1 x2 x3 x4 -> do putWord8 1 put x1 put x2 put x3 put x4 DoBindP x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 DoLet x1 x2 x3 x4 x5 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 DoLetP x1 x2 x3 -> do putWord8 4 put x1 put x2 put x3 DoRewrite x1 x2 -> do putWord8 5 put x1 put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (DoExp x1 x2) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (DoBind x1 x2 x3 x4) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (DoBindP x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (DoLet x1 x2 x3 x4 x5) 4 -> do x1 <- get x2 <- get x3 <- get return (DoLetP x1 x2 x3) 5 -> do x1 <- get x2 <- get return (DoRewrite x1 x2) _ -> error "Corrupted binary data for PDo'" instance (Binary t) => Binary (PArg' t) where put x = case x of PImp x1 x2 x3 x4 x5 -> do putWord8 0 put x1 put x2 put x3 put x4 put x5 PExp x1 x2 x3 x4 -> do putWord8 1 put x1 put x2 put x3 put x4 PConstraint x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 PTacImplicit x1 x2 x3 x4 x5 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PImp x1 x2 x3 x4 x5) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PExp x1 x2 x3 x4) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PConstraint x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PTacImplicit x1 x2 x3 x4 x5) _ -> error "Corrupted binary data for PArg'" instance Binary InterfaceInfo where put (CI x1 x2 x3 x4 x5 x6 x7 _ x8) = do put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (CI x1 x2 x3 x4 x5 x6 x7 [] x8) instance Binary RecordInfo where put (RI x1 x2 x3) = do put x1 put x2 put x3 get = do x1 <- get x2 <- get x3 <- get return (RI x1 x2 x3) instance Binary OptInfo where put (Optimise x1 x2 x3) = do put x1 put x2 put x3 get = do x1 <- get x2 <- get x3 <- get return (Optimise x1 x2 x3) instance Binary FnInfo where put (FnInfo x1) = put x1 get = do x1 <- get return (FnInfo x1) instance Binary TypeInfo where put (TI x1 x2 x3 x4 x5 x6) = do put x1 put x2 put x3 put x4 put x5 put x6 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (TI x1 x2 x3 x4 x5 x6) instance Binary SynContext where put x = case x of PatternSyntax -> putWord8 0 TermSyntax -> putWord8 1 AnySyntax -> putWord8 2 get = do i <- getWord8 case i of 0 -> return PatternSyntax 1 -> return TermSyntax 2 -> return AnySyntax _ -> error "Corrupted binary data for SynContext" instance Binary Syntax where put (Rule x1 x2 x3) = do putWord8 0 put x1 put x2 put x3 put (DeclRule x1 x2) = do putWord8 1 put x1 put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (Rule x1 x2 x3) 1 -> do x1 <- get x2 <- get return (DeclRule x1 x2) _ -> error "Corrupted binary data for Syntax" instance (Binary t) => Binary (DSL' t) where put (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9) = do put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get return (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9) instance Binary SSymbol where put x = case x of Keyword x1 -> do putWord8 0 put x1 Symbol x1 -> do putWord8 1 put x1 Expr x1 -> do putWord8 2 put x1 SimpleExpr x1 -> do putWord8 3 put x1 Binding x1 -> do putWord8 4 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Keyword x1) 1 -> do x1 <- get return (Symbol x1) 2 -> do x1 <- get return (Expr x1) 3 -> do x1 <- get return (SimpleExpr x1) 4 -> do x1 <- get return (Binding x1) _ -> error "Corrupted binary data for SSymbol" instance Binary Codegen where put x = case x of Via ir str -> do putWord8 0 put ir put str Bytecode -> putWord8 1 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (Via x1 x2) 1 -> return Bytecode _ -> error "Corrupted binary data for Codegen" instance Binary IRFormat where put x = case x of IBCFormat -> putWord8 0 JSONFormat -> putWord8 1 get = do i <- getWord8 case i of 0 -> return IBCFormat 1 -> return JSONFormat _ -> error "Corrupted binary data for IRFormat"
markuspf/Idris-dev
src/Idris/IBC.hs
bsd-3-clause
102,813
0
21
56,870
28,131
12,917
15,214
2,464
17
{-# LANGUAGE DeriveDataTypeable #-} module Latex ( texString , writeTexStdOut , writeTexToFile , writeTemplateToFile ) where import Data.List import System.IO import System.Directory import System.FilePath.Posix import Args import Lib texString :: Arguments -> String texString (Install {}) = error "Cannot form a LaTeX string while installing" texString a@Generate {} = intercalate "\n" [ assembleFileHeader a , assemblePackages $ pkg a , "\\author{" ++ author a ++ "}" , "\\title{" ++ title a ++ "}" , "\\date{" ++ date a ++ "}" , beginDocument , makeTitle , documentBody , endDocument ] where fullLineComment = replicate 80 '%' commentString :: String -> String commentString xs = "%% " ++ xs beginDocument = "\n\n\\begin{document}" endDocument = "\n\n\\end{document}" makeTitle = "\\maketitle" documentBody = "\n\n" ++ "%% Your latex code goes here" assembleFileHeader :: Arguments -> String assembleFileHeader a = fullLineComment ++ intercalate "\n%% " ( ["\n%% Author: " ++ author a ,"Title: " ++ title a ,"Date: Current Date Here" ] ++ ( notes a) ) ++ ('\n':fullLineComment) -- formatPackage s = "\usepackage" ++ extractPackageOptions s formPackageString :: String -> String formPackageString xs = let (pkgName, pkgOpt) = span (/= '[') xs in "\\usepackage" ++ pkgOpt ++ ( '{' : (pkgName ++ "}")) assemblePackages = intercalate "\n" . map formPackageString templateString :: Arguments -> IO String templateString Install {} = error "Install is not a Template" templateString Generate {} = error "Generate is not a Template" templateString a@Template {} = do appDir <- getAppUserDataDirectory programName let filePath = appDir </> "templates" </> name_ a readFile filePath writeTexStdOut :: Arguments -> IO () writeTexStdOut Install{} = error "Cannot form a LaTeX string while installing" writeTexStdOut Template{} = error "writeTexStdOut(Template)!! unimplemented" writeTexStdOut a = putStrLn $ texString a writeTexToFile :: Arguments -> IO () writeTexToFile Install {} = error "Cannot form a LaTeX string while installing" writeTexToFile Template {} = error "writeTexToFile(Template)!! unimplemented" writeTexToFile a = writeFile (fileName a) (texString a) writeTemplateToFile :: Arguments -> IO () writeTemplateToFile Install {} = error "Install is not a template" writeTemplateToFile Generate {} = error "Run is not a template" writeTemplateToFile a = do contents <- templateString a writeFile (fileName a) contents
bkushigian/makeltx
src/Latex.hs
bsd-3-clause
2,932
0
14
859
672
342
330
65
1
{-# LANGUAGE MultiParamTypeClasses, FlexibleContexts, FlexibleInstances, TypeFamilies, Rank2Types, FunctionalDependencies #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Matrix.Banded.Base -- Copyright : Copyright (c) , Patrick Perry <[email protected]> -- License : BSD3 -- Maintainer : Patrick Perry <[email protected]> -- Stability : experimental -- module Data.Matrix.Banded.Base where import Control.Monad import Control.Monad.Interleave import Control.Monad.ST import Data.AEq import Data.Maybe import Data.Ix import System.IO.Unsafe import BLAS.Internal( clearArray, checkedRow, checkedCol, checkedDiag, diagLen, inlinePerformIO ) import Data.Elem.BLAS import Data.Tensor.Class import Data.Tensor.Class.ITensor import Data.Tensor.Class.MTensor import Data.Matrix.Class import Data.Matrix.Class.IMatrixBase import Data.Matrix.Class.MMatrixBase import Data.Matrix.Class.ISolveBase import Data.Matrix.Class.MSolveBase import Data.Matrix.Herm import Data.Matrix.Tri import Data.Vector.Dense.ST( runSTVector ) import Data.Vector.Dense.Base( BaseVector, ReadVector, WriteVector, Vector(..), STVector(..), dim, unsafeVectorToIOVector, unsafePerformIOWithVector, unsafeConvertIOVector, newZeroVector, newCopyVector ) import Data.Matrix.Dense.ST( runSTMatrix ) import Data.Matrix.Dense.Base( BaseMatrix, ReadMatrix, WriteMatrix, Matrix(..), STMatrix(..), unsafeMatrixToIOMatrix, unsafePerformIOWithMatrix ) import Data.Matrix.Banded.IOBase( IOBanded(..) ) import qualified Data.Matrix.Banded.IOBase as IO -- | Immutable banded matrices. The type arguments are as follows: -- -- * @e@: the element type of the matrix. Only certain element types -- are supported. -- newtype Banded e = Banded (IOBanded e) freezeIOBanded :: IOBanded e -> IO (Banded e) freezeIOBanded x = do y <- IO.newCopyIOBanded x return (Banded y) thawIOBanded :: Banded e -> IO (IOBanded e) thawIOBanded (Banded x) = IO.newCopyIOBanded x unsafeFreezeIOBanded :: IOBanded e -> IO (Banded e) unsafeFreezeIOBanded = return . Banded unsafeThawIOBanded :: Banded e -> IO (IOBanded e) unsafeThawIOBanded (Banded x) = return x -- | Common functionality for all banded matrix types. class ( MatrixShaped a, HasHerm a, HasVectorView a, HasMatrixStorage a, BaseVector (VectorView a), BaseMatrix (MatrixStorage a) ) => BaseBanded a where -- | Get the number of lower diagonals in the banded matrix. numLower :: a e -> Int -- | Get the number of upper diagonals in the banded matrix numUpper :: a e -> Int -- | Get the range of valid diagonals in the banded matrix. -- @bandwidthds a@ is equal to @(numLower a, numUpper a)@. bandwidths :: a e -> (Int,Int) -- | Get the leading dimension of the underlying storage of the -- banded matrix. ldaBanded :: a e -> Int -- | Get the storage type of the banded matrix. transEnumBanded :: a e -> TransEnum -- | Indicate whether or not the banded matrix storage is -- transposed and conjugated. isHermBanded :: a e -> Bool isHermBanded = (ConjTrans ==) . transEnumBanded {-# INLINE isHermBanded #-} -- | Get a matrix with the underlying storage of the banded matrix. -- This will fail if the banded matrix is hermed. maybeMatrixStorageFromBanded :: a e -> Maybe (MatrixStorage a e) -- | Given a shape and bandwidths, possibly view the elements stored -- in a dense matrix as a banded matrix. This will if the matrix -- storage is hermed. An error will be called if the number of rows -- in the matrix does not equal the desired number of diagonals or -- if the number of columns in the matrix does not equal the desired -- number of columns. maybeBandedFromMatrixStorage :: (Int,Int) -> (Int,Int) -> MatrixStorage a e -> Maybe (a e) -- | View a vector as a banded matrix of the given shape. The vector -- must have length equal to one of the specified dimensions. viewVectorAsBanded :: (Int,Int) -> VectorView a e -> a e -- | View a vector as a diagonal banded matrix. viewVectorAsDiagBanded :: VectorView a e -> a e viewVectorAsDiagBanded x = let n = dim x in viewVectorAsBanded (n,n) x {-# INLINE viewVectorAsBanded #-} -- | If the banded matrix has only a single diagonal, return a view -- into that diagonal. Otherwise, return @Nothing@. maybeViewBandedAsVector :: a e -> Maybe (VectorView a e) unsafeDiagViewBanded :: a e -> Int -> VectorView a e unsafeRowViewBanded :: a e -> Int -> (Int, VectorView a e, Int) unsafeColViewBanded :: a e -> Int -> (Int, VectorView a e, Int) -- | Unsafe cast from a matrix to an 'IOBanded'. unsafeBandedToIOBanded :: a e -> IOBanded e unsafeIOBandedToBanded :: IOBanded e -> a e -- | Banded matrices that can be read in a monad. class ( BaseBanded a, MonadInterleave m, ReadTensor a (Int,Int) m, MMatrix a m, MMatrix (Herm a) m, MMatrix (Tri a) m, MSolve (Tri a) m, ReadVector (VectorView a) m, ReadMatrix (MatrixStorage a) m ) => ReadBanded a m where -- | Cast the banded matrix to an 'IOBanded', perform an @IO@ action, and -- convert the @IO@ action to an action in the monad @m@. This -- operation is /very/ unsafe. unsafePerformIOWithBanded :: a e -> (IOBanded e -> IO r) -> m r -- | Convert a mutable banded matrix to an immutable one by taking a -- complete copy of it. freezeBanded :: a e -> m (Banded e) unsafeFreezeBanded :: a e -> m (Banded e) -- | Banded matrices that can be created or modified in a monad. class ( ReadBanded a m, WriteTensor a (Int,Int) m, WriteVector (VectorView a) m, WriteMatrix (MatrixStorage a) m ) => WriteBanded a m | m -> a where -- | Creates a new banded matrix of the given shape and bandwidths. -- The elements will be uninitialized. newBanded_ :: (Elem e) => (Int,Int) -> (Int,Int) -> m (a e) -- | Unsafely convert an 'IO' action that creates an 'IOBanded' into -- an action in @m@ that creates a matrix. unsafeConvertIOBanded :: IO (IOBanded e) -> m (a e) -- | Convert an immutable banded matrix to a mutable one by taking a -- complete copy of it. thawBanded :: Banded e -> m (a e) unsafeThawBanded :: Banded e -> m (a e) -- | Create a banded matrix with the given shape, bandwidths, and -- associations. The indices in the associations list must all fall -- in the bandwidth of the matrix. Unspecified elements will be set -- to zero. newBanded :: (WriteBanded a m, Elem e) => (Int,Int) -> (Int,Int) -> [((Int,Int), e)] -> m (a e) newBanded = newBandedHelp writeElem {-# INLINE newBanded #-} unsafeNewBanded :: (WriteBanded a m, Elem e) => (Int,Int) -> (Int,Int) -> [((Int,Int), e)] -> m (a e) unsafeNewBanded = newBandedHelp unsafeWriteElem {-# INLINE unsafeNewBanded #-} newBandedHelp :: (WriteBanded a m, Elem e) => (IOBanded e -> (Int,Int) -> e -> IO ()) -> (Int,Int) -> (Int,Int) -> [((Int,Int),e)] -> m (a e) newBandedHelp set (m,n) (kl,ku) ijes = unsafeConvertIOBanded $ do x <- newBanded_ (m,n) (kl,ku) IO.withIOBanded x $ flip clearArray ((kl+1+ku)*n) mapM_ (uncurry $ set x) ijes return x {-# INLINE newBandedHelp #-} -- | Create a banded matrix of the given shape and bandwidths by specifying -- its diagonal elements. The lists must all have the same length, equal -- to the number of elements in the main diagonal of the matrix. The -- sub-diagonals are specified first, then the super-diagonals. In -- subdiagonal @i@, the first @i@ elements of the list are ignored. newListsBanded :: (WriteBanded a m, Elem e) => (Int,Int) -> (Int,Int) -> [[e]] -> m (a e) newListsBanded (m,n) (kl,ku) xs = do a <- newBanded_ (m,n) (kl,ku) zipWithM_ (writeDiagElems a) [(negate kl)..ku] xs return a where writeDiagElems :: (WriteBanded a m, Elem e) => a e -> Int -> [e] -> m () writeDiagElems a i es = let d = unsafeDiagViewBanded a i nb = max 0 (negate i) es' = drop nb es in zipWithM_ (unsafeWriteElem d) [0..(dim d - 1)] es' {-# INLINE newListsBanded #-} -- | Create a zero banded matrix with the specified shape and bandwidths. newZeroBanded :: (WriteBanded a m, Elem e) => (Int,Int) -> (Int,Int) -> m (a e) newZeroBanded mn bw = unsafeConvertIOBanded $ IO.newZeroIOBanded mn bw {-# INLINE newZeroBanded #-} -- | Create a constant banded matrix of the specified shape and bandwidths. newConstantBanded :: (WriteBanded a m, Elem e) => (Int,Int) -> (Int,Int) -> e -> m (a e) newConstantBanded mn bw e = unsafeConvertIOBanded $ IO.newConstantIOBanded mn bw e {-# INLINE newConstantBanded #-} -- | Set every element of a banded matrix to zero. setZeroBanded :: (WriteBanded a m) => a e -> m () setZeroBanded a = unsafePerformIOWithBanded a $ IO.setZeroIOBanded {-# INLINE setZeroBanded #-} -- | Set every element of a banded matrix to a constant. setConstantBanded :: (WriteBanded a m) => e -> a e -> m () setConstantBanded e a = unsafePerformIOWithBanded a $ IO.setConstantIOBanded e {-# INLINE setConstantBanded #-} -- | Create a new banded matrix by taking a copy of another one. newCopyBanded :: (ReadBanded a m, WriteBanded b m) => a e -> m (b e) newCopyBanded a = unsafeConvertIOBanded $ IO.newCopyIOBanded (unsafeBandedToIOBanded a) {-# INLINE newCopyBanded #-} -- | Copy the elements of one banded matrix into another. The two matrices -- must have the same shape and badwidths. copyBanded :: (WriteBanded b m, ReadBanded a m) => b e -> a e -> m () copyBanded dst src | shape dst /= shape src = error "Shape mismatch in copyBanded." | bandwidths dst /= bandwidths src = error "Bandwidth mismatch in copyBanded." | otherwise = unsafeCopyBanded dst src {-# INLINE copyBanded #-} unsafeCopyBanded :: (WriteBanded b m, ReadBanded a m) => b e -> a e -> m () unsafeCopyBanded dst src = unsafePerformIOWithBanded dst $ \dst' -> IO.unsafeCopyIOBanded dst' (unsafeBandedToIOBanded src) {-# INLINE unsafeCopyBanded #-} -- | Get a view of a diagonal of the banded matrix. This will fail if -- the index is outside of the bandwidth. diagViewBanded :: (BaseBanded a) => a e -> Int -> VectorView a e diagViewBanded a i | i < -(numLower a) || i > numUpper a = error $ "Tried to get a diagonal view outside of the bandwidth." | otherwise = unsafeDiagViewBanded a i {-# INLINE diagViewBanded #-} -- | Get a view into the partial row of the banded matrix, along with the -- number of zeros to pad before and after the view. rowViewBanded :: (BaseBanded a) => a e -> Int -> (Int, VectorView a e, Int) rowViewBanded a = checkedRow (shape a) (unsafeRowViewBanded a) {-# INLINE rowViewBanded #-} -- | Get a view into the partial column of the banded matrix, along with the -- number of zeros to pad before and after the view. colViewBanded :: (BaseBanded a) => a e -> Int -> (Int, VectorView a e, Int) colViewBanded a = checkedCol (shape a) (unsafeColViewBanded a) {-# INLINE colViewBanded #-} -- | Get a copy of the given diagonal of a banded matrix. getDiagBanded :: (ReadBanded a m, WriteVector y m, Elem e) => a e -> Int -> m (y e) getDiagBanded a i | i >= -kl && i <= ku = newCopyVector $ diagViewBanded a i | otherwise = newZeroVector $ diagLen (m,n) i where (m,n) = shape a (kl,ku) = bandwidths a {-# INLINE getDiagBanded #-} unsafeGetDiagBanded :: (ReadBanded a m, WriteVector y m, Elem e) => a e -> Int -> m (y e) unsafeGetDiagBanded a i = newCopyVector $ unsafeDiagViewBanded a i {-# INLINE unsafeGetDiagBanded #-} unsafeGetRowBanded :: (ReadBanded a m, WriteVector y m, Elem e) => a e -> Int -> m (y e) unsafeGetRowBanded a i = unsafeConvertIOVector $ IO.unsafeGetRowIOBanded (unsafeBandedToIOBanded a) i {-# INLINE unsafeGetRowBanded #-} unsafeGetColBanded :: (ReadBanded a m, WriteVector y m, Elem e) => a e -> Int -> m (y e) unsafeGetColBanded a i = unsafeConvertIOVector $ IO.unsafeGetColIOBanded (unsafeBandedToIOBanded a) i {-# INLINE unsafeGetColBanded #-} gbmv :: (ReadBanded a m, ReadVector x m, WriteVector y m, BLAS2 e) => e -> a e -> x e -> e -> y e -> m () gbmv alpha a x beta y = unsafePerformIOWithVector y $ IO.gbmv alpha (unsafeBandedToIOBanded a) (unsafeVectorToIOVector x) beta {-# INLINE gbmv #-} gbmm :: (ReadBanded a m, ReadMatrix b m, WriteMatrix c m, BLAS2 e) => e -> a e -> b e -> e -> c e -> m () gbmm alpha a b beta c = unsafePerformIOWithMatrix c $ IO.gbmm alpha (unsafeBandedToIOBanded a) (unsafeMatrixToIOMatrix b) beta {-# INLINE gbmm #-} unsafeGetColHermBanded :: (ReadBanded a m, WriteVector x m, Elem e) => Herm a e -> Int -> m (x e) unsafeGetColHermBanded a i = unsafeConvertIOVector $ IO.unsafeGetColHermIOBanded (mapHerm unsafeBandedToIOBanded a) i {-# INLINE unsafeGetColHermBanded #-} unsafeGetRowHermBanded :: (ReadBanded a m, WriteVector x m, Elem e) => Herm a e -> Int -> m (x e) unsafeGetRowHermBanded a i = unsafeConvertIOVector $ IO.unsafeGetRowHermIOBanded (mapHerm unsafeBandedToIOBanded a) i {-# INLINE unsafeGetRowHermBanded #-} hbmv :: (ReadBanded a m, ReadVector x m, WriteVector y m, BLAS2 e) => e -> Herm a e -> x e -> e -> y e -> m () hbmv alpha a x beta y = unsafePerformIOWithVector y $ IO.hbmv alpha (mapHerm unsafeBandedToIOBanded a) (unsafeVectorToIOVector x) beta {-# INLINE hbmv #-} hbmm :: (ReadBanded a m, ReadMatrix b m, WriteMatrix c m, BLAS2 e) => e -> Herm a e -> b e -> e -> c e -> m () hbmm alpha a b beta c = unsafePerformIOWithMatrix c $ IO.hbmm alpha (mapHerm unsafeBandedToIOBanded a) (unsafeMatrixToIOMatrix b) beta {-# INLINE hbmm #-} unsafeGetColTriBanded :: (ReadBanded a m, WriteVector x m, Elem e) => Tri a e -> Int -> m (x e) unsafeGetColTriBanded a i = unsafeConvertIOVector $ IO.unsafeGetColTriIOBanded (mapTri unsafeBandedToIOBanded a) i {-# INLINE unsafeGetColTriBanded #-} unsafeGetRowTriBanded :: (ReadBanded a m, WriteVector x m, Elem e) => Tri a e -> Int -> m (x e) unsafeGetRowTriBanded a i = unsafeConvertIOVector $ IO.unsafeGetRowTriIOBanded (mapTri unsafeBandedToIOBanded a) i {-# INLINE unsafeGetRowTriBanded #-} tbmv :: (ReadBanded a m, WriteVector y m, BLAS2 e) => e -> Tri a e -> y e -> m () tbmv alpha a x = unsafePerformIOWithVector x $ IO.tbmv alpha (mapTri unsafeBandedToIOBanded a) {-# INLINE tbmv #-} tbmm :: (ReadBanded a m, WriteMatrix b m, BLAS2 e) => e -> Tri a e -> b e -> m () tbmm alpha a b = unsafePerformIOWithMatrix b $ IO.tbmm alpha (mapTri unsafeBandedToIOBanded a) {-# INLINE tbmm #-} tbmv' :: (ReadBanded a m, ReadVector x m, WriteVector y m, BLAS2 e) => e -> Tri a e -> x e -> e -> y e -> m () tbmv' alpha a x beta y = unsafePerformIOWithVector y $ IO.tbmv' alpha (mapTri unsafeBandedToIOBanded a) (unsafeVectorToIOVector x) beta {-# INLINE tbmv' #-} tbmm' :: (ReadBanded a m, ReadMatrix b m, WriteMatrix c m, BLAS2 e) => e -> Tri a e -> b e -> e -> c e -> m () tbmm' alpha a b beta c = unsafePerformIOWithMatrix c $ IO.tbmm' alpha (mapTri unsafeBandedToIOBanded a) (unsafeMatrixToIOMatrix b) beta {-# INLINE tbmm' #-} tbsv :: (ReadBanded a m, WriteVector y m, BLAS2 e) => e -> Tri a e -> y e -> m () tbsv alpha a x = unsafePerformIOWithVector x $ IO.tbmv alpha (mapTri unsafeBandedToIOBanded a) {-# INLINE tbsv #-} tbsm :: (ReadBanded a m, WriteMatrix b m, BLAS2 e) => e -> Tri a e -> b e -> m () tbsm alpha a b = unsafePerformIOWithMatrix b $ IO.tbsm alpha (mapTri unsafeBandedToIOBanded a) {-# INLINE tbsm #-} tbsv' :: (ReadBanded a m, ReadVector y m, WriteVector x m, BLAS2 e) => e -> Tri a e -> y e -> x e -> m () tbsv' alpha a y x = unsafePerformIOWithVector x $ IO.tbsv' alpha (mapTri unsafeBandedToIOBanded a) (unsafeVectorToIOVector y) {-# INLINE tbsv' #-} tbsm' :: (ReadBanded a m, ReadMatrix c m, WriteMatrix b m, BLAS2 e) => e -> Tri a e -> c e -> b e -> m () tbsm' alpha a c b = unsafePerformIOWithMatrix b $ IO.tbsm' alpha (mapTri unsafeBandedToIOBanded a) (unsafeMatrixToIOMatrix c) {-# INLINE tbsm' #-} instance BaseBanded IOBanded where numLower = IO.numLowerIOBanded {-# INLINE numLower #-} numUpper = IO.numUpperIOBanded {-# INLINE numUpper #-} bandwidths = IO.bandwidthsIOBanded {-# INLINE bandwidths #-} ldaBanded = IO.ldaIOBanded {-# INLINE ldaBanded #-} transEnumBanded = IO.transEnumIOBanded {-# INLINE transEnumBanded #-} maybeMatrixStorageFromBanded = IO.maybeMatrixStorageFromIOBanded {-# INLINE maybeMatrixStorageFromBanded #-} maybeBandedFromMatrixStorage = IO.maybeIOBandedFromMatrixStorage {-# INLINE maybeBandedFromMatrixStorage #-} viewVectorAsBanded = IO.viewVectorAsIOBanded {-# INLINE viewVectorAsBanded #-} maybeViewBandedAsVector = IO.maybeViewIOBandedAsVector {-# INLINE maybeViewBandedAsVector #-} unsafeDiagViewBanded = IO.unsafeDiagViewIOBanded {-# INLINE unsafeDiagViewBanded #-} unsafeRowViewBanded = IO.unsafeRowViewIOBanded {-# INLINE unsafeRowViewBanded #-} unsafeColViewBanded = IO.unsafeColViewIOBanded {-# INLINE unsafeColViewBanded #-} unsafeIOBandedToBanded = id {-# INLINE unsafeIOBandedToBanded #-} unsafeBandedToIOBanded = id {-# INLINE unsafeBandedToIOBanded #-} instance ReadBanded IOBanded IO where unsafePerformIOWithBanded a f = f a {-# INLINE unsafePerformIOWithBanded #-} freezeBanded = freezeIOBanded {-# INLINE freezeBanded #-} unsafeFreezeBanded = unsafeFreezeIOBanded {-# INLINE unsafeFreezeBanded #-} instance WriteBanded IOBanded IO where newBanded_ = IO.newIOBanded_ {-# INLINE newBanded_ #-} unsafeConvertIOBanded = id {-# INLINE unsafeConvertIOBanded #-} thawBanded = thawIOBanded {-# INLINE thawBanded #-} unsafeThawBanded = unsafeThawIOBanded {-# INLINE unsafeThawBanded #-} -- | Create a banded matrix with the given shape, bandwidths, and -- associations. The indices in the associations list must all fall -- in the bandwidth of the matrix. Unspecified elements will be set -- to zero. banded :: (Elem e) => (Int,Int) -> (Int,Int) -> [((Int,Int), e)] -> Banded e banded mn kl ies = unsafePerformIO $ unsafeFreezeIOBanded =<< IO.newIOBanded mn kl ies unsafeBanded :: (Elem e) => (Int,Int) -> (Int,Int) -> [((Int,Int), e)] -> Banded e unsafeBanded mn kl ies = unsafePerformIO $ unsafeFreezeIOBanded =<< IO.unsafeNewIOBanded mn kl ies -- | Create a banded matrix of the given shape and bandwidths by specifying -- its diagonal elements. The lists must all have the same length, equal -- to the number of elements in the main diagonal of the matrix. The -- sub-diagonals are specified first, then the super-diagonals. In -- subdiagonal @i@, the first @i@ elements of the list are ignored. listsBanded :: (Elem e) => (Int,Int) -> (Int,Int) -> [[e]] -> Banded e listsBanded mn kl xs = unsafePerformIO $ unsafeFreezeIOBanded =<< IO.newListsIOBanded mn kl xs -- | Create a zero banded matrix with the specified shape and bandwidths. zeroBanded :: (Elem e) => (Int,Int) -> (Int,Int) -> Banded e zeroBanded mn kl = unsafePerformIO $ unsafeFreezeIOBanded =<< IO.newZeroIOBanded mn kl -- | Create a constant banded matrix of the specified shape and bandwidths. constantBanded :: (Elem e) => (Int,Int) -> (Int,Int) -> e -> Banded e constantBanded mn kl e = unsafePerformIO $ unsafeFreezeIOBanded =<< IO.newConstantIOBanded mn kl e -- | Create a banded matrix from a vector. The vector must have length -- equal to one of the specified dimension sizes. bandedFromVector :: (Int,Int) -> Vector e -> Banded e bandedFromVector = viewVectorAsBanded {-# INLINE bandedFromVector #-} -- | Create a diagonal banded matrix from a vector. diagBandedFromVector :: Vector e -> Banded e diagBandedFromVector = viewVectorAsDiagBanded {-# INLINE diagBandedFromVector #-} -- | Convert a diagonal banded matrix to a vector. Fail if the banded -- matrix has more than one diagonal maybeVectorFromBanded :: Banded e -> Maybe (Vector e) maybeVectorFromBanded = maybeViewBandedAsVector {-# INLINE maybeVectorFromBanded #-} -- | Get a the given diagonal in a banded matrix. Negative indices correspond -- to sub-diagonals. diagBanded :: Banded e -> Int -> Vector e diagBanded a = checkedDiag (shape a) (unsafeDiagBanded a) {-# INLINE diagBanded #-} unsafeDiagBanded :: Banded e -> Int -> Vector e unsafeDiagBanded a@(Banded (IOBanded _ _ _ _ _ _ _ _)) i | i >= -kl && i <= ku = unsafeDiagViewBanded a i | otherwise = runSTVector $ newZeroVector $ diagLen (shape a) i where (kl,ku) = bandwidths a {-# INLINE unsafeDiagBanded #-} listsFromBanded :: Banded e -> ((Int,Int), (Int,Int),[[e]]) listsFromBanded a@(Banded (IOBanded _ _ _ _ _ _ _ _)) = ( (m,n) , (kl,ku) , map paddedDiag [(-kl)..ku] ) where (m,n) = shape a (kl,ku) = bandwidths a padBegin i = replicate (max (-i) 0) 0 padEnd i = replicate (max (m-n+i) 0) 0 paddedDiag i = ( padBegin i ++ elems (unsafeDiagViewBanded a i) ++ padEnd i ) instance (Show e) => Show (Banded e) where show a | isHermBanded a = "herm (" ++ show (herm a) ++ ")" | otherwise = let (mn,kl,es) = listsFromBanded a in "listsBanded " ++ show mn ++ " " ++ show kl ++ " " ++ show es compareBandedHelp :: (e -> e -> Bool) -> Banded e -> Banded e -> Bool compareBandedHelp cmp a b | shape a /= shape b = False | isHermBanded a == isHermBanded b && bandwidths a == bandwidths b = let elems' = if isHermBanded a then elems . herm else elems in and $ zipWith cmp (elems' a) (elems' b) | otherwise = let l = max (numLower a) (numLower b) u = max (numUpper a) (numUpper b) in and $ zipWith cmp (diagElems (-l,u) a) (diagElems (-l,u) b) where diagElems bw c = concatMap elems [ diagBanded c i | i <- range bw ] instance (Eq e) => Eq (Banded e) where (==) = compareBandedHelp (==) instance (AEq e) => AEq (Banded e) where (===) = compareBandedHelp (===) (~==) = compareBandedHelp (~==) replaceBandedHelp :: (IOBanded e -> (Int,Int) -> e -> IO ()) -> Banded e -> [((Int,Int), e)] -> Banded e replaceBandedHelp set x ies = unsafePerformIO $ do y <- IO.newCopyIOBanded =<< unsafeThawIOBanded x mapM_ (uncurry $ set y) ies unsafeFreezeIOBanded y {-# NOINLINE replaceBandedHelp #-} tmapBanded :: (e -> e) -> Banded e -> Banded e tmapBanded f a@(Banded (IOBanded _ _ _ _ _ _ _ _)) = case maybeMatrixStorageFromBanded a of Just a' -> fromJust $ maybeBandedFromMatrixStorage (shape a) (bandwidths a) (tmap f a') Nothing -> let f' = conjugate . f . conjugate in herm (tmapBanded f' (herm a)) instance ITensor Banded (Int,Int) where (//) = replaceBandedHelp writeElem {-# INLINE (//) #-} unsafeReplace = replaceBandedHelp unsafeWriteElem {-# INLINE unsafeReplace #-} unsafeAt (Banded a) i = inlinePerformIO (unsafeReadElem a i) {-# INLINE unsafeAt #-} size (Banded a) = IO.sizeIOBanded a {-# INLINE size #-} elems (Banded a) = inlinePerformIO $ getElems a {-# INLINE elems #-} indices (Banded a) = IO.indicesIOBanded a {-# INLINE indices #-} assocs (Banded a) = inlinePerformIO $ getAssocs a {-# INLINE assocs #-} tmap f = tmapBanded f {-# INLINE tmap #-} instance (Monad m) => ReadTensor Banded (Int,Int) m where getSize = return . size {-# INLINE getSize #-} getAssocs = return . assocs {-# INLINE getAssocs #-} getIndices = return . indices {-# INLINE getIndices #-} getElems = return . elems {-# INLINE getElems #-} getAssocs' = return . assocs {-# INLINE getAssocs' #-} getIndices' = return . indices {-# INLINE getIndices' #-} getElems' = return . elems {-# INLINE getElems' #-} unsafeReadElem x i = return (unsafeAt x i) {-# INLINE unsafeReadElem #-} instance HasVectorView Banded where type VectorView Banded = Vector instance HasMatrixStorage Banded where type MatrixStorage Banded = Matrix instance Shaped Banded (Int,Int) where shape (Banded a) = IO.shapeIOBanded a {-# INLINE shape #-} bounds (Banded a) = IO.boundsIOBanded a {-# INLINE bounds #-} instance MatrixShaped Banded where instance HasHerm Banded where herm (Banded a) = Banded $ IO.hermIOBanded a {-# INLINE herm #-} instance BaseBanded Banded where numLower (Banded a) = IO.numLowerIOBanded a {-# INLINE numLower #-} numUpper (Banded a) = IO.numUpperIOBanded a {-# INLINE numUpper #-} bandwidths (Banded a) = IO.bandwidthsIOBanded a {-# INLINE bandwidths #-} ldaBanded (Banded a) = IO.ldaIOBanded a {-# INLINE ldaBanded #-} transEnumBanded (Banded a) = IO.transEnumIOBanded a {-# INLINE transEnumBanded #-} maybeMatrixStorageFromBanded (Banded a) = liftM Matrix $ IO.maybeMatrixStorageFromIOBanded a {-# INLINE maybeMatrixStorageFromBanded #-} maybeBandedFromMatrixStorage mn kl (Matrix a) = liftM Banded $ IO.maybeIOBandedFromMatrixStorage mn kl a {-# INLINE maybeBandedFromMatrixStorage #-} viewVectorAsBanded mn (Vector x) = Banded $ IO.viewVectorAsIOBanded mn x {-# INLINE viewVectorAsBanded #-} maybeViewBandedAsVector (Banded a) = liftM Vector $ IO.maybeViewIOBandedAsVector a {-# INLINE maybeViewBandedAsVector #-} unsafeDiagViewBanded (Banded a) i = Vector $ IO.unsafeDiagViewIOBanded a i {-# INLINE unsafeDiagViewBanded #-} unsafeRowViewBanded (Banded a) i = case IO.unsafeRowViewIOBanded a i of (nb,x,na) -> (nb, Vector x, na) {-# INLINE unsafeRowViewBanded #-} unsafeColViewBanded (Banded a) j = case IO.unsafeColViewIOBanded a j of (nb,x,na) -> (nb, Vector x, na) {-# INLINE unsafeColViewBanded #-} unsafeIOBandedToBanded = Banded {-# INLINE unsafeIOBandedToBanded #-} unsafeBandedToIOBanded (Banded a) = a {-# INLINE unsafeBandedToIOBanded #-} -- The NOINLINE pragmas and the strictness annotations here are *really* -- important. Otherwise, the compiler might think that certain actions -- don't need to be run. instance (MonadInterleave m) => ReadBanded Banded m where freezeBanded (Banded a) = return $! unsafePerformIO $ freezeIOBanded a {-# NOINLINE freezeBanded #-} unsafeFreezeBanded = return . id {-# INLINE unsafeFreezeBanded #-} unsafePerformIOWithBanded (Banded a) f = return $! unsafePerformIO $ f a {-# NOINLINE unsafePerformIOWithBanded #-} instance (MonadInterleave m) => MMatrix Banded m where unsafeDoSApplyAddVector = gbmv {-# INLINE unsafeDoSApplyAddVector #-} unsafeDoSApplyAddMatrix = gbmm {-# INLINE unsafeDoSApplyAddMatrix #-} unsafeGetRow = unsafeGetRowBanded {-# INLINE unsafeGetRow #-} unsafeGetCol = unsafeGetColBanded {-# INLINE unsafeGetCol #-} instance (MonadInterleave m) => MMatrix (Herm Banded) m where unsafeDoSApplyAddVector = hbmv {-# INLINE unsafeDoSApplyAddVector #-} unsafeDoSApplyAddMatrix = hbmm {-# INLINE unsafeDoSApplyAddMatrix #-} unsafeGetRow = unsafeGetRowHermBanded {-# INLINE unsafeGetRow #-} unsafeGetCol = unsafeGetColHermBanded {-# INLINE unsafeGetCol #-} instance (MonadInterleave m) => MMatrix (Tri Banded) m where unsafeDoSApplyVector_ = tbmv {-# INLINE unsafeDoSApplyVector_ #-} unsafeDoSApplyMatrix_ = tbmm {-# INLINE unsafeDoSApplyMatrix_ #-} unsafeDoSApplyAddVector = tbmv' {-# INLINE unsafeDoSApplyAddVector #-} unsafeDoSApplyAddMatrix = tbmm' {-# INLINE unsafeDoSApplyAddMatrix #-} unsafeGetRow = unsafeGetRowTriBanded {-# INLINE unsafeGetRow #-} unsafeGetCol = unsafeGetColTriBanded {-# INLINE unsafeGetCol #-} instance (MonadInterleave m) => MSolve (Tri Banded) m where unsafeDoSSolveVector_ = tbsv {-# INLINE unsafeDoSSolveVector_ #-} unsafeDoSSolveMatrix_ = tbsm {-# INLINE unsafeDoSSolveMatrix_ #-} unsafeDoSSolveVector = tbsv' {-# INLINE unsafeDoSSolveVector #-} unsafeDoSSolveMatrix = tbsm' {-# INLINE unsafeDoSSolveMatrix #-} instance IMatrix Banded where unsafeSApplyVector alpha a x = runSTVector $ unsafeGetSApplyVector alpha a x {-# INLINE unsafeSApplyVector #-} unsafeSApplyMatrix alpha a b = runSTMatrix $ unsafeGetSApplyMatrix alpha a b {-# INLINE unsafeSApplyMatrix #-} unsafeRow a i = runSTVector $ unsafeGetRow a i {-# INLINE unsafeRow #-} unsafeCol a j = runSTVector $ unsafeGetCol a j {-# INLINE unsafeCol #-} instance IMatrix (Herm Banded) where unsafeSApplyVector alpha a x = runSTVector $ unsafeGetSApplyVector alpha a x {-# INLINE unsafeSApplyVector #-} unsafeSApplyMatrix alpha a b = runSTMatrix $ unsafeGetSApplyMatrix alpha a b {-# INLINE unsafeSApplyMatrix #-} unsafeRow a i = runSTVector $ unsafeGetRow a i {-# INLINE unsafeRow #-} unsafeCol a j = runSTVector $ unsafeGetCol a j {-# INLINE unsafeCol #-} instance IMatrix (Tri Banded) where unsafeSApplyVector alpha a x = runSTVector $ unsafeGetSApplyVector alpha a x {-# INLINE unsafeSApplyVector #-} unsafeSApplyMatrix alpha a b = runSTMatrix $ unsafeGetSApplyMatrix alpha a b {-# INLINE unsafeSApplyMatrix #-} unsafeRow a i = runSTVector $ unsafeGetRow a i {-# INLINE unsafeRow #-} unsafeCol a j = runSTVector $ unsafeGetCol a j {-# INLINE unsafeCol #-} instance ISolve (Tri Banded) where unsafeSSolveVector alpha a y = runSTVector $ unsafeGetSSolveVector alpha a y {-# NOINLINE unsafeSSolveVector #-} unsafeSSolveMatrix alpha a c = runSTMatrix $ unsafeGetSSolveMatrix alpha a c {-# NOINLINE unsafeSSolveMatrix #-} -- | Banded matrix in the 'ST' monad. The type arguments are as follows: -- -- * @s@: the state variable argument for the 'ST' type -- -- * @e@: the element type of the matrix. Only certain element types -- are supported. -- newtype STBanded s e = STBanded (IOBanded e) -- | A safe way to create and work with a mutable banded matrix before returning -- an immutable one for later perusal. This function avoids copying -- the matrix before returning it - it uses unsafeFreezeBanded internally, -- but this wrapper is a safe interface to that function. runSTBanded :: (forall s . ST s (STBanded s e)) -> Banded e runSTBanded mx = runST $ mx >>= \(STBanded x) -> return (Banded x) instance HasVectorView (STBanded s) where type VectorView (STBanded s) = STVector s instance HasMatrixStorage (STBanded s) where type MatrixStorage (STBanded s) = (STMatrix s) instance Shaped (STBanded s) (Int,Int) where shape (STBanded a) = IO.shapeIOBanded a {-# INLINE shape #-} bounds (STBanded a) = IO.boundsIOBanded a {-# INLINE bounds #-} instance MatrixShaped (STBanded s) where instance HasHerm (STBanded s) where herm (STBanded a) = STBanded $ IO.hermIOBanded a {-# INLINE herm #-} instance ReadTensor (STBanded s) (Int,Int) (ST s) where getSize (STBanded a) = unsafeIOToST $ IO.getSizeIOBanded a {-# INLINE getSize #-} getAssocs (STBanded a) = unsafeIOToST $ IO.getAssocsIOBanded a {-# INLINE getAssocs #-} getIndices (STBanded a) = unsafeIOToST $ IO.getIndicesIOBanded a {-# INLINE getIndices #-} getElems (STBanded a) = unsafeIOToST $ IO.getElemsIOBanded a {-# INLINE getElems #-} getAssocs' (STBanded a) = unsafeIOToST $ IO.getAssocsIOBanded' a {-# INLINE getAssocs' #-} getIndices' (STBanded a) = unsafeIOToST $ IO.getIndicesIOBanded' a {-# INLINE getIndices' #-} getElems' (STBanded a) = unsafeIOToST $ IO.getElemsIOBanded' a {-# INLINE getElems' #-} unsafeReadElem (STBanded a) i = unsafeIOToST $ IO.unsafeReadElemIOBanded a i {-# INLINE unsafeReadElem #-} instance WriteTensor (STBanded s) (Int,Int) (ST s) where setConstant k (STBanded a) = unsafeIOToST $ IO.setConstantIOBanded k a {-# INLINE setConstant #-} setZero (STBanded a) = unsafeIOToST $ IO.setZeroIOBanded a {-# INLINE setZero #-} modifyWith f (STBanded a) = unsafeIOToST $ IO.modifyWithIOBanded f a {-# INLINE modifyWith #-} unsafeWriteElem (STBanded a) i e = unsafeIOToST $ IO.unsafeWriteElemIOBanded a i e {-# INLINE unsafeWriteElem #-} canModifyElem (STBanded a) i = unsafeIOToST $ IO.canModifyElemIOBanded a i {-# INLINE canModifyElem #-} instance BaseBanded (STBanded s) where numLower (STBanded a) = IO.numLowerIOBanded a {-# INLINE numLower #-} numUpper (STBanded a) = IO.numUpperIOBanded a {-# INLINE numUpper #-} bandwidths (STBanded a) = IO.bandwidthsIOBanded a {-# INLINE bandwidths #-} ldaBanded (STBanded a) = IO.ldaIOBanded a {-# INLINE ldaBanded #-} transEnumBanded (STBanded a) = IO.transEnumIOBanded a {-# INLINE transEnumBanded #-} maybeMatrixStorageFromBanded (STBanded a) = liftM STMatrix $ IO.maybeMatrixStorageFromIOBanded a {-# INLINE maybeMatrixStorageFromBanded #-} maybeBandedFromMatrixStorage mn kl (STMatrix a) = liftM STBanded $ IO.maybeIOBandedFromMatrixStorage mn kl a {-# INLINE maybeBandedFromMatrixStorage #-} viewVectorAsBanded mn (STVector x) = STBanded $ IO.viewVectorAsIOBanded mn x {-# INLINE viewVectorAsBanded #-} maybeViewBandedAsVector (STBanded a) = liftM STVector $ IO.maybeViewIOBandedAsVector a {-# INLINE maybeViewBandedAsVector #-} unsafeDiagViewBanded (STBanded a) i = STVector $ IO.unsafeDiagViewIOBanded a i {-# INLINE unsafeDiagViewBanded #-} unsafeRowViewBanded (STBanded a) i = case IO.unsafeRowViewIOBanded a i of (nb,x,na) -> (nb, STVector x, na) {-# INLINE unsafeRowViewBanded #-} unsafeColViewBanded (STBanded a) j = case IO.unsafeColViewIOBanded a j of (nb,x,na) -> (nb, STVector x, na) {-# INLINE unsafeColViewBanded #-} unsafeIOBandedToBanded = STBanded {-# INLINE unsafeIOBandedToBanded #-} unsafeBandedToIOBanded (STBanded a) = a {-# INLINE unsafeBandedToIOBanded #-} instance ReadBanded (STBanded s) (ST s) where unsafePerformIOWithBanded (STBanded a) f = unsafeIOToST $ f a {-# INLINE unsafePerformIOWithBanded #-} freezeBanded (STBanded a) = unsafeIOToST $ freezeIOBanded a {-# INLINE freezeBanded #-} unsafeFreezeBanded (STBanded a) = unsafeIOToST $ unsafeFreezeIOBanded a {-# INLINE unsafeFreezeBanded #-} instance WriteBanded (STBanded s) (ST s) where newBanded_ mn bw = unsafeIOToST $ liftM STBanded $ IO.newIOBanded_ mn bw {-# INLINE newBanded_ #-} thawBanded = unsafeIOToST . liftM STBanded . thawIOBanded {-# INLINE thawBanded #-} unsafeThawBanded = unsafeIOToST . liftM STBanded . unsafeThawIOBanded {-# INLINE unsafeThawBanded #-} unsafeConvertIOBanded ioa = unsafeIOToST $ liftM STBanded ioa {-# INLINE unsafeConvertIOBanded #-} instance MMatrix (STBanded s) (ST s) where unsafeDoSApplyAddVector = gbmv {-# INLINE unsafeDoSApplyAddVector #-} unsafeDoSApplyAddMatrix = gbmm {-# INLINE unsafeDoSApplyAddMatrix #-} unsafeGetRow = unsafeGetRowBanded {-# INLINE unsafeGetRow #-} unsafeGetCol = unsafeGetColBanded {-# INLINE unsafeGetCol #-} instance MMatrix (Herm (STBanded s)) (ST s) where unsafeDoSApplyAddVector = hbmv {-# INLINE unsafeDoSApplyAddVector #-} unsafeDoSApplyAddMatrix = hbmm {-# INLINE unsafeDoSApplyAddMatrix #-} unsafeGetRow = unsafeGetRowHermBanded {-# INLINE unsafeGetRow #-} unsafeGetCol = unsafeGetColHermBanded {-# INLINE unsafeGetCol #-} instance MMatrix (Tri (STBanded s)) (ST s) where unsafeDoSApplyVector_ = tbmv {-# INLINE unsafeDoSApplyVector_ #-} unsafeDoSApplyMatrix_ = tbmm {-# INLINE unsafeDoSApplyMatrix_ #-} unsafeDoSApplyAddVector = tbmv' {-# INLINE unsafeDoSApplyAddVector #-} unsafeDoSApplyAddMatrix = tbmm' {-# INLINE unsafeDoSApplyAddMatrix #-} unsafeGetRow = unsafeGetRowTriBanded {-# INLINE unsafeGetRow #-} unsafeGetCol = unsafeGetColTriBanded {-# INLINE unsafeGetCol #-} instance MSolve (Tri (STBanded s)) (ST s) where unsafeDoSSolveVector_ = tbsv {-# INLINE unsafeDoSSolveVector_ #-} unsafeDoSSolveMatrix_ = tbsm {-# INLINE unsafeDoSSolveMatrix_ #-} unsafeDoSSolveVector = tbsv' {-# INLINE unsafeDoSSolveVector #-} unsafeDoSSolveMatrix = tbsm' {-# INLINE unsafeDoSSolveMatrix #-}
patperry/hs-linear-algebra
lib/Data/Matrix/Banded/Base.hs
bsd-3-clause
37,697
0
14
8,806
9,481
4,964
4,517
-1
-1
-------------------------------------------------------------------------------- -- | -- Module : Test.Connection -- Copyright : (C) 2017 Yorick Laupa -- License : (see the file LICENSE) -- -- Maintainer : Yorick Laupa <[email protected]> -- Stability : provisional -- Portability : non-portable -- -------------------------------------------------------------------------------- module Test.Connection (spec) where -------------------------------------------------------------------------------- import Database.EventStore.Internal.Test hiding (i) -------------------------------------------------------------------------------- import Test.Bogus.Connection import Test.Common import Test.Tasty.Hspec spec :: Spec spec = beforeAll (createLoggerRef testGlobalLog) $ do specify "Connection should retry on connection failure" $ \logRef -> do counter <- newCounter bus <- newBus logRef testSettings let builder = alwaysFailConnectionBuilder $ incrCounter counter disc = staticEndPointDiscovery "localhost" 2000 exec <- newExec testSettings bus builder disc atomically $ do i <- readCounterSTM counter when (i /= 3) retrySTM publishWith exec SystemShutdown execWaitTillClosed exec specify "Connection should close on heartbeat timeout" $ \logRef -> do counter <- newCounter bus <- newBus logRef testSettings let builder = silentConnectionBuilder $ incrCounter counter disc = staticEndPointDiscovery "localhost" 2000 exec <- newExec testSettings bus builder disc atomically $ do i <- readCounterSTM counter unless (i > 1) retrySTM publishWith exec SystemShutdown execWaitTillClosed exec
YoEight/eventstore
tests/Test/Connection.hs
bsd-3-clause
1,708
0
17
298
321
158
163
29
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. 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.RO (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 = -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}}), ("absorption of , after 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}}), ("acum", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("intersect", Classifier{okData = ClassData{prior = -0.13353139262452263, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("daymonth", -1.9924301646902063), ("dayday", -1.2992829841302609), ("<named-day> <day-of-month> (number)named-month", -1.9924301646902063), ("absorption of , after named day<day-of-month>(number) <named-month>", -1.9924301646902063), ("absorption of , after named day<day-of-month> (non ordinal) <named-month>", -1.9924301646902063), ("named-daythe <day-of-month> (number)", -2.3978952727983707)], n = 7}, koData = ClassData{prior = -2.0794415416798357, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("named-month<hour-of-day> <integer> (as relative minutes)", -1.6094379124341003), ("monthminute", -1.6094379124341003)], n = 1}}), ("<named-day> <day-of-month> (number)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("named-dayinteger (numeric)", -1.2992829841302609), ("day", -0.7884573603642702), ("absorption of , after named dayinteger (numeric)", -1.2992829841302609)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("named-month", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("numbers prefix with - or minus", 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}}), ("craciun", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("the <day-of-month> (number)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("time-of-day (latent)", 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}}), ("ieri", 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}}), ("intersect by \",\"", Classifier{okData = ClassData{prior = 0.0, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("dayday", -0.7884573603642702), ("named-day<day-of-month>(number) <named-month>", -1.2992829841302609), ("named-day<day-of-month> (non ordinal) <named-month>", -1.2992829841302609)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("azi", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("named-day", Classifier{okData = ClassData{prior = 0.0, unseen = -3.1780538303479458, likelihoods = HashMap.fromList [("", 0.0)], n = 22}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<named-day> pe <day-of-month> (number)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("named-dayinteger (numeric)", -0.6931471805599453), ("day", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("integer (0..10)", 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}}), ("<time> (aceasta|acesta|[a\259]sta)", 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}}), ("<named-month> <day-of-month> (non ordinal)", Classifier{okData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("named-monthinteger (numeric)", -0.6931471805599453), ("month", -0.6931471805599453)], n = 1}}), ("<day-of-month> (non ordinal) <named-month>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("integer (numeric)named-month", -1.0116009116784799), ("integer (0..10)named-month", -1.7047480922384253), ("month", -0.7884573603642702)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("this|next <day-of-week>", 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}}), ("maine", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<month> dd-dd (interval)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("named-month", -0.6931471805599453), ("month", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("<hour-of-day> <integer> (as relative minutes)", Classifier{okData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("time-of-day (latent)integer (numeric)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 1}}), ("<day-of-month>(number) <named-month>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("integer (numeric)named-month", -1.0116009116784799), ("integer (0..10)named-month", -1.7047480922384253), ("month", -0.7884573603642702)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}})]
rfranek/duckling
Duckling/Ranking/Classifiers/RO.hs
bsd-3-clause
14,669
0
15
6,829
2,787
1,730
1,057
251
1
module Main where import File import Git main :: IO () main = do pullFilesToDisk addCommitPush "Feeling hard working today!"
gaoyuan/CodeThief
src/Main.hs
bsd-3-clause
131
0
7
26
34
18
16
7
1
{-# LANGUAGE TemplateHaskell, RankNTypes, ScopedTypeVariables #-} {-# LANGUAGE ViewPatterns, DeriveGeneric #-} -- | This analysis identifies the addRef and decRef functions for a library, -- along with the set of types that is reference counted. This analysis is -- unsound and incomplete, but still useful. -- -- It first identifies the decRef function with a heuristic: -- -- 1) Find a function that conditionally calls a finalizer -- -- 2) The finalizer call is guarded by a conditional check of an -- access path p (whose *base* is reachable from an argument to the -- function), and -- -- 3) That same access path p is decremented -- -- The incRef function is simply the function that increments access -- path p -- -- The set of types that are reference counted by a given -- incRef/decRef pair are those types that are structural subtypes of -- the argument to decRef (after derefencing the pointer, since all of -- these types are passed by pointer). module Foreign.Inference.Analysis.RefCount ( RefCountSummary, identifyRefCounting, -- * Testing refCountSummaryToTestFormat ) where import GHC.Generics ( Generic ) import Control.Arrow import Control.DeepSeq import Control.DeepSeq.Generics ( genericRnf ) import Control.Lens ( Getter, Lens', makeLenses, view, to, (%~), (^.), (.~) ) import Data.Foldable ( find ) import Data.HashSet ( HashSet ) import qualified Data.HashSet as HS import Data.HashMap.Strict ( HashMap ) import qualified Data.HashMap.Strict as HM import Data.Map ( Map ) import qualified Data.Map as M import Data.Maybe ( catMaybes, mapMaybe ) import Data.Monoid import LLVM.Analysis import LLVM.Analysis.AccessPath import LLVM.Analysis.CFG import LLVM.Analysis.CallGraphSCCTraversal import Foreign.Inference.AnalysisMonad import Foreign.Inference.Analysis.Finalize import Foreign.Inference.Analysis.ScalarEffects import Foreign.Inference.Diagnostics import Foreign.Inference.Interface -- import Text.Printf -- import Debug.Trace -- debug = flip trace -- | The data needed to track unref functions. The -- @unrefCountAccessPath@ is the access path to the struct field that -- serves as the reference count (and is decremented in the unref -- function). -- -- The @unrefFuncPtrCalls@ are the access paths of function pointers -- called in the unref function. The idea is that these functions -- will tell us the types that are involved in reference counting for -- object systems like glib. For example, assuming the following line -- is in an unref function -- -- > obj->finalize(obj) -- -- and (in some other function) -- -- > obj->class = cls; -- > cls->finalize = finalizeFoo; -- -- and -- -- > void finalizeFoo(Object *o) { -- > RealObject* obj = (RealObject*)o; -- > // use obj -- > } -- -- This tells us that the type RealObject is reference counted. We -- just need to look at places where the field recorded here is -- initialized with a function and then analyze the types used by that -- function. data UnrefData = UnrefData { unrefCountAccessPath :: AbstractAccessPath , unrefFuncPtrCalls :: [AbstractAccessPath] , unrefWitnesses :: [Witness] } deriving (Eq, Generic) instance NFData UnrefData where rnf = genericRnf -- | Summary information for the reference counting analysis data RefCountSummary = RefCountSummary { _conditionalFinalizers :: HashSet Function , _unrefArguments :: HashMap Argument UnrefData , _refArguments :: HashMap Argument (AbstractAccessPath, [Witness]) , _refCountedTypes :: HashMap (String, String) (HashSet Type) , _refCountDiagnostics :: !Diagnostics } deriving (Generic) $(makeLenses ''RefCountSummary) instance Monoid RefCountSummary where mempty = RefCountSummary mempty mempty mempty mempty mempty mappend (RefCountSummary s1 a1 r1 rcts1 d1) (RefCountSummary s2 a2 r2 rcts2 d2) = RefCountSummary { _conditionalFinalizers = s1 `mappend` s2 , _unrefArguments = a1 `mappend` a2 , _refArguments = r1 `mappend` r2 , _refCountedTypes = HM.unionWith HS.union rcts1 rcts2 , _refCountDiagnostics = d1 `mappend` d2 } instance NFData RefCountSummary where rnf = genericRnf instance Eq RefCountSummary where (RefCountSummary s1 a1 r1 rcts1 _) == (RefCountSummary s2 a2 r2 rcts2 _) = s1 == s2 && a1 == a2 && r1 == r2 && rcts1 == rcts2 instance HasDiagnostics RefCountSummary where diagnosticLens = refCountDiagnostics -- | The summarizing functions match incref and decref functions. We -- need to do that here rather than on the fly since either could be -- analyzed before the other, so every analysis step would have to try -- to match up any outstanding references. Here we can just do it on -- demand. -- -- Matching is done based on argument type and the access path used to -- modify the reference count parameter. If an unref function matches -- up with exactly one ref function, they are paired by name. The -- code generator should deal with it appropriately. instance SummarizeModule RefCountSummary where summarizeFunction _ _ = [] summarizeArgument a (RefCountSummary _ unrefArgs refArgs _ _) = case HM.lookup a unrefArgs of Nothing -> case HM.lookup a refArgs of Nothing -> [] Just (fieldPath, ws) -> case matchingTypeAndPath (argumentType a) fieldPath unrefCountAccessPath unrefArgs of Nothing -> [(PAAddRef "", ws)] Just fname -> [(PAAddRef fname, ws)] Just (UnrefData fieldPath fptrPaths ws) -> case matchingTypeAndPath (argumentType a) fieldPath fst refArgs of Nothing -> [(PAUnref "" (mapMaybe externalizeAccessPath fptrPaths) [], ws)] Just fname -> let unrefFunc = argumentFunction a unrefName = identifierAsString (functionName unrefFunc) ssts = HS.toList $ argumentCastedTypes a structuralSupertypes = mapMaybe (structTypeToName . stripPointerTypes) ssts in [(PAUnref fname (mapMaybe externalizeAccessPath fptrPaths) structuralSupertypes, ws)] summarizeType t (RefCountSummary _ _ _ rcTypes _) = case t of CStruct n _ -> case find entryForType (HM.toList rcTypes) of Nothing -> [] Just ((addRef, decRef), _) -> [(TARefCounted addRef decRef, [])] where entryForType (_, typeSet) = let groupTypeNames = mapMaybe (structTypeToName . stripPointerTypes) (HS.toList typeSet) in n `elem` groupTypeNames _ -> [] matchingTypeAndPath :: Type -> AbstractAccessPath -> (a -> AbstractAccessPath) -> HashMap Argument a -> Maybe String matchingTypeAndPath t accPath toPath m = case filter matchingPair pairs of [(singleMatch, _)] -> let f = argumentFunction singleMatch in Just $ identifierAsString (functionName f) _ -> Nothing where pairs = HM.toList m matchingPair (arg, d) = argumentType arg == t && (toPath d) == accPath type Analysis = AnalysisMonad () () -- | The main analysis to identify both incref and decref functions. identifyRefCounting :: forall compositeSummary funcLike . (FuncLike funcLike, HasFunction funcLike, HasCFG funcLike) => DependencySummary -> Lens' compositeSummary RefCountSummary -> Getter compositeSummary FinalizerSummary -> Getter compositeSummary ScalarEffectSummary -> ComposableAnalysis compositeSummary funcLike identifyRefCounting ds lns depLens1 depLens2 = composableDependencyAnalysisM runner refCountAnalysis lns depLens where runner a = runAnalysis a ds () () depLens :: Getter compositeSummary (FinalizerSummary, ScalarEffectSummary) depLens = to (view depLens1 &&& view depLens2) -- | Check to see if the given function is a conditional finalizer. -- If it is, return the call instruction that (conditionally) invokes -- a finalizer AND the argument being finalized. -- -- This argument is needed for later steps. -- -- Note that no finalizer is allowed to be a conditional finalizer isConditionalFinalizer :: FinalizerSummary -> Function -> Analysis (Maybe (Instruction, Argument)) isConditionalFinalizer summ f = do fin <- functionIsFinalizer summ f case fin of True -> return Nothing False -> do -- Find the list of all arguments that are finalized in the -- function. finArgs <- mapM (isFinalizerCall summ) (functionInstructions f) case catMaybes finArgs of -- case mapMaybe (isFinalizerCall summ) (functionInstructions f) of [] -> return Nothing -- If there is more than one match, ensure that they all -- finalize the same argument. If that is not the case, -- return Nothing x@(_, a) : rest -> case all (==a) (map snd rest) of False -> return Nothing True -> return (Just x) isFinalizerCall :: FinalizerSummary -> Instruction -> Analysis (Maybe (Instruction, Argument)) isFinalizerCall summ i = case i of CallInst { callFunction = callee, callArguments = args } -> callFinalizes summ i callee (map fst args) InvokeInst { invokeFunction = callee, invokeArguments = args } -> callFinalizes summ i callee (map fst args) _ -> return Nothing -- | If the given call (value + args) is a finalizer, return the -- Argument it is finalizing. If it is a finalizer but does not -- finalize an argument, returns Nothing. callFinalizes :: FinalizerSummary -> Instruction -> Value -- ^ The called value -> [Value] -- ^ Actual arguments -> Analysis (Maybe (Instruction, Argument)) callFinalizes fs i callee args = do finArgs <- mapM isFinalizedArgument (zip [0..] args) case catMaybes finArgs of [finArg] -> return $ Just (i, finArg) _ -> return Nothing where isFinalizedArgument (ix, arg) = do annots <- lookupArgumentSummaryList fs callee ix case (PAFinalize `elem` annots, valueContent' arg) of (False, _) -> return Nothing -- We only return a hit if this is an Argument to the *caller* -- that is being finalized (True, ArgumentC a) -> return (Just a) (True, _) -> return Nothing functionIsFinalizer :: FinalizerSummary -> Function -> Analysis Bool functionIsFinalizer fs f = do allArgAnnots <- mapM (lookupArgumentSummaryList fs f) [0..maxArg] return $ any argFinalizes allArgAnnots where maxArg = length (functionParameters f) - 1 argFinalizes annots = PAFinalize `elem` annots refCountAnalysis :: (FuncLike funcLike, HasCFG funcLike, HasFunction funcLike) => (FinalizerSummary, ScalarEffectSummary) -> funcLike -> RefCountSummary -> Analysis RefCountSummary refCountAnalysis (finSumm, seSumm) funcLike summ = do let summ' = incRefAnalysis seSumm f summ condFinData <- isConditionalFinalizer finSumm f rcTypes <- refCountTypes f let summ'' = (refCountedTypes %~ HM.unionWith HS.union rcTypes) summ' case condFinData of Nothing -> return summ'' Just (cfi, cfa) -> let summWithCondFin = (conditionalFinalizers %~ HS.insert f) summ'' finWitness = Witness cfi "condfin" fptrAccessPaths = mapMaybe (indirectCallAccessPath cfa) (functionInstructions f) -- If this is a conditional finalizer, figure out which -- field (if any) is unrefed. newUnref = case (decRefCountFields seSumm f, functionParameters f) of ([(accPath, decWitness)], [a]) -> let ud = UnrefData accPath fptrAccessPaths [finWitness, decWitness] in HM.insert a ud _ -> id summWithUnref = (unrefArguments %~ newUnref) summWithCondFin in return summWithUnref where f = getFunction funcLike refCountTypes :: Function -> Analysis (HashMap (String, String) (HashSet Type)) refCountTypes f = do ds <- getDependencySummary let fptrFuncs = mapMaybe (identifyIndicatorFields ds) (functionInstructions f) rcTypesByField = map (id *** unaryFuncToCastedArgTypes) fptrFuncs structuralRefTypes = mapMaybe (subtypeRefCountTypes ds) interfaceTypes rcTypes = rcTypesByField ++ structuralRefTypes return $ foldr (\(k, v) m -> HM.insertWith HS.union k v m) mempty rcTypes where interfaceTypes = functionReturnType f : map argumentType (functionParameters f) identifyIndicatorFields ds i = case i of StoreInst { storeValue = (valueContent' -> FunctionC sv) } -> case accessPath i of Nothing -> Nothing Just cAccPath -> do let aAccPath = abstractAccessPath cAccPath refFuncs <- refCountFunctionsForField ds aAccPath return (refFuncs, sv) _ -> Nothing subtypeRefCountTypes :: DependencySummary -> Type -> Maybe ((String, String), HashSet Type) subtypeRefCountTypes ds t0 = go t1 where t1 = stripPointerTypes t0 go t = case t of TypeStruct _ (structuralParent:_) _ -> do -- If this type is known to be ref counted, just return. -- Otherwise, check if any structural parents of this type are -- known to be ref counted. We check this by considering the -- constituent types of t. If the first one is a struct type, -- that is the structural parent (since they are -- interchangable to code expecting the parent type). case isRefCountedObject ds t of Just rcFuncs -> return (rcFuncs, HS.singleton t1) Nothing -> go structuralParent TypeStruct _ _ _ -> do rcFuncs <- isRefCountedObject ds t return (rcFuncs, HS.singleton t1) _ -> Nothing -- | If the function is unary, return a set with the type of that -- argument along with all of the types it is casted to in the body of -- the function unaryFuncToCastedArgTypes :: Function -> HashSet Type unaryFuncToCastedArgTypes f = case functionParameters f of [p] -> argumentCastedTypes p _ -> mempty argumentCastedTypes :: Argument -> HashSet Type argumentCastedTypes a = fst $ foldr captureCastedType s0 (functionInstructions f) where f = argumentFunction a s0 = (HS.singleton (argumentType a), HS.singleton (toValue a)) captureCastedType i acc@(ts, vs) = case i of BitcastInst { castedValue = cv } -> case cv `HS.member` vs of False -> acc True -> (HS.insert (valueType i) ts, HS.insert (toValue i) vs) _ -> acc incRefAnalysis :: ScalarEffectSummary -> Function -> RefCountSummary -> RefCountSummary incRefAnalysis seSumm f summ = case (incRefCountFields seSumm f, functionParameters f) of ([], _) -> summ ([(fieldPath, w)], [a]) -> let newAddRef = HM.insert a (fieldPath, [w]) (summ ^. refArguments) in (refArguments .~ newAddRef) summ _ -> summ -- Note, here pass in the argument that is conditionally finalized. It should -- be an argument to this indirect call. Additionally, the base of the access -- path should be this argument -- | If the instruction is an indirect function call, return the -- *concrete* AccessPath from which the function pointer was obtained. indirectCallAccessPath :: Argument -> Instruction -> Maybe AbstractAccessPath indirectCallAccessPath arg i = case i of CallInst { callFunction = f, callArguments = actuals } -> notDirect f (map fst actuals) InvokeInst { invokeFunction = f, invokeArguments = actuals } -> notDirect f (map fst actuals) _ -> Nothing where -- The only indirect calls occur through a load instruction. -- Additionally, we want the Argument input to the caller to -- appear in the argument list of the indirect call. -- -- Ideally, we would like to ensure that the function pointer -- being invoked is in some way derived from the argument being -- finalized. This is a kind of backwards reachability from the -- base of the access path notDirect v actuals = case (any (isSameArg arg) actuals, valueContent' v) of (True, InstructionC callee@LoadInst {}) -> do accPath <- accessPath callee return $! abstractAccessPath accPath _ -> Nothing isSameArg :: Argument -> Value -> Bool isSameArg arg v = case valueContent' v of ArgumentC a -> arg == a _ -> False -- FIXME: Equality with arg isn't enough because of bitcasts -- | Find all of the fields of argument objects that are decremented -- in the given Function, returning the affected AbstractAccessPaths decRefCountFields :: ScalarEffectSummary -> Function -> [(AbstractAccessPath, Witness)] decRefCountFields seSumm f = mapMaybe (checkDecRefCount seSumm) allInsts where allInsts = concatMap basicBlockInstructions (functionBody f) -- | Likewise, but for incremented fields incRefCountFields :: ScalarEffectSummary -> Function -> [(AbstractAccessPath, Witness)] incRefCountFields seSumm f = mapMaybe (checkIncRefCount seSumm) allInsts where allInsts = concatMap basicBlockInstructions (functionBody f) -- | This function checks whether or not the given 'Instruction' -- decrements a reference count (really, any integer field embedded in -- an object). If it does, the function returns the -- AbstractAccessPath that was decremented. -- -- FIXME: Add support for cmpxchg? checkDecRefCount :: ScalarEffectSummary -> Instruction -> Maybe (AbstractAccessPath, Witness) checkDecRefCount seSumm i = do p <- case i of AtomicRMWInst { atomicRMWOperation = AOSub , atomicRMWValue = (valueContent -> ConstantC ConstantInt { constantIntValue = 1 })} -> absPathIfArg i AtomicRMWInst { atomicRMWOperation = AOAdd , atomicRMWValue = (valueContent -> ConstantC ConstantInt { constantIntValue = -1 })} -> absPathIfArg i StoreInst { storeValue = (valueContent' -> InstructionC SubInst { binaryRhs = (valueContent' -> ConstantC ConstantInt { constantIntValue = 1 }) , binaryLhs = (valueContent' -> InstructionC oldRefCount) })} -> absPathIfArg oldRefCount StoreInst { storeValue = (valueContent' -> InstructionC AddInst { binaryRhs = (valueContent' -> ConstantC ConstantInt { constantIntValue = -1 }) , binaryLhs = (valueContent' -> InstructionC oldRefCount) })} -> absPathIfArg oldRefCount StoreInst { storeValue = (valueContent' -> InstructionC AddInst { binaryLhs = (valueContent' -> ConstantC ConstantInt { constantIntValue = -1 }) , binaryRhs = (valueContent' -> InstructionC oldRefCount) })} -> absPathIfArg oldRefCount CallInst { callFunction = (valueContent' -> FunctionC f) , callArguments = [(a,_)] } -> absPathThroughCall seSumm scalarEffectSubOne (functionParameters f) a InvokeInst { invokeFunction = (valueContent' -> FunctionC f) , invokeArguments = [(a,_)] } -> absPathThroughCall seSumm scalarEffectSubOne (functionParameters f) a _ -> Nothing return (p, Witness i "decr") -- | Analogous to 'checkDecRefCount', but for increments checkIncRefCount :: ScalarEffectSummary -> Instruction -> Maybe (AbstractAccessPath, Witness) checkIncRefCount seSumm i = do p <- case i of AtomicRMWInst { atomicRMWOperation = AOAdd , atomicRMWValue = (valueContent -> ConstantC ConstantInt { constantIntValue = 1 })} -> absPathIfArg i AtomicRMWInst { atomicRMWOperation = AOSub , atomicRMWValue = (valueContent -> ConstantC ConstantInt { constantIntValue = -1 })} -> absPathIfArg i StoreInst { storeValue = (valueContent' -> InstructionC SubInst { binaryRhs = (valueContent' -> ConstantC ConstantInt { constantIntValue = -1 }) , binaryLhs = (valueContent' -> InstructionC oldRefCount) })} -> absPathIfArg oldRefCount StoreInst { storeValue = (valueContent' -> InstructionC AddInst { binaryRhs = (valueContent' -> ConstantC ConstantInt { constantIntValue = 1 }) , binaryLhs = (valueContent' -> InstructionC oldRefCount) })} -> absPathIfArg oldRefCount StoreInst { storeValue = (valueContent' -> InstructionC AddInst { binaryLhs = (valueContent' -> ConstantC ConstantInt { constantIntValue = 1 }) , binaryRhs = (valueContent' -> InstructionC oldRefCount) })} -> absPathIfArg oldRefCount CallInst { callFunction = (valueContent' -> FunctionC f) , callArguments = [(a,_)] } -> absPathThroughCall seSumm scalarEffectAddOne (functionParameters f) a InvokeInst { invokeFunction = (valueContent' -> FunctionC f) , invokeArguments = [(a,_)] } -> absPathThroughCall seSumm scalarEffectAddOne (functionParameters f) a _ -> Nothing return (p, Witness i "incr") -- | At a call site, if the callee has a scalar effect on its argument, -- match up the access path of the actual argument passed to the callee -- with the access path affected by the callee. -- -- The scalar effect desired is controlled by the second argument and -- should probably be one of -- -- * scalarEffectAddOne -- -- * scalarEffectSubOne -- -- This function is meant to determine the effective abstract access -- path of increments/decrements performed by called functions on data -- in the caller. For example: -- -- > void decRef(Object * o) { -- > atomic_dec(&o->refCount); -- > } -- -- In this example, @atomic_dec@ only decrements the location passed -- to it. The abstract access path of the call instruction, however, -- (and the value returned by this function) is Object/refCount. -- -- This function deals only with single-argument callees absPathThroughCall :: ScalarEffectSummary -> (ScalarEffectSummary -> Argument -> Maybe AbstractAccessPath) -- ^ Type of access -> [Argument] -- ^ Argument list of the callee -> Value -- ^ Actual argument at call site -> Maybe AbstractAccessPath absPathThroughCall seSumm effect [singleFormal] actual = do -- This is the access path of the argument of the callee (if and -- only if the function subtracts one from an int component of the -- argument). The access path describes *which* component of the -- argument is modified. calleeAccessPath <- effect seSumm singleFormal case valueContent' actual of InstructionC i -> do actualAccessPath <- accessPath i -- Now see if the actual passed to this call is derived from one -- of the formal parameters of the current function. This -- access path tells us which component of the argument was -- passed to the callee. case valueContent' (accessPathBaseValue actualAccessPath) of -- If it really was derived from an argument, connect up -- the access paths for the caller and callee so we have a -- single description of the field that was modified -- (interprocedurally). ArgumentC _ -> abstractAccessPath actualAccessPath `appendAccessPath` calleeAccessPath _ -> Nothing _ -> Nothing absPathThroughCall _ _ _ _ = Nothing -- | If the Instruction produces an access path rooted at an Argument, -- return the corresponding AbstractAccessPath absPathIfArg :: Instruction -> Maybe AbstractAccessPath absPathIfArg i = case accessPath i of Nothing -> Nothing Just cap -> case valueContent' (accessPathBaseValue cap) of ArgumentC _ -> Just (abstractAccessPath cap) _ -> Nothing -- Testing -- | Extract a map of unref functions to ref functions refCountSummaryToTestFormat :: RefCountSummary -> Map String String refCountSummaryToTestFormat (RefCountSummary _ unrefArgs refArgs _ _) = foldr addIfRefFound mempty (HM.toList unrefArgs) where addIfRefFound (uarg, UnrefData fieldPath _ _) acc = let ufunc = identifierAsString $ functionName $ argumentFunction uarg in case matchingTypeAndPath (argumentType uarg) fieldPath fst refArgs of Nothing -> acc Just rfunc -> M.insert ufunc rfunc acc
travitch/foreign-inference
src/Foreign/Inference/Analysis/RefCount.hs
bsd-3-clause
24,835
7
31
6,267
5,057
2,701
2,356
384
8
{-# LANGUAGE OverloadedStrings #-} module Juno.Monitoring.EkgSnap ( startServer ) where import Control.Exception (throwIO) import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import Data.Function (on) import qualified Data.HashMap.Strict as M import qualified Data.List as List import qualified Data.Text.Encoding as T import Data.Word (Word8) import Network.Socket (NameInfoFlag(NI_NUMERICHOST), addrAddress, getAddrInfo, getNameInfo) import Prelude hiding (read) import Snap.Core (MonadSnap, Request, Snap, finishWith, getHeaders, getRequest, getResponse, method, Method(GET), modifyResponse, pass, rqPathInfo, setContentType, setResponseStatus, writeLBS) import Snap.Http.Server (httpServe) import qualified Snap.Http.Server.Config as Config import System.Metrics -- Juno Change! import Juno.Monitoring.EkgJson import qualified Snap.Core as Snap ------------------------------------------------------------------------ -- | Convert a host name (e.g. \"localhost\" or \"127.0.0.1\") to a -- numeric host address (e.g. \"127.0.0.1\"). getNumericHostAddress :: S.ByteString -> IO S.ByteString getNumericHostAddress host = do ais <- getAddrInfo Nothing (Just (S8.unpack host)) Nothing case ais of [] -> unsupportedAddressError (ai:_) -> do ni <- getNameInfo [NI_NUMERICHOST] True False (addrAddress ai) case ni of (Just numericHost, _) -> return $! S8.pack numericHost _ -> unsupportedAddressError where unsupportedAddressError = throwIO $ userError $ "unsupported address: " ++ S8.unpack host startServer :: Store -> S.ByteString -- ^ Host to listen on (e.g. \"localhost\") -> Int -- ^ Port to listen on (e.g. 8000) -> IO () startServer store host port = do -- Snap doesn't allow for non-numeric host names in -- 'Snap.setBind'. We work around that limitation by converting a -- possible non-numeric host name to a numeric address. numericHost <- getNumericHostAddress host let conf = Config.setVerbose False $ Config.setErrorLog Config.ConfigNoLog $ Config.setAccessLog Config.ConfigNoLog $ Config.setPort port $ Config.setHostname host $ Config.setBind numericHost $ Config.defaultConfig httpServe conf (monitor store) -- | A handler that can be installed into an existing Snap application. monitor :: Store -> Snap () monitor store = do -- Juno Change! Snap.modifyResponse $ Snap.addHeader "Access-Control-Allow-Origin" "*" jsonHandler $ serve store where jsonHandler = wrapHandler "application/json" wrapHandler fmt handler = method GET $ format fmt $ handler -- | The Accept header of the request. acceptHeader :: Request -> Maybe S.ByteString acceptHeader req = S.intercalate "," <$> getHeaders "Accept" req -- | Runs a Snap monad action only if the request's Accept header -- matches the given MIME type. format :: MonadSnap m => S.ByteString -> m a -> m a format fmt action = do req <- getRequest let acceptHdr = (List.head . parseHttpAccept) <$> acceptHeader req case acceptHdr of Just hdr | hdr == fmt -> action _ -> pass -- | Serve all counter, gauges and labels, built-in or not, as a -- nested JSON object. serve :: MonadSnap m => Store -> m () serve store = do req <- getRequest modifyResponse $ setContentType "application/json" if S.null (rqPathInfo req) then serveAll else serveOne (rqPathInfo req) where serveAll = do metrics <- liftIO $ sampleAll store writeLBS $ encodeAll metrics serveOne pathInfo = do let segments = S8.split '/' pathInfo nameBytes = S8.intercalate "." segments case T.decodeUtf8' nameBytes of Left _ -> do modifyResponse $ setResponseStatus 400 "Bad Request" r <- getResponse finishWith r Right name -> do metrics <- liftIO $ sampleAll store case M.lookup name metrics of Nothing -> pass Just metric -> writeLBS $ encodeOne metric ------------------------------------------------------------------------ -- Utilities for working with accept headers -- | Parse the HTTP accept string to determine supported content types. parseHttpAccept :: S.ByteString -> [S.ByteString] parseHttpAccept = List.map fst . List.sortBy (rcompare `on` snd) . List.map grabQ . S.split 44 -- comma where rcompare :: Double -> Double -> Ordering rcompare = flip compare grabQ s = let (s', q) = breakDiscard 59 s -- semicolon (_, q') = breakDiscard 61 q -- equals sign in (trimWhite s', readQ $ trimWhite q') readQ s = case reads $ S8.unpack s of (x, _):_ -> x _ -> 1.0 trimWhite = S.dropWhile (== 32) -- space breakDiscard :: Word8 -> S.ByteString -> (S.ByteString, S.ByteString) breakDiscard w s = let (x, y) = S.break (== w) s in (x, S.drop 1 y)
buckie/juno
src/Juno/Monitoring/EkgSnap.hs
bsd-3-clause
5,304
0
18
1,421
1,296
678
618
107
4
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} module Pusher where import Network.Google.Logging.Types import Data.Scientific (fromFloatDigits) import Data.Bifunctor (second) import Data.Bits (shiftR, xor, (.&.)) import Data.Word (Word32) import GHC.Int (Int32, Int64) import Data.Time (UTCTime) import Data.Time.Format (defaultTimeLocale, formatTime) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Data.Maybe (fromMaybe) import Data.ProtoLens.Encoding (decodeMessage) import GHC.Generics (Generic) import Network.Wai (Application, rawPathInfo, responseLBS, Request, Response, lazyRequestBody) import Network.HTTP.Types.Status (status404, status400, status422, status204) import Data.Aeson (eitherDecode, FromJSON) import Data.Text (Text) import Network.Google.PubSub (PubsubMessage, pmData) import Control.Lens ((^.), (.~), (&), (^?)) import Control.Monad.Log (Handler) import qualified Data.Aeson as Aeson import qualified Data.Text as Text import qualified Data.ByteString.Lazy.Char8 as BSLC8 import qualified Proto.CommonLogRep as ProtoBuf import qualified Proto.Timestamp as ProtoBuf import qualified Proto.Struct as ProtoBuf import qualified Data.HashMap.Strict as HashMap import qualified Data.Map.Strict as Map import qualified Data.Vector as Vector -- | Push request body -- https://cloud.google.com/pubsub/docs/subscriber#receive data PushMessage = PushMessage { message :: PubsubMessage , subscription :: Text } deriving (Generic) instance FromJSON PushMessage app :: Handler IO LogEntry -> Application app logger request respond = case rawPathInfo request of "/push" -> pusher logger request >>= respond _ -> respond (responseLBS status404 [("Content-Type", "plain/text")] "not found - 404") pusher :: Handler IO LogEntry -> Request -> IO Response pusher logger request = lazyRequestBody request >>= \body -> case eitherDecode body :: Either String PushMessage of Left err -> return (responseLBS status400 [("Content-Type", "plain/text")] (BSLC8.pack err)) Right res -> case decodeMessage (fromMaybe "" ((message res) ^. pmData)) :: Either String ProtoBuf.LogEntry of Left err -> return (responseLBS status422 [("Content-Type", "plain/text")] (BSLC8.pack err)) Right res' -> logger ( localiso res' ) >> return (responseLBS status204 [("Content-Type", "plain/text")] "ok") localiso :: ProtoBuf.LogEntry -> LogEntry localiso le = ((((((((logEntry & leJSONPayload .~ (jsonpayload' <$> le ^? ProtoBuf.jsonpayload)) & leOperation .~ (operation' <$> le ^? ProtoBuf.operation)) & leLabels .~ ((logEntryLabels . HashMap.fromList . Map.toList) <$> le ^? ProtoBuf.labels)) & leHTTPRequest .~ (httprequest' <$> le ^? ProtoBuf.httprequest)) & leSeverity .~ (showSeverity <$> le ^? ProtoBuf.severity)) & leTimestamp .~ (showTimestamp <$> (le ^? ProtoBuf.timestamp))) & leResource .~ (resource' <$> (le ^? ProtoBuf.resource))) & leLogName .~ (le ^? ProtoBuf.logname)) jsonpayload' :: ProtoBuf.Struct -> LogEntryJSONPayload jsonpayload' jsonstruct = (logEntryJSONPayload (fromProtoBufStructToJson jsonstruct)) operation' :: ProtoBuf.LogEntryOperation -> LogEntryOperation operation' oprtn = ((((logEntryOperation & leoLast .~ (oprtn ^? ProtoBuf.last)) & leoFirst .~ (oprtn ^? ProtoBuf.first)) & leoProducer .~ (oprtn ^? ProtoBuf.producer)) & leoId .~ (oprtn ^? ProtoBuf.id)) httprequest' :: ProtoBuf.HttpRequest -> HTTPRequest httprequest' httpr = ((((((((((((hTTPRequest & httprCacheValidatedWithOriginServer .~ (httpr ^? ProtoBuf.cachevalidatewithoriginserver)) & httprCacheHit .~ (httpr ^? ProtoBuf.cachehit)) & httprCacheLookup .~ (httpr ^? ProtoBuf.cachelookup)) & httprReferer .~ (httpr ^? ProtoBuf.referer)) & httprRemoteIP .~ (httpr ^? ProtoBuf.remoteip)) & httprUserAgent .~ (httpr ^? ProtoBuf.useragent)) & httprResponseSize .~ (fromTextToInt64 <$> httpr ^? ProtoBuf.responsesize)) & httprRequestMethod .~ (httpr ^? ProtoBuf.requestmethod)) & httprRequestSize .~ (fromTextToInt64 <$> httpr ^? ProtoBuf.requestsize)) & httprCacheFillBytes .~ (fromTextToInt64 <$> httpr ^? ProtoBuf.cachefillbytes)) & httprRequestURL .~ (httpr ^? ProtoBuf.requesturl)) & httprStatus .~ (zzDecode32 <$> (httpr ^? ProtoBuf.status))) resource' :: ProtoBuf.MonitoredResource -> MonitoredResource resource' res = let labels' = case res ^? ProtoBuf.labels of Nothing -> Nothing Just res' -> Just (monitoredResourceLabels (HashMap.fromList (Map.toList res'))) in ((monitoredResource & mrType .~ (res ^? ProtoBuf.type')) & mrLabels .~ labels') fromTimestampToUTCTime :: ProtoBuf.Timestamp -> UTCTime fromTimestampToUTCTime tmstp = posixSecondsToUTCTime (fromInteger (fromIntegral (tmstp ^. ProtoBuf.seconds))) -- | A timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds. -- Example: "2014-10-02T15:01:23.045123456Z". showTimestamp :: ProtoBuf.Timestamp -> UTCTime showTimestamp = fromTimestampToUTCTime showSeverity :: ProtoBuf.LogSeverity -> LogEntrySeverity showSeverity = \case ProtoBuf.DEFAULT -> Default ProtoBuf.DEBUG -> Debug ProtoBuf.INFO -> Info ProtoBuf.NOTICE -> Notice ProtoBuf.WARNING -> Warning ProtoBuf.ERROR -> Error' ProtoBuf.CRITICAL -> Critical ProtoBuf.ALERT -> Alert ProtoBuf.EMERGENCY -> Emergency -- | I took from -- <https://www.stackage.org/haddock/lts-7.4/protobuf-0.2.1.1/src/Data.ProtocolBuffers.Wire.html#zzDecode32 protobuf> -- see where find this solution them ;) zzDecode32 :: Word32 -> Int32 zzDecode32 w = fromIntegral (w `shiftR` 1) `xor` negate (fromIntegral (w .&. 1)) fromTextToInt64 :: Text -> Int64 fromTextToInt64 = read . Text.unpack fromProtoBufStructValueToAesonValue :: ProtoBuf.Value -> Aeson.Value fromProtoBufStructValueToAesonValue value = case value ^? ProtoBuf.numberValue of Just num -> Aeson.Number (fromFloatDigits num) Nothing -> case value ^? ProtoBuf.stringValue of Just str -> Aeson.String str Nothing -> case value ^? ProtoBuf.boolValue of Just bln -> Aeson.Bool bln Nothing -> case value ^? ProtoBuf.structValue of Just obj -> Aeson.Object (fromProtoBufStructToJson obj) Nothing -> case value ^? ProtoBuf.listValue of Just arr -> Aeson.Array (Vector.fromList (map fromProtoBufStructValueToAesonValue (arr ^. ProtoBuf.values))) Nothing -> case value ^? ProtoBuf.nullValue of Just _ -> Aeson.Null Nothing -> Aeson.Null fromProtoBufStructToJson :: ProtoBuf.Struct -> HashMap.HashMap Text Aeson.Value fromProtoBufStructToJson jsonstruct = HashMap.fromList (map (second fromProtoBufStructValueToAesonValue) (Map.toList (jsonstruct ^. ProtoBuf.fields)))
dp-cylme/labourer
src/Pusher.hs
bsd-3-clause
8,865
0
42
3,144
1,952
1,071
881
178
9
{-# LANGUAGE OverloadedStrings #-} {- | Module : Network.MPD.Applicative.ClientToClient Copyright : (c) Joachim Fasting 2013 License : MIT Maintainer : [email protected] Stability : stable Portability : unportable Client to client communication. -} module Network.MPD.Applicative.ClientToClient ( -- * Types ChannelName , MessageText -- * Subscribing to channels , subscribe , unsubscribe , channels -- * Communicating with other clients , readMessages , sendMessage ) where import Control.Applicative import Network.MPD.Commands.Arg hiding (Command) import Network.MPD.Applicative.Internal import Network.MPD.Applicative.Util import Network.MPD.Util import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.UTF8 as UTF8 ------------------------------------------------------------------------ type ChannelName = String type MessageText = String ------------------------------------------------------------------------ subscribe :: ChannelName -> Command () subscribe name = Command emptyResponse ["subscribe" <@> name] unsubscribe :: ChannelName -> Command () unsubscribe name = Command emptyResponse ["unsubscribe" <@> name] channels :: Command [ChannelName] channels = Command p ["channels"] where p = map UTF8.toString . takeValues <$> getResponse ------------------------------------------------------------------------ readMessages :: Command [(ChannelName, MessageText)] readMessages = Command (liftParser p) ["readmessages"] where p = mapM parseMessage . splitGroups ["channel"] . toAssocList parseMessage :: [(ByteString, ByteString)] -> Either String (ChannelName, MessageText) parseMessage [("channel", ch),("message", msg)] = Right (UTF8.toString ch, UTF8.toString msg) parseMessage _ = Left "Unexpected result from readMessages" sendMessage :: ChannelName -> MessageText -> Command () sendMessage name text = Command emptyResponse ["sendmessage" <@> name <++> text]
beni55/libmpd-haskell
src/Network/MPD/Applicative/ClientToClient.hs
mit
2,070
0
10
373
410
235
175
34
2
import qualified Data.Map as Map import qualified Protein as P -- | The prefix spectrum of a weighted string is the collection of all its -- prefix weights. Given a list L of n (n≤100) positive real numbers, -- return a protein string of length n−1 whose prefix spectrum is equal to L. -- -- Notes: -- If multiple solutions exist, pick any. -- Consult the monoisotopic mass table. -- -- >>> 3524.8542 -- >>> 3710.9335 -- >>> 3841.974 -- >>> 3970.0326 -- >>> 4057.0646 -- WMQS -- | looks up a mass weights and returns list of possible proteins spec :: Foldable t => t Double -> [[P.AminoAcid]] spec masses = let parseWeight = \acc m -> findMatches m : acc findMatches m = Map.foldrWithKey (compareMass m) [] P.massTable compareMass m = \k v acc -> if (abs(v-m) < 0.001) then k : acc else acc in reverse $ foldl parseWeight [] masses main = do inp <- getContents let weights = map (\l -> read l :: Double) $ lines inp masses = zip weights (tail weights) prots = spec $ map (\(a,b) -> abs(a-b)) masses if length weights < 2 then print "not enough elements" >> print weights else print (concat prots)
mitochon/hoosalind
src/problems/spec.hs
mit
1,153
0
16
257
312
168
144
16
2
{-# LANGUAGE CPP, ScopedTypeVariables, OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Leksah -- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GNU-GPL -- -- Maintainer : <maintainer at leksah.org> -- Stability : provisional -- Portability : portable -- -- -- Main function of Leksah, an Haskell IDE written in Haskell -- --------------------------------------------------------------------------------- module IDE.Leksah ( leksah ) where import Graphics.UI.Gtk import Control.Concurrent import Data.IORef import Data.Maybe import qualified Data.Map as Map import System.Console.GetOpt import System.Environment import Data.Version import Prelude hiding(catch) import qualified IDE.OSX as OSX import qualified IDE.YiConfig as Yi #ifdef LEKSAH_WITH_YI_DYRE import System.Directory (getAppUserDataDirectory) import System.FilePath ((</>)) import Control.Applicative ((<$>)) import qualified Config.Dyre as Dyre #endif import IDE.Session import IDE.Core.State import Control.Event import IDE.SourceCandy import IDE.Utils.FileUtils import Graphics.UI.Editor.MakeEditor import Graphics.UI.Editor.Parameters import IDE.Command import IDE.Pane.Preferences import IDE.Keymap import IDE.Pane.SourceBuffer import IDE.Find import Graphics.UI.Editor.Composite (filesEditor, maybeEditor) import Graphics.UI.Editor.Simple (stringEditor, enumEditor, textEditor) import IDE.Metainfo.Provider (initInfo) import IDE.Workspaces (workspaceAddPackage', workspaceTryQuiet, workspaceNewHere, workspaceOpenThis, backgroundMake) import IDE.Utils.GUIUtils import Network (withSocketsDo) import Control.Exception import System.Exit(exitFailure) import qualified IDE.StrippedPrefs as SP import IDE.Utils.Tool (runTool, toolline, waitForProcess) import System.Log import System.Log.Logger (getLevel, getRootLogger, debugM, updateGlobalLogger, rootLoggerName, setLevel) import Data.List (stripPrefix) import System.Directory (doesDirectoryExist, copyFile, createDirectoryIfMissing, getHomeDirectory, doesFileExist) import System.FilePath (dropExtension, splitExtension, (</>)) import qualified Data.Conduit as C import qualified Data.Conduit.List as CL import Data.Conduit (($$)) import Control.Monad (when, unless, liftM) import Control.Monad.IO.Class (MonadIO(..)) import Control.Applicative ((<$>)) import qualified Data.Text as T (pack, unpack, stripPrefix) import Data.Text (Text) import Data.Monoid ((<>)) -- -------------------------------------------------------------------- -- Command line options -- data Flag = VersionF | SessionN Text | EmptySession | DefaultSession | Help | Verbosity Text deriving (Show,Eq) options :: [OptDescr Flag] options = [Option ['e'] ["emptySession"] (NoArg EmptySession) "Start with empty session" , Option ['d'] ["defaultSession"] (NoArg DefaultSession) "Start with default session (can be used together with a source file)" , Option ['l'] ["loadSession"] (ReqArg (SessionN . T.pack) "NAME") "Load session" , Option ['h'] ["help"] (NoArg Help) "Display command line options" , Option ['v'] ["version"] (NoArg VersionF) "Show the version number of ide" , Option ['e'] ["verbosity"] (ReqArg (Verbosity . T.pack) "Verbosity") "One of DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL, ALERT, EMERGENCY"] header = "Usage: leksah [OPTION...] [file(.lkshs|.lkshw|.hs|.lhs)]" ideOpts :: [Text] -> IO ([Flag], [Text]) ideOpts argv = case getOpt Permute options $ map T.unpack argv of (o,n,[] ) -> return (o,map T.pack n) (_,_,errs) -> ioError $ userError $ concat errs ++ usageInfo header options -- --------------------------------------------------------------------- -- | Main function -- #ifdef LEKSAH_WITH_YI_DYRE leksahDriver = Dyre.wrapMain Dyre.defaultParams { Dyre.projectName = "yi" , Dyre.realMain = \(config, mbError) -> do case mbError of Just error -> putStrLn $ "Error in yi configuration file : " ++ error Nothing -> return () realMain config , Dyre.showError = \(config, _) error -> (config, Just error) , Dyre.configDir = Just . getAppUserDataDirectory $ "yi" , Dyre.cacheDir = Just $ ((</> "leksah") <$> (getAppUserDataDirectory "cache")) , Dyre.hidePackages = ["mtl"] , Dyre.ghcOpts = ["-DLEKSAH"] } leksah yiConfig = leksahDriver (yiConfig, Nothing) #else leksah = realMain #endif realMain yiConfig = do withSocketsDo $ handleExceptions $ do dataDir <- getDataDir args <- getArgs (o,files) <- ideOpts $ map T.pack args isFirstStart <- liftM not $ hasSavedConfigFile standardPreferencesFilename let sessions = catMaybes $ map (\x -> case x of SessionN s -> Just s _ -> Nothing) o let sessionFPs = filter (\f -> snd (splitExtension f) == leksahSessionFileExtension) $ map T.unpack files let workspaceFPs = filter (\f -> snd (splitExtension f) == leksahWorkspaceFileExtension) $ map T.unpack files let sourceFPs = filter (\f -> let (_,s) = splitExtension f in s == ".hs" || s == ".lhs" || s == ".chs") $ map T.unpack files let mbWorkspaceFP'= case workspaceFPs of [] -> Nothing w:_ -> Just w (mbWSessionFP, mbWorkspaceFP) <- case mbWorkspaceFP' of Nothing -> return (Nothing,Nothing) Just fp -> let spath = dropExtension fp ++ leksahSessionFileExtension in do exists <- liftIO $ doesFileExist spath if exists then return (Just spath,Nothing) else return (Nothing,Just fp) let ssession = case sessions of (s:_) -> T.unpack s <> leksahSessionFileExtension _ -> if null sourceFPs then standardSessionFilename else emptySessionFilename sessionFP <- if elem EmptySession o then getConfigFilePathForLoad emptySessionFilename Nothing dataDir else if elem DefaultSession o then getConfigFilePathForLoad standardSessionFilename Nothing dataDir else case mbWSessionFP of Just fp -> return fp Nothing -> getConfigFilePathForLoad ssession Nothing dataDir let verbosity' = catMaybes $ map (\x -> case x of Verbosity s -> Just s _ -> Nothing) o let verbosity = case verbosity' of [] -> INFO h:_ -> read $ T.unpack h updateGlobalLogger rootLoggerName (\ l -> setLevel verbosity l) when (elem VersionF o) (sysMessage Normal $ "Leksah the Haskell IDE, version " <> T.pack (showVersion version)) when (elem Help o) (sysMessage Normal $ "Leksah the Haskell IDE " <> T.pack (usageInfo header options)) prefsPath <- getConfigFilePathForLoad standardPreferencesFilename Nothing dataDir prefs <- readPrefs prefsPath when (not (elem VersionF o) && not (elem Help o)) (startGUI yiConfig sessionFP mbWorkspaceFP sourceFPs prefs isFirstStart) handleExceptions inner = catch inner (\(exception :: SomeException) -> do sysMessage Normal ("leksah: internal IDE error: " <> T.pack (show exception)) exitFailure ) -- --------------------------------------------------------------------- -- | Start the GUI startGUI :: Yi.Config -> FilePath -> Maybe FilePath -> [FilePath] -> Prefs -> Bool -> IO () startGUI yiConfig sessionFP mbWorkspaceFP sourceFPs iprefs isFirstStart = do Yi.start yiConfig $ \yiControl -> do st <- unsafeInitGUIForThreadedRTS when rtsSupportsBoundThreads (sysMessage Normal "Linked with -threaded") timeout <- timeoutAddFull (yield >> return True) priorityLow 10 mapM_ (sysMessage Normal . T.pack) st initGtkRc dataDir <- getDataDir mbStartupPrefs <- if not isFirstStart then return $ Just iprefs else do firstStartOK <- firstStart iprefs if not firstStartOK then return Nothing else do prefsPath <- getConfigFilePathForLoad standardPreferencesFilename Nothing dataDir prefs <- readPrefs prefsPath return $ Just prefs timeoutRemove timeout postGUIAsync $ do case mbStartupPrefs of Nothing -> return () Just startupPrefs -> startMainWindow yiControl sessionFP mbWorkspaceFP sourceFPs startupPrefs isFirstStart debugM "leksah" "starting mainGUI" mainGUI debugM "leksah" "finished mainGUI" mainLoop :: IO () -> IO () mainLoop = if rtsSupportsBoundThreads then mainLoopThreaded else mainLoopSingleThread mainLoopThreaded :: IO () -> IO () mainLoopThreaded onIdle = loop where loop = do quit <- loopTillIdle if quit then return () else do active <- newEmptyMVar mvarSentIdleMessage <- newEmptyMVar idleThread <- forkIO $ do threadDelay 50000 isActive <- isJust <$> tryTakeMVar active unless isActive $ do putMVar mvarSentIdleMessage () postGUIAsync onIdle quit <- mainIteration putMVar active () if quit then return () else do -- If an idle message was sent then wait again sentIdleMessage <- isJust <$> tryTakeMVar mvarSentIdleMessage quit <- if sentIdleMessage then mainIteration else return False if quit then return () else loop loopTillIdle = do pending <- eventsPending if pending == 0 then return False else do quit <- loopn (pending + 2) if quit then return True else loopTillIdle mainLoopSingleThread :: IO () -> IO () mainLoopSingleThread onIdle = eventsPending >>= loop False 50 where loop :: Bool -> Int -> Int -> IO () loop False delay 0 | delay > 2000 = onIdle >> loop True delay 0 loop isIdle delay n = do quit <- if n > 0 then do timeout <- timeoutAddFull (yield >> return True) priorityLow 10 quit <- loopn (n+2) timeoutRemove timeout return quit else loopn (n+2) if quit then return () else do yield pending <- eventsPending if pending > 0 then do loop False 50 pending else do threadDelay delay eventsPending >>= loop isIdle (if n > 0 then 50 else min (delay+delay) 50000) loopn :: Int -> IO Bool loopn 0 = return False loopn n = do quit <- mainIterationDo False if quit then return True else loopn (n - 1) startMainWindow :: Yi.Control -> FilePath -> Maybe FilePath -> [FilePath] -> Prefs -> Bool -> IO () startMainWindow yiControl sessionFP mbWorkspaceFP sourceFPs startupPrefs isFirstStart = do timeout <- timeoutAddFull (yield >> return True) priorityLow 10 debugM "leksah" "startMainWindow" osxApp <- OSX.applicationNew uiManager <- uiManagerNew newIcons dataDir <- getDataDir candyPath <- getConfigFilePathForLoad (case sourceCandy startupPrefs of (_,name) -> T.unpack name <> leksahCandyFileExtension) Nothing dataDir candySt <- parseCandy candyPath -- keystrokes keysPath <- getConfigFilePathForLoad (T.unpack (keymapName startupPrefs) <> leksahKeymapFileExtension) Nothing dataDir keyMap <- parseKeymap keysPath let accelActions = setKeymap (keyMap :: KeymapI) mkActions specialKeys <- buildSpecialKeys keyMap accelActions win <- windowNew widgetSetName win ("Leksah Main Window"::Text) let fs = FrameState { windows = [win] , uiManager = uiManager , panes = Map.empty , activePane = Nothing , paneMap = Map.empty , layout = (TerminalP Map.empty Nothing (-1) Nothing Nothing) , panePathFromNB = Map.empty } let ide = IDE { frameState = fs , recentPanes = [] , specialKeys = specialKeys , specialKey = Nothing , candy = candySt , prefs = startupPrefs , workspace = Nothing , activePack = Nothing , activeExe = Nothing , bufferProjCache = Map.empty , allLogRefs = [] , currentHist = 0 , currentEBC = (Nothing, Nothing, Nothing) , systemInfo = Nothing , packageInfo = Nothing , workspaceInfo = Nothing , workspInfoCache = Map.empty , handlers = Map.empty , currentState = IsStartingUp , guiHistory = (False,[],-1) , findbar = (False,Nothing) , toolbar = (True,Nothing) , recentFiles = [] , recentWorkspaces = [] , runningTool = Nothing , debugState = Nothing , completion = ((750,400),Nothing) , yiControl = yiControl , server = Nothing , vcsData = (Map.empty, Nothing) , logLaunches = Map.empty , autoCommand = return () , autoURI = Nothing } ideR <- newIORef ide menuDescription' <- menuDescription reflectIDE (makeMenu uiManager accelActions menuDescription') ideR nb <- reflectIDE (newNotebook []) ideR after nb switchPage (\i -> reflectIDE (handleNotebookSwitch nb i) ideR) widgetSetName nb ("root"::Text) on win deleteEvent . liftIO $ reflectIDE quit ideR >> return True reflectIDE (instrumentWindow win startupPrefs (castToWidget nb)) ideR reflectIDE (do setCandyState (fst (sourceCandy startupPrefs)) setBackgroundBuildToggled (backgroundBuild startupPrefs) setRunUnitTests (runUnitTests startupPrefs) setMakeModeToggled (makeMode startupPrefs)) ideR let (x,y) = defaultSize startupPrefs windowSetDefaultSize win x y (tbv,fbv) <- reflectIDE (do registerLeksahEvents pair <- recoverSession sessionFP workspaceOpenThis False mbWorkspaceFP mapM fileOpenThis sourceFPs wins <- getWindows mapM_ instrumentSecWindow (tail wins) return pair ) ideR debugM "leksah" "Show main window" widgetShowAll win reflectIDE (do triggerEventIDE UpdateRecent if tbv then showToolbar else hideToolbar if fbv then showFindbar else hideFindbar OSX.updateMenu osxApp uiManager) ideR OSX.applicationReady osxApp configDir <- getConfigDir let welcomePath = configDir</>"leksah-welcome" welcomeExists <- doesDirectoryExist welcomePath unless welcomeExists $ do let welcomeSource = dataDir</>"data"</>"leksah-welcome" welcomeCabal = welcomePath</>"leksah-welcome.cabal" welcomeMain = welcomePath</>"src"</>"Main.hs" createDirectoryIfMissing True $ welcomePath</>"src" copyFile (welcomeSource</>"Setup.lhs") (welcomePath</>"Setup.lhs") copyFile (welcomeSource</>"leksah-welcome.cabal") (welcomeCabal) copyFile (welcomeSource</>"src"</>"Main.hs") (welcomeMain) defaultWorkspace <- liftIO $ (</> "leksah.lkshw") <$> getHomeDirectory defaultExists <- liftIO $ doesFileExist defaultWorkspace reflectIDE (do if defaultExists then workspaceOpenThis False (Just defaultWorkspace) else workspaceNewHere defaultWorkspace workspaceTryQuiet $ workspaceAddPackage' welcomeCabal >> return () fileOpenThis welcomeMain) ideR reflectIDE (initInfo (modifyIDE_ (\ide -> ide{currentState = IsRunning}))) ideR timeoutRemove timeout postGUIAsync . mainLoop $ reflectIDE (do currentPrefs <- readIDE prefs when (backgroundBuild currentPrefs) $ backgroundMake) ideR -- timeoutAddFull (do -- reflectIDE (do -- currentPrefs <- readIDE prefs -- when (backgroundBuild currentPrefs) $ backgroundMake) ideR -- return True) priorityDefaultIdle 1000 reflectIDE (triggerEvent ideR (Sensitivity [(SensitivityInterpreting, False)])) ideR return () -- mainGUI fDescription :: FilePath -> FieldDescription Prefs fDescription configPath = VFD emptyParams [ mkField (paraName <<<- ParaName "Paths under which haskell sources for packages may be found" $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1, 150) $ emptyParams) sourceDirectories (\b a -> a{sourceDirectories = b}) (filesEditor Nothing FileChooserActionSelectFolder "Select folders") , mkField (paraName <<<- ParaName "Unpack source for cabal packages to" $ emptyParams) unpackDirectory (\b a -> a{unpackDirectory = b}) (maybeEditor (stringEditor (const True) True,emptyParams) True "") , mkField (paraName <<<- ParaName "URL from which to download prebuilt metadata" $ emptyParams) retrieveURL (\b a -> a{retrieveURL = b}) (textEditor (\ _ -> True) True) , mkField (paraName <<<- ParaName "Strategy for downloading prebuilt metadata" $ emptyParams) retrieveStrategy (\b a -> a{retrieveStrategy = b}) (enumEditor ["Try to download and then build locally if that fails","Try to build locally and then download if that fails","Never download (just try to build locally)"])] -- -- | Called when leksah is first called (the .leksah-xx directory does not exist) -- firstStart :: Prefs -> IO Bool firstStart prefs = do dataDir <- getDataDir prefsPath <- getConfigFilePathForLoad standardPreferencesFilename Nothing dataDir prefs <- readPrefs prefsPath configDir <- getConfigDir dialog <- dialogNew setLeksahIcon dialog set dialog [ windowTitle := ("Welcome to Leksah, the Haskell IDE"::Text), windowWindowPosition := WinPosCenter] dialogAddButton dialog ("gtk-ok"::Text) ResponseOk dialogAddButton dialog ("gtk-cancel"::Text) ResponseCancel #ifdef MIN_VERSION_gtk3 vb <- dialogGetContentArea dialog #else vb <- dialogGetUpper dialog #endif label <- labelNew (Just ( "Before you start using Leksah it will collect and download metadata about your installed Haskell packages.\n" <> "You can add folders under which you have sources for Haskell packages not available from Hackage."::Text)) (widget, setInj, getExt,notifier) <- buildEditor (fDescription configDir) prefs boxPackStart (castToBox vb) label PackNatural 7 sw <- scrolledWindowNew Nothing Nothing scrolledWindowAddWithViewport sw widget scrolledWindowSetPolicy sw PolicyNever PolicyAutomatic boxPackStart (castToBox vb) sw PackGrow 7 windowSetDefaultSize dialog 800 630 widgetShowAll dialog response <- dialogRun dialog widgetHide dialog case response of ResponseOk -> do mbNewPrefs <- extract prefs [getExt] widgetDestroy dialog case mbNewPrefs of Nothing -> do sysMessage Normal "No dialog results" return False Just newPrefs -> do fp <- getConfigFilePathForSave standardPreferencesFilename writePrefs fp newPrefs fp2 <- getConfigFilePathForSave strippedPreferencesFilename SP.writeStrippedPrefs fp2 (SP.Prefs {SP.sourceDirectories = sourceDirectories newPrefs, SP.unpackDirectory = unpackDirectory newPrefs, SP.retrieveURL = retrieveURL newPrefs, SP.retrieveStrategy = retrieveStrategy newPrefs, SP.serverPort = serverPort newPrefs, SP.endWithLastConn = endWithLastConn newPrefs}) firstBuild newPrefs return True _ -> do widgetDestroy dialog return False setLeksahIcon :: (WindowClass self) => self -> IO () setLeksahIcon window = do dataDir <- getDataDir let iconPath = dataDir </> "pics" </> "leksah.png" iconExists <- doesFileExist iconPath when iconExists $ windowSetIconFromFile window iconPath firstBuild newPrefs = do dialog <- dialogNew setLeksahIcon dialog set dialog [ windowTitle := ("Leksah: Updating Metadata"::Text), windowWindowPosition := WinPosCenter, windowDeletable := False] #ifdef MIN_VERSION_gtk3 vb <- dialogGetContentArea dialog #else vb <- dialogGetUpper dialog #endif progressBar <- progressBarNew progressBarSetText progressBar ("Please wait while Leksah collects information about Haskell packages on your system"::Text) progressBarSetFraction progressBar 0.0 boxPackStart (castToBox vb) progressBar PackGrow 7 forkIO $ do logger <- getRootLogger let verbosity = case getLevel logger of Just level -> ["--verbosity=" <> T.pack (show level)] Nothing -> [] (output, pid) <- runTool "leksah-server" (["-sbo", "+RTS", "-N2", "-RTS"] ++ verbosity) Nothing output $$ CL.mapM_ (update progressBar) waitForProcess pid postGUIAsync (dialogResponse dialog ResponseOk) widgetShowAll dialog dialogRun dialog widgetHide dialog widgetDestroy dialog return () where update pb to = do let str = toolline to case T.stripPrefix "update_toolbar " str of Just rest -> postGUIAsync $ progressBarSetFraction pb (read $ T.unpack rest) Nothing -> liftIO $ debugM "leksah" $ T.unpack str
juhp/leksah
src/IDE/Leksah.hs
gpl-2.0
24,775
0
23
8,750
5,601
2,850
2,751
476
12
-- Copyright (C) 2016-2019 Sergey Vinokurov <[email protected]> -- Copyright (C) 2014-2016 Sebastian Wiesner <[email protected]> -- Copyright (C) 2016-2018 Danny Navarro <[email protected]> -- Copyright (C) 2015 Mark Karpov <[email protected]> -- Copyright (C) 2015 Michael Alan Dorman <[email protected]> -- Copyright (C) 2014 Gracjan Polak <[email protected]> -- This file is not part of GNU Emacs. -- This program is free software; you can redistribute it and/or modify it under -- the terms of the GNU General Public License as published by the Free Software -- Foundation, either version 3 of the License, or (at your option) any later -- version. -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -- details. -- You should have received a copy of the GNU General Public License along with -- this program. If not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Main (main) where #if __GLASGOW_HASKELL__ >= 800 #define GHC_INCLUDES_VERSION_MACRO 1 #endif #if defined(GHC_INCLUDES_VERSION_MACRO) # if MIN_VERSION_Cabal(3, 2, 0) # define Cabal32 1 # define Cabal32OrLater 1 # define Cabal30OrLater 1 # define Cabal22OrLater 1 # define Cabal20OrLater 1 # elif MIN_VERSION_Cabal(3, 0, 0) # define Cabal30 1 # define Cabal30OrLater 1 # define Cabal22OrLater 1 # define Cabal20OrLater 1 # elif MIN_VERSION_Cabal(2, 3, 0) # define Cabal24 1 # define Cabal22OrLater 1 # define Cabal20OrLater 1 # elif MIN_VERSION_Cabal(2, 1, 0) # define Cabal22 1 # define Cabal22OrLater 1 # define Cabal20OrLater 1 # elif MIN_VERSION_Cabal(2, 0, 0) # define Cabal20 1 # define Cabal20OrLater 1 # endif #else -- Hack - we may actually be using Cabal 2.0 with e.g. 7.8 GHC. But -- that's not likely to occur for average user who's relying on -- packages bundled with GHC. The 2.0 Cabal is bundled starting with 8.2.1. # undef Cabal24 # undef Cabal22 # undef Cabal20 #endif #if __GLASGOW_HASKELL__ >= 704 # define Cabal114OrMore 1 #endif #if __GLASGOW_HASKELL__ < 710 # define Cabal118OrLess 1 #endif #if __GLASGOW_HASKELL__ <= 763 #undef HAVE_DATA_FUNCTOR_IDENTITY #else #define HAVE_DATA_FUNCTOR_IDENTITY #endif import qualified Data.ByteString.Char8 as C8 #if MIN_VERSION_bytestring(0, 10, 2) import qualified Data.ByteString.Builder as BS.Builder #elif MIN_VERSION_bytestring(0, 10, 0) import qualified Data.ByteString.Lazy.Builder as BS.Builder #else import qualified Data.ByteString.Lazy.Char8 as CL8 #endif import Distribution.ModuleName (ModuleName) import qualified Distribution.ModuleName as ModuleName import Distribution.PackageDescription () #if defined(Cabal20OrLater) import Distribution.Types.Benchmark (benchmarkBuildInfo, benchmarkInterface) import Distribution.Types.ForeignLib (foreignLibBuildInfo) import Distribution.Types.TestSuite (testBuildInfo, testInterface) import Distribution.PackageDescription (allLibraries, libName) #else import Distribution.PackageDescription (library) #endif import qualified Control.Applicative as A import Control.Exception (SomeException, try) import Control.Monad (when) #if defined(Cabal22OrLater) import qualified Data.ByteString as BS #endif import Data.Char (isSpace) #if defined(HAVE_DATA_FUNCTOR_IDENTITY) import Data.Functor.Identity #endif import Data.List (nub, foldl', intersperse) import Data.Maybe (maybeToList) #if __GLASGOW_HASKELL__ < 710 import Data.Monoid #endif #if defined(Cabal32OrLater) import Data.List.NonEmpty (toList) #endif import Data.Set (Set) import qualified Data.Set as S #ifdef Cabal118OrLess import Distribution.Compiler (CompilerFlavor(GHC), CompilerId(CompilerId), buildCompilerFlavor) #else import Distribution.Compiler (AbiTag(NoAbiTag), CompilerFlavor(GHC), CompilerId(CompilerId), CompilerInfo, buildCompilerFlavor, unknownCompilerInfo) #endif import Distribution.Package (pkgName, Dependency(..)) import Distribution.PackageDescription (GenericPackageDescription, PackageDescription(..), TestSuiteInterface(..), BuildInfo(..), Library, Executable, allBuildInfo, usedExtensions, allLanguages, hcOptions, exeName, buildInfo, modulePath, libBuildInfo, exposedModules) import Distribution.Simple.BuildPaths (defaultDistPref) import Distribution.Simple.Utils (cabalVersion) import Distribution.System (buildPlatform) #if defined(Cabal20OrLater) import Distribution.System (OS(OSX), buildArch, buildOS) #endif import Distribution.Text (display) #if defined(Cabal20OrLater) import Distribution.Types.PackageId (PackageId) #endif import Distribution.Verbosity (silent) import Language.Haskell.Extension (Extension(..),Language(..)) import System.Console.GetOpt import System.Environment (getArgs) import System.Exit (ExitCode(..), exitFailure, exitSuccess) import System.FilePath ((</>), dropFileName, normalise, isPathSeparator) import System.Info (compilerVersion) import System.IO (Handle, hGetContents, hPutStrLn, stderr, stdout) import System.Process (readProcessWithExitCode) import qualified System.Process as Process #if __GLASGOW_HASKELL__ >= 710 && !defined(Cabal20) && !defined(Cabal22OrLater) import Data.Version (Version) #endif #if defined(Cabal24) || defined(Cabal30) || defined(Cabal32) import Distribution.PackageDescription (allBuildDepends) #endif #if defined(Cabal114OrMore) import Distribution.PackageDescription (BenchmarkInterface(..),) #endif #if defined(Cabal20OrLater) import Control.Monad (filterM) import Distribution.Package (unPackageName, depPkgName, PackageName) import Distribution.PackageDescription.Configuration (finalizePD) import Distribution.Types.ComponentRequestedSpec (ComponentRequestedSpec(..)) import Distribution.Types.ForeignLib (ForeignLib(foreignLibName)) import Distribution.Types.UnqualComponentName (unUnqualComponentName) import qualified Distribution.Version as CabalVersion import Distribution.Types.Benchmark (Benchmark(benchmarkName)) import Distribution.Types.TestSuite (TestSuite(testName)) import System.Directory (doesDirectoryExist, doesFileExist) #else import Control.Arrow (second) import Data.Version (showVersion) import Distribution.Package (PackageName(..)) import Distribution.PackageDescription.Configuration (finalizePackageDescription, mapTreeData) # if defined(Cabal114OrMore) import Distribution.PackageDescription (TestSuite(..), Benchmark(..), condTestSuites, condBenchmarks, benchmarkEnabled, testEnabled) # else import Distribution.PackageDescription (TestSuite(..), condTestSuites, testEnabled) # endif #endif #if defined(Cabal22OrLater) import Distribution.Pretty (prettyShow) #endif #if defined(Cabal32OrLater) import Distribution.PackageDescription (mkFlagAssignment) #elif defined(Cabal22OrLater) import Distribution.Types.GenericPackageDescription (mkFlagAssignment) #endif #if defined(Cabal22OrLater) import Distribution.PackageDescription.Parsec (runParseResult, readGenericPackageDescription, parseGenericPackageDescription) # if defined(Cabal30OrLater) import Distribution.Parsec.Error (showPError) #else import Distribution.Parsec.Common (showPError) # endif #elif defined(Cabal20) import Distribution.PackageDescription.Parse (ParseResult(..), readGenericPackageDescription, parseGenericPackageDescription) import Distribution.ParseUtils (locatedErrorMsg) #else import Distribution.PackageDescription.Parse (ParseResult(..), parsePackageDescription, readPackageDescription) import Distribution.ParseUtils (locatedErrorMsg) #endif #if defined(Cabal30OrLater) import Distribution.Types.LibraryName (libraryNameString) #endif newtype UnixFilepath = UnixFilepath { unUnixFilepath :: C8.ByteString } deriving (Eq, Ord) mkUnixFilepath :: FilePath -> UnixFilepath mkUnixFilepath = UnixFilepath . C8.map (\c -> if isPathSeparator c then '/' else c) . C8.pack . normalise data Sexp = SList [Sexp] | SString C8.ByteString | SSymbol C8.ByteString data TargetTool = Cabal | Stack #if defined(Cabal20OrLater) | CabalNew PackageId GhcVersion type GhcVersion = String #endif #if MIN_VERSION_bytestring(0, 10, 0) type Builder = BS.Builder.Builder builderFromByteString :: C8.ByteString -> Builder builderFromByteString = BS.Builder.byteString builderFromChar :: Char -> Builder builderFromChar = BS.Builder.char8 hPutBuilder :: Handle -> Builder -> IO () hPutBuilder = BS.Builder.hPutBuilder #else type Builder = Endo CL8.ByteString builderFromByteString :: C8.ByteString -> Builder builderFromByteString x = Endo (CL8.fromChunks [x] `mappend`) builderFromChar :: Char -> Builder builderFromChar c = Endo (CL8.singleton c `mappend`) hPutBuilder :: Handle -> Builder -> IO () hPutBuilder h (Endo f) = CL8.hPut h $ f CL8.empty #endif sym :: C8.ByteString -> Sexp sym = SSymbol renderSexp :: Sexp -> Builder renderSexp (SSymbol s) = builderFromByteString s renderSexp (SString s) = dquote `mappend` builderFromByteString s `mappend` dquote where dquote = builderFromChar '"' renderSexp (SList xs) = lparen `mappend` mconcat (intersperse space (map renderSexp xs)) `mappend` rparen where lparen = builderFromChar '(' rparen = builderFromChar ')' space = builderFromChar ' ' class ToSexp a where toSexp :: a -> Sexp instance ToSexp C8.ByteString where toSexp = SString instance ToSexp UnixFilepath where toSexp = SString . unUnixFilepath instance ToSexp Extension where toSexp (EnableExtension ext) = toSexp (C8.pack (show ext)) toSexp (DisableExtension ext) = toSexp ("No" `mappend` C8.pack (show ext)) toSexp (UnknownExtension ext) = toSexp (C8.pack ext) instance ToSexp Language where toSexp (UnknownLanguage lang) = toSexp (C8.pack lang) toSexp lang = toSexp (C8.pack (show lang)) instance ToSexp Dependency where toSexp = toSexp . C8.pack . unPackageName' . depPkgName' instance ToSexp Sexp where toSexp = id instance ToSexp Bool where toSexp b = SSymbol $ if b then "t" else "nil" instance ToSexp a => ToSexp [a] where toSexp = SList . map toSexp instance ToSexp a => ToSexp (Maybe a) where toSexp Nothing = SSymbol "nil" toSexp (Just x) = toSexp x instance ToSexp ModuleName where toSexp = toSexp . map C8.pack . ModuleName.components instance (ToSexp a, ToSexp b, ToSexp c, ToSexp d) => ToSexp (a, b, c, d) where toSexp (a, b, c, d) = SList [toSexp a, toSexp b, toSexp c, toSexp d] cons :: (ToSexp a, ToSexp b) => a -> [b] -> Sexp cons h t = SList (toSexp h : map toSexp t) -- | Get possible dist directory distDir :: TargetTool -> IO FilePath distDir Cabal = return defaultDistPref distDir Stack = do res <- try $ readProcessWithExitCode "stack" ["path", "--dist-dir"] [] return $ case res of Left (_ :: SomeException) -> defaultDistDir Right (ExitSuccess, stdOut, _) -> stripWhitespace stdOut Right (ExitFailure _, _, _) -> defaultDistDir where defaultDistDir :: FilePath defaultDistDir = ".stack-work" </> defaultDistPref </> display buildPlatform </> "Cabal-" ++ cabalVersion' #if defined(Cabal20OrLater) distDir (CabalNew packageId ghcVersion) = return $ "dist-newstyle/build" </> display buildPlatform </> "ghc-" ++ ghcVersion </> display packageId #endif getBuildDirectories :: TargetTool -> PackageDescription -> FilePath -> IO ([UnixFilepath], [UnixFilepath]) getBuildDirectories tool pkgDesc cabalDir = do distDir' <- distDir tool let buildDir :: FilePath buildDir = cabalDir </> distDir' </> "build" componentNames :: [String] componentNames = getExeNames pkgDesc ++ getTestNames pkgDesc ++ getBenchmarkNames pkgDesc ++ getForeignLibNames pkgDesc autogenDirs <- getAutogenDirs buildDir componentNames let componentBuildDir :: String -> FilePath componentBuildDir componentName = #if defined(Cabal20OrLater) case tool of CabalNew _ _ -> cabalDir </> distDir' </> "build" </> componentName </> (componentName ++ "-tmp") _ -> buildDir </> componentName </> (componentName ++ "-tmp") #else buildDir </> componentName </> (componentName ++ "-tmp") #endif buildDirs :: [FilePath] buildDirs = autogenDirs ++ map componentBuildDir componentNames buildDirs' = case library pkgDesc of Just _ -> buildDir : buildDirs Nothing -> buildDirs return (map mkUnixFilepath buildDirs', map mkUnixFilepath autogenDirs) getAutogenDirs :: FilePath -> [String] -> IO [FilePath] getAutogenDirs buildDir componentNames = (autogenDir :) A.<$> componentsAutogenDirs buildDir componentNames where -- 'dist/bulid/autogen' OR -- '.stack-work/dist/x86_64-linux/Cabal-1.24.2.0/build/autogen' OR -- ./dist-newstyle/build/x86_64-linux/ghc-8.4.3/lens-4.17/build/autogen autogenDir :: FilePath autogenDir = buildDir </> "autogen" getSourceDirectories :: [BuildInfo] -> FilePath -> [String] getSourceDirectories buildInfo cabalDir = map (cabalDir </>) (concatMap hsSourceDirs buildInfo) #if defined(Cabal20OrLater) doesPackageEnvExist :: GhcVersion -> FilePath -> IO Bool doesPackageEnvExist ghcVersion projectDir = doesFileExist $ projectDir </> packageEnvFn where packageEnvFn = -- The filename for package environments in MacOS uses the synonym "darwin -- "instead of the "official" buildPlatform, "osx". case buildOS of OSX -> ".ghc.environment." ++ display buildArch ++ "-" ++ "darwin" ++ "-" ++ ghcVersion _ -> ".ghc.environment." ++ display buildPlatform ++ "-" ++ ghcVersion #endif allowedOptions :: Set C8.ByteString allowedOptions = S.fromList [ "-w" , "-fglasgow-exts" , "-fpackage-trust" , "-fhelpful-errors" , "-F" , "-cpp" ] allowedOptionPrefixes :: [C8.ByteString] allowedOptionPrefixes = [ "-fwarn-" , "-fno-warn-" , "-W" , "-fcontext-stack=" , "-firrefutable-tuples" , "-D" , "-U" , "-I" , "-fplugin=" , "-fplugin-opt=" , "-pgm" , "-opt" ] forbiddenOptions :: Set C8.ByteString forbiddenOptions = S.fromList [ "-Wmissing-home-modules" , "-Werror=missing-home-modules" ] isAllowedOption :: C8.ByteString -> Bool isAllowedOption opt = S.member opt allowedOptions || any (`C8.isPrefixOf` opt) allowedOptionPrefixes && S.notMember opt forbiddenOptions dumpPackageDescription :: PackageDescription -> FilePath -> IO Sexp dumpPackageDescription pkgDesc projectDir = do (cabalDirs, cabalAutogen) <- getBuildDirectories Cabal pkgDesc projectDir (stackDirs, stackAutogen) <- getBuildDirectories Stack pkgDesc projectDir #if defined(Cabal20OrLater) ghcVersion <- getGhcVersion (cabalNewDirs, cabalNewAutogen) <- getBuildDirectories (CabalNew (package pkgDesc) ghcVersion) pkgDesc projectDir packageEnvExists <- doesPackageEnvExist ghcVersion projectDir let buildDirs = cabalDirs ++ stackDirs ++ cabalNewDirs autogenDirs = cabalAutogen ++ stackAutogen ++ cabalNewAutogen #else let buildDirs = cabalDirs ++ stackDirs autogenDirs = cabalAutogen ++ stackAutogen #endif let packageName = C8.pack $ unPackageName' $ pkgName $ package pkgDesc return $ SList [ cons (sym "build-directories") (ordNub (buildDirs :: [UnixFilepath])) , cons (sym "source-directories") (sourceDirs :: [UnixFilepath]) , cons (sym "extensions") exts , cons (sym "languages") langs , cons (sym "dependencies") deps , cons (sym "other-options") (cppOpts ++ ghcOpts) , cons (sym "autogen-directories") (autogenDirs :: [UnixFilepath]) , cons (sym "should-include-version-header") [not ghcIncludesVersionMacro] #if defined(Cabal20OrLater) , cons (sym "package-env-exists") [packageEnvExists] #endif , cons (sym "package-name") [packageName] , cons (sym "components") $ getComponents packageName pkgDesc ] where buildInfo :: [BuildInfo] buildInfo = allBuildInfo pkgDesc sourceDirs :: [UnixFilepath] sourceDirs = ordNub (map mkUnixFilepath (getSourceDirectories buildInfo projectDir)) exts :: [Extension] exts = nub (concatMap usedExtensions buildInfo) langs :: [Language] langs = nub (concatMap allLanguages buildInfo) thisPackage :: PackageName thisPackage = pkgName (package pkgDesc) deps :: [Dependency] deps = nub (filter ((/= thisPackage) . depPkgName') (buildDepends' pkgDesc)) -- The "cpp-options" configuration field. cppOpts :: [C8.ByteString] cppOpts = ordNub (filter isAllowedOption (map C8.pack (concatMap cppOptions buildInfo))) -- The "ghc-options" configuration field. ghcOpts :: [C8.ByteString] ghcOpts = ordNub (filter isAllowedOption (map C8.pack (concatMap (hcOptions GHC) buildInfo))) #if defined(Cabal20OrLater) -- We don't care about the stack ghc compiler because we don't need it for -- the stack checker getGhcVersion :: IO String getGhcVersion = go "cabal" ["new-exec", "ghc", "--", "--numeric-version"] (go "ghc" ["--numeric-version"] A.empty) where go :: String -> [String] -> IO String -> IO String go comm opts cont = do res <- try $ readProcessWithExitCode comm opts [] case res of Left (_ :: SomeException) -> cont Right (ExitSuccess, stdOut, _) -> return $ stripWhitespace stdOut Right (ExitFailure _, _, _) -> cont #endif data ComponentType = CTLibrary | CTForeignLibrary | CTExecutable | CTTestSuite | CTBenchmark deriving (Eq, Ord, Show, Enum, Bounded) componentTypePrefix :: ComponentType -> C8.ByteString componentTypePrefix x = case x of CTLibrary -> "lib" CTForeignLibrary -> "flib" CTExecutable -> "exe" CTTestSuite -> "test" CTBenchmark -> "bench" instance ToSexp ComponentType where toSexp = toSexp . componentTypePrefix -- | Gather files and modules that constitute each component. getComponents :: C8.ByteString -> PackageDescription -> [(ComponentType, C8.ByteString, Maybe C8.ByteString, [ModuleName])] getComponents packageName pkgDescr = [ (CTLibrary, name, Nothing, exposedModules lib ++ biMods bi) | lib <- allLibraries' pkgDescr , let bi = libBuildInfo lib , let name = maybe packageName C8.pack $ libName' lib ] ++ #if defined(Cabal20OrLater) [ (CTForeignLibrary, C8.pack (foreignLibName' flib), Nothing, biMods bi) | flib <- foreignLibs pkgDescr , let bi = foreignLibBuildInfo flib ] ++ #endif [ (CTExecutable, C8.pack (exeName' exe), Just (C8.pack (modulePath exe)), biMods bi) | exe <- executables pkgDescr , let bi = buildInfo exe ] ++ [ (CTTestSuite, C8.pack (testName' tst), exeFile, maybeToList extraMod ++ biMods bi) | tst <- testSuites pkgDescr , let bi = testBuildInfo tst , let (exeFile, extraMod) = case testInterface tst of TestSuiteExeV10 _ path -> (Just (C8.pack path), Nothing) TestSuiteLibV09 _ modName -> (Nothing, Just modName) TestSuiteUnsupported{} -> (Nothing, Nothing) ] #ifdef Cabal114OrMore ++ [ (CTBenchmark, C8.pack (benchmarkName' tst), exeFile, biMods bi) | tst <- benchmarks pkgDescr , let bi = benchmarkBuildInfo tst , let exeFile = case benchmarkInterface tst of BenchmarkExeV10 _ path -> Just (C8.pack path) BenchmarkUnsupported{} -> Nothing ] #endif where #if defined(Cabal20OrLater) biMods bi = otherModules bi #if defined(Cabal22OrLater) ++ virtualModules bi #endif ++ autogenModules bi #else biMods = otherModules #endif getCabalConfiguration :: HPackExe -> ConfigurationFile -> IO Sexp getCabalConfiguration hpackExe configFile = do genericDesc <- case configFile of HPackFile path -> readHPackPkgDescr hpackExe path projectDir CabalFile path -> readGenericPkgDescr path case getConcretePackageDescription genericDesc of Left e -> die' $ "Issue with package configuration\n" ++ show e Right pkgDesc -> dumpPackageDescription pkgDesc projectDir where projectDir :: FilePath projectDir = dropFileName $ configFilePath configFile readHPackPkgDescr :: HPackExe -> FilePath -> FilePath -> IO GenericPackageDescription readHPackPkgDescr exe configFile projectDir = do (Nothing, Just out, Just err, procHandle) <- Process.createProcess p cabalFileContents <- readCabalFileContentsFromHandle out exitCode <- Process.waitForProcess procHandle case exitCode of ExitFailure{} -> do err' <- hGetContents err die' $ "Failed to obtain cabal configuration by running hpack on '" ++ configFile ++ "':\n" ++ err' ExitSuccess -> case parsePkgDescr "<generated by hpack>" cabalFileContents of Left msgs -> die' $ "Failed to parse cabal file produced by hpack from '" ++ configFile ++ "':\n" ++ unlines msgs Right x -> return x where p = (Process.proc (unHPackExe exe) [configFile, "-"]) { Process.std_in = Process.Inherit , Process.std_out = Process.CreatePipe , Process.std_err = Process.CreatePipe , Process.cwd = Just projectDir } buildDepends' :: PackageDescription -> [Dependency] buildDepends' = #if defined(Cabal24) || defined(Cabal30) || defined(Cabal32) allBuildDepends #else buildDepends #endif readGenericPkgDescr :: FilePath -> IO GenericPackageDescription readGenericPkgDescr = #if defined(Cabal20OrLater) readGenericPackageDescription silent #else readPackageDescription silent #endif newtype CabalFileContents = CabalFileContents { unCabalFileContents :: #if defined(Cabal22OrLater) BS.ByteString #else String #endif } readCabalFileContentsFromHandle :: Handle -> IO CabalFileContents readCabalFileContentsFromHandle = fmap CabalFileContents . #if defined(Cabal22OrLater) BS.hGetContents #else hGetContents #endif parsePkgDescr :: FilePath -> CabalFileContents -> Either [String] GenericPackageDescription parsePkgDescr _fileName cabalFileContents = #if defined(Cabal32OrLater) case runParseResult $ parseGenericPackageDescription $ unCabalFileContents cabalFileContents of (_warnings, res) -> case res of Left (_version, errs) -> Left $ map (showPError _fileName) $ toList errs Right x -> return x #elif defined(Cabal22OrLater) case runParseResult $ parseGenericPackageDescription $ unCabalFileContents cabalFileContents of (_warnings, res) -> case res of Left (_version, errs) -> Left $ map (showPError _fileName) errs Right x -> return x #elif defined(Cabal20) case parseGenericPackageDescription $ unCabalFileContents cabalFileContents of ParseFailed failure -> let (_line, msg) = locatedErrorMsg failure in Left [msg] ParseOk _warnings x -> Right x #else case parsePackageDescription $ unCabalFileContents cabalFileContents of ParseFailed failure -> let (_line, msg) = locatedErrorMsg failure in Left [msg] ParseOk _warnings x -> Right x #endif getConcretePackageDescription :: GenericPackageDescription -> Either [Dependency] PackageDescription getConcretePackageDescription genericDesc = do #if defined(Cabal22OrLater) let enabled :: ComponentRequestedSpec enabled = ComponentRequestedSpec { testsRequested = True , benchmarksRequested = True } fst A.<$> finalizePD (mkFlagAssignment []) -- Flag assignment enabled -- Enable all components (const True) -- Whether given dependency is available buildPlatform buildCompilerId [] -- Additional constraints genericDesc #elif defined(Cabal20) let enabled :: ComponentRequestedSpec enabled = ComponentRequestedSpec { testsRequested = True , benchmarksRequested = True } fst A.<$> finalizePD [] -- Flag assignment enabled -- Enable all components (const True) -- Whether given dependency is available buildPlatform buildCompilerId [] -- Additional constraints genericDesc #elif Cabal114OrMore -- This let block is eerily like one in Cabal.Distribution.Simple.Configure let enableTest :: TestSuite -> TestSuite enableTest t = t { testEnabled = True } enableBenchmark :: Benchmark -> Benchmark enableBenchmark bm = bm { benchmarkEnabled = True } flaggedTests = map (second (mapTreeData enableTest)) (condTestSuites genericDesc) flaggedBenchmarks = map (second (mapTreeData enableBenchmark)) (condBenchmarks genericDesc) genericDesc' = genericDesc { condTestSuites = flaggedTests , condBenchmarks = flaggedBenchmarks } fst A.<$> finalizePackageDescription [] (const True) buildPlatform buildCompilerId [] genericDesc' #else -- This let block is eerily like one in Cabal.Distribution.Simple.Configure let enableTest :: TestSuite -> TestSuite enableTest t = t { testEnabled = True } flaggedTests = map (second (mapTreeData enableTest)) (condTestSuites genericDesc) genericDesc' = genericDesc { condTestSuites = flaggedTests } fst A.<$> finalizePackageDescription [] (const True) buildPlatform buildCompilerId [] genericDesc' #endif componentsAutogenDirs :: FilePath -> [String] -> IO [FilePath] #if defined(Cabal20OrLater) componentsAutogenDirs buildDir componentNames = filterM doesDirectoryExist $ map (\path -> buildDir </> path </> "autogen") componentNames #else componentsAutogenDirs _ _ = return [] #endif #if defined(Cabal118OrLess) buildCompilerId :: CompilerId buildCompilerId = CompilerId buildCompilerFlavor compilerVersion #else buildCompilerId :: CompilerInfo buildCompilerId = unknownCompilerInfo compId NoAbiTag where compId :: CompilerId compId = CompilerId buildCompilerFlavor compVersion # if defined(Cabal20OrLater) compVersion :: CabalVersion.Version compVersion = CabalVersion.mkVersion' compilerVersion # else compVersion :: Version compVersion = compilerVersion # endif #endif allLibraries' :: PackageDescription -> [Library] allLibraries' = #if defined(Cabal20OrLater) allLibraries #else maybeToList . library #endif libName' :: Library -> Maybe String libName' = #if defined(Cabal30OrLater) fmap unUnqualComponentName . libraryNameString . libName #elif defined(Cabal20) || defined(Cabal22) || defined(Cabal24) fmap unUnqualComponentName . libName #else const Nothing #endif exeName' :: Executable -> String exeName' = #if defined(Cabal20OrLater) unUnqualComponentName . exeName #else exeName #endif #if defined(Cabal20OrLater) foreignLibName' :: ForeignLib -> String foreignLibName' = unUnqualComponentName . foreignLibName #endif testName' :: TestSuite -> String testName' = #if defined(Cabal20OrLater) unUnqualComponentName . testName #else testName #endif #ifdef Cabal114OrMore benchmarkName' :: Benchmark -> FilePath benchmarkName' = # if defined(Cabal20OrLater) unUnqualComponentName . benchmarkName # else benchmarkName # endif #endif getExeNames :: PackageDescription -> [String] getExeNames = map exeName' . executables getForeignLibNames :: PackageDescription -> [String] getForeignLibNames = #if defined(Cabal20OrLater) map foreignLibName' . foreignLibs #else const [] #endif getTestNames :: PackageDescription -> [String] getTestNames = map testName' . testSuites getBenchmarkNames :: PackageDescription -> [String] getBenchmarkNames = #ifdef Cabal114OrMore map benchmarkName' . benchmarks #else const [] #endif depPkgName' :: Dependency -> PackageName depPkgName' = #if defined(Cabal20OrLater) depPkgName #else let f (Dependency x _) = x in f #endif unPackageName' :: PackageName -> String unPackageName' = #if defined(Cabal20OrLater) unPackageName #else let f (PackageName x) = x in f #endif -- Textual representation of cabal version cabalVersion' :: String cabalVersion' = #if defined(Cabal22OrLater) prettyShow cabalVersion #elif defined(Cabal20) CabalVersion.showVersion cabalVersion #else showVersion cabalVersion #endif ghcIncludesVersionMacro :: Bool ghcIncludesVersionMacro = #if defined(GHC_INCLUDES_VERSION_MACRO) True #else False #endif ordNub :: forall a. Ord a => [a] -> [a] ordNub = go S.empty where go :: Set a -> [a] -> [a] go _ [] = [] go !acc (x:xs) | S.member x acc = go acc xs | otherwise = x : go (S.insert x acc) xs stripWhitespace :: String -> String stripWhitespace = reverse . dropWhile isSpace . reverse . dropWhile isSpace die' :: String -> IO a die' msg = do hPutStrLn stderr msg exitFailure #if !defined(HAVE_DATA_FUNCTOR_IDENTITY) newtype Identity a = Identity { runIdentity :: a } #endif data ConfigurationFile = CabalFile FilePath | HPackFile FilePath configFilePath :: ConfigurationFile -> FilePath configFilePath (CabalFile path) = path configFilePath (HPackFile path) = path newtype HPackExe = HPackExe { unHPackExe :: FilePath } data Config f = Config { cfgInputFile :: f ConfigurationFile , cfgHPackExe :: HPackExe } reifyConfig :: Config Maybe -> IO (Config Identity) reifyConfig Config{cfgInputFile, cfgHPackExe} = do cfgInputFile' <- case cfgInputFile of Nothing -> die' "Input file not specified. Use --cabal-file or --hpack-file to specify one." Just path -> return path return Config { cfgInputFile = Identity cfgInputFile' , cfgHPackExe } optionDescr :: [OptDescr (Config Maybe -> Config Maybe)] optionDescr = [ Option [] ["cabal-file"] (ReqArg (\path cfg -> cfg { cfgInputFile = Just (CabalFile path) }) "FILE") "Cabal file to process" , Option [] ["hpack-file"] (ReqArg (\path cfg -> cfg { cfgInputFile = Just (HPackFile path) }) "FILE") "HPack package.yaml file to process" , Option [] ["hpack-exe"] (ReqArg (\path cfg -> cfg { cfgHPackExe = HPackExe path }) "FILE") "Path to 'hpack' executable" ] defaultConfig :: Config Maybe defaultConfig = Config { cfgInputFile = Nothing , cfgHPackExe = HPackExe "hpack" } main' :: Config Identity -> IO () main' Config{cfgInputFile, cfgHPackExe} = hPutBuilder stdout . renderSexp =<< getCabalConfiguration cfgHPackExe (runIdentity cfgInputFile) main :: IO () main = do args <- getArgs when (any (`elem` ["-h", "--help"]) args) $ do putStrLn usage exitSuccess case getOpt' RequireOrder optionDescr args of (fs, [], [], []) -> do let cfg = foldl' (flip ($)) defaultConfig fs main' =<< reifyConfig cfg (_, x:_, [], []) -> die' $ "Unrecognised argument: " ++ x (_, [], y:_, []) -> die' $ "Unrecognised command-line option: " ++ y (_, _, _, es) -> die' $ "Failed to parse command-line options:\n" ++ unlines es where header = "Usage: get-cabal-configuration [OPTION...]" usage = usageInfo header optionDescr
emacsmirror/flycheck-haskell
get-cabal-configuration.hs
gpl-3.0
32,647
0
19
7,155
6,102
3,358
2,744
445
5
module Base.Renderable.CenterHorizontally where import Graphics.Qt import Base.Types import Base.Renderable.Common () centerHorizontally :: Renderable r => r -> RenderableInstance centerHorizontally = RenderableInstance . CenterHorizontally . RenderableInstance data CenterHorizontally = CenterHorizontally RenderableInstance instance Renderable CenterHorizontally where label = const "CenterHorizontally" render ptr app config parentSize (CenterHorizontally child) = do (childSize, childAction) <- render ptr app config parentSize child let size = Size (width parentSize) (height childSize) offset = (width parentSize - width childSize) / 2 action = do translate ptr $ Position offset 0 childAction return (size, action)
geocurnoff/nikki
src/Base/Renderable/CenterHorizontally.hs
lgpl-3.0
818
0
14
182
209
107
102
17
1
yes = [(foo bar)]
bitemyapp/apply-refact
tests/examples/Bracket10.hs
bsd-3-clause
17
0
7
3
15
8
7
1
1
{-# LANGUAGE Unsafe #-} {-# LANGUAGE ExistentialQuantification, NoImplicitPrelude #-} module GHC.Event.Internal ( -- * Event back end Backend , backend , delete , poll , modifyFd , modifyFdOnce -- * Event type , Event , evtRead , evtWrite , evtClose , eventIs -- * Lifetimes , Lifetime(..) , EventLifetime , eventLifetime , elLifetime , elEvent -- * Timeout type , Timeout(..) -- * Helpers , throwErrnoIfMinus1NoRetry ) where import Data.Bits ((.|.), (.&.)) import Data.OldList (foldl', filter, intercalate, null) import Foreign.C.Error (eINTR, getErrno, throwErrno) import System.Posix.Types (Fd) import GHC.Base import GHC.Word (Word64) import GHC.Num (Num(..)) import GHC.Show (Show(..)) import Data.Semigroup.Internal (stimesMonoid) -- | An I\/O event. newtype Event = Event Int deriving Eq -- ^ @since 4.4.0.0 evtNothing :: Event evtNothing = Event 0 {-# INLINE evtNothing #-} -- | Data is available to be read. evtRead :: Event evtRead = Event 1 {-# INLINE evtRead #-} -- | The file descriptor is ready to accept a write. evtWrite :: Event evtWrite = Event 2 {-# INLINE evtWrite #-} -- | Another thread closed the file descriptor. evtClose :: Event evtClose = Event 4 {-# INLINE evtClose #-} eventIs :: Event -> Event -> Bool eventIs (Event a) (Event b) = a .&. b /= 0 -- | @since 4.4.0.0 instance Show Event where show e = '[' : (intercalate "," . filter (not . null) $ [evtRead `so` "evtRead", evtWrite `so` "evtWrite", evtClose `so` "evtClose"]) ++ "]" where ev `so` disp | e `eventIs` ev = disp | otherwise = "" -- | @since 4.10.0.0 instance Semigroup Event where (<>) = evtCombine stimes = stimesMonoid -- | @since 4.4.0.0 instance Monoid Event where mempty = evtNothing mconcat = evtConcat evtCombine :: Event -> Event -> Event evtCombine (Event a) (Event b) = Event (a .|. b) {-# INLINE evtCombine #-} evtConcat :: [Event] -> Event evtConcat = foldl' evtCombine evtNothing {-# INLINE evtConcat #-} -- | The lifetime of an event registration. -- -- @since 4.8.1.0 data Lifetime = OneShot -- ^ the registration will be active for only one -- event | MultiShot -- ^ the registration will trigger multiple times deriving ( Show -- ^ @since 4.8.1.0 , Eq -- ^ @since 4.8.1.0 ) -- | The longer of two lifetimes. elSupremum :: Lifetime -> Lifetime -> Lifetime elSupremum OneShot OneShot = OneShot elSupremum _ _ = MultiShot {-# INLINE elSupremum #-} -- | @since 4.10.0.0 instance Semigroup Lifetime where (<>) = elSupremum stimes = stimesMonoid -- | @mappend@ takes the longer of two lifetimes. -- -- @since 4.8.0.0 instance Monoid Lifetime where mempty = OneShot -- | A pair of an event and lifetime -- -- Here we encode the event in the bottom three bits and the lifetime -- in the fourth bit. newtype EventLifetime = EL Int deriving ( Show -- ^ @since 4.8.0.0 , Eq -- ^ @since 4.8.0.0 ) -- | @since 4.11.0.0 instance Semigroup EventLifetime where EL a <> EL b = EL (a .|. b) -- | @since 4.8.0.0 instance Monoid EventLifetime where mempty = EL 0 eventLifetime :: Event -> Lifetime -> EventLifetime eventLifetime (Event e) l = EL (e .|. lifetimeBit l) where lifetimeBit OneShot = 0 lifetimeBit MultiShot = 8 {-# INLINE eventLifetime #-} elLifetime :: EventLifetime -> Lifetime elLifetime (EL x) = if x .&. 8 == 0 then OneShot else MultiShot {-# INLINE elLifetime #-} elEvent :: EventLifetime -> Event elEvent (EL x) = Event (x .&. 0x7) {-# INLINE elEvent #-} -- | A type alias for timeouts, specified in nanoseconds. data Timeout = Timeout {-# UNPACK #-} !Word64 | Forever deriving Show -- ^ @since 4.4.0.0 -- | Event notification backend. data Backend = forall a. Backend { _beState :: !a -- | Poll backend for new events. The provided callback is called -- once per file descriptor with new events. , _bePoll :: a -- backend state -> Maybe Timeout -- timeout in milliseconds ('Nothing' for non-blocking poll) -> (Fd -> Event -> IO ()) -- I/O callback -> IO Int -- | Register, modify, or unregister interest in the given events -- on the given file descriptor. , _beModifyFd :: a -> Fd -- file descriptor -> Event -- old events to watch for ('mempty' for new) -> Event -- new events to watch for ('mempty' to delete) -> IO Bool -- | Register interest in new events on a given file descriptor, set -- to be deactivated after the first event. , _beModifyFdOnce :: a -> Fd -- file descriptor -> Event -- new events to watch -> IO Bool , _beDelete :: a -> IO () } backend :: (a -> Maybe Timeout -> (Fd -> Event -> IO ()) -> IO Int) -> (a -> Fd -> Event -> Event -> IO Bool) -> (a -> Fd -> Event -> IO Bool) -> (a -> IO ()) -> a -> Backend backend bPoll bModifyFd bModifyFdOnce bDelete state = Backend state bPoll bModifyFd bModifyFdOnce bDelete {-# INLINE backend #-} poll :: Backend -> Maybe Timeout -> (Fd -> Event -> IO ()) -> IO Int poll (Backend bState bPoll _ _ _) = bPoll bState {-# INLINE poll #-} -- | Returns 'True' if the modification succeeded. -- Returns 'False' if this backend does not support -- event notifications on this type of file. modifyFd :: Backend -> Fd -> Event -> Event -> IO Bool modifyFd (Backend bState _ bModifyFd _ _) = bModifyFd bState {-# INLINE modifyFd #-} -- | Returns 'True' if the modification succeeded. -- Returns 'False' if this backend does not support -- event notifications on this type of file. modifyFdOnce :: Backend -> Fd -> Event -> IO Bool modifyFdOnce (Backend bState _ _ bModifyFdOnce _) = bModifyFdOnce bState {-# INLINE modifyFdOnce #-} delete :: Backend -> IO () delete (Backend bState _ _ _ bDelete) = bDelete bState {-# INLINE delete #-} -- | Throw an 'Prelude.IOError' corresponding to the current value of -- 'getErrno' if the result value of the 'IO' action is -1 and -- 'getErrno' is not 'eINTR'. If the result value is -1 and -- 'getErrno' returns 'eINTR' 0 is returned. Otherwise the result -- value is returned. throwErrnoIfMinus1NoRetry :: (Eq a, Num a) => String -> IO a -> IO a throwErrnoIfMinus1NoRetry loc f = do res <- f if res == -1 then do err <- getErrno if err == eINTR then return 0 else throwErrno loc else return res
sdiehl/ghc
libraries/base/GHC/Event/Internal.hs
bsd-3-clause
6,918
0
16
1,992
1,455
816
639
147
3
module Docs.AST where import qualified Data.Map as Map import qualified Elm.Compiler.Type as Type import qualified Reporting.Annotation as A -- FULL DOCUMENTATION data Docs t = Docs { comment :: String , aliases :: Map.Map String (A.Located Alias) , types :: Map.Map String (A.Located Union) , values :: Map.Map String (A.Located (Value t)) } type Centralized = Docs (Maybe Type.Type) type Checked = Docs Type.Type -- VALUE DOCUMENTATION data Alias = Alias { aliasComment :: Maybe String , aliasArgs :: [String] , aliasType :: Type.Type } data Union = Union { unionComment :: Maybe String , unionArgs :: [String] , unionCases :: [(String, [Type.Type])] } data Value t = Value { valueComment :: Maybe String , valueType :: t , valueAssocPrec :: Maybe (String,Int) }
pairyo/elm-compiler
src/Docs/AST.hs
bsd-3-clause
848
0
13
207
268
160
108
23
0
module Fail2 where f = let g xs = map (+1) xs in g list where list = [1,1,2,3,4]
kmate/HaRe
old/testing/letToWhere/Fail2_TokOut.hs
bsd-3-clause
101
0
10
39
57
32
25
3
1
{-# htermination addListToFM_C :: (b -> b -> b) -> FiniteMap Char b -> [(Char,b)] -> FiniteMap Char b #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_addListToFM_C_3.hs
mit
123
0
3
22
5
3
2
1
0
module Text.ParserCombinators.TagWiki where import Control.Applicative hiding ( many, (<|>) ) import Data.List import Text.ParserCombinators.Parsec class Parseable a where parser :: GenParser Char st a -- Parses and reads one or more digits number :: GenParser Char st Int number = read <$> many1 digit real :: (RealFrac r, Read r) => GenParser Char st r real = read <$> str where str = (++) <$> int <*> option "" decimal decimal = char '.' *> int int = many1 digit -- \s → \\\\ quadrupleHack :: GenParser Char st String quadrupleHack = hack *> char 's' *> return "\\\\\\\\" -- Excludes newlines whitespace :: GenParser Char st String whitespace = many $ oneOf " \t" -- Includes newlines anyWhite :: GenParser Char st String anyWhite = many $ oneOf " \t\n" -- newline or EOF eol :: GenParser Char st String eol = try (return <$> newline) <|> (eof *> return "") -- \\ -> \ hackhack :: GenParser Char st Char hackhack = hack *> hack *> return '\\' -- '\ ' -> space, \t -> tab, '\n' -> newline escWhite :: GenParser Char st Char escWhite = try (hack *> space) <|> try (hack *> tab) <|> try (hack *> newline) <?> "escaped whitespace" -- Ignored hack hack :: GenParser Char st () hack = char '\\' *> return () -- Parses a character not present in `chars`, unless escaped with a backslash. -- If escaped, 'unescapes' the character in the parsed string. -- Ex. -- parseTest (escaping "abc") "\a \b \c" → "a b c" -- parseTest (escaping "abc") "a \b \c" → error (unescaped a) escaping :: String -> GenParser Char st Char escaping chars = try hackhack <|> try (hack *> oneOf chars) <|> noneOf (nub chars) <?> "[^" ++ oneLine chars ++ "] or an escape sequence" where oneLine = intercalate "\\n" . lines -- Parse a whole string of escaping characters except :: String -> GenParser Char st String except = many1 . escaping -- A whitespace-wrapped parser floating :: GenParser Char st a -> GenParser Char st a floating p = anyWhite *> p <* anyWhite -- An multiline operator operator :: String -> GenParser Char st () operator c = anyWhite *> string c *> anyWhite *> return () -- A symbol with optional whitespace preciding it designator :: String -> GenParser Char st () designator c = whitespace *> string c *> return () -- A symbol with optional whitespace before and after (no newlines) marker :: String -> GenParser Char st () marker c = whitespace *> string c *> whitespace *> return ()
Soares/tagwiki
src/Text/ParserCombinators/TagWiki.hs
mit
2,500
0
13
551
697
360
337
46
1
module Y2018.M08.D15.Exercise where {-- Today we have a list of the top 5000 English language words (by frequency) from https://www.wordfrequency.info. We are going to parse this file and answer a question. --} import Prelude hiding (Word) import Data.Array import Data.Map -- below modules available via 1HaskellADay git repository import Control.Scan.CSV import qualified Data.MultiMap as MM exDir, tsvFile :: FilePath exDir = "Y2018/M08/D15/" tsvFile = "words_counts.tsv" -- The TSV file has a header and footer, so watch out. Parse the file into -- the following structure: type Word = String type PartOfSpeech = Char data WordFreq = WF { word :: Word, partOfSpeech :: PartOfSpeech, freq :: Int, dispersion :: Float } deriving Show -- the parts of speech are catalogued here: ... um ... okay, bad link. -- deal with it: guess away. -- So, our word frequencies: readWordFreqs :: FilePath -> IO (Array Int WordFreq) readWordFreqs file = undefined -- What is the part-of-speech that has the most words? second most? etc? partsOfSpeech :: Array Int WordFreq -> Map PartOfSpeech [Word] partsOfSpeech wordfreqs = undefined -- you can use a multi-map to construct the above result if you'd like -- What are the words of length 5 in this list? Or, more generally, what are -- the words of length n? type Length = Int nwords :: Array Int WordFreq -> Map Length [Word] nwords wordfreqs = undefined -- Again, use a multi-map if you'd like
geophf/1HaskellADay
exercises/HAD/Y2018/M08/D15/Exercise.hs
mit
1,475
0
8
280
212
130
82
21
1
{-# LANGUAGE Rank2Types #-} module Battle ( ix, ixM, ixIM, BattleState(..), Board (Board), Tactic, TacticList, addTactic, runBoard, player, enemy, turn, tacticList, battleState, module Character ) where import Control.Arrow import Control.Monad.State import Data.List import qualified Data.Map as M import qualified Data.IntMap as IM import Lens.Family2 import Lens.Family2.State.Lazy import Lens.Family2.Unchecked import Character ix :: Int -> Lens' [a] a ix n = lens (!! n) (\l x -> take (n-1) l ++ [x] ++ drop (n+1) l) ixM :: (Ord a) => a -> Lens' (M.Map a b) b ixM n = lens (M.! n) (\l x -> M.insert n x l) ixIM :: Int -> Lens' (IM.IntMap b) b ixIM n = lens (IM.! n) (\l x -> IM.insert n x l) getCommand :: CommandList -> (Command, CommandList) getCommand cl = ((cl ^. commandMap) IM.! (cl ^. index), cl & index .~ nextIndex) where nextIndex = if (cl^.index) == (cl^.listSize) - 1 then 0 else cl^.index + 1 type Tactic = M.Map String CommandList type TacticList = IM.IntMap Tactic addTactic :: Tactic -> TacticList -> TacticList addTactic x tt = IM.insert (mi + 1) x tt where mi = maximum $ IM.keys tt data BattleState = Waiting | Win | Lose | Battling deriving (Eq, Show) data Board = Board { _player :: [Character], _enemy :: [Character], _turn :: Int, _tacticList :: TacticList, _battleState :: BattleState } deriving (Show) player :: Lens' Board [Character] player = lens _player (\f x -> f { _player = x }) enemy :: Lens' Board [Character] enemy = lens _enemy (\f x -> f { _enemy = x }) turn :: Lens' Board Int turn = lens _turn (\f x -> f { _turn = x }) tacticList :: Lens' Board TacticList tacticList = lens _tacticList (\f x -> f { _tacticList = x }) battleState :: Lens' Board BattleState battleState = lens _battleState (\f x -> f { _battleState = x }) attackCalc :: Character -> Int attackCalc ch = (ch ^. strength) * 5 defenceCalc :: Character -> Int defenceCalc ch = (ch ^. vitality) * 2 damageCalc :: Character -> Character -> Int damageCalc s t = attackCalc s - defenceCalc t toAction :: Target -> Command -> Action toAction t Attack = AttackTo t toAction t com = Iso com runCommand :: Int -> StateT Board IO [Command] runCommand tti = do tt <- use (tacticList . ixIM tti) forM (M.assocs tt) $ \(chara, cl) -> do let (com, cl') = getCommand cl tacticList . ixIM tti . ixM chara .= cl' return com runBoard :: StateT Board IO () runBoard = do turn += 1 comp <- runCommand 0 pair1 <- liftM2 zip (return $ fmap (toAction ToEnemy) comp) (use player) es <- use enemy let (come, enemy') = unzip $ fmap (\e -> second (\cl -> e & commandList .~ cl) $ getCommand $ e^.commandList) es enemy .= enemy' pair2 <- liftM2 zip (return $ fmap (toAction ToPlayer) come) (use enemy) let ps = sortBy (\(_,a) (_,b) -> compare (a^.agility) (b^.agility)) $ concat [pair1,pair2] forM_ ps $ \(com,chara) -> case com of AttackTo ToPlayer -> do pchara <- use $ player . ix 0 player . ix 0 . hp -= damageCalc chara pchara AttackTo ToEnemy -> do penemy <- use $ enemy . ix 0 enemy . ix 0 . hp -= damageCalc chara penemy Iso _ -> return () lift . print =<< use player lift . print =<< use enemy es <- use enemy when (all (\e -> e ^. hp <= 0) es) $ do battleState .= Win ps <- use player when (all (\p -> p ^. hp <= 0) ps) $ do battleState .= Lose main = do let b = Board [princess, madman] [enemy1] 0 (IM.fromList []) Waiting execStateT (runBoard >> runBoard >> runBoard >> runBoard >> runBoard) b {- - STR: 攻撃ダメージ比率と攻撃ヒット率が上がる - INT: 最大MPが上がる 回復スキルの回復量が上がる - TEC: スキルダメージ比率が上がる 攻撃スキルの追加効果発生率が少し上がる - VIT: 最大HPが上がる 防御力が上がる - AGI: 速度補正率が上がる 回避率が少し上がる - LUC: 確率スキルと装備品の成功率が上がる -}
myuon/OoP
src/Battle.hs
mit
3,968
0
21
827
1,630
856
774
-1
-1
{-# LANGUAGE OverloadedStrings #-} module BigTable.TypeOfHtml where import Criterion.Main (Benchmark, bench, nf) import Data.Text.Lazy (Text) import Html import Weigh (Weigh, func) -- | Render the argument matrix as an HTML table. -- bigTable :: [[Int]] -- ^ Matrix. -> Text -- ^ Result. bigTable rows = renderText $ h1_ ("i am a real big old table\n" :: Text) # p_ ("i am good at lots of static data\n" :: Text) # p_ ("i am glab at lots of static data\n" :: Text) # p_ ("i am glob at lots of static data\n" :: Text) # p_ ("i am glib at lots of static data\n" :: Text) # p_ ("i am glub at lots of static data\n" :: Text) # p_ ("i am glom at lots of static data\n" :: Text) # p_ ("i am glof at lots of static data\n" :: Text) # p_ ("i am gref at lots of static data\n" :: Text) # p_ ("i am greg at lots of static data\n" :: Text) # table_ ( thead_ (tr_ (map (th_ . show) [1..10 :: Int])) # tbody_ (map row rows)) # p_ ("i am good at lots of static data\n" :: Text) # p_ ("i am glab at lots of static data\n" :: Text) # p_ ("i am glob at lots of static data\n" :: Text) # p_ ("i am glib at lots of static data\n" :: Text) # p_ ("i am glub at lots of static data\n" :: Text) # p_ ("i am glom at lots of static data\n" :: Text) # p_ ("i am glof at lots of static data\n" :: Text) # p_ ("i am gref at lots of static data\n" :: Text) # p_ ("i am greg at lots of static data\n" :: Text) where row r = tr_ (map (\t -> td_ $ p_ ("hi!\n" :: Text) # show t # p_ ("hello!\n" :: Text)) r) benchmark :: [[Int]] -> Benchmark benchmark rows = bench "type-of-html" (bigTable `nf` rows) weight :: [[Int]] -> Weigh () weight i = func (show (length i) ++ "/type-of-html") bigTable i
TransportEngineering/nice-html
benchmarks/BigTable/TypeOfHtml.hs
mit
1,874
0
26
555
529
289
240
41
1
-- a program for testing the alignment algorithm {-# LANGUAGE OverloadedStrings #-} import System.Environment import Data.Text as ST import Data.Text.IO as STIO import Data.Text.Lazy as LT import FastA import Alignment import NucModel import PWMModel import Align smallprob = 0.0001 scale = 1000 main = do [mod, seq] <- getArgs let modf = FastA "mod" $ LT.pack mod let moda = fastARecordsToAln [modf] let modn = alnToNucModel smallprob scale "model" moda let modc = NucPWMModel modn let alnres = msalign defScScheme modc $ ST.pack seq STIO.putStrLn alnres
tjunier/mlgsc
src/alntoy.hs
mit
583
0
12
113
171
90
81
20
1
{-# LANGUAGE NoImplicitPrelude #-} module Nix ( module Nix.Expr, module Nix.Parser, module Nix.LicenseType ) where import Nix.Common import Nix.Expr import Nix.Parser import Nix.LicenseType
adnelson/simple-nix
src/Nix.hs
mit
205
0
5
38
45
29
16
9
0
{-# LANGUAGE Arrows, TupleSections #-} module Server.Simulation( mainWire ) where import Control.DeepSeq import Core import Data.Text (Text) import FRP.Netwire import Prelude hiding (id, (.)) import Server.Game.Player import Server.Game.World mainWire :: GameMonad (GameWire () ()) mainWire = do logInfo "Starting default world..." return $ proc _ -> do -- Running predefined world (w, wid) <- runIndexed (world "default") -< () -- When player connects, add to default world cplayers <- liftEvent spawnPlayers . playersConnected -< () putMessagesE . mapE (fmap $ second SpawnPlayer) -< fmap (wid,) <$> cplayers -- When player disconnect, remove from world dplayers <- playersDisconnected -< () putMessagesE . mapE (fmap $ second DespawnPlayer) -< fmap (wid,) <$> dplayers forceNF -< w `deepseq` () where spawnPlayers :: GameWire [Text] [Player] spawnPlayers = liftGameMonad1 $ mapM $ \name -> do i <- registerObject return $! Player i name
NCrashed/sinister
src/server/Server/Simulation.hs
mit
1,030
1
17
229
311
163
148
24
1
module BankAccount ( BankAccount , closeAccount , getBalance , incrementBalance , openAccount ) where import Control.Concurrent.STM (TVar, atomically, modifyTVar, newTVarIO, readTVarIO, writeTVar) data BankAccount = BankAccount { balance :: TVar (Maybe Integer) } openAccount :: IO BankAccount openAccount = do startingBalance <- newTVarIO (Just 0) return BankAccount { balance = startingBalance } getBalance :: BankAccount -> IO (Maybe Integer) getBalance = readTVarIO . balance incrementBalance :: BankAccount -> Integer -> IO (Maybe Integer) incrementBalance account amount = do atomically $ modifyTVar (balance account) (fmap (+ amount)) getBalance account closeAccount :: BankAccount -> IO () closeAccount = atomically . flip writeTVar Nothing . balance
tfausak/exercism-solutions
haskell/bank-account/BankAccount.hs
mit
781
0
11
125
239
127
112
20
1
{-# OPTIONS -Wall #-} import Helpers.Grid (Grid, (!)) import qualified Helpers.Grid as Grid main :: IO () main = do heightMap <- Grid.fromDigits <$> getContents let lowestPoints = findLowestPoints heightMap print $ sum $ map succ lowestPoints findLowestPoints :: Grid Int -> [Int] findLowestPoints heightMap = [ heightMap ! points | points <- Grid.allPointsList heightMap, let value = heightMap ! points in all (value <) (Grid.neighboringValues points heightMap) ]
SamirTalwar/advent-of-code
2021/AOC_09_1.hs
mit
495
0
12
99
162
84
78
14
1
-- | Specification for the exercises of Chapter 2. module Chapter02Spec where import Chapter02 (myInit, myInit', myLast, myLast') import Test.Hspec (Spec, describe, it) import Test.QuickCheck (Property, property, (==>)) checkLastDef :: ([Int] -> Int) -> Property checkLastDef lastImpl = property $ \xs -> not (null xs) ==> lastImpl xs == last xs checkInitDef :: ([Int] -> [Int]) -> Property checkInitDef initImpl = property $ \xs -> not (null xs) ==> initImpl xs == init xs spec :: Spec spec = do describe "myLast" $ do it "correctly implements last" $ checkLastDef myLast describe "myLast'" $ do it "correctly implements last" $ checkLastDef myLast' describe "myInit" $ do it "correctly implements init" $ checkInitDef myInit describe "myInit'" $ do it "correctly implements init" $ checkInitDef myInit'
EindhovenHaskellMeetup/meetup
courses/programming-in-haskell/pih-exercises/test/Chapter02Spec.hs
mit
886
0
11
205
279
141
138
20
1
--The following iterative sequence is defined for the set of positive integers: --n → n/2 (n is even) --n → 3n + 1 (n is odd) --Using the rule above and starting with 13, we generate the following sequence: --13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 --It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. --Which starting number, under one million, produces the longest chain? --NOTE: Once the chain starts the terms are allowed to go above one million. -- Generate a list of Collatz sequences with arguments 1 to 1000000. listOfSequences = map collatzSequence [1..1000000] -- Generate a list of lengths of Collatz sequences listOfSubsetLengths = map length listOfSequences -- Zip indices starting from 1 to the list of the lengths of Collatz sequences -- Select the largest value pair and print the second value from the pair. main = print $ snd . maximum $ zip listOfSubsetLengths [1..] -- The Collatz function to generate the next term. collatz :: Integer -> Integer collatz 1 = 1 collatz n = if (odd n) then (3 * n + 1) else n `div` 2 -- Generate the entire Collatz sequence collatzSequence :: Integer -> [Integer] collatzSequence = terminate . iterate collatz where terminate (1:_) = [1] terminate (x:xs) = x:terminate xs
jongensvantechniek/Project-Euler
problem014-haskell/problem14.hs
mit
1,427
0
9
282
187
106
81
12
2
module Main where import Render.Setup import Graphics.UI.GLUT import Data.Time main :: IO () main = do (progName, _args) <- getArgsAndInitialize start <- getCurrentTime initialDisplayMode $= [ SingleBuffered, RGBMode ] initialWindowSize $= Size 512 512 initialWindowPosition $= Position 100 100 _ <- createWindow progName state <- makeState sceneImage <- createShadedImage displayCallback $= display sceneImage reshapeCallback $= Just reshape stop <- getCurrentTime putStr "Rendered in: " print $ (diffUTCTime stop start) mainLoop
dongy7/raytracer
src/Main.hs
mit
576
0
9
115
167
79
88
20
1
module Twilio.IVRSpec where import Test.Hspec import Twilio.IVR import Control.Lens import Control.Lens.Setter import Control.Monad.Coroutine import Control.Monad.Coroutine.SuspensionFunctors import Text.XML.Light -- never use for production purposes, NOT TRUE XML EQUIVALENCE instance Eq Content where x == y = (showContent x) == (showContent y) spec :: Spec spec = do describe "say" $ do it "generates data structure" $ do Left (Request res _) <- resume (say "Test Message") res `shouldBe` (Right (Say "Test Message")) it "generates XML" $ do Left (Request res _) <- resume (say "Test Message") renderTwiML res `shouldBe` (Elem $ unode "Say" "Test Message") describe "hangup" $ do it "generates data structure" $ do Left (Request res _) <- resume hangup res `shouldBe` (Right Hangup) it "generates XML" $ do Left (Request res _) <- resume hangup renderTwiML res `shouldBe` (Elem $ unode "Hangup" ()) describe "gather" $ do it "generates XML" $ do Left (Request res _) <- resume (gather "Test Message" (numDigits .~ 10)) renderTwiML res `shouldBe` (Elem $ unode "Gather" (Elem $ unode "Say" "Test Message") & add_attrs [ Attr (unqual "timeout") "5", Attr (unqual "finishOnKey") "#", Attr (unqual "numDigits") "10", Attr (unqual "method") "POST", Attr (unqual "action") "" ]) Left (Request res2 _) <- resume (gather "Test Message" ( (numDigits .~ 5) . (timeout .~ 10) . (finishOnKey .~ Nothing) )) renderTwiML res2 `shouldBe` (Elem $ unode "Gather" (Elem $ unode "Say" "Test Message") & add_attrs [ Attr (unqual "timeout") "10", Attr (unqual "finishOnKey") "", Attr (unqual "numDigits") "5", Attr (unqual "method") "POST", Attr (unqual "action") "" ])
steven777400/TwilioIVR
test/Twilio/IVRSpec.hs
mit
2,244
0
21
844
677
332
345
47
1
module Neural_Net where import System.Random import qualified System.Posix.Types as P import qualified GHC.IO.Handle.Types as T import Data.Dynamic import qualified Data.Array.Repa as R import qualified Data.Array.Repa.Eval as R import qualified Data.Array.Repa.Unsafe as R import qualified Data.Vector as V import qualified Data.Vector.Unboxed as VUN --import qualified ConvolveCPU as CV --import qualified ConvolveGPU as CV import qualified ConvolvePY as CV import qualified Data.Array.Repa.Repr.Unboxed as RU import qualified Data.Array.Repa.Algorithms.Matrix as RM import qualified Data.Array.Repa.Algorithms.Randomish as RR import qualified Configure as CF import qualified Utils as U -- Define the parameters for the two convulational layers cnvLyr1Config = ([4, 84, 84], 16, [4, 8, 8], 4, U.sol [20, 20, 16, 1]) cnvLyr2Config = ([16, 20, 20], 32, [16, 4, 4], 2, U.sol [2592, 1]) type NNEnv = ((RU.Array RU.U R.DIM4 Float, RU.Array RU.U R.DIM4 Float, RU.Array RU.U R.DIM2 Float, RU.Array RU.U R.DIM2 Float), (RU.Array RU.U R.DIM4 Float, RU.Array RU.U R.DIM4 Float, RU.Array RU.U R.DIM2 Float, RU.Array RU.U R.DIM2 Float)) initilaizeEnv :: NNEnv initilaizeEnv = -- Setup the weight and bias vector for layer 1 let (w1,b1) = let (inpImgDim, numFltrs, fltrDim, strd, _) = cnvLyr1Config -- Feature map dimensions ftrMpSd = (1 + quot (inpImgDim !! 1 - fltrDim !! 1) strd) -- number of input and output connections per neuron numInpPer = (fltrDim !! 0 * fltrDim !! 1 * fltrDim !! 2) numOutPer = (numFltrs * ftrMpSd * ftrMpSd) wBnd = sqrt (6.0 / (fromIntegral (numInpPer + numOutPer))) dummyWieghtTest = R.fromListUnboxed (U.sol $ reverse (numFltrs : fltrDim)) [0.037 | _ <- [1..numFltrs * product fltrDim]] w = dummyWieghtTest -- XXX reactivate this --w = RR.randomishDoubleArray -- (U.sol $ reverse (numFltrs : fltrDim)) -- (-wBnd) -- wBnd -- 1 b = R.fromUnboxed ((U.sol [ftrMpSd, ftrMpSd, numFltrs, 1])) (VUN.replicate (numFltrs * ftrMpSd * ftrMpSd) (0 :: Float)) in (w, b) -- Setup the weight and bias vector for layer 2 (w2,b2) = let (inpImgDim, numFltrs, fltrDim, strd, _) = cnvLyr2Config -- Feature map dimensions ftrMpSd = (1 + quot (inpImgDim !! 1 - fltrDim !! 1) strd) -- number of input and output connections per neuron numInpPer = (fltrDim !! 0 * fltrDim !! 1 * fltrDim !! 2) numOutPer = (numFltrs * ftrMpSd * ftrMpSd) wBnd = sqrt (6.0 / (fromIntegral (numInpPer + numOutPer))) dummyWieghtTest = R.fromListUnboxed (U.sol $ reverse (numFltrs : fltrDim)) [0.037 | _ <- [1..numFltrs * product fltrDim]] w = dummyWieghtTest -- XXX reactivate this --w = RR.randomishDoubleArray -- (U.sol $ reverse (numFltrs : fltrDim)) -- (-wBnd) -- wBnd -- 1 b = R.fromUnboxed ((U.sol [ftrMpSd, ftrMpSd, numFltrs, 1])) (VUN.replicate (numFltrs * ftrMpSd * ftrMpSd) (0 :: Float)) in (w, b) -- Setup the weight and bias vector for layer 3 (w3,b3) = let nIn = 32 * 9 * 9 -- Number of inputs nOut = 256 -- Number of neurons wBnd = sqrt (6.0 / (fromIntegral (nIn + nOut))) dummyWieghtTest = R.fromListUnboxed (U.sol [nOut, nIn]) [0.037 | _ <- [1..nOut * nIn]] w = dummyWieghtTest --w = RR.randomishDoubleArray ((U.sol [nOut, nIn])) (-wBnd) -- wBnd 1 b = R.fromUnboxed ((U.sol [nOut, 1])) (VUN.replicate nOut (0 :: Float)) in (w, b) -- Setup the weight and bias vector for layer 4 (w4,b4) = let nIn = 256 -- Number of inputs nOut = length CF.availActns -- Number of neurons wBnd = sqrt (6.0 / (fromIntegral (nIn + nOut))) dummyWieghtTest = R.fromListUnboxed (U.sol [nOut, nIn]) [0.037 | _ <- [1..nOut * nIn]] w = dummyWieghtTest --w = RR.randomishDoubleArray ((U.sol [nOut, nIn])) (-wBnd) -- wBnd 1 b = R.fromUnboxed ((U.sol [nOut, 1])) (VUN.replicate nOut (0 :: Float)) in (w, b) in ((w1, w2, w3, w4), (b1, b2, b3, b4)) nnBestAction :: T.Handle -> T.Handle -> V.Vector (VUN.Vector Float) -> NNEnv -> IO (Char) nnBestAction toC fromC screens nnEnv = do -- Link the layers and give output let ((w1, w2, w3, w4), (b1, b2, b3, b4)) = nnEnv if V.length screens < 4 then return '0' else do actnProb <- evalActnProb toC fromC nnEnv (getLastState screens) -- Get the most probable action return (CF.availActns !! (VUN.maxIndex actnProb)) --evalActnProb -- :: (Monad m) -- => NNEnv -- -> RU.Array R.D R.DIM4 Float -- -> m(VUN.Vector Float) evalActnProb toC fromC nnEnv input = do -- Link the layers and give output let ((w1, w2, w3, w4), (b1, b2, b3, b4)) = nnEnv out1 <- cnvLyr toC fromC cnvLyr1Config input w1 b1 out2 <- cnvLyr toC fromC cnvLyr2Config out1 w2 b2 out3 <- cnctdLyr3 out2 w3 b3 actnProb <- outptLyr4 out3 w4 b4 return actnProb trainHelper :: T.Handle -> T.Handle -> IO (NNEnv) -> (RU.Array R.D R.DIM4 Float, Char, Integer, RU.Array R.D R.DIM4 Float) -> IO (NNEnv) trainHelper toC fromC nnEnv transition = do let (pre, act, reward, post) = transition nnEnvUnwraped <- nnEnv -- Train the nn on transition here preProb <- evalActnProb toC fromC nnEnvUnwraped pre postProb <- evalActnProb toC fromC nnEnvUnwraped post return nnEnvUnwraped nnTrain :: T.Handle -> T.Handle -> V.Vector (VUN.Vector Float) -> V.Vector Char -> V.Vector Integer -> NNEnv -> IO NNEnv nnTrain toC fromC screens actions rewards nnEnv = do let ((w1, w2, w3, w4), (b1, b2, b3, b4)) = nnEnv lMem = V.length screens g <- newStdGen if V.length screens < 4 then do return nnEnv else do -- Pick n random states from memory and train on them let numMiniBatches = 32 indices = take numMiniBatches (randomRs (0, lMem - 2) g :: [Int]) getTransition i = ((getState screens i), actions V.! i, rewards V.! i, (getState screens (i + 1))) transitions = map getTransition indices putStrLn ("Training on state indices: " ++ show indices) -- Our fold helper that accumulates on nnEnv nnNew <- (foldl (trainHelper toC fromC) (return nnEnv) transitions) return nnNew getState screens n = -- Consturct the indices of the 4 frames and extract them from mem let indices = map (max 0) [n - 3..n] screenState = map (screens V.!) indices as1DVector = foldl (VUN.++) (head screenState) (tail screenState) asTensor = R.delay (R.fromUnboxed ((U.sol [84, 84, 4, 1]) :: R.DIM4) as1DVector) in asTensor getLastState screens = let last4 = V.take 4 screens as1DVector = V.foldl (VUN.++) (V.head last4) (V.tail last4) asTensor = R.delay (R.fromUnboxed (U.sol [84, 84, 4, 1]) as1DVector) in asTensor --cnvLyr -- :: (Monad m, R.Shape sh1, R.Shape sh2) -- => ([Int], Int, [Int], Int, sh1) -- -> RU.Array R.D R.DIM4 Float -- -> RU.Array R.U R.DIM4 Float -- -> RU.Array R.U R.DIM4 Float -- -> m(sh2) cnvLyr toC fromC lyrConfig input w b = do let (_, _, _, strd, outPShape) = lyrConfig convOutpt <- (CV.conv4D toC fromC input (R.delay w) strd) let thresh = (0.0 :: Float) actvtn = (R.+^) convOutpt b abvThresh = R.map (\e -> if e > thresh then (e - thresh) else 0) actvtn outP = R.reshape outPShape abvThresh return outP --cnctdLyr3 -- :: (Monad m) -- => RU.Array R.D R.DIM2 Float -- -> RU.Array R.U R.DIM2 Float -- -> RU.Array R.U R.DIM2 Float -- -> m(RU.Array R.D R.DIM2 Float) cnctdLyr3 input w b = do -- input has extent 1, 32 * 9 * 9 inputC <- R.computeUnboxedP input prodIW <- mmultP inputC w let actvtn = (R.+^) prodIW b abvThresh = R.map (\e -> if e > 0.0 then (e - 0.0) else 0) actvtn outP = abvThresh -- outP has extent 256 return outP --outptLyr4 -- :: (Monad m) -- => RU.Array R.D R.DIM2 Float -- -> RU.Array R.U R.DIM2 Float -- -> RU.Array R.U R.DIM2 Float -- -> m(VUN.Vector Float) outptLyr4 input w b = do -- input has extent 256 inputC <- R.computeUnboxedP input prodIW <- mmultP inputC w let actvtn = (R.+^) prodIW b outP = VUN.fromList (R.toList actvtn) -- outP has extent (length availActns) return outP mmultP :: Monad m => R.Array RU.U R.DIM2 Float -> R.Array RU.U R.DIM2 Float -> m (R.Array RU.U R.DIM2 Float) mmultP arr brr = [arr, brr] `R.deepSeqArrays` do trr <- transpose2P brr let (R.Z R.:. h1 R.:. _) = R.extent arr let (R.Z R.:. _ R.:. w2) = R.extent brr R.computeP $ R.fromFunction (R.Z R.:. h1 R.:. w2) $ \ix -> R.sumAllS $ R.zipWith (*) (R.unsafeSlice arr (R.Any R.:. (RM.row ix) R.:. R.All)) (R.unsafeSlice trr (R.Any R.:. (RM.col ix) R.:. R.All)) transpose2P :: Monad m => R.Array RU.U R.DIM2 Float -> m (R.Array RU.U R.DIM2 Float) transpose2P arr = arr `R.deepSeqArray` do R.computeUnboxedP $ R.unsafeBackpermute new_extent swap arr where swap (R.Z R.:. i R.:. j) = R.Z R.:. j R.:. i new_extent = swap (R.extent arr)
hamsal/DM-AtariAI
src/Neural_Net.hs
mit
11,066
0
19
4,186
3,134
1,708
1,426
189
2
{- Reasonably fast enumerations for combinations, `recombinations', and permutations. 2009 Nathan Blythe, Dr. Oscar Boykin (see LICENSE for details) A combination is a length m subset of {0 .. n - 1}. A `recombination' is a length m submultiset of {0 .. n - 1}. A permutation is a length m ordered subset of {0 .. n - 1}. General notes: - The num* functions determine how many of that particular object can be constructed. - The nat2* functions construct the unique * corresponding to the natural number provided. - The *2nat functions construct the unique natural number corresponding to the * provided. - select constructs a sublist of a provided list using indices from another provided list. - nat2* is slow, but next* is fast. make* uses nat2* and next* to construct sequences of *s. - Unfortunately there is no nextPerm or makePerm (yet!). For the time being, use Perms.hs when a large series of permutations is needed. -} module Combinadics (numCombs, comb2nat, nat2comb, nextComb, makeCombs, numRecombs, recomb2nat, nat2recomb, nextRecomb, makeRecombs, numPerms, perm2nat, nat2perm, select) where import Data.List import Data.Maybe {- A handy factorial function (memoized). -} facs :: [Integer] facs = scanl (*) 1 [1..] fac :: Integer -> Integer fac n = genericIndex facs n {- A handy n-choose-k function. -} nchoosek :: Integer -> Integer -> Integer nchoosek n k | k > n = 0 | k == n = 1 | otherwise = div (fac n) ((fac (n - k)) * (fac k)) {- Infix notation for n-choose-k. -} (#) :: Integer -> Integer -> Integer (#) n k = nchoosek n k {- Infix notation for n-choose-k (with repetition/replacement). -} (&) :: Integer -> Integer -> Integer (&) n k = nchoosek (n + k - 1) k {- Number of length m combinations in n variables. -} numCombs :: Integer -> Integer -> Integer numCombs n m = n # m {- Natural number corresponding to a combination r in n variables. -} comb2nat :: Integer -> [Integer] -> Integer comb2nat n r = f (m - 1) r where m = toInteger $ length r f 0 _ = (n # m) - ((n - (head r)) # m) f j (h1 : h2 : t) = ((n - h1 - 1) # j) - ((n - h2) # j) + f (j - 1) (h2 : t) {- Length m combination in n variables corresponding to a natural number x. -} nat2comb :: Integer -> Integer -> Integer -> [Integer] nat2comb n m x = f (-1) m x where f _ 1 i = [i] f p d i = j : f j (d - 1) (i' j) where i' v = i - (n # d) + ((n - v) # d) + (n # (d - 1)) - ((n - v - 1) # (d - 1)) g v = ((i' v) >= 0) && ((i' v) < (n#(d-1))) && (v > p) j = head $ filter g [0 .. n - 1] {- Next combination in n variables. -} nextComb :: Integer -> [Integer] -> [Integer] nextComb n x = snd $ f n x where f k (h : []) = (h == k - 1, (h + 1) : [] ) f k (h : t) = (h' == k - (toInteger $ length t), h' : g h' r) where h' = if c then h + 1 else h (c, r) = f k t g v [] = [] g v (lH : lT) = if lH == k - (toInteger $ length lT) then (v + 1) : (g (v + 1) lT) else lH : lT {- Length m combinations x through x + c - 1 (c combinations starting with x) in n variables. -} makeCombs :: Integer -> Integer -> Integer -> Integer -> [[Integer]] makeCombs n m x c = genericTake c $ iterate (nextComb n) f where f = nat2comb n m x {- Number of length m recombinations in n variables. -} numRecombs :: Integer -> Integer -> Integer numRecombs n m = n & m {- Natural number corresponding to a recombination r in n variables. -} recomb2nat :: Integer -> [Integer] -> Integer recomb2nat n r = f (m - 1) r where m = toInteger $ length r f 0 _ = (n & m) - ((n - (head r)) & m) f j (h1 : h2 : t) = ((n - h1) & j) - ((n - h2) & j) + f (j - 1) (h2 : t) {- Length m recombination in n variables corresponding to a natural number x. -} nat2recomb :: Integer -> Integer -> Integer -> [Integer] nat2recomb n m x = f 0 m x where f _ 1 i = [i] f p d i = j : f j (d - 1) (i' j) where i' v = i - (n & d) + ((n - v) & d) + (n & (d - 1)) - ((n - v) & (d - 1)) g v = ((i' v) >= 0) && ((i' v) < (n&(d-1))) && (v >= p) j = head $ filter g [0 .. n - 1] {- Next recombination in n variables. -} nextRecomb :: Integer -> [Integer] -> [Integer] nextRecomb n x = snd $ f n x where f k (h : []) = (h == k - 1, (h + 1) : []) f k (h : t) = (h' == k, h' : g h' r) where h' = if c then h + 1 else h (c, r) = f k t g v [] = [] g v (lH : lT) = if lH == k then v : (g v lT) else lH : lT {- Length m recombinations x through x + c - 1 (c recombinations starting with x) in n variables. -} makeRecombs :: Integer -> Integer -> Integer -> Integer -> [[Integer]] makeRecombs n m x c = genericTake c $ iterate (nextRecomb n) f where f = nat2recomb n m x {- Number of length m permutations. -} numPerms :: Integer -> Integer numPerms m = fac m {- Natural number corresponding to a factoradic f. -} fact2nat :: [Integer] -> Integer fact2nat [] = 0 fact2nat (h : t) = h * (fac . toInteger $ length t) + (fact2nat t) {- Length m factoradic corresponding to a natural number x. -} nat2fact :: Integer -> Integer -> [Integer] nat2fact 0 _ = [] nat2fact m x = (div x (fac (m - 1))) : nat2fact (m - 1) (mod x (fac (m - 1))) {- Natural number corresponding to a permutation p. -} perm2nat :: [Integer] -> Integer perm2nat [] = 0 perm2nat p = fact2nat $ f' [0 .. (toInteger $ length p) - 1] p where f' _ [] = [] f' l (h : t) = h' : f' l' t where h' = (toInteger . fromJust) (findIndex (== h) l) l' = delete h l {- Length m permutation corresponding to a natural number x. -} nat2perm :: Integer -> Integer -> [Integer] nat2perm m x = f' [0 .. m - 1] (nat2fact m x) where f' _ [] = [] f' l (h : t) = h' : f' l' t where h' = genericIndex l h l' = delete h' l {- Select elements from a list x based on indices in s. -} select :: [a] -> [Integer] -> [a] select x s = map (genericIndex x) s {- Test functions for combinations, recombinations, and permutations.. Should return a list of `True's. Use `and' to test for failure. Note: these functions are not a good test of the speed of generation and do not test next*. -} testCombs :: Integer -> Integer -> [Bool] testCombs n m = map (\ (a, b) -> a == b) $ zip xs x's where xs = [0 .. (numCombs n m) - 1] cs = map (nat2comb n m) xs x's = map (comb2nat n) cs testRecombs :: Integer -> Integer -> [Bool] testRecombs n m = map (\ (a, b) -> a == b) $ zip xs x's where xs = [0 .. (numRecombs n m) - 1] rs = map (nat2recomb n m) xs x's = map (recomb2nat n) rs testPerms :: Integer -> [Bool] testPerms m = map (\ (a, b) -> a == b) $ zip xs x's where xs = [0 .. (numPerms m) - 1] ps = map (nat2perm m) xs x's = map (perm2nat) ps
nblythe/MUB-Search
Combinadics.hs
mit
9,472
0
16
4,528
2,651
1,418
1,233
134
5
module Main where import qualified LexArithm_C import qualified LexArithm_JVM import qualified ParArithm_C import qualified ParArithm_JVM import qualified PrintArithm_C import qualified PrintArithm_JVM import AbsArithm import ErrM import System ( getArgs ) main :: IO () main = do i:o:f:_ <- getArgs s <- readFile f case parse i s of Ok t -> putStrLn $ prin o t Bad s -> error s parse i = case i of "C" -> ParArithm_C.pExp . ParArithm_C.myLexer "JVM" -> ParArithm_JVM.pExp . ParArithm_JVM.myLexer prin o = case o of "C" -> PrintArithm_C.printTree "JVM" -> PrintArithm_JVM.printTree
MetaBorgCube/metaborg-lbnf
metaborg-lbnf/examples/multi/TestArithm.hs
gpl-2.0
610
0
11
118
196
103
93
23
2
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Pane.PackageEditor -- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GNU-GPL -- -- Maintainer : Juergen Nicklisch-Franken <[email protected]> -- Stability : provisional -- Portability : portable -- -- | Module for editing of cabal packages and build infos -- ----------------------------------------------------------------------------------- module IDE.Pane.PackageEditor ( packageNew' , packageClone , packageEdit , packageEditText , choosePackageDir , choosePackageFile , hasConfigs , standardSetup ) where import Graphics.UI.Gtk import Distribution.Package import Distribution.PackageDescription import Distribution.Verbosity import System.FilePath import Data.Maybe import System.Directory import IDE.Core.State import IDE.Utils.FileUtils import Graphics.UI.Editor.MakeEditor import Distribution.PackageDescription.Parse (readPackageDescription) import Distribution.PackageDescription.Configuration (flattenPackageDescription) import Distribution.ModuleName(ModuleName) import Data.Typeable (Typeable(..)) import Graphics.UI.Editor.Composite (versionEditor, versionRangeEditor, dependenciesEditor, textsEditor, filesEditor, tupel3Editor, eitherOrEditor, maybeEditor, pairEditor, ColumnDescr(..), multisetEditor) import Distribution.Text (simpleParse, display) import Graphics.UI.Editor.Parameters (paraInnerPadding, paraInnerAlignment, paraOuterPadding, paraOuterAlignment, Parameter(..), paraPack, Direction(..), paraDirection, paraMinSize, paraShadow, paraSynopsis, (<<<-), emptyParams, paraName, getParameterPrim) import Graphics.UI.Editor.Simple (stringEditor, comboEntryEditor, staticListMultiEditor, intEditor, boolEditor, fileEditor, comboSelectionEditor, multilineStringEditor, textEditor) import Graphics.UI.Editor.Basics (Notifier, Editor(..), GUIEventSelector(..), GUIEvent(..)) import Distribution.Compiler (CompilerFlavor(..)) import Distribution.Simple (knownExtensions, Extension(..), VersionRange, anyVersion) import Default (Default(..)) import IDE.Utils.GUIUtils import IDE.Pane.SourceBuffer (fileOpenThis) import Control.Event (EventSource(..)) import qualified Graphics.UI.Gtk.Gdk.Events as GTK (Event(..)) import Data.List (isPrefixOf, sort, nub, sortBy) import Data.Text (Text) import Control.Monad.Trans.Reader (ask) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Trans.Class (lift) import Control.Monad (void, when) import Distribution.PackageDescription.PrettyPrint (writeGenericPackageDescription) import Distribution.Version (Version(..), orLaterVersion) import Control.Applicative ((<*>), (<$>)) import IDE.Utils.Tool (ToolOutput(..)) import System.Exit (ExitCode(..)) import qualified Data.Conduit.List as CL (fold) import qualified Data.Conduit as C (Sink, ZipSink(..), getZipSink) import IDE.Utils.ExternalTool (runExternalTool') import qualified System.IO.Strict as S (readFile) import Data.Char (toLower) import qualified Data.Text as T (replace, span, splitAt, isPrefixOf, length, toLower, lines, unlines, pack, unpack, null) import Data.Monoid ((<>)) import qualified Data.Text.IO as T (writeFile, readFile) import qualified Text.Printf as S (printf) import Text.Printf (PrintfType) import MyMissing (forceJust) import Language.Haskell.Extension (Language(..)) import Distribution.License (License(..)) import Control.Exception (SomeException(..)) import IDE.Metainfo.Provider (getAllPackageIds) printf :: PrintfType r => Text -> r printf = S.printf . T.unpack -- | Get the last item sinkLast = CL.fold (\_ a -> Just a) Nothing -------------------------------------------------------------------------- -- Handling of Generic Package Descriptions toGenericPackageDescription :: PackageDescription -> GenericPackageDescription toGenericPackageDescription pd = GenericPackageDescription { packageDescription = pd{ library = Nothing, executables = [], testSuites = [], benchmarks = [], buildDepends = []}, genPackageFlags = [], condLibrary = case library pd of Nothing -> Nothing Just lib -> Just (buildCondTreeLibrary lib), condExecutables = map buildCondTreeExe (executables pd), condTestSuites = map buildCondTreeTest (testSuites pd), condBenchmarks = map buildCondTreeBenchmark (benchmarks pd)} where buildCondTreeLibrary lib = CondNode { condTreeData = lib { libBuildInfo = (libBuildInfo lib) { targetBuildDepends = buildDepends pd } }, condTreeConstraints = buildDepends pd, condTreeComponents = []} buildCondTreeExe exe = (exeName exe, CondNode { condTreeData = exe { buildInfo = (buildInfo exe) { targetBuildDepends = buildDepends pd } }, condTreeConstraints = buildDepends pd, condTreeComponents = []}) buildCondTreeTest test = (testName test, CondNode { condTreeData = test { testBuildInfo = (testBuildInfo test) { targetBuildDepends = buildDepends pd } }, condTreeConstraints = buildDepends pd, condTreeComponents = []}) buildCondTreeBenchmark bm = (benchmarkName bm, CondNode { condTreeData = bm { benchmarkBuildInfo = (benchmarkBuildInfo bm) { targetBuildDepends = buildDepends pd } }, condTreeConstraints = buildDepends pd, condTreeComponents = []}) -- --------------------------------------------------------------------- -- The exported stuff goes here -- choosePackageDir :: Window -> Maybe FilePath -> IO (Maybe FilePath) choosePackageDir window = chooseDir window (__ "Select root folder for package") choosePackageFile :: Window -> Maybe FilePath -> IO (Maybe FilePath) choosePackageFile window mbfp = chooseFile window (__ "Select cabal package file (.cabal)") mbfp [("Cabal Package Files", ["*.cabal"])] packageEdit :: PackageAction packageEdit = do idePackage <- ask let dirName = ipdPackageDir idePackage modules <- liftIO $ allModules dirName package <- liftIO $ readPackageDescription normal (ipdCabalFile idePackage) if hasConfigs package then do liftIDE $ ideMessage High (__ "Cabal file with configurations can't be edited with the current version of the editor") liftIDE $ fileOpenThis $ ipdCabalFile idePackage return () else do let flat = flattenPackageDescription package if hasUnknownTestTypes flat || hasUnknownBenchmarkTypes flat then do liftIDE $ ideMessage High (__ "Cabal file with tests or benchmarks of this type can't be edited with the current version of the editor") liftIDE $ fileOpenThis $ ipdCabalFile idePackage return () else do liftIDE $ editPackage flat dirName modules (\ _ -> return ()) return () packageEditText :: PackageAction packageEditText = do idePackage <- ask liftIDE $ fileOpenThis $ ipdCabalFile idePackage return () hasConfigs :: GenericPackageDescription -> Bool hasConfigs gpd = let libConds = case condLibrary gpd of Nothing -> False Just condTree -> not (null (condTreeComponents condTree)) exeConds = foldr (\ (_,condTree) hasConfigs -> (hasConfigs || not (null (condTreeComponents condTree)))) False (condExecutables gpd) testConds = foldr (\ (_,condTree) hasConfigs -> (hasConfigs || not (null (condTreeComponents condTree)))) False (condTestSuites gpd) in libConds || exeConds || testConds hasUnknownTestTypes :: PackageDescription -> Bool hasUnknownTestTypes pd = any unknown $ testSuites pd where unknown (TestSuite _ (TestSuiteExeV10 _ _) _ _) = False unknown _ = True hasUnknownBenchmarkTypes :: PackageDescription -> Bool hasUnknownBenchmarkTypes pd = any unknown $ benchmarks pd where unknown (Benchmark _ (BenchmarkExeV10 _ _) _ _) = False unknown _ = True data NewPackage = NewPackage { newPackageName :: Text, newPackageParentDir :: FilePath, templatePackage :: Maybe Text} packageFields :: FilePath -> FieldDescription NewPackage packageFields workspaceDir = VFD emptyParams [ mkField (paraName <<<- ParaName (__ "New package name") $ emptyParams) newPackageName (\ a b -> b{newPackageName = a}) (textEditor (const True) True), mkField (paraName <<<- ParaName (__ "Parent directory") $ paraMinSize <<<- ParaMinSize (-1, 120) $ emptyParams) newPackageParentDir (\ a b -> b{newPackageParentDir = a}) (fileEditor (Just workspaceDir) FileChooserActionSelectFolder "Select"), mkField (paraName <<<- ParaName (__ "Copy existing package") $ emptyParams) templatePackage (\ a b -> b{templatePackage = a}) (maybeEditor (comboEntryEditor examplePackages, emptyParams) True "")] examplePackages = [ "hello" , "gtk2hs-hello" , "ghcjs-dom-hello" , "jsaddle-hello"] newPackageDialog :: Window -> FilePath -> IO (Maybe NewPackage) newPackageDialog parent workspaceDir = do dia <- dialogNew set dia [ windowTransientFor := parent , windowTitle := __ "Create New Package" ] upper <- dialogGetContentArea dia lower <- dialogGetActionArea dia (widget,inj,ext,_) <- buildEditor (packageFields workspaceDir) (NewPackage "" workspaceDir Nothing) okButton <- dialogAddButton dia (__"Create Package") ResponseOk dialogAddButton dia (__"Cancel") ResponseCancel boxPackStart (castToBox upper) widget PackGrow 7 set okButton [widgetCanDefault := True] widgetGrabDefault okButton widgetShowAll dia resp <- dialogRun dia value <- ext (NewPackage "" workspaceDir Nothing) widgetDestroy dia --find case resp of ResponseOk -> return value _ -> return Nothing packageNew' :: FilePath -> C.Sink ToolOutput IDEM () -> (Bool -> FilePath -> IDEAction) -> IDEAction packageNew' workspaceDir log activateAction = do windows <- getWindows mbNewPackage <- liftIO $ newPackageDialog (head windows) workspaceDir case mbNewPackage of Nothing -> return () Just NewPackage{..} | isNothing templatePackage -> do let dirName = newPackageParentDir </> T.unpack newPackageName mbCabalFile <- liftIO $ cabalFileName dirName window <- getMainWindow case mbCabalFile of Just cfn -> do add <- liftIO $ do md <- messageDialogNew (Just window) [] MessageQuestion ButtonsCancel (T.pack $ printf (__ "There is already file %s in this directory. Would you like to add this package to the workspace?") (takeFileName cfn)) dialogAddButton md (__ "_Add Package") (ResponseUser 1) dialogSetDefaultResponse md (ResponseUser 1) set md [ windowWindowPosition := WinPosCenterOnParent ] rid <- dialogRun md widgetDestroy md return $ rid == ResponseUser 1 when add $ activateAction False cfn Nothing -> do liftIO $ createDirectoryIfMissing True dirName isEmptyDir <- liftIO $ isEmptyDirectory dirName make <- if isEmptyDir then return True else liftIO $ do md <- messageDialogNew (Just window) [] MessageQuestion ButtonsCancel (T.pack $ printf (__ "The path you have choosen %s is not an empty directory. Are you sure you want to make a new package here?") dirName) dialogAddButton md (__ "_Make Package Here") (ResponseUser 1) dialogSetDefaultResponse md (ResponseUser 1) set md [ windowWindowPosition := WinPosCenterOnParent ] rid <- dialogRun md widgetDestroy md return $ rid == ResponseUser 1 when make $ do modules <- liftIO $ allModules dirName let Just initialVersion = simpleParse "0.0.1" editPackage emptyPackageDescription { package = PackageIdentifier (PackageName $ T.unpack newPackageName) initialVersion , buildType = Just Simple , specVersionRaw = Right (orLaterVersion (Version [1,12] [])) , license = AllRightsReserved , buildDepends = [ Dependency (PackageName "base") anyVersion , Dependency (PackageName "QuickCheck") anyVersion , Dependency (PackageName "doctest") anyVersion] , executables = [emptyExecutable { exeName = T.unpack newPackageName , modulePath = "Main.hs" , buildInfo = emptyBuildInfo { hsSourceDirs = ["src"] , targetBuildDepends = [Dependency (PackageName "base") anyVersion] , options = [(GHC, ["-ferror-spans"])] , defaultLanguage = Just Haskell2010}}] , testSuites = [emptyTestSuite { testName = "test-" ++ T.unpack newPackageName , testInterface = TestSuiteExeV10 (Version [1,0] []) "Main.hs" , testBuildInfo = emptyBuildInfo { hsSourceDirs = ["test"] , targetBuildDepends = [ Dependency (PackageName "base") anyVersion , Dependency (PackageName "QuickCheck") anyVersion , Dependency (PackageName "doctest") anyVersion] , options = [(GHC, ["-ferror-spans"])] , defaultLanguage = Just Haskell2010}}] , benchmarks = [] } dirName modules (activateAction True) return () Just NewPackage{..} -> cabalUnpack newPackageParentDir (fromJust templatePackage) False (Just newPackageName) log (activateAction False) standardSetup :: Text standardSetup = "#!/usr/bin/runhaskell \n" <> "> module Main where\n" <> "> import Distribution.Simple\n" <> "> main :: IO ()\n" <> "> main = defaultMain\n\n" data ClonePackageSourceRepo = ClonePackageSourceRepo { packageToClone :: Text, cloneParentDir :: FilePath} cloneFields :: [PackageId] -> FilePath -> FieldDescription ClonePackageSourceRepo cloneFields packages workspaceDir = VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Existing package to copy source repository") $ emptyParams) packageToClone (\ a b -> b{packageToClone = a}) (comboEntryEditor ((sort . nub) (map (T.pack . display . pkgName) packages))), mkField (paraName <<<- ParaName (__ "Parent directory") $ paraMinSize <<<- ParaMinSize (-1, 120) $ emptyParams) cloneParentDir (\ a b -> b{cloneParentDir = a}) (fileEditor (Just workspaceDir) FileChooserActionSelectFolder "Select")] clonePackageSourceDialog :: Window -> FilePath -> IDEM (Maybe ClonePackageSourceRepo) clonePackageSourceDialog parent workspaceDir = do packages <- getAllPackageIds liftIO $ do dia <- dialogNew set dia [ windowTransientFor := parent , windowTitle := __ "Copy Installed Package" ] upper <- dialogGetContentArea dia lower <- dialogGetActionArea dia (widget,inj,ext,_) <- buildEditor (cloneFields packages workspaceDir) (ClonePackageSourceRepo "" workspaceDir) okButton <- dialogAddButton dia (__"Copy Package") ResponseOk dialogAddButton dia (__"Cancel") ResponseCancel boxPackStart (castToBox upper) widget PackGrow 7 set okButton [widgetCanDefault := True] widgetGrabDefault okButton widgetShowAll dia resp <- dialogRun dia value <- ext (ClonePackageSourceRepo "" workspaceDir) widgetDestroy dia --find case resp of ResponseOk -> return value _ -> return Nothing packageClone :: FilePath -> C.Sink ToolOutput IDEM () -> (FilePath -> IDEAction) -> IDEAction packageClone workspaceDir log activateAction = flip catchIDE (\(e :: SomeException) -> print e) $ do windows <- getWindows mbResult <- clonePackageSourceDialog (head windows) workspaceDir case mbResult of Nothing -> return () Just ClonePackageSourceRepo{..} -> cabalUnpack cloneParentDir packageToClone True Nothing log activateAction cabalUnpack :: FilePath -> Text -> Bool -> Maybe Text -> C.Sink ToolOutput IDEM () -> (FilePath -> IDEAction) -> IDEAction cabalUnpack parentDir packageToUnpack sourceRepo mbNewName log activateAction = do let tempDir = parentDir </> (T.unpack packageToUnpack ++ ".leksah.temp") liftIO $ do oldDirExists <- doesDirectoryExist tempDir when oldDirExists $ removeDirectoryRecursive tempDir createDirectory tempDir runExternalTool' (__ "Unpacking") "cabal" (["unpack"] ++ ["--source-repository" | sourceRepo] ++ ["--destdir=" <> T.pack tempDir, packageToUnpack]) tempDir $ do mbLastOutput <- C.getZipSink $ const <$> C.ZipSink sinkLast <*> C.ZipSink log case mbLastOutput of Just (ToolExit ExitSuccess) -> do contents <- liftIO $ getDirectoryContents tempDir case filter (not . isPrefixOf ".") contents of [] -> do liftIO $ removeDirectoryRecursive tempDir lift $ ideMessage High $ "Nothing found in " <> T.pack tempDir <> " after doing a cabal unpack." [repoName] -> do let destDir = parentDir </> fromMaybe repoName (T.unpack <$> mbNewName) exists <- liftIO $ (||) <$> doesDirectoryExist destDir <*> doesFileExist destDir if exists then lift $ ideMessage High $ T.pack destDir <> " already exists" else do liftIO $ renameDirectory (tempDir </> repoName) destDir mbCabalFile <- liftIO $ cabalFileName destDir window <- lift getMainWindow lift $ case (mbCabalFile, mbNewName) of (Just cfn, Just newName) -> do let newCfn = takeDirectory cfn </> T.unpack newName ++ ".cabal" when (cfn /= newCfn) . liftIO $ do s <- T.readFile cfn T.writeFile newCfn $ renameCabalFile (T.pack $ takeBaseName cfn) newName s removeFile cfn activateAction newCfn (Just cfn, _) -> activateAction cfn _ -> ideMessage High $ "Unpacked source reposity to " <> T.pack destDir <> " but it does not contain a .cabal file in the root directory." liftIO $ removeDirectoryRecursive tempDir _ -> do liftIO $ removeDirectoryRecursive tempDir lift $ ideMessage High $ "More than one subdirectory found in " <> T.pack tempDir <> " after doing a cabal unpack." _ -> do liftIO $ removeDirectoryRecursive tempDir lift $ ideMessage High $ "Failed to unpack source reposity to " <> T.pack tempDir renameCabalFile :: Text -> Text -> Text -> Text renameCabalFile oldName newName = T.unlines . map renameLine . T.lines where prefixes = ["name:", "executable ", "test-suite "] prefixesWithLength :: [(Text, Int)] prefixesWithLength = zip prefixes $ map T.length prefixes renameLine :: Text -> Text renameLine line = case mapMaybe (rename (line, T.toLower line)) prefixesWithLength of l:_ -> l [] -> line rename :: (Text, Text) -> (Text, Int) -> Maybe Text rename (line, lcLine) (lcPrefix, pLen) | lcPrefix `T.isPrefixOf` lcLine = let (prefix, rest) = T.splitAt pLen line (spaces, value) = T.span (==' ') rest in Just $ prefix <> spaces <> T.replace oldName newName value rename _ _ = Nothing -- --------------------------------------------------------------------- -- | We do some twist for handling build infos seperately to edit them in one editor together -- with the other stuff. This type show what we really edit here -- data PackageDescriptionEd = PDE { pd :: PackageDescription, exes :: [Executable'], tests :: [Test'], bms :: [Benchmark'], mbLib :: Maybe Library', bis :: [BuildInfo]} deriving Eq comparePDE a b = do when (pd a /= pd b) $ putStrLn "pd" when (exes a /= exes b) $ putStrLn "exes" when (tests a /= tests b) $ putStrLn "tests" when (mbLib a /= mbLib b) $ putStrLn "mbLib" when (bis a /= bis b) $ putStrLn "bis" fromEditor :: PackageDescriptionEd -> PackageDescription fromEditor (PDE pd exes' tests' benchmarks' mbLib' buildInfos) = let exes = map (\ (Executable' s fb bii) -> if bii + 1 > length buildInfos then Executable (T.unpack s) fb (buildInfos !! (length buildInfos - 1)) else Executable (T.unpack s) fb (buildInfos !! bii)) exes' tests = map (\ (Test' s fb bii) -> if bii + 1 > length buildInfos then TestSuite (T.unpack s) fb (buildInfos !! (length buildInfos - 1)) False else TestSuite (T.unpack s) fb (buildInfos !! bii) False) tests' bms = map (\ (Benchmark' s fb bii) -> if bii + 1 > length buildInfos then Benchmark (T.unpack s) fb (buildInfos !! (length buildInfos - 1)) False else Benchmark (T.unpack s) fb (buildInfos !! bii) False) benchmarks' mbLib = case mbLib' of Nothing -> Nothing #if MIN_VERSION_Cabal(1,22,0) Just (Library' mn rmn rs es b bii) -> if bii + 1 > length buildInfos then Just (Library mn rmn rs es b (buildInfos !! (length buildInfos - 1))) else Just (Library mn rmn rs es b (buildInfos !! bii)) #else Just (Library' mn b bii) -> if bii + 1 > length buildInfos then Just (Library mn b (buildInfos !! (length buildInfos - 1))) else Just (Library mn b (buildInfos !! bii)) #endif in pd { library = mbLib , executables = exes , testSuites = tests , benchmarks = bms } toEditor :: PackageDescription -> PackageDescriptionEd toEditor pd = let (exes,exeBis) = unzip $ map (\(Executable s fb bi, i) -> (Executable' (T.pack s) fb i, bi)) (zip (executables pd) [0..]) (tests,testBis) = unzip $ map (\(TestSuite s fb bi _, i) -> (Test' (T.pack s) fb i, bi)) (zip (testSuites pd) [length exeBis..]) (bms,benchmarkBis) = unzip $ map (\(Benchmark s fb bi _, i) -> (Benchmark' (T.pack s) fb i, bi)) (zip (benchmarks pd) [length testBis..]) bis = exeBis ++ testBis ++ benchmarkBis (mbLib,bis2) = case library pd of Nothing -> (Nothing,bis) #if MIN_VERSION_Cabal(1,22,0) Just (Library mn rmn rs es b bi) -> (Just (Library' (sort mn) rmn rs es b (length bis)), bis ++ [bi]) #else Just (Library mn b bi) -> (Just (Library' (sort mn) b (length bis)), bis ++ [bi]) #endif bis3 = if null bis2 then [emptyBuildInfo] else bis2 in PDE (pd {library = Nothing , executables = []}) exes tests bms mbLib bis3 -- --------------------------------------------------------------------- -- The pane stuff -- data PackagePane = PackagePane { packageBox :: VBox, packageNotifer :: Notifier } deriving Typeable data PackageState = PackageState deriving (Read, Show, Typeable) instance Pane PackagePane IDEM where primPaneName _ = __ "Package" getAddedIndex _ = 0 getTopWidget = castToWidget . packageBox paneId b = "*Package" instance RecoverablePane PackagePane PackageState IDEM where saveState p = return Nothing recoverState pp st = return Nothing buildPane panePath notebook builder = return Nothing builder pp nb w = return (Nothing,[]) editPackage :: PackageDescription -> FilePath -> [ModuleName] -> (FilePath -> IDEAction) -> IDEAction editPackage packageD packagePath modules afterSaveAction = do mbPane :: Maybe PackagePane <- getPane case mbPane of Nothing -> do pp <- getBestPathForId "*Package" nb <- getNotebook pp packageInfos <- getAllPackageIds let packageEd = toEditor packageD initPackage packagePath packageEd (packageDD packageInfos (takeDirectory packagePath) modules (length (bis packageEd)) (concatMap (buildInfoD (Just (takeDirectory packagePath)) modules) [0..length (bis packageEd) - 1])) pp nb modules afterSaveAction packageEd Just p -> liftIO $ bringPaneToFront p initPackage :: FilePath -> PackageDescriptionEd -> FieldDescription PackageDescriptionEd -> PanePath -> Notebook -> [ModuleName] -> (FilePath -> IDEAction) -> PackageDescriptionEd -> IDEM () initPackage packageDir packageD packageDescr panePath nb modules afterSaveAction origPackageD = do let fields = flattenFieldDescription packageDescr let initialPackagePath = packageDir </> (display . pkgName . package . pd) packageD ++ ".cabal" packageInfos <- getAllPackageIds mbP <- buildThisPane panePath nb (builder' packageDir packageD packageDescr afterSaveAction initialPackagePath modules packageInfos fields origPackageD) case mbP of Nothing -> return () Just (PackagePane{packageNotifer = pn}) -> do liftIO $ triggerEvent pn GUIEvent{selector = MayHaveChanged, eventText = "", gtkReturn = True} return () builder' :: FilePath -> PackageDescriptionEd -> FieldDescription PackageDescriptionEd -> (FilePath -> IDEAction) -> FilePath -> [ModuleName] -> [PackageId] -> [FieldDescription PackageDescriptionEd] -> PackageDescriptionEd -> PanePath -> Notebook -> Window -> IDEM (Maybe PackagePane,Connections) builder' packageDir packageD packageDescr afterSaveAction initialPackagePath modules packageInfos fields origPackageD panePath nb window = reifyIDE $ \ ideR -> do vb <- vBoxNew False 0 bb <- hButtonBoxNew save <- buttonNewFromStock "gtk-save" widgetSetSensitive save False closeB <- buttonNewFromStock "gtk-close" addB <- buttonNewFromStock (__ "Add Build Info") removeB <- buttonNewFromStock (__ "Remove Build Info") label <- labelNew (Nothing :: Maybe Text) boxPackStart bb addB PackNatural 0 boxPackStart bb removeB PackNatural 0 boxPackEnd bb closeB PackNatural 0 boxPackEnd bb save PackNatural 0 (widget, setInj, getExt, notifier) <- buildEditor packageDescr packageD let packagePane = PackagePane vb notifier boxPackStart vb widget PackGrow 7 boxPackStart vb label PackNatural 0 boxPackEnd vb bb PackNatural 7 let fieldNames = map (fromMaybe (__ "Unnamed") . getParameterPrim paraName . parameters) fields on addB buttonActivated $ do mbNewPackage' <- extract packageD [getExt] case mbNewPackage' of Nothing -> sysMessage Normal (__ "Content doesn't validate") Just pde -> reflectIDE (do closePane packagePane initPackage packageDir pde {bis = bis pde ++ [head (bis pde)]} (packageDD packageInfos packageDir modules (length (bis pde) + 1) (concatMap (buildInfoD (Just packageDir) modules) [0..length (bis pde)])) panePath nb modules afterSaveAction origPackageD) ideR on removeB buttonActivated $ do mbNewPackage' <- extract packageD [getExt] case mbNewPackage' of Nothing -> sysMessage Normal (__ "Content doesn't validate") Just pde | length (bis pde) == 1 -> sysMessage Normal (__ "Just one Build Info") | otherwise -> reflectIDE (do closePane packagePane initPackage packageDir pde{bis = take (length (bis pde) - 1) (bis pde)} (packageDD packageInfos packageDir modules (length (bis pde) - 1) (concatMap (buildInfoD (Just packageDir) modules) [0..length (bis pde) - 2])) panePath nb modules afterSaveAction origPackageD) ideR on closeB buttonActivated $ do mbP <- extract packageD [getExt] let hasChanged = case mbP of Nothing -> False Just p -> p /= origPackageD if not hasChanged then reflectIDE (void (closePane packagePane)) ideR else do md <- messageDialogNew (Just window) [] MessageQuestion ButtonsYesNo (__ "Unsaved changes. Close anyway?") set md [ windowWindowPosition := WinPosCenterOnParent ] resp <- dialogRun md widgetDestroy md case resp of ResponseYes -> reflectIDE (void (closePane packagePane)) ideR _ -> return () on save buttonActivated $ do mbNewPackage' <- extract packageD [getExt] case mbNewPackage' of Nothing -> return () Just newPackage' -> let newPackage = fromEditor newPackage' in do let packagePath = packageDir </> (display . pkgName . package . pd) newPackage' ++ ".cabal" writeGenericPackageDescription packagePath (toGenericPackageDescription newPackage) reflectIDE (do afterSaveAction packagePath closePane packagePane return ()) ideR registerEvent notifier MayHaveChanged (\ e -> do mbP <- extract packageD [getExt] let hasChanged = case mbP of Nothing -> False Just p -> p /= origPackageD when (isJust mbP) $ labelSetMarkup label ("" :: Text) when (isJust mbP) $ comparePDE (fromJust mbP) packageD markLabel nb (getTopWidget packagePane) hasChanged widgetSetSensitive save hasChanged return (e{gtkReturn=False})) registerEvent notifier ValidationError (\e -> do labelSetMarkup label $ "<span foreground=\"red\" size=\"x-large\">The following fields have invalid values: " <> eventText e <> "</span>" return e) return (Just packagePane,[]) -- --------------------------------------------------------------------- -- The description with some tricks -- packageDD :: [PackageIdentifier] -> FilePath -> [ModuleName] -> Int -> [(Text, FieldDescription PackageDescriptionEd)] -> FieldDescription PackageDescriptionEd packageDD packages fp modules numBuildInfos extras = NFD ([ (__ "Package", VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Synopsis") $ paraSynopsis <<<- ParaSynopsis (__ "A one-line summary of this package") $ emptyParams) (synopsis . pd) (\ a b -> b{pd = (pd b){synopsis = a}}) (stringEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Package Identifier") $ emptyParams) (package . pd) (\ a b -> b{pd = (pd b){package = a}}) packageEditor , mkField (paraName <<<- ParaName (__ "Description") $ paraSynopsis <<<- ParaSynopsis (__ "A more verbose description of this package") $ paraShadow <<<- ParaShadow ShadowOut $ paraMinSize <<<- ParaMinSize (-1,210) $ emptyParams) (T.pack . description . pd) (\ a b -> b{pd = (pd b){description = T.unpack $ if T.null a then " " else a}}) multilineStringEditor , mkField (paraName <<<- ParaName (__ "Homepage") $ emptyParams) (homepage . pd) (\ a b -> b{pd = (pd b){homepage = a}}) (stringEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Package URL") $ emptyParams) (pkgUrl . pd) (\ a b -> b{pd = (pd b){pkgUrl = a}}) (stringEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Category") $ emptyParams) (category . pd) (\ a b -> b{pd = (pd b){category = a}}) (stringEditor (const True) True) ]), (__ "Description", VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Stability") $ emptyParams) (stability . pd) (\ a b -> b{pd = (pd b){stability = a}}) (stringEditor (const True) True) -- TODO Fix this up to work with current Cabal -- , mkField -- (paraName <<<- ParaName (__ "License") $ emptyParams) -- (license . pd) -- (\ a b -> b{pd = (pd b){license = a}}) -- (comboSelectionEditor [GPL, LGPL, BSD3, BSD4, PublicDomain, AllRightsReserved, OtherLicense] show) , mkField #if MIN_VERSION_Cabal(1,22,0) (paraName <<<- ParaName (__ "License Files") $ paraSynopsis <<<- ParaSynopsis (__ "A list of license files.") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,250) $ emptyParams) (licenseFiles . pd) (\ a b -> b{pd = (pd b){licenseFiles = a}}) (filesEditor (Just fp) FileChooserActionOpen (__ "Select File")) #else (paraName <<<- ParaName (__ "License File") $ emptyParams) (licenseFile . pd) (\ a b -> b{pd = (pd b){licenseFile = a}}) (fileEditor (Just fp) FileChooserActionOpen (__ "Select file")) #endif , mkField (paraName <<<- ParaName (__ "Copyright") $ emptyParams) (copyright . pd) (\ a b -> b{pd = (pd b){copyright = a}}) (stringEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Author") $ emptyParams) (author . pd) (\ a b -> b{pd = (pd b){author = a}}) (stringEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Maintainer") $ emptyParams) (maintainer . pd) (\ a b -> b{pd = (pd b){maintainer = a}}) (stringEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Bug Reports") $ emptyParams) (bugReports . pd) (\ a b -> b{pd = (pd b){bugReports = a}}) (stringEditor (const True) True) ]), -- ("Repositories", VFD emptyParams [ -- mkField -- (paraName <<<- ParaName "Source Repositories" $ emptyParams) -- (sourceRepos . pd) -- (\ a b -> b{pd = (pd b){sourceRepos = a}}) -- reposEditor]), (__ "Dependencies ", VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Build Dependencies") $ paraSynopsis <<<- ParaSynopsis (__ "Does this package depends on other packages?") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,250) $ emptyParams) (nub . buildDepends . pd) (\ a b -> b{pd = (pd b){buildDepends = a}}) (dependenciesEditor packages) ]), (__ "Meta Dep.", VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Cabal version") $ paraSynopsis <<<- ParaSynopsis (__ "Does this package depends on a specific version of Cabal?") $ paraShadow <<<- ParaShadow ShadowIn $ emptyParams) (specVersion . pd) (\ a b -> b{pd = (pd b){specVersionRaw = Left a}}) versionEditor , mkField (paraName <<<- ParaName (__ "Tested with compiler") $ paraShadow <<<- ParaShadow ShadowIn $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,150) $ emptyParams) (\a -> case (testedWith . pd) a of [] -> []--(GHC,anyVersion)] l -> l) (\ a b -> b{pd = (pd b){testedWith = a}}) testedWithEditor ]), (__ "Data Files", VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Data Files") $ paraSynopsis <<<- ParaSynopsis (__ "A list of files to be installed for run-time use by the package.") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,250) $ emptyParams) (dataFiles . pd) (\ a b -> b{pd = (pd b){dataFiles = a}}) (filesEditor (Just fp) FileChooserActionOpen (__ "Select File")) , mkField (paraName <<<- ParaName (__ "Data directory") $ emptyParams) (dataDir . pd) (\ a b -> b{pd = (pd b){dataDir = a}}) (fileEditor (Just fp) FileChooserActionSelectFolder (__ "Select file")) ]), (__ "Extra Files", VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Extra Source Files") $ paraSynopsis <<<- ParaSynopsis (__ "A list of additional files to be included in source distributions.") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,120) $ emptyParams) (extraSrcFiles . pd) (\ a b -> b{pd = (pd b){extraSrcFiles = a}}) (filesEditor (Just fp) FileChooserActionOpen (__ "Select File")) , mkField (paraName <<<- ParaName (__ "Extra Tmp Files") $ paraSynopsis <<<- ParaSynopsis (__ "A list of additional files or directories to be removed by setup clean.") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,120) $ emptyParams) (extraTmpFiles . pd) (\ a b -> b{pd = (pd b){extraTmpFiles = a}}) (filesEditor (Just fp) FileChooserActionOpen (__ "Select File")) ]), (__ "Other",VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Build Type") $ paraSynopsis <<<- ParaSynopsis (__ "Describe executable programs contained in the package") $ paraShadow <<<- ParaShadow ShadowIn $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (buildType . pd) (\ a b -> b{pd = (pd b){buildType = a}}) (maybeEditor (buildTypeEditor, emptyParams) True (__ "Specify?")) , mkField (paraName <<<- ParaName (__ "Custom Fields") $ paraShadow <<<- ParaShadow ShadowIn $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (customFieldsPD . pd) (\ a b -> b{pd = (pd b){customFieldsPD = a}}) (multisetEditor (ColumnDescr True [(__ "Name",\(n,_) -> [cellText := T.pack n]) ,(__ "Value",\(_,v) -> [cellText := T.pack v])]) (pairEditor (stringxEditor (const True), emptyParams) (stringEditor (const True) True, emptyParams), emptyParams) Nothing Nothing) ]), (__ "Executables",VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Executables") $ paraSynopsis <<<- ParaSynopsis (__ "Describe executable programs contained in the package") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) exes (\ a b -> b{exes = a}) (executablesEditor (Just fp) modules numBuildInfos) ]), (__ "Tests",VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Tests") $ paraSynopsis <<<- ParaSynopsis (__ "Describe tests contained in the package") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) tests (\ a b -> b{tests = a}) (testsEditor (Just fp) modules numBuildInfos) ]), (__ "Benchmarks",VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Benchmarks") $ paraSynopsis <<<- ParaSynopsis (__ "Describe tests contained in the package") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) bms (\ a b -> b{bms = a}) (benchmarksEditor (Just fp) modules numBuildInfos) ]), (__ "Library", VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Library") $ paraSynopsis <<<- ParaSynopsis (__ "If the package contains a library, specify the exported modules here") $ paraDirection <<<- ParaDirection Vertical $ paraShadow <<<- ParaShadow ShadowIn $ emptyParams) mbLib (\ a b -> b{mbLib = a}) (maybeEditor (libraryEditor (Just fp) modules numBuildInfos, paraName <<<- ParaName (__ "Specify exported modules") $ emptyParams) True (__ "Does this package contain a library?")) ]) ] ++ extras) update :: [BuildInfo] -> Int -> (BuildInfo -> BuildInfo) -> [BuildInfo] update bis index func = map (\(bi,ind) -> if ind == index then func bi else bi) (zip bis [0..length bis - 1]) buildInfoD :: Maybe FilePath -> [ModuleName] -> Int -> [(Text,FieldDescription PackageDescriptionEd)] buildInfoD fp modules i = [ (T.pack $ printf (__ "%s Build Info") (show (i + 1)), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Component is buildable here") $ emptyParams) (buildable . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{buildable = a})}) boolEditor , mkField (paraName <<<- ParaName (__ "Where to look for the source hierarchy") $ paraSynopsis <<<- ParaSynopsis (__ "Root directories for the source hierarchy.") $ paraShadow <<<- ParaShadow ShadowIn $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,150) $ emptyParams) (hsSourceDirs . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{hsSourceDirs = a})}) (filesEditor fp FileChooserActionSelectFolder (__ "Select folder")) , mkField (paraName <<<- ParaName (__ "Non-exposed or non-main modules") $ paraSynopsis <<<- ParaSynopsis (__ "A list of modules used by the component but not exposed to users.") $ paraShadow <<<- ParaShadow ShadowIn $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,300) $ paraPack <<<- ParaPack PackGrow $ emptyParams) (map (T.pack . display) . otherModules . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{otherModules = map (\i -> forceJust (simpleParse $ T.unpack i) " PackageEditor >> buildInfoD: no parse for moduile name" ) a})}) (modulesEditor modules) ]), (T.pack $ printf (__ "%s Compiler ") (show (i + 1)), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Options for haskell compilers") $ paraDirection <<<- ParaDirection Vertical $ paraShadow <<<- ParaShadow ShadowIn $ paraPack <<<- ParaPack PackGrow $ emptyParams) (options . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{options = a})}) (multisetEditor (ColumnDescr True [( __ "Compiler Flavor",\(cv,_) -> [cellText := T.pack $ show cv]) ,(__ "Options",\(_,op) -> [cellText := T.pack $ concatMap (\s -> ' ' : s) op])]) (pairEditor (compilerFlavorEditor,emptyParams) (optsEditor,emptyParams), paraDirection <<<- ParaDirection Vertical $ paraShadow <<<- ParaShadow ShadowIn $ emptyParams) Nothing Nothing) #if MIN_VERSION_Cabal(1,22,0) , mkField (paraName <<<- ParaName (__ "Additional options for GHC when built with profiling") $ emptyParams) (profOptions . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{profOptions = a})}) compilerOptsEditor , mkField (paraName <<<- ParaName (__ "Additional options for GHC when the package is built as shared library") $ emptyParams) (sharedOptions . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{sharedOptions = a})}) compilerOptsEditor #else , mkField (paraName <<<- ParaName (__ "Additional options for GHC when built with profiling") $ emptyParams) (ghcProfOptions . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{ghcProfOptions = a})}) optsEditor , mkField (paraName <<<- ParaName (__ "Additional options for GHC when the package is built as shared library") $ emptyParams) (ghcSharedOptions . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{ghcSharedOptions = a})}) optsEditor #endif ]), (T.pack $ printf (__ "%s Extensions ") (show (i + 1)), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Extensions") $ paraSynopsis <<<- ParaSynopsis (__ "A list of Haskell extensions used by every module.") $ paraMinSize <<<- ParaMinSize (-1,400) $ paraPack <<<- ParaPack PackGrow $ emptyParams) (oldExtensions . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{oldExtensions = a})}) extensionsEditor ]), (T.pack $ printf (__ "%s Build Tools ") (show (i + 1)), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Tools needed for a build") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,120) $ emptyParams) (buildTools . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{buildTools = a})}) (dependenciesEditor []) ]), (T.pack $ printf (__ "%s Pkg Config ") (show (i + 1)), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "A list of pkg-config packages, needed to build this package") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,120) $ emptyParams) (pkgconfigDepends . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{pkgconfigDepends = a})}) (dependenciesEditor []) ]), (T.pack $ printf (__ "%s Opts C -1-") (show (i + 1)), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Options for C compiler") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (ccOptions . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{ccOptions = a})}) optsEditor , mkField (paraName <<<- ParaName (__ "Options for linker") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (ldOptions . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{ldOptions = a})}) optsEditor , mkField (paraName <<<- ParaName (__ "A list of header files to use when compiling") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (map T.pack . includes . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{includes = map T.unpack a})}) (textsEditor (const True) True) , mkField (paraName <<<- ParaName (__ "A list of header files to install") $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (installIncludes . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{installIncludes = a})}) (filesEditor fp FileChooserActionOpen (__ "Select File")) ]), (T.pack $ printf (__ "%s Opts C -2-") (show (i + 1)), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "A list of directories to search for header files") $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (includeDirs . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{includeDirs = a})}) (filesEditor fp FileChooserActionSelectFolder (__ "Select Folder")) , mkField (paraName <<<- ParaName (__ "A list of C source files to be compiled,linked with the Haskell files.") $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (cSources . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{cSources = a})}) (filesEditor fp FileChooserActionOpen (__ "Select file")) ]), (T.pack $ printf (__ "%s Opts Libs ") (show (i + 1)), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "A list of extra libraries to link with") $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (map T.pack . extraLibs . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{extraLibs = map T.unpack a})}) (textsEditor (const True) True) , mkField (paraName <<<- ParaName (__ "A list of directories to search for libraries.") $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (extraLibDirs . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{extraLibDirs = a})}) (filesEditor fp FileChooserActionSelectFolder (__ "Select Folder")) ]), (T.pack $ printf (__ "%s Other") (show (i + 1)), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Options for C preprocessor") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (cppOptions . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{cppOptions = a})}) optsEditor , mkField (paraName <<<- ParaName (__ "Support frameworks for Mac OS X") $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (map T.pack . frameworks . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{frameworks = map T.unpack a})}) (textsEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Custom fields build info") $ paraShadow <<<- ParaShadow ShadowIn $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (customFieldsBI . (!! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{customFieldsBI = a})}) (multisetEditor (ColumnDescr True [(__ "Name",\(n,_) -> [cellText := T.pack n]) ,(__ "Value",\(_,v) -> [cellText := T.pack v])]) (pairEditor (stringxEditor (const True),emptyParams) (stringEditor (const True) True,emptyParams),emptyParams) Nothing Nothing) ])] stringxEditor :: (String -> Bool) -> Editor String stringxEditor val para noti = do (wid,inj,ext) <- stringEditor val True para noti let xinj ("") = inj "" xinj ('x':'-':rest) = inj rest xinj _ = throwIDE "PackageEditor>>stringxEditor: field without leading x-" xext = do res <- ext case res of Nothing -> return Nothing Just str -> return (Just ("x-" ++ str)) return (wid,xinj,xext) optsEditor :: Editor [String] optsEditor para noti = do (wid,inj,ext) <- stringEditor (const True) True para noti let oinj = inj . unwords oext = do res <- ext case res of Nothing -> return Nothing Just str -> return (Just (words str)) return (wid,oinj,oext) compilerOptRecordEditor :: Editor (CompilerFlavor, [String]) compilerOptRecordEditor para = pairEditor (compilerFlavorEditor , paraName <<<- ParaName "Compiler" $ emptyParams) (optsEditor,paraName <<<- ParaName "Options" $ emptyParams) (paraDirection <<<- ParaDirection Vertical $ para) compilerOptsEditor :: Editor [(CompilerFlavor, [String])] compilerOptsEditor p = multisetEditor (ColumnDescr True [("Compiler",\(compiler, _) -> [cellText := T.pack $ show compiler]) ,("Options",\(_, opts ) -> [cellText := T.pack $ unwords opts])]) (compilerOptRecordEditor, paraOuterAlignment <<<- ParaInnerAlignment (0.0, 0.5, 1.0, 1.0) $ paraInnerAlignment <<<- ParaOuterAlignment (0.0, 0.5, 1.0, 1.0) $ emptyParams) (Just (sortBy (\ (f1, _) (f2, _) -> compare f1 f2))) (Just (\ (f1, _) (f2, _) -> f1 == f2)) (paraShadow <<<- ParaShadow ShadowIn $ paraOuterAlignment <<<- ParaInnerAlignment (0.0, 0.5, 1.0, 1.0) $ paraInnerAlignment <<<- ParaOuterAlignment (0.0, 0.5, 1.0, 1.0) $ paraDirection <<<- ParaDirection Vertical $ paraPack <<<- ParaPack PackGrow $ p) packageEditor :: Editor PackageIdentifier packageEditor para noti = do (wid,inj,ext) <- pairEditor (stringEditor (not . null) True, paraName <<<- ParaName (__ "Name") $ emptyParams) (versionEditor, paraName <<<- ParaName (__ "Version") $ emptyParams) (paraDirection <<<- ParaDirection Horizontal $ paraShadow <<<- ParaShadow ShadowIn $ para) noti let pinj (PackageIdentifier (PackageName n) v) = inj (n,v) let pext = do mbp <- ext case mbp of Nothing -> return Nothing Just (n,v) -> return $ if null n then Nothing else Just $ PackageIdentifier (PackageName n) v return (wid,pinj,pext) testedWithEditor :: Editor [(CompilerFlavor, VersionRange)] testedWithEditor = multisetEditor (ColumnDescr True [(__ "Compiler Flavor",\(cv,_) -> [cellText := T.pack $ show cv]) ,(__ "Version Range",\(_,vr) -> [cellText := T.pack $ display vr])]) (pairEditor (compilerFlavorEditor, paraShadow <<<- ParaShadow ShadowNone $ emptyParams) (versionRangeEditor, paraShadow <<<- ParaShadow ShadowNone $ emptyParams), paraDirection <<<- ParaDirection Vertical $ emptyParams) Nothing (Just (==)) compilerFlavorEditor :: Editor CompilerFlavor compilerFlavorEditor para noti = do (wid,inj,ext) <- eitherOrEditor (comboSelectionEditor flavors (T.pack . show), paraName <<<- ParaName (__ "Select compiler") $ emptyParams) (textEditor (not . T.null) True, paraName <<<- ParaName (__ "Specify compiler") $ emptyParams) (__ "Other") (paraName <<<- ParaName (__ "Select") $ para) noti let cfinj comp = case comp of (OtherCompiler str) -> inj (Right $ T.pack str) other -> inj (Left other) let cfext = do mbp <- ext case mbp of Nothing -> return Nothing Just (Right s) -> return (Just . OtherCompiler $ T.unpack s) Just (Left other) -> return (Just other) return (wid,cfinj,cfext) where flavors = [GHC, NHC, Hugs, HBC, Helium, JHC] buildTypeEditor :: Editor BuildType buildTypeEditor para noti = do (wid,inj,ext) <- eitherOrEditor (comboSelectionEditor flavors (T.pack . show), paraName <<<- ParaName (__ "Select") $ emptyParams) (textEditor (const True) True, paraName <<<- ParaName (__ "Unknown") $ emptyParams) (__ "Unknown") (paraName <<<- ParaName (__ "Select") $ para) noti let cfinj comp = case comp of (UnknownBuildType str) -> inj (Right $ T.pack str) other -> inj (Left other) let cfext = do mbp <- ext case mbp of Nothing -> return Nothing Just (Right s) -> return (Just . UnknownBuildType $ T.unpack s) Just (Left other) -> return (Just other) return (wid,cfinj,cfext) where flavors = [Simple, Configure, Make, Custom] extensionsEditor :: Editor [Extension] extensionsEditor = staticListMultiEditor extensionsL (T.pack . show) extensionsL :: [Extension] extensionsL = map EnableExtension [minBound..maxBound] {-- reposEditor :: Editor [SourceRepo] reposEditor p noti = multisetEditor (ColumnDescr False [("",\repo -> [cellText := display repo])]) (repoEditor, paraOuterAlignment <<<- ParaInnerAlignment (0.0, 0.5, 1.0, 1.0) $ paraInnerAlignment <<<- ParaOuterAlignment (0.0, 0.5, 1.0, 1.0) $ emptyParams) Nothing Nothing (paraShadow <<<- ParaShadow ShadowIn $ paraOuterAlignment <<<- ParaInnerAlignment (0.0, 0.5, 1.0, 1.0) $ paraInnerAlignment <<<- ParaOuterAlignment (0.0, 0.5, 1.0, 1.0) $ paraDirection <<<- ParaDirection Vertical $ paraPack <<<- ParaPack PackGrow $ p) noti instance Text SourceRepo where disp (SourceRepo repoKind repoType repoLocation repoModule repoBranch repoTag repoSubdir) = disp repoKind <+> case repoType of Nothing -> empty Just repoT -> disp repoT <+> case repoLocation of Nothing -> empty Just repoL -> text repoL repoEditor :: Editor SourceRepo repoEditor paras noti = do (widg,inj,ext) <- tupel7Editor (repoKindEditor,noBorder) (maybeEditor (repoTypeEditor,noBorder) True "Specify a type", emptyParams) (maybeEditor (textEditor (const True) True,noBorder) True "Specify a location", emptyParams) (maybeEditor (textEditor (const True) True,noBorder) True "Specify a module", emptyParams) (maybeEditor (textEditor (const True) True,noBorder) True "Specify a branch", emptyParams) (maybeEditor (textEditor (const True) True,noBorder) True "Specify a tag", emptyParams) (maybeEditor (textEditor (const True) True,noBorder) True "Specify a subdir", emptyParams) (paraDirection <<<- ParaDirection Vertical $ noBorder) noti return (widg, (\ r -> inj (repoKind r,repoType r,repoLocation r,repoModule r,repoBranch r,repoTag r,repoSubdir r)), (do mb <- ext case mb of Nothing -> return Nothing Just (a,b,c,d,e,f,g) -> return (Just (SourceRepo a b c d e f g)))) where noBorder = paraOuterAlignment <<<- ParaOuterAlignment (0.0, 0.0, 0.0, 0.0) $ paraOuterPadding <<<- ParaOuterPadding (0, 0, 0, 0) $ paraInnerAlignment <<<- ParaInnerAlignment (0.0, 0.0, 0.0, 0.0) $ paraInnerPadding <<<- ParaInnerPadding (0, 0, 0, 0) $ emptyParams repoKindEditor :: Editor RepoKind repoKindEditor paras noti = do (widg,inj,ext) <- pairEditor (comboSelectionEditor selectionList show, emptyParams) (textEditor (const True) True,emptyParams) paras noti return (widg, (\kind -> case kind of RepoKindUnknown str -> inj (RepoKindUnknown "",str) other -> inj (other,"")), (do mbRes <- ext case mbRes of Nothing -> return Nothing Just (RepoKindUnknown "",str) -> return (Just (RepoKindUnknown str)) Just (other,_) -> return (Just other))) where selectionList = [RepoHead, RepoThis, RepoKindUnknown ""] repoTypeEditor :: Editor RepoType repoTypeEditor paras noti = do (widg,inj,ext) <- pairEditor (comboSelectionEditor selectionList show, emptyParams) (textEditor (const True) True,emptyParams) paras noti return (widg, (\kind -> case kind of OtherRepoType str -> inj (OtherRepoType "",str) other -> inj (other,"")), (do mbRes <- ext case mbRes of Nothing -> return Nothing Just (OtherRepoType "",str) -> return (Just (OtherRepoType str)) Just (other,_) -> return (Just other))) where selectionList = [Darcs, Git, SVN, CVS, Mercurial, GnuArch, Bazaar, Monotone, OtherRepoType ""] --} -- ------------------------------------------------------------ -- * BuildInfos -- ------------------------------------------------------------ data Library' = Library'{ exposedModules' :: [ModuleName] #if MIN_VERSION_Cabal(1,22,0) , reexportedModules' :: [ModuleReexport] , requiredSignatures':: [ModuleName] , exposedSignatures' :: [ModuleName] #endif , libExposed' :: Bool , libBuildInfoIdx :: Int} deriving (Show, Eq) data Executable' = Executable'{ exeName' :: Text , modulePath' :: FilePath , buildInfoIdx :: Int} deriving (Show, Eq) data Test' = Test'{ testName' :: Text , testInterface' :: TestSuiteInterface , testBuildInfoIdx :: Int} deriving (Show, Eq) data Benchmark' = Benchmark'{ benchmarkName' :: Text , benchmarkInterface' :: BenchmarkInterface , benchmarkBuildInfoIdx :: Int} deriving (Show, Eq) instance Default Library' #if MIN_VERSION_Cabal(1,22,0) where getDefault = Library' [] [] [] [] getDefault getDefault #else where getDefault = Library' [] getDefault getDefault #endif instance Default Executable' where getDefault = Executable' getDefault getDefault getDefault instance Default Test' where getDefault = Test' getDefault (TestSuiteExeV10 (Version [1,0] []) getDefault) getDefault instance Default Benchmark' where getDefault = Benchmark' getDefault (BenchmarkExeV10 (Version [1,0] []) getDefault) getDefault #if MIN_VERSION_Cabal(1,22,0) libraryEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor Library' libraryEditor fp modules numBuildInfos para noti = do (wid,inj,ext) <- pairEditor (tupel3Editor (boolEditor, paraName <<<- ParaName (__ "Exposed") $ paraSynopsis <<<- ParaSynopsis (__ "Is the lib to be exposed by default?") $ emptyParams) (modulesEditor (sort modules), paraName <<<- ParaName (__ "Exposed Modules") $ paraMinSize <<<- ParaMinSize (-1,300) $ para) (buildInfoEditorP numBuildInfos, paraName <<<- ParaName (__ "Build Info") $ paraPack <<<- ParaPack PackNatural $ para), paraDirection <<<- ParaDirection Vertical $ emptyParams) (tupel3Editor (modulesEditor (sort modules), paraName <<<- ParaName (__ "Reexported Modules") $ paraMinSize <<<- ParaMinSize (-1,300) $ para) (modulesEditor (sort modules), paraName <<<- ParaName (__ "Required Signatures") $ paraMinSize <<<- ParaMinSize (-1,300) $ para) (modulesEditor (sort modules), paraName <<<- ParaName (__ "Exposed Signatures") $ paraMinSize <<<- ParaMinSize (-1,300) $ para), paraDirection <<<- ParaDirection Vertical $ emptyParams) (paraDirection <<<- ParaDirection Vertical $ emptyParams) noti let pinj (Library' em rmn rs es exp bi) = inj ((exp, map (T.pack . display) em,bi), (map (T.pack . display) rmn, map (T.pack . display) rs, map (T.pack . display) es)) parseModuleNames = map (\s -> forceJust (simpleParse $ T.unpack s) "SpecialEditor >> libraryEditor: no parse for moduile name") parseRexportedModules = map (\s -> forceJust (simpleParse $ T.unpack s) "SpecialEditor >> libraryEditor: no parse for moduile name") pext = do mbp <- ext case mbp of Nothing -> return Nothing Just ((exp,em,bi), (rmn, rs, es)) -> return (Just $ Library' (parseModuleNames em) (parseRexportedModules rmn) (parseModuleNames rs) (parseModuleNames es) exp bi) return (wid,pinj,pext) #else libraryEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor Library' libraryEditor fp modules numBuildInfos para noti = do (wid,inj,ext) <- tupel3Editor (boolEditor, paraName <<<- ParaName (__ "Exposed") $ paraSynopsis <<<- ParaSynopsis (__ "Is the lib to be exposed by default?") $ emptyParams) (modulesEditor (sort modules), paraName <<<- ParaName (__ "Exposed Modules") $ paraMinSize <<<- ParaMinSize (-1,300) $ para) (buildInfoEditorP numBuildInfos, paraName <<<- ParaName (__ "Build Info") $ paraPack <<<- ParaPack PackNatural $ para) (paraDirection <<<- ParaDirection Vertical $ emptyParams) noti let pinj (Library' em exp bi) = inj (exp, map (T.pack . display) em,bi) let pext = do mbp <- ext case mbp of Nothing -> return Nothing Just (exp,em,bi) -> return (Just $ Library' (map (\s -> forceJust (simpleParse $ T.unpack s) "SpecialEditor >> libraryEditor: no parse for moduile name") em) exp bi) return (wid,pinj,pext) #endif modulesEditor :: [ModuleName] -> Editor [Text] modulesEditor modules = staticListMultiEditor (map (T.pack . display) modules) id executablesEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor [Executable'] executablesEditor fp modules countBuildInfo p = multisetEditor (ColumnDescr True [(__ "Executable Name",\(Executable' exeName _ _) -> [cellText := exeName]) ,(__ "Module Path",\(Executable' _ mp _) -> [cellText := T.pack mp]) ,(__ "Build info index",\(Executable' _ _ bii) -> [cellText := T.pack $ show (bii + 1)])]) (executableEditor fp modules countBuildInfo,emptyParams) Nothing Nothing (paraShadow <<<- ParaShadow ShadowIn $ paraMinSize <<<- ParaMinSize (-1,200) $ p) executableEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor Executable' executableEditor fp modules countBuildInfo para noti = do (wid,inj,ext) <- tupel3Editor (textEditor (not . T.null) True, paraName <<<- ParaName (__ "Executable Name") $ emptyParams) (stringEditor (not . null) True, paraDirection <<<- ParaDirection Vertical $ paraName <<<- ParaName (__ "File with main function") $ emptyParams) (buildInfoEditorP countBuildInfo, paraName <<<- ParaName (__ "Build Info") $ paraOuterAlignment <<<- ParaOuterAlignment (0.0, 0.0, 0.0, 0.0) $ paraOuterPadding <<<- ParaOuterPadding (0, 0, 0, 0) $ paraInnerAlignment <<<- ParaInnerAlignment (0.0, 0.0, 0.0, 0.0) $ paraInnerPadding <<<- ParaInnerPadding (0, 0, 0, 0) $ emptyParams) (paraDirection <<<- ParaDirection Vertical $ para) noti let pinj (Executable' s f bi) = inj (s,f,bi) let pext = do mbp <- ext case mbp of Nothing -> return Nothing Just (s,f,bi) -> return (Just $Executable' s f bi) return (wid,pinj,pext) testsEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor [Test'] testsEditor fp modules countBuildInfo p = multisetEditor (ColumnDescr True [(__ "Test Name",\(Test' testName _ _) -> [cellText := testName]) ,(__ "Interface",\(Test' _ i _) -> [cellText := T.pack $ interfaceName i]) ,(__ "Build info index",\(Test' _ _ bii) -> [cellText := T.pack $ show (bii + 1)])]) (testEditor fp modules countBuildInfo,emptyParams) Nothing Nothing (paraShadow <<<- ParaShadow ShadowIn $ paraMinSize <<<- ParaMinSize (-1,200) $ p) where interfaceName (TestSuiteExeV10 _ f) = f interfaceName i = show i testEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor Test' testEditor fp modules countBuildInfo para noti = do (wid,inj,ext) <- tupel3Editor (textEditor (not . T.null) True, paraName <<<- ParaName (__ "Test Name") $ emptyParams) (stringEditor (not . null) True, paraDirection <<<- ParaDirection Vertical $ paraName <<<- ParaName (__ "File with main function") $ emptyParams) (buildInfoEditorP countBuildInfo, paraName <<<- ParaName (__ "Build Info") $ paraOuterAlignment <<<- ParaOuterAlignment (0.0, 0.0, 0.0, 0.0) $ paraOuterPadding <<<- ParaOuterPadding (0, 0, 0, 0) $ paraInnerAlignment <<<- ParaInnerAlignment (0.0, 0.0, 0.0, 0.0) $ paraInnerPadding <<<- ParaInnerPadding (0, 0, 0, 0) $ emptyParams) (paraDirection <<<- ParaDirection Vertical $ para) noti let pinj (Test' s (TestSuiteExeV10 (Version [1,0] []) f) bi) = inj (s,f,bi) pinj _ = error "Unexpected Test Interface" let pext = do mbp <- ext case mbp of Nothing -> return Nothing Just (s,f,bi) -> return (Just $Test' s (TestSuiteExeV10 (Version [1,0] []) f) bi) return (wid,pinj,pext) benchmarksEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor [Benchmark'] benchmarksEditor fp modules countBuildInfo p = multisetEditor (ColumnDescr True [(__ "Benchmark Name",\(Benchmark' benchmarkName _ _) -> [cellText := benchmarkName]) ,(__ "Interface",\(Benchmark' _ i _) -> [cellText := T.pack $ interfaceName i]) ,(__ "Build info index",\(Benchmark' _ _ bii) -> [cellText := T.pack $ show (bii + 1)])]) (benchmarkEditor fp modules countBuildInfo,emptyParams) Nothing Nothing (paraShadow <<<- ParaShadow ShadowIn $ paraMinSize <<<- ParaMinSize (-1,200) $ p) where interfaceName (BenchmarkExeV10 _ f) = f interfaceName i = show i benchmarkEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor Benchmark' benchmarkEditor fp modules countBuildInfo para noti = do (wid,inj,ext) <- tupel3Editor (textEditor (not . T.null) True, paraName <<<- ParaName (__ "Benchmark Name") $ emptyParams) (stringEditor (not . null) True, paraDirection <<<- ParaDirection Vertical $ paraName <<<- ParaName (__ "File with main function") $ emptyParams) (buildInfoEditorP countBuildInfo, paraName <<<- ParaName (__ "Build Info") $ paraOuterAlignment <<<- ParaOuterAlignment (0.0, 0.0, 0.0, 0.0) $ paraOuterPadding <<<- ParaOuterPadding (0, 0, 0, 0) $ paraInnerAlignment <<<- ParaInnerAlignment (0.0, 0.0, 0.0, 0.0) $ paraInnerPadding <<<- ParaInnerPadding (0, 0, 0, 0) $ emptyParams) (paraDirection <<<- ParaDirection Vertical $ para) noti let pinj (Benchmark' s (BenchmarkExeV10 (Version [1,0] []) f) bi) = inj (s,f,bi) pinj _ = error "Unexpected Benchmark Interface" let pext = do mbp <- ext case mbp of Nothing -> return Nothing Just (s,f,bi) -> return (Just $Benchmark' s (BenchmarkExeV10 (Version [1,0] []) f) bi) return (wid,pinj,pext) buildInfoEditorP :: Int -> Editor Int buildInfoEditorP numberOfBuildInfos para noti = do (wid,inj,ext) <- intEditor (1.0,fromIntegral numberOfBuildInfos,1.0) (paraName <<<- ParaName (__ "Build Info") $para) noti let pinj i = inj (i + 1) let pext = do mbV <- ext case mbV of Nothing -> return Nothing Just i -> return (Just (i - 1)) return (wid,pinj,pext) -- ------------------------------------------------------------ -- * (Boring) default values -- ------------------------------------------------------------ instance Default CompilerFlavor where getDefault = GHC instance Default BuildInfo where getDefault = emptyBuildInfo instance Default Library where getDefault = Library [] #if MIN_VERSION_Cabal(1,22,0) [] [] [] #endif getDefault getDefault instance Default Executable where getDefault = Executable getDefault getDefault getDefault instance Default RepoType where getDefault = Darcs instance Default RepoKind where getDefault = RepoThis instance Default SourceRepo where getDefault = SourceRepo getDefault getDefault getDefault getDefault getDefault getDefault getDefault instance Default BuildType where getDefault = Simple
jaccokrijnen/leksah
src/IDE/Pane/PackageEditor.hs
gpl-2.0
79,913
0
36
27,695
20,349
10,601
9,748
1,373
8
{- This module was generated from data in the Kate syntax highlighting file erlang.xml, version 1.03, by Bill Ross ([email protected]) -} module Text.Highlighting.Kate.Syntax.Erlang (highlight, parseExpression, syntaxName, syntaxExtensions) where import Text.Highlighting.Kate.Types import Text.Highlighting.Kate.Common import qualified Text.Highlighting.Kate.Syntax.Alert import Text.ParserCombinators.Parsec hiding (State) import Control.Monad.State import Data.Char (isSpace) import qualified Data.Set as Set -- | Full name of language. syntaxName :: String syntaxName = "Erlang" -- | Filename extensions for this language. syntaxExtensions :: String syntaxExtensions = "*.erl" -- | Highlight source code using this syntax definition. highlight :: String -> [SourceLine] highlight input = evalState (mapM parseSourceLine $ lines input) startingState parseSourceLine :: String -> State SyntaxState SourceLine parseSourceLine = mkParseSourceLine (parseExpression Nothing) -- | Parse an expression using appropriate local context. parseExpression :: Maybe (String,String) -> KateParser Token parseExpression mbcontext = do (lang,cont) <- maybe currentContext return mbcontext result <- parseRules (lang,cont) optional $ do eof updateState $ \st -> st{ synStPrevChar = '\n' } pEndLine return result startingState = SyntaxState {synStContexts = [("Erlang","Normal Text")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = True, synStCaptures = []} pEndLine = do updateState $ \st -> st{ synStPrevNonspace = False } context <- currentContext contexts <- synStContexts `fmap` getState st <- getState if length contexts >= 2 then case context of _ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False } ("Erlang","Normal Text") -> return () ("Erlang","isfunction") -> (popContext) >> pEndLine ("Erlang","atomquote") -> (popContext) >> pEndLine ("Erlang","stringquote") -> (popContext) >> pEndLine ("Erlang","comment") -> (popContext) >> pEndLine _ -> return () else return () withAttribute attr txt = do when (null txt) $ fail "Parser matched no text" updateState $ \st -> st { synStPrevChar = last txt , synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) } return (attr, txt) list_keywords = Set.fromList $ words $ "after begin case catch cond end fun if let of query receive all_true some_true" list_operators = Set.fromList $ words $ "div rem or xor bor bxor bsl bsr and band not bnot" list_functions = Set.fromList $ words $ "abs accept alarm apply atom_to_list binary_to_list binary_to_term check_process_code concat_binary date delete_module disconnect_node element erase exit float float_to_list garbage_collect get get_keys group_leader halt hd integer_to_list is_alive is_atom is_binary is_boolean is_float is_function is_integer is_list is_number is_pid is_port is_process_alive is_record is_reference is_tuple length link list_to_atom list_to_binary list_to_float list_to_integer list_to_pid list_to_tuple load_module loaded localtime make_ref module_loaded node nodes now open_port pid_to_list port_close port_command port_connect port_control ports pre_loaded process_flag process_info processes purge_module put register registered round self setelement size spawn spawn_link spawn_opt split_binary statistics term_to_binary throw time tl trunc tuple_to_list unlink unregister whereis" regex_'28'3f'3a'2dmodule'7c'2dexport'7c'2ddefine'7c'2dundef'7c'2difdef'7c'2difndef'7c'2delse'7c'2dendif'7c'2dinclude'7c'2dinclude'5flib'29 = compileRegex True "(?:-module|-export|-define|-undef|-ifdef|-ifndef|-else|-endif|-include|-include_lib)" regex_'28'3f'3a'5c'2b'7c'2d'7c'5c'2a'7c'5c'2f'7c'3d'3d'7c'5c'2f'3d'7c'3d'3a'3d'7c'3d'5c'2f'3d'7c'3c'7c'3d'3c'7c'3e'7c'3e'3d'7c'5c'2b'5c'2b'7c'2d'2d'7c'3d'7c'21'7c'3c'2d'29 = compileRegex True "(?:\\+|-|\\*|\\/|==|\\/=|=:=|=\\/=|<|=<|>|>=|\\+\\+|--|=|!|<-)" regex_'28'3f'3a'5c'28'7c'5c'29'7c'5c'7b'7c'5c'7d'7c'5c'5b'7c'5c'5d'7c'5c'2e'7c'5c'3a'7c'5c'7c'7c'5c'7c'5c'7c'7c'3b'7c'5c'2c'7c'5c'3f'7c'2d'3e'7c'5c'23'29 = compileRegex True "(?:\\(|\\)|\\{|\\}|\\[|\\]|\\.|\\:|\\||\\|\\||;|\\,|\\?|->|\\#)" regex_'5cb'5ba'2dz'5d'5b'5fa'2dz'40'2dZ0'2d9'5d'2a'28'3f'3a'28'3f'3d'5b'5e'5fa'2dz'40'2dZ0'2d9'5d'29'7c'24'29'3a'5cb'5ba'2dz'5d'5b'5fa'2dz'40'2dZ0'2d9'5d'2a'28'3f'3a'28'3f'3d'5b'5e'5fa'2dz'40'2dZ0'2d9'5d'29'7c'24'29 = compileRegex True "\\b[a-z][_a-z@-Z0-9]*(?:(?=[^_a-z@-Z0-9])|$):\\b[a-z][_a-z@-Z0-9]*(?:(?=[^_a-z@-Z0-9])|$)" regex_'5cb'5ba'2dz'5d'5b'5fa'2dz'40'2dZ0'2d9'5d'2a'28'3f'3a'28'3f'3d'5b'5e'5fa'2dz'40'2dZ0'2d9'5d'29'7c'24'29'5c'28 = compileRegex True "\\b[a-z][_a-z@-Z0-9]*(?:(?=[^_a-z@-Z0-9])|$)\\(" regex_'5cb'5b'5fA'2dZ'5d'5b'5fa'2dz'40'2dZ0'2d9'5d'2a'28'3f'3a'28'3f'3d'5b'5e'5fa'2dz'40'2dZ0'2d9'5d'29'7c'24'29 = compileRegex True "\\b[_A-Z][_a-z@-Z0-9]*(?:(?=[^_a-z@-Z0-9])|$)" regex_'5cb'5ba'2dz'5d'5b'5fa'2dz'40'2dZ0'2d9'5d'2a'28'3f'3a'28'3f'3d'5b'5e'5fa'2dz'40'2dZ0'2d9'5d'29'7c'24'29 = compileRegex True "\\b[a-z][_a-z@-Z0-9]*(?:(?=[^_a-z@-Z0-9])|$)" regex_'5b0'2d9'5d'2b'5c'2e'5b0'2d9'5d'2b'28'3f'3a'5beE'5d'5b'2b'2d'5d'3f'5b0'2d9'5d'2b'29'3f = compileRegex True "[0-9]+\\.[0-9]+(?:[eE][+-]?[0-9]+)?" regex_'5cd'2b'23'5ba'2dzA'2dZ0'2d9'5d'2b = compileRegex True "\\d+#[a-zA-Z0-9]+" regex_'5c'24'5cS = compileRegex True "\\$\\S" regex_'5b0'2d9'5d'2b = compileRegex True "[0-9]+" regex_'28'3f'3a'28'3f'3a'5c'5c'27'29'3f'5b'5e'27'5d'2a'29'2a'27 = compileRegex True "(?:(?:\\\\')?[^']*)*'" regex_'28'3f'3a'28'3f'3a'5c'5c'22'29'3f'5b'5e'22'5d'2a'29'2a'22 = compileRegex True "(?:(?:\\\\\")?[^\"]*)*\"" parseRules ("Erlang","Normal Text") = (((pColumn 0 >> pRegExpr regex_'28'3f'3a'2dmodule'7c'2dexport'7c'2ddefine'7c'2dundef'7c'2difdef'7c'2difndef'7c'2delse'7c'2dendif'7c'2dinclude'7c'2dinclude'5flib'29 >>= withAttribute KeywordTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_keywords >>= withAttribute KeywordTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_operators >>= withAttribute KeywordTok)) <|> ((pRegExpr regex_'28'3f'3a'5c'2b'7c'2d'7c'5c'2a'7c'5c'2f'7c'3d'3d'7c'5c'2f'3d'7c'3d'3a'3d'7c'3d'5c'2f'3d'7c'3c'7c'3d'3c'7c'3e'7c'3e'3d'7c'5c'2b'5c'2b'7c'2d'2d'7c'3d'7c'21'7c'3c'2d'29 >>= withAttribute KeywordTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_functions >>= withAttribute FunctionTok)) <|> ((pRegExpr regex_'28'3f'3a'5c'28'7c'5c'29'7c'5c'7b'7c'5c'7d'7c'5c'5b'7c'5c'5d'7c'5c'2e'7c'5c'3a'7c'5c'7c'7c'5c'7c'5c'7c'7c'3b'7c'5c'2c'7c'5c'3f'7c'2d'3e'7c'5c'23'29 >>= withAttribute FunctionTok)) <|> ((pDetectSpaces >>= withAttribute NormalTok)) <|> ((pDetectChar False '%' >>= withAttribute CommentTok) >>~ pushContext ("Erlang","comment")) <|> ((pRegExpr regex_'5cb'5ba'2dz'5d'5b'5fa'2dz'40'2dZ0'2d9'5d'2a'28'3f'3a'28'3f'3d'5b'5e'5fa'2dz'40'2dZ0'2d9'5d'29'7c'24'29'3a'5cb'5ba'2dz'5d'5b'5fa'2dz'40'2dZ0'2d9'5d'2a'28'3f'3a'28'3f'3d'5b'5e'5fa'2dz'40'2dZ0'2d9'5d'29'7c'24'29 >>= withAttribute FunctionTok)) <|> ((lookAhead (pRegExpr regex_'5cb'5ba'2dz'5d'5b'5fa'2dz'40'2dZ0'2d9'5d'2a'28'3f'3a'28'3f'3d'5b'5e'5fa'2dz'40'2dZ0'2d9'5d'29'7c'24'29'5c'28) >> pushContext ("Erlang","isfunction") >> currentContext >>= parseRules)) <|> ((pRegExpr regex_'5cb'5b'5fA'2dZ'5d'5b'5fa'2dz'40'2dZ0'2d9'5d'2a'28'3f'3a'28'3f'3d'5b'5e'5fa'2dz'40'2dZ0'2d9'5d'29'7c'24'29 >>= withAttribute DataTypeTok)) <|> ((pDetectChar False '\'' >>= withAttribute CharTok) >>~ pushContext ("Erlang","atomquote")) <|> ((pRegExpr regex_'5cb'5ba'2dz'5d'5b'5fa'2dz'40'2dZ0'2d9'5d'2a'28'3f'3a'28'3f'3d'5b'5e'5fa'2dz'40'2dZ0'2d9'5d'29'7c'24'29 >>= withAttribute CharTok)) <|> ((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("Erlang","stringquote")) <|> ((pRegExpr regex_'5b0'2d9'5d'2b'5c'2e'5b0'2d9'5d'2b'28'3f'3a'5beE'5d'5b'2b'2d'5d'3f'5b0'2d9'5d'2b'29'3f >>= withAttribute FloatTok)) <|> ((pRegExpr regex_'5cd'2b'23'5ba'2dzA'2dZ0'2d9'5d'2b >>= withAttribute BaseNTok)) <|> ((pRegExpr regex_'5c'24'5cS >>= withAttribute DecValTok)) <|> ((pRegExpr regex_'5b0'2d9'5d'2b >>= withAttribute DecValTok)) <|> (currentContext >>= \x -> guard (x == ("Erlang","Normal Text")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Erlang","isfunction") = (((pRegExpr regex_'5cb'5ba'2dz'5d'5b'5fa'2dz'40'2dZ0'2d9'5d'2a'28'3f'3a'28'3f'3d'5b'5e'5fa'2dz'40'2dZ0'2d9'5d'29'7c'24'29 >>= withAttribute FunctionTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Erlang","isfunction")) >> pDefault >>= withAttribute FunctionTok)) parseRules ("Erlang","atomquote") = (((pRegExpr regex_'28'3f'3a'28'3f'3a'5c'5c'27'29'3f'5b'5e'27'5d'2a'29'2a'27 >>= withAttribute CharTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Erlang","atomquote")) >> pDefault >>= withAttribute CharTok)) parseRules ("Erlang","stringquote") = (((pRegExpr regex_'28'3f'3a'28'3f'3a'5c'5c'22'29'3f'5b'5e'22'5d'2a'29'2a'22 >>= withAttribute StringTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Erlang","stringquote")) >> pDefault >>= withAttribute StringTok)) parseRules ("Erlang","comment") = (((pDetectSpaces >>= withAttribute CommentTok)) <|> ((Text.Highlighting.Kate.Syntax.Alert.parseExpression (Just ("Alerts","")) >>= ((withAttribute CommentTok) . snd))) <|> ((pDetectIdentifier >>= withAttribute CommentTok)) <|> (currentContext >>= \x -> guard (x == ("Erlang","comment")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Alerts", _) = Text.Highlighting.Kate.Syntax.Alert.parseExpression Nothing parseRules x = parseRules ("Erlang","Normal Text") <|> fail ("Unknown context" ++ show x)
ambiata/highlighting-kate
Text/Highlighting/Kate/Syntax/Erlang.hs
gpl-2.0
9,859
0
28
1,107
1,756
941
815
123
8
{-# LANGUAGE TypeSynonymInstances #-} module Language.PiCalc.Semantics.Process ( PiProcess , PiAction(..) , nextFree , term , origin -- , pdefs -- * Conversion , mkProcess , fromProg , fromProgWith -- , toProg , toTerm , toStdNF , successors , optSuccessors , successors' ) where import Language.PiCalc.Syntax.Term import Language.PiCalc.Syntax.StdNF import Language.PiCalc.Semantics.Substitutions import Data.Set (Set) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map import Data.MultiSet(MultiSet, distinctElems) import qualified Data.MultiSet as MSet -- TODO: Represent Redexes with a dedicated data structure {- | Representation of the states of the execution of a pi-term. For better performance it is not just a PiTerm, but a structure which gives easier access to the redexes and better support for rewriting. More efficient structures could be used but our focus is on simplicity. This structure's main purpose is hiding details at the moment but could be expanded in the future. -} data PiProcess = PiProc{ nextFree :: NameId , term :: StdNFTerm , origin :: PiAction } deriving (Show, Eq) data PiAction = InitState | SyncOn PiName | TauAction | Unfolding PiTerm deriving (Show, Eq, Ord) mkProcess :: StdNFTerm -> NameId -> PiProcess mkProcess t free = PiProc{ nextFree = free , term = t , origin = InitState } fromProg :: PiProg -> PiProcess fromProg prog = fromProgWith prog (1 + maxName) where maxName = maximum $ (maxNameId $ start prog): [ max (maxArg a) (maxNameId p) | (a,p) <- Map.elems (defs prog) ] maxArg [] = 0 maxArg xs = unique $ maximum xs fromProgWith :: PiProg -> NameId -> PiProcess fromProgWith prog freeName = PiProc{ nextFree = freeName , term = stdNF $ start prog , origin = InitState } -- toProg :: PiProcess -> PiProg -- toProg (PiProc{pdefs=d, term=t}) = PiProg{start=stdToTerm t, defs=d} toTerm :: PiProcess -> PiTerm toTerm (PiProc{term=t}) = stdToTerm t toStdNF :: PiProcess -> StdNFTerm toStdNF = term successors :: PiDefs -> PiProcess -> [PiProcess] successors pdefs proc@PiProc{term=t, nextFree=next} = synchSucc ++ tauSucc ++ unfSucc where synchSucc = [ proc{term=resTerm, origin=SyncOn x} | (x, inR, outR, a@(_,inCont), b@(_,outCont), σ, c) <- matchInRedexes $ pickInputs t, let reactum = stdNF $ New (Set.union (restrNames inR) (restrNames outR)) $ prl [ applySub σ inCont, outCont ], let resTerm = mergeStd c reactum ] tauSucc = [ proc{term=resTerm, origin=TauAction} | (redex, cont, c) <- pickTauRedex t, let resTerm = mergeStd c (stdNF $ New (restrNames redex) cont) ] unfSucc = [ proc{term=resTerm, nextFree=free, origin=Unfolding $ seqTerm redex} | (redex, cont, free, c) <- pickUnfoldRedex pdefs next t, let resTerm = mergeStd c (stdNF $ New (restrNames redex) cont) ] optSuccessors :: PiDefs -> PiProcess -> [PiProcess] optSuccessors pdefs proc@PiProc{term=t, nextFree=next} = (synchSucc ++ tauSucc) ++ unfSucc where synchSucc = [ proc{term=resTerm, origin=SyncOn x} | (x, inR, outR, a@(_,inCont), b@(_,outCont), σ, c) <- matchInRedexes $ pickInputs t, let reactum = stdNF $ New (Set.union (restrNames inR) (restrNames outR)) $ prl [ applySub σ inCont, outCont ], let resTerm = mergeStd c reactum ] tauSucc = [ proc{term=resTerm, origin=TauAction} | (redex, cont, c) <- pickTauRedex t, let resTerm = mergeStd c (stdNF $ New (restrNames redex) cont) ] unfSucc = [ proc{term=resTerm, nextFree=free, origin=Unfolding $ seqTerm redex} | (redex, reacta, free, c) <- allUnfoldRedex pdefs next t, let resTerm = mergeStd c (stdNF $ New (restrNames redex) $ paralls reacta) ] successors' :: PiDefs -> PiProcess -> [(PiTerm, PiProcess)] successors' pdefs proc@PiProc{term=t, nextFree=next} = synchSucc ++ tauSucc ++ unfSucc where synchSucc = [ (prl [alt [a], alt [b]], proc{term=resTerm, origin=SyncOn x}) | (x, inR, outR, a@(_,inCont), b@(_,outCont), σ, c) <- matchInRedexes $ pickInputs t, let reactum = stdNF $ New (Set.union (restrNames inR) (restrNames outR)) $ prl [ applySub σ inCont, outCont ], let resTerm = mergeStd c reactum ] tauSucc = [ (alt $ [(Tau, cont)], proc{term=resTerm, origin=TauAction}) | (redex, cont, c) <- pickTauRedex t, let resTerm = mergeStd c (stdNF $ New (restrNames redex) cont) ] unfSucc = [ (seqTerm redex, proc{term=resTerm, nextFree=free, origin=Unfolding $ seqTerm redex}) | (redex, cont, free, c) <- pickUnfoldRedex pdefs next t, let resTerm = mergeStd c (stdNF $ New (restrNames redex) cont) ] matchInRedexes :: [(PiName, StdFactor, PiPrefTerm, StdNFTerm)] -> [(PiName, StdFactor, StdFactor, PiPrefTerm, PiPrefTerm, NameSubst, StdNFTerm)] matchInRedexes potential = [ (x, inR, outR, inPick, outPick, σ, StdNF context) | (x, inR, inPick, StdNF rest) <- potential, outR@(StdFactor {seqTerm=Alt alts}) <- distinctElems rest, outPick@(Out _ _, _) <- distinctElems alts, σ <- match inPick outPick, let context = MSet.delete outR rest ] pickInputs :: StdNFTerm -> [(PiName, StdFactor, PiPrefTerm, StdNFTerm)] pickInputs (StdNF ps) = [ (x, inRedex, pick, StdNF context) | inRedex@(StdFactor {seqTerm=Alt alts}) <- distinctElems ps, pick@(In x _, _) <- distinctElems alts, let context = MSet.delete inRedex ps ] pickTauRedex :: StdNFTerm -> [(StdFactor, PiTerm, StdNFTerm)] pickTauRedex (StdNF ps) = [ (redex, cont, StdNF context) | redex@(StdFactor {seqTerm=Alt alts}) <- distinctElems ps, (Tau, cont) <- distinctElems alts, let context = MSet.delete redex ps ] -- maybe keep subst separate as in InOutRed? Whould help when thinking in terms of derivatives pickUnfoldRedex :: PiDefs -> NameId -> StdNFTerm -> [(StdFactor, PiTerm, NameId, StdNFTerm)] pickUnfoldRedex pdefs nextFree (StdNF ps) = [ (redex, reactum, max free nextFree, StdNF context) | redex <- distinctElems ps, (reactum, free) <- getUnfolded pdefs nextFree $ seqTerm redex, let context = MSet.delete redex ps ] allUnfoldRedex :: Monad m => PiDefs -> NameId -> StdNFTerm -> m (StdFactor, [PiTerm], NameId, StdNFTerm) allUnfoldRedex pdefs nextFree (StdNF ps) = optUnf ([], Set.empty, [], nextFree, ps) $ MSet.distinctElems ps -- altern: elems => eager where optUnf ([], _, _, _, _) [] = fail "No unfoldable redex" optUnf (redexes, fnames, reacta, nextfr, context) [] = return (StdFactor {seqTerm=paralls redexes, restrNames=fnames}, reacta, nextfr, StdNF context) optUnf acc@(redexes, fnames, reacta, nextfr, context) (f:seqs) = let redex = seqTerm f in case getUnfolded pdefs nextfr redex of Nothing -> optUnf acc seqs Just (reactum, free) -> optUnf (redex:redexes, Set.union fnames (restrNames f), reactum:reacta, max free nextfr, MSet.delete f context) seqs getUnfolded :: Monad m => PiDefs -> NameId -> PiTerm -> m (PiTerm, NameId) getUnfolded pdefs nextFree (PiCall pvar args) = -- no need to check arity here: they have been checked by the name resolver case getDef pdefs pvar of Just (formArgs, proc) -> let (proc', free) = refreshWith nextFree (Set.fromList formArgs) proc in return (applySub (mkSubst $ zip formArgs args) $ proc', free) Nothing -> fail $ "No definition found for " ++ show pvar -- questionable: here we choose to make undefined calls just deadlock -- error $ "No definition found for " ++ show pvar getUnfolded pdefs nextFree (Bang p) = let (p', f) = refresh nextFree p in return (parall p' (Bang p), f) getUnfolded _ _ _ = fail "Not unfoldable redex" match (In x xs, _) (Out y ys, _) | x == y && length xs == length ys = [mkSubst $ zip xs ys] match a@(Out _ _, _) b@(In _ _, _) = match b a -- just to avoid code duplication match _ _ = []
bordaigorl/jamesbound
src/Language/PiCalc/Semantics/Process.hs
gpl-2.0
8,345
0
18
2,060
2,914
1,602
1,312
152
4
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Vim.ExMap -- License : GPL-2 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- I'm a module waiting for some kind soul to give me a commentary! module Yi.Keymap.Vim.ExMap (defExMap) where import Control.Applicative import Control.Monad (when) import Data.Char (isSpace) import Data.Maybe (fromJust) import Data.Monoid import qualified Data.Text as T import System.FilePath (isPathSeparator) import Yi.Buffer.Adjusted hiding (Insert) import Yi.Editor import Yi.History import Yi.Keymap import Yi.Keymap.Vim.Common import Yi.Keymap.Vim.Ex import Yi.Keymap.Vim.StateUtils import Yi.Keymap.Vim.Utils import qualified Yi.Rope as R import Yi.String defExMap :: [EventString -> Maybe ExCommand] -> [VimBinding] defExMap cmdParsers = [ exitBinding , completionBinding cmdParsers , finishBindingY cmdParsers , finishBindingE cmdParsers , failBindingE , historyBinding , printable ] completionBinding :: [EventString -> Maybe ExCommand] -> VimBinding completionBinding commandParsers = VimBindingY f where f "<Tab>" (VimState { vsMode = Ex }) = WholeMatch $ do commandString <- Ev . R.toText <$> withCurrentBuffer elemsB case evStringToExCommand commandParsers commandString of Just cmd -> complete cmd Nothing -> return () return Drop f _ _ = NoMatch complete :: ExCommand -> YiM () complete cmd = do possibilities <- cmdComplete cmd case possibilities of [] -> return () (s:[]) -> updateCommand s ss -> do let s = commonTPrefix' ss updateCommand s printMsg . T.unwords . fmap (dropToLastWordOf s) $ ss updateCommand :: T.Text -> YiM () updateCommand s = do withCurrentBuffer $ replaceBufferContent (R.fromText s) withEditor $ do historyPrefixSet s modifyStateE $ \state -> state { vsOngoingInsertEvents = Ev s } -- | TODO: verify whether 'T.split' works fine here in place of -- @split@'s 'splitWhen'. If something breaks then you should use -- 'splitWhen' + 'T.pack'/'T.unpack'. dropToLastWordOf :: T.Text -> T.Text -> T.Text dropToLastWordOf s = case reverse . T.split isWordSep $ s of [] -> id [_] -> id _ : ws -> T.drop . succ . T.length . T.unwords $ ws where isWordSep :: Char -> Bool isWordSep c = isPathSeparator c || isSpace c exitEx :: Bool -> EditorM () exitEx success = do when success historyFinish resetCountE switchModeE Normal closeBufferAndWindowE exitBinding :: VimBinding exitBinding = VimBindingE f where f "<CR>" (VimState { vsMode = Ex, vsOngoingInsertEvents = Ev "" }) = WholeMatch action f evs (VimState { vsMode = Ex }) = action <$ matchFromBool (evs `elem` ["<Esc>", "<C-c>"]) f _ _ = NoMatch action = exitEx False >> return Drop finishBindingY :: [EventString -> Maybe ExCommand] -> VimBinding finishBindingY commandParsers = VimBindingY f where f evs state = finishAction commandParsers exEvalY <$ finishPrereq commandParsers (not . cmdIsPure) evs state finishBindingE :: [EventString -> Maybe ExCommand] -> VimBinding finishBindingE commandParsers = VimBindingE f where f evs state = finishAction commandParsers exEvalE <$ finishPrereq commandParsers cmdIsPure evs state finishPrereq :: [EventString -> Maybe ExCommand] -> (ExCommand -> Bool) -> EventString -> VimState -> MatchResult () finishPrereq commandParsers cmdPred evs s = matchFromBool . and $ [ vsMode s == Ex , evs `elem` ["<CR>", "<C-m>"] , case evStringToExCommand commandParsers (vsOngoingInsertEvents s) of Just cmd -> cmdPred cmd _ -> False ] finishAction :: MonadEditor m => [EventString -> Maybe ExCommand] -> ([EventString -> Maybe ExCommand] -> EventString -> m ()) -> m RepeatToken finishAction commandParsers execute = do s <- withEditor $ withCurrentBuffer elemsB withEditor $ exitEx True execute commandParsers (Ev $ R.toText s) -- TODO return Drop failBindingE :: VimBinding failBindingE = VimBindingE f where f evs s | vsMode s == Ex && evs == "<CR>" = WholeMatch $ do exitEx False state <- getEditorDyn printMsg . _unEv $ "Not an editor command: " <> vsOngoingInsertEvents state return Drop f _ _ = NoMatch printable :: VimBinding printable = VimBindingE f where f evs (VimState { vsMode = Ex }) = WholeMatch $ editAction evs f _ _ = NoMatch historyBinding :: VimBinding historyBinding = VimBindingE f where f evs (VimState { vsMode = Ex }) | evs `elem` fmap fst binds = WholeMatch $ do fromJust $ lookup evs binds command <- withCurrentBuffer elemsB modifyStateE $ \state -> state { vsOngoingInsertEvents = Ev $ R.toText command } return Drop f _ _ = NoMatch binds = [ ("<Up>", historyUp) , ("<C-p>", historyUp) , ("<Down>", historyDown) , ("<C-n>", historyDown) ] editAction :: EventString -> EditorM RepeatToken editAction (Ev evs) = do withCurrentBuffer $ case evs of "<BS>" -> bdeleteB "<C-h>" -> bdeleteB "<C-w>" -> do r <- regionOfPartNonEmptyB unitViWordOnLine Backward deleteRegionB r "<C-r>" -> return () -- TODO "<lt>" -> insertB '<' "<Del>" -> deleteB Character Forward "<Left>" -> moveXorSol 1 "<C-b>" -> moveXorSol 1 "<Right>" -> moveXorEol 1 "<C-f>" -> moveXorEol 1 "<Home>" -> moveToSol "<C-a>" -> moveToSol "<End>" -> moveToEol "<C-e>" -> moveToEol "<C-u>" -> moveToSol >> deleteToEol "<C-k>" -> deleteToEol evs' -> case T.length evs' of 1 -> insertB $ T.head evs' _ -> error $ "Unhandled event " ++ show evs' ++ " in ex mode" command <- R.toText <$> withCurrentBuffer elemsB historyPrefixSet command modifyStateE $ \state -> state { vsOngoingInsertEvents = Ev command } return Drop
atsukotakahashi/wi
src/library/Yi/Keymap/Vim/ExMap.hs
gpl-2.0
6,565
0
18
1,942
1,794
907
887
157
18
-- Copyright (c) 2011 - All rights reserved - Keera Studios module Physics.Collisions where import Control.Applicative import Control.Arrow import Data.Maybe import FRP.Yampa.VectorSpace import Physics.TwoDimensions.Dimensions import Physics.Shapes import Data ( pointX, rotateRespect, unrotateRespect , minimumWith, swap ) circleAABBOverlap :: Circle -> AABB -> Bool circleAABBOverlap c@(cp,cr) (rp, rs) = circleAABBOverlap' ((0,0), cr) (rp ^-^ cp, rs) circleAABBOverlap' :: Circle -> AABB -> Bool circleAABBOverlap' ((p1x,p1y),r1) (p2@(p2x, p2y), s2@(w2, h2)) = overlapX && overlapY && overlapP11 && overlapP12 && overlapP21 && overlapP22 where -- Square coordinates p211@(p211x, p211y) = p2 ^-^ s2 p212@(p212x, p212y) = p2 ^+^ (-w2, h2) p221@(p221x, p221y) = p2 ^+^ (w2, -h2) p222@(p222x, p222y) = p2 ^+^ s2 -- Horizontal projection overlap overlapX = (-r1, r1) `overlapSegment` (p2x - w2, p2x + w2) overlapY = (-r1, r1) `overlapSegment` (p2y - h2, p2y + h2) rectangleVertices = [p211, p212, p221, p222] rotatedP211 = map (fst.rotateRespect p211) rectangleVertices rotatedP212 = map (fst.rotateRespect p212) rectangleVertices rotatedP221 = map (fst.rotateRespect p221) rectangleVertices rotatedP222 = map (fst.rotateRespect p222) rectangleVertices projection ps = (minimum ps, maximum ps) overlapP11 = (-r1, r1) `overlapSegment` projection rotatedP211 overlapP12 = (-r1, r1) `overlapSegment` projection rotatedP212 overlapP21 = (-r1, r1) `overlapSegment` projection rotatedP221 overlapP22 = (-r1, r1) `overlapSegment` projection rotatedP222 overlapSegment (x01,x02) (x11, x12) = min x02 x12 > max x01 x11 -- * Colision detection responseCircleAABB :: Circle -> AABB -> Maybe Pos2D responseCircleAABB c@(cp,cr) (rp, rs) = responseCircleAABB' ((0,0), cr) (rp ^-^ cp, rs) responseCircleAABB' :: Circle -> AABB -> Maybe Pos2D responseCircleAABB' ((p1x,p1y),r1) (p2@(p2x, p2y), s2@(w2, h2)) | all isJust overlaps = (Just . snd) $ minimumWith (abs.fst) $ map fromJust overlaps | otherwise = Nothing where overlaps = [ overlapX, overlapY , overlapP11, overlapP12 , overlapP21, overlapP22 ] -- Square coordinates p211@(p211x, p211y) = p2 ^-^ s2 p212@(p212x, p212y) = p2 ^+^ (-w2, h2) p221@(p221x, p221y) = p2 ^+^ (w2, -h2) p222@(p222x, p222y) = p2 ^+^ s2 -- Horizontal projection overlap overlapX = (pointX &&& id) <$> (-r1, r1) `overlapSegment` (p2x - w2, p2x + w2) overlapY = (pointX &&& swap) <$> (-r1, r1) `overlapSegment` (p2y - h2, p2y + h2) rectangleVertices = [p211, p212, p221, p222] rotatedP211 = map (rotateRespect p211) rectangleVertices rotatedP212 = map (rotateRespect p212) rectangleVertices rotatedP221 = map (rotateRespect p221) rectangleVertices rotatedP222 = map (rotateRespect p222) rectangleVertices xProjection = (minimum &&& maximum) . map pointX circleOverlaps = overlapSegment (-r1, r1) overlapP11 = (pointX &&& unrotateRespect p211) <$> circleOverlaps (xProjection rotatedP211) overlapP12 = (pointX &&& unrotateRespect p212) <$> circleOverlaps (xProjection rotatedP212) overlapP21 = (pointX &&& unrotateRespect p221) <$> circleOverlaps (xProjection rotatedP221) overlapP22 = (pointX &&& unrotateRespect p222) <$> circleOverlaps (xProjection rotatedP222) overlapSegment (x01,x02) (x11, x12) | segmentLength' > 0 = Just (segmentLength, 0) | otherwise = Nothing where segmentLength = if x01 < x11 then -segmentLength' else segmentLength' segmentLength' = if segmentLength'' == 0 then 1 else segmentLength'' segmentLength'' = min x02 x12 - max x01 x11 responseAABB2 :: AABB -> AABB -> Maybe Pos2D responseAABB2 (pos1, size1) (pos2, size2) | overlap && overlapx > overlapy = Just cy | overlap && overlapy > overlapx = Just cx | overlap = Just (cx ^+^ cy) | otherwise = Nothing where (x1,y1) = pos1 (w1,h1) = size1 (x2,y2) = pos2 (w2,h2) = size2 toRight = x1 > x2 toLeft = x1 < x2 above = y1 < y2 below = y1 > y2 overlapx = max 0 (w1 + w2 - abs (x1 - x2)) overlapy = max 0 (h1 + h2 - abs (y1 - y2)) overlap = overlapx > 0 && overlapy > 0 cx = if toRight then (overlapx, 0) else (-overlapx, 0) cy = if above then (0, -overlapy) else (0, overlapy) (x1,y1) ^+^ (x2,y2) = (x1+x2, y1+y2) overlapsAABB2 :: AABB -> AABB -> Bool overlapsAABB2 (pos1, size1) (pos2, size2) = abs (x1 - x2) < w1 + w2 && abs (y1 - y2) < h1 + h2 where (x1,y1) = pos1 (w1,h1) = size1 (x2,y2) = pos2 (w2,h2) = size2
keera-studios/pang-a-lambda
src/Physics/Collisions.hs
gpl-3.0
4,931
0
12
1,284
1,803
1,009
794
94
3