Files
sfz/parse.go
T

285 lines
8.2 KiB
Go
Raw Normal View History

package sfz
import (
"fmt"
"io"
"io/fs"
"path"
"regexp"
"strings"
)
// Resolver returns the contents of an included file. The path is relative to
// the folder of the main file, with forward slashes.
type Resolver func(path string) ([]byte, error)
// IncludeMode is what [Parse] does with an #include.
type IncludeMode int
// The include modes.
const (
// IncludesResolve reads each include. One that can't be read is reported
// as a [Problem] and left unresolved.
IncludesResolve IncludeMode = iota
// IncludesKeep reads no includes, and works out their paths only.
IncludesKeep
// IncludesFail reads each include, and returns [ErrUnresolved] for one
// that can't be read.
IncludesFail
)
// Limits bound what an instrument may make Parse do.
type Limits struct {
// MaxDepth is how deeply #include may nest. The main file is at depth 0.
MaxDepth int
// MaxBytes is how many bytes all the files together may hold.
MaxBytes int
}
// DefaultLimits are the limits [Parse] uses unless [WithLimits] says otherwise.
var DefaultLimits = Limits{MaxDepth: 16, MaxBytes: 16 << 20}
type parseConfig struct {
resolver Resolver
includes IncludeMode
limits Limits
}
// ParseOption changes how [Parse] works.
type ParseOption func(*parseConfig)
// WithResolver sets how includes are read. Without one, includes aren't read.
func WithResolver(r Resolver) ParseOption {
return func(c *parseConfig) { c.resolver = r }
}
// WithIncludes sets what to do with includes. The default is
// [IncludesResolve].
func WithIncludes(m IncludeMode) ParseOption {
return func(c *parseConfig) { c.includes = m }
}
// WithLimits sets the limits. A field that is 0 uses its default.
func WithLimits(l Limits) ParseOption {
return func(c *parseConfig) {
if l.MaxDepth > 0 {
c.limits.MaxDepth = l.MaxDepth
}
if l.MaxBytes > 0 {
c.limits.MaxBytes = l.MaxBytes
}
}
}
// Parse reads an instrument from r, and its includes with the resolver.
func Parse(r io.Reader, opts ...ParseOption) (*Document, error) {
p := newParser(opts)
data, err := p.read(r)
if err != nil {
return nil, err
}
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) {
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
}
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
// variables it defines itself substituted, in the order they first appear. The
// 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 := newParser([]ParseOption{WithIncludes(IncludesKeep)}).document("", text)
if err != nil {
return nil
}
var found []string
seen := map[string]bool{}
for _, n := range doc.Root.Nodes {
if n.Kind == KindInclude && !seen[n.Resolved] {
seen[n.Resolved] = true
found = append(found, n.Resolved)
}
}
return found
}
// parser reads a document's files, keeping the variables defined so far.
type parser struct {
parseConfig
defines defines
// including holds the files being read, to refuse an include loop.
including []string
bytes int
problems []Problem
}
func newParser(opts []ParseOption) *parser {
p := &parser{parseConfig: parseConfig{limits: DefaultLimits}, defines: defines{}}
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
}
return &Document{Root: root, problems: p.problems}, nil
}
// file lexes a file and reads the directives in it, in order.
func (p *parser) file(name string, data []byte, depth int) (*File, error) {
if depth > p.limits.MaxDepth {
return nil, fmt.Errorf("%w: includes nest more than %d deep at %s", ErrInvalid, p.limits.MaxDepth, name)
}
for _, f := range p.including {
if f == name {
return nil, fmt.Errorf("%w: %w: %s includes itself", ErrInvalid, ErrIncludeLoop, name)
}
}
p.bytes += len(data)
if p.bytes > p.limits.MaxBytes {
return nil, p.tooLong()
}
p.including = append(p.including, name)
defer func() { p.including = p.including[:len(p.including)-1] }()
f := &File{Path: name, Nodes: lex(string(data))}
for _, n := range f.Nodes {
switch n.Kind {
case KindDefine:
value, err := p.expand(n.Value)
if err != nil {
return nil, err
}
p.defines.set(n.Name, 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:
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
}
child, err := p.resolver(n.Resolved)
if err != nil {
if p.includes == IncludesFail {
return nil, fmt.Errorf("%w: %s: %w", ErrUnresolved, n.Resolved, err)
}
p.problems = append(p.problems, Problem{
File: name, Line: n.Line, Col: n.Col, Severity: SeverityWarning,
Code: "include.unresolved", Msg: fmt.Sprintf("can't read %s: %v", n.Resolved, err),
})
continue
}
if n.File, err = p.file(n.Resolved, child, depth+1); err != nil {
return nil, err
}
}
}
return f, nil
}
// variableRE finds a $ and the run of name characters after it. Only the start
// 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, limit < 0 || len(text) <= limit
}
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 {
b.WriteString(text[last:loc[0]])
b.WriteString(value)
last = loc[0] + end
break
}
}
if limit >= 0 && b.Len() > limit {
return "", false
}
}
b.WriteString(text[last:])
if limit >= 0 && b.Len() > limit {
return "", false
}
return b.String(), true
}