Added eof parser
[cc1516.git] / src / yard.icl
1 implementation module yard
2
3 import StdTuple
4 import StdClass
5 import StdString
6 import StdList
7 import StdInt
8 from Data.List import intersperse
9 from Text import instance Text String, class Text(concat)
10 import Data.Functor
11 import Data.Either
12 import Control.Monad
13 import Control.Applicative
14 from Data.Func import $
15 import Data.Void
16
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)
21
22 runParser :: (Parser a b) [a] -> (Either Error b, [a])
23 runParser (Parser f) i = f i
24
25 instance + Error where
26 (+) ParseError r = r
27 (+) r ParseError = r
28 (+) r _ = r
29
30 instance Functor (Parser a) where
31 fmap f m = liftM f m
32
33 instance Applicative (Parser a) where
34 pure a = Parser \i -> (Right a, i)
35 (<*>) sf p = ap sf p
36
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, rest) = (Left e, rest)
41
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, rest)
48 (Right r, rest) = (Right r, rest)
49
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)
55
56 fail :: Parser a b
57 fail = empty
58
59 top :: Parser a a
60 top = Parser \i -> case i of
61 [] = (Left ParseError, [])
62 [x:xs] = (Right x, xs)
63
64 peek :: Parser a a
65 peek = Parser \i -> case i of
66 [] = (Left ParseError, [])
67 [x:xs] = (Right x, [x:xs])
68
69 eof :: Parser a Void
70 eof = Parser \i -> case i of
71 [] = (Right Void, [])
72 _ = (Left ParseError, i)
73
74 satisfy :: (a -> Bool) -> Parser a a
75 satisfy f = top >>= \r -> if (f r) (return r) fail
76
77 check :: (a -> Bool) -> Parser a a
78 check f = peek >>= \r -> if (f r) (return r) fail
79
80 item :: a -> Parser a a | Eq a
81 item a = satisfy ((==)a)
82
83 list :: [a] -> Parser a [a] | Eq a
84 list as = mapM item as