-
Notifications
You must be signed in to change notification settings - Fork 10
/
atom.go
91 lines (82 loc) · 2.16 KB
/
atom.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
package goP2
import "reflect"
// One 仅仅简单的返回下一个迭代结果,或者得到 eof 错误
func One(state State) (interface{}, error) {
return state.Next()
}
// Eq 判断下一个数据是否与给定值相等,这里简单的使用了反射
func Eq(val interface{}) P {
return func(state State) (interface{}, error) {
x, err := state.Next()
if err != nil {
return nil, err
}
if reflect.DeepEqual(x, val) {
return x, nil
}
return nil, state.Trap("Expact %v but %v", val, x)
}
}
// Ne 判断下一个数据是否与给定值不相等,这里简单的使用了反射
func Ne(val interface{}) P {
return func(state State) (interface{}, error) {
x, err := state.Next()
if err != nil {
return nil, err
}
if reflect.DeepEqual(x, val) {
return nil, state.Trap("Expact not %v but %v", val, x)
}
return x, nil
}
}
// Return 生成的算子总是返回给定值
func Return(val interface{}) P {
return func(state State) (interface{}, error) {
return val, nil
}
}
// Fail 生成的算子总是返回给定错误
func Fail(message string, args ...interface{}) P {
return func(state State) (interface{}, error) {
return nil, state.Trap(message, args...)
}
}
// EOF 仅仅到达结尾时匹配成功
func EOF(state State) (interface{}, error) {
data, err := state.Next()
if err == nil {
return nil, state.Trap("Expect eof but %v", data)
}
return nil, nil
}
// OneOf 期待下一个元素属于给定的参数中的一个
func OneOf(args ...interface{}) P {
return func(state State) (interface{}, error) {
data, err := state.Next()
if err != nil {
return nil, err
}
for element := range args {
if reflect.DeepEqual(data, element) {
return data, nil
}
}
return nil, state.Trap("Expect one of [%v] but %v", args, data)
}
}
// NoneOf 期待下一个元素不属于给定的参数中的任一个
func NoneOf(args ...interface{}) P {
return func(state State) (interface{}, error) {
data, err := state.Next()
if err != nil {
return nil, err
}
for element := range args {
if reflect.DeepEqual(data, element) {
return nil, state.Trap("Expect none of [%v] but %v", args, data)
}
}
return data, nil
}
}