SPB Git

Repository Public

examples.rs 11.3 KB 259 lines rust

1//! ORIX Sonata2//! File: crates/sonata-compiler/tests/examples.rs3//! Description: Every file of Examples/ compiles with the real registry, formats idempotently,4//! compiles deterministically and yields instruments and effects the DSP crates can build.5//! Golden AST / IR / graph files live in Tests/golden (SONATA_UPDATE_GOLDEN=1 rewrites them).6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use sonata_compiler::{compile, format, registry, CompileOptions, CompileOutput, DirLoader};11use std::path::{Path, PathBuf};1213fn repo() -> PathBuf {14    Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").canonicalize().unwrap()15}1617fn examples() -> Vec<PathBuf> {18    let mut v: Vec<PathBuf> = std::fs::read_dir(repo().join("Examples"))19        .unwrap()20        .filter_map(|e| e.ok().map(|e| e.path()))21        .filter(|p| p.extension().map(|e| e == "sonata").unwrap_or(false))22        .collect();23    v.sort();24    assert!(v.len() >= 12, "expected at least 12 examples, found {}", v.len());25    v26}2728fn build(path: &Path, source: &str) -> CompileOutput {29    let name = format!("Examples/{}", path.file_name().unwrap().to_string_lossy());30    compile(&name, source, &DirLoader::new(repo().join("Examples")), &CompileOptions::default())31}3233fn strip_spans(v: &mut serde_json::Value) {34    match v {35        serde_json::Value::Object(m) => {36            m.retain(|k, _| !k.ends_with("span"));37            m.values_mut().for_each(strip_spans);38        }39        serde_json::Value::Array(a) => a.iter_mut().for_each(strip_spans),40        _ => {}41    }42}4344#[test]45fn the_registry_of_this_build_is_valid_and_complete() {46    let r = registry();47    r.validate().unwrap();48    for model in [49        "piano",50        "plucked_string",51        "bowed_string",52        "flute",53        "clarinet",54        "brass",55        "organ",56        "bass",57        "synth",58        "kick",59        "snare",60        "hihat",61        "modal_percussion",62        "patch",63    ] {64        assert!(r.engine(model).is_some(), "engine '{model}' is missing");65    }66    for kind in ["eq", "compressor", "limiter", "gate", "delay", "chorus", "flanger", "phaser", "reverb", "distortion", "stereo_width", "tremolo", "autopan"] {67        assert!(r.effect(kind).is_some(), "effect '{kind}' is missing");68    }69    for node in ["sine", "saw", "adsr", "lowpass", "add", "mul", "delay"] {70        assert!(r.patch_node(node).is_some(), "patch node '{node}' is missing");71    }72}7374#[test]75fn every_example_compiles_cleanly_and_is_buildable() {76    for path in examples() {77        let source = std::fs::read_to_string(&path).unwrap();78        let out = build(&path, &source);79        assert!(out.diagnostics.is_empty(), "{}:\n{}", path.display(), out.render_diagnostics());80        let program = out.program.as_ref().unwrap_or_else(|| panic!("{} has no program", path.display()));81        let graph = out.graph.as_ref().unwrap();82        graph.validate().unwrap();83        assert!(program.stats.notes > 0 && program.end_sec > 0.0, "{} is silent", path.display());84        assert_eq!(out.stats.events, program.stats.notes);85        assert_eq!(out.stats.nodes as usize, graph.nodes.len());86        // What the compiler emits must be accepted by the DSP crates.87        for t in &program.tracks {88            if let Some(spec) = &t.instrument {89                if let Err(e) = sonata_instruments::create_instrument(spec, program.tuning_hz, program.seed) {90                    panic!("{}: instrument '{}' of track '{}' cannot be built: {e}", path.display(), spec.name, t.name);91                }92            }93            for fx in &t.effects {94                assert!(sonata_dsp::create_effect(&fx.kind).is_some(), "{}: effect '{}'", path.display(), fx.kind);95            }96        }97        for fx in program.buses.iter().flat_map(|b| &b.effects).chain(&program.master.effects) {98            assert!(sonata_dsp::create_effect(&fx.kind).is_some(), "{}: effect '{}'", path.display(), fx.kind);99        }100    }101}102103#[test]104fn every_standard_instrument_resolves_and_builds() {105    let std = sonata_semantics::STD_MODULES.iter().find(|(n, _)| *n == "std.instruments").unwrap().1;106    let names: Vec<&str> = std.lines().filter_map(|l| l.strip_prefix("instrument ")).map(|l| l.split_whitespace().next().unwrap()).collect();107    assert!(names.len() >= 80, "{} standard instruments", names.len());108    let mut src = String::from("composition \"all\" {\n");109    for (i, n) in names.iter().enumerate() {110        src.push_str(&format!("    instrument t{i}: {n} {{ play C4 }}\n"));111    }112    src.push('}');113    let out = compile("all.sonata", &src, &sonata_compiler::NoLoader, &CompileOptions::default());114    assert!(!out.has_errors(), "{}", out.render_diagnostics());115    let program = out.program.unwrap();116    let mut distinct = std::collections::BTreeSet::new();117    for t in &program.tracks {118        let spec = t.instrument.as_ref().unwrap();119        sonata_instruments::create_instrument(spec, 440.0, 0).unwrap_or_else(|e| panic!("{}: {e}", spec.name));120        distinct.insert(format!("{}:{}", spec.model, serde_json::to_string(&spec.params).unwrap()));121    }122    // No two standard instruments are the same engine with the same parameters, except that a123    // preset equal to the engine defaults legitimately has no override.124    assert!(distinct.len() >= names.len() - 15, "{} distinct sounds for {} names", distinct.len(), names.len());125}126127#[test]128fn formatting_is_idempotent_and_preserves_meaning() {129    let mut files = examples();130    files.push(repo().join("Examples/lib/motifs.sonata"));131    for path in files {132        let source = std::fs::read_to_string(&path).unwrap();133        let once = format(&source).unwrap_or_else(|d| panic!("{}: {d:?}", path.display()));134        assert_eq!(format(&once).unwrap(), once, "{} is not stable under formatting", path.display());135        assert_eq!(once, source, "{} is not in canonical format (run: cargo run -p sonata-compiler --example check -- <file> --fmt)", path.display());136        if path.parent().unwrap().ends_with("lib") {137            continue;138        }139        let (a, b) = (build(&path, &source), build(&path, &once));140        let (mut ja, mut jb) = (serde_json::to_value(a.program.as_deref()).unwrap(), serde_json::to_value(b.program.as_deref()).unwrap());141        strip_spans(&mut ja);142        strip_spans(&mut jb);143        assert_eq!(ja, jb, "{}: formatting changed the program", path.display());144    }145    for (name, text) in sonata_semantics::STD_MODULES {146        let once = format(text).unwrap_or_else(|d| panic!("{name}: {d:?}"));147        assert_eq!(&once, text, "{name} is not in canonical format");148    }149}150151#[test]152fn compilation_is_deterministic() {153    for path in examples() {154        let source = std::fs::read_to_string(&path).unwrap();155        let (a, b) = (build(&path, &source), build(&path, &source));156        assert_eq!(a.program, b.program, "{}", path.display());157        assert_eq!(a.graph, b.graph, "{}", path.display());158        assert_eq!(a.program_json(), b.program_json());159    }160}161162fn golden(name: &str, actual: &str) {163    let path = repo().join("Tests/golden").join(name);164    if std::env::var("SONATA_UPDATE_GOLDEN").is_ok() {165        std::fs::write(&path, actual).unwrap();166        return;167    }168    let expected = std::fs::read_to_string(&path).unwrap_or_else(|_| panic!("missing golden file {}; run with SONATA_UPDATE_GOLDEN=1", path.display()));169    if expected != actual {170        let (e, a): (Vec<&str>, Vec<&str>) = (expected.lines().collect(), actual.lines().collect());171        let line = e.iter().zip(&a).position(|(x, y)| x != y).unwrap_or(e.len().min(a.len()));172        panic!("{name} differs from the golden file at line {}:\n  expected: {}\n  actual:   {}\nIf the change is intended, run with SONATA_UPDATE_GOLDEN=1 and review the diff.", line + 1, e.get(line).unwrap_or(&"<end>"), a.get(line).unwrap_or(&"<end>"));173    }174}175176#[test]177fn golden_ast_ir_and_graph() {178    for name in ["aurora", "crystal_harp", "subtractive_patch"] {179        let path = repo().join(format!("Examples/{name}.sonata"));180        let out = build(&path, &std::fs::read_to_string(&path).unwrap());181        assert!(!out.has_errors());182        golden(&format!("{name}.ast.json"), &(out.ast_json() + "\n"));183        golden(&format!("{name}.ir.json"), &(out.program_json() + "\n"));184        golden(&format!("{name}.graph.json"), &(out.graph_json() + "\n"));185    }186}187188#[test]189fn aurora_has_the_expected_music() {190    let path = repo().join("Examples/aurora.sonata");191    let out = build(&path, &std::fs::read_to_string(&path).unwrap());192    let p = out.program.unwrap();193    assert_eq!((p.title.as_str(), p.seed, p.master.sample_rate, p.master.peak_limit_db), ("Aurora", 42, 48_000, Some(-1.0)));194    let piano = &p.tracks[0];195    assert_eq!((piano.name.as_str(), piano.gain_db, piano.notes.len()), ("piano", -8.0, 7));196    assert_eq!(piano.instrument.as_ref().unwrap().model, "piano");197    assert_eq!(piano.effects[0].kind, "reverb");198    assert!((piano.effects[0].mix - 0.2).abs() < 1e-12);199    // D minor chord for a half note at 120 bpm = 1 s, then F major, a quarter rest, then A4.200    assert_eq!(piano.notes[..3].iter().map(|n| n.pitch).collect::<Vec<_>>(), vec![50.0, 57.0, 62.0]);201    assert!(piano.notes[..3].iter().all(|n| n.start_sec == 0.0 && (n.end_sec - 1.0).abs() < 1e-12));202    let a4 = piano.notes.last().unwrap();203    assert_eq!((a4.pitch, a4.velocity), (69.0, 0.75));204    assert!((a4.start_sec - 2.5).abs() < 1e-12 && (a4.end_sec - 3.0).abs() < 1e-12);205    let strings = &p.tracks[1];206    assert_eq!(strings.notes[0].articulation, sonata_ir::Articulation::Legato);207    assert!((strings.notes[0].end_sec - 2.0).abs() < 1e-12);208    assert!((p.end_sec - 3.0).abs() < 1e-12);209}210211/// The two listings of the engineering mandate, byte for byte.212const MANDATE_AURORA: &str = r#"import std.music213import std.effects214composition "Aurora" {215    tempo 120bpm216    key D minor217    signature 4/4218    seed 42219    instrument piano: GrandPiano {220        gain -8dB221        sequence {222            chord [D3, A3, D4] duration 1/2223            chord [F3, A3, C4] duration 1/2224            rest 1/4225            play A4 duration 1/4 velocity 0.75226        }227        effects { reverb hall(mix: 0.2) }228    }229    instrument strings: ConcertStrings {230        articulation legato231        play D4 duration 1/1232    }233    master { sample_rate 48000Hz; peak_limit -1dB }234}235"#;236237const MANDATE_CRYSTAL_HARP: &str = r#"instrument CrystalHarp {238    model plucked_string239    damping 0.015240    excitation pluck(position: 0.35)241    resonance modal(frequencies: [440Hz, 880Hz, 1320Hz])242    envelope adsr(attack: 5ms, decay: 300ms, sustain: 0.6, release: 2s)243}244"#;245246#[test]247fn the_mandate_listings_compile_unchanged() {248    let out = compile("aurora.sonata", MANDATE_AURORA, &sonata_compiler::NoLoader, &CompileOptions::default());249    assert!(out.diagnostics.is_empty(), "{}", out.render_diagnostics());250    assert_eq!(out.program.as_ref().unwrap().stats.notes, 8);251    let src = format!("{MANDATE_CRYSTAL_HARP}composition \"h\" {{ instrument h: CrystalHarp {{ play A4 }} }}");252    let out = compile("harp.sonata", &src, &sonata_compiler::NoLoader, &CompileOptions::default());253    assert!(out.diagnostics.is_empty(), "{}", out.render_diagnostics());254    let p = out.program.unwrap();255    let spec = p.tracks[0].instrument.as_ref().unwrap();256    assert_eq!(spec.params["resonance.frequencies"], sonata_ir::ParamValue::List(vec![440.0, 880.0, 1320.0]));257    sonata_instruments::create_instrument(spec, 440.0, 0).unwrap();258}259
Files main
Menu

Theme