-
Notifications
You must be signed in to change notification settings - Fork 47
/
parser.go
569 lines (478 loc) · 10.8 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
/*
Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
package selector
import (
"fmt"
"strings"
"unicode/utf8"
)
// Parser parses a selector incrementally.
type Parser struct {
// s stores the string to be tokenized
s string
// pos is the position currently tokenized
pos int
// m is an optional mark
m int
skipValidation bool
}
// Parse does the actual parsing.
func (p *Parser) Parse() (Selector, error) {
p.s = strings.TrimSpace(p.s)
if len(p.s) == 0 {
return Any{}, nil
}
var b rune
var selector, subSelector Selector
var err error
var word string
var op string
// loop over "clauses"
// clauses are separated by commas and grouped logically as "ands"
for {
// sniff the !haskey form
b = p.current()
if b == Bang {
p.advance() // we aren't going to use the '!'
// read off the !KEY
// readWord will leave us on the next non-alpha char
word, err = p.readWord()
if err != nil {
return nil, err
}
selector = p.addAnd(selector, p.notHasKey(word)) // add the !KEY term
if p.done() {
break
}
p.skipToNonWhitespace()
b = p.current()
if b != Comma {
return nil, p.parseError("consecutive not has key terms")
}
p.advance()
continue
}
// we're done peeking the first char
// read the first KEY
word, err = p.readWord()
if err != nil {
return nil, err
}
p.mark() // mark to revert if the sniff for the `KEY` form fails
// sniff if the next character after the word is a comma
// this indicates it's a "key" form, or existence check on a key
b = p.skipToNonWhitespace() // the comma is not whitespace
if b == Comma || p.done() {
selector = p.addAnd(selector, p.hasKey(word))
if b == Comma {
// this is largely a no-op unless we hit a comma
p.advance()
// we _have_ to eat the next whitespace
_ = p.skipToNonWhitespace()
if p.done() {
return nil, p.parseError()
}
}
if p.done() {
break
}
continue
} else {
p.popMark()
}
op, err = p.readOp()
if err != nil {
return nil, err
}
switch op {
case OpEquals, OpDoubleEquals:
subSelector, err = p.equals(word)
case OpNotEquals:
subSelector, err = p.notEquals(word)
case OpIn:
subSelector, err = p.in(word)
case OpNotIn:
subSelector, err = p.notIn(word)
default:
return nil, p.parseError("invalid operator")
}
if err != nil {
return nil, err
}
selector = p.addAnd(selector, subSelector)
b = p.skipToNonWhitespace()
if b == Comma {
p.advance()
if p.done() {
return nil, p.parseError(errExpectedNonEmptyKey)
}
p.skipToNonWhitespace()
continue
}
if p.done() {
break
}
// we have a "foo == bar foo" situation
return nil, p.parseError("keys not separated by comma")
}
if !p.skipValidation {
err = selector.Validate()
if err != nil {
return nil, err
}
}
return selector, nil
}
// addAnd starts grouping selectors into a high level `and`, returning the aggregate selector.
func (p *Parser) addAnd(current, next Selector) Selector {
if current == nil {
return next
}
if typed, isTyped := current.(And); isTyped {
return append(typed, next)
}
return And([]Selector{current, next})
}
func (p *Parser) hasKey(key string) Selector {
return HasKey(key)
}
func (p *Parser) notHasKey(key string) Selector {
return NotHasKey(key)
}
func (p *Parser) equals(key string) (Selector, error) {
value, err := p.readWord()
if err != nil {
return nil, err
}
return Equals{Key: key, Value: value}, nil
}
func (p *Parser) notEquals(key string) (Selector, error) {
value, err := p.readWord()
if err != nil {
return nil, err
}
return NotEquals{Key: key, Value: value}, nil
}
func (p *Parser) in(key string) (Selector, error) {
csv, err := p.readCSV()
if err != nil {
return nil, err
}
return In{Key: key, Values: csv}, nil
}
func (p *Parser) notIn(key string) (Selector, error) {
csv, err := p.readCSV()
if err != nil {
return nil, err
}
return NotIn{Key: key, Values: csv}, nil
}
// done indicates the cursor is past the usable length of the string.
func (p *Parser) done() bool {
return p.pos == len(p.s)
}
// mark sets a mark at the current position.
func (p *Parser) mark() {
p.m = p.pos
}
// popMark moves the cursor back to the previous mark.
func (p *Parser) popMark() {
if p.m > 0 {
p.pos = p.m
}
p.m = 0
}
// current returns the rune at the current position.
func (p *Parser) current() (r rune) {
r, _ = utf8.DecodeRuneInString(p.s[p.pos:])
return
}
// advance moves the cursor forward one rune.
func (p *Parser) advance() {
if p.pos < len(p.s) {
_, width := utf8.DecodeRuneInString(p.s[p.pos:])
p.pos += width
}
}
// readOp reads a valid operator.
// valid operators include:
// [ =, ==, !=, in, notin ]
// errors if it doesn't read one of the above, or there is another structural issue.
// this will leave the position on the character after the operator
func (p *Parser) readOp() (string, error) {
// skip preceding whitespace
p.skipWhiteSpace()
const (
stateFirstOpChar = 0
stateEqual = 1
stateBang = 2
stateInI = 3
stateNotInN = 4
stateNotInO = 5
stateNotInT = 6
stateNotInI = 7
)
var state int
var ch rune
var op []rune
for {
if p.done() {
return "", p.parseError("invalid operator")
}
ch = p.current()
switch state {
case stateFirstOpChar: // initial state, determine what op we're reading for
if ch == Equal {
state = stateEqual
break
}
if ch == Bang {
state = stateBang
break
}
if ch == 'i' {
state = stateInI
break
}
if ch == 'n' {
state = stateNotInN
break
}
return "", p.parseError("invalid operator")
case stateEqual:
if p.isWhitespace(ch) || isAlpha(ch) || ch == Comma {
return string(op), nil
}
if ch == Equal {
op = append(op, ch)
p.advance()
return string(op), nil
}
return "", p.parseError("invalid operator")
case stateBang:
if ch == Equal {
op = append(op, ch)
p.advance()
return string(op), nil
}
return "", p.parseError("invalid operator")
case stateInI:
if ch == 'n' {
op = append(op, ch)
p.advance()
return string(op), nil
}
return "", p.parseError("invalid operator")
case stateNotInN:
if ch == 'o' {
state = stateNotInO
break
}
return "", p.parseError("invalid operator")
case stateNotInO:
if ch == 't' {
state = stateNotInT
break
}
return "", p.parseError("invalid operator")
case stateNotInT:
if ch == 'i' {
state = stateNotInI
break
}
return "", p.parseError("invalid operator")
case stateNotInI:
if ch == 'n' {
op = append(op, ch)
p.advance()
return string(op), nil
}
return "", p.parseError("invalid operator")
}
op = append(op, ch)
p.advance()
}
}
// readWord skips whitespace, then reads a word until whitespace or a token.
// it will leave the cursor on the next char after the word, i.e. the space or token.
func (p *Parser) readWord() (string, error) {
p.skipWhiteSpace()
var word []rune
var ch rune
for {
if p.done() {
break
}
ch = p.current()
if isWhitespace(ch) ||
ch == Comma ||
isOperatorSymbol(ch) {
break
}
word = append(word, ch)
p.advance()
}
if len(word) == 0 {
return "", p.parseError(errExpectedNonEmptyKey)
}
return string(word), nil
}
// readCSV reads an array of strings in csv form.
// it expects to start just before the first `(` and
// will read until just past the closing `)`
func (p *Parser) readCSV() (results []string, err error) {
// skip preceding whitespace
p.skipWhiteSpace()
const (
stateBeforeParens = 0
stateWord = 1
stateWhitespaceAfterOpenParens = 2
stateWhitespaceAfterComma = 3
stateWhitespaceAfterWord = 4
)
var word []rune
var ch rune
var state int
for {
if p.done() {
results = nil
err = p.parseError("csv; expects close parenthesis")
// err = ErrInvalidSelector
return
}
ch = p.current()
switch state {
case stateBeforeParens:
if ch == OpenParens {
state = stateWhitespaceAfterOpenParens
p.advance()
continue
}
// not open parens, bail
err = p.parseError("csv; expects open parenthesis")
results = nil
return
case stateWord:
if ch == Comma {
if len(word) > 0 {
results = append(results, string(word))
word = nil
}
// the symbol is the comma
state = stateWhitespaceAfterComma
p.advance()
continue
}
if ch == CloseParens {
if len(word) > 0 {
results = append(results, string(word))
}
p.advance()
return
}
if p.isWhitespace(ch) {
if len(word) > 0 {
results = append(results, string(word))
word = nil
}
state = stateWhitespaceAfterWord
p.advance()
continue
}
if !p.isValidValue(ch) {
err = p.parseError("csv; word contains invalid characters")
results = nil
return
}
word = append(word, ch)
p.advance()
continue
case stateWhitespaceAfterOpenParens, stateWhitespaceAfterComma:
if p.isWhitespace(ch) {
p.advance()
continue
}
if isAlpha(ch) {
state = stateWord
continue
}
if ch == Comma {
p.advance()
state = stateWhitespaceAfterComma
continue
}
if ch == CloseParens {
p.advance()
return // exit reading the csv
}
if state == stateWhitespaceAfterOpenParens {
err = p.parseError("csv; invalid characters after '('")
return
}
err = p.parseError("csv; invalid characters after ','")
return
case stateWhitespaceAfterWord:
if ch == CloseParens {
if len(word) > 0 {
results = append(results, string(word))
}
p.advance()
return
}
if p.isWhitespace(ch) {
p.advance()
continue
}
if ch == Comma {
state = stateWhitespaceAfterComma
p.advance()
continue
}
err = p.parseError("csv; consecutive whitespace separated words without a comma")
results = nil
return
}
}
}
func (p *Parser) skipWhiteSpace() {
var ch rune
for {
if p.done() {
return
}
ch = p.current()
if !p.isWhitespace(ch) {
return
}
p.advance()
}
}
func (p *Parser) skipToNonWhitespace() (ch rune) {
for {
if p.done() {
return
}
ch = p.current()
if ch == Comma || !p.isWhitespace(ch) {
return
}
p.advance()
}
}
// isWhitespace returns true if the rune is a space, tab, or newline.
func (p *Parser) isWhitespace(ch rune) bool {
return ch == Space || ch == Tab || ch == CarriageReturn || ch == NewLine
}
func (p *Parser) isValidValue(ch rune) bool {
return isAlpha(ch) || isNameSymbol(ch)
}
func (p *Parser) parseError(message ...interface{}) error {
return &ParseError{
Err: ErrInvalidSelector,
Input: p.s,
Position: p.pos,
Message: fmt.Sprint(message...),
}
}