forked from expr-lang/expr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
608 lines (528 loc) · 12.7 KB
/
parser.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
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
package expr
import (
"fmt"
"reflect"
"regexp"
"strconv"
"unicode/utf8"
)
type associativity int
const (
left associativity = iota + 1
right
)
type info struct {
precedence int
associativity associativity
}
var unaryOperators = map[string]info{
"not": {50, left},
"!": {50, left},
"-": {500, left},
"+": {500, left},
}
var binaryOperators = map[string]info{
"or": {10, left},
"||": {10, left},
"and": {15, left},
"&&": {15, left},
"|": {16, left},
"^": {17, left},
"&": {18, left},
"==": {20, left},
"!=": {20, left},
"<": {20, left},
">": {20, left},
">=": {20, left},
"<=": {20, left},
"not in": {20, left},
"in": {20, left},
"matches": {20, left},
"..": {25, left},
"+": {30, left},
"-": {30, left},
"~": {40, left},
"*": {60, left},
"/": {60, left},
"%": {60, left},
"**": {200, right},
}
var builtins = map[string]bool{
"len": true,
}
type parser struct {
input string
tokens []token
position int
current token
strict bool
types typesTable
}
// OptionFn for configuring parser.
type OptionFn func(p *parser)
// Parse parses input into ast.
func Parse(input string, ops ...OptionFn) (Node, error) {
tokens, err := lex(input)
if err != nil {
return nil, err
}
p := &parser{
input: input,
tokens: tokens,
current: tokens[0],
types: make(typesTable),
}
for _, op := range ops {
op(p)
}
node, err := p.parseExpression(0)
if err != nil {
return nil, err
}
if !p.isEOF() {
return nil, p.errorf("unexpected token %v", p.current)
}
if p.strict {
_, err = node.Type(p.types)
if err != nil {
return nil, err
}
}
return node, nil
}
// Define sets variable for type checks during parsing.
func Define(name string, t interface{}) OptionFn {
return func(p *parser) {
p.strict = true
p.types[name] = reflect.TypeOf(t)
}
}
// Deprecated: Use expr.Env instead.
func With(i interface{}) OptionFn {
return Env(i)
}
// Env sets variables for type checks during parsing.
// If struct is passed, all fields will be treated as variables,
// as well as all fields of embedded structs and struct itself.
//
// If map is passed, all items will be treated as variables
// (key as name, value as type).
func Env(i interface{}) OptionFn {
return func(p *parser) {
p.strict = true
for k, v := range p.createTypesTable(i) {
p.types[k] = v
}
}
}
func (p *parser) createTypesTable(i interface{}) typesTable {
types := make(typesTable)
v := reflect.ValueOf(i)
t := reflect.TypeOf(i)
d := t
if t.Kind() == reflect.Ptr {
d = t.Elem()
}
switch d.Kind() {
case reflect.Struct:
types = p.fieldsFromStruct(d)
// Methods of struct should be gathered from original struct with pointer,
// as methods maybe declared on pointer receiver. Also this method retrieves
// all embedded structs methods as well, no need to recursion.
for i := 0; i < t.NumMethod(); i++ {
m := t.Method(i)
types[m.Name] = m.Type
}
case reflect.Map:
for _, key := range v.MapKeys() {
value := v.MapIndex(key)
if key.Kind() == reflect.String && value.IsValid() && value.CanInterface() {
types[key.String()] = reflect.TypeOf(value.Interface())
}
}
}
return types
}
func (p *parser) fieldsFromStruct(t reflect.Type) typesTable {
types := make(typesTable)
t = dereference(t)
if t == nil {
return types
}
switch t.Kind() {
case reflect.Struct:
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Anonymous {
for name, typ := range p.fieldsFromStruct(f.Type) {
types[name] = typ
}
}
types[f.Name] = f.Type
}
}
return types
}
func (p *parser) errorf(format string, args ...interface{}) *syntaxError {
return &syntaxError{
message: fmt.Sprintf(format, args...),
input: p.input,
pos: p.current.pos,
}
}
func (p *parser) next() error {
p.position++
if p.position >= len(p.tokens) {
return p.errorf("unexpected end of expression")
}
p.current = p.tokens[p.position]
return nil
}
func (p *parser) expect(kind tokenKind, values ...string) error {
if p.current.is(kind, values...) {
return p.next()
}
return p.errorf("unexpected token %v", p.current)
}
func (p *parser) isEOF() bool {
return p.current.is(eof)
}
// parse functions
func (p *parser) parseExpression(precedence int) (Node, error) {
node, err := p.parsePrimary()
if err != nil {
return nil, err
}
token := p.current
for token.is(operator) {
if op, ok := binaryOperators[token.value]; ok {
if op.precedence >= precedence {
if err = p.next(); err != nil {
return nil, err
}
var expr Node
if op.associativity == left {
expr, err = p.parseExpression(op.precedence + 1)
if err != nil {
return nil, err
}
} else {
expr, err = p.parseExpression(op.precedence)
if err != nil {
return nil, err
}
}
if token.is(operator, "matches") {
var r *regexp.Regexp
if s, ok := expr.(textNode); ok {
r, err = regexp.Compile(s.value)
if err != nil {
return nil, p.errorf("%v", err)
}
}
node = matchesNode{r: r, left: node, right: expr}
} else {
node = binaryNode{operator: token.value, left: node, right: expr}
}
token = p.current
continue
}
}
break
}
if precedence == 0 {
node, err = p.parseConditionalExpression(node)
if err != nil {
return nil, err
}
}
return node, nil
}
func (p *parser) parsePrimary() (Node, error) {
token := p.current
if token.is(operator) {
if op, ok := unaryOperators[token.value]; ok {
if err := p.next(); err != nil {
return nil, err
}
expr, err := p.parseExpression(op.precedence)
if err != nil {
return nil, err
}
return p.parsePostfixExpression(unaryNode{operator: token.value, node: expr})
}
}
if token.is(punctuation, "(") {
if err := p.next(); err != nil {
return nil, err
}
expr, err := p.parseExpression(0)
if err != nil {
return nil, err
}
err = p.expect(punctuation, ")")
if err != nil {
return nil, p.errorf("an opened parenthesis is not properly closed")
}
return p.parsePostfixExpression(expr)
}
return p.parsePrimaryExpression()
}
func (p *parser) parseConditionalExpression(node Node) (Node, error) {
var err error
var expr1, expr2 Node
for p.current.is(punctuation, "?") {
if err := p.next(); err != nil {
return nil, err
}
if !p.current.is(punctuation, ":") {
expr1, err = p.parseExpression(0)
if err != nil {
return nil, err
}
if err := p.expect(punctuation, ":"); err != nil {
return nil, err
}
expr2, err = p.parseExpression(0)
if err != nil {
return nil, err
}
} else {
if err := p.next(); err != nil {
return nil, err
}
expr1 = node
expr2, err = p.parseExpression(0)
if err != nil {
return nil, err
}
}
node = conditionalNode{node, expr1, expr2}
}
return node, nil
}
func (p *parser) parsePrimaryExpression() (Node, error) {
var err error
var node Node
token := p.current
switch token.kind {
case name:
if err := p.next(); err != nil {
return nil, err
}
switch token.value {
case "true":
return boolNode{value: true}, nil
case "false":
return boolNode{value: false}, nil
case "nil":
return nilNode{}, nil
default:
node, err = p.parseNameExpression(token)
if err != nil {
return nil, err
}
}
case number:
if err := p.next(); err != nil {
return nil, err
}
number, err := strconv.ParseFloat(token.value, 64)
if err != nil {
return nil, p.errorf("%v", err)
}
return numberNode{value: number}, nil
case text:
if err := p.next(); err != nil {
return nil, err
}
return textNode{value: token.value}, nil
default:
if token.is(punctuation, "[") {
node, err = p.parseArrayExpression()
if err != nil {
return nil, err
}
} else if token.is(punctuation, "{") {
node, err = p.parseMapExpression()
if err != nil {
return nil, err
}
} else {
return nil, p.errorf("unexpected token %v", token).at(token)
}
}
return p.parsePostfixExpression(node)
}
func (p *parser) parseNameExpression(token token) (Node, error) {
var node Node
if p.current.is(punctuation, "(") {
arguments, err := p.parseArguments()
if err != nil {
return nil, err
}
if _, ok := builtins[token.value]; ok {
node = builtinNode{name: token.value, arguments: arguments}
} else {
node = functionNode{name: token.value, arguments: arguments}
}
} else {
node = nameNode{name: token.value}
}
return node, nil
}
func (p *parser) parseArrayExpression() (Node, error) {
nodes, err := p.parseList("array items", "[", "]")
if err != nil {
return nil, err
}
return arrayNode{nodes}, nil
}
func (p *parser) parseMapExpression() (Node, error) {
err := p.expect(punctuation, "{")
if err != nil {
return nil, err
}
nodes := make([]pairNode, 0)
for !p.current.is(punctuation, "}") {
if len(nodes) > 0 {
err = p.expect(punctuation, ",")
if err != nil {
return nil, p.errorf("a map value must be followed by a comma")
}
}
var key Node
// a map key can be:
// * a number
// * a text
// * a name, which is equivalent to a string
// * an expression, which must be enclosed in parentheses -- (1 + 2)
if p.current.is(number) || p.current.is(text) || p.current.is(name) {
key = identifierNode{p.current.value}
if err := p.next(); err != nil {
return nil, err
}
} else if p.current.is(punctuation, "(") {
key, err = p.parseExpression(0)
if err != nil {
return nil, err
}
} else {
return nil, p.errorf("a map key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token %v)", p.current)
}
err = p.expect(punctuation, ":")
if err != nil {
return nil, p.errorf("a map key must be followed by a colon (:)")
}
node, err := p.parseExpression(0)
if err != nil {
return nil, err
}
nodes = append(nodes, pairNode{key, node})
}
err = p.expect(punctuation, "}")
if err != nil {
return nil, err
}
return mapNode{nodes}, nil
}
func (p *parser) parsePostfixExpression(node Node) (Node, error) {
token := p.current
for token.is(punctuation) {
if token.value == "." {
if err := p.next(); err != nil {
return nil, err
}
token = p.current
if err := p.next(); err != nil {
return nil, err
}
if token.kind != name &&
// Operators like "not" and "matches" are valid method or property names,
//
// In other words, besides name token kind, operator kind could also be parsed as a property or method.
// This is because operators are processed by the lexer prior to names. So "not" in "foo.not()"
// or "matches" in "foo.matches" will be recognized as an operator first. But in fact, "not"
// and "matches" in such expressions shall be parsed as method or property names.
//
// And this ONLY works if the operator consists of valid characters for a property or method name.
//
// Other types, such as text kind and number kind, can't be parsed as property nor method names.
//
// As a result, if token is NOT an operator OR token.value is NOT a valid property or method name,
// an error shall be returned.
(token.kind != operator || !isValidIdentifier(token.value)) {
return nil, p.errorf("expected name").at(token)
}
if p.current.is(punctuation, "(") {
arguments, err := p.parseArguments()
if err != nil {
return nil, err
}
node = methodNode{node: node, method: token.value, arguments: arguments}
} else {
node = propertyNode{node: node, property: token.value}
}
} else if token.value == "[" {
if err := p.next(); err != nil {
return nil, err
}
arg, err := p.parseExpression(0)
if err != nil {
return nil, err
}
node = indexNode{node: node, index: arg}
err = p.expect(punctuation, "]")
if err != nil {
return nil, err
}
} else {
break
}
token = p.current
}
return node, nil
}
func isValidIdentifier(str string) bool {
if len(str) == 0 {
return false
}
h, w := utf8.DecodeRuneInString(str)
if !isAlphabetic(h) {
return false
}
for _, r := range str[w:] {
if !isAlphaNumeric(r) {
return false
}
}
return true
}
func (p *parser) parseArguments() ([]Node, error) {
return p.parseList("arguments", "(", ")")
}
func (p *parser) parseList(what, start, end string) ([]Node, error) {
err := p.expect(punctuation, start)
if err != nil {
return nil, err
}
nodes := make([]Node, 0)
for !p.current.is(punctuation, end) {
if len(nodes) > 0 {
err = p.expect(punctuation, ",")
if err != nil {
return nil, p.errorf("%v must be separated by a comma", what)
}
}
node, err := p.parseExpression(0)
if err != nil {
return nil, err
}
nodes = append(nodes, node)
}
err = p.expect(punctuation, end)
if err != nil {
return nil, err
}
return nodes, nil
}