Files

88 lines
2.8 KiB
Go
Raw Permalink Normal View History

package sfz
import "strings"
// defines are the variables defined so far, by name with their $, with their
// values as they stand after the variables in them are replaced.
type defines map[string]string
// set gives a variable a value, which has had its own variables replaced
// already.
func (d defines) set(name, value string) { d[name] = strings.TrimSpace(value) }
// define sets the variable of a #define node, replacing the variables in its
// value.
func (d defines) define(n *Node) { d.set(n.Name, substitute(d, n.Value)) }
// undefined returns the variables in text that haven't been defined.
func (d defines) undefined(text string) []string {
var out []string
for _, run := range variableRE.FindAllString(text, -1) {
if substitute(d, run) == run {
out = append(out, run)
}
}
return out
}
// visitor is what [walk] tells about the nodes of a document, in order.
type visitor interface {
// define is called for a #define, before its variable is set.
define(f *File, n *Node)
// include is called for an #include, before the file it read is walked.
include(f *File, n *Node)
// variables is called for an opcode or text node that uses variables,
// before the headers, opcodes and text that it makes are told of.
variables(f *File, n *Node)
// header is called for a header. Variable is whether the value of a
// variable made it, in which case n is the node that uses the variable.
header(f *File, n *Node, name string, variable bool)
// opcode is called for an opcode. Variable is as for header, and n is
// likewise the node that uses the variable.
opcode(f *File, n *Node, name, value string, variable bool)
// text is called for text that isn't an opcode or a header, which is n or
// is made by n.
text(f *File, n *Node, raw string)
}
// walk tells v of the nodes of a file in order, and of the files it includes
// where the includes stand, with defs holding the variables as they are at each
// node. A node that uses a variable is lexed again with its variables replaced,
// because a value can hold opcodes and headers.
func walk(f *File, defs defines, v visitor) {
for _, n := range f.Nodes {
switch n.Kind {
case KindDefine:
v.define(f, n)
defs.define(n)
case KindInclude:
v.include(f, n)
if n.File != nil {
walk(n.File, defs, v)
}
case KindHeader:
v.header(f, n, n.Name, false)
case KindOpcode, KindText:
if !strings.Contains(n.Raw, "$") {
if n.Kind == KindOpcode {
v.opcode(f, n, n.Name, n.Value, false)
} else {
v.text(f, n, n.Raw)
}
continue
}
v.variables(f, n)
for _, m := range lex(substitute(defs, n.Raw)) {
switch m.Kind {
case KindHeader:
v.header(f, n, m.Name, true)
case KindOpcode:
v.opcode(f, n, m.Name, m.Value, true)
case KindText:
v.text(f, n, m.Raw)
}
}
}
}
}