-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLispParser.hs
110 lines (79 loc) · 1.94 KB
/
LispParser.hs
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
96
97
98
99
100
101
102
103
104
105
106
107
108
module LispParser where
import LispVal
import Control.Monad
import Control.Monad.Error
import Text.ParserCombinators.Parsec hiding (spaces)
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=?>@^_~#"
spaces :: Parser ()
spaces = skipMany1 space
readExpr :: String -> ThrowsError LispVal
readExpr input = case parse parseExpr "lisp" input of
Left err -> throwError $ Parser err
Right val -> return val
parseString :: Parser LispVal
parseString = do
char '"'
x <- many (noneOf "\"")
char '"'
return $ String x
parseAtom :: Parser LispVal
parseAtom = do
first <- letter <|> symbol
rest <- many (letter <|> digit <|> symbol)
let atom = first : rest
return $ case atom of
"#t" -> Bool True
"#f" -> Bool False
otherwise ->Atom atom
parseNumber :: Parser LispVal
parseNumber = do
num <- many1 digit
return $ (Number . read) num
spaces1 :: Parser ()
spaces1 = skipMany1 space
parseList :: Parser LispVal
parseList = do
char '('
x <- liftM List $ sepBy parseExpr spaces1
char ')'
return x
parseDottedList :: Parser LispVal
parseDottedList = do
char '('
x <- endBy parseExpr spaces1
char '.'
spaces1
xs <- parseExpr
char ')'
return $ DottedList x xs
parseQuote :: Parser LispVal
parseQuote = do
char '\''
x <- parseExpr
return $ List [Atom "quote", x]
parseQuasiquote :: Parser LispVal
parseQuasiquote = do
char '`'
x <- parseExpr
return $ List [Atom "quasiquote", x]
parseUnquote :: Parser LispVal
parseUnquote = do
char ','
x <- parseExpr
return $ List [Atom "unquote", x]
parseVector :: Parser LispVal
parseVector = do
string "#("
x <- sepBy parseExpr spaces1
char ')'
return $ Vector (length x, x)
parseExpr :: Parser LispVal
parseExpr = try parseAtom
<|> try parseString
<|> try parseNumber
<|> try parseQuote
<|> try parseQuasiquote
<|> try parseUnquote
<|> try parseList
<|> try parseDottedList