Files
sfz/internal/gen/main.go
T

303 lines
8.6 KiB
Go
Raw Normal View History

// Command gen turns the SFZ format's syntax data into the sfz package's
// opcode registry.
//
// Usage: go run . -in syntax.yml -out ../../registry_data.go
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"html"
"log"
"os"
"regexp"
"sort"
"strconv"
"strings"
"gopkg.in/yaml.v3"
)
// entry is an opcode as it goes into the registry, with the fields of
// OpcodeInfo that the data gives it.
type entry struct {
name string
aliases []string
version string
deprecated bool
category string
typeName string
min, max *float64
def string
unit string
options []string
description string
}
// notes matches the names of the integer opcodes that also take a note name.
var notes = regexp.MustCompile(`^(?:key|(?:lo|hi)key|pitch_keycenter|sw_(?:lokey|hikey|last|previous|down|up|default)|xf(?:in|out)_(?:lo|hi)key|(?:lo|hi)_?key)$`)
// tags matches an HTML tag.
var tags = regexp.MustCompile(`<[^>]*>`)
// text turns one of the data's HTML snippets into plain text on one line. It
// returns an empty string for a value that isn't text.
func text(v any) string {
s, _ := v.(string)
s = html.UnescapeString(tags.ReplaceAllString(s, ""))
return strings.Join(strings.Fields(s), " ")
}
// str returns a value of the data as text, or an empty string if there is none.
func str(v any) string {
if v == nil {
return ""
}
return fmt.Sprint(v)
}
// number returns a number of the data, or nil if the value isn't one.
func number(v any) *float64 {
switch n := v.(type) {
case int:
f := float64(n)
return &f
case float64:
return &n
}
return nil
}
// asMap returns v as a map, or nil if it isn't one.
func asMap(v any) map[string]any {
m, _ := v.(map[string]any)
return m
}
// asList returns v as a list, or nil if it isn't one.
func asList(v any) []any {
l, _ := v.([]any)
return l
}
// generator collects the opcodes of the data.
type generator struct {
// entries are the opcodes read so far, in the order they are listed.
entries []*entry
byName map[string]*entry
}
// add reads an opcode of the data, and its aliases and modulations, into
// entries, and returns it, or nil if the data's entry isn't an opcode. inherit
// is the opcode whose value an opcode without one takes, or nil.
func (g *generator) add(x map[string]any, category string, inherit *entry) *entry {
name := str(x["name"])
if name == "" || x["macro"] == true {
return nil
}
e := &entry{name: name, version: str(x["version"]), category: category}
e.deprecated, _ = x["deprecated"].(bool)
e.description = text(x["short_description"])
if v := asMap(x["value"]); v != nil {
e.typeName = str(v["type_name"])
e.min, e.max = number(v["min"]), number(v["max"])
e.def, e.unit = text(v["default"]), str(v["unit"])
for _, o := range asList(v["options"]) {
e.options = append(e.options, str(asMap(o)["name"]))
}
} else if inherit != nil {
e.typeName, e.min, e.max, e.def, e.unit, e.options = inherit.typeName, inherit.min, inherit.max, inherit.def, inherit.unit, inherit.options
if e.description == "" {
e.description = inherit.description
}
}
if e.version == "" && inherit != nil {
e.version = inherit.version
}
g.entries = append(g.entries, e)
var independent []map[string]any
for _, a := range asList(x["alias"]) {
am := asMap(a)
if am == nil {
continue
}
// An alias with modulations of its own is another opcode, as cutoff2 is.
if am["modulation"] != nil {
independent = append(independent, am)
continue
}
e.aliases = append(e.aliases, str(am["name"]))
}
g.modulations(x, e, category, e)
for _, am := range independent {
g.addAlias(am, e, category)
}
return e
}
// addAlias reads an alias that is an opcode in its own right, whose
// modulations take their values from those of the opcode it copies.
func (g *generator) addAlias(am map[string]any, parent *entry, category string) {
own := &entry{name: str(am["name"]), version: str(am["version"]), category: category}
own.typeName, own.min, own.max, own.def, own.unit, own.options, own.description = parent.typeName, parent.min, parent.max, parent.def, parent.unit, parent.options, parent.description
if own.version == "" {
own.version = parent.version
}
own.deprecated, _ = am["deprecated"].(bool)
g.entries = append(g.entries, own)
g.modulations(am, own, category, parent)
}
// modulations reads the modulations that an opcode lists. A modulation
// without a value takes that of the one named like it under parent.
func (g *generator) modulations(x map[string]any, e *entry, category string, parent *entry) {
mods := asMap(x["modulation"])
keys := make([]string, 0, len(mods))
for k := range mods {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
for _, item := range asList(mods[k]) {
m := asMap(item)
if m == nil {
continue
}
var inherit *entry
if parent != e {
swapped := strings.Replace(str(m["name"]), e.name, parent.name, 1)
for _, c := range g.entries {
if c.name == swapped {
inherit = c
}
}
}
me := g.add(m, category, inherit)
if me != nil && me.version == "" {
me.version = e.version
}
}
}
}
// walk reads the opcodes under a part of the data's tree of categories into
// entries. The category of an opcode is the names of the categories it is under,
// joined with a slash; category is those of the parts above o.
func (g *generator) walk(o any, category string) {
switch v := o.(type) {
case map[string]any:
if n := str(v["name"]); n != "" && v["opcodes"] != nil && category == "" {
category = n
}
for _, x := range asList(v["opcodes"]) {
if m := asMap(x); m != nil {
g.add(m, category, nil)
}
}
for k, c := range v {
if k != "opcodes" {
g.walk(c, category)
}
}
case []any:
for _, c := range v {
cat := category
if m := asMap(c); m != nil {
if n := str(m["name"]); n != "" && (m["opcodes"] != nil || m["types"] != nil) {
if category == "" {
cat = n
} else if m["opcodes"] != nil {
cat = category + " / " + n
}
}
}
g.walk(c, cat)
}
}
}
// quote returns s as a Go string literal.
func quote(s string) string { return strconv.Quote(s) }
// fl returns the Go expression for an optional number: nil, or a pointer made
// with ptr.
func fl(p *float64) string {
if p == nil {
return "nil"
}
return "ptr(float64(" + strconv.FormatFloat(*p, 'g', -1, 64) + "))"
}
// main reads the syntax data and writes the registry's Go source.
func main() {
in := flag.String("in", "syntax.yml", "the syntax data")
out := flag.String("out", "registry_data.go", "the Go file to write")
flag.Parse()
data, err := os.ReadFile(*in)
if err != nil {
log.Fatal(err)
}
var doc map[string]any
if err := yaml.Unmarshal(data, &doc); err != nil {
log.Fatal(err)
}
g := &generator{byName: map[string]*entry{}}
g.walk(doc["categories"], "")
var b bytes.Buffer
b.WriteString("// Code generated by internal/gen from the SFZ format's syntax data; DO NOT EDIT.\n\npackage sfz\n\n")
b.WriteString("// headerData are the headers of the format.\nvar headerData = []HeaderInfo{\n")
for _, h := range asList(doc["headers"]) {
m := asMap(h)
dep, _ := m["deprecated"].(bool)
fmt.Fprintf(&b, "\t{Name: %s, Version: %s, Deprecated: %t, Description: %s},\n",
quote(str(m["name"])), quote(str(m["version"])), dep, quote(text(m["short_description"])))
}
b.WriteString("}\n\n// opcodeData are the opcodes of the format, with their aliases.\nvar opcodeData = []OpcodeInfo{\n")
seen := map[string]bool{}
count := 0
for _, e := range g.entries {
if seen[e.name] {
log.Printf("duplicate opcode %s", e.name)
continue
}
seen[e.name] = true
count++
typ := map[string]string{"integer": "TypeInteger", "float": "TypeFloat", "string": "TypeString"}[e.typeName]
if typ == "" {
typ = "TypeUnspecified"
}
note := e.typeName == "integer" && notes.MatchString(e.name)
fmt.Fprintf(&b, "\t{Name: %s, Aliases: %s, Version: %s, Deprecated: %t, Category: %s, Type: %s, Min: %s, Max: %s, Default: %s, Unit: %s, Options: %s, Note: %t, Description: %s},\n",
quote(e.name), strs(e.aliases), quote(e.version), e.deprecated, quote(e.category), typ, fl(e.min), fl(e.max),
quote(e.def), quote(e.unit), strs(e.options), note, quote(e.description))
}
b.WriteString("}\n")
src, err := format.Source(b.Bytes())
if err != nil {
os.WriteFile(*out, b.Bytes(), 0o644)
log.Fatal(err)
}
if err := os.WriteFile(*out, src, 0o644); err != nil {
log.Fatal(err)
}
log.Printf("wrote %d opcodes", count)
}
// strs returns the Go expression for a list of strings.
func strs(s []string) string {
if len(s) == 0 {
return "nil"
}
q := make([]string, len(s))
for i, v := range s {
q[i] = quote(v)
}
return "[]string{" + strings.Join(q, ", ") + "}"
}