Errors nog steeds niet goede token :(
[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
16 instance toString Error where
17 toString ParseError = "General parse error"
18 toString (LexError e) = "Lexer error: " +++ e
19 toString (Unexpected e pos) = "Unexpected " +++ e +++ " at position " +++ (toString pos)
20
21 runParser :: (Parser a b) [a] -> (Either Error b, [a])
22 runParser (Parser f) i = f i
23
24 instance + Error where
25 (+) ParseError r = r
26 (+) r ParseError = r
27 (+) r _ = r
28
29 instance Functor (Parser a) where
30 fmap f m = liftM f m
31
32 instance Applicative (Parser a) where
33 pure a = Parser \i -> (Right a, i)
34 (<*>) sf p = ap sf p
35
36 instance Monad (Parser a) where
37 bind p f = Parser \i -> case runParser p i of
38 (Right r, rest) = runParser (f r) rest
39 (Left e, rest) = (Left e, rest)
40
41 instance Alternative (Parser a) where
42 empty = Parser \i -> (Left ParseError, i)
43 (<|>) p1 p2 = Parser \i -> case runParser p1 i of
44 (Right r, rest) = (Right r, rest)
45 (Left e1, rest) = case runParser p2 i of
46 (Left e2, rest) = (Left $ e1+e2, rest)
47 (Right r, rest) = (Right r, rest)
48
49 //Try the parser, if it fails decorate the error with Expected of the given String and position
50 (<?>) :: (Parser a b) (String, Int) -> Parser a b
51 (<?>) p (e,pos) = Parser \i -> case runParser p i of
52 (Left e1, rest) = (Left $ e1 + Unexpected e pos, rest)
53 (Right r, rest) = (Right r, rest)
54
55 fail :: Parser a b
56 fail = empty
57
58 top :: Parser a a
59 top = Parser \i -> case i of
60 [] = (Left ParseError, [])
61 [x:xs] = (Right x, xs)
62
63 satisfy :: (a -> Bool) -> Parser a a
64 satisfy f = top >>= \r -> if (f r) (return r) fail
65
66 item :: a -> Parser a a | Eq a
67 item a = satisfy ((==)a)
68
69 list :: [a] -> Parser a [a] | Eq a
70 list as = mapM item as