forked from cockroachdb/cockroach
/
normalize.go
443 lines (401 loc) · 10.6 KB
/
normalize.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
// Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Peter Mattis (peter@cockroachlabs.com)
package parser
import (
"fmt"
"math"
)
type normalizableExpr interface {
Expr
normalize(*normalizeVisitor) Expr
}
func (expr *AndExpr) normalize(v *normalizeVisitor) Expr {
// Use short-circuit evaluation to simplify AND expressions.
if v.isConst(expr.Left) {
expr.Left, v.err = expr.Left.Eval(v.ctx)
if v.err != nil {
return expr
}
if expr.Left != DNull {
if d, err := GetBool(expr.Left.(Datum)); err != nil {
return DNull
} else if !d {
return expr.Left
}
return expr.Right
}
return expr
}
if v.isConst(expr.Right) {
expr.Right, v.err = expr.Right.Eval(v.ctx)
if v.err != nil {
return expr
}
if expr.Right != DNull {
if d, err := GetBool(expr.Right.(Datum)); err != nil {
return DNull
} else if d {
return expr.Left
}
return expr.Right
}
return expr
}
return expr
}
func (expr *ComparisonExpr) normalize(v *normalizeVisitor) Expr {
switch expr.Operator {
case EQ, GE, GT, LE, LT:
// We want var nodes (VariableExpr, QualifiedName, etc) to be immediate
// children of the comparison expression and not second or third
// children. That is, we want trees that look like:
//
// cmp cmp
// / \ / \
// a op op a
// / \ / \
// 1 2 1 2
//
// Not trees that look like:
//
// cmp cmp cmp cmp
// / \ / \ / \ / \
// op 2 op 2 1 op 1 op
// / \ / \ / \ / \
// a 1 1 a a 2 2 a
//
// We loop attempting to simplify the comparison expression. As a
// pre-condition, we know there is at least one variable in the expression
// tree or we would not have entered this code path.
for {
if v.isConst(expr.Left) {
switch expr.Right.(type) {
case *BinaryExpr, VariableExpr, *QualifiedName, ValArg:
break
default:
return expr
}
// The left side is const and the right side is a binary expression or a
// variable. Flip the comparison op so that the right side is const and
// the left side is a binary expression or variable.
// Create a new ComparisonExpr so the function cache isn't reused.
*expr = ComparisonExpr{
Operator: invertComparisonOp(expr.Operator),
Left: expr.Right,
Right: expr.Left,
}
} else if !v.isConst(expr.Right) {
return expr
}
left, ok := expr.Left.(*BinaryExpr)
if !ok {
return expr
}
// The right is const and the left side is a binary expression. Rotate the
// comparison combining portions that are const.
switch {
case v.isConst(left.Right):
// cmp cmp
// / \ / \
// [+-/] 2 -> a [-+*]
// / \ / \
// a 1 2 1
rotating := true
switch left.Operator {
case Plus:
left.Operator = Minus
case Minus:
left.Operator = Plus
case Div:
left.Operator = Mult
default:
rotating = false
}
if rotating {
// Clear the function caches since we're rotating.
expr.fn.fn = nil
left.fn.fn = nil
expr.Left = left.Left
left.Left = expr.Right
expr.Right, v.err = left.Eval(v.ctx)
if v.err != nil {
return nil
}
if !isVar(expr.Left) {
// Continue as long as the left side of the comparison is not a
// variable.
continue
}
}
case v.isConst(left.Left):
// cmp cmp
// / \ / \
// [+-] 2 -> [+-] a
// / \ / \
// 1 a 1 2
switch left.Operator {
case Plus, Minus:
// Clear the function caches; we're about to change stuff.
expr.fn.fn = nil
left.fn.fn = nil
left.Right, expr.Right = expr.Right, left.Right
if left.Operator == Plus {
left.Operator = Minus
left.Left, left.Right = left.Right, left.Left
} else {
expr.Operator = invertComparisonOp(expr.Operator)
}
expr.Left, v.err = left.Eval(v.ctx)
if v.err != nil {
return nil
}
expr.Left, expr.Right = expr.Right, expr.Left
if !isVar(expr.Left) {
// Continue as long as the left side of the comparison is not a
// variable.
continue
}
}
}
// We've run out of work to do.
break
}
case In, NotIn:
// If the right tuple in an In or NotIn comparison expression is constant, it can
// be normalized.
tuple, ok := expr.Right.(DTuple)
if ok {
tuple.Normalize()
expr.Right = tuple
}
}
return expr
}
func (expr *OrExpr) normalize(v *normalizeVisitor) Expr {
// Use short-circuit evaluation to simplify OR expressions.
if v.isConst(expr.Left) {
expr.Left, v.err = expr.Left.Eval(v.ctx)
if v.err != nil {
return expr
}
if expr.Left != DNull {
if d, err := GetBool(expr.Left.(Datum)); err != nil {
return DNull
} else if d {
return expr.Left
}
return expr.Right
}
}
if v.isConst(expr.Right) {
expr.Right, v.err = expr.Right.Eval(v.ctx)
if v.err != nil {
return expr
}
if expr.Right != DNull {
if d, err := GetBool(expr.Right.(Datum)); err != nil {
return DNull
} else if d {
return expr.Right
}
return expr.Left
}
}
return expr
}
func (expr *ParenExpr) normalize(v *normalizeVisitor) Expr {
return expr.Expr
}
func (expr *RangeCond) normalize(v *normalizeVisitor) Expr {
if expr.Not {
// "a NOT BETWEEN b AND c" -> "a < b OR a > c"
return &OrExpr{
Left: &ComparisonExpr{
Operator: LT,
Left: expr.Left,
Right: expr.From,
},
Right: &ComparisonExpr{
Operator: GT,
Left: expr.Left,
Right: expr.To,
},
}
}
// "a BETWEEN b AND c" -> "a >= b AND a <= c"
return &AndExpr{
Left: &ComparisonExpr{
Operator: GE,
Left: expr.Left,
Right: expr.From,
},
Right: &ComparisonExpr{
Operator: LE,
Left: expr.Left,
Right: expr.To,
},
}
}
func (expr *UnaryExpr) normalize(v *normalizeVisitor) Expr {
// Ugliness: when we see a UnaryMinus, check to see if the expression
// being negated is math.MinInt64. This IntVal is only possible if we
// parsed "9223372036854775808" as a signed int and is the only negative
// IntVal that can be output from the scanner.
//
// TODO(pmattis): Seems like this should happen in Eval, yet if we
// put it there we blow up during normalization when we try to
// Eval("9223372036854775808") a few lines down from here before
// doing Eval("- 9223372036854775808"). Perhaps we can move
// expression evaluation during normalization to the downward
// traversal. Or do it during the downward traversal for const
// UnaryExprs.
if expr.Operator == UnaryMinus {
if d, ok := expr.Expr.(*IntVal); ok && d.Val == math.MinInt64 {
return DInt(math.MinInt64)
}
}
return expr
}
func (expr Row) normalize(v *normalizeVisitor) Expr {
return Tuple(expr)
}
// NormalizeExpr normalizes an expression, simplifying where possible, but
// guaranteeing that the result of evaluating the expression is
// unchanged. Example normalizations:
//
// (a) -> a
// ROW(a, b, c) -> (a, b, c)
// a = 1 + 1 -> a = 2
// a + 1 = 2 -> a = 1
// a BETWEEN b AND c -> (a >= b) AND (a <= c)
// a NOT BETWEEN b AND c -> (a < b) OR (a > c)
func (ctx EvalContext) NormalizeExpr(expr Expr) (Expr, error) {
v := normalizeVisitor{ctx: ctx}
expr = WalkExpr(&v, expr)
return expr, v.err
}
type normalizeVisitor struct {
ctx EvalContext
err error
isConstVisitor isConstVisitor
}
var _ Visitor = &normalizeVisitor{}
func (v *normalizeVisitor) Visit(expr Expr, pre bool) (Visitor, Expr) {
if v.err != nil {
return nil, expr
}
// Normalize expressions that know how to normalize themselves.
if normalizeable, ok := expr.(normalizableExpr); ok {
expr = normalizeable.normalize(v)
if v.err != nil {
return nil, expr
}
}
if pre {
switch expr.(type) {
case *CaseExpr, *IfExpr, *NullIfExpr, *CoalesceExpr:
// Conditional expressions need to be evaluated during the downward
// traversal in order to avoid evaluating sub-expressions which should
// not be evaluated due to the case/conditional.
if v.isConst(expr) {
expr, v.err = expr.Eval(v.ctx)
if v.err != nil {
return nil, expr
}
}
}
} else {
// Evaluate all constant expressions.
if v.isConst(expr) {
expr, v.err = expr.Eval(v.ctx)
if v.err != nil {
return nil, expr
}
}
}
return v, expr
}
func (v *normalizeVisitor) isConst(expr Expr) bool {
return v.isConstVisitor.run(expr)
}
func invertComparisonOp(op ComparisonOp) ComparisonOp {
switch op {
case EQ:
return EQ
case GE:
return LE
case GT:
return LT
case LE:
return GE
case LT:
return GT
default:
panic(fmt.Sprintf("unable to invert: %s", op))
}
}
type isConstVisitor struct {
isConst bool
}
var _ Visitor = &isConstVisitor{}
func (v *isConstVisitor) Visit(expr Expr, pre bool) (Visitor, Expr) {
if pre && v.isConst {
if isVar(expr) {
v.isConst = false
return nil, expr
}
switch t := expr.(type) {
case *Subquery:
v.isConst = false
return nil, expr
case *FuncExpr:
// typeCheckFuncExpr populates t.fn.impure.
if _, err := t.TypeCheck(nil); err != nil || t.fn.impure {
v.isConst = false
return nil, expr
}
}
}
return v, expr
}
func (v *isConstVisitor) run(expr Expr) bool {
v.isConst = true
_ = WalkExpr(v, expr)
return v.isConst
}
func isVar(expr Expr) bool {
_, ok := expr.(VariableExpr)
return ok
}
type containsVarsVisitor struct {
containsVars bool
}
var _ Visitor = &containsVarsVisitor{}
func (v *containsVarsVisitor) Visit(expr Expr, pre bool) (Visitor, Expr) {
if pre && !v.containsVars {
if isVar(expr) {
v.containsVars = true
return nil, expr
}
}
return v, expr
}
// ContainsVars returns true if the expression contains any variables.
func ContainsVars(expr Expr) bool {
v := containsVarsVisitor{containsVars: false}
_ = WalkExpr(&v, expr)
return v.containsVars
}