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:
@@ -73,25 +73,31 @@ func WithLimits(l Limits) ParseOption {
|
||||
|
||||
// Parse reads an instrument from r, and its includes with the resolver.
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
return parse("", data, opts)
|
||||
return p.document("", data)
|
||||
}
|
||||
|
||||
// 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 are read.
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
dir := path.Dir(name)
|
||||
read := func(p string) ([]byte, error) { return fs.ReadFile(fsys, path.Join(dir, p)) }
|
||||
opts = append([]ParseOption{WithResolver(read)}, opts...)
|
||||
return parse(path.Base(name), data, opts)
|
||||
defer f.Close()
|
||||
data, err := p.read(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.document(path.Base(name), data)
|
||||
}
|
||||
|
||||
// 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
|
||||
// included file makes aren't followed.
|
||||
func Includes(text []byte) []string {
|
||||
doc, err := parse("", text, []ParseOption{WithIncludes(IncludesKeep)})
|
||||
doc, err := newParser([]ParseOption{WithIncludes(IncludesKeep)}).document("", text)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -124,11 +130,45 @@ type parser struct {
|
||||
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{}}
|
||||
for _, o := range opts {
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -148,7 +188,7 @@ func (p *parser) file(name string, data []byte, depth int) (*File, error) {
|
||||
}
|
||||
p.bytes += len(data)
|
||||
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)
|
||||
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 {
|
||||
switch n.Kind {
|
||||
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:
|
||||
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 {
|
||||
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).
|
||||
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
|
||||
// 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
|
||||
// variable that isn't defined is left as it is.
|
||||
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, "$") {
|
||||
return text
|
||||
return text, limit < 0 || len(text) <= limit
|
||||
}
|
||||
return variableRE.ReplaceAllStringFunc(text, func(run string) string {
|
||||
for end := 2; end <= len(run); end++ {
|
||||
var b strings.Builder
|
||||
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 {
|
||||
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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user