-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
85 lines (69 loc) · 1.52 KB
/
node.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
package decide
import (
"fmt"
"github.com/pkg/errors"
exp "github.com/sjhitchner/go-decide/expression"
)
// Generate syntax parser
//go:generate gocc -a grammar.bnf
// Decision Tree Node
type Node struct {
Expression exp.Expression
Payload []string
True []*Node
False *Node
}
func NewNode(expression exp.Expression) *Node {
return &Node{
expression,
nil,
nil,
nil,
}
}
func (t Node) Evaluate(ctx exp.Context, payloadMap map[string]struct{}, trace Logger) error {
result, err := toBool(t.Expression.Evaluate(ctx))
if err != nil {
return errors.Wrapf(err, "failed to evaluate expression %v", t.Expression)
}
if result {
for _, payload := range t.Payload {
payloadMap[payload] = struct{}{}
}
}
if trace != nil {
trace.Appendf("EVAL %s %v", t.Expression, t.Payload)
}
if result && len(t.True) > 0 {
for _, trueNode := range t.True {
err := trueNode.Evaluate(ctx, payloadMap, trace)
if err != nil {
return err
}
}
return nil
} else if t.False != nil {
return t.False.Evaluate(ctx, payloadMap, trace)
} else if result {
for _, payload := range t.Payload {
payloadMap[payload] = struct{}{}
}
}
return nil
}
func toBool(result interface{}, err error) (bool, error) {
if err != nil {
return false, err
}
if result == nil {
return false, nil
}
b, ok := result.(bool)
if !ok {
return false, errors.Errorf("Expect bool got %v", result)
}
return b, nil
}
func (t Node) String() string {
return fmt.Sprintf("(%s [%s] %s)", t.True, t.Expression, t.False)
}