-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.kt
More file actions
279 lines (231 loc) · 9.08 KB
/
Parser.kt
File metadata and controls
279 lines (231 loc) · 9.08 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package Interpreter
class ParseState(val success: Boolean, val node: Node = Node(), val error : String = "")
typealias ParseFunction = () -> ParseState
class Parser(val tokens: List<Token>) {
var index = 0
fun MoveIndexTo(n: Int) {
index = n
}
fun PeekValue(value: String): Boolean {
if (index >= tokens.size) return false
return value == tokens[index].value
}
fun PeekType(type: String): Boolean {
if (index >= tokens.size) return false
return type == tokens[index].type
}
fun Value(value: String, fmap: (Token) -> Node = { token -> Node() }): ParseState {
if (!PeekValue(value)) {
val error = if (index < tokens.size) "line ${tokens[index].line}: unexpected value ${tokens[index].value}. expected $value" else "line ${tokens[index - 1].line}: expected $value"
return ParseState(false, error = error)
}
val token = tokens[index]
index += 1
return ParseState(true, fmap(token))
}
fun Type(type: String, fmap: (Token) -> Node = { token -> Node() }): ParseState {
if (!PeekType(type)) {
val error = if (index < tokens.size) "line ${tokens[index].line}: unexpected token ${tokens[index].type}. expected $type" else "line ${tokens[index - 1].line}: expected $type"
return ParseState(false, error = error)
}
val token = tokens[index]
index += 1
return ParseState(true, fmap(token))
}
fun OneOf(vararg parsers : ParseFunction): ParseState {
for (parser in parsers) {
val startIndex = index
val result = parser()
if (result.success) {
return result
}
MoveIndexTo(startIndex)
}
val error = if (index < tokens.size) "line ${tokens[index].line}: unexpected token ${tokens[index].value}" else "unexpected eof"
return ParseState(false, error=error)
}
fun Expect(parser: ParseFunction, callback: (ParseState) -> ParseState): ParseState {
val startIndex = index
val result = parser()
if (result.success) return callback(result)
RaiseError(result.error)
MoveIndexTo(startIndex)
return result
}
fun MayExpect(parser: ParseFunction, callback: (ParseState) -> ParseState): ParseState {
val startIndex = index
val result = parser()
if (result.success) return callback(result)
MoveIndexTo(startIndex)
return result
}
fun SepBy(sep: String, parser: ParseFunction): List<Node> {
var list: List<Node> = listOf()
MayExpect(parser, fun (state: ParseState): ParseState {
list += state.node
var prev = state
while (prev.success && Value(sep).success) {
prev = Expect(parser, fun (curr: ParseState): ParseState {
list += curr.node
return curr
})
}
return prev
})
return list
}
fun List(): ParseState {
return MayExpect({ Value("[") }) {
val elems = SepBy(",", ::Expr)
Expect({ Value("]") }) { ParseState(true, ListNode(elems) ) }
}
}
fun Fun(): ParseState {
return MayExpect({ Value("fun") }) {
Expect({ Value("(") }) {
val initialIndex = index
SepBy(",", { Type("identifier", { token -> Ident(token.value) }) })
val params = tokens.subList(initialIndex, index).map { it.value }.filter { it != "," }
Expect({ Value(")") }) {
Expect(::ParseBlock) { block ->
ParseState(true, FunNode(params, block.node))
}
}
}
}
}
fun FunCall(): ParseState {
return OneOf({ MayExpect(::Literal, fun (expr: ParseState): ParseState {
var result = MayExpect({ Value("(") }, fun (_: ParseState): ParseState {
val args = SepBy(",", ::Expr)
return Expect({ Value(")") }) { ParseState(true, Apply(expr.node, args) ) }
})
while (result.success && PeekValue("(")) {
result = MayExpect({ Value("(") }, fun (_: ParseState): ParseState {
val args = SepBy(",", ::Expr)
return Expect({ Value(")") }) { ParseState(true, Apply(result.node, args) ) }
})
}
return result
}) }, ::Literal)
}
fun Literal(): ParseState {
val number = { Type("number", { token -> Number(token.value.toDouble()) }) }
val string = { Type("string", { token -> Str(token.value) }) }
val ident = { Type("identifier", { token -> Ident(token.value) }) }
val trueBool = { Value("true", { token -> Bool(true) }) }
val falseBool = { Value("false", { token -> Bool(false) }) }
val paren = {
MayExpect({ Value("(") }) {
Expect(::Expr) {expr ->
Expect({ Value(")") }) { expr }
}
}
}
return OneOf(number, string, trueBool, falseBool, ::Fun, ident, ::List, paren)
}
fun ParseBinOp(op: String, SubExpr: ParseFunction): ParseState {
return MayExpect(SubExpr) { state ->
var left = state
while (left.success && Value(op).success) {
left = Expect(SubExpr) { right ->
ParseState(true, BinOp(op, left.node, right.node))
}
}
left
}
}
fun Div(): ParseState = ParseBinOp("/", ::FunCall)
fun Mul(): ParseState = ParseBinOp("*", ::Div)
fun Add(): ParseState = ParseBinOp("+", ::Mul)
fun Sub(): ParseState = ParseBinOp("-", ::Add)
fun Eq(): ParseState = ParseBinOp("==", ::Sub)
fun Geq(): ParseState = ParseBinOp(">=", ::Eq)
fun Leq(): ParseState = ParseBinOp("<=", ::Geq)
fun Less(): ParseState = ParseBinOp("<", ::Leq)
fun Greater(): ParseState = ParseBinOp(">", ::Less)
fun And(): ParseState = ParseBinOp("and", ::Greater)
fun Or(): ParseState = ParseBinOp(">", ::And)
fun Expr(): ParseState = Or()
fun ParseAssign(): ParseState {
return MayExpect({ Type("identifier") }) {
val id = tokens[index - 1].value
MayExpect({ Value("=") }) {
Expect(::Expr) { expr ->
ParseState(true, Assign(id, expr.node))
}
}
}
}
fun ParseNext(): ParseState {
return Expect({ OneOf(::ParseIf, ::ParseWhile, ::ParseFor, ::ParseReturn, ::ParseAssign, ::Expr) }) { state ->
state
}
}
fun ParseBlock(): ParseState {
var list: List<Node> = listOf()
Expect({ Value("{") }) {
while (!PeekValue("}")) {
Expect({ ParseNext() }) { stateB ->
list += stateB.node
stateB
}
}
Expect({ Value("}") }) { stateC -> stateC }
}
return ParseState(true, Body(list))
}
fun ParseWhile(): ParseState {
return MayExpect({ Value("while") }) {
Expect(::Expr) { expr ->
Expect(::ParseBlock) { block ->
ParseState(true, WhileNode(expr.node, block.node))
}
}
}
}
fun ParseFor(): ParseState {
return MayExpect({ Value("for") }) {
Expect({ Type("identifier") }) {
Expect({ Value("in") }) {
val id = tokens[index - 2].value
Expect(::Expr) { iter ->
Expect(::ParseBlock) { block ->
ParseState(true, ForNode(id, iter.node, block.node))
}
}
}
}
}
}
fun ParseReturn(): ParseState {
return MayExpect({ Value("return") }) {
Expect(::Expr) { expr ->
ParseState(true, ReturnNode(expr.node))
}
}
}
fun ParseIf(): ParseState {
return MayExpect({ Value("if") }) {
Expect(::Expr) { expr ->
Expect(::ParseBlock) { then ->
if (PeekValue("else")) Expect({ Value("else") }) {
Expect({ OneOf(::ParseIf, ::ParseBlock) }) { el ->
ParseState(true, IfNode(expr.node, then.node, el.node))
}
} else ParseState(true, IfNode(expr.node, then.node, Node()))
}
}
}
}
fun Parse(): Body {
var nodes: List<Node> = listOf()
while (index < tokens.size) {
Expect({ ParseNext() }) {state ->
nodes += state.node
state
}
}
return Body(nodes)
}
}