-
Notifications
You must be signed in to change notification settings - Fork 142
/
spec_func.go
344 lines (322 loc) · 8.02 KB
/
spec_func.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
// Copyright 2019 Bytedance Inc. All Rights Reserved.
//
// 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.
package tagexpr
import (
"context"
"fmt"
"reflect"
"regexp"
"strings"
"github.com/andeya/goutil/errors"
)
// --------------------------- Custom function ---------------------------
var funcList = map[string]func(p *Expr, expr *string) ExprNode{}
// MustRegFunc registers function expression.
// NOTE:
//
// example: len($), regexp("\\d") or regexp("\\d",$);
// If @force=true, allow to cover the existed same @funcName;
// The go number types always are float64;
// The go string types always are string;
// Panic if there is an error.
func MustRegFunc(funcName string, fn func(...interface{}) interface{}, force ...bool) {
err := RegFunc(funcName, fn, force...)
if err != nil {
panic(err)
}
}
// RegFunc registers function expression.
// NOTE:
//
// example: len($), regexp("\\d") or regexp("\\d",$);
// If @force=true, allow to cover the existed same @funcName;
// The go number types always are float64;
// The go string types always are string.
func RegFunc(funcName string, fn func(...interface{}) interface{}, force ...bool) error {
if len(force) == 0 || !force[0] {
_, ok := funcList[funcName]
if ok {
return errors.Errorf("duplicate registration expression function: %s", funcName)
}
}
funcList[funcName] = newFunc(funcName, fn)
return nil
}
func (p *Expr) parseFuncSign(funcName string, expr *string) (boolOpposite *bool, signOpposite *bool, args []ExprNode, found bool) {
prefix := funcName + "("
length := len(funcName)
last, boolOpposite, signOpposite := getBoolAndSignOpposite(expr)
if !strings.HasPrefix(last, prefix) {
return
}
*expr = last[length:]
lastStr := *expr
subExprNode := readPairedSymbol(expr, '(', ')')
if subExprNode == nil {
return
}
*subExprNode = "," + *subExprNode
for {
if strings.HasPrefix(*subExprNode, ",") {
*subExprNode = (*subExprNode)[1:]
operand := newGroupExprNode()
err := p.parseExprNode(trimLeftSpace(subExprNode), operand)
if err != nil {
*expr = lastStr
return
}
sortPriority(operand)
args = append(args, operand)
} else {
*expr = lastStr
return
}
trimLeftSpace(subExprNode)
if len(*subExprNode) == 0 {
found = true
return
}
}
}
func newFunc(funcName string, fn func(...interface{}) interface{}) func(*Expr, *string) ExprNode {
return func(p *Expr, expr *string) ExprNode {
boolOpposite, signOpposite, args, found := p.parseFuncSign(funcName, expr)
if !found {
return nil
}
return &funcExprNode{
fn: fn,
boolOpposite: boolOpposite,
signOpposite: signOpposite,
args: args,
}
}
}
type funcExprNode struct {
exprBackground
args []ExprNode
fn func(...interface{}) interface{}
boolOpposite *bool
signOpposite *bool
}
func (f *funcExprNode) String() string {
return "func()"
}
func (f *funcExprNode) Run(ctx context.Context, currField string, tagExpr *TagExpr) interface{} {
var args []interface{}
if n := len(f.args); n > 0 {
args = make([]interface{}, n)
for k, v := range f.args {
args[k] = v.Run(ctx, currField, tagExpr)
}
}
return realValue(f.fn(args...), f.boolOpposite, f.signOpposite)
}
// --------------------------- Built-in function ---------------------------
func init() {
funcList["regexp"] = readRegexpFuncExprNode
funcList["sprintf"] = readSprintfFuncExprNode
funcList["range"] = readRangeFuncExprNode
// len: Built-in function len, the length of struct field X
MustRegFunc("len", func(args ...interface{}) (n interface{}) {
if len(args) != 1 {
return 0
}
v := args[0]
switch e := v.(type) {
case string:
return float64(len(e))
case float64, bool, nil:
return 0
}
defer func() {
if recover() != nil {
n = 0
}
}()
return float64(reflect.ValueOf(v).Len())
}, true)
// mblen: get the length of string field X (character number)
MustRegFunc("mblen", func(args ...interface{}) (n interface{}) {
if len(args) != 1 {
return 0
}
v := args[0]
switch e := v.(type) {
case string:
return float64(len([]rune(e)))
case float64, bool, nil:
return 0
}
defer func() {
if recover() != nil {
n = 0
}
}()
return float64(reflect.ValueOf(v).Len())
}, true)
// in: Check if the first parameter is one of the enumerated parameters
MustRegFunc("in", func(args ...interface{}) interface{} {
switch len(args) {
case 0:
return true
case 1:
return false
default:
elem := args[0]
set := args[1:]
for _, e := range set {
if elem == e {
return true
}
}
return false
}
}, true)
}
type regexpFuncExprNode struct {
exprBackground
re *regexp.Regexp
boolOpposite bool
}
func (re *regexpFuncExprNode) String() string {
return "regexp()"
}
func readRegexpFuncExprNode(p *Expr, expr *string) ExprNode {
last, boolOpposite, _ := getBoolAndSignOpposite(expr)
if !strings.HasPrefix(last, "regexp(") {
return nil
}
*expr = last[6:]
lastStr := *expr
subExprNode := readPairedSymbol(expr, '(', ')')
if subExprNode == nil {
return nil
}
s := readPairedSymbol(trimLeftSpace(subExprNode), '\'', '\'')
if s == nil {
*expr = lastStr
return nil
}
rege, err := regexp.Compile(*s)
if err != nil {
*expr = lastStr
return nil
}
operand := newGroupExprNode()
trimLeftSpace(subExprNode)
if strings.HasPrefix(*subExprNode, ",") {
*subExprNode = (*subExprNode)[1:]
err = p.parseExprNode(trimLeftSpace(subExprNode), operand)
if err != nil {
*expr = lastStr
return nil
}
} else {
var currFieldVal = "$"
p.parseExprNode(&currFieldVal, operand)
}
trimLeftSpace(subExprNode)
if *subExprNode != "" {
*expr = lastStr
return nil
}
e := ®expFuncExprNode{
re: rege,
}
if boolOpposite != nil {
e.boolOpposite = *boolOpposite
}
e.SetRightOperand(operand)
return e
}
func (re *regexpFuncExprNode) Run(ctx context.Context, currField string, tagExpr *TagExpr) interface{} {
param := re.rightOperand.Run(ctx, currField, tagExpr)
switch v := param.(type) {
case string:
bol := re.re.MatchString(v)
if re.boolOpposite {
return !bol
}
return bol
case float64, bool:
return false
}
v := reflect.ValueOf(param)
if v.Kind() == reflect.String {
bol := re.re.MatchString(v.String())
if re.boolOpposite {
return !bol
}
return bol
}
return false
}
type sprintfFuncExprNode struct {
exprBackground
format string
args []ExprNode
}
func (se *sprintfFuncExprNode) String() string {
return "sprintf()"
}
func readSprintfFuncExprNode(p *Expr, expr *string) ExprNode {
if !strings.HasPrefix(*expr, "sprintf(") {
return nil
}
*expr = (*expr)[7:]
lastStr := *expr
subExprNode := readPairedSymbol(expr, '(', ')')
if subExprNode == nil {
return nil
}
format := readPairedSymbol(trimLeftSpace(subExprNode), '\'', '\'')
if format == nil {
*expr = lastStr
return nil
}
e := &sprintfFuncExprNode{
format: *format,
}
for {
trimLeftSpace(subExprNode)
if len(*subExprNode) == 0 {
return e
}
if strings.HasPrefix(*subExprNode, ",") {
*subExprNode = (*subExprNode)[1:]
operand := newGroupExprNode()
err := p.parseExprNode(trimLeftSpace(subExprNode), operand)
if err != nil {
*expr = lastStr
return nil
}
sortPriority(operand)
e.args = append(e.args, operand)
} else {
*expr = lastStr
return nil
}
}
}
func (se *sprintfFuncExprNode) Run(ctx context.Context, currField string, tagExpr *TagExpr) interface{} {
var args []interface{}
if n := len(se.args); n > 0 {
args = make([]interface{}, n)
for i, e := range se.args {
args[i] = e.Run(ctx, currField, tagExpr)
}
}
return fmt.Sprintf(se.format, args...)
}