Merge branch 'darcs' into master
[git-darcs-import.git] / src / Darcs / Patch / ReadMonads.hs
blobf71e6a34144b94adbcbe9399f1767b71fca6f872
2 module Darcs.Patch.ReadMonads (ParserM, work, maybe_work, alter_input,
3 parse_strictly, parse_lazily,
4 peek_input,
5 lex_char, lex_string, lex_strings, lex_eof,
6 my_lex) where
8 import ByteStringUtils ( dropSpace, breakSpace )
9 import qualified Data.ByteString as B (null, empty, ByteString)
10 import qualified Data.ByteString.Char8 as BC (unpack, pack)
12 lex_char :: ParserM m => Char -> m ()
13 lex_char c = lex_string [c]
15 lex_string :: ParserM m => String -> m ()
16 lex_string str = work
17 $ \s -> case my_lex s of
18 Just (xs, ys) | xs == BC.pack str -> Just ((), ys)
19 _ -> Nothing
21 lex_eof :: ParserM m => m ()
22 lex_eof = work
23 $ \s -> if B.null (dropSpace s)
24 then Just ((), B.empty)
25 else Nothing
27 lex_strings :: ParserM m => [String] -> m String
28 lex_strings str =
29 work $ \s ->
30 case my_lex s of
31 Just (xs, ys) | xs' `elem` str -> Just (xs', ys)
32 where xs' = BC.unpack xs
33 _ -> Nothing
35 my_lex :: B.ByteString -> Maybe (B.ByteString, B.ByteString)
36 my_lex s = let s' = dropSpace s
37 in if B.null s'
38 then Nothing
39 else Just $ breakSpace s'
41 alter_input :: ParserM m
42 => (B.ByteString -> B.ByteString) -> m ()
43 alter_input f = work (\s -> Just ((), f s))
45 class Monad m => ParserM m where
46 work :: (B.ByteString -> Maybe (a, B.ByteString)) -> m a
47 maybe_work :: (B.ByteString -> Maybe (a, B.ByteString)) -> m (Maybe a)
48 peek_input :: m B.ByteString
50 ----- Strict Monad -----
51 parse_strictly :: SM a -> B.ByteString -> Maybe (a, B.ByteString)
52 parse_strictly (SM f) s = f s
54 newtype SM a = SM (B.ByteString -> Maybe (a, B.ByteString))
55 instance Monad SM where
56 SM m >>= k = SM $ \s -> case m s of
57 Nothing -> Nothing
58 Just (x, s') ->
59 case k x of
60 SM y -> y s'
61 return x = SM (\s -> Just (x,s))
62 fail _ = SM (\_ -> Nothing)
64 instance ParserM SM where
65 work f = SM f
66 maybe_work f = SM $ \s -> case f s of
67 Just (x, s') -> Just (Just x, s')
68 Nothing -> Just (Nothing, s)
69 peek_input = SM $ \s -> Just (s, s)
71 ----- Lazy Monad -----
72 parse_lazily :: LM a -> B.ByteString -> (a, B.ByteString)
73 parse_lazily (LM f) s = f s
75 newtype LM a = LM (B.ByteString -> (a, B.ByteString))
76 instance Monad LM where
77 LM m >>= k = LM $ \s -> let (x, s') = m s
78 LM y = k x
79 in y s'
80 return x = LM (\s -> (x,s))
81 fail s = error s
83 instance ParserM LM where
84 work f = LM $ \s -> case f s of
85 Nothing -> error "parser error"
86 Just x -> x
87 maybe_work f = LM $ \s -> case f s of
88 Nothing -> (Nothing, s)
89 Just (x, s') -> (Just x, s')
90 peek_input = LM $ \s -> (s, s)