package sfz import ( "fmt" "slices" "strings" ) // Header is a header of a file, with the opcodes that follow it in the same // file up to the next header. The nodes of a file that an #include in that // range reads are the nodes of that file, and not of the header. type Header struct { // File is the file the header is in. File *File // Node is the header's own node. Node *Node } // Name returns the header's name without its brackets, as written. func (h *Header) Name() string { return h.Node.Name } // indexOf returns where a node is in the file's nodes, or -1 if it isn't. A // node remembers where it was, and edits move it only a short way from there, // so the search starts there and goes outwards. func (f *File) indexOf(n *Node) int { at := func(i int) bool { return i >= 0 && i < len(f.Nodes) && f.Nodes[i] == n } if at(n.idx) { return n.idx } for d := 1; ; d++ { if at(n.idx + d) { n.idx += d return n.idx } if at(n.idx - d) { n.idx -= d return n.idx } if n.idx-d < 0 && n.idx+d >= len(f.Nodes) { return -1 } } } // span returns the range of the file's nodes that follow the header's own, up // to the next header or the end of the file. func (h *Header) span() (start, end int) { start = h.File.indexOf(h.Node) + 1 end = start for end < len(h.File.Nodes) && h.File.Nodes[end].Kind != KindHeader { end++ } return start, end } // Opcodes returns the header's opcode nodes, in order. func (h *Header) Opcodes() []*Node { start, end := h.span() var out []*Node for _, n := range h.File.Nodes[start:end] { if n.Kind == KindOpcode { out = append(out, n) } } return out } // Get returns the header's last node for an opcode, which is the one that takes // effect, and whether it has one. func (h *Header) Get(name string) (*Node, bool) { start, end := h.span() for i := end - 1; i >= start; i-- { if n := h.File.Nodes[i]; n.Kind == KindOpcode && n.Name == name { return n, true } } return nil, false } // checkOpcode returns an error wrapping [ErrInvalid] if name=value wouldn't be // read back as one opcode with that value, as when the value holds a line // break, a comment or another opcode. func checkOpcode(name, value string) error { text := name + "=" + value nodes := lex(text) if len(nodes) > 0 && nodes[0].Kind == KindOpcode && nodes[0].Name == name && nodes[0].Value == strings.TrimSpace(value) && nodes[0].Raw == text && onlySpace(nodes[1:]) { return nil } return fmt.Errorf("%w: %s=%q can't be written as one opcode", ErrInvalid, name, value) } // checkDefine returns an error wrapping [ErrInvalid] if a #define of the // variable name with the value wouldn't be read back as that directive. func checkDefine(name, value string) error { nodes := lex("#define " + name + " " + value) if len(nodes) > 0 && nodes[0].Kind == KindDefine && nodes[0].Name == name && nodes[0].Value == strings.TrimSpace(value) && onlySpace(nodes[1:]) { return nil } return fmt.Errorf("%w: #define %s %q can't be written as one directive", ErrInvalid, name, value) } // onlySpace reports whether every node is whitespace. func onlySpace(nodes []*Node) bool { for _, n := range nodes { if n.Kind != KindSpace { return false } } return true } // Set gives the opcode a value. It returns an error wrapping [ErrInvalid], and // changes nothing, if the name and value can't be written as one opcode. An // opcode that the header has keeps its place and the text around it, and takes // the value as written, even if the value was a variable. A new opcode goes // after the header's last, and after any comment on that opcode's line, laid // out as that opcode is. func (h *Header) Set(name, value string) error { value = strings.TrimSpace(value) if err := checkOpcode(name, value); err != nil { return err } if n, ok := h.Get(name); ok { n.Raw = name + "=" + value n.Value = value h.File.dirty = true return nil } start, end := h.span() last := -1 for i := start; i < end; i++ { if h.File.Nodes[i].Kind == KindOpcode { last = i } } nodes := []*Node{{Kind: KindOpcode, Raw: name + "=" + value, Name: name, Value: value}} at := start var sep string if last < 0 { // With no opcode to follow, the new one goes after the header, on a line // of its own if the header has one. sep = " " if start < len(h.File.Nodes) && h.File.Nodes[start].Kind == KindSpace && strings.Contains(h.File.Nodes[start].Raw, "\n") { sep = h.File.Nodes[start].Raw } else if start >= len(h.File.Nodes) { sep = "\n" } } else { at = last + 1 sep = " " if i := last - 1; i >= start && h.File.Nodes[i].Kind == KindSpace { sep = h.File.Nodes[i].Raw } else if h.File.hasLineBreak() { sep = "\n" } // The new opcode goes after the comments that end the last one's line. A // line comment runs to the end of its line, so the opcode then goes on a // line of its own. A block comment that never ends can't be passed. for { k := at for k < end && h.File.Nodes[k].Kind == KindSpace && !strings.Contains(h.File.Nodes[k].Raw, "\n") { k++ } if k >= end || h.File.Nodes[k].Kind != KindComment || unterminated(h.File.Nodes[k]) { break } if c := h.File.Nodes[k]; strings.HasPrefix(c.Raw, "//") && !strings.Contains(sep, "\n") { sep = "\n" } at = k + 1 } } inserted := append([]*Node{{Kind: KindSpace, Raw: sep}}, nodes...) // A value runs to the end of its line unless a header, opcode, comment or // directive ends it, so text after the new opcode on its line would become // part of the value. A line break after the opcode keeps it out. k := at for k < len(h.File.Nodes) && h.File.Nodes[k].Kind == KindSpace && !strings.Contains(h.File.Nodes[k].Raw, "\n") { k++ } if k < len(h.File.Nodes) && h.File.Nodes[k].Kind == KindText { inserted = append(inserted, &Node{Kind: KindSpace, Raw: "\n"}) } h.File.insert(at, inserted...) return nil } // unterminated reports whether n is a block comment that never ends, and so // takes in all that follows it. func unterminated(n *Node) bool { return n.Kind == KindComment && strings.HasPrefix(n.Raw, "/*") && (len(n.Raw) < 4 || !strings.HasSuffix(n.Raw, "*/")) } // hasLineBreak reports whether the file has a line break anywhere. func (f *File) hasLineBreak() bool { for _, n := range f.Nodes { if n.Kind == KindSpace && strings.Contains(n.Raw, "\n") { return true } } return false } // Delete removes the opcode, each time the header has it, with the space that // separated it from what came before, and leaves the line breaks around other // text as they are. func (h *Header) Delete(name string) { for { n, ok := h.Get(name) if !ok { return } i := h.File.indexOf(n) from, to := i, i+1 isSpace := func(i int, lineBreak bool) bool { return i >= 0 && i < len(h.File.Nodes) && h.File.Nodes[i].Kind == KindSpace && strings.Contains(h.File.Nodes[i].Raw, "\n") == lineBreak } switch { case isSpace(i-1, false): from = i - 1 case isSpace(i-1, true): // The line break before the opcode goes with it only if the opcode ends // its line, so that its whole line goes. Otherwise the text after it // keeps its line, and the space that separated it from the opcode goes. if i+1 >= len(h.File.Nodes) || isSpace(i+1, true) || h.File.Nodes[i+1].Kind == KindHeader { from = i - 1 } else if isSpace(i+1, false) { to = i + 2 } } h.File.Nodes = slices.Delete(h.File.Nodes, from, to) h.File.dirty = true } } // insert adds nodes to the file at the index. func (f *File) insert(at int, nodes ...*Node) { f.Nodes = slices.Insert(f.Nodes, at, nodes...) for i, n := range nodes { n.idx = at + i } f.dirty = true } // Position returns the line and the column, both from 1, where a node of the // file starts. The column is in bytes. Edits move the nodes after them, which // Position works out when it is next called, and not at each edit. func (f *File) Position(n *Node) (line, col int) { if f.dirty { f.reposition() } return n.line, n.col } // reposition sets the line, column and index of each node from the text before // it. func (f *File) reposition() { line, col := 1, 1 for i, n := range f.Nodes { n.line, n.col, n.idx = line, col, i for j := 0; j < len(n.Raw); j++ { if n.Raw[j] == '\n' { line++ col = 1 } else { col++ } } } f.dirty = false } // Headers returns the headers of every file of the document, in the order the // files are read, as [Document.Files] returns them. func (d *Document) Headers() []*Header { var out []*Header for _, f := range d.Files() { for _, n := range f.Nodes { if n.Kind == KindHeader { out = append(out, &Header{File: f, Node: n}) } } } return out } // AddHeader adds an empty header, on a line of its own, after the header after // and its opcodes, or at the end of the main file if after is nil, and returns // it. It returns an error wrapping [ErrInvalid] if name isn't one that a header // can have, or if the header would fall inside a block comment that never ends. func (d *Document) AddHeader(name string, after *Header) (*Header, error) { if m := headerRE.FindString("<" + name + ">"); m != "<"+name+">" { return nil, fmt.Errorf("%w: <%s> isn't a header", ErrInvalid, name) } f := d.Root at := len(f.Nodes) if after != nil { f = after.File _, at = after.span() } if at > 0 { // A header after a block comment that never ends would be inside the // comment. if c := f.Nodes[at-1]; unterminated(c) { return nil, fmt.Errorf("%w: a comment that doesn't end is where <%s> would go", ErrInvalid, name) } } var nodes []*Node if at > 0 && !strings.HasSuffix(f.Nodes[at-1].Raw, "\n") { nodes = append(nodes, &Node{Kind: KindSpace, Raw: "\n"}) } h := &Node{Kind: KindHeader, Raw: "<" + name + ">", Name: name} nodes = append(nodes, h, &Node{Kind: KindSpace, Raw: "\n"}) f.insert(at, nodes...) return &Header{File: f, Node: h}, nil } // Defines returns the #define nodes of every file, in order. func (d *Document) Defines() []*Node { return d.nodes(KindDefine) } // Includes returns the #include nodes of every file, in order. func (d *Document) Includes() []*Node { return d.nodes(KindInclude) } // nodes returns the nodes of a kind in every file, in order. func (d *Document) nodes(kind NodeKind) []*Node { var out []*Node for _, f := range d.Files() { for _, n := range f.Nodes { if n.Kind == kind { out = append(out, n) } } } return out } // SetDefine gives a variable a new value by changing its first #define, so // that each opcode that uses the variable changes with it. [Header.Set] on an // opcode that uses the variable replaces the variable in that opcode instead. A // variable with no #define gets one at the start of the main file. The name // includes its $. SetDefine returns an error wrapping [ErrInvalid], and changes // nothing, if the name and value can't be written as a #define. func (d *Document) SetDefine(name, value string) error { value = strings.TrimSpace(value) if err := checkDefine(name, value); err != nil { return err } for _, f := range d.Files() { for _, n := range f.Nodes { if n.Kind == KindDefine && n.Name == name { n.Raw = "#define " + name + " " + value n.Value = value f.dirty = true return nil } } } d.Root.insert(0, &Node{Kind: KindDefine, Raw: "#define " + name + " " + value, Name: name, Value: value}, &Node{Kind: KindSpace, Raw: "\n"}) return nil }