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
+200 -75
View File
@@ -1,6 +1,10 @@
package sfz
import "strings"
import (
"fmt"
"slices"
"strings"
)
// 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
@@ -15,20 +19,30 @@ type Header struct {
// Name returns the header's name without brackets, as written.
func (h *Header) Name() string { return h.Node.Name }
// index returns where the header's node is in its file.
func (h *Header) index() int {
for i, n := range h.File.Nodes {
if n == h.Node {
return i
// indexOf returns where a node is in the file, or -1. A node remembers where it
// was, which stays close to where it is after edits, so the search starts
// there.
func (f *File) indexOf(n *Node) int {
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
// next header.
func (h *Header) span() (start, end int) {
start = h.index() + 1
start = h.File.indexOf(h.Node) + 1
end = start
for end < len(h.File.Nodes) && h.File.Nodes[end].Kind != KindHeader {
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
// takes effect.
func (h *Header) Get(name string) (*Node, bool) {
ops := h.Opcodes()
for i := len(ops) - 1; i >= 0; i-- {
if ops[i].Name == name {
return ops[i], true
start, end := h.span()
for i := end - 1; i >= start; i-- {
if n := h.File.Nodes[i]; n.Kind == KindOpcode && n.Name == name {
return n, true
}
}
return nil, false
}
// Set gives the opcode a value. 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, laid out as that
// one is.
func (h *Header) Set(name, value string) {
if n, ok := h.Get(name); ok {
n.Raw = name + "=" + value
n.Value = strings.TrimSpace(value)
h.File.reposition()
return
// checkOpcode returns an error if name=value wouldn't be read back as one
// opcode with that value, as when the value holds a line break, a comment, or
// another opcode.
func checkOpcode(name, value string) error {
text := name + "=" + value
nodes := lex(text)
if len(nodes) > 0 && nodes[0].Kind == KindOpcode && nodes[0].Name == name && nodes[0].Value == strings.TrimSpace(value) &&
nodes[0].Raw == text && onlySpace(nodes[1:]) {
return nil
}
start, end := h.span()
at := start
sep := ""
for i := start; i < end; i++ {
if h.File.Nodes[i].Kind == KindOpcode {
at = i + 1
return fmt.Errorf("%w: %s=%q can't be written as one opcode", ErrInvalid, name, value)
}
// checkDefine returns an error if the text of a #define of name with value
// wouldn't be read back as that directive.
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 {
// With no opcode to follow, the new one goes after the header, on its
// own line if the header is.
return true
}
// 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 = " "
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
@@ -89,18 +143,58 @@ func (h *Header) Set(name, value string) {
sep = "\n"
}
} else {
at = last + 1
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
} else if strings.Contains(h.File.String(), "\n") {
} else if h.File.hasLineBreak() {
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{
{Kind: KindSpace, Raw: sep},
{Kind: KindOpcode, Raw: name + "=" + value, Name: name, Value: strings.TrimSpace(value)},
inserted := append([]*Node{{Kind: KindSpace, Raw: sep}}, nodes...)
// A value runs to the end of its line unless a header, opcode, comment or
// 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
@@ -111,38 +205,56 @@ func (h *Header) Delete(name string) {
if !ok {
return
}
i := indexOf(h.File.Nodes, n)
from := i
if i > 0 && h.File.Nodes[i-1].Kind == KindSpace {
i := h.File.indexOf(n)
from, to := i, i+1
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
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.reposition()
h.File.Nodes = slices.Delete(h.File.Nodes, from, to)
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.
func (f *File) insert(at int, nodes ...*Node) {
f.Nodes = append(f.Nodes[:at], append(nodes, f.Nodes[at:]...)...)
f.reposition()
f.Nodes = slices.Insert(f.Nodes, at, nodes...)
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() {
line, col := 1, 1
for _, n := range f.Nodes {
n.Line, n.Col = line, col
for i := 0; i < len(n.Raw); i++ {
if n.Raw[i] == '\n' {
for i, n := range f.Nodes {
n.line, n.col, n.idx = line, col, i
for j := 0; j < len(n.Raw); j++ {
if n.Raw[j] == '\n' {
line++
col = 1
} 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
@@ -168,13 +281,24 @@ func (d *Document) Headers() []*Header {
// 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.
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
at := len(f.Nodes)
if after != nil {
f = after.File
_, 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
if at > 0 && !strings.HasSuffix(f.Nodes[at-1].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}
nodes = append(nodes, h, &Node{Kind: KindSpace, Raw: "\n"})
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.
@@ -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
// 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
// includes its $.
func (d *Document) SetDefine(name, value string) {
for _, n := range d.Defines() {
if n.Name == name {
n.Raw = "#define " + name + " " + value
n.Value = value
d.reposition()
return
// includes its $. It returns an error wrapping [ErrInvalid], and changes
// nothing, if the name or value can't be written as a #define.
func (d *Document) SetDefine(name, value string) error {
value = strings.TrimSpace(value)
if err := checkDefine(name, value); err != nil {
return err
}
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,
&Node{Kind: KindDefine, Raw: "#define " + name + " " + value, Name: name, Value: value},
&Node{Kind: KindSpace, Raw: "\n"})
}
// reposition sets the positions of every file's nodes.
func (d *Document) reposition() {
for _, f := range d.Files() {
f.reposition()
}
return nil
}