-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
243 lines (211 loc) · 5.95 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
package filter
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/alecthomas/participle"
"github.com/alecthomas/participle/lexer"
"github.com/alecthomas/participle/lexer/ebnf"
)
// bits stolen from: https://github.com/alecthomas/participle/blob/v0.1.0/_examples/sql/main.go
type Boolean bool
func (b *Boolean) Capture(values []string) error {
*b = strings.ToUpper(values[0]) == "TRUE"
return nil
}
type CompareOperator string
type CompositeOperator string
var (
Eq = CompareOperator("=")
Neq = CompareOperator("!=")
Gt = CompareOperator(">")
Gte = CompareOperator(">=")
Lt = CompareOperator("<")
Lte = CompareOperator("<=")
OR = CompositeOperator("OR")
AND = CompositeOperator("AND")
)
var validOperators = []string{
string(Eq), string(Neq), string(Gt), string(Gte), string(Lt), string(Lte),
}
func (op *CompareOperator) Capture(values []string) error {
ops := values[0]
if ops == "==" {
ops = "="
}
if len(values) > 1 {
panic(fmt.Sprintf("vals: '%q'", strings.Join(values, ", ")))
}
for _, valid := range validOperators {
if ops == valid {
*op = CompareOperator(ops)
return nil
}
}
return fmt.Errorf("invalid operator: '%s', (expected: %s )", *op, strings.Join(validOperators, " | "))
}
func (op *CompareOperator) MatchCompareResult(cmp int) bool {
switch *op {
case Eq:
return cmp == 0
case Neq:
return cmp != 0
case Gt:
return cmp < 0
case Gte:
return cmp <= 0
case Lt:
return cmp > 0
case Lte:
return cmp >= 0
default:
panic("Invalid compare operator")
}
}
type Expression struct {
And []AndCondition `@@ { ("OR" | "|") @@ }`
}
type AndCondition struct {
Or []Condition `@@ { [("AND" | "+" )] @@ }`
}
type Condition struct {
Not *Condition ` "NOT" @@`
SubExpression *Expression `| "(" @@ ")"`
Operand *ConditionOperand `| @@`
}
type ConditionOperand struct {
FieldPath string `@FieldPath`
ConditionRHS ConditionRHS `@@ `
}
type ConditionRHS struct {
Compare *Compare ` @@`
Is *Is `| "IS" @@`
In Array `| "IN" ("(" @@ { "," @@ } ")" | "[" @@ { "," @@ } "]")`
NotIn Array `| "NOT" "IN" ("(" @@ { "," @@ } ")" | "[" @@ { "," @@ } "]")`
Contains *Contains `| ("CONTAINS" | "HAS") @@`
Like *string `| "LIKE" @String`
}
func (crhs ConditionRHS) JSONValue() ([]byte, error) {
var value interface{}
if crhs.Compare != nil {
value = crhs.Compare.Value
} else if crhs.In != nil {
value = crhs.In
} else if crhs.NotIn != nil {
value = crhs.NotIn
} else if crhs.Like != nil {
value = *crhs.Like
} else if crhs.Contains != nil {
if crhs.Contains.All != nil {
value = crhs.Contains.All
} else if crhs.Contains.Any != nil {
value = crhs.Contains.Any
} else if crhs.Contains.Value != nil {
value = crhs.Contains.Value
}
}
return json.Marshal(value)
}
type Compare struct {
Operator CompareOperator `@CompareOperator`
Value Value `@@`
}
type Contains struct {
Any Array ` "ANY" ("(" @@ { "," @@ } ")" | "[" @@ { "," @@ } "]")`
All Array `| "ALL" ("(" @@ { "," @@ } ")" | "[" @@ { "," @@ } "]")`
Value *Value `| ["VALUE"] @@`
}
func (c *Contains) GetArray() Array {
if c.Any != nil {
return c.Any
} else if c.All != nil {
return c.All
} else {
panic(fmt.Errorf("conditon %v has no array", c))
}
}
type Is struct {
Not bool `[ @"NOT" ]`
Null bool `( @"NULL"`
NaN bool ` | @"NAN" )`
}
type Array []Value
type Value struct {
Null bool `( @"NULL"`
Boolean *Boolean ` | @("TRUE" | "FALSE")`
Number *string ` | @Number`
String *string ` | @String`
Map *Map ` | @@ )`
}
type Map struct {
Entries []*MapEntry `"{" ( @@ ( ( "," )? @@ )* )? "}"`
}
type MapEntry struct {
Key *Value `@@`
Value *Value `":"? @@`
}
func (v Value) MarshalJSON() ([]byte, error) {
if v.Null {
return json.Marshal(nil)
} else if v.Boolean != nil {
return json.Marshal(v.Boolean)
} else if v.Number != nil {
return []byte(*v.Number), nil
} else if v.String != nil {
return json.Marshal(v.String)
} else if v.Map != nil {
jsonEntries := make([]string, 0, len(v.Map.Entries))
for _, entry := range v.Map.Entries {
jsonKey, err := entry.Key.MarshalJSON()
if err != nil {
return nil, errors.New("error marshaling map key: " + err.Error())
}
jsonValue, err := entry.Value.MarshalJSON()
if err != nil {
return nil, errors.New("error marshaling map value: " + err.Error())
}
jsonEntries = append(jsonEntries, fmt.Sprintf("%s:%s", string(jsonKey), string(jsonValue)))
}
value := fmt.Sprintf("{%s}", strings.Join(jsonEntries, ","))
return []byte(value), nil
} else {
return nil, errors.New("primitive value contains none of Null, Boolean, Number nor String")
}
}
var (
filterLexer = lexer.Must(ebnf.New(`
Comment = "--" { "\u0000"…"\uffff"-"\n" } .
FieldPath = Ident { dot Ident } .
Ident = (alpha | "_") { "_" | "-" | "/" | alpha | digit } { "_" | "/" | alpha | digit } .
String = "\"" { "\u0000"…"\uffff"-"\""-"\\" | "\\" any } "\"" .
CompareOperator = opchar { opchar } .
Number = [ "-" | "+" ] ("." | digit) {"." | digit} [("E" | "e") [ "-" | "+" ] digit { digit }] .
Punct = "!"…"/" | ":"…"@" | "["…` + "\"`\"" + ` | "{"…"~" .
Whitespace = " " | "\t" | "\n" | "\r" .
alpha = "a"…"z" | "A"…"Z" .
digit = "0"…"9" .
opchar = ("<" | ">" | "=" | "!") .
dot = ("\\." | ".") .
any = "\u0000"…"\uffff" .
`))
filterParser = participle.MustBuild(
&Expression{},
participle.Lexer(filterLexer),
participle.Unquote("String"),
participle.Elide("Whitespace", "Comment"),
participle.Map(func(token lexer.Token) (lexer.Token, error) {
token.Value = strings.Replace(token.Value, `\.`, ".", -1)
return token, nil
}, "FieldPath"),
participle.CaseInsensitive("Ident", "FieldPath"),
)
)
func Parse(data []byte) (*Expression, error) {
filter := &Expression{}
if err := filterParser.Parse(bytes.NewReader(data), filter); err != nil {
return nil, fmt.Errorf("error when parsing filter expression: \"%q\": %s", string(data), err)
}
return filter, nil
}