-
Notifications
You must be signed in to change notification settings - Fork 20
/
parser.go
211 lines (172 loc) · 5.09 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
package contactql
import (
"fmt"
"reflect"
"strings"
"time"
"github.com/nyaruka/goflow/contactql/gen"
"github.com/nyaruka/goflow/utils"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
type boolOp string
const (
boolOpAnd boolOp = "and"
boolOpOr boolOp = "or"
)
// QueryNode is the base for nodes in our query parse tree
type QueryNode interface {
fmt.Stringer
Evaluate(utils.Environment, Queryable) (bool, error)
}
// Condition represents a comparison between a keywed value on the contact and a provided value
type Condition struct {
key string
comparator string
value string
}
// Evaluate evaluates this condition against the queryable contact
func (c *Condition) Evaluate(env utils.Environment, queryable Queryable) (bool, error) {
if c.key == ImplicitKey {
return false, errors.Errorf("dynamic group queries can't contain implicit conditions")
}
// contacts can return multiple values per key, e.g. multiple phone numbers in a "tel = x" condition
vals := queryable.ResolveQueryKey(env, c.key)
// is this an existence check?
if c.value == "" {
if c.comparator == "=" {
return len(vals) == 0, nil // x = "" is true if x doesn't exist
} else if c.comparator == "!=" {
return len(vals) > 0, nil // x != "" is false if x doesn't exist (i.e. true if x does exist)
}
}
// if keyed value doesn't exist on our contact then all other comparisons at this point are false
if len(vals) == 0 {
return false, nil
}
// check each resolved value
for _, val := range vals {
res, err := c.evaluateValue(env, val)
if err != nil {
return false, err
}
if res {
return true, nil
}
}
return false, nil
}
func (c *Condition) evaluateValue(env utils.Environment, val interface{}) (bool, error) {
switch val.(type) {
case string:
return textComparison(val.(string), c.comparator, c.value)
case decimal.Decimal:
asDecimal, err := decimal.NewFromString(c.value)
if err != nil {
return false, errors.Errorf("can't convert '%s' to a number", c.value)
}
return numberComparison(val.(decimal.Decimal), c.comparator, asDecimal)
case time.Time:
asDate, err := utils.DateTimeFromString(env, c.value, false)
if err != nil {
return false, err
}
return dateComparison(val.(time.Time), c.comparator, asDate)
default:
return false, errors.Errorf("unsupported query data type: %+v", reflect.TypeOf(val))
}
}
func (c *Condition) String() string {
var value string
if c.value == "" {
value = `""`
} else {
value = c.value
}
return fmt.Sprintf("%s%s%s", c.key, c.comparator, value)
}
// BoolCombination is a AND or OR combination of multiple conditions
type BoolCombination struct {
op boolOp
children []QueryNode
}
// NewBoolCombination creates a new boolean combination
func NewBoolCombination(op boolOp, children ...QueryNode) *BoolCombination {
return &BoolCombination{op: op, children: children}
}
// Evaluate returns whether this combination evaluates to true or false
func (b *BoolCombination) Evaluate(env utils.Environment, queryable Queryable) (bool, error) {
var childRes bool
var err error
if b.op == boolOpAnd {
for _, child := range b.children {
if childRes, err = child.Evaluate(env, queryable); err != nil {
return false, err
}
if !childRes {
return false, nil
}
}
return true, nil
}
for _, child := range b.children {
if childRes, err = child.Evaluate(env, queryable); err != nil {
return false, err
}
if childRes {
return true, nil
}
}
return false, nil
}
func (b *BoolCombination) String() string {
children := make([]string, len(b.children))
for c := range b.children {
children[c] = b.children[c].String()
}
return fmt.Sprintf("%s(%s)", strings.ToUpper(string(b.op)), strings.Join(children, ", "))
}
type ContactQuery struct {
root QueryNode
}
func (q *ContactQuery) Evaluate(env utils.Environment, queryable Queryable) (bool, error) {
return q.root.Evaluate(env, queryable)
}
func (q *ContactQuery) String() string {
return q.root.String()
}
// ParseQuery parses a ContactQL query from the given input
func ParseQuery(text string) (*ContactQuery, error) {
errListener := NewErrorListener()
input := antlr.NewInputStream(text)
lexer := gen.NewContactQLLexer(input)
stream := antlr.NewCommonTokenStream(lexer, 0)
p := gen.NewContactQLParser(stream)
p.RemoveErrorListeners()
p.AddErrorListener(errListener)
tree := p.Parse()
// if we ran into errors parsing, bail
if errListener.HasErrors() {
return nil, errListener.Error()
}
visitor := NewVisitor()
rootNode := visitor.Visit(tree).(QueryNode)
return &ContactQuery{root: rootNode}, nil
}
type errorListener struct {
*antlr.DefaultErrorListener
messages []string
}
func NewErrorListener() *errorListener {
return &errorListener{}
}
func (l *errorListener) HasErrors() bool {
return len(l.messages) > 0
}
func (l *errorListener) Error() error {
return errors.Errorf(strings.Join(l.messages, "\n"))
}
func (l *errorListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line, column int, msg string, e antlr.RecognitionException) {
l.messages = append(l.messages, msg)
}