Files
sfz/lex.go
T
aneurinandClaude Sonnet 5.5 8134660721 Fix the differences from the spec and sfizz that a conformance review found
Read opcodes under their other names. The registry lists the other names an
opcode has, and the typed model now reads each under its own name: amp_release
for ampeg_release, offby, bendup, tune_keytrack and the rest. Apply treats an
old name as belonging to the same field, so it doesn't leave one behind.

Cut a #define's value at the first space, as ARIA and sfizz do, so that two
defines can share a line. Before, the first define took the rest of the line,
and a kit that writes "#define $lo 1  #define $hi 25" lost its velocity layers.

Ignore opcodes before any header when flattening, as sfizz does, and report
them as a warning. Included files that hold only opcodes are not affected.

Read the limits of a controller the same way each time. A region that sets
lohdccN and inherits loccN took whichever the map gave first, so Apply's change
could read back as the old limits. The hdcc opcodes now win.

Accept -1 for lokey, hikey and key, which SFZ v2 allows, and don't report a
region with a hikey of -1 as an inverted range.

Cut numbers that don't fit to what a setting can hold, so offset=1e30 doesn't
turn negative, and ignore a controller number or octave that overflows.

Read polyphony=legato_high, legato_last and legato_low as a limit of 1.

Put a new #define after a byte order mark.

Mark in the tests where each expected value comes from, correct the tags that
the spec doesn't support, and add tests for each of these.

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

181 lines
5.9 KiB
Go

package sfz
import (
"regexp"
"strings"
"unicode/utf8"
)
var (
// headerRE reads a header at the start of the text.
headerRE = regexp.MustCompile(`^<([A-Za-z_]+)>`)
// opcodeRE reads an opcode's name and = at the start of the text.
opcodeRE = regexp.MustCompile(`^([A-Za-z0-9_$]+)=`)
// defineRE reads a #define's variable and the rest of its line, whose first
// word is the value.
defineRE = regexp.MustCompile(`^#define[ \t]+(\$[A-Za-z0-9_]{1,128})[ \t]+([^\r\n]*)`)
// includeRE reads an #include's quoted path.
includeRE = regexp.MustCompile(`^#include[ \t]+"([^"\r\n]*)"`)
// breakRE finds where an opcode's value ends: at a header, the next
// opcode after whitespace, a comment, a directive after whitespace, or the
// end of the line, so that a value can hold spaces and = signs, as a
// sample's path can.
breakRE = regexp.MustCompile(`<[A-Za-z_]+>|\s[A-Za-z0-9_$]+=|//|/\*|\s#(?:define|include)\b|\n`)
)
// byteOrderMark is the UTF-8 mark that some editors put at the start of a file.
// The lexer reads it as space.
const byteOrderMark = "\ufeff"
// atLineStart reports whether a directive may start at offset i of src, which
// is so at the start of the text, after the byte order mark, and after
// whitespace.
func atLineStart(src string, i int) bool {
return i == 0 || isSpace(src[i-1]) || i == len(byteOrderMark) && strings.HasPrefix(src, byteOrderMark)
}
// isSpace reports whether c is whitespace.
func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n' }
// isNameChar reports whether c may be in the name of an opcode or a variable.
func isNameChar(c byte) bool {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '$'
}
// lexer cuts text into nodes and keeps count of the position.
type lexer struct {
// nodes are the nodes cut so far.
nodes []*Node
// line is the line the next node starts on, from 1.
line int
// lineStart is the offset where the current line starts.
lineStart int
// pos is the offset the next node starts at.
pos int
}
// add gives n the text from the current position to end, and appends it, or
// extends the node before it if both are text.
func (l *lexer) add(src string, end int, n *Node) {
n.Raw = src[l.pos:end]
n.line, n.col = l.line, l.pos-l.lineStart+1
if n.Kind == KindText && len(l.nodes) > 0 {
if last := l.nodes[len(l.nodes)-1]; last.Kind == KindText {
// Nodes tile the text, so the two are one run of it.
last.Raw = src[l.pos-len(last.Raw) : end]
l.advance(src, end)
return
}
}
l.nodes = append(l.nodes, n)
l.advance(src, end)
}
// advance moves the position to end, counting the lines it passes.
func (l *lexer) advance(src string, end int) {
for i := l.pos; i < end; i++ {
if src[i] == '\n' {
l.line++
l.lineStart = i + 1
}
}
l.pos = end
}
// lex cuts text into nodes whose raw text, joined, is the text. Text that
// isn't a space, comment, header, opcode or directive is kept as text nodes,
// so that any text can be lexed.
func lex(src string) []*Node {
l := &lexer{line: 1}
for l.pos < len(src) {
i := l.pos
rest := src[i:]
switch {
case isSpace(src[i]) || i == 0 && strings.HasPrefix(src, byteOrderMark):
// A byte order mark and the whitespace after it make one space node.
j := i
if i == 0 && strings.HasPrefix(src, byteOrderMark) {
j = len(byteOrderMark)
}
for j < len(src) && isSpace(src[j]) {
j++
}
l.add(src, j, &Node{Kind: KindSpace})
case strings.HasPrefix(rest, "//"):
j := len(src)
if e := strings.IndexByte(rest, '\n'); e >= 0 {
j = i + e
}
l.add(src, j, &Node{Kind: KindComment})
case strings.HasPrefix(rest, "/*"):
j := len(src)
if e := strings.Index(rest[2:], "*/"); e >= 0 {
j = i + 2 + e + 2
}
l.add(src, j, &Node{Kind: KindComment})
case src[i] == '<' && headerRE.MatchString(rest):
m := headerRE.FindStringSubmatch(rest)
l.add(src, i+len(m[0]), &Node{Kind: KindHeader, Name: m[1]})
case src[i] == '#' && atLineStart(src, i) && l.directive(src):
// The directive is added by the call that tests for it.
case opcodeRE.MatchString(rest):
// A value runs to the next break, or to the end of the text.
m := opcodeRE.FindStringSubmatch(rest)
valueStart := i + len(m[0])
end := len(src)
if loc := breakRE.FindStringIndex(src[valueStart:]); loc != nil {
end = valueStart + loc[0]
}
for end > valueStart && isSpace(src[end-1]) {
end--
}
l.add(src, end, &Node{Kind: KindOpcode, Name: m[1], Value: strings.TrimSpace(src[valueStart:end])})
case isNameChar(src[i]):
j := i
for j < len(src) && isNameChar(src[j]) {
j++
}
l.add(src, j, &Node{Kind: KindText})
default:
_, size := utf8.DecodeRuneInString(rest)
l.add(src, i+size, &Node{Kind: KindText})
}
}
for i, n := range l.nodes {
n.idx = i
}
return l.nodes
}
// directive adds the #define or #include at the current position, and reports
// whether there was one that can be read. Otherwise it adds nothing.
func (l *lexer) directive(src string) bool {
rest := src[l.pos:]
if m := defineRE.FindStringSubmatch(rest); m != nil {
length := len(m[0])
// A comment ends the value.
valueStart := length - len(m[2])
if loc := commentRE.FindStringIndex(m[2]); loc != nil {
length = valueStart + loc[0]
}
for length > valueStart && isSpace(rest[length-1]) {
length--
}
// The value is the first word, as ARIA and sfizz read it, so that two
// directives can share a line. What follows it is read as the text it is.
if k := strings.IndexAny(rest[valueStart:length], " \t"); k >= 0 {
length = valueStart + k
}
l.add(src, l.pos+length, &Node{Kind: KindDefine, Name: m[1], Value: strings.TrimSpace(rest[valueStart:length])})
return true
}
if m := includeRE.FindStringSubmatch(rest); m != nil {
l.add(src, l.pos+len(m[0]), &Node{Kind: KindInclude, Value: m[1]})
return true
}
return false
}
// commentRE finds the start of a comment, which ends the value of a #define.
var commentRE = regexp.MustCompile(`//|/\*`)