forked from BatchLabs/charlatan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
668 lines (524 loc) · 13.2 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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
package charlatan
import (
"errors"
"fmt"
)
// the automate state
type state int
const (
invalidState state = -1
initial state = iota
selectInitial
selectField
fromInitial
operationInitial
leftOperand
operator
rightOperand
startingInitial
startingAt
limitInitial
limitSep
limitMax
rangeMin
rangeAnd
rangeMax
clauseEnd
end
)
// parser is the parser itself
type parser struct {
// the lexer to read tokens
lexer *lexer
// the current state
state state
// the array of fields,
// before the query is initialized
fields []*Field
// the query
query *Query
// the operation context stack
stack []*context
// and the current context
current *context
}
// the context, that contains informations
// about the current operations
type context struct {
// the current operation
left operand
operator tokenType
right operand
// the logical operation nodes
first *logicalOperation
last *logicalOperation
// the current range test, if there's one
rangeTest *rangeTestOperation
// the current logical operator
logicalOperator tokenType
// if stacked, in which state
// this context should be restored
// only leftOperand or rightOperand
stackState state
}
// parserFromString creates a new parser from the given string
func parserFromString(s string) *parser {
return &parser{
lexer: lexerFromString(s),
state: initial,
fields: make([]*Field, 0),
stack: make([]*context, 0),
current: newContext(),
}
}
// Parse parses and returns the query
func (p *parser) Parse() (*Query, error) {
// Read tokens, move step by step
// until the next state is the end
for p.state != end {
tok, err := p.lexer.NextToken()
if err != nil {
return nil, err
}
switch p.state {
// the very begining
case initial:
p.state, err = p.initialState(tok)
// SELECT
case selectInitial:
p.state, err = p.selectState(tok)
case selectField:
p.state, err = p.selectFieldState(tok)
// FROM
case fromInitial:
p.state, err = p.fromState(tok)
// WHERE
case operationInitial:
p.state, err = p.operationState(tok)
case leftOperand:
p.state, err = p.operandLeftState(tok)
case operator:
p.state, err = p.operatorState(tok)
case rightOperand:
p.state, err = p.operandRightState(tok)
// range
case rangeMin:
p.state, err = p.rangeMin(tok)
case rangeAnd:
p.state, err = p.expect(tokAnd, tok, rangeMax)
case rangeMax:
p.state, err = p.rangeMax(tok)
// STARTING
case startingInitial:
p.state, err = p.expect(tokAt, tok, startingAt)
// AT
case startingAt:
p.state, err = p.startingAt(tok)
// LIMIT N
// ^
case limitInitial:
p.state, err = p.limit(tok)
// LIMIT N, M
// ^
case limitSep:
p.state, err = p.limitSep(tok)
// LIMIT N, M
// ^
case limitMax:
p.state, err = p.limitMax(tok)
case clauseEnd:
p.state, err = p.clauseEnd(tok)
// unknown
default:
err = fmt.Errorf("Unknown state %d", p.state)
}
// an error occured during handling the state
if err != nil {
return nil, err
}
}
// Handle the operation context
if len(p.stack) > 0 {
return nil, fmt.Errorf("Unbalanced parenthesis")
}
if p.current.first != nil {
// affect the logical node as the expression
// FIXME should we finish the operation ???
p.query.setWhere(p.current.first.simplify())
}
return p.query, nil
}
// We’re only waiting for the SELECT keyword
func (p *parser) initialState(tok *token) (state, error) {
if tok.Type != tokSelect {
return unexpected(tok, tokSelect)
}
return selectInitial, nil
}
// We’re waiting for a field
func (p *parser) selectState(tok *token) (state, error) {
if tok.Type != tokField {
return unexpected(tok, tokField)
}
p.fields = append(p.fields, NewField(tok.Value))
return selectField, nil
}
// We’re waiting for a comma, or the FROM keyword
func (p *parser) selectFieldState(tok *token) (state, error) {
if tok.Type == tokComma {
// we just jump to the next field
return selectInitial, nil
}
if tok.Type != tokFrom {
return unexpected(tok, tokFrom)
}
return fromInitial, nil
}
// We’re waiting for a name of the from
func (p *parser) fromState(tok *token) (state, error) {
if tok.Type != tokField {
return unexpected(tok, tokField)
}
p.query = NewQuery(tok.Value)
p.query.AddFields(p.fields)
p.fields = nil
return clauseEnd, nil
}
// We’re waiting for any of the WHERE, STARTING, or LIMIT keywords, or the end
func (p *parser) clauseEnd(tok *token) (state, error) {
switch tok.Type {
case tokEnd:
return end, nil
case tokWhere:
return operationInitial, nil
case tokStarting:
return startingInitial, nil
case tokLimit:
return limitInitial, nil
default:
if p.query != nil && p.query.expression != nil {
if p.query.startingAt == 0 {
return unexpected(tok, tokStarting)
}
if !p.query.HasLimit() {
return unexpected(tok, tokLimit)
}
}
return unexpected(tok, tokWhere)
}
}
func tok2operand(tok *token) (operand, error) {
if tok.isField() {
return NewField(tok.Value), nil
}
if tok.isConst() {
return tok.Const()
}
return nil, fmt.Errorf("Invalid token: not an operand: %v", tok)
}
// We’re waiting for a left operand, or a (
func (p *parser) operationState(tok *token) (state, error) {
if tok.Type == tokLeftParenthesis {
// push the context and start a new operation
p.pushContext(leftOperand)
return operationInitial, nil
}
c, err := tok2operand(tok)
if err != nil {
return invalidState, err
}
p.current.left = c
// the left operand has been setted jump to the left operand state
return leftOperand, nil
}
// We’re waiting for an operator:
// - logical operator, we step to the next operation
// - comparison operator, we continue to the operator state
// - "BETWEEN", we continue to the range operator state
//
// We can encounter a ), or the end
func (p *parser) operandLeftState(tok *token) (state, error) {
if tok.isEnd() {
// end the previous operation
if err := p.current.endOperation(); err != nil {
return invalidState, err
}
return end, nil
}
switch tok.Type {
case tokStarting:
return startingInitial, nil
case tokLimit:
return limitInitial, nil
}
if tok.isLogicalOperator() {
// this is the end of the previous operation
if err := p.current.endOperation(); err != nil {
return invalidState, err
}
// set this operator and jump to a new operation
p.current.logicalOperator = tok.Type
return operationInitial, nil
}
if tok.isComparisonOperator() {
// set the operator and jump to the operator state
p.current.operator = tok.Type
return operator, nil
}
// we close a context, pop it
if tok.Type == tokRightParenthesis {
return p.popContext()
}
if tok.Type == tokBetween {
p.current.rangeTest = &rangeTestOperation{
test: p.current.left,
}
p.current.left = p.current.rangeTest
return rangeMin, nil
}
return unexpected(tok, tokInvalid)
}
func (p *parser) rangeMin(tok *token) (state, error) {
c, err := tok2operand(tok)
if err != nil {
return invalidState, err
}
if p.current.rangeTest == nil {
return invalidState, errors.New("Nil range test")
}
p.current.rangeTest.min = c
return rangeAnd, nil
}
func (p *parser) rangeMax(tok *token) (state, error) {
c, err := tok2operand(tok)
if err != nil {
return invalidState, err
}
if p.current.rangeTest == nil {
return invalidState, errors.New("Nil range test")
}
p.current.rangeTest.max = c
return rightOperand, nil
}
// We're waiting for a right operand, nothing else, or a (
func (p *parser) operatorState(tok *token) (state, error) {
// handle the (
if tok.Type == tokLeftParenthesis {
// we push the state
p.pushContext(rightOperand)
// jump the the start of an operation
return operationInitial, nil
}
if tok.isField() {
p.current.right = NewField(tok.Value)
} else if tok.isConst() {
c, err := tok.Const()
if err != nil {
return invalidState, err
}
p.current.right = c
} else {
return unexpected(tok, tokInvalid)
}
// the right operand has been setted jump to the left operand state
return rightOperand, nil
}
// We're waiting for a logical operator, ), or the end
func (p *parser) operandRightState(tok *token) (state, error) {
// end of a context
// we pop, and continue to the correct state
// (the pop will handle the end of the operation)
if tok.Type == tokRightParenthesis {
return p.popContext()
}
// in all following case we have to end the current operation
if err := p.current.endOperation(); err != nil {
return invalidState, err
}
switch tok.Type {
case tokStarting:
return startingInitial, nil
case tokLimit:
return limitInitial, nil
}
// the end of the expression
if tok.isEnd() {
return end, nil
}
// we continue to chain
if tok.isLogicalOperator() {
// set this operator and jump to a new operation
p.current.logicalOperator = tok.Type
return operationInitial, nil
}
return unexpected(tok, tokInvalid)
}
func (p *parser) startingInitial(tok *token) (state, error) {
return p.expect(tokAt, tok, startingAt)
}
func (p *parser) startingAt(tok *token) (state, error) {
if tok.isNumeric() {
c, err := tok.Const()
if err != nil {
return invalidState, err
}
p.query.startingAt = c.AsInt()
return clauseEnd, nil
}
return unexpected(tok, tokInt)
}
func (p *parser) limit(tok *token) (state, error) {
if tok.isNumeric() {
c, err := tok.Const()
if err != nil {
return invalidState, err
}
p.query.setLimit(c.AsInt())
return limitSep, nil
}
return unexpected(tok, tokInt)
}
func (p *parser) limitSep(tok *token) (state, error) {
if tok.Type == tokComma {
return limitMax, nil
}
return p.clauseEnd(tok)
}
func (p *parser) limitMax(tok *token) (state, error) {
if tok.isNumeric() {
c, err := tok.Const()
if err != nil {
return invalidState, err
}
p.query.startingAt = p.query.Limit()
p.query.setLimit(c.AsInt())
return limitSep, nil
}
return unexpected(tok, tokInt)
}
func (p *parser) expect(expected tokenType, tok *token, state state) (state, error) {
if tok.Type != expected {
return unexpected(tok, expected)
}
return state, nil
}
// Push the context and create a new one
func (p *parser) pushContext(state state) {
// stack the context
p.current.stackState = state
p.stack = append(p.stack, p.current)
// creates a new one and reset it
p.current = newContext()
}
// End the current operation, and continue to the correct state (given on push)
func (p *parser) popContext() (state, error) {
// first we end the operation
if err := p.current.endOperation(); err != nil {
return invalidState, err
}
// creates a group operand
g, err := newGroupOperand(p.current.first.simplify())
if err != nil {
return invalidState, err
}
// pop
l := len(p.stack)
p.current = p.stack[l-1]
p.stack = p.stack[:l-1]
// according the stack state, put the group it on the correct side
switch p.current.stackState {
case leftOperand:
p.current.left = g
case rightOperand:
p.current.right = g
}
// clear the current stackState
s := p.current.stackState
p.current.stackState = -1
// return the next state
return s, nil
}
// Creates a new and fresh context
func newContext() *context {
return &context{
operator: tokInvalid,
logicalOperator: tokInvalid,
stackState: invalidState,
}
}
// End the current operation
// wrap the current operation into a simple LogicalOperation, and chain it
func (c *context) endOperation() error {
if c.left == nil {
return errors.New("Empty operation")
}
// Creates the operand
var op operand
var err error
if c.rangeTest != nil {
op = c.rangeTest
}
if c.operator != tokInvalid {
op, err = newComparison(c.left, operatorTypeFromTokenType(c.operator), c.right)
if err != nil {
return err
}
} else {
op = c.left
}
// reset the operation
c.left = nil
c.right = nil
c.operator = tokInvalid
// Creates a simple logical operation and chain it
lo, err := newLeftLogicalOperation(op)
if err != nil {
return err
}
if c.logicalOperator == tokInvalid {
if c.first != nil || c.last != nil {
return errors.New("Unexpected state, the logical operations should be not initialized")
}
c.first = lo
c.last = lo
return nil
}
if c.first == nil || c.last == nil {
return errors.New("Unexpected state, no logical operation initialized")
}
// define how to chain according the logical operator
switch c.logicalOperator {
case tokAnd:
c.last.chain(operatorTypeFromTokenType(c.logicalOperator), lo)
c.last = lo
case tokOr:
c.first, err = newLeftLogicalOperation(c.first)
if err != nil {
return err
}
c.first.chain(operatorTypeFromTokenType(c.logicalOperator), lo)
c.last = lo
}
// reset the logical operator
c.logicalOperator = tokInvalid
return nil
}
// Helper to creates the unexpected error
func unexpected(tok *token, expected tokenType) (state, error) {
if expected != tokInvalid {
if tok.isEnd() {
return invalidState, fmt.Errorf(
"Expected '%s' at position %d, got end of stream",
expected, tok.Pos)
}
return invalidState, fmt.Errorf(
"Expected '%s' at position %d, got '%s'",
expected, tok.Pos, tok.Value)
}
if tok.isEnd() {
return invalidState, fmt.Errorf(
"Unexpected end of stream at pos %d", tok.Pos)
}
return invalidState, fmt.Errorf(
"Unexpected '%s' at pos %d", tok.Value, tok.Pos)
}