Share variable scope and the walk over a document's nodes

Flatten and Validate read nodes through one walk, and the parser, flattener,
validator and writer set variables through one type.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 18:20:35 +00:00
co-authored by Claude Sonnet 5.5
parent cc484ac3ef
commit 1bb842589e
5 changed files with 129 additions and 104 deletions
+17 -43
View File
@@ -73,8 +73,7 @@ type target struct {
// flattener reads a document's nodes in order.
type flattener struct {
flat *Flat
defines map[string]string
flat *Flat
// levels are the opcodes set at each level.
levels [levelRegion + 1]Opcodes
into *target
@@ -86,55 +85,30 @@ type flattener struct {
// new header clears the ones below it, so a <group> starts with no group
// opcodes. Comments are dropped. An include that wasn't read is skipped.
func (d *Document) Flatten() *Flat {
f := &flattener{
flat: &Flat{Control: Opcodes{}, Headers: map[string]int{}},
defines: map[string]string{},
}
f := &flattener{flat: &Flat{Control: Opcodes{}, Headers: map[string]int{}}}
for i := range f.levels {
f.levels[i] = Opcodes{}
}
f.file(d.Root)
walk(d.Root, defines{}, f)
f.closeRegion()
return f.flat
}
func (f *flattener) file(file *File) {
for _, n := range file.Nodes {
switch n.Kind {
case KindDefine:
f.defines[n.Name] = strings.TrimSpace(substitute(f.defines, n.Value))
case KindInclude:
if n.File != nil {
f.file(n.File)
}
case KindHeader:
f.header(n, file.Path)
case KindOpcode:
if !strings.Contains(n.Name+n.Value, "$") {
f.opcode(n.Name, n.Value)
continue
}
f.expand(n, file.Path, n.Name+"="+n.Value)
case KindText:
if strings.Contains(n.Raw, "$") {
f.expand(n, file.Path, n.Raw)
}
}
func (f *flattener) define(*File, *Node) {}
func (f *flattener) include(*File, *Node) {}
func (f *flattener) variables(*File, *Node) {}
func (f *flattener) text(*File, *Node, string) {}
func (f *flattener) header(file *File, n *Node, name string, variable bool) {
if variable {
// The header has no node of its own, so it takes the line of the node that
// made it.
n = &Node{Name: name, Line: n.Line}
}
f.startHeader(n, file.Path)
}
// expand reads again the text that a node makes once its variables are
// replaced, as a variable's value can hold opcodes or headers.
func (f *flattener) expand(n *Node, file, text string) {
for _, m := range lex(substitute(f.defines, text)) {
switch m.Kind {
case KindHeader:
f.header(&Node{Name: m.Name, Line: n.Line}, file)
case KindOpcode:
f.opcode(m.Name, m.Value)
}
}
}
func (f *flattener) opcode(_ *File, _ *Node, name, value string, _ bool) { f.setOpcode(name, value) }
// closeRegion adds the region being read, if any. A region takes the <control>
// settings made before it, which later <control> headers don't change.
@@ -152,7 +126,7 @@ func (f *flattener) closeRegion() {
f.flat.Regions = append(f.flat.Regions, FlatRegion{Opcodes: ops, File: f.into.file, Line: f.into.region.Line})
}
func (f *flattener) header(n *Node, file string) {
func (f *flattener) startHeader(n *Node, file string) {
f.closeRegion()
name := strings.ToLower(n.Name)
switch name {
@@ -182,7 +156,7 @@ func (f *flattener) header(n *Node, file string) {
}
}
func (f *flattener) opcode(name, value string) {
func (f *flattener) setOpcode(name, value string) {
if f.into == nil {
// Opcodes before any header apply to every region.
f.into = &target{ops: f.levels[levelGlobal]}
+3 -3
View File
@@ -123,7 +123,7 @@ func Includes(text []byte) []string {
// parser reads a document's files, keeping the variables defined so far.
type parser struct {
parseConfig
defines map[string]string
defines defines
// including holds the files being read, to refuse an include loop.
including []string
bytes int
@@ -131,7 +131,7 @@ type parser struct {
}
func newParser(opts []ParseOption) *parser {
p := &parser{parseConfig: parseConfig{limits: DefaultLimits}, defines: map[string]string{}}
p := &parser{parseConfig: parseConfig{limits: DefaultLimits}, defines: defines{}}
for _, o := range opts {
o(&p.parseConfig)
}
@@ -201,7 +201,7 @@ func (p *parser) file(name string, data []byte, depth int) (*File, error) {
if err != nil {
return nil, err
}
p.defines[n.Name] = strings.TrimSpace(value)
p.defines.set(n.Name, value)
case KindOpcode, KindText:
// Flattening and writing expand these again, so what they make counts.
if strings.Contains(n.Raw, "$") {
+84
View File
@@ -0,0 +1,84 @@
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)
}
}
}
}
}
+21 -54
View File
@@ -13,9 +13,10 @@ import (
// read. It reports what is wrong with the text and with values the format
// describes, and never fails on an opcode it doesn't know.
func (d *Document) Validate() []Problem {
v := &validator{defines: map[string]string{}, known: map[string]known{}}
defs := defines{}
v := &validator{defs: defs, known: map[string]known{}}
v.problems = append(v.problems, d.problems...)
v.file(d.Root)
walk(d.Root, defs, v)
v.endHeader()
return v.problems
}
@@ -34,7 +35,8 @@ type known struct {
}
type validator struct {
defines map[string]string
// defs are the variables defined so far, which [walk] sets.
defs defines
// known holds the lookups made, as a document names the same few opcodes
// many times.
known map[string]known
@@ -50,58 +52,25 @@ func (v *validator) add(file string, n *Node, sev Severity, code, msg string) {
v.problems = append(v.problems, Problem{File: file, Line: n.Line, Col: n.Col, Severity: sev, Code: code, Msg: msg})
}
func (v *validator) file(f *File) {
for _, n := range f.Nodes {
switch n.Kind {
case KindDefine:
v.undefined(f, n, n.Value)
v.defines[n.Name] = strings.TrimSpace(substitute(v.defines, n.Value))
case KindInclude:
v.undefined(f, n, n.Value)
if n.Resolved != "" && !fs.ValidPath(n.Resolved) {
v.add(f.Path, n, SeverityWarning, "include.outside", fmt.Sprintf("%s is outside the folder of the main file", n.Resolved))
}
if n.File != nil {
v.file(n.File)
}
case KindHeader:
v.header(f, n, n.Name)
case KindOpcode, KindText:
if n.Kind == KindOpcode && !strings.Contains(n.Raw, "$") {
v.opcode(f, n, n.Name, n.Value)
continue
}
v.undefined(f, n, n.Raw)
text := n.Raw
if strings.Contains(text, "$") {
// A variable's value can hold opcodes and headers, so the
// text it makes is read again.
text = substitute(v.defines, text)
}
v.read(f, n, text)
}
func (v *validator) define(f *File, n *Node) { v.undefined(f, n, n.Value) }
func (v *validator) include(f *File, n *Node) {
v.undefined(f, n, n.Value)
if n.Resolved != "" && !fs.ValidPath(n.Resolved) {
v.add(f.Path, n, SeverityWarning, "include.outside", fmt.Sprintf("%s is outside the folder of the main file", n.Resolved))
}
}
// read checks the headers and opcodes that text holds, which stands where n
// does.
func (v *validator) read(f *File, n *Node, text string) {
for _, m := range lex(text) {
switch m.Kind {
case KindHeader:
v.header(f, n, m.Name)
case KindOpcode:
v.opcode(f, n, m.Name, m.Value)
case KindText:
if strings.Contains(m.Raw, "$") {
continue
}
v.add(f.Path, n, SeverityWarning, "text.unreadable", fmt.Sprintf("can't read %q", strings.TrimSpace(m.Raw)))
}
func (v *validator) variables(f *File, n *Node) { v.undefined(f, n, n.Raw) }
func (v *validator) text(f *File, n *Node, raw string) {
if strings.Contains(raw, "$") {
return
}
v.add(f.Path, n, SeverityWarning, "text.unreadable", fmt.Sprintf("can't read %q", strings.TrimSpace(raw)))
}
func (v *validator) header(f *File, n *Node, name string) {
func (v *validator) header(f *File, n *Node, name string, _ bool) {
v.endHeader()
v.inHeader = true
v.numbers = map[string]opcodeAt{}
@@ -131,7 +100,7 @@ func (v *validator) endHeader() {
v.numbers = nil
}
func (v *validator) opcode(f *File, n *Node, name, value string) {
func (v *validator) opcode(f *File, n *Node, name, value string, _ bool) {
if !v.inHeader {
v.add(f.Path, n, SeverityInfo, "opcode.no-header", fmt.Sprintf("%s is before any header", name))
v.inHeader = true
@@ -216,10 +185,8 @@ func bounds(info OpcodeInfo) string {
// undefined reports the variables in text that haven't been defined.
func (v *validator) undefined(f *File, n *Node, text string) {
for _, run := range variableRE.FindAllString(text, -1) {
if substitute(v.defines, run) == run {
v.add(f.Path, n, SeverityWarning, "define.undefined", fmt.Sprintf("%s isn't defined", run))
}
for _, run := range v.defs.undefined(text) {
v.add(f.Path, n, SeverityWarning, "define.undefined", fmt.Sprintf("%s isn't defined", run))
}
}
+4 -4
View File
@@ -46,7 +46,7 @@ type FileWriter func(path string, data []byte) error
// defines, so it is an error unless no include was read; use [Document.WriteFiles]
// then.
func (d *Document) Write(w io.Writer, opts WriteOptions) error {
r := &renderer{opts: opts, defines: map[string]string{}, outputs: map[string]string{}}
r := &renderer{opts: opts, defines: defines{}, outputs: map[string]string{}}
text := r.file(d.Root)
if r.err != nil {
return r.err
@@ -63,7 +63,7 @@ func (d *Document) Write(w io.Writer, opts WriteOptions) error {
// and returns [ErrInvalid] if an include's path is absolute or leaves the
// folder.
func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) error {
r := &renderer{opts: opts, defines: map[string]string{}, outputs: map[string]string{}}
r := &renderer{opts: opts, defines: defines{}, outputs: map[string]string{}}
text := r.file(d.Root)
if r.err != nil {
return r.err
@@ -93,7 +93,7 @@ func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) err
// renderer writes files as the options say.
type renderer struct {
opts WriteOptions
defines map[string]string
defines defines
// outputs are the included files that stand apart, by path.
outputs map[string]string
err error
@@ -118,7 +118,7 @@ func (r *renderer) file(f *File) string {
switch n.Kind {
case KindDefine:
if r.opts.ExpandVariables {
r.defines[n.Name] = strings.TrimSpace(substitute(r.defines, n.Value))
r.defines.define(n)
dropBreak = true
continue
}