forked from araddon/qlbridge
/
node.go
2252 lines (2125 loc) · 53.5 KB
/
node.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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Expression structures, ie the `a = b` type expression syntax
// including parser, node types, boolean logic check, functions.
package expr
import (
"fmt"
"io"
"reflect"
"strconv"
"strings"
"time"
u "github.com/araddon/gou"
"github.com/gogo/protobuf/proto"
"github.com/araddon/qlbridge/lex"
"github.com/araddon/qlbridge/value"
)
var (
// ErrNotSupported indicates an error of a piece of expression syntax not
// being supported.
ErrNotSupported = fmt.Errorf("Not supported")
// ErrNotImplemented an error of expression/statement syntax not being supported
ErrNotImplemented = fmt.Errorf("Not implemented")
// ErrUnknownCommand Unknown Command
ErrUnknownCommand = fmt.Errorf("Unknown Command")
// ErrInternalError Internal Error
ErrInternalError = fmt.Errorf("Internal Error")
// ErrNoIncluder is message saying a FilterQL included reference
// to an include when no Includer was available to resolve
ErrNoIncluder = fmt.Errorf("No Includer is available")
// ErrIncludeNotFound Include Not Found
ErrIncludeNotFound = fmt.Errorf("Include Not Found")
// a static nil includer whose job is to return errors
// for vm's that don't have an includer
noIncluder = &IncludeContext{}
// Ensure our dialect writer implements interface
_ DialectWriter = (*defaultDialect)(nil)
// Ensure some of our nodes implement Interfaces
//_ NegateableNode = (*BinaryNode)(nil)
_ NegateableNode = (*BooleanNode)(nil)
_ NegateableNode = (*TriNode)(nil)
_ NegateableNode = (*IncludeNode)(nil)
// Ensure we implement interface
_ Includer = (*IncludeContext)(nil)
// Ensure some of our nodes implement NodeArgs
_ NodeArgs = (*BooleanNode)(nil)
_ NodeArgs = (*TriNode)(nil)
_ NodeArgs = (*BinaryNode)(nil)
_ NodeArgs = (*FuncNode)(nil)
_ NodeArgs = (*UnaryNode)(nil)
_ NodeArgs = (*ArrayNode)(nil)
)
type (
// Node is a node in an expression tree, implemented
// by different types (binary, urnary, func, identity, etc)
//
// qlbridge does not currently implement statements (if, for, switch, etc)
// just expressions, and operators
Node interface {
// String representation of Node parseable back to itself
String() string
// WriteDialect Given a dialect writer write out, equivalent of String()
// but allows different escape characters
WriteDialect(w DialectWriter)
// Validate Syntax validation of this expression node
Validate() error
// NodePb Convert this node to a Protobuf copy of it
NodePb() *NodePb
// FromPB Convert a protobuf presentation of node to Node.
FromPB(*NodePb) Node
// Expr Convert node into a simple expression syntax
// which can be used for json respresentation
Expr() *Expr
// FromExpr
FromExpr(*Expr) error
// Equal compares deep equality of
Equal(Node) bool
// NodeType the String, Identity, etc
NodeType() string
}
// NodeArgs is an interface for nodes which have child arguments
NodeArgs interface {
ChildrenArgs() []Node
}
// NegateableNode A negateable node requires a special type of String() function due to
// an enclosing urnary NOT being inserted into middle of string syntax
//
// <expression> [NOT] IN ("a","b")
// <expression> [NOT] BETWEEN <expression> AND <expression>
// <expression> [NOT] LIKE <expression>
// <expression> [NOT] CONTAINS <expression>
// <expression> [NOT] INTERSECTS ("a", "b")
//
NegateableNode interface {
// Node the negateable nodes also implement the entire Node
Node
// Negated Say if this node is negateable (it may not be), If the node
// is negateable, we may collapse an surrounding negation into here
Negated() bool
// ReverseNegation if Possible: for instance:
// "A" NOT IN ("a","b") => "A" IN ("a","b")
ReverseNegation() bool
// StringNegate
StringNegate() string
// WriteNegate write out this node into a writer
WriteNegate(w DialectWriter)
// Collapse Negateable nodes may be collapsed logically into new nodes
// return this node collapsed down to simpliest form
Collapse() Node
}
// EvalContext used to contain info for usage/lookup at runtime evaluation
EvalContext interface {
ContextReader
}
// EvalIncludeContext context, used to contain info for usage/lookup at runtime evaluation
EvalIncludeContext interface {
ContextReader
Includer
}
// ContextReader is a key-value interface to read the context of message/row
// using a Get("key") interface. Used by vm to evaluate messages
ContextReader interface {
Get(key string) (value.Value, bool)
Row() map[string]value.Value
Ts() time.Time
}
// ContextWriter For evaluation storage
// vm writes results to this after evaluation
ContextWriter interface {
Put(col SchemaInfo, readCtx ContextReader, v value.Value) error
Delete(row map[string]value.Value) error
}
// ContextReadWriter represents a Context which can be Read & Written.
ContextReadWriter interface {
ContextReader
ContextWriter
}
// RowWriter for committing row ops (insert, update)
RowWriter interface {
// Commit the given rowInfo to persist
Commit(rowInfo []SchemaInfo, row RowWriter) error
// Put (persist) given Column info write single column.
Put(col SchemaInfo, readCtx ContextReader, v value.Value) error
}
)
type (
// Expr represents single part of an Expression, it is a generic AST structure
// that can be built in tree structure and JSON serialized to represent full AST
// as json.
Expr struct {
// The `Op` (aka token), and Args expressions are non
// nil if it is an expression
Op string `json:"op,omitempty"`
Args []*Expr `json:"args,omitempty"`
// If op is 0, and args nil then exactly one of these should be set
Identity string `json:"ident,omitempty"`
Value string `json:"val,omitempty"`
// Really would like to use these instead of un-typed guesses above
// if we desire serialization into string representation that is fine
// Int int64
// Float float64
// Bool bool
}
// Func Describes a function expression which wraps and allows native go functions
// to be called in expression vm
Func struct {
Name string // name of func, lower-cased
Aggregate bool // is this aggregate func?
CustomFunc // CustomFunc Is dynamic function that can be registered
Eval EvaluatorFunc // The memoized evaluation function
}
// FuncNode holds a Func, which desribes a go Function as
// well as fulfilling the Pos, String() etc for a Node
FuncNode struct {
Name string // Name of func
F Func // The actual function that this AST maps to
Eval EvaluatorFunc // the evaluator function
Missing bool
Args []Node // Arguments are them-selves nodes
}
// IdentityNode will look up a value out of a env bag also identities of
// sql objects (tables, columns, etc) we often need to rewrite these as in
// sql it is `table.column`
IdentityNode struct {
Quote byte
Text string
original string
escaped string
left string
right string
}
// IdentityNodes is a list of identities
IdentityNodes []*IdentityNode
// StringNode holds a value literal, quotes not included
StringNode struct {
Quote byte
Text string
noQuote bool
needsEscape bool // Does Text contain Quote value?
}
// NullNode is a simple NULL type node
NullNode struct{}
// NumberNode holds a number: signed or unsigned integer or float.
// The value is parsed and stored under all the types that can represent the value.
// This simulates in a small amount of code the behavior of Go's ideal constants.
NumberNode struct {
IsInt bool // Number has an integer value.
IsFloat bool // Number has a floating-point value.
Int64 int64 // The integer value.
Float64 float64 // The floating-point value.
Text string // The original textual representation from the input.
}
// ValueNode holds a value.Value type
// value.Values can be strings, numbers, arrays, objects, etc
ValueNode struct {
Value value.Value
rv reflect.Value
}
// BinaryNode is x op y, two nodes (left, right) and an operator
// operators can be a variety of:
// +, -, *, %, /, LIKE, CONTAINS, INTERSECTS
// Also, parenthesis may wrap these
BinaryNode struct {
negated bool
Paren bool
Args []Node
Operator lex.Token
}
// BooleanNode is n nodes and an operator
// operators can be only AND/OR
BooleanNode struct {
negated bool
Args []Node
Operator lex.Token
}
// TriNode 3 part expression such as
// ARG1 Between ARG2 AND ARG3
TriNode struct {
negated bool
Args []Node
Operator lex.Token
}
// UnaryNode negates a single node argument
//
// ( not <expression> | !<expression> )
//
// !eq(5,6)
// !true
// !(true OR false)
// !toint(now())
UnaryNode struct {
Arg Node
Operator lex.Token
}
// IncludeNode references a named node
//
// ( ! INCLUDE <identity> | INCLUDE <identity> | NOT INCLUDE <identity> )
//
IncludeNode struct {
negated bool
inlineExpr Node // a non-pointer copy of the referred to include, itself resolved
ExprNode Node // The expression of the referred to include
Identity *IdentityNode
Operator lex.Token
}
// ArrayNode for holding multiple similar elements
// arg0 IN (arg1,arg2.....)
// 5 in (1,2,3,4)
ArrayNode struct {
wraptype string // ( or [
Args []Node
}
)
// Includer defines an interface used for resolving INCLUDE clauses into a
// Indclude reference. Implementations should return an error if the name cannot
// be resolved.
type Includer interface {
Include(name string) (Node, error)
}
// IncludeContext A ContextReader that implements Include interface.
type IncludeContext struct {
ContextReader
}
// NewIncludeContext a new IncludeContext from contextreader.
func NewIncludeContext(cr ContextReader) *IncludeContext {
return &IncludeContext{ContextReader: cr}
}
// Include interface not implemented.
func (*IncludeContext) Include(name string) (Node, error) { return nil, ErrNoIncluder }
// FindFirstIdentity Recursively descend down a node looking for first Identity Field
//
// min(year) == year
// eq(min(item), max(month)) == item
// eq(min(user.last_name), max(month)) == user.last_name
//
func FindFirstIdentity(node Node) string {
l := findIdentities(node, nil).Strings()
if len(l) == 0 {
return ""
}
return l[0]
}
// FindAllIdentityField Recursively descend down a node looking for all Identity Fields
//
// min(year) == {year}
// eq(min(user.name), max(month)) == {user.name, month}
//
func FindAllIdentityField(node Node) []string {
return findIdentities(node, nil).Strings()
}
// FindAllLeftIdentityFields Recursively descend down a node looking for all
// LEFT Identity Fields
//
// min(year) == {year}
// eq(min(user.name), max(month)) == {user, month}
//
func FindAllLeftIdentityFields(node Node) []string {
return findIdentities(node, nil).LeftStrings()
}
// FindAllIdentities gets all identity
func FindAllIdentities(node Node) IdentityNodes {
in := make(IdentityNodes, 0)
return findIdentities(node, in)
}
func findIdentities(node Node, l IdentityNodes) IdentityNodes {
switch n := node.(type) {
case *IdentityNode:
l = append(l, n)
case *BinaryNode:
for _, arg := range n.Args {
l = findIdentities(arg, l)
}
case *BooleanNode:
for _, arg := range n.Args {
l = findIdentities(arg, l)
}
case *UnaryNode:
l = findIdentities(n.Arg, l)
case *TriNode:
for _, arg := range n.Args {
l = findIdentities(arg, l)
}
case *ArrayNode:
for _, arg := range n.Args {
l = findIdentities(arg, l)
}
case *FuncNode:
for _, arg := range n.Args {
l = findIdentities(arg, l)
}
}
return l
}
// FilterSpecialIdentities given a list of identities, filter out
// special identities such as "null", "*", "match_all"
func FilterSpecialIdentities(l []string) []string {
s := make([]string, 0, len(l))
for _, val := range l {
switch strings.ToLower(val) {
case "*", "match_all", "null", "true", "false":
// skip
default:
s = append(s, val)
}
}
return s
}
// Strings get all identity strings
func (m IdentityNodes) Strings() []string {
s := make([]string, len(m))
for i, in := range m {
s[i] = in.Text
}
return s
}
// LeftStrings get all Left Identity fields.
func (m IdentityNodes) LeftStrings() []string {
s := make([]string, len(m))
for i, in := range m {
l, r, hasLr := in.LeftRight()
if hasLr {
s[i] = l
} else {
s[i] = r
}
}
return s
}
// FindIdentityName Recursively walk a node looking for first Identity Field
// and combine with outermost expression to create an alias
//
// min(year) => "min_year"
// eq(min(year), max(month)) => "eq_year
// EXISTS url => "exists_url"
func FindIdentityName(depth int, node Node, prefix string) string {
switch n := node.(type) {
case *IdentityNode:
if prefix == "" {
return n.Text
}
return fmt.Sprintf("%s_%s", prefix, n.Text)
case *BinaryNode:
for _, arg := range n.Args {
return FindIdentityName(depth+1, arg, prefix)
}
case *FuncNode:
if depth > 10 {
return ""
}
for _, arg := range n.Args {
if prefix == "" {
prefix = strings.ToLower(n.F.Name)
switch prefix {
case "count":
prefix = "ct"
case "valuect", "mapct":
prefix = "cts"
case "todate", "toint", "tostring", "tofloat":
prefix = ""
default:
// use the name of function
}
}
return FindIdentityName(depth+1, arg, prefix)
}
}
return ""
}
// ValueTypeFromNode Infer Value type from Node
func ValueTypeFromNode(n Node) value.ValueType {
switch nt := n.(type) {
case *FuncNode:
if nt == nil {
return value.UnknownType
}
if nt.F.CustomFunc == nil {
return value.UnknownType
}
return nt.F.Type()
case *StringNode:
return value.StringType
case *IdentityNode:
// Identity types will draw type from context.
return value.UnknownType
case *NumberNode:
return value.NumberType
case *BooleanNode:
return value.BoolType
case *BinaryNode:
switch nt.Operator.T {
case lex.TokenLogicAnd, lex.TokenAnd, lex.TokenLogicOr, lex.TokenOr,
lex.TokenEqual, lex.TokenEqualEqual:
return value.BoolType
case lex.TokenMultiply, lex.TokenMinus, lex.TokenAdd, lex.TokenDivide:
return value.NumberType
case lex.TokenModulus:
return value.IntType
case lex.TokenLT, lex.TokenLE, lex.TokenGT, lex.TokenGE:
return value.BoolType
}
}
return value.UnknownType
}
// NewFuncNode create new Function Expression Node.
func NewFuncNode(name string, f Func) *FuncNode {
return &FuncNode{Name: name, F: f}
}
func (m *FuncNode) append(arg Node) {
m.Args = append(m.Args, arg)
}
func (m *FuncNode) NodeType() string { return "Func" }
func (m *FuncNode) String() string {
w := NewDefaultWriter()
m.WriteDialect(w)
return w.String()
}
func (m *FuncNode) WriteDialect(w DialectWriter) {
io.WriteString(w, m.Name)
io.WriteString(w, "(")
for i, arg := range m.Args {
if i > 0 {
io.WriteString(w, ", ")
}
arg.WriteDialect(w)
}
io.WriteString(w, ")")
}
func (m *FuncNode) Validate() error {
if m.F.CustomFunc != nil {
// Nice new style function
ev, err := m.F.CustomFunc.Validate(m)
if err != nil {
return err
}
m.Eval = ev
return nil
}
if m.Missing {
switch strings.ToLower(m.Name) {
case "distinct":
return nil
}
return nil
}
return nil
}
func (m *FuncNode) ChildrenArgs() []Node {
return m.Args
}
func (m *FuncNode) NodePb() *NodePb {
n := &FuncNodePb{}
n.Name = m.Name
n.Args = make([]NodePb, len(m.Args))
for i, a := range m.Args {
n.Args[i] = *a.NodePb()
}
return &NodePb{Fn: n}
}
func (m *FuncNode) FromPB(n *NodePb) Node {
fn, ok := funcReg.FuncGet(strings.ToLower(n.Fn.Name))
if !ok {
u.Debugf("Not Found Func %q", n.Fn.Name)
// Panic?
}
f := FuncNode{
Name: n.Fn.Name,
Args: NodesFromNodesPb(n.Fn.Args),
F: fn,
}
if err := f.Validate(); err != nil {
u.Warnf("could not validate %v", err)
}
return &f
}
// Expr convert the FuncNode to Expr
func (m *FuncNode) Expr() *Expr {
fe := &Expr{Op: lex.TokenUdfExpr.String()}
if len(m.Args) > 0 {
fe.Args = []*Expr{{Identity: m.Name}}
fe.Args = append(fe.Args, ExprsFromNodes(m.Args)...)
}
return fe
}
func (m *FuncNode) FromExpr(e *Expr) error {
if e.Op != lex.TokenUdfExpr.String() {
return fmt.Errorf("Expected 'expr' but got %v", e.Op)
}
if len(e.Args) < 1 {
return fmt.Errorf("Expected function name in args but got none")
}
m.Name = e.Args[0].Identity
if len(e.Args) > 1 {
args, err := NodesFromExprs(e.Args[1:])
if err != nil {
return err
}
m.Args = args
}
s := m.String()
n, err := ParseExpression(s)
if err != nil {
return fmt.Errorf("Could not round-trip parse func: %s err=%v", s, err)
}
fn, ok := n.(*FuncNode)
if !ok {
return fmt.Errorf("Expected funcnode but got %T", n)
}
m.F = fn.F
if err = fn.Validate(); err != nil {
return err
}
if m.Eval == nil {
m.Eval = fn.Eval
}
return nil
}
func (m *FuncNode) Equal(n Node) bool {
if m == nil && n == nil {
return true
}
if m == nil && n != nil {
return false
}
if m != nil && n == nil {
return false
}
if nt, ok := n.(*FuncNode); ok {
if m.Name != nt.Name {
return false
}
if len(m.Args) != len(nt.Args) {
return false
}
for i, arg := range nt.Args {
if !arg.Equal(m.Args[i]) {
return false
}
}
return true
}
return false
}
// NewNumberStr is a little weird in that this Node accepts string @text
// and uses go to parse into Int, AND Float.
func NewNumberStr(text string) (*NumberNode, error) {
n := &NumberNode{Text: text}
return n, n.load()
}
func NewNumber(fv float64) (*NumberNode, error) {
n := &NumberNode{Float64: fv, IsFloat: true}
iv := int64(fv)
if float64(iv) == fv {
n.IsInt = true
n.Int64 = iv
}
n.Text = strconv.FormatFloat(fv, 'f', 4, 64)
return n, nil
}
func (n *NumberNode) load() error {
// Do integer test first so we get 0x123 etc.
iv, err := strconv.ParseInt(n.Text, 0, 64) // will fail for -0.
if err == nil {
n.IsInt = true
n.Int64 = iv
}
// If an integer extraction succeeded, promote the float.
if n.IsInt {
n.IsFloat = true
n.Float64 = float64(n.Int64)
} else {
f, err := strconv.ParseFloat(n.Text, 64)
if err == nil {
n.IsFloat = true
n.Float64 = f
// If a floating-point extraction succeeded, extract the int if needed.
if !n.IsInt && float64(int64(f)) == f {
n.IsInt = true
n.Int64 = int64(f)
}
}
}
if !n.IsInt && !n.IsFloat {
return fmt.Errorf("illegal number syntax: %q", n.Text)
}
return nil
}
func (m *NumberNode) NodeType() string { return "Number" }
func (n *NumberNode) String() string { return n.Text }
func (m *NumberNode) WriteDialect(w DialectWriter) { w.WriteNumber(m.Text) }
func (m *NumberNode) Validate() error { return nil }
func (m *NumberNode) NodePb() *NodePb {
n := &NumberNodePb{}
n.Text = m.Text
n.Fv = m.Float64
n.Iv = m.Int64
return &NodePb{Nn: n}
}
func (m *NumberNode) FromPB(n *NodePb) Node {
nn := &NumberNode{
Text: n.Nn.Text,
Float64: n.Nn.Fv,
Int64: n.Nn.Iv,
}
nn.load()
return nn
}
func (m *NumberNode) Expr() *Expr {
return &Expr{Value: m.Text}
}
func (m *NumberNode) FromExpr(e *Expr) error {
if len(e.Value) > 0 {
m.Text = e.Value
return m.load()
}
return nil
}
func (m *NumberNode) Equal(n Node) bool {
if m == nil && n == nil {
return true
}
if m == nil && n != nil {
return false
}
if m != nil && n == nil {
return false
}
if nt, ok := n.(*NumberNode); ok {
if m.Text != nt.Text {
return false
}
if m.Float64 != nt.Float64 {
return false
}
if m.Int64 != nt.Int64 {
return false
}
return true
}
return false
}
func NewStringNode(text string) *StringNode {
return &StringNode{Text: text}
}
func NewStringNodeToken(t lex.Token) *StringNode {
return &StringNode{Text: t.V, Quote: t.Quote}
}
func NewStringNoQuoteNode(text string) *StringNode {
return &StringNode{Text: text, noQuote: true}
}
func NewStringNeedsEscape(t lex.Token) *StringNode {
newVal, needsEscape := StringUnEscape('"', t.V)
return &StringNode{Text: newVal, Quote: t.Quote, needsEscape: needsEscape}
}
func (m *StringNode) NodeType() string { return "String" }
func (m *StringNode) String() string {
if m.noQuote {
return m.Text
}
if m.Quote > 0 {
return fmt.Sprintf("%s%s%s", string(m.Quote), StringEscape(rune(m.Quote), m.Text), string(m.Quote))
}
return fmt.Sprintf("%q", m.Text)
}
func (m *StringNode) WriteDialect(w DialectWriter) {
w.WriteLiteral(m.Text)
}
func (m *StringNode) Validate() error { return nil }
func (m *StringNode) NodePb() *NodePb {
n := &StringNodePb{}
n.Text = m.Text
if m.noQuote {
n.Noquote = proto.Bool(true)
}
if m.Quote > 0 {
n.Quote = proto.Int32(int32(m.Quote))
}
return &NodePb{Sn: n}
}
func (m *StringNode) FromPB(n *NodePb) Node {
noQuote := false
quote := 0
if n.Sn.Noquote != nil {
noQuote = *n.Sn.Noquote
}
if n.Sn.Quote != nil {
quote = int(*n.Sn.Quote)
}
return &StringNode{
noQuote: noQuote,
Text: n.Sn.Text,
Quote: byte(quote),
}
}
func (m *StringNode) Expr() *Expr {
return &Expr{Value: m.Text}
}
func (m *StringNode) FromExpr(e *Expr) error {
if len(e.Value) > 0 {
m.Text = e.Value
}
return nil
}
func (m *StringNode) Equal(n Node) bool {
if m == nil && n == nil {
return true
}
if m == nil && n != nil {
return false
}
if m != nil && n == nil {
return false
}
if nt, ok := n.(*StringNode); ok {
if m.Text != nt.Text {
return false
}
return true
}
return false
}
func NewValueNode(val value.Value) *ValueNode {
return &ValueNode{Value: val, rv: reflect.ValueOf(val)}
}
func (m *ValueNode) NodeType() string { return "Value" }
func (m *ValueNode) IsArray() bool {
if m.Value == nil {
return false
}
if _, ok := m.Value.(value.Slice); ok {
return true
}
return false
}
func (m *ValueNode) String() string {
switch vt := m.Value.(type) {
case value.StringsValue:
vals := make([]string, vt.Len())
for i, v := range vt.Val() {
vals[i] = fmt.Sprintf("%q", v)
}
return fmt.Sprintf("[%s]", strings.Join(vals, ", "))
case value.SliceValue:
vals := make([]string, vt.Len())
for i, v := range vt.Val() {
vals[i] = fmt.Sprintf("%q", v.ToString())
}
return fmt.Sprintf("[%s]", strings.Join(vals, ", "))
}
return m.Value.ToString()
}
func (m *ValueNode) WriteDialect(w DialectWriter) {
switch vt := m.Value.(type) {
case value.StringsValue:
io.WriteString(w, "[")
for i, v := range vt.Val() {
if i != 0 {
io.WriteString(w, ", ")
}
w.WriteLiteral(v)
}
io.WriteString(w, "]")
case value.SliceValue:
io.WriteString(w, "[")
for i, v := range vt.Val() {
if i != 0 {
io.WriteString(w, ", ")
}
w.WriteLiteral(v.ToString())
}
io.WriteString(w, "]")
case value.StringValue:
w.WriteLiteral(vt.Val())
case value.IntValue:
w.WriteNumber(vt.ToString())
case value.NumberValue:
w.WriteNumber(vt.ToString())
case value.BoolValue:
w.WriteLiteral(vt.ToString())
default:
u.Warnf("unsupported value-node writer: %T", vt)
io.WriteString(w, vt.ToString())
}
}
func (m *ValueNode) Validate() error { return nil }
func (m *ValueNode) NodePb() *NodePb {
u.Errorf("Not implemented %#v", m)
return nil
}
func (m *ValueNode) FromPB(n *NodePb) Node {
u.Errorf("Not implemented %#v", n)
return &ValueNode{}
}
func (m *ValueNode) Expr() *Expr {
return &Expr{Value: m.Value.ToString()}
}
func (m *ValueNode) FromExpr(e *Expr) error {
if len(e.Value) > 0 {
m.Value = value.NewStringValue(e.Value)
return nil
}
return fmt.Errorf("unrecognized value")
}
func (m *ValueNode) Equal(n Node) bool {
if m == nil && n == nil {
return true
}
if m == nil && n != nil {
return false
}
if m != nil && n == nil {
return false
}
if nt, ok := n.(*ValueNode); ok {
if m.Value.Value() != nt.Value.Value() {
return false
}
return true
}
return false
}
func NewIdentityNode(tok *lex.Token) *IdentityNode {
in := &IdentityNode{Text: tok.V, Quote: tok.Quote}
in.load()
return in
}
func NewIdentityNodeVal(val string) *IdentityNode {
in := &IdentityNode{Text: val}
in.load()
u.Debugf("identity{l=%q r=%q}", in.left, in.right)
return in
}
func (m *IdentityNode) load() {
if m.Quote != 0 {
// This is all deeply flawed, need to go fix it. Upgrade path will
// be sweep through and remove all usage of existing ones that used the flawed
// `left.right value` escape syntax assuming the period is a split
if strings.Contains(m.Text, "`.`") {
// this came in with quote which has been stripped by lexer
m.original = fmt.Sprintf("%s%s%s", string(m.Quote), m.Text, string(m.Quote))
m.left, m.right, _ = LeftRight(m.original)
//u.Debugf("branch1: l:%q r:%q original:%q text:%q", m.left, m.right, m.original, m.Text)
} else if strings.Contains(m.Text, "`.") || strings.Contains(m.Text, ".`") {
m.left, m.right, _ = LeftRight(m.Text)
l, r := IdentityMaybeQuote(m.Quote, m.left), IdentityMaybeQuote(m.Quote, m.right)
m.original = fmt.Sprintf("%s.%s", l, r)
m.left, m.right, _ = LeftRight(m.original)
//u.Debugf("branch2: l:%q r:%q original:%q text:%q", m.left, m.right, m.original, m.Text)
// this came in with quote which has been stripped by lexer
// m.original = fmt.Sprintf("%s%s%s", string(m.Quote), m.Text, string(m.Quote))
// m.left, m.right, _ = LeftRight(m.original)
} else {
// this came in with quote which has been stripped by lexer
m.original = fmt.Sprintf("%s%s%s", string(m.Quote), m.Text, string(m.Quote))
m.left, m.right, _ = LeftRight(m.original)
//u.Debugf("branch3: l:%q r:%q original:%q text:%q", m.left, m.right, m.original, m.Text)
}
} else {
m.left, m.right, _ = LeftRight(m.Text)