Files
sfz/structure.go
T
aneurinandClaude Sonnet 5.5 8db34cc16c Check the text of structural edits and refuse stale instruments
AddRegion, RemoveRegion and MoveRegion now refuse an edit whose written text
would read differently from the nodes, as when a comment that never ends
takes in the text after it, and an instrument whose regions were changed
other than by Apply. Build refuses an unknown trigger and an empty random
range. Add tests for edits across files, defines, skipped regions and edge
cases, a random-sequence test and FuzzRegionEdits.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 01:26:36 +00:00

238 lines
8.5 KiB
Go

package sfz
import (
"errors"
"fmt"
"slices"
"strings"
)
// Source returns the flattened region that typed region i was read from, with
// its header, or false if there is no region i. The header is nil if a variable
// made it. The result is only good until the next [Instrument.AddRegion],
// [Instrument.RemoveRegion] or [Instrument.MoveRegion], which read the
// instrument again.
func (inst *Instrument) Source(i int) (*FlatRegion, bool) {
if i < 0 || i >= len(inst.sources) {
return nil, false
}
return &inst.sources[i], true
}
// AddRegion adds a <region> for r at the end of the document that the
// instrument was read from, and makes it the last of the instrument's regions.
// It writes only the opcodes that differ from the format's defaults if they
// read back as r, and every opcode if the headers above it need to be
// overridden. It changes nothing, and returns an error, if r can't be written
// so that it reads back as r: [ErrInvalid] if r or its sample can't be written
// as it is, [ErrUnpatchable] if the headers above the new region or a
// default_path change it, and [ErrNoSource] if the instrument wasn't read from
// a document.
//
// Afterwards the instrument is as the document reads, with Skipped, Unread and
// Controls too. It returns an error wrapping [ErrNoSource], and changes nothing,
// if the document was edited since the instrument was read, or the instrument's
// regions were changed other than with [Instrument.Apply]. Use [Instrument.Source] to set opcodes the typed model doesn't
// hold on the new region's header.
func (inst *Instrument) AddRegion(r Region) error {
if err := checkRegion(r); err != nil {
return fmt.Errorf("%w: %w", ErrInvalid, err)
}
var err error
for _, all := range []bool{false, true} {
err = inst.restructure(
func() error { return inst.writeRegion(r, all) },
func(old []Region) []Region { return append(slices.Clone(old), r) })
if !errors.Is(err, ErrUnpatchable) {
return err
}
}
return err
}
// writeRegion adds a <region> for r at the end of the main file. It writes the
// opcodes that the format's defaults would give too if all is set.
func (inst *Instrument) writeRegion(r Region, all bool) error {
defaultPath := strings.ReplaceAll(strings.TrimSpace(inst.doc.Flatten().Control["default_path"]), `\`, "/")
h, err := inst.doc.AddHeader("region", nil)
if err != nil {
return err
}
for _, l := range regionLines(r, all) {
value := l.value
if l.field == "Sample" {
// The sample is read as relative to default_path.
value = strings.TrimPrefix(value, defaultPath)
}
if err := checkOpcode(l.name, value); err != nil {
return err
}
if err := h.Set(l.name, value); err != nil {
return err
}
}
return nil
}
// RemoveRegion removes region i from the document that the instrument was read
// from, with the comments and spacing that follow its header. A comment on the
// lines above a <region> follows the header before it, so it isn't removed
// with the region it is above. It changes
// nothing, and returns an error, if the document can't be edited there: an
// error wrapping [ErrNoSource] if there is no region i or it has no header of
// its own to remove. Afterwards the instrument is as the document reads.
func (inst *Instrument) RemoveRegion(i int) error {
src, err := inst.source(i)
if err != nil {
return err
}
return inst.restructure(
func() error {
f := src.Header.File
start, end := src.Header.span()
f.Nodes = slices.Delete(f.Nodes, start-1, end)
f.dirty = true
return nil
},
func(old []Region) []Region { return slices.Delete(slices.Clone(old), i, i+1) })
}
// MoveRegion moves region from in the document that the instrument was read
// from so that it is region to, with the comments and spacing that follow its
// header, as for [Instrument.RemoveRegion]. The regions between keep their
// order, and so do the regions the typed
// model has no region for. It changes nothing, and returns an error, if the
// document can't be edited there: an error wrapping [ErrNoSource] if either
// region has no header of its own to move, and [ErrUnpatchable] if the headers
// above the new place would change the region, as when it moves into another
// <group>. Afterwards the instrument is as the document reads.
func (inst *Instrument) MoveRegion(from, to int) error {
src, err := inst.source(from)
if err != nil {
return err
}
dst, err := inst.source(to)
if err != nil {
return err
}
if from == to {
return nil
}
return inst.restructure(
func() error {
f := src.Header.File
start, end := src.Header.span()
moved := slices.Clone(f.Nodes[start-1 : end])
f.Nodes = slices.Delete(f.Nodes, start-1, end)
f.dirty = true
g := dst.Header.File
at := g.indexOf(dst.Header.Node)
if from < to {
_, at = dst.Header.span()
}
insertNodes(g, at, moved)
return nil
},
func(old []Region) []Region {
out := slices.Delete(slices.Clone(old), from, from+1)
return slices.Insert(out, to, old[from])
})
}
// insertNodes inserts the nodes of whole lines into a file at a node index,
// with a line break before or after them if the text around them lacks one.
func insertNodes(f *File, at int, nodes []*Node) {
if at > 0 && !strings.HasSuffix(f.Nodes[at-1].Raw, "\n") {
nodes = append([]*Node{{Kind: KindSpace, Raw: "\n"}}, nodes...)
}
if at < len(f.Nodes) && !strings.HasSuffix(nodes[len(nodes)-1].Raw, "\n") {
nodes = append(nodes, &Node{Kind: KindSpace, Raw: "\n"})
}
f.insert(at, nodes...)
}
// restructure edits the instrument's document with change, and then reads the
// document again. The edit stands if the regions read from it are those that
// want makes from the regions the document had before, and the instrument then
// becomes what the document reads as. Otherwise the document is as it was, and
// the error wraps [ErrUnpatchable] if the edit changed what the regions are.
func (inst *Instrument) restructure(change func() error, want func(old []Region) []Region) error {
if inst.doc == nil {
return fmt.Errorf("%w: the instrument wasn't read from a document", ErrNoSource)
}
before := inst.doc.Flatten().Instrument()
if !inst.matches(before) {
return fmt.Errorf("%w: the document or the instrument has changed since the instrument was read, so read it again", ErrNoSource)
}
saved := map[*File][]*Node{}
for _, f := range inst.doc.Files() {
saved[f] = slices.Clone(f.Nodes)
}
undo := func() {
for f, nodes := range saved {
f.Nodes = nodes
f.dirty = true
}
}
if err := change(); err != nil {
undo()
return err
}
// The text that is written has to read back as the nodes, which it doesn't
// when a comment that never ends, or a line comment, would take in the text
// that comes after it.
for _, f := range inst.doc.Files() {
if !slices.Equal(significantNodes(lex(f.String())), significantNodes(f.Nodes)) {
undo()
return fmt.Errorf("%w: the text of %q would read differently from the nodes", ErrUnpatchable, f.Path)
}
}
after := inst.doc.Flatten().Instrument()
expected := want(before.Regions)
if len(after.Regions) != len(expected) {
undo()
return fmt.Errorf("%w: the document would read as %d regions, not %d", ErrUnpatchable, len(after.Regions), len(expected))
}
for i := range expected {
if wrong := differing(after.Regions[i], expected[i]); len(wrong) > 0 {
undo()
return fmt.Errorf("%w: region %d would read differently: %s", ErrUnpatchable, i, strings.Join(wrong, ", "))
}
}
inst.Regions, inst.sources, inst.eval = after.Regions, after.sources, after.eval
inst.Unread, inst.Skipped, inst.Controls, inst.Keyswitches = after.Unread, after.Skipped, after.Controls, after.Keyswitches
return nil
}
// significantNodes returns the kind and text of the nodes that aren't
// whitespace.
func significantNodes(nodes []*Node) []string {
var out []string
for _, n := range nodes {
if n.Kind != KindSpace {
out = append(out, n.Kind.String()+":"+n.Raw)
}
}
return out
}
// matches reports whether other, read from the instrument's document, has the
// regions that the instrument holds, from the same headers. An instrument whose
// regions were changed other than by [Instrument.Apply] doesn't match, as
// reading it again would lose the change.
func (inst *Instrument) matches(other *Instrument) bool {
if len(inst.sources) != len(other.sources) || len(inst.Regions) != len(other.Regions) {
return false
}
for i, s := range inst.sources {
o := other.sources[i]
if (s.Header == nil) != (o.Header == nil) || s.Header != nil && s.Header.Node != o.Header.Node {
return false
}
if len(differing(inst.Regions[i], other.Regions[i])) > 0 {
return false
}
}
return true
}