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 (PositionalError l c e) =
19 concat [toString l,":",toString c,": ",e, "\n"]
20 toString (Error e) = concat ["-:-: ", e, "\n"]
22 runParser :: (Parser a b) [a] -> (Either Error b, [a])
23 runParser (Parser f) i = f i
25 instance Functor (Parser a) where
28 instance Applicative (Parser a) where
29 pure a = Parser \i -> (Right a, i)
32 instance Monad (Parser a) where
33 bind p f = Parser \i -> case runParser p i of
34 (Right r, rest) = runParser (f r) rest
35 (Left e, _) = (Left e, i)
37 instance Alternative (Parser a) where
38 empty = Parser \i -> (Left $ Error "" , i)
39 (<|>) p1 p2 = Parser \i -> case runParser p1 i of
40 (Right r, rest) = (Right r, rest)
41 (Left e1, rest) = case runParser p2 i of
42 (Left e2, rest) = (Left e2, i)
43 (Right r, rest) = (Right r, rest)
45 //Try parser, if it fails decorate the error with the given String and position
46 (<?>) :: (Parser a b) Error -> Parser a b
47 (<?>) p e = Parser \i -> case runParser p i of
48 (Left e1, rest) = (Left e, rest)
49 (Right r, rest) = (Right r, rest)
55 top = Parser \i -> case i of
56 [] = (Left $ Error "", [])
57 [x:xs] = (Right x, xs)
60 peek = Parser \i -> case i of
61 [] = (Left $ Error "", [])
62 [x:xs] = (Right x, [x:xs])
64 (until) infix 2 :: (Parser a b) (Parser a c) -> Parser a [b]
65 (until) p guard = try $ until` p guard []
67 until` :: (Parser a b) (Parser a c) [b] -> Parser a [b]
68 until` p guard acc = Parser \i -> case runParser guard i of
69 (Right _, rest) = (Right acc, rest)
70 (Left _, _) = case runParser p i of
71 (Right r, rest) = runParser (until` p guard [r:acc]) rest
72 (Left e, _) = (Left e, i)
73 try :: (Parser a b) -> Parser a b
74 try p = Parser \i -> case runParser p i of
75 (Left e, _) = (Left e, i)
76 (Right r, rest) = (Right r, rest)
79 eof = Parser \i -> case i of
81 _ = (Left $ Error "", i)
83 satisfy :: (a -> Bool) -> Parser a a
84 satisfy f = top >>= \r -> if (f r) (return r) fail
86 check :: (a -> Bool) -> Parser a a
87 check f = peek >>= \r -> if (f r) (return r) fail
89 item :: a -> Parser a a | Eq a
90 item a = satisfy ((==)a)
92 list :: [a] -> Parser a [a] | Eq a
93 list as = mapM item as