-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
437 lines (373 loc) · 10.5 KB
/
parser.go
File metadata and controls
437 lines (373 loc) · 10.5 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
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
package wirefilter
import (
"fmt"
"net"
"time"
)
// Operator precedence levels for parsing expressions.
// Precedence order (lowest to highest): OR < XOR < AND < PREFIX < EQUALS < COMPARE < MEMBERSHIP < SUM < PRODUCT
// PREFIX is used for NOT operator - it binds tighter than AND/OR/XOR but looser than comparisons.
const (
_ int = iota
LOWEST
OR
XOR
AND
PREFIX // NOT operator precedence - higher than AND so "not A and B" parses as "(not A) and B"
EQUALS
COMPARE
MEMBERSHIP
SUM // +, -
PRODUCT // *, /, %
)
var precedences = map[TokenType]int{
TokenOr: OR,
TokenXor: XOR,
TokenAnd: AND,
TokenEq: EQUALS,
TokenNe: EQUALS,
TokenAllEq: EQUALS,
TokenAnyNe: EQUALS,
TokenLt: COMPARE,
TokenGt: COMPARE,
TokenLe: COMPARE,
TokenGe: COMPARE,
TokenContains: MEMBERSHIP,
TokenMatches: MEMBERSHIP,
TokenIn: MEMBERSHIP,
TokenWildcard: MEMBERSHIP,
TokenStrictWildcard: MEMBERSHIP,
TokenPlus: SUM,
TokenMinus: SUM,
TokenAsterisk: PRODUCT,
TokenDiv: PRODUCT,
TokenMod: PRODUCT,
}
// Parser parses tokens from a lexer into an abstract syntax tree.
type Parser struct {
lexer *Lexer
curToken Token
peekToken Token
peekPeekToken Token
errors []string
}
// NewParser creates a new parser for the given lexer.
func NewParser(lexer *Lexer) *Parser {
p := &Parser{lexer: lexer}
p.nextToken()
p.nextToken()
p.nextToken()
return p
}
func (p *Parser) nextToken() {
p.curToken = p.peekToken
p.peekToken = p.peekPeekToken
p.peekPeekToken = p.lexer.NextToken()
}
// Errors returns the list of parsing errors encountered.
func (p *Parser) Errors() []string {
return p.errors
}
func (p *Parser) addError(format string, args ...any) {
p.errors = append(p.errors, fmt.Sprintf(format, args...))
}
// Parse parses the input and returns an expression tree.
// Returns an error if parsing fails or if there is trailing input.
// Parse parses the input and returns an expression tree.
// Collects multiple errors when possible via synchronization recovery.
// Returns an error if parsing fails or if there is trailing input.
func (p *Parser) Parse() (Expression, error) {
expr := p.parseExpression(LOWEST)
// Check for trailing tokens (garbage after valid expression)
if p.peekToken.Type == TokenError {
if errMsg, ok := p.peekToken.Value.(string); ok {
p.addError("lexer error: %s", errMsg)
} else {
p.addError("lexer error at: %s", p.peekToken.Literal)
}
} else if p.peekToken.Type != TokenEOF {
p.addError("unexpected trailing token: %s", p.peekToken.Type)
}
if len(p.errors) > 0 {
return nil, fmt.Errorf("parse errors: %v", p.errors)
}
return expr, nil
}
func (p *Parser) parseExpression(precedence int) Expression {
var left Expression
switch p.curToken.Type {
case TokenError:
if errMsg, ok := p.curToken.Value.(string); ok {
p.addError("lexer error: %s", errMsg)
} else {
p.addError("lexer error at: %s", p.curToken.Literal)
}
p.synchronize()
return nil
case TokenNot:
left = p.parseUnaryExpression()
case TokenLParen:
left = p.parseGroupedExpression()
case TokenIdent:
left = p.parseFieldExpression()
case TokenString, TokenRawString, TokenInt, TokenFloat, TokenBool,
TokenIP, TokenCIDR, TokenTime, TokenDuration:
left = p.parseLiteralExpression()
case TokenListRef:
left = p.parseListRefExpression()
if p.peekToken.Type == TokenLBracket {
left = p.parseIndexExpression(left)
}
default:
p.addError("unexpected token: %s", p.curToken.Type)
p.synchronize()
return nil
}
for p.peekToken.Type != TokenEOF && precedence < p.peekPrecedence() {
p.nextToken()
left = p.parseBinaryExpression(left)
}
return left
}
// synchronize skips tokens until the parser reaches a safe restart point.
// This enables multi-error reporting by recovering from parse failures.
func (p *Parser) synchronize() {
for p.peekToken.Type != TokenEOF {
switch p.peekToken.Type {
case TokenAnd, TokenOr, TokenXor:
return
case TokenRParen, TokenRBrace, TokenRBracket:
return
}
p.nextToken()
}
}
func (p *Parser) parseUnaryExpression() Expression {
operator := p.curToken.Type
p.nextToken()
operand := p.parseExpression(PREFIX)
return &UnaryExpr{
Operator: operator,
Operand: operand,
}
}
func (p *Parser) parseGroupedExpression() Expression {
p.nextToken()
expr := p.parseExpression(LOWEST)
if p.peekToken.Type != TokenRParen {
p.addError("expected ), got %s", p.peekToken.Type)
p.synchronize()
return expr
}
p.nextToken()
return expr
}
func (p *Parser) parseFieldExpression() Expression {
name := p.curToken.Literal
// Check if this is a function call (identifier followed by '(')
if p.peekToken.Type == TokenLParen {
expr := p.parseFunctionCallExpression(name)
// Check for array index on function result: func()[0]
if p.peekToken.Type == TokenLBracket {
return p.parseIndexExpression(expr)
}
return expr
}
field := &FieldExpr{Name: name}
if p.peekToken.Type == TokenLBracket {
return p.parseIndexExpression(field)
}
return field
}
func (p *Parser) parseFunctionCallExpression(name string) Expression {
p.nextToken() // consume '('
p.nextToken() // move to first argument or ')'
args := []Expression{}
// Handle empty argument list
if p.curToken.Type == TokenRParen {
return &FunctionCallExpr{Name: name, Arguments: args}
}
// Parse first argument
arg := p.parseExpression(LOWEST)
args = append(args, arg)
// Parse remaining arguments
for p.peekToken.Type == TokenComma {
p.nextToken() // consume ','
p.nextToken() // move to next argument
arg = p.parseExpression(LOWEST)
args = append(args, arg)
}
if p.peekToken.Type != TokenRParen {
p.addError("expected ), got %s", p.peekToken.Type)
p.synchronize()
return &FunctionCallExpr{Name: name, Arguments: args}
}
p.nextToken() // consume ')'
return &FunctionCallExpr{Name: name, Arguments: args}
}
func (p *Parser) parseIndexExpression(object Expression) Expression {
p.nextToken() // consume [
p.nextToken() // move to the index expression
// Check for array unpack [*]
if p.curToken.Type == TokenAsterisk {
if p.peekToken.Type != TokenRBracket {
p.addError("expected ], got %s", p.peekToken.Type)
p.synchronize()
return &UnpackExpr{Array: object}
}
p.nextToken() // consume ]
return &UnpackExpr{Array: object}
}
// Parse index: literal (string, int, float) or field reference
var index Expression
switch p.curToken.Type {
case TokenString, TokenRawString, TokenInt, TokenFloat:
index = p.parseLiteralExpression()
case TokenIdent:
index = p.parseFieldExpression()
default:
p.addError("index must be a literal or field reference, got %s", p.curToken.Type)
p.synchronize()
return object
}
if p.peekToken.Type != TokenRBracket {
p.addError("expected ], got %s", p.peekToken.Type)
p.synchronize()
return &IndexExpr{Object: object, Index: index}
}
p.nextToken() // consume ]
expr := &IndexExpr{
Object: object,
Index: index,
}
// Support chained index expressions like field["a"]["b"]
if p.peekToken.Type == TokenLBracket {
return p.parseIndexExpression(expr)
}
return expr
}
func (p *Parser) parseLiteralExpression() Expression {
var value Value
switch p.curToken.Type {
case TokenString:
value = StringValue(p.curToken.Literal)
case TokenRawString:
value = StringValue(p.curToken.Literal)
case TokenInt:
value = IntValue(p.curToken.Value.(int64))
case TokenFloat:
value = FloatValue(p.curToken.Value.(float64))
case TokenBool:
value = BoolValue(p.curToken.Value.(bool))
case TokenIP:
value = IPValue{IP: p.curToken.Value.(net.IP)}
case TokenCIDR:
value = CIDRValue{IPNet: p.curToken.Value.(*net.IPNet)}
case TokenTime:
value = NewTimeValue(p.curToken.Value.(time.Time))
case TokenDuration:
value = DurationValue(p.curToken.Value.(time.Duration))
}
return &LiteralExpr{Value: value}
}
func (p *Parser) parseListRefExpression() Expression {
return &ListRefExpr{Name: p.curToken.Literal}
}
func (p *Parser) parseBinaryExpression(left Expression) Expression {
// Handle "not in" / "not contains" compound operators
if p.curToken.Type == TokenNot && (p.peekToken.Type == TokenIn || p.peekToken.Type == TokenContains) {
p.nextToken() // consume in/contains
operator := p.curToken.Type
precedence := p.curPrecedence()
p.nextToken()
var right Expression
if p.curToken.Type == TokenLBrace {
right = p.parseArrayExpression()
} else {
right = p.parseExpression(precedence)
}
return &UnaryExpr{
Operator: TokenNot,
Operand: &BinaryExpr{
Left: left,
Operator: operator,
Right: right,
},
}
}
operator := p.curToken.Type
precedence := p.curPrecedence()
if operator == TokenIn || operator == TokenContains {
p.nextToken()
var right Expression
if p.curToken.Type == TokenLBrace {
right = p.parseArrayExpression()
} else {
right = p.parseExpression(precedence)
}
return &BinaryExpr{
Left: left,
Operator: operator,
Right: right,
}
}
p.nextToken()
right := p.parseExpression(precedence)
return &BinaryExpr{
Left: left,
Operator: operator,
Right: right,
}
}
func (p *Parser) parseArrayExpression() Expression {
elements := []Expression{}
p.nextToken()
if p.curToken.Type == TokenRBrace {
return &ArrayExpr{Elements: elements}
}
element := p.parseExpression(LOWEST)
if p.peekToken.Type == TokenRange {
p.nextToken()
p.nextToken()
end := p.parseExpression(LOWEST)
element = &RangeExpr{Start: element, End: end}
}
elements = append(elements, element)
for p.peekToken.Type == TokenComma {
p.nextToken()
p.nextToken()
element = p.parseExpression(LOWEST)
if p.peekToken.Type == TokenRange {
p.nextToken()
p.nextToken()
end := p.parseExpression(LOWEST)
element = &RangeExpr{Start: element, End: end}
}
elements = append(elements, element)
}
if p.peekToken.Type != TokenRBrace {
p.addError("expected }, got %s", p.peekToken.Type)
p.synchronize()
return &ArrayExpr{Elements: elements}
}
p.nextToken()
return &ArrayExpr{Elements: elements}
}
func (p *Parser) curPrecedence() int {
if p, ok := precedences[p.curToken.Type]; ok {
return p
}
return LOWEST
}
func (p *Parser) peekPrecedence() int {
// Handle "not in" / "not contains" compound operators
if p.peekToken.Type == TokenNot {
if p.peekPeekToken.Type == TokenIn || p.peekPeekToken.Type == TokenContains {
return MEMBERSHIP
}
}
if prec, ok := precedences[p.peekToken.Type]; ok {
return prec
}
return LOWEST
}