Files
sfz/scope.go
T

85 lines
2.5 KiB
Go
Raw Normal View History

package sfz
import "strings"
// defines are the variables defined so far, by name with their $.
type defines map[string]string
// set gives a variable the value, which has its own variables replaced
// already.
func (d defines) set(name, value string) { d[name] = strings.TrimSpace(value) }
// define reads 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 reads a document's nodes as [walk] meets them.
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 what it makes is read.
variables(f *File, n *Node)
// header is called for a header. Variable is whether a variable's value
// 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.
opcode(f *File, n *Node, name, value string, variable bool)
// text is called for text that isn't an opcode or header, which n is or
// holds.
text(f *File, n *Node, raw string)
}
// walk reads the nodes of a file in order, and of the files it includes where
// they stand, with the variables as they are at each node. Text that uses a
// variable is read again with the variable replaced, as the 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)
}
}
}
}
}