-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathexpr.go
518 lines (458 loc) · 13.6 KB
/
expr.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
package parser
import (
"bytes"
"fmt"
"strconv"
"strings"
"time"
"github.com/genjidb/genji/document"
"github.com/genjidb/genji/sql/query/expr"
"github.com/genjidb/genji/sql/scanner"
)
type dummyOperator struct {
leftHand, rightHand expr.Expr
}
func (d *dummyOperator) Token() scanner.Token { panic("not implemented") }
func (d *dummyOperator) Equal(expr.Expr) bool { panic("not implemented") }
func (d *dummyOperator) Eval(expr.EvalStack) (document.Value, error) { panic("not implemented") }
func (d *dummyOperator) Precedence() int { panic("not implemented") }
func (d *dummyOperator) LeftHand() expr.Expr { panic("not implemented") }
func (d *dummyOperator) RightHand() expr.Expr { return d.rightHand }
func (d *dummyOperator) SetLeftHandExpr(e expr.Expr) { panic("not implemented") }
func (d *dummyOperator) SetRightHandExpr(e expr.Expr) { d.rightHand = e }
// ParseExpr parses an expression.
func (p *Parser) ParseExpr() (e expr.Expr, lit string, err error) {
// enable the expression buffer to store the literal representation
// of the parsed expression
if p.buf == nil {
p.buf = new(bytes.Buffer)
defer func() { p.buf = nil }()
}
// Dummy root node.
var root expr.Operator = new(dummyOperator)
// Parse a non-binary expression type to start.
// This variable will always be the root of the expression tree.
e, err = p.parseUnaryExpr()
if err != nil {
return nil, "", err
}
root.SetRightHandExpr(e)
// Loop over operations and unary exprs and build a tree based on precedence.
for {
// If the next token is NOT an operator then return the expression.
op, tok, err := p.parseOperator()
if err != nil {
return nil, "", err
}
if tok == 0 {
return root.RightHand(), strings.TrimSpace(p.buf.String()), nil
}
var rhs expr.Expr
if rhs, err = p.parseUnaryExpr(); err != nil {
return nil, "", err
}
// Find the right spot in the tree to add the new expression by
// descending the RHS of the expression tree until we reach the last
// BinaryExpr or a BinaryExpr whose RHS has an operator with
// precedence >= the operator being added.
for node := root.(expr.Operator); ; {
p, ok := node.RightHand().(expr.Operator)
if !ok || p.Precedence() >= tok.Precedence() {
// Add the new expression here and break.
node.SetRightHandExpr(op(node.RightHand(), rhs))
break
}
node = p
}
}
}
func (p *Parser) parseOperator() (func(lhs, rhs expr.Expr) expr.Expr, scanner.Token, error) {
op, _, _ := p.ScanIgnoreWhitespace()
if !op.IsOperator() && op != scanner.NOT {
p.Unscan()
return nil, 0, nil
}
switch op {
case scanner.EQ:
return expr.Eq, op, nil
case scanner.NEQ:
return expr.Neq, op, nil
case scanner.GT:
return expr.Gt, op, nil
case scanner.GTE:
return expr.Gte, op, nil
case scanner.LT:
return expr.Lt, op, nil
case scanner.LTE:
return expr.Lte, op, nil
case scanner.AND:
return expr.And, op, nil
case scanner.OR:
return expr.Or, op, nil
case scanner.ADD:
return expr.Add, op, nil
case scanner.SUB:
return expr.Sub, op, nil
case scanner.MUL:
return expr.Mul, op, nil
case scanner.DIV:
return expr.Div, op, nil
case scanner.MOD:
return expr.Mod, op, nil
case scanner.BITWISEAND:
return expr.BitwiseAnd, op, nil
case scanner.BITWISEOR:
return expr.BitwiseOr, op, nil
case scanner.BITWISEXOR:
return expr.BitwiseXor, op, nil
case scanner.IN:
return expr.In, op, nil
case scanner.IS:
if tok, _, _ := p.ScanIgnoreWhitespace(); tok == scanner.NOT {
return expr.IsNot, op, nil
}
p.Unscan()
return expr.Is, op, nil
case scanner.NOT:
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != scanner.IN {
return nil, 0, newParseError(scanner.Tokstr(tok, lit), []string{"IN"}, pos)
}
return expr.NotIn, op, nil
}
panic(fmt.Sprintf("unknown operator %q", op))
}
// parseUnaryExpr parses an non-binary expression.
func (p *Parser) parseUnaryExpr() (expr.Expr, error) {
tok, pos, lit := p.ScanIgnoreWhitespace()
switch tok {
case scanner.CAST:
p.Unscan()
return p.parseCastExpression()
case scanner.IDENT:
// if the next token is a left parenthesis, this is a function
if tok1, _, _ := p.Scan(); tok1 == scanner.LPAREN {
p.Unscan()
p.Unscan()
return p.parseFunction()
}
p.Unscan()
p.Unscan()
field, err := p.parseFieldRef()
if err != nil {
return nil, err
}
fs := expr.FieldSelector(field)
return fs, nil
case scanner.NAMEDPARAM:
if len(lit) == 1 {
return nil, &ParseError{Message: "missing param name"}
}
if p.orderedParams > 0 {
return nil, &ParseError{Message: "cannot mix positional arguments with named arguments"}
}
p.namedParams++
return expr.NamedParam(lit[1:]), nil
case scanner.POSITIONALPARAM:
if p.namedParams > 0 {
return nil, &ParseError{Message: "cannot mix positional arguments with named arguments"}
}
p.orderedParams++
return expr.PositionalParam(p.orderedParams), nil
case scanner.STRING:
return expr.TextValue(lit), nil
case scanner.NUMBER:
v, err := strconv.ParseFloat(lit, 64)
if err != nil {
return nil, &ParseError{Message: "unable to parse number", Pos: pos}
}
return expr.DoubleValue(v), nil
case scanner.INTEGER:
v, err := strconv.ParseInt(lit, 10, 64)
if err != nil {
// The literal may be too large to fit into an int64, parse as Float64
if v, err := strconv.ParseFloat(lit, 64); err == nil {
return expr.DoubleValue(v), nil
}
return nil, &ParseError{Message: "unable to parse integer", Pos: pos}
}
return expr.IntegerValue(v), nil
case scanner.TRUE, scanner.FALSE:
return expr.BoolValue(tok == scanner.TRUE), nil
case scanner.NULL:
return expr.NullValue(), nil
case scanner.DURATION:
d, err := time.ParseDuration(lit)
if err != nil {
return nil, &ParseError{Message: "unable to parse duration", Pos: pos}
}
return expr.DurationValue(d), nil
case scanner.LBRACKET:
p.Unscan()
e, err := p.parseDocument()
return e, err
case scanner.LSBRACKET:
p.Unscan()
return p.parseExprList(scanner.LSBRACKET, scanner.RSBRACKET)
case scanner.LPAREN:
p.Unscan()
return p.parseExprList(scanner.LPAREN, scanner.RPAREN)
default:
return nil, newParseError(scanner.Tokstr(tok, lit), []string{"identifier", "string", "number", "bool"}, pos)
}
}
// parseIdent parses an identifier.
func (p *Parser) parseIdent() (string, error) {
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok != scanner.IDENT {
return "", newParseError(scanner.Tokstr(tok, lit), []string{"identifier"}, pos)
}
return lit, nil
}
// parseIdentList parses a comma delimited list of identifiers.
func (p *Parser) parseIdentList() ([]string, error) {
// Parse first (required) identifier.
ident, err := p.parseIdent()
if err != nil {
return nil, err
}
idents := []string{ident}
// Parse remaining (optional) identifiers.
for {
if tok, _, _ := p.ScanIgnoreWhitespace(); tok != scanner.COMMA {
p.Unscan()
return idents, nil
}
if ident, err = p.parseIdent(); err != nil {
return nil, err
}
idents = append(idents, ident)
}
}
// parseParam parses a positional or named param.
func (p *Parser) parseParam() (expr.Expr, error) {
tok, _, lit := p.ScanIgnoreWhitespace()
switch tok {
case scanner.NAMEDPARAM:
if len(lit) == 1 {
return nil, &ParseError{Message: "missing param name"}
}
if p.orderedParams > 0 {
return nil, &ParseError{Message: "cannot mix positional arguments with named arguments"}
}
p.namedParams++
return expr.NamedParam(lit[1:]), nil
case scanner.POSITIONALPARAM:
if p.namedParams > 0 {
return nil, &ParseError{Message: "cannot mix positional arguments with named arguments"}
}
p.orderedParams++
return expr.PositionalParam(p.orderedParams), nil
default:
return nil, nil
}
}
func (p *Parser) parseType() document.ValueType {
tok, _, _ := p.ScanIgnoreWhitespace()
switch tok {
case scanner.TYPEARRAY:
return document.ArrayValue
case scanner.TYPEBLOB:
return document.BlobValue
case scanner.TYPEBOOL:
return document.BoolValue
case scanner.TYPEBYTES:
return document.BlobValue
case scanner.TYPEDOCUMENT:
return document.DocumentValue
case scanner.TYPEDURATION:
return document.DurationValue
case scanner.TYPEDOUBLE:
return document.DoubleValue
case scanner.TYPEINTEGER:
return document.IntegerValue
case scanner.TYPETEXT:
return document.TextValue
}
p.Unscan()
return 0
}
// parseDocument parses a document
func (p *Parser) parseDocument() (expr.Expr, error) {
// Parse { token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != scanner.LBRACKET {
return nil, newParseError(scanner.Tokstr(tok, lit), []string{"{"}, pos)
}
var pairs expr.KVPairs
var pair expr.KVPair
var err error
// Parse kv pairs.
for {
if pair, err = p.parseKV(); err != nil {
p.Unscan()
break
}
pairs = append(pairs, pair)
if tok, _, _ := p.ScanIgnoreWhitespace(); tok != scanner.COMMA {
p.Unscan()
break
}
}
// Parse required } token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != scanner.RBRACKET {
return nil, newParseError(scanner.Tokstr(tok, lit), []string{"}"}, pos)
}
return pairs, nil
}
// parseKV parses a key-value pair in the form IDENT : Expr.
func (p *Parser) parseKV() (expr.KVPair, error) {
var k string
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok == scanner.IDENT || tok == scanner.STRING {
k = lit
} else {
return expr.KVPair{}, newParseError(scanner.Tokstr(tok, lit), []string{"ident", "string"}, pos)
}
tok, pos, lit = p.ScanIgnoreWhitespace()
if tok != scanner.COLON {
p.Unscan()
return expr.KVPair{}, newParseError(scanner.Tokstr(tok, lit), []string{":"}, pos)
}
e, _, err := p.ParseExpr()
if err != nil {
return expr.KVPair{}, err
}
return expr.KVPair{
K: k,
V: e,
}, nil
}
// parseFieldRef parses a field reference in the form ident (.ident|integer)*
func (p *Parser) parseFieldRef() ([]string, error) {
var fieldRef []string
// parse first mandatory ident
chunk, err := p.parseIdent()
if err != nil {
return nil, err
}
fieldRef = append(fieldRef, chunk)
LOOP:
for {
// scan the very next token.
// if can be either a '.' or a number starting with '.'
// because the scanner is unable to detect a dot when
// it's followed by digits.
// Otherwise, unscan and return the fieldRef
tok, _, lit := p.Scan()
switch tok {
case scanner.DOT:
// scan the next token for an ident
tok, pos, lit := p.Scan()
if tok != scanner.IDENT {
return nil, newParseError(lit, []string{"array index", "identifier"}, pos)
}
fieldRef = append(fieldRef, lit)
case scanner.NUMBER:
// if it starts with a dot, it's considered as an array index
if lit[0] != '.' {
p.Unscan()
return fieldRef, nil
}
lit = lit[1:]
fieldRef = append(fieldRef, lit)
default:
p.Unscan()
break LOOP
}
}
return fieldRef, nil
}
func (p *Parser) parseExprList(leftToken, rightToken scanner.Token) (expr.LiteralExprList, error) {
// Parse ( or [ token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != leftToken {
return nil, newParseError(scanner.Tokstr(tok, lit), []string{leftToken.String()}, pos)
}
var exprList expr.LiteralExprList
var expr expr.Expr
var err error
// Parse expressions.
for {
if expr, _, err = p.ParseExpr(); err != nil {
p.Unscan()
break
}
exprList = append(exprList, expr)
if tok, _, _ := p.ScanIgnoreWhitespace(); tok != scanner.COMMA {
p.Unscan()
break
}
}
// Parse required ) or ] token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != rightToken {
return nil, newParseError(scanner.Tokstr(tok, lit), []string{rightToken.String()}, pos)
}
return exprList, nil
}
// parseFunction parses a function call.
// a function is an identifier followed by a parenthesis,
// an optional coma-separated list of expressions and a closing parenthesis.
func (p *Parser) parseFunction() (expr.Expr, error) {
// Parse function name.
fname, err := p.parseIdent()
if err != nil {
return nil, err
}
// Parse required ( token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != scanner.LPAREN {
return nil, newParseError(scanner.Tokstr(tok, lit), []string{"("}, pos)
}
// Check if the function is called without arguments.
if tok, _, _ := p.ScanIgnoreWhitespace(); tok == scanner.RPAREN {
return expr.GetFunc(fname)
}
p.Unscan()
var exprs []expr.Expr
// Parse expressions.
for {
e, _, err := p.ParseExpr()
if err != nil {
return nil, err
}
exprs = append(exprs, e)
if tok, _, _ := p.ScanIgnoreWhitespace(); tok != scanner.COMMA {
p.Unscan()
return expr.GetFunc(fname, exprs...)
}
}
}
// parseCastExpression parses a string of the form CAST(expr AS type).
func (p *Parser) parseCastExpression() (expr.Expr, error) {
// Parse required CAST token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != scanner.CAST {
return nil, newParseError(scanner.Tokstr(tok, lit), []string{"CAST"}, pos)
}
// Parse required ( token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != scanner.LPAREN {
return nil, newParseError(scanner.Tokstr(tok, lit), []string{"("}, pos)
}
// parse required expression.
e, _, err := p.ParseExpr()
if err != nil {
return nil, err
}
// Parse required AS token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != scanner.AS {
return nil, newParseError(scanner.Tokstr(tok, lit), []string{"AS"}, pos)
}
// Parse require typename.
tp := p.parseType()
if tp == 0 {
tok, pos, lit := p.ScanIgnoreWhitespace()
p.Unscan()
return nil, newParseError(scanner.Tokstr(tok, lit), []string{"type"}, pos)
}
// Parse required ) token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != scanner.RPAREN {
return nil, newParseError(scanner.Tokstr(tok, lit), []string{")"}, pos)
}
return expr.Cast{Expr: e, ConvertTo: tp}, nil
}