SPB Git

Repository Public

gen_reference.rs 10.5 KB 265 lines rust

1//! ORIX Sonata2//! File: crates/sonata-cli/examples/gen_reference.rs3//! Description: Generates the parameter reference of the manual from the runtime registry and4//! the standard-library sources, so the documentation cannot diverge from what the compiler5//! validates. Run through Scripts/gen-reference.sh; `--check` fails when a committed file is stale.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use sonata_ir::{ParamDesc, Registry, Unit};11use std::fmt::Write;12use std::path::{Path, PathBuf};1314const HEADER: &str = "<!--\nORIX Sonata\nFile: Documentation/manual/reference/{FILE}\nGenerated file — do not edit. Regenerate with Scripts/gen-reference.sh\nAuthor: Simon-Pierre Boucher\nContact: contact@spboucher.ai\n-->\n";1516fn unit(u: Unit) -> &'static str {17    match u {18        Unit::Scalar => "number",19        Unit::Ratio => "0–1 or %",20        Unit::Decibel => "dB",21        Unit::Hertz => "Hz",22        Unit::Seconds => "time (s, ms or a duration)",23        Unit::Semitones => "st or cents",24        Unit::Count => "integer",25        Unit::Degrees => "deg",26        Unit::HertzList => "list of Hz",27        Unit::ScalarList => "list of numbers",28        Unit::Choice => "choice",29    }30}3132fn num(x: f64) -> String {33    if x == x.round() && x.abs() < 1e9 {34        format!("{}", x as i64)35    } else {36        let s = format!("{x:.6}");37        s.trim_end_matches('0').trim_end_matches('.').to_string()38    }39}4041/// Markdown table cells must not contain a bare pipe or a line break.42fn cell(s: &str) -> String {43    s.replace('|', "\\|").replace('\n', " ")44}4546fn params(out: &mut String, list: &[ParamDesc]) {47    if list.is_empty() {48        out.push_str("No parameter.\n\n");49        return;50    }51    out.push_str("| Parameter | Unit | Range | Default | Automatable | Description |\n|---|---|---|---|---|---|\n");52    for p in list {53        let (range, default) = match p.unit {54            Unit::Choice => {55                (p.choices.iter().map(|c| format!("`{c}`")).collect::<Vec<_>>().join(" "), format!("`{}`", p.default_choice.clone().unwrap_or_default()))56            }57            Unit::HertzList | Unit::ScalarList => (format!("each {} to {}", num(p.min), num(p.max)), "—".to_string()),58            _ => (format!("{} to {}", num(p.min), num(p.max)), num(p.default)),59        };60        let _ = writeln!(out, "| `{}` | {} | {} | {} | {} | {} |", p.name, unit(p.unit), range, default, if p.automatable { "yes" } else { "" }, cell(&p.doc));61    }62    out.push('\n');63}6465fn head(file: &str, title: &str, intro: &str) -> String {66    format!("{}# {title}\n\n{intro}\n\n", HEADER.replace("{FILE}", file))67}6869/// Name, model and preset of every `instrument` definition of the standard library, in order,70/// with the comment line that introduces each group.71pub fn std_instruments(source: &str) -> Vec<(String, String, String, String)> {72    let mut out = Vec::new();73    let mut group = String::new();74    let mut current: Option<(String, String, String)> = None;75    for line in source.lines() {76        let t = line.trim();77        if let Some(c) = t.strip_prefix("// ") {78            if current.is_none()79                && !c.starts_with("ORIX")80                && !c.starts_with("File:")81                && !c.starts_with("Description:")82                && !c.starts_with("Author:")83                && !c.starts_with("Contact:")84            {85                group = c.to_string();86            }87        } else if let Some(rest) = t.strip_prefix("instrument ") {88            let name = rest.trim_end_matches('{').trim().to_string();89            current = Some((name, String::new(), String::new()));90        } else if let Some(m) = t.strip_prefix("model ") {91            if let Some(c) = current.as_mut() {92                c.1 = m.trim().to_string();93            }94        } else if let Some(p) = t.strip_prefix("preset ") {95            if let Some(c) = current.as_mut() {96                c.2 = p.trim().to_string();97            }98        } else if t == "}" {99            if let Some((n, m, p)) = current.take() {100                out.push((n, m, p, group.clone()));101            }102        }103    }104    out105}106107/// The four reference files as (file name, content).108pub fn generate(r: &Registry, std_instruments_source: &str) -> Vec<(String, String)> {109    let mut files = Vec::new();110111    let mut s = head(112        "instruments.md",113        "Instrument engines",114        &format!("The {} engines of Sonata {} with every parameter the compiler accepts. An engine is selected with `model NAME` in an instrument definition; the named instruments of the standard library are listed in [Standard instruments](std-instruments.md).", r.engines.len(), sonata_ir::LANGUAGE_VERSION),115    );116    s.push_str("| Engine | Family | Presets | Method |\n|---|---|---|---|\n");117    for e in &r.engines {118        let _ = writeln!(s, "| [`{}`](#{}) | {} | {} | {} |", e.model, e.model.replace('_', "-"), e.family, e.presets.len(), cell(&e.method));119    }120    s.push('\n');121    for e in &r.engines {122        let _ = writeln!(s, "## {}\n\n**{}** — family {}. {}\n", e.model, e.title, e.family, e.doc);123        let _ = writeln!(s, "*Method.* {}\n", e.method);124        let _ = writeln!(125            s,126            "*Range.* MIDI {} to {}{}. *Articulations.* {}.\n",127            e.range.0,128            e.range.1,129            if e.pitched { "" } else { " (unpitched: the note pitch is ignored)" },130            e.articulations.join(", ")131        );132        params(&mut s, &e.params);133        if !e.presets.is_empty() {134            s.push_str("| Preset | Description |\n|---|---|\n");135            for p in &e.presets {136                let _ = writeln!(s, "| `{}` | {} |", p.name, cell(&p.doc));137            }138            s.push('\n');139        }140    }141    files.push(("instruments.md".to_string(), s));142143    let mut s = head(144        "effects.md",145        "Effects",146        &format!(147            "The {} effects with their parameters and presets. Every effect also takes `mix`, its dry/wet ratio from 0 to 1 (or a percentage).",148            r.effects.len()149        ),150    );151    s.push_str("| Effect | Category | Default mix | Latency | Presets |\n|---|---|---|---|---|\n");152    for e in &r.effects {153        let lat = e.latency.at(48_000);154        let _ = writeln!(155            s,156            "| [`{}`](#{}) | {} | {} | {} | {} |",157            e.kind,158            e.kind.replace('_', "-"),159            e.category,160            num(e.default_mix),161            if lat == 0 { "none".to_string() } else { format!("{lat} samples at 48 kHz") },162            e.presets.iter().map(|p| format!("`{}`", p.name)).collect::<Vec<_>>().join(" ")163        );164    }165    s.push('\n');166    for e in &r.effects {167        let _ = writeln!(s, "## {}\n\n**{}** — {}. {}\n", e.kind, e.title, e.category, e.doc);168        params(&mut s, &e.params);169        if !e.presets.is_empty() {170            s.push_str("| Preset | Description | Values |\n|---|---|---|\n");171            for p in &e.presets {172                let mut values: Vec<String> = p.values.iter().map(|(k, v)| format!("{k} = {}", num(*v))).collect();173                values.extend(p.choices.iter().map(|(k, v)| format!("{k} = {v}")));174                let _ = writeln!(s, "| `{}` | {} | {} |", p.name, cell(&p.doc), cell(&values.join(", ")));175            }176            s.push('\n');177        }178    }179    files.push(("effects.md".to_string(), s));180181    let mut s = head(182        "patch-nodes.md",183        "Patch nodes",184        &format!(185            "The {} node kinds available inside `graph {{ }}` of an instrument with `model patch`. Ports are given by name; a port left out takes its default.",186            r.patch_nodes.len()187        ),188    );189    for n in &r.patch_nodes {190        let rate = match n.output_rate {191            sonata_ir::Rate::Audio => "audio rate",192            sonata_ir::Rate::Control => "control rate",193        };194        let _ = writeln!(s, "## {}\n\n**{}** — {}, {}. {}\n", n.kind, n.title, n.category, rate, n.doc);195        if n.ports.is_empty() {196            s.push_str("No port.\n\n");197            continue;198        }199        s.push_str("| Port | Unit | Range | Default | Constant only | Description |\n|---|---|---|---|---|---|\n");200        for p in &n.ports {201            let _ = writeln!(202                s,203                "| `{}` | {} | {} to {} | {} | {} | {} |",204                p.name,205                unit(p.unit),206                num(p.min),207                num(p.max),208                num(p.default),209                if p.constant_only { "yes" } else { "" },210                cell(&p.doc)211            );212        }213        s.push('\n');214    }215    files.push(("patch-nodes.md".to_string(), s));216217    let list = std_instruments(std_instruments_source);218    let mut s = head(219        "std-instruments.md",220        "Standard instruments",221        &format!("The {} named instruments of `std.instruments`. Each one is an engine with one of its presets; they are always in scope.", list.len()),222    );223    let mut group = String::new();224    for (name, model, preset, g) in &list {225        if *g != group {226            group = g.clone();227            let _ = writeln!(s, "\n## {}\n\n| Instrument | Engine | Preset | Sound |\n|---|---|---|---|", group.trim_end_matches('.'));228        }229        let doc = r.engine(model).and_then(|e| e.presets.iter().find(|p| &p.name == preset)).map(|p| p.doc.clone()).unwrap_or_default();230        let _ = writeln!(s, "| `{name}` | [`{model}`](instruments.md#{}) | `{preset}` | {} |", model.replace('_', "-"), cell(&doc));231    }232    files.push(("std-instruments.md".to_string(), s));233    files234}235236#[allow(dead_code)]237fn repo() -> PathBuf {238    Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")239}240241#[allow(dead_code)]242fn main() {243    let check = std::env::args().any(|a| a == "--check");244    let source = std::fs::read_to_string(repo().join("StandardLibrary/std/instruments.sonata")).expect("the standard library is readable");245    let dir = repo().join("Documentation/manual/reference");246    let mut stale = false;247    for (name, content) in generate(sonata_compiler::registry(), &source) {248        let path = dir.join(&name);249        if check {250            if std::fs::read_to_string(&path).ok().as_deref() != Some(content.as_str()) {251                eprintln!("stale: Documentation/manual/reference/{name}");252                stale = true;253            }254        } else {255            std::fs::create_dir_all(&dir).expect("the reference directory can be created");256            std::fs::write(&path, content).expect("the reference file can be written");257            println!("wrote Documentation/manual/reference/{name}");258        }259    }260    if stale {261        eprintln!("run Scripts/gen-reference.sh");262        std::process::exit(1);263    }264}265
Files main
Menu

Theme