-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.go
330 lines (266 loc) · 8.05 KB
/
parse.go
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package expronaut
import (
"fmt"
"strconv"
)
type Parser struct {
tokens []Token
errors []error
current int
}
func NewParser(lexer *Lexer) *Parser {
var tokens []Token
for {
tok := lexer.NextToken()
tokens = append(tokens, tok)
if tok.Type == TokenTypeEOF {
break
}
}
return &Parser{
tokens: tokens,
current: 0,
}
}
// expression parses an expression.
func (p *Parser) expression() ASTNode {
return p.logicalOr()
}
// logicalOr handles ||.
func (p *Parser) logicalOr() ASTNode {
node := p.logicalAnd()
for p.match(TokenTypeOr) {
operator := p.previous()
right := p.logicalAnd()
node = &LogicalOperationNode{Left: node, Operator: operator.Type, Right: right}
}
return node
}
// logicalAnd handles &&.
func (p *Parser) logicalAnd() ASTNode {
node := p.equality()
for p.match(TokenTypeAnd) {
operator := p.previous()
right := p.equality()
node = &LogicalOperationNode{Left: node, Operator: operator.Type, Right: right}
}
return node
}
// equality handles == and !=.
func (p *Parser) equality() ASTNode {
node := p.comparison()
for p.match(TokenTypeEqual, TokenTypeNotEqual) {
operator := p.previous()
right := p.comparison()
node = &BinaryOperationNode{Left: node, Operator: operator.Type, Right: right}
}
return node
}
// comparison handles <, <=, >, and >=.
func (p *Parser) comparison() ASTNode {
node := p.shift()
for p.match(TokenTypeGreaterThan, TokenTypeGreaterThanOrEqual, TokenTypeLessThan, TokenTypeLessThanOrEqual) {
operator := p.previous()
right := p.shift()
node = &BinaryOperationNode{Left: node, Operator: operator.Type, Right: right}
}
return node
}
// shift handles << and >>.
func (p *Parser) shift() ASTNode {
node := p.addition()
for p.match(TokenTypeLeftShift, TokenTypeRightShift) {
operator := p.previous()
right := p.addition()
node = &BinaryOperationNode{Left: node, Operator: operator.Type, Right: right}
}
return node
}
// addition handles + and -.
func (p *Parser) addition() ASTNode {
node := p.multiplication()
for p.match(TokenTypePlus, TokenTypeMinus) {
operator := p.previous()
right := p.multiplication()
node = &BinaryOperationNode{Left: node, Operator: operator.Type, Right: right}
}
return node
}
// multiplication handles *, /
func (p *Parser) multiplication() ASTNode {
node := p.functions()
for p.match(TokenTypeMultiply, TokenTypeDivide, TokenTypeModulo, TokenTypeDivideInteger) {
operator := p.previous()
right := p.functions()
node = &BinaryOperationNode{Left: node, Operator: operator.Type, Right: right}
}
return node
}
func (p *Parser) functions() ASTNode {
node := p.primary()
for p.match(TokenTypeExponent, TokenTypeFunction) {
operator := p.previous()
right := p.functions()
node = &BinaryOperationNode{Left: node, Operator: operator.Type, Right: right}
}
return node
}
// primary handles the base case of the recursive descent parser.
func (p *Parser) primary() ASTNode {
switch {
case p.match(TokenTypeInt):
return &IntLiteralNode{Value: parseInt(p.previous().Literal)}
case p.match(TokenTypeFloat):
return &FloatLiteralNode{Value: parseFloat(p.previous().Literal)}
case p.match(TokenTypeString):
return &StringLiteralNode{Value: p.previous().Literal}
case p.match(TokenTypeBool):
return &BooleanLiteralNode{Value: parseBool(p.previous().Literal)}
case p.match(TokenTypeVariable):
return &VariableNode{Name: p.previous().Literal}
case p.match(TokenTypeParenLeft):
expr := p.expression()
p.consume(TokenTypeParenRight, "Expect ')' after expression.")
return expr
case p.match(TokenTypeFunction):
funcName := p.previous().Literal
var arguments []ASTNode
p.consume(TokenTypeParenLeft, "Expect '(' after function.")
if !p.check(TokenTypeParenRight) {
for {
// Parse an argument expression.
argument := p.expression()
arguments = append(arguments, argument)
// If there's no comma, stop parsing arguments.
if !p.match(TokenTypeComma) {
break
}
}
}
// After parsing all arguments, expect the closing parenthesis.
p.consume(TokenTypeParenRight, "Expect ')' after arguments to function.")
return &FunctionCallNode{FunctionName: funcName, Arguments: arguments}
case p.match(TokenTypeArray):
var elements []ASTNode
arrayType := arrayType(p.previous().Literal)
p.consume(TokenTypeArrayStart, "Expect '[' after array.")
if !p.check(TokenTypeArrayEnd) {
for {
// Parse an element expression.
element := p.expression()
elements = append(elements, element)
// If there's no comma, stop parsing elements.
if !p.match(TokenTypeComma) {
break
}
}
}
// After parsing all elements, expect the closing bracket.
p.consume(TokenTypeArrayEnd, "Expect ']' after elements to array.")
return &ArrayNode{Type: arrayType, Elements: elements}
}
return &IntLiteralNode{Value: 0}
}
// previous returns the previous token.
func (p *Parser) previous() Token {
return p.tokens[p.current-1]
}
func (p *Parser) currentToken() Token {
return p.tokens[p.current]
}
func (p *Parser) next() Token {
if p.current+1 >= len(p.tokens) {
return Token{Type: TokenTypeEOF, Literal: ""}
}
return p.tokens[p.current+1]
}
func (p *Parser) next2() Token {
if p.current+2 >= len(p.tokens) {
return Token{Type: TokenTypeEOF, Literal: ""}
}
return p.tokens[p.current+2]
}
func (p *Parser) isModifier(tokenType TokenType) bool {
if tokenType == TokenTypePlus || tokenType == TokenTypeMinus || tokenType == TokenTypeMultiply || tokenType == TokenTypeDivide || tokenType == TokenTypeModulo || tokenType == TokenTypeDivideInteger || tokenType == TokenTypeExponent {
return true
}
return false
}
func (p *Parser) isOperand(tokenType TokenType) bool {
if tokenType == TokenTypeInt || tokenType == TokenTypeFloat || tokenType == TokenTypeString || tokenType == TokenTypeBool || tokenType == TokenTypeVariable || tokenType == TokenTypeFunction || tokenType == TokenTypeArray {
return true
}
return false
}
// consume expects the next token to be of a given type and consumes it, or throws an error.
func (p *Parser) consume(tokenType TokenType, message string) Token {
if p.isOperand(tokenType) && p.isOperand(p.next().Type) {
p.errors = append(p.errors, fmt.Errorf("operand should be followed by a modifier: got: %s(%v), next: %s(%v)", p.currentToken().Type, p.currentToken().Literal, p.next().Type, p.next().Literal))
}
if p.check(tokenType) {
return p.advance()
}
if tokenType == TokenTypeParenRight {
// keep going until we find the closing parenthesis
for !p.check(TokenTypeParenRight) {
p.consume(p.peek().Type, "Expect ')' after expression.")
}
return p.advance()
}
p.errors = append(p.errors, fmt.Errorf("%s: got: %s", message, tokenType))
return p.peek()
}
// check looks at the current token and returns true if it matches the given type.
func (p *Parser) check(typ TokenType) bool {
if p.isAtEnd() {
return false
}
return p.peek().Type == typ
}
// isAtEnd checks if we've consumed all tokens.
func (p *Parser) isAtEnd() bool {
return p.peek().Type == TokenTypeEOF
}
// peek returns the current token without consuming it.
func (p *Parser) peek() Token {
return p.tokens[p.current]
}
// advance consumes the current token and returns it.
func (p *Parser) advance() Token {
if !p.isAtEnd() {
p.current++
}
return p.tokens[p.current-1]
}
// match checks if the current token matches any of the given types.
func (p *Parser) match(types ...TokenType) bool {
for _, typ := range types {
if p.check(typ) {
p.advance()
return true
}
}
return false
}
// Parse starts the parsing process.
func (p *Parser) Parse() ASTNode {
return p.expression() // Start parsing from the highest level of precedence.
}
// parseNumber converts a string literal to a float64.
func parseFloat(lit string) float64 {
value, err := strconv.ParseFloat(lit, 64)
if err != nil {
panic(err) // or handle the error as appropriate
}
return value
}
func parseInt(lit string) int {
value, err := strconv.Atoi(lit)
if err != nil {
panic(err) // or handle the error as appropriate
}
return value
}
func parseBool(lit string) bool {
return lit == "true" // Returns true for "true", false otherwise
}