added errors to Yard
[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) = Expected (as++bs)
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 <?> :: (Parser a b) String -> Parser a b
45 <?> p e = Parser \i -> case runParser p i of
46 (Left e1, rest) = (Left (e1+(Expected [e])), rest)
47 (Right r, rest) = (Right r, rest)
48
49 fail :: Parser a b
50 fail = empty
51
52 top :: Parser a a
53 top = Parser \i -> case i of
54 [] = (Left ParseError, [])
55 [x:xs] = (Right x, xs)
56
57 satisfy :: (a -> Bool) -> Parser a a
58 satisfy f = top >>= \r -> if (f r) (return r) fail
59
60 item :: a -> Parser a a | Eq a
61 item a = satisfy ((==)a)
62
63 list :: [a] -> Parser a [a] | Eq a
64 list as = mapM item as