Files
sfz/document.go
aneurinandClaude Sonnet 5.5 158661eefe Rewrite the code comments for consistent tone and accuracy
Comments only: the tokens of every Go file are unchanged.

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

203 lines
6.1 KiB
Go

// Package sfz reads, validates, edits and writes SFZ instruments: text files
// that map samples to keys, velocities and playback settings. It handles SFZ v1
// and v2 with the ARIA extensions as data. It doesn't play instruments or load
// samples.
//
// A [Document] keeps a file exactly as written, including comments, spacing,
// unknown opcodes, and #define and #include directives, so that a document
// that hasn't been edited is written as the text it was read from.
// [Document.Flatten] resolves directives and header inheritance into regions,
// and [Flat.Instrument] reads those into a typed model. [Instrument.Apply]
// writes a change to a typed region back to the document as changes to the
// region's own opcodes.
package sfz
import (
"errors"
"fmt"
"io"
"strings"
)
// The errors that the package returns, directly or wrapped.
var (
// ErrInvalid is returned for text that can't be read as an instrument, and
// for an edit or an output that can't be written as SFZ.
ErrInvalid = errors.New("invalid SFZ")
// ErrIncludeLoop is returned when a file includes itself, directly or
// through the files it includes.
ErrIncludeLoop = errors.New("include loop")
// ErrUnresolved is returned, with [IncludesFail], for an include that can't
// be read.
ErrUnresolved = errors.New("unresolved include")
)
// NodeKind is what a [Node] holds.
type NodeKind int
// The kinds of node.
const (
// KindSpace is a run of whitespace.
KindSpace NodeKind = iota
// KindComment is a // or /* */ comment.
KindComment
// KindHeader is a header such as <region>.
KindHeader
// KindOpcode is an opcode and its value, such as lokey=60.
KindOpcode
// KindDefine is a #define directive.
KindDefine
// KindInclude is an #include directive.
KindInclude
// KindText is text that isn't any of the above, such as a directive that
// can't be read.
KindText
)
// String returns the kind's name.
func (k NodeKind) String() string {
switch k {
case KindSpace:
return "space"
case KindComment:
return "comment"
case KindHeader:
return "header"
case KindOpcode:
return "opcode"
case KindDefine:
return "define"
case KindInclude:
return "include"
}
return "text"
}
// Node is one piece of a file. The raw text of a file's nodes, in order, is the
// file's text.
type Node struct {
// Kind is what the node holds, and so which of the other fields are set.
Kind NodeKind
// Raw is the node's text as written.
Raw string
// Name is a header's name without its brackets, as written, an opcode's
// name, or a define's variable name with its $. Other nodes have none.
Name string
// Value is an opcode's or a define's value without surrounding whitespace,
// or an include's path as written.
Value string
// Resolved is an include's path with its variables substituted, with
// forward slashes, relative to the folder of the main file.
Resolved string
// File is the file an include reads, or nil if it wasn't read.
File *File
// line and col are where the node starts, from 1, with col in bytes, as of
// the last time its 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. Edits move a node only a short way from there.
idx int
}
// File is one file of a document: the main file or an included one.
type File struct {
// Path is the file's path relative to the folder of the main file, with
// forward slashes. For the main file of a document read with [Parse], which
// has no name, it is empty.
Path string
// Nodes are the file's nodes, in order.
Nodes []*Node
// dirty is whether edits have moved nodes since their lines and columns were
// last worked out.
dirty bool
}
// String returns the file's text.
func (f *File) String() string {
var b strings.Builder
for _, n := range f.Nodes {
b.WriteString(n.Raw)
}
return b.String()
}
// Document is an instrument as written: a main file and the files it
// includes.
type Document struct {
// Root is the main file.
Root *File
// problems are the problems found while parsing.
problems []Problem
}
// WriteTo writes the main file's text to w, or returns [ErrInvalid] if the
// document has includes that were read, as the text would not hold the files
// they read. Use [Document.Write] or [Document.WriteFiles] for those.
func (d *Document) WriteTo(w io.Writer) (int64, error) {
if d.hasIncludes() {
return 0, fmt.Errorf("%w: the document has includes, which need Write with InlineIncludes, or WriteFiles", ErrInvalid)
}
n, err := io.WriteString(w, d.Root.String())
return int64(n), err
}
// String returns the main file's text.
func (d *Document) String() string { return d.Root.String() }
// Files returns the main file and the files it includes, in the order they are
// read. A file that is included more than once is returned once for each time,
// as each is read with the variables defined at that point.
func (d *Document) Files() []*File {
var out []*File
var walk func(f *File)
walk = func(f *File) {
out = append(out, f)
for _, n := range f.Nodes {
if n.Kind == KindInclude && n.File != nil {
walk(n.File)
}
}
}
walk(d.Root)
return out
}
// Severity is how serious a [Problem] is.
type Severity int
// The severities.
const (
// SeverityInfo is something unusual that is allowed.
SeverityInfo Severity = iota
// SeverityWarning is something that is probably a mistake.
SeverityWarning
// SeverityError is something that makes the instrument unreadable.
SeverityError
)
// String returns the severity's name.
func (s Severity) String() string {
switch s {
case SeverityInfo:
return "info"
case SeverityWarning:
return "warning"
}
return "error"
}
// Problem is something found in a document that its writer may want to fix.
type Problem struct {
// File is the path of the file, as in [File.Path].
File string
// Line and Col are where the problem is, from 1.
Line, Col int
// Severity is how serious the problem is.
Severity Severity
// Code is a short stable name for the kind of problem, such as
// "include.unresolved".
Code string
// Msg describes the problem for a person to read.
Msg string
}