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, _) = (Left e, i)
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, i)
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])
69 //runs the left parser until the right parser succeeds. Returns the result of the left parser
70 //Note: if the right parser consumes input then this input is lost!
71 //If the left parser fails before the right parser succeeds the whole parser fails
72 (until) infix 2 :: (Parser a b) (Parser a c) -> Parser a [b]
73 (until) p guard = try $ until` p guard []
75 until` :: (Parser a b) (Parser a c) [b] -> Parser a [b]
76 until` p guard acc = Parser \i -> case runParser guard i of
77 (Right _, rest) = (Right acc, rest)
78 (Left _, _) = case runParser p i of
79 (Right r, rest) = runParser (until` p guard [r:acc]) rest
80 (Left e, _) = (Left e, i)
81 try :: (Parser a b) -> Parser a b
82 try p = Parser \i -> case runParser p i of
83 (Left e, _) = (Left e, i)
84 (Right r, rest) = (Right r, rest)
88 eof = Parser \i -> case i of
90 _ = (Left ParseError, i)
92 satisfy :: (a -> Bool) -> Parser a a
93 satisfy f = top >>= \r -> if (f r) (return r) fail
95 check :: (a -> Bool) -> Parser a a
96 check f = peek >>= \r -> if (f r) (return r) fail
98 item :: a -> Parser a a | Eq a
99 item a = satisfy ((==)a)
101 list :: [a] -> Parser a [a] | Eq a
102 list as = mapM item as