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 (l,c)) = "Unexpected " +++ e +++ " at "
21 +++ (toString l) +++ ":" +++ (toString c)
23 runParser :: (Parser a b) [a] -> (Either Error b, [a])
24 runParser (Parser f) i = f i
26 instance + Error where
31 instance Functor (Parser a) where
34 instance Applicative (Parser a) where
35 pure a = Parser \i -> (Right a, i)
38 instance Monad (Parser a) where
39 bind p f = Parser \i -> case runParser p i of
40 (Right r, rest) = runParser (f r) rest
41 (Left e, _) = (Left e, i)
43 instance Alternative (Parser a) where
44 empty = Parser \i -> (Left ParseError, i)
45 (<|>) p1 p2 = Parser \i -> case runParser p1 i of
46 (Right r, rest) = (Right r, rest)
47 (Left e1, rest) = case runParser p2 i of
48 (Left e2, rest) = (Left $ e1+e2, i)
49 (Right r, rest) = (Right r, rest)
51 //Try the parser, if it fails decorate the error with Expected of the given String and position
52 (<?>) :: (Parser a b) Error -> Parser a b
53 (<?>) p e = Parser \i -> case runParser p i of
54 (Left e1, rest) = (Left $ e1 + e, rest)
55 (Right r, rest) = (Right r, rest)
61 top = Parser \i -> case i of
62 [] = (Left ParseError, [])
63 [x:xs] = (Right x, xs)
66 peek = Parser \i -> case i of
67 [] = (Left ParseError, [])
68 [x:xs] = (Right x, [x:xs])
70 //runs the left parser until the right parser succeeds. Returns the result of the left parser
71 //Note: if the right parser consumes input then this input is lost!
72 //If the left parser fails before the right parser succeeds the whole parser fails
73 (until) infix 2 :: (Parser a b) (Parser a c) -> Parser a [b]
74 (until) p guard = try $ until` p guard []
76 until` :: (Parser a b) (Parser a c) [b] -> Parser a [b]
77 until` p guard acc = Parser \i -> case runParser guard i of
78 (Right _, rest) = (Right acc, rest)
79 (Left _, _) = case runParser p i of
80 (Right r, rest) = runParser (until` p guard [r:acc]) rest
81 (Left e, _) = (Left e, i)
82 try :: (Parser a b) -> Parser a b
83 try p = Parser \i -> case runParser p i of
84 (Left e, _) = (Left e, i)
85 (Right r, rest) = (Right r, rest)
89 eof = Parser \i -> case i of
91 _ = (Left ParseError, i)
93 satisfy :: (a -> Bool) -> Parser a a
94 satisfy f = top >>= \r -> if (f r) (return r) fail
96 check :: (a -> Bool) -> Parser a a
97 check f = peek >>= \r -> if (f r) (return r) fail
99 item :: a -> Parser a a | Eq a
100 item a = satisfy ((==)a)
102 list :: [a] -> Parser a [a] | Eq a
103 list as = mapM item as