Improved error type with position annotation
[cc1516.git] / src / yard.icl
1 implementation module yard
2
3 import StdTuple
4 import StdClass
5 import StdString
6 import StdList
7 import Data.Functor
8 import Data.Either
9 import Control.Monad
10 import Control.Applicative
11 from Data.Func import $
12
13 instance toString Error where
14 toString ParseError = "General parse error"
15 toString (LexError e) = "Lexer error: " +++ e
16
17 instance + Error where
18 (+) (Expected as _) (Expected bs p) = Expected (as++bs) p
19 (+) _ r = r
20
21 runParser :: (Parser a b) [a] -> (Either Error b, [a])
22 runParser (Parser f) i = f i
23
24 instance Functor (Parser a) where
25 fmap f m = liftM f m
26
27 instance Applicative (Parser a) where
28 pure a = Parser \i -> (Right a, i)
29 (<*>) sf p = ap sf p
30
31 instance Monad (Parser a) where
32 bind p f = Parser \i -> case runParser p i of
33 (Right r, rest) = runParser (f r) rest
34 (Left e, rest) = (Left e, rest)
35
36 instance Alternative (Parser a) where
37 empty = Parser \i -> (Left ParseError, i)
38 (<|>) p1 p2 = Parser \i -> case runParser p1 i of
39 (Right r, rest) = (Right r, rest)
40 (Left e1, rest) = case runParser p2 i of
41 (Right r, rest) = (Right r, rest)
42 (Left e2, rest) = (Left (e1+e2), rest)
43
44 //Try the parser, if it fails decorate the error with Expected of the given String and position
45 (<?>) :: (Parser a b) (String, Int) -> Parser a b
46 (<?>) p (e,pos) = Parser \i -> case runParser p i of
47 (Left e1, rest) = let error = (e1+(Expected [e] pos)) in (Left error, rest)
48 (Right r, rest) = (Right r, rest)
49
50 fail :: Parser a b
51 fail = empty
52
53 top :: Parser a a
54 top = Parser \i -> case i of
55 [] = (Left ParseError, [])
56 [x:xs] = (Right x, xs)
57
58 satisfy :: (a -> Bool) -> Parser a a
59 satisfy f = top >>= \r -> if (f r) (return r) fail
60
61 item :: a -> Parser a a | Eq a
62 item a = satisfy ((==)a)
63
64 list :: [a] -> Parser a [a] | Eq a
65 list as = mapM item as