-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_utils.go
96 lines (82 loc) · 2.23 KB
/
node_utils.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
92
93
94
95
96
package eval
import (
"github.com/markusbkk/elvish/pkg/diag"
"github.com/markusbkk/elvish/pkg/parse"
"github.com/markusbkk/elvish/pkg/parse/cmpd"
)
// Utilities for working with nodes.
func stringLiteralOrError(cp *compiler, n *parse.Compound, what string) string {
s, err := cmpd.StringLiteralOrError(n, what)
if err != nil {
cp.errorpf(n, "%v", err)
}
return s
}
type errorpfer interface {
errorpf(r diag.Ranger, fmt string, args ...interface{})
}
// argsWalker is used by builtin special forms to implement argument parsing.
type argsWalker struct {
cp errorpfer
form *parse.Form
idx int
}
func (cp *compiler) walkArgs(f *parse.Form) *argsWalker {
return &argsWalker{cp, f, 0}
}
func (aw *argsWalker) more() bool {
return aw.idx < len(aw.form.Args)
}
func (aw *argsWalker) peek() *parse.Compound {
if !aw.more() {
aw.cp.errorpf(aw.form, "need more arguments")
}
return aw.form.Args[aw.idx]
}
func (aw *argsWalker) next() *parse.Compound {
n := aw.peek()
aw.idx++
return n
}
// nextIs returns whether the next argument's source matches the given text. It
// also consumes the argument if it is.
func (aw *argsWalker) nextIs(text string) bool {
if aw.more() && parse.SourceText(aw.form.Args[aw.idx]) == text {
aw.idx++
return true
}
return false
}
// nextMustLambda fetches the next argument, raising an error if it is not a
// lambda.
func (aw *argsWalker) nextMustLambda(what string) *parse.Primary {
n := aw.next()
pn, ok := cmpd.Lambda(n)
if !ok {
aw.cp.errorpf(n, "%s must be lambda, found %s", what, cmpd.Shape(n))
}
return pn
}
// nextMustThunk fetches the next argument, raising an error if it is not a
// thunk.
func (aw *argsWalker) nextMustThunk(what string) *parse.Primary {
n := aw.nextMustLambda(what)
if len(n.Elements) > 0 {
aw.cp.errorpf(n, "%s must not have arguments", what)
}
if len(n.MapPairs) > 0 {
aw.cp.errorpf(n, "%s must not have options", what)
}
return n
}
func (aw *argsWalker) nextMustThunkIfAfter(leader string) *parse.Primary {
if aw.nextIs(leader) {
return aw.nextMustLambda(leader + " body")
}
return nil
}
func (aw *argsWalker) mustEnd() {
if aw.more() {
aw.cp.errorpf(diag.Ranging{From: aw.form.Args[aw.idx].Range().From, To: aw.form.Range().To}, "too many arguments")
}
}