Bound parsing work and fix writer, lexer and keyswitch bugs
- Count variable expansions against MaxBytes and stop substituting past it, so nested #defines can't grow exponentially. Read at most MaxBytes from a reader. - Lex in linear time: end an opcode value at the next line break with the same regexp, and merge text nodes by slicing. Cap variable names at 128 bytes. - Read a byte order mark as space so a directive after it is recognised. - Refuse in WriteFiles an include path that is absolute or leaves the folder, and report include.outside and sample.outside from Validate. - Give a lone sw_lokey or sw_hikey a one-key range. - Sum controller modulations in a fixed order so Instrument is deterministic. - Stop samplePrefix looping on a sample at the root. - Validate without lexing plain opcodes again, and cache registry lookups. - Add regression tests and FuzzWrite, FuzzEdit and FuzzBuild. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -204,7 +204,7 @@ func samplePrefix(regions []Region) string {
|
|||||||
}
|
}
|
||||||
prefix := path.Dir(regions[0].Sample)
|
prefix := path.Dir(regions[0].Sample)
|
||||||
for _, r := range regions {
|
for _, r := range regions {
|
||||||
for prefix != "." && !strings.HasPrefix(r.Sample, prefix+"/") {
|
for prefix != "." && prefix != "/" && !strings.HasPrefix(r.Sample, prefix+"/") {
|
||||||
prefix = path.Dir(prefix)
|
prefix = path.Dir(prefix)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+33
-15
@@ -350,8 +350,11 @@ func keyswitchRange(regions []Opcodes) *KeyswitchRange {
|
|||||||
if r == nil {
|
if r == nil {
|
||||||
r = &KeyswitchRange{Low: 127, High: 0}
|
r = &KeyswitchRange{Low: 127, High: 0}
|
||||||
}
|
}
|
||||||
if lowOK && highOK {
|
if lowOK {
|
||||||
keys = append(keys, low+shift, high+shift)
|
keys = append(keys, low+shift)
|
||||||
|
}
|
||||||
|
if highOK {
|
||||||
|
keys = append(keys, high+shift)
|
||||||
}
|
}
|
||||||
for _, k := range keys {
|
for _, k := range keys {
|
||||||
r.Low, r.High = min(r.Low, k), max(r.High, k)
|
r.Low, r.High = min(r.Low, k), max(r.High, k)
|
||||||
@@ -872,18 +875,39 @@ func (e evaluator) modulations(ops Opcodes, only ...string) []Modulation {
|
|||||||
// form targetccN, shaped by target_curveccN at the controller's value.
|
// form targetccN, shaped by target_curveccN at the controller's value.
|
||||||
func (e evaluator) modulation(ops Opcodes, target string, cc func(int) float64, from int) float64 {
|
func (e evaluator) modulation(ops Opcodes, target string, cc func(int) float64, from int) float64 {
|
||||||
total := 0.0
|
total := 0.0
|
||||||
|
for _, m := range modulators(ops, target, from) {
|
||||||
|
total += m.depth * e.shape(ops, target, m.controller, cc(m.controller))
|
||||||
|
}
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
|
||||||
|
// modulatorOpcode is a controller modulation of a target in a region's
|
||||||
|
// opcodes.
|
||||||
|
type modulatorOpcode struct {
|
||||||
|
name string
|
||||||
|
controller int
|
||||||
|
depth float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// modulators returns the controller modulations of a target from the
|
||||||
|
// controller given up, whose depths are numbers, ordered by controller and then
|
||||||
|
// by name. The order makes sums of them, which floating-point addition makes
|
||||||
|
// depend on it, the same each time.
|
||||||
|
func modulators(ops Opcodes, target string, from int) []modulatorOpcode {
|
||||||
|
var out []modulatorOpcode
|
||||||
for name, v := range ops {
|
for name, v := range ops {
|
||||||
n, ok := modulator(name, target)
|
n, ok := modulator(name, target)
|
||||||
if !ok || n < from {
|
if !ok || n < from {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
depth, ok := parseNumber(v)
|
if depth, ok := parseNumber(v); ok {
|
||||||
if !ok {
|
out = append(out, modulatorOpcode{name, n, depth})
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
total += depth * e.shape(ops, target, n, cc(n))
|
|
||||||
}
|
}
|
||||||
return total
|
slices.SortFunc(out, func(a, b modulatorOpcode) int {
|
||||||
|
return cmp.Or(cmp.Compare(a.controller, b.controller), cmp.Compare(a.name, b.name))
|
||||||
|
})
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// amplitude returns the region's amplitude as a factor: amplitude and the
|
// amplitude returns the region's amplitude as a factor: amplitude and the
|
||||||
@@ -896,14 +920,8 @@ func (e evaluator) amplitude(ops Opcodes, cc func(int) float64) float64 {
|
|||||||
a *= v / 100
|
a *= v / 100
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for name, v := range ops {
|
for _, m := range modulators(ops, "amplitude", extendedOnly) {
|
||||||
n, ok := modulator(name, "amplitude")
|
a *= m.depth / 100 * e.shape(ops, "amplitude", m.controller, cc(m.controller))
|
||||||
if !ok || n < extendedOnly {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if depth, ok := parseNumber(v); ok {
|
|
||||||
a *= depth / 100 * e.shape(ops, "amplitude", n, cc(n))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,15 +12,25 @@ var (
|
|||||||
// opcodeRE reads an opcode's name and = at the start of the text.
|
// opcodeRE reads an opcode's name and = at the start of the text.
|
||||||
opcodeRE = regexp.MustCompile(`^([A-Za-z0-9_$]+)=`)
|
opcodeRE = regexp.MustCompile(`^([A-Za-z0-9_$]+)=`)
|
||||||
// defineRE reads a #define's variable and value, up to the end of its line.
|
// defineRE reads a #define's variable and value, up to the end of its line.
|
||||||
defineRE = regexp.MustCompile(`^#define[ \t]+(\$[A-Za-z0-9_]+)[ \t]+([^\r\n]*)`)
|
defineRE = regexp.MustCompile(`^#define[ \t]+(\$[A-Za-z0-9_]{1,128})[ \t]+([^\r\n]*)`)
|
||||||
// includeRE reads an #include's quoted path.
|
// includeRE reads an #include's quoted path.
|
||||||
includeRE = regexp.MustCompile(`^#include[ \t]+"([^"\r\n]*)"`)
|
includeRE = regexp.MustCompile(`^#include[ \t]+"([^"\r\n]*)"`)
|
||||||
// breakRE finds where an opcode's value ends: at a header, the next
|
// breakRE finds where an opcode's value ends: at a header, the next
|
||||||
// opcode, a comment, or a directive after whitespace. Without one it runs
|
// opcode, a comment, a directive after whitespace, or the end of the line,
|
||||||
// to the end of its line, so it can hold spaces, as a sample's path can.
|
// so that a value can hold spaces, as a sample's path can.
|
||||||
breakRE = regexp.MustCompile(`<[A-Za-z_]+>|[A-Za-z0-9_$]+=|//|/\*|\s#(?:define|include)\b`)
|
breakRE = regexp.MustCompile(`<[A-Za-z_]+>|[A-Za-z0-9_$]+=|//|/\*|\s#(?:define|include)\b|\n`)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// byteOrderMark is the UTF-8 mark some editors put at the start of a file. It
|
||||||
|
// is read as space.
|
||||||
|
const byteOrderMark = "\ufeff"
|
||||||
|
|
||||||
|
// atLineStart reports whether a directive may start at offset i: at the start
|
||||||
|
// of the text, after the byte order mark, or after whitespace.
|
||||||
|
func atLineStart(src string, i int) bool {
|
||||||
|
return i == 0 || isSpace(src[i-1]) || i == len(byteOrderMark) && strings.HasPrefix(src, byteOrderMark)
|
||||||
|
}
|
||||||
|
|
||||||
func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n' }
|
func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n' }
|
||||||
|
|
||||||
func isNameChar(c byte) bool {
|
func isNameChar(c byte) bool {
|
||||||
@@ -43,7 +53,8 @@ func (l *lexer) add(src string, end int, n *Node) {
|
|||||||
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 {
|
||||||
last.Raw += n.Raw
|
// 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)
|
l.advance(src, end)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -70,8 +81,11 @@ func lex(src string) []*Node {
|
|||||||
i := l.pos
|
i := l.pos
|
||||||
rest := src[i:]
|
rest := src[i:]
|
||||||
switch {
|
switch {
|
||||||
case isSpace(src[i]):
|
case isSpace(src[i]) || i == 0 && strings.HasPrefix(src, byteOrderMark):
|
||||||
j := i
|
j := i
|
||||||
|
if i == 0 && strings.HasPrefix(src, byteOrderMark) {
|
||||||
|
j = len(byteOrderMark)
|
||||||
|
}
|
||||||
for j < len(src) && isSpace(src[j]) {
|
for j < len(src) && isSpace(src[j]) {
|
||||||
j++
|
j++
|
||||||
}
|
}
|
||||||
@@ -91,16 +105,12 @@ func lex(src string) []*Node {
|
|||||||
case src[i] == '<' && headerRE.MatchString(rest):
|
case src[i] == '<' && headerRE.MatchString(rest):
|
||||||
m := headerRE.FindStringSubmatch(rest)
|
m := headerRE.FindStringSubmatch(rest)
|
||||||
l.add(src, i+len(m[0]), &Node{Kind: KindHeader, Name: m[1]})
|
l.add(src, i+len(m[0]), &Node{Kind: KindHeader, Name: m[1]})
|
||||||
case src[i] == '#' && (i == 0 || isSpace(src[i-1])) && l.directive(src):
|
case src[i] == '#' && atLineStart(src, i) && l.directive(src):
|
||||||
case opcodeRE.MatchString(rest):
|
case opcodeRE.MatchString(rest):
|
||||||
m := opcodeRE.FindStringSubmatch(rest)
|
m := opcodeRE.FindStringSubmatch(rest)
|
||||||
valueStart := i + len(m[0])
|
valueStart := i + len(m[0])
|
||||||
lineEnd := len(src)
|
end := len(src)
|
||||||
if e := strings.IndexByte(src[valueStart:], '\n'); e >= 0 {
|
if loc := breakRE.FindStringIndex(src[valueStart:]); loc != nil {
|
||||||
lineEnd = valueStart + e
|
|
||||||
}
|
|
||||||
end := lineEnd
|
|
||||||
if loc := breakRE.FindStringIndex(src[valueStart:lineEnd]); loc != nil {
|
|
||||||
end = valueStart + loc[0]
|
end = valueStart + loc[0]
|
||||||
}
|
}
|
||||||
for end > valueStart && isSpace(src[end-1]) {
|
for end > valueStart && isSpace(src[end-1]) {
|
||||||
|
|||||||
@@ -73,25 +73,31 @@ func WithLimits(l Limits) ParseOption {
|
|||||||
|
|
||||||
// Parse reads an instrument from r, and its includes with the resolver.
|
// Parse reads an instrument from r, and its includes with the resolver.
|
||||||
func Parse(r io.Reader, opts ...ParseOption) (*Document, error) {
|
func Parse(r io.Reader, opts ...ParseOption) (*Document, error) {
|
||||||
data, err := io.ReadAll(r)
|
p := newParser(opts)
|
||||||
|
data, err := p.read(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return parse("", data, opts)
|
return p.document("", data)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseFile reads the instrument whose main file is name in fsys, and its
|
// ParseFile reads the instrument whose main file is name in fsys, and its
|
||||||
// includes from the folder of the main file. [WithResolver] overrides how
|
// includes from the folder of the main file. [WithResolver] overrides how
|
||||||
// includes are read.
|
// includes are read.
|
||||||
func ParseFile(fsys fs.FS, name string, opts ...ParseOption) (*Document, error) {
|
func ParseFile(fsys fs.FS, name string, opts ...ParseOption) (*Document, error) {
|
||||||
data, err := fs.ReadFile(fsys, name)
|
dir := path.Dir(name)
|
||||||
|
read := func(p string) ([]byte, error) { return fs.ReadFile(fsys, path.Join(dir, p)) }
|
||||||
|
p := newParser(append([]ParseOption{WithResolver(read)}, opts...))
|
||||||
|
f, err := fsys.Open(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
dir := path.Dir(name)
|
defer f.Close()
|
||||||
read := func(p string) ([]byte, error) { return fs.ReadFile(fsys, path.Join(dir, p)) }
|
data, err := p.read(f)
|
||||||
opts = append([]ParseOption{WithResolver(read)}, opts...)
|
if err != nil {
|
||||||
return parse(path.Base(name), data, opts)
|
return nil, err
|
||||||
|
}
|
||||||
|
return p.document(path.Base(name), data)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Includes returns the files that an SFZ file includes directly, with the
|
// Includes returns the files that an SFZ file includes directly, with the
|
||||||
@@ -99,7 +105,7 @@ func ParseFile(fsys fs.FS, name string, opts ...ParseOption) (*Document, error)
|
|||||||
// paths are relative to the folder of the main file. Includes that an
|
// paths are relative to the folder of the main file. Includes that an
|
||||||
// included file makes aren't followed.
|
// included file makes aren't followed.
|
||||||
func Includes(text []byte) []string {
|
func Includes(text []byte) []string {
|
||||||
doc, err := parse("", text, []ParseOption{WithIncludes(IncludesKeep)})
|
doc, err := newParser([]ParseOption{WithIncludes(IncludesKeep)}).document("", text)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -124,11 +130,45 @@ type parser struct {
|
|||||||
problems []Problem
|
problems []Problem
|
||||||
}
|
}
|
||||||
|
|
||||||
func parse(name string, data []byte, opts []ParseOption) (*Document, error) {
|
func newParser(opts []ParseOption) *parser {
|
||||||
p := &parser{parseConfig: parseConfig{limits: DefaultLimits}, defines: map[string]string{}}
|
p := &parser{parseConfig: parseConfig{limits: DefaultLimits}, defines: map[string]string{}}
|
||||||
for _, o := range opts {
|
for _, o := range opts {
|
||||||
o(&p.parseConfig)
|
o(&p.parseConfig)
|
||||||
}
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// read returns the text of the main file, and refuses one that is longer than
|
||||||
|
// the limit without reading the rest of it.
|
||||||
|
func (p *parser) read(r io.Reader) ([]byte, error) {
|
||||||
|
data, err := io.ReadAll(io.LimitReader(r, int64(p.limits.MaxBytes)+1))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(data) > p.limits.MaxBytes {
|
||||||
|
return nil, p.tooLong()
|
||||||
|
}
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *parser) tooLong() error {
|
||||||
|
return fmt.Errorf("%w: the instrument, with what its variables expand to, is longer than %d bytes", ErrInvalid, p.limits.MaxBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// expand replaces the variables in text, counting the result against the
|
||||||
|
// limit on bytes, so that variables that hold variables can't make text
|
||||||
|
// that grows faster than the text that makes it.
|
||||||
|
func (p *parser) expand(text string) (string, error) {
|
||||||
|
out, ok := expand(p.defines, text, p.limits.MaxBytes-p.bytes)
|
||||||
|
if !ok {
|
||||||
|
return "", p.tooLong()
|
||||||
|
}
|
||||||
|
p.bytes += len(out)
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// document reads the main file and the files it includes.
|
||||||
|
func (p *parser) document(name string, data []byte) (*Document, error) {
|
||||||
root, err := p.file(name, data, 0)
|
root, err := p.file(name, data, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -148,7 +188,7 @@ func (p *parser) file(name string, data []byte, depth int) (*File, error) {
|
|||||||
}
|
}
|
||||||
p.bytes += len(data)
|
p.bytes += len(data)
|
||||||
if p.bytes > p.limits.MaxBytes {
|
if p.bytes > p.limits.MaxBytes {
|
||||||
return nil, fmt.Errorf("%w: the instrument's text is longer than %d MB", ErrInvalid, p.limits.MaxBytes>>20)
|
return nil, p.tooLong()
|
||||||
}
|
}
|
||||||
p.including = append(p.including, name)
|
p.including = append(p.including, name)
|
||||||
defer func() { p.including = p.including[:len(p.including)-1] }()
|
defer func() { p.including = p.including[:len(p.including)-1] }()
|
||||||
@@ -157,9 +197,24 @@ func (p *parser) file(name string, data []byte, depth int) (*File, error) {
|
|||||||
for _, n := range f.Nodes {
|
for _, n := range f.Nodes {
|
||||||
switch n.Kind {
|
switch n.Kind {
|
||||||
case KindDefine:
|
case KindDefine:
|
||||||
p.defines[n.Name] = strings.TrimSpace(substitute(p.defines, n.Value))
|
value, err := p.expand(n.Value)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
p.defines[n.Name] = strings.TrimSpace(value)
|
||||||
|
case KindOpcode, KindText:
|
||||||
|
// Flattening and writing expand these again, so what they make counts.
|
||||||
|
if strings.Contains(n.Raw, "$") {
|
||||||
|
if _, err := p.expand(n.Raw); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
case KindInclude:
|
case KindInclude:
|
||||||
n.Resolved = path.Clean(strings.ReplaceAll(substitute(p.defines, n.Value), `\`, "/"))
|
value, err := p.expand(n.Value)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
n.Resolved = path.Clean(strings.ReplaceAll(value, `\`, "/"))
|
||||||
if p.includes == IncludesKeep || p.resolver == nil {
|
if p.includes == IncludesKeep || p.resolver == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -186,20 +241,44 @@ func (p *parser) file(name string, data []byte, depth int) (*File, error) {
|
|||||||
// of the run may be the name of a variable (see substitute).
|
// of the run may be the name of a variable (see substitute).
|
||||||
var variableRE = regexp.MustCompile(`\$[A-Za-z0-9_]+`)
|
var variableRE = regexp.MustCompile(`\$[A-Za-z0-9_]+`)
|
||||||
|
|
||||||
|
// maxVariableName is the most bytes a variable's name may have, with its $.
|
||||||
|
const maxVariableName = 129
|
||||||
|
|
||||||
// substitute replaces the variables defined so far in text. A variable's name
|
// substitute replaces the variables defined so far in text. A variable's name
|
||||||
// ends at the shortest run of characters that is a defined name, so in
|
// ends at the shortest run of characters that is a defined name, so in
|
||||||
// $MIC_$ART the underscore is text between $MIC and $ART, as in ARIA. A
|
// $MIC_$ART the underscore is text between $MIC and $ART, as in ARIA. A
|
||||||
// variable that isn't defined is left as it is.
|
// variable that isn't defined is left as it is.
|
||||||
func substitute(defines map[string]string, text string) string {
|
func substitute(defines map[string]string, text string) string {
|
||||||
|
out, _ := expand(defines, text, -1)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// expand is substitute with a limit on the length of the result, which it
|
||||||
|
// reports as false if text would make more than that. A negative limit is
|
||||||
|
// none.
|
||||||
|
func expand(defines map[string]string, text string, limit int) (string, bool) {
|
||||||
if !strings.Contains(text, "$") {
|
if !strings.Contains(text, "$") {
|
||||||
return text
|
return text, limit < 0 || len(text) <= limit
|
||||||
}
|
}
|
||||||
return variableRE.ReplaceAllStringFunc(text, func(run string) string {
|
var b strings.Builder
|
||||||
for end := 2; end <= len(run); end++ {
|
last := 0
|
||||||
|
for _, loc := range variableRE.FindAllStringIndex(text, -1) {
|
||||||
|
run := text[loc[0]:loc[1]]
|
||||||
|
for end := 2; end <= len(run) && end <= maxVariableName; end++ {
|
||||||
if value, ok := defines[run[:end]]; ok {
|
if value, ok := defines[run[:end]]; ok {
|
||||||
return value + run[end:]
|
b.WriteString(text[last:loc[0]])
|
||||||
|
b.WriteString(value)
|
||||||
|
last = loc[0] + end
|
||||||
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return run
|
if limit >= 0 && b.Len() > limit {
|
||||||
})
|
return "", false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.WriteString(text[last:])
|
||||||
|
if limit >= 0 && b.Len() > limit {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return b.String(), true
|
||||||
}
|
}
|
||||||
|
|||||||
+287
@@ -0,0 +1,287 @@
|
|||||||
|
package sfz
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestDefinesCannotOutgrowLimit checks that variables that hold variables
|
||||||
|
// stop at the byte limit, as a few lines of them would otherwise make gigabytes.
|
||||||
|
func TestDefinesCannotOutgrowLimit(t *testing.T) {
|
||||||
|
var b strings.Builder
|
||||||
|
// The names are as long as each other, so none is the start of another.
|
||||||
|
name := func(i int) string { return fmt.Sprintf("$N%c%c", 'a'+i/26, 'a'+i%26) }
|
||||||
|
fmt.Fprintf(&b, "#define %s xxxxxxxx\n", name(0))
|
||||||
|
for i := 1; i <= 40; i++ {
|
||||||
|
fmt.Fprintf(&b, "#define %s %s%s\n", name(i), name(i-1), name(i-1))
|
||||||
|
}
|
||||||
|
start := time.Now()
|
||||||
|
_, err := Parse(strings.NewReader(b.String()))
|
||||||
|
if !errors.Is(err, ErrInvalid) {
|
||||||
|
t.Errorf("err %v", err)
|
||||||
|
}
|
||||||
|
if d := time.Since(start); d > 5*time.Second {
|
||||||
|
t.Errorf("took %v", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestUseOfDefinesCountsAgainstLimit checks that an opcode that expands a large
|
||||||
|
// variable many times is counted, as flattening makes the text.
|
||||||
|
func TestUseOfDefinesCountsAgainstLimit(t *testing.T) {
|
||||||
|
text := "#define $A " + strings.Repeat("x", 100) + "\n" + strings.Repeat("<region> sample=$A.wav\n", 100)
|
||||||
|
if _, err := Parse(strings.NewReader(text), WithLimits(Limits{MaxBytes: 5000})); !errors.Is(err, ErrInvalid) {
|
||||||
|
t.Errorf("err %v", err)
|
||||||
|
}
|
||||||
|
if _, err := Parse(strings.NewReader(text), WithLimits(Limits{MaxBytes: 50000})); err != nil {
|
||||||
|
t.Errorf("err %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// countingReader counts the bytes read from it, and never ends.
|
||||||
|
type countingReader struct{ n int }
|
||||||
|
|
||||||
|
func (r *countingReader) Read(p []byte) (int, error) {
|
||||||
|
r.n += len(p)
|
||||||
|
for i := range p {
|
||||||
|
p[i] = ' '
|
||||||
|
}
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseReadsNoMoreThanLimit(t *testing.T) {
|
||||||
|
var r countingReader
|
||||||
|
_, err := Parse(&r, WithLimits(Limits{MaxBytes: 1000}))
|
||||||
|
if !errors.Is(err, ErrInvalid) {
|
||||||
|
t.Errorf("err %v", err)
|
||||||
|
}
|
||||||
|
if r.n > 1<<16 {
|
||||||
|
t.Errorf("read %d bytes", r.n)
|
||||||
|
}
|
||||||
|
if _, err := Parse(io.LimitReader(&countingReader{}, 1000), WithLimits(Limits{MaxBytes: 1000})); err != nil {
|
||||||
|
t.Errorf("text at the limit: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLimitsDepth(t *testing.T) {
|
||||||
|
m := map[string]string{"a": "#include \"b\"", "b": "#include \"c\"", "c": "<region>"}
|
||||||
|
_, err := Parse(strings.NewReader("#include \"a\""), WithResolver(files(m)), WithLimits(Limits{MaxDepth: 2}))
|
||||||
|
if !errors.Is(err, ErrInvalid) {
|
||||||
|
t.Errorf("err %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLexScales checks that text a few megabytes long takes a moment to
|
||||||
|
// read in each shape that was once quadratic.
|
||||||
|
func TestLexScales(t *testing.T) {
|
||||||
|
for name, text := range map[string]string{
|
||||||
|
"opcodes on one line": strings.Repeat("a=1 ", 1<<19),
|
||||||
|
"punctuation": strings.Repeat("!", 1<<20),
|
||||||
|
"unknown variable": "x=$" + strings.Repeat("b", 1<<20) + "\n<region>",
|
||||||
|
"long define name": "#define $" + strings.Repeat("b", 1<<20) + " 1\n<region> sample=$" + strings.Repeat("b", 1<<20),
|
||||||
|
} {
|
||||||
|
start := time.Now()
|
||||||
|
doc, err := Parse(strings.NewReader(text))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s: %v", name, err)
|
||||||
|
}
|
||||||
|
doc.Flatten()
|
||||||
|
doc.Validate()
|
||||||
|
if doc.String() != text {
|
||||||
|
t.Errorf("%s: not written back", name)
|
||||||
|
}
|
||||||
|
if d := time.Since(start); d > 3*time.Second {
|
||||||
|
t.Errorf("%s: took %v", name, d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestByteOrderMark(t *testing.T) {
|
||||||
|
text := "\ufeff#define $A 1\n<region> sample=$A.wav\n"
|
||||||
|
doc := mustParse(t, text, nil)
|
||||||
|
if doc.String() != text {
|
||||||
|
t.Errorf("wrote %q", doc.String())
|
||||||
|
}
|
||||||
|
if got := doc.Flatten().Regions[0].Opcodes["sample"]; got != "1.wav" {
|
||||||
|
t.Errorf("sample %q", got)
|
||||||
|
}
|
||||||
|
for _, p := range doc.Validate() {
|
||||||
|
t.Errorf("problem %+v", p)
|
||||||
|
}
|
||||||
|
doc = mustParse(t, "\ufeff<region> sample=a.wav", nil)
|
||||||
|
if len(doc.Flatten().Regions) != 1 {
|
||||||
|
t.Error("region after the mark")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWriteFilesStaysInFolder(t *testing.T) {
|
||||||
|
anyFile := func(string) ([]byte, error) { return []byte("<region> sample=a.wav\n"), nil }
|
||||||
|
for _, include := range []string{"../evil.sfz", "a/../../evil.sfz", "/evil.sfz", "..\\evil.sfz"} {
|
||||||
|
doc, err := Parse(strings.NewReader(fmt.Sprintf("#include %q\n", include)), WithResolver(anyFile))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var written []string
|
||||||
|
err = doc.WriteFiles("out/main.sfz", func(p string, _ []byte) error { written = append(written, p); return nil }, WriteOptions{})
|
||||||
|
if !errors.Is(err, ErrInvalid) || len(written) != 0 {
|
||||||
|
t.Errorf("%s: err %v, wrote %q", include, err, written)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateOutsideFolder(t *testing.T) {
|
||||||
|
doc := mustParse(t, "#include \"../x.sfz\"\n<region> sample=../a.wav\n<region> sample=/a.wav\n<region> sample=C:\\a.wav\n<region> sample=ok/../b.wav\n", map[string]string{"../x.sfz": ""})
|
||||||
|
var codes []string
|
||||||
|
for _, p := range doc.Validate() {
|
||||||
|
codes = append(codes, p.Code)
|
||||||
|
}
|
||||||
|
want := []string{"include.outside", "sample.outside", "sample.outside", "sample.outside"}
|
||||||
|
if !reflect.DeepEqual(codes, want) {
|
||||||
|
t.Errorf("codes %q, want %q", codes, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestKeyswitchRangeOneEnd(t *testing.T) {
|
||||||
|
for text, want := range map[string]KeyswitchRange{
|
||||||
|
"<region> sample=a.wav sw_lokey=36": {Low: 36, High: 36},
|
||||||
|
"<region> sample=a.wav sw_hikey=40": {Low: 40, High: 40},
|
||||||
|
} {
|
||||||
|
got := parseText(t, text).Keyswitches
|
||||||
|
if got == nil || got.Low != want.Low || got.High != want.High {
|
||||||
|
t.Errorf("%s: %+v", text, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestInstrumentIsDeterministic checks that regions with many controller
|
||||||
|
// modulations read the same each time.
|
||||||
|
func TestInstrumentIsDeterministic(t *testing.T) {
|
||||||
|
text := "<region> sample=a.wav pitch_keycenter=77 lovel=3 hivel=71 " +
|
||||||
|
"volume_oncc131=0.1 volume_oncc133=0.37 volume_oncc134=0.7 volume_cc131=0.3 gain_oncc131=0.9 gain_oncc133=0.3 " +
|
||||||
|
"pitch_oncc131=3.3 pitch_oncc133=1.1 pitch_oncc134=1e16 tune_oncc131=-1e16 tune_oncc133=0.3 tune_oncc134=0.7 " +
|
||||||
|
"amplitude_oncc131=80 amplitude_oncc133=70 amplitude_oncc134=90 amplitude_oncc132=33\n"
|
||||||
|
want := parseText(t, text).Regions
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
if got := parseText(t, text).Regions; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("run %d: %+v, want %+v", i, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeCombinations are the write options a fuzzer tries.
|
||||||
|
var writeCombinations = []WriteOptions{
|
||||||
|
{}, {InlineIncludes: true}, {ExpandVariables: true}, {InlineIncludes: true, ExpandVariables: true},
|
||||||
|
{LineEnding: LF}, {LineEnding: CRLF, InlineIncludes: true},
|
||||||
|
}
|
||||||
|
|
||||||
|
// FuzzWrite checks that a document is written, and read back, with any
|
||||||
|
// options, and that without changes the zero value gives the text back.
|
||||||
|
func FuzzWrite(f *testing.F) {
|
||||||
|
for _, text := range roundTripTexts {
|
||||||
|
f.Add(text, "<region> sample=$S.wav")
|
||||||
|
}
|
||||||
|
f.Fuzz(func(t *testing.T, text, included string) {
|
||||||
|
resolver := func(string) ([]byte, error) { return []byte(included), nil }
|
||||||
|
doc, err := Parse(strings.NewReader(text), WithResolver(resolver))
|
||||||
|
if err != nil {
|
||||||
|
t.Skip()
|
||||||
|
}
|
||||||
|
for _, opts := range writeCombinations {
|
||||||
|
var b strings.Builder
|
||||||
|
if err := doc.Write(&b, opts); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, err := Parse(strings.NewReader(b.String()), WithResolver(resolver)); err != nil {
|
||||||
|
t.Skip()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
if err := doc.Write(&b, WriteOptions{}); err == nil && doc.String() != b.String() {
|
||||||
|
t.Fatalf("wrote %q, want %q", b.String(), doc.String())
|
||||||
|
}
|
||||||
|
doc.WriteFiles("main.sfz", func(string, []byte) error { return nil }, WriteOptions{})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// FuzzEdit checks that editing any document doesn't panic, and keeps the
|
||||||
|
// layout it didn't change.
|
||||||
|
func FuzzEdit(f *testing.F) {
|
||||||
|
for _, text := range roundTripTexts {
|
||||||
|
f.Add(text, "lokey", "60")
|
||||||
|
}
|
||||||
|
f.Fuzz(func(t *testing.T, text, name, value string) {
|
||||||
|
doc, err := Parse(strings.NewReader(text))
|
||||||
|
if err != nil {
|
||||||
|
t.Skip()
|
||||||
|
}
|
||||||
|
for _, h := range doc.Headers() {
|
||||||
|
h.Set(name, value)
|
||||||
|
h.Get(name)
|
||||||
|
h.Delete(name)
|
||||||
|
}
|
||||||
|
doc.AddHeader("region", nil).Set(name, value)
|
||||||
|
doc.SetDefine("$X", value)
|
||||||
|
doc.Flatten()
|
||||||
|
doc.Validate()
|
||||||
|
for _, f := range doc.Files() {
|
||||||
|
prev := f.String()
|
||||||
|
f.reposition()
|
||||||
|
if f.String() != prev {
|
||||||
|
t.Fatal("repositioning changed the text")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// FuzzBuild checks that an instrument read from any text builds into a
|
||||||
|
// document that reads, whichever the options.
|
||||||
|
func FuzzBuild(f *testing.F) {
|
||||||
|
for _, text := range roundTripTexts {
|
||||||
|
f.Add(text)
|
||||||
|
}
|
||||||
|
f.Add("<region> sample=a.wav sw_lokey=3 volume_oncc7=1 locc7=3 hicc7=9 lochan=2")
|
||||||
|
f.Fuzz(func(t *testing.T, text string) {
|
||||||
|
doc, err := Parse(strings.NewReader(text))
|
||||||
|
if err != nil {
|
||||||
|
t.Skip()
|
||||||
|
}
|
||||||
|
inst := doc.Flatten().Instrument()
|
||||||
|
for _, opts := range []BuildOptions{{}, {Variables: true, MinRepeat: 1}, {SplitFiles: true, RegionsPerFile: 1}} {
|
||||||
|
built, err := Build(inst, opts)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
built.Validate()
|
||||||
|
built.Flatten().Instrument()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBuildVariablesWithAbsoluteSamples checks that samples in the root, or in
|
||||||
|
// no common folder, build with a folder of variables.
|
||||||
|
func TestBuildVariablesWithAbsoluteSamples(t *testing.T) {
|
||||||
|
for _, samples := range [][]string{{"/"}, {"/a.wav", "/b/c.wav"}, {"/a/b.wav", "/a/c.wav"}, {"a/b.wav", "/a/c.wav"}} {
|
||||||
|
inst := &Instrument{}
|
||||||
|
for _, s := range samples {
|
||||||
|
r := defaultRegion()
|
||||||
|
r.Sample = s
|
||||||
|
inst.Regions = append(inst.Regions, r)
|
||||||
|
}
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(done)
|
||||||
|
if _, err := Build(inst, BuildOptions{Variables: true}); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatalf("%q: Build didn't return", samples)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
@@ -0,0 +1,2 @@
|
|||||||
|
go test fuzz v1
|
||||||
|
string("//\n/<region>sample=/ hikey=60l")
|
||||||
+44
-3
@@ -2,6 +2,9 @@ package sfz
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"path"
|
||||||
|
"regexp"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
@@ -10,7 +13,7 @@ import (
|
|||||||
// read. It reports what is wrong with the text and with values the format
|
// read. It reports what is wrong with the text and with values the format
|
||||||
// describes, and never fails on an opcode it doesn't know.
|
// describes, and never fails on an opcode it doesn't know.
|
||||||
func (d *Document) Validate() []Problem {
|
func (d *Document) Validate() []Problem {
|
||||||
v := &validator{defines: map[string]string{}}
|
v := &validator{defines: map[string]string{}, known: map[string]known{}}
|
||||||
v.problems = append(v.problems, d.problems...)
|
v.problems = append(v.problems, d.problems...)
|
||||||
v.file(d.Root)
|
v.file(d.Root)
|
||||||
v.endHeader()
|
v.endHeader()
|
||||||
@@ -24,8 +27,17 @@ type opcodeAt struct {
|
|||||||
file string
|
file string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// known is the result of a [Lookup].
|
||||||
|
type known struct {
|
||||||
|
info OpcodeInfo
|
||||||
|
ok bool
|
||||||
|
}
|
||||||
|
|
||||||
type validator struct {
|
type validator struct {
|
||||||
defines map[string]string
|
defines map[string]string
|
||||||
|
// known holds the lookups made, as a document names the same few opcodes
|
||||||
|
// many times.
|
||||||
|
known map[string]known
|
||||||
problems []Problem
|
problems []Problem
|
||||||
// inHeader is whether a header has been read.
|
// inHeader is whether a header has been read.
|
||||||
inHeader bool
|
inHeader bool
|
||||||
@@ -46,12 +58,19 @@ func (v *validator) file(f *File) {
|
|||||||
v.defines[n.Name] = strings.TrimSpace(substitute(v.defines, n.Value))
|
v.defines[n.Name] = strings.TrimSpace(substitute(v.defines, n.Value))
|
||||||
case KindInclude:
|
case KindInclude:
|
||||||
v.undefined(f, n, n.Value)
|
v.undefined(f, n, n.Value)
|
||||||
|
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))
|
||||||
|
}
|
||||||
if n.File != nil {
|
if n.File != nil {
|
||||||
v.file(n.File)
|
v.file(n.File)
|
||||||
}
|
}
|
||||||
case KindHeader:
|
case KindHeader:
|
||||||
v.header(f, n, n.Name)
|
v.header(f, n, n.Name)
|
||||||
case KindOpcode, KindText:
|
case KindOpcode, KindText:
|
||||||
|
if n.Kind == KindOpcode && !strings.Contains(n.Raw, "$") {
|
||||||
|
v.opcode(f, n, n.Name, n.Value)
|
||||||
|
continue
|
||||||
|
}
|
||||||
v.undefined(f, n, n.Raw)
|
v.undefined(f, n, n.Raw)
|
||||||
text := n.Raw
|
text := n.Raw
|
||||||
if strings.Contains(text, "$") {
|
if strings.Contains(text, "$") {
|
||||||
@@ -121,7 +140,12 @@ func (v *validator) opcode(f *File, n *Node, name, value string) {
|
|||||||
if strings.Contains(name, "$") {
|
if strings.Contains(name, "$") {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
info, ok := Lookup(name)
|
k, seen := v.known[name]
|
||||||
|
if !seen {
|
||||||
|
k.info, k.ok = Lookup(name)
|
||||||
|
v.known[name] = k
|
||||||
|
}
|
||||||
|
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.Path, n, SeverityInfo, "opcode.unknown", fmt.Sprintf("%s isn't an opcode of the format", name))
|
||||||
return
|
return
|
||||||
@@ -132,6 +156,9 @@ func (v *validator) opcode(f *File, n *Node, name, value string) {
|
|||||||
if strings.Contains(value, "$") {
|
if strings.Contains(value, "$") {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
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.value(f, n, name, value, info)
|
v.value(f, n, name, value, info)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,3 +222,17 @@ func (v *validator) undefined(f *File, n *Node, text string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// driveRE reads the drive of a Windows path.
|
||||||
|
var driveRE = regexp.MustCompile(`^[A-Za-z]:`)
|
||||||
|
|
||||||
|
// outsideFolder reports whether a sample path is absolute or leaves the
|
||||||
|
// folder it is relative to.
|
||||||
|
func outsideFolder(p string) bool {
|
||||||
|
p = strings.ReplaceAll(strings.TrimSpace(p), `\`, "/")
|
||||||
|
if strings.HasPrefix(p, "/") || driveRE.MatchString(p) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
p = path.Clean(p)
|
||||||
|
return p == ".." || strings.HasPrefix(p, "../")
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package sfz
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"io/fs"
|
||||||
"path"
|
"path"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -58,21 +59,28 @@ func (d *Document) Write(w io.Writer, opts WriteOptions) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// WriteFiles writes the main file with the path root, and each file it
|
// WriteFiles writes the main file with the path root, and each file it
|
||||||
// includes at its own path, in the folder of root, using fw.
|
// includes at its own path, in the folder of root, using fw. It writes nothing
|
||||||
|
// and returns [ErrInvalid] if an include's path is absolute or leaves the
|
||||||
|
// folder.
|
||||||
func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) error {
|
func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) error {
|
||||||
r := &renderer{opts: opts, defines: map[string]string{}, outputs: map[string]string{}}
|
r := &renderer{opts: opts, defines: map[string]string{}, outputs: map[string]string{}}
|
||||||
text := r.file(d.Root)
|
text := r.file(d.Root)
|
||||||
if r.err != nil {
|
if r.err != nil {
|
||||||
return r.err
|
return r.err
|
||||||
}
|
}
|
||||||
if err := fw(root, []byte(r.lineEndings(text))); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
paths := make([]string, 0, len(r.outputs))
|
paths := make([]string, 0, len(r.outputs))
|
||||||
for p := range r.outputs {
|
for p := range r.outputs {
|
||||||
|
// An include path comes from the text, so it can't be trusted to stay in
|
||||||
|
// the folder.
|
||||||
|
if !fs.ValidPath(p) {
|
||||||
|
return fmt.Errorf("%w: the include %q is outside the folder of the main file", ErrInvalid, p)
|
||||||
|
}
|
||||||
paths = append(paths, p)
|
paths = append(paths, p)
|
||||||
}
|
}
|
||||||
sort.Strings(paths)
|
sort.Strings(paths)
|
||||||
|
if err := fw(root, []byte(r.lineEndings(text))); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
dir := path.Dir(root)
|
dir := path.Dir(root)
|
||||||
for _, p := range paths {
|
for _, p := range paths {
|
||||||
if err := fw(path.Join(dir, p), []byte(r.lineEndings(r.outputs[p]))); err != nil {
|
if err := fw(path.Join(dir, p), []byte(r.lineEndings(r.outputs[p]))); err != nil {
|
||||||
|
|||||||
Reference in New Issue
Block a user