package sfz import ( "fmt" "io" "io/fs" "path" "regexp" "strings" ) // Resolver returns the contents of an included file. The path it is given is // relative to the folder of the main file, with forward slashes. It may hold .. // elements or be absolute, as the text of an instrument decides, so a Resolver // that reads from a disk needs to keep to the instrument's folder. type Resolver func(path string) ([]byte, error) // IncludeMode is what [Parse] does with each #include. type IncludeMode int // The include modes. const ( // IncludesResolve reads each include. An include that can't be read is // reported as a [Problem] and left unresolved. IncludesResolve IncludeMode = iota // IncludesKeep reads no includes, and only works out their paths. IncludesKeep // IncludesFail reads each include, and makes [Parse] return // [ErrUnresolved] for one that can't be read. IncludesFail ) // Limits bound the work that the text of an instrument can 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, counting // what their variables expand to as well. MaxBytes int } // DefaultLimits are the limits [Parse] uses unless [WithLimits] sets others. var DefaultLimits = Limits{MaxDepth: 16, MaxBytes: 16 << 20} // parseConfig is what the [ParseOption]s set. 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 a resolver, 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 keeps 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. It // returns an error wrapping [ErrInvalid] for an instrument that is past the // limits or that includes itself, and one wrapping [ErrUnresolved] for an // include that can't be read if [IncludesFail] is set. Any other text can be // read, and what in it isn't SFZ is for [Document.Validate] to report. 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, which fsys keeps them to. // [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, in the order // they first appear, each once. A variable that the file defines itself is // replaced by its value. The paths are relative to the folder of the main file. // Includes that an included file makes aren't followed. It returns nil if text // is past the limits. 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 is how many bytes the files read so far, and what their variables // expand to, come to. bytes int // problems are the problems found so far. problems []Problem } // newParser returns a parser with the options set. 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. It 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 } // tooLong returns the error for an instrument that is past the limit on bytes. 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 and counts the result against the // limit on bytes. The count stops variables that hold variables from making // text that grows much 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: each #define sets // a variable and each #include reads the file it names, at depth levels of // include below the main file. 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 // against the limit now. 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) } line, col := f.Position(n) p.problems = append(p.problems, Problem{ File: name, Line: line, Col: 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. The name of a // variable is the start of the run (see substitute). var variableRE = regexp.MustCompile(`\$[A-Za-z0-9_]+`) // maxVariableName is the most bytes that the name of a variable may have, with // its $. It keeps the search for the end of a name short. 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 stays 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. It reports // false, and returns nothing, if text would make more than that. A negative // limit is no limit. 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 }