Check edited values, keep comments in place and make edits cheap

- Header.Set, Document.SetDefine and Document.AddHeader return an error for
  a value or name that can't be written as one opcode, define or header, and
  Build returns the same error for what it can't write.
- Set puts a new opcode after the last one's trailing comment, and never
  where text on its line would become part of its value. Delete keeps the
  line breaks it doesn't own.
- Node.Line and Node.Col are replaced by File.Position, which works lines and
  columns out when asked, and a node remembers where it was in its file, so an
  edit no longer renumbers the file or searches it from the start.
- Add FuzzEdit checks that an edited file reads back as its nodes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 18:27:17 +00:00
co-authored by Claude Sonnet 5.5
parent 1bb842589e
commit d4b44b6ffb
11 changed files with 482 additions and 129 deletions
+26 -2
View File
@@ -113,7 +113,7 @@ func Build(inst *Instrument, opts ...BuildOptions) (*Document, error) {
b := &builder{indent: o.Indent} b := &builder{indent: o.Indent}
for _, d := range defines { for _, d := range defines {
b.line("#define " + d.name + " " + d.value) b.define(d.name, d.value)
} }
if len(control) > 0 { if len(control) > 0 {
b.header("control", control) b.header("control", control)
@@ -126,10 +126,16 @@ func Build(inst *Instrument, opts ...BuildOptions) (*Document, error) {
for _, ops := range regions { for _, ops := range regions {
b.header("region", ops) b.header("region", ops)
} }
if b.err != nil {
return nil, b.err
}
return &Document{Root: b.file("")}, nil return &Document{Root: b.file("")}, nil
} }
// The main file includes a file for each run of regions. // The main file includes a file for each run of regions.
if b.err != nil {
return nil, b.err
}
main := b.file("") main := b.file("")
for i := 0; i*o.RegionsPerFile < len(regions); i++ { for i := 0; i*o.RegionsPerFile < len(regions); i++ {
chunk := regions[i*o.RegionsPerFile : min(len(regions), (i+1)*o.RegionsPerFile)] chunk := regions[i*o.RegionsPerFile : min(len(regions), (i+1)*o.RegionsPerFile)]
@@ -137,13 +143,19 @@ func Build(inst *Instrument, opts ...BuildOptions) (*Document, error) {
for _, ops := range chunk { for _, ops := range chunk {
cb.header("region", ops) cb.header("region", ops)
} }
if cb.err != nil {
return nil, cb.err
}
name := path.Clean(o.FileNamer(i)) name := path.Clean(o.FileNamer(i))
if nodes := lex(`#include "` + name + `"`); len(nodes) != 1 || nodes[0].Kind != KindInclude || nodes[0].Value != name {
return nil, fmt.Errorf("%w: %q can't be the path of an included file", ErrInvalid, name)
}
child := cb.file(name) child := cb.file(name)
main.Nodes = append(main.Nodes, main.Nodes = append(main.Nodes,
&Node{Kind: KindInclude, Raw: `#include "` + name + `"`, Value: name, Resolved: name, File: child}, &Node{Kind: KindInclude, Raw: `#include "` + name + `"`, Value: name, Resolved: name, File: child},
&Node{Kind: KindSpace, Raw: "\n"}) &Node{Kind: KindSpace, Raw: "\n"})
} }
main.reposition() main.dirty = true
return &Document{Root: main}, nil return &Document{Root: main}, nil
} }
@@ -151,6 +163,8 @@ func Build(inst *Instrument, opts ...BuildOptions) (*Document, error) {
type builder struct { type builder struct {
indent string indent string
text strings.Builder text strings.Builder
// err is the first thing that couldn't be written.
err error
} }
func (b *builder) line(s string) { func (b *builder) line(s string) {
@@ -161,10 +175,20 @@ func (b *builder) line(s string) {
func (b *builder) header(name string, ops []opcodeLine) { func (b *builder) header(name string, ops []opcodeLine) {
b.line("<" + name + ">") b.line("<" + name + ">")
for _, op := range ops { for _, op := range ops {
if err := checkOpcode(op.name, op.value); err != nil && b.err == nil {
b.err = err
}
b.line(b.indent + op.name + "=" + op.value) b.line(b.indent + op.name + "=" + op.value)
} }
} }
func (b *builder) define(name, value string) {
if err := checkDefine(name, value); err != nil && b.err == nil {
b.err = err
}
b.line("#define " + name + " " + value)
}
// file returns what the builder has written as a file with the path. // file returns what the builder has written as a file with the path.
func (b *builder) file(p string) *File { func (b *builder) file(p string) *File {
f := &File{Path: p, Nodes: lex(b.text.String())} f := &File{Path: p, Nodes: lex(b.text.String())}
+8 -2
View File
@@ -79,13 +79,17 @@ type Node struct {
// Value is an opcode's or a define's value without surrounding // Value is an opcode's or a define's value without surrounding
// whitespace, or an include's path as written. // whitespace, or an include's path as written.
Value string Value string
// Line and Col are where the node starts, from 1, with Col in bytes.
Line, Col int
// Resolved is an include's path with its variables substituted, with // Resolved is an include's path with its variables substituted, with
// forward slashes, relative to the folder of the main file. // forward slashes, relative to the folder of the main file.
Resolved string Resolved string
// File is the file an include reads, or nil if it wasn't read. // File is the file an include reads, or nil if it wasn't read.
File *File File *File
// line and col are where the node starts, from 1, with col in bytes, as of
// the last time the file's positions were worked out (see [File.Position]).
line, col int
// idx is where the node was in its file's nodes the last time it was
// looked for, which stays close to where it is.
idx int
} }
// File is one file of a document: the main file or an included one. // File is one file of a document: the main file or an included one.
@@ -94,6 +98,8 @@ type File struct {
// forward slashes. For a file read with [Parse] and no name, it is empty. // forward slashes. For a file read with [Parse] and no name, it is empty.
Path string Path string
Nodes []*Node Nodes []*Node
// dirty is whether edits have left the nodes' lines and columns out of date.
dirty bool
} }
// String returns the file's text. // String returns the file's text.
+200 -75
View File
@@ -1,6 +1,10 @@
package sfz package sfz
import "strings" import (
"fmt"
"slices"
"strings"
)
// Header is a header of a file, with the opcodes that follow it up to the // Header is a header of a file, with the opcodes that follow it up to the
// next header in the same file. Opcodes that an #include after it brings in // next header in the same file. Opcodes that an #include after it brings in
@@ -15,20 +19,30 @@ type Header struct {
// Name returns the header's name without brackets, as written. // Name returns the header's name without brackets, as written.
func (h *Header) Name() string { return h.Node.Name } func (h *Header) Name() string { return h.Node.Name }
// index returns where the header's node is in its file. // indexOf returns where a node is in the file, or -1. A node remembers where it
func (h *Header) index() int { // was, which stays close to where it is after edits, so the search starts
for i, n := range h.File.Nodes { // there.
if n == h.Node { func (f *File) indexOf(n *Node) int {
return i at := func(i int) bool { return i >= 0 && i < len(f.Nodes) && f.Nodes[i] == n }
for d := 0; ; d++ {
if at(n.idx + d) {
n.idx += d
return n.idx
}
if at(n.idx - d) {
n.idx -= d
return n.idx
}
if n.idx-d < 0 && n.idx+d >= len(f.Nodes) {
return -1
} }
} }
return -1
} }
// span returns the range of the file's nodes after the header's own, up to the // span returns the range of the file's nodes after the header's own, up to the
// next header. // next header.
func (h *Header) span() (start, end int) { func (h *Header) span() (start, end int) {
start = h.index() + 1 start = h.File.indexOf(h.Node) + 1
end = start end = start
for end < len(h.File.Nodes) && h.File.Nodes[end].Kind != KindHeader { for end < len(h.File.Nodes) && h.File.Nodes[end].Kind != KindHeader {
end++ end++
@@ -51,37 +65,77 @@ func (h *Header) Opcodes() []*Node {
// Get returns the header's last node for an opcode, which is the one that // Get returns the header's last node for an opcode, which is the one that
// takes effect. // takes effect.
func (h *Header) Get(name string) (*Node, bool) { func (h *Header) Get(name string) (*Node, bool) {
ops := h.Opcodes() start, end := h.span()
for i := len(ops) - 1; i >= 0; i-- { for i := end - 1; i >= start; i-- {
if ops[i].Name == name { if n := h.File.Nodes[i]; n.Kind == KindOpcode && n.Name == name {
return ops[i], true return n, true
} }
} }
return nil, false return nil, false
} }
// Set gives the opcode a value. An opcode the header already has keeps its // checkOpcode returns an error if name=value wouldn't be read back as one
// place and the text around it, and takes the value as written even if it was a // opcode with that value, as when the value holds a line break, a comment, or
// variable. A new one goes after the header's last opcode, laid out as that // another opcode.
// one is. func checkOpcode(name, value string) error {
func (h *Header) Set(name, value string) { text := name + "=" + value
if n, ok := h.Get(name); ok { nodes := lex(text)
n.Raw = name + "=" + value if len(nodes) > 0 && nodes[0].Kind == KindOpcode && nodes[0].Name == name && nodes[0].Value == strings.TrimSpace(value) &&
n.Value = strings.TrimSpace(value) nodes[0].Raw == text && onlySpace(nodes[1:]) {
h.File.reposition() return nil
return
} }
start, end := h.span() return fmt.Errorf("%w: %s=%q can't be written as one opcode", ErrInvalid, name, value)
at := start }
sep := ""
for i := start; i < end; i++ { // checkDefine returns an error if the text of a #define of name with value
if h.File.Nodes[i].Kind == KindOpcode { // wouldn't be read back as that directive.
at = i + 1 func checkDefine(name, value string) error {
nodes := lex("#define " + name + " " + value)
if len(nodes) > 0 && nodes[0].Kind == KindDefine && nodes[0].Name == name && nodes[0].Value == strings.TrimSpace(value) && onlySpace(nodes[1:]) {
return nil
}
return fmt.Errorf("%w: #define %s %q can't be written as one directive", ErrInvalid, name, value)
}
// onlySpace reports whether every node is whitespace.
func onlySpace(nodes []*Node) bool {
for _, n := range nodes {
if n.Kind != KindSpace {
return false
} }
} }
if at == start { return true
// With no opcode to follow, the new one goes after the header, on its }
// own line if the header is.
// Set gives the opcode a value, or returns an error wrapping [ErrInvalid], and
// changes nothing, if the value can't be written as the value of one opcode. An
// opcode the header already has keeps its place and the text around it, and
// takes the value as written even if it was a variable. A new one goes after the
// header's last opcode, and its comment, laid out as that opcode is.
func (h *Header) Set(name, value string) error {
value = strings.TrimSpace(value)
if err := checkOpcode(name, value); err != nil {
return err
}
if n, ok := h.Get(name); ok {
n.Raw = name + "=" + value
n.Value = value
h.File.dirty = true
return nil
}
start, end := h.span()
last := -1
for i := start; i < end; i++ {
if h.File.Nodes[i].Kind == KindOpcode {
last = i
}
}
nodes := []*Node{{Kind: KindOpcode, Raw: name + "=" + value, Name: name, Value: value}}
at := start
var sep string
if last < 0 {
// With no opcode to follow, the new one goes after the header, on its own
// line if the header is.
sep = " " sep = " "
if start < len(h.File.Nodes) && h.File.Nodes[start].Kind == KindSpace && strings.Contains(h.File.Nodes[start].Raw, "\n") { if start < len(h.File.Nodes) && h.File.Nodes[start].Kind == KindSpace && strings.Contains(h.File.Nodes[start].Raw, "\n") {
sep = h.File.Nodes[start].Raw sep = h.File.Nodes[start].Raw
@@ -89,18 +143,58 @@ func (h *Header) Set(name, value string) {
sep = "\n" sep = "\n"
} }
} else { } else {
at = last + 1
sep = " " sep = " "
if i := at - 2; i >= start && h.File.Nodes[i].Kind == KindSpace { if i := last - 1; i >= start && h.File.Nodes[i].Kind == KindSpace {
sep = h.File.Nodes[i].Raw sep = h.File.Nodes[i].Raw
} else if strings.Contains(h.File.String(), "\n") { } else if h.File.hasLineBreak() {
sep = "\n" sep = "\n"
} }
// The new opcode goes after what ends the last one's line. A line comment
// runs to the end of the line, so the opcode then needs a line of its own.
for {
k := at
for k < end && h.File.Nodes[k].Kind == KindSpace && !strings.Contains(h.File.Nodes[k].Raw, "\n") {
k++
}
if k >= end || h.File.Nodes[k].Kind != KindComment || unterminated(h.File.Nodes[k]) {
break
}
if c := h.File.Nodes[k]; strings.HasPrefix(c.Raw, "//") && !strings.Contains(sep, "\n") {
sep = "\n"
}
at = k + 1
}
} }
nodes := []*Node{ inserted := append([]*Node{{Kind: KindSpace, Raw: sep}}, nodes...)
{Kind: KindSpace, Raw: sep}, // A value runs to the end of its line unless a header, opcode, comment or
{Kind: KindOpcode, Raw: name + "=" + value, Name: name, Value: strings.TrimSpace(value)}, // directive ends it, so text after the new opcode on its line would become
// part of the value. It goes on a line of its own.
k := at
for k < len(h.File.Nodes) && h.File.Nodes[k].Kind == KindSpace && !strings.Contains(h.File.Nodes[k].Raw, "\n") {
k++
} }
h.File.insert(at, nodes...) if k < len(h.File.Nodes) && h.File.Nodes[k].Kind == KindText {
inserted = append(inserted, &Node{Kind: KindSpace, Raw: "\n"})
}
h.File.insert(at, inserted...)
return nil
}
// unterminated reports whether a node is a block comment that never ends, which
// takes in all that follows it.
func unterminated(n *Node) bool {
return n.Kind == KindComment && strings.HasPrefix(n.Raw, "/*") && (len(n.Raw) < 4 || !strings.HasSuffix(n.Raw, "*/"))
}
// hasLineBreak reports whether the file has a line break.
func (f *File) hasLineBreak() bool {
for _, n := range f.Nodes {
if n.Kind == KindSpace && strings.Contains(n.Raw, "\n") {
return true
}
}
return false
} }
// Delete removes the opcode, every time the header has it, with the space // Delete removes the opcode, every time the header has it, with the space
@@ -111,38 +205,56 @@ func (h *Header) Delete(name string) {
if !ok { if !ok {
return return
} }
i := indexOf(h.File.Nodes, n) i := h.File.indexOf(n)
from := i from, to := i, i+1
if i > 0 && h.File.Nodes[i-1].Kind == KindSpace { isSpace := func(i int, lineBreak bool) bool {
return i >= 0 && i < len(h.File.Nodes) && h.File.Nodes[i].Kind == KindSpace && strings.Contains(h.File.Nodes[i].Raw, "\n") == lineBreak
}
switch {
case isSpace(i-1, false):
from = i - 1 from = i - 1
case isSpace(i-1, true):
// The line break before the opcode goes with it only if what follows
// ends the line, as the opcode's own line then goes. Otherwise the
// text after it stays on the line, without the space that separated it.
if i+1 >= len(h.File.Nodes) || isSpace(i+1, true) || h.File.Nodes[i+1].Kind == KindHeader {
from = i - 1
} else if isSpace(i+1, false) {
to = i + 2
}
} }
h.File.Nodes = append(h.File.Nodes[:from], h.File.Nodes[i+1:]...) h.File.Nodes = slices.Delete(h.File.Nodes, from, to)
h.File.reposition() h.File.dirty = true
} }
} }
func indexOf(nodes []*Node, n *Node) int {
for i, m := range nodes {
if m == n {
return i
}
}
return -1
}
// insert adds nodes at an index. // insert adds nodes at an index.
func (f *File) insert(at int, nodes ...*Node) { func (f *File) insert(at int, nodes ...*Node) {
f.Nodes = append(f.Nodes[:at], append(nodes, f.Nodes[at:]...)...) f.Nodes = slices.Insert(f.Nodes, at, nodes...)
f.reposition() for i, n := range nodes {
n.idx = at + i
}
f.dirty = true
} }
// reposition sets the line and column of each node from the text before it. // Position returns where a node of the file starts, with the line and the
// column, in bytes, from 1. Edits move what follows them, which is worked out
// when this is next called.
func (f *File) Position(n *Node) (line, col int) {
if f.dirty {
f.reposition()
}
return n.line, n.col
}
// reposition sets the line, column and index of each node from the text
// before it.
func (f *File) reposition() { func (f *File) reposition() {
line, col := 1, 1 line, col := 1, 1
for _, n := range f.Nodes { for i, n := range f.Nodes {
n.Line, n.Col = line, col n.line, n.col, n.idx = line, col, i
for i := 0; i < len(n.Raw); i++ { for j := 0; j < len(n.Raw); j++ {
if n.Raw[i] == '\n' { if n.Raw[j] == '\n' {
line++ line++
col = 1 col = 1
} else { } else {
@@ -150,6 +262,7 @@ func (f *File) reposition() {
} }
} }
} }
f.dirty = false
} }
// Headers returns the headers of every file of the document, in the order the // Headers returns the headers of every file of the document, in the order the
@@ -168,13 +281,24 @@ func (d *Document) Headers() []*Header {
// AddHeader adds an empty header on a line of its own after another header and // AddHeader adds an empty header on a line of its own after another header and
// its opcodes, or at the end of the main file if after is nil, and returns it. // its opcodes, or at the end of the main file if after is nil, and returns it.
func (d *Document) AddHeader(name string, after *Header) *Header { // It returns an error wrapping [ErrInvalid] if the name isn't one a header can
// have.
func (d *Document) AddHeader(name string, after *Header) (*Header, error) {
if m := headerRE.FindString("<" + name + ">"); m != "<"+name+">" {
return nil, fmt.Errorf("%w: <%s> isn't a header", ErrInvalid, name)
}
f := d.Root f := d.Root
at := len(f.Nodes) at := len(f.Nodes)
if after != nil { if after != nil {
f = after.File f = after.File
_, at = after.span() _, at = after.span()
} }
if at > 0 {
// A header after a block comment that never ends would be inside it.
if c := f.Nodes[at-1]; unterminated(c) {
return nil, fmt.Errorf("%w: a comment that doesn't end is where <%s> would go", ErrInvalid, name)
}
}
var nodes []*Node var nodes []*Node
if at > 0 && !strings.HasSuffix(f.Nodes[at-1].Raw, "\n") { if at > 0 && !strings.HasSuffix(f.Nodes[at-1].Raw, "\n") {
nodes = append(nodes, &Node{Kind: KindSpace, Raw: "\n"}) nodes = append(nodes, &Node{Kind: KindSpace, Raw: "\n"})
@@ -182,7 +306,7 @@ func (d *Document) AddHeader(name string, after *Header) *Header {
h := &Node{Kind: KindHeader, Raw: "<" + name + ">", Name: name} h := &Node{Kind: KindHeader, Raw: "<" + name + ">", Name: name}
nodes = append(nodes, h, &Node{Kind: KindSpace, Raw: "\n"}) nodes = append(nodes, h, &Node{Kind: KindSpace, Raw: "\n"})
f.insert(at, nodes...) f.insert(at, nodes...)
return &Header{File: f, Node: h} return &Header{File: f, Node: h}, nil
} }
// Defines returns the #define nodes of every file, in order. // Defines returns the #define nodes of every file, in order.
@@ -207,24 +331,25 @@ func (d *Document) nodes(kind NodeKind) []*Node {
// that each opcode that uses it changes with it. Setting an opcode that uses // that each opcode that uses it changes with it. Setting an opcode that uses
// the variable with [Header.Set] replaces the variable there instead. A // the variable with [Header.Set] replaces the variable there instead. A
// variable with no #define gets one at the start of the main file. The name // variable with no #define gets one at the start of the main file. The name
// includes its $. // includes its $. It returns an error wrapping [ErrInvalid], and changes
func (d *Document) SetDefine(name, value string) { // nothing, if the name or value can't be written as a #define.
for _, n := range d.Defines() { func (d *Document) SetDefine(name, value string) error {
if n.Name == name { value = strings.TrimSpace(value)
n.Raw = "#define " + name + " " + value if err := checkDefine(name, value); err != nil {
n.Value = value return err
d.reposition() }
return for _, f := range d.Files() {
for _, n := range f.Nodes {
if n.Kind == KindDefine && n.Name == name {
n.Raw = "#define " + name + " " + value
n.Value = value
f.dirty = true
return nil
}
} }
} }
d.Root.insert(0, d.Root.insert(0,
&Node{Kind: KindDefine, Raw: "#define " + name + " " + value, Name: name, Value: value}, &Node{Kind: KindDefine, Raw: "#define " + name + " " + value, Name: name, Value: value},
&Node{Kind: KindSpace, Raw: "\n"}) &Node{Kind: KindSpace, Raw: "\n"})
} return nil
// reposition sets the positions of every file's nodes.
func (d *Document) reposition() {
for _, f := range d.Files() {
f.reposition()
}
} }
+160 -12
View File
@@ -1,6 +1,9 @@
package sfz package sfz
import ( import (
"errors"
"fmt"
"strconv"
"strings" "strings"
"testing" "testing"
) )
@@ -17,6 +20,14 @@ func mustParse(t *testing.T, text string, m map[string]string) *Document {
return doc return doc
} }
// set sets an opcode, which the test expects to be allowed.
func set(t *testing.T, h *Header, name, value string) {
t.Helper()
if err := h.Set(name, value); err != nil {
t.Fatal(err)
}
}
func TestSetKeepsLayout(t *testing.T) { func TestSetKeepsLayout(t *testing.T) {
doc := mustParse(t, "// piano\n<group>\n\tvolume=-1 // quiet\n\tpan=5\n<region> sample=a.wav\n", nil) doc := mustParse(t, "// piano\n<group>\n\tvolume=-1 // quiet\n\tpan=5\n<region> sample=a.wav\n", nil)
hs := doc.Headers() hs := doc.Headers()
@@ -25,15 +36,17 @@ func TestSetKeepsLayout(t *testing.T) {
} }
// An existing opcode keeps its place and the comment after it, a new one // An existing opcode keeps its place and the comment after it, a new one
// goes after the last and is laid out as it is. // goes after the last and is laid out as it is.
hs[0].Set("volume", "-2") set(t, hs[0], "volume", "-2")
hs[0].Set("tune", "10") set(t, hs[0], "tune", "10")
hs[1].Set("lokey", "c4") set(t, hs[1], "lokey", "c4")
want := "// piano\n<group>\n\tvolume=-2 // quiet\n\tpan=5\n\ttune=10\n<region> sample=a.wav lokey=c4\n" want := "// piano\n<group>\n\tvolume=-2 // quiet\n\tpan=5\n\ttune=10\n<region> sample=a.wav lokey=c4\n"
if got := doc.String(); got != want { if got := doc.String(); got != want {
t.Errorf("got %q\nwant %q", got, want) t.Errorf("got %q\nwant %q", got, want)
} }
if n, ok := hs[0].Get("tune"); !ok || n.Value != "10" || n.Line != 5 { if n, ok := hs[0].Get("tune"); !ok || n.Value != "10" {
t.Errorf("tune %+v", n) t.Errorf("tune %+v", n)
} else if line, col := hs[0].File.Position(n); line != 5 || col != 2 {
t.Errorf("tune at %d:%d", line, col)
} }
// What was written reads back. // What was written reads back.
if v, _ := GetAs[int](doc.Flatten().Regions[0].Opcodes, "lokey"); v != 60 { if v, _ := GetAs[int](doc.Flatten().Regions[0].Opcodes, "lokey"); v != 60 {
@@ -54,10 +67,16 @@ func TestDelete(t *testing.T) {
func TestAddHeader(t *testing.T) { func TestAddHeader(t *testing.T) {
doc := mustParse(t, "<group> volume=1\n<region> sample=a.wav", nil) doc := mustParse(t, "<group> volume=1\n<region> sample=a.wav", nil)
hs := doc.Headers() hs := doc.Headers()
h := doc.AddHeader("region", hs[0]) h, err := doc.AddHeader("region", hs[0])
h.Set("sample", "b.wav") if err != nil {
h2 := doc.AddHeader("region", nil) t.Fatal(err)
h2.Set("sample", "c.wav") }
set(t, h, "sample", "b.wav")
h2, err := doc.AddHeader("region", nil)
if err != nil {
t.Fatal(err)
}
set(t, h2, "sample", "c.wav")
want := "<group> volume=1\n<region>\nsample=b.wav\n<region> sample=a.wav\n<region>\nsample=c.wav\n" want := "<group> volume=1\n<region>\nsample=b.wav\n<region> sample=a.wav\n<region>\nsample=c.wav\n"
if got := doc.String(); got != want { if got := doc.String(); got != want {
t.Errorf("got %q\nwant %q", got, want) t.Errorf("got %q\nwant %q", got, want)
@@ -72,16 +91,20 @@ func TestAddHeader(t *testing.T) {
func TestEditVariables(t *testing.T) { func TestEditVariables(t *testing.T) {
text := "#define $V 5\n<region> sample=a.wav lokey=$V\n<region> sample=b.wav hikey=$V\n" text := "#define $V 5\n<region> sample=a.wav lokey=$V\n<region> sample=b.wav hikey=$V\n"
doc := mustParse(t, text, nil) doc := mustParse(t, text, nil)
doc.Headers()[0].Set("lokey", "7") set(t, doc.Headers()[0], "lokey", "7")
if got, want := doc.String(), "#define $V 5\n<region> sample=a.wav lokey=7\n<region> sample=b.wav hikey=$V\n"; got != want { if got, want := doc.String(), "#define $V 5\n<region> sample=a.wav lokey=7\n<region> sample=b.wav hikey=$V\n"; got != want {
t.Errorf("Set: %q", got) t.Errorf("Set: %q", got)
} }
doc.SetDefine("$V", "9") if err := doc.SetDefine("$V", "9"); err != nil {
t.Fatal(err)
}
regions := doc.Flatten().Regions regions := doc.Flatten().Regions
if regions[0].Opcodes["lokey"] != "7" || regions[1].Opcodes["hikey"] != "9" { if regions[0].Opcodes["lokey"] != "7" || regions[1].Opcodes["hikey"] != "9" {
t.Errorf("SetDefine: %v %v", regions[0].Opcodes, regions[1].Opcodes) t.Errorf("SetDefine: %v %v", regions[0].Opcodes, regions[1].Opcodes)
} }
doc.SetDefine("$NEW", "1") if err := doc.SetDefine("$NEW", "1"); err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(doc.String(), "#define $NEW 1\n#define $V 9\n") || len(doc.Defines()) != 2 { if !strings.HasPrefix(doc.String(), "#define $NEW 1\n#define $V 9\n") || len(doc.Defines()) != 2 {
t.Errorf("new define: %q", doc.String()) t.Errorf("new define: %q", doc.String())
} }
@@ -95,7 +118,7 @@ func TestEditIncluded(t *testing.T) {
if len(hs) != 1 || hs[0].File.Path != "x.sfz" { if len(hs) != 1 || hs[0].File.Path != "x.sfz" {
t.Fatalf("headers %+v", hs) t.Fatalf("headers %+v", hs)
} }
hs[0].Set("lokey", "3") set(t, hs[0], "lokey", "3")
if doc.String() != "#include \"x.sfz\"\n" || doc.Files()[1].String() != "<region> sample=a.wav lokey=3\n" { if doc.String() != "#include \"x.sfz\"\n" || doc.Files()[1].String() != "<region> sample=a.wav lokey=3\n" {
t.Errorf("%q %q", doc.String(), doc.Files()[1].String()) t.Errorf("%q %q", doc.String(), doc.Files()[1].String())
} }
@@ -103,3 +126,128 @@ func TestEditIncluded(t *testing.T) {
t.Error("includes") t.Error("includes")
} }
} }
func TestSetKeepsComments(t *testing.T) {
for _, tc := range []struct{ text, want string }{
{"<region>\n sample=a.wav // the sample\n", "<region>\n sample=a.wav // the sample\n lokey=1\n"},
{"<region> sample=a.wav // c\n<region>", "<region> sample=a.wav // c\nlokey=1\n<region>"},
{"<region> sample=a.wav /* c */\n", "<region> sample=a.wav /* c */ lokey=1\n"},
{"<region> sample=a.wav #include \"x\"\n", "<region> sample=a.wav lokey=1 #include \"x\"\n"},
{"<region> sample=a.wav /* open", "<region> sample=a.wav lokey=1 /* open"},
{"<region>\nstray\n", "<region>\nlokey=1\nstray\n"},
} {
doc := mustParse(t, tc.text, nil)
set(t, doc.Headers()[0], "lokey", "1")
if got := doc.String(); got != tc.want {
t.Errorf("%q\n got %q\nwant %q", tc.text, got, tc.want)
}
}
}
func TestSetRefusesBadValues(t *testing.T) {
text := "<region> sample=a.wav\n"
for _, value := range []string{"1\n<region>", "1 // c", "1 /* c", "1 hikey=2", "<group>", "1\r\n2"} {
doc := mustParse(t, text, nil)
if err := doc.Headers()[0].Set("lokey", value); !errors.Is(err, ErrInvalid) || doc.String() != text {
t.Errorf("%q: err %v, text %q", value, err, doc.String())
}
}
doc := mustParse(t, text, nil)
for _, name := range []string{"", "a b", "a=b", "lo\nkey", "<x>"} {
if err := doc.Headers()[0].Set(name, "1"); !errors.Is(err, ErrInvalid) || doc.String() != text {
t.Errorf("name %q: err %v, text %q", name, err, doc.String())
}
}
// A value may hold spaces and =.
set(t, doc.Headers()[0], "sample", " A=440 b.wav ")
if got := doc.String(); got != "<region> sample=A=440 b.wav\n" {
t.Errorf("got %q", got)
}
if err := doc.SetDefine("$X", "1\n2"); !errors.Is(err, ErrInvalid) {
t.Errorf("define err %v", err)
}
if err := doc.SetDefine("X", "1"); !errors.Is(err, ErrInvalid) {
t.Errorf("define name err %v", err)
}
if _, err := doc.AddHeader("a b", nil); !errors.Is(err, ErrInvalid) {
t.Errorf("header err %v", err)
}
if _, err := mustParse(t, "<region> x=1 /* open", nil).AddHeader("region", nil); !errors.Is(err, ErrInvalid) {
t.Errorf("header after open comment err %v", err)
}
}
func TestDeleteKeepsLines(t *testing.T) {
for _, tc := range []struct{ text, want string }{
{"<region>\n a=1\n b=2\n a=3 // x\n", "<region>\n b=2\n // x\n"},
{"<region> a=1 b=2 c=3\n", "<region> b=2 c=3\n"},
{"<region> x=1 // c\na=1 /* y */ b=2\n", "<region> x=1 // c\n/* y */ b=2\n"},
{"<region> x=1 // c\na=1", "<region> x=1 // c"},
} {
doc := mustParse(t, tc.text, nil)
doc.Headers()[0].Delete("a")
if got := doc.String(); got != tc.want {
t.Errorf("%q\n got %q\nwant %q", tc.text, got, tc.want)
}
}
}
// bigDocument is a document with n regions.
func bigDocument(t testing.TB, n int) *Document {
var b strings.Builder
for i := 0; i < n; i++ {
fmt.Fprintf(&b, "<region> sample=a%d.wav lokey=%d hikey=%d pitch_keycenter=%d lovel=1 hivel=127 tune=3 // %d\n", i, i%100, i%100, i%100, i)
}
doc, err := Parse(strings.NewReader(b.String()))
if err != nil {
t.Fatal(err)
}
return doc
}
// TestPositionsAfterEdits checks that lines and columns follow edits.
func TestPositionsAfterEdits(t *testing.T) {
doc := bigDocument(t, 50)
hs := doc.Headers()
for i := 0; i < 50; i += 2 {
set(t, hs[i], "volume", "-3")
hs[i].Delete("tune")
}
file := doc.Root
for _, h := range doc.Headers() {
line, col := file.Position(h.Node)
// Each region is one line, and a new volume opcode adds none.
if col != 1 || strings.Count(file.String()[:offsetOf(file, h.Node)], "\n")+1 != line {
t.Fatalf("header at %d:%d", line, col)
}
}
}
// offsetOf returns the byte offset of a node in its file's text.
func offsetOf(f *File, n *Node) int {
off := 0
for _, m := range f.Nodes {
if m == n {
return off
}
off += len(m.Raw)
}
return -1
}
// BenchmarkSet edits each region of a large document, the way a bulk change
// does.
func BenchmarkSet(b *testing.B) {
doc := bigDocument(b, 20000)
hs := doc.Headers()
b.ResetTimer()
for i := 0; i < b.N; i++ {
h := hs[i%len(hs)]
if err := h.Set("zz", strconv.Itoa(i)); err != nil {
b.Fatal(err)
}
if err := h.Set("lokey", strconv.Itoa(i)); err != nil {
b.Fatal(err)
}
}
}
+13 -14
View File
@@ -65,9 +65,10 @@ var controlSettings = []string{"default_path", "note_offset", "octave_offset"}
// target is where the opcodes after a header go. // target is where the opcodes after a header go.
type target struct { type target struct {
ops Opcodes ops Opcodes
// region is the header of a <region>, which becomes a region when the next // region is whether the header is a <region>, which becomes a region when
// header starts or the text ends. // the next header starts or the text ends, and line is where it is.
region *Node region bool
line int
file string file string
} }
@@ -100,12 +101,10 @@ func (f *flattener) variables(*File, *Node) {}
func (f *flattener) text(*File, *Node, string) {} func (f *flattener) text(*File, *Node, string) {}
func (f *flattener) header(file *File, n *Node, name string, variable bool) { func (f *flattener) header(file *File, n *Node, name string, variable bool) {
if variable { // A header that a variable made has no node of its own, so it takes the line
// The header has no node of its own, so it takes the line of the node that // of the node that made it.
// made it. line, _ := file.Position(n)
n = &Node{Name: name, Line: n.Line} f.startHeader(name, line, file.Path)
}
f.startHeader(n, file.Path)
} }
func (f *flattener) opcode(_ *File, _ *Node, name, value string, _ bool) { f.setOpcode(name, value) } func (f *flattener) opcode(_ *File, _ *Node, name, value string, _ bool) { f.setOpcode(name, value) }
@@ -113,7 +112,7 @@ func (f *flattener) opcode(_ *File, _ *Node, name, value string, _ bool) { f.set
// closeRegion adds the region being read, if any. A region takes the <control> // closeRegion adds the region being read, if any. A region takes the <control>
// settings made before it, which later <control> headers don't change. // settings made before it, which later <control> headers don't change.
func (f *flattener) closeRegion() { func (f *flattener) closeRegion() {
if f.into == nil || f.into.region == nil { if f.into == nil || !f.into.region {
return return
} }
control := Opcodes{} control := Opcodes{}
@@ -123,12 +122,12 @@ func (f *flattener) closeRegion() {
} }
} }
ops := control.with(f.levels[levelGlobal]).with(f.levels[levelMaster]).with(f.levels[levelGroup]).with(f.into.ops) ops := control.with(f.levels[levelGlobal]).with(f.levels[levelMaster]).with(f.levels[levelGroup]).with(f.into.ops)
f.flat.Regions = append(f.flat.Regions, FlatRegion{Opcodes: ops, File: f.into.file, Line: f.into.region.Line}) f.flat.Regions = append(f.flat.Regions, FlatRegion{Opcodes: ops, File: f.into.file, Line: f.into.line})
} }
func (f *flattener) startHeader(n *Node, file string) { func (f *flattener) startHeader(header string, line int, file string) {
f.closeRegion() f.closeRegion()
name := strings.ToLower(n.Name) name := strings.ToLower(header)
switch name { switch name {
case "control": case "control":
// A new <control> resets default_path, as ARIA does, but keeps the // A new <control> resets default_path, as ARIA does, but keeps the
@@ -151,7 +150,7 @@ func (f *flattener) startHeader(n *Node, file string) {
} }
f.into = &target{ops: f.levels[lvl], file: file} f.into = &target{ops: f.levels[lvl], file: file}
if lvl == levelRegion { if lvl == levelRegion {
f.into.region = n f.into.region, f.into.line = true, line
} }
} }
} }
+4 -1
View File
@@ -51,7 +51,7 @@ type lexer struct {
// add appends a node for the text from the current position to end. // add appends a node for the text from the current position to end.
func (l *lexer) add(src string, end int, n *Node) { func (l *lexer) add(src string, end int, n *Node) {
n.Raw = src[l.pos:end] n.Raw = src[l.pos:end]
n.Line, n.Col = l.line, l.pos-l.lineStart+1 n.line, n.col = l.line, l.pos-l.lineStart+1
if n.Kind == KindText && len(l.nodes) > 0 { if n.Kind == KindText && len(l.nodes) > 0 {
if last := l.nodes[len(l.nodes)-1]; last.Kind == KindText { if last := l.nodes[len(l.nodes)-1]; last.Kind == KindText {
// Nodes tile the text, so the two are one run of it. // Nodes tile the text, so the two are one run of it.
@@ -129,6 +129,9 @@ func lex(src string) []*Node {
l.add(src, i+size, &Node{Kind: KindText}) l.add(src, i+size, &Node{Kind: KindText})
} }
} }
for i, n := range l.nodes {
n.idx = i
}
return l.nodes return l.nodes
} }
+2 -1
View File
@@ -223,8 +223,9 @@ func (p *parser) file(name string, data []byte, depth int) (*File, error) {
if p.includes == IncludesFail { if p.includes == IncludesFail {
return nil, fmt.Errorf("%w: %s: %w", ErrUnresolved, n.Resolved, err) return nil, fmt.Errorf("%w: %s: %w", ErrUnresolved, n.Resolved, err)
} }
line, col := f.Position(n)
p.problems = append(p.problems, Problem{ p.problems = append(p.problems, Problem{
File: name, Line: n.Line, Col: n.Col, Severity: SeverityWarning, File: name, Line: line, Col: col, Severity: SeverityWarning,
Code: "include.unresolved", Msg: fmt.Sprintf("can't read %s: %v", n.Resolved, err), Code: "include.unresolved", Msg: fmt.Sprintf("can't read %s: %v", n.Resolved, err),
}) })
continue continue
+44 -6
View File
@@ -207,24 +207,59 @@ func FuzzWrite(f *testing.F) {
}) })
} }
// FuzzEdit checks that editing any document doesn't panic, and keeps the // significant returns the kind and text of the nodes of a file that aren't
// layout it didn't change. // whitespace.
func significant(nodes []*Node) []string {
var out []string
for _, n := range nodes {
if n.Kind != KindSpace {
out = append(out, n.Kind.String()+":"+n.Raw)
}
}
return out
}
// FuzzEdit checks that editing any document doesn't panic, that what is
// written reads back as the nodes that were edited, and that an edit that
// is refused changes nothing.
func FuzzEdit(f *testing.F) { func FuzzEdit(f *testing.F) {
for _, text := range roundTripTexts { for _, text := range roundTripTexts {
f.Add(text, "lokey", "60") f.Add(text, "lokey", "60")
} }
f.Add("<region> sample=a.wav // c\n", "hikey", "3")
f.Add("<region> sample=a.wav", "x", "1\n<region>")
f.Fuzz(func(t *testing.T, text, name, value string) { f.Fuzz(func(t *testing.T, text, name, value string) {
doc, err := Parse(strings.NewReader(text)) doc, err := Parse(strings.NewReader(text))
if err != nil { if err != nil {
t.Skip() t.Skip()
} }
check := func(what string) {
for _, file := range doc.Files() {
if got, want := significant(lex(file.String())), significant(file.Nodes); !reflect.DeepEqual(got, want) {
t.Fatalf("%s: wrote %q, which reads as %q, not %q", what, file.String(), got, want)
}
}
}
for _, h := range doc.Headers() { for _, h := range doc.Headers() {
h.Set(name, value) before := doc.String()
if err := h.Set(name, value); err != nil {
if doc.String() != before {
t.Fatalf("refused Set changed the text to %q", doc.String())
}
continue
}
check("Set")
h.Get(name) h.Get(name)
h.Delete(name) h.Delete(name)
check("Delete")
}
if h, err := doc.AddHeader("region", nil); err == nil {
h.Set(name, value)
check("AddHeader")
}
if err := doc.SetDefine("$X", value); err == nil {
check("SetDefine")
} }
doc.AddHeader("region", nil).Set(name, value)
doc.SetDefine("$X", value)
doc.Flatten() doc.Flatten()
doc.Validate() doc.Validate()
for _, f := range doc.Files() { for _, f := range doc.Files() {
@@ -253,7 +288,10 @@ func FuzzBuild(f *testing.F) {
for _, opts := range []BuildOptions{{}, {Variables: true, MinRepeat: 1}, {SplitFiles: true, RegionsPerFile: 1}} { for _, opts := range []BuildOptions{{}, {Variables: true, MinRepeat: 1}, {SplitFiles: true, RegionsPerFile: 1}} {
built, err := Build(inst, opts) built, err := Build(inst, opts)
if err != nil { if err != nil {
t.Fatal(err) if !errors.Is(err, ErrInvalid) {
t.Fatal(err)
}
continue
} }
built.Validate() built.Validate()
built.Flatten().Instrument() built.Flatten().Instrument()
+4
View File
@@ -0,0 +1,4 @@
go test fuzz v1
string("<A>0")
string("0")
string("0")
+4
View File
@@ -0,0 +1,4 @@
go test fuzz v1
string("<A>0=/*")
string("1")
string("0")
+17 -16
View File
@@ -25,7 +25,7 @@ func (d *Document) Validate() []Problem {
type opcodeAt struct { type opcodeAt struct {
value float64 value float64
at *Node at *Node
file string file *File
} }
// known is the result of a [Lookup]. // known is the result of a [Lookup].
@@ -48,8 +48,9 @@ type validator struct {
numbers map[string]opcodeAt numbers map[string]opcodeAt
} }
func (v *validator) add(file string, n *Node, sev Severity, code, msg string) { func (v *validator) add(f *File, 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}) line, col := f.Position(n)
v.problems = append(v.problems, Problem{File: f.Path, Line: line, Col: col, Severity: sev, Code: code, Msg: msg})
} }
func (v *validator) define(f *File, n *Node) { v.undefined(f, n, n.Value) } func (v *validator) define(f *File, n *Node) { v.undefined(f, n, n.Value) }
@@ -57,7 +58,7 @@ func (v *validator) define(f *File, n *Node) { v.undefined(f, n, n.Value) }
func (v *validator) include(f *File, n *Node) { func (v *validator) include(f *File, n *Node) {
v.undefined(f, n, n.Value) v.undefined(f, n, n.Value)
if n.Resolved != "" && !fs.ValidPath(n.Resolved) { 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)) v.add(f, n, SeverityWarning, "include.outside", fmt.Sprintf("%s is outside the folder of the main file", n.Resolved))
} }
} }
@@ -67,7 +68,7 @@ func (v *validator) text(f *File, n *Node, raw string) {
if strings.Contains(raw, "$") { if strings.Contains(raw, "$") {
return return
} }
v.add(f.Path, n, SeverityWarning, "text.unreadable", fmt.Sprintf("can't read %q", strings.TrimSpace(raw))) v.add(f, n, SeverityWarning, "text.unreadable", fmt.Sprintf("can't read %q", strings.TrimSpace(raw)))
} }
func (v *validator) header(f *File, n *Node, name string, _ bool) { func (v *validator) header(f *File, n *Node, name string, _ bool) {
@@ -75,7 +76,7 @@ func (v *validator) header(f *File, n *Node, name string, _ bool) {
v.inHeader = true v.inHeader = true
v.numbers = map[string]opcodeAt{} v.numbers = map[string]opcodeAt{}
if _, ok := LookupHeader(name); !ok { if _, ok := LookupHeader(name); !ok {
v.add(f.Path, n, SeverityInfo, "header.unknown", fmt.Sprintf("<%s> isn't a header of the format", name)) v.add(f, n, SeverityInfo, "header.unknown", fmt.Sprintf("<%s> isn't a header of the format", name))
} }
} }
@@ -102,7 +103,7 @@ func (v *validator) endHeader() {
func (v *validator) opcode(f *File, n *Node, name, value string, _ bool) { func (v *validator) opcode(f *File, n *Node, name, value string, _ bool) {
if !v.inHeader { if !v.inHeader {
v.add(f.Path, n, SeverityInfo, "opcode.no-header", fmt.Sprintf("%s is before any header", name)) v.add(f, n, SeverityInfo, "opcode.no-header", fmt.Sprintf("%s is before any header", name))
v.inHeader = true v.inHeader = true
v.numbers = map[string]opcodeAt{} v.numbers = map[string]opcodeAt{}
} }
@@ -116,17 +117,17 @@ func (v *validator) opcode(f *File, n *Node, name, value string, _ bool) {
} }
info, ok := k.info, k.ok info, ok := k.info, k.ok
if !ok { if !ok {
v.add(f.Path, n, SeverityInfo, "opcode.unknown", fmt.Sprintf("%s isn't an opcode of the format", name)) v.add(f, n, SeverityInfo, "opcode.unknown", fmt.Sprintf("%s isn't an opcode of the format", name))
return return
} }
if info.Deprecated { if info.Deprecated {
v.add(f.Path, n, SeverityInfo, "opcode.deprecated", fmt.Sprintf("%s is deprecated", name)) v.add(f, n, SeverityInfo, "opcode.deprecated", fmt.Sprintf("%s is deprecated", name))
} }
if strings.Contains(value, "$") { if strings.Contains(value, "$") {
return return
} }
if (name == "sample" || name == "default_path") && outsideFolder(value) { if (name == "sample" || name == "default_path") && outsideFolder(value) {
v.add(f.Path, n, SeverityInfo, "sample.outside", fmt.Sprintf("%s=%s is outside the folder of the main file", name, value)) v.add(f, n, SeverityInfo, "sample.outside", fmt.Sprintf("%s=%s is outside the folder of the main file", name, value))
} }
v.value(f, n, name, value, info) v.value(f, n, name, value, info)
} }
@@ -148,16 +149,16 @@ func (v *validator) value(f *File, n *Node, name, value string, info OpcodeInfo)
x, ok = parseNumber(value) x, ok = parseNumber(value)
} }
if !ok { if !ok {
v.add(f.Path, n, SeverityWarning, "value.type", fmt.Sprintf("%s=%s isn't a number", name, value)) v.add(f, n, SeverityWarning, "value.type", fmt.Sprintf("%s=%s isn't a number", name, value))
return return
} }
if info.Type == TypeInteger && !info.Note && x != float64(int64(x)) { if info.Type == TypeInteger && !info.Note && x != float64(int64(x)) {
v.add(f.Path, n, SeverityInfo, "value.type", fmt.Sprintf("%s=%s isn't a whole number", name, value)) v.add(f, n, SeverityInfo, "value.type", fmt.Sprintf("%s=%s isn't a whole number", name, value))
} }
if info.Min != nil && x < *info.Min || info.Max != nil && x > *info.Max { if info.Min != nil && x < *info.Min || info.Max != nil && x > *info.Max {
v.add(f.Path, n, SeverityWarning, "value.range", fmt.Sprintf("%s=%s is outside %s", name, value, bounds(info))) v.add(f, n, SeverityWarning, "value.range", fmt.Sprintf("%s=%s is outside %s", name, value, bounds(info)))
} }
v.numbers[name] = opcodeAt{value: x, at: n, file: f.Path} v.numbers[name] = opcodeAt{value: x, at: n, file: f}
case TypeString: case TypeString:
if len(info.Options) == 0 { if len(info.Options) == 0 {
return return
@@ -167,7 +168,7 @@ func (v *validator) value(f *File, n *Node, name, value string, info OpcodeInfo)
return return
} }
} }
v.add(f.Path, n, SeverityWarning, "value.option", fmt.Sprintf("%s=%s isn't one of %s", name, value, strings.Join(info.Options, ", "))) v.add(f, n, SeverityWarning, "value.option", fmt.Sprintf("%s=%s isn't one of %s", name, value, strings.Join(info.Options, ", ")))
} }
} }
@@ -186,7 +187,7 @@ func bounds(info OpcodeInfo) string {
// undefined reports the variables in text that haven't been defined. // undefined reports the variables in text that haven't been defined.
func (v *validator) undefined(f *File, n *Node, text string) { func (v *validator) undefined(f *File, n *Node, text string) {
for _, run := range v.defs.undefined(text) { for _, run := range v.defs.undefined(text) {
v.add(f.Path, n, SeverityWarning, "define.undefined", fmt.Sprintf("%s isn't defined", run)) v.add(f, n, SeverityWarning, "define.undefined", fmt.Sprintf("%s isn't defined", run))
} }
} }