-
Notifications
You must be signed in to change notification settings - Fork 78
/
op_negate.go
80 lines (68 loc) · 1.85 KB
/
op_negate.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
package spruce
import (
"fmt"
"github.com/geofffranks/spruce/log"
"github.com/starkandwayne/goutils/tree"
)
// NegateOperator ...
type NegateOperator struct{}
// Setup ...
func (NegateOperator) Setup() error {
return nil
}
// Phase ...
func (NegateOperator) Phase() OperatorPhase {
return EvalPhase
}
// Dependencies ...
func (NegateOperator) Dependencies(_ *Evaluator, _ []*Expr, _ []*tree.Cursor, auto []*tree.Cursor) []*tree.Cursor {
return auto
}
// Run ...
func (NegateOperator) Run(ev *Evaluator, args []*Expr) (*Response, error) {
log.DEBUG("running (( negate ... )) operation at $.%s", ev.Here)
defer log.DEBUG("done with (( negate ... )) operation at $%s\n", ev.Here)
if len(args) != 1 {
return nil, fmt.Errorf("negate operator requires exactly one reference argument")
}
var arg = args[0]
var val bool
v, err := arg.Resolve(ev.Tree)
if err != nil {
log.DEBUG(" resolution failed\n error: %s", err)
return nil, err
}
switch v.Type {
case Reference:
log.DEBUG(" trying to resolve reference $.%s", v.Reference)
s, err := v.Reference.Resolve(ev.Tree)
if err != nil {
log.DEBUG(" resolution failed\n error: %s", err)
return nil, fmt.Errorf("Unable to resolve `%s`: %s", v.Reference, err)
}
log.DEBUG(" resolved to a value")
switch s2 := s.(type) {
case bool:
val = !s2
default:
return nil, fmt.Errorf("negate operator only accepts references to bools")
}
case Literal:
switch literal := v.Literal.(type) {
case bool:
val = !literal
default:
return nil, fmt.Errorf("negate operator only operates on bools")
}
default:
log.DEBUG(" unsupported expression type %v, only references are allowed: '%v'", v.Type, arg)
return nil, fmt.Errorf("negate operator only accepts reference arguments")
}
return &Response{
Type: Replace,
Value: val,
}, nil
}
func init() {
RegisterOp("negate", NegateOperator{})
}