1 implementation module yard
8 from Data.List import intersperse
9 from Text import instance Text String, class Text(concat)
13 import Control.Applicative
14 from Data.Func import $
17 instance toString Error where
18 toString ParseError = "General parse error"
19 toString (LexError e) = "Lexer error: " +++ e
20 toString (Unexpected e pos) = "Unexpected " +++ e +++ " at position " +++ (toString pos)
22 runParser :: (Parser a b) [a] -> (Either Error b, [a])
23 runParser (Parser f) i = f i
25 instance + Error where
30 instance Functor (Parser a) where
33 instance Applicative (Parser a) where
34 pure a = Parser \i -> (Right a, i)
37 instance Monad (Parser a) where
38 bind p f = Parser \i -> case runParser p i of
39 (Right r, rest) = runParser (f r) rest
40 (Left e, rest) = (Left e, rest)
42 instance Alternative (Parser a) where
43 empty = Parser \i -> (Left ParseError, i)
44 (<|>) p1 p2 = Parser \i -> case runParser p1 i of
45 (Right r, rest) = (Right r, rest)
46 (Left e1, rest) = case runParser p2 i of
47 (Left e2, rest) = (Left $ e1+e2, rest)
48 (Right r, rest) = (Right r, rest)
50 //Try the parser, if it fails decorate the error with Expected of the given String and position
51 (<?>) :: (Parser a b) (String, Int) -> Parser a b
52 (<?>) p (e,pos) = Parser \i -> case runParser p i of
53 (Left e1, rest) = (Left $ e1 + Unexpected e pos, rest)
54 (Right r, rest) = (Right r, rest)
60 top = Parser \i -> case i of
61 [] = (Left ParseError, [])
62 [x:xs] = (Right x, xs)
65 peek = Parser \i -> case i of
66 [] = (Left ParseError, [])
67 [x:xs] = (Right x, [x:xs])
70 eof = Parser \i -> case i of
72 _ = (Left ParseError, i)
74 satisfy :: (a -> Bool) -> Parser a a
75 satisfy f = top >>= \r -> if (f r) (return r) fail
77 check :: (a -> Bool) -> Parser a a
78 check f = peek >>= \r -> if (f r) (return r) fail
80 item :: a -> Parser a a | Eq a
81 item a = satisfy ((==)a)
83 list :: [a] -> Parser a [a] | Eq a
84 list as = mapM item as