206 lines
6.2 KiB
Go
206 lines
6.2 KiB
Go
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) {
|
||
|
|
data, err := io.ReadAll(r)
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
return parse("", data, opts)
|
||
|
|
}
|
||
|
|
|
||
|
|
// 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)
|
||
|
|
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)
|
||
|
|
}
|
||
|
|
|
||
|
|
// 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 := parse("", text, []ParseOption{WithIncludes(IncludesKeep)})
|
||
|
|
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 map[string]string
|
||
|
|
// including holds the files being read, to refuse an include loop.
|
||
|
|
including []string
|
||
|
|
bytes int
|
||
|
|
problems []Problem
|
||
|
|
}
|
||
|
|
|
||
|
|
func parse(name string, data []byte, opts []ParseOption) (*Document, error) {
|
||
|
|
p := &parser{parseConfig: parseConfig{limits: DefaultLimits}, defines: map[string]string{}}
|
||
|
|
for _, o := range opts {
|
||
|
|
o(&p.parseConfig)
|
||
|
|
}
|
||
|
|
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, fmt.Errorf("%w: the instrument's text is longer than %d MB", ErrInvalid, p.limits.MaxBytes>>20)
|
||
|
|
}
|
||
|
|
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:
|
||
|
|
p.defines[n.Name] = strings.TrimSpace(substitute(p.defines, n.Value))
|
||
|
|
case KindInclude:
|
||
|
|
n.Resolved = path.Clean(strings.ReplaceAll(substitute(p.defines, n.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_]+`)
|
||
|
|
|
||
|
|
// 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 {
|
||
|
|
if !strings.Contains(text, "$") {
|
||
|
|
return text
|
||
|
|
}
|
||
|
|
return variableRE.ReplaceAllStringFunc(text, func(run string) string {
|
||
|
|
for end := 2; end <= len(run); end++ {
|
||
|
|
if value, ok := defines[run[:end]]; ok {
|
||
|
|
return value + run[end:]
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return run
|
||
|
|
})
|
||
|
|
}
|