-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtokenParser.hs
More file actions
96 lines (70 loc) · 2.17 KB
/
tokenParser.hs
File metadata and controls
96 lines (70 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
module TokenParser where
import Lexer
import Control.Monad
import Control.Applicative
newtype Parser a = Parser {run :: [Token] -> [(a,[Token])]}
data ParseTree = Empty | Lit {tok :: Token} | Node {name :: String, children :: [ParseTree]} deriving(Read)
instance Functor Parser where
fmap = liftM
instance Applicative Parser where
pure a = Parser (\toks -> [(a,toks)])
(<*>) = ap
instance Monad Parser where
return = pure
p >>= f = Parser (\toks -> concat [run (f a) toks' | (a,toks') <- run p toks])
instance Alternative Parser where
empty = mzero
(<|>) = mplus
instance MonadPlus Parser where
mzero = Parser (\toks -> [])
mplus p q = Parser (\toks -> run p toks ++ run q toks)
(+++) :: Parser a -> Parser a -> Parser a
p +++ q = Parser (\toks -> case run (p `mplus` q) toks of
[] -> []
(x:xs) -> [x])
sat :: (Token -> Bool) -> Parser Token
sat p = do
t <- singleTok
if p t then return t
else mzero
singleTok :: Parser Token
singleTok = Parser f
where f [] = []
f (x:xs) = [(x,xs)]
many0 :: Parser a -> Parser [a]
many0 p = many1 p +++ return []
many1 p = do
a <- p
as <- many0 p
return (a:as)
sepby :: Parser a -> Parser b -> Parser [a]
p `sepby` sep = (p `sepby1` sep) +++ return []
sepby1 :: Parser a -> Parser b -> Parser [a]
p `sepby1` sep = do a <- p
as <- many0 (do{sep;p})
return (a:as)
parseLit :: Token -> Parser ParseTree
parseLit t = Lit <$> sat (==t)
isType :: Token -> Bool
isType (Keyword "int") = True
isType (Keyword "char") = True
isType (Keyword "boolean") = True
isType (Id _) = True
isType _ = False
isName :: Token -> Bool
isName (Id _) = True
isName _ = False
parseName :: Parser ParseTree
parseName = Lit <$> sat isName
parseSemiC :: Parser ParseTree
parseSemiC = parseLit (Symbol ";")
parseType :: Parser ParseTree
parseType = Lit <$> sat isType
parseInt :: Parser ParseTree
parseInt = Lit <$> sat (f)
where f (IntConst _) = True
f _ = False
parseString :: Parser ParseTree
parseString = Lit <$> sat (f)
where f (SConst _) = True
f _ = False