-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunccreator.go
653 lines (606 loc) · 16.7 KB
/
funccreator.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
package eudore
import (
"context"
"fmt"
"reflect"
"sort"
"strings"
"sync"
)
const (
FuncCreateInvalid FuncCreateKind = iota
FuncCreateString
FuncCreateInt
FuncCreateUint
FuncCreateFloat
FuncCreateBool
FuncCreateAny
FuncCreateSetString
FuncCreateSetInt
FuncCreateSetUint
FuncCreateSetFloat
FuncCreateSetBool
FuncCreateSetAny
FuncCreateNumber = FuncCreateAny
)
// FuncCreateKind 定义FuncCreator可以创建的函数类型。
type FuncCreateKind uint8
// FuncCreator 定义校验函数构造器,默认由RouterStd、validate、filter使用。
type FuncCreator interface {
RegisterFunc(string, ...any) error
CreateFunc(FuncCreateKind, string) (any, error)
List() []string
}
type funcTypeParams interface {
string | int | uint | float64 | bool | any
}
type funcCreatorBase struct {
String typeCreator[func(string) bool]
Int typeCreator[func(int) bool]
Uint typeCreator[func(uint) bool]
Float typeCreator[func(float64) bool]
Bool typeCreator[func(bool) bool]
Any typeCreator[func(any) bool]
SetString typeCreator[func(string) string]
SetInt typeCreator[func(int) int]
SetUint typeCreator[func(uint) uint]
SetFloat typeCreator[func(float64) float64]
SetAny typeCreator[func(any) any]
Errors map[string]string
}
type MetadataFuncCreator struct {
Health bool `alias:"health" json:"health" xml:"health" yaml:"health"`
Name string `alias:"name" json:"name" xml:"name" yaml:"name"`
Funcs []string `alias:"funcs" json:"funcs" xml:"funcs" yaml:"funcs"`
Exprs []string `alias:"exprs,omitempty" json:"exprs,omitempty" xml:"exprs,omitempty" yaml:"exprs,omitempty"`
Errors []string `alias:"errors,omitempty" json:"errors,omitempty" xml:"errors,omitempty" yaml:"errors,omitempty"`
}
// FuncRunner 定义创建函数类型和地址信息。
type FuncRunner struct {
Kind FuncCreateKind
Func any
}
// NewFuncCreator 函数创建默认FuncCreator并加载默认规则。
func NewFuncCreator() FuncCreator {
fc := &funcCreatorBase{
String: newTypeCreator[func(string) bool](),
Int: newTypeCreator[func(int) bool](),
Uint: newTypeCreator[func(uint) bool](),
Float: newTypeCreator[func(float64) bool](),
Bool: newTypeCreator[func(bool) bool](),
Any: newTypeCreator[func(any) bool](),
SetString: newTypeCreator[func(string) string](),
SetInt: newTypeCreator[func(int) int](),
SetUint: newTypeCreator[func(uint) uint](),
SetFloat: newTypeCreator[func(float64) float64](),
SetAny: newTypeCreator[func(any) any](),
Errors: make(map[string]string),
}
loadDefaultFuncDefine(fc)
return fc
}
// NewFuncCreatorExpr 函数创建一个支持AND OR NOT关系表达式解析的FuncCreator。
func NewFuncCreatorExpr() FuncCreator {
return &funcCreatorExpr{
data: NewFuncCreator().(*funcCreatorBase),
parser: newFcExprParser(),
}
}
// NewFuncCreatorWithContext 函数从环境上下文创建FuncCreator。
func NewFuncCreatorWithContext(ctx context.Context) FuncCreator {
fc, ok := ctx.Value(ContextKeyFuncCreator).(FuncCreator)
if ok {
return fc
}
return DefaultFuncCreator
}
// RegisterFunc 函数给一个名称注册多个类型的的ValidateFunc或ValidateNewFunc。
//
//nolint:cyclop,gocyclo
func (fc *funcCreatorBase) RegisterFunc(name string, funcs ...any) error {
for i := range funcs {
switch fn := funcs[i].(type) {
case func(string) bool:
fc.String.Register(name, fn)
case func(int) bool:
fc.Int.Register(name, fn)
case func(uint) bool:
fc.Uint.Register(name, fn)
case func(float64) bool:
fc.Float.Register(name, fn)
case func(bool) bool:
fc.Bool.Register(name, fn)
case func(any) bool:
fc.Any.Register(name, fn)
case func(string) (func(string) bool, error):
fc.String.RegisterNew(name, fn)
case func(string) (func(uint) bool, error):
fc.Uint.RegisterNew(name, fn)
case func(string) (func(int) bool, error):
fc.Int.RegisterNew(name, fn)
case func(string) (func(float64) bool, error):
fc.Float.RegisterNew(name, fn)
case func(string) (func(bool) bool, error):
fc.Bool.RegisterNew(name, fn)
case func(string) (func(any) bool, error):
fc.Any.RegisterNew(name, fn)
case func(string) string:
fc.SetString.Register(name, fn)
case func(int) int:
fc.SetInt.Register(name, fn)
case func(uint) uint:
fc.SetUint.Register(name, fn)
case func(float64) float64:
fc.SetFloat.Register(name, fn)
case func(any) any:
fc.SetAny.Register(name, fn)
case func(string) (func(string) string, error):
fc.SetString.RegisterNew(name, fn)
case func(string) (func(uint) uint, error):
fc.SetUint.RegisterNew(name, fn)
case func(string) (func(int) int, error):
fc.SetInt.RegisterNew(name, fn)
case func(string) (func(float64) float64, error):
fc.SetFloat.RegisterNew(name, fn)
case func(string) (func(any) any, error):
fc.SetAny.RegisterNew(name, fn)
default:
return fc.appendError(name, fmt.Errorf(ErrFormatFuncCreatorRegisterInvalidType, name, fn))
}
}
return nil
}
// CreateFunc 方法感觉类型和名称创建校验函数。
//
// 不支持动态创建具有NOT AND OR关系表达式函数,闭包影响性能。
func (fc *funcCreatorBase) CreateFunc(kind FuncCreateKind, name string) (fn any, err error) {
switch kind {
case FuncCreateString:
fn, err = fc.String.Create(name)
case FuncCreateInt:
fn, err = fc.Int.Create(name)
case FuncCreateUint:
fn, err = fc.Uint.Create(name)
case FuncCreateFloat:
fn, err = fc.Float.Create(name)
case FuncCreateBool, FuncCreateSetBool:
fn, err = fc.Bool.Create(name)
case FuncCreateAny:
fn, err = fc.Any.Create(name)
case FuncCreateSetString:
fn, err = fc.SetString.Create(name)
case FuncCreateSetInt:
fn, err = fc.SetInt.Create(name)
case FuncCreateSetUint:
fn, err = fc.SetUint.Create(name)
case FuncCreateSetFloat:
fn, err = fc.SetFloat.Create(name)
case FuncCreateSetAny:
fn, err = fc.SetAny.Create(name)
default:
err = fmt.Errorf("invalid func kind %d", kind)
}
if err != nil {
return nil, fc.appendError(kind.String()+name, fmt.Errorf("funcCreator create kind %s func %s err: %w", kind, name, err))
}
return fn, nil
}
func (fc *funcCreatorBase) appendError(key string, err error) error {
fc.Bool.Lock()
fc.Errors[key] = err.Error()
fc.Bool.Unlock()
return err
}
func (fc *funcCreatorBase) List() []string {
names := make([]string, 0, 128)
names = fc.String.List(names)
names = fc.Int.List(names)
names = fc.Uint.List(names)
names = fc.Float.List(names)
names = fc.Bool.List(names)
names = fc.Any.List(names)
names = fc.SetString.List(names)
names = fc.SetInt.List(names)
names = fc.SetUint.List(names)
names = fc.SetFloat.List(names)
names = fc.SetAny.List(names)
sort.Strings(names)
return names
}
func (fc *funcCreatorBase) Metadata() any {
errs := make([]string, 0, len(fc.Errors))
fc.Bool.RLock()
defer fc.Bool.RUnlock()
for _, v := range fc.Errors {
errs = append(errs, v)
}
return MetadataFuncCreator{
Health: len(errs) == 0,
Name: "eudore.funcCreatorBase",
Funcs: fc.List(),
Errors: errs,
}
}
type typeCreator[T any] struct {
sync.RWMutex
Values map[string]T
Constructor map[string]func(string) (T, error)
}
func newTypeCreator[T any]() typeCreator[T] {
return typeCreator[T]{
Values: make(map[string]T),
Constructor: make(map[string]func(string) (T, error)),
}
}
func (tc *typeCreator[T]) Register(name string, fn T) {
tc.Lock()
tc.Values[name] = fn
tc.Unlock()
}
func (tc *typeCreator[T]) RegisterNew(name string, fn func(string) (T, error)) {
tc.Lock()
tc.Constructor[name] = fn
tc.Unlock()
}
func (tc *typeCreator[T]) Get(fullname string) (T, bool) {
tc.RLock()
fn, ok := tc.Values[fullname]
tc.RUnlock()
return fn, ok
}
func (tc *typeCreator[T]) Create(fullname string) (T, error) {
tc.RLock()
fn, ok := tc.Values[fullname]
tc.RUnlock()
if ok {
return fn, nil
}
name, arg := getFuncNameArg(fullname)
if arg != "" {
tc.RLock()
fnnews, ok := tc.Constructor[name]
tc.RUnlock()
if ok {
fn, err := fnnews(arg)
if err == nil {
tc.Register(fullname, fn)
}
return fn, err
}
}
return fn, ErrFuncCreatorNotFunc
}
func (tc *typeCreator[T]) List(names []string) []string {
tc.RLock()
defer tc.RUnlock()
for key, fn := range tc.Values {
names = append(names, fmt.Sprintf("%s: %T", key, fn))
}
for key, fn := range tc.Constructor {
names = append(names, fmt.Sprintf("%s: %T", key, fn))
}
return names
}
func getFuncNameArg(name string) (string, string) {
for i, b := range name {
// ! [0-9A-Za-z]
if b < 0x30 || (0x39 < b && b < 0x41) || (0x5A < b && b < 0x61) || 0x7A < b {
return name[:i], name[i:]
}
}
return name, ""
}
type funcCreatorExpr struct {
data *funcCreatorBase
parser *fcExprParser
}
func (fc *funcCreatorExpr) RegisterFunc(name string, funcs ...any) error {
return fc.data.RegisterFunc(name, funcs...)
}
func (fc *funcCreatorExpr) CreateFunc(kind FuncCreateKind, name string) (any, error) {
if kind < FuncCreateSetString && (strings.Contains(name, "NOT") ||
strings.Contains(name, "AND") || strings.Contains(name, "OR")) {
var fn any
var err error
switch kind {
case FuncCreateString:
fn, err = createFunc(&fc.data.String, name, fc.parser.parse)
case FuncCreateInt:
fn, err = createFunc(&fc.data.Int, name, fc.parser.parse)
case FuncCreateUint:
fn, err = createFunc(&fc.data.Uint, name, fc.parser.parse)
case FuncCreateFloat:
fn, err = createFunc(&fc.data.Float, name, fc.parser.parse)
case FuncCreateBool, FuncCreateSetBool:
fn, err = createFunc(&fc.data.Bool, name, fc.parser.parse)
case FuncCreateAny:
fn, err = createFunc(&fc.data.Any, name, fc.parser.parse)
}
if err != nil {
return nil, fc.data.appendError(kind.String()+name, err)
}
return fn, nil
}
return fc.data.CreateFunc(kind, name)
}
func createFunc[T funcTypeParams](tc *typeCreator[func(T) bool], name string, parser fcExprFunc) (func(T) bool, error) {
fn, ok := tc.Get(name)
if ok {
return fn, nil
}
expr, s := parser(name)
if s != "" {
return nil, fmt.Errorf("funcCreatorExpr not parse: %s, pos in %d", name, len(name)-len(s))
}
fn, err := createExpr(tc, expr)
if _, isstr := expr.(string); err == nil && !isstr {
tc.Register(name, fn)
}
return fn, err
}
func createExpr[T funcTypeParams](tc *typeCreator[func(T) bool], expr any) (func(T) bool, error) {
switch e := expr.(type) {
case fcExprNot:
fn, err := createExpr(tc, e.Expr)
if err != nil {
return nil, err
}
return func(t T) bool {
return !fn(t)
}, nil
case fcExprAnd:
fns := make([]func(T) bool, len(e.Exprs))
for i := range e.Exprs {
fn, err := createExpr(tc, e.Exprs[i])
if err != nil {
return nil, err
}
fns[i] = fn
}
return func(t T) bool {
for i := range fns {
if !fns[i](t) {
return false
}
}
return true
}, nil
case fcExprOr:
fns := make([]func(T) bool, len(e.Exprs))
for i := range e.Exprs {
fn, err := createExpr(tc, e.Exprs[i])
if err != nil {
return nil, err
}
fns[i] = fn
}
return func(t T) bool {
for i := range fns {
if fns[i](t) {
return true
}
}
return false
}, nil
default:
return tc.Create(expr.(string))
}
}
func (fc *funcCreatorExpr) List() []string {
return fc.data.List()
}
func (fc *funcCreatorExpr) Metadata() any {
meta := fc.data.Metadata().(MetadataFuncCreator)
meta.Name = "eudore.funcCreatorExpr"
var funcs, exprs []string
for _, f := range meta.Funcs {
if strings.Contains(f, "NOT") || strings.Contains(f, "AND") || strings.Contains(f, "OR") {
exprs = append(exprs, f)
} else {
funcs = append(funcs, f)
}
}
meta.Funcs = funcs
meta.Exprs = exprs
return meta
}
type (
fcExprFunc func(string) (any, string)
fcExprParser struct {
Parsers [][]fcExprFunc
Handler []func([]any) any
parse fcExprFunc
}
fcExprNot struct{ Expr any }
fcExprAnd struct{ Exprs []any }
fcExprOr struct{ Exprs []any }
)
func newFcExprParser() *fcExprParser {
p := &fcExprParser{Handler: []func(data []any) any{
func(data []any) any { return fcExprOr{fcExprData(data, false)} },
func(data []any) any { return fcExprAnd{fcExprData(data, true)} },
func(data []any) any { return fcExprNot{data[1]} },
func(data []any) any { return data[1] },
func(data []any) any { return data[0] },
}}
p0, p1, p2 := p.p(0), p.p(1), p.p(2)
p.parse = p0
p.Parsers = [][]fcExprFunc{
{p1, fcExprMatch("OR"), p0},
{p2, fcExprMatch("AND"), p1},
{fcExprMatch("NOT"), p2},
{fcExprMatch("("), p0, fcExprMatch(")")},
{fcExprVal},
}
return p
}
func (p *fcExprParser) p(start int) fcExprFunc {
return func(s string) (any, string) {
for i, fns := range p.Parsers[start:] {
var val any
var vals []any
str := s
for _, fn := range fns {
val, str = fn(strings.TrimSpace(str))
if val == nil {
break
}
vals = append(vals, val)
}
if len(vals) == len(fns) {
return p.Handler[i+start](vals), str
}
}
return nil, s
}
}
func fcExprVal(s string) (any, string) {
l := len(s)
for _, sub := range []string{"NOT", "AND", "OR", ")"} {
pos := strings.Index(s[:l], sub)
if pos != -1 {
l = pos
}
}
s1, s2 := strings.TrimSpace(s[:l]), s[l:]
if s1 == "" {
return nil, s
}
return s1, s2
}
var exprEnd = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1, '(': 1}
func fcExprMatch(str string) fcExprFunc {
return func(s string) (any, string) {
if strings.HasPrefix(s, str) {
if len(str) == 1 || (str != s && exprEnd[s[len(str)]] == 1) {
return "", s[len(str):]
}
}
return nil, s
}
}
func fcExprData(data []any, and bool) []any {
d := make([]any, 0, len(data))
for i := range data {
switch val := data[i].(type) {
case string:
if val == "" {
continue
}
case fcExprAnd:
if and {
d = append(d, val.Exprs...)
continue
}
case fcExprOr:
if !and {
d = append(d, val.Exprs...)
continue
}
}
d = append(d, data[i])
}
return d
}
var defaultFuncCreateKindStrings = [...]string{
"invalid", "string", "int", "uint", "float", "bool", "any",
"setstring", "setint", "setuint", "setfloat", "setbool", "setany",
}
// NewFuncCreateKind 函数解析FuncCreateKind字符串。
func NewFuncCreateKind(s string) FuncCreateKind {
s = strings.ToLower(s)
for i, str := range defaultFuncCreateKindStrings {
if s == str {
return FuncCreateKind(i)
}
}
return FuncCreateInvalid
}
// NewFuncCreateKindWithType 函数类型创建FuncCreateKind。
func NewFuncCreateKindWithType(t reflect.Type) FuncCreateKind {
if t == nil {
return FuncCreateInvalid
}
for {
switch t.Kind() {
case reflect.Ptr:
t = t.Elem()
case reflect.Slice, reflect.Array:
t = t.Elem()
case reflect.String:
return FuncCreateString
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return FuncCreateInt
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return FuncCreateUint
case reflect.Float32, reflect.Float64:
return FuncCreateFloat
case reflect.Bool:
return FuncCreateBool
case reflect.Struct, reflect.Map, reflect.Interface:
return FuncCreateAny
default:
return FuncCreateInvalid
}
}
}
func (kind FuncCreateKind) String() string {
return defaultFuncCreateKindStrings[kind]
}
// RunPtr executes any function, dereferences the Ptr type,
// and executes each value of Slice and Array.
//
// RunPtr 执行任意函数,对Ptr类型会解除引用,对Slice和Array每一个值进行执行。
func (fn *FuncRunner) RunPtr(v reflect.Value) bool {
switch v.Kind() {
case reflect.Ptr:
if v.IsNil() {
return fn.RunPtr(reflect.Zero(v.Type().Elem()))
}
return fn.RunPtr(v.Elem())
case reflect.Slice, reflect.Array:
for i := 0; i < v.Len(); i++ {
if !fn.RunPtr(v.Index(i)) {
return false
}
}
return true
default:
return fn.Run(v)
}
}
// Run 执行任意函数。
func (fn *FuncRunner) Run(v reflect.Value) bool {
switch fn.Kind {
case FuncCreateString:
return fn.Func.(func(string) bool)(v.String())
case FuncCreateInt:
return fn.Func.(func(int) bool)(int(v.Int()))
case FuncCreateUint:
return fn.Func.(func(uint) bool)(uint(v.Uint()))
case FuncCreateFloat:
return fn.Func.(func(float64) bool)(v.Float())
case FuncCreateBool:
return fn.Func.(func(bool) bool)(v.Bool())
case FuncCreateAny:
return fn.Func.(func(any) bool)(v.Interface())
case FuncCreateSetString:
v.SetString(fn.Func.(func(string) string)(v.String()))
case FuncCreateSetInt:
v.SetInt(int64((fn.Func.(func(int) int)(int(v.Int())))))
case FuncCreateSetUint:
v.SetUint(uint64(fn.Func.(func(uint) uint)(uint(v.Uint()))))
case FuncCreateSetFloat:
v.SetFloat(fn.Func.(func(float64) float64)(v.Float()))
case FuncCreateSetBool:
v.SetBool(fn.Func.(func(bool) bool)(v.Bool()))
case FuncCreateSetAny:
val := fn.Func.(func(any) any)(v.Interface())
if val != nil {
v.Set(reflect.ValueOf(val))
} else {
v.Set(reflect.Zero(v.Type()))
}
}
return true
}