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
module Main where import System.Environment (getArgs) main :: IO () main = do [arg] <- getArgs putStrLn $ reverse $ takeWhile (/= '/') $ reverse arg
tyoko-dev/coreutils-haskell
src/basename.hs
agpl-3.0
160
0
10
37
64
34
30
5
1
-- | Parsing of callbacks. module Data.GI.GIR.Callback ( Callback(..) , parseCallback ) where import Data.GI.GIR.Parser import Data.GI.GIR.Callable (Callable, parseCallable) data Callback = Callback Callable deriving Show parseCallback :: Parser (Name, Callback) parseCallback = do name <- parseName callable <- parseCallable return (name, Callback callable)
hamishmack/haskell-gi
lib/Data/GI/GIR/Callback.hs
lgpl-2.1
384
0
9
69
103
61
42
12
1
module CLTerm( assignType, baseCombinators, val, com, CLTerm.ap, var, con, func, base, int, float, char) where import Control.Monad hiding (ap) import Data.List as L import Data.Map as M import Data.Set as S import ErrorHandling data CLTerm a = Val a | Com String | Ap (CLTerm a) (CLTerm a) deriving (Eq, Ord) instance Show a => Show (CLTerm a) where show (Val a) = show a show (Com name) = name show (Ap l r) = "(" ++ show l ++ show r ++ ")" val = Val com = Com ap = Ap data Type = Var String | Base String | Con String Int [Type] deriving (Ord) instance Eq Type where (==) (Var n1) (Var n2) = n1 == n2 (==) (Base n1) (Base n2) = n1 == n2 (==) (Con n1 a1 _) (Con n2 a2 _) = n1 == n2 && a1 == a2 (==) _ _ = False instance Show Type where show (Var name) = name show (Base name) = name show (Con "->" 2 [x, y]) = "(" ++ show x ++ " -> " ++ show y ++ ")" show (Con n _ params) = n ++ " " ++ (L.concat $ L.intersperse " " $ L.map show params) var = Var con = Con base = Base func = Con "->" 2 allVars :: Type -> [Type] allVars (Base _) = [] allVars (Var n) = [Var n] allVars (Con _ _ params) = L.nub $ L.concat $ L.map allVars params class Typeable a where getType :: a -> Type assignType :: (Typeable a) => Map String Type -> CLTerm a -> Error Type assignType comTypes term = failOrType where rootTypeVar = "t0" constraints = typeConstraints comTypes rootTypeVar term unifier = constraints >>= unify failOrType = liftM (\sub -> prettyTypeVars $ applySubstitution sub (var rootTypeVar)) unifier prettyTypeVars :: Type -> Type prettyTypeVars t = applySubstitution uglyVarsToPrettyVars t where varsInType = allVars t prettyVars = take (length varsInType) (L.map var (L.map (:[]) ['a'..'z'])) uglyVarsToPrettyVars = case length varsInType > 25 of True -> error $ "MORE THAN 25 VARS IN TYPE EXPRESSION" False -> M.fromList $ zip varsInType prettyVars baseCombinators = M.fromList [("I", func [var "o", var "o"]), ("K", func [var "o", func [var "t", var "o"]]), ("S", func [func [var "p", func [var "o", var "t"]], func [func [var "p", var "o"], func [var "p", var "t"]]])] -- Basic datatypes for language data BasicT = INT Int | FLOAT Float | CHAR Char deriving (Eq, Ord, Show) instance Typeable BasicT where getType (INT _) = Base "INT" getType (FLOAT _) = Base "FLOAT" getType (CHAR _) = Base "CHAR" int = INT float = FLOAT char = CHAR -- Type checking type TypeConstraint = (Type, Type) type TypeSubstitution = Map Type Type typeConstraint :: Type -> Type -> TypeConstraint typeConstraint t1 t2 = (t1, t2) replaceSub :: Type -> Type -> TypeSubstitution -> TypeSubstitution replaceSub t1 t2 sub = M.mapKeys (replaceBy t1 t2) (M.map (replaceBy t1 t2) sub) replaceTC :: Type -> Type -> TypeConstraint -> TypeConstraint replaceTC t1 t2 (x, y) = (replaceBy t1 t2 x, replaceBy t1 t2 y) replaceBy :: Type -> Type -> Type -> Type replaceBy t1 t2 x = case x == t1 of True -> t2 False -> case x of (Con a n params) -> Con a n (L.map (replaceBy t1 t2) params) _ -> x typeConstraints :: (Typeable a) => Map String Type -> String -> CLTerm a -> Error [TypeConstraint] typeConstraints _ tv (Val v) = Succeeded [typeConstraint (var tv) (getType v)] typeConstraints comTypes tv (Com name) = case M.lookup name comTypes of Just t -> Succeeded [typeConstraint (var tv) (uniqueTypeVars tv t)] Nothing -> Failed $ "Unrecognized combinator " ++ name typeConstraints comTypes tv (Ap l r) = liftM2 (++) (Succeeded thisTC) (liftM2 (++) leftTC rightTC) where leftTV = tv ++ "0" rightTV = tv ++ "1" thisTC = [typeConstraint (var leftTV) (func [var rightTV, var tv])] leftTC = typeConstraints comTypes leftTV l rightTC = typeConstraints comTypes rightTV r uniqueTypeVars :: String -> Type -> Type uniqueTypeVars uniquePrefix (Var n) = Var (n ++ uniquePrefix) uniqueTypeVars uniquePrefix (Con n a params) = Con n a $ L.map (uniqueTypeVars uniquePrefix) params uniqueTypeVars _ t = t unify :: [TypeConstraint] -> Error TypeSubstitution unify constraints = unf M.empty constraints unf :: TypeSubstitution -> [TypeConstraint] -> Error TypeSubstitution unf sub [] = Succeeded sub unf sub ((Base n1, Base n2):tcs) = case n1 == n2 of True -> unf sub tcs False -> unificationError (Base n1) (Base n2) unf sub ((t1@(Var n1), t2@(Var n2)):tcs) = case t1 == t2 of True -> unf sub tcs False -> unf newSub newTCS where newSub = (M.insert t2 t1 (replaceSub t2 t1 (M.insert t1 t2 (replaceSub t1 t2 sub)))) newTCS = replaceInTCS t2 t1 (replaceInTCS t1 t2 tcs) unf sub ((t1@(Var n1), t2):tcs) = case t1 == t2 of True -> unf sub tcs False -> unf newSub newTCS where newSub = M.insert t1 t2 (replaceSub t1 t2 sub) newTCS = replaceInTCS t1 t2 tcs unf sub ((t1, Var n):tcs) = unf newSub newTCS where newSub = M.insert (Var n) t1 (replaceSub (Var n) t1 sub) newTCS = replaceInTCS (Var n) t1 tcs unf sub ((Con n1 a1 p1, Con n2 a2 p2):tcs) = case (Con n1 a1 p1) == (Con n2 a2 p2) of True -> unf sub (zip p1 p2 ++ tcs) False -> unificationError (Con n1 a1 p1) (Con n2 a2 p2) unf _ ((t1, t2):tcs) = unificationError t1 t2 replaceInTCS :: Type -> Type -> [TypeConstraint] -> [TypeConstraint] replaceInTCS t1 t2 tcs = L.map (replaceTC t1 t2) tcs unificationError :: Type -> Type -> Error TypeSubstitution unificationError t1 t2 = Failed $ "Cannot unify types " ++ show t1 ++ " and " ++ show t2 applySubstitution :: TypeSubstitution -> Type -> Type applySubstitution sub (Con name arity params) = Con name arity (L.map (applySubstitution sub) params) applySubstitution sub v = case M.lookup v sub of Just s -> applySubstitution (M.delete v sub) s Nothing -> v
dillonhuff/CLP
src/CLTerm.hs
lgpl-3.0
6,040
0
15
1,544
2,593
1,336
1,257
132
5
-- # LANGUAGE OverloadedStrings # import Data.Aeson import Data.Aeson.Lens import Control.Lens -- this code is intended for ghci experimentation, so we use "let" to bind a value to a name jsonBlob = "[{\"someObject\": {\"version\": [1, 0, 3]}}]" -- example from above myVal = jsonBlob ^? nth 0 . key "someObject" . key "version" . nth 1 -- What progressively composing the prisms looks like, note the composition order: -- λ> jsonBlob ^? nth 0 Just (Object fromList [("someObject", Object fromList [("version",Array (fromList [Number 1.0, Number 0.0, Number 3.0]))])]) -- λ> jsonBlob ^? nth 0 . key "someObject" Just (Object fromList [("version", Array (fromList [Number 1.0, Number 0.0, Number 3.0]))]) -- λ> jsonBlob ^? nth 0 . key "someObject" . key "version" Just (Array (fromList [Number 1.0, Number 0.0, Number 3.0])) -- λ> jsonBlob ^? nth 0 . key "someObject" . key "version" . nth 1 Just (Number 0.0)
gmp26/panda
Experimental/AesonLens.hs
lgpl-3.0
975
0
17
210
225
116
109
-1
-1
module Data.P440.Domain.PB where import Data.P440.Domain.SimpleTypes import Data.Text (Text) -- 3.2 Подтверждение data Файл = Файл { идЭС :: GUID ,типИнф :: Text ,версПрог :: Text ,телОтпр :: Text ,должнОтпр :: Text ,фамОтпр :: Text ,версФорм :: Text ,подбнпринт :: ПОДБНПРИНТ } deriving (Eq, Show) data ПОДБНПРИНТ = ПОДБНПРИНТ { имяФайла :: Text ,датаВремяПроверки :: DateTime ,результат :: [Результат] } deriving (Eq, Show) data Результат = Результат { кодРезПроверки :: Text ,пояснение :: Maybe Text ,кодРекв :: Maybe Text ,значРекв :: Maybe Text } deriving (Eq, Show)
Macil-dev/p440
src/Data/P440/Domain/PB.hs
unlicense
906
36
7
211
468
254
214
24
0
import Data.List import System.IO import Control.Monad(when) import System.Exit import System.Environment(getArgs) main :: IO () main = do -- load the command line arguments args <- getArgs when (length args /= 2) $ do putStrLn "Syntax: passwd-a1 filename uid" exitFailure content <- readFile (args !! 0) let username = findByUID content (read (args !! 1)) case username of Just x -> putStrLn x Nothing-> putStrLn "Could not find that UID" findByUID :: String -> Integer -> Maybe String findByUID content uid = let a1 = map parseline . lines $ content in lookup uid a1 parseline :: String -> (Integer, String) parseline input = let fields = split ':' input in (read (fields !! 2), fields !! 0) split :: Eq a => a -> [a] -> [[a]] split _ [] = [] split delim str = let (before, reminder) = span (/= delim) str in before : case reminder of [] -> [] x -> split delim (tail x)
EricYT/real-world
src/chapter-13/passwd-a1.hs
apache-2.0
1,017
1
14
304
396
194
202
32
2
module Parse (parseProgram) where import Control.Monad import Control.Applicative import Data.Char import Text.Parsec (parse, ParseError, try) import Text.Parsec.Char import Text.Parsec.Combinator import Text.Parsec.Expr import Text.Parsec.String (Parser) import Text.Parsec.Token (reservedOp) import qualified Data.Map as M import Expressions -- ================================================================================== err = error "Parsing error" simpleParse p = parse p err betterParse :: Parser a -> String -> Either ParseError a betterParse p = parse (spaces *> p) err infixr 5 <:> (<:>) :: Applicative f => f a -> f [a] -> f [a] a <:> b = (:) <$> a <*> b -- parser to consume the spaces after it token :: Parser a -> Parser a token = (<* spaces) symbol :: Char -> Parser Char symbol = token . char -- parses a single word word :: Parser String word = many1 (alphaNum <|> char '$' <|> char '.') -- reads in c1<this>c2 parserWrapped :: Char -> Char -> Parser a -> Parser a parserWrapped c1 c2 = between (symbol c1) (symbol c2) -- Some helper functions brackets :: Parser a -> Parser a brackets = parserWrapped '[' ']' parserQuot :: Parser a -> Parser a parserQuot = parserWrapped '"' '"' inParens :: Parser a -> Parser a inParens = parserWrapped '(' ')' -- =========================================================== -- parses a variable, needs to start with a letter pVariable :: Parser Expr pVariable = Expr <$> (token $ letter <:> many alphaNum) myNone :: String -> Parser String myNone s = many1 $ noneOf s -- everything except quotes anyThing :: Parser String anyThing = myNone "\"" pStringInQuotes :: Parser String pStringInQuotes = parserQuot anyThing pString :: Parser Expr pString = Expr <$> (token $ pStringInQuotes <|> word) pCmdArgs :: Parser [Expr] pCmdArgs = many (pString) pStream :: String -> Parser Expr pStream name = Expr <$> string name *> spaces *> pString pReadS = pStream "<" pWriteS = pStream ">" pAppendS = pStream ">>" pCmd' :: Parser Cmd pCmd' = do n <- pString args <- pCmdArgs r <- optionMaybe pReadS a' <- optionMaybe $ try pAppendS w' <- optionMaybe pWriteS end <- symbol ';' let (w,a) = resolve w' a' return $ Cmd n args r w a where resolve w a = case w of Just p -> (Just p, False) Nothing -> case a of Just p -> (Just p, True) Nothing -> (Nothing, False) pCmd = (try pAtoC) <|> pCmd' -- =================================================================================== pAssign :: Parser Assign pAssign = Assign <$> pVariable <*> ( symbol '=' *> pString) <* symbol ';' pAtoC :: Parser Cmd pAtoC = do (Assign var val) <- pAssign return $ Cmd (Expr "assign") [var,val] Nothing Nothing False pComment :: Parser Comment pComment = Comment <$> (char '#' *> myNone "\n" <* spaces) string' :: String -> Parser String string' = token . string compTable :: [Parser Comp] compTable = zipWith binary ["==","/=",">=",">", "<=","<"] $ [CEQ, CNE, CGE, CGT, CLE, CLT] where binary name f = f <$> pString <*> (rest name) rest name = string' name *> pString pComp :: Parser Comp pComp = choice $ map try compTable compOp name f = Infix (f <$ (string' name)) AssocLeft compAnd = compOp "&&" And compOr = compOp "||" Or compNot = Prefix (Not <$ (symbol '!')) predTable = [[compNot], [compAnd], [compOr]] pPred' :: Parser Pred pPred' = Pred <$> pComp inParensPred :: Parser Pred inParensPred = inParens pPred' pPred :: Parser Pred pPred = buildExpressionParser predTable parser' where parser' = inParensPred <|> pPred' pCmdBlock :: Parser [Cmd] pCmdBlock = parserWrapped '{' '}' p <|> p where p = many $ spaces *> pCmd pCond :: Parser Conditional pCond = do string' "if" p <- pPred t <- pCmdBlock spaces e' <- optionMaybe $ string' "else" >> pCmdBlock return $ case e' of Nothing -> If p t Just e -> IfElse p t e pWhile :: Parser Loop pWhile = string' "while" >> pPred >>= \p -> pCmdBlock >>= return . While p pDoWhile :: Parser Loop pDoWhile = string' "do" >> pCmdBlock >>= f where f b = string' "while" >> pPred <* symbol ';' >>= return . flip DoWhile b pFor :: Parser Loop pFor = do string' "for" symbol '(' i <- pAssign spaces c <- pPred symbol ';' spaces s <- pAssign symbol ')' For i c s <$> pCmdBlock pLoop :: Parser Loop pLoop = choice [pWhile, pDoWhile, pFor] pTLExpr :: Parser TLExpr pTLExpr = choice $ map try [ TLCmt <$> pComment , TLCnd <$> pCond , TLClp <$> pLoop , TLCmd <$> pCmd ] parser :: Parser [TLExpr] parser = many1 pTLExpr parseProgram :: String -> Either ParseError [TLExpr] parseProgram = betterParse parser s = concat [ "do {" , " rmdir a;" , " mkdir b;" , "} while (a>b);" ] s1 = concat [ "for ( i=1 ; i<2; i=2 ) {\n" , "some cmd;" , "}" ] s2 = concat [ "while a==1 && b==2 {" , "echo uspjelo;" , "a = 2;\n" , "}" ]
filiphrenic/hash
Parse.hs
apache-2.0
5,142
0
14
1,293
1,744
895
849
147
3
{-# LANGUAGE RecordWildCards, ScopedTypeVariables, TemplateHaskell #-} module TH.FFI ( generateFFI , generateFFIs ) where import Control.Applicative ((<$>)) import Data.Char import Data.Monoid ((<>)) import Foreign.Marshal.Utils import Foreign.Ptr (Ptr) import Foreign.Storable (Storable(..)) import Language.Haskell.TH (Body(..), Callconv(..), Dec(..), Exp(..), Foreign(..), Pat(..), Q, Type(..), mkName, runIO) import Language.Haskell.TH.Syntax (Name(..), OccName(..)) import Control.Monad.Trans.API (runAPIT) import Data.List (intercalate) import Data.Settings.YQL import Data.State.YQL import Data.TH.API import Data.TH.FFI import FFI.Data.Settings.YQL () import Helper.Name data State = State instance YQLState State where generateFFIs :: [API] -> Q [FFI] generateFFIs apis = do wrappers <- sequence $ generateFFIWrapper <$> apis cppWrappers <- sequence $ generateFFICppWrapper <$> apis runIO $ do writeHeaderFile wrappers writeCppHeaderFile cppWrappers sequence $ generateFFI <$> apis generateFFI :: API -> Q FFI generateFFI api = do let cc = camelCase . apiName $ api base = (toLower . head $ cc):(tail cc) inType = apiInputType . apiInput $ api outType = apiOutputType . apiOutput $ api let name = mkName $ base ffiName = mkName $ base <> "_ffi" ffiT = AppT (AppT ArrowT (AppT (ConT ''Ptr) (ConT ''YQLSettings))) (AppT (AppT ArrowT (AppT (ConT ''Ptr) inType)) (AppT (ConT ''IO) (AppT (ConT ''Ptr) (AppT (ConT ''Maybe) outType)))) ffiSig = SigD ffiName ffiT ffiRun <- [| \pipe ptrSettings ptrInput -> do settings <- peek ptrSettings input <- peek ptrInput let action = pipe settings input ret <- fst <$> runAPIT State action new ret |] let ffiBody = AppE ffiRun (VarE name) let ffiDec = ValD (VarP ffiName) (NormalB ffiBody) [] ffiE = ForeignD $ ExportF CCall (show ffiName) ffiName ffiT return $ FFI ffiSig ffiDec ffiE writeHeaderFile :: [String] -> IO () writeHeaderFile funs = do let ifndef = "#ifndef API_DEFINE_API\n" ++ "#define API_DEFINE_API\n" include = "#include <TH/FFIs_stub.h>\n" ++ "#include \"array.h\"\n" ++ "#include \"ghc.h\"\n" ++ "#include \"maybe.h\"\n" ++ "#include \"types.h\"\n" ++ "#include \"void.h\"\n" ++ "#include \"yql.h\"\n" endif = "#endif" header = intercalate "\n" [ ifndef , include , intercalate "\n" funs , endif ] writeFile "ffi/c/lib/api.h" header generateFFIWrapper :: API -> Q String generateFFIWrapper api = do let cc = camelCase . apiName $ api base = (toLower . head $ cc):(tail cc) (ConT (Name (OccName inName) _)) = apiInputType . apiInput $ api (ConT (Name (OccName outName) _)) = apiOutputType . apiOutput $ api let name = base ffiName = base <> "_ffi" return $ "Maybe * " ++ name ++ "(YQLSettings *settings, " ++ inName ++ " *input) " ++ " { return (Maybe *)" ++ ffiName ++ "(settings, input);" ++ " };\n" writeCppHeaderFile :: [String] -> IO () writeCppHeaderFile funs = do let ifndef = "#ifndef API_DEFINE_API\n" ++ "#define API_DEFINE_API\n" include = "#include <TH/FFIs_stub.h>\n" ++ "#include \"array.hpp\"\n" ++ "#include \"ghc.hpp\"\n" ++ "#include \"maybe.hpp\"\n" ++ "#include \"types.hpp\"\n" ++ "#include \"void.hpp\"\n" ++ "#include \"yql.hpp\"\n" endif = "#endif" header = intercalate "\n" [ ifndef , include , intercalate "\n" funs , endif ] writeFile "ffi/cpp/lib/api.hpp" header generateFFICppWrapper :: API -> Q String generateFFICppWrapper api = do let cc = camelCase . apiName $ api base = (toLower . head $ cc):(tail cc) (ConT (Name (OccName inName) _)) = apiInputType . apiInput $ api (ConT (Name (OccName outName) _)) = apiOutputType . apiOutput $ api let name = base ffiName = base <> "_ffi" return $ "Maybe<" ++ outName ++ "> * " ++ name ++ "(YQLSettings *settings, " ++ inName ++ " *input) " ++ " { return (Maybe<" ++ outName ++ "> *)" ++ ffiName ++ "(settings, input);" ++ " };\n"
fabianbergmark/APIs
src/TH/FFI.hs
bsd-2-clause
4,581
0
21
1,382
1,276
676
600
111
1
-- | Provides the application model. module ApplicationModel ( RectangleData(..) ) where -- | Represents data of the rectangle. data RectangleData = RectangleData Int Int
fujiyan/toriaezuzakki
haskell/glfw/keyboard/ApplicationModel.hs
bsd-2-clause
181
0
6
35
26
17
9
3
0
-- case expression 和 patterm matching head' :: [a] -> a head' [] = error "Empty lists" head' (x: _) = x headcase' :: [a] -> a headcase' xs = case xs of [] -> error "empty lists" (x: _) -> x -- case vs pattern-matching 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."
sharkspeed/dororis
languages/haskell/LYHGG/4-syntax-in-functions/5-case-expression.hs
bsd-2-clause
667
2
10
254
203
106
97
-1
-1
module HLearn.Models.Distributions.ParticleFunctor where import Control.Monad.Random import qualified Data.Vector as V import GHC.TypeLits import HLearn.Algebra import HLearn.Models.Distributions.Common ------------------------------------------------------------------------------- -- data types newtype ParticleFunctor (seed::Nat) (n::Nat) dp = ParticleFunctor { datapoints :: V.Vector dp } deriving (Read,Show,Eq,Ord,Functor) mkFunctor :: ------------------------------------------------------------------------------- -- algebra
ehlemur/HLearn
src/HLearn/Models/Distributions/Experimental/ParticleFunctor.hs
bsd-3-clause
565
1
9
72
102
67
35
-1
-1
module Development.GCCXML.Declarations.Templates where import qualified PatternParser as P callParser = P.Parser '(' ')' ',' isCallInvocation :: String -> Bool isInstantiation = P.hasPattern callParser name :: String -> Bool name = P.name callParser args :: String -> [String] args = P.args callParser split :: String -> (String, [String]) split = P.split templateParser splitRecursive :: String -> [(String, [String])] splitRecursive = P.splitRecursive templateParser join :: String -> [String] join x y = P.join templateParser x y Nothing
avaitla/Haskell-to-C---Bridge
src/GCCXML/Declarations/CallInvocation.hs
bsd-3-clause
550
0
8
84
180
101
79
15
1
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE Safe #-} {- | Module : Physics.Learn.CompositeQuadrature Copyright : (c) Scott N. Walck 2012-2018 License : BSD3 (see LICENSE) Maintainer : Scott N. Walck <walck@lvc.edu> Stability : experimental Composite Trapezoid Rule and Composite Simpson's Rule -} module Physics.Learn.CompositeQuadrature ( compositeTrapezoid , compositeSimpson ) where import Data.VectorSpace ( VectorSpace , Scalar , (^+^) , (*^) , zeroV ) -- | Composite Trapezoid Rule compositeTrapezoid :: (VectorSpace v, Fractional (Scalar v)) => Int -- ^ number of intervals (one less than the number of function evaluations) -> Scalar v -- ^ lower limit -> Scalar v -- ^ upper limit -> (Scalar v -> v) -- ^ function to be integrated -> v -- ^ definite integral compositeTrapezoid n a b f = let dt = (b - a) / fromIntegral n ts = [a + fromIntegral m * dt | m <- [0..n]] pairs = [(t,f t) | t <- ts] combine [] = error "compositeSimpson: odd number of half-intervals" -- this should never happen combine [_] = zeroV combine ((t0,f0):(t1,f1):ps) = ((t1 - t0) / 2) *^ (f0 ^+^ f1) ^+^ combine ((t1,f1):ps) in combine pairs -- | Composite Simpson's Rule compositeSimpson :: (VectorSpace v, Fractional (Scalar v)) => Int -- ^ number of half-intervals (one less than the number of function evaluations) -> Scalar v -- ^ lower limit -> Scalar v -- ^ upper limit -> (Scalar v -> v) -- ^ function to be integrated -> v -- ^ definite integral compositeSimpson n a b f = let nEven = 2 * div n 2 dt = (b - a) / fromIntegral nEven ts = [a + fromIntegral m * dt | m <- [0..nEven]] pairs = [(t,f t) | t <- ts] combine [] = error "compositeSimpson: odd number of half-intervals" -- this should never happen combine [_] = zeroV combine (_:_:[]) = error "compositeSimpson: odd number of half-intervals" -- this should never happen combine ((t0,f0):(_,f1):(t2,f2):ps) = ((t2 - t0) / 6) *^ (f0 ^+^ 4 *^ f1 ^+^ f2) ^+^ combine ((t2,f2):ps) in combine pairs
walck/learn-physics
src/Physics/Learn/CompositeQuadrature.hs
bsd-3-clause
2,425
0
14
806
630
346
284
42
4
{-# LANGUAGE UndecidableSuperClasses #-} {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE TypeFamilies #-} class A (T a) => A a where type T a -- test1 :: forall a. A a => () -- test1 = () test2 :: A a => proxy a -> () test2 _ = ()
mikeizbicki/homoiconic
old/Bug2.hs
bsd-3-clause
240
0
8
56
63
33
30
-1
-1
{- | Module : XMonad.Actions.Search Description : Easily run Internet searches on web sites through xmonad. Copyright : (C) 2007 Gwern Branwen License : None; public domain Maintainer : <gwern0@gmail.com> Stability : unstable Portability : unportable; depends on XSelection, XPrompt A module for easily running Internet searches on web sites through xmonad. Modeled after the handy Surfraw CLI search tools at <https://secure.wikimedia.org/wikipedia/en/wiki/Surfraw>. Additional sites welcomed. -} module XMonad.Actions.Search ( -- * Usage -- $usage search, SearchEngine(..), searchEngine, searchEngineF, promptSearch, promptSearchBrowser, promptSearchBrowser', selectSearch, selectSearchBrowser, isPrefixOf, escape, use, intelligent, (!>), prefixAware, namedEngine, amazon, alpha, codesearch, deb, debbts, debpts, dictionary, ebay, github, google, hackage, hoogle, images, imdb, lucky, maps, mathworld, openstreetmap, scholar, stackage, thesaurus, wayback, wikipedia, wiktionary, youtube, vocabulary, duckduckgo, multi, -- * Use case: searching with a submap -- $tip -- * Types Browser, Site, Query, Name, Search ) where import Codec.Binary.UTF8.String (encode) import Text.Printf import XMonad (X (), liftIO) import XMonad.Prompt (XPConfig (), XPrompt (showXPrompt, nextCompletion, commandToComplete), getNextCompletion, historyCompletionP, mkXPrompt) import XMonad.Prelude (isAlphaNum, isAscii, isPrefixOf) import XMonad.Prompt.Shell (getBrowser) import XMonad.Util.Run (safeSpawn) import XMonad.Util.XSelection (getSelection) {- $usage This module is intended to allow easy access to databases on the Internet through xmonad's interface. The idea is that one wants to run a search but the query string and the browser to use must come from somewhere. There are two places the query string can come from - the user can type it into a prompt which pops up, or the query could be available already in the X Windows copy\/paste buffer (perhaps you just highlighted the string of interest). Thus, there are two main functions: 'promptSearch', and 'selectSearch' (implemented using the more primitive 'search'). To each of these is passed an engine function; this is a function that knows how to search a particular site. For example, the 'google' function knows how to search Google, and so on. You pass 'promptSearch' and 'selectSearch' the engine you want, the browser you want, and anything special they might need; this whole line is then bound to a key of you choosing in your xmonad.hs. For specific examples, see each function. This module is easily extended to new sites by using 'searchEngine'. The currently available search engines are: * 'amazon' -- Amazon keyword search. * 'alpha' -- Wolfram|Alpha query. * 'codesearch' -- Google Labs Code Search search. * 'deb' -- Debian package search. * 'debbts' -- Debian Bug Tracking System. * 'debpts' -- Debian Package Tracking System. * 'dictionary' -- dictionary.reference.com search. * 'ebay' -- Ebay keyword search. * 'github' -- GitHub keyword search. * 'google' -- basic Google search. * 'hackage' -- Hackage, the Haskell package database. * 'hoogle' -- Hoogle, the Haskell libraries API search engine. * 'stackage' -- Stackage, An alternative Haskell libraries API search engine. * 'images' -- Google images. * 'imdb' -- the Internet Movie Database. * 'lucky' -- Google "I'm feeling lucky" search. * 'maps' -- Google maps. * 'mathworld' -- Wolfram MathWorld search. * 'openstreetmap' -- OpenStreetMap free wiki world map. * 'scholar' -- Google scholar academic search. * 'thesaurus' -- thesaurus.com search. * 'wayback' -- the Wayback Machine. * 'wikipedia' -- basic Wikipedia search. * 'youtube' -- Youtube video search. * 'vocabulary' -- Dictionary search * 'duckduckgo' -- DuckDuckGo search engine. * 'multi' -- Search based on the prefix. \"amazon:Potter\" will use amazon, etc. With no prefix searches google. Feel free to add more! -} {- $tip In combination with "XMonad.Actions.Submap" you can create a powerful and easy way to search without adding a whole bunch of bindings. First import the necessary modules: > import qualified XMonad.Prompt as P > import qualified XMonad.Actions.Submap as SM > import qualified XMonad.Actions.Search as S Then add the following to your key bindings: > ... > -- Search commands > , ((modm, xK_s), SM.submap $ searchEngineMap $ S.promptSearch P.def) > , ((modm .|. shiftMask, xK_s), SM.submap $ searchEngineMap $ S.selectSearch) > > ... > > searchEngineMap method = M.fromList $ > [ ((0, xK_g), method S.google) > , ((0, xK_h), method S.hoogle) > , ((0, xK_w), method S.wikipedia) > ] Or in combination with XMonad.Util.EZConfig: > ... > ] -- end of regular keybindings > -- Search commands > ++ [("M-s " ++ k, S.promptSearch P.def f) | (k,f) <- searchList ] > ++ [("M-S-s " ++ k, S.selectSearch f) | (k,f) <- searchList ] > > ... > > searchList :: [(String, S.SearchEngine)] > searchList = [ ("g", S.google) > , ("h", S.hoogle) > , ("w", S.wikipedia) > ] Make sure to set firefox to open new pages in a new window instead of in a new tab: @Firefox -> Edit -> Preferences -> Tabs -> New pages should be opened in...@ Now /mod-s/ + /g/\//h/\//w/ prompts you for a search string, then opens a new firefox window that performs the search on Google, Hoogle or Wikipedia respectively. If you select something in whatever application and hit /mod-shift-s/ + /g/\//h/\//w/ it will search the selected string with the specified engine. Happy searching! -} -- | A customized prompt indicating we are searching, and the name of the site. newtype Search = Search Name instance XPrompt Search where showXPrompt (Search name)= "Search [" ++ name ++ "]: " nextCompletion _ = getNextCompletion commandToComplete _ c = c -- | Escape the search string so search engines understand it. Only -- digits and ASCII letters are not encoded. All non ASCII characters -- which are encoded as UTF8 escape :: String -> String escape = concatMap escapeURIChar escapeURIChar :: Char -> String escapeURIChar c | isAscii c && isAlphaNum c = [c] | otherwise = concatMap (printf "%%%02X") $ encode [c] type Browser = FilePath type Query = String type Site = String -> String type Name = String data SearchEngine = SearchEngine Name Site -- | Given an already defined search engine, extracts its transformation -- function, making it easy to create compound search engines. -- For an instance you can use @use google@ to get a function which -- makes the same transformation as the google search engine would. use :: SearchEngine -> Site use (SearchEngine _ engine) = engine -- | Given a browser, a search engine's transformation function, and a search term, perform the -- requested search in the browser. search :: Browser -> Site -> Query -> X () search browser site query = safeSpawn browser [site query] {- | Given a base URL, create the 'SearchEngine' that escapes the query and appends it to the base. You can easily define a new engine locally using exported functions without needing to modify "XMonad.Actions.Search": > myNewEngine = searchEngine "site" "https://site.com/search=" The important thing is that the site has a interface which accepts the escaped query string as part of the URL. Alas, the exact URL to feed searchEngine varies from site to site, often considerably, so there\'s no general way to cover this. Generally, examining the resultant URL of a search will allow you to reverse-engineer it if you can't find the necessary URL already described in other projects such as Surfraw. -} searchEngine :: Name -> String -> SearchEngine searchEngine name site = searchEngineF name (\s -> site ++ escape s) {- | If your search engine is more complex than this (you may want to identify the kind of input and make the search URL dependent on the input or put the query inside of a URL instead of in the end) you can use the alternative 'searchEngineF' function. > searchFunc :: String -> String > searchFunc s | "wiki:" `isPrefixOf` s = "https://en.wikipedia.org/wiki/" ++ (escape $ tail $ snd $ break (==':') s) > | "https://" `isPrefixOf` s = s > | otherwise = (use google) s > myNewEngine = searchEngineF "mymulti" searchFunc @searchFunc@ here searches for a word in wikipedia if it has a prefix of \"wiki:\" (you can use the 'escape' function to escape any forbidden characters), opens an address directly if it starts with \"https:\/\/\" and otherwise uses the provided google search engine. You can use other engines inside of your own through the 'use' function as shown above to make complex searches. The user input will be automatically escaped in search engines created with 'searchEngine', 'searchEngineF', however, completely depends on the transformation function passed to it. -} searchEngineF :: Name -> Site -> SearchEngine searchEngineF = SearchEngine -- The engines. amazon, alpha, codesearch, deb, debbts, debpts, dictionary, ebay, github, google, hackage, hoogle, images, imdb, lucky, maps, mathworld, openstreetmap, scholar, stackage, thesaurus, vocabulary, wayback, wikipedia, wiktionary, youtube, duckduckgo :: SearchEngine amazon = searchEngine "amazon" "https://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=" alpha = searchEngine "alpha" "https://www.wolframalpha.com/input/?i=" codesearch = searchEngine "codesearch" "https://developers.google.com/s/results/code-search?q=" deb = searchEngine "deb" "https://packages.debian.org/" debbts = searchEngine "debbts" "https://bugs.debian.org/" debpts = searchEngine "debpts" "https://packages.qa.debian.org/" dictionary = searchEngine "dict" "https://dictionary.reference.com/browse/" ebay = searchEngine "ebay" "https://www.ebay.com/sch/i.html?_nkw=" github = searchEngine "github" "https://github.com/search?q=" google = searchEngine "google" "https://www.google.com/search?q=" hackage = searchEngine "hackage" "https://hackage.haskell.org/package/" hoogle = searchEngine "hoogle" "https://hoogle.haskell.org/?hoogle=" images = searchEngine "images" "https://images.google.fr/images?q=" imdb = searchEngine "imdb" "https://www.imdb.com/find?s=all&q=" lucky = searchEngine "lucky" "https://www.google.com/search?btnI&q=" maps = searchEngine "maps" "https://maps.google.com/maps?q=" mathworld = searchEngine "mathworld" "https://mathworld.wolfram.com/search/?query=" openstreetmap = searchEngine "openstreetmap" "https://www.openstreetmap.org/search?query=" scholar = searchEngine "scholar" "https://scholar.google.com/scholar?q=" stackage = searchEngine "stackage" "https://www.stackage.org/lts/hoogle?q=" thesaurus = searchEngine "thesaurus" "https://thesaurus.com/browse/" wikipedia = searchEngine "wiki" "https://en.wikipedia.org/wiki/Special:Search?go=Go&search=" wiktionary = searchEngine "wikt" "https://en.wiktionary.org/wiki/Special:Search?go=Go&search=" youtube = searchEngine "youtube" "https://www.youtube.com/results?search_type=search_videos&search_query=" wayback = searchEngineF "wayback" ("https://web.archive.org/web/*/"++) vocabulary = searchEngine "vocabulary" "https://www.vocabulary.com/search?q=" duckduckgo = searchEngine "duckduckgo" "https://duckduckgo.com/?t=lm&q=" multi :: SearchEngine multi = namedEngine "multi" $ foldr1 (!>) [amazon, alpha, codesearch, deb, debbts, debpts, dictionary, ebay, github, google, hackage, hoogle, images, imdb, lucky, maps, mathworld, openstreetmap, scholar, thesaurus, wayback, wikipedia, wiktionary, duckduckgo, prefixAware google] {- | This function wraps up a search engine and creates a new one, which works like the argument, but goes directly to a URL if one is given rather than searching. > myIntelligentGoogleEngine = intelligent google Now if you search for https:\/\/xmonad.org it will directly open in your browser-} intelligent :: SearchEngine -> SearchEngine intelligent (SearchEngine name site) = searchEngineF name (\s -> if takeWhile (/= ':') s `elem` ["http", "https", "ftp"] then s else site s) -- | > removeColonPrefix "foo://bar" ~> "//bar" -- > removeColonPrefix "foo//bar" ~> "foo//bar" removeColonPrefix :: String -> String removeColonPrefix s = if ':' `elem` s then drop 1 $ dropWhile (':' /=) s else s {- | Connects a few search engines into one. If the search engines\' names are \"s1\", \"s2\" and \"s3\", then the resulting engine will use s1 if the query is @s1:word@, s2 if you type @s2:word@ and s3 in all other cases. Example: > multiEngine = intelligent (wikipedia !> mathworld !> (prefixAware google)) Now if you type \"wiki:Haskell\" it will search for \"Haskell\" in Wikipedia, \"mathworld:integral\" will search mathworld, and everything else will fall back to google. The use of intelligent will make sure that URLs are opened directly. -} (!>) :: SearchEngine -> SearchEngine -> SearchEngine (SearchEngine name1 site1) !> (SearchEngine name2 site2) = searchEngineF (name1 ++ "/" ++ name2) (\s -> if (name1++":") `isPrefixOf` s then site1 (removeColonPrefix s) else site2 s) infixr 6 !> {- | Makes a search engine prefix-aware. Especially useful together with '!>'. It will automatically remove the prefix from a query so that you don\'t end up searching for google:xmonad if google is your fallback engine and you explicitly add the prefix. -} prefixAware :: SearchEngine -> SearchEngine prefixAware (SearchEngine name site) = SearchEngine name (\s -> if (name++":") `isPrefixOf` s then site $ removeColonPrefix s else site s) {- | Changes search engine's name -} namedEngine :: Name -> SearchEngine -> SearchEngine namedEngine name (SearchEngine _ site) = searchEngineF name site {- | Like 'search', but for use with the output from a Prompt; it grabs the Prompt's result, passes it to a given searchEngine and opens it in a given browser. -} promptSearchBrowser :: XPConfig -> Browser -> SearchEngine -> X () promptSearchBrowser config browser (SearchEngine name site) = do hc <- historyCompletionP ("Search [" `isPrefixOf`) mkXPrompt (Search name) config hc $ search browser site {- | Like 'promptSearchBrowser', but only suggest previous searches for the given 'SearchEngine' in the prompt. -} promptSearchBrowser' :: XPConfig -> Browser -> SearchEngine -> X () promptSearchBrowser' config browser (SearchEngine name site) = do hc <- historyCompletionP (searchName `isPrefixOf`) mkXPrompt (Search name) config hc $ search browser site where searchName = showXPrompt (Search name) {- | Like 'search', but in this case, the string is not specified but grabbed from the user's response to a prompt. Example: > , ((modm, xK_g), promptSearch greenXPConfig google) This specializes "promptSearchBrowser" by supplying the browser argument as supplied by 'getBrowser' from "XMonad.Prompt.Shell". -} promptSearch :: XPConfig -> SearchEngine -> X () promptSearch config engine = liftIO getBrowser >>= \ browser -> promptSearchBrowser config browser engine -- | Like 'search', but for use with the X selection; it grabs the selection, -- passes it to a given searchEngine and opens it in a given browser. selectSearchBrowser :: Browser -> SearchEngine -> X () selectSearchBrowser browser (SearchEngine _ site) = search browser site =<< getSelection {- | Like 'search', but for use with the X selection; it grabs the selection, passes it to a given searchEngine and opens it in the default browser . Example: > , ((modm .|. shiftMask, xK_g), selectSearch google) This specializes "selectSearchBrowser" by supplying the browser argument as supplied by 'getBrowser' from "XMonad.Prompt.Shell". -} selectSearch :: SearchEngine -> X () selectSearch engine = liftIO getBrowser >>= \browser -> selectSearchBrowser browser engine
xmonad/xmonad-contrib
XMonad/Actions/Search.hs
bsd-3-clause
18,242
0
11
4,952
1,690
964
726
137
2
module Module5.Task8 where import Control.Monad (liftM, ap) import Module5.Task5 (Log(..)) import Module5.Task6 (returnLog) import Module5.Task7 (bindLog) -- system code instance Monad Log where return = returnLog (>>=) = bindLog instance Functor Log where fmap = liftM instance Applicative Log where pure = return (<*>) = ap -- solution code execLoggersList :: a -> [a -> Log a] -> Log a execLoggersList = foldl (>>=) . return
dstarcev/stepic-haskell
src/Module5/Task8.hs
bsd-3-clause
443
0
9
81
148
87
61
15
1
{-# LANGUAGE PackageImports #-} module Text.Read (module M) where import "base" Text.Read as M
silkapp/base-noprelude
src/Text/Read.hs
bsd-3-clause
100
0
4
18
21
15
6
3
0
module Zero.Bittrex.Internal ( Message(..) , MarketSummary(..) , defaultMessage , defaultMarketSummary ) where import GHC.Generics (Generic) import Data.Aeson import Data.Text (Text) ------------------------------------------------------------------------------ -- Generic Message ------------------------------------------------------------------------------ data Message a = Message { m_success :: Bool , m_message :: Text , m_result :: a } deriving (Show, Generic) defaultMessage :: Message [MarketSummary] defaultMessage = Message False "" [defaultMarketSummary] instance FromJSON a => FromJSON (Message a) where parseJSON = withObject "Message" $ \v -> Message <$> v .: "success" <*> v .: "message" <*> v .: "result" instance ToJSON a => ToJSON (Message a) where toJSON (Message success message result) = object [ "success" .= success , "message" .= message , "result" .= result ] ------------------------------------------------------------------------------ -- Types ------------------------------------------------------------------------------ data MarketSummary = MarketSummary { ms_marketName :: Text , ms_high :: Double , ms_low :: Double , ms_volume :: Double , ms_last :: Double , ms_baseVolume :: Double , ms_timeStamp :: Text , ms_bid :: Double , ms_ask :: Double , ms_openBuyOrders :: Integer , ms_openSellOrders :: Integer , ms_prevDay :: Double , ms_created :: Text , ms_displayMarketName :: Maybe Text } deriving (Show, Generic) defaultMarketSummary :: MarketSummary defaultMarketSummary = MarketSummary "" 0.0 0.0 0.0 0.0 0.0 "" 0.0 0.0 0 0 0.0 "" Nothing instance FromJSON MarketSummary where parseJSON = withObject "MarketSummary" $ \v -> MarketSummary <$> v .: "MarketName" <*> v .: "High" <*> v .: "Low" <*> v .: "Volume" <*> v .: "Last" <*> v .: "BaseVolume" <*> v .: "TimeStamp" <*> v .: "Bid" <*> v .: "Ask" <*> v .: "OpenBuyOrders" <*> v .: "OpenSellOrders" <*> v .: "PrevDay" <*> v .: "Created" <*> v .:? "DisplayMarketName" instance ToJSON MarketSummary where toJSON (MarketSummary a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14) = object [ "MarketName" .= a1 , "High" .= a2 , "Low" .= a3 , "Volume" .= a4 , "Last" .= a5 , "BaseVolume" .= a6 , "TimeStamp" .= a7 , "Bid" .= a8 , "Ask" .= a9 , "OpenBuyOrders" .= a10 , "OpenSellOrders" .= a11 , "PrevDay" .= a12 , "Created" .= a13 , "DisplayMarketName" .= a14 ]
et4te/zero
src-shared/Zero/Bittrex/Internal.hs
bsd-3-clause
2,607
0
35
614
682
380
302
80
1
{-# LANGUAGE CPP, DeriveGeneric, DeriveFunctor, RecordWildCards #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.TargetSelector -- Copyright : (c) Duncan Coutts 2012, 2015, 2016 -- License : BSD-like -- -- Maintainer : duncan@community.haskell.org -- -- Handling for user-specified target selectors. -- ----------------------------------------------------------------------------- module Distribution.Client.TargetSelector ( -- * Target selectors TargetSelector(..), TargetImplicitCwd(..), ComponentKind(..), SubComponentTarget(..), QualLevel(..), componentKind, -- * Reading target selectors readTargetSelectors, TargetSelectorProblem(..), reportTargetSelectorProblems, showTargetSelector, TargetString, showTargetString, parseTargetString, -- ** non-IO readTargetSelectorsWith, DirActions(..), defaultDirActions, ) where import Distribution.Package ( Package(..), PackageId, PackageIdentifier(..), packageName , mkPackageName ) import Distribution.Version ( mkVersion ) import Distribution.Types.UnqualComponentName ( unUnqualComponentName ) import Distribution.Client.Types ( PackageLocation(..) ) import Distribution.Verbosity import Distribution.PackageDescription ( PackageDescription , Executable(..) , TestSuite(..), TestSuiteInterface(..), testModules , Benchmark(..), BenchmarkInterface(..), benchmarkModules , BuildInfo(..), explicitLibModules, exeModules ) import Distribution.PackageDescription.Configuration ( flattenPackageDescription ) import Distribution.Solver.Types.SourcePackage ( SourcePackage(..) ) import Distribution.ModuleName ( ModuleName, toFilePath ) import Distribution.Simple.LocalBuildInfo ( Component(..), ComponentName(..) , pkgComponents, componentName, componentBuildInfo ) import Distribution.Types.ForeignLib import Distribution.Text ( display, simpleParse ) import Distribution.Simple.Utils ( die', lowercase, ordNub ) import Distribution.Client.Utils ( makeRelativeCanonical ) import Data.Either ( partitionEithers ) import Data.Function ( on ) import Data.List ( nubBy, stripPrefix, partition, intercalate, sortBy, groupBy ) import Data.Maybe ( maybeToList ) import Data.Ord ( comparing ) import Distribution.Compat.Binary (Binary) import GHC.Generics (Generic) #if MIN_VERSION_containers(0,5,0) import qualified Data.Map.Lazy as Map.Lazy import qualified Data.Map.Strict as Map import Data.Map.Strict (Map) #else import qualified Data.Map as Map.Lazy import qualified Data.Map as Map import Data.Map (Map) #endif import qualified Data.Set as Set import Control.Arrow ((&&&)) import Control.Monad #if __GLASGOW_HASKELL__ < 710 import Control.Applicative (Applicative(..), (<$>)) #endif import Control.Applicative (Alternative(..)) import qualified Distribution.Compat.ReadP as Parse import Distribution.Compat.ReadP ( (+++), (<++) ) import Distribution.ParseUtils ( readPToMaybe ) import Data.Char ( isSpace, isAlphaNum ) import System.FilePath as FilePath ( takeExtension, dropExtension , splitDirectories, joinPath, splitPath ) import qualified System.Directory as IO ( doesFileExist, doesDirectoryExist, canonicalizePath , getCurrentDirectory ) import System.FilePath ( (</>), (<.>), normalise, dropTrailingPathSeparator ) import Text.EditDistance ( defaultEditCosts, restrictedDamerauLevenshteinDistance ) -- ------------------------------------------------------------ -- * Target selector terms -- ------------------------------------------------------------ -- | A target selector is expression selecting a set of components (as targets -- for a actions like @build@, @run@, @test@ etc). A target selector -- corresponds to the user syntax for referring to targets on the command line. -- -- From the users point of view a target can be many things: packages, dirs, -- component names, files etc. Internally we consider a target to be a specific -- component (or module\/file within a component), and all the users' notions -- of targets are just different ways of referring to these component targets. -- -- So target selectors are expressions in the sense that they are interpreted -- to refer to one or more components. For example a 'TargetPackage' gets -- interpreted differently by different commands to refer to all or a subset -- of components within the package. -- -- The syntax has lots of optional parts: -- -- > [ package name | package dir | package .cabal file ] -- > [ [lib:|exe:] component name ] -- > [ module name | source file ] -- data TargetSelector pkg = -- | A package as a whole: the default components for the package or all -- components of a particular kind. -- TargetPackage TargetImplicitCwd pkg (Maybe ComponentKindFilter) -- | All packages, or all components of a particular kind in all packages. -- | TargetAllPackages (Maybe ComponentKindFilter) -- | A specific component in a package. -- | TargetComponent pkg ComponentName SubComponentTarget deriving (Eq, Ord, Functor, Show, Generic) -- | Does this 'TargetPackage' selector arise from syntax referring to a -- packge in the current directory (e.g. @tests@ or no giving no explicit -- target at all) or does it come from syntax referring to a package name -- or location. -- data TargetImplicitCwd = TargetImplicitCwd | TargetExplicitNamed deriving (Eq, Ord, Show, Generic) data ComponentKind = LibKind | FLibKind | ExeKind | TestKind | BenchKind deriving (Eq, Ord, Enum, Show) type ComponentKindFilter = ComponentKind -- | Either the component as a whole or detail about a file or module target -- within a component. -- data SubComponentTarget = -- | The component as a whole WholeComponent -- | A specific module within a component. | ModuleTarget ModuleName -- | A specific file within a component. | FileTarget FilePath deriving (Eq, Ord, Show, Generic) instance Binary SubComponentTarget -- ------------------------------------------------------------ -- * Top level, do everything -- ------------------------------------------------------------ -- | Parse a bunch of command line args as 'TargetSelector's, failing with an -- error if any are unrecognised. The possible target selectors are based on -- the available packages (and their locations). -- readTargetSelectors :: [SourcePackage (PackageLocation a)] -> [String] -> IO (Either [TargetSelectorProblem] [TargetSelector PackageId]) readTargetSelectors = readTargetSelectorsWith defaultDirActions readTargetSelectorsWith :: (Applicative m, Monad m) => DirActions m -> [SourcePackage (PackageLocation a)] -> [String] -> m (Either [TargetSelectorProblem] [TargetSelector PackageId]) readTargetSelectorsWith dirActions@DirActions{..} pkgs targetStrs = case parseTargetStrings targetStrs of ([], utargets) -> do utargets' <- mapM (getTargetStringFileStatus dirActions) utargets pkgs' <- mapM (selectPackageInfo dirActions) pkgs cwd <- getCurrentDirectory let (cwdPkg, otherPkgs) = selectCwdPackage cwd pkgs' case resolveTargetSelectors cwdPkg otherPkgs utargets' of ([], btargets) -> return (Right (map (fmap packageId) btargets)) (problems, _) -> return (Left problems) (strs, _) -> return (Left (map TargetSelectorUnrecognised strs)) where selectCwdPackage :: FilePath -> [PackageInfo] -> ([PackageInfo], [PackageInfo]) selectCwdPackage cwd pkgs' = let (cwdpkg, others) = partition isPkgDirCwd pkgs' in (cwdpkg, others) where isPkgDirCwd PackageInfo { pinfoDirectory = Just (dir,_) } | dir == cwd = True isPkgDirCwd _ = False data DirActions m = DirActions { doesFileExist :: FilePath -> m Bool, doesDirectoryExist :: FilePath -> m Bool, canonicalizePath :: FilePath -> m FilePath, getCurrentDirectory :: m FilePath } defaultDirActions :: DirActions IO defaultDirActions = DirActions { doesFileExist = IO.doesFileExist, doesDirectoryExist = IO.doesDirectoryExist, -- Workaround for <https://github.com/haskell/directory/issues/63> canonicalizePath = IO.canonicalizePath . dropTrailingPathSeparator, getCurrentDirectory = IO.getCurrentDirectory } makeRelativeToCwd :: Applicative m => DirActions m -> FilePath -> m FilePath makeRelativeToCwd DirActions{..} path = makeRelativeCanonical <$> canonicalizePath path <*> getCurrentDirectory -- ------------------------------------------------------------ -- * Parsing target strings -- ------------------------------------------------------------ -- | The outline parse of a target selector. It takes one of the forms: -- -- > str1 -- > str1:str2 -- > str1:str2:str3 -- > str1:str2:str3:str4 -- data TargetString = TargetString1 String | TargetString2 String String | TargetString3 String String String | TargetString4 String String String String | TargetString5 String String String String String | TargetString7 String String String String String String String deriving (Show, Eq) -- | Parse a bunch of 'TargetString's (purely without throwing exceptions). -- parseTargetStrings :: [String] -> ([String], [TargetString]) parseTargetStrings = partitionEithers . map (\str -> maybe (Left str) Right (parseTargetString str)) parseTargetString :: String -> Maybe TargetString parseTargetString = readPToMaybe parseTargetApprox where parseTargetApprox :: Parse.ReadP r TargetString parseTargetApprox = (do a <- tokenQ return (TargetString1 a)) +++ (do a <- tokenQ0 _ <- Parse.char ':' b <- tokenQ return (TargetString2 a b)) +++ (do a <- tokenQ0 _ <- Parse.char ':' b <- tokenQ _ <- Parse.char ':' c <- tokenQ return (TargetString3 a b c)) +++ (do a <- tokenQ0 _ <- Parse.char ':' b <- token _ <- Parse.char ':' c <- tokenQ _ <- Parse.char ':' d <- tokenQ return (TargetString4 a b c d)) +++ (do a <- tokenQ0 _ <- Parse.char ':' b <- token _ <- Parse.char ':' c <- tokenQ _ <- Parse.char ':' d <- tokenQ _ <- Parse.char ':' e <- tokenQ return (TargetString5 a b c d e)) +++ (do a <- tokenQ0 _ <- Parse.char ':' b <- token _ <- Parse.char ':' c <- tokenQ _ <- Parse.char ':' d <- tokenQ _ <- Parse.char ':' e <- tokenQ _ <- Parse.char ':' f <- tokenQ _ <- Parse.char ':' g <- tokenQ return (TargetString7 a b c d e f g)) token = Parse.munch1 (\x -> not (isSpace x) && x /= ':') tokenQ = parseHaskellString <++ token token0 = Parse.munch (\x -> not (isSpace x) && x /= ':') tokenQ0= parseHaskellString <++ token0 parseHaskellString :: Parse.ReadP r String parseHaskellString = Parse.readS_to_P reads -- | Render a 'TargetString' back as the external syntax. This is mainly for -- error messages. -- showTargetString :: TargetString -> String showTargetString = intercalate ":" . components where components (TargetString1 s1) = [s1] components (TargetString2 s1 s2) = [s1,s2] components (TargetString3 s1 s2 s3) = [s1,s2,s3] components (TargetString4 s1 s2 s3 s4) = [s1,s2,s3,s4] components (TargetString5 s1 s2 s3 s4 s5) = [s1,s2,s3,s4,s5] components (TargetString7 s1 s2 s3 s4 s5 s6 s7) = [s1,s2,s3,s4,s5,s6,s7] showTargetSelector :: Package p => TargetSelector p -> String showTargetSelector ts = let (t':_) = [ t | ql <- [QL1 .. QLFull] , t <- renderTargetSelector ql ts ] in showTargetString (forgetFileStatus t') showTargetSelectorKind :: TargetSelector a -> String showTargetSelectorKind bt = case bt of TargetPackage TargetExplicitNamed _ Nothing -> "package" TargetPackage TargetExplicitNamed _ (Just _) -> "package:filter" TargetPackage TargetImplicitCwd _ Nothing -> "cwd-package" TargetPackage TargetImplicitCwd _ (Just _) -> "cwd-package:filter" TargetAllPackages Nothing -> "all-packages" TargetAllPackages (Just _) -> "all-packages:filter" TargetComponent _ _ WholeComponent -> "component" TargetComponent _ _ ModuleTarget{} -> "module" TargetComponent _ _ FileTarget{} -> "file" -- ------------------------------------------------------------ -- * Checking if targets exist as files -- ------------------------------------------------------------ data TargetStringFileStatus = TargetStringFileStatus1 String FileStatus | TargetStringFileStatus2 String FileStatus String | TargetStringFileStatus3 String FileStatus String String | TargetStringFileStatus4 String String String String | TargetStringFileStatus5 String String String String String | TargetStringFileStatus7 String String String String String String String deriving (Eq, Ord, Show) data FileStatus = FileStatusExistsFile FilePath -- the canonicalised filepath | FileStatusExistsDir FilePath -- the canonicalised filepath | FileStatusNotExists Bool -- does the parent dir exist even? deriving (Eq, Ord, Show) noFileStatus :: FileStatus noFileStatus = FileStatusNotExists False getTargetStringFileStatus :: (Applicative m, Monad m) => DirActions m -> TargetString -> m TargetStringFileStatus getTargetStringFileStatus DirActions{..} t = case t of TargetString1 s1 -> (\f1 -> TargetStringFileStatus1 s1 f1) <$> fileStatus s1 TargetString2 s1 s2 -> (\f1 -> TargetStringFileStatus2 s1 f1 s2) <$> fileStatus s1 TargetString3 s1 s2 s3 -> (\f1 -> TargetStringFileStatus3 s1 f1 s2 s3) <$> fileStatus s1 TargetString4 s1 s2 s3 s4 -> return (TargetStringFileStatus4 s1 s2 s3 s4) TargetString5 s1 s2 s3 s4 s5 -> return (TargetStringFileStatus5 s1 s2 s3 s4 s5) TargetString7 s1 s2 s3 s4 s5 s6 s7 -> return (TargetStringFileStatus7 s1 s2 s3 s4 s5 s6 s7) where fileStatus f = do fexists <- doesFileExist f dexists <- doesDirectoryExist f case splitPath f of _ | fexists -> FileStatusExistsFile <$> canonicalizePath f | dexists -> FileStatusExistsDir <$> canonicalizePath f (d:_) -> FileStatusNotExists <$> doesDirectoryExist d _ -> pure (FileStatusNotExists False) forgetFileStatus :: TargetStringFileStatus -> TargetString forgetFileStatus t = case t of TargetStringFileStatus1 s1 _ -> TargetString1 s1 TargetStringFileStatus2 s1 _ s2 -> TargetString2 s1 s2 TargetStringFileStatus3 s1 _ s2 s3 -> TargetString3 s1 s2 s3 TargetStringFileStatus4 s1 s2 s3 s4 -> TargetString4 s1 s2 s3 s4 TargetStringFileStatus5 s1 s2 s3 s4 s5 -> TargetString5 s1 s2 s3 s4 s5 TargetStringFileStatus7 s1 s2 s3 s4 s5 s6 s7 -> TargetString7 s1 s2 s3 s4 s5 s6 s7 -- ------------------------------------------------------------ -- * Resolving target strings to target selectors -- ------------------------------------------------------------ -- | Given a bunch of user-specified targets, try to resolve what it is they -- refer to. -- resolveTargetSelectors :: [PackageInfo] -- any pkg in the cur dir -> [PackageInfo] -- all the other local packages -> [TargetStringFileStatus] -> ([TargetSelectorProblem], [TargetSelector PackageInfo]) -- default local dir target if there's no given target: resolveTargetSelectors [] [] [] = ([TargetSelectorNoTargetsInProject], []) resolveTargetSelectors [] _opinfo [] = ([TargetSelectorNoTargetsInCwd], []) resolveTargetSelectors ppinfo _opinfo [] = ([], [TargetPackage TargetImplicitCwd (head ppinfo) Nothing]) --TODO: in future allow multiple packages in the same dir resolveTargetSelectors ppinfo opinfo targetStrs = partitionEithers . map (resolveTargetSelector ppinfo opinfo) $ targetStrs resolveTargetSelector :: [PackageInfo] -> [PackageInfo] -> TargetStringFileStatus -> Either TargetSelectorProblem (TargetSelector PackageInfo) resolveTargetSelector ppinfo opinfo targetStrStatus = case findMatch (matcher targetStrStatus) of Unambiguous _ | projectIsEmpty -> Left TargetSelectorNoTargetsInProject Unambiguous (TargetPackage TargetImplicitCwd _ mkfilter) | null ppinfo -> Left (TargetSelectorNoCurrentPackage targetStr) | otherwise -> Right (TargetPackage TargetImplicitCwd (head ppinfo) mkfilter) --TODO: in future allow multiple packages in the same dir Unambiguous target -> Right target None errs | projectIsEmpty -> Left TargetSelectorNoTargetsInProject | otherwise -> Left (classifyMatchErrors errs) Ambiguous exactMatch targets -> case disambiguateTargetSelectors matcher targetStrStatus exactMatch targets of Right targets' -> Left (TargetSelectorAmbiguous targetStr (map (fmap (fmap packageId)) targets')) Left ((m, ms):_) -> Left (MatchingInternalError targetStr (fmap packageId m) (map (fmap (map (fmap packageId))) ms)) Left [] -> internalError "resolveTargetSelector" where matcher = matchTargetSelector ppinfo opinfo targetStr = forgetFileStatus targetStrStatus projectIsEmpty = null ppinfo && null opinfo classifyMatchErrors errs | not (null expected) = let (things, got:_) = unzip expected in TargetSelectorExpected targetStr things got | not (null nosuch) = TargetSelectorNoSuch targetStr nosuch | otherwise = internalError $ "classifyMatchErrors: " ++ show errs where expected = [ (thing, got) | (_, MatchErrorExpected thing got) <- map (innerErr Nothing) errs ] -- Trim the list of alternatives by dropping duplicates and -- retaining only at most three most similar (by edit distance) ones. nosuch = Map.foldrWithKey genResults [] $ Map.fromListWith Set.union $ [ ((inside, thing, got), Set.fromList alts) | (inside, MatchErrorNoSuch thing got alts) <- map (innerErr Nothing) errs ] genResults (inside, thing, got) alts acc = ( inside , thing , got , take maxResults $ map fst $ takeWhile distanceLow $ sortBy (comparing snd) $ map addLevDist $ Set.toList alts ) : acc where addLevDist = id &&& restrictedDamerauLevenshteinDistance defaultEditCosts got distanceLow (_, dist) = dist < length got `div` 2 maxResults = 3 innerErr _ (MatchErrorIn kind thing m) = innerErr (Just (kind,thing)) m innerErr c m = (c,m) -- | The various ways that trying to resolve a 'TargetString' to a -- 'TargetSelector' can fail. -- data TargetSelectorProblem = TargetSelectorExpected TargetString [String] String -- ^ [expected thing] (actually got) | TargetSelectorNoSuch TargetString [(Maybe (String, String), String, String, [String])] -- ^ [([in thing], no such thing, actually got, alternatives)] | TargetSelectorAmbiguous TargetString [(TargetString, TargetSelector PackageId)] | MatchingInternalError TargetString (TargetSelector PackageId) [(TargetString, [TargetSelector PackageId])] | TargetSelectorUnrecognised String -- ^ Syntax error when trying to parse a target string. | TargetSelectorNoCurrentPackage TargetString | TargetSelectorNoTargetsInCwd | TargetSelectorNoTargetsInProject deriving (Show, Eq) data QualLevel = QL1 | QL2 | QL3 | QLFull deriving (Eq, Enum, Show) disambiguateTargetSelectors :: (TargetStringFileStatus -> Match (TargetSelector PackageInfo)) -> TargetStringFileStatus -> Bool -> [TargetSelector PackageInfo] -> Either [(TargetSelector PackageInfo, [(TargetString, [TargetSelector PackageInfo])])] [(TargetString, TargetSelector PackageInfo)] disambiguateTargetSelectors matcher matchInput exactMatch matchResults = case partitionEithers results of (errs@(_:_), _) -> Left errs ([], ok) -> Right ok where -- So, here's the strategy. We take the original match results, and make a -- table of all their renderings at all qualification levels. -- Note there can be multiple renderings at each qualification level. matchResultsRenderings :: [(TargetSelector PackageInfo, [TargetStringFileStatus])] matchResultsRenderings = [ (matchResult, matchRenderings) | matchResult <- matchResults , let matchRenderings = [ rendering | ql <- [QL1 .. QLFull] , rendering <- renderTargetSelector ql matchResult ] ] -- Of course the point is that we're looking for renderings that are -- unambiguous matches. So we build another memo table of all the matches -- for all of those renderings. So by looking up in this table we can see -- if we've got an unambiguous match. memoisedMatches :: Map TargetStringFileStatus (Match (TargetSelector PackageInfo)) memoisedMatches = -- avoid recomputing the main one if it was an exact match (if exactMatch then Map.insert matchInput (ExactMatch 0 matchResults) else id) $ Map.Lazy.fromList [ (rendering, matcher rendering) | rendering <- concatMap snd matchResultsRenderings ] -- Finally, for each of the match results, we go through all their -- possible renderings (in order of qualification level, though remember -- there can be multiple renderings per level), and find the first one -- that has an unambiguous match. results :: [Either (TargetSelector PackageInfo, [(TargetString, [TargetSelector PackageInfo])]) (TargetString, TargetSelector PackageInfo)] results = [ case findUnambiguous originalMatch matchRenderings of Just unambiguousRendering -> Right ( forgetFileStatus unambiguousRendering , originalMatch) -- This case is an internal error, but we bubble it up and report it Nothing -> Left ( originalMatch , [ (forgetFileStatus rendering, matches) | rendering <- matchRenderings , let (ExactMatch _ matches) = memoisedMatches Map.! rendering ] ) | (originalMatch, matchRenderings) <- matchResultsRenderings ] findUnambiguous :: TargetSelector PackageInfo -> [TargetStringFileStatus] -> Maybe TargetStringFileStatus findUnambiguous _ [] = Nothing findUnambiguous t (r:rs) = case memoisedMatches Map.! r of ExactMatch _ [t'] | fmap packageName t == fmap packageName t' -> Just r ExactMatch _ _ -> findUnambiguous t rs InexactMatch _ _ -> internalError "InexactMatch" NoMatch _ _ -> internalError "NoMatch" internalError :: String -> a internalError msg = error $ "TargetSelector: internal error: " ++ msg -- | Throw an exception with a formatted message if there are any problems. -- reportTargetSelectorProblems :: Verbosity -> [TargetSelectorProblem] -> IO a reportTargetSelectorProblems verbosity problems = do case [ str | TargetSelectorUnrecognised str <- problems ] of [] -> return () targets -> die' verbosity $ unlines [ "Unrecognised target syntax for '" ++ name ++ "'." | name <- targets ] case [ (t, m, ms) | MatchingInternalError t m ms <- problems ] of [] -> return () ((target, originalMatch, renderingsAndMatches):_) -> die' verbosity $ "Internal error in target matching. It should always " ++ "be possible to find a syntax that's sufficiently qualified to " ++ "give an unambiguous match. However when matching '" ++ showTargetString target ++ "' we found " ++ showTargetSelector originalMatch ++ " (" ++ showTargetSelectorKind originalMatch ++ ") which does " ++ "not have an unambiguous syntax. The possible syntax and the " ++ "targets they match are as follows:\n" ++ unlines [ "'" ++ showTargetString rendering ++ "' which matches " ++ intercalate ", " [ showTargetSelector match ++ " (" ++ showTargetSelectorKind match ++ ")" | match <- matches ] | (rendering, matches) <- renderingsAndMatches ] case [ (t, e, g) | TargetSelectorExpected t e g <- problems ] of [] -> return () targets -> die' verbosity $ unlines [ "Unrecognised target '" ++ showTargetString target ++ "'.\n" ++ "Expected a " ++ intercalate " or " expected ++ ", rather than '" ++ got ++ "'." | (target, expected, got) <- targets ] case [ (t, e) | TargetSelectorNoSuch t e <- problems ] of [] -> return () targets -> die' verbosity $ unlines [ "Unknown target '" ++ showTargetString target ++ "'.\n" ++ unlines [ (case inside of Just (kind, "") -> "The " ++ kind ++ " has no " Just (kind, thing) -> "The " ++ kind ++ " " ++ thing ++ " has no " Nothing -> "There is no ") ++ intercalate " or " [ mungeThing thing ++ " '" ++ got ++ "'" | (thing, got, _alts) <- nosuch' ] ++ "." ++ if null alternatives then "" else "\nPerhaps you meant " ++ intercalate ";\nor " [ "the " ++ thing ++ " '" ++ intercalate "' or '" alts ++ "'?" | (thing, alts) <- alternatives ] | (inside, nosuch') <- groupByContainer nosuch , let alternatives = [ (thing, alts) | (thing,_got,alts@(_:_)) <- nosuch' ] ] | (target, nosuch) <- targets , let groupByContainer = map (\g@((inside,_,_,_):_) -> (inside, [ (thing,got,alts) | (_,thing,got,alts) <- g ])) . groupBy ((==) `on` (\(x,_,_,_) -> x)) . sortBy (compare `on` (\(x,_,_,_) -> x)) ] where mungeThing "file" = "file target" mungeThing thing = thing case [ (t, ts) | TargetSelectorAmbiguous t ts <- problems ] of [] -> return () targets -> die' verbosity $ unlines [ "Ambiguous target '" ++ showTargetString target ++ "'. It could be:\n " ++ unlines [ " "++ showTargetString ut ++ " (" ++ showTargetSelectorKind bt ++ ")" | (ut, bt) <- amb ] | (target, amb) <- targets ] case [ t | TargetSelectorNoCurrentPackage t <- problems ] of [] -> return () target:_ -> die' verbosity $ "The target '" ++ showTargetString target ++ "' refers to the " ++ "components in the package in the current directory, but there " ++ "is no package in the current directory (or at least not listed " ++ "as part of the project)." --TODO: report a different error if there is a .cabal file but it's -- not a member of the project case [ () | TargetSelectorNoTargetsInCwd <- problems ] of [] -> return () _:_ -> die' verbosity $ "No targets given and there is no package in the current " ++ "directory. Use the target 'all' for all packages in the " ++ "project or specify packages or components by name or location. " ++ "See 'cabal build --help' for more details on target options." case [ () | TargetSelectorNoTargetsInProject <- problems ] of [] -> return () _:_ -> die' verbosity $ "There is no <pkgname>.cabal package file or cabal.project file. " ++ "To build packages locally you need at minimum a <pkgname>.cabal " ++ "file. You can use 'cabal init' to create one.\n" ++ "\n" ++ "For non-trivial projects you will also want a cabal.project " ++ "file in the root directory of your project. This file lists the " ++ "packages in your project and all other build configuration. " ++ "See the Cabal user guide for full details." fail "reportTargetSelectorProblems: internal error" ---------------------------------- -- Syntax type -- -- | Syntax for the 'TargetSelector': the matcher and renderer -- data Syntax = Syntax QualLevel Matcher Renderer | AmbiguousAlternatives Syntax Syntax | ShadowingAlternatives Syntax Syntax type Matcher = TargetStringFileStatus -> Match (TargetSelector PackageInfo) type Renderer = TargetSelector PackageId -> [TargetStringFileStatus] foldSyntax :: (a -> a -> a) -> (a -> a -> a) -> (QualLevel -> Matcher -> Renderer -> a) -> (Syntax -> a) foldSyntax ambiguous unambiguous syntax = go where go (Syntax ql match render) = syntax ql match render go (AmbiguousAlternatives a b) = ambiguous (go a) (go b) go (ShadowingAlternatives a b) = unambiguous (go a) (go b) ---------------------------------- -- Top level renderer and matcher -- renderTargetSelector :: Package p => QualLevel -> TargetSelector p -> [TargetStringFileStatus] renderTargetSelector ql ts = foldSyntax (++) (++) (\ql' _ render -> guard (ql == ql') >> render (fmap packageId ts)) syntax where syntax = syntaxForms [] [] -- don't need pinfo for rendering matchTargetSelector :: [PackageInfo] -> [PackageInfo] -> TargetStringFileStatus -> Match (TargetSelector PackageInfo) matchTargetSelector ppinfo opinfo = \utarget -> nubMatchesBy ((==) `on` (fmap packageName)) $ let ql = targetQualLevel utarget in foldSyntax (<|>) (<//>) (\ql' match _ -> guard (ql == ql') >> match utarget) syntax where syntax = syntaxForms ppinfo opinfo targetQualLevel TargetStringFileStatus1{} = QL1 targetQualLevel TargetStringFileStatus2{} = QL2 targetQualLevel TargetStringFileStatus3{} = QL3 targetQualLevel TargetStringFileStatus4{} = QLFull targetQualLevel TargetStringFileStatus5{} = QLFull targetQualLevel TargetStringFileStatus7{} = QLFull ---------------------------------- -- Syntax forms -- -- | All the forms of syntax for 'TargetSelector'. -- syntaxForms :: [PackageInfo] -> [PackageInfo] -> Syntax syntaxForms ppinfo opinfo = -- The various forms of syntax here are ambiguous in many cases. -- Our policy is by default we expose that ambiguity and report -- ambiguous matches. In certain cases we override the ambiguity -- by having some forms shadow others. -- -- We make modules shadow files because module name "Q" clashes -- with file "Q" with no extension but these refer to the same -- thing anyway so it's not a useful ambiguity. Other cases are -- not ambiguous like "Q" vs "Q.hs" or "Data.Q" vs "Data/Q". ambiguousAlternatives -- convenient single-component forms [ shadowingAlternatives [ ambiguousAlternatives [ syntaxForm1All , syntaxForm1Filter , shadowingAlternatives [ syntaxForm1Component pcinfo , syntaxForm1Package pinfo ] ] , syntaxForm1Component ocinfo , syntaxForm1Module cinfo , syntaxForm1File pinfo ] -- two-component partially qualified forms -- fully qualified form for 'all' , syntaxForm2MetaAll , syntaxForm2AllFilter , syntaxForm2NamespacePackage pinfo , syntaxForm2PackageComponent pinfo , syntaxForm2PackageFilter pinfo , syntaxForm2KindComponent cinfo , shadowingAlternatives [ syntaxForm2PackageModule pinfo , syntaxForm2PackageFile pinfo ] , shadowingAlternatives [ syntaxForm2ComponentModule cinfo , syntaxForm2ComponentFile cinfo ] -- rarely used partially qualified forms , syntaxForm3PackageKindComponent pinfo , shadowingAlternatives [ syntaxForm3PackageComponentModule pinfo , syntaxForm3PackageComponentFile pinfo ] , shadowingAlternatives [ syntaxForm3KindComponentModule cinfo , syntaxForm3KindComponentFile cinfo ] , syntaxForm3NamespacePackageFilter pinfo -- fully-qualified forms for all and cwd with filter , syntaxForm3MetaAllFilter , syntaxForm3MetaCwdFilter -- fully-qualified form for package and package with filter , syntaxForm3MetaNamespacePackage pinfo , syntaxForm4MetaNamespacePackageFilter pinfo -- fully-qualified forms for component, module and file , syntaxForm5MetaNamespacePackageKindComponent pinfo , syntaxForm7MetaNamespacePackageKindComponentNamespaceModule pinfo , syntaxForm7MetaNamespacePackageKindComponentNamespaceFile pinfo ] where ambiguousAlternatives = foldr1 AmbiguousAlternatives shadowingAlternatives = foldr1 ShadowingAlternatives pinfo = ppinfo ++ opinfo cinfo = concatMap pinfoComponents pinfo pcinfo = concatMap pinfoComponents ppinfo ocinfo = concatMap pinfoComponents opinfo -- | Syntax: "all" to select all packages in the project -- -- > cabal build all -- syntaxForm1All :: Syntax syntaxForm1All = syntaxForm1 render $ \str1 _fstatus1 -> do guardMetaAll str1 return (TargetAllPackages Nothing) where render (TargetAllPackages Nothing) = [TargetStringFileStatus1 "all" noFileStatus] render _ = [] -- | Syntax: filter -- -- > cabal build tests -- syntaxForm1Filter :: Syntax syntaxForm1Filter = syntaxForm1 render $ \str1 _fstatus1 -> do kfilter <- matchComponentKindFilter str1 return (TargetPackage TargetImplicitCwd dummyPackageInfo (Just kfilter)) where render (TargetPackage TargetImplicitCwd _ (Just kfilter)) = [TargetStringFileStatus1 (dispF kfilter) noFileStatus] render _ = [] -- Only used for TargetPackage TargetImplicitCwd dummyPackageInfo :: PackageInfo dummyPackageInfo = PackageInfo { pinfoId = PackageIdentifier (mkPackageName "dummyPackageInfo") (mkVersion []), pinfoLocation = unused, pinfoDirectory = unused, pinfoPackageFile = unused, pinfoComponents = unused } where unused = error "dummyPackageInfo" -- | Syntax: package (name, dir or file) -- -- > cabal build foo -- > cabal build ../bar ../bar/bar.cabal -- syntaxForm1Package :: [PackageInfo] -> Syntax syntaxForm1Package pinfo = syntaxForm1 render $ \str1 fstatus1 -> do guardPackage str1 fstatus1 p <- matchPackage pinfo str1 fstatus1 return (TargetPackage TargetExplicitNamed p Nothing) where render (TargetPackage TargetExplicitNamed p Nothing) = [TargetStringFileStatus1 (dispP p) noFileStatus] render _ = [] -- | Syntax: component -- -- > cabal build foo -- syntaxForm1Component :: [ComponentInfo] -> Syntax syntaxForm1Component cs = syntaxForm1 render $ \str1 _fstatus1 -> do guardComponentName str1 c <- matchComponentName cs str1 return (TargetComponent (cinfoPackage c) (cinfoName c) WholeComponent) where render (TargetComponent p c WholeComponent) = [TargetStringFileStatus1 (dispC p c) noFileStatus] render _ = [] -- | Syntax: module -- -- > cabal build Data.Foo -- syntaxForm1Module :: [ComponentInfo] -> Syntax syntaxForm1Module cs = syntaxForm1 render $ \str1 _fstatus1 -> do guardModuleName str1 let ms = [ (m,c) | c <- cs, m <- cinfoModules c ] (m,c) <- matchModuleNameAnd ms str1 return (TargetComponent (cinfoPackage c) (cinfoName c) (ModuleTarget m)) where render (TargetComponent _p _c (ModuleTarget m)) = [TargetStringFileStatus1 (dispM m) noFileStatus] render _ = [] -- | Syntax: file name -- -- > cabal build Data/Foo.hs bar/Main.hsc -- syntaxForm1File :: [PackageInfo] -> Syntax syntaxForm1File ps = -- Note there's a bit of an inconsistency here vs the other syntax forms -- for files. For the single-part syntax the target has to point to a file -- that exists (due to our use of matchPackageDirectoryPrefix), whereas for -- all the other forms we don't require that. syntaxForm1 render $ \str1 fstatus1 -> expecting "file" str1 $ do (pkgfile, p) <- matchPackageDirectoryPrefix ps fstatus1 orNoThingIn "package" (display (packageName p)) $ do (filepath, c) <- matchComponentFile (pinfoComponents p) pkgfile return (TargetComponent p (cinfoName c) (FileTarget filepath)) where render (TargetComponent _p _c (FileTarget f)) = [TargetStringFileStatus1 f noFileStatus] render _ = [] --- -- | Syntax: :all -- -- > cabal build :all -- syntaxForm2MetaAll :: Syntax syntaxForm2MetaAll = syntaxForm2 render $ \str1 _fstatus1 str2 -> do guardNamespaceMeta str1 guardMetaAll str2 return (TargetAllPackages Nothing) where render (TargetAllPackages Nothing) = [TargetStringFileStatus2 "" noFileStatus "all"] render _ = [] -- | Syntax: all : filer -- -- > cabal build all:tests -- syntaxForm2AllFilter :: Syntax syntaxForm2AllFilter = syntaxForm2 render $ \str1 _fstatus1 str2 -> do guardMetaAll str1 kfilter <- matchComponentKindFilter str2 return (TargetAllPackages (Just kfilter)) where render (TargetAllPackages (Just kfilter)) = [TargetStringFileStatus2 "all" noFileStatus (dispF kfilter)] render _ = [] -- | Syntax: package : filer -- -- > cabal build foo:tests -- syntaxForm2PackageFilter :: [PackageInfo] -> Syntax syntaxForm2PackageFilter ps = syntaxForm2 render $ \str1 fstatus1 str2 -> do guardPackage str1 fstatus1 p <- matchPackage ps str1 fstatus1 kfilter <- matchComponentKindFilter str2 return (TargetPackage TargetExplicitNamed p (Just kfilter)) where render (TargetPackage TargetExplicitNamed p (Just kfilter)) = [TargetStringFileStatus2 (dispP p) noFileStatus (dispF kfilter)] render _ = [] -- | Syntax: pkg : package name -- -- > cabal build pkg:foo -- syntaxForm2NamespacePackage :: [PackageInfo] -> Syntax syntaxForm2NamespacePackage pinfo = syntaxForm2 render $ \str1 _fstatus1 str2 -> do guardNamespacePackage str1 guardPackageName str2 p <- matchPackage pinfo str2 noFileStatus return (TargetPackage TargetExplicitNamed p Nothing) where render (TargetPackage TargetExplicitNamed p Nothing) = [TargetStringFileStatus2 "pkg" noFileStatus (dispP p)] render _ = [] -- | Syntax: package : component -- -- > cabal build foo:foo -- > cabal build ./foo:foo -- > cabal build ./foo.cabal:foo -- syntaxForm2PackageComponent :: [PackageInfo] -> Syntax syntaxForm2PackageComponent ps = syntaxForm2 render $ \str1 fstatus1 str2 -> do guardPackage str1 fstatus1 guardComponentName str2 p <- matchPackage ps str1 fstatus1 orNoThingIn "package" (display (packageName p)) $ do c <- matchComponentName (pinfoComponents p) str2 return (TargetComponent p (cinfoName c) WholeComponent) --TODO: the error here ought to say there's no component by that name in -- this package, and name the package where render (TargetComponent p c WholeComponent) = [TargetStringFileStatus2 (dispP p) noFileStatus (dispC p c)] render _ = [] -- | Syntax: namespace : component -- -- > cabal build lib:foo exe:foo -- syntaxForm2KindComponent :: [ComponentInfo] -> Syntax syntaxForm2KindComponent cs = syntaxForm2 render $ \str1 _fstatus1 str2 -> do ckind <- matchComponentKind str1 guardComponentName str2 c <- matchComponentKindAndName cs ckind str2 return (TargetComponent (cinfoPackage c) (cinfoName c) WholeComponent) where render (TargetComponent p c WholeComponent) = [TargetStringFileStatus2 (dispK c) noFileStatus (dispC p c)] render _ = [] -- | Syntax: package : module -- -- > cabal build foo:Data.Foo -- > cabal build ./foo:Data.Foo -- > cabal build ./foo.cabal:Data.Foo -- syntaxForm2PackageModule :: [PackageInfo] -> Syntax syntaxForm2PackageModule ps = syntaxForm2 render $ \str1 fstatus1 str2 -> do guardPackage str1 fstatus1 guardModuleName str2 p <- matchPackage ps str1 fstatus1 orNoThingIn "package" (display (packageName p)) $ do let ms = [ (m,c) | c <- pinfoComponents p, m <- cinfoModules c ] (m,c) <- matchModuleNameAnd ms str2 return (TargetComponent p (cinfoName c) (ModuleTarget m)) where render (TargetComponent p _c (ModuleTarget m)) = [TargetStringFileStatus2 (dispP p) noFileStatus (dispM m)] render _ = [] -- | Syntax: component : module -- -- > cabal build foo:Data.Foo -- syntaxForm2ComponentModule :: [ComponentInfo] -> Syntax syntaxForm2ComponentModule cs = syntaxForm2 render $ \str1 _fstatus1 str2 -> do guardComponentName str1 guardModuleName str2 c <- matchComponentName cs str1 orNoThingIn "component" (cinfoStrName c) $ do let ms = cinfoModules c m <- matchModuleName ms str2 return (TargetComponent (cinfoPackage c) (cinfoName c) (ModuleTarget m)) where render (TargetComponent p c (ModuleTarget m)) = [TargetStringFileStatus2 (dispC p c) noFileStatus (dispM m)] render _ = [] -- | Syntax: package : filename -- -- > cabal build foo:Data/Foo.hs -- > cabal build ./foo:Data/Foo.hs -- > cabal build ./foo.cabal:Data/Foo.hs -- syntaxForm2PackageFile :: [PackageInfo] -> Syntax syntaxForm2PackageFile ps = syntaxForm2 render $ \str1 fstatus1 str2 -> do guardPackage str1 fstatus1 p <- matchPackage ps str1 fstatus1 orNoThingIn "package" (display (packageName p)) $ do (filepath, c) <- matchComponentFile (pinfoComponents p) str2 return (TargetComponent p (cinfoName c) (FileTarget filepath)) where render (TargetComponent p _c (FileTarget f)) = [TargetStringFileStatus2 (dispP p) noFileStatus f] render _ = [] -- | Syntax: component : filename -- -- > cabal build foo:Data/Foo.hs -- syntaxForm2ComponentFile :: [ComponentInfo] -> Syntax syntaxForm2ComponentFile cs = syntaxForm2 render $ \str1 _fstatus1 str2 -> do guardComponentName str1 c <- matchComponentName cs str1 orNoThingIn "component" (cinfoStrName c) $ do (filepath, _) <- matchComponentFile [c] str2 return (TargetComponent (cinfoPackage c) (cinfoName c) (FileTarget filepath)) where render (TargetComponent p c (FileTarget f)) = [TargetStringFileStatus2 (dispC p c) noFileStatus f] render _ = [] --- -- | Syntax: :all : filter -- -- > cabal build :all:tests -- syntaxForm3MetaAllFilter :: Syntax syntaxForm3MetaAllFilter = syntaxForm3 render $ \str1 _fstatus1 str2 str3 -> do guardNamespaceMeta str1 guardMetaAll str2 kfilter <- matchComponentKindFilter str3 return (TargetAllPackages (Just kfilter)) where render (TargetAllPackages (Just kfilter)) = [TargetStringFileStatus3 "" noFileStatus "all" (dispF kfilter)] render _ = [] syntaxForm3MetaCwdFilter :: Syntax syntaxForm3MetaCwdFilter = syntaxForm3 render $ \str1 _fstatus1 str2 str3 -> do guardNamespaceMeta str1 guardNamespaceCwd str2 kfilter <- matchComponentKindFilter str3 return (TargetPackage TargetImplicitCwd dummyPackageInfo (Just kfilter)) where render (TargetPackage TargetImplicitCwd _ (Just kfilter)) = [TargetStringFileStatus3 "" noFileStatus "cwd" (dispF kfilter)] render _ = [] -- | Syntax: :pkg : package name -- -- > cabal build :pkg:foo -- syntaxForm3MetaNamespacePackage :: [PackageInfo] -> Syntax syntaxForm3MetaNamespacePackage pinfo = syntaxForm3 render $ \str1 _fstatus1 str2 str3 -> do guardNamespaceMeta str1 guardNamespacePackage str2 guardPackageName str3 p <- matchPackage pinfo str3 noFileStatus return (TargetPackage TargetExplicitNamed p Nothing) where render (TargetPackage TargetExplicitNamed p Nothing) = [TargetStringFileStatus3 "" noFileStatus "pkg" (dispP p)] render _ = [] -- | Syntax: package : namespace : component -- -- > cabal build foo:lib:foo -- > cabal build foo/:lib:foo -- > cabal build foo.cabal:lib:foo -- syntaxForm3PackageKindComponent :: [PackageInfo] -> Syntax syntaxForm3PackageKindComponent ps = syntaxForm3 render $ \str1 fstatus1 str2 str3 -> do guardPackage str1 fstatus1 ckind <- matchComponentKind str2 guardComponentName str3 p <- matchPackage ps str1 fstatus1 orNoThingIn "package" (display (packageName p)) $ do c <- matchComponentKindAndName (pinfoComponents p) ckind str3 return (TargetComponent p (cinfoName c) WholeComponent) where render (TargetComponent p c WholeComponent) = [TargetStringFileStatus3 (dispP p) noFileStatus (dispK c) (dispC p c)] render _ = [] -- | Syntax: package : component : module -- -- > cabal build foo:foo:Data.Foo -- > cabal build foo/:foo:Data.Foo -- > cabal build foo.cabal:foo:Data.Foo -- syntaxForm3PackageComponentModule :: [PackageInfo] -> Syntax syntaxForm3PackageComponentModule ps = syntaxForm3 render $ \str1 fstatus1 str2 str3 -> do guardPackage str1 fstatus1 guardComponentName str2 guardModuleName str3 p <- matchPackage ps str1 fstatus1 orNoThingIn "package" (display (packageName p)) $ do c <- matchComponentName (pinfoComponents p) str2 orNoThingIn "component" (cinfoStrName c) $ do let ms = cinfoModules c m <- matchModuleName ms str3 return (TargetComponent p (cinfoName c) (ModuleTarget m)) where render (TargetComponent p c (ModuleTarget m)) = [TargetStringFileStatus3 (dispP p) noFileStatus (dispC p c) (dispM m)] render _ = [] -- | Syntax: namespace : component : module -- -- > cabal build lib:foo:Data.Foo -- syntaxForm3KindComponentModule :: [ComponentInfo] -> Syntax syntaxForm3KindComponentModule cs = syntaxForm3 render $ \str1 _fstatus1 str2 str3 -> do ckind <- matchComponentKind str1 guardComponentName str2 guardModuleName str3 c <- matchComponentKindAndName cs ckind str2 orNoThingIn "component" (cinfoStrName c) $ do let ms = cinfoModules c m <- matchModuleName ms str3 return (TargetComponent (cinfoPackage c) (cinfoName c) (ModuleTarget m)) where render (TargetComponent p c (ModuleTarget m)) = [TargetStringFileStatus3 (dispK c) noFileStatus (dispC p c) (dispM m)] render _ = [] -- | Syntax: package : component : filename -- -- > cabal build foo:foo:Data/Foo.hs -- > cabal build foo/:foo:Data/Foo.hs -- > cabal build foo.cabal:foo:Data/Foo.hs -- syntaxForm3PackageComponentFile :: [PackageInfo] -> Syntax syntaxForm3PackageComponentFile ps = syntaxForm3 render $ \str1 fstatus1 str2 str3 -> do guardPackage str1 fstatus1 guardComponentName str2 p <- matchPackage ps str1 fstatus1 orNoThingIn "package" (display (packageName p)) $ do c <- matchComponentName (pinfoComponents p) str2 orNoThingIn "component" (cinfoStrName c) $ do (filepath, _) <- matchComponentFile [c] str3 return (TargetComponent p (cinfoName c) (FileTarget filepath)) where render (TargetComponent p c (FileTarget f)) = [TargetStringFileStatus3 (dispP p) noFileStatus (dispC p c) f] render _ = [] -- | Syntax: namespace : component : filename -- -- > cabal build lib:foo:Data/Foo.hs -- syntaxForm3KindComponentFile :: [ComponentInfo] -> Syntax syntaxForm3KindComponentFile cs = syntaxForm3 render $ \str1 _fstatus1 str2 str3 -> do ckind <- matchComponentKind str1 guardComponentName str2 c <- matchComponentKindAndName cs ckind str2 orNoThingIn "component" (cinfoStrName c) $ do (filepath, _) <- matchComponentFile [c] str3 return (TargetComponent (cinfoPackage c) (cinfoName c) (FileTarget filepath)) where render (TargetComponent p c (FileTarget f)) = [TargetStringFileStatus3 (dispK c) noFileStatus (dispC p c) f] render _ = [] syntaxForm3NamespacePackageFilter :: [PackageInfo] -> Syntax syntaxForm3NamespacePackageFilter ps = syntaxForm3 render $ \str1 _fstatus1 str2 str3 -> do guardNamespacePackage str1 guardPackageName str2 p <- matchPackage ps str2 noFileStatus kfilter <- matchComponentKindFilter str3 return (TargetPackage TargetExplicitNamed p (Just kfilter)) where render (TargetPackage TargetExplicitNamed p (Just kfilter)) = [TargetStringFileStatus3 "pkg" noFileStatus (dispP p) (dispF kfilter)] render _ = [] -- syntaxForm4MetaNamespacePackageFilter :: [PackageInfo] -> Syntax syntaxForm4MetaNamespacePackageFilter ps = syntaxForm4 render $ \str1 str2 str3 str4 -> do guardNamespaceMeta str1 guardNamespacePackage str2 guardPackageName str3 p <- matchPackage ps str3 noFileStatus kfilter <- matchComponentKindFilter str4 return (TargetPackage TargetExplicitNamed p (Just kfilter)) where render (TargetPackage TargetExplicitNamed p (Just kfilter)) = [TargetStringFileStatus4 "" "pkg" (dispP p) (dispF kfilter)] render _ = [] -- | Syntax: :pkg : package : namespace : component -- -- > cabal build :pkg:foo:lib:foo -- syntaxForm5MetaNamespacePackageKindComponent :: [PackageInfo] -> Syntax syntaxForm5MetaNamespacePackageKindComponent ps = syntaxForm5 render $ \str1 str2 str3 str4 str5 -> do guardNamespaceMeta str1 guardNamespacePackage str2 guardPackageName str3 ckind <- matchComponentKind str4 guardComponentName str5 p <- matchPackage ps str3 noFileStatus orNoThingIn "package" (display (packageName p)) $ do c <- matchComponentKindAndName (pinfoComponents p) ckind str5 return (TargetComponent p (cinfoName c) WholeComponent) where render (TargetComponent p c WholeComponent) = [TargetStringFileStatus5 "" "pkg" (dispP p) (dispK c) (dispC p c)] render _ = [] -- | Syntax: :pkg : package : namespace : component : module : module -- -- > cabal build :pkg:foo:lib:foo:module:Data.Foo -- syntaxForm7MetaNamespacePackageKindComponentNamespaceModule :: [PackageInfo] -> Syntax syntaxForm7MetaNamespacePackageKindComponentNamespaceModule ps = syntaxForm7 render $ \str1 str2 str3 str4 str5 str6 str7 -> do guardNamespaceMeta str1 guardNamespacePackage str2 guardPackageName str3 ckind <- matchComponentKind str4 guardComponentName str5 guardNamespaceModule str6 p <- matchPackage ps str3 noFileStatus orNoThingIn "package" (display (packageName p)) $ do c <- matchComponentKindAndName (pinfoComponents p) ckind str5 orNoThingIn "component" (cinfoStrName c) $ do let ms = cinfoModules c m <- matchModuleName ms str7 return (TargetComponent p (cinfoName c) (ModuleTarget m)) where render (TargetComponent p c (ModuleTarget m)) = [TargetStringFileStatus7 "" "pkg" (dispP p) (dispK c) (dispC p c) "module" (dispM m)] render _ = [] -- | Syntax: :pkg : package : namespace : component : file : filename -- -- > cabal build :pkg:foo:lib:foo:file:Data/Foo.hs -- syntaxForm7MetaNamespacePackageKindComponentNamespaceFile :: [PackageInfo] -> Syntax syntaxForm7MetaNamespacePackageKindComponentNamespaceFile ps = syntaxForm7 render $ \str1 str2 str3 str4 str5 str6 str7 -> do guardNamespaceMeta str1 guardNamespacePackage str2 guardPackageName str3 ckind <- matchComponentKind str4 guardComponentName str5 guardNamespaceFile str6 p <- matchPackage ps str3 noFileStatus orNoThingIn "package" (display (packageName p)) $ do c <- matchComponentKindAndName (pinfoComponents p) ckind str5 orNoThingIn "component" (cinfoStrName c) $ do (filepath,_) <- matchComponentFile [c] str7 return (TargetComponent p (cinfoName c) (FileTarget filepath)) where render (TargetComponent p c (FileTarget f)) = [TargetStringFileStatus7 "" "pkg" (dispP p) (dispK c) (dispC p c) "file" f] render _ = [] --------------------------------------- -- Syntax utils -- type Match1 = String -> FileStatus -> Match (TargetSelector PackageInfo) type Match2 = String -> FileStatus -> String -> Match (TargetSelector PackageInfo) type Match3 = String -> FileStatus -> String -> String -> Match (TargetSelector PackageInfo) type Match4 = String -> String -> String -> String -> Match (TargetSelector PackageInfo) type Match5 = String -> String -> String -> String -> String -> Match (TargetSelector PackageInfo) type Match7 = String -> String -> String -> String -> String -> String -> String -> Match (TargetSelector PackageInfo) syntaxForm1 :: Renderer -> Match1 -> Syntax syntaxForm2 :: Renderer -> Match2 -> Syntax syntaxForm3 :: Renderer -> Match3 -> Syntax syntaxForm4 :: Renderer -> Match4 -> Syntax syntaxForm5 :: Renderer -> Match5 -> Syntax syntaxForm7 :: Renderer -> Match7 -> Syntax syntaxForm1 render f = Syntax QL1 match render where match = \(TargetStringFileStatus1 str1 fstatus1) -> f str1 fstatus1 syntaxForm2 render f = Syntax QL2 match render where match = \(TargetStringFileStatus2 str1 fstatus1 str2) -> f str1 fstatus1 str2 syntaxForm3 render f = Syntax QL3 match render where match = \(TargetStringFileStatus3 str1 fstatus1 str2 str3) -> f str1 fstatus1 str2 str3 syntaxForm4 render f = Syntax QLFull match render where match (TargetStringFileStatus4 str1 str2 str3 str4) = f str1 str2 str3 str4 match _ = mzero syntaxForm5 render f = Syntax QLFull match render where match (TargetStringFileStatus5 str1 str2 str3 str4 str5) = f str1 str2 str3 str4 str5 match _ = mzero syntaxForm7 render f = Syntax QLFull match render where match (TargetStringFileStatus7 str1 str2 str3 str4 str5 str6 str7) = f str1 str2 str3 str4 str5 str6 str7 match _ = mzero dispP :: Package p => p -> String dispP = display . packageName dispC :: Package p => p -> ComponentName -> String dispC = componentStringName dispK :: ComponentName -> String dispK = showComponentKindShort . componentKind dispF :: ComponentKind -> String dispF = showComponentKindFilterShort dispM :: ModuleName -> String dispM = display ------------------------------- -- Package and component info -- data PackageInfo = PackageInfo { pinfoId :: PackageId, pinfoLocation :: PackageLocation (), pinfoDirectory :: Maybe (FilePath, FilePath), pinfoPackageFile :: Maybe (FilePath, FilePath), pinfoComponents :: [ComponentInfo] } -- not instance of Show due to recursive construction data ComponentInfo = ComponentInfo { cinfoName :: ComponentName, cinfoStrName :: ComponentStringName, cinfoPackage :: PackageInfo, cinfoSrcDirs :: [FilePath], cinfoModules :: [ModuleName], cinfoHsFiles :: [FilePath], -- other hs files (like main.hs) cinfoCFiles :: [FilePath], cinfoJsFiles :: [FilePath] } -- not instance of Show due to recursive construction type ComponentStringName = String instance Package PackageInfo where packageId = pinfoId selectPackageInfo :: (Applicative m, Monad m) => DirActions m -> SourcePackage (PackageLocation a) -> m PackageInfo selectPackageInfo dirActions@DirActions{..} SourcePackage { packageDescription = pkg, packageSource = loc } = do (pkgdir, pkgfile) <- case loc of --TODO: local tarballs, remote tarballs etc LocalUnpackedPackage dir -> do dirabs <- canonicalizePath dir dirrel <- makeRelativeToCwd dirActions dirabs --TODO: ought to get this earlier in project reading let fileabs = dirabs </> display (packageName pkg) <.> "cabal" filerel = dirrel </> display (packageName pkg) <.> "cabal" exists <- doesFileExist fileabs return ( Just (dirabs, dirrel) , if exists then Just (fileabs, filerel) else Nothing ) _ -> return (Nothing, Nothing) let pinfo = PackageInfo { pinfoId = packageId pkg, pinfoLocation = fmap (const ()) loc, pinfoDirectory = pkgdir, pinfoPackageFile = pkgfile, pinfoComponents = selectComponentInfo pinfo (flattenPackageDescription pkg) } return pinfo selectComponentInfo :: PackageInfo -> PackageDescription -> [ComponentInfo] selectComponentInfo pinfo pkg = [ ComponentInfo { cinfoName = componentName c, cinfoStrName = componentStringName pkg (componentName c), cinfoPackage = pinfo, cinfoSrcDirs = ordNub (hsSourceDirs bi), -- [ pkgroot </> srcdir -- | (pkgroot,_) <- maybeToList (pinfoDirectory pinfo) -- , srcdir <- hsSourceDirs bi ], cinfoModules = ordNub (componentModules c), cinfoHsFiles = ordNub (componentHsFiles c), cinfoCFiles = ordNub (cSources bi), cinfoJsFiles = ordNub (jsSources bi) } | c <- pkgComponents pkg , let bi = componentBuildInfo c ] componentStringName :: Package pkg => pkg -> ComponentName -> ComponentStringName componentStringName pkg CLibName = display (packageName pkg) componentStringName _ (CSubLibName name) = unUnqualComponentName name componentStringName _ (CFLibName name) = unUnqualComponentName name componentStringName _ (CExeName name) = unUnqualComponentName name componentStringName _ (CTestName name) = unUnqualComponentName name componentStringName _ (CBenchName name) = unUnqualComponentName name componentModules :: Component -> [ModuleName] -- I think it's unlikely users will ask to build a requirement -- which is not mentioned locally. componentModules (CLib lib) = explicitLibModules lib componentModules (CFLib flib) = foreignLibModules flib componentModules (CExe exe) = exeModules exe componentModules (CTest test) = testModules test componentModules (CBench bench) = benchmarkModules bench componentHsFiles :: Component -> [FilePath] componentHsFiles (CExe exe) = [modulePath exe] componentHsFiles (CTest TestSuite { testInterface = TestSuiteExeV10 _ mainfile }) = [mainfile] componentHsFiles (CBench Benchmark { benchmarkInterface = BenchmarkExeV10 _ mainfile }) = [mainfile] componentHsFiles _ = [] ------------------------------ -- Matching meta targets -- guardNamespaceMeta :: String -> Match () guardNamespaceMeta = guardToken [""] "meta namespace" guardMetaAll :: String -> Match () guardMetaAll = guardToken ["all"] "meta-target 'all'" guardNamespacePackage :: String -> Match () guardNamespacePackage = guardToken ["pkg", "package"] "'pkg' namespace" guardNamespaceCwd :: String -> Match () guardNamespaceCwd = guardToken ["cwd"] "'cwd' namespace" guardNamespaceModule :: String -> Match () guardNamespaceModule = guardToken ["mod", "module"] "'module' namespace" guardNamespaceFile :: String -> Match () guardNamespaceFile = guardToken ["file"] "'file' namespace" guardToken :: [String] -> String -> String -> Match () guardToken tokens msg s | caseFold s `elem` tokens = increaseConfidence | otherwise = matchErrorExpected msg s ------------------------------ -- Matching component kinds -- componentKind :: ComponentName -> ComponentKind componentKind CLibName = LibKind componentKind (CSubLibName _) = LibKind componentKind (CFLibName _) = FLibKind componentKind (CExeName _) = ExeKind componentKind (CTestName _) = TestKind componentKind (CBenchName _) = BenchKind cinfoKind :: ComponentInfo -> ComponentKind cinfoKind = componentKind . cinfoName matchComponentKind :: String -> Match ComponentKind matchComponentKind s | s' `elem` liblabels = increaseConfidence >> return LibKind | s' `elem` fliblabels = increaseConfidence >> return FLibKind | s' `elem` exelabels = increaseConfidence >> return ExeKind | s' `elem` testlabels = increaseConfidence >> return TestKind | s' `elem` benchlabels = increaseConfidence >> return BenchKind | otherwise = matchErrorExpected "component kind" s where s' = caseFold s liblabels = ["lib", "library"] fliblabels = ["flib", "foreign-library"] exelabels = ["exe", "executable"] testlabels = ["tst", "test", "test-suite"] benchlabels = ["bench", "benchmark"] matchComponentKindFilter :: String -> Match ComponentKind matchComponentKindFilter s | s' `elem` liblabels = increaseConfidence >> return LibKind | s' `elem` fliblabels = increaseConfidence >> return FLibKind | s' `elem` exelabels = increaseConfidence >> return ExeKind | s' `elem` testlabels = increaseConfidence >> return TestKind | s' `elem` benchlabels = increaseConfidence >> return BenchKind | otherwise = matchErrorExpected "component kind filter" s where s' = caseFold s liblabels = ["libs", "libraries"] fliblabels = ["flibs", "foreign-libraries"] exelabels = ["exes", "executables"] testlabels = ["tests", "test-suites"] benchlabels = ["benches", "benchmarks"] showComponentKind :: ComponentKind -> String showComponentKind LibKind = "library" showComponentKind FLibKind = "foreign library" showComponentKind ExeKind = "executable" showComponentKind TestKind = "test-suite" showComponentKind BenchKind = "benchmark" showComponentKindShort :: ComponentKind -> String showComponentKindShort LibKind = "lib" showComponentKindShort FLibKind = "flib" showComponentKindShort ExeKind = "exe" showComponentKindShort TestKind = "test" showComponentKindShort BenchKind = "bench" showComponentKindFilterShort :: ComponentKind -> String showComponentKindFilterShort LibKind = "libs" showComponentKindFilterShort FLibKind = "flibs" showComponentKindFilterShort ExeKind = "exes" showComponentKindFilterShort TestKind = "tests" showComponentKindFilterShort BenchKind = "benchmarks" ------------------------------ -- Matching package targets -- guardPackage :: String -> FileStatus -> Match () guardPackage str fstatus = guardPackageName str <|> guardPackageDir str fstatus <|> guardPackageFile str fstatus guardPackageName :: String -> Match () guardPackageName s | validPackageName s = increaseConfidence | otherwise = matchErrorExpected "package name" s validPackageName :: String -> Bool validPackageName s = all validPackageNameChar s && not (null s) where validPackageNameChar c = isAlphaNum c || c == '-' guardPackageDir :: String -> FileStatus -> Match () guardPackageDir _ (FileStatusExistsDir _) = increaseConfidence guardPackageDir str _ = matchErrorExpected "package directory" str guardPackageFile :: String -> FileStatus -> Match () guardPackageFile _ (FileStatusExistsFile file) | takeExtension file == ".cabal" = increaseConfidence guardPackageFile str _ = matchErrorExpected "package .cabal file" str matchPackage :: [PackageInfo] -> String -> FileStatus -> Match PackageInfo matchPackage pinfo = \str fstatus -> orNoThingIn "project" "" $ matchPackageName pinfo str <//> (matchPackageDir pinfo str fstatus <|> matchPackageFile pinfo str fstatus) matchPackageName :: [PackageInfo] -> String -> Match PackageInfo matchPackageName ps = \str -> do guard (validPackageName str) orNoSuchThing "package" str (map (display . packageName) ps) $ increaseConfidenceFor $ matchInexactly caseFold (display . packageName) ps str matchPackageDir :: [PackageInfo] -> String -> FileStatus -> Match PackageInfo matchPackageDir ps = \str fstatus -> case fstatus of FileStatusExistsDir canondir -> orNoSuchThing "package directory" str (map (snd . fst) dirs) $ increaseConfidenceFor $ fmap snd $ matchExactly (fst . fst) dirs canondir _ -> mzero where dirs = [ ((dabs,drel),p) | p@PackageInfo{ pinfoDirectory = Just (dabs,drel) } <- ps ] matchPackageFile :: [PackageInfo] -> String -> FileStatus -> Match PackageInfo matchPackageFile ps = \str fstatus -> do case fstatus of FileStatusExistsFile canonfile -> orNoSuchThing "package .cabal file" str (map (snd . fst) files) $ increaseConfidenceFor $ fmap snd $ matchExactly (fst . fst) files canonfile _ -> mzero where files = [ ((fabs,frel),p) | p@PackageInfo{ pinfoPackageFile = Just (fabs,frel) } <- ps ] --TODO: test outcome when dir exists but doesn't match any known one --TODO: perhaps need another distinction, vs no such thing, point is the -- thing is not known, within the project, but could be outside project ------------------------------ -- Matching component targets -- guardComponentName :: String -> Match () guardComponentName s | all validComponentChar s && not (null s) = increaseConfidence | otherwise = matchErrorExpected "component name" s where validComponentChar c = isAlphaNum c || c == '.' || c == '_' || c == '-' || c == '\'' matchComponentName :: [ComponentInfo] -> String -> Match ComponentInfo matchComponentName cs str = orNoSuchThing "component" str (map cinfoStrName cs) $ increaseConfidenceFor $ matchInexactly caseFold cinfoStrName cs str matchComponentKindAndName :: [ComponentInfo] -> ComponentKind -> String -> Match ComponentInfo matchComponentKindAndName cs ckind str = orNoSuchThing (showComponentKind ckind ++ " component") str (map render cs) $ increaseConfidenceFor $ matchInexactly (\(ck, cn) -> (ck, caseFold cn)) (\c -> (cinfoKind c, cinfoStrName c)) cs (ckind, str) where render c = showComponentKindShort (cinfoKind c) ++ ":" ++ cinfoStrName c ------------------------------ -- Matching module targets -- guardModuleName :: String -> Match () guardModuleName s = case simpleParse s :: Maybe ModuleName of Just _ -> increaseConfidence _ | all validModuleChar s && not (null s) -> return () | otherwise -> matchErrorExpected "module name" s where validModuleChar c = isAlphaNum c || c == '.' || c == '_' || c == '\'' matchModuleName :: [ModuleName] -> String -> Match ModuleName matchModuleName ms str = orNoSuchThing "module" str (map display ms) $ increaseConfidenceFor $ matchInexactly caseFold display ms str matchModuleNameAnd :: [(ModuleName, a)] -> String -> Match (ModuleName, a) matchModuleNameAnd ms str = orNoSuchThing "module" str (map (display . fst) ms) $ increaseConfidenceFor $ matchInexactly caseFold (display . fst) ms str ------------------------------ -- Matching file targets -- matchPackageDirectoryPrefix :: [PackageInfo] -> FileStatus -> Match (FilePath, PackageInfo) matchPackageDirectoryPrefix ps (FileStatusExistsFile filepath) = increaseConfidenceFor $ matchDirectoryPrefix pkgdirs filepath where pkgdirs = [ (dir, p) | p@PackageInfo { pinfoDirectory = Just (dir,_) } <- ps ] matchPackageDirectoryPrefix _ _ = mzero matchComponentFile :: [ComponentInfo] -> String -> Match (FilePath, ComponentInfo) matchComponentFile cs str = orNoSuchThing "file" str [] $ matchComponentModuleFile cs str <|> matchComponentOtherFile cs str matchComponentOtherFile :: [ComponentInfo] -> String -> Match (FilePath, ComponentInfo) matchComponentOtherFile cs = matchFile [ (file, c) | c <- cs , file <- cinfoHsFiles c ++ cinfoCFiles c ++ cinfoJsFiles c ] matchComponentModuleFile :: [ComponentInfo] -> String -> Match (FilePath, ComponentInfo) matchComponentModuleFile cs str = do matchFile [ (normalise (d </> toFilePath m), c) | c <- cs , d <- cinfoSrcDirs c , m <- cinfoModules c ] (dropExtension (normalise str)) -- utils matchFile :: [(FilePath, a)] -> FilePath -> Match (FilePath, a) matchFile fs = increaseConfidenceFor . matchInexactly caseFold fst fs matchDirectoryPrefix :: [(FilePath, a)] -> FilePath -> Match (FilePath, a) matchDirectoryPrefix dirs filepath = tryEach $ [ (file, x) | (dir,x) <- dirs , file <- maybeToList (stripDirectory dir) ] where stripDirectory :: FilePath -> Maybe FilePath stripDirectory dir = joinPath `fmap` stripPrefix (splitDirectories dir) filepathsplit filepathsplit = splitDirectories filepath ------------------------------ -- Matching monad -- -- | A matcher embodies a way to match some input as being some recognised -- value. In particular it deals with multiple and ambiguous matches. -- -- There are various matcher primitives ('matchExactly', 'matchInexactly'), -- ways to combine matchers ('matchPlus', 'matchPlusShadowing') and finally we -- can run a matcher against an input using 'findMatch'. -- data Match a = NoMatch Confidence [MatchError] | ExactMatch Confidence [a] | InexactMatch Confidence [a] deriving Show type Confidence = Int data MatchError = MatchErrorExpected String String -- thing got | MatchErrorNoSuch String String [String] -- thing got alts | MatchErrorIn String String MatchError -- kind thing deriving (Show, Eq) instance Functor Match where fmap _ (NoMatch d ms) = NoMatch d ms fmap f (ExactMatch d xs) = ExactMatch d (fmap f xs) fmap f (InexactMatch d xs) = InexactMatch d (fmap f xs) instance Applicative Match where pure a = ExactMatch 0 [a] (<*>) = ap instance Alternative Match where empty = NoMatch 0 [] (<|>) = matchPlus instance Monad Match where return = pure NoMatch d ms >>= _ = NoMatch d ms ExactMatch d xs >>= f = addDepth d $ msum (map f xs) InexactMatch d xs >>= f = addDepth d . forceInexact $ msum (map f xs) instance MonadPlus Match where mzero = empty mplus = matchPlus (<//>) :: Match a -> Match a -> Match a (<//>) = matchPlusShadowing infixl 3 <//> addDepth :: Confidence -> Match a -> Match a addDepth d' (NoMatch d msgs) = NoMatch (d'+d) msgs addDepth d' (ExactMatch d xs) = ExactMatch (d'+d) xs addDepth d' (InexactMatch d xs) = InexactMatch (d'+d) xs forceInexact :: Match a -> Match a forceInexact (ExactMatch d ys) = InexactMatch d ys forceInexact m = m -- | Combine two matchers. Exact matches are used over inexact matches -- but if we have multiple exact, or inexact then the we collect all the -- ambiguous matches. -- -- This operator is associative, has unit 'mzero' and is also commutative. -- matchPlus :: Match a -> Match a -> Match a matchPlus (ExactMatch d1 xs) (ExactMatch d2 xs') = ExactMatch (max d1 d2) (xs ++ xs') matchPlus a@(ExactMatch _ _ ) (InexactMatch _ _ ) = a matchPlus a@(ExactMatch _ _ ) (NoMatch _ _ ) = a matchPlus (InexactMatch _ _ ) b@(ExactMatch _ _ ) = b matchPlus (InexactMatch d1 xs) (InexactMatch d2 xs') = InexactMatch (max d1 d2) (xs ++ xs') matchPlus a@(InexactMatch _ _ ) (NoMatch _ _ ) = a matchPlus (NoMatch _ _ ) b@(ExactMatch _ _ ) = b matchPlus (NoMatch _ _ ) b@(InexactMatch _ _ ) = b matchPlus a@(NoMatch d1 ms) b@(NoMatch d2 ms') | d1 > d2 = a | d1 < d2 = b | otherwise = NoMatch d1 (ms ++ ms') -- | Combine two matchers. This is similar to 'matchPlus' with the -- difference that an exact match from the left matcher shadows any exact -- match on the right. Inexact matches are still collected however. -- -- This operator is associative, has unit 'mzero' and is not commutative. -- matchPlusShadowing :: Match a -> Match a -> Match a matchPlusShadowing a@(ExactMatch _ _) _ = a matchPlusShadowing a b = matchPlus a b ------------------------------ -- Various match primitives -- matchErrorExpected :: String -> String -> Match a matchErrorExpected thing got = NoMatch 0 [MatchErrorExpected thing got] matchErrorNoSuch :: String -> String -> [String] -> Match a matchErrorNoSuch thing got alts = NoMatch 0 [MatchErrorNoSuch thing got alts] expecting :: String -> String -> Match a -> Match a expecting thing got (NoMatch 0 _) = matchErrorExpected thing got expecting _ _ m = m orNoSuchThing :: String -> String -> [String] -> Match a -> Match a orNoSuchThing thing got alts (NoMatch 0 _) = matchErrorNoSuch thing got alts orNoSuchThing _ _ _ m = m orNoThingIn :: String -> String -> Match a -> Match a orNoThingIn kind name (NoMatch n ms) = NoMatch n [ MatchErrorIn kind name m | m <- ms ] orNoThingIn _ _ m = m increaseConfidence :: Match () increaseConfidence = ExactMatch 1 [()] increaseConfidenceFor :: Match a -> Match a increaseConfidenceFor m = m >>= \r -> increaseConfidence >> return r nubMatchesBy :: (a -> a -> Bool) -> Match a -> Match a nubMatchesBy _ (NoMatch d msgs) = NoMatch d msgs nubMatchesBy eq (ExactMatch d xs) = ExactMatch d (nubBy eq xs) nubMatchesBy eq (InexactMatch d xs) = InexactMatch d (nubBy eq xs) -- | Lift a list of matches to an exact match. -- exactMatches, inexactMatches :: [a] -> Match a exactMatches [] = mzero exactMatches xs = ExactMatch 0 xs inexactMatches [] = mzero inexactMatches xs = InexactMatch 0 xs tryEach :: [a] -> Match a tryEach = exactMatches ------------------------------ -- Top level match runner -- -- | Given a matcher and a key to look up, use the matcher to find all the -- possible matches. There may be 'None', a single 'Unambiguous' match or -- you may have an 'Ambiguous' match with several possibilities. -- findMatch :: Match a -> MaybeAmbiguous a findMatch match = case match of NoMatch _ msgs -> None msgs ExactMatch _ [x] -> Unambiguous x InexactMatch _ [x] -> Unambiguous x ExactMatch _ [] -> error "findMatch: impossible: ExactMatch []" InexactMatch _ [] -> error "findMatch: impossible: InexactMatch []" ExactMatch _ xs -> Ambiguous True xs InexactMatch _ xs -> Ambiguous False xs data MaybeAmbiguous a = None [MatchError] | Unambiguous a | Ambiguous Bool [a] deriving Show ------------------------------ -- Basic matchers -- -- | A primitive matcher that looks up a value in a finite 'Map'. The -- value must match exactly. -- matchExactly :: Ord k => (a -> k) -> [a] -> (k -> Match a) matchExactly key xs = \k -> case Map.lookup k m of Nothing -> mzero Just ys -> exactMatches ys where m = Map.fromListWith (++) [ (key x, [x]) | x <- xs ] -- | A primitive matcher that looks up a value in a finite 'Map'. It checks -- for an exact or inexact match. We get an inexact match if the match -- is not exact, but the canonical forms match. It takes a canonicalisation -- function for this purpose. -- -- So for example if we used string case fold as the canonicalisation -- function, then we would get case insensitive matching (but it will still -- report an exact match when the case matches too). -- matchInexactly :: (Ord k, Ord k') => (k -> k') -> (a -> k) -> [a] -> (k -> Match a) matchInexactly cannonicalise key xs = \k -> case Map.lookup k m of Just ys -> exactMatches ys Nothing -> case Map.lookup (cannonicalise k) m' of Just ys -> inexactMatches ys Nothing -> mzero where m = Map.fromListWith (++) [ (key x, [x]) | x <- xs ] -- the map of canonicalised keys to groups of inexact matches m' = Map.mapKeysWith (++) cannonicalise m ------------------------------ -- Utils -- caseFold :: String -> String caseFold = lowercase ------------------------------ -- Example inputs -- {- ex1pinfo :: [PackageInfo] ex1pinfo = [ addComponent (CExeName (mkUnqualComponentName "foo-exe")) [] ["Data.Foo"] $ PackageInfo { pinfoId = PackageIdentifier (mkPackageName "foo") (mkVersion [1]), pinfoLocation = LocalUnpackedPackage "/the/foo", pinfoDirectory = Just ("/the/foo", "foo"), pinfoPackageFile = Just ("/the/foo/foo.cabal", "foo/foo.cabal"), pinfoComponents = [] } , PackageInfo { pinfoId = PackageIdentifier (mkPackageName "bar") (mkVersion [1]), pinfoLocation = LocalUnpackedPackage "/the/foo", pinfoDirectory = Just ("/the/bar", "bar"), pinfoPackageFile = Just ("/the/bar/bar.cabal", "bar/bar.cabal"), pinfoComponents = [] } ] where addComponent n ds ms p = p { pinfoComponents = ComponentInfo n (componentStringName (pinfoId p) n) p ds (map mkMn ms) [] [] [] : pinfoComponents p } mkMn :: String -> ModuleName mkMn = ModuleName.fromString -} {- stargets = [ TargetComponent (CExeName "foo") WholeComponent , TargetComponent (CExeName "foo") (ModuleTarget (mkMn "Foo")) , TargetComponent (CExeName "tst") (ModuleTarget (mkMn "Foo")) ] where mkMn :: String -> ModuleName mkMn = fromJust . simpleParse ex_pkgid :: PackageIdentifier Just ex_pkgid = simpleParse "thelib" -} {- ex_cs :: [ComponentInfo] ex_cs = [ (mkC (CExeName "foo") ["src1", "src1/src2"] ["Foo", "Src2.Bar", "Bar"]) , (mkC (CExeName "tst") ["src1", "test"] ["Foo"]) ] where mkC n ds ms = ComponentInfo n (componentStringName n) ds (map mkMn ms) mkMn :: String -> ModuleName mkMn = fromJust . simpleParse pkgid :: PackageIdentifier Just pkgid = simpleParse "thelib" -}
mydaum/cabal
cabal-install/Distribution/Client/TargetSelector.hs
bsd-3-clause
81,003
0
26
20,979
19,096
9,850
9,246
1,445
13
import Data.List (intersperse) import qualified Data.Vector.Storable as V import qualified Data.Vector.Storable.Mutable as VM import DistanceTransform.Euclidean3D import Text.Printf import qualified DistanceTransform.Meijster2D as M2D import qualified DistanceTransform.Meijster as Mn testRes :: Int testRes = 9 -- A cube of zeros with a one at the center. testData :: V.Vector Int testData = V.create $ do v <- VM.replicate (testRes^3) 1 VM.write v (4*testRes^2+4*testRes+4) 0 return v showSquare :: VM.Storable a => Int -> (a -> String) -> V.Vector a -> IO () showSquare res shw v = do putStr "[" putStrLn (head rows') mapM_ (putStrLn . (" "++)) (take (res - 2) $ tail rows') putStr (" "++last rows') putStrLn "]" where rows = map showRow [0..res-1] rows' = map (concat . intersperse " " . map pad) rows showRow r = map shw . V.toList $ V.slice (r*res) res v maxWord = maximum $ map (maximum . map length) rows pad w = let d = maxWord - length w in if d > 0 then replicate d ' ' ++ w else w showCube :: VM.Storable a => Int -> (a -> String) -> V.Vector a -> IO () showCube res shw v = mapM_ ((>> putStrLn "") . showPlane) [0..res-1] where showPlane z = showSquare res shw $ V.slice (z*res*res) (res*res) v testDT = edt testRes testData testDT2 = Mn.edt [testRes,testRes,testRes] testData showDT2 = showCube testRes (printf "%0.1f") testDT2 showDT = showCube testRes (printf "%0.1f") testDT testDT2D = showSquare testRes (printf "%0.1f") . M2D.edt testRes testRes $ V.create $ do v <- VM.replicate (testRes^2) 1 VM.write v (4*testRes+4) 0 return v testDTND = showSquare testRes (printf "%0.1f") . Mn.edt [testRes,testRes] $ V.create $ do v <- VM.replicate (testRes^2) 1 VM.write v (4*testRes+4) 0 return v
acowley/DistanceTransform
src/tests/Test1.hs
bsd-3-clause
2,104
0
14
683
814
411
403
43
2
{-# LANGUAGE OverloadedStrings #-} module Dipper.Core.Examples where import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as T import Data.Tuple.Strict (Pair(..)) import Dipper.Core.Types ------------------------------------------------------------------------ example1 :: Term String () example1 = Let x0 (Read input) $ Let x1 (ConcatMap (\x -> [x + 1]) (Var x0)) $ Let x2 (ConcatMap (\x -> [x * 2]) (Var x0)) $ Let x3 (Concat [Var x1, Var x2]) $ Write output (Var x3) $ Return (Const []) where input = MapperInput "input.csv" :: Input Int output = ReducerOutput "output.csv" :: Output Int x0 = "x0" x1 = "x1" x2 = "x2" x3 = "x3" ------------------------------------------------------------------------ example2 :: Term String () example2 = Let i1 (Read input1) $ Let a (ConcatMap add1 (Var i1)) $ Let write1 (ConcatMap add1 (Var a)) $ Write output1 (Var write1) $ Let jtag1 (ConcatMap (tag 1) (Var a)) $ Let i2 (Read input2) $ Let i3 (Read input3) $ Let b (ConcatMap add1 (Var i2)) $ Let c (ConcatMap add1 (Var i3)) $ Let fltn (Concat [Var b, Var c]) $ Let d (ConcatMap add1 (Var fltn)) $ Let jtag2 (ConcatMap (tag 2) (Var d)) $ Let i4 (Read input4) $ Let gmap (ConcatMap kv_add1 (Var i4)) $ Let ggbk (GroupByKey (Var gmap)) $ Let gcv (FoldValues (+) (Var ggbk)) $ Let e (ConcatMap untag (Var gcv)) $ Let jtag3 (ConcatMap (tag 3) (Var e)) $ Let jfltn (Concat [Var jtag1, Var jtag2, Var jtag3]) $ Let jgbk (GroupByKey (Var jfltn)) $ Let juntag (ConcatMap untag (Var jgbk)) $ Let f (ConcatMap (:[]) (Var juntag)) $ Let write2 (Concat [Var f]) $ Write output2 (Var write2) $ Return (Const []) where add1 :: Int -> [Int] add1 x = [x+1] kv_add1 :: Pair Text Int -> [Pair Text Int] kv_add1 (k :!: v) = [k :!: v+1] tag :: Int -> a -> [Pair Int a] tag ix x = [ix :!: x] untag :: Pair k v -> [v] untag (_ :!: x) = [x] -- i/o input1 = MapperInput "input1.csv" input2 = MapperInput "input2.csv" input3 = MapperInput "input3.csv" input4 = MapperInput "input4.csv" output1 = ReducerOutput "output1.csv" output2 = ReducerOutput "output2.csv" -- names i1 = "input1" i2 = "input2" i3 = "input3" i4 = "input4" a = "A" b = "B" c = "C" d = "D" e = "E" f = "F" fltn = "Fltn" gmap = "G:Map" ggbk = "G:GBK" gcv = "G:CV" jtag1 = "J:Tag1" jtag2 = "J:Tag2" jtag3 = "J:Tag3" jfltn = "J:Fltn" jgbk = "J:GBK" juntag = "J:Untag" write1 = "write1" write2 = "write2" ------------------------------------------------------------------------ example3 :: Term String () example3 = Let i1 (Read input1) $ Let i2 (Read input2) $ Let i3 (Read input3) $ Let concat1 (Concat [Var i1, Var i2]) $ Let concat2 (Concat [Var i2, Var i3]) $ Let text1 (ConcatMap (\(k :!: v) -> [k :!: T.pack (show v)]) (Var concat1)) $ Let gbk1 (GroupByKey (Var text1)) $ Let gbk2 (GroupByKey (Var concat2)) $ Let mklist1 (ConcatMap (\(k :!: v) -> [k :!: [v]]) (Var gbk1)) $ Let mklist2 (ConcatMap (\(k :!: v) -> [k :!: [v]]) (Var gbk2)) $ Let foldlist1 (FoldValues (++) (Var mklist1)) $ Let foldlist2 (FoldValues (++) (Var mklist2)) $ Write output1 (Var foldlist1) $ Write output2 (Var foldlist2) $ Return (Const []) where input1 = MapperInput "in-1.csv" :: Input (Pair Text Int) input2 = MapperInput "in-2.csv" input3 = MapperInput "in-3.csv" output1 = ReducerOutput "out-1.csv" :: Output (Pair Text [Text]) output2 = ReducerOutput "out-2.csv" :: Output (Pair Text [Int]) i1 = "input1" i2 = "input2" i3 = "input3" text1 = "text1" concat1 = "concat1" concat2 = "concat2" gbk1 = "gbk1" gbk2 = "gbk2" mklist1 = "mklist1" mklist2 = "mklist2" foldlist1 = "foldlist1" foldlist2 = "foldlist2" ------------------------------------------------------------------------ example4 :: Term String () example4 = Let x0 (Read input) $ Let x1 (ConcatMap (\(k :!: v) -> [k :!: T.toUpper v]) (Var x0)) $ Let x2 (GroupByKey (Var x1)) $ Write output3 (Var x2) $ Let x3 (FoldValues (\x y -> x <> ", " <> y) (Var x2)) $ Let x4 (GroupByKey (Var x3)) $ Let x5 (ConcatMap (\(k :!: _) -> [k :!: (1 :: Int)]) (Var x2)) $ Let x6 (FoldValues (+) (Var x5)) $ Let x7 (ConcatMap (\(k :!: v) -> [k :!: T.pack (show v)]) (Var x6)) $ Let x8 (GroupByKey (Var x7)) $ Write output1 (Var x4) $ Write output2 (Var x8) $ Return (Const []) where input = MapperInput "input.csv" :: Input (Pair Text Text) output1 = ReducerOutput "output1.csv" :: Output (Pair Text Text) output2 = ReducerOutput "output2.csv" :: Output (Pair Text Text) output3 = ReducerOutput "output3.csv" :: Output (Pair Text Text) x0 = "x0" x1 = "x1" x2 = "x2" x3 = "x3" x4 = "x4" x5 = "x5" x6 = "x6" x7 = "x7" x8 = "x8"
jystic/dipper
src/Dipper/Core/Examples.hs
bsd-3-clause
5,294
0
33
1,574
2,210
1,142
1,068
146
1
module Snap.Snaplet.Neo4j ( Neo4jSnaplet , HasNeo4j(..) , neo4jInit , withNeo4j , withNeo4jSnaplet ) where import Snap.Snaplet.Neo4j.Internal
zearen-wover/snaplet-neo4j
src/Snap/Snaplet/Neo4j.hs
bsd-3-clause
155
0
5
29
35
24
11
7
0
-------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ARB.GetTextureSubImage -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ARB.GetTextureSubImage ( -- * Extension Support glGetARBGetTextureSubImage, gl_ARB_get_texture_sub_image, -- * Functions glGetCompressedTextureSubImage, glGetTextureSubImage ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/ARB/GetTextureSubImage.hs
bsd-3-clause
673
0
4
89
47
36
11
7
0
{-# LANGUAGE OverloadedStrings #-} module Parser.CSV (parse) where import Control.Exception import qualified Data.Csv as C import qualified Data.ByteString.Lazy as LBS import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.Sequence as S import qualified Data.Vector as V import Parser.Base parse :: T.Text -> Transactions parse t = case csvToSeq <$> parseCSV t of Left err -> throw $ ParserException (T.pack err) Right xs -> S.fromList $ map mkTransaction xs csvToSeq :: V.Vector [T.Text] -> [S.Seq T.Text] csvToSeq = map S.fromList . drop 2 . V.toList parseCSV :: T.Text -> Either String (V.Vector [T.Text]) parseCSV = C.decode C.NoHeader . LBS.fromStrict . TE.encodeUtf8
ostronom/pokerstars-audit
src/Parser/CSV.hs
bsd-3-clause
728
0
12
118
251
140
111
18
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Text.RE.Types.CaptureID where import Data.Ix import Data.Hashable import qualified Data.HashMap.Strict as HMS import Data.Maybe import qualified Data.Text as T -- | CaptureID identifies captures, either by number -- (e.g., [cp|1|]) or name (e.g., [cp|foo|]). data CaptureID = IsCaptureOrdinal CaptureOrdinal -- [cp|3|] | IsCaptureName CaptureName -- [cp|y|] deriving (Show,Ord,Eq) -- | the dictionary for named captures stored in compiled regular -- expressions associates type CaptureNames = HMS.HashMap CaptureName CaptureOrdinal -- | an empty 'CaptureNames' dictionary noCaptureNames :: CaptureNames noCaptureNames = HMS.empty -- | a 'CaptureName' is just the text of the name newtype CaptureName = CaptureName { getCaptureName :: T.Text } deriving (Show,Ord,Eq) instance Hashable CaptureName where hashWithSalt i = hashWithSalt i . getCaptureName -- | a 'CaptureOrdinal' is just the number of the capture, starting -- with 0 for the whole of the text matched, then in leftmost, -- outermost newtype CaptureOrdinal = CaptureOrdinal { getCaptureOrdinal :: Int } deriving (Show,Ord,Eq,Enum,Ix,Num) -- | look up a 'CaptureID' in the 'CaptureNames' dictionary findCaptureID :: CaptureID -> CaptureNames -> Int findCaptureID (IsCaptureOrdinal o) _ = getCaptureOrdinal o findCaptureID (IsCaptureName n) hms = getCaptureOrdinal $ fromMaybe oops $ HMS.lookup n hms where oops = error $ unlines $ ("lookupCaptureID: " ++ T.unpack t ++ " not found in:") : [ " "++T.unpack (getCaptureName nm) | nm <- HMS.keys hms ] t = getCaptureName n
Lainepress/easy
Text/RE/Types/CaptureID.hs
bsd-3-clause
1,708
0
13
353
340
192
148
28
1
{-# LANGUAGE RankNTypes #-} {- | For those who like lenses, here are Lens library versions of the functions from "Pipes.Break.Text" To learn more about using lenses to manipulate pipes, check out the in depth tutorial at <http://hackage.haskell.org/package/pipes-group/docs/Pipes-Group-Tutorial.html> Due to the fact that the endsBy family of functions are non invertible, it doesn't make much sense to encourage their use as lenses. For example, if your protocol were blocks of lines delimited by a double newline at the end (such as in email or http). >>> fmap mconcat <$> P.toListM $ >>> over (endsBy "\n\n" . individually) (over (endsBy "\n" . individually) id) >>> (yield "A\nB\n\nA\nB\nC\n\n") "A\nB\n\n\nA\nB\nC\n\n\n\n\n" As you can see, this would result in the wrong number of newlines being appended when reforming. -} module Pipes.Break.ByteString.Lens ( -- * Grouping producers by a delimiter -- -- $breakbyoverview breaksBy, unBreaksBy, ) where import Pipes as P import Pipes.Group as P import qualified Data.ByteString as B import Pipes.Break.Internal type Lens' a b = forall f . Functor f => (b -> f b) -> (a -> f a) {- $breakbyoverview >>> fmap mconcat <$> P.toListM $ >>> over (breaksBy "\n\n" . individually) (over (breaksBy "\n" . individually) (<* yield "!")) >>> (P.each ["A\nB","\n\n","A","","\nB\nC","\n\n"]) "A!\nB!\n\nA!\nB!\nC!\n\n" -} breaksBy :: Monad m => B.ByteString -> Lens' (Producer B.ByteString m r) (FreeT (Producer B.ByteString m) m r) breaksBy del k p' = fmap (_unBreaksBy del) (k (_breaksBy del p')) unBreaksBy :: Monad m => B.ByteString -> Lens' (FreeT (Producer B.ByteString m) m r) (Producer B.ByteString m r) unBreaksBy del k p' = fmap (_breaksBy del) (k (_unBreaksBy del p'))
mindreader/pipes-break
src/Pipes/Break/ByteString/Lens.hs
bsd-3-clause
1,785
0
12
328
277
151
126
12
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE LambdaCase #-} -------------------------------------------------------------------------------- -- | -- Module : Database.EventStore.Internal.Connection -- Copyright : (C) 2017 Yorick Laupa -- License : (see the file LICENSE) -- -- Maintainer : Yorick Laupa <yo.eight@gmail.com> -- Stability : provisional -- Portability : non-portable -- -------------------------------------------------------------------------------- module Database.EventStore.Internal.Connection ( ConnectionBuilder(..) , Connection(..) , RecvOutcome(..) , PackageArrived(..) , ConnectionError(..) , ConnectionEstablished(..) , ConnectionClosed(..) , ConnectionRef(..) , getConnection , connectionBuilder , connectionError ) where -------------------------------------------------------------------------------- import Prelude (String) import Text.Printf -------------------------------------------------------------------------------- import Control.Monad.Reader import Data.Serialize import Data.UUID import qualified Network.Connection as Network -------------------------------------------------------------------------------- import Database.EventStore.Internal.Command import Database.EventStore.Internal.Control import Database.EventStore.Internal.EndPoint import Database.EventStore.Internal.Logger import Database.EventStore.Internal.Prelude import Database.EventStore.Internal.Types -------------------------------------------------------------------------------- newtype ConnectionBuilder = ConnectionBuilder { connect :: EndPoint -> EventStore Connection } -------------------------------------------------------------------------------- data RecvOutcome = ResetByPeer | Recv Package | WrongFraming | ParsingError -------------------------------------------------------------------------------- type ConnectionId = UUID -------------------------------------------------------------------------------- newtype ConnectionRef = ConnectionRef { maybeConnection :: EventStore (Maybe Connection) } -------------------------------------------------------------------------------- getConnection :: ConnectionRef -> EventStore Connection getConnection ref = maybeConnection ref >>= \case Just conn -> return conn Nothing -> do $(logError) "Expected a connection but got none." throwString "No current connection (impossible situation)" -------------------------------------------------------------------------------- data Connection = Connection { connectionId :: ConnectionId , connectionEndPoint :: EndPoint , enqueuePackage :: Package -> EventStore () , dispose :: EventStore () } -------------------------------------------------------------------------------- instance Show Connection where show Connection{..} = "Connection [" <> show connectionId <> "] on " <> show connectionEndPoint -------------------------------------------------------------------------------- instance Eq Connection where a == b = connectionId a == connectionId b -------------------------------------------------------------------------------- newtype ConnectionState = ConnectionState { _sendQueue :: TBMQueue Package } -------------------------------------------------------------------------------- data PackageArrived = PackageArrived Connection Package deriving Typeable -------------------------------------------------------------------------------- data ConnectionError = ConnectionError Connection SomeException deriving Typeable -------------------------------------------------------------------------------- connectionError :: Exception e => Connection -> e -> ConnectionError connectionError c = ConnectionError c . toException -------------------------------------------------------------------------------- data ConnectionClosed = ConnectionClosed Connection SomeException deriving Typeable -------------------------------------------------------------------------------- data ConnectionEstablished = ConnectionEstablished Connection deriving Typeable -------------------------------------------------------------------------------- newtype ConnectionResetByPeer = ConnectionResetByPeer SomeException deriving Typeable -------------------------------------------------------------------------------- instance Show ConnectionResetByPeer where show (ConnectionResetByPeer reason) = "Connection reset by peer: " <> show reason -------------------------------------------------------------------------------- instance Exception ConnectionResetByPeer -------------------------------------------------------------------------------- data ProtocolError = WrongFramingError !String | PackageParsingError !String deriving Typeable -------------------------------------------------------------------------------- instance Show ProtocolError where show (WrongFramingError reason) = "Package framing error: " <> reason show (PackageParsingError reason) = "Package parsing error: " <> reason -------------------------------------------------------------------------------- instance Exception ProtocolError -------------------------------------------------------------------------------- connectionBuilder :: Settings -> IO ConnectionBuilder connectionBuilder setts = do ctx <- Network.initConnectionContext return $ ConnectionBuilder $ \ept -> do cid <- freshUUID state <- createState mfix $ \self -> do tcpConnAsync <- async $ tryAny (createConnection setts ctx ept) >>= \case Left e -> do publish (ConnectionClosed self e) throw e Right conn -> do publish (ConnectionEstablished self) return conn sendAsync <- async (sending state self tcpConnAsync) recvAsync <- async (receiving state self tcpConnAsync) return Connection { connectionId = cid , connectionEndPoint = ept , enqueuePackage = enqueue state , dispose = do closeState state disposeConnection tcpConnAsync cancel sendAsync cancel recvAsync } -------------------------------------------------------------------------------- createState :: EventStore ConnectionState createState = ConnectionState <$> liftIO (newTBMQueueIO 500) -------------------------------------------------------------------------------- closeState :: ConnectionState -> EventStore () closeState ConnectionState{..} = atomically $ closeTBMQueue _sendQueue -------------------------------------------------------------------------------- createConnection :: Settings -> Network.ConnectionContext -> EndPoint -> EventStore Network.Connection createConnection setts ctx ept = liftIO $ Network.connectTo ctx params where host = endPointIp ept port = fromIntegral $ endPointPort ept params = Network.ConnectionParams host port (s_ssl setts) Nothing -------------------------------------------------------------------------------- disposeConnection :: Async Network.Connection -> EventStore () disposeConnection as = traverse_ tryDisposing =<< poll as where tryDisposing = traverse_ disposing disposing = liftIO . Network.connectionClose -------------------------------------------------------------------------------- receivePackage :: Connection -> Network.Connection -> EventStore Package receivePackage self conn = tryAny (liftIO $ Network.connectionGetExact conn 4) >>= \case Left e -> do publish (ConnectionClosed self e) throw e Right frame -> case runGet getLengthPrefix frame of Left reason -> do let cause = WrongFramingError reason publish (connectionError self cause) throw cause Right prefix -> do tryAny (liftIO $ Network.connectionGetExact conn prefix) >>= \case Left e -> do publish (ConnectionClosed self e) throw e Right payload -> case runGet getPackage payload of Left reason -> do let cause = PackageParsingError reason publish (connectionError self cause) throw cause Right pkg -> return pkg -------------------------------------------------------------------------------- receiving :: ConnectionState -> Connection -> Async Network.Connection -> EventStore () receiving ConnectionState{..} self tcpConnAsync = forever . go =<< wait tcpConnAsync where go conn = publish . PackageArrived self =<< receivePackage self conn -------------------------------------------------------------------------------- enqueue :: ConnectionState -> Package -> EventStore () enqueue ConnectionState{..} pkg@Package{..} = do $(logDebug) [i|Package enqueued: #{pkg}|] atomically $ writeTBMQueue _sendQueue pkg -------------------------------------------------------------------------------- sending :: ConnectionState -> Connection -> Async Network.Connection -> EventStore () sending ConnectionState{..} self tcpConnAsync = go =<< wait tcpConnAsync where go conn = let loop = traverse_ send =<< atomically (readTBMQueue _sendQueue) send pkg = tryAny (liftIO $ Network.connectionPut conn bytes) >>= \case Left e -> publish (ConnectionClosed self e) Right _ -> do monitorAddDataTransmitted (length bytes) loop where bytes = runPut $ putPackage pkg in loop -------------------------------------------------------------------------------- -- Serialization -------------------------------------------------------------------------------- -- | Serializes a 'Package' into raw bytes. putPackage :: Package -> Put putPackage pkg = do putWord32le length_prefix putWord8 (cmdWord8 $ packageCmd pkg) putWord8 flag_word8 putLazyByteString corr_bytes for_ cred_m $ \(Credentials login passw) -> do putWord8 $ fromIntegral $ length login putByteString login putWord8 $ fromIntegral $ length passw putByteString passw putByteString pack_data where pack_data = packageData pkg cred_len = maybe 0 credSize cred_m length_prefix = fromIntegral (length pack_data + mandatorySize + cred_len) cred_m = packageCred pkg flag_word8 = maybe 0x00 (const 0x01) cred_m corr_bytes = toByteString $ packageCorrelation pkg -------------------------------------------------------------------------------- credSize :: Credentials -> Int credSize (Credentials login passw) = length login + length passw + 2 -------------------------------------------------------------------------------- -- | The minimun size a 'Package' should have. It's basically a command byte, -- correlation bytes ('UUID') and a 'Flag' byte. mandatorySize :: Int mandatorySize = 18 -------------------------------------------------------------------------------- -- Parsing -------------------------------------------------------------------------------- getLengthPrefix :: Get Int getLengthPrefix = fmap fromIntegral getWord32le -------------------------------------------------------------------------------- getPackage :: Get Package getPackage = do cmd <- getWord8 flg <- getFlag col <- getUUID cred <- getCredentials flg rest <- remaining dta <- getBytes rest let pkg = Package { packageCmd = getCommand cmd , packageCorrelation = col , packageData = dta , packageCred = cred } return pkg -------------------------------------------------------------------------------- getFlag :: Get Flag getFlag = do wd <- getWord8 case wd of 0x00 -> return None 0x01 -> return Authenticated _ -> fail $ printf "TCP: Unhandled flag value 0x%x" wd -------------------------------------------------------------------------------- getCredEntryLength :: Get Int getCredEntryLength = fmap fromIntegral getWord8 -------------------------------------------------------------------------------- getCredentials :: Flag -> Get (Maybe Credentials) getCredentials None = return Nothing getCredentials _ = do loginLen <- getCredEntryLength login <- getBytes loginLen passwLen <- getCredEntryLength passw <- getBytes passwLen return $ Just $ credentials login passw -------------------------------------------------------------------------------- getUUID :: Get UUID getUUID = do bs <- getLazyByteString 16 case fromByteString bs of Just uuid -> return uuid _ -> fail "TCP: Wrong UUID format"
YoEight/eventstore
Database/EventStore/Internal/Connection.hs
bsd-3-clause
13,110
3
27
2,583
2,343
1,186
1,157
-1
-1
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-} module Network.AmazonEmailer.Client.Snap where import Data.Text (Text) import Control.Monad (void) import Control.Monad.Trans (liftIO) import Snap.Snaplet (Handler) import Snap.Snaplet.PostgresqlSimple (HasPostgres, execute, executeMany) data Email = Email { emTo :: Text , emFrom :: Text , emFromName :: Text , emSubject :: Text , emBody :: Text } deriving (Show, Eq) -- | Sends a single plain text message sendMessage :: HasPostgres (Handler b a) => Email -> Handler b a () sendMessage e@(Email to from fromName subj body) = void $ execute "insert into amazon_email_queue (to_addr, from_addr, from_name, subject, body) values (?,?,?,?,?)" (to, from, fromName, subj, body) -- | Sends a single plain text message, writing it out to the stdout. sendMessageVerbose :: HasPostgres (Handler b a) => Email -> Handler b a () sendMessageVerbose e@(Email to from fromName subj body) = do liftIO $ print e sendMessage e -- | Sends a single html message sendMessageHtml :: HasPostgres (Handler b a) => Email -> Handler b a () sendMessageHtml e@(Email to from fromName subj body) = void $ execute "insert into amazon_email_queue (to_addr, from_addr, from_name, subject, body, html) values (?,?,?,?,?, true)" (to, from, fromName, subj, body) -- | Sends a single html message, writing it out to the stdout sendMessageHtmlVerbose :: HasPostgres (Handler b a) => Email -> Handler b a () sendMessageHtmlVerbose e@(Email to from fromName subj body) = do liftIO $ print e sendMessageHtml e -- | Sends many plain text messages sendMessages :: HasPostgres (Handler b a) => [Email] -> Handler b a () sendMessages es = do executeMany "insert into amazon_email_queue (to_addr,from_addr,from_name,subject,body) values (?,?,?,?,?)" (map (\(Email to from fromName subj body) -> (to,from,fromName,subj,body)) es) return () -- | Sends many plain text messages, logging the result to stdout sendMessagesVerbose :: HasPostgres (Handler b a) => [Email] -> Handler b a () sendMessagesVerbose es = do liftIO $ putStrLn $ "Sending " ++ show (length es) ++ " messages." sendMessages es -- | Sends many html messages sendMessagesHtml :: HasPostgres (Handler b a) => [Email] -> Handler b a () sendMessagesHtml es = do executeMany "insert into amazon_email_queue (to_addr,from_addr,from_name,subject,body,html) values (?,?,?,?,?,?, true)" (map (\(Email to from fromName subj body) -> (to,from,fromName,subj,body)) es) return () -- | Sends many html messages, logging the result to stdout sendMessagesHtmlVerbose :: HasPostgres (Handler b a) => [Email] -> Handler b a () sendMessagesHtmlVerbose es = do liftIO $ putStrLn $ "Sending " ++ show (length es) ++ " messages." sendMessagesHtml es
dbp/amazon-emailer-client-snap
src/Network/AmazonEmailer/Client/Snap.hs
bsd-3-clause
2,854
0
13
554
803
420
383
45
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} ------------------------------------------------------------------------------- -- | -- Module : Reflex.Gloss -- Copyright : (c) 2015 Jeffrey Rosenbluth -- License : BSD-style (see LICENSE) -- Maintainer : jeffrey.rosenbluth@gmail.com -- -- A Gloss interface for Reflex. -- ------------------------------------------------------------------------------- module Reflex.Gloss ( playReflex , InputEvent , GlossApp ) where import Control.Monad.Fix (MonadFix) import Control.Monad.IO.Class (liftIO) import Data.Dependent.Sum (DSum ((:=>))) import Data.IORef (readIORef) import Graphics.Gloss (Color, Display, Picture) import Graphics.Gloss.Interface.IO.Game (playIO) import qualified Graphics.Gloss.Interface.IO.Game as G import Reflex import Reflex.Host.Class (newEventWithTriggerRef, runHostFrame, fireEvents) -- | Synonym for a Gloss Event to prevent name clashes. type InputEvent = G.Event -- | Convert the refresh and input events to a Behavior t Picture. type GlossApp t m = (Reflex t, MonadHold t m, MonadFix m) => Event t Float -> Event t InputEvent -> m (Behavior t Picture) -- | Play the 'GlossApp' in a window, updating when the Behavior t Picture -- changes. playReflex :: Display -- ^ Display mode. -> Color -- ^ Background color. -> Int -- ^ Maximum frames per second. -> (forall t m. GlossApp t m) -- ^ A reflex function that returns a 'Behavior t Picture' -> IO () playReflex display color frequency network = runSpiderHost $ do (tickEvent, tickTriggerRef) <- newEventWithTriggerRef (inputEvent, inputTriggerRef) <- newEventWithTriggerRef picture <- runHostFrame $ network tickEvent inputEvent liftIO $ playIO display color frequency () (\_ -> runSpiderHost $ runHostFrame (sample picture)) (\ge _ -> runSpiderHost $ handleTrigger ge inputTriggerRef) (\fl _ -> runSpiderHost $ handleTrigger fl tickTriggerRef) where handleTrigger e trigger = do mETrigger <- liftIO $ readIORef trigger case mETrigger of Nothing -> return () Just eTrigger -> fireEvents [eTrigger :=> e]
Saulzar/reflex-gloss
src/Reflex/Gloss.hs
bsd-3-clause
2,455
0
15
688
461
263
198
43
2
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeFamilies #-} module Pos.Binary.Limit ( Limit (..) , (<+>) , mlBool , mlMaybe , mlEither , mlTuple , mlTriple , vectorOf , vectorOfNE ) where import Universum -- | A limit on the length of something (in bytes). -- TODO should check for overflow in the Num instance. -- Although, if the limit is anywhere near maxBound :: Word32 then something -- is almost certainly amiss. newtype Limit t = Limit { getLimit :: Word32 } deriving (Eq, Ord, Show, Num, Enum, Real, Integral) instance Functor Limit where fmap _ (Limit x) = Limit x -- TODO: use <*> instead of <+> infixl 4 <+> (<+>) :: Limit (a -> b) -> Limit a -> Limit b Limit x <+> Limit y = Limit $ x + y mlBool :: Limit Bool mlBool = 1 mlMaybe :: Limit a -> Limit (Maybe a) mlMaybe lim = Just <$> lim + 1 mlEither :: Limit a -> Limit b -> Limit (Either a b) mlEither limA limB = 1 + max (Left <$> limA) (Right <$> limB) mlTuple :: Limit a -> Limit b -> Limit (a, b) mlTuple limA limB = (,) <$> limA <+> limB mlTriple :: Limit a -> Limit b -> Limit c -> Limit (a, b, c) mlTriple limA limB limC = (,,) <$> limA <+> limB <+> limC -- | Given a limit for a list item, generate limit for a list with N elements vectorOf :: Int -> Limit l -> Limit [l] vectorOf k (Limit x) = Limit $ encodedListLength + x * (fromIntegral k) where -- should be enough for most reasonable cases -- FIXME this is silly. -- Better solution: never read in an arbitrary-length structure from the -- network. If you want a list, read in one item at a time. encodedListLength = 20 vectorOfNE :: Int -> Limit l -> Limit (NonEmpty l) vectorOfNE k (Limit x) = Limit $ encodedListLength + x * (fromIntegral k) where encodedListLength = 20
input-output-hk/pos-haskell-prototype
binary/src/Pos/Binary/Limit.hs
mit
1,937
0
9
508
550
295
255
41
1
{-# LANGUAGE NamedFieldPuns, DeriveDataTypeable, ExtendedDefaultRules, EmptyDataDecls, MultiParamTypeClasses #-} module Main where import System.IO (hPutStrLn, stderr) import System.Posix.Signals as SIG import Control.Applicative ((<|>)) import Control.Concurrent (forkIO, forkOS, killThread) import qualified Control.Concurrent.Thread as Thread (forkIO, forkOS, result) import Control.Concurrent.Thread.Delay (delay) import Control.Concurrent.MVar import Control.Monad (forever, unless, when) import Control.Monad.Trans (liftIO) import Control.Monad.State (modify) import Control.Exception.Base (mask, onException, catch, SomeException) import Network.Socket (withSocketsDo) import Data.Char (chr) import Data.Text (Text) import Data.Text.Lazy (toStrict) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Network.WebSockets as WS import qualified Foreign.C.Types as C import Data.Aeson as J import Data.Text.Lazy.Encoding as E import qualified UI.HSCurses.Curses as N import qualified UI.HSCurses.Widgets as NW cfg_server = "toastystoemp.com" cfg_port = 6060 cfg_channel = "testing" cfg_nick = "HaskellNick" data Event = EventButton C.CInt | EventNop | EventSend String | EventTimeout data Queue = Queue (MVar Bool) (MVar [Event]) newEventQueue :: IO Queue newEventQueue = do lock <- newEmptyMVar queue <- newMVar [] return $ Queue lock queue addEvent :: Queue -> Event -> IO() addEvent (Queue lock queue) e = do a <- takeMVar queue success <- tryPutMVar lock True putMVar queue (a++[e]) return $! () takeEvent :: Queue -> IO Event takeEvent q = do let (Queue lock queue) = q a <- takeMVar queue case a of [] -> do putMVar queue [] tryTakeMVar lock tryReadMVar lock takeEvent q otherwise -> putMVar queue (tail a) >> return (head a) cmdPing :: Text cmdPing = T.pack "{\"cmd\": \"ping\"}" cmdChat :: Text -> Text cmdChat msg = do toStrict $ E.decodeUtf8 $ J.encode $ J.object [ T.pack "cmd" .= "chat", T.pack "text" .= msg ] cmdJoin :: String -> String -> Text cmdJoin channel nick = do toStrict $ E.decodeUtf8 $ J.encode $ J.object [ T.pack "cmd" .= "join", T.pack "channel" .= channel, T.pack "nick" .= nick ] app :: MVar Bool -> Queue -> Queue -> WS.ClientApp() app clientStopping guiEvents netEvents conn = do WS.sendTextData conn $ cmdJoin cfg_channel cfg_nick recvThreadId <- forkIO $ forever $ do putStrLn.T.unpack.toStrict =<< WS.receiveData conn return $! () pingThreadId <- forkIO $ forever $ do delay (60*1000*1000) >> WS.sendTextData conn (cmdPing) timeoutThreadId <- forkIO $ forever $ do delay (300*1000) >> addEvent netEvents EventTimeout let loop :: IO() loop = do stopping <- readMVar clientStopping case stopping of True -> return $! () False -> do hPutStrLn stderr "EVENT" e <- takeEvent netEvents hPutStrLn stderr "AfterTake" case e of EventSend msg -> do hPutStrLn stderr $ "Sending Message: "++msg WS.sendTextData conn $ cmdChat $ T.pack msg EventTimeout -> return $! () otherwise -> return $! () hPutStrLn stderr "AfterCase" loop loop killThread timeoutThreadId killThread recvThreadId killThread pingThreadId WS.sendClose conn (T.pack "") runGui :: MVar Bool -> Queue -> Queue -> IO() runGui clientStopping guiEvents netEvents = do window <- N.initScr oldCursorMode <- N.cursSet N.CursorInvisible N.echo False -- HANDLER let sigWinchHandler signalInfo = do case (siginfoSignal signalInfo) of siginfoSignal -> do hPutStrLn stderr "Resize" case N.cursesSigWinch of Just a -> installHandler (a) (SIG.CatchInfo $ sigWinchHandler) Nothing -- INITIALIZE VIEWS --let tableWidet = NW.newTableWidget (NW.TBWOptions {}) [] -- REFRESH --N.wRefresh window chatMessage <- newMVar "" -- LOOP -- keyboard events keyboardThread <- forkIO $ forever $ do keyCode <- N.getch addEvent guiEvents (EventButton keyCode) return $! () -- process keyboard events let processButtonAction :: C.CInt -> IO() processButtonAction ckeyCode = do let keyCode = fromIntegral ckeyCode :: Int liftIO $ hPutStrLn stderr $ "Keycode " ++ (show keyCode) case keyCode of 27 -> liftIO $ takeMVar clientStopping >> putMVar clientStopping True 10 -> do msg <- takeMVar chatMessage putMVar chatMessage "" addEvent netEvents $ EventSend msg hPutStrLn stderr $ "Sending Message: "++msg otherwise -> do msg <- takeMVar chatMessage let msg' = msg ++ [chr $ fromIntegral keyCode] putMVar chatMessage msg' hPutStrLn stderr $ "New Message: "++msg' return $! () -- main event loop let eventLoop :: IO() eventLoop = do stopping <- readMVar clientStopping unless(stopping) $ do e <- takeEvent guiEvents case e of EventButton button -> processButtonAction button EventNop -> return $! () eventLoop -- SPAWN (_, waitEvents) <- Thread.forkIO $ eventLoop -- WAIT & EXIT waitEvents killThread keyboardThread N.cursSet oldCursorMode N.echo True N.endWin runNet :: MVar Bool -> Queue -> Queue -> IO() runNet stopping guiEvents netEvents = do catch (withSocketsDo $ WS.runClient cfg_server cfg_port "/chat-ws" (app stopping guiEvents netEvents)) (\e -> do let err = show (e :: SomeException) hPutStrLn stderr ("Error: " ++ err) return $! ()) main :: IO() main = do clientStopping <- newMVar False guiEvents <- newEventQueue netEvents <- newEventQueue (_, netWait) <- Thread.forkIO $ runNet clientStopping guiEvents netEvents (_, guiWait) <- Thread.forkIO $ runGui clientStopping guiEvents netEvents netWait guiWait return $! ()
icetruckde/HackChat-Haskell-Client
client.hs
mit
6,487
1
25
1,932
1,923
950
973
-1
-1
module Main where import Data.Traversable import Test.Framework.Runners.Console import Test.Framework.Providers.API as API import Test.Framework.Providers.HUnit import Test.HUnit import TestDef import qualified LoaderTests import qualified ParserTests main :: IO () main = do g <- fileBasedTestGroup defaultMain [ g , ParserTests.main , LoaderTests.main ] fileBasedTestGroup :: IO API.Test fileBasedTestGroup = do ts <- traverse defToTest fileBasedTests return $ testGroup "File Based Tests" ts -- add more tesst here! fileBasedTests :: [TestDef] fileBasedTests = concat [ParserTests.parsingFileBasedTests]
PipocaQuemada/ermine
tests/unit-tests/UnitTests.hs
bsd-2-clause
636
0
9
101
150
86
64
22
1
{- Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE PackageImports #-} {-# LANGUAGE NoImplicitPrelude #-} module Foreign.Safe (module M) where import "base" Foreign.Safe as M
d191562687/codeworld
codeworld-base/src/Foreign/Safe.hs
apache-2.0
739
0
4
136
23
17
6
4
0
-- Example of concurrent Haskell and Gtk. -- -- This demo uses GHC's support for OS level threads. It has to be -- linked using the ghc -threaded flag. -- -- Because Gtk+ is single threaded we have to be very careful to call -- Gtk+ only from the main GUI thread. So while it's ok to forkIO, -- any GUI actions in that thread have to be 'posted' to the main GUI -- thread using postGUI, or postGUIAsync as in the example here. import Graphics.UI.Gtk import Control.Concurrent main :: IO () main = do -- It is marked unsafe becuase it is your obligation to ensure you -- only call Gtk+ from one OS thread, or 'bad things' will happen. unsafeInitGUIForThreadedRTS dia <- dialogNew dialogAddButton dia stockClose ResponseClose contain <- dialogGetUpper dia pb <- progressBarNew boxPackStartDefaults contain pb widgetShowAll dia forkIO (doTask pb) dialogRun dia return () doTask :: ProgressBar -> IO () doTask pb = do postGUIAsync $ progressBarPulse pb threadDelay 100000 doTask pb
phischu/gtk2hs
gtk/demo/concurrent/ProgressThreadedRTS.hs
lgpl-3.0
1,015
1
9
203
166
76
90
19
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeOperators #-} module T10321 where import GHC.TypeLits data Vec :: Nat -> * -> * where Nil :: Vec 0 a (:>) :: a -> Vec n a -> Vec (n + 1) a infixr 5 :>
urbanslug/ghc
testsuite/tests/ghci/scripts/T10321.hs
bsd-3-clause
274
0
10
75
74
44
30
10
0
{-# LANGUAGE QuasiQuotes #-} -- | This module defines a generator for @getopt_long@ based command -- line argument parsing. Each option is associated with arbitrary C -- code that will perform side effects, usually by setting some global -- variables. module Futhark.CodeGen.Backends.GenericC.Options ( Option (..) , OptionArgument (..) , generateOptionParser ) where import Data.Maybe import qualified Language.C.Syntax as C import qualified Language.C.Quote.C as C -- | Specification if a single command line option. The option must -- have a long name, and may also have a short name. -- -- In the action, the option argument (if any) is stored as in the -- @char*@-typed variable @optarg@. data Option = Option { optionLongName :: String , optionShortName :: Maybe Char , optionArgument :: OptionArgument , optionAction :: C.Stm } -- | Whether an option accepts an argument. data OptionArgument = NoArgument | RequiredArgument | OptionalArgument -- | Generate an option parser as a function of the given name, that -- accepts the given command line options. The result is a function -- that should be called with @argc@ and @argv@. The function returns -- the number of @argv@ elements that have been processed. -- -- If option parsing fails for any reason, the entire process will -- terminate with error code 1. generateOptionParser :: String -> [Option] -> C.Func generateOptionParser fname options = [C.cfun|int $id:fname(struct futhark_context_config *cfg, int argc, char* const argv[]) { int $id:chosen_option; static struct option long_options[] = { $inits:option_fields, {0, 0, 0, 0} }; while (($id:chosen_option = getopt_long(argc, argv, $string:option_string, long_options, NULL)) != -1) { $stms:option_applications if ($id:chosen_option == ':') { panic(-1, "Missing argument for option %s\n", argv[optind-1]); } if ($id:chosen_option == '?') { panic(-1, "Unknown option %s\n", argv[optind-1]); } } return optind; } |] where chosen_option = "ch" option_string = ':' : optionString options option_applications = optionApplications chosen_option options option_fields = optionFields options optionFields :: [Option] -> [C.Initializer] optionFields = zipWith field [(1::Int)..] where field i option = [C.cinit| { $string:(optionLongName option), $id:arg, NULL, $int:i } |] where arg = case optionArgument option of NoArgument -> "no_argument" RequiredArgument -> "required_argument" OptionalArgument -> "optional_argument" optionApplications :: String -> [Option] -> [C.Stm] optionApplications chosen_option = zipWith check [(1::Int)..] where check i option = [C.cstm|if ($exp:cond) $stm:(optionAction option)|] where cond = case optionShortName option of Nothing -> [C.cexp|$id:chosen_option == $int:i|] Just c -> [C.cexp|($id:chosen_option == $int:i) || ($id:chosen_option == $char:c)|] optionString :: [Option] -> String optionString = concat . mapMaybe optionStringChunk where optionStringChunk option = do short <- optionShortName option return $ short : case optionArgument option of NoArgument -> "" RequiredArgument -> ":" OptionalArgument -> "::"
ihc/futhark
src/Futhark/CodeGen/Backends/GenericC/Options.hs
isc
3,699
0
12
1,060
460
272
188
46
3
module GHCJS.DOM.TextMetrics ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/TextMetrics.hs
mit
41
0
3
7
10
7
3
1
0
module Util where import Data.List (intercalate) import Data.List.Utils (replace) import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Maybe as Maybe import System.Directory (doesPathExist) choose :: a -> a -> Bool -> a choose a b cond = if cond then a else b if' :: Bool -> a -> a -> a if' cond a b = if cond then a else b putShowLn :: Show a => a -> IO () putShowLn = putStrLn . show prettyPrintList :: Show a => [a] -> IO () prettyPrintList list = putStrLn $ "[ " ++ inner ++ "\n]" where inner = intercalate "\n, " $ map show list ifM :: Monad m => m Bool -> m a -> m a -> m a ifM cond a b = cond >>= choose a b ifM_ :: Monad m => m Bool -> m a -> m b -> m () ifM_ cond a b = ifM cond (a >> return ()) (b >> return ()) allBefore :: Eq a => a -> [a] -> [a] allBefore el = takeWhile (/= el) select :: (a -> Bool) -> [a] -> [a] select = filter replaceSafe :: Eq a => [a] -> [a] -> [a] -> [a] replaceSafe [] _ _ = error "The first argument to replaceSafe must not be []" replaceSafe old new cont = replace old new cont readFileWithDefault :: String -> FilePath -> IO String readFileWithDefault defCont path = ifM (doesPathExist path) (readFile path) (return defCont) flattenMap :: Map k (Maybe v) -> Map k v flattenMap m = Map.map Maybe.fromJust $ Map.filter Maybe.isJust m
larioj/nemo
src/Util.hs
mit
1,429
0
10
400
614
317
297
38
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Types.Team where import Types.Imports data Team = Team { teamId :: Maybe Int, name :: String } deriving (Show, Generic) instance HasId Team where getId a = teamId a setId a id = a { teamId = id } instance FromJSON Team where parseJSON (Object v) = Team <$> v .:? "teamId" <*> v .: "name" instance ToJSON Team instance FromRow Team where fromRow = Team <$> field <*> field instance ToRow Team where toRow u = [toField (name u)]
maciejspychala/haskell-server
src/Types/Team.hs
mit
552
0
9
141
179
95
84
18
0
module GearScript.Parser where import qualified GearScript.Lexer as L import Control.Applicative((<$>), (<$), (<*), (*>)) import Text.Parsec.Error import Text.Parsec.Pos import Text.Parsec.Prim import Text.Parsec.Combinator import GearScript.Util import GearScript.AST type Parser = Parsec [L.GSToken] () satisfyM :: (L.Token -> Maybe a) -> Parser a satisfyM f = token showTok posFromTok (f . snd) where showTok (_, t) = show t posFromTok (pos, _) = pos satisfy :: (L.Token -> Bool) -> Parser L.Token satisfy f = satisfyM cond where cond x | f x = Just x | otherwise = Nothing tok :: L.Token -> Parser L.Token tok x = satisfy (==x) takeName :: L.Token -> Maybe String takeName (L.Name n) = Just n takeName _ = Nothing localVariable :: Parser String localVariable = satisfyM takeVar where takeVar (L.LocalVariable n) = Just n takeVar _ = Nothing globalVariable :: Parser String globalVariable = satisfyM takeVar where takeVar (L.GlobalVariable n) = Just n takeVar _ = Nothing variable :: Parser Expression variable = LocalVariable <$> localVariable <|> GlobalVariable <$> globalVariable stringLiteral :: Parser Expression stringLiteral = satisfyM takeLit where takeLit (L.StringLiteral x) = Just $ StringLiteral x takeLit _ = Nothing parens :: Parser a -> Parser a parens p = do _ <- tok L.ParenBegin result <- p _ <- tok L.ParenEnd return result functionDef :: Parser TopStatement functionDef = do _ <- tok $ L.KeywordTok L.Function funcName <- satisfyM takeName args <- parens (localVariable `sepBy` tok L.ArgumentSeparator) body <- block return $ FunctionDef funcName args body functionCall :: Parser Expression functionCall = do funcName <- satisfyM takeName args <- parens (expr `sepBy` tok L.ArgumentSeparator) return $ Call Nothing funcName args expr :: Parser Expression expr = term `chainl1` exprOp exprOp :: Parser (Expression -> Expression -> Expression) exprOp = Plus <$ tok L.Plus <|> Minus <$ tok L.Minus term :: Parser Expression term = factor `chainl1` termOp termOp :: Parser (Expression -> Expression -> Expression) termOp = Mult <$ tok L.Mult <|> Div <$ tok L.Div <|> Mod <$ tok L.Mod factor :: Parser Expression factor = tryChoice [ functionCall , variable , stringLiteral ] block :: Parser [Statement] block = tok L.BlockBegin *> many statement <* tok L.BlockEnd statementOp :: Parser Statement statementOp = tryChoice [ ExprStatement <$> expr ] statement :: Parser Statement statement = statementOp <* tok L.StmtEnd topLevelStatement :: Parser TopStatement topLevelStatement = tryChoice [ TopPlainStatement <$> statement , functionDef ] parseGS :: SourceName -> [L.GSToken] -> Either ParseError [TopStatement] parseGS = runP (many topLevelStatement <* eof) ()
teozkr/GearScript
src/GearScript/Parser.hs
mit
2,992
0
12
720
1,004
513
491
85
2
module GHCJS.DOM.IDBObjectStore ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/IDBObjectStore.hs
mit
44
0
3
7
10
7
3
1
0
{-# LANGUAGE MagicHash #-} {-# LANGUAGE MultiParamTypeClasses #-} module Data.Words where import GHC.Word class Included a b where embed :: a -> b instance Included Word8 Word16 where embed (W8# w) = W16# w
gallais/word-arithmetic
src/Data/Words.hs
mit
227
0
8
54
60
32
28
8
0
{-| Module : rectifier Description : Convert our "wiki-style" markdown links to exact titles/headers/filenames. Copyright : (c) Robin Lee Powell, 2017 License : MIT Maintainer : rlpowell@digitalkingdom.org Stability : experimental Portability : POSIX Check our "wiki-style" markdown links, which match fuzzily in various ways, to make sure they point at something unique, and replace them with the exact titles/headers/filenames of the thing they point at. See "Wiki Links" in DESIGN-CODE for full details. -} -------------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE FlexibleContexts #-} module HBlog.Rectifier ( rectifierMain ) where import System.Directory (createDirectoryIfMissing) import System.FilePath (makeRelative, (</>), takeDirectory, takeBaseName) import System.Environment (getArgs) import qualified System.FilePath.Find as F (find, always, extension) import System.FilePath.Find ((==?)) import Control.Monad (mapM) import Text.Pandoc (readMarkdown, Inline(..), docTitle, writePlain, writeMarkdown, writerTemplate, runPure, PandocError(..)) import Text.Pandoc.Templates (getDefaultTemplate) import Text.Pandoc.Walk (query, walk) import Text.Pandoc.Definition (Pandoc(..), Block(..), nullMeta) import Network.URI (unEscapeString, isURI) import Data.List (find, intercalate, sortBy) import Data.Maybe (isJust) import Data.Char (toLower) -- import Debug.Trace import Text.Regex.PCRE.Heavy ((=~)) import Text.Regex.PCRE.Light (compile, caseless) import Data.ByteString.Char8 (pack) import Text.EditDistance (defaultEditCosts, levenshteinDistance) import Data.Function (on) import qualified Data.Text as T import HBlog.Lib import Data.String.Utils (strip) -- MissingH -------------------------------------------------------------------------------- -- Headers and titles from markdown files. data Target = THeader { tTarget :: String, tFile :: FilePath } | TTitle { tTarget :: String, tFile :: FilePath } deriving (Eq, Ord, Show) isHeader :: Target -> Bool isHeader (THeader _ _) = True isHeader _ = False isTitle :: Target -> Bool isTitle (TTitle _ _) = True isTitle _ = False -------------------------------------------------------------------------------- rectifierMain :: IO () rectifierMain = do args <- getArgs case args of indir:outdir:[] -> walkTree indir outdir _ -> putStrLn "Need exactly two arguments, input directory and output directory." -- Walk the tree of input files, rewriting as necessary the links in -- each file to point to the full text of link targets that actually -- exist. -- -- A mildly unfortunate issue is that we walk the files twice; once -- to get all the targets and again to munge the links to them. -- It's not obvious that that's fixable, though, and it's not like -- we're talking about thousands of files. walkTree :: String -> String -> IO () walkTree indir outdir = do -- Grab the possible link targets targets <- targetPrep indir -- error $ "targets: " ++ show targets putStrLn $ "Searching for files ending in .md" files <- F.find F.always (F.extension ==? ".md") indir putStrLn $ "Files found: " ++ (intercalate " " files) _ <- mapM (handleFile indir outdir targets) files return () -- Walks the file tree running readTargets targetPrep :: FilePath -> IO [Target] targetPrep indir = do files <- F.find F.always (F.extension ==? ".md") indir targets <- mapM readTargets files return $ filter (\x -> (tTarget x) /= "") $ concat targets -- Gather all the titles and headers from all the files, along with -- their file namers, and turn them into Targets -- -- We don't care about anything else about these files; we're just -- making sure that each link points to a valid target. readTargets :: FilePath -> IO [Target] readTargets file = do body <- readFile file let pandocEither = runPure $ readMarkdown hblogPandocReaderOptions $ T.pack body return $ concat [titleQuery pandocEither file, headersQuery pandocEither file] -- Turn titles into Targets titleQuery :: Either PandocError Pandoc -> FilePath -> [Target] titleQuery (Right (Pandoc meta _)) file = [TTitle { tFile = file, tTarget = (strip target) }] where target = case runPure $ writePlain hblogPandocWriterOptions $ Pandoc nullMeta $ [Plain $ docTitle meta] of Left (PandocSomeError err) -> "rectifier titleQuery: unknown error: " ++ err Left _ -> "rectifier titleQuery: unknown error!" Right item' -> T.unpack item' titleQuery (Left e) file = error $ "Pandoc error! on file " ++ file ++ ": " ++ (show e) -- Turn headers into Targets headersQuery :: Either PandocError Pandoc -> FilePath -> [Target] headersQuery (Right x) file = map (\str -> THeader { tFile = file, tTarget = (strip str)}) $ query getHeaders x headersQuery (Left e) file = error $ "Pandoc error! on file " ++ file ++ ": " ++ (show e) -- Pull headers out as strings getHeaders :: Block -> [String] getHeaders (Header _ _ xs) = [headers] where headers = case runPure $ writePlain hblogPandocWriterOptions $ Pandoc nullMeta $ [Plain xs] of Left (PandocSomeError err) -> "rectifier getHeaders: unknown error: " ++ err Left _ -> "rectifier getHeaders: unknown error!" Right item' -> T.unpack item' getHeaders _ = [] -- Basically a wrapper for rectifie that does the IO bits; the code -- below this is pure handleFile :: FilePath -> FilePath -> [Target] -> FilePath -> IO () handleFile indir outdir targets file = do putStrLn $ "Processing file " ++ file let shortname = makeRelative indir file body <- readFile $ indir </> shortname Right mdTemplate <- getDefaultTemplate Nothing "markdown" let newBody = rectify body file targets mdTemplate in do _ <- createDirectoryIfMissing True (takeDirectory $ (outdir </> shortname)) _ <- writeFile (outdir </> shortname) newBody return () -- Read, munge, and rebuild the markdown file we're working on rectify :: String -> FilePath -> [Target] -> String -> String rectify body file targets mdTemplate = let pandocEither = runPure $ readMarkdown hblogPandocReaderOptions $ T.pack body newPandoc = linksWalk pandocEither file targets in case runPure $ writeMarkdown hblogPandocWriterOptions { writerTemplate = Just mdTemplate } newPandoc of Left (PandocSomeError err) -> "rectifier rectify: unknown error: " ++ err Left _ -> "rectifier rectify: unknown error!" Right item' -> T.unpack item' -- Walk the Pandoc linksWalk :: Either PandocError Pandoc -> FilePath -> [Target] -> Pandoc linksWalk (Right x) file targets = walk (replaceLink file targets) x linksWalk (Left e) file _ = error $ "Pandoc error! on file " ++ file ++ ": " ++ (show e) -- Return true if the target is a header in the specified file isFileHeader :: FilePath -> Target -> Bool isFileHeader file target = isHeader target && tFile target == file -- Replaces the given link; mostly this is just a wrapper for -- findTarget, but there's some complexity if it's a fragment style -- link replaceLink :: FilePath -> [Target] -> Inline -> Inline replaceLink file targets linky@(Link x y (ickyLinkStr, z)) = let linkStr = unEscapeString ickyLinkStr in -- Step 1 from "Rectification" in DESIGN-CODE : check if it -- looks like a URL or an absolute path within our blog, and -- ignore it in those cases if isURI linkStr || head linkStr == '/' then linky else if (length $ filter (== '#') linkStr) == 1 then -- If it's a fragment (a # link), first check the left side -- of the # and if that matches a title, look in that file -- for header matches let hashFirst = fst $ span (/= '#') linkStr maybeGoodTarget = findTarget hashFirst isTitle targets hashSecond = tail $ snd $ span (/= '#') linkStr in if hashFirst == "" then error $ "Found link \"" ++ linkStr ++ "\" in file " ++ file ++ ", which isn't valid. If you're trying to link to a heading in the current file, just copy the heading's name as written (i.e. \"This Is My Heading\") as your link target; hblog will handle the rest." else case maybeGoodTarget of Nothing -> error $ "Failed to find valid main target (the part before #) for link \"" ++ linkStr ++ "\" in file " ++ file Just goodTarget -> -- Now that we have the file, look for the fragment -- in the headers of that file let maybeGoodFragTarget = findTarget hashSecond (isFileHeader (tFile goodTarget)) targets in case maybeGoodFragTarget of Nothing -> error $ "Failed to find valid fragment target (the part after #) for link \"" ++ linkStr ++ "\" in file " ++ file Just goodFragTarget -> Link x y ((tTarget goodTarget) ++ "#" ++ (tTarget goodFragTarget), z) else -- No # ; try all the internal file headers first, and then -- all the titles. let twoMaybes = find isJust [ findTarget linkStr (isTitle) targets , findTarget linkStr (isFileHeader file) targets ] in -- FIXME: There *must* be a more idiomatic way to do this case twoMaybes of Nothing -> noTarget linkStr file targets Just Nothing -> noTarget linkStr file targets Just (Just goodTarget) -> Link x y ((tTarget goodTarget), z) replaceLink _ _ x = x -- Return true if the target is visible to us, that is, is a title -- or is a header in this same file. isTitleOrFileHeader :: FilePath -> Target -> Bool isTitleOrFileHeader file target = isFileHeader file target || isTitle target levenshteinTargetSort :: String -> [Target] -> FilePath -> [Char] levenshteinTargetSort linkStr targets file = intercalate "\n" $ sortBy (compare `on` (levenshteinDistance defaultEditCosts) linkStr) $ map tTarget $ filter (isTitleOrFileHeader file) targets noTarget :: [Char] -> [Char] -> [Target] -> a noTarget linkStr file targets = error $ "Failed to find valid target for link \"" ++ linkStr ++ "\" in file " ++ file ++ "\n\nPossible targets include:\n\n" ++ (levenshteinTargetSort linkStr targets file) ++ "\n\n" makeFuzzy :: String -> String makeFuzzy input = ".*" ++ (intercalate ".*" $ words input) ++ ".*" leftRegex :: String -> String -> Bool leftRegex left right = right =~ (compile (pack left) [caseless]) -- This is where we actually walk through the steps from -- "Rectification" in DESIGN-CODE (except step 1); details are there. findTarget :: String -> (Target -> Bool) -> [Target] -> Maybe Target findTarget linkStr myFilter targets = -- We want to stop immediately once we find something that works. let twoMaybes = find isJust [ -- Step 2 applyToBothAndFind id tTarget (==) linkStr (filter myFilter targets) -- Step 3 , applyToBothAndFind (map toLower) ((map toLower) . tTarget) (==) linkStr (filter myFilter targets) -- Step 4 , applyToBothAndFind trimMD (trimMD . tFile) (==) linkStr (filter myFilter targets) -- Step 5 , applyToBothAndFind trimMDLower (trimMDLower . tFile) (==) linkStr (filter myFilter targets) -- Step 6 , applyToBothAndFind makeFuzzy tTarget (leftRegex) linkStr (filter myFilter targets) , applyToBothAndFind makeFuzzy tFile (leftRegex) linkStr (filter myFilter targets) , Nothing ] in -- FIXME: There *must* be a more idiomatic way to do this case twoMaybes of Nothing -> Nothing Just Nothing -> Nothing Just (Just x) -> Just x -- Trim ".md" from the file name trimMD :: FilePath -> String trimMD fname = let maybeStripped = T.stripSuffix ".md" $ T.pack $ (takeBaseName fname) in maybe fname T.unpack maybeStripped -- Trim ".md" from the file name and force it to lowercase trimMDLower :: FilePath -> String trimMDLower fname = map toLower (trimMD (takeBaseName fname)) -- Take left and right string munging functions, a comparison -- function, the link string we want to rectify, and the targets to -- use to rectify it. Applies the munging functions to the -- appropriate sides of the comparison, and runs the comparison -- function. applyToBothAndFind :: (String -> String) -> (Target -> String) -> (String -> String -> Bool) -> String -> [Target] -> Maybe Target applyToBothAndFind _ _ _ _ [] = Nothing applyToBothAndFind mungeLeft mungeRight comp linkStr xs = let findings = applyToBothAndFindInner mungeLeft mungeRight comp linkStr xs in if length findings > 1 then error $ "Found more than one match for \"" ++ linkStr ++ "\": " ++ (intercalate " " $ map tFile findings) else if length findings < 1 then Nothing else Just $ head findings applyToBothAndFindInner :: (String -> String) -> (Target -> String) -> (String -> String -> Bool) -> String -> [Target] -> [Target] applyToBothAndFindInner _ _ _ _ [] = [] applyToBothAndFindInner mungeLeft mungeRight comp linkStr (target:xs) = -- trace ("mlls: " ++ (mungeLeft linkStr)) $ -- trace ("mrt: " ++ (mungeRight target)) $ if (mungeLeft linkStr) `comp` (mungeRight target) then [target] ++ (applyToBothAndFindInner mungeLeft mungeRight comp linkStr xs) else applyToBothAndFindInner mungeLeft mungeRight comp linkStr xs
rlpowell/hblog
lib/HBlog/Rectifier.hs
mit
13,811
0
25
3,239
3,186
1,680
1,506
175
8
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-} {-# OPTIONS_GHC -fconstraint-solver-iterations=20 #-} module AI.Funn.CL.Batched.Network ( Network(..), params, batchSize, liftDiff, network, runNetwork ) where import Control.Applicative import Control.Category import Control.Exception import Control.Monad import Control.Monad.IO.Class import Data.Foldable import Data.Monoid import Data.Proxy import Data.Random import Data.Traversable import GHC.TypeLits import Prelude hiding (id) import System.IO.Unsafe import AI.Funn.CL.Batched.BTensor (BTensor(..)) import qualified AI.Funn.CL.Batched.BTensor as BT import AI.Funn.CL.Batched.Param (Param(..)) import qualified AI.Funn.CL.Batched.Param as Param import AI.Funn.CL.Tensor (Tensor) import qualified AI.Funn.CL.Tensor as T import qualified AI.Funn.CL.TensorLazy as TL import AI.Funn.Diff.Diff (Diff(..), Derivable(..)) import qualified AI.Funn.Diff.Diff as Diff import qualified AI.Funn.Flat.Blob as Blob import AI.Funn.Indexed.Indexed import AI.Funn.Space data Network m (ω :: Nat) (p :: Nat) a b = Network { netDiff :: Diff m (Param ω p, a) b, netInit :: RVar (Blob.Blob p) } params :: Network m ω p a b -> Proxy p params _ = Proxy batchSize :: Network m ω p a b -> Proxy ω batchSize _ = Proxy network :: (Monad m, Prod ds ~ p, KnownNat ω, KnownNat p) => Diff m (BTensor ω ds, a) b -> RVar (Blob.Blob p) -> Network m ω p a b network diff init = Network (Diff run) init where run (par, a) = do (b, k) <- runDiff diff (BTensor (Param.reshape par), a) return (b, backward k) backward k db = do (dpar, da) <- k db return (TL.fromStrict (T.reshape dpar), da) runNetwork :: (Monad m) => Network m ω i a b -> (Tensor '[i], a) -> m (b, D b -> m (Tensor '[ω, i], D a)) runNetwork net (par, a) = do (b, k) <- runDiff (netDiff net) (Param par, a) let backward db = do (dpar, da) <- k db return (TL.toStrict dpar, da) return (b, backward) connect :: (KnownDimsF [i,j,ω], Monad m) => Network m ω i a b -> Network m ω j b c -> Network m ω (i+j) a c connect (Network one i1) (Network two i2) = Network (Diff run) init where run (par, a) = do let (par1, par2) = Param.split par (b, k1) <- runDiff one (par1, a) (c, k2) <- runDiff two (par2, b) return (c, backward k1 k2) backward k1 k2 dc = do (dpar2, db) <- k2 dc (dpar1, da) <- k1 db return (Param.appendD dpar1 dpar2, da) init = liftA2 Blob.cat i1 i2 instance (KnownNat ω, Monad m) => Indexed (Network m ω) where iid = liftDiff id (~>>) = connect liftDiff :: (Monad m) => Diff m a b -> Network m ω 0 a b liftDiff diff = Network (Diff run) (pure (Blob.fromList [])) where run (_, a) = do (b, k) <- runDiff diff a return (b, backward k) backward k db = do da <- k db return (TL.nul, da) pfirst :: (Monad m) => Network m ω p a b -> Network m ω p (a,c) (b,c) pfirst (Network diff init) = Network (Diff run) init where run (p, (a,c)) = do (b, k) <- runDiff diff (p, a) return ((b,c), backward k) backward k (db, dc) = do (dp, da) <- k db return (dp, (da, dc)) psecond :: (Monad m) => Network m ω p a b -> Network m ω p (c,a) (c,b) psecond (Network diff init) = Network (Diff run) init where run (p, (c,a)) = do (b, k) <- runDiff diff (p, a) return ((c,b), backward k) backward k (dc, db) = do (dp, da) <- k db return (dp, (dc, da)) pswap :: (Monad m) => Network m ω 0 (a,b) (b,a) pswap = liftDiff Diff.swap passocL :: (Monad m) => Network m ω 0 (a,(b,c)) ((a,b),c) passocL = liftDiff Diff.assocL passocR :: (Monad m) => Network m ω 0 ((a,b),c) (a,(b,c)) passocR = liftDiff Diff.assocR instance (KnownNat ω, Monad m) => Assoc (Network m ω) where first = pfirst second = psecond swap = pswap assocL = passocL assocR = passocR
nshepperd/funn
AI/Funn/CL/Batched/Network.hs
mit
4,398
0
15
1,154
1,909
1,049
860
-1
-1
{-# LANGUAGE OverloadedStrings #-} import Control.Monad (mapM_) import qualified Crypto.Hash import Data.ByteString (ByteString) import qualified Data.Text as Text import Data.Text.Encoding (decodeUtf8, encodeUtf8) import qualified Data.Text.IO as IO main = do doorId <- Text.strip <$> IO.getContents IO.putStrLn $ crackPassword doorId crackPassword doorId = [0 ..] |> map (\i -> hashText (doorId `Text.append` (Text.pack $ show i))) |> filter (\digest -> Text.take 5 digest == "00000") |> map (\digest -> Text.index digest 5) |> take 8 |> Text.pack hashText :: Text.Text -> Text.Text hashText text = Text.pack $ show $ md5 $ encodeUtf8 text md5 :: ByteString -> Crypto.Hash.Digest Crypto.Hash.MD5 md5 = Crypto.Hash.hash (|>) = flip ($)
SamirTalwar/advent-of-code
2016/AOC_05_1.hs
mit
769
7
16
137
296
156
140
22
1
{-# LANGUAGE BangPatterns, PackageImports, RecordWildCards #-} module UI ( UIState , UIT , Split(..) , Rectangle(..) , rectFromWndFB , rectFromXYWH , runUI , splitRect , split , center , frame , layer , dimensions , fill , text -- Re-export from QuadRendering , RGBA(..) , FillColor(..) , Transparency(..) ) where import Control.Monad.Trans.Reader import Control.Monad.IO.Class import qualified Graphics.Rendering.OpenGL as GL import qualified "GLFW-b" Graphics.UI.GLFW as GLFW import Data.Tuple import QuadRendering import FontRendering -- Drawing, layout and event handling for the user interface -- TODO: Consider FRP library like netwire or reactive-banana for UI animations -- TODO: Use 'linear' package for OpenGL vector / matrix stuff -- https://github.com/ocharles/blog/blob/master/code/2013-12-02-linear-example.hs -- TODO: We have a lot of overhead by running inside of a StateT on top of a -- RWST from App. Also see here: -- -- http://www.haskell.org/haskellwiki/Performance/Monads -- http://www.haskell.org/pipermail/haskell-cafe/2011-September/095622.html -- TODO: Think about having XYWH vs X1Y1X2Y2 and where to use relative vs -- absolute coordinates. Probably need to have more of the code in -- place. Having newtype wrappers for abs/rel might avoid bugs and -- make the API safer -- -- TODO: Can we reuse or cache the UI structure build up instead of completely redoing it -- every frame? data Rectangle = Rectangle { rcX1 :: !Float , rcY1 :: !Float , rcX2 :: !Float , rcY2 :: !Float } deriving (Show) {- newtype ARectangle = ARectangle { fromARect :: Rectangle } newtype RRectangle = RRectangle { fromRRect :: Rectangle } stuff1 :: ARectangle stuff1 = ARectangle $ Rectangle 1 2 3 4 stuff2 :: RRectangle stuff2 = RRectangle $ Rectangle 1 2 3 4 -} -- TODO: Record hit boxes and event handlers registered during runUI data UIState = UIState { uisRect :: !Rectangle , uisDepth :: !Float , uisQB :: !QuadRenderBuffer } type UIT m a = ReaderT UIState m a -- TODO: Maybe we should rather put this in the GLFW module or somewhere else? rectFromWndFB :: GLFW.Window -> IO Rectangle rectFromWndFB wnd = do (rcX2, rcY2) <- liftIO $ (\(w, h) -> (fromIntegral w, fromIntegral h)) <$> GLFW.getFramebufferSize wnd return $ Rectangle { rcX1 = 0, rcY1 = 0, .. } rectFromXYWH :: Float -> Float -> Float -> Float -> Rectangle rectFromXYWH x y w h = Rectangle x y (x + w) (y + h) data Split = SLeft | SRight | SBottom | STop | SCenterH | SCenterV deriving (Show, Eq, Enum) splitRect :: Split -> Float -> Rectangle -> (Rectangle, Rectangle) splitRect side pos rc = let (Rectangle x1 y1 x2 y2) = rc splitV pos' = ( Rectangle x1 y1 (x1 + pos') y2 , Rectangle (x1 + pos') y1 x2 y2 ) splitH pos' = ( Rectangle x1 y1 x2 (y1 + pos') , Rectangle x1 (y1 + pos') x2 y2 ) in case side of SLeft -> splitV pos SRight -> swap $ splitV (x2 - x1 - pos) SBottom -> splitH pos STop -> swap $ splitH (y2 - y1 - pos) -- Ignore position if we're asked to do a center split SCenterH -> splitH $ (y2 - y1) / 2 SCenterV -> splitV $ (x2 - x1) / 2 split :: (Applicative m, Monad m) => Split -> Float -> UIT m () -> UIT m () -> UIT m () split side pos near far = do (rcNear, rcFar) <- splitRect side pos <$> asks uisRect frameAbsolute rcNear near frameAbsolute rcFar far center :: Monad m => Float -> Float -> UIT m a -> UIT m a center w h f = do (Rectangle x1 y1 x2 y2) <- asks uisRect let centerX = x1 + (x2 - x1) / 2 centerY = y1 + (y2 - y1) / 2 halfW = w / 2 halfH = h / 2 frameAbsolute ( Rectangle (centerX - halfW) (centerY - halfH) (centerX + halfW) (centerY + halfH) ) f rectOffset :: Rectangle -> Rectangle -> Rectangle rectOffset inner outer = let (Rectangle ix1 iy1 ix2 iy2) = inner (Rectangle ox1 oy1 _ _ ) = outer in Rectangle (ox1 + ix1) (oy1 + iy1) (ox1 + ix2) (oy1 + iy2) frame :: Monad m => Rectangle -> UIT m a -> UIT m a frame inner f = do outer <- asks uisRect frameAbsolute (rectOffset inner outer) f frameAbsolute :: Monad m => Rectangle -> UIT m a -> UIT m a frameAbsolute rc = local (\s -> s { uisRect = rc }) -- TODO: Make better use of the depth range. Have a system where user can -- specify different priorities of 'front' layers, and all the children of -- a given layer can be guaranteed to never exceed a given depth layer :: Monad m => UIT m a -> UIT m a layer = local (\s -> s { uisDepth = uisDepth s - 1 }) -- TODO: Implement a few more combinators -- -- layout (using RectPacker) -- clip (two types, one clipping the rectangle, the other using glScissor) dimensions :: Monad m => UIT m (Float, Float) dimensions = do (Rectangle x1 y1 x2 y2) <- asks uisRect return (x2 - x1, y2 - y1) runUI :: Monad m => Rectangle -> Float -> QuadRenderBuffer -> UIT m a -> m a {-(a, UIState)-} runUI uisRect uisDepth uisQB f = runReaderT f UIState { .. } fill :: MonadIO m => FillColor -> Transparency -> Maybe GL.TextureObject -> QuadUV -> UIT m () fill col trans tex uv = do UIState { .. } <- ask liftIO $ -- drawQuadAdHocVBOShader -- drawQuadImmediate drawQuad uisQB (rcX1 uisRect) (rcY1 uisRect) (rcX2 uisRect) (rcY2 uisRect) uisDepth col trans tex uv text :: MonadIO m => FontRenderer -- TODO: Keep font renderer inside the UI state? -> Typeface -> String -> [TextLayout] -> UIT m () text fr face string layout = do UIState { .. } <- ask let (Rectangle x1 y1 x2 y2) = uisRect liftIO $ drawText fr uisQB face string x1 y1 x2 y2 uisDepth layout {-# INLINEABLE fill #-} --{-# INLINEABLE text #-} --{-# INLINEABLE frame #-} --{-# INLINEABLE frameAbsolute #-} --{-# INLINEABLE rectOffset #-} --{-# INLINEABLE layer #-} --{-# INLINEABLE runUI #-} --{-# INLINEABLE split #-} --{-# INLINEABLE splitRect #-}
blitzcode/jacky
src/UI.hs
mit
6,910
0
14
2,345
1,647
878
769
140
6
module Y2018.M11.D23.Exercise where {-- A puzzle game from https://www.logic-puzzles.org/game.php?u2=63d3ded6b70a71eac63ba911fadacc6e The Springfield County Bird Club met today, and several of its members brought their newest acquisitions. Match each girl to her newest bird - determine its species and the month in which it was purchased. 1. Ida's pet was bought 1 month before the parrot. 2. Tamara's pet, the lorikeet and the bird bought in February are all different birds. 3. The finch was bought 1 month before Ida's pet. 4. The bird bought in February is either the finch or Ellen's pet. 5. Ellen's pet is either the canary or the bird bought in February. Here are the data values under consideration: --} data Month = January | February | March | April deriving (Eq, Ord, Show) data Bird = Canary | Finch | Lorikeet | Parrot deriving (Eq, Show) data Girl = Alberta | Ellen | Ida | Tamara deriving (Eq, Show) data Answer = Ans Girl Bird Month deriving (Eq, Show) -- how do you represent a Clue as a Haskell term? data Clue = IDK -- and given the above clues, solve the puzzle solver :: [Clue] -> [Answer] solver clues = undefined
geophf/1HaskellADay
exercises/HAD/Y2018/M11/D23/Exercise.hs
mit
1,164
0
6
223
150
89
61
12
1
{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE LambdaCase #-} module L.Registers where import Control.Lens import Data.Map as Map import L.Parser.SExpr import Prelude hiding (LT, EQ) data Register = Rax | Rbx | Rcx | Rdx | Rsi | Rdi | Rbp | Rsp | R8 | R9 | R10 | R11 | R12 | R13 | R14 | R15 deriving (Eq,Ord,Enum,Bounded) instance Show Register where show Rax = "rax"; show Rbx = "rbx"; show Rcx = "rcx"; show Rdx = "rdx" show Rsi = "rsi"; show Rdi = "rdi"; show Rbp = "rbp"; show Rsp = "rsp" show R8 = "r8"; show R9 = "r9"; show R10 = "r10"; show R11 = "r11" show R12 = "r12"; show R13 = "r13"; show R14 = "r14"; show R15 = "r15" class AsRegister t where _Register :: Prism' t Register instance AsRegister Register where _Register = id rsi, rdi, rbp, rsp, rax, rbx, rcx, rdx, r8, r9, r10, r11, r12, r13, r14, r15 :: AsRegister t => t rsi = _Register # Rsi rdi = _Register # Rdi rbp = _Register # Rbp rsp = _Register # Rsp r8 = _Register # R8 r9 = _Register # R9 r10 = _Register # R10 r11 = _Register # R11 r12 = _Register # R12 r13 = _Register # R13 r14 = _Register # R14 r15 = _Register # R15 rax = _Register # Rax rbx = _Register # Rbx rcx = _Register # Rcx rdx = _Register # Rdx registersList :: [Register] registersList = [Rax, Rbx, Rcx, Rdx, Rsi, Rdi, Rbp, Rsp, R8, R9, R10, R11, R12, R13, R14, R15] -- saving r15 for storing labels into memory allocatableRegisters :: AsRegister t => [t] allocatableRegisters = [rax, rbx, rcx, rdx, rdi, rsi, r8, r9, r10, r11, r12, r13, r14] registerNames :: [String] registerNames = fmap show registersList registerNamesMap :: Map String Register registerNamesMap = Map.fromList (zip registerNames registersList) registerFromName :: String -> Either String Register registerFromName s = maybe (badRegister s) return (Map.lookup s registerNamesMap) badRegister :: String -> Either String Register badRegister s = Left $ "invalid register: " ++ s instance AsSExpr Register where asSExpr = AtomSym . show instance FromSExpr Register where fromSExpr (AtomSym s) = registerFromName s fromSExpr bad = badRegister $ showSExpr bad low8 :: Register -> String low8 Rax = "al" low8 Rbx = "bl" low8 Rcx = "cl" low8 Rdx = "dl" low8 Rsi = "sil" low8 Rdi = "dil" low8 Rbp = "bpl" low8 Rsp = "spl" low8 R8 = "r8b" low8 R9 = "r9b" low8 R10 = "r10b" low8 R11 = "r11b" low8 R12 = "r12b" low8 R13 = "r13b" low8 R14 = "r14b" low8 R15 = "r15b" low16 :: Register -> String low16 Rax = "ax" low16 Rbx = "bx" low16 Rcx = "cx" low16 Rdx = "dx" low16 Rsi = "si" low16 Rdi = "di" low16 Rbp = "bp" low16 Rsp = "sp" low16 R8 = "r8w" low16 R9 = "r9w" low16 R10 = "r10w" low16 R11 = "r11w" low16 R12 = "r12w" low16 R13 = "r13w" low16 R14 = "r14w" low16 R15 = "r15w" low32 :: Register -> String low32 Rax = "eax" low32 Rbx = "ebx" low32 Rcx = "ecx" low32 Rdx = "edx" low32 Rsi = "esi" low32 Rdi = "edi" low32 Rbp = "ebp" low32 Rsp = "esp" low32 R8 = "r8d" low32 R9 = "r9d" low32 R10 = "r10d" low32 R11 = "r11d" low32 R12 = "r12d" low32 R13 = "r13d" low32 R14 = "r14d" low32 R15 = "r15d"
joshcough/L5-Haskell
src/L/Registers.hs
mit
3,200
0
8
652
1,189
660
529
110
1
{-| Module: Main Description: Oil server. License: MIT -} {-# LANGUAGE OverloadedStrings #-} module Main ( main ) where import Control.Concurrent.STM import qualified Data.ByteString.Lazy as BL import qualified Data.Serialize as S import qualified Data.Text as T import qualified Network.HTTP.Types as H import qualified Network.Wai as W import qualified Network.Wai.Middleware.Gzip as W import qualified Network.Wai.Middleware.RequestLogger as W import qualified Network.Wai.Handler.Warp as Warp import qualified Options.Applicative as O import Flaw.Book import Flaw.Flow import Flaw.Oil.Repo import Flaw.Oil.ServerRepo main :: IO () main = run =<< O.execParser parser where parser = O.info (O.helper <*> opts) ( O.fullDesc <> O.progDesc "Opens FILE repo and starts listening on given PORT" <> O.header "oild - Flaw Oil server" ) opts = Options <$> O.strOption ( O.short 'f' <> O.metavar "FILE" <> O.help "Server repo file" ) <*> O.option O.auto ( O.long "port" <> O.short 'p' <> O.value 8080 <> O.showDefault <> O.metavar "PORT" <> O.help "Port to listen at" ) <*> O.option O.auto ( O.long "watch-delay" <> O.value 25000000 <> O.showDefault <> O.metavar "WATCH-DELAY" <> O.help "Delay before negative response to watch request, in μs" ) data Options = Options { optionsRepoFileName :: String , optionsPort :: Int , optionsWatchDelay :: Int } run :: Options -> IO () run Options { optionsRepoFileName = repoFileName , optionsPort = port , optionsWatchDelay = watchDelay } = withBook $ \bk -> do let -- form manifest with limits manifest = defaultManifest -- calculate rough limit for sync requests syncRequestBodyLimit = manifestMaxPushItemsCount manifest * (manifestMaxKeySize manifest + manifestMaxValueSize manifest + 0x1000) + 0x1000 -- limit for watch requests watchRequestBodyLimit = 16 -- open repo repo <- book bk $ openServerRepo $ T.pack repoFileName -- flow for repo processing flow <- book bk newFlow -- server revision var revisionVar <- newTVarIO =<< serverRepoMaxRevision repo -- logger logger <- W.mkRequestLogger $ W.def { W.outputFormat = W.Apache W.FromFallback , W.autoFlush = False } -- start web server Warp.run port $ W.gzip W.def $ logger $ \request respond -> do -- helper methods let respondFail status msg = respond $ W.responseLBS status [(H.hContentType, "text/plain; charset=utf-8")] $ BL.fromStrict msg case W.queryString request of [("manifest", Nothing)] -> respond $ W.responseLBS H.status200 [(H.hContentType, "application/x-flawoil-manifest")] $ S.encodeLazy manifest [("sync", Nothing)] -> do -- read request body <- BL.take (fromIntegral $ syncRequestBodyLimit + 1) <$> W.lazyRequestBody request if BL.length body <= fromIntegral syncRequestBodyLimit then -- deserialize push case S.decodeLazy body of Right push -> do -- perform sync let userId = 1 -- TODO: implement user auth -- sync in a flow pull <- runInFlow flow $ do -- perform sync pull <- syncServerRepo repo manifest push userId -- update current revision revision <- serverRepoMaxRevision repo atomically $ writeTVar revisionVar revision return pull -- respond with pull respond $ W.responseLBS H.status200 [(H.hContentType, "application/x-flawoil-sync")] $ S.encodeLazy pull Left _ -> respondFail H.status400 "wrong push format" else respondFail H.status400 "too big sync request" [("watch", Nothing)] -> do body <- BL.take (watchRequestBodyLimit + 1) <$> W.lazyRequestBody request if BL.length body <= watchRequestBodyLimit then -- deserialize revision case S.decodeLazy body of Right watchRevision -> do -- timer timerVar <- registerDelay watchDelay -- wait until revision become bigger than watch revison, or time outs revision <- atomically $ do repoRevision <- readTVar revisionVar let checkRevision = if watchRevision < repoRevision then return repoRevision else retry checkTimer = do timer <- readTVar timerVar if timer then return repoRevision else retry in orElse checkRevision checkTimer -- respond with repo revision respond $ W.responseLBS H.status200 [(H.hContentType, "application/x-flawoil-watch")] $ S.encodeLazy revision Left _ -> respondFail H.status400 "wrong watch format" else respondFail H.status400 "too big watch request" _ -> respondFail H.status404 "wrong request"
quyse/flaw
flaw-oil-server/oild.hs
mit
5,166
0
35
1,566
1,182
613
569
108
10
module StaticFilters.Filter7 where filter7 :: [Integer] filter7 = [0,1,2332800000,2332800001,11664000000,11664000001,37324800000,37324800001,46656000000]
jbetzend/hA258107
src/StaticFilters/Filter7.hs
cc0-1.0
154
0
5
9
46
30
16
3
1
import Data.List rtriangle lim = [[a,b,c] | a <- [1..lim], b <- [1..a], c <- [1..b], a^2 == c^2 + b^2] squares lim = [i^2 | i <- [1..lim], 0 == (rem (i^2) 5)] coords lim = [[a,b]| a <- [1..lim], b <- [1..lim]]
zeniuseducation/poly-euler
haskell/tutorial.hs
epl-1.0
213
0
11
47
183
99
84
4
1
data Boolx = Minx | Plusx data Natx a = Zx | Sx a | SSx (Natx a) Boolx map1 :: Natx Int -> (Int -> Int) -> Natx Int map1 x = \ f -> case x of Zx -> Sx (f 0) Sx n -> Sx (f n)
nevrenato/Hets_Fork
Haskell/test/HOLCF/incmpl.hs
gpl-2.0
193
2
11
69
120
59
61
6
2
module Cryptography.ComputationalProblems.Games.DistinctionProblems.Terms where import Notes makeDefs [ "deterministic distinction problem" , "probabilistic distinction problem" , "distinction problem" , "deterministic distinguisher" , "probabilistic distinguisher" , "distinguisher" , "deterministic distinction game" , "distinction game" ]
NorfairKing/the-notes
src/Cryptography/ComputationalProblems/Games/DistinctionProblems/Terms.hs
gpl-2.0
392
0
6
83
42
27
15
-1
-1
-- Copyright (C) 2006-2008 Angelos Charalambidis <a.charalambidis@di.uoa.gr> -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2, 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; see the file COPYING. If not, write to -- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -- Boston, MA 02110-1301, USA. {-# LANGUAGE MultiParamTypeClasses #-} module Lang where import Types (Typed(..)) type Name = String class Symbol a where liftSym :: String -> a data Sym = Sym String | AnonSym data Var = V Name | NoNameVar instance Show Var where showsPrec p (V n) = showsPrec p n showsPrec p (NoNameVar) = showString "_" instance Show Sym where showsPrec p (Sym a) = showsPrec p a showsPrec p AnonSym = showString "_" instance Symbol Sym where liftSym a = Sym a instance Eq Sym where (Sym s1) == (Sym s2) = s1 == s2 AnonSym == s = False s == AnonSym = False instance Symbol a => Symbol (Typed a) where liftSym a = T (liftSym a) (error "not valid type") -- | Signature is the union of constants and variables type Sig a = ([a], [a]) emptySig = ([],[]) joinSig (a1,a2) (b1,b2) = (a1 ++ b1, a2 ++ b2) rigSig s = ([s], []) varSig s = ([], [s]) class Symbol s => HasSignature a s where sig :: a -> Sig s {- instance Symbol a => HasSignature a a where sig a = rigSig a -- sig AnonSym = emptySig -} instance HasSignature Sym Sym where sig AnonSym = emptySig sig a = rigSig a vars :: (Symbol b, HasSignature a b) => a -> [b] rigids :: (Symbol b, HasSignature a b) => a -> [b] -- symbols :: HasSignature a b => a -> [b] -- symbols = symbolsSig . sig where symbolsSig (as, bs) = as ++ bs vars = varsSig . sig where varsSig (as, bs) = bs rigids = rigidsSig . sig where rigidsSig (as, bs) = as class Eq a => HasLogicConstants a where ctop :: a cbot :: a cor :: a cand :: a ceq :: a cexists :: a contradiction :: HasLogicConstants a => a contradiction = ctop isContra :: HasLogicConstants a => a -> Bool isContra = (==contradiction)
acharal/hopes
src/basic/Lang.hs
gpl-2.0
2,585
0
8
632
657
360
297
49
1
{-# LANGUAGE GADTs, FlexibleInstances, MultiParamTypeClasses #-} module Keyboard where import Music (AbstractPitch2(..), AbstractInt2(..), pitchToFa, FreeAbelian(..), Scale(..), AbstractPitch3(..)) import Tuning import Scales (transposeScale, scaleDegree, completeScale, major, minor) import Shortcuts import Util (rotateN) playKeyboard k t = (tune t) . (applyScale k) faDot :: (Int, Int) -> AbstractPitch2 -> Int faDot (x, y) p = let a ::+ d = pitchToFa p in x*a + y*d numbering7 = faDot (0, 1) numbering12 = faDot (1, 0) numbering19 = faDot (1, 1) data Wolf = Wolf AbstractPitch2 deriving Show wolfChromatic = [aes, a, bes, b, c, cis, d, ees, e, f, fis, g] instance Scale Wolf AbstractPitch2 AbstractInt2 where tonic (Wolf t) = t scale s = let newScale = transposeScale wolfChromatic a (tonic s) rotated = rotateN (12 - (numbering12 (tonic s))) newScale --transposed = map (.-^ _P8) rotated transposed = rotated in take 11 transposed applyScale s p = let i = numbering12 p notes = completeScale s i in notes !! (abs i) standardWolf = Wolf a data Costeley = Costeley AbstractPitch2 deriving Show costeleyScale = [aes, a, ais, bes, b, bis, c, cis, des, d, dis, ees, e, eis, f, fis, ges, g, gis] instance Scale Costeley AbstractPitch2 AbstractInt2 where tonic (Costeley t) = t scale s = let newScale = transposeScale wolfChromatic a (tonic s) rotated = rotateN (19 - (numbering19 (tonic s))) newScale transposed = map (.+^ _P8) rotated in take 18 transposed applyScale s p = let i = numbering19 p notes = completeScale s i in notes !! (abs i)
ejlilley/AbstractMusic
Keyboard.hs
gpl-3.0
1,827
0
16
540
643
357
286
41
1
module Embedded where import Control.Monad.Trans.Except import Control.Monad.Trans.Maybe import Control.Monad.Trans.Reader -- We only need to use return once -- because it's one big Monad embedded :: MaybeT (ExceptT String (ReaderT () IO)) Int embedded = return 1 -- We can sort of peel away the layers one by one: maybeUnwrap :: ExceptT String (ReaderT () IO) (Maybe Int) maybeUnwrap = runMaybeT embedded -- Next eitherUnwrap :: ReaderT () IO (Either String (Maybe Int)) eitherUnwrap = runExceptT maybeUnwrap -- Lastly readerUnwrap :: () -> IO (Either String (Maybe Int)) readerUnwrap = runReaderT eitherUnwrap -- Exercise: Wrap It Up -- Turn readerUnwrap from the previous example back into embedded -- through the use of the data constructors for each transformer. -- Modify it to make it work. embedded' :: MaybeT (ExceptT String (ReaderT () IO)) Int embedded' = MaybeT . ExceptT . ReaderT $ pure . (const (Right (Just 1)))
nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles
MonadTransformers/src/Embedded.hs
gpl-3.0
1,097
0
11
316
245
133
112
24
1
{-# LANGUAGE QuasiQuotes, OverloadedStrings #-} module ObjectOrientedSpec (spec) where import Test.Hspec import Language.Mulang.Parsers.JavaScript import Language.Mulang.Parsers.Java (java) import Language.Mulang.Ast import Language.Mulang.Identifier import Language.Mulang.Inspector.ObjectOriented import Language.Mulang.Inspector.Combiner spec :: Spec spec = do describe "declaresInterface" $ do it "is True when present" $ do declaresInterface (named "Optional") (java "interface Optional { Object get(); }") `shouldBe` True it "is False when not present" $ do declaresInterface (named "Bird") (java "class Bird extends Animal {}") `shouldBe` False describe "instantiates" $ do it "is True when instantiates" $ do instantiates (named "Bird") (java "class Main { void main(String[] args) { Animal a = new Bird(); } }") `shouldBe` True it "is False when not instantiates" $ do instantiates (named "Bird") (java "class Main { void main(String[] args) { Animal a = new Mammal(); } }") `shouldBe` False it "is True when instantiates a HashSet" $ do instantiates (named "TreeSet") (java "class Main { private Set<String> aSet = new TreeSet<>(); }") `shouldBe` True instantiates (named "HashSet") (java "class Main { private Set<String> aSet = new TreeSet<>(); }") `shouldBe` False it "is False when not instantiates a HashSet" $ do instantiates (named "TreeSet") (java "class Main { private Set<String> aSet = new HashSet<>(); }") `shouldBe` False instantiates (named "HashSet") (java "class Main { private Set<String> aSet = new HashSet<>(); }") `shouldBe` True describe "implements" $ do it "is True when implements" $ do implements (named "Bird") (java "class Eagle implements Bird {}") `shouldBe` True it "is False when implements declaration not present" $ do implements (named "Bird") (java "class Cell {}") `shouldBe` False it "is False when a superinterface is declares" $ do implements (named "Iterable") (java "interface Collection extends Iterable {}") `shouldBe` False describe "usesInheritance" $ do it "is True when present" $ do usesInheritance (Class "Bird" (Just "Animal") None) `shouldBe` True it "is False when not present" $ do usesInheritance (Class "Bird" Nothing None) `shouldBe` False it "is True when present, scoped" $ do (scoped "Bird" usesInheritance) (Sequence [Class "Bird" (Just "Animal") None, Class "Fox" (Just "Animal") None]) `shouldBe` True it "is True when present, scoped" $ do (scoped "Hercules" usesInheritance) (Sequence [Class "Hercules" Nothing None, Class "Fox" (Just "Animal") None]) `shouldBe` False describe "usesMixins" $ do it "is True when include present" $ do usesMixins (Class "Dragon" Nothing (Include (Reference "FlyingCreature"))) `shouldBe` True it "is False when include not present" $ do usesMixins (Class "Dragon" Nothing (Implement (Reference "FlyingCreature"))) `shouldBe` False describe "declaresMethod" $ do it "is True when present" $ do declaresMethod (named "x") (js "let f = {x: function(){}}") `shouldBe` True it "is works with except" $ do declaresMethod (except "x") (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True declaresMethod (except "a") (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True declaresMethod (except "y") (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True declaresMethod (except "b") (js "let obj = {b: function(){}}") `shouldBe` False it "is works with anyOf" $ do declaresMethod (anyOf ["x", "y"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` False declaresMethod (anyOf ["a", "y"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True declaresMethod (anyOf ["x", "b"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True declaresMethod (anyOf ["a", "b"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True it "is works with noneOf" $ do declaresMethod (noneOf ["x", "y"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True declaresMethod (noneOf ["x", "b"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True declaresMethod (noneOf ["a", "y"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True declaresMethod (noneOf ["a", "b"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` False it "is True when any present" $ do declaresMethod anyone (js "let f = {x: function(){}}") `shouldBe` True it "is True when scoped in a class" $ do scoped "A" (declaresMethod (named "foo")) (java "class A { void foo() {} }") `shouldBe` True it "is False when scoped in a class and not present" $ do scoped "A" (declaresMethod (named "foo")) (java "class A { void foobar() {} }") `shouldBe` False it "is False when not present" $ do declaresMethod (named "m") (js "let f = {x: function(){}}") `shouldBe` False it "is False when not a method" $ do declaresMethod (named "m") (js "let f = {x: 6}") `shouldBe` False it "is True when object present, scoped" $ do scoped "f" (declaresMethod (named "x")) (js "let f = {x: function(){}}") `shouldBe` True it "is False when object not present, scoped" $ do scoped "p" (declaresMethod (named "x")) (js "let f = {x: function(){}}") `shouldBe` False describe "declaresAttribute" $ do it "is True when present" $ do declaresAttribute (named "x") (js "let f = {x: 6}") `shouldBe` True it "is True when present and there are many" $ do declaresAttribute (named "x") (js "let f = {j: 20, x: 6}") `shouldBe` True it "is False when not present" $ do declaresAttribute (named "m") (js "let f = {x: 6}") `shouldBe` False it "is True when attribute present, scoped" $ do scoped "f" (declaresAttribute (named "x")) (js "let f = {x: 6}") `shouldBe` True it "is True when any attribute present, scoped" $ do scoped "f" (declaresAttribute anyone) (js "let f = {x: 6}") `shouldBe` True it "is False when attribute not present, scoped" $ do scoped "g" (declaresAttribute (named "x")) (js "let f = {x: 6}") `shouldBe` False describe "declaresObject" $ do it "is True when present" $ do declaresObject (named "f") (js "let f = {x: 6}") `shouldBe` True it "is False when not present" $ do declaresObject (named "f") (js "let f = 6") `shouldBe` False it "is False when not present, scoped" $ do declaresObject (named "f") (js "let g = {}") `shouldBe` False it "is True when present, scoped" $ do declaresObject (named "g") (js "let g = {}") `shouldBe` True it "is True when anyone present, scoped" $ do declaresObject anyone (js "let g = {}") `shouldBe` True describe "declaresEnumeration" $ do it "is True when present" $ do declaresEnumeration (named "Direction") (Enumeration "Direction" ["SOUTH", "EAST", "WEST", "NORTH"]) `shouldBe` True it "is False when not present" $ do declaresEnumeration (named "Bird") (Class "Bird" (Just "Animal") None) `shouldBe` False
mumuki/mulang
spec/ObjectOrientedSpec.hs
gpl-3.0
7,370
0
20
1,650
2,032
990
1,042
109
1
import Colors import Configuration import Calendar import ArgumentHandling -- Color support? colorSupport :: [Argument] -> Bool colorSupport args = elem (ColorSupport True) args numberOfDays :: [Argument] -> Int numberOfDays args = let findNmbr :: Argument -> Bool findNmbr (NumberOfDays _) = True findNmbr _ = False filterCorrectArgs = filter findNmbr args unwrapNmbr (NumberOfDays n) = n unwrapNmbr e = error $ "numberOfDays: unwrapNmbr got wrong input" ++ show e in if filterCorrectArgs == [] then 5 else (unwrapNmbr $ last (filterCorrectArgs)) -- Program logic getWorkDayTable :: (Day -> Bool) -> CalendarMonad (Weekday,Bool) getWorkDayTable workDay = CalendarMonad $ \day -> let weekday = formatTimeToWeekday day in (succ day, (weekday, workDay day)) regularWorkDays :: IO [Weekday] regularWorkDays = let weekdayString :: IO String weekdayString = fmap (maybe "" id) $ getConfigOption "default.workdays" in fmap (map read . words) weekdayString uniqueWorkDays :: IO [Day] uniqueWorkDays = let getString :: IO (Maybe String) getString = getConfigOption "unique.workdays" unpackMaybeString :: Maybe String -> String unpackMaybeString = maybe "" id stringToDays :: String -> [Day] stringToDays s = map read (words s) in fmap (stringToDays . unpackMaybeString) getString isWorkDay :: [Weekday] -> [Day] -> Day -> Bool isWorkDay regular unique day = elem (formatTimeToWeekday day) regular || (elem day unique) listNextDays :: Day -> Int -> (Day -> Bool) -> [(Weekday, Bool)] listNextDays startDate n procedure = let nd 0 accu = return accu nd m accu = do wd <- getWorkDayTable procedure nd (m-1) (wd:accu) CalendarMonad runIt = nd n [] in reverse $ snd $ (runIt startDate) makeTable :: [(Weekday, Bool)] -> Bool -> String makeTable dates colorsupport = let makeLine :: (Weekday, Bool) -> String makeLine (wd,bool) = "| " ++ show wd ++ "\t | " ++ (workdayToString bool) ++ " |" workdayToString :: Bool -> String workdayToString True = condRed ++ "work" ++ condNormal workdayToString False = condGreen ++ "free" ++ condNormal condRed = if colorsupport then red else "" condGreen = if colorsupport then green else "" condNormal = if colorsupport then normal else "" in unlines $ map makeLine dates main :: IO () main = getCommandLineArgs >>= \cmdLineArgs -> let color = colorSupport cmdLineArgs howManyDays = numberOfDays cmdLineArgs in getToday >>= \today -> regularWorkDays >>= \regular -> uniqueWorkDays >>= \uniques -> let renderTable :: [(Weekday, Bool)] -> String renderTable pairs = makeTable pairs color generateInformation = listNextDays today howManyDays (isWorkDay regular uniques) in putStr $ renderTable $ generateInformation
seppeljordan/haskell-calendar
src/workcalendar.hs
gpl-3.0
3,332
0
21
1,096
937
484
453
70
5
{-# LANGUAGE DeriveFunctor #-} module WeatherReporterFree where import Control.Monad.Free -- KISS. type WeatherData = String data WeatherF a = Fetch (WeatherData -> a) | Store WeatherData a | Report WeatherData a deriving (Functor) fetch :: Free WeatherF WeatherData fetch = liftF $ Fetch id store :: WeatherData -> Free WeatherF () store w = liftF $ Store w () report :: WeatherData -> Free WeatherF () report w = liftF $ Report w () reportWeather :: Free WeatherF () reportWeather = do w <- fetch store w report w -- Now it is easy to write an interpreter for this. interp :: WeatherF a -> IO a interp (Fetch f) = return $ f "it's gonna freeze!" interp (Store w a) = do putStrLn $ "I'm also throwing this away: " ++ w return a interp (Report w a) = do putStrLn $ "The blackie weather forecast says " ++ w return a dummyWeatherReport :: IO () dummyWeatherReport = foldFree interp reportWeather -- The problem with the interpreter above is that we don't have separation of -- concerns.
capitanbatata/sandbox
on-dependency-injection-in-fp/a-weather-app/src/WeatherReporterFree.hs
gpl-3.0
1,084
0
8
276
309
156
153
29
1
module Hadolint.Ignore (ignored) where import qualified Control.Foldl as Foldl import qualified Data.IntMap.Strict as Map import qualified Data.Set as Set import qualified Data.Text as Text import Data.Void (Void) import Hadolint.Rule (RuleCode (RuleCode)) import Language.Docker.Syntax import qualified Text.Megaparsec as Megaparsec import qualified Text.Megaparsec.Char as Megaparsec ignored :: Foldl.Fold (InstructionPos Text.Text) (Map.IntMap (Set.Set RuleCode)) ignored = Foldl.Fold parse mempty id where parse acc InstructionPos {instruction = Comment comment, lineNumber = line} = case parseComment comment of Just ignores@(_ : _) -> Map.insert (line + 1) (Set.fromList . fmap RuleCode $ ignores) acc _ -> acc parse acc _ = acc parseComment :: Text.Text -> Maybe [Text.Text] parseComment = Megaparsec.parseMaybe commentParser commentParser :: Megaparsec.Parsec Void Text.Text [Text.Text] commentParser = do spaces >> string "hadolint" >> spaces1 >> string "ignore=" >> spaces >> Megaparsec.sepBy1 ruleName (spaces >> string "," >> spaces) ruleName = Megaparsec.takeWhile1P Nothing (\c -> c `elem` Set.fromList "DLSC0123456789") string = Megaparsec.string spaces = Megaparsec.takeWhileP Nothing space spaces1 = Megaparsec.takeWhile1P Nothing space space c = c == ' ' || c == '\t'
lukasmartinelli/hadolint
src/Hadolint/Ignore.hs
gpl-3.0
1,419
0
14
303
432
237
195
34
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Prediction.HostedModels.Predict -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Submit input and request an output against a hosted model. -- -- /See:/ <https://developers.google.com/prediction/docs/developer-guide Prediction API Reference> for @prediction.hostedmodels.predict@. module Network.Google.Resource.Prediction.HostedModels.Predict ( -- * REST Resource HostedModelsPredictResource -- * Creating a Request , hostedModelsPredict , HostedModelsPredict -- * Request Lenses , hmpProject , hmpPayload , hmpHostedModelName ) where import Network.Google.Prediction.Types import Network.Google.Prelude -- | A resource alias for @prediction.hostedmodels.predict@ method which the -- 'HostedModelsPredict' request conforms to. type HostedModelsPredictResource = "prediction" :> "v1.6" :> "projects" :> Capture "project" Text :> "hostedmodels" :> Capture "hostedModelName" Text :> "predict" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Input :> Post '[JSON] Output -- | Submit input and request an output against a hosted model. -- -- /See:/ 'hostedModelsPredict' smart constructor. data HostedModelsPredict = HostedModelsPredict' { _hmpProject :: !Text , _hmpPayload :: !Input , _hmpHostedModelName :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'HostedModelsPredict' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'hmpProject' -- -- * 'hmpPayload' -- -- * 'hmpHostedModelName' hostedModelsPredict :: Text -- ^ 'hmpProject' -> Input -- ^ 'hmpPayload' -> Text -- ^ 'hmpHostedModelName' -> HostedModelsPredict hostedModelsPredict pHmpProject_ pHmpPayload_ pHmpHostedModelName_ = HostedModelsPredict' { _hmpProject = pHmpProject_ , _hmpPayload = pHmpPayload_ , _hmpHostedModelName = pHmpHostedModelName_ } -- | The project associated with the model. hmpProject :: Lens' HostedModelsPredict Text hmpProject = lens _hmpProject (\ s a -> s{_hmpProject = a}) -- | Multipart request metadata. hmpPayload :: Lens' HostedModelsPredict Input hmpPayload = lens _hmpPayload (\ s a -> s{_hmpPayload = a}) -- | The name of a hosted model. hmpHostedModelName :: Lens' HostedModelsPredict Text hmpHostedModelName = lens _hmpHostedModelName (\ s a -> s{_hmpHostedModelName = a}) instance GoogleRequest HostedModelsPredict where type Rs HostedModelsPredict = Output type Scopes HostedModelsPredict = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/prediction"] requestClient HostedModelsPredict'{..} = go _hmpProject _hmpHostedModelName (Just AltJSON) _hmpPayload predictionService where go = buildClient (Proxy :: Proxy HostedModelsPredictResource) mempty
brendanhay/gogol
gogol-prediction/gen/Network/Google/Resource/Prediction/HostedModels/Predict.hs
mpl-2.0
3,835
0
16
903
468
279
189
77
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.Jobs.Projects.Tenants.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves specified tenant. -- -- /See:/ <https://cloud.google.com/talent-solution/job-search/docs/ Cloud Talent Solution API Reference> for @jobs.projects.tenants.get@. module Network.Google.Resource.Jobs.Projects.Tenants.Get ( -- * REST Resource ProjectsTenantsGetResource -- * Creating a Request , projectsTenantsGet , ProjectsTenantsGet -- * Request Lenses , ptgXgafv , ptgUploadProtocol , ptgAccessToken , ptgUploadType , ptgName , ptgCallback ) where import Network.Google.Jobs.Types import Network.Google.Prelude -- | A resource alias for @jobs.projects.tenants.get@ method which the -- 'ProjectsTenantsGet' request conforms to. type ProjectsTenantsGetResource = "v4" :> 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] Tenant -- | Retrieves specified tenant. -- -- /See:/ 'projectsTenantsGet' smart constructor. data ProjectsTenantsGet = ProjectsTenantsGet' { _ptgXgafv :: !(Maybe Xgafv) , _ptgUploadProtocol :: !(Maybe Text) , _ptgAccessToken :: !(Maybe Text) , _ptgUploadType :: !(Maybe Text) , _ptgName :: !Text , _ptgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsTenantsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ptgXgafv' -- -- * 'ptgUploadProtocol' -- -- * 'ptgAccessToken' -- -- * 'ptgUploadType' -- -- * 'ptgName' -- -- * 'ptgCallback' projectsTenantsGet :: Text -- ^ 'ptgName' -> ProjectsTenantsGet projectsTenantsGet pPtgName_ = ProjectsTenantsGet' { _ptgXgafv = Nothing , _ptgUploadProtocol = Nothing , _ptgAccessToken = Nothing , _ptgUploadType = Nothing , _ptgName = pPtgName_ , _ptgCallback = Nothing } -- | V1 error format. ptgXgafv :: Lens' ProjectsTenantsGet (Maybe Xgafv) ptgXgafv = lens _ptgXgafv (\ s a -> s{_ptgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ptgUploadProtocol :: Lens' ProjectsTenantsGet (Maybe Text) ptgUploadProtocol = lens _ptgUploadProtocol (\ s a -> s{_ptgUploadProtocol = a}) -- | OAuth access token. ptgAccessToken :: Lens' ProjectsTenantsGet (Maybe Text) ptgAccessToken = lens _ptgAccessToken (\ s a -> s{_ptgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ptgUploadType :: Lens' ProjectsTenantsGet (Maybe Text) ptgUploadType = lens _ptgUploadType (\ s a -> s{_ptgUploadType = a}) -- | Required. The resource name of the tenant to be retrieved. The format is -- \"projects\/{project_id}\/tenants\/{tenant_id}\", for example, -- \"projects\/foo\/tenants\/bar\". ptgName :: Lens' ProjectsTenantsGet Text ptgName = lens _ptgName (\ s a -> s{_ptgName = a}) -- | JSONP ptgCallback :: Lens' ProjectsTenantsGet (Maybe Text) ptgCallback = lens _ptgCallback (\ s a -> s{_ptgCallback = a}) instance GoogleRequest ProjectsTenantsGet where type Rs ProjectsTenantsGet = Tenant type Scopes ProjectsTenantsGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/jobs"] requestClient ProjectsTenantsGet'{..} = go _ptgName _ptgXgafv _ptgUploadProtocol _ptgAccessToken _ptgUploadType _ptgCallback (Just AltJSON) jobsService where go = buildClient (Proxy :: Proxy ProjectsTenantsGetResource) mempty
brendanhay/gogol
gogol-jobs/gen/Network/Google/Resource/Jobs/Projects/Tenants/Get.hs
mpl-2.0
4,612
0
15
1,048
700
410
290
101
1
-- | Module containing enums from GEGL module GEGL.Enums ( GeglAccessMode(..) , GeglAbyssPolicy(..) , GeglOrientation(..) , GeglSamplerType(..) , GeglBlitFlag(..) ) where -- | Access mode to buffers data GeglAccessMode = GeglAccessRead | GeglAccessWrite | GeglAccessReadWrite deriving (Eq, Show) instance Enum GeglAccessMode where fromEnum GeglAccessRead = 1 fromEnum GeglAccessWrite = 2 fromEnum GeglAccessReadWrite = 3 toEnum 1 = GeglAccessRead toEnum 2 = GeglAccessWrite toEnum 3 = GeglAccessReadWrite toEnum unmatched = error ("GeglAccessMode.toEnum: Cannot match " ++ show unmatched) -- | I don't know data GeglAbyssPolicy = GeglAbyssNone | GeglAbyssClamp | GeglAbyssLoop | GeglAbyssBlack | GeglAbyssWhite deriving (Eq, Show) instance Enum GeglAbyssPolicy where fromEnum GeglAbyssNone = 0 fromEnum GeglAbyssClamp = 1 fromEnum GeglAbyssLoop = 2 fromEnum GeglAbyssBlack = 3 fromEnum GeglAbyssWhite = 4 toEnum 0 = GeglAbyssNone toEnum 1 = GeglAbyssClamp toEnum 2 = GeglAbyssLoop toEnum 3 = GeglAbyssBlack toEnum 4 = GeglAbyssWhite toEnum unmatched = error ("GeglAbyssPolicy.toEnum: cannot match " ++ show unmatched) -- | Orientation of a buffer data GeglOrientation = GeglOrientationHorizontal | GeglOrientationVertical deriving (Eq, Show) instance Enum GeglOrientation where fromEnum GeglOrientationHorizontal = 0 fromEnum GeglOrientationVertical = 1 toEnum 0 = GeglOrientationHorizontal toEnum 1 = GeglOrientationVertical toEnum unmatched = error ("GeglOrientation.toEnum: cannot match " ++ show unmatched) data GeglSamplerType = GeglSamplerNearest | GeglSamplerLinear | GeglSamplerCubic | GeglSamplerNohalo | GeglSamplerLohalo deriving (Eq, Show) instance Enum GeglSamplerType where fromEnum GeglSamplerNearest = 0 fromEnum GeglSamplerLinear = 1 fromEnum GeglSamplerCubic = 2 fromEnum GeglSamplerNohalo = 3 fromEnum GeglSamplerLohalo = 4 toEnum 0 = GeglSamplerNearest toEnum 1 = GeglSamplerLinear toEnum 2 = GeglSamplerCubic toEnum 3 = GeglSamplerNohalo toEnum 4 = GeglSamplerLohalo toEnum unmatched = error ("GeglSamplerType.toEnum: cannot match " ++ show unmatched) -- | enum type for blit flags data GeglBlitFlag = GeglBlitDefault -- ^ Default blitting. nothing special and sufficient in -- most cases | GeglBlitCache -- ^ Set up a cache for any subsequent requests of image -- data from this node. | GeglBlitDirty -- ^ Return the latest rendered results in cache without -- regard to wether the regions had been rendered or not. instance Enum GeglBlitFlag where fromEnum GeglBlitDefault = 0 fromEnum GeglBlitCache = 1 fromEnum GeglBlitDirty = 2 toEnum 0 = GeglBlitDefault toEnum 1 = GeglBlitCache toEnum 2 = GeglBlitDirty toEnum u = error ("GeglBlitFlag.toEnum: cannot match " ++ show u)
nek0/gegl
src/GEGL/Enums.hs
lgpl-3.0
2,941
0
9
616
605
325
280
79
0
{-# LANGUAGE RankNTypes #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files -- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. ----------------------------------------------------------------------------- -- | -- Maintainer : bastiaan.heeren@ou.nl -- Stability : provisional -- Portability : portable (depends on ghc) -- -- Manages links to information -- ----------------------------------------------------------------------------- module Ideas.Encoding.LinkManager ( LinkManager(..), makeLinkManager , stateToXML -- , pathLevel, (</>) -- links to services and exercises , linkToIndex, linkToExercises, linkToServices, linkToService -- links to exercise information , linkToExercise, linkToStrategy, linkToRules, linkToExamples , linkToDerivations, linkToRule, linkToRandomExample, linkToTestReport -- links to state information (dynamic) , linkToState, linkToFirsts, linkToApplications, linkToDerivation , linkToMicrosteps , escapeInURL ) where import Data.Maybe import Data.Monoid import Ideas.Common.Library import Ideas.Encoding.EncoderXML import Ideas.Encoding.Options import Ideas.Service.State import Ideas.Service.Types import Ideas.Text.HTML import Ideas.Text.XML import Ideas.Utils.Decoding data LinkManager = LinkManager { urlForCSS :: String -> String , urlForImage :: String -> String , urlForRequest :: String -- links to services and exercises , urlForIndex :: String , urlForExercises :: String , urlForServices :: String , urlForService :: Service -> String -- links to exercise information , urlForExercise :: forall a . Exercise a -> String , urlForStrategy :: forall a . Exercise a -> String , urlForRules :: forall a . Exercise a -> String , urlForConstraints :: forall a . Exercise a -> String , urlForExamples :: forall a . Exercise a -> String , urlForDerivations :: forall a . Exercise a -> String , urlForRule :: forall a . Exercise a -> Rule (Context a) -> String , urlForTestReport :: forall a . Exercise a -> String -- dynamic exercise information , urlForRandomExample :: forall a . Exercise a -> Difficulty -> String -- dynamic state information , urlForState :: forall a . State a -> String , urlForFirsts :: forall a . State a -> String , urlForApplications :: forall a . State a -> String , urlForDerivation :: forall a . State a -> String , urlForMicrosteps :: forall a . State a -> String } --------------------------------------------------------------------- -- links to services and exercises linkToIndex :: LinkManager -> HTMLBuilder -> HTMLBuilder linkToIndex = linkWith urlForIndex linkToExercises :: LinkManager -> HTMLBuilder -> HTMLBuilder linkToExercises = linkWith urlForExercises linkToServices :: LinkManager -> HTMLBuilder -> HTMLBuilder linkToServices = linkWith urlForServices linkToService :: LinkManager -> Service -> HTMLBuilder -> HTMLBuilder linkToService = linkWith . urlForService --------------------------------------------------------------------- -- links to exercise information linkToExercise :: LinkManager -> Exercise a -> HTMLBuilder -> HTMLBuilder linkToExercise = linkWith . urlForExercise linkToStrategy :: LinkManager -> Exercise a -> HTMLBuilder -> HTMLBuilder linkToStrategy = linkWith . urlForStrategy linkToRules :: LinkManager -> Exercise a -> HTMLBuilder -> HTMLBuilder linkToRules = linkWith . urlForRules linkToExamples :: LinkManager -> Exercise a -> HTMLBuilder -> HTMLBuilder linkToExamples = linkWith . urlForExamples linkToDerivations :: LinkManager -> Exercise a -> HTMLBuilder -> HTMLBuilder linkToDerivations = linkWith . urlForDerivations linkToRule :: LinkManager -> Exercise a -> Rule (Context a) -> HTMLBuilder -> HTMLBuilder linkToRule lm = linkWith . urlForRule lm linkToTestReport :: LinkManager -> Exercise a -> HTMLBuilder -> HTMLBuilder linkToTestReport = linkWith . urlForTestReport --------------------------------------------------------------------- -- dynamic exercise information linkToRandomExample :: LinkManager -> Exercise a -> Difficulty -> HTMLBuilder -> HTMLBuilder linkToRandomExample lm = linkWith . urlForRandomExample lm --------------------------------------------------------------------- -- links to state information (dynamic) linkToState :: LinkManager -> State a -> HTMLBuilder -> HTMLBuilder linkToState = linkWith . urlForState linkToFirsts :: LinkManager -> State a -> HTMLBuilder -> HTMLBuilder linkToFirsts = linkWith . urlForFirsts linkToMicrosteps :: LinkManager -> State a -> HTMLBuilder -> HTMLBuilder linkToMicrosteps = linkWith . urlForMicrosteps linkToApplications :: LinkManager -> State a -> HTMLBuilder -> HTMLBuilder linkToApplications = linkWith . urlForApplications linkToDerivation :: LinkManager -> State a -> HTMLBuilder -> HTMLBuilder linkToDerivation = linkWith . urlForDerivation --------------------------------------------------------------------- -- Dynamic links makeLinkManager :: String -> String -> LinkManager makeLinkManager base cgiBinary = LinkManager { urlForRequest = prefix , urlForCSS = \s -> base ++ "css/" ++ s , urlForImage = \s -> base ++ "images/" ++ s , urlForIndex = url $ simpleRequest "index" , urlForExercises = url $ simpleRequest "exerciselist" , urlForServices = url $ simpleRequest "servicelist" , urlForService = url . makeRequest "serviceinfo" . tag "location" . text , urlForExercise = url . exerciseRequest "exerciseinfo" , urlForStrategy = url . exerciseRequest "strategyinfo" , urlForRules = url . exerciseRequest "rulelist" , urlForConstraints = url . exerciseRequest "constraintlist" , urlForTestReport = url . exerciseRequest "testreport" , urlForExamples = url . exerciseRequest "examples" , urlForDerivations = url . exerciseRequest "examplederivations" , urlForRule = \ex r -> url $ exerciseRequestWith "ruleinfo" ex $ tag "ruleid" $ text r , urlForRandomExample = \ex d -> url $ exerciseRequestWith "generate" ex $ "difficulty" .=. show d , urlForState = url . stateRequest "stateinfo" , urlForFirsts = url . stateRequest "allfirsts" , urlForApplications = url . stateRequest "allapplications" , urlForDerivation = url . stateRequest "derivation" , urlForMicrosteps = url . stateRequest "microsteps" } where prefix = cgiBinary ++ "?input=" url req = prefix ++ compactXML req simpleRequest :: String -> XML simpleRequest s = makeRequest s mempty makeRequest :: String -> XMLBuilder -> XML makeRequest s rest = makeXML "request" $ ("service" .=. s) <> ("encoding" .=. "html") <> rest exerciseRequest :: String -> Exercise a -> XML exerciseRequest s ex = makeRequest s ("exerciseid" .=. showId ex) exerciseRequestWith :: String -> Exercise a -> XMLBuilder -> XML exerciseRequestWith s ex rest = makeRequest s (("exerciseid" .=. showId ex) <> rest) stateRequest :: String -> State a -> XML stateRequest s state = exerciseRequestWith s (exercise state) (stateToXML state) -- assume nothing goest wrong stateToXML :: State a -> XMLBuilder stateToXML st = fromMaybe (error "LinkManager: Invalid state") $ runEncoder (encodeState st) (exercise st, optionHtml mempty) linkWith :: (a -> String) -> a -> HTMLBuilder -> HTMLBuilder linkWith f = link . escapeInURL . f escapeInURL :: String -> String escapeInURL = concatMap f where f '+' = "%2B" f '>' = "%3E" f '&' = "%26" f '%' = "%25" f '#' = "%23" f ';' = "%3B" f c = [c]
ideas-edu/ideas
src/Ideas/Encoding/LinkManager.hs
apache-2.0
8,101
0
14
1,700
1,765
962
803
135
7
module Subsets.A272082Spec (main, spec) where import Test.Hspec import Subsets.A272082 (a272082) main :: IO () main = hspec spec spec :: Spec spec = describe "A272082" $ it "correctly computes the first 20 elements" $ take 20 (map a272082 [0..]) `shouldBe` expectedValue where expectedValue = [1,6,3,2,6,3,2,1,12,6,4,2,12,6,4,2,1,15,10,3]
peterokagey/haskellOEIS
test/Subsets/A272082Spec.hs
apache-2.0
353
0
10
59
160
95
65
10
1
module Range where inclusive :: (Ord a, Num a) => a -> a -> a -> [a] inclusive s e 0 = [s, e] -- Avoid inifinite loops because of 0 increments inclusive s e ic = (takeWhile (< e) $ iterate (ic +) s) ++ [e] -- inclusive 0 1 0 = [0, 1] -- inclusive 0 1 0.5 = [0, 0.5, 1] -- etc
epeld/zatacka
old/Range.hs
apache-2.0
278
0
9
68
103
59
44
4
1
{-# LANGUAGE RecordWildCards #-} {-# OPTIONS -Wall #-} ---------------------------------------------------------------------- -- | -- Module : Data.ZoomCache.Write -- Copyright : Conrad Parker -- License : BSD3-style (see LICENSE) -- -- Maintainer : Conrad Parker <conrad@metadecks.org> -- Stability : unstable -- Portability : unknown -- -- Pretty-printing of zoom-cache types ---------------------------------------------------------------------- module Data.ZoomCache.Pretty ( prettyGlobal , prettyTrackSpec , prettyTimeStamp , prettySampleOffset , prettySummarySO ) where import qualified Data.ByteString.Char8 as C import Data.Ratio import Data.Time (UTCTime, formatTime) import System.Locale (defaultTimeLocale) import Text.Printf import Data.ZoomCache.Common import Data.ZoomCache.Types ---------------------------------------------------------------------- -- | Pretty-print a 'Global' prettyGlobal :: Global -> String prettyGlobal Global{..} = unlines [ "Version:\t\t" ++ show vMaj ++ "." ++ show vMin , "No. tracks:\t\t" ++ show noTracks , "UTC baseTime:\t\t" ++ maybe "undefined" showUTC baseUTC ] where Version vMaj vMin = version showUTC :: UTCTime -> String showUTC = formatTime defaultTimeLocale "%Y-%m-%d %T" -- | Pretty-print a 'TrackSpec' prettyTrackSpec :: TrackNo -> TrackSpec -> String prettyTrackSpec trackNo TrackSpec{..} = unlines [ "Track " ++ show trackNo ++ ":" , "\tName:\t" ++ C.unpack specName , "\tType:\t" ++ show specType , "\tEnc:\t" ++ unwords [encoding, compression] , "\tRate:\t" ++ show specSRType ++ " " ++ ratShow specRate ] where encoding | specDeltaEncode = "Delta" | otherwise = "Raw" compression | specZlibCompress = "Zlib" | otherwise = "Uncompressed" -- | Pretty-print a 'SampleOffset', given a datarate prettyTimeStamp :: TimeStamp -> String prettyTimeStamp (TS ts) = printf "%02d:%02d:%02d.%03d" hrs minN secN msN where secT, msN :: Integer secT = floor ts msN = round (1000 * (ts - fromIntegral secT)) (minT, secN) = quotRem secT 60 (hrs, minN) = quotRem minT 60 -- | Pretty-print a 'SampleOffset', given a datarate prettySampleOffset :: Rational -> SampleOffset -> String prettySampleOffset r (SO t) | d == 0 = "00:00:00.000" {- | d < 100 = printf "%02d:%02d:%02d::%02d" hrs minN secN framesN -} | otherwise = printf "%02d:%02d:%02d.%03d" hrs minN secN msN where d = denominator r n = numerator r msN = quot (1000 * framesN) n (secT, framesN) = quotRem (fromIntegral t*d) n (minT, secN) = quotRem secT 60 (hrs, minN) = quotRem minT 60 -- | Pretty-print a 'SummarySO', given a datarate prettySummarySO :: ZoomReadable a => Rational -> SummarySO a -> String prettySummarySO r s = concat [ prettySummarySOTimes r s , prettySummarySOLevel s , prettySummaryData (summarySOData s) ] prettySummarySOTimes :: Rational -> SummarySO a -> String prettySummarySOTimes r s = concat [ "[", (prettySampleOffset r $ summarySOEntry s) , "-", (prettySampleOffset r $ summarySOExit s), "] " ] prettySummarySOLevel :: SummarySO a -> String prettySummarySOLevel s = printf "lvl: %d" (summarySOLevel s) ---------------------------------------------------------------------- ratShow :: Rational -> String ratShow r | d == 0 = "0" | d == 1 = show n | otherwise = show n ++ "/" ++ show d where n = numerator r d = denominator r
kfish/zoom-cache
Data/ZoomCache/Pretty.hs
bsd-2-clause
3,645
0
12
858
862
452
410
69
1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} module SpecHelper ( locally , port , dns -- * Users , bulbasaur , ivysaur , venusaur , charmander , charmeleon , charizard , squirtle , wartortle , blastoise , caterpie , metapod , butterfree , pikachu , raichu , vulpix , oddish ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$)) #endif import Control.Monad (forever) import Control.Concurrent (forkIO) import Control.Exception (bracket) import System.Environment (getEnvironment) import System.IO (hGetLine) import System.IO.Error (tryIOError) import System.Process (runInteractiveProcess, terminateProcess, waitForProcess) import Ldap.Client as Ldap locally :: (Ldap -> IO a) -> IO (Either LdapError a) locally f = bracket (do env <- getEnvironment (_, out, _, h) <- runInteractiveProcess "./test/ldap.js" [] Nothing (Just (("PORT", show port) : ("SSL_CERT", "./ssl/cert.pem") : ("SSL_KEY", "./ssl/key.pem") : env)) hGetLine out forkIO (() <$ tryIOError (forever (hGetLine out >>= putStrLn))) return h) (\h -> do terminateProcess h waitForProcess h) (\_ -> Ldap.with localhost port f) localhost :: Host localhost = Insecure "localhost" port :: Num a => a port = 24620 dns :: [SearchEntry] -> [Dn] dns (SearchEntry dn _ : es) = dn : dns es dns [] = [] bulbasaur :: Dn bulbasaur = Dn "cn=bulbasaur,o=localhost" ivysaur :: Dn ivysaur = Dn "cn=ivysaur,o=localhost" venusaur :: Dn venusaur = Dn "cn=venusaur,o=localhost" charmander :: Dn charmander = Dn "cn=charmander,o=localhost" charmeleon :: Dn charmeleon = Dn "cn=charmeleon,o=localhost" charizard :: Dn charizard = Dn "cn=charizard,o=localhost" squirtle :: Dn squirtle = Dn "cn=squirtle,o=localhost" wartortle :: Dn wartortle = Dn "cn=wartortle,o=localhost" blastoise :: Dn blastoise = Dn "cn=blastoise,o=localhost" caterpie :: Dn caterpie = Dn "cn=caterpie,o=localhost" metapod :: Dn metapod = Dn "cn=metapod,o=localhost" butterfree :: Dn butterfree = Dn "cn=butterfree,o=localhost" pikachu :: Dn pikachu = Dn "cn=pikachu,o=localhost" raichu :: Dn raichu = Dn "cn=raichu,o=localhost" vulpix :: Dn vulpix = Dn "cn=vulpix,o=localhost" oddish :: Dn oddish = Dn "cn=oddish,o=localhost"
VictorDenisov/ldap-client
test/SpecHelper.hs
bsd-2-clause
2,483
0
18
622
666
368
298
84
1
{-# LANGUAGE TemplateHaskell #-} -- | A code generation template haskell. Everything is taken as literal text, -- with ~var~ variable interpolation. module Scaffolding.CodeGen (codegen, codegenDir) where import Language.Haskell.TH.Syntax import Text.ParserCombinators.Parsec import qualified Data.ByteString.Lazy as L import qualified Data.Text.Lazy as LT import qualified Data.Text.Lazy.Encoding as LT data Token = VarToken String | LitToken String | EmptyToken codegenDir :: FilePath -> FilePath -> Q Exp codegenDir dir fp = do s' <- qRunIO $ L.readFile $ (dir ++ "/" ++ fp ++ ".cg") let s = LT.unpack $ LT.decodeUtf8 s' case parse (many parseToken) s s of Left e -> error $ show e Right tokens' -> do let tokens'' = map toExp tokens' concat' <- [|concat|] return $ concat' `AppE` ListE tokens'' codegen :: FilePath -> Q Exp codegen fp = codegenDir "scaffold" fp toExp :: Token -> Exp toExp (LitToken s) = LitE $ StringL s toExp (VarToken s) = VarE $ mkName s toExp EmptyToken = LitE $ StringL "" parseToken :: Parser Token parseToken = parseVar <|> parseLit where parseVar = do _ <- char '~' s <- many alphaNum _ <- char '~' return $ if null s then EmptyToken else VarToken s parseLit = do s <- many1 $ noneOf "~" return $ LitToken s
chreekat/yesod
yesod/Scaffolding/CodeGen.hs
bsd-2-clause
1,369
0
15
342
433
223
210
35
2
{-# LANGUAGE FlexibleContexts #-} ----------------------------------------------------------- -- | -- Module : Database.HaskellDB.Connect.HDBC.Lifted -- Copyright : Kei Hibino 2012 -- License : BSD-style -- -- Maintainer : ex8k.hibino@gmail.com -- Stability : experimental -- Portability : portable -- -- Bracketed HaskellDB session with 'MonadBaseControl' 'IO'. -- ----------------------------------------------------------- module Database.HaskellDB.Connect.HDBC.Lifted ( hdbcSession ) where import Database.HDBC (IConnection) import Database.HaskellDB.Database (Database) import Database.HaskellDB.Sql.Generate (SqlGenerator) import Database.HaskellDB.Connect.HDBC (makeHDBCSession) import Control.Monad.Base (liftBase) import Control.Monad.Trans.Control (MonadBaseControl) import Control.Exception.Lifted (bracket) -- | Run an action on a HDBC IConnection and close the connection. -- 'MonadBaseControl' 'IO' version. hdbcSession :: (MonadBaseControl IO m, IConnection conn) => SqlGenerator -> IO conn -- ^ Connect action -> (conn -> Database -> m a) -- ^ Transaction body -> m a hdbcSession gen = makeHDBCSession bracket liftBase gen
khibino/haskelldb-connect-hdbc
lifted-base/src/Database/HaskellDB/Connect/HDBC/Lifted.hs
bsd-3-clause
1,229
5
9
215
177
114
63
16
1
module Data.Array.Accelerate.APL ( Array, Scalar, Vector, Elt, Shape, Z, (:.), Nat, empty, zilde, singleton, iota, size, each, shape, enlist, reshape, ) where import Prelude hiding (map) import Data.Array.Accelerate type Nat = Int -- nonnegative integers, for ranks, shapes and indexing; must be >= 0 empty :: Elt e => Acc (Vector e) empty = use $ fromList (Z:.(0::Nat)) [] zilde :: Z zilde = Z singleton :: Elt e => Exp e -> Acc (Vector e) singleton v = fill (index1 1) v iota :: Exp Nat -> Acc (Vector Nat) iota n = enumFromN (index1 n) (constant 1) each :: (Elt a, Elt b, Shape sh) => (Exp a -> Exp b) -> Acc (Array sh a) -> Acc (Array sh b) each = map -- Do we need this? -- rank :: Array sh e -> Exp Nat enlist :: (Elt e, Shape sh) => Acc (Array sh e) -> Acc (Vector e) enlist arr = reshape (index1 (size arr)) arr
henglein/apl
Data/Array/Accelerate/APL.hs
bsd-3-clause
857
0
10
200
384
208
176
20
1
{-# LANGUAGE LambdaCase, PatternGuards, ViewPatterns #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.Elab.Term where import Idris.AbsSyntax import Idris.AbsSyntaxTree import Idris.DSL import Idris.Delaborate import Idris.Error import Idris.ProofSearch import Idris.Output (pshow) import Idris.Core.CaseTree (SC, SC'(STerm), findCalls, findUsedArgs) import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.Unify import Idris.Core.ProofTerm (getProofTerm) import Idris.Core.Typecheck (check, recheck, converts, isType) import Idris.Core.WHNF (whnf) import Idris.Coverage (buildSCG, checkDeclTotality, genClauses, recoverableCoverage, validCoverageCase) import Idris.ErrReverse (errReverse) import Idris.ElabQuasiquote (extractUnquotes) import Idris.Elab.Utils import Idris.Reflection import qualified Util.Pretty as U import Control.Applicative ((<$>)) import Control.Monad import Control.Monad.State.Strict import Data.List import qualified Data.Map as M import Data.Maybe (mapMaybe, fromMaybe, catMaybes) import qualified Data.Set as S import qualified Data.Text as T import Debug.Trace data ElabMode = ETyDecl | ETransLHS | ELHS | ERHS deriving Eq data ElabResult = ElabResult { resultTerm :: Term -- ^ The term resulting from elaboration , resultMetavars :: [(Name, (Int, Maybe Name, Type, [Name]))] -- ^ Information about new metavariables , resultCaseDecls :: [PDecl] -- ^ Deferred declarations as the meaning of case blocks , resultContext :: Context -- ^ The potentially extended context from new definitions , resultTyDecls :: [RDeclInstructions] -- ^ Meta-info about the new type declarations , resultHighlighting :: [(FC, OutputAnnotation)] } -- Using the elaborator, convert a term in raw syntax to a fully -- elaborated, typechecked term. -- -- If building a pattern match, we convert undeclared variables from -- holes to pattern bindings. -- Also find deferred names in the term and their types build :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm -> ElabD ElabResult build ist info emode opts fn tm = do elab ist info emode opts fn tm let tmIn = tm let inf = case lookupCtxt fn (idris_tyinfodata ist) of [TIPartial] -> True _ -> False hs <- get_holes ivs <- get_instances ptm <- get_term -- Resolve remaining type classes. Two passes - first to get the -- default Num instances, second to clean up the rest when (not pattern) $ mapM_ (\n -> when (n `elem` hs) $ do focus n g <- goal try (resolveTC' True False 10 g fn ist) (movelast n)) ivs ivs <- get_instances hs <- get_holes when (not pattern) $ mapM_ (\n -> when (n `elem` hs) $ do focus n g <- goal ptm <- get_term resolveTC' True True 10 g fn ist) ivs when (not pattern) $ solveAutos ist fn False tm <- get_term ctxt <- get_context probs <- get_probs u <- getUnifyLog hs <- get_holes when (not pattern) $ traceWhen u ("Remaining holes:\n" ++ show hs ++ "\n" ++ "Remaining problems:\n" ++ qshow probs) $ do unify_all; matchProblems True; unifyProblems when (not pattern) $ solveAutos ist fn True probs <- get_probs case probs of [] -> return () ((_,_,_,_,e,_,_):es) -> traceWhen u ("Final problems:\n" ++ qshow probs ++ "\nin\n" ++ show tm) $ if inf then return () else lift (Error e) when tydecl (do mkPat update_term liftPats update_term orderPats) EState is _ impls highlights <- getAux tt <- get_term ctxt <- get_context let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) [] log <- getLog if log /= "" then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights) else return (ElabResult tm ds (map snd is) ctxt impls highlights) where pattern = emode == ELHS tydecl = emode == ETyDecl mkPat = do hs <- get_holes tm <- get_term case hs of (h: hs) -> do patvar h; mkPat [] -> return () -- Build a term autogenerated as a typeclass method definition -- (Separate, so we don't go overboard resolving things that we don't -- know about yet on the LHS of a pattern def) buildTC :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm -> ElabD ElabResult buildTC ist info emode opts fn tm = do -- set name supply to begin after highest index in tm let ns = allNamesIn tm let tmIn = tm let inf = case lookupCtxt fn (idris_tyinfodata ist) of [TIPartial] -> True _ -> False initNextNameFrom ns elab ist info emode opts fn tm probs <- get_probs tm <- get_term case probs of [] -> return () ((_,_,_,_,e,_,_):es) -> if inf then return () else lift (Error e) dots <- get_dotterm -- 'dots' are the PHidden things which have not been solved by -- unification when (not (null dots)) $ lift (Error (CantMatch (getInferTerm tm))) EState is _ impls highlights <- getAux tt <- get_term ctxt <- get_context let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) [] log <- getLog if (log /= "") then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights) else return (ElabResult tm ds (map snd is) ctxt impls highlights) where pattern = emode == ELHS -- return whether arguments of the given constructor name can be -- matched on. If they're polymorphic, no, unless the type has beed made -- concrete by the time we get around to elaborating the argument. getUnmatchable :: Context -> Name -> [Bool] getUnmatchable ctxt n | isDConName n ctxt && n /= inferCon = case lookupTyExact n ctxt of Nothing -> [] Just ty -> checkArgs [] [] ty where checkArgs :: [Name] -> [[Name]] -> Type -> [Bool] checkArgs env ns (Bind n (Pi _ t _) sc) = let env' = case t of TType _ -> n : env _ -> env in checkArgs env' (intersect env (refsIn t) : ns) (instantiate (P Bound n t) sc) checkArgs env ns t = map (not . null) (reverse ns) getUnmatchable ctxt n = [] data ElabCtxt = ElabCtxt { e_inarg :: Bool, e_isfn :: Bool, -- ^ Function part of application e_guarded :: Bool, e_intype :: Bool, e_qq :: Bool, e_nomatching :: Bool -- ^ can't pattern match } initElabCtxt = ElabCtxt False False False False False False goal_polymorphic :: ElabD Bool goal_polymorphic = do ty <- goal case ty of P _ n _ -> do env <- get_env case lookup n env of Nothing -> return False _ -> return True _ -> return False -- | Returns the set of declarations we need to add to complete the -- definition (most likely case blocks to elaborate) as well as -- declarations resulting from user tactic scripts (%runElab) elab :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm -> ElabD () elab ist info emode opts fn tm = do let loglvl = opt_logLevel (idris_options ist) when (loglvl > 5) $ unifyLog True compute -- expand type synonyms, etc let fc = maybe "(unknown)" elabE initElabCtxt (elabFC info) tm -- (in argument, guarded, in type, in qquote) est <- getAux sequence_ (get_delayed_elab est) end_unify ptm <- get_term when (pattern || intransform) -- convert remaining holes to pattern vars (do update_term orderPats unify_all matchProblems False -- only the ones we matched earlier unifyProblems mkPat) where pattern = emode == ELHS intransform = emode == ETransLHS bindfree = emode == ETyDecl || emode == ELHS || emode == ETransLHS get_delayed_elab est = let ds = delayed_elab est in map snd $ sortBy (\(p1, _) (p2, _) -> compare p1 p2) ds tcgen = Dictionary `elem` opts reflection = Reflection `elem` opts isph arg = case getTm arg of Placeholder -> (True, priority arg) tm -> (False, priority arg) toElab ina arg = case getTm arg of Placeholder -> Nothing v -> Just (priority arg, elabE ina (elabFC info) v) toElab' ina arg = case getTm arg of Placeholder -> Nothing v -> Just (elabE ina (elabFC info) v) mkPat = do hs <- get_holes tm <- get_term case hs of (h: hs) -> do patvar h; mkPat [] -> return () -- | elabE elaborates an expression, possibly wrapping implicit coercions -- and forces/delays. If you make a recursive call in elab', it is -- normally correct to call elabE - the ones that don't are desugarings -- typically elabE :: ElabCtxt -> Maybe FC -> PTerm -> ElabD () elabE ina fc' t = do solved <- get_recents as <- get_autos hs <- get_holes -- If any of the autos use variables which have recently been solved, -- have another go at solving them now. mapM_ (\(a, (failc, ns)) -> if any (\n -> n `elem` solved) ns && head hs /= a then solveAuto ist fn False (a, failc) else return ()) as itm <- if not pattern then insertImpLam ina t else return t ct <- insertCoerce ina itm t' <- insertLazy ct g <- goal tm <- get_term ps <- get_probs hs <- get_holes --trace ("Elaborating " ++ show t' ++ " in " ++ show g -- ++ "\n" ++ show tm -- ++ "\nholes " ++ show hs -- ++ "\nproblems " ++ show ps -- ++ "\n-----------\n") $ --trace ("ELAB " ++ show t') $ let fc = fileFC "Force" env <- get_env handleError (forceErr t' env) (elab' ina fc' t') (elab' ina fc' (PApp fc (PRef fc [] (sUN "Force")) [pimp (sUN "t") Placeholder True, pimp (sUN "a") Placeholder True, pexp ct])) forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _) | (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t), ht == txt "Lazy'" = notDelay orig forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _) | (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t'), ht == txt "Lazy'" = notDelay orig forceErr orig env (InfiniteUnify _ t _) | (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t), ht == txt "Lazy'" = notDelay orig forceErr orig env (Elaborating _ _ t) = forceErr orig env t forceErr orig env (ElaboratingArg _ _ _ t) = forceErr orig env t forceErr orig env (At _ t) = forceErr orig env t forceErr orig env t = False notDelay t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = False notDelay _ = True local f = do e <- get_env return (f `elem` map fst e) -- | Is a constant a type? constType :: Const -> Bool constType (AType _) = True constType StrType = True constType VoidType = True constType _ = False -- "guarded" means immediately under a constructor, to help find patvars elab' :: ElabCtxt -- ^ (in an argument, guarded, in a type, in a quasiquote) -> Maybe FC -- ^ The closest FC in the syntax tree, if applicable -> PTerm -- ^ The term to elaborate -> ElabD () elab' ina fc (PNoImplicits t) = elab' ina fc t -- skip elabE step elab' ina fc (PType fc') = do apply RType [] solve highlightSource fc' (AnnType "Type" "The type of types") elab' ina fc (PUniverse u) = do apply (RUType u) []; solve -- elab' (_,_,inty) (PConstant c) -- | constType c && pattern && not reflection && not inty -- = lift $ tfail (Msg "Typecase is not allowed") elab' ina fc tm@(PConstant fc' c) | pattern && not reflection && not (e_qq ina) && not (e_intype ina) && isTypeConst c = lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm) | pattern && not reflection && not (e_qq ina) && e_nomatching ina = lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm) | otherwise = do apply (RConstant c) [] solve highlightSource fc' (AnnConst c) elab' ina fc (PQuote r) = do fill r; solve elab' ina _ (PTrue fc _) = do hnf_compute g <- goal case g of TType _ -> elab' ina (Just fc) (PRef fc [] unitTy) UType _ -> elab' ina (Just fc) (PRef fc [] unitTy) _ -> elab' ina (Just fc) (PRef fc [] unitCon) elab' ina fc (PResolveTC (FC "HACK" _ _)) -- for chasing parent classes = do g <- goal; resolveTC' False False 5 g fn ist elab' ina fc (PResolveTC fc') = do c <- getNameFrom (sMN 0 "class") instanceArg c -- Elaborate the equality type first homogeneously, then -- heterogeneously as a fallback elab' ina _ (PApp fc (PRef _ _ n) args) | n == eqTy, [Placeholder, Placeholder, l, r] <- map getTm args = try (do tyn <- getNameFrom (sMN 0 "aqty") claim tyn RType movelast tyn elab' ina (Just fc) (PApp fc (PRef fc [] eqTy) [pimp (sUN "A") (PRef NoFC [] tyn) True, pimp (sUN "B") (PRef NoFC [] tyn) False, pexp l, pexp r])) (do atyn <- getNameFrom (sMN 0 "aqty") btyn <- getNameFrom (sMN 0 "bqty") claim atyn RType movelast atyn claim btyn RType movelast btyn elab' ina (Just fc) (PApp fc (PRef fc [] eqTy) [pimp (sUN "A") (PRef NoFC [] atyn) True, pimp (sUN "B") (PRef NoFC [] btyn) False, pexp l, pexp r])) elab' ina _ (PPair fc hls _ l r) = do hnf_compute g <- goal let (tc, _) = unApply g case g of TType _ -> elab' ina (Just fc) (PApp fc (PRef fc hls pairTy) [pexp l,pexp r]) UType _ -> elab' ina (Just fc) (PApp fc (PRef fc hls upairTy) [pexp l,pexp r]) _ -> case tc of P _ n _ | n == upairTy -> elab' ina (Just fc) (PApp fc (PRef fc hls upairCon) [pimp (sUN "A") Placeholder False, pimp (sUN "B") Placeholder False, pexp l, pexp r]) _ -> elab' ina (Just fc) (PApp fc (PRef fc hls pairCon) [pimp (sUN "A") Placeholder False, pimp (sUN "B") Placeholder False, pexp l, pexp r]) -- _ -> try' (elab' ina (Just fc) (PApp fc (PRef fc pairCon) -- [pimp (sUN "A") Placeholder False, -- pimp (sUN "B") Placeholder False, -- pexp l, pexp r])) -- (elab' ina (Just fc) (PApp fc (PRef fc upairCon) -- [pimp (sUN "A") Placeholder False, -- pimp (sUN "B") Placeholder False, -- pexp l, pexp r])) -- True elab' ina _ (PDPair fc hls p l@(PRef nfc hl n) t r) = case t of Placeholder -> do hnf_compute g <- goal case g of TType _ -> asType _ -> asValue _ -> asType where asType = elab' ina (Just fc) (PApp fc (PRef NoFC hls sigmaTy) [pexp t, pexp (PLam fc n nfc Placeholder r)]) asValue = elab' ina (Just fc) (PApp fc (PRef fc hls sigmaCon) [pimp (sMN 0 "a") t False, pimp (sMN 0 "P") Placeholder True, pexp l, pexp r]) elab' ina _ (PDPair fc hls p l t r) = elab' ina (Just fc) (PApp fc (PRef fc hls sigmaCon) [pimp (sMN 0 "a") t False, pimp (sMN 0 "P") Placeholder True, pexp l, pexp r]) elab' ina fc (PAlternative ms (ExactlyOne delayok) as) = do as_pruned <- doPrune as -- Finish the mkUniqueNames job with the pruned set, rather than -- the full set. uns <- get_usedns let as' = map (mkUniqueNames (uns ++ map snd ms) ms) as_pruned (h : hs) <- get_holes -- trace (show (map showHd as')) $ ty <- goal case as' of [] -> lift $ tfail $ NoValidAlts (map showHd as) [x] -> elab' ina fc x -- If there's options, try now, and if that fails, postpone -- to later. _ -> handleError isAmbiguous (tryAll (zip (map (elab' ina fc) as') (map showHd as'))) (do movelast h delayElab 5 $ do hs <- get_holes when (h `elem` hs) $ do focus h as'' <- doPrune as' case as'' of [x] -> elab' ina fc x _ -> tryAll (zip (map (elab' ina fc) as'') (map showHd as''))) where showHd (PApp _ (PRef _ _ (UN l)) [_, _, arg]) | l == txt "Delay" = showHd (getTm arg) showHd (PApp _ (PRef _ _ n) _) = n showHd (PRef _ _ n) = n showHd (PApp _ h _) = showHd h showHd x = NErased -- We probably should do something better than this here doPrune as = do compute ty <- goal let (tc, _) = unApply (unDelay ty) env <- get_env return $ pruneByType env tc ist as unDelay t | (P _ (UN l) _, [_, arg]) <- unApply t, l == txt "Lazy'" = unDelay arg | otherwise = t isAmbiguous (CantResolveAlts _) = delayok isAmbiguous (Elaborating _ _ e) = isAmbiguous e isAmbiguous (ElaboratingArg _ _ _ e) = isAmbiguous e isAmbiguous (At _ e) = isAmbiguous e isAmbiguous _ = False elab' ina fc (PAlternative ms FirstSuccess as_in) = do -- finish the mkUniqueNames job uns <- get_usedns let as = map (mkUniqueNames (uns ++ map snd ms) ms) as_in trySeq as where -- if none work, take the error from the first trySeq (x : xs) = let e1 = elab' ina fc x in try' e1 (trySeq' e1 xs) True trySeq [] = fail "Nothing to try in sequence" trySeq' deferr [] = proofFail deferr trySeq' deferr (x : xs) = try' (do elab' ina fc x solveAutos ist fn False) (trySeq' deferr xs) True elab' ina fc (PAlternative ms TryImplicit (orig : alts)) = do env <- get_env compute ty <- goal let doelab = elab' ina fc orig tryCatch doelab (\err -> if recoverableErr err then -- trace ("NEED IMPLICIT! " ++ show orig ++ "\n" ++ -- show alts ++ "\n" ++ -- showQuick err) $ -- Prune the coercions so that only the ones -- with the right type to fix the error will be tried! case pruneAlts err alts env of [] -> lift $ tfail err alts' -> do try' (elab' ina fc (PAlternative ms (ExactlyOne False) alts')) (lift $ tfail err) -- take error from original if all fail True else lift $ tfail err) where recoverableErr (CantUnify _ _ _ _ _ _) = True recoverableErr (TooManyArguments _) = False recoverableErr (CantSolveGoal _ _) = False recoverableErr (CantResolveAlts _) = False recoverableErr (NoValidAlts _) = True recoverableErr (ProofSearchFail (Msg _)) = True recoverableErr (ProofSearchFail _) = False recoverableErr (ElaboratingArg _ _ _ e) = recoverableErr e recoverableErr (At _ e) = recoverableErr e recoverableErr (ElabScriptDebug _ _ _) = False recoverableErr _ = True pruneAlts (CantUnify _ (inc, _) (outc, _) _ _ _) alts env = case unApply (normalise (tt_ctxt ist) env inc) of (P (TCon _ _) n _, _) -> filter (hasArg n env) alts (Constant _, _) -> alts _ -> filter isLend alts -- special case hack for 'Borrowed' pruneAlts (ElaboratingArg _ _ _ e) alts env = pruneAlts e alts env pruneAlts (At _ e) alts env = pruneAlts e alts env pruneAlts (NoValidAlts as) alts env = alts pruneAlts err alts _ = filter isLend alts hasArg n env ap | isLend ap = True -- special case hack for 'Borrowed' hasArg n env (PApp _ (PRef _ _ a) _) = case lookupTyExact a (tt_ctxt ist) of Just ty -> let args = map snd (getArgTys (normalise (tt_ctxt ist) env ty)) in any (fnIs n) args Nothing -> False hasArg n env (PAlternative _ _ as) = any (hasArg n env) as hasArg n _ tm = False isLend (PApp _ (PRef _ _ l) _) = l == sNS (sUN "lend") ["Ownership"] isLend _ = False fnIs n ty = case unApply ty of (P _ n' _, _) -> n == n' _ -> False showQuick (CantUnify _ (l, _) (r, _) _ _ _) = show (l, r) showQuick (ElaboratingArg _ _ _ e) = showQuick e showQuick (At _ e) = showQuick e showQuick (ProofSearchFail (Msg _)) = "search fail" showQuick _ = "No chance" elab' ina _ (PPatvar fc n) | bindfree = do patvar n update_term liftPats highlightSource fc (AnnBoundName n False) -- elab' (_, _, inty) (PRef fc f) -- | isTConName f (tt_ctxt ist) && pattern && not reflection && not inty -- = lift $ tfail (Msg "Typecase is not allowed") elab' ec _ tm@(PRef fc hl n) | pattern && not reflection && not (e_qq ec) && not (e_intype ec) && isTConName n (tt_ctxt ist) = lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm) | pattern && not reflection && not (e_qq ec) && e_nomatching ec = lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm) | (pattern || intransform || (bindfree && bindable n)) && not (inparamBlock n) && not (e_qq ec) = do let ina = e_inarg ec guarded = e_guarded ec inty = e_intype ec ctxt <- get_context let defined = case lookupTy n ctxt of [] -> False _ -> True -- this is to stop us resolve type classes recursively -- trace (show (n, guarded)) $ if (tcname n && ina && not intransform) then erun fc $ do patvar n update_term liftPats highlightSource fc (AnnBoundName n False) else if (defined && not guarded) then do apply (Var n) [] annot <- findHighlight n solve highlightSource fc annot else try (do apply (Var n) [] annot <- findHighlight n solve highlightSource fc annot) (do patvar n update_term liftPats highlightSource fc (AnnBoundName n False)) where inparamBlock n = case lookupCtxtName n (inblock info) of [] -> False _ -> True bindable (NS _ _) = False bindable (UN xs) = True bindable n = implicitable n elab' ina _ f@(PInferRef fc hls n) = elab' ina (Just fc) (PApp NoFC f []) elab' ina fc' tm@(PRef fc hls n) | pattern && not reflection && not (e_qq ina) && not (e_intype ina) && isTConName n (tt_ctxt ist) = lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm) | pattern && not reflection && not (e_qq ina) && e_nomatching ina = lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm) | otherwise = do fty <- get_type (Var n) -- check for implicits ctxt <- get_context env <- get_env let a' = insertScopedImps fc (normalise ctxt env fty) [] if null a' then erun fc $ do apply (Var n) [] hilite <- findHighlight n solve mapM_ (uncurry highlightSource) $ (fc, hilite) : map (\f -> (f, hilite)) hls else elab' ina fc' (PApp fc tm []) elab' ina _ (PLam _ _ _ _ PImpossible) = lift . tfail . Msg $ "Only pattern-matching lambdas can be impossible" elab' ina _ (PLam fc n nfc Placeholder sc) = do -- if n is a type constructor name, this makes no sense... ctxt <- get_context when (isTConName n ctxt) $ lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here") checkPiGoal n attack; intro (Just n); addPSname n -- okay for proof search -- trace ("------ intro " ++ show n ++ " ---- \n" ++ show ptm) elabE (ina { e_inarg = True } ) (Just fc) sc; solve highlightSource nfc (AnnBoundName n False) elab' ec _ (PLam fc n nfc ty sc) = do tyn <- getNameFrom (sMN 0 "lamty") -- if n is a type constructor name, this makes no sense... ctxt <- get_context when (isTConName n ctxt) $ lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here") checkPiGoal n claim tyn RType explicit tyn attack ptm <- get_term hs <- get_holes introTy (Var tyn) (Just n) addPSname n -- okay for proof search focus tyn elabE (ec { e_inarg = True, e_intype = True }) (Just fc) ty elabE (ec { e_inarg = True }) (Just fc) sc solve highlightSource nfc (AnnBoundName n False) elab' ina fc (PPi p n nfc Placeholder sc) = do attack; arg n (is_scoped p) (sMN 0 "ty") addPSname n -- okay for proof search elabE (ina { e_inarg = True, e_intype = True }) fc sc solve highlightSource nfc (AnnBoundName n False) elab' ina fc (PPi p n nfc ty sc) = do attack; tyn <- getNameFrom (sMN 0 "ty") claim tyn RType n' <- case n of MN _ _ -> unique_hole n _ -> return n forall n' (is_scoped p) (Var tyn) addPSname n' -- okay for proof search focus tyn let ec' = ina { e_inarg = True, e_intype = True } elabE ec' fc ty elabE ec' fc sc solve highlightSource nfc (AnnBoundName n False) elab' ina _ tm@(PLet fc n nfc ty val sc) = do attack ivs <- get_instances tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) explicit valn letbind n (Var tyn) (Var valn) addPSname n case ty of Placeholder -> return () _ -> do focus tyn explicit tyn elabE (ina { e_inarg = True, e_intype = True }) (Just fc) ty focus valn elabE (ina { e_inarg = True, e_intype = True }) (Just fc) val ivs' <- get_instances env <- get_env elabE (ina { e_inarg = True }) (Just fc) sc when (not (pattern || intransform)) $ mapM_ (\n -> do focus n g <- goal hs <- get_holes if all (\n -> n == tyn || not (n `elem` hs)) (freeNames g) then try (resolveTC' True False 10 g fn ist) (movelast n) else movelast n) (ivs' \\ ivs) -- HACK: If the name leaks into its type, it may leak out of -- scope outside, so substitute in the outer scope. expandLet n (case lookup n env of Just (Let t v) -> v other -> error ("Value not a let binding: " ++ show other)) solve highlightSource nfc (AnnBoundName n False) elab' ina _ (PGoal fc r n sc) = do rty <- goal attack tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letbind n (Var tyn) (Var valn) focus valn elabE (ina { e_inarg = True, e_intype = True }) (Just fc) (PApp fc r [pexp (delab ist rty)]) env <- get_env computeLet n elabE (ina { e_inarg = True }) (Just fc) sc solve -- elab' ina fc (PLet n Placeholder -- (PApp fc r [pexp (delab ist rty)]) sc) elab' ina _ tm@(PApp fc (PInferRef _ _ f) args) = do rty <- goal ds <- get_deferred ctxt <- get_context -- make a function type a -> b -> c -> ... -> rty for the -- new function name env <- get_env argTys <- claimArgTys env args fn <- getNameFrom (sMN 0 "inf_fn") let fty = fnTy argTys rty -- trace (show (ptm, map fst argTys)) $ focus fn -- build and defer the function application attack; deferType (mkN f) fty (map fst argTys); solve -- elaborate the arguments, to unify their types. They all have to -- be explicit. mapM_ elabIArg (zip argTys args) where claimArgTys env [] = return [] claimArgTys env (arg : xs) | Just n <- localVar env (getTm arg) = do nty <- get_type (Var n) ans <- claimArgTys env xs return ((n, (False, forget nty)) : ans) claimArgTys env (_ : xs) = do an <- getNameFrom (sMN 0 "inf_argTy") aval <- getNameFrom (sMN 0 "inf_arg") claim an RType claim aval (Var an) ans <- claimArgTys env xs return ((aval, (True, (Var an))) : ans) fnTy [] ret = forget ret fnTy ((x, (_, xt)) : xs) ret = RBind x (Pi Nothing xt RType) (fnTy xs ret) localVar env (PRef _ _ x) = case lookup x env of Just _ -> Just x _ -> Nothing localVar env _ = Nothing elabIArg ((n, (True, ty)), def) = do focus n; elabE ina (Just fc) (getTm def) elabIArg _ = return () -- already done, just a name mkN n@(NS _ _) = n mkN n@(SN _) = n mkN n = case namespace info of Just xs@(_:_) -> sNS n xs _ -> n elab' ina _ (PMatchApp fc fn) = do (fn', imps) <- case lookupCtxtName fn (idris_implicits ist) of [(n, args)] -> return (n, map (const True) args) _ -> lift $ tfail (NoSuchVariable fn) ns <- match_apply (Var fn') (map (\x -> (x,0)) imps) solve -- if f is local, just do a simple_app -- FIXME: Anyone feel like refactoring this mess? - EB elab' ina topfc tm@(PApp fc (PRef ffc hls f) args_in) | pattern && not reflection && not (e_qq ina) && e_nomatching ina = lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm) | otherwise = implicitApp $ do env <- get_env ty <- goal fty <- get_type (Var f) ctxt <- get_context annot <- findHighlight f mapM_ checkKnownImplicit args_in let args = insertScopedImps fc (normalise ctxt env fty) args_in let unmatchableArgs = if pattern then getUnmatchable (tt_ctxt ist) f else [] -- trace ("BEFORE " ++ show f ++ ": " ++ show ty) $ when (pattern && not reflection && not (e_qq ina) && not (e_intype ina) && isTConName f (tt_ctxt ist)) $ lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm) -- trace (show (f, args_in, args)) $ if (f `elem` map fst env && length args == 1 && length args_in == 1) then -- simple app, as below do simple_app False (elabE (ina { e_isfn = True }) (Just fc) (PRef ffc hls f)) (elabE (ina { e_inarg = True }) (Just fc) (getTm (head args))) (show tm) solve mapM (uncurry highlightSource) $ (ffc, annot) : map (\f -> (f, annot)) hls return [] else do ivs <- get_instances ps <- get_probs -- HACK: we shouldn't resolve type classes if we're defining an instance -- function or default definition. let isinf = f == inferCon || tcname f -- if f is a type class, we need to know its arguments so that -- we can unify with them case lookupCtxt f (idris_classes ist) of [] -> return () _ -> do mapM_ setInjective (map getTm args) -- maybe more things are solvable now unifyProblems let guarded = isConName f ctxt -- trace ("args is " ++ show args) $ return () ns <- apply (Var f) (map isph args) -- trace ("ns is " ++ show ns) $ return () -- mark any type class arguments as injective when (not pattern) $ mapM_ checkIfInjective (map snd ns) unifyProblems -- try again with the new information, -- to help with disambiguation ulog <- getUnifyLog annot <- findHighlight f mapM (uncurry highlightSource) $ (ffc, annot) : map (\f -> (f, annot)) hls elabArgs ist (ina { e_inarg = e_inarg ina || not isinf }) [] fc False f (zip ns (unmatchableArgs ++ repeat False)) (f == sUN "Force") (map (\x -> getTm x) args) -- TODO: remove this False arg imp <- if (e_isfn ina) then do guess <- get_guess env <- get_env case safeForgetEnv (map fst env) guess of Nothing -> return [] Just rguess -> do gty <- get_type rguess let ty_n = normalise ctxt env gty return $ getReqImps ty_n else return [] -- Now we find out how many implicits we needed at the -- end of the application by looking at the goal again -- - Have another go, but this time add the -- implicits (can't think of a better way than this...) case imp of rs@(_:_) | not pattern -> return rs -- quit, try again _ -> do solve hs <- get_holes ivs' <- get_instances -- Attempt to resolve any type classes which have 'complete' types, -- i.e. no holes in them when (not pattern || (e_inarg ina && not tcgen && not (e_guarded ina))) $ mapM_ (\n -> do focus n g <- goal env <- get_env hs <- get_holes if all (\n -> not (n `elem` hs)) (freeNames g) then try (resolveTC' False False 10 g fn ist) (movelast n) else movelast n) (ivs' \\ ivs) return [] where -- Run the elaborator, which returns how many implicit -- args were needed, then run it again with those args. We need -- this because we have to elaborate the whole application to -- find out whether any computations have caused more implicits -- to be needed. implicitApp :: ElabD [ImplicitInfo] -> ElabD () implicitApp elab | pattern || intransform = do elab; return () | otherwise = do s <- get imps <- elab case imps of [] -> return () es -> do put s elab' ina topfc (PAppImpl tm es) checkKnownImplicit imp | UnknownImp `elem` argopts imp = lift $ tfail $ UnknownImplicit (pname imp) f checkKnownImplicit _ = return () getReqImps (Bind x (Pi (Just i) ty _) sc) = i : getReqImps sc getReqImps _ = [] checkIfInjective n = do env <- get_env case lookup n env of Nothing -> return () Just b -> case unApply (normalise (tt_ctxt ist) env (binderTy b)) of (P _ c _, args) -> case lookupCtxtExact c (idris_classes ist) of Nothing -> return () Just ci -> -- type class, set as injective do mapM_ setinjArg (getDets 0 (class_determiners ci) args) -- maybe we can solve more things now... ulog <- getUnifyLog probs <- get_probs traceWhen ulog ("Injective now " ++ show args ++ "\n" ++ qshow probs) $ unifyProblems probs <- get_probs traceWhen ulog (qshow probs) $ return () _ -> return () setinjArg (P _ n _) = setinj n setinjArg _ = return () getDets i ds [] = [] getDets i ds (a : as) | i `elem` ds = a : getDets (i + 1) ds as | otherwise = getDets (i + 1) ds as tacTm (PTactics _) = True tacTm (PProof _) = True tacTm _ = False setInjective (PRef _ _ n) = setinj n setInjective (PApp _ (PRef _ _ n) _) = setinj n setInjective _ = return () elab' ina _ tm@(PApp fc f [arg]) = erun fc $ do simple_app (not $ headRef f) (elabE (ina { e_isfn = True }) (Just fc) f) (elabE (ina { e_inarg = True }) (Just fc) (getTm arg)) (show tm) solve where headRef (PRef _ _ _) = True headRef (PApp _ f _) = headRef f headRef (PAlternative _ _ as) = all headRef as headRef _ = False elab' ina fc (PAppImpl f es) = do appImpl (reverse es) -- not that we look... solve where appImpl [] = elab' (ina { e_isfn = False }) fc f -- e_isfn not set, so no recursive expansion of implicits appImpl (e : es) = simple_app False (appImpl es) (elab' ina fc Placeholder) (show f) elab' ina fc Placeholder = do (h : hs) <- get_holes movelast h elab' ina fc (PMetavar nfc n) = do ptm <- get_term -- When building the metavar application, leave out the unique -- names which have been used elsewhere in the term, since we -- won't be able to use them in the resulting application. let unique_used = getUniqueUsed (tt_ctxt ist) ptm let n' = metavarName (namespace info) n attack psns <- getPSnames defer unique_used n' solve highlightSource nfc (AnnName n' (Just MetavarOutput) Nothing Nothing) elab' ina fc (PProof ts) = do compute; mapM_ (runTac True ist (elabFC info) fn) ts elab' ina fc (PTactics ts) | not pattern = do mapM_ (runTac False ist fc fn) ts | otherwise = elab' ina fc Placeholder elab' ina fc (PElabError e) = lift $ tfail e elab' ina _ (PRewrite fc r sc newg) = do attack tyn <- getNameFrom (sMN 0 "rty") claim tyn RType valn <- getNameFrom (sMN 0 "rval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "_rewrite_rule") letbind letn (Var tyn) (Var valn) focus valn elab' ina (Just fc) r compute g <- goal rewrite (Var letn) g' <- goal when (g == g') $ lift $ tfail (NoRewriting g) case newg of Nothing -> elab' ina (Just fc) sc Just t -> doEquiv t sc solve where doEquiv t sc = do attack tyn <- getNameFrom (sMN 0 "ety") claim tyn RType valn <- getNameFrom (sMN 0 "eqval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "equiv_val") letbind letn (Var tyn) (Var valn) focus tyn elab' ina (Just fc) t focus valn elab' ina (Just fc) sc elab' ina (Just fc) (PRef fc [] letn) solve elab' ina _ c@(PCase fc scr opts) = do attack tyn <- getNameFrom (sMN 0 "scty") claim tyn RType valn <- getNameFrom (sMN 0 "scval") scvn <- getNameFrom (sMN 0 "scvar") claim valn (Var tyn) letbind scvn (Var tyn) (Var valn) focus valn elabE (ina { e_inarg = True }) (Just fc) scr -- Solve any remaining implicits - we need to solve as many -- as possible before making the 'case' type unifyProblems matchProblems True args <- get_env envU <- mapM (getKind args) args let namesUsedInRHS = nub $ scvn : concatMap (\(_,rhs) -> allNamesIn rhs) opts -- Drop the unique arguments used in the term already -- and in the scrutinee (since it's -- not valid to use them again anyway) -- -- Also drop unique arguments which don't appear explicitly -- in either case branch so they don't count as used -- unnecessarily (can only do this for unique things, since we -- assume they don't appear implicitly in types) ptm <- get_term let inOpts = (filter (/= scvn) (map fst args)) \\ (concatMap (\x -> allNamesIn (snd x)) opts) let argsDropped = filter (isUnique envU) (nub $ allNamesIn scr ++ inApp ptm ++ inOpts) let args' = filter (\(n, _) -> n `notElem` argsDropped) args cname <- unique_hole' True (mkCaseName fn) let cname' = mkN cname -- elab' ina fc (PMetavar cname') attack; defer argsDropped cname'; solve -- if the scrutinee is one of the 'args' in env, we should -- inspect it directly, rather than adding it as a new argument let newdef = PClauses fc [] cname' (caseBlock fc cname' scr (map (isScr scr) (reverse args')) opts) -- elaborate case updateAux (\e -> e { case_decls = (cname', newdef) : case_decls e } ) -- if we haven't got the type yet, hopefully we'll get it later! movelast tyn solve where mkCaseName (NS n ns) = NS (mkCaseName n) ns mkCaseName n = SN (CaseN n) -- mkCaseName (UN x) = UN (x ++ "_case") -- mkCaseName (MN i x) = MN i (x ++ "_case") mkN n@(NS _ _) = n mkN n = case namespace info of Just xs@(_:_) -> sNS n xs _ -> n inApp (P _ n _) = [n] inApp (App _ f a) = inApp f ++ inApp a inApp (Bind n (Let _ v) sc) = inApp v ++ inApp sc inApp (Bind n (Guess _ v) sc) = inApp v ++ inApp sc inApp (Bind n b sc) = inApp sc inApp _ = [] isUnique envk n = case lookup n envk of Just u -> u _ -> False getKind env (n, _) = case lookup n env of Nothing -> return (n, False) -- can't happen, actually... Just b -> do ty <- get_type (forget (binderTy b)) case ty of UType UniqueType -> return (n, True) UType AllTypes -> return (n, True) _ -> return (n, False) tcName tm | (P _ n _, _) <- unApply tm = case lookupCtxt n (idris_classes ist) of [_] -> True _ -> False tcName _ = False usedIn ns (n, b) = n `elem` ns || any (\x -> x `elem` ns) (allTTNames (binderTy b)) elab' ina fc (PUnifyLog t) = do unifyLog True elab' ina fc t unifyLog False elab' ina fc (PQuasiquote t goalt) = do -- First extract the unquoted subterms, replacing them with fresh -- names in the quasiquoted term. Claim their reflections to be -- an inferred type (to support polytypic quasiquotes). finalTy <- goal (t, unq) <- extractUnquotes 0 t let unquoteNames = map fst unq mapM_ (\uqn -> claim uqn (forget finalTy)) unquoteNames -- Save the old state - we need a fresh proof state to avoid -- capturing lexically available variables in the quoted term. ctxt <- get_context datatypes <- get_datatypes saveState updatePS (const . newProof (sMN 0 "q") ctxt datatypes $ P Ref (reflm "TT") Erased) -- Re-add the unquotes, letting Idris infer the (fictional) -- types. Here, they represent the real type rather than the type -- of their reflection. mapM_ (\n -> do ty <- getNameFrom (sMN 0 "unqTy") claim ty RType movelast ty claim n (Var ty) movelast n) unquoteNames -- Determine whether there's an explicit goal type, and act accordingly -- Establish holes for the type and value of the term to be -- quasiquoted qTy <- getNameFrom (sMN 0 "qquoteTy") claim qTy RType movelast qTy qTm <- getNameFrom (sMN 0 "qquoteTm") claim qTm (Var qTy) -- Let-bind the result of elaborating the contained term, so that -- the hole doesn't disappear nTm <- getNameFrom (sMN 0 "quotedTerm") letbind nTm (Var qTy) (Var qTm) -- Fill out the goal type, if relevant case goalt of Nothing -> return () Just gTy -> do focus qTy elabE (ina { e_qq = True }) fc gTy -- Elaborate the quasiquoted term into the hole focus qTm elabE (ina { e_qq = True }) fc t end_unify -- We now have an elaborated term. Reflect it and solve the -- original goal in the original proof state, preserving highlighting env <- get_env EState _ _ _ hs <- getAux loadState updateAux (\aux -> aux { highlighting = hs }) let quoted = fmap (explicitNames . binderVal) $ lookup nTm env isRaw = case unApply (normaliseAll ctxt env finalTy) of (P _ n _, []) | n == reflm "Raw" -> True _ -> False case quoted of Just q -> do ctxt <- get_context (q', _, _) <- lift $ recheck ctxt [(uq, Lam Erased) | uq <- unquoteNames] (forget q) q if pattern then if isRaw then reflectRawQuotePattern unquoteNames (forget q') else reflectTTQuotePattern unquoteNames q' else do if isRaw then -- we forget q' instead of using q to ensure rechecking fill $ reflectRawQuote unquoteNames (forget q') else fill $ reflectTTQuote unquoteNames q' solve Nothing -> lift . tfail . Msg $ "Broken elaboration of quasiquote" -- Finally fill in the terms or patterns from the unquotes. This -- happens last so that their holes still exist while elaborating -- the main quotation. mapM_ elabUnquote unq where elabUnquote (n, tm) = do focus n elabE (ina { e_qq = False }) fc tm elab' ina fc (PUnquote t) = fail "Found unquote outside of quasiquote" elab' ina fc (PQuoteName n nfc) = do ctxt <- get_context env <- get_env case lookup n env of Just _ -> do fill $ reflectName n solve highlightSource nfc (AnnBoundName n False) Nothing -> case lookupNameDef n ctxt of [(n', _)] -> do fill $ reflectName n' solve highlightSource nfc (AnnName n' Nothing Nothing Nothing) [] -> lift . tfail . NoSuchVariable $ n more -> lift . tfail . CantResolveAlts $ map fst more elab' ina fc (PAs _ n t) = lift . tfail . Msg $ "@-pattern not allowed here" elab' ina fc (PHidden t) | reflection = elab' ina fc t | otherwise = do (h : hs) <- get_holes -- Dotting a hole means that either the hole or any outer -- hole (a hole outside any occurrence of it) -- must be solvable by unification as well as being filled -- in directly. -- Delay dotted things to the end, then when we elaborate them -- we can check the result against what was inferred movelast h delayElab 10 $ do focus h dotterm elab' ina fc t elab' ina fc (PRunElab fc' tm ns) = do attack n <- getNameFrom (sMN 0 "tacticScript") n' <- getNameFrom (sMN 0 "tacticExpr") let scriptTy = RApp (Var (sNS (sUN "Elab") ["Elab", "Reflection", "Language"])) (Var unitTy) claim n scriptTy movelast n letbind n' scriptTy (Var n) focus n elab' ina (Just fc') tm env <- get_env runElabAction ist (maybe fc' id fc) env (P Bound n' Erased) ns solve elab' ina fc (PConstSugar constFC tm) = -- Here we elaborate the contained term, then calculate -- highlighting for constFC. The highlighting is the -- highlighting for the outermost constructor of the result of -- evaluating the elaborated term, if one exists (it always -- should, but better to fail gracefully for something silly -- like highlighting info). This is how implicit applications of -- fromInteger get highlighted. do saveState -- so we don't pollute the elaborated term n <- getNameFrom (sMN 0 "cstI") n' <- getNameFrom (sMN 0 "cstIhole") g <- forget <$> goal claim n' g movelast n' -- In order to intercept the elaborated value, we need to -- let-bind it. attack letbind n g (Var n') focus n' elab' ina fc tm env <- get_env ctxt <- get_context let v = fmap (normaliseAll ctxt env . finalise . binderVal) (lookup n env) loadState -- we have the highlighting - re-elaborate the value elab' ina fc tm case v of Just val -> highlightConst constFC val Nothing -> return () where highlightConst fc (P _ n _) = highlightSource fc (AnnName n Nothing Nothing Nothing) highlightConst fc (App _ f _) = highlightConst fc f highlightConst fc (Constant c) = highlightSource fc (AnnConst c) highlightConst _ _ = return () elab' ina fc x = fail $ "Unelaboratable syntactic form " ++ showTmImpls x -- delay elaboration of 't', with priority 'pri' until after everything -- else is done. -- The delayed things with lower numbered priority will be elaborated -- first. (In practice, this means delayed alternatives, then PHidden -- things.) delayElab pri t = updateAux (\e -> e { delayed_elab = delayed_elab e ++ [(pri, t)] }) isScr :: PTerm -> (Name, Binder Term) -> (Name, (Bool, Binder Term)) isScr (PRef _ _ n) (n', b) = (n', (n == n', b)) isScr _ (n', b) = (n', (False, b)) caseBlock :: FC -> Name -> PTerm -- original scrutinee -> [(Name, (Bool, Binder Term))] -> [(PTerm, PTerm)] -> [PClause] caseBlock fc n scr env opts = let args' = findScr env args = map mkarg (map getNmScr args') in map (mkClause args) opts where -- Find the variable we want as the scrutinee and mark it as -- 'True'. If the scrutinee is in the environment, match on that -- otherwise match on the new argument we're adding. findScr ((n, (True, t)) : xs) = (n, (True, t)) : scrName n xs findScr [(n, (_, t))] = [(n, (True, t))] findScr (x : xs) = x : findScr xs -- [] can't happen since scrutinee is in the environment! findScr [] = error "The impossible happened - the scrutinee was not in the environment" -- To make sure top level pattern name remains in scope, put -- it at the end of the environment scrName n [] = [] scrName n [(_, t)] = [(n, t)] scrName n (x : xs) = x : scrName n xs getNmScr (n, (s, _)) = (n, s) mkarg (n, s) = (PRef fc [] n, s) -- may be shadowed names in the new pattern - so replace the -- old ones with an _ -- Also, names which don't appear on the rhs should not be -- fixed on the lhs, or this restricts the kind of matching -- we can do to non-dependent types. mkClause args (l, r) = let args' = map (shadowed (allNamesIn l)) args args'' = map (implicitable (allNamesIn r ++ keepscrName scr)) args' lhs = PApp (getFC fc l) (PRef NoFC [] n) (map (mkLHSarg l) args'') in PClause (getFC fc l) n lhs [] r [] -- Keep scrutinee available if it's just a name (this makes -- the names in scope look better when looking at a hole on -- the rhs of a case) keepscrName (PRef _ _ n) = [n] keepscrName _ = [] mkLHSarg l (tm, True) = pexp l mkLHSarg l (tm, False) = pexp tm shadowed new (PRef _ _ n, s) | n `elem` new = (Placeholder, s) shadowed new t = t implicitable rhs (PRef _ _ n, s) | n `notElem` rhs = (Placeholder, s) implicitable rhs t = t getFC d (PApp fc _ _) = fc getFC d (PRef fc _ _) = fc getFC d (PAlternative _ _ (x:_)) = getFC d x getFC d x = d insertLazy :: PTerm -> ElabD PTerm insertLazy t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = return t insertLazy t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Force" = return t insertLazy (PCoerced t) = return t insertLazy t = do ty <- goal env <- get_env let (tyh, _) = unApply (normalise (tt_ctxt ist) env ty) let tries = if pattern then [t, mkDelay env t] else [mkDelay env t, t] case tyh of P _ (UN l) _ | l == txt "Lazy'" -> return (PAlternative [] FirstSuccess tries) _ -> return t where mkDelay env (PAlternative ms b xs) = PAlternative ms b (map (mkDelay env) xs) mkDelay env t = let fc = fileFC "Delay" in addImplBound ist (map fst env) (PApp fc (PRef fc [] (sUN "Delay")) [pexp t]) -- Don't put implicit coercions around applications which are marked -- as '%noImplicit', or around case blocks, otherwise we get exponential -- blowup especially where there are errors deep in large expressions. notImplicitable (PApp _ f _) = notImplicitable f -- TMP HACK no coercing on bind (make this configurable) notImplicitable (PRef _ _ n) | [opts] <- lookupCtxt n (idris_flags ist) = NoImplicit `elem` opts notImplicitable (PAlternative _ _ as) = any notImplicitable as -- case is tricky enough without implicit coercions! If they are needed, -- they can go in the branches separately. notImplicitable (PCase _ _ _) = True notImplicitable _ = False insertScopedImps fc (Bind n (Pi im@(Just i) _ _) sc) xs | tcinstance i = pimp n (PResolveTC fc) True : insertScopedImps fc sc xs | otherwise = pimp n Placeholder True : insertScopedImps fc sc xs insertScopedImps fc (Bind n (Pi _ _ _) sc) (x : xs) = x : insertScopedImps fc sc xs insertScopedImps _ _ xs = xs insertImpLam ina t = do ty <- goal env <- get_env let ty' = normalise (tt_ctxt ist) env ty addLam ty' t where -- just one level at a time addLam (Bind n (Pi (Just _) _ _) sc) t = do impn <- unique_hole n -- (sMN 0 "scoped_imp") if e_isfn ina -- apply to an implicit immediately then return (PApp emptyFC (PLam emptyFC impn NoFC Placeholder t) [pexp Placeholder]) else return (PLam emptyFC impn NoFC Placeholder t) addLam _ t = return t insertCoerce ina t@(PCase _ _ _) = return t insertCoerce ina t | notImplicitable t = return t insertCoerce ina t = do ty <- goal -- Check for possible coercions to get to the goal -- and add them as 'alternatives' env <- get_env let ty' = normalise (tt_ctxt ist) env ty let cs = getCoercionsTo ist ty' let t' = case (t, cs) of (PCoerced tm, _) -> tm (_, []) -> t (_, cs) -> PAlternative [] TryImplicit (t : map (mkCoerce env t) cs) return t' where mkCoerce env (PAlternative ms aty tms) n = PAlternative ms aty (map (\t -> mkCoerce env t n) tms) mkCoerce env t n = let fc = maybe (fileFC "Coercion") id (highestFC t) in addImplBound ist (map fst env) (PApp fc (PRef fc [] n) [pexp (PCoerced t)]) -- | Elaborate the arguments to a function elabArgs :: IState -- ^ The current Idris state -> ElabCtxt -- ^ (in an argument, guarded, in a type, in a qquote) -> [Bool] -> FC -- ^ Source location -> Bool -> Name -- ^ Name of the function being applied -> [((Name, Name), Bool)] -- ^ (Argument Name, Hole Name, unmatchable) -> Bool -- ^ under a 'force' -> [PTerm] -- ^ argument -> ElabD () elabArgs ist ina failed fc retry f [] force _ = return () elabArgs ist ina failed fc r f (((argName, holeName), unm):ns) force (t : args) = do hs <- get_holes if holeName `elem` hs then do focus holeName case t of Placeholder -> do movelast holeName elabArgs ist ina failed fc r f ns force args _ -> elabArg t else elabArgs ist ina failed fc r f ns force args where elabArg t = do -- solveAutos ist fn False now_elaborating fc f argName wrapErr f argName $ do hs <- get_holes tm <- get_term -- No coercing under an explicit Force (or it can Force/Delay -- recursively!) let elab = if force then elab' else elabE failed' <- -- trace (show (n, t, hs, tm)) $ -- traceWhen (not (null cs)) (show ty ++ "\n" ++ showImp True t) $ do focus holeName; g <- goal -- Can't pattern match on polymorphic goals poly <- goal_polymorphic ulog <- getUnifyLog traceWhen ulog ("Elaborating argument " ++ show (argName, holeName, g)) $ elab (ina { e_nomatching = unm && poly }) (Just fc) t return failed done_elaborating_arg f argName elabArgs ist ina failed fc r f ns force args wrapErr f argName action = do elabState <- get while <- elaborating_app let while' = map (\(x, y, z)-> (y, z)) while (result, newState) <- case runStateT action elabState of OK (res, newState) -> return (res, newState) Error e -> do done_elaborating_arg f argName lift (tfail (elaboratingArgErr while' e)) put newState return result elabArgs _ _ _ _ _ _ (((arg, hole), _) : _) _ [] = fail $ "Can't elaborate these args: " ++ show arg ++ " " ++ show hole -- For every alternative, look at the function at the head. Automatically resolve -- any nested alternatives where that function is also at the head pruneAlt :: [PTerm] -> [PTerm] pruneAlt xs = map prune xs where prune (PApp fc1 (PRef fc2 hls f) as) = PApp fc1 (PRef fc2 hls f) (fmap (fmap (choose f)) as) prune t = t choose f (PAlternative ms a as) = let as' = fmap (choose f) as fs = filter (headIs f) as' in case fs of [a] -> a _ -> PAlternative ms a as' choose f (PApp fc f' as) = PApp fc (choose f f') (fmap (fmap (choose f)) as) choose f t = t headIs f (PApp _ (PRef _ _ f') _) = f == f' headIs f (PApp _ f' _) = headIs f f' headIs f _ = True -- keep if it's not an application -- Rule out alternatives that don't return the same type as the head of the goal -- (If there are none left as a result, do nothing) pruneByType :: Env -> Term -> -- head of the goal IState -> [PTerm] -> [PTerm] -- if an alternative has a locally bound name at the head, take it pruneByType env t c as | Just a <- locallyBound as = [a] where locallyBound [] = Nothing locallyBound (t:ts) | Just n <- getName t, n `elem` map fst env = Just t | otherwise = locallyBound ts getName (PRef _ _ n) = Just n getName (PApp _ (PRef _ _ (UN l)) [_, _, arg]) -- ignore Delays | l == txt "Delay" = getName (getTm arg) getName (PApp _ f _) = getName f getName (PHidden t) = getName t getName _ = Nothing -- 'n' is the name at the head of the goal type pruneByType env (P _ n _) ist as -- if the goal type is polymorphic, keep everything | Nothing <- lookupTyExact n ctxt = as -- if the goal type is a ?metavariable, keep everything | Just _ <- lookup n (idris_metavars ist) = as | otherwise = let asV = filter (headIs True n) as as' = filter (headIs False n) as in case as' of [] -> asV _ -> as' where ctxt = tt_ctxt ist headIs var f (PRef _ _ f') = typeHead var f f' headIs var f (PApp _ (PRef _ _ (UN l)) [_, _, arg]) | l == txt "Delay" = headIs var f (getTm arg) headIs var f (PApp _ (PRef _ _ f') _) = typeHead var f f' headIs var f (PApp _ f' _) = headIs var f f' headIs var f (PPi _ _ _ _ sc) = headIs var f sc headIs var f (PHidden t) = headIs var f t headIs var f t = True -- keep if it's not an application typeHead var f f' = -- trace ("Trying " ++ show f' ++ " for " ++ show n) $ case lookupTyExact f' ctxt of Just ty -> case unApply (getRetTy ty) of (P _ ctyn _, _) | isConName ctyn ctxt -> ctyn == f _ -> let ty' = normalise ctxt [] ty in case unApply (getRetTy ty') of (P _ ftyn _, _) -> ftyn == f (V _, _) -> -- keep, variable -- trace ("Keeping " ++ show (f', ty') -- ++ " for " ++ show n) $ isPlausible ist var env n ty _ -> False _ -> False pruneByType _ t _ as = as -- Could the name feasibly be the return type? -- If there is a type class constraint on the return type, and no instance -- in the environment or globally for that name, then no -- Otherwise, yes -- (FIXME: This isn't complete, but I'm leaving it here and coming back -- to it later - just returns 'var' for now. EB) isPlausible :: IState -> Bool -> Env -> Name -> Type -> Bool isPlausible ist var env n ty = let (hvar, classes) = collectConstraints [] [] ty in case hvar of Nothing -> True Just rth -> var -- trace (show (rth, classes)) var where collectConstraints :: [Name] -> [(Term, [Name])] -> Type -> (Maybe Name, [(Term, [Name])]) collectConstraints env tcs (Bind n (Pi _ ty _) sc) = let tcs' = case unApply ty of (P _ c _, _) -> case lookupCtxtExact c (idris_classes ist) of Just tc -> ((ty, map fst (class_instances tc)) : tcs) Nothing -> tcs _ -> tcs in collectConstraints (n : env) tcs' sc collectConstraints env tcs t | (V i, _) <- unApply t = (Just (env !! i), tcs) | otherwise = (Nothing, tcs) -- | Use the local elab context to work out the highlighting for a name findHighlight :: Name -> ElabD OutputAnnotation findHighlight n = do ctxt <- get_context env <- get_env case lookup n env of Just _ -> return $ AnnBoundName n False Nothing -> case lookupTyExact n ctxt of Just _ -> return $ AnnName n Nothing Nothing Nothing Nothing -> lift . tfail . InternalMsg $ "Can't find name" ++ show n -- Try again to solve auto implicits solveAuto :: IState -> Name -> Bool -> (Name, [FailContext]) -> ElabD () solveAuto ist fn ambigok (n, failc) = do hs <- get_holes when (not (null hs)) $ do env <- get_env g <- goal handleError cantsolve (when (n `elem` hs) $ do focus n isg <- is_guess -- if it's a guess, we're working on it recursively, so stop when (not isg) $ proofSearch' ist True ambigok 100 True Nothing fn [] []) (lift $ Error (addLoc failc (CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env)))) return () where addLoc (FailContext fc f x : prev) err = At fc (ElaboratingArg f x (map (\(FailContext _ f' x') -> (f', x')) prev) err) addLoc _ err = err cantsolve (CantSolveGoal _ _) = True cantsolve (InternalMsg _) = True cantsolve (At _ e) = cantsolve e cantsolve (Elaborating _ _ e) = cantsolve e cantsolve (ElaboratingArg _ _ _ e) = cantsolve e cantsolve _ = False solveAutos :: IState -> Name -> Bool -> ElabD () solveAutos ist fn ambigok = do autos <- get_autos mapM_ (solveAuto ist fn ambigok) (map (\(n, (fc, _)) -> (n, fc)) autos) trivial' ist = trivial (elab ist toplevel ERHS [] (sMN 0 "tac")) ist trivialHoles' psn h ist = trivialHoles psn h (elab ist toplevel ERHS [] (sMN 0 "tac")) ist proofSearch' ist rec ambigok depth prv top n psns hints = do unifyProblems proofSearch rec prv ambigok (not prv) depth (elab ist toplevel ERHS [] (sMN 0 "tac")) top n psns hints ist resolveTC' di mv depth tm n ist = resolveTC di mv depth tm n (elab ist toplevel ERHS [] (sMN 0 "tac")) ist collectDeferred :: Maybe Name -> [Name] -> Context -> Term -> State [(Name, (Int, Maybe Name, Type, [Name]))] Term collectDeferred top casenames ctxt (Bind n (GHole i psns t) app) = do ds <- get t' <- collectDeferred top casenames ctxt t when (not (n `elem` map fst ds)) $ put (ds ++ [(n, (i, top, tidyArg [] t', psns))]) collectDeferred top casenames ctxt app where -- Evaluate the top level functions in arguments, if possible, and if it's -- not a name we're immediately going to define in a case block, so that -- any immediate specialisation of the function applied to constructors -- can be done tidyArg env (Bind n b@(Pi im t k) sc) = Bind n (Pi im (tidy ctxt env t) k) (tidyArg ((n, b) : env) sc) tidyArg env t = tidy ctxt env t tidy ctxt env t = normalise ctxt env t getFn (Bind n (Lam _) t) = getFn t getFn t | (f, a) <- unApply t = f collectDeferred top ns ctxt (Bind n b t) = do b' <- cdb b t' <- collectDeferred top ns ctxt t return (Bind n b' t') where cdb (Let t v) = liftM2 Let (collectDeferred top ns ctxt t) (collectDeferred top ns ctxt v) cdb (Guess t v) = liftM2 Guess (collectDeferred top ns ctxt t) (collectDeferred top ns ctxt v) cdb b = do ty' <- collectDeferred top ns ctxt (binderTy b) return (b { binderTy = ty' }) collectDeferred top ns ctxt (App s f a) = liftM2 (App s) (collectDeferred top ns ctxt f) (collectDeferred top ns ctxt a) collectDeferred top ns ctxt t = return t case_ :: Bool -> Bool -> IState -> Name -> PTerm -> ElabD () case_ ind autoSolve ist fn tm = do attack tyn <- getNameFrom (sMN 0 "ity") claim tyn RType valn <- getNameFrom (sMN 0 "ival") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "irule") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") tm env <- get_env let (Just binding) = lookup letn env let val = binderVal binding if ind then induction (forget val) else casetac (forget val) when autoSolve solveAll -- | Compute the appropriate name for a top-level metavariable metavarName :: Maybe [String] -> Name -> Name metavarName _ n@(NS _ _) = n metavarName (Just (ns@(_:_))) n = sNS n ns metavarName _ n = n runElabAction :: IState -> FC -> Env -> Term -> [String] -> ElabD Term runElabAction ist fc env tm ns = do tm' <- eval tm runTacTm tm' where eval tm = do ctxt <- get_context return $ normaliseAll ctxt env (finalise tm) returnUnit = return $ P (DCon 0 0 False) unitCon (P (TCon 0 0) unitTy Erased) patvars :: [Name] -> Term -> ([Name], Term) patvars ns (Bind n (PVar t) sc) = patvars (n : ns) (instantiate (P Bound n t) sc) patvars ns tm = (ns, tm) pullVars :: (Term, Term) -> ([Name], Term, Term) pullVars (lhs, rhs) = (fst (patvars [] lhs), snd (patvars [] lhs), snd (patvars [] rhs)) -- TODO alpha-convert rhs defineFunction :: RFunDefn -> ElabD () defineFunction (RDefineFun n clauses) = do ctxt <- get_context ty <- maybe (fail "no type decl") return $ lookupTyExact n ctxt let info = CaseInfo True True False -- TODO document and figure out clauses' <- forM clauses (\case RMkFunClause lhs rhs -> do (lhs', lty) <- lift $ check ctxt [] lhs (rhs', rty) <- lift $ check ctxt [] rhs lift $ converts ctxt [] lty rty return $ Right (lhs', rhs') RMkImpossibleClause lhs -> do lhs' <- fmap fst . lift $ check ctxt [] lhs return $ Left lhs') let clauses'' = map (\case Right c -> pullVars c Left lhs -> let (ns, lhs') = patvars [] lhs' in (ns, lhs', Impossible)) clauses' ctxt'<- lift $ addCasedef n (const []) info False (STerm Erased) True False -- TODO what are these? (map snd $ getArgTys ty) [] -- TODO inaccessible types clauses' clauses'' clauses'' clauses'' clauses'' ty ctxt set_context ctxt' updateAux $ \e -> e { new_tyDecls = RClausesInstrs n clauses'' : new_tyDecls e} return () checkClosed :: Raw -> Elab' aux (Term, Type) checkClosed tm = do ctxt <- get_context (val, ty) <- lift $ check ctxt [] tm return $! (finalise val, finalise ty) -- | Do a step in the reflected elaborator monad. The input is the -- step, the output is the (reflected) term returned. runTacTm :: Term -> ElabD Term runTacTm (unApply -> tac@(P _ n _, args)) | n == tacN "prim__Solve", [] <- args = do solve returnUnit | n == tacN "prim__Goal", [] <- args = do hs <- get_holes case hs of (h : _) -> do t <- goal fmap fst . checkClosed $ rawPair (Var (reflm "TTName"), Var (reflm "TT")) (reflectName h, reflect t) [] -> lift . tfail . Msg $ "Elaboration is complete. There are no goals." | n == tacN "prim__Holes", [] <- args = do hs <- get_holes fmap fst . checkClosed $ mkList (Var $ reflm "TTName") (map reflectName hs) | n == tacN "prim__Guess", [] <- args = do ok <- is_guess if ok then do guess <- fmap forget get_guess fmap fst . get_type_val $ RApp (RApp (Var (sNS (sUN "Just") ["Maybe", "Prelude"])) (Var (reflm "TT"))) guess else fmap fst . checkClosed $ RApp (Var (sNS (sUN "Nothing") ["Maybe", "Prelude"])) (Var (reflm "TT")) | n == tacN "prim__LookupTy", [n] <- args = do n' <- reifyTTName n ctxt <- get_context let getNameTypeAndType = \case Function ty _ -> (Ref, ty) TyDecl nt ty -> (nt, ty) Operator ty _ _ -> (Ref, ty) CaseOp _ ty _ _ _ _ -> (Ref, ty) -- Idris tuples nest to the right reflectTriple (x, y, z) = raw_apply (Var pairCon) [ Var (reflm "TTName") , raw_apply (Var pairTy) [Var (reflm "NameType"), Var (reflm "TT")] , x , raw_apply (Var pairCon) [ Var (reflm "NameType"), Var (reflm "TT") , y, z]] let defs = [ reflectTriple (reflectName n, reflectNameType nt, reflect ty) | (n, def) <- lookupNameDef n' ctxt , let (nt, ty) = getNameTypeAndType def ] fmap fst . checkClosed $ rawList (raw_apply (Var pairTy) [ Var (reflm "TTName") , raw_apply (Var pairTy) [ Var (reflm "NameType") , Var (reflm "TT")]]) defs | n == tacN "prim__LookupDatatype", [name] <- args = do n' <- reifyTTName name datatypes <- get_datatypes ctxt <- get_context fmap fst . checkClosed $ rawList (Var (tacN "Datatype")) (map reflectDatatype (buildDatatypes ist n')) | n == tacN "prim__SourceLocation", [] <- args = fmap fst . checkClosed $ reflectFC fc | n == tacN "prim__Namespace", [] <- args = fmap fst . checkClosed $ rawList (RConstant StrType) (map (RConstant . Str) ns) | n == tacN "prim__Env", [] <- args = do env <- get_env fmap fst . checkClosed $ reflectEnv env | n == tacN "prim__Fail", [_a, errs] <- args = do errs' <- eval errs parts <- reifyReportParts errs' lift . tfail $ ReflectionError [parts] (Msg "") | n == tacN "prim__PureElab", [_a, tm] <- args = return tm | n == tacN "prim__BindElab", [_a, _b, first, andThen] <- args = do first' <- eval first res <- eval =<< runTacTm first' next <- eval (App Complete andThen res) runTacTm next | n == tacN "prim__Try", [_a, first, alt] <- args = do first' <- eval first alt' <- eval alt try' (runTacTm first') (runTacTm alt') True | n == tacN "prim__Fill", [raw] <- args = do raw' <- reifyRaw =<< eval raw fill raw' returnUnit | n == tacN "prim__Apply" || n == tacN "prim__MatchApply" , [raw, argSpec] <- args = do raw' <- reifyRaw =<< eval raw argSpec' <- reifyList (reifyPair reifyBool reifyInt) argSpec let op = if n == tacN "prim__Apply" then apply else match_apply ns <- op raw' argSpec' fmap fst . checkClosed $ rawList (rawPairTy (Var $ reflm "TTName") (Var $ reflm "TTName")) [ rawPair (Var $ reflm "TTName", Var $ reflm "TTName") (reflectName n1, reflectName n2) | (n1, n2) <- ns ] | n == tacN "prim__Gensym", [hint] <- args = do hintStr <- eval hint case hintStr of Constant (Str h) -> do n <- getNameFrom (sMN 0 h) fmap fst $ get_type_val (reflectName n) _ -> fail "no hint" | n == tacN "prim__Claim", [n, ty] <- args = do n' <- reifyTTName n ty' <- reifyRaw ty claim n' ty' returnUnit | n == tacN "prim__Check", [raw] <- args = do raw' <- reifyRaw =<< eval raw ctxt <- get_context env <- get_env (tm, ty) <- lift $ check ctxt env raw' fmap fst . checkClosed $ rawPair (Var (reflm "TT"), Var (reflm "TT")) (reflect tm, reflect ty) | n == tacN "prim__Forget", [tt] <- args = do tt' <- reifyTT tt fmap fst . checkClosed . reflectRaw $ forget tt' | n == tacN "prim__Attack", [] <- args = do attack returnUnit | n == tacN "prim__Rewrite", [rule] <- args = do r <- reifyRaw rule rewrite r returnUnit | n == tacN "prim__Focus", [what] <- args = do n' <- reifyTTName what hs <- get_holes if elem n' hs then focus n' >> returnUnit else lift . tfail . Msg $ "The name " ++ show n' ++ " does not denote a hole" | n == tacN "prim__Unfocus", [what] <- args = do n' <- reifyTTName what movelast n' returnUnit | n == tacN "prim__Intro", [mn] <- args = do n <- case fromTTMaybe mn of Nothing -> return Nothing Just name -> fmap Just $ reifyTTName name intro n returnUnit | n == tacN "prim__Forall", [n, ty] <- args = do n' <- reifyTTName n ty' <- reifyRaw ty forall n' Nothing ty' returnUnit | n == tacN "prim__PatVar", [n] <- args = do n' <- reifyTTName n patvar' n' returnUnit | n == tacN "prim__PatBind", [n] <- args = do n' <- reifyTTName n patbind n' returnUnit | n == tacN "prim__LetBind", [n, ty, tm] <- args = do n' <- reifyTTName n ty' <- reifyRaw ty tm' <- reifyRaw tm letbind n' ty' tm' returnUnit | n == tacN "prim__Compute", [] <- args = do compute ; returnUnit | n == tacN "prim__Normalise", [env, tm] <- args = do env' <- reifyEnv env tm' <- reifyTT tm ctxt <- get_context let out = normaliseAll ctxt env' (finalise tm') fmap fst . checkClosed $ reflect out | n == tacN "prim__Whnf", [tm] <- args = do tm' <- reifyTT tm ctxt <- get_context fmap fst . checkClosed . reflect $ whnf ctxt tm' | n == tacN "prim__DeclareType", [decl] <- args = do (RDeclare n args res) <- reifyTyDecl decl ctxt <- get_context let mkPi arg res = RBind (argName arg) (Pi Nothing (argTy arg) (RUType AllTypes)) res rty = foldr mkPi res args (checked, ty') <- lift $ check ctxt [] rty case normaliseAll ctxt [] (finalise ty') of UType _ -> return () TType _ -> return () ty'' -> lift . tfail . InternalMsg $ show checked ++ " is not a type: it's " ++ show ty'' case lookupDefExact n ctxt of Just _ -> lift . tfail . InternalMsg $ show n ++ " is already defined." Nothing -> return () let decl = TyDecl Ref checked ctxt' = addCtxtDef n decl ctxt set_context ctxt' updateAux $ \e -> e { new_tyDecls = (RTyDeclInstrs n fc (map rFunArgToPArg args) checked) : new_tyDecls e } aux <- getAux returnUnit | n == tacN "prim__DefineFunction", [decl] <- args = do defn <- reifyFunDefn decl defineFunction defn returnUnit | n == tacN "prim__AddInstance", [cls, inst] <- args = do className <- reifyTTName cls instName <- reifyTTName inst updateAux $ \e -> e { new_tyDecls = RAddInstance className instName : new_tyDecls e} returnUnit | n == tacN "prim__ResolveTC", [fn] <- args = do g <- goal fn <- reifyTTName fn resolveTC' False True 100 g fn ist returnUnit | n == tacN "prim__Search", [depth, hints] <- args = do d <- eval depth hints' <- eval hints case (d, unList hints') of (Constant (I i), Just hs) -> do actualHints <- mapM reifyTTName hs unifyProblems let psElab = elab ist toplevel ERHS [] (sMN 0 "tac") proofSearch True True False False i psElab Nothing (sMN 0 "search ") [] actualHints ist returnUnit (Constant (I _), Nothing ) -> lift . tfail . InternalMsg $ "Not a list: " ++ show hints' (_, _) -> lift . tfail . InternalMsg $ "Can't reify int " ++ show d | n == tacN "prim__RecursiveElab", [goal, script] <- args = do goal' <- reifyRaw goal ctxt <- get_context script <- eval script (goalTT, goalTy) <- lift $ check ctxt [] goal' lift $ isType ctxt [] goalTy recH <- getNameFrom (sMN 0 "recElabHole") aux <- getAux datatypes <- get_datatypes env <- get_env (_, ES (p, aux') _ _) <- do (ES (current_p, _) _ _) <- get lift $ runElab aux (runElabAction ist fc [] script ns) ((newProof recH ctxt datatypes goalTT) { nextname = nextname current_p}) let tm_out = getProofTerm (pterm p) do (ES (prf, _) s e) <- get let p' = prf { nextname = nextname p } put (ES (p', aux') s e) env' <- get_env (tm, ty, _) <- lift $ recheck ctxt env (forget tm_out) tm_out let (tm', ty') = (reflect tm, reflect ty) fmap fst . checkClosed $ rawPair (Var $ reflm "TT", Var $ reflm "TT") (tm', ty') | n == tacN "prim__Metavar", [n] <- args = do n' <- reifyTTName n ctxt <- get_context ptm <- get_term -- See documentation above in the elab case for PMetavar let unique_used = getUniqueUsed ctxt ptm let mvn = metavarName (Just ns) n' attack defer unique_used mvn solve returnUnit | n == tacN "prim__Fixity", [op'] <- args = do opTm <- eval op' case opTm of Constant (Str op) -> let opChars = ":!#$%&*+./<=>?@\\^|-~" invalidOperators = [":", "=>", "->", "<-", "=", "?=", "|", "**", "==>", "\\", "%", "~", "?", "!"] fixities = idris_infixes ist in if not (all (flip elem opChars) op) || elem op invalidOperators then lift . tfail . Msg $ "'" ++ op ++ "' is not a valid operator name." else case nub [f | Fix f someOp <- fixities, someOp == op] of [] -> lift . tfail . Msg $ "No fixity found for operator '" ++ op ++ "'." [f] -> fmap fst . checkClosed $ reflectFixity f many -> lift . tfail . InternalMsg $ "Ambiguous fixity for '" ++ op ++ "'! Found " ++ show many _ -> lift . tfail . Msg $ "Not a constant string for an operator name: " ++ show opTm | n == tacN "prim__Debug", [ty, msg] <- args = do msg' <- eval msg parts <- reifyReportParts msg debugElaborator parts runTacTm x = lift . tfail $ ElabScriptStuck x -- Running tactics directly -- if a tactic adds unification problems, return an error runTac :: Bool -> IState -> Maybe FC -> Name -> PTactic -> ElabD () runTac autoSolve ist perhapsFC fn tac = do env <- get_env g <- goal let tac' = fmap (addImplBound ist (map fst env)) tac if autoSolve then runT tac' else no_errors (runT tac') (Just (CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env))) where runT (Intro []) = do g <- goal attack; intro (bname g) where bname (Bind n _ _) = Just n bname _ = Nothing runT (Intro xs) = mapM_ (\x -> do attack; intro (Just x)) xs runT Intros = do g <- goal attack; intro (bname g) try' (runT Intros) (return ()) True where bname (Bind n _ _) = Just n bname _ = Nothing runT (Exact tm) = do elab ist toplevel ERHS [] (sMN 0 "tac") tm when autoSolve solveAll runT (MatchRefine fn) = do fnimps <- case lookupCtxtName fn (idris_implicits ist) of [] -> do a <- envArgs fn return [(fn, a)] ns -> return (map (\ (n, a) -> (n, map (const True) a)) ns) let tacs = map (\ (fn', imps) -> (match_apply (Var fn') (map (\x -> (x, 0)) imps), fn')) fnimps tryAll tacs when autoSolve solveAll where envArgs n = do e <- get_env case lookup n e of Just t -> return $ map (const False) (getArgTys (binderTy t)) _ -> return [] runT (Refine fn []) = do fnimps <- case lookupCtxtName fn (idris_implicits ist) of [] -> do a <- envArgs fn return [(fn, a)] ns -> return (map (\ (n, a) -> (n, map isImp a)) ns) let tacs = map (\ (fn', imps) -> (apply (Var fn') (map (\x -> (x, 0)) imps), fn')) fnimps tryAll tacs when autoSolve solveAll where isImp (PImp _ _ _ _ _) = True isImp _ = False envArgs n = do e <- get_env case lookup n e of Just t -> return $ map (const False) (getArgTys (binderTy t)) _ -> return [] runT (Refine fn imps) = do ns <- apply (Var fn) (map (\x -> (x,0)) imps) when autoSolve solveAll runT DoUnify = do unify_all when autoSolve solveAll runT (Claim n tm) = do tmHole <- getNameFrom (sMN 0 "newGoal") claim tmHole RType claim n (Var tmHole) focus tmHole elab ist toplevel ERHS [] (sMN 0 "tac") tm focus n runT (Equiv tm) -- let bind tm, then = do attack tyn <- getNameFrom (sMN 0 "ety") claim tyn RType valn <- getNameFrom (sMN 0 "eqval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "equiv_val") letbind letn (Var tyn) (Var valn) focus tyn elab ist toplevel ERHS [] (sMN 0 "tac") tm focus valn when autoSolve solveAll runT (Rewrite tm) -- to elaborate tm, let bind it, then rewrite by that = do attack; -- (h:_) <- get_holes tyn <- getNameFrom (sMN 0 "rty") -- start_unify h claim tyn RType valn <- getNameFrom (sMN 0 "rval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "rewrite_rule") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") tm rewrite (Var letn) when autoSolve solveAll runT (Induction tm) -- let bind tm, similar to the others = case_ True autoSolve ist fn tm runT (CaseTac tm) = case_ False autoSolve ist fn tm runT (LetTac n tm) = do attack tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- unique_hole n letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") tm when autoSolve solveAll runT (LetTacTy n ty tm) = do attack tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- unique_hole n letbind letn (Var tyn) (Var valn) focus tyn elab ist toplevel ERHS [] (sMN 0 "tac") ty focus valn elab ist toplevel ERHS [] (sMN 0 "tac") tm when autoSolve solveAll runT Compute = compute runT Trivial = do trivial' ist; when autoSolve solveAll runT TCInstance = runT (Exact (PResolveTC emptyFC)) runT (ProofSearch rec prover depth top psns hints) = do proofSearch' ist rec False depth prover top fn psns hints when autoSolve solveAll runT (Focus n) = focus n runT Unfocus = do hs <- get_holes case hs of [] -> return () (h : _) -> movelast h runT Solve = solve runT (Try l r) = do try' (runT l) (runT r) True runT (TSeq l r) = do runT l; runT r runT (ApplyTactic tm) = do tenv <- get_env -- store the environment tgoal <- goal -- store the goal attack -- let f : List (TTName, Binder TT) -> TT -> Tactic = tm in ... script <- getNameFrom (sMN 0 "script") claim script scriptTy scriptvar <- getNameFrom (sMN 0 "scriptvar" ) letbind scriptvar scriptTy (Var script) focus script elab ist toplevel ERHS [] (sMN 0 "tac") tm (script', _) <- get_type_val (Var scriptvar) -- now that we have the script apply -- it to the reflected goal and context restac <- getNameFrom (sMN 0 "restac") claim restac tacticTy focus restac fill (raw_apply (forget script') [reflectEnv tenv, reflect tgoal]) restac' <- get_guess solve -- normalise the result in order to -- reify it ctxt <- get_context env <- get_env let tactic = normalise ctxt env restac' runReflected tactic where tacticTy = Var (reflm "Tactic") listTy = Var (sNS (sUN "List") ["List", "Prelude"]) scriptTy = (RBind (sMN 0 "__pi_arg") (Pi Nothing (RApp listTy envTupleType) RType) (RBind (sMN 1 "__pi_arg") (Pi Nothing (Var $ reflm "TT") RType) tacticTy)) runT (ByReflection tm) -- run the reflection function 'tm' on the -- goal, then apply the resulting reflected Tactic = do tgoal <- goal attack script <- getNameFrom (sMN 0 "script") claim script scriptTy scriptvar <- getNameFrom (sMN 0 "scriptvar" ) letbind scriptvar scriptTy (Var script) focus script ptm <- get_term elab ist toplevel ERHS [] (sMN 0 "tac") (PApp emptyFC tm [pexp (delabTy' ist [] tgoal True True)]) (script', _) <- get_type_val (Var scriptvar) -- now that we have the script apply -- it to the reflected goal restac <- getNameFrom (sMN 0 "restac") claim restac tacticTy focus restac fill (forget script') restac' <- get_guess solve -- normalise the result in order to -- reify it ctxt <- get_context env <- get_env let tactic = normalise ctxt env restac' runReflected tactic where tacticTy = Var (reflm "Tactic") scriptTy = tacticTy runT (Reflect v) = do attack -- let x = reflect v in ... tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "letvar") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") v (value, _) <- get_type_val (Var letn) ctxt <- get_context env <- get_env let value' = hnf ctxt env value runTac autoSolve ist perhapsFC fn (Exact $ PQuote (reflect value')) runT (Fill v) = do attack -- let x = fill x in ... tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "letvar") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") v (value, _) <- get_type_val (Var letn) ctxt <- get_context env <- get_env let value' = normalise ctxt env value rawValue <- reifyRaw value' runTac autoSolve ist perhapsFC fn (Exact $ PQuote rawValue) runT (GoalType n tac) = do g <- goal case unApply g of (P _ n' _, _) -> if nsroot n' == sUN n then runT tac else fail "Wrong goal type" _ -> fail "Wrong goal type" runT ProofState = do g <- goal return () runT Skip = return () runT (TFail err) = lift . tfail $ ReflectionError [err] (Msg "") runT SourceFC = case perhapsFC of Nothing -> lift . tfail $ Msg "There is no source location available." Just fc -> do fill $ reflectFC fc solve runT Qed = lift . tfail $ Msg "The qed command is only valid in the interactive prover" runT x = fail $ "Not implemented " ++ show x runReflected t = do t' <- reify ist t runTac autoSolve ist perhapsFC fn t' elaboratingArgErr :: [(Name, Name)] -> Err -> Err elaboratingArgErr [] err = err elaboratingArgErr ((f,x):during) err = fromMaybe err (rewrite err) where rewrite (ElaboratingArg _ _ _ _) = Nothing rewrite (ProofSearchFail e) = fmap ProofSearchFail (rewrite e) rewrite (At fc e) = fmap (At fc) (rewrite e) rewrite err = Just (ElaboratingArg f x during err) withErrorReflection :: Idris a -> Idris a withErrorReflection x = idrisCatch x (\ e -> handle e >>= ierror) where handle :: Err -> Idris Err handle e@(ReflectionError _ _) = do logLvl 3 "Skipping reflection of error reflection result" return e -- Don't do meta-reflection of errors handle e@(ReflectionFailed _ _) = do logLvl 3 "Skipping reflection of reflection failure" return e -- At and Elaborating are just plumbing - error reflection shouldn't rewrite them handle e@(At fc err) = do logLvl 3 "Reflecting body of At" err' <- handle err return (At fc err') handle e@(Elaborating what n err) = do logLvl 3 "Reflecting body of Elaborating" err' <- handle err return (Elaborating what n err') handle e@(ElaboratingArg f a prev err) = do logLvl 3 "Reflecting body of ElaboratingArg" hs <- getFnHandlers f a err' <- if null hs then handle err else applyHandlers err hs return (ElaboratingArg f a prev err') -- ProofSearchFail is an internal detail - so don't expose it handle (ProofSearchFail e) = handle e -- TODO: argument-specific error handlers go here for ElaboratingArg handle e = do ist <- getIState logLvl 2 "Starting error reflection" logLvl 5 (show e) let handlers = idris_errorhandlers ist applyHandlers e handlers getFnHandlers :: Name -> Name -> Idris [Name] getFnHandlers f arg = do ist <- getIState let funHandlers = maybe M.empty id . lookupCtxtExact f . idris_function_errorhandlers $ ist return . maybe [] S.toList . M.lookup arg $ funHandlers applyHandlers e handlers = do ist <- getIState let err = fmap (errReverse ist) e logLvl 3 $ "Using reflection handlers " ++ concat (intersperse ", " (map show handlers)) let reports = map (\n -> RApp (Var n) (reflectErr err)) handlers -- Typecheck error handlers - if this fails, then something else was wrong earlier! handlers <- case mapM (check (tt_ctxt ist) []) reports of Error e -> ierror $ ReflectionFailed "Type error while constructing reflected error" e OK hs -> return hs -- Normalize error handler terms to produce the new messages ctxt <- getContext let results = map (normalise ctxt []) (map fst handlers) logLvl 3 $ "New error message info: " ++ concat (intersperse " and " (map show results)) -- For each handler term output, either discard it if it is Nothing or reify it the Haskell equivalent let errorpartsTT = mapMaybe unList (mapMaybe fromTTMaybe results) errorparts <- case mapM (mapM reifyReportPart) errorpartsTT of Left err -> ierror err Right ok -> return ok return $ case errorparts of [] -> e parts -> ReflectionError errorparts e solveAll = try (do solve; solveAll) (return ()) -- | Do the left-over work after creating declarations in reflected -- elaborator scripts processTacticDecls :: ElabInfo -> [RDeclInstructions] -> Idris () processTacticDecls info steps = -- The order of steps is important: type declarations might -- establish metavars that later function bodies resolve. forM_ (reverse steps) $ \case RTyDeclInstrs n fc impls ty -> do logLvl 3 $ "Declaration from tactics: " ++ show n ++ " : " ++ show ty logLvl 3 $ " It has impls " ++ show impls updateIState $ \i -> i { idris_implicits = addDef n impls (idris_implicits i) } addIBC (IBCImp n) ds <- checkDef fc (\_ e -> e) [(n, (-1, Nothing, ty, []))] addIBC (IBCDef n) ctxt <- getContext case lookupDef n ctxt of (TyDecl _ _ : _) -> -- If the function isn't defined at the end of the elab script, -- then it must be added as a metavariable. This needs guarding -- to prevent overwriting case defs with a metavar, if the case -- defs come after the type decl in the same script! let ds' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, True))) ds in addDeferred ds' _ -> return () RAddInstance className instName -> do -- The type class resolution machinery relies on a special logLvl 2 $ "Adding elab script instance " ++ show instName ++ " for " ++ show className addInstance False True className instName addIBC (IBCInstance False True className instName) RClausesInstrs n cs -> do logLvl 3 $ "Pattern-matching definition from tactics: " ++ show n solveDeferred n let lhss = map (\(_, lhs, _) -> lhs) cs let fc = fileFC "elab_reflected" pmissing <- do ist <- getIState possible <- genClauses fc n lhss (map (\lhs -> delab' ist lhs True True) lhss) missing <- filterM (checkPossible n) possible return (filter (noMatch ist lhss) missing) let tot = if null pmissing then Unchecked -- still need to check recursive calls else Partial NotCovering -- missing cases implies not total setTotality n tot updateIState $ \i -> i { idris_patdefs = addDef n (cs, pmissing) $ idris_patdefs i } addIBC (IBCDef n) ctxt <- getContext case lookupDefExact n ctxt of Just (CaseOp _ _ _ _ _ cd) -> -- Here, we populate the call graph with a list of things -- we refer to, so that if they aren't total, the whole -- thing won't be. let (scargs, sc) = cases_compiletime cd (scargs', sc') = cases_runtime cd calls = findCalls sc' scargs used = findUsedArgs sc' scargs' cg = CGInfo scargs' calls [] used [] in do logLvl 2 $ "Called names in reflected elab: " ++ show cg addToCG n cg addToCalledG n (nub (map fst calls)) addIBC $ IBCCG n Just _ -> return () -- TODO throw internal error Nothing -> return () -- checkDeclTotality requires that the call graph be present -- before calling it. -- TODO: reduce code duplication with Idris.Elab.Clause buildSCG (fc, n) -- Actually run the totality checker. In the main clause -- elaborator, this is deferred until after. Here, we run it -- now to get totality information as early as possible. tot' <- checkDeclTotality (fc, n) setTotality n tot' when (tot' /= Unchecked) $ addIBC (IBCTotal n tot') where -- TODO: see if the code duplication with Idris.Elab.Clause can be -- reduced or eliminated. checkPossible :: Name -> PTerm -> Idris Bool checkPossible fname lhs_in = do ctxt <- getContext ist <- getIState let lhs = addImplPat ist lhs_in let fc = fileFC "elab_reflected_totality" let tcgen = False -- TODO: later we may support dictionary generation case elaborate ctxt (idris_datatypes ist) (sMN 0 "refPatLHS") infP initEState (erun fc (buildTC ist info ELHS [] fname (infTerm lhs))) of OK (ElabResult lhs' _ _ _ _ _, _) -> do -- not recursively calling here, because we don't -- want to run infinitely many times let lhs_tm = orderPats (getInferTerm lhs') case recheck ctxt [] (forget lhs_tm) lhs_tm of OK _ -> return True err -> return False -- if it's a recoverable error, the case may become possible Error err -> if tcgen then return (recoverableCoverage ctxt err) else return (validCoverageCase ctxt err || recoverableCoverage ctxt err) -- TODO: Attempt to reduce/eliminate code duplication with Idris.Elab.Clause noMatch i cs tm = all (\x -> case matchClause i (delab' i x True True) tm of Right _ -> False Left _ -> True) cs
osa1/Idris-dev
src/Idris/Elab/Term.hs
bsd-3-clause
116,442
1,102
16
51,409
14,327
10,741
3,586
2,056
221
{-# LANGUAGE Rank2Types #-} module CabalLenses.Traversals.BuildInfo ( allBuildInfo , buildInfo , buildInfoIf ) where import CabalLenses.Section (Section(..)) import CabalLenses.Traversals.Internal (traverseData, traverseDataIf) import CabalLenses.CondVars (CondVars) import CabalLenses.PackageDescription import Control.Lens import Distribution.PackageDescription (GenericPackageDescription(GenericPackageDescription), BuildInfo) import Distribution.Types.UnqualComponentName (unUnqualComponentName) -- | A traversal for all 'BuildInfo' of all 'Section' allBuildInfo :: Traversal' GenericPackageDescription BuildInfo allBuildInfo f (GenericPackageDescription descrp flags lib subLibs foreignLibs exes tests benchs) = GenericPackageDescription <$> pure descrp <*> pure flags <*> (_Just . traverseData . libBuildInfoL) f lib <*> pure subLibs <*> pure foreignLibs <*> (traverse . _2 . traverseData . buildInfoL) f exes <*> (traverse . _2 . traverseData . testBuildInfoL) f tests <*> (traverse . _2 . traverseData . benchmarkBuildInfoL) f benchs -- | A traversal for all 'BuildInfo' of 'Section'. buildInfo :: Section -> Traversal' GenericPackageDescription BuildInfo buildInfo Library = condLibraryL . _Just . traverseData . libBuildInfoL buildInfo (Executable name) = condExecutablesL . traverse . having name . _2 . traverseData . buildInfoL buildInfo (TestSuite name) = condTestSuitesL . traverse . having name . _2 . traverseData . testBuildInfoL buildInfo (Benchmark name) = condBenchmarksL . traverse . having name . _2 . traverseData . benchmarkBuildInfoL -- | A traversal for the 'BuildInfo' of 'Section' that match 'CondVars'. buildInfoIf :: CondVars -> Section -> Traversal' GenericPackageDescription BuildInfo buildInfoIf condVars Library = condLibraryL . _Just . traverseDataIf condVars . libBuildInfoL buildInfoIf condVars (Executable name) = condExecutablesL . traverse . having name . _2 . traverseDataIf condVars . buildInfoL buildInfoIf condVars (TestSuite name) = condTestSuitesL . traverse . having name . _2 . traverseDataIf condVars . testBuildInfoL buildInfoIf condVars (Benchmark name) = condBenchmarksL . traverse . having name . _2 . traverseDataIf condVars . benchmarkBuildInfoL having name = filtered ((== name) . unUnqualComponentName . fst)
dan-t/cabal-lenses
lib/CabalLenses/Traversals/BuildInfo.hs
bsd-3-clause
2,517
0
14
534
598
308
290
33
1
-- | An effect is a processed version of an action, ready -- to change tiles in the world but it only contains raw -- information. Example: -- -- A monster 'M' wants to attack a guy '@' with its hands, -- then the game generates an 'Hit' action: -- "Action 'M' '@' (Hit 'Bare_Hands')" or something like that. -- Then an effect is returned, and it could be (ChangeInHp (-4)), -- beacuse an normal punch attack has -2 change in hp, but in this -- case, the monster M has an power to increase the attack when using -- its hands. -- In the final part, the program look at the effect and the target, -- and generates the final state of the target tile (In this case -- would be the loss in HP, counting with any defense tool that the -- target could be using). module Effect where import Data.List import qualified World as W import qualified Tile as T import qualified Tile.TileType as TT import qualified Attribute as A -- | Represent an effect to a target CTile. data Effect = Effect W.CTile EffectType deriving (Eq, Show) -- | All the possible effects generated by actions: data EffectType = ChangeInPositionAbove W.TileCoord -- ^ Change in position to get above something. | ChangeInPositionInside W.TileCoord -- ^ Change in position to get inside something. | OccupySameSpace W.TileCoord -- ^ Change in position to occupy the same space. | ChangeInHP Int -- ^ Change the HP by an Int. | Break -- ^ Break something. | Sprawl W.CTile -- ^ Hit something with force. | Sprawled W.CTile -- ^ Get sprawled by something. | NoEffect -- ^ No effect, Nothing. deriving (Eq, Show) -- | Returns the sprawl damage to the two -- tiles, who sprawled and who got sprawled. sprawlDamage :: T.Tile -> T.Tile -> (Int, Int) sprawlDamage _ _ = (-5, -5) -- | Retuns the type of an effect. effectType :: Effect -> EffectType effectType (Effect _ e) = e -- Handles an effect by changing the world state. -- WARNING : This function will be big, very big. onEffect :: W.WorldState -> Effect -> W.WorldState onEffect ws@(W.World s str tiles) (Effect t@(_, tile) (ChangeInPositionAbove c2)) = W.World s str $ (c2, T.Above tile (snd $ W.loadTile c2 ws)) : (W.deleteTile (W.loadTile c2 ws) $ W.deleteTile t tiles) onEffect ws@(W.World s str tiles) (Effect t@(_, tile) (ChangeInPositionInside c2)) = W.World s str $ (c2, T.Inside tile (snd $ W.loadTile c2 ws)) : (W.deleteTile (W.loadTile c2 ws) $ W.deleteTile t tiles) onEffect ws@(W.World s str tiles) (Effect t@(_, tile) (OccupySameSpace c2))= W.World s str $ (c2, T.Tiles tile (snd $ W.loadTile c2 ws)) : (W.deleteTile (W.loadTile c2 ws) $ W.deleteTile t tiles) onEffect (W.World s str tiles) (Effect t@(c, (T.Tile tt@(TT.TEntity _) a)) (ChangeInHP hp)) = W.World s str $ (c, T.Tile tt ((A.addHp (A.findSomeData a) hp) : (delete (A.findSomeData a) a))) : (W.deleteTile t tiles) onEffect (W.World s str tiles) (Effect t@(c, (T.Tiles (T.Tile tt@(TT.TEntity _) a) t2)) (ChangeInHP hp)) = W.World s str $ (c, T.Tiles (T.Tile tt ((A.addHp (A.findSomeData a) hp) : (delete (A.findSomeData a) a))) t2) : (W.deleteTile t tiles) onEffect (W.World s str tiles) (Effect t@(c, (T.Above (T.Tile tt@(TT.TEntity _) a) t2)) (ChangeInHP hp)) = W.World s str $ (c, T.Above (T.Tile tt ((A.addHp (A.findSomeData a) hp) : (delete (A.findSomeData a) a))) t2) : (W.deleteTile t tiles) onEffect (W.World s str tiles) (Effect t@(c, (T.Inside (T.Tile tt@(TT.TEntity _) a) t2)) (ChangeInHP hp)) = W.World s str $ (c, T.Inside (T.Tile tt ((A.addHp (A.findSomeData a) hp) : (delete (A.findSomeData a) a))) t2) : (W.deleteTile t tiles) onEffect ws (Effect _ (ChangeInHP _)) = ws onEffect (W.World s str tiles) (Effect t@(c, tile) Break) = W.World s str $ (c, T.mapAttribute (A.addAttribute A.Broke ) tile) : (W.deleteTile t tiles) onEffect (W.World s str tiles) (Effect t@(c, tile) (Sprawl (_, tile2))) = W.World s str $ (c, T.mapAttribute (\x -> A.addHp (A.findSomeData x) (fst $ sprawlDamage tile tile2) : (delete (A.findSomeData x) x)) tile) : (W.deleteTile t tiles) onEffect (W.World s str tiles) (Effect t@(c, tile) (Sprawled (_, tile2))) = W.World s str $ (c, T.mapAttribute (\x -> A.addHp (A.findSomeData x) (fst $ sprawlDamage tile2 tile) : (delete (A.findSomeData x) x)) tile) : (W.deleteTile t tiles) onEffect ws _ = ws --onEffect (W.World _ _ tiles) (Effect (x,y) ()) = undefined
Megaleo/Minehack
src/Effect.hs
bsd-3-clause
4,803
0
17
1,244
1,642
877
765
54
1
{- Data/Singletons/CustomStar.hs (c) Richard Eisenbeg 2012 eir@cis.upenn.edu This file implements singletonStar, which generates a datatype Rep and associated singleton from a list of types. The promoted version of Rep is kind * and the Haskell types themselves. This is still very experimental, so expect unusual results! -} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Data.Singletons.CustomStar where import Language.Haskell.TH import Data.Singletons.Util import Data.Singletons.Promote import Data.Singletons.Singletons import Control.Monad -- Produce a representation and singleton for the collection of types given singletonStar :: [Name] -> Q [Dec] singletonStar names = do kinds <- mapM getKind names ctors <- zipWithM (mkCtor True) names kinds let repDecl = DataD [] repName [] ctors [mkName "Eq", mkName "Show", mkName "Read"] fakeCtors <- zipWithM (mkCtor False) names kinds eqTypeInstances <- mapM mkEqTypeInstance [ (c1, c2) | c1 <- fakeCtors, c2 <- fakeCtors ] singletonDecls <- singDataD True [] repName [] fakeCtors [mkName "Eq", mkName "Show", mkName "Read"] return $ repDecl : eqTypeInstances ++ singletonDecls where -- get the kinds of the arguments to the tycon with the given name getKind :: Name -> Q [Kind] getKind name = do info <- reifyWithWarning name case info of TyConI (DataD (_:_) _ _ _ _) -> fail "Cannot make a representation of a constrainted data type" TyConI (DataD [] _ tvbs _ _) -> return $ map extractTvbKind tvbs TyConI (NewtypeD (_:_) _ _ _ _) -> fail "Cannot make a representation of a constrainted newtype" TyConI (NewtypeD [] _ tvbs _ _) -> return $ map extractTvbKind tvbs TyConI (TySynD _ tvbs _) -> return $ map extractTvbKind tvbs PrimTyConI _ n _ -> return $ replicate n StarT _ -> fail $ "Invalid thing for representation: " ++ (show name) -- first parameter is whether this is a real ctor (with a fresh name) -- or a fake ctor (when the name is actually a Haskell type) mkCtor :: Bool -> Name -> [Kind] -> Q Con mkCtor real name args = do (types, vars) <- evalForPair $ mapM kindToType args let ctor = NormalC ((if real then reinterpret else id) name) (map (\ty -> (NotStrict, ty)) types) if length vars > 0 then return $ ForallC (map PlainTV vars) [] ctor else return ctor -- demote a kind back to a type, accumulating any unbound parameters kindToType :: Kind -> QWithAux [Name] Type kindToType (ForallT _ _ _) = fail "Explicit forall encountered in kind" kindToType (AppT k1 k2) = do t1 <- kindToType k1 t2 <- kindToType k2 return $ AppT t1 t2 kindToType (SigT _ _) = fail "Sort signature encountered in kind" kindToType (VarT n) = do addElement n return $ VarT n kindToType (ConT n) = return $ ConT n kindToType (PromotedT _) = fail "Promoted type used as a kind" kindToType (TupleT n) = return $ TupleT n kindToType (UnboxedTupleT _) = fail "Unboxed tuple kind encountered" kindToType ArrowT = return ArrowT kindToType ListT = return ListT kindToType (PromotedTupleT _) = fail "Promoted tuple kind encountered" kindToType PromotedNilT = fail "Promoted nil kind encountered" kindToType PromotedConsT = fail "Promoted cons kind encountered" kindToType StarT = return $ ConT repName kindToType ConstraintT = fail $ "Cannot make a representation of a type that has " ++ "an argument of kind Constraint" kindToType (LitT _) = fail "Literal encountered at the kind level"
jonsterling/singletons
Data/Singletons/CustomStar.hs
bsd-3-clause
4,038
0
17
1,256
975
478
497
70
24
{-# LANGUAGE OverloadedStrings , ScopedTypeVariables , TemplateHaskell , TypeFamilies #-} module Test.Util where import Prelude.Compat import Data.Aeson hiding (Result) import Data.Aeson.Parser () import Data.Attoparsec.Lazy import Data.ByteString.Lazy (ByteString) import Data.ByteString.Lazy.Char8 (unpack) import Data.List.Compat (intersperse) import Data.Proxy.Compat import Test.Tasty.HUnit import qualified Data.Aeson.Parser as A import qualified Data.Aeson.Types as A import qualified Data.Vector as V import Data.JSON.Schema import Data.JSON.Schema.Validate -- | Serializes a value to an aeson Value and validates that against the type's schema valid :: forall a . (Show a, ToJSON a, FromJSON a, JSONSchema a) => a -> Assertion valid v = do case eitherDecode (encode v) of Left err -> error err Right r -> case V.toList $ validate sch r of [] -> assertBool "x" True errs -> assertFailure ("schema validation for " ++ show v ++ " value: " ++ show r ++ " schema: " ++ show sch ++ " errors: " ++ show errs) where sch = schema (Proxy :: Proxy a) encDec :: (FromJSON a, ToJSON a) => a -> Either String a encDec a = case (parse A.value . encode) a of Done _ r -> case fromJSON r of A.Success v -> Right v; Error s -> Left $ "fromJSON r=" ++ show r ++ ", s=" ++ s Fail _ ss e -> Left . concat $ intersperse "," (ss ++ [e]) unsafeParse :: ByteString -> Value unsafeParse b = fromResult . parse A.value $ b where fromResult (Done _ r) = r fromResult _ = error $ "unsafeParse failed on: " ++ unpack b eq :: (Show a, Eq a) => a -> a -> Assertion eq = (@=?) bidir :: (FromJSON a, ToJSON a, Show a, Eq a) => ByteString -> a -> IO () bidir s d = do eq (unsafeParse s) (toJSON d) eq (Right d) (encDec d)
silkapp/json-schema
tests/Test/Util.hs
bsd-3-clause
1,784
0
22
388
659
347
312
44
3
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE TypeInType #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} module MathFlow.PythonSpec where import GHC.TypeLits import Data.Proxy import Data.Singletons import Data.Singletons.TypeLits import Data.Singletons.TH import Data.Promotion.Prelude import MathFlow import MathFlow.TF import Test.Hspec import Test.Hspec.Server import Text.Shakespeare.Text import qualified Data.Text.Lazy as T import Data.Monoid import Control.Monad.IO.Class src = [lbt| |import tensorflow as tf |num1 = tf.constant(1) |num2 = tf.constant(2) |num3 = tf.constant(3) |num1PlusNum2 = tf.add(num1,num2) |num1PlusNum2PlusNum3 = tf.add(num1PlusNum2,num3) |sess = tf.Session() |result = sess.run(num1PlusNum2PlusNum3) |print(result) |] testNet :: Tensor '[1] Float PyString testNet = let n1 = "n1" <-- (Tensor "tf.constant(1)") :: Tensor '[1] Float PyString n2 = "n2" <-- (Tensor "tf.constant(2)") :: Tensor '[1] Float PyString n3 = "n3" <-- (Tensor "tf.constant(3)") :: Tensor '[1] Float PyString y = "y" <-- (n1 + n2 + n3) :: Tensor '[1] Float PyString in y testSub :: Tensor '[1] Float PyString testSub = let n1 = "n1" <-- (Tensor "tf.constant(100)") :: Tensor '[1] Float PyString n2 = "n2" <-- (Tensor "tf.constant(50)") :: Tensor '[1] Float PyString n3 = "n3" <-- (Tensor "tf.constant(2)") :: Tensor '[1] Float PyString y = "y" <-- (n3 * (n1 - n2)) :: Tensor '[1] Float PyString in y testMatMul :: Tensor '[2,1] Float PyString testMatMul = let n1 = "n1" <-- $(pyConst2 [[2],[3]]) :: Tensor '[2,1] Float PyString n2 = "n2" <-- $(pyConst2 [[2,0],[0,1]]) :: Tensor '[2,2] Float PyString y = "y" <-- (n2 %* n1) :: Tensor '[2,1] Float PyString in y testConcat :: Tensor '[2,2] Float PyString testConcat = let n1 = "n1" <-- (Tensor "tf.constant([[2],[3]])") :: Tensor '[2,1] Float PyString n2 = "n2" <-- (Tensor "tf.constant([[2],[3]])") :: Tensor '[2,1] Float PyString y = "y" <-- (TConcat n1 n2) :: Tensor '[2,2] Float PyString in y testReplicate :: Tensor '[2,2] Float PyString testReplicate = let n1 = "n1" <-- (Tensor "tf.constant([[2],[3]])") :: Tensor '[2,1] Float PyString n2 = "n2" <-- (Tensor "tf.constant([[2],[3]])") :: Tensor '[2,1] Float PyString y = "y" <-- (TConcat n1 n2) :: Tensor '[2,2] Float PyString in y #ifdef USE_PYTHON spec = do describe "run tensorflow" $ with localhost $ do it "command test" $ do command "python3" [] (T.unpack src) @>= exit 0 <> stdout "6\n" describe "run pystring" $ with localhost $ do it "abs" $ do let src = toRunnableString (fromTensor (abs' (Tensor "tf.constant(-100)" :: Tensor '[1] Float PyString) "\"x\"")) liftIO $ putStr src command "python3" [] src @>= exit 0 <> stdout "100\n" it "adder" $ do command "python3" [] (toRunnableString (fromTensor testNet)) @>= exit 0 <> stdout "6\n" it "subtract" $ do command "python3" [] (toRunnableString (fromTensor testSub)) @>= exit 0 <> stdout "100\n" it "matmul" $ do let src = toRunnableString (fromTensor testMatMul) command "python3" [] src @>= exit 0 <> stdout "[[4]\n [3]]\n" it "concat" $ do let src = toRunnableString (fromTensor testConcat) liftIO $ putStr src command "python3" [] src @>= exit 0 <> stdout "[[2 2]\n [3 3]]\n" #else spec :: Spec spec = return () #endif
junjihashimoto/mathflow
test/MathFlow/PythonSpec.hs
bsd-3-clause
3,896
0
24
850
1,239
649
590
-1
-1
-- | A program to sanitize an HTML tag to a Haskell function. -- module Util.Sanitize ( sanitize , keywords , prelude ) where import Data.Char (toLower, toUpper) import Data.Set (Set) import qualified Data.Set as S -- | Sanitize a tag. This function returns a name that can be used as -- combinator in haskell source code. -- -- Examples: -- -- > sanitize "class" == "class_" -- > sanitize "http-equiv" == "httpEquiv" -- sanitize :: String -> String sanitize = appendUnderscore . removeDash . map toLower where -- Remove a dash, replacing it by camelcase notation -- -- Example: -- -- > removeDash "foo-bar" == "fooBar" -- removeDash ('-' : x : xs) = toUpper x : removeDash xs removeDash (x : xs) = x : removeDash xs removeDash [] = [] appendUnderscore t | t `S.member` keywords = t ++ "_" | otherwise = t -- | A set of standard Haskell keywords, which cannot be used as combinators. -- keywords :: Set String keywords = S.fromList [ "case", "class", "data", "default", "deriving", "do", "else", "if" , "import", "in", "infix", "infixl", "infixr", "instance" , "let", "module" , "newtype", "of", "then", "type", "where" ] -- | Set of functions from the Prelude, which we do not use as combinators. -- prelude :: Set String prelude = S.fromList [ "abs", "acos", "acosh", "all", "and", "any", "appendFile", "asTypeOf" , "asin", "asinh", "atan", "atan2", "atanh", "break", "catch", "ceiling" , "compare", "concat", "concatMap", "const", "cos", "cosh", "curry", "cycle" , "decodeFloat", "div", "divMod", "drop", "dropWhile", "either", "elem" , "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo", "enumFromTo" , "error", "even", "exp", "exponent", "fail", "filter", "flip" , "floatDigits", "floatRadix", "floatRange", "floor", "fmap", "foldl" , "foldl1", "foldr", "foldr1", "fromEnum", "fromInteger", "fromIntegral" , "fromRational", "fst", "gcd", "getChar", "getContents", "getLine", "head" , "id", "init", "interact", "ioError", "isDenormalized", "isIEEE" , "isInfinite", "isNaN", "isNegativeZero", "iterate", "last", "lcm" , "length", "lex", "lines", "log", "logBase", "lookup", "map", "mapM" , "mapM_", "max", "maxBound", "maximum", "maybe", "min", "minBound" , "minimum", "mod", "negate", "not", "notElem", "null", "odd", "or" , "otherwise", "pi", "pred", "print", "product", "properFraction", "putChar" , "putStr", "putStrLn", "quot", "quotRem", "read", "readFile", "readIO" , "readList", "readLn", "readParen", "reads", "readsPrec", "realToFrac" , "recip", "rem", "repeat", "replicate", "return", "reverse", "round" , "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq", "sequence" , "sequence_", "show", "showChar", "showList", "showParen", "showString" , "shows", "showsPrec", "significand", "signum", "sin", "sinh", "snd" , "span", "splitAt", "sqrt", "subtract", "succ", "sum", "tail", "take" , "takeWhile", "tan", "tanh", "toEnum", "toInteger", "toRational" , "truncate", "uncurry", "undefined", "unlines", "until", "unwords", "unzip" , "unzip3", "userError", "words", "writeFile", "zip", "zip3", "zipWith" , "zipWith3" ]
jgm/blaze-html
Util/Sanitize.hs
bsd-3-clause
3,265
0
10
640
811
519
292
47
3
module Main where import qualified Test.Framework as TF import qualified Test.Framework.Providers.HUnit as TFH import qualified Test.HUnit as TH import Syntax import qualified MLexer import qualified MParser import Id import qualified Type main :: IO () main = TF.defaultMain tests exprOfString :: String -> Syntax exprOfString str = let toks = MLexer.lex str exprOrErr = MParser.parse toks in case exprOrErr of Right x -> x Left _ -> error $ "no parse: " ++ str testEq :: (Eq a, Show a) => String -> a -> a -> TF.Test testEq msg actual expected = TFH.testCase msg (TH.assertEqual msg expected actual) checkInvalidExpr :: String -> String -> TF.Test checkInvalidExpr name str = TFH.testCase name $ TH.assertBool "failure expected" $ let toks = MLexer.lex str exprOrErr = MParser.parse toks in case exprOrErr of Right _ -> False Left _ -> True tests :: [TF.Test] tests = [testOpPrecedence, testLet, testApp, testCmp] testOpPrecedence :: TF.Test testOpPrecedence = TF.testGroup "op_precedence" [ testEq "op_precedence1" (exprOfString "(1+2) *. (3 *. 4 + 5 *. 6)") (FloatBin FMul (ArithBin Add (Int 1) (Int 2)) (ArithBin Add (FloatBin FMul (Int 3) (Int 4)) (FloatBin FMul (Int 5) (Int 6)))) , testEq "op_precedence2" (exprOfString "2*.5+3*.4") (ArithBin Add (FloatBin FMul (Int 2) (Int 5)) (FloatBin FMul (Int 3) (Int 4))) , testEq "op_precedence3" (exprOfString "let x = 3 in x + 4") (Let (Id "x") Type.genType (Int 3) (ArithBin Add (Var (Id "x")) (Int 4))) ] testLet :: TF.Test testLet = TF.testGroup "let" [ testEq "let1" (exprOfString "let x = 39 in x") (Let (Id "x") Type.genType (Int 39) (Var (Id "x"))) , testEq "let2" (exprOfString "38; 4") (Let (Id "") Type.TUnit (Int 38) (Int 4)) ] testApp :: TF.Test testApp = TF.testGroup "app" [ testEq "app1" (exprOfString "let x = () in x x") (Let (Id "x") Type.genType Unit (App (Var (Id "x")) [Var (Id "x")])) ] testCmp :: TF.Test testCmp = TF.testGroup "comparison" [ testEq "comparison1" (exprOfString "3 < 4") (Not (Cmp LE (Int 4) (Int 3))) , testEq "comparison2" (exprOfString "3 > 4") (Not (Cmp LE (Int 3) (Int 4))) , testEq "comparison3" (exprOfString "3 <= 4") (Cmp LE (Int 3) (Int 4)) , testEq "comparison4" (exprOfString "3 >= 4") (Cmp LE (Int 4) (Int 3)) , testEq "comparison5" (exprOfString "3 <> 4") (Not (Cmp Eq (Int 3) (Int 4))) , testEq "comparison6" (exprOfString "3 = 4") (Cmp Eq (Int 3) (Int 4)) ] testTuple :: TF.Test testTuple = TF.testGroup "tuple" [ testEq "tuple1" (exprOfString "3, 4") (Tuple [Int 3, Int 4]) , testEq "tuple2" (exprOfString "(3, 4, 8)") (Tuple [Int 3, Int 4, Int 8]) , testEq "tuple3" (exprOfString "3, (4, 8)") (Tuple [Int 3, Tuple [Int 4, Int 8]]) ]
koba-e964/hayashii-mcc
test/ParserTest.hs
bsd-3-clause
2,728
0
15
530
1,197
613
584
54
2
module Main where import Test.DocTest --import Test.QuickCheck main :: IO () main = doctest [ "src/Scheme/DataType.hs" ]
ocean0yohsuke/Scheme
test/doctests.hs
bsd-3-clause
138
0
6
34
31
18
13
4
1
{-# LANGUAGE PatternSynonyms, TemplateHaskell, TypeOperators, TypeFamilies, CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Units.CGS -- Copyright : (C) 2014 Richard Eisenberg -- License : BSD-style (see LICENSE) -- Maintainer : Richard Eisenberg (rae@cs.brynmawr.edu) -- Stability : experimental -- Portability : non-portable -- -- This module defines units used in the centimeter\/gram\/second system -- of measurement. -- -- Included are all mechanical units mentioned here: -- <http://en.wikipedia.org/wiki/Centimetre%E2%80%93gram%E2%80%93second_system_of_units> -- -- Some electromagnetic units are not included, because these do not have -- reliable conversions to\/from the SI units, on which the @units-defs@ -- edifice is based. ----------------------------------------------------------------------------- module Data.Units.CGS ( Centi(..), centi, Meter(..), pattern Metre, Gram(..), Second(..), module Data.Units.CGS ) where import Data.Units.SI import Data.Units.SI.Prefixes import Data.Metrology.Poly import Data.Metrology.TH type Centimeter = Centi :@ Meter #if __GLASGOW_HASKELL__ >= 710 pattern Centimeter :: Centimeter #endif pattern Centimeter = Centi :@ Meter type Centimetre = Centimeter #if __GLASGOW_HASKELL__ >= 710 pattern Centimetre :: Centimetre #endif pattern Centimetre = Centimeter declareDerivedUnit "Gal" [t| Centimeter :/ Second :^ Two |] 1 (Just "Gal") declareDerivedUnit "Dyne" [t| Gram :* Centimeter :/ Second :^ Two |] 1 (Just "dyn") declareDerivedUnit "Erg" [t| Gram :* Centimeter :^ Two :/ Second :^ Two |] 1 (Just "erg") declareDerivedUnit "Barye" [t| Gram :/ (Centimeter :* Second :^ Two) |] 1 (Just "Ba") declareDerivedUnit "Poise" [t| Gram :/ (Centimeter :* Second) |] 1 (Just "P") declareDerivedUnit "Stokes" [t| Centimeter :^ Two :/ Second |] 1 (Just "St") declareDerivedUnit "Kayser" [t| Centimeter :^ MOne |] 1 Nothing declareDerivedUnit "Maxwell" [t| Nano :@ Weber |] 10 (Just "Mx") declareDerivedUnit "Gauss" [t| Milli :@ Tesla |] 0.1 (Just "G")
goldfirere/units
units-defs/Data/Units/CGS.hs
bsd-3-clause
2,198
0
7
409
343
210
133
29
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-| This module provides leak-free and referentially transparent higher-order discrete signals. -} module FRP.Elerea.Simple ( -- * The signal abstraction Signal , SignalGen -- * Embedding into I/O , start , external , externalMulti -- * Basic building blocks , delay , snapshot , generator , memo , until -- * Derived combinators , stateful , transfer , transfer2 , transfer3 , transfer4 -- * Signals with side effects -- $effectful , execute , effectful , effectful1 , effectful2 , effectful3 , effectful4 -- * A longer example -- $example ) where import Control.Applicative import Control.Concurrent.MVar import Control.Monad import Control.Monad.Base import Control.Monad.Fix import Control.Monad.IO.Class import Data.IORef import Data.Maybe import Prelude hiding (until) import System.Mem.Weak -- | A signal represents a value changing over time. It can be -- thought of as a function of type @Nat -> a@, where the argument is -- the sampling time, and the 'Monad' instance agrees with the -- intuition (bind corresponds to extracting the current sample). -- Signals and the values they carry are denoted the following way in -- the documentation: -- -- > s = <<s0 s1 s2 ...>> -- -- This says that @s@ is a signal that reads @s0@ during the first -- sampling, @s1@ during the second and so on. You can also think of -- @s@ as the following function: -- -- > s t_sample = [s0,s1,s2,...] !! t_sample -- -- Signals are constrained to be sampled sequentially, there is no -- random access. The only way to observe their output is through -- 'start'. newtype Signal a = S (IO a) deriving (Functor, Applicative, Monad) -- | A dynamic set of actions to update a network without breaking -- consistency. type UpdatePool = [Weak (IO (), IO ())] -- | A signal generator is the only source of stateful signals. It -- can be thought of as a function of type @Nat -> a@, where the -- result is an arbitrary data structure that can potentially contain -- new signals, and the argument is the creation time of these new -- signals. It exposes the 'MonadFix' interface, which makes it -- possible to define signals in terms of each other. The denotation -- of signal generators happens to be the same as that of signals, but -- this partly accidental (it does not hold in the other variants), so -- we will use a separate notation for generators: -- -- > g = <|g0 g1 g2 ...|> -- -- Just like signals, generators behave as functions of time: -- -- > g t_start = [g0,g1,g2,...] !! t_start -- -- The conceptual difference between the two notions is that signals -- are passed a sampling time, while generators expect a start time -- that will be the creation time of all the freshly generated -- signals in the resulting structure. newtype SignalGen a = SG { unSG :: IORef UpdatePool -> IO a } -- | The phases every signal goes through during a superstep. data Phase a = Ready a | Updated a a instance Functor SignalGen where fmap = liftM instance Applicative SignalGen where pure = return (<*>) = ap instance Monad SignalGen where return x = SG $ \_ -> return x SG g >>= f = SG $ \p -> g p >>= \x -> unSG (f x) p instance MonadFix SignalGen where mfix f = SG $ \p -> mfix $ \x -> unSG (f x) p instance MonadIO SignalGen where liftIO = execute instance MonadBase SignalGen SignalGen where liftBase = id -- | Embedding a signal into an 'IO' environment. Repeated calls to -- the computation returned cause the whole network to be updated, and -- the current sample of the top-level signal is produced as a -- result. This is the only way to extract a signal generator outside -- the network, and it is equivalent to passing zero to the function -- representing the generator. In general: -- -- > replicateM n =<< start <|<<x0 x1 x2 x3 ...>> ...|> == take n [x0,x1,x2,x3,...] -- -- Example: -- -- > do -- > smp <- start (stateful 3 (+2)) -- > res <- replicateM 5 smp -- > print res -- -- Output: -- -- > [3,5,7,9,11] start :: SignalGen (Signal a) -- ^ the generator of the top-level signal -> IO (IO a) -- ^ the computation to sample the signal start (SG gen) = do pool <- newIORef [] S sample <- gen pool return $ do res <- sample superstep pool return res -- | Performing the two-phase superstep. superstep :: IORef UpdatePool -> IO () superstep pool = loop id [] where deref ptr = (fmap.fmap) ((,) ptr) (deRefWeak ptr) loop getPtrs final = do (ptrs,acts) <- unzip.catMaybes <$> (mapM deref =<< readIORef pool) case acts of [] -> do sequence_ final writeIORef pool (getPtrs []) _ -> do writeIORef pool [] mapM_ fst acts loop ((ptrs++) . getPtrs) (mapM_ snd acts : final) -- | Auxiliary function used by all the primitives that create a -- mutable variable. addSignal :: (a -> IO a) -- ^ sampling function -> (a -> IO ()) -- ^ aging function -> IORef (Phase a) -- ^ the mutable variable behind the signal -> IORef UpdatePool -- ^ the pool of update actions -> IO (Signal a) -- ^ the signal created addSignal sample update ref pool = do let upd = readIORef ref >>= \v -> case v of Ready x -> update x _ -> return () fin = readIORef ref >>= \v -> case v of Updated x _ -> writeIORef ref $! Ready x _ -> error "Signal not updated!" sig = S $ readIORef ref >>= \v -> case v of Ready x -> sample x Updated _ x -> return x {-# NOINLINE sig #-} -- NOINLINE to prevent sig from getting inlined into the -- argument position of mkWeak. updateActions <- mkWeak sig (upd,fin) Nothing modifyIORef pool (updateActions:) return sig -- | The 'delay' combinator is the elementary building block for -- adding state to the signal network by constructing delayed versions -- of a signal that emit a given value at creation time and the -- previous output of the signal afterwards (@--@ is undefined): -- -- > delay x0 s = <| <<x0 s0 s1 s2 s3 ...>> -- > <<-- x0 s1 s2 s3 ...>> -- > <<-- -- x0 s2 s3 ...>> -- > <<-- -- -- x0 s3 ...>> -- > ... -- > |> -- -- It can be thought of as the following function (which should also -- make it clear why the return value is 'SignalGen'): -- -- > delay x0 s t_start t_sample -- > | t_start == t_sample = x0 -- > | t_start < t_sample = s (t_sample-1) -- > | otherwise = error \"Premature sample!\" -- -- The way signal generators are extracted by 'generator' ensures that -- the error can never happen. -- -- Example (requires the @DoRec@ extension): -- -- > do -- > smp <- start $ do -- > rec let fib'' = liftA2 (+) fib' fib -- > fib' <- delay 1 fib'' -- > fib <- delay 1 fib' -- > return fib -- > res <- replicateM 7 smp -- > print res -- -- Output: -- -- > [1,1,2,3,5,8,13] delay :: a -- ^ initial output at creation time -> Signal a -- ^ the signal to delay -> SignalGen (Signal a) -- ^ the delayed signal delay x0 (S s) = SG $ \pool -> do ref <- newIORef (Ready x0) let update x = s >>= \x' -> x' `seq` writeIORef ref (Updated x' x) addSignal return update ref pool -- | A formal conversion from signals to signal generators, which -- effectively allows for retrieving the current value of a previously -- created signal within a generator. This includes both signals -- defined in an external scope as well as those created earlier in -- the same generator. In the model, it corresponds to the identity -- function. snapshot :: Signal a -> SignalGen a snapshot (S s) = SG $ \_ -> s -- | Auxiliary function. memoise :: IORef (Phase a) -> a -> IO a memoise ref x = writeIORef ref (Updated undefined x) >> return x -- | A reactive signal that takes the value to output from a signal -- generator carried by its input with the sampling time provided as -- the start time for the generated structure. It is possible to -- create new signals in the monad, which is the key to defining -- dynamic data-flow networks. -- -- > generator << <|x00 x01 x02 ...|> -- > <|x10 x11 x12 ...|> -- > <|x20 x21 x22 ...|> -- > ... -- > >> = <| <<x00 x11 x22 ...>> -- > <<x00 x11 x22 ...>> -- > <<x00 x11 x22 ...>> -- > ... -- > |> -- -- It can be thought of as the following function: -- -- > generator g t_start t_sample = g t_sample t_sample -- -- It has to live in the 'SignalGen' monad, because it needs to -- maintain an internal state to be able to cache the current sample -- for efficiency reasons. However, this state is not carried between -- samples, therefore start time doesn't matter and can be ignored. -- -- Refer to the longer example at the bottom to see how it can be -- used. generator :: Signal (SignalGen a) -- ^ the signal of generators to run -> SignalGen (Signal a) -- ^ the signal of generated structures generator (S s) = SG $ \pool -> do ref <- newIORef (Ready undefined) let sample = (s >>= \(SG g) -> g pool) >>= memoise ref addSignal (const sample) (const (() <$ sample)) ref pool -- | Memoising combinator. It can be used to cache results of -- applicative combinators in case they are used in several places. -- It is observationally equivalent to 'return' in the 'SignalGen' -- monad. -- -- > memo s = <|s s s s ...|> -- -- For instance, if @s = f \<$\> s'@, then @f@ will be recalculated -- once for each sampling of @s@. This can be avoided by writing @s -- \<- memo (f \<$\> s')@ instead. However, 'memo' incurs a small -- overhead, therefore it should not be used blindly. -- -- All the functions defined in this module return memoised signals. memo :: Signal a -- ^ the signal to cache -> SignalGen (Signal a) -- ^ a signal observationally equivalent to the argument memo (S s) = SG $ \pool -> do ref <- newIORef (Ready undefined) let sample = s >>= memoise ref addSignal (const sample) (const (() <$ sample)) ref pool -- | A signal that is true exactly once: the first time the input -- signal is true. Afterwards, it is constantly false, and it holds -- no reference to the input signal. For instance (assuming the rest -- of the input is constantly @False@): -- -- > until <<False False True True False True ...>> = -- > <| <<False False True False False False False False False False ...>> -- > << --- False True False False False False False False False ...>> -- > << --- --- True False False False False False False False ...>> -- > << --- --- --- True False False False False False False ...>> -- > << --- --- --- --- False True False False False False ...>> -- > << --- --- --- --- --- True False False False False ...>> -- > << --- --- --- --- --- --- False False False False ...>> -- > ... -- > |> -- -- It is observationally equivalent to the following expression (which -- would hold onto @s@ forever): -- -- > until s = do -- > step <- transfer False (||) s -- > dstep <- delay False step -- > memo (liftA2 (/=) step dstep) -- -- Example: -- -- > do -- > smp <- start $ do -- > cnt <- stateful 0 (+1) -- > tick <- until ((>=3) <$> cnt) -- > return $ liftA2 (,) cnt tick -- > res <- replicateM 6 smp -- > print res -- -- Output: -- -- > [(0,False),(1,False),(2,False),(3,True),(4,False),(5,False)] until :: Signal Bool -- ^ the boolean input signal -> SignalGen (Signal Bool) -- ^ a one-shot signal true only the first time the input is true until (S s) = SG $ \pool -> do ref <- newIORef (Ready undefined) rsmp <- mfix $ \rs -> newIORef $ do x <- s writeIORef ref (Updated undefined x) when x $ writeIORef rs $ do writeIORef ref (Updated undefined False) return False return x let sample = join (readIORef rsmp) addSignal (const sample) (const (() <$ sample)) ref pool -- | A signal that can be directly fed through the sink function -- returned. This can be used to attach the network to the outer -- world. The signal always yields the value last written to the -- sink. In other words, if the sink is written less frequently than -- the network sampled, the output remains the same during several -- samples. If values are pushed in the sink more frequently, only -- the last one before sampling is visible on the output. -- -- Example: -- -- > do -- > (sig,snk) <- external 4 -- > smp <- start (return sig) -- > r1 <- smp -- > r2 <- smp -- > snk 7 -- > r3 <- smp -- > snk 9 -- > snk 2 -- > r4 <- smp -- > print [r1,r2,r3,r4] -- -- Output: -- -- > [4,4,7,2] external :: a -- ^ initial value -> IO (Signal a, a -> IO ()) -- ^ the signal and an IO function to feed it external x = do ref <- newIORef x return (S (readIORef ref), writeIORef ref) -- | An event-like signal that can be fed through the sink function -- returned. The signal carries a list of values fed in since the -- last sampling, i.e. it is constantly @[]@ if the sink is never -- invoked. The order of elements is reversed, so the last value -- passed to the sink is the head of the list. Note that unlike -- 'external' this function only returns a generator to be used within -- the expression constructing the top-level stream, and this -- generator can only be used once. -- -- Example: -- -- > do -- > (gen,snk) <- externalMulti -- > smp <- start gen -- > r1 <- smp -- > snk 7 -- > r2 <- smp -- > r3 <- smp -- > snk 9 -- > snk 2 -- > r4 <- smp -- > print [r1,r2,r3,r4] -- -- Output: -- -- > [[],[7],[],[2,9]] externalMulti :: IO (SignalGen (Signal [a]), a -> IO ()) -- ^ a generator for the event signal and the associated sink externalMulti = do var <- newMVar [] return (SG $ \pool -> do ref <- newIORef (Ready undefined) let sample = modifyMVar var $ \list -> memoise ref list >> return ([], list) addSignal (const sample) (const (() <$ sample)) ref pool ,\val -> do vals <- takeMVar var putMVar var (val:vals) ) -- | A pure stateful signal. The initial state is the first output, -- and every subsequent state is derived from the preceding one by -- applying a pure transformation. -- -- Example: -- -- > do -- > smp <- start (stateful "x" ('x':)) -- > res <- replicateM 5 smp -- > print res -- -- Output: -- -- > ["x","xx","xxx","xxxx","xxxxx"] stateful :: a -- ^ initial state -> (a -> a) -- ^ state transformation -> SignalGen (Signal a) stateful x0 f = mfix $ \sig -> delay x0 (f <$> sig) -- | A stateful transfer function. The current input affects the -- current output, i.e. the initial state given in the first argument -- is considered to appear before the first output, and can never be -- observed, and subsequent states are determined by combining the -- preceding state with the current output of the input signal using -- the function supplied. -- -- Example: -- -- > do -- > smp <- start $ do -- > cnt <- stateful 1 (+1) -- > transfer 10 (+) cnt -- > res <- replicateM 5 smp -- > print res -- -- Output: -- -- > [11,13,16,20,25] transfer :: a -- ^ initial internal state -> (t -> a -> a) -- ^ state updater function -> Signal t -- ^ input signal -> SignalGen (Signal a) transfer x0 f s = mfix $ \sig -> do sig' <- delay x0 sig memo (liftA2 f s sig') -- | A variation of 'transfer' with two input signals. transfer2 :: a -- ^ initial internal state -> (t1 -> t2 -> a -> a) -- ^ state updater function -> Signal t1 -- ^ input signal 1 -> Signal t2 -- ^ input signal 2 -> SignalGen (Signal a) transfer2 x0 f s1 s2 = mfix $ \sig -> do sig' <- delay x0 sig memo (liftA3 f s1 s2 sig') -- | A variation of 'transfer' with three input signals. transfer3 :: a -- ^ initial internal state -> (t1 -> t2 -> t3 -> a -> a) -- ^ state updater function -> Signal t1 -- ^ input signal 1 -> Signal t2 -- ^ input signal 2 -> Signal t3 -- ^ input signal 3 -> SignalGen (Signal a) transfer3 x0 f s1 s2 s3 = mfix $ \sig -> do sig' <- delay x0 sig memo (liftM4 f s1 s2 s3 sig') -- | A variation of 'transfer' with four input signals. transfer4 :: a -- ^ initial internal state -> (t1 -> t2 -> t3 -> t4 -> a -> a) -- ^ state updater function -> Signal t1 -- ^ input signal 1 -> Signal t2 -- ^ input signal 2 -> Signal t3 -- ^ input signal 3 -> Signal t4 -- ^ input signal 4 -> SignalGen (Signal a) transfer4 x0 f s1 s2 s3 s4 = mfix $ \sig -> do sig' <- delay x0 sig memo (liftM5 f s1 s2 s3 s4 sig') {- $effectful The following combinators are primarily aimed at library implementors who wish build abstractions to effectful libraries on top of Elerea. -} -- | An IO action executed in the 'SignalGen' monad. Can be used as -- `liftIO`. execute :: IO a -> SignalGen a execute act = SG $ \_ -> act -- | A signal that executes a given IO action once at every sampling. -- -- In essence, this combinator provides cooperative multitasking -- capabilities, and its primary purpose is to assist library writers -- in wrapping effectful APIs as conceptually pure signals. If there -- are several effectful signals in the system, their order of -- execution is undefined and should not be relied on. -- -- Example: -- -- > do -- > smp <- start $ do -- > ref <- execute $ newIORef 0 -- > effectful $ do -- > x <- readIORef ref -- > putStrLn $ "Count: " ++ show x -- > writeIORef ref $! x+1 -- > return () -- > replicateM_ 5 smp -- -- Output: -- -- > Count: 0 -- > Count: 1 -- > Count: 2 -- > Count: 3 -- > Count: 4 -- -- Another example (requires mersenne-random): -- -- > do -- > smp <- start $ effectful randomIO :: IO (IO Double) -- > res <- replicateM 5 smp -- > print res -- -- Output: -- -- > [0.12067753390401374,0.8658877349182655,0.7159264443196786,0.1756941896012891,0.9513646060896676] effectful :: IO a -- ^ the action to be executed repeatedly -> SignalGen (Signal a) effectful act = SG $ \pool -> do ref <- newIORef (Ready undefined) let sample = act >>= memoise ref addSignal (const sample) (const (() <$ sample)) ref pool -- | A signal that executes a parametric IO action once at every -- sampling. The parameter is supplied by another signal at every -- sampling step. effectful1 :: (t -> IO a) -- ^ the action to be executed repeatedly -> Signal t -- ^ parameter signal -> SignalGen (Signal a) effectful1 act (S s) = SG $ \pool -> do ref <- newIORef (Ready undefined) let sample = s >>= act >>= memoise ref addSignal (const sample) (const (() <$ sample)) ref pool -- | Like 'effectful1', but with two parameter signals. effectful2 :: (t1 -> t2 -> IO a) -- ^ the action to be executed repeatedly -> Signal t1 -- ^ parameter signal 1 -> Signal t2 -- ^ parameter signal 2 -> SignalGen (Signal a) effectful2 act (S s1) (S s2) = SG $ \pool -> do ref <- newIORef (Ready undefined) let sample = join (liftM2 act s1 s2) >>= memoise ref addSignal (const sample) (const (() <$ sample)) ref pool -- | Like 'effectful1', but with three parameter signals. effectful3 :: (t1 -> t2 -> t3 -> IO a) -- ^ the action to be executed repeatedly -> Signal t1 -- ^ parameter signal 1 -> Signal t2 -- ^ parameter signal 2 -> Signal t3 -- ^ parameter signal 3 -> SignalGen (Signal a) effectful3 act (S s1) (S s2) (S s3) = SG $ \pool -> do ref <- newIORef (Ready undefined) let sample = join (liftM3 act s1 s2 s3) >>= memoise ref addSignal (const sample) (const (() <$ sample)) ref pool -- | Like 'effectful1', but with four parameter signals. effectful4 :: (t1 -> t2 -> t3 -> t4 -> IO a) -- ^ the action to be executed repeatedly -> Signal t1 -- ^ parameter signal 1 -> Signal t2 -- ^ parameter signal 2 -> Signal t3 -- ^ parameter signal 3 -> Signal t4 -- ^ parameter signal 4 -> SignalGen (Signal a) effectful4 act (S s1) (S s2) (S s3) (S s4) = SG $ \pool -> do ref <- newIORef (Ready undefined) let sample = join (liftM4 act s1 s2 s3 s4) >>= memoise ref addSignal (const sample) (const (() <$ sample)) ref pool -- | The Show instance is only defined for the sake of Num... instance Show (Signal a) where showsPrec _ _ s = "<SIGNAL>" ++ s -- | Equality test is impossible. instance Eq (Signal a) where _ == _ = False -- | Error message for unimplemented instance functions. unimp :: String -> a unimp = error . ("Signal: "++) instance Ord t => Ord (Signal t) where compare = unimp "compare" min = liftA2 min max = liftA2 max instance Enum t => Enum (Signal t) where succ = fmap succ pred = fmap pred toEnum = pure . toEnum fromEnum = unimp "fromEnum" enumFrom = unimp "enumFrom" enumFromThen = unimp "enumFromThen" enumFromTo = unimp "enumFromTo" enumFromThenTo = unimp "enumFromThenTo" instance Bounded t => Bounded (Signal t) where minBound = pure minBound maxBound = pure maxBound instance Num t => Num (Signal t) where (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) signum = fmap signum abs = fmap abs negate = fmap negate fromInteger = pure . fromInteger instance Real t => Real (Signal t) where toRational = unimp "toRational" instance Integral t => Integral (Signal t) where quot = liftA2 quot rem = liftA2 rem div = liftA2 div mod = liftA2 mod quotRem a b = (fst <$> qrab,snd <$> qrab) where qrab = quotRem <$> a <*> b divMod a b = (fst <$> dmab,snd <$> dmab) where dmab = divMod <$> a <*> b toInteger = unimp "toInteger" instance Fractional t => Fractional (Signal t) where (/) = liftA2 (/) recip = fmap recip fromRational = pure . fromRational instance Floating t => Floating (Signal t) where pi = pure pi exp = fmap exp sqrt = fmap sqrt log = fmap log (**) = liftA2 (**) logBase = liftA2 logBase sin = fmap sin tan = fmap tan cos = fmap cos asin = fmap asin atan = fmap atan acos = fmap acos sinh = fmap sinh tanh = fmap tanh cosh = fmap cosh asinh = fmap asinh atanh = fmap atanh acosh = fmap acosh {- $example For a not entirely trivial example, let's create a dynamic collection of countdown timers, where each expired timer is removed from the collection. First of all, we'll need a simple tester function: @ sigtest gen = 'replicateM' 15 '=<<' 'start' gen @ We can try it with a trivial example: @ \> sigtest $ 'stateful' 2 (+3) [2,5,8,11,14,17,20,23,26,29,32,35,38,41,44,47] @ Our first definition will be a signal representing a simple named timer: @ countdown :: String -\> Int -\> SignalGen (Signal (String,Maybe Int)) countdown name t = do let tick prev = do { t \<- prev ; 'guard' (t \> 0) ; 'return' (t-1) } timer \<- 'stateful' (Just t) tick 'return' ((,) name '<$>' timer) @ Let's see if it works: @ \> sigtest $ countdown \"foo\" 4 [(\"foo\",Just 4),(\"foo\",Just 3),(\"foo\",Just 2),(\"foo\",Just 1),(\"foo\",Just 0), (\"foo\",Nothing),(\"foo\",Nothing),(\"foo\",Nothing),...] @ Next, we will define a timer source that takes a list of timer names, starting values and start times and creates a signal that delivers the list of new timers at every point: @ timerSource :: [(String, Int, Int)] -\> SignalGen (Signal [Signal (String, Maybe Int)]) timerSource ts = do let gen t = 'mapM' ('uncurry' countdown) newTimers where newTimers = [(n,v) | (n,v,st) \<- ts, st == t] cnt \<- 'stateful' 0 (+1) 'generator' (gen '<$>' cnt) @ Now we need to encapsulate the timer source signal in another signal expression that takes care of maintaining the list of live timers. Since working with dynamic collections is a recurring task, let's define a generic combinator that maintains a dynamic list of signals given a source and a test that tells from the output of each signal whether it should be kept. We can use @mdo@ expressions (a variant of @do@ expressions allowing forward references) as syntactic sugar for 'mfix' to make life easier: @ collection :: Signal [Signal a] -\> (a -\> Bool) -\> SignalGen (Signal [a]) collection source isAlive = mdo sig \<- 'delay' [] ('map' 'snd' '<$>' collWithVals') coll \<- 'memo' ('liftA2' (++) source sig) let collWithVals = 'zip' '<$>' ('sequence' '=<<' coll) '<*>' coll collWithVals' \<- 'memo' ('filter' (isAlive . 'fst') '<$>' collWithVals) 'return' $ 'map' 'fst' '<$>' collWithVals' @ We need recursion to define the @coll@ signal as a delayed version of its continuation, which does not contain signals that need to be removed in the current sample. At every point of time the running collection is concatenated with the source. We define @collWithVals@, which simply pairs up every signal with its current output. The output is obtained by extracting the current value of the signal container and sampling each element with 'sequence'. We can then derive @collWithVals'@, which contains only the signals that must be kept for the next round along with their output. Both @coll@ and @collWithVals'@ have to be memoised, because they are used more than once (the program would work without that, but it would recalculate both signals each time they are used). By throwing out the respective parts, we can get both the final output and the collection for the next step (@coll'@). Now we can easily finish the original task: @ timers :: [(String, Int, Int)] -\> SignalGen (Signal [(String, Int)]) timers timerData = do src \<- timerSource timerData getOutput '<$>' collection src ('isJust' . 'snd') where getOutput = 'fmap' ('map' (\\(name,Just val) -> (name,val))) @ As a test, we can start four timers: /a/ at t=0 with value 3, /b/ and /c/ at t=1 with values 5 and 3, and /d/ at t=3 with value 4: @ \> sigtest $ timers [(\"a\",3,0),(\"b\",5,1),(\"c\",3,1),(\"d\",4,3)] [[(\"a\",3)],[(\"b\",5),(\"c\",3),(\"a\",2)],[(\"b\",4),(\"c\",2),(\"a\",1)], [(\"d\",4),(\"b\",3),(\"c\",1),(\"a\",0)],[(\"d\",3),(\"b\",2),(\"c\",0)], [(\"d\",2),(\"b\",1)],[(\"d\",1),(\"b\",0)],[(\"d\",0)],[],[],[],[],[],[],[]] @ If the noise of the applicative lifting operators feels annoying, she (<http://personal.cis.strath.ac.uk/~conor/pub/she/>) comes to the save. Among other features it provides idiom brackets, which can substitute the explicit lifting. For instance, it allows us to define @collection@ this way: @ collection :: Stream [Stream a] -> (a -> Bool) -> StreamGen (Stream [a]) collection source isAlive = mdo sig \<- 'delay' [] (|'map' ~'snd' collWithVals'|) coll \<- 'memo' (|source ++ sig|) collWithVals' \<- 'memo' (|'filter' ~(isAlive . 'fst') (|'zip' ('sequence' '=<<' coll) coll|)|) 'return' (|'map' ~'fst' collWithVals'|) @ -}
cabrera/elerea
FRP/Elerea/Simple.hs
bsd-3-clause
28,044
0
21
7,456
4,306
2,327
1,979
289
4
module Main where import EC2Tests.VPCTests main :: IO () main = do runVpcTests
worksap-ate/aws-sdk
test/VPCTests.hs
bsd-3-clause
85
0
6
19
27
15
12
5
1
module Paths_hlint(version, getDataDir) where import Data.Version.Extra version :: Version version = makeVersion [0,0] getDataDir :: IO FilePath getDataDir = pure "data"
ndmitchell/hlint
src/Paths.hs
bsd-3-clause
174
0
6
25
53
31
22
6
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE IncoherentInstances #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Data.Vector.Image.Color.YUV ( YUV(..) ) where import Prelude hiding(map) import qualified Prelude as P import qualified Data.List as L import Data.Vector.Storable hiding(forM_,map,replicate,fromList,toList,(!?),(!)) import Data.Maybe import Numeric.LinearAlgebra.Data hiding (fromList,toList,(!)) import Numeric.LinearAlgebra.HMatrix hiding (fromList,toList,(!)) import qualified Data.Vector.Storable as V import Foreign import GHC.Real import Foreign.C.String import Foreign.C.Types import qualified Control.Monad as C import Data.Vector.Image.Color.RGB data YUV a = YUV { yuv_y :: a , yuv_u :: a , yuv_b :: a } deriving (Show,Eq,Ord) instance Functor YUV where fmap func (YUV r g b) = YUV (func r) (func g) (func b) rgb2yuv :: (Num a,Integral a) => RGB a -> YUV a rgb2yuv (RGB r g b) = YUV ((r+2*g+b)`div`4) (b-g) (r-g) yuv2rgb :: (Num a,Integral a) => YUV a -> RGB a yuv2rgb (YUV y u v) = RGB (v+g) g (u+g) where g = y - ((u + v)`div`4) instance (Num a,Integral a) => ColorSpace YUV a where toRGB = yuv2rgb fromRGB = rgb2yuv toList (YUV r g b) = [r,g,b] fromList [r,g,b] = (YUV r g b) fromList val = error $ "List length must be 3 but " L.++ show (L.length val) dim _ = 3
junjihashimoto/img-vector
Data/Vector/Image/Color/YUV.hs
bsd-3-clause
1,651
0
11
278
588
348
240
47
1
{-# LANGUAGE PatternGuards, StandaloneDeriving #-} -- | Duck primitive operation declarations module Prims ( module Gen.Prims , binopString , primString -- * Primitive datatypes , datatypeUnit , datatypeTuples , isDatatypeTuple , datatypeInt , datatypeChar , datatypeDelay , datatypeType , datatypeBool -- * Primitive types , typeUnit , typeArrow, isTypeArrow , typeClosure , typeTuple , typeInt , typeChar , typeType , typeBool , transType ) where import SrcLoc import Var import Memory import Type -- Pull in definitions of Binop and Prim import Gen.Prims -- Add instance declarations deriving instance Eq Binop deriving instance Ord Binop deriving instance Show Binop deriving instance Eq Prim deriving instance Ord Prim deriving instance Show Prim -- |Primitive datatypes datatypeTuples = datatypeUnit : error "no singleton tuples" : map dt [2..] where dt i = makeDatatype c noLoc vars (replicate i Covariant) $ DataAlgebraic [(L noLoc c, map TsVar vars)] where c = tupleCons vars vars = take i standardVars datatypeUnit = makeDatatype (V "()") noLoc [] [] $ DataAlgebraic [(L noLoc (V "()"), [])] datatypeInt = makeDatatype (V "Int") noLoc [] [] $ DataPrim wordSize -- TODO: change size? datatypeChar = makeDatatype (V "Char") noLoc [] [] $ DataPrim wordSize -- TODO: change size datatypeDelay = makeDatatype (V "Delay") noLoc [V "a"] [Covariant] $ DataPrim wordSize datatypeType = makeDatatype (V "Type") noLoc [V "t"] [Invariant] $ DataPrim 0 datatypeBool = makeDatatype (V "Bool") noLoc [] [] $ DataAlgebraic [(L noLoc (V "False"),[]), (L noLoc (V "True") ,[])] isDatatypeTuple :: Datatype -> Bool isDatatypeTuple = isTuple . dataName -- Type construction convenience functions typeC :: IsType t => Datatype -> t typeC c = typeCons c [] typeC1 :: IsType t => Datatype -> t -> t typeC1 c t = typeCons c [t] typeUnit :: IsType t => t typeUnit = typeC datatypeUnit typeArrow :: IsType t => t -> t -> t typeArrow s t = typeFun [FunArrow NoTrans s t] isTypeArrow :: TypePat -> Maybe (TypePat,TypePat) isTypeArrow t | Just [FunArrow NoTrans s t] <- unTypeFun t = Just (s,t) | otherwise = Nothing typeClosure :: IsType t => Var -> [t] -> t typeClosure f tl = typeFun [FunClosure f tl] typeTuple :: IsType t => [t] -> t typeTuple tl = typeCons (datatypeTuples !! length tl) tl typeInt :: IsType t => t typeInt = typeC datatypeInt typeChar :: IsType t => t typeChar = typeC datatypeChar typeType :: IsType t => t -> t typeType = typeC1 datatypeType typeBool :: IsType t => t typeBool = typeC datatypeBool -- |Converts an annotation argument type to the effective type of the argument within the function. transType :: IsType t => TransType t -> t transType (NoTrans, t) = t transType (Delay, t) = typeCons datatypeDelay [t] transType (Static, t) = t -- really TyStatic -- Pretty printing binopString :: Binop -> String binopString op = case op of IntAddOp -> "+" IntSubOp -> "-" IntMulOp -> "*" IntDivOp -> "/" IntEqOp -> "==" ChrEqOp -> "==" IntLTOp -> "<" IntGTOp -> ">" IntLEOp -> "<=" IntGEOp -> ">=" primString :: Prim -> String primString (Binop op) = binopString op primString p = show p
girving/duck
duck/Prims.hs
bsd-3-clause
3,269
0
11
699
1,086
566
520
89
10
{-# LANGUAGE OverloadedStrings #-} -- | Test suite. module Main where import Data.Foldable import Hell.Lexer import Hell.Types import Test.Hspec import qualified Text.Megaparsec as Mega main :: IO () main = hspec spec spec :: SpecWith () spec = lexer lexer :: SpecWith () lexer = describe "Lexer" (describe "Unquoted" (do it "Variable" (lexed "var letvar" [LowerWordToken "var", LowerWordToken "letvar"]) it "Number" (lexed "123" [NumberToken 123]) it "Symbols" (lexed "=[]()," [ EqualsToken , OpenBracketToken , CloseBracketToken , OpenParenToken , CloseParenToken , CommaToken ]) it "Quotation" (lexed "{ foo; bar }" [ QuoteBeginToken , QuotedToken "foo" , SemiToken , QuotedToken "bar" , QuoteEndToken ]) it "Quotation with variable splice" (lexed "{ foo; $bar }" [ QuoteBeginToken , QuotedToken "foo" , SemiToken , SpliceVarToken "bar" , QuoteEndToken ]) it "Quotation with code splice" (lexed "{ foo; ${bar} }" [ QuoteBeginToken , QuotedToken "foo" , SemiToken , SpliceBeginToken , LowerWordToken "bar" , SpliceEndToken , QuoteEndToken ]) it "Comments" (lexed "foo#bar\nmu" [LowerWordToken "foo", CommentToken "bar", LowerWordToken "mu"]))) where lexed i y = case Mega.runParser (lexUnquoted <* Mega.eof) "" i of Left e -> error (Mega.parseErrorPretty' i e) Right x -> shouldBe (map locatedThing (toList x)) y
chrisdone/hell
test/Main.hs
bsd-3-clause
2,163
0
15
1,039
417
215
202
69
2
-------------------------------------------------------------------- -- | -- Module : XMonad.Util.EZConfig -- Copyright : Devin Mullins <me@twifkak.com> -- Brent Yorgey <byorgey@gmail.com> (key parsing) -- License : BSD3-style (see LICENSE) -- -- Maintainer : Devin Mullins <me@twifkak.com> -- -- Useful helper functions for amending the defaultConfig, and for -- parsing keybindings specified in a special (emacs-like) format. -- -- (See also "XMonad.Util.CustomKeys" in xmonad-contrib.) -- -------------------------------------------------------------------- module XMonad.Util.EZConfig ( -- * Usage -- $usage -- * Adding or removing keybindings additionalKeys, additionalKeysP, removeKeys, removeKeysP, additionalMouseBindings, removeMouseBindings, -- * Emacs-style keybinding specifications mkKeymap, checkKeymap, mkNamedKeymap, parseKey -- used by XMonad.Util.Paste ) where import XMonad import XMonad.Actions.Submap import XMonad.Util.NamedActions import qualified Data.Map as M import Data.List (foldl', sortBy, groupBy, nub) import Data.Ord (comparing) import Data.Maybe import Control.Arrow (first, (&&&)) import Text.ParserCombinators.ReadP -- $usage -- To use this module, first import it into your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Util.EZConfig -- -- Then, use one of the provided functions to modify your -- configuration. You can use 'additionalKeys', 'removeKeys', -- 'additionalMouseBindings', and 'removeMouseBindings' to easily add -- and remove keybindings or mouse bindings. You can use 'mkKeymap' -- to create a keymap using emacs-style keybinding specifications -- like @\"M-x\"@ instead of @(modMask, xK_x)@, or 'additionalKeysP' -- and 'removeKeysP' to easily add or remove emacs-style keybindings. -- If you use emacs-style keybindings, the 'checkKeymap' function is -- provided, suitable for adding to your 'startupHook', which can warn -- you of any parse errors or duplicate bindings in your keymap. -- -- For more information and usage examples, see the documentation -- provided with each exported function, and check the xmonad config -- archive (<http://haskell.org/haskellwiki/Xmonad/Config_archive>) -- for some real examples of use. -- | -- Add or override keybindings from the existing set. Example use: -- -- > main = xmonad $ defaultConfig { terminal = "urxvt" } -- > `additionalKeys` -- > [ ((mod1Mask, xK_m ), spawn "echo 'Hi, mom!' | dzen2 -p 4") -- > , ((mod1Mask, xK_BackSpace), withFocused hide) -- N.B. this is an absurd thing to do -- > ] -- -- This overrides the previous definition of mod-m. -- -- Note that, unlike in xmonad 0.4 and previous, you can't use modMask to refer -- to the modMask you configured earlier. You must specify mod1Mask (or -- whichever), or add your own @myModMask = mod1Mask@ line. additionalKeys :: XConfig a -> [((ButtonMask, KeySym), X ())] -> XConfig a additionalKeys conf keyList = conf { keys = \cnf -> M.union (M.fromList keyList) (keys conf cnf) } -- | Like 'additionalKeys', except using short @String@ key -- descriptors like @\"M-m\"@ instead of @(modMask, xK_m)@, as -- described in the documentation for 'mkKeymap'. For example: -- -- > main = xmonad $ defaultConfig { terminal = "urxvt" } -- > `additionalKeysP` -- > [ ("M-m", spawn "echo 'Hi, mom!' | dzen2 -p 4") -- > , ("M-<Backspace>", withFocused hide) -- N.B. this is an absurd thing to do -- > ] additionalKeysP :: XConfig l -> [(String, X ())] -> XConfig l additionalKeysP conf keyList = conf { keys = \cnf -> M.union (mkKeymap cnf keyList) (keys conf cnf) } -- | -- Remove standard keybindings you're not using. Example use: -- -- > main = xmonad $ defaultConfig { terminal = "urxvt" } -- > `removeKeys` [(mod1Mask .|. shiftMask, n) | n <- [xK_1 .. xK_9]] removeKeys :: XConfig a -> [(ButtonMask, KeySym)] -> XConfig a removeKeys conf keyList = conf { keys = \cnf -> keys conf cnf `M.difference` M.fromList (zip keyList $ repeat ()) } -- | Like 'removeKeys', except using short @String@ key descriptors -- like @\"M-m\"@ instead of @(modMask, xK_m)@, as described in the -- documentation for 'mkKeymap'. For example: -- -- > main = xmonad $ defaultConfig { terminal = "urxvt" } -- > `removeKeysP` ["M-S-" ++ [n] | n <- ['1'..'9']] removeKeysP :: XConfig l -> [String] -> XConfig l removeKeysP conf keyList = conf { keys = \cnf -> keys conf cnf `M.difference` mkKeymap cnf (zip keyList $ repeat (return ())) } -- | Like 'additionalKeys', but for mouse bindings. additionalMouseBindings :: XConfig a -> [((ButtonMask, Button), Window -> X ())] -> XConfig a additionalMouseBindings conf mouseBindingsList = conf { mouseBindings = \cnf -> M.union (M.fromList mouseBindingsList) (mouseBindings conf cnf) } -- | Like 'removeKeys', but for mouse bindings. removeMouseBindings :: XConfig a -> [(ButtonMask, Button)] -> XConfig a removeMouseBindings conf mouseBindingList = conf { mouseBindings = \cnf -> mouseBindings conf cnf `M.difference` M.fromList (zip mouseBindingList $ return ()) } -------------------------------------------------------------- -- Keybinding parsing --------------------------------------- -------------------------------------------------------------- -- | Given a config (used to determine the proper modifier key to use) -- and a list of @(String, X ())@ pairs, create a key map by parsing -- the key sequence descriptions contained in the Strings. The key -- sequence descriptions are \"emacs-style\": @M-@, @C-@, @S-@, and -- @M\#-@ denote mod, control, shift, and mod1-mod5 (where @\#@ is -- replaced by the appropriate number) respectively. Note that if -- you want to make a keybinding using \'alt\' even though you use a -- different key (like the \'windows\' key) for \'mod\', you can use -- something like @\"M1-x\"@ for alt+x (check the output of @xmodmap@ -- to see which mod key \'alt\' is bound to). Some special keys can -- also be specified by enclosing their name in angle brackets. -- -- For example, @\"M-C-x\"@ denotes mod+ctrl+x; @\"S-\<Escape\>\"@ -- denotes shift-escape; @\"M1-C-\<Delete\>\"@ denotes alt+ctrl+delete -- (assuming alt is bound to mod1, which is common). -- -- Sequences of keys can also be specified by separating the key -- descriptions with spaces. For example, @\"M-x y \<Down\>\"@ denotes the -- sequence of keys mod+x, y, down. Submaps (see -- "XMonad.Actions.Submap") will be automatically generated to -- correctly handle these cases. -- -- So, for example, a complete key map might be specified as -- -- > keys = \c -> mkKeymap c $ -- > [ ("M-S-<Return>", spawn $ terminal c) -- > , ("M-x w", spawn "xmessage 'woohoo!'") -- type mod+x then w to pop up 'woohoo!' -- > , ("M-x y", spawn "xmessage 'yay!'") -- type mod+x then y to pop up 'yay!' -- > , ("M-S-c", kill) -- > ] -- -- Alternatively, you can use 'additionalKeysP' to automatically -- create a keymap and add it to your config. -- -- Here is a complete list of supported special keys. Note that a few -- keys, such as the arrow keys, have synonyms. If there are other -- special keys you would like to see supported, feel free to submit a -- patch, or ask on the xmonad mailing list; adding special keys is -- quite simple. -- -- > <Backspace> -- > <Tab> -- > <Return> -- > <Pause> -- > <Scroll_lock> -- > <Sys_Req> -- > <Print> -- > <Escape>, <Esc> -- > <Delete> -- > <Home> -- > <Left>, <L> -- > <Up>, <U> -- > <Right>, <R> -- > <Down>, <D> -- > <Page_Up> -- > <Page_Down> -- > <End> -- > <Insert> -- > <Break> -- > <Space> -- > <F1>-<F24> -- > <KP_Space> -- > <KP_Tab> -- > <KP_Enter> -- > <KP_F1> -- > <KP_F2> -- > <KP_F3> -- > <KP_F4> -- > <KP_Home> -- > <KP_Left> -- > <KP_Up> -- > <KP_Right> -- > <KP_Down> -- > <KP_Prior> -- > <KP_Page_Up> -- > <KP_Next> -- > <KP_Page_Down> -- > <KP_End> -- > <KP_Begin> -- > <KP_Insert> -- > <KP_Delete> -- > <KP_Equal> -- > <KP_Multiply> -- > <KP_Add> -- > <KP_Separator> -- > <KP_Subtract> -- > <KP_Decimal> -- > <KP_Divide> -- > <KP_0>-<KP_9> -- -- Long list of multimedia keys. Please note that not all keys may be -- present in your particular setup although most likely they will do. -- -- > <XF86ModeLock> -- > <XF86MonBrightnessUp> -- > <XF86MonBrightnessDown> -- > <XF86KbdLightOnOff> -- > <XF86KbdBrightnessUp> -- > <XF86KbdBrightnessDown> -- > <XF86Standby> -- > <XF86AudioLowerVolume> -- > <XF86AudioMute> -- > <XF86AudioRaiseVolume> -- > <XF86AudioPlay> -- > <XF86AudioStop> -- > <XF86AudioPrev> -- > <XF86AudioNext> -- > <XF86HomePage> -- > <XF86Mail> -- > <XF86Start> -- > <XF86Search> -- > <XF86AudioRecord> -- > <XF86Calculator> -- > <XF86Memo> -- > <XF86ToDoList> -- > <XF86Calendar> -- > <XF86PowerDown> -- > <XF86ContrastAdjust> -- > <XF86RockerUp> -- > <XF86RockerDown> -- > <XF86RockerEnter> -- > <XF86Back> -- > <XF86Forward> -- > <XF86Stop> -- > <XF86Refresh> -- > <XF86PowerOff> -- > <XF86WakeUp> -- > <XF86Eject> -- > <XF86ScreenSaver> -- > <XF86WWW> -- > <XF86Sleep> -- > <XF86Favorites> -- > <XF86AudioPause> -- > <XF86AudioMedia> -- > <XF86MyComputer> -- > <XF86VendorHome> -- > <XF86LightBulb> -- > <XF86Shop> -- > <XF86History> -- > <XF86OpenURL> -- > <XF86AddFavorite> -- > <XF86HotLinks> -- > <XF86BrightnessAdjust> -- > <XF86Finance> -- > <XF86Community> -- > <XF86AudioRewind> -- > <XF86XF86BackForward> -- > <XF86Launch0>-<XF86Launch9>, <XF86LaunchA>-<XF86LaunchF> -- > <XF86ApplicationLeft> -- > <XF86ApplicationRight> -- > <XF86Book> -- > <XF86CD> -- > <XF86Calculater> -- > <XF86Clear> -- > <XF86Close> -- > <XF86Copy> -- > <XF86Cut> -- > <XF86Display> -- > <XF86DOS> -- > <XF86Documents> -- > <XF86Excel> -- > <XF86Explorer> -- > <XF86Game> -- > <XF86Go> -- > <XF86iTouch> -- > <XF86LogOff> -- > <XF86Market> -- > <XF86Meeting> -- > <XF86MenuKB> -- > <XF86MenuPB> -- > <XF86MySites> -- > <XF86New> -- > <XF86News> -- > <XF86OfficeHome> -- > <XF86Open> -- > <XF86Option> -- > <XF86Paste> -- > <XF86Phone> -- > <XF86Q> -- > <XF86Reply> -- > <XF86Reload> -- > <XF86RotateWindows> -- > <XF86RotationPB> -- > <XF86RotationKB> -- > <XF86Save> -- > <XF86ScrollUp> -- > <XF86ScrollDown> -- > <XF86ScrollClick> -- > <XF86Send> -- > <XF86Spell> -- > <XF86SplitScreen> -- > <XF86Support> -- > <XF86TaskPane> -- > <XF86Terminal> -- > <XF86Tools> -- > <XF86Travel> -- > <XF86UserPB> -- > <XF86User1KB> -- > <XF86User2KB> -- > <XF86Video> -- > <XF86WheelButton> -- > <XF86Word> -- > <XF86Xfer> -- > <XF86ZoomIn> -- > <XF86ZoomOut> -- > <XF86Away> -- > <XF86Messenger> -- > <XF86WebCam> -- > <XF86MailForward> -- > <XF86Pictures> -- > <XF86Music> -- > <XF86_Switch_VT_1>-<XF86_Switch_VT_12> -- > <XF86_Ungrab> -- > <XF86_ClearGrab> -- > <XF86_Next_VMode> -- > <XF86_Prev_VMode> mkKeymap :: XConfig l -> [(String, X ())] -> M.Map (KeyMask, KeySym) (X ()) mkKeymap c = M.fromList . mkSubmaps . readKeymap c mkNamedKeymap :: XConfig l -> [(String, NamedAction)] -> [((KeyMask, KeySym), NamedAction)] mkNamedKeymap c = mkNamedSubmaps . readKeymap c -- | Given a list of pairs of parsed key sequences and actions, -- group them into submaps in the appropriate way. mkNamedSubmaps :: [([(KeyMask, KeySym)], NamedAction)] -> [((KeyMask, KeySym), NamedAction)] mkNamedSubmaps = mkSubmaps' submapName mkSubmaps :: [ ([(KeyMask,KeySym)], X ()) ] -> [((KeyMask, KeySym), X ())] mkSubmaps = mkSubmaps' $ submap . M.fromList mkSubmaps' :: (Ord a) => ([(a, c)] -> c) -> [([a], c)] -> [(a, c)] mkSubmaps' subm binds = map combine gathered where gathered = groupBy fstKey . sortBy (comparing fst) $ binds combine [([k],act)] = (k,act) combine ks = (head . fst . head $ ks, subm . mkSubmaps' subm $ map (first tail) ks) fstKey = (==) `on` (head . fst) on :: (a -> a -> b) -> (c -> a) -> c -> c -> b op `on` f = \x y -> f x `op` f y -- | Given a configuration record and a list of (key sequence -- description, action) pairs, parse the key sequences into lists of -- @(KeyMask,KeySym)@ pairs. Key sequences which fail to parse will -- be ignored. readKeymap :: XConfig l -> [(String, t)] -> [([(KeyMask, KeySym)], t)] readKeymap c = mapMaybe (maybeKeys . first (readKeySequence c)) where maybeKeys (Nothing,_) = Nothing maybeKeys (Just k, act) = Just (k, act) -- | Parse a sequence of keys, returning Nothing if there is -- a parse failure (no parse, or ambiguous parse). readKeySequence :: XConfig l -> String -> Maybe [(KeyMask, KeySym)] readKeySequence c = listToMaybe . parses where parses = map fst . filter (null.snd) . readP_to_S (parseKeySequence c) -- | Parse a sequence of key combinations separated by spaces, e.g. -- @\"M-c x C-S-2\"@ (mod+c, x, ctrl+shift+2). parseKeySequence :: XConfig l -> ReadP [(KeyMask, KeySym)] parseKeySequence c = sepBy1 (parseKeyCombo c) (many1 $ char ' ') -- | Parse a modifier-key combination such as "M-C-s" (mod+ctrl+s). parseKeyCombo :: XConfig l -> ReadP (KeyMask, KeySym) parseKeyCombo c = do mods <- many (parseModifier c) k <- parseKey return (foldl' (.|.) 0 mods, k) -- | Parse a modifier: either M- (user-defined mod-key), -- C- (control), S- (shift), or M#- where # is an integer -- from 1 to 5 (mod1Mask through mod5Mask). parseModifier :: XConfig l -> ReadP KeyMask parseModifier c = (string "M-" >> return (modMask c)) +++ (string "C-" >> return controlMask) +++ (string "S-" >> return shiftMask) +++ do char 'M' n <- satisfy (`elem` ['1'..'5']) char '-' return $ indexMod (read [n] - 1) where indexMod = (!!) [mod1Mask,mod2Mask,mod3Mask,mod4Mask,mod5Mask] -- | Parse an unmodified basic key, like @\"x\"@, @\"<F1>\"@, etc. parseKey :: ReadP KeySym parseKey = parseRegular +++ parseSpecial -- | Parse a regular key name (represented by itself). parseRegular :: ReadP KeySym parseRegular = choice [ char s >> return k | (s,k) <- zip ['!'..'~'] [xK_exclam..xK_asciitilde] ] -- | Parse a special key name (one enclosed in angle brackets). parseSpecial :: ReadP KeySym parseSpecial = do char '<' key <- choice [ string name >> return k | (name,k) <- keyNames ] char '>' return key -- | A list of all special key names and their associated KeySyms. keyNames :: [(String, KeySym)] keyNames = functionKeys ++ specialKeys ++ multimediaKeys -- | A list pairing function key descriptor strings (e.g. @\"<F2>\"@) with -- the associated KeySyms. functionKeys :: [(String, KeySym)] functionKeys = [ ('F' : show n, k) | (n,k) <- zip ([1..24] :: [Int]) [xK_F1..] ] -- | A list of special key names and their corresponding KeySyms. specialKeys :: [(String, KeySym)] specialKeys = [ ("Backspace" , xK_BackSpace) , ("Tab" , xK_Tab) , ("Return" , xK_Return) , ("Pause" , xK_Pause) , ("Scroll_lock", xK_Scroll_Lock) , ("Sys_Req" , xK_Sys_Req) , ("Print" , xK_Print) , ("Escape" , xK_Escape) , ("Esc" , xK_Escape) , ("Delete" , xK_Delete) , ("Home" , xK_Home) , ("Left" , xK_Left) , ("Up" , xK_Up) , ("Right" , xK_Right) , ("Down" , xK_Down) , ("L" , xK_Left) , ("U" , xK_Up) , ("R" , xK_Right) , ("D" , xK_Down) , ("Page_Up" , xK_Page_Up) , ("Page_Down" , xK_Page_Down) , ("End" , xK_End) , ("Insert" , xK_Insert) , ("Break" , xK_Break) , ("Space" , xK_space) , ("KP_Space" , xK_KP_Space) , ("KP_Tab" , xK_KP_Tab) , ("KP_Enter" , xK_KP_Enter) , ("KP_F1" , xK_KP_F1) , ("KP_F2" , xK_KP_F2) , ("KP_F3" , xK_KP_F3) , ("KP_F4" , xK_KP_F4) , ("KP_Home" , xK_KP_Home) , ("KP_Left" , xK_KP_Left) , ("KP_Up" , xK_KP_Up) , ("KP_Right" , xK_KP_Right) , ("KP_Down" , xK_KP_Down) , ("KP_Prior" , xK_KP_Prior) , ("KP_Page_Up" , xK_KP_Page_Up) , ("KP_Next" , xK_KP_Next) , ("KP_Page_Down", xK_KP_Page_Down) , ("KP_End" , xK_KP_End) , ("KP_Begin" , xK_KP_Begin) , ("KP_Insert" , xK_KP_Insert) , ("KP_Delete" , xK_KP_Delete) , ("KP_Equal" , xK_KP_Equal) , ("KP_Multiply", xK_KP_Multiply) , ("KP_Add" , xK_KP_Add) , ("KP_Separator", xK_KP_Separator) , ("KP_Subtract", xK_KP_Subtract) , ("KP_Decimal" , xK_KP_Decimal) , ("KP_Divide" , xK_KP_Divide) , ("KP_0" , xK_KP_0) , ("KP_1" , xK_KP_1) , ("KP_2" , xK_KP_2) , ("KP_3" , xK_KP_3) , ("KP_4" , xK_KP_4) , ("KP_5" , xK_KP_5) , ("KP_6" , xK_KP_6) , ("KP_7" , xK_KP_7) , ("KP_8" , xK_KP_8) , ("KP_9" , xK_KP_9) ] -- | List of multimedia keys. If X server does not know about some -- | keysym it's omitted from list. (stringToKeysym returns noSymbol in this case) multimediaKeys :: [(String, KeySym)] multimediaKeys = filter ((/= noSymbol) . snd) . map (id &&& stringToKeysym) $ [ "XF86ModeLock" , "XF86MonBrightnessUp" , "XF86MonBrightnessDown" , "XF86KbdLightOnOff" , "XF86KbdBrightnessUp" , "XF86KbdBrightnessDown" , "XF86Standby" , "XF86AudioLowerVolume" , "XF86AudioMute" , "XF86AudioRaiseVolume" , "XF86AudioPlay" , "XF86AudioStop" , "XF86AudioPrev" , "XF86AudioNext" , "XF86HomePage" , "XF86Mail" , "XF86Start" , "XF86Search" , "XF86AudioRecord" , "XF86Calculator" , "XF86Memo" , "XF86ToDoList" , "XF86Calendar" , "XF86PowerDown" , "XF86ContrastAdjust" , "XF86RockerUp" , "XF86RockerDown" , "XF86RockerEnter" , "XF86Back" , "XF86Forward" , "XF86Stop" , "XF86Refresh" , "XF86PowerOff" , "XF86WakeUp" , "XF86Eject" , "XF86ScreenSaver" , "XF86WWW" , "XF86Sleep" , "XF86Favorites" , "XF86AudioPause" , "XF86AudioMedia" , "XF86MyComputer" , "XF86VendorHome" , "XF86LightBulb" , "XF86Shop" , "XF86History" , "XF86OpenURL" , "XF86AddFavorite" , "XF86HotLinks" , "XF86BrightnessAdjust" , "XF86Finance" , "XF86Community" , "XF86AudioRewind" , "XF86BackForward" , "XF86Launch0" , "XF86Launch1" , "XF86Launch2" , "XF86Launch3" , "XF86Launch4" , "XF86Launch5" , "XF86Launch6" , "XF86Launch7" , "XF86Launch8" , "XF86Launch9" , "XF86LaunchA" , "XF86LaunchB" , "XF86LaunchC" , "XF86LaunchD" , "XF86LaunchE" , "XF86LaunchF" , "XF86ApplicationLeft" , "XF86ApplicationRight" , "XF86Book" , "XF86CD" , "XF86Calculater" , "XF86Clear" , "XF86Close" , "XF86Copy" , "XF86Cut" , "XF86Display" , "XF86DOS" , "XF86Documents" , "XF86Excel" , "XF86Explorer" , "XF86Game" , "XF86Go" , "XF86iTouch" , "XF86LogOff" , "XF86Market" , "XF86Meeting" , "XF86MenuKB" , "XF86MenuPB" , "XF86MySites" , "XF86New" , "XF86News" , "XF86OfficeHome" , "XF86Open" , "XF86Option" , "XF86Paste" , "XF86Phone" , "XF86Q" , "XF86Reply" , "XF86Reload" , "XF86RotateWindows" , "XF86RotationPB" , "XF86RotationKB" , "XF86Save" , "XF86ScrollUp" , "XF86ScrollDown" , "XF86ScrollClick" , "XF86Send" , "XF86Spell" , "XF86SplitScreen" , "XF86Support" , "XF86TaskPane" , "XF86Terminal" , "XF86Tools" , "XF86Travel" , "XF86UserPB" , "XF86User1KB" , "XF86User2KB" , "XF86Video" , "XF86WheelButton" , "XF86Word" , "XF86Xfer" , "XF86ZoomIn" , "XF86ZoomOut" , "XF86Away" , "XF86Messenger" , "XF86WebCam" , "XF86MailForward" , "XF86Pictures" , "XF86Music" , "XF86_Switch_VT_1" , "XF86_Switch_VT_2" , "XF86_Switch_VT_3" , "XF86_Switch_VT_4" , "XF86_Switch_VT_5" , "XF86_Switch_VT_6" , "XF86_Switch_VT_7" , "XF86_Switch_VT_8" , "XF86_Switch_VT_9" , "XF86_Switch_VT_10" , "XF86_Switch_VT_11" , "XF86_Switch_VT_12" , "XF86_Ungrab" , "XF86_ClearGrab" , "XF86_Next_VMode" , "XF86_Prev_VMode" ] -- | Given a configuration record and a list of (key sequence -- description, action) pairs, check the key sequence descriptions -- for validity, and warn the user (via a popup xmessage window) of -- any unparseable or duplicate key sequences. This function is -- appropriate for adding to your @startupHook@, and you are highly -- encouraged to do so; otherwise, duplicate or unparseable -- keybindings will be silently ignored. -- -- For example, you might do something like this: -- -- > main = xmonad $ myConfig -- > -- > myKeymap = [("S-M-c", kill), ...] -- > myConfig = defaultConfig { -- > ... -- > keys = \c -> mkKeymap c myKeymap -- > startupHook = return () >> checkKeymap myConfig myKeymap -- > ... -- > } -- -- NOTE: the @return ()@ in the example above is very important! -- Otherwise, you might run into problems with infinite mutual -- recursion: the definition of myConfig depends on the definition of -- startupHook, which depends on the definition of myConfig, ... and -- so on. Actually, it's likely that the above example in particular -- would be OK without the @return ()@, but making @myKeymap@ take -- @myConfig@ as a parameter would definitely lead to -- problems. Believe me. It, uh, happened to my friend. In... a -- dream. Yeah. In any event, the @return () >>@ introduces enough -- laziness to break the deadlock. -- checkKeymap :: XConfig l -> [(String, a)] -> X () checkKeymap conf km = warn (doKeymapCheck conf km) where warn ([],[]) = return () warn (bad,dup) = spawn $ "xmessage 'Warning:\n" ++ msg "bad" bad ++ "\n" ++ msg "duplicate" dup ++ "'" msg _ [] = "" msg m xs = m ++ " keybindings detected: " ++ showBindings xs showBindings = unwords . map (("\""++) . (++"\"")) -- | Given a config and a list of (key sequence description, action) -- pairs, check the key sequence descriptions for validity, -- returning a list of unparseable key sequences, and a list of -- duplicate key sequences. doKeymapCheck :: XConfig l -> [(String,a)] -> ([String], [String]) doKeymapCheck conf km = (bad,dups) where ks = map ((readKeySequence conf &&& id) . fst) km bad = nub . map snd . filter (isNothing . fst) $ ks dups = map (snd . head) . filter ((>1) . length) . groupBy ((==) `on` fst) . sortBy (comparing fst) . map (first fromJust) . filter (isJust . fst) $ ks
MasseR/xmonadcontrib
XMonad/Util/EZConfig.hs
bsd-3-clause
25,949
0
16
8,310
3,664
2,267
1,397
326
3
-- | Simplices are modelled as vertex lists, together with a parity -- indicating the orientation of the simplex. Vertices come from an -- ordered set, so the ascending vertex list is assumed to be -- positively oriented. The orientation of a simplex with vertex list -- @v@ is thus taken as the signature of the permutation taking @v@ -- into @'sort' v@. module Math.Simplicial.Simplex where import Prelude hiding (fromIntegral) import qualified Math.Algebra.Monoid as M import qualified Math.Misc.Nat as Nat import Math.Misc.Parity import qualified Math.Misc.Permutation as Perm import Misc.Misc import Data.List import Data.Hashable -- | Do not construct simplices directly using the constructor. Use -- 'fromList'. data Simplex a = C Parity Int [a] type ISimplex = Simplex Int type CSimplex = Simplex Char instance (Hashable a) => Hashable (Simplex a) where hash (C p _ vs) = hash (p, vs) -- | Construct a simplex from a list of its vertices. The list cannot -- contain duplicates, a condition that is /not checked/. If you are -- uncertain, pass the list through 'nub' first or use 'fromList''. fromList :: (Eq a, Ord a) => [a] -> Simplex a fromList v = C (Perm.parity (v', v)) (length v' - 1) v' where v' = sort v -- | A 0-dimensional simplex. vertex :: (Eq a, Ord a) => Parity -> a -> Simplex a vertex p v = C p 0 [v] -- | A 0-dimensional simplex. positiveVertex :: (Eq a, Ord a) => a -> Simplex a positiveVertex = vertex Even fromPair :: (Eq a, Ord a) => (a, a) -> Simplex a fromPair (v, w) | v == w = error "Unhandled error in Simplex.hs." | v < w = fromAscendingList Even [v, w] | otherwise = fromAscendingList Even [w, v] -- | A (significantly slower) version of 'fromList' that passes the -- input list through 'nub', removing duplicates. fromList' :: (Eq a, Ord a) => [a] -> Simplex a fromList' = fromList . nub -- | Construct a simplex from a sorted (/strictly/ ascending) list of -- its vertices, and orientation parity. The condition that the list -- is sorted is not checked. fromAscendingList :: Parity -> [a] -> Simplex a fromAscendingList p vs = C p (length vs - 1) vs toList :: Simplex a -> [a] toList (C _ _ vs) = vs instance (Show a) => Show (Simplex a) where show (C Even _ v) = "simplex" ++ show v show (C Odd _ v) = "-simplex" ++ show v -- | A version of 'show' ignoring orientation. showSansSign :: (Show a) => Simplex a -> String showSansSign (C _ d v) = show (C Even d v) instance (Eq a) => Eq (Simplex a) where (C p d v) == (C q e u) = p == q && d == e && v == u -- Dimension comparison is there for quicker failure. instance (Ord a) => Ord (Simplex a) where compare (C p1 d1 v1) (C p2 d2 v2) = {-# SCC "Simplex.hs:compare" #-} compare (d1, v1, p1) (d2, v2, p2) isNullSimplex :: Simplex a -> Bool isNullSimplex (C _ _ []) = True isNullSimplex (C _ _ (_:_)) = False nullSimplex :: Simplex a nullSimplex = C Even (-1) [] dimension :: Simplex a -> Nat.N dimension (C _ d v) | null v = M.nil | otherwise = Nat.fromInt d dimension' :: Simplex a -> Int dimension' (C _ d v) | null v = 0 | otherwise = d -- | @'remove' k@ is /signed/ removal of the @k@'th vertex. remove :: Nat.N -> Simplex a -> Simplex a remove k (C p d v) = C (p M.<*> (fromIntegral k')) (d - 1) (removeAt k' v) where k' = Nat.toInt k -- | @'remove''@ is the /unsigned/ version of 'remove'. remove' :: Nat.N -> Simplex a -> Simplex a remove' k (C p d v) = C p (d - 1) (removeAt k' v) where k' = Nat.toInt k -- | Signed codimension-1 faces. faces :: Simplex a -> [Simplex a] faces s = map (\i -> remove i s) (takeWhile (<= dimension s) Nat.naturals) -- | Unsigned codimension-1 faces. faces' :: Simplex a -> [Simplex a] faces' s = map (\i -> remove' i s) (takeWhile (<= dimension s) Nat.naturals) parity :: Simplex a -> Parity parity (C p _ _) = p reverse :: Simplex a -> Simplex a reverse (C p d v) = C (opposite p) d v evenVersion :: Simplex a -> Simplex a evenVersion (C _ d v) = C Even d v -- Testing s0 :: Simplex Char s0 = fromList "a" s1 :: Simplex Char s1 = fromList "b" s2 :: Simplex Char s2 = fromList "c" s3 :: Simplex Char s3 = fromList "d" s4 :: Simplex Char s4 = fromList "ab" s5 :: Simplex Char s5 = fromList "bc" s6 :: Simplex Char s6 = fromList "cd" s7 :: Simplex Char s7 = fromList "ad" s8 :: Simplex Char s8 = fromList "ac" s9 :: Simplex Char s9 = fromList "abc" s10 :: Simplex Char s10 = fromList "acd" longS1 :: Simplex Int longS1 = fromList [0..100000] longS2 :: Simplex Int longS2 = fromList ([0..50000] ++ [50002, 50001] ++ [50003..100000]) benchmark = compare longS1 longS2
michiexile/hplex
pershom/src/Math/Simplicial/Simplex.hs
bsd-3-clause
4,612
0
10
1,000
1,679
875
804
97
1
{-# LANGUAGE GADTs, GeneralizedNewtypeDeriving, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, FlexibleContexts, RankNTypes, MultiParamTypeClasses, FlexibleInstances, ViewPatterns, ImplicitParams, TypeOperators, PackageImports #-} module HoasId ( InCtxt (..), Cons,List0,List1,List2,List3,List4,List5,First,Second,Third,Tail,(:++:), lookupCtx, Name(), -- hides Name implementation Binding(), -- hides Binding implementation Mb(), -- hides MultiBind implementation nu, cmpName,mbCmpName, Fresh(Fresh), runFresh, unsafeRunFresh, emptyMb, combineMb, separateMb, mbInt, mbRebind, mbToplevel, ToplevelFun, ToplevelRes, topFun, -- things for using mbMatch Tag(Tag),FTag(FTag),TFunApply,Repr(Repr),Args(ArgsNil,ArgsCons),ArgsMbMap, MbMatchable,toRepr,mbCtor,CtorsFun,MatchTpFun, mbMatch, -- things for CtxtFLists CtxtFList(CtxtFListBase,CtxtFListStep),ctxtFListSingle,(:|>),(|>), lookupCtxFList ) where import Unsafe.Coerce import Data.List import Data.IORef import System.IO.Unsafe(unsafePerformIO) import Control.Applicative import Test.StrictBench import "mtl" Control.Monad.Identity(Identity,runIdentity) import Control.Monad ------------------------------------------------------------ -- the fresh monad ------------------------------------------------------------ counter :: IORef Int {-# NOINLINE counter #-} counter = unsafePerformIO (newIORef 0) newtype Fresh a = Fresh (Identity a) deriving (Monad,Functor) instance Applicative Fresh where pure = return (<*>) = ap runFresh :: Fresh a -> IO a runFresh (Fresh m) = return $ runIdentity m -- README: this is not actually unsafe for the Id monad unsafeRunFresh :: Fresh a -> a unsafeRunFresh (Fresh m) = runIdentity m fresh_int :: () -> Fresh Int {-# NOINLINE fresh_int #-} fresh_int () = Fresh . return . unsafePerformIO $ do x <- readIORef counter writeIORef counter (x+1) return x ------------------------------------------------------------ -- manipulating lists of types -- note: we do right on the outside for efficiency of -- adding a single binder inside another one ------------------------------------------------------------ type List0 = () type List1 a = ((), a) type List2 a b = (((), b), a) type List3 a b c = ((((), c), b), a) type List4 a b c d = (((((), d), c), b), a) type List5 a b c d e = ((((((), e), d), c), b), a) type Cons a l = (l, a) type family First a type instance First (l, a) = a type family Second a type instance Second ((l, a2), a1) = a2 type family Third a type instance Third (((l, a3), a2), a1) = a3 type family Tail a type instance Tail (l, a) = l type family (ctx1 :++: ctx2) type instance ctx1 :++: () = ctx1 type instance ctx1 :++: (Cons a ctx2) = (Cons a (ctx1 :++: ctx2)) ------------------------------------------------------------ -- defining InCtxt ctx a as the proofs that ctx has the form -- (a1, (a2, ... (an, b))) where a = ai for some i ------------------------------------------------------------ -- proofs that a type is in a tuple-list of types data InCtxt ctx a where InCtxtBase :: InCtxt (Cons a ctx) a InCtxtStep :: InCtxt ctx a -> InCtxt (Cons b ctx) a instance Eq (InCtxt ctx a) where InCtxtBase == InCtxtBase = True (InCtxtStep p1) == (InCtxtStep p2) = p1 == p2 _ == _ = False -- looking up a value in a tuple-list lookupCtx :: InCtxt ctx a -> ctx -> a lookupCtx InCtxtBase (l, a) = a lookupCtx (InCtxtStep pf) (l, a) = lookupCtx pf l -- this is for when we know the ith element of ctx must be type a unsafeLookupCtx :: Int -> InCtxt ctx a unsafeLookupCtx 0 = unsafeCoerce InCtxtBase unsafeLookupCtx n = unsafeCoerce (InCtxtStep (unsafeLookupCtx (n-1))) ------------------------------------------------------------ -- now we define our data-types -- under the hood, names are just integers ------------------------------------------------------------ data Name a = MkName Int deriving Eq data Mb ctx b = MkMb [Int] b deriving Eq type Binding a = Mb (List1 a) -- for benchmarking instance NFData (Name a) where rnf (MkName i) = rnf i -- for benchmarking instance NFData a => NFData (Mb ctx a) where rnf (MkMb l x) = rnf l `seq` rnf x ------------------------------------------------------------ -- printing methods ------------------------------------------------------------ -- for printing things (debug only) instance Show (Name a) where show (MkName n) = "#" ++ show n ++ "#" instance Show b => Show (Mb a b) where show (MkMb l b) = "#" ++ show l ++ "." ++ show b instance Show b => Show (InCtxt ctx b) where show InCtxtBase = "InCtxtBase" show (InCtxtStep pf) = "InCtxtStep (" ++ show pf ++ ")" ------------------------------------------------------------ -- simple operations for creating and manipulating bindings ------------------------------------------------------------ -- nu creates bindings nu :: (Name a -> Fresh b) -> Fresh (Binding a b) nu f = do i <- fresh_int () i `seq` MkMb [i] <$> (f $ MkName i) -- combine binding of a binding into a single binding -- README: inner-most bindings come FIRST combineMb :: Mb ctx1 (Mb ctx2 b) -> Mb (ctx1 :++: ctx2) b combineMb (MkMb l1 (MkMb l2 b)) = MkMb (l2++l1) b -- separates inner-most binding separateMb :: Mb (ctx :++: List1 a) b -> Mb ctx (Binding a b) separateMb (MkMb (a:l) b) = MkMb l (MkMb [a] b) -- make an empty binding emptyMb :: a -> Mb () a emptyMb t = MkMb [] t ------------------------------------------------------------ -- name-matching operations ------------------------------------------------------------ data a :=: b where TEq :: (a ~ b) => a :=: b cmpName :: Name a -> Name b -> Maybe (a :=: b) cmpName (MkName n1) (MkName n2) = if n1 == n2 then Just $ unsafeCoerce TEq else Nothing -- name_multi_bind_cmp checks if a name is bound in a multi-binding mbCmpName :: Mb ctx (Name a) -> Either (InCtxt ctx a) (Name a) mbCmpName (MkMb names (MkName n)) = helper (elemIndex n names) where helper Nothing = Right (MkName n) helper (Just i) = Left (unsafeLookupCtx i) ------------------------------------------------------------ -- re-binding names in terms ------------------------------------------------------------ mbRebind :: (Name a) -> b -> (Binding a b) mbRebind (MkName i) b = MkMb [i] b ------------------------------------------------------------ -- applying top-level functions under binders ------------------------------------------------------------ class ToplevelFun tag a where type ToplevelRes tag a topFun :: Tag tag -> a -> ToplevelRes tag a mbToplevel :: ToplevelFun tag a => Tag tag -> Mb ctx a -> Mb ctx (ToplevelRes tag a) mbToplevel tag (MkMb names i) = MkMb names (topFun tag i) ------------------------------------------------------------ -- special-purpose matching under binders ------------------------------------------------------------ mbInt :: Mb ctx Int -> Int mbInt (MkMb _ i) = i ------------------------------------------------------------ -- generic matching under binders ------------------------------------------------------------ -- for supplying type arguments data Tag a = Tag data FTag (f :: * -> *) = FTag -- user-extensible function for applying the type function ftag to args type family TFunApply f targs -- abstract representation of a (G)ADT data Repr f a where Repr :: Tag z -> InCtxt (TFunApply f z) (args, a) -> Args args -> Repr f a -- this is essentially a value representation of a nested tuple type data Args args where ArgsNil :: Args List0 ArgsCons :: a -> Args args -> Args (Cons a args) -- mapping (Mb ctx) over nested arrow types and replacing the ret value with ret type family ArgsMbMap ctx args ret type instance ArgsMbMap ctx List0 ret = ret type instance ArgsMbMap ctx (Cons a args) ret = Mb ctx a -> ArgsMbMap ctx args ret -- type class stating that FIXME {- class MbMatchable (f :: * -> *) where type CtorsFun f -- type function to get ctors list type MatchTpFun f :: * -> * -> * -- type function to get match result type toRepr :: f x -> Repr (CtorsFun f) (f x) mbCtor :: Tag z -> Tag ctx -> InCtxt (TFunApply (CtorsFun f) z) (args, f x) -> ArgsMbMap ctx args (MatchTpFun f ctx x) -} class MbMatchable a where type CtorsFun a -- type function to get ctors list type MatchTpFun a -- type function to get match result type toRepr :: a -> Repr (CtorsFun a) a mbCtor :: Tag z -> Tag ctx -> InCtxt (TFunApply (CtorsFun a) z) (args, a) -> ArgsMbMap ctx args (TFunApply (MatchTpFun a) ctx) -- matching under bindings mbMatch :: MbMatchable a => Tag ctx -> Mb ctx a -> TFunApply (MatchTpFun a) ctx mbMatch ctxT (MkMb names x) = case toRepr x of Repr zT in_ctors args -> argsMapApply ctxT Tag (MkMb names) (mbCtor zT ctxT in_ctors) args -- helper function for applying a function to arguments argsMapApply :: Tag ctx -> Tag ret -> (forall x. x -> Mb ctx x) -> ArgsMbMap ctx args ret -> Args args -> ret argsMapApply ctxT rT addMb f ArgsNil = f argsMapApply ctxT rT addMb f (ArgsCons x args) = argsMapApply ctxT rT addMb (f (addMb x)) args ------------------------------------------------------------ -- lists of things that match the context ------------------------------------------------------------ data CtxtFList f ctx where CtxtFListBase :: CtxtFList f () CtxtFListStep :: f a -> CtxtFList f ctx -> CtxtFList f (Cons a ctx) ctxtFListSingle :: f a -> CtxtFList f (List1 a) ctxtFListSingle x = CtxtFListStep x CtxtFListBase -- FIXME: I think this is now just Cons... type ctx :|> a = (Cons a ctx) --type ctx :|> a = ctx :++: (List1 a) (|>) :: CtxtFList f ctx -> f a -> CtxtFList f (ctx :|> a) l |> y = CtxtFListStep y l --CtxtFListBase |> y = single y --CtxtFListStep x xs |> y = CtxtFListStep x (xs |> y) lookupCtxFList :: InCtxt ctx a -> CtxtFList f ctx -> f a lookupCtxFList InCtxtBase (CtxtFListStep x _ ) = x lookupCtxFList (InCtxtStep p) (CtxtFListStep _ xs) = lookupCtxFList p xs --lookupCtxFList _ _ = error "never happens"
eddywestbrook/hobbits
archival/HoasId.hs
bsd-3-clause
10,128
4
14
1,954
2,787
1,535
1,252
180
2
{-# LANGUAGE Strict #-} import Iter import Canonical.Tuple fib :: Int -> Int fib n = start (go (0, 1, n)) where
ku-fpg/ku-accelerate-examples
fib/FibNorth.hs
bsd-3-clause
137
0
8
47
46
26
20
6
1
-- | Matrix datatype and operations. -- -- Every provided example has been tested. -- Run @cabal test@ for further tests. module Data.Matrix ( -- * Matrix type Matrix , prettyMatrix , nrows , ncols , forceMatrix -- * Builders , matrix , fromList , fromLists , rowVector , colVector -- ** Special matrices , zero , identity , permMatrix -- * Accessing , getElem , (!) , safeGet , getRow , getCol , getDiag , getMatrixAsVector -- * Manipulating matrices , setElem , transpose , setSize , extendTo , mapRow , mapCol -- * Submatrices -- ** Splitting blocks , submatrix , minorMatrix , splitBlocks -- ** Joining blocks , (<|>) , (<->) , joinBlocks -- * Matrix operations , elementwise -- * Matrix multiplication -- ** About matrix multiplication -- $mult -- ** Functions , multStd , multStrassen , multStrassenMixed -- * Linear transformations , scaleMatrix , scaleRow , combineRows , switchRows , switchCols -- * Decompositions , luDecomp , luDecompUnsafe , luDecomp', luDecompUnsafe' , cholDecomp -- * Properties , trace , diagProd -- ** Determinants , detLaplace , detLU ) where -- Classes import Control.DeepSeq import Control.Monad (forM_) import Data.Foldable (Foldable (..)) import Data.Monoid import Data.Traversable -- Data import Control.Monad.Primitive (PrimMonad, PrimState) import Data.List (maximumBy,foldl1') import Data.Ord (comparing) import qualified Data.Vector as V import qualified Data.Vector.Mutable as MV import Data.Semiring hiding (sum, prod, zero) import qualified Data.Semiring as S ------------------------------------------------------- ------------------------------------------------------- ---- MATRIX TYPE encode :: Int -> (Int,Int) -> Int {-# INLINE encode #-} encode m (i,j) = (i-1)*m + j - 1 decode :: Int -> Int -> (Int,Int) {-# INLINE decode #-} decode m k = (q+1,r+1) where (q,r) = quotRem k m -- | Type of matrices. data Matrix a = M { nrows :: {-# UNPACK #-} !Int -- ^ Number of rows. , ncols :: {-# UNPACK #-} !Int -- ^ Number of columns. , mvect :: V.Vector a -- ^ Content of the matrix as a plain vector. } deriving Eq -- | Just a cool way to output the size of a matrix. sizeStr :: Int -> Int -> String sizeStr n m = show n ++ "x" ++ show m -- | Display a matrix as a 'String' using the 'Show' instance of its elements. prettyMatrix :: Show a => Matrix a -> String prettyMatrix m@(M _ _ v) = unlines [ "( " <> unwords (fmap (\j -> fill mx $ show $ m ! (i,j)) [1..ncols m]) <> " )" | i <- [1..nrows m] ] where mx = V.maximum $ fmap (length . show) v fill k str = replicate (k - length str) ' ' ++ str instance Show a => Show (Matrix a) where show = prettyMatrix instance NFData a => NFData (Matrix a) where rnf (M _ _ v) = rnf v -- | /O(rows*cols)/. Similar to 'V.force', drop any extra memory. -- -- Useful when using 'submatrix' from a big matrix. forceMatrix :: Matrix a -> Matrix a forceMatrix (M n m v) = M n m $ V.force v ------------------------------------------------------- ------------------------------------------------------- ---- FUNCTOR INSTANCE instance Functor Matrix where {-# INLINE fmap #-} fmap f (M n m v) = M n m $ V.map f v ------------------------------------------------------- ------------------------------------------------------- -- | /O(rows*cols)/. Map a function over a row. -- Example: -- -- > ( 1 2 3 ) ( 1 2 3 ) -- > ( 4 5 6 ) ( 5 6 7 ) -- > mapRow (\_ x -> x + 1) 2 ( 7 8 9 ) = ( 7 8 9 ) -- mapRow :: (Int -> a -> a) -- ^ Function takes the current column as additional argument. -> Int -- ^ Row to map. -> Matrix a -> Matrix a mapRow f r (M n m v) = M n m $ V.imap (\k x -> let (i,j) = decode m k in if i == r then f j x else x) v -- | /O(rows*cols)/. Map a function over a column. -- Example: -- -- > ( 1 2 3 ) ( 1 3 3 ) -- > ( 4 5 6 ) ( 4 6 6 ) -- > mapCol (\_ x -> x + 1) 2 ( 7 8 9 ) = ( 7 9 9 ) -- mapCol :: (Int -> a -> a) -- ^ Function takes the current row as additional argument. -> Int -- ^ Column to map. -> Matrix a -> Matrix a mapCol f c (M n m v) = M n m $ V.imap (\k x -> let (i,j) = decode m k in if j == c then f i x else x) v ------------------------------------------------------- ------------------------------------------------------- ---- FOLDABLE AND TRAVERSABLE INSTANCES instance Foldable Matrix where foldMap f = foldMap f . mvect instance Traversable Matrix where sequenceA (M n m v) = fmap (M n m) $ sequenceA v ------------------------------------------------------- ------------------------------------------------------- ---- BUILDERS -- | /O(rows*cols)/. The zero matrix of the given size. -- -- > zero n m = -- > n -- > 1 ( 0 0 ... 0 0 ) -- > 2 ( 0 0 ... 0 0 ) -- > ( ... ) -- > ( 0 0 ... 0 0 ) -- > n ( 0 0 ... 0 0 ) zero :: Semiring a => Int -- ^ Rows -> Int -- ^ Columns -> Matrix a zero n m = M n m $ V.replicate (n*m) S.zero -- | /O(rows*cols)/. Generate a matrix from a generator function. -- Example of usage: -- -- > ( 1 0 -1 -2 ) -- > ( 3 2 1 0 ) -- > ( 5 4 3 2 ) -- > matrix 4 4 $ \(i,j) -> 2*i - j = ( 7 6 5 4 ) matrix :: Int -- ^ Rows -> Int -- ^ Columns -> ((Int,Int) -> a) -- ^ Generator function -> Matrix a {-# INLINE matrix #-} matrix n m f = M n m $ V.generate (n*m) $ f . decode m -- | /O(rows*cols)/. Identity matrix of the given order. -- -- > identity n = -- > n -- > 1 ( 1 0 ... 0 0 ) -- > 2 ( 0 1 ... 0 0 ) -- > ( ... ) -- > ( 0 0 ... 1 0 ) -- > n ( 0 0 ... 0 1 ) -- identity :: Semiring a => Int -> Matrix a identity n = matrix n n $ \(i,j) -> if i == j then one else zero -- | Create a matrix from a non-empty list given the desired size. -- The list must have at least /rows*cols/ elements. -- An example: -- -- > ( 1 2 3 ) -- > ( 4 5 6 ) -- > fromList 3 3 [1..] = ( 7 8 9 ) -- fromList :: Int -- ^ Rows -> Int -- ^ Columns -> [a] -- ^ List of elements -> Matrix a {-# INLINE fromList #-} fromList n m = M n m . V.fromListN (n*m) -- | Create a matrix from an non-empty list of non-empty lists. -- /Each list must have the same number of elements/. -- For example: -- -- > fromLists [ [1,2,3] ( 1 2 3 ) -- > , [4,5,6] ( 4 5 6 ) -- > , [7,8,9] ] = ( 7 8 9 ) -- fromLists :: [[a]] -> Matrix a {-# INLINE fromLists #-} fromLists xss = fromList (length xss) (length $ head xss) $ concat xss -- | /O(1)/. Represent a vector as a one row matrix. rowVector :: V.Vector a -> Matrix a rowVector v = M 1 (V.length v) v -- | /O(1)/. Represent a vector as a one column matrix. colVector :: V.Vector a -> Matrix a colVector v = M (V.length v) 1 v -- | /O(rows*cols)/. Permutation matrix. -- -- > permMatrix n i j = -- > i j n -- > 1 ( 1 0 ... 0 ... 0 ... 0 0 ) -- > 2 ( 0 1 ... 0 ... 0 ... 0 0 ) -- > ( ... ... ... ) -- > i ( 0 0 ... 0 ... 1 ... 0 0 ) -- > ( ... ... ... ) -- > j ( 0 0 ... 1 ... 0 ... 0 0 ) -- > ( ... ... ... ) -- > ( 0 0 ... 0 ... 0 ... 1 0 ) -- > n ( 0 0 ... 0 ... 0 ... 0 1 ) -- -- When @i == j@ it reduces to 'identity' @n@. -- permMatrix :: Semiring a => Int -- ^ Size of the matrix. -> Int -- ^ Permuted row 1. -> Int -- ^ Permuted row 2. -> Matrix a -- ^ Permutation matrix. permMatrix n r1 r2 | r1 == r2 = identity n permMatrix n r1 r2 = matrix n n f where f (i,j) | i == r1 = if j == r2 then one else zero | i == r2 = if j == r1 then one else zero | i == j = one | otherwise = zero ------------------------------------------------------- ------------------------------------------------------- ---- ACCESSING -- | /O(1)/. Get an element of a matrix. Indices range from /(1,1)/ to /(n,m)/. getElem :: Int -- ^ Row -> Int -- ^ Column -> Matrix a -- ^ Matrix -> a {-# INLINE getElem #-} getElem i j (M _ m v) = V.unsafeIndex v $ encode m (i,j) -- | Short alias for 'getElem'. {-# INLINE (!) #-} (!) :: Matrix a -> (Int,Int) -> a m ! (i,j) = getElem i j m -- | Safe variant of 'getElem'. safeGet :: Int -> Int -> Matrix a -> Maybe a safeGet i j a@(M n m _) | i > n || j > m || i < 1 || j < 1 = Nothing | otherwise = Just $ getElem i j a -- | /O(1)/. Get a row of a matrix as a vector. getRow :: Int -> Matrix a -> V.Vector a getRow i (M _ m v) = V.slice (m*(i-1)) m v -- | /O(rows)/. Get a column of a matrix as a vector. getCol :: Int -> Matrix a -> V.Vector a getCol j (M n m v) = V.generate n $ \i -> v V.! encode m (i+1,j) -- | /O(min rows cols)/. Diagonal of a /not necessarily square/ matrix. getDiag :: Matrix a -> V.Vector a getDiag m = V.generate k $ \i -> m ! (i+1,i+1) where k = min (nrows m) (ncols m) -- | /O(1)/. Transform a 'Matrix' to a 'V.Vector' of size /rows*cols/. -- This is equivalent to get all the rows of the matrix using 'getRow' -- and then append them, but far more efficient. getMatrixAsVector :: Matrix a -> V.Vector a getMatrixAsVector = mvect ------------------------------------------------------- ------------------------------------------------------- ---- MANIPULATING MATRICES msetElem:: PrimMonad m => a -> Int -> (Int,Int) -> MV.MVector (PrimState m) a -> m () msetElem x m p v = MV.write v (encode m p) x -- | /O(1)/. Replace the value of a cell in a matrix. setElem :: a -- ^ New value. -> (Int,Int) -- ^ Position to replace. -> Matrix a -- ^ Original matrix. -> Matrix a -- ^ Matrix with the given position replaced with the given value. setElem x p (M n m v) = M n m $ V.modify (msetElem x m p) v -- | /O(rows*cols)/. The transpose of a matrix. -- Example: -- -- > ( 1 2 3 ) ( 1 4 7 ) -- > ( 4 5 6 ) ( 2 5 8 ) -- > transpose ( 7 8 9 ) = ( 3 6 9 ) transpose :: Matrix a -> Matrix a transpose m = matrix (ncols m) (nrows m) $ \(i,j) -> m ! (j,i) -- | Extend a matrix to a given size adding a default element. -- If the matrix already has the required size, nothing happens. -- The matrix is /never/ reduced in size. -- Example: -- -- > ( 1 2 3 0 0 ) -- > ( 1 2 3 ) ( 4 5 6 0 0 ) -- > ( 4 5 6 ) ( 7 8 9 0 0 ) -- > extendTo 0 4 5 ( 7 8 9 ) = ( 0 0 0 0 0 ) extendTo :: a -- ^ Element to add when extending. -> Int -- ^ Minimal number of rows. -> Int -- ^ Minimal number of columns. -> Matrix a -> Matrix a extendTo e n m a = setSize e (max n $ nrows a) (max m $ ncols a) a -- | Set the size of a matrix to given parameters. Use a default element -- for undefined entries if the matrix has been extended. setSize :: a -- ^ Default element. -> Int -- ^ Number of rows. -> Int -- ^ Number of columns. -> Matrix a -> Matrix a setSize e n m a@(M r c _) = M n m $ V.generate (n*m) $ \k -> let (i,j) = d k in if i <= r && j <= c then a ! (i,j) else e where d = decode m ------------------------------------------------------- ------------------------------------------------------- ---- WORKING WITH BLOCKS -- | /O(subrows*subcols)/. Extract a submatrix given row and column limits. -- Example: -- -- > ( 1 2 3 ) -- > ( 4 5 6 ) ( 2 3 ) -- > submatrix 1 2 2 3 ( 7 8 9 ) = ( 5 6 ) submatrix :: Int -- ^ Starting row -> Int -- ^ Ending row -> Int -- ^ Starting column -> Int -- ^ Ending column -> Matrix a -> Matrix a {-# INLINE submatrix #-} submatrix r1 r2 c1 c2 (M _ m vs) = M r' c' $ V.generate (r'*c') $ \k -> let (i,j) = decode c' k in vs V.! encode m (i+r1-1,j+c1-1) where r' = r2-r1+1 c' = c2-c1+1 -- | /O(rows*cols)/. Remove a row and a column from a matrix. -- Example: -- -- > ( 1 2 3 ) -- > ( 4 5 6 ) ( 1 3 ) -- > minorMatrix 2 2 ( 7 8 9 ) = ( 7 9 ) minorMatrix :: Int -- ^ Row @r@ to remove. -> Int -- ^ Column @c@ to remove. -> Matrix a -- ^ Original matrix. -> Matrix a -- ^ Matrix with row @r@ and column @c@ removed. minorMatrix r c (M n m v) = M (n-1) (m-1) $ V.ifilter (\k _ -> let (i,j) = decode m k in i /= r && j /= c) v -- | Make a block-partition of a matrix using a given element as reference. -- The element will stay in the bottom-right corner of the top-left corner matrix. -- -- > ( ) ( | ) -- > ( ) ( ... | ... ) -- > ( x ) ( x | ) -- > splitBlocks i j ( ) = (-------------) , where x = a_{i,j} -- > ( ) ( | ) -- > ( ) ( ... | ... ) -- > ( ) ( | ) -- -- Note that some blocks can end up empty. We use the following notation for these blocks: -- -- > ( TL | TR ) -- > (---------) -- > ( BL | BR ) -- -- Where T = Top, B = Bottom, L = Left, R = Right. -- -- Implementation is done via slicing of vectors. splitBlocks :: Int -- ^ Row of the splitting element. -> Int -- ^ Column of the splitting element. -> Matrix a -- ^ Matrix to split. -> (Matrix a,Matrix a ,Matrix a,Matrix a) -- ^ (TL,TR,BL,BR) splitBlocks i j a@(M n m _) = ( submatrix 1 i 1 j a , submatrix 1 i (j+1) m a , submatrix (i+1) n 1 j a , submatrix (i+1) n (j+1) m a ) -- | Join blocks of the form detailed in 'splitBlocks'. joinBlocks :: (Matrix a,Matrix a,Matrix a,Matrix a) -> Matrix a joinBlocks (tl,tr,bl,br) = (tl <|> tr) <-> (bl <|> br) {-# RULES "matrix/splitAndJoin" forall i j m. joinBlocks (splitBlocks i j m) = m #-} -- | Horizontally join two matrices. Visually: -- -- > ( A ) <|> ( B ) = ( A | B ) -- -- Where both matrices /A/ and /B/ have the same number of rows. -- /This condition is not checked/. (<|>) :: Matrix a -> Matrix a -> Matrix a {-# INLINE (<|>) #-} (M n m v) <|> (M _ m' v') = M n m'' $ V.generate (n*m'') $ \k -> let (i,j) = decode m'' k in if j <= m then v V.! encode m (i,j) else v' V.! encode m' (i,j-m) where m'' = m + m' -- | Vertically join two matrices. Visually: -- -- > ( A ) -- > ( A ) <-> ( B ) = ( - ) -- > ( B ) -- -- Where both matrices /A/ and /B/ have the same number of columns. -- /This condition is not checked/. (<->) :: Matrix a -> Matrix a -> Matrix a {-# INLINE (<->) #-} (M n m v) <-> (M n' _ v') = M (n+n') m $ v V.++ v' ------------------------------------------------------- ------------------------------------------------------- ---- MATRIX OPERATIONS -- | Perform an operation elementwise. The input matrices are assumed -- to have the same dimensions, but this is not checked. elementwise :: (a -> b -> c) -> (Matrix a -> Matrix b -> Matrix c) elementwise f (M n m v) (M _ _ v') = M n m $ V.zipWith f v v' ------------------------------------------------------- ------------------------------------------------------- ---- MATRIX MULTIPLICATION {- $mult Three methods are provided for matrix multiplication. * 'multStd': Matrix multiplication following directly the definition. This is the best choice when you know for sure that your matrices are small. * 'multStrassen': Matrix multiplication following the Strassen's algorithm. Complexity grows slower but also some work is added partitioning the matrix. Also, it only works on square matrices of order @2^n@, so if this condition is not met, it is zero-padded until this is accomplished. Therefore, its use it is not recommended. * 'multStrassenMixed': This function mixes the 'multStd' and 'multStrassen' methods. It provides a better performance in general. Method @(@'*'@)@ of the 'Num' class uses this function because it gives the best average performance. However, if you know for sure that your matrices are small, you should use 'multStd' instead, since 'multStrassenMixed' is going to switch to that function anyway. -} -- | Standard matrix multiplication by definition. multStd :: Semiring a => Matrix a -> Matrix a -> Matrix a {-# INLINE multStd #-} multStd a1@(M n m _) a2@(M n' m' _) -- Checking that sizes match... | m /= n' = error $ "Multiplication of " ++ sizeStr n m ++ " and " ++ sizeStr n' m' ++ " matrices." | otherwise = multStd_ a1 a2 -- | Standard matrix multiplication by definition, without checking if sizes match. multStd_ :: Semiring a => Matrix a -> Matrix a -> Matrix a {-# INLINE multStd_ #-} multStd_ a1@(M n m _) a2@(M _ m' _) = matrix n m' $ \(i,j) -> S.sum [ a1 ! (i,k) .*. a2 ! (k,j) | k <- [1 .. m] ] first :: (a -> Bool) -> [a] -> a first f = go where go (x:xs) = if f x then x else go xs go [] = error "first: no element match the condition." -- | Strassen's algorithm over square matrices of order @2^n@. strassen :: Num a => Matrix a -> Matrix a -> Matrix a -- Trivial 1x1 multiplication. strassen (M 1 1 v) (M 1 1 v') = M 1 1 $ V.zipWith (*) v v' -- General case guesses that the input matrices are square matrices -- whose order is a power of two. strassen a b = joinBlocks (c11,c12,c21,c22) where -- Size of the subproblem is halved. n = div (nrows a) 2 -- Split of the original problem into smaller subproblems. (a11,a12,a21,a22) = splitBlocks n n a (b11,b12,b21,b22) = splitBlocks n n b -- The seven Strassen's products. p1 = strassen (a11 + a22) (b11 + b22) p2 = strassen (a21 + a22) b11 p3 = strassen a11 (b12 - b22) p4 = strassen a22 (b21 - b11) p5 = strassen (a11 + a12) b22 p6 = strassen (a21 - a11) (b11 + b12) p7 = strassen (a12 - a22) (b21 + b22) -- Merging blocks c11 = p1 + p4 - p5 + p7 c12 = p3 + p5 c21 = p2 + p4 c22 = p1 - p2 + p3 + p6 -- | Strassen's matrix multiplication. multStrassen :: Num a => Matrix a -> Matrix a -> Matrix a multStrassen a1@(M n m _) a2@(M n' m' _) | m /= n' = error $ "Multiplication of " ++ sizeStr n m ++ " and " ++ sizeStr n' m' ++ " matrices." | otherwise = let mx = maximum [n,m,n',m'] n2 = first (>= mx) $ fmap (2^) [(0 :: Int)..] b1 = setSize 0 n2 n2 a1 b2 = setSize 0 n2 n2 a2 in submatrix 1 n 1 m' $ strassen b1 b2 strmixFactor :: Int strmixFactor = 2 ^ (6 :: Int) -- | Strassen's mixed algorithm. strassenMixed :: Num a => Matrix a -> Matrix a -> Matrix a {-# SPECIALIZE strassenMixed :: Matrix Double -> Matrix Double -> Matrix Double #-} {-# SPECIALIZE strassenMixed :: Matrix Int -> Matrix Int -> Matrix Int #-} strassenMixed a@(M r _ _) b | r < strmixFactor = multStd_ a b | odd r = let r' = r + 1 a' = setSize 0 r' r' a b' = setSize 0 r' r' b in submatrix 1 r 1 r $ strassenMixed a' b' | otherwise = joinBlocks (c11,c12,c21,c22) where -- Size of the subproblem is halved. n = quot r 2 -- Split of the original problem into smaller subproblems. (a11,a12,a21,a22) = splitBlocks n n a (b11,b12,b21,b22) = splitBlocks n n b -- The seven Strassen's products. p1 = strassenMixed (a11 + a22) (b11 + b22) p2 = strassenMixed (a21 + a22) b11 p3 = strassenMixed a11 (b12 - b22) p4 = strassenMixed a22 (b21 - b11) p5 = strassenMixed (a11 + a12) b22 p6 = strassenMixed (a21 - a11) (b11 + b12) p7 = strassenMixed (a12 - a22) (b21 + b22) -- Merging blocks c11 = p1 + p4 - p5 + p7 c12 = p3 + p5 c21 = p2 + p4 c22 = p1 - p2 + p3 + p6 -- | Mixed Strassen's matrix multiplication. multStrassenMixed :: Num a => Matrix a -> Matrix a -> Matrix a {-# INLINE multStrassenMixed #-} multStrassenMixed a1@(M n m _) a2@(M n' m' _) | m /= n' = error $ "Multiplication of " ++ sizeStr n m ++ " and " ++ sizeStr n' m' ++ " matrices." | n < strmixFactor = multStd_ a1 a2 | otherwise = let mx = maximum [n,m,n',m'] n2 = if even mx then mx else mx+1 b1 = setSize 0 n2 n2 a1 b2 = setSize 0 n2 n2 a2 in submatrix 1 n 1 m' $ strassenMixed b1 b2 ------------------------------------------------------- ------------------------------------------------------- ---- NUMERICAL INSTANCE instance Num a => Num (Matrix a) where fromInteger = M 1 1 . V.singleton . fromInteger negate = fmap negate abs = fmap abs signum = fmap signum -- Addition of matrices. {-# SPECIALIZE (+) :: Matrix Double -> Matrix Double -> Matrix Double #-} {-# SPECIALIZE (+) :: Matrix Int -> Matrix Int -> Matrix Int #-} (M n m v) + (M n' m' v') -- Checking that sizes match... | n /= n' || m /= m' = error $ "Addition of " ++ sizeStr n m ++ " and " ++ sizeStr n' m' ++ " matrices." -- Otherwise, trivial zip. | otherwise = M n m $ V.zipWith (+) v v' -- Substraction of matrices. {-# SPECIALIZE (-) :: Matrix Double -> Matrix Double -> Matrix Double #-} {-# SPECIALIZE (-) :: Matrix Int -> Matrix Int -> Matrix Int #-} (M n m v) - (M n' m' v') -- Checking that sizes match... | n /= n' || m /= m' = error $ "Substraction of " ++ sizeStr n m ++ " and " ++ sizeStr n' m' ++ " matrices." -- Otherwise, trivial zip. | otherwise = M n m $ V.zipWith (-) v v' -- Multiplication of matrices. {-# INLINE (*) #-} (*) = multStrassenMixed instance Semiring a => Semiring (Matrix a) where S.zero = zero one = identity ------------------------------------------------------- ------------------------------------------------------- ---- TRANSFORMATIONS -- | Scale a matrix by a given factor. -- Example: -- -- > ( 1 2 3 ) ( 2 4 6 ) -- > ( 4 5 6 ) ( 8 10 12 ) -- > scaleMatrix 2 ( 7 8 9 ) = ( 14 16 18 ) scaleMatrix :: Num a => a -> Matrix a -> Matrix a scaleMatrix = fmap . (*) -- | Scale a row by a given factor. -- Example: -- -- > ( 1 2 3 ) ( 1 2 3 ) -- > ( 4 5 6 ) ( 8 10 12 ) -- > scaleRow 2 2 ( 7 8 9 ) = ( 7 8 9 ) scaleRow :: Num a => a -> Int -> Matrix a -> Matrix a scaleRow = mapRow . const . (*) -- | Add to one row a scalar multiple of other row. -- Example: -- -- > ( 1 2 3 ) ( 1 2 3 ) -- > ( 4 5 6 ) ( 6 9 12 ) -- > combineRows 2 2 1 ( 7 8 9 ) = ( 7 8 9 ) combineRows :: Num a => Int -> a -> Int -> Matrix a -> Matrix a combineRows r1 l r2 m = mapRow (\j x -> x + l * getElem r2 j m) r1 m -- | Switch two rows of a matrix. -- Example: -- -- > ( 1 2 3 ) ( 4 5 6 ) -- > ( 4 5 6 ) ( 1 2 3 ) -- > switchRows 1 2 ( 7 8 9 ) = ( 7 8 9 ) switchRows :: Int -- ^ Row 1. -> Int -- ^ Row 2. -> Matrix a -- ^ Original matrix. -> Matrix a -- ^ Matrix with rows 1 and 2 switched. switchRows r1 r2 (M n m vs) = M n m $ V.modify (\mv -> do forM_ [1..m] $ \j -> MV.swap mv (encode m (r1, j)) (encode m (r2, j))) vs -- | Switch two coumns of a matrix. -- Example: -- -- > ( 1 2 3 ) ( 2 1 3 ) -- > ( 4 5 6 ) ( 5 4 6 ) -- > switchCols 1 2 ( 7 8 9 ) = ( 8 7 9 ) switchCols :: Int -- ^ Col 1. -> Int -- ^ Col 2. -> Matrix a -- ^ Original matrix. -> Matrix a -- ^ Matrix with cols 1 and 2 switched. switchCols c1 c2 (M n m vs) = M n m $ V.modify (\mv -> do forM_ [1..n] $ \j -> MV.swap mv (encode m (j, c1)) (encode m (j, c2))) vs ------------------------------------------------------- ------------------------------------------------------- ---- DECOMPOSITIONS -- LU DECOMPOSITION -- | Matrix LU decomposition with /partial pivoting/. -- The result for a matrix /M/ is given in the format /(U,L,P,d)/ where: -- -- * /U/ is an upper triangular matrix. -- -- * /L/ is an /unit/ lower triangular matrix. -- -- * /P/ is a permutation matrix. -- -- * /d/ is the determinant of /P/. -- -- * /PM = LU/. -- -- These properties are only guaranteed when the input matrix is invertible. -- An additional property matches thanks to the strategy followed for pivoting: -- -- * /L_(i,j)/ <= 1, for all /i,j/. -- -- This follows from the maximal property of the selected pivots, which also -- leads to a better numerical stability of the algorithm. -- -- Example: -- -- > ( 1 2 0 ) ( 2 0 2 ) ( 1 0 0 ) ( 0 0 1 ) -- > ( 0 2 1 ) ( 0 2 -1 ) ( 1/2 1 0 ) ( 1 0 0 ) -- > luDecomp ( 2 0 2 ) = ( ( 0 0 2 ) , ( 0 1 1 ) , ( 0 1 0 ) , 1 ) luDecomp :: (Ord a, Fractional a) => Matrix a -> Maybe (Matrix a,Matrix a,Matrix a,a) luDecomp a = recLUDecomp a i i 1 1 n where i = identity $ nrows a n = min (nrows a) (ncols a) recLUDecomp :: (Ord a, Fractional a) => Matrix a -- ^ U -> Matrix a -- ^ L -> Matrix a -- ^ P -> a -- ^ d -> Int -- ^ Current row -> Int -- ^ Total rows -> Maybe (Matrix a,Matrix a,Matrix a,a) recLUDecomp u l p d k n = if k > n then Just (u,l,p,d) else if ukk == 0 then Nothing else recLUDecomp u'' l'' p' d' (k+1) n where -- Pivot strategy: maximum value in absolute value below the current row. i = maximumBy (\x y -> compare (abs $ u ! (x,k)) (abs $ u ! (y,k))) [ k .. n ] -- Switching to place pivot in current row. u' = switchRows k i u l' = M (nrows l) (ncols l) $ V.modify (\mv -> mapM_ (\j -> do msetElem (l ! (k,j)) (ncols l) (i,j) mv msetElem (l ! (i,j)) (ncols l) (k,j) mv ) [1 .. k-1] ) $ mvect l p' = switchRows k i p -- Permutation determinant d' = if i == k then d else negate d -- Cancel elements below the pivot. (u'',l'') = go u' l' (k+1) ukk = u' ! (k,k) go u_ l_ j = if j > nrows u_ then (u_,l_) else let x = (u_ ! (j,k)) / ukk in go (combineRows j (-x) k u_) (setElem x (j,k) l_) (j+1) -- | Unsafe version of 'luDecomp'. It fails when the input matrix is singular. luDecompUnsafe :: (Ord a, Fractional a) => Matrix a -> (Matrix a, Matrix a, Matrix a, a) luDecompUnsafe m = case luDecomp m of Just x -> x _ -> error "luDecompUnsafe of singular matrix." -- | Matrix LU decomposition with /complete pivoting/. -- The result for a matrix /M/ is given in the format /(U,L,P,Q,d,e)/ where: -- -- * /U/ is an upper triangular matrix. -- -- * /L/ is an /unit/ lower triangular matrix. -- -- * /P,Q/ are permutation matrices. -- -- * /d,e/ are the determinants of /P/ and /Q/ respectively. -- -- * /PMQ = LU/. -- -- These properties are only guaranteed when the input matrix is invertible. -- An additional property matches thanks to the strategy followed for pivoting: -- -- * /L_(i,j)/ <= 1, for all /i,j/. -- -- This follows from the maximal property of the selected pivots, which also -- leads to a better numerical stability of the algorithm. -- -- Example: -- -- > ( 1 0 ) ( 2 1 ) ( 1 0 0 ) ( 0 0 1 ) -- > ( 0 2 ) ( 0 2 ) ( 0 1 0 ) ( 0 1 0 ) ( 1 0 ) -- > luDecomp' ( 2 1 ) = ( ( 0 0 ) , ( 1/2 -1/4 1 ) , ( 1 0 0 ) , ( 0 1 ) , -1 , 1 ) luDecomp' :: (Ord a, Fractional a) => Matrix a -> Maybe (Matrix a,Matrix a,Matrix a,Matrix a,a,a) luDecomp' a = recLUDecomp' a i i (identity $ ncols a) 1 1 1 n where i = identity $ nrows a n = min (nrows a) (ncols a) -- | Unsafe version of 'luDecomp''. It fails when the input matrix is singular. luDecompUnsafe' :: (Ord a, Fractional a) => Matrix a -> (Matrix a, Matrix a, Matrix a, Matrix a, a, a) luDecompUnsafe' m = case luDecomp' m of Just x -> x _ -> error "luDecompUnsafe' of singular matrix." recLUDecomp' :: (Ord a, Fractional a) => Matrix a -- ^ U -> Matrix a -- ^ L -> Matrix a -- ^ P -> Matrix a -- ^ Q -> a -- ^ d -> a -- ^ e -> Int -- ^ Current row -> Int -- ^ Total rows -> Maybe (Matrix a,Matrix a,Matrix a,Matrix a,a,a) recLUDecomp' u l p q d e k n = if k > n || u'' ! (k, k) == 0 then Just (u,l,p,q,d,e) else if ukk == 0 then Nothing else recLUDecomp' u'' l'' p' q' d' e' (k+1) n where -- Pivot strategy: maximum value in absolute value below the current row & col. (i, j) = maximumBy (comparing (\(i0, j0) -> abs $ u ! (i0,j0))) [ (i0, j0) | i0 <- [k .. nrows u], j0 <- [k .. ncols u] ] -- Switching to place pivot in current row. u' = switchCols k j $ switchRows k i u l'0 = M (nrows l) (ncols l) $ V.modify (\mv -> forM_ [1..k-1] $ \ h -> do msetElem (l ! (k,h)) (ncols l) (i,h) mv msetElem (l ! (i,h)) (ncols l) (k,h) mv ) $ mvect l l' = M (nrows l) (ncols l) $ V.modify (\mv -> forM_ [1..k-1] $ \h -> do msetElem (l'0 ! (h,k)) (ncols l) (h,i) mv msetElem (l'0 ! (h,i)) (ncols l) (h,k) mv ) $ mvect l'0 p' = switchRows k i p q' = switchCols k j q -- Permutation determinant d' = if i == k then d else negate d e' = if j == k then e else negate e -- Cancel elements below the pivot. (u'',l'') = go u' l' (k+1) ukk = u' ! (k,k) go u_ l_ h = if h > nrows u_ then (u_,l_) else let x = (u_ ! (h,k)) / ukk in go (combineRows h (-x) k u_) (setElem x (h,k) l_) (h+1) -- CHOLESKY DECOMPOSITION -- | Simple Cholesky decomposition of a symmetric, positive definite matrix. -- The result for a matrix /M/ is a lower triangular matrix /L/ such that: -- -- * /M = LL^T/. -- -- Example: -- -- > ( 2 -1 0 ) ( 1.41 0 0 ) -- > ( -1 2 -1 ) ( -0.70 1.22 0 ) -- > cholDecomp ( 0 -1 2 ) = ( 0.00 -0.81 1.15 ) cholDecomp :: (Floating a) => Matrix a -> Matrix a cholDecomp a | (nrows a == 1) && (ncols a == 1) = fmap sqrt a | otherwise = joinBlocks (l11, l12, l21, l22) where (a11, a12, a21, a22) = splitBlocks 1 1 a l11' = sqrt (a11 ! (1,1)) l11 = fromList 1 1 [l11'] l12 = zero (nrows a12) (ncols a12) l21 = scaleMatrix (1/l11') a21 a22' = a22 - multStd l21 (transpose l21) l22 = cholDecomp a22' ------------------------------------------------------- ------------------------------------------------------- ---- PROPERTIES {-# RULES "matrix/traceOfSum" forall a b. trace (a + b) = trace a + trace b "matrix/traceOfScale" forall k a. trace (scaleMatrix k a) = k * trace a #-} -- | Sum of the elements in the diagonal. See also 'getDiag'. -- Example: -- -- > ( 1 2 3 ) -- > ( 4 5 6 ) -- > trace ( 7 8 9 ) = 15 trace :: Num a => Matrix a -> a trace = V.sum . getDiag -- | Product of the elements in the diagonal. See also 'getDiag'. -- Example: -- -- > ( 1 2 3 ) -- > ( 4 5 6 ) -- > diagProd ( 7 8 9 ) = 45 diagProd :: Num a => Matrix a -> a diagProd = V.product . getDiag -- DETERMINANT {-# RULES "matrix/detLaplaceProduct" forall a b. detLaplace (a*b) = detLaplace a * detLaplace b "matrix/detLUProduct" forall a b. detLU (a*b) = detLU a * detLU b #-} -- | Matrix determinant using Laplace expansion. -- If the elements of the 'Matrix' are instance of 'Ord' and 'Fractional' -- consider to use 'detLU' in order to obtain better performance. -- Function 'detLaplace' is /extremely/ slow. detLaplace :: Num a => Matrix a -> a detLaplace (M 1 1 v) = V.head v detLaplace m = sum1 [ (-1)^(i-1) * m ! (i,1) * detLaplace (minorMatrix i 1 m) | i <- [1 .. nrows m] ] where sum1 = foldl1' (+) -- | Matrix determinant using LU decomposition. -- It works even when the input matrix is singular. detLU :: (Ord a, Fractional a) => Matrix a -> a detLU m = case luDecomp m of Just (u,_,_,d) -> d * diagProd u Nothing -> 0
eruonna/tropical
Data/Matrix.hs
bsd-3-clause
32,582
1
20
10,094
8,449
4,576
3,873
-1
-1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE RankNTypes #-} module Data.Oddjob.Worker ( WorkerService(..) , WorkerServiceState(..) , WorkerServiceEvent(..) , WorkerFn , EventHandler , Jobs , startWorkerService , stopWorkerService , setJobs , setJobsSTM , getState ) where import Prelude hiding (mapM_) import Control.Concurrent import Control.Concurrent.Async import Control.Concurrent.STM import Control.Exception import Control.Monad (void, forever, when, unless) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.State.Strict (MonadState, StateT, evalStateT, get) import Data.Foldable (mapM_) import Data.Maybe (fromMaybe) import qualified Data.Map.Strict as Map import Data.Map.Strict ((!)) import Data.Set (Set, (\\)) import qualified Data.Set as Set import Data.Time (DiffTime, picosecondsToDiffTime) import Lens.Micro (Lens', (^.), lens) import Lens.Micro.Mtl ((%=), use) import System.Clock (Clock(Monotonic), TimeSpec, getTime, diffTimeSpec, timeSpecAsNanoSecs) type WorkerHandle = Async () type WorkerMap b = Map.Map b (TimeSpec, WorkerHandle) type Jobs b = Set b type WorkerFn b = b -> IO () data WorkerServiceState b = WorkerServiceState [(b, DiffTime)] deriving (Show, Functor) data WorkerServiceEvent b = JobStarted [b] | JobCancelled [(b, DiffTime)] | JobCrashed b DiffTime SomeException deriving (Show, Functor) type EventHandler b = WorkerServiceEvent b -> IO () data WorkerService b = WorkerService { _asyncHandle :: Async () , _inputVar :: TMVar (Jobs b) , _stateVar :: TMVar (TMVar (WorkerServiceState b)) } asyncHandle :: Lens' (WorkerService b) (Async ()) asyncHandle = lens _asyncHandle (\s n -> s { _asyncHandle = n }) inputVar :: Lens' (WorkerService b) (TMVar (Jobs b)) inputVar = lens _inputVar (\s n -> s { _inputVar = n }) stateVar :: Lens' (WorkerService b) (TMVar (TMVar (WorkerServiceState b))) stateVar = lens _stateVar (\s n -> s { _stateVar = n }) data WorkerState b = WorkerState { _workerMap :: WorkerMap b , _updateVar:: TMVar (Jobs b) , _stateRequest :: TMVar (TMVar (WorkerServiceState b)) , _diedQueue :: TBQueue (SomeException, b) , _runJob :: WorkerFn b , _self :: Async () , _eventHandler :: EventHandler b } data WakeupReason b = SetJobs (Jobs b) | Crashed SomeException b | StateRequest (TMVar (WorkerServiceState b)) workerMap :: Lens' (WorkerState b) (WorkerMap b) workerMap = lens _workerMap (\s n -> s { _workerMap = n }) updateVar :: Lens' (WorkerState b) (TMVar (Jobs b)) updateVar = lens _updateVar (\s n -> s { _updateVar = n }) diedQueue :: Lens' (WorkerState b) (TBQueue (SomeException, b)) diedQueue = lens _diedQueue (\s n -> s { _diedQueue = n }) runJob :: Lens' (WorkerState b) (b -> IO ()) runJob = lens _runJob (\s n -> s { _runJob = n }) self :: Lens' (WorkerState b) (Async ()) self = lens _self (\s n -> s { _self = n }) eventHandler :: Lens' (WorkerState b) (EventHandler b) eventHandler = lens _eventHandler (\s n -> s { _eventHandler = n }) stateRequest :: Lens' (WorkerState b) (TMVar (TMVar (WorkerServiceState b))) stateRequest = lens _stateRequest (\s n -> s { _stateRequest = n }) startWorkerService :: Ord b => WorkerFn b -> Maybe (EventHandler b) -> IO (WorkerService b) startWorkerService jobFn mEventHandler = do let eHandler = fromMaybe (const (return ())) mEventHandler updateQ <- newEmptyTMVarIO stateReqQ <- newEmptyTMVarIO diedQ <- newTBQueueIO 10 controller <- asyncWithReferenceToSelf $ \me -> let initial = WorkerState Map.empty updateQ stateReqQ diedQ jobFn me eHandler in runWorkerService workerServiceLoop initial return (WorkerService controller updateQ stateReqQ) stopWorkerService :: WorkerService a -> IO () stopWorkerService service = cancel (service ^. asyncHandle) setJobs :: Ord b => WorkerService b -> Jobs b -> IO () setJobs service jobs = atomically (setJobsSTM service jobs) setJobsSTM :: Ord b => WorkerService b -> Jobs b -> STM () setJobsSTM service jobs = putTMVar (service ^. inputVar) jobs getState :: Ord b => WorkerService b -> IO (WorkerServiceState b) getState service = do replyVar <- newEmptyTMVarIO atomically (putTMVar (service ^. stateVar) replyVar) atomically (takeTMVar replyVar) newtype WS b a = WS { _unWorkerState :: StateT (WorkerState b) IO a } deriving ( Functor, Applicative, Monad, MonadIO, MonadState (WorkerState b) ) runWorkerService :: WS b a -> WorkerState b -> IO a runWorkerService s = evalStateT (_unWorkerState s) jobStatus :: Ord b => TimeSpec -> b -> WorkerMap b -> DiffTime jobStatus now job wMap = let (workerStartTime, _) = wMap ! job timeDiff = diffTimeSpec now workerStartTime in timeSpecToDiffTime timeDiff controlJob :: Ord b => b -> WS b () controlJob job = do jobFn <- use runJob diedQ <- use diedQueue workerHandle <- liftIO (asyncFinally (jobFn job) (\e -> atomically (writeTBQueue diedQ (e, job)))) me <- use self workerStartTime <- liftIO (getTime Monotonic) liftIO (linkChildToParent me workerHandle) workerMap %= Map.insert job (workerStartTime, workerHandle) cancelJob :: Ord b => b -> WS b () cancelJob job = do (_, workerHandle) <- (! job) <$> use workerMap liftIO (cancel workerHandle) workerMap %= Map.delete job updateRunningState :: Ord b => Jobs b -> WS b () updateRunningState needRunning = do wMap <- use workerMap eHandler <- use eventHandler let currentlyRunning = Set.fromList (Map.keys wMap) noLongerNeeded = currentlyRunning \\ needRunning notRunning = needRunning \\ currentlyRunning void $ liftIO $ do updateTime <- getTime Monotonic let jobStatusTuple j = (j, jobStatus updateTime j wMap) -- Call the event handler with the cancelled jobs let canceling = fmap jobStatusTuple (Set.toList noLongerNeeded) unless (null canceling) (eHandler (JobCancelled canceling)) unless (Set.null notRunning) (eHandler (JobStarted (Set.toList notRunning))) mapM_ cancelJob noLongerNeeded mapM_ controlJob notRunning workerServiceLoop :: Ord b => WS b () workerServiceLoop = forever $ do reasonToWakeUp <- get >>= liftIO . atomically . wakeupSTM case reasonToWakeUp of (SetJobs needRunning) -> updateRunningState needRunning (Crashed exception job) -> do wMap <- use workerMap eHandler <- use eventHandler -- Only restart the worker if we're actually supposed to be -- running it. when (Map.member job wMap) $ do -- Notify the event handler liftIO $ do updateTime <- getTime Monotonic let diffTime = jobStatus updateTime job wMap eHandler (JobCrashed job diffTime exception) -- this results in an unneeded Async.cancel, but it keeps the code -- nice and clean, and it's innocuous cancelJob job controlJob job (StateRequest replyQ) -> do wMap <- use workerMap now <- liftIO (getTime Monotonic) let statuses = fmap (\j -> (j, jobStatus now j wMap)) (Map.keys wMap) liftIO (atomically (putTMVar replyQ (WorkerServiceState statuses))) wakeupSTM :: WorkerState b -> STM (WakeupReason b) wakeupSTM apState = (SetJobs <$> needRunningSTM (apState ^. updateVar)) `orElse` (StateRequest <$> stateRequestSTM (apState ^. stateRequest)) `orElse` (uncurry Crashed <$> stoppedWithExceptionSTM (apState ^. diedQueue)) needRunningSTM :: TMVar (Jobs b) -> STM (Jobs b) needRunningSTM = takeTMVar stateRequestSTM :: TMVar (TMVar (WorkerServiceState b)) -> STM (TMVar (WorkerServiceState b)) stateRequestSTM = takeTMVar stoppedWithExceptionSTM :: TBQueue (SomeException, b) -> STM (SomeException, b) stoppedWithExceptionSTM = readTBQueue -- Time Helpers ************************************************************** ------------------------------------------------------------------------------ timeSpecToDiffTime :: TimeSpec -> DiffTime timeSpecToDiffTime ts = picosecondsToDiffTime (timeSpecAsNanoSecs ts * 1000) -- Things Reid wishes were in Control.Concurrent.Async *********************** ------------------------------------------------------------------------------ asyncWithReferenceToSelf :: (Async a -> IO a) -> IO (Async a) asyncWithReferenceToSelf action = do var <- newEmptyMVar a <- async (takeMVar var >>= action) putMVar var a return a linkChildToParent :: Async a -> Async b -> IO () linkChildToParent parent child = void $ forkRepeat $ do r <- waitCatch parent case r of (Left e) -> cancelWith child e _ -> return () asyncFinally :: IO a -> (SomeException -> IO b) -> IO (Async a) asyncFinally action handler = let finallyE io what = io `catch` \e -> what e >> throwIO (e :: SomeException) in mask $ \restore -> async (restore action `finallyE` handler) -- From Control.Concurrent.Async internals -- -- | Fork a thread that runs the supplied action, and if it raises an -- exception, re-runs the action. The thread terminates only when the -- action runs to completion without raising an exception. forkRepeat :: IO a -> IO ThreadId forkRepeat action = mask $ \restore -> let go = do r <- tryAll (restore action) case r of Left _ -> go _ -> return () in forkIO go -- From Control.Concurrent.Async internals -- tryAll :: IO a -> IO (Either SomeException a) tryAll = try
helium/oddjob
src/Data/Oddjob/Worker.hs
bsd-3-clause
10,182
0
22
2,607
3,156
1,630
1,526
219
3
-- 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.SV.Rules ( rules ) where import Control.Monad (liftM2) import Prelude import Duckling.Dimensions.Types import Duckling.Numeral.Helpers (parseInt) import Duckling.Ordinal.Types (OrdinalData (..)) import qualified Duckling.Ordinal.Types as TOrdinal 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 "m\x00e5ndag(en)?|m\x00e5n\\.?" ] , prod = \_ -> tt $ dayOfWeek 1 } ruleTheDayAfterTomorrow :: Rule ruleTheDayAfterTomorrow = Rule { name = "the day after tomorrow" , pattern = [ regex "i \x00f6verimorgon" ] , prod = \_ -> tt $ cycleNth TG.Day 2 } ruleNamedmonth12 :: Rule ruleNamedmonth12 = Rule { name = "named-month" , pattern = [ regex "december|dec\\.?" ] , prod = \_ -> tt $ month 12 } ruleRelativeMinutesTotillbeforeIntegerHourofday :: Rule ruleRelativeMinutesTotillbeforeIntegerHourofday = Rule { name = "relative minutes to|till|before <integer> (hour-of-day)" , pattern = [ Predicate $ isIntegerBetween 1 59 , regex "i" , Predicate isAnHourOfDay ] , prod = \tokens -> case tokens of (token:_:Token Time td:_) -> do n <- getIntValue token t <- minutesBefore n td Just $ Token Time t _ -> Nothing } ruleRelativeMinutesAfterpastIntegerHourofday :: Rule ruleRelativeMinutesAfterpastIntegerHourofday = Rule { name = "relative minutes after|past <integer> (hour-of-day)" , pattern = [ Predicate $ isIntegerBetween 1 59 , regex "\x00f6ver" , Predicate isAnHourOfDay ] , prod = \tokens -> case tokens of (token: _: Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) _)}: _) -> do n <- getIntValue token tt $ hourMinute True hours n _ -> Nothing } 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) _)}: token: _) -> do n <- getIntValue token tt $ hourMinute True hours n _ -> Nothing } ruleQuarterTotillbeforeIntegerHourofday :: Rule ruleQuarterTotillbeforeIntegerHourofday = Rule { name = "quarter to|till|before <integer> (hour-of-day)" , pattern = [ regex "(en)? ?(kvart)(er)?" , regex "i" , Predicate isAnHourOfDay ] , prod = \tokens -> case tokens of (_:_:Token Time td:_) -> Token Time <$> minutesBefore 15 td _ -> Nothing } ruleQuarterAfterpastIntegerHourofday :: Rule ruleQuarterAfterpastIntegerHourofday = Rule { name = "quarter after|past <integer> (hour-of-day)" , pattern = [ regex "(en)? ?(kvart)(er)?" , regex "\x00f6ver" , Predicate isAnHourOfDay ] , prod = \tokens -> case tokens of (_: _: Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) _)}: _) -> tt $ hourMinute True hours 15 _ -> Nothing } ruleHourofdayQuarter :: Rule ruleHourofdayQuarter = Rule { name = "<hour-of-day> quarter (as relative minutes)" , pattern = [ Predicate isAnHourOfDay , regex "(en)? ?(kvart)(er)?" ] , prod = \tokens -> case tokens of (Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) _)}: _) -> tt $ hourMinute True hours 15 _ -> Nothing } ruleHalfTotillbeforeIntegerHourofday :: Rule ruleHalfTotillbeforeIntegerHourofday = Rule { name = "half to|till|before <integer> (hour-of-day)" , pattern = [ regex "halvtimme" , regex "i" , Predicate isAnHourOfDay ] , prod = \tokens -> case tokens of (_:_:Token Time td:_) -> Token Time <$> minutesBefore 30 td _ -> Nothing } ruleHalfAfterpastIntegerHourofday :: Rule ruleHalfAfterpastIntegerHourofday = Rule { name = "half after|past <integer> (hour-of-day)" , pattern = [ regex "halvtimme" , regex "\x00f6ver" , Predicate isAnHourOfDay ] , prod = \tokens -> case tokens of (_: _: Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) _)}: _) -> tt $ hourMinute True hours 30 _ -> Nothing } ruleHourofdayHalf :: Rule ruleHourofdayHalf = Rule { name = "<hour-of-day> half (as relative minutes)" , pattern = [ Predicate isAnHourOfDay , regex "halvtimme" ] , prod = \tokens -> case tokens of (Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) _)}: _) -> tt $ hourMinute True hours 30 _ -> Nothing } ruleNamedday2 :: Rule ruleNamedday2 = Rule { name = "named-day" , pattern = [ regex "tisdag(en)?|tis?\\.?" ] , prod = \_ -> tt $ dayOfWeek 2 } ruleTheOrdinalCycleOfTime :: Rule ruleTheOrdinalCycleOfTime = Rule { name = "the <ordinal> <cycle> of <time>" , pattern = [ regex "den" , dimension Ordinal , dimension TimeGrain , regex "av|i|fr\x00e5n" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Ordinal od:Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter True grain (TOrdinal.value od - 1) td _ -> Nothing } ruleNthTimeOfTime2 :: Rule ruleNthTimeOfTime2 = Rule { name = "nth <time> of <time>" , pattern = [ regex "den" , dimension Ordinal , dimension Time , regex "av|i" , dimension Time ] , prod = \tokens -> case tokens of (_: Token Ordinal (OrdinalData {TOrdinal.value = v}): Token Time td1: _: Token Time td2: _) -> Token Time . predNth (v - 1) False <$> intersect td2 td1 _ -> Nothing } ruleNewYearsDay :: Rule ruleNewYearsDay = Rule { name = "new year's day" , pattern = [ regex "ny\x00e5rsdag(en)?" ] , prod = \_ -> tt $ monthDay 1 1 } ruleLastTime :: Rule ruleLastTime = Rule { name = "last <time>" , pattern = [ regex "(sista|f\x00f6rra|senaste)" , 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 "l\x00f6rdag(en)?|l\x00f6r\\.?" ] , prod = \_ -> tt $ dayOfWeek 6 } ruleDatetimeDatetimeInterval :: Rule ruleDatetimeDatetimeInterval = Rule { name = "<datetime> - <datetime> (interval)" , pattern = [ Predicate isNotLatent , regex "\\-|till|till och med|tom" , Predicate isNotLatent ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_) -> Token Time <$> interval TTime.Closed td1 td2 _ -> Nothing } ruleNamedmonth7 :: Rule ruleNamedmonth7 = Rule { name = "named-month" , pattern = [ regex "juli|jul\\.?" ] , prod = \_ -> tt $ month 7 } ruleEvening :: Rule ruleEvening = Rule { name = "evening" , pattern = [ regex "kv\x00e4ll(en)?" ] , prod = \_ -> let from = hour False 18 to = hour False 0 in Token Time . mkLatent . partOfDay <$> interval TTime.Open from to } ruleTheDayofmonthNonOrdinal :: Rule ruleTheDayofmonthNonOrdinal = Rule { name = "the <day-of-month> (non ordinal)" , pattern = [ regex "den" , Predicate isDOMInteger ] , prod = \tokens -> case tokens of (_:token:_) -> do v <- getIntValue token tt . mkLatent $ dayOfMonth v _ -> Nothing } ruleCycleAfterTime :: Rule ruleCycleAfterTime = Rule { name = "<cycle> after <time>" , pattern = [ dimension TimeGrain , regex "efter" , dimension Time ] , prod = \tokens -> case tokens of (Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter False grain 1 td _ -> Nothing } ruleInDuration :: Rule ruleInDuration = Rule { name = "in <duration>" , pattern = [ regex "om" , dimension Duration ] , prod = \tokens -> case tokens of (_:Token Duration dd:_) -> tt $ inDuration dd _ -> Nothing } ruleNow :: Rule ruleNow = Rule { name = "now" , pattern = [ regex "just nu|nu|(i )?detta \x00f6gonblick" ] , prod = \_ -> tt $ cycleNth TG.Second 0 } ruleLastCycleOfTime :: Rule ruleLastCycleOfTime = Rule { name = "last <cycle> of <time>" , pattern = [ regex "sista" , dimension TimeGrain , regex "av|i" , dimension Time ] , prod = \tokens -> case tokens of (_:Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleLastOf grain td _ -> Nothing } ruleFromDatetimeDatetimeInterval :: Rule ruleFromDatetimeDatetimeInterval = Rule { name = "from <datetime> - <datetime> (interval)" , pattern = [ regex "fr\x00e5n" , dimension Time , regex "\\-|till|till och med|tom" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td1:_:Token Time td2:_) -> Token Time <$> interval TTime.Closed td1 td2 _ -> Nothing } ruleMonthDdddInterval :: Rule ruleMonthDdddInterval = Rule { name = "<month> dd-dd (interval)" , pattern = [ regex "([012]?\\d|30|31)(er|\\.)?" , regex "\\-|till" , regex "([012]?\\d|30|31)(er|\\.)?" , Predicate isAMonth ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (m1:_)): _: Token RegexMatch (GroupMatch (m2:_)): Token Time td: _) -> do v1 <- parseInt m1 v2 <- parseInt m2 from <- intersect (dayOfMonth v1) td to <- intersect (dayOfMonth v2) td Token Time <$> interval TTime.Closed from to _ -> Nothing } ruleNamedday4 :: Rule ruleNamedday4 = Rule { name = "named-day" , pattern = [ regex "torsdag(en)?|tors?\\.?" ] , prod = \_ -> tt $ dayOfWeek 4 } ruleTheCycleAfterTime :: Rule ruleTheCycleAfterTime = Rule { name = "the <cycle> after <time>" , pattern = [ dimension TimeGrain , regex "(en|na|et)? efter" , dimension Time ] , prod = \tokens -> case tokens of (Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter False grain 1 td _ -> Nothing } ruleTheCycleBeforeTime :: Rule ruleTheCycleBeforeTime = Rule { name = "the <cycle> before <time>" , pattern = [ dimension TimeGrain , regex "(en|na|et)? f\x00f6re" , dimension Time ] , prod = \tokens -> case tokens of (Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter False grain (-1) td _ -> Nothing } ruleYearLatent2 :: Rule ruleYearLatent2 = Rule { name = "year (latent)" , pattern = [ Predicate $ isIntegerBetween 2101 10000 ] , prod = \tokens -> case tokens of (token:_) -> do v <- getIntValue token tt . mkLatent $ year v _ -> Nothing } ruleTimeAfterNext :: Rule ruleTimeAfterNext = Rule { name = "<time> after next" , pattern = [ regex "n\x00e4sta" , dimension Time , regex "igen" ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ predNth 1 True td _ -> Nothing } ruleTheIdesOfNamedmonth :: Rule ruleTheIdesOfNamedmonth = Rule { name = "the ides of <named-month>" , pattern = [ regex "mitten av" , Predicate isAMonth ] , prod = \tokens -> case tokens of (_:Token Time td@TimeData {TTime.form = Just (TTime.Month m)}:_) -> Token Time <$> intersect (dayOfMonth $ if elem m [3, 5, 7, 10] then 15 else 13) td _ -> Nothing } ruleNoon :: Rule ruleNoon = Rule { name = "noon" , pattern = [ regex "middag|(kl(\\.|ockan)?)? tolv" ] , prod = \_ -> tt $ hour False 12 } ruleToday :: Rule ruleToday = Rule { name = "today" , pattern = [ regex "i dag|idag" ] , prod = \_ -> tt $ cycleNth TG.Day 0 } ruleThisnextDayofweek :: Rule ruleThisnextDayofweek = Rule { name = "this|next <day-of-week>" , pattern = [ regex "(kommande|n\x00e4sta)" , 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 "i f\x00f6rrg\x00e5r" ] , prod = \_ -> tt . cycleNth TG.Day $ - 2 } ruleBetweenTimeofdayAndTimeofdayInterval :: Rule ruleBetweenTimeofdayAndTimeofdayInterval = Rule { name = "between <time-of-day> and <time-of-day> (interval)" , pattern = [ regex "mellan" , Predicate isATimeOfDay , regex "och" , Predicate isATimeOfDay ] , prod = \tokens -> case tokens of (_:Token Time td1:_:Token Time td2:_) -> Token Time <$> interval TTime.Closed td1 td2 _ -> Nothing } ruleNextCycle :: Rule ruleNextCycle = Rule { name = "next <cycle>" , pattern = [ regex "n\x00e4sta|kommande" , dimension TimeGrain ] , prod = \tokens -> case tokens of (_:Token TimeGrain grain:_) -> tt $ cycleNth grain 1 _ -> Nothing } ruleNamedmonth :: Rule ruleNamedmonth = Rule { name = "named-month" , pattern = [ regex "januari|jan\\.?" ] , prod = \_ -> tt $ month 1 } ruleTheCycleOfTime :: Rule ruleTheCycleOfTime = Rule { name = "the <cycle> of <time>" , pattern = [ dimension TimeGrain , regex "(en|na|et)? av" , dimension Time ] , prod = \tokens -> case tokens of (Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter True grain 0 td _ -> Nothing } ruleTimeofdayApproximately :: Rule ruleTimeofdayApproximately = Rule { name = "<time-of-day> approximately" , pattern = [ Predicate isATimeOfDay , regex "(cirka|ca\\.|-?ish)" ] , prod = \tokens -> case tokens of (Token Time td:_) -> tt $ notLatent td _ -> Nothing } ruleOnDate :: Rule ruleOnDate = Rule { name = "on <date>" , pattern = [ regex "den|p\x00e5|under" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ notLatent td _ -> Nothing } ruleNamedmonth3 :: Rule ruleNamedmonth3 = Rule { name = "named-month" , pattern = [ regex "mars|mar\\.?" ] , prod = \_ -> tt $ month 3 } ruleDurationFromNow :: Rule ruleDurationFromNow = Rule { name = "<duration> from now" , pattern = [ dimension Duration , regex "fr\x00e5n (idag|nu)" ] , prod = \tokens -> case tokens of (Token Duration dd:_) -> tt $ inDuration dd _ -> Nothing } ruleLunch :: Rule ruleLunch = Rule { name = "lunch" , pattern = [ regex "lunch(en)?" ] , prod = \_ -> let from = hour False 12 to = hour False 14 in Token Time . mkLatent . partOfDay <$> interval TTime.Open from to } ruleLastCycle :: Rule ruleLastCycle = Rule { name = "last <cycle>" , pattern = [ regex "sista|senaste|f\x00f6rra" , dimension TimeGrain ] , prod = \tokens -> case tokens of (_:Token TimeGrain grain:_) -> tt . cycleNth grain $ - 1 _ -> 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 (m1:m2:_)):_) -> do d <- parseInt m1 m <- parseInt m2 tt $ monthDay m d _ -> Nothing } ruleAfternoon :: Rule ruleAfternoon = Rule { name = "afternoon" , pattern = [ regex "eftermiddag(en)?" ] , 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 "april|apr\\.?" ] , prod = \_ -> tt $ month 4 } ruleTimeBeforeLast :: Rule ruleTimeBeforeLast = Rule { name = "<time> before last" , pattern = [ regex "sista" , dimension Time , regex "igen" ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ predNth (-2) False td _ -> Nothing } ruleNamedmonthDayofmonthOrdinal :: Rule ruleNamedmonthDayofmonthOrdinal = Rule { name = "<named-month> <day-of-month> (ordinal)" , pattern = [ Predicate isAMonth , Predicate isDOMOrdinal ] , prod = \tokens -> case tokens of (Token Time td:token:_) -> Token Time <$> intersectDOM td token _ -> Nothing } ruleChristmasEve :: Rule ruleChristmasEve = Rule { name = "christmas eve" , pattern = [ regex "julafton?" ] , prod = \_ -> tt $ monthDay 12 24 } ruleInduringThePartofday :: Rule ruleInduringThePartofday = Rule { name = "in|during the <part-of-day>" , pattern = [ regex "om|i" , Predicate isAPartOfDay ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ notLatent td _ -> Nothing } ruleNamedday5 :: Rule ruleNamedday5 = Rule { name = "named-day" , pattern = [ regex "fredag(en)?|fre\\.?" ] , prod = \_ -> tt $ dayOfWeek 5 } ruleDayofmonthordinalNamedmonth :: Rule ruleDayofmonthordinalNamedmonth = Rule { name = "<day-of-month>(ordinal) <named-month>" , pattern = [ Predicate isDOMOrdinal , Predicate isAMonth ] , prod = \tokens -> case tokens of (token:Token Time td:_) -> Token Time <$> intersectDOM td token _ -> Nothing } ruleIntersectBy :: Rule ruleIntersectBy = Rule { name = "intersect by \",\"" , pattern = [ Predicate isNotLatent , regex "," , Predicate isNotLatent ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_) -> Token Time <$> intersect td1 td2 _ -> Nothing } ruleNthTimeAfterTime :: Rule ruleNthTimeAfterTime = Rule { name = "nth <time> after <time>" , pattern = [ dimension Ordinal , dimension Time , regex "efter" , dimension Time ] , prod = \tokens -> case tokens of (Token Ordinal (OrdinalData {TOrdinal.value = v}): Token Time td1: _: Token Time td2: _) -> tt $ predNthAfter (v - 1) td1 td2 _ -> Nothing } ruleAfterDuration :: Rule ruleAfterDuration = Rule { name = "after <duration>" , pattern = [ regex "efter" , dimension Duration ] , prod = \tokens -> case tokens of (_:Token Duration dd:_) -> tt . withDirection TTime.After $ inDuration dd _ -> Nothing } ruleTimeofdayLatent :: Rule ruleTimeofdayLatent = Rule { name = "time-of-day (latent)" , pattern = [ Predicate $ isIntegerBetween 0 23 ] , prod = \tokens -> case tokens of (token:_) -> do n <- getIntValue token tt . mkLatent $ hour False n _ -> Nothing } ruleDayofmonthOrdinalOfNamedmonth :: Rule ruleDayofmonthOrdinalOfNamedmonth = Rule { name = "<day-of-month> (ordinal) of <named-month>" , pattern = [ Predicate isDOMOrdinal , regex "av|i" , Predicate isAMonth ] , prod = \tokens -> case tokens of (token:_:Token Time td:_) -> Token Time <$> intersectDOM td token _ -> Nothing } ruleFromTimeofdayTimeofdayInterval :: Rule ruleFromTimeofdayTimeofdayInterval = Rule { name = "from <time-of-day> - <time-of-day> (interval)" , pattern = [ regex "(efter|fr\x00e5n)" , Predicate isATimeOfDay , regex "((men )?f\x00f6re)|\\-|till|till och med|tom" , Predicate isATimeOfDay ] , prod = \tokens -> case tokens of (_:Token Time td1:_:Token Time td2:_) -> Token Time <$> interval TTime.Closed td1 td2 _ -> Nothing } ruleNamedmonth2 :: Rule ruleNamedmonth2 = Rule { name = "named-month" , pattern = [ regex "februari|feb\\.?" ] , prod = \_ -> tt $ month 2 } ruleExactlyTimeofday :: Rule ruleExactlyTimeofday = Rule { name = "exactly <time-of-day>" , pattern = [ regex "(precis|exakt)( kl.| klockan)?" , Predicate isATimeOfDay ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ notLatent td _ -> Nothing } ruleInduringThePartofday2 :: Rule ruleInduringThePartofday2 = Rule { name = "in|during the <part-of-day>" , pattern = [ regex "om|i" , Predicate isAPartOfDay , regex "en|ten" ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ notLatent td _ -> Nothing } ruleSeason :: Rule ruleSeason = Rule { name = "season" , pattern = [ regex "sommar(en)" ] , prod = \_ -> let from = monthDay 6 21 to = monthDay 9 23 in Token Time <$> interval TTime.Open from to } ruleBetweenDatetimeAndDatetimeInterval :: Rule ruleBetweenDatetimeAndDatetimeInterval = Rule { name = "between <datetime> and <datetime> (interval)" , pattern = [ regex "mellan" , dimension Time , regex "och" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td1:_:Token Time td2:_) -> Token Time <$> interval TTime.Closed td1 td2 _ -> Nothing } ruleNewYearsEve :: Rule ruleNewYearsEve = Rule { name = "new year's eve" , pattern = [ regex "ny\x00e5rsafton?" ] , prod = \_ -> tt $ monthDay 12 31 } ruleDurationAgo :: Rule ruleDurationAgo = Rule { name = "<duration> ago" , pattern = [ dimension Duration , regex "sedan" ] , prod = \tokens -> case tokens of (Token Duration dd:_) -> tt $ durationAgo dd _ -> Nothing } ruleByTheEndOfTime :: Rule ruleByTheEndOfTime = Rule { name = "by the end of <time>" , pattern = [ regex "i slutet av" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> Token Time <$> interval TTime.Closed (cycleNth TG.Second 0) td _ -> Nothing } ruleAfterWork :: Rule ruleAfterWork = Rule { name = "after work" , pattern = [ regex "efter jobbet" ] , prod = \_ -> do let td1 = cycleNth TG.Day 0 td2 <- interval TTime.Open (hour False 17) (hour False 21) Token Time . partOfDay <$> intersect td1 td2 } ruleLastNCycle :: Rule ruleLastNCycle = Rule { name = "last n <cycle>" , pattern = [ regex "sista|senaste|f\x00f6rra" , Predicate $ isIntegerBetween 1 9999 , dimension TimeGrain ] , prod = \tokens -> case tokens of (_:token:Token TimeGrain grain:_) -> do v <- getIntValue token tt $ cycleN True grain (- v) _ -> Nothing } ruleTimeofdaySharp :: Rule ruleTimeofdaySharp = Rule { name = "<time-of-day> sharp" , pattern = [ Predicate isATimeOfDay , regex "(sharp|precis|exakt)" ] , prod = \tokens -> case tokens of (Token Time td:_) -> tt $ notLatent td _ -> Nothing } ruleWithinDuration :: Rule ruleWithinDuration = Rule { name = "within <duration>" , pattern = [ regex "(innanf\x00f6r|inom)" , 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 } ruleMidnighteodendOfDay :: Rule ruleMidnighteodendOfDay = Rule { name = "midnight|EOD|end of day" , pattern = [ regex "midnatt|EOD" ] , prod = \_ -> tt $ hour False 0 } ruleDayofmonthNonOrdinalNamedmonth :: Rule ruleDayofmonthNonOrdinalNamedmonth = Rule { name = "<day-of-month> (non ordinal) <named-month>" , pattern = [ Predicate isDOMInteger , Predicate isAMonth ] , prod = \tokens -> case tokens of (token:Token Time td:_) -> Token Time <$> intersectDOM td token _ -> 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 } ruleAboutTimeofday :: Rule ruleAboutTimeofday = Rule { name = "about <time-of-day>" , pattern = [ regex "(omkring|cirka|vid|runt|ca\\.)( kl\\.| klockan)?" , Predicate isATimeOfDay ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ notLatent td _ -> Nothing } ruleUntilTimeofday :: Rule ruleUntilTimeofday = Rule { name = "until <time-of-day>" , pattern = [ regex "innan|f\x00f6re|intill" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ withDirection TTime.Before td _ -> Nothing } ruleAtTimeofday :: Rule ruleAtTimeofday = Rule { name = "at <time-of-day>" , pattern = [ regex "klockan|kl.|kl|@" , Predicate isATimeOfDay ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ notLatent td _ -> Nothing } ruleNamedmonth6 :: Rule ruleNamedmonth6 = Rule { name = "named-month" , pattern = [ regex "juni|jun\\.?" ] , prod = \_ -> tt $ month 6 } ruleNthTimeOfTime :: Rule ruleNthTimeOfTime = Rule { name = "nth <time> of <time>" , pattern = [ dimension Ordinal , dimension Time , regex "av|i" , dimension Time ] , prod = \tokens -> case tokens of (Token Ordinal (OrdinalData {TOrdinal.value = v}): Token Time td1: _: Token Time td2: _) -> Token Time . predNth (v - 1) False <$> intersect td2 td1 _ -> Nothing } ruleNamedmonth8 :: Rule ruleNamedmonth8 = Rule { name = "named-month" , pattern = [ regex "augusti|aug\\.?" ] , prod = \_ -> tt $ month 8 } ruleTimePartofday :: Rule ruleTimePartofday = Rule { name = "<time> <part-of-day>" , pattern = [ dimension Time , Predicate isAPartOfDay ] , prod = \tokens -> case tokens of (Token Time td1:Token Time td2:_) -> Token Time <$> intersect td1 td2 _ -> Nothing } ruleWeekend :: Rule ruleWeekend = Rule { name = "week-end" , pattern = [ regex "((week(\\s|-)?end)|helg)(en)?" ] , prod = \_ -> do from <- intersect (dayOfWeek 5) (hour False 18) to <- intersect (dayOfWeek 1) (hour False 0) Token Time <$> interval TTime.Open from to } ruleEomendOfMonth :: Rule ruleEomendOfMonth = Rule { name = "EOM|End of month" , pattern = [ regex "EOM" ] , prod = \_ -> tt $ cycleNth TG.Month 1 } ruleLastYear :: Rule ruleLastYear = Rule { name = "Last year" , pattern = [ regex "i fjol|ifjol" ] , prod = \_ -> tt . cycleNth TG.Year $ - 1 } ruleNthTimeAfterTime2 :: Rule ruleNthTimeAfterTime2 = Rule { name = "nth <time> after <time>" , pattern = [ regex "den" , dimension Ordinal , dimension Time , regex "efter" , dimension Time ] , prod = \tokens -> case tokens of (_: Token Ordinal (OrdinalData {TOrdinal.value = v}): Token Time td1: _: Token Time td2: _) -> tt $ predNthAfter (v - 1) td1 td2 _ -> Nothing } ruleNextTime :: Rule ruleNextTime = Rule { name = "next <time>" , pattern = [ regex "n\x00e4sta|kommande" , Predicate isNotLatent ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ predNth 0 True td _ -> Nothing } ruleOrdinalQuarterYear :: Rule ruleOrdinalQuarterYear = Rule { name = "<ordinal> quarter <year>" , pattern = [ dimension Ordinal , Predicate $ isGrain TG.Quarter , dimension Time ] , prod = \tokens -> case tokens of (Token Ordinal od:_:Token Time td:_) -> tt $ cycleNthAfter False TG.Quarter (TOrdinal.value od - 1) td _ -> 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 (m1:m2:m3:_)):_) -> do y <- parseInt m1 m <- parseInt m2 d <- parseInt m3 tt $ yearMonthDay y m d _ -> Nothing } ruleTheOrdinalCycleAfterTime :: Rule ruleTheOrdinalCycleAfterTime = Rule { name = "the <ordinal> <cycle> after <time>" , pattern = [ regex "den" , dimension Ordinal , dimension TimeGrain , regex "efter" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Ordinal od:Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter True grain (TOrdinal.value od - 1) td _ -> Nothing } ruleIntersectByOfFromS :: Rule ruleIntersectByOfFromS = Rule { name = "intersect by \"of\", \"from\", \"'s\"" , pattern = [ Predicate isNotLatent , regex "i" , Predicate isNotLatent ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_) -> Token Time <$> intersect td1 td2 _ -> Nothing } ruleNextNCycle :: Rule ruleNextNCycle = Rule { name = "next n <cycle>" , pattern = [ regex "n\x00e4sta" , Predicate $ isIntegerBetween 1 9999 , dimension TimeGrain ] , prod = \tokens -> case tokens of (_:token:Token TimeGrain grain:_) -> do v <- getIntValue token tt $ cycleN True grain v _ -> Nothing } ruleADuration :: Rule ruleADuration = Rule { name = "a <duration>" , pattern = [ regex "(om )?en|ett" , dimension Duration ] , prod = \tokens -> case tokens of (_:Token Duration dd:_) -> tt $ inDuration dd _ -> Nothing } ruleMorning :: Rule ruleMorning = Rule { name = "morning" , pattern = [ regex "morgon(en)?" ] , 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 "i|denna" , Predicate isAPartOfDay ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> Token Time . partOfDay <$> intersect (cycleNth TG.Day 0) td _ -> Nothing } ruleThisCycle :: Rule ruleThisCycle = Rule { name = "this <cycle>" , pattern = [ regex "denna|detta|i|nuvarande" , dimension TimeGrain ] , prod = \tokens -> case tokens of (_:Token TimeGrain grain:_) -> tt $ cycleNth grain 0 _ -> Nothing } ruleThisTime :: Rule ruleThisTime = Rule { name = "this <time>" , pattern = [ regex "(denna|detta|i|den h\x00e4r)" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt $ predNth 0 False td _ -> Nothing } ruleDayofmonthNonOrdinalOfNamedmonth :: Rule ruleDayofmonthNonOrdinalOfNamedmonth = Rule { name = "<day-of-month> (non ordinal) of <named-month>" , pattern = [ Predicate isDOMInteger , regex "av|i" , Predicate isAMonth ] , prod = \tokens -> case tokens of (token:_:Token Time td:_) -> Token Time <$> intersectDOM td token _ -> Nothing } ruleAfterLunch :: Rule ruleAfterLunch = Rule { name = "after lunch" , pattern = [ regex "efter (lunch)" ] , prod = \_ -> do let td1 = cycleNth TG.Day 0 td2 <- interval TTime.Open (hour False 13) (hour False 17) Token Time . partOfDay <$> intersect td1 td2 } ruleOnANamedday :: Rule ruleOnANamedday = Rule { name = "on a named-day" , pattern = [ regex "p\x00e5 en" , Predicate isADayOfWeek ] , prod = \tokens -> case tokens of (_:x:_) -> Just x _ -> Nothing } ruleYearLatent :: Rule ruleYearLatent = Rule { name = "year (latent)" , pattern = [ Predicate $ isIntegerBetween (- 10000) 999 ] , prod = \tokens -> case tokens of (token:_) -> do v <- getIntValue token tt . mkLatent $ year v _ -> Nothing } ruleYesterday :: Rule ruleYesterday = Rule { name = "yesterday" , pattern = [ regex "i g\x00e5r|ig\x00e5r" ] , prod = \_ -> tt . cycleNth TG.Day $ - 1 } ruleSeason2 :: Rule ruleSeason2 = Rule { name = "season" , pattern = [ regex "vinter(n)" ] , prod = \_ -> let from = monthDay 12 21 to = monthDay 3 20 in Token Time <$> interval TTime.Open from to } ruleAfterTimeofday :: Rule ruleAfterTimeofday = Rule { name = "after <time-of-day>" , pattern = [ regex "efter" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td:_) -> tt . notLatent $ withDirection TTime.After td _ -> Nothing } ruleChristmas :: Rule ruleChristmas = Rule { name = "christmas" , pattern = [ regex "juldag(en)?" ] , prod = \_ -> tt $ monthDay 12 25 } ruleNight :: Rule ruleNight = Rule { name = "night" , pattern = [ regex "natt(en)?" ] , prod = \_ -> let from = hour False 0 to = hour False 4 in Token Time . mkLatent . partOfDay <$> interval TTime.Open from to } ruleDayofmonthOrdinal :: Rule ruleDayofmonthOrdinal = Rule { name = "<day-of-month> (ordinal)" , pattern = [ Predicate isDOMOrdinal ] , prod = \tokens -> case tokens of (Token Ordinal (OrdinalData {TOrdinal.value = v}):_) -> tt . mkLatent $ dayOfMonth v _ -> Nothing } ruleOrdinalCycleAfterTime :: Rule ruleOrdinalCycleAfterTime = Rule { name = "<ordinal> <cycle> after <time>" , pattern = [ dimension Ordinal , dimension TimeGrain , regex "efter" , dimension Time ] , prod = \tokens -> case tokens of (Token Ordinal od:Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter True grain (TOrdinal.value od - 1) td _ -> Nothing } ruleOrdinalCycleOfTime :: Rule ruleOrdinalCycleOfTime = Rule { name = "<ordinal> <cycle> of <time>" , pattern = [ dimension Ordinal , dimension TimeGrain , regex "av|i|fr\x00e5n" , dimension Time ] , prod = \tokens -> case tokens of (Token Ordinal od:Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter True grain (TOrdinal.value od - 1) td _ -> Nothing } ruleNamedmonth5 :: Rule ruleNamedmonth5 = Rule { name = "named-month" , pattern = [ regex "maj" ] , prod = \_ -> tt $ month 5 } ruleNamedday7 :: Rule ruleNamedday7 = Rule { name = "named-day" , pattern = [ regex "s\x00f6ndag(en)?|s\x00f6n\\.?" ] , prod = \_ -> tt $ dayOfWeek 7 } ruleHhmm :: Rule ruleHhmm = Rule { name = "hh:mm" , 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 $ hourMinute False h m _ -> Nothing } ruleTonight :: Rule ruleTonight = Rule { name = "tonight" , pattern = [ regex "ikv\x00e4ll" ] , prod = \_ -> do let td1 = cycleNth TG.Day 0 td2 <- interval TTime.Open (hour False 18) (hour False 0) Token Time . partOfDay <$> intersect td1 td2 } ruleYear :: Rule ruleYear = Rule { name = "year" , pattern = [ Predicate $ isIntegerBetween 1000 2100 ] , prod = \tokens -> case tokens of (token:_) -> do v <- getIntValue token tt $ year v _ -> Nothing } ruleNamedmonth10 :: Rule ruleNamedmonth10 = Rule { name = "named-month" , pattern = [ regex "oktober|okt\\.?" ] , prod = \_ -> tt $ month 10 } ruleNamedmonthDayofmonthNonOrdinal :: Rule ruleNamedmonthDayofmonthNonOrdinal = Rule { name = "<named-month> <day-of-month> (non ordinal)" , pattern = [ Predicate isAMonth , Predicate isDOMInteger ] , prod = \tokens -> case tokens of (Token Time td:token:_) -> Token Time <$> intersectDOM td token _ -> Nothing } ruleAbsorptionOfAfterNamedDay :: Rule ruleAbsorptionOfAfterNamedDay = Rule { name = "absorption of , after named day" , pattern = [ Predicate isADayOfWeek , regex "," ] , prod = \tokens -> case tokens of (x:_) -> Just x _ -> Nothing } ruleLastDayofweekOfTime :: Rule ruleLastDayofweekOfTime = Rule { name = "last <day-of-week> of <time>" , pattern = [ regex "sista" , Predicate isADayOfWeek , regex "av|i" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Time td1:_:Token Time td2:_) -> tt $ predLastOf td1 td2 _ -> Nothing } ruleCycleBeforeTime :: Rule ruleCycleBeforeTime = Rule { name = "<cycle> before <time>" , pattern = [ dimension TimeGrain , regex "f\x00f6re" , dimension Time ] , prod = \tokens -> case tokens of (Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter False grain (-1) td _ -> 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 } ruleTimeofdayTimeofdayInterval :: Rule ruleTimeofdayTimeofdayInterval = Rule { name = "<time-of-day> - <time-of-day> (interval)" , pattern = [ Predicate $ liftM2 (&&) isATimeOfDay isNotLatent , regex "\\-|till|till och med|tom" , Predicate isATimeOfDay ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_) -> Token Time <$> interval TTime.Closed td1 td2 _ -> Nothing } ruleNamedmonth11 :: Rule ruleNamedmonth11 = Rule { name = "named-month" , pattern = [ regex "november|nov\\.?" ] , prod = \_ -> tt $ month 11 } ruleDurationAfterTime :: Rule ruleDurationAfterTime = Rule { name = "<duration> after <time>" , pattern = [ dimension Duration , regex "efter" , dimension Time ] , prod = \tokens -> case tokens of (Token Duration dd:_:Token Time td:_) -> tt $ durationAfter dd td _ -> Nothing } ruleOrdinalQuarter :: Rule ruleOrdinalQuarter = Rule { name = "<ordinal> quarter" , pattern = [ dimension Ordinal , Predicate $ isGrain TG.Quarter ] , prod = \tokens -> case tokens of (Token Ordinal (OrdinalData {TOrdinal.value = v}):_) -> tt . cycleNthAfter False TG.Quarter (v - 1) $ cycleNth TG.Year 0 _ -> Nothing } ruleNamedday3 :: Rule ruleNamedday3 = Rule { name = "named-day" , pattern = [ regex "onsdag(en)?|ons\\.?" ] , prod = \_ -> tt $ dayOfWeek 3 } ruleTheDayofmonthOrdinal :: Rule ruleTheDayofmonthOrdinal = Rule { name = "the <day-of-month> (ordinal)" , pattern = [ regex "den" , Predicate isDOMOrdinal ] , prod = \tokens -> case tokens of (_: Token Ordinal (OrdinalData {TOrdinal.value = v}): _) -> tt $ dayOfMonth v _ -> Nothing } ruleDurationBeforeTime :: Rule ruleDurationBeforeTime = Rule { name = "<duration> before <time>" , pattern = [ dimension Duration , regex "f\x00f6re" , dimension Time ] , prod = \tokens -> case tokens of (Token Duration dd:_:Token Time td:_) -> tt $ durationBefore dd td _ -> Nothing } rulePartofdayOfTime :: Rule rulePartofdayOfTime = Rule { name = "<part-of-day> of <time>" , pattern = [ Predicate isAPartOfDay , regex "(en |ten )?den" , dimension Time ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_) -> Token Time <$> intersect td1 td2 _ -> Nothing } ruleEoyendOfYear :: Rule ruleEoyendOfYear = Rule { name = "EOY|End of year" , pattern = [ regex "EOY" ] , prod = \_ -> tt $ cycleNth TG.Year 1 } ruleTomorrow :: Rule ruleTomorrow = Rule { name = "tomorrow" , pattern = [ regex "i morgon|imorgon" ] , prod = \_ -> tt $ cycleNth TG.Day 1 } ruleTimeofdayOclock :: Rule ruleTimeofdayOclock = Rule { name = "<time-of-day> o'clock" , pattern = [ Predicate isATimeOfDay , regex "( )?h" ] , prod = \tokens -> case tokens of (Token Time td:_) -> tt $ notLatent td _ -> Nothing } ruleNamedmonth9 :: Rule ruleNamedmonth9 = Rule { name = "named-month" , pattern = [ regex "september|sept?\\.?" ] , prod = \_ -> tt $ month 9 } ruleDayofmonthordinalNamedmonthYear :: Rule ruleDayofmonthordinalNamedmonthYear = Rule { name = "<day-of-month>(ordinal) <named-month> year" , pattern = [ Predicate isDOMOrdinal , Predicate isAMonth , regex "(\\d{2,4})" ] , prod = \tokens -> case tokens of (token: Token Time td: Token RegexMatch (GroupMatch (match:_)): _) -> do y <- parseInt match dom <- intersectDOM td token Token Time <$> intersect dom (year y) _ -> Nothing } ruleHhmmss :: Rule ruleHhmmss = Rule { name = "hh:mm:ss" , pattern = [ regex "((?:[01]?\\d)|(?:2[0-3]))[:.]([0-5]\\d)[:.]([0-5]\\d)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (hh:mm:ss:_)):_) -> do h <- parseInt hh m <- parseInt mm s <- parseInt ss tt $ hourMinuteSecond False h m s _ -> Nothing } ruleTimezone :: Rule ruleTimezone = Rule { name = "<time> timezone" , pattern = [ Predicate $ liftM2 (&&) isATimeOfDay isNotLatent , 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 = [ ruleADuration , ruleAboutTimeofday , ruleAbsorptionOfAfterNamedDay , ruleAfterDuration , ruleAfterLunch , ruleAfterTimeofday , ruleAfterWork , ruleAfternoon , ruleAtTimeofday , ruleBetweenDatetimeAndDatetimeInterval , ruleBetweenTimeofdayAndTimeofdayInterval , ruleByTheEndOfTime , ruleChristmas , ruleChristmasEve , ruleCycleAfterTime , ruleCycleBeforeTime , ruleDatetimeDatetimeInterval , ruleDayofmonthNonOrdinalNamedmonth , ruleDayofmonthNonOrdinalOfNamedmonth , ruleDayofmonthOrdinal , ruleDayofmonthOrdinalOfNamedmonth , ruleDayofmonthordinalNamedmonth , ruleDayofmonthordinalNamedmonthYear , ruleDdmm , ruleDdmmyyyy , ruleDurationAfterTime , ruleDurationAgo , ruleDurationBeforeTime , ruleDurationFromNow , ruleEomendOfMonth , ruleEoyendOfYear , ruleEvening , ruleExactlyTimeofday , ruleFromDatetimeDatetimeInterval , ruleFromTimeofdayTimeofdayInterval , ruleHhmm , ruleHhmmss , ruleHourofdayIntegerAsRelativeMinutes , ruleHourofdayQuarter , ruleHourofdayHalf , ruleInDuration , ruleInduringThePartofday , ruleInduringThePartofday2 , ruleIntersect , ruleIntersectBy , ruleIntersectByOfFromS , ruleLastCycle , ruleLastCycleOfTime , ruleLastDayofweekOfTime , ruleLastNCycle , ruleLastTime , ruleLastYear , ruleLunch , ruleMidnighteodendOfDay , ruleMonthDdddInterval , ruleMorning , ruleNamedday , ruleNamedday2 , ruleNamedday3 , ruleNamedday4 , ruleNamedday5 , ruleNamedday6 , ruleNamedday7 , ruleNamedmonth , ruleNamedmonth10 , ruleNamedmonth11 , ruleNamedmonth12 , ruleNamedmonth2 , ruleNamedmonth3 , ruleNamedmonth4 , ruleNamedmonth5 , ruleNamedmonth6 , ruleNamedmonth7 , ruleNamedmonth8 , ruleNamedmonth9 , ruleNamedmonthDayofmonthNonOrdinal , ruleNamedmonthDayofmonthOrdinal , ruleNewYearsDay , ruleNewYearsEve , ruleNextCycle , ruleNextNCycle , ruleNextTime , ruleNight , ruleNoon , ruleNow , ruleNthTimeAfterTime , ruleNthTimeAfterTime2 , ruleNthTimeOfTime , ruleNthTimeOfTime2 , ruleOnANamedday , ruleOnDate , ruleOrdinalCycleAfterTime , ruleOrdinalCycleOfTime , ruleOrdinalQuarter , ruleOrdinalQuarterYear , rulePartofdayOfTime , ruleRelativeMinutesAfterpastIntegerHourofday , ruleQuarterAfterpastIntegerHourofday , ruleHalfAfterpastIntegerHourofday , ruleRelativeMinutesTotillbeforeIntegerHourofday , ruleQuarterTotillbeforeIntegerHourofday , ruleHalfTotillbeforeIntegerHourofday , ruleSeason , ruleSeason2 , ruleTheCycleAfterTime , ruleTheCycleBeforeTime , ruleTheCycleOfTime , ruleTheDayAfterTomorrow , ruleTheDayBeforeYesterday , ruleTheDayofmonthNonOrdinal , ruleTheDayofmonthOrdinal , ruleTheIdesOfNamedmonth , ruleTheOrdinalCycleAfterTime , ruleTheOrdinalCycleOfTime , ruleThisCycle , ruleThisPartofday , ruleThisTime , ruleThisnextDayofweek , ruleTimeAfterNext , ruleTimeBeforeLast , ruleTimePartofday , ruleTimeofdayApproximately , ruleTimeofdayLatent , ruleTimeofdayOclock , ruleTimeofdaySharp , ruleTimeofdayTimeofdayInterval , ruleToday , ruleTomorrow , ruleTonight , ruleUntilTimeofday , ruleWeekend , ruleWithinDuration , ruleYear , ruleYearLatent , ruleYearLatent2 , ruleYesterday , ruleYyyymmdd , ruleTimezone ]
rfranek/duckling
Duckling/Time/SV/Rules.hs
bsd-3-clause
46,094
0
23
12,283
13,466
7,309
6,157
1,496
3
{-# OPTIONS_GHC -fno-warn-orphans #-} -- | Aeson orphan instances for core module Pos.Core.Aeson.Orphans ( ) where import qualified Data.Aeson.Options as S (defaultOptions) import Data.Aeson.TH (deriveJSON) import Data.Time.Units (Microsecond, Millisecond, Second) deriveJSON S.defaultOptions ''Millisecond deriveJSON S.defaultOptions ''Microsecond deriveJSON S.defaultOptions ''Second
input-output-hk/pos-haskell-prototype
core/src/Pos/Core/Aeson/Orphans.hs
mit
424
0
6
77
91
53
38
-1
-1
{-# LANGUAGE TypeFamilies #-} module Pos.Chain.Ssc.Functions ( hasCommitment , hasOpening , hasShares , hasVssCertificate -- * SscPayload , verifySscPayload -- * VSS , vssThreshold , getStableCertsPure ) where import Universum hiding (id) import Control.Lens (to) import Control.Monad.Except (MonadError (throwError)) import qualified Data.HashMap.Strict as HM import Serokell.Util.Verify (isVerSuccess) import Pos.Chain.Block.IsHeader (IsMainHeader, headerSlotL) import Pos.Chain.Genesis as Genesis (Config (..), configBlkSecurityParam, configVssCerts) import Pos.Chain.Ssc.Base (checkCertTTL, isCommitmentId, isOpeningId, isSharesId, verifySignedCommitment, vssThreshold) import Pos.Chain.Ssc.CommitmentsMap (CommitmentsMap (..)) import Pos.Chain.Ssc.Error (SscVerifyError (..)) import Pos.Chain.Ssc.Payload (SscPayload (..)) import Pos.Chain.Ssc.Toss.Base (verifyEntriesGuardM) import Pos.Chain.Ssc.Types (SscGlobalState (..)) import qualified Pos.Chain.Ssc.VssCertData as VCD import Pos.Chain.Ssc.VssCertificatesMap (VssCertificatesMap) import Pos.Core (EpochIndex (..), SlotId (..), StakeholderId, pcBlkSecurityParam) import Pos.Core.Slotting (crucialSlot) import Pos.Util.Some (Some) ---------------------------------------------------------------------------- -- Simple predicates for SSC.Types ---------------------------------------------------------------------------- hasCommitment :: StakeholderId -> SscGlobalState -> Bool hasCommitment id = HM.member id . getCommitmentsMap . _sgsCommitments hasOpening :: StakeholderId -> SscGlobalState -> Bool hasOpening id = HM.member id . _sgsOpenings hasShares :: StakeholderId -> SscGlobalState -> Bool hasShares id = HM.member id . _sgsShares hasVssCertificate :: StakeholderId -> SscGlobalState -> Bool hasVssCertificate id = VCD.member id . _sgsVssCertificates ---------------------------------------------------------------------------- -- SscPayload Part ---------------------------------------------------------------------------- -- CHECK: @verifySscPayload -- Verify payload using header containing this payload. -- -- For each DS datum we check: -- -- 1. Whether it's stored in the correct block (e.g. commitments have to be -- in first 2 * blkSecurityParam blocks, etc.) -- -- 2. Whether the message itself is correct (e.g. commitment signature is -- valid, etc.) -- -- We also do some general sanity checks. verifySscPayload :: MonadError SscVerifyError m => Genesis.Config -> Either EpochIndex (Some IsMainHeader) -> SscPayload -> m () verifySscPayload genesisConfig eoh payload = case payload of CommitmentsPayload comms certs -> do whenHeader eoh isComm commChecks comms certsChecks certs OpeningsPayload _ certs -> do whenHeader eoh isOpen certsChecks certs SharesPayload _ certs -> do whenHeader eoh isShare certsChecks certs CertificatesPayload certs -> do whenHeader eoh isOther certsChecks certs where whenHeader (Left _) _ = pass whenHeader (Right header) f = f $ header ^. headerSlotL epochId = either identity (view $ headerSlotL . to siEpoch) eoh pc = configProtocolConstants genesisConfig k = pcBlkSecurityParam pc isComm slotId = unless (isCommitmentId k slotId) $ throwError $ NotCommitmentPhase slotId isOpen slotId = unless (isOpeningId k slotId) $ throwError $ NotOpeningPhase slotId isShare slotId = unless (isSharesId k slotId) $ throwError $ NotSharesPhase slotId isOther slotId = unless (all not $ map ($ slotId) [isCommitmentId k, isOpeningId k, isSharesId k]) $ throwError $ NotIntermediatePhase slotId -- We *forbid* blocks from having commitments/openings/shares in blocks -- with wrong slotId (instead of merely discarding such commitments/etc) -- because it's the miner's responsibility not to include them into the -- block if they're late. -- -- CHECK: For commitments specifically, we also -- -- * check there are only commitments in the block -- * use verifySignedCommitment, which checks commitments themselves, -- e.g. checks their signatures (which includes checking that the -- commitment has been generated for this particular epoch) -- -- #verifySignedCommitment commChecks commitments = do let checkComm = isVerSuccess . verifySignedCommitment (configProtocolMagic genesisConfig) epochId verifyEntriesGuardM fst snd CommitmentInvalid (pure . checkComm) (HM.toList . getCommitmentsMap $ commitments) -- CHECK: Vss certificates checker -- -- * VSS certificates are signed properly -- * VSS certificates have valid TTLs -- -- #checkCert certsChecks certs = verifyEntriesGuardM identity identity CertificateInvalidTTL (pure . checkCertTTL pc epochId) (toList certs) ---------------------------------------------------------------------------- -- Modern ---------------------------------------------------------------------------- getStableCertsPure :: Genesis.Config -> EpochIndex -> VCD.VssCertData -> VssCertificatesMap getStableCertsPure genesisConfig epoch certs | epoch == 0 = configVssCerts genesisConfig | otherwise = VCD.certs $ VCD.setLastKnownSlot (crucialSlot (configBlkSecurityParam genesisConfig) epoch) certs
input-output-hk/pos-haskell-prototype
chain/src/Pos/Chain/Ssc/Functions.hs
mit
5,863
0
15
1,426
1,047
579
468
-1
-1
module SugarScape.Core.Simulation ( SimulationState (..) , SimStepOut , AgentObservable , initSimulation , initSimulationOpt , initSimulationRng , initSimulationSeed , simulationStep , mkSimState , simulateUntil , simulateUntilLast , sugarScapeTimeDelta , runAgentSF , runEnv ) where import Data.Maybe import System.Random import Control.Monad.Random import Control.Monad.State.Strict import Data.MonadicStreamFunction.InternalCore import qualified Data.IntMap.Strict as Map -- better performance than normal Map according to hackage page import SugarScape.Agent.Interface import SugarScape.Core.Common import SugarScape.Core.Environment import SugarScape.Core.Model import SugarScape.Core.Init import SugarScape.Core.Random import SugarScape.Core.Scenario type AgentMap g = Map.IntMap (SugAgentMSF g, SugAgentObservable) type EventList = [(AgentId, ABSEvent SugEvent)] -- from, to, event type AgentObservable o = (AgentId, o) type SimStepOut = (Time, Int, SugEnvironment, [AgentObservable SugAgentObservable]) -- NOTE: strictness on those fields, otherwise space-leak -- (memory consumption increases throughout run-time and execution gets slower and slower) data SimulationState g = SimulationState { simAgentMap :: !(AgentMap g) , simAbsState :: !ABSState , simEnvState :: !SugEnvironment , simEnvBeh :: !SugEnvBehaviour , simRng :: !g , simSteps :: !Int } -- sugarscape is stepped with a time-delta of 1.0 sugarScapeTimeDelta :: DTime sugarScapeTimeDelta = 1 initSimulation :: SugarScapeScenario -> IO ( SimulationState StdGen , SimStepOut , SugarScapeScenario) initSimulation params = do g0 <- newStdGen return $ initSimulationRng g0 params initSimulationOpt :: Maybe Int -> SugarScapeScenario -> IO ( SimulationState StdGen , SimStepOut , SugarScapeScenario) initSimulationOpt Nothing params = initSimulation params initSimulationOpt (Just seed) params = return $ initSimulationSeed seed params initSimulationSeed :: Int -> SugarScapeScenario -> ( SimulationState StdGen , SimStepOut , SugarScapeScenario) initSimulationSeed seed = initSimulationRng g0 where g0 = mkStdGen seed initSimulationRng :: RandomGen g => g -> SugarScapeScenario -> ( SimulationState g , SimStepOut , SugarScapeScenario) initSimulationRng g0 params = (initSimState, initOut, params') where -- initial agents and environment data ((initAs, initEnv, params'), g') = runRand (createSugarScape params) g0 -- initial agent map agentMap = foldr (\(aid, obs, asf) am' -> Map.insert aid (asf, obs) am') Map.empty initAs (initAis, initObs, _) = unzip3 initAs initOut = (0, 0, initEnv, zip initAis initObs) -- initial simulation state initSimState = mkSimState agentMap (mkAbsState $ maximum initAis) initEnv (sugEnvBehaviour params') g' 0 simulateUntil :: RandomGen g => Time -> SimulationState g -> [SimStepOut] simulateUntil tMax ss0 = simulateUntilAux ss0 [] where simulateUntilAux :: RandomGen g => SimulationState g -> [SimStepOut] -> [SimStepOut] simulateUntilAux ss acc | t < tMax = simulateUntilAux ss' acc' | otherwise = reverse acc' where (ss', so@(t, _, _, _)) = simulationStep ss acc' = so : acc simulateUntilLast :: RandomGen g => Time -> SimulationState g -> SimStepOut simulateUntilLast tMax ss | t < tMax = simulateUntilLast tMax ss' | otherwise = so where (ss', so@(t, _, _, _)) = simulationStep ss simulationStep :: RandomGen g => SimulationState g -> (SimulationState g, SimStepOut) simulationStep ss0 = (ssFinal, sao) where am0 = simAgentMap ss0 ais0 = Map.keys am0 g0 = simRng ss0 (aisShuffled, gShuff) = randomShuffle g0 ais0 -- schedule Tick messages in random order by generating event-list from shuffled agent-ids -- this will result in the agents emitting loads of additional events, -- processEvents will return after all events are processed tickEvents = zip aisShuffled (repeat $ Tick sugarScapeTimeDelta) ssTicks = processEvents tickEvents (ss0 { simRng = gShuff }) -- run the environment envFinal = runEnv ssTicks ssTime = incrementTime ssTicks ssFinal = ssTime { simEnvState = envFinal } -- produce final output of this step sao = simStepOutFromSimState ssFinal incrementTime :: SimulationState g -> SimulationState g incrementTime ss = ss { simAbsState = absState' } where absState = simAbsState ss absState' = absState { absTime = absTime absState + sugarScapeTimeDelta } simStepOutFromSimState :: SimulationState g -> SimStepOut simStepOutFromSimState ss = (t, steps, env, aos) where t = absTime $ simAbsState ss steps = simSteps ss env = simEnvState ss aos = map (\(aid, (_, obs)) -> (aid, obs)) (Map.assocs $ simAgentMap ss) processEvents :: RandomGen g => EventList -> SimulationState g -> SimulationState g processEvents [] ss = ss processEvents ((aid, evt) : es) ss | isNothing mayAgent = processEvents es ss | otherwise = processEvents es' ss' where am = simAgentMap ss absState = simAbsState ss env = simEnvState ss g = simRng ss steps = simSteps ss mayAgent = Map.lookup aid am (asf, _) = fromJust mayAgent (ao, obs, asf', absState', env', g') = runAgentSF asf evt absState env g am' = updateMsfAndObservable asf' obs am (am'', newEvents) = handleAgentOut ao am' -- schedule events of the agent: will always be put infront of the list, thus processed immediately es' = newEvents ++ es ss' = ss { simAgentMap = am'' , simAbsState = absState' , simEnvState = env' , simRng = g' , simSteps = steps + 1 } updateMsfAndObservable :: SugAgentMSF g -> SugAgentObservable -> AgentMap g -> AgentMap g updateMsfAndObservable asfUp obsUp amUp = amUp' where -- update new signalfunction and agent-observable amUp' = Map.insert aid (asfUp, obsUp) amUp handleAgentOut :: RandomGen g => SugAgentOut g -> AgentMap g -> (AgentMap g, EventList) handleAgentOut aoOut amOut = (amOut'', evtsOut) where -- QUESTION: should an agent who isDead schedule events? ANSWER: yes, general solution evtsOut = map (\(receiver, domEvt) -> (receiver, DomainEvent aid domEvt)) (aoEvents aoOut) -- agent is dead, remove from set (technically its a map) of agents amOut' = if isDeadAo aoOut then Map.delete aid amOut else amOut -- add newly created agents -- QUESTION: should an agent who isDead be allowed to create new ones? -- ANSWER: depends on the model, we leave that to the model implementer to have a general solution -- in case of SugarScape when an agent dies it wont engage in mating, which is prevented -- in the agent implementation thus aoCreate will always be null in case of a isDead agent -- NOTE the exception (there is always an exception) is when the R (replacement) rule is active -- which replaces a dead agent by a random new-born, then aoCreate contains exactly 1 element amOut'' = foldr (\ad acc -> Map.insert (adId ad) (adSf ad, adInitObs ad) acc) amOut' (aoCreate aoOut) runEnv :: SimulationState g -> SugEnvironment runEnv ss = eb t env where eb = simEnvBeh ss env = simEnvState ss t = absTime $ simAbsState ss runAgentSF :: RandomGen g => SugAgentMSF g -> ABSEvent SugEvent -> ABSState -> SugEnvironment -> g -> (SugAgentOut g, SugAgentObservable, SugAgentMSF g, ABSState, SugEnvironment, g) runAgentSF msf evt absState env g = (ao, obs, msf', absState', env', g') where msfAbsState = unMSF msf evt -- to get rid of unMSF we would need to run it all in an MSF... msfEnvState = runStateT msfAbsState absState msfRand = runStateT msfEnvState env (((((ao, obs), msf'), absState'), env'), g') = runRand msfRand g mkSimState :: AgentMap g -> ABSState -> SugEnvironment -> SugEnvBehaviour -> g -> Int -> SimulationState g mkSimState am absState env eb g steps = SimulationState { simAgentMap = am , simAbsState = absState , simEnvState = env , simEnvBeh = eb , simRng = g , simSteps = steps }
thalerjonathan/phd
thesis/code/sugarscape/src/SugarScape/Core/Simulation.hs
gpl-3.0
9,478
0
16
3,028
2,073
1,135
938
204
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.EC2.AcceptVpcPeeringConnection -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Accept a VPC peering connection request. To accept a request, the VPC peering -- connection must be in the 'pending-acceptance' state, and you must be the owner -- of the peer VPC. Use the 'DescribeVpcPeeringConnections' request to view your -- outstanding VPC peering connection requests. -- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AcceptVpcPeeringConnection.html> module Network.AWS.EC2.AcceptVpcPeeringConnection ( -- * Request AcceptVpcPeeringConnection -- ** Request constructor , acceptVpcPeeringConnection -- ** Request lenses , avpcDryRun , avpcVpcPeeringConnectionId -- * Response , AcceptVpcPeeringConnectionResponse -- ** Response constructor , acceptVpcPeeringConnectionResponse -- ** Response lenses , avpcrVpcPeeringConnection ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.EC2.Types import qualified GHC.Exts data AcceptVpcPeeringConnection = AcceptVpcPeeringConnection { _avpcDryRun :: Maybe Bool , _avpcVpcPeeringConnectionId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'AcceptVpcPeeringConnection' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'avpcDryRun' @::@ 'Maybe' 'Bool' -- -- * 'avpcVpcPeeringConnectionId' @::@ 'Maybe' 'Text' -- acceptVpcPeeringConnection :: AcceptVpcPeeringConnection acceptVpcPeeringConnection = AcceptVpcPeeringConnection { _avpcDryRun = Nothing , _avpcVpcPeeringConnectionId = Nothing } avpcDryRun :: Lens' AcceptVpcPeeringConnection (Maybe Bool) avpcDryRun = lens _avpcDryRun (\s a -> s { _avpcDryRun = a }) -- | The ID of the VPC peering connection. avpcVpcPeeringConnectionId :: Lens' AcceptVpcPeeringConnection (Maybe Text) avpcVpcPeeringConnectionId = lens _avpcVpcPeeringConnectionId (\s a -> s { _avpcVpcPeeringConnectionId = a }) newtype AcceptVpcPeeringConnectionResponse = AcceptVpcPeeringConnectionResponse { _avpcrVpcPeeringConnection :: Maybe VpcPeeringConnection } deriving (Eq, Read, Show) -- | 'AcceptVpcPeeringConnectionResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'avpcrVpcPeeringConnection' @::@ 'Maybe' 'VpcPeeringConnection' -- acceptVpcPeeringConnectionResponse :: AcceptVpcPeeringConnectionResponse acceptVpcPeeringConnectionResponse = AcceptVpcPeeringConnectionResponse { _avpcrVpcPeeringConnection = Nothing } -- | Information about the VPC peering connection. avpcrVpcPeeringConnection :: Lens' AcceptVpcPeeringConnectionResponse (Maybe VpcPeeringConnection) avpcrVpcPeeringConnection = lens _avpcrVpcPeeringConnection (\s a -> s { _avpcrVpcPeeringConnection = a }) instance ToPath AcceptVpcPeeringConnection where toPath = const "/" instance ToQuery AcceptVpcPeeringConnection where toQuery AcceptVpcPeeringConnection{..} = mconcat [ "DryRun" =? _avpcDryRun , "VpcPeeringConnectionId" =? _avpcVpcPeeringConnectionId ] instance ToHeaders AcceptVpcPeeringConnection instance AWSRequest AcceptVpcPeeringConnection where type Sv AcceptVpcPeeringConnection = EC2 type Rs AcceptVpcPeeringConnection = AcceptVpcPeeringConnectionResponse request = post "AcceptVpcPeeringConnection" response = xmlResponse instance FromXML AcceptVpcPeeringConnectionResponse where parseXML x = AcceptVpcPeeringConnectionResponse <$> x .@? "vpcPeeringConnection"
kim/amazonka
amazonka-ec2/gen/Network/AWS/EC2/AcceptVpcPeeringConnection.hs
mpl-2.0
4,578
0
9
879
482
293
189
62
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.MachineLearning.GetBatchPrediction -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Returns a 'BatchPrediction' that includes detailed metadata, status, and data -- file information for a 'Batch Prediction' request. -- -- <http://http://docs.aws.amazon.com/machine-learning/latest/APIReference/API_GetBatchPrediction.html> module Network.AWS.MachineLearning.GetBatchPrediction ( -- * Request GetBatchPrediction -- ** Request constructor , getBatchPrediction -- ** Request lenses , gbpBatchPredictionId -- * Response , GetBatchPredictionResponse -- ** Response constructor , getBatchPredictionResponse -- ** Response lenses , gbprBatchPredictionDataSourceId , gbprBatchPredictionId , gbprCreatedAt , gbprCreatedByIamUser , gbprInputDataLocationS3 , gbprLastUpdatedAt , gbprLogUri , gbprMLModelId , gbprMessage , gbprName , gbprOutputUri , gbprStatus ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.MachineLearning.Types import qualified GHC.Exts newtype GetBatchPrediction = GetBatchPrediction { _gbpBatchPredictionId :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'GetBatchPrediction' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gbpBatchPredictionId' @::@ 'Text' -- getBatchPrediction :: Text -- ^ 'gbpBatchPredictionId' -> GetBatchPrediction getBatchPrediction p1 = GetBatchPrediction { _gbpBatchPredictionId = p1 } -- | An ID assigned to the 'BatchPrediction' at creation. gbpBatchPredictionId :: Lens' GetBatchPrediction Text gbpBatchPredictionId = lens _gbpBatchPredictionId (\s a -> s { _gbpBatchPredictionId = a }) data GetBatchPredictionResponse = GetBatchPredictionResponse { _gbprBatchPredictionDataSourceId :: Maybe Text , _gbprBatchPredictionId :: Maybe Text , _gbprCreatedAt :: Maybe POSIX , _gbprCreatedByIamUser :: Maybe Text , _gbprInputDataLocationS3 :: Maybe Text , _gbprLastUpdatedAt :: Maybe POSIX , _gbprLogUri :: Maybe Text , _gbprMLModelId :: Maybe Text , _gbprMessage :: Maybe Text , _gbprName :: Maybe Text , _gbprOutputUri :: Maybe Text , _gbprStatus :: Maybe EntityStatus } deriving (Eq, Read, Show) -- | 'GetBatchPredictionResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gbprBatchPredictionDataSourceId' @::@ 'Maybe' 'Text' -- -- * 'gbprBatchPredictionId' @::@ 'Maybe' 'Text' -- -- * 'gbprCreatedAt' @::@ 'Maybe' 'UTCTime' -- -- * 'gbprCreatedByIamUser' @::@ 'Maybe' 'Text' -- -- * 'gbprInputDataLocationS3' @::@ 'Maybe' 'Text' -- -- * 'gbprLastUpdatedAt' @::@ 'Maybe' 'UTCTime' -- -- * 'gbprLogUri' @::@ 'Maybe' 'Text' -- -- * 'gbprMLModelId' @::@ 'Maybe' 'Text' -- -- * 'gbprMessage' @::@ 'Maybe' 'Text' -- -- * 'gbprName' @::@ 'Maybe' 'Text' -- -- * 'gbprOutputUri' @::@ 'Maybe' 'Text' -- -- * 'gbprStatus' @::@ 'Maybe' 'EntityStatus' -- getBatchPredictionResponse :: GetBatchPredictionResponse getBatchPredictionResponse = GetBatchPredictionResponse { _gbprBatchPredictionId = Nothing , _gbprMLModelId = Nothing , _gbprBatchPredictionDataSourceId = Nothing , _gbprInputDataLocationS3 = Nothing , _gbprCreatedByIamUser = Nothing , _gbprCreatedAt = Nothing , _gbprLastUpdatedAt = Nothing , _gbprName = Nothing , _gbprStatus = Nothing , _gbprOutputUri = Nothing , _gbprLogUri = Nothing , _gbprMessage = Nothing } -- | The ID of the 'DataSource' that was used to create the 'BatchPrediction'. gbprBatchPredictionDataSourceId :: Lens' GetBatchPredictionResponse (Maybe Text) gbprBatchPredictionDataSourceId = lens _gbprBatchPredictionDataSourceId (\s a -> s { _gbprBatchPredictionDataSourceId = a }) -- | An ID assigned to the 'BatchPrediction' at creation. This value should be -- identical to the value of the 'BatchPredictionID' in the request. gbprBatchPredictionId :: Lens' GetBatchPredictionResponse (Maybe Text) gbprBatchPredictionId = lens _gbprBatchPredictionId (\s a -> s { _gbprBatchPredictionId = a }) -- | The time when the 'BatchPrediction' was created. The time is expressed in epoch -- time. gbprCreatedAt :: Lens' GetBatchPredictionResponse (Maybe UTCTime) gbprCreatedAt = lens _gbprCreatedAt (\s a -> s { _gbprCreatedAt = a }) . mapping _Time -- | The AWS user account that invoked the 'BatchPrediction'. The account type can -- be either an AWS root account or an AWS Identity and Access Management (IAM) -- user account. gbprCreatedByIamUser :: Lens' GetBatchPredictionResponse (Maybe Text) gbprCreatedByIamUser = lens _gbprCreatedByIamUser (\s a -> s { _gbprCreatedByIamUser = a }) -- | The location of the data file or directory in Amazon Simple Storage Service -- (Amazon S3). gbprInputDataLocationS3 :: Lens' GetBatchPredictionResponse (Maybe Text) gbprInputDataLocationS3 = lens _gbprInputDataLocationS3 (\s a -> s { _gbprInputDataLocationS3 = a }) -- | The time of the most recent edit to 'BatchPrediction'. The time is expressed in -- epoch time. gbprLastUpdatedAt :: Lens' GetBatchPredictionResponse (Maybe UTCTime) gbprLastUpdatedAt = lens _gbprLastUpdatedAt (\s a -> s { _gbprLastUpdatedAt = a }) . mapping _Time -- | A link to the file that contains logs of the 'CreateBatchPrediction' operation. gbprLogUri :: Lens' GetBatchPredictionResponse (Maybe Text) gbprLogUri = lens _gbprLogUri (\s a -> s { _gbprLogUri = a }) -- | The ID of the 'MLModel' that generated predictions for the 'BatchPrediction' -- request. gbprMLModelId :: Lens' GetBatchPredictionResponse (Maybe Text) gbprMLModelId = lens _gbprMLModelId (\s a -> s { _gbprMLModelId = a }) -- | A description of the most recent details about processing the batch -- prediction request. gbprMessage :: Lens' GetBatchPredictionResponse (Maybe Text) gbprMessage = lens _gbprMessage (\s a -> s { _gbprMessage = a }) -- | A user-supplied name or description of the 'BatchPrediction'. gbprName :: Lens' GetBatchPredictionResponse (Maybe Text) gbprName = lens _gbprName (\s a -> s { _gbprName = a }) -- | The location of an Amazon S3 bucket or directory to receive the operation -- results. gbprOutputUri :: Lens' GetBatchPredictionResponse (Maybe Text) gbprOutputUri = lens _gbprOutputUri (\s a -> s { _gbprOutputUri = a }) -- | The status of the 'BatchPrediction', which can be one of the following values: -- -- 'PENDING' - Amazon Machine Learning (Amazon ML) submitted a request to -- generate batch predictions. 'INPROGRESS' - The batch predictions are in -- progress. 'FAILED' - The request to perform a batch prediction did not run to -- completion. It is not usable. 'COMPLETED' - The batch prediction process -- completed successfully. 'DELETED' - The 'BatchPrediction' is marked as deleted. -- It is not usable. gbprStatus :: Lens' GetBatchPredictionResponse (Maybe EntityStatus) gbprStatus = lens _gbprStatus (\s a -> s { _gbprStatus = a }) instance ToPath GetBatchPrediction where toPath = const "/" instance ToQuery GetBatchPrediction where toQuery = const mempty instance ToHeaders GetBatchPrediction instance ToJSON GetBatchPrediction where toJSON GetBatchPrediction{..} = object [ "BatchPredictionId" .= _gbpBatchPredictionId ] instance AWSRequest GetBatchPrediction where type Sv GetBatchPrediction = MachineLearning type Rs GetBatchPrediction = GetBatchPredictionResponse request = post "GetBatchPrediction" response = jsonResponse instance FromJSON GetBatchPredictionResponse where parseJSON = withObject "GetBatchPredictionResponse" $ \o -> GetBatchPredictionResponse <$> o .:? "BatchPredictionDataSourceId" <*> o .:? "BatchPredictionId" <*> o .:? "CreatedAt" <*> o .:? "CreatedByIamUser" <*> o .:? "InputDataLocationS3" <*> o .:? "LastUpdatedAt" <*> o .:? "LogUri" <*> o .:? "MLModelId" <*> o .:? "Message" <*> o .:? "Name" <*> o .:? "OutputUri" <*> o .:? "Status"
romanb/amazonka
amazonka-ml/gen/Network/AWS/MachineLearning/GetBatchPrediction.hs
mpl-2.0
9,455
0
31
2,130
1,285
758
527
130
1
module Graphics ( animate ) where import Control.Applicative import Control.Concurrent import Control.Monad import Data.Colour.SRGB (toSRGB24, RGB(..)) import Data.Text (Text) import qualified Data.Vector.Storable as Vector import FRP.Yampa import Linear (V2(..), V4(..)) import Linear.Affine (Point(..)) import qualified SDL import Shapes import Types -- | (Object to render, should the app exit) -- TODO: Datatype type WinOutput = (Object, Bool) animate :: Text -- ^ window title -> Int -- ^ window width in pixels -> Int -- ^ window height in pixels -> SF WinInput WinOutput -- ^ signal function to animate -> IO () animate title winWidth winHeight sf = do SDL.initialize [SDL.InitVideo] window <- SDL.createWindow title windowConf SDL.showWindow window renderer <- SDL.createRenderer window (-1) rendererConf SDL.setRenderDrawColor renderer (V4 maxBound maxBound maxBound maxBound) lastInteraction <- newMVar =<< SDL.time let senseInput _canBlock = do currentTime <- SDL.time dt <- (currentTime -) <$> swapMVar lastInteraction currentTime mEvent <- SDL.pollEvent return (dt, Event . SDL.eventPayload <$> mEvent) renderOutput changed (obj, shouldExit) = do when changed $ do renderObject renderer winHeight obj SDL.renderPresent renderer return shouldExit reactimate (return NoEvent) senseInput renderOutput sf SDL.destroyRenderer renderer SDL.destroyWindow window SDL.quit where windowConf = SDL.defaultWindow { SDL.windowSize = V2 (fromIntegral winWidth) (fromIntegral winHeight) } rendererConf = SDL.RendererConfig { SDL.rendererAccelerated = True , SDL.rendererSoftware = False , SDL.rendererTargetTexture = False , SDL.rendererPresentVSync = False } renderObject :: SDL.Renderer -> Int -> Object -> IO () renderObject renderer winHeight obj = setRenderAttrs >> renderShape where setRenderAttrs = do let (RGB r g b) = toSRGB24 $ objColour obj SDL.setRenderDrawColor renderer (V4 r g b maxBound) renderShape = case objShape obj of Rectangle x y -> SDL.renderFillRect renderer $ Just $ SDL.Rectangle (P (V2 (toEnum $ floor px) (toEnum $ winHeight - floor py))) (V2 (toEnum x) (toEnum y)) Scene objs -> do SDL.renderClear renderer mapM_ (renderObject renderer winHeight) objs Circle r -> SDL.renderDrawPoints renderer $ Vector.fromList $ map (\(x,y) -> P (V2 (toEnum x) (toEnum y))) $ translate (floor px, winHeight - floor py) $ rasterCircle r (px, py) = objPos obj -- | Get octant points for a circle of given radius. octant :: (Num a, Ord a) => a -> [(a, a)] octant r = takeWhile inOctant . map fst $ iterate step ((r, 0), 1 - r) where -- check if we are still in octant inOctant (x, y) = x >= y -- go to the next point in the circle step ((x, y), e) | e < 0 = ((x, y + 1), e + 2 * (y + 1) + 1) | otherwise = ((x - 1, y + 1), e + 2 * (y - x + 2) + 1) -- | Get quadrant points for a circle of given radius. -- To do that we just mirror octant with respect to x = y line. quadrant :: (Num a, Ord a) => a -> [(a, a)] quadrant r = octant r >>= mirror where mirror (x, y) = [ (x, y), (y, x) ] -- | Get points of a circle of given radius. -- To do that we just mirror quadrant with respect to x = 0 and y = 0 lines. rasterCircle :: (Num a, Ord a) => a -> [(a, a)] rasterCircle r = quadrant r >>= mirror where mirror (x, y) = [ (u, v) | u <- [x, -x], v <- [y, -y] ] -- | Move all points by a given vector. translate :: (Num a, Eq a) => (a, a) -> [(a, a)] -> [(a, a)] translate v = map (v .+) -- | Vector addition generalized for Num (.+) :: Num a => (a, a) -> (a, a) -> (a, a) (x, y) .+ (u, v) = (x + u, y + v)
pyrtsa/yampa-demos-template
src/Graphics.hs
bsd-3-clause
4,468
0
20
1,575
1,393
743
650
83
3