-
Notifications
You must be signed in to change notification settings - Fork 0
/
var.go
67 lines (50 loc) · 1.24 KB
/
var.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
package jq
import (
"fmt"
)
type (
Variable struct {
Name string
Value Off
}
Binding struct {
Name string
Value Filter
}
Var string
VarNotDefinedError string
)
func (b *Buffer) Bind(name string, off Off) {
b.Vars = append(b.Vars, Variable{Name: name, Value: off})
}
func (b *Buffer) Var(name string) Off {
for i := len(b.Vars) - 1; i >= 0; i-- {
v := b.Vars[i]
if v.Name == name {
return v.Value
}
}
return None
}
func Bind(name string, v Filter) *Binding {
return &Binding{Name: name, Value: v}
}
func (f *Binding) ApplyTo(b *Buffer, off Off, next bool) (res Off, more bool, err error) {
res, more, err = f.Value.ApplyTo(b, off, next)
if err != nil || res == None {
return None, false, err
}
b.Bind(f.Name, res)
return off, more, nil
}
func (f Var) ApplyTo(b *Buffer, off Off, next bool) (res Off, more bool, err error) {
// log.Printf("b vars: %v", b.Vars)
res = b.Var(string(f))
if res == None {
return None, false, VarNotDefinedError(f)
}
return res, false, nil
}
func (f *Binding) String() string { return fmt.Sprintf("%+v as $%s", f.Value, f.Name) }
func (f Var) String() string { return "$" + string(f) }
func (e VarNotDefinedError) Error() string { return "variable is not defined: " + string(e) }