2 module Darcs
.Patch
.ReadMonads
(ParserM
, work
, maybe_work
, alter_input
,
3 parse_strictly
, parse_lazily
,
5 lex_char
, lex_string
, lex_strings
, lex_eof
,
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
()
17 $ \s
-> case my_lex s
of
18 Just
(xs
, ys
) | xs
== BC
.pack str
-> Just
((), ys
)
21 lex_eof
:: ParserM m
=> m
()
23 $ \s
-> if B
.null (dropSpace s
)
24 then Just
((), B
.empty)
27 lex_strings
:: ParserM m
=> [String] -> m
String
31 Just
(xs
, ys
) | xs
' `
elem` str
-> Just
(xs
', ys
)
32 where xs
' = BC
.unpack xs
35 my_lex
:: B
.ByteString
-> Maybe (B
.ByteString
, B
.ByteString
)
36 my_lex s
= let s
' = dropSpace s
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
61 return x
= SM
(\s
-> Just
(x
,s
))
62 fail _
= SM
(\_
-> Nothing
)
64 instance ParserM SM
where
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
80 return x
= LM
(\s
-> (x
,s
))
83 instance ParserM LM
where
84 work f
= LM
$ \s
-> case f s
of
85 Nothing
-> error "parser error"
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
)