-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgparser.go
More file actions
110 lines (103 loc) · 2.58 KB
/
Copy pathgparser.go
File metadata and controls
110 lines (103 loc) · 2.58 KB
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
package goparser
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"strconv"
)
// Match 利用原生parser完成表达式与输入数据匹配任务
func Match(expr string, data map[string]interface{}) (bool, error) {
// 空表达式默认匹配成功
if expr == "" {
return true, nil
}
// 空数据默认匹配失败
if data == nil {
return false, nil
}
// 解析表达式
parseExpr, err := parser.ParseExpr(expr)
if err != nil {
return false, err
}
// 表达式中的 true、false 值被识别为变量
data["true"] = true
data["false"] = false
// 匹配表达式与输入数据
result := Eval(parseExpr, data)
// 返回匹配结果
if _, ok := result.(error); ok {
return false, result.(error)
}
return result.(bool), nil
}
func Eval(expr ast.Expr, data map[string]interface{}) interface{} {
switch expr := expr.(type) {
case *ast.BasicLit: // 匹配到数据
return getlitValue(expr)
case *ast.BinaryExpr: // 匹配到子树
x := Eval(expr.X, data)
y := Eval(expr.Y, data)
if x == nil || y == nil {
return fmt.Errorf("%+v, %+v is nil", x, y)
}
op := expr.Op
// 规则计算(按照规则表达式中变量的类型进行匹配)
switch y.(type) {
case int:
return calculateForInt(x, y, op)
case int64:
return calculateForInt64(x, y, op)
case string:
return calculateForString(x, y, op)
case bool:
return calculateForBool(x, y, op)
case error:
return fmt.Errorf("%+v %+v %+v eval failed", x, op, y)
default:
return fmt.Errorf("%+v op is not support", op)
}
case *ast.CallExpr: // 匹配到函数
return calculateForFunc(expr.Fun.(*ast.Ident).Name, expr.Args, data)
case *ast.ParenExpr: // 匹配到括号
return Eval(expr.X, data)
case *ast.UnaryExpr: // 匹配到一元表达式
x := Eval(expr.X, data)
if x == nil {
return fmt.Errorf("%+v is nil", x)
}
op := expr.Op
switch op {
case token.NOT:
switch x.(type) {
case bool:
xb := x.(bool)
return !xb
}
}
return fmt.Errorf("%x type is not support", expr)
case *ast.Ident: // 匹配到变量
return data[expr.Name]
default:
return fmt.Errorf("%x type is not support", expr)
}
}
// 获取AST中变量的数据(表达式中的数字为int,转为int64)
func getlitValue(basicLit *ast.BasicLit) interface{} {
switch basicLit.Kind {
case token.INT:
value, err := strconv.ParseInt(basicLit.Value, 10, 64)
if err != nil {
return err
}
return value
case token.STRING:
value, err := strconv.Unquote(basicLit.Value)
if err != nil {
return err
}
return value
}
return fmt.Errorf("%s is not support type", basicLit.Kind)
}