SPB Git

Repository Public

semantics.rs 29.4 KB 536 lines rust

1//! ORIX Sonata2//! File: crates/sonata-semantics/tests/semantics.rs3//! Description: Semantic analysis tests against the fixture registry: timing, units, music4//! transforms, instruments, effects, graphs, routing, quotas, imports, determinism.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use sonata_ir::*;10use sonata_semantics::testing::fixture_registry;11use sonata_semantics::*;1213const DEFS: &str = "instrument Piano { model piano }\ninstrument Lead { model synth }\n";1415fn run_with(src: &str, loader: &dyn SourceLoader, options: &Options) -> Analysis {16    let set = load_modules("test.sonata", src, loader, options.quotas.max_import_depth);17    analyze(&set, &fixture_registry(), options)18}19fn run(src: &str) -> Analysis {20    run_with(src, &NoLoader, &Options::default())21}22fn ok(src: &str) -> Program {23    let a = run(src);24    assert!(!a.has_errors(), "{:#?}", a.diagnostics);25    a.program.expect("program")26}27/// A composition with one piano track `p` holding `body`.28fn piece(settings: &str, body: &str) -> String {29    format!("{DEFS}composition \"t\" {{\n{settings}\ninstrument p: Piano {{\n{body}\n}}\n}}")30}31fn codes(src: &str) -> Vec<String> {32    run(src).diagnostics.iter().filter(|d| d.is_error()).map(|d| d.code.clone()).collect()33}34fn warnings(src: &str) -> Vec<String> {35    run(src).diagnostics.iter().filter(|d| d.severity == Severity::Warning).map(|d| d.code.clone()).collect()36}37fn r(n: i64, d: i64) -> Rational {38    Rational::new(n, d).unwrap()39}40fn close(a: f64, b: f64) -> bool {41    (a - b).abs() < 1e-942}4344#[test]45fn notes_are_timed_exactly() {46    let p = ok(&piece("tempo 120bpm", "play D4 duration 1/4\nchord [F3, A3, C4] duration 1/2 velocity 0.5\nrest 1/4\nplay A4"));47    let t = &p.tracks[0];48    assert_eq!(t.notes.len(), 5);49    assert_eq!((t.notes[0].pitch, t.notes[0].start, t.notes[0].duration), (62.0, Rational::ZERO, r(1, 4)));50    assert!(close(t.notes[0].end_sec, 0.5));51    // Chord notes share a start and are ordered by pitch.52    assert_eq!(t.notes[1..4].iter().map(|n| n.pitch).collect::<Vec<_>>(), vec![53.0, 57.0, 60.0]);53    assert!(t.notes[1..4].iter().all(|n| n.start == r(1, 4) && close(n.start_sec, 0.5) && close(n.end_sec, 1.5) && n.velocity == 0.5));54    // Defaults: 1/4 and velocity 0.8, after the rest.55    assert_eq!((t.notes[4].start, t.notes[4].duration, t.notes[4].velocity), (r(1, 1), r(1, 4), 0.8));56    assert_eq!(t.notes.iter().map(|n| n.id).collect::<Vec<_>>(), (0..5u64).collect::<Vec<_>>());57    assert_eq!(p.stats.notes, 5);58    assert_eq!(p.stats.max_polyphony, 3);59    assert!(close(p.end_sec, 2.5));60    assert_eq!(seconds_to_samples(t.notes[4].start_sec, 48_000), 96_000);61}6263#[test]64fn tempo_changes_ramps_and_signatures() {65    let p = ok(&piece(66        "tempo 120bpm\nsignature 3/4",67        "play C4 duration 1bar\ntempo 60bpm\nplay C4 duration 2beats\nrest 1beat\nsignature 4/4\nplay C4 duration 1bar",68    ));69    // 3/4 bar at 120 = 1.5 s; then 2 beats at 60 = 2 s.70    let n = &p.tracks[0].notes;71    assert_eq!(n[0].duration, r(3, 4));72    assert!(close(n[0].end_sec, 1.5) && close(n[1].end_sec, 3.5));73    assert_eq!(p.tempo_map.points.len(), 2);74    assert_eq!(p.signatures.iter().map(|s| (s.at, s.numerator)).collect::<Vec<_>>(), vec![(Rational::ZERO, 3), (r(3, 2), 4)]);75    assert_eq!(n[2].duration, r(1, 1), "1bar follows the signature in effect at the cursor");76    assert_eq!(codes(&piece("signature 3/4", "play C4 duration 1/4\nsignature 4/4")), vec!["M4002"]);7778    let p = ok(&piece("tempo 120bpm", "rest 1bar\ntempo 60bpm ramp 1bar\nplay C4 duration 2bars"));79    assert_eq!(80        p.tempo_map.points.iter().map(|t| (t.at, t.bpm, t.ramp)).collect::<Vec<_>>(),81        vec![(Rational::ZERO, 120.0, false), (r(1, 1), 120.0, true), (r(2, 1), 60.0, false)]82    );83    // Bar 2 ramps 2 s/whole -> 4 s/whole (mean 3 s); bar 3 lasts 4 s.84    assert!(close(p.tracks[0].notes[0].start_sec, 2.0) && close(p.tracks[0].notes[0].end_sec, 9.0));85    assert_eq!(codes(&piece("tempo 0bpm", "")), vec!["M4003"]);86    assert_eq!(codes(&piece("tempo 120", "")), vec!["T3006"]);87    assert_eq!(codes(&format!("{DEFS}composition \"t\" {{ instrument a: Piano {{ tempo 90bpm }}; instrument b: Piano {{ tempo 100bpm }} }}")), vec!["M4004"]);88}8990#[test]91fn swing_tuplets_and_articulations() {92    let p = ok(&piece("tempo 120bpm\nswing 66% of 1/8", "repeat 4 { play C4 duration 1/8 }"));93    let starts: Vec<Rational> = p.tracks[0].notes.iter().map(|n| n.start).collect();94    // Off-beat eighths are delayed by (2·0.66 − 1)/8 = 0.04 of a whole note.95    assert_eq!(starts, vec![Rational::ZERO, r(1, 8).checked_add(r(32, 800)).unwrap(), r(1, 4), r(3, 8).checked_add(r(32, 800)).unwrap()]);96    assert_eq!(p.tracks[0].notes[1].notated_start, r(1, 8));97    assert_eq!(codes(&piece("swing 90%", "")), vec!["M4006"]);9899    let p = ok(&piece("", "tuplet 3 in 2 { repeat 3 { play C4 duration 1/8 } }\nplay D4"));100    let n = &p.tracks[0].notes;101    assert_eq!(n.iter().map(|x| x.start).collect::<Vec<_>>(), vec![Rational::ZERO, r(1, 12), r(1, 6), r(1, 4)]);102    assert_eq!(n[0].duration, r(1, 12));103104    let p = ok(&piece("", "play C4 staccato\nplay C4 staccatissimo\nplay C4 velocity 0.9 accent\nplay C4 velocity 0.5 marcato\narticulation legato\nplay C4"));105    let n = &p.tracks[0].notes;106    assert_eq!((n[0].duration, n[0].notated_duration, n[0].articulation), (r(1, 8), r(1, 4), Articulation::Staccato));107    assert_eq!(n[1].duration, r(1, 16));108    assert_eq!(n[2].velocity, 1.0);109    assert!((n[3].velocity - 0.6).abs() < 1e-6);110    assert_eq!(n[4].articulation, Articulation::Legato);111    assert_eq!(n[1].start, r(1, 4), "staccato shortens the sound, not the cursor advance");112}113114#[test]115fn ties_merge_into_one_sounding_note() {116    let p = ok(&piece("", "play C4 duration 1/2 tie\nplay C4 duration 1/4 tie\nplay C4 duration 1/4\nplay C4 duration 1/4"));117    let n = &p.tracks[0].notes;118    assert_eq!(n.len(), 2);119    assert_eq!((n[0].start, n[0].duration, n[0].notated_duration), (Rational::ZERO, r(1, 1), r(1, 1)));120    assert_eq!(n[1].start, r(1, 1));121    assert_eq!(warnings(&piece("", "play C4 tie\nplay D4")), vec!["M4005"]);122    assert_eq!(warnings(&piece("", "play C4 tie\nrest 1/4\nplay C4")), vec!["M4005"]);123}124125#[test]126fn voices_parallel_and_at() {127    let p = ok(&piece(128        "",129        "voice { play C5 duration 1/2 }\nvoice { play C3 duration 1/4\n play G3 duration 1/2 }\nplay E4\nparallel {\n play C4 duration 1/1\n sequence { rest 1/2\n play G4 duration 1/4 }\n}\nat 8bars { play A4 }\nplay B4",130    ));131    let n = &p.tracks[0].notes;132    let find = |pitch: f64| n.iter().find(|x| x.pitch == pitch).unwrap();133    assert_eq!((find(72.0).start, find(72.0).voice), (Rational::ZERO, 1));134    assert_eq!((find(48.0).start, find(55.0).start, find(55.0).voice), (Rational::ZERO, r(1, 4), 2));135    // The cursor advanced by the longest voice (3/4).136    assert_eq!((find(64.0).start, find(64.0).voice), (r(3, 4), 0));137    assert_eq!(find(60.0).start, r(1, 1));138    assert_eq!(find(67.0).start, r(3, 2));139    assert_eq!(find(69.0).start, r(8, 1));140    // `at` does not move the cursor: B4 follows the parallel block (1 + 1).141    assert_eq!(find(71.0).start, r(2, 1));142}143144#[test]145fn functions_patterns_and_control_flow() {146    let src = format!(147        r#"{DEFS}148const root = D3149fn fib(n: Number) -> Number {{150    if n < 2 {{ return n }}151    return fib(n - 1) + fib(n - 2)152}}153fn up(p: Pitch, steps: Number = 1) -> Pitch {{ return p + 2st * steps }}154pattern arp(notes: List<Pitch>, step: Duration = 1/8) {{155    for n in notes {{ play n duration step }}156}}157composition "t" {{158    key D minor159    let count = fib(6)160    instrument p: Piano {{161        arp(chord(root, min7))162        arp(scale(root, dorian), step: 1/16)163        let i = 0164        repeat 3 {{165            if i % 2 == 0 {{ play up(root, steps: i) }} else {{ rest 1/4 }}166            i = i + 1167        }}168        for k in [1, 3, 5] {{ play degree(k) duration 1/8 }}169        play if count == 8 then A4 else B4170        play [root, root + perfect_fifth][1]171    }}172}}"#173    );174    let p = ok(&src);175    let pitches: Vec<f64> = p.tracks[0].notes.iter().map(|n| n.pitch).collect();176    assert_eq!(&pitches[..4], &[50.0, 53.0, 57.0, 60.0]);177    assert_eq!(&pitches[4..11], &[50.0, 52.0, 53.0, 55.0, 57.0, 59.0, 60.0]);178    assert_eq!(&pitches[11..13], &[50.0, 54.0]);179    // Degrees 1, 3, 5 of D minor in octave 4.180    assert_eq!(&pitches[13..16], &[62.0, 65.0, 69.0]);181    assert_eq!(&pitches[16..], &[69.0, 57.0]);182    assert_eq!(p.key.unwrap().mode, Mode::Minor);183    assert_eq!(p.key.unwrap().tonic, 2);184}185186#[test]187fn unit_and_type_errors_are_precise() {188    let e = |body: &str| run(&piece("", body)).diagnostics.into_iter().filter(|d| d.is_error()).collect::<Vec<_>>();189    let d = e("play D4 duration 1s");190    assert_eq!(d[0].code, "T3003");191    assert!(d[0].suggestion.as_ref().unwrap().contains("seconds are a different type"));192    assert_eq!(e("play D4 duration 0.25")[0].code, "T3003");193    assert_eq!(e("play D4 + 2")[0].code, "T3001");194    assert!(e("play D4 + 2")[0].suggestion.as_ref().unwrap().contains("2st"));195    assert_eq!(e("let x = 1s + 1/4")[0].code, "T3001");196    let g = e("gain -8");197    assert_eq!(g[0].code, "T3006");198    assert_eq!(g[0].fix.as_ref().unwrap().replacement, "dB");199    assert_eq!(e("play D4 velocity 1.5")[0].code, "M4008");200    assert_eq!(e("play D")[0].code, "T3004");201    assert_eq!(e("play 440Hz")[0].code, "T3004");202    assert_eq!(e("play D4 duration 0")[0].code, "M4009");203    assert_eq!(e("let x = 1 / 0")[0].code, "T3007");204    assert_eq!(e("let x = [1, 2][5]")[0].code, "T3008");205    assert_eq!(e("if 1 { play D4 }")[0].code, "T3011");206    assert_eq!(e("for x in 3 { play D4 }")[0].code, "T3012");207    assert_eq!(e("let x: Pitch = 3")[0].code, "T3009");208    assert_eq!(e("let x: Signal = 3")[0].code, "T3010");209    assert_eq!(e("let x: Pich = D4")[0].code, "S2004");210    let u = e("play rooot");211    assert_eq!(u[0].code, "S2001");212    assert_eq!(u.len(), 1, "the resolver and the evaluator report an unknown name once");213    assert_eq!(e("const k = 1\nk = 2")[0].code, "S2007");214    assert_eq!(e("pann 0.5")[0].code, "S2009");215    assert_eq!(e("pann 0.5")[0].fix.as_ref().unwrap().replacement, "pan");216    assert_eq!(e("return 1")[0].code, "S2008");217    // Several independent errors are all reported.218    assert_eq!(e("play D4 duration 1s\nplay E4 velocity 2\nplay nope").iter().map(|d| d.code.as_str()).collect::<Vec<_>>(), vec!["T3003", "M4008", "S2001"]);219    // Explicit conversions work.220    ok(&piece("tempo 120bpm", "let s = seconds(1/4)\nlet b = beats(1/2)\nlet f = hz(A4) * 2\nlet g = db(0.5) + 3dB\nlet l = linear(-6dB)\nplay A4 + 25cents duration dotted(1/4) + triplet(1/8)"));221}222223#[test]224fn instruments_inherit_and_validate() {225    let src = r#"226instrument CrystalHarp {227    model plucked_string228    damping 0.015229    excitation pluck(position: 0.35)230    resonance modal(frequencies: [440Hz, 880Hz, 1320Hz])231    envelope adsr(attack: 5ms, decay: 300ms, sustain: 0.6, release: 2s)232}233instrument DarkHarp: CrystalHarp { damping 0.2; preset nylon; envelope.release half }234instrument Pad { model synth; preset pad; waveform square; cutoff 2kHz; unison 3 }235composition "t" {236    tempo 60bpm237    instrument a: CrystalHarp { play A4 }238    instrument b: DarkHarp { play A3 }239    instrument c: Pad { play A2 }240    instrument d: flute { play A5 }241}"#;242    let p = ok(src);243    let a = p.tracks[0].instrument.as_ref().unwrap();244    assert_eq!((a.name.as_str(), a.model.as_str()), ("CrystalHarp", "plucked_string"));245    assert_eq!(a.params["damping"], ParamValue::Num(0.015));246    assert_eq!(a.params["excitation"], ParamValue::Text("pluck".into()));247    assert_eq!(a.params["excitation.position"], ParamValue::Num(0.35));248    assert_eq!(a.params["resonance.frequencies"], ParamValue::List(vec![440.0, 880.0, 1320.0]));249    assert_eq!(a.params["envelope.attack"], ParamValue::Num(0.005));250    assert_eq!(a.params["envelope.release"], ParamValue::Num(2.0));251    let b = p.tracks[1].instrument.as_ref().unwrap();252    // Members apply in order: damping 0.2, then the preset overrides it.253    assert_eq!(b.params["damping"], ParamValue::Num(0.03));254    assert_eq!(b.params["excitation.position"], ParamValue::Num(0.35));255    // A musical duration given to a time parameter: 1/2 at 60 bpm = 2 s.256    assert_eq!(b.params["envelope.release"], ParamValue::Num(2.0));257    let c = p.tracks[2].instrument.as_ref().unwrap();258    assert_eq!(259        (c.params["waveform"].clone(), c.params["cutoff"].clone(), c.params["unison"].clone(), c.params["envelope.attack"].clone()),260        (ParamValue::Text("square".into()), ParamValue::Num(2000.0), ParamValue::Num(3.0), ParamValue::Num(0.4))261    );262    assert_eq!(p.tracks[3].instrument.as_ref().unwrap().model, "flute");263264    let bad = |def: &str| codes(&format!("{def}\ncomposition \"t\" {{ }}"));265    assert_eq!(bad("instrument X { damping 0.1 }"), vec!["S2025"]);266    assert_eq!(bad("instrument X { model plucked_strin }"), vec!["S2020"]);267    assert_eq!(bad("instrument X { model plucked_string; dampin 0.1 }"), vec!["S2023"]);268    assert_eq!(bad("instrument X { model plucked_string; damping 3 }"), vec!["T3005"]);269    assert_eq!(bad("instrument X { model plucked_string; damping 5ms }"), vec!["T3006"]);270    assert_eq!(bad("instrument X { model plucked_string; excitation bow(position: 0.3) }"), vec!["S2024"]);271    assert_eq!(bad("instrument X { model plucked_string; excitation pluck(pos: 0.3) }"), vec!["S2023"]);272    assert_eq!(bad("instrument X { model plucked_string; preset steel }"), vec!["S2022"]);273    assert_eq!(bad("instrument X { model synth; waveform sow }"), vec!["S2024"]);274    assert_eq!(bad("instrument X { model synth; unison 2.5 }"), vec!["T3006"]);275    assert_eq!(bad("instrument X: Y { }\ninstrument Y: X { }"), vec!["S2012"]);276    assert_eq!(bad("instrument X: Nope { }"), vec!["S2001"]);277    assert_eq!(bad("instrument X { model piano }\ninstrument Y: X { model synth }"), vec!["S2027"]);278    assert_eq!(bad("instrument X { model piano; graph { node o = sine(); out o } }"), vec!["G5004"]);279    assert_eq!(bad("instrument X { model patch }"), vec!["G5004"]);280    assert_eq!(codes("composition \"t\" { instrument a: Nope { } }"), vec!["S2001"]);281    assert_eq!(warnings(&piece("", "play C9")), vec!["M4001"]);282}283284#[test]285fn effects_buses_automation_and_master() {286    let src = format!(287        r#"{DEFS}composition "t" {{288    tempo 120bpm289    bus hall {{ effects {{ reverb hall(mix: 100%) }}; gain -3dB }}290    bus drums {{ output hall; send hall -12dB pre }}291    marker "B" at 4bars292    marker "A"293    instrument p: Piano {{294        gain -8dB; pan -0.25; solo295        effects {{296            eq(low_gain: -3dB)297            bypass delay(time: note_value(1/8), feedback: 0.4, mix: 0.2)298            reverb room299        }}300        send hall -6dB301        output drums302        play D4 duration 2bars303        automate gain {{ 0bars: -12dB, 1bar: 0dB, 2bars: -6dB exp }}304        automate delay.feedback {{ 0bars: 0.1, 2bars: 0.6 step }}305        automate reverb.mix {{ 1bar: 0.5 }}306        automate instrument.brightness {{ 0bars: 0.2, 2bars: 0.9 }}307    }}308    audio loop {{ clip "drums/loop.wav" at 2bars gain -3dB fade_in 10ms length 4s; mute }}309    master {{ sample_rate 96000Hz; peak_limit off; gain -1dB; effects {{ limiter(ceiling: -0.5dB) }} }}310}}"#311    );312    let p = ok(&src);313    let t = &p.tracks[0];314    assert_eq!((t.gain_db, t.pan, t.solo, t.output), (-8.0, -0.25, true, Output::Bus(1)));315    assert_eq!(t.sends, vec![Send { bus: 0, gain_db: -6.0, pre_fader: false }]);316    assert_eq!(317        t.effects.iter().map(|e| (e.kind.as_str(), e.bypass, e.mix)).collect::<Vec<_>>(),318        vec![("eq", false, 1.0), ("delay", true, 0.2), ("reverb", false, 0.25)]319    );320    // 1/8 at 120 bpm = 0.25 s.321    assert_eq!(t.effects[1].params["time"], ParamValue::Num(0.25));322    assert_eq!((t.effects[2].preset.as_deref(), t.effects[2].params["size"].clone()), (Some("room"), ParamValue::Num(0.3)));323    assert_eq!(t.automation.len(), 4);324    assert_eq!(t.automation[0].target, AutomationTarget::Gain);325    // Automation positions are relative to the cursor (after the 2-bar note).326    assert_eq!(327        t.automation[0].points.iter().map(|x| (x.at, x.value, x.curve)).collect::<Vec<_>>(),328        vec![(r(2, 1), -12.0, Curve::Linear), (r(3, 1), 0.0, Curve::Linear), (r(4, 1), -6.0, Curve::Exponential)]329    );330    assert!(close(t.automation[0].points[1].at_sec, 6.0));331    assert_eq!(t.automation[1].target, AutomationTarget::Effect { index: 1, param: "feedback".into() });332    assert_eq!(t.automation[2].target, AutomationTarget::Effect { index: 2, param: "mix".into() });333    assert_eq!(t.automation[3].target, AutomationTarget::Instrument { param: "brightness".into() });334    assert_eq!((p.buses[0].name.as_str(), p.buses[0].gain_db, p.buses[0].effects[0].mix), ("hall", -3.0, 1.0));335    assert_eq!((p.buses[1].output, p.buses[1].sends[0].pre_fader), (Output::Bus(0), true));336    assert_eq!(p.markers.iter().map(|m| (m.name.as_str(), m.at)).collect::<Vec<_>>(), vec![("A", Rational::ZERO), ("B", r(4, 1))]);337    let a = &p.tracks[1];338    assert_eq!((a.kind, a.mute, a.clips.len()), (TrackKind::Audio, true, 1));339    assert_eq!(340        (a.clips[0].asset.as_str(), a.clips[0].start, a.clips[0].gain_db, a.clips[0].fade_in_sec, a.clips[0].length_sec),341        ("drums/loop.wav", r(2, 1), -3.0, 0.01, Some(4.0))342    );343    assert!(close(a.clips[0].start_sec, 4.0));344    assert_eq!((p.master.sample_rate, p.master.peak_limit_db, p.master.gain_db, p.master.effects.len()), (96_000, None, -1.0, 1));345346    let fx = |body: &str| codes(&piece("", body));347    assert_eq!(fx("effects { reverbb hall }"), vec!["S2021"]);348    assert_eq!(fx("effects { reverb cathedral }"), vec!["S2022"]);349    assert_eq!(fx("effects { reverb(siz: 0.2) }"), vec!["S2023"]);350    assert_eq!(fx("effects { reverb(size: 2) }"), vec!["T3005"]);351    assert_eq!(fx("effects { reverb(0.2) }"), vec!["S2005"]);352    assert_eq!(fx("effects { eq(low_gain: 3) }"), vec!["T3006"]);353    assert_eq!(fx("effects { distortion(mode: fuzz) }"), vec!["S2024"]);354    assert_eq!(fx("send nowhere"), vec!["S2001"]);355    assert_eq!(fx("automate chorus.rate { 0bars: 1Hz }"), vec!["S2001"]);356    assert_eq!(fx("effects { distortion }\nautomate distortion.mode { 0bars: 1 }"), vec!["T3014"]);357    assert_eq!(fx("automate gain { 2bars: 0dB, 1bar: 0dB }"), vec!["M4011"]);358    assert_eq!(fx("automate gain { 0bars: 99dB }"), vec!["T3005"]);359    assert_eq!(codes(&format!("{DEFS}composition \"t\" {{ audio a {{ clip \"../secret.wav\" }} }}")), vec!["I7005"]);360    assert_eq!(codes(&format!("{DEFS}composition \"t\" {{ audio a {{ clip \"/etc/passwd\" }} }}")), vec!["I7005"]);361    assert_eq!(codes(&format!("{DEFS}composition \"t\" {{ master {{ sample_rate 12345Hz }} }}")), vec!["M4012"]);362    assert_eq!(codes(&format!("{DEFS}composition \"t\" {{ master {{ peak_limit 3dB }} }}")), vec!["M4013"]);363    assert_eq!(codes(&format!("{DEFS}composition \"t\" {{ bus a {{ output a }} }}")), vec!["G5001"]);364    assert_eq!(codes(&format!("{DEFS}composition \"t\" {{ bus a {{ play D4 }} }}")), vec!["S2008"]);365    assert_eq!(codes(&format!("{DEFS}composition \"t\" {{ instrument p: Piano {{ }}; instrument p: Piano {{ }} }}")), vec!["S2011"]);366}367368#[test]369fn graphs_compile_to_patches() {370    let src = r#"371const base = 800Hz372instrument Lead {373    model patch374    graph {375        node osc1 = saw(freq: note.freq, detune: 7cents)376        node osc2 = square(note.freq * 2)377        node env = adsr(attack: 5ms, decay: 200ms, sustain: 0.6, release: 400ms)378        node wobble = lfo(freq: 5Hz)379        node f = lowpass(in: osc1 + osc2 * 0.5, cutoff: base + env * (2 * 2000Hz) + wobble * 50, q: 0.7)380        node fb = delay(in: mixed, time: 10ms)381        node mixed = f + fb * 0.3382        out mixed * env * note.velocity383    }384}385composition "t" { instrument a: Lead { play A3 } }"#;386    let p = ok(src);387    let patch = p.tracks[0].instrument.as_ref().unwrap().patch.as_ref().unwrap();388    patch.validate().unwrap();389    let by_name = |n: &str| patch.nodes.iter().position(|x| x.name == n).unwrap();390    let (osc1, env, f, fb, mixed) = (by_name("osc1"), by_name("env"), by_name("f"), by_name("fb"), by_name("mixed"));391    assert_eq!(patch.nodes[osc1].inputs["freq"], PatchInput::Note(NoteInput::Freq));392    assert_eq!(patch.nodes[osc1].inputs["detune"], PatchInput::Const(0.07));393    assert_eq!(patch.nodes[env].inputs["attack"], PatchInput::Const(0.005));394    assert_eq!((patch.nodes[env].rate, patch.nodes[osc1].rate, patch.nodes[f].rate), (Rate::Control, Rate::Audio, Rate::Audio));395    // Constant folding: 2 * 2000Hz became one constant feeding a mul with env.396    assert!(patch.nodes.iter().any(|n| n.kind == "mul"397        && n.inputs.values().any(|i| *i == PatchInput::Const(4000.0))398        && n.inputs.values().any(|i| *i == PatchInput::Node(env as u32))399        && n.rate == Rate::Control));400    // Feedback through the delay reads a later node.401    assert_eq!(patch.nodes[fb].inputs["in"], PatchInput::Node(mixed as u32));402    assert!(mixed > fb);403    assert_eq!(patch.amp_envelope, Some(env as u32));404    assert_eq!(patch.nodes[patch.output as usize].rate, Rate::Audio);405406    // A node that does not reach the output is removed, with a warning for named ones.407    let dead = "instrument X { model patch\n graph { node unused = sine(freq: 3Hz) * 2\n node o = saw()\n node e = adsr()\n out o * e } }\ncomposition \"t\" { instrument a: X { play A3 } }";408    let a = run(dead);409    assert_eq!(a.diagnostics.iter().map(|d| (d.code.as_str(), d.severity)).collect::<Vec<_>>(), vec![("G5011", Severity::Warning)]);410    let patch = a.program.unwrap().tracks[0].instrument.clone().unwrap().patch.unwrap();411    assert_eq!(patch.nodes.iter().map(|n| n.kind.as_str()).collect::<Vec<_>>(), vec!["saw", "adsr", "mul"]);412    assert_eq!((patch.output, patch.amp_envelope), (2, Some(1)));413    patch.validate().unwrap();414415    let g = |body: &str| codes(&format!("instrument X {{ model patch\n graph {{ {body} }} }}\ncomposition \"t\" {{ }}"));416    assert_eq!(g("node a = lowpass(in: b)\n node b = gain(in: a)\n out b"), vec!["G5002"]);417    assert_eq!(g("node a = sine()"), vec!["G5003"]);418    assert_eq!(g("node a = adsr()\n out a"), vec!["G5007"]);419    assert_eq!(g("out 0.5"), vec!["G5007"]);420    assert_eq!(g("node a = sine()\n node a = saw()\n out a"), vec!["G5009"]);421    assert_eq!(g("node a = sinus()\n out a"), vec!["S2026"]);422    assert_eq!(g("node a = sine(frq: 3Hz)\n out a"), vec!["S2026"]);423    assert_eq!(g("node a = sine(freq: 5ms)\n out a"), vec!["T3006"]);424    assert_eq!(g("node e = adsr(attack: note.velocity)\n node a = sine()\n out a * e"), vec!["G5008"]);425    assert_eq!(g("node a = sine()\n node b = sine()\n out a / b"), vec!["G5005"]);426    assert_eq!(g("node a = lowpass(q: 500)\n out a"), vec!["T3005"]);427}428429#[test]430fn randomness_is_seeded_and_reproducible() {431    let src = |seed: u32| {432        piece(&format!("seed {seed}"), "repeat 32 { play choose(scale(C4, pentatonic_minor)) duration choose([1/8, 1/16]) velocity 0.4 + random() * 0.5 }\nlet order = shuffle([1, 2, 3, 4, 5])\nplay midi(60 + random_int(0, 11))")433    };434    let (a, b, c) = (ok(&src(42)), ok(&src(42)), ok(&src(43)));435    assert_eq!(a, b, "same source and seed give the same Program");436    assert_ne!(a.tracks[0].notes, c.tracks[0].notes);437    assert_eq!(a.seed, 42);438    // Tracks draw from independent streams: adding a track does not change another.439    let two = format!("{DEFS}composition \"t\" {{ seed 7\n instrument a: Piano {{ repeat 8 {{ play midi(60 + random_int(0, 11)) }} }}\n instrument b: Piano {{ repeat 8 {{ play midi(60 + random_int(0, 11)) }} }} }}");440    let one = format!("{DEFS}composition \"t\" {{ seed 7\n instrument a: Piano {{ repeat 8 {{ play midi(60 + random_int(0, 11)) }} }} }}");441    let (p2, p1) = (ok(&two), ok(&one));442    let pitches = |t: &Track| t.notes.iter().map(|n| n.pitch).collect::<Vec<_>>();443    assert_eq!(pitches(&p2.tracks[0]), pitches(&p1.tracks[0]));444    assert_ne!(pitches(&p2.tracks[0]), pitches(&p2.tracks[1]));445}446447#[test]448fn quotas_stop_cleanly() {449    let q = |quotas: Quotas, src: &str| {450        run_with(src, &NoLoader, &Options { quotas, composition: None }).diagnostics.into_iter().filter(|d| d.is_error()).map(|d| d.code).collect::<Vec<_>>()451    };452    let small = || Quotas { max_events: 100, max_steps: 10_000, max_list_len: 50, max_tracks: 2, ..Quotas::default() };453    assert_eq!(q(small(), &piece("", "repeat 1000 { play C4 duration 1/16 }")), vec!["Q6001"]);454    assert_eq!(q(small(), &piece("", "repeat 1000000 { rest 1/16 }")), vec!["Q6002"]);455    assert_eq!(q(small(), &piece("", "let xs = 0..1000")), vec!["Q6004"]);456    assert_eq!(q(small(), &piece("", "let xs = cycle([1], 1000)")), vec!["Q6004"]);457    assert_eq!(q(Quotas::default(), &format!("fn f(n: Number) -> Number {{ return f(n + 1) }}\n{}", piece("", "let x = f(0)"))), vec!["Q6003"]);458    assert_eq!(q(Quotas::default(), &format!("pattern p() {{ p() }}\n{}", piece("", "p()"))), vec!["Q6003"]);459    assert_eq!(460        q(small(), &format!("{DEFS}composition \"t\" {{ instrument a: Piano {{ }}; instrument b: Piano {{ }}; instrument c: Piano {{ }} }}")),461        vec!["Q6006"]462    );463    assert_eq!(q(Quotas::default(), &piece("", "let d = 1bar\nrepeat 80 { d = d * 3 }\nrest d")), vec!["Q6005"]);464    // The default quotas let a large but legitimate piece through.465    let big = ok(&piece("", "repeat 20000 { play C4 duration 1/16 }"));466    assert_eq!(big.stats.notes, 20_000);467}468469#[test]470fn imports_modules_and_shadowing() {471    let loader = MapLoader::default()472        .with("lib.motifs", "import lib.scales\npattern motif(root: Pitch) { for n in take(my_scale(root), 3) { play n duration 1/8 } }")473        .with("lib.scales", "fn my_scale(root: Pitch) -> List<Pitch> { return scale(root, lydian) }")474        .with("cyc.a", "import cyc.b\nconst a = 1")475        .with("cyc.b", "import cyc.a\nconst b = 2")476        .with("dup", "const whole_dup = 1\nfn my_scale(root: Pitch) -> List<Pitch> { return [root] }");477    let go = |src: &str| run_with(src, &loader, &Options::default());478    let a = go(&format!("import lib.motifs\n{}", piece("", "motif(C4)")));479    assert!(!a.has_errors(), "{:#?}", a.diagnostics);480    assert_eq!(a.program.unwrap().tracks[0].notes.iter().map(|n| n.pitch).collect::<Vec<_>>(), vec![60.0, 62.0, 64.0]);481    let errs = |src: &str| go(src).diagnostics.into_iter().filter(|d| d.is_error()).map(|d| d.code).collect::<Vec<_>>();482    assert_eq!(errs("import lib.nope"), vec!["I7001"]);483    let d = go("import std.musik").diagnostics;484    assert_eq!(d[0].fix.as_ref().unwrap().replacement, "std.music");485    assert_eq!(errs("import cyc.a"), vec!["I7002"]);486    assert_eq!(errs("import lib.scales\nimport dup"), vec!["S2002"]);487    assert_eq!(errs("sonata 9.0\nconst x = 1"), vec!["I7004"]);488    assert!(errs("sonata 0.1\nconst x = 1").is_empty());489    // The prelude is always there, and project definitions shadow it.490    let p = ok(&piece("", "play C4 duration quarter velocity mf\narpeggio([C4, E4], step: eighth)"));491    assert_eq!(p.tracks[0].notes.len(), 3);492    let p = ok(&format!("const quarter = 1/2\n{}", piece("", "play C4 duration quarter")));493    assert_eq!(p.tracks[0].notes[0].duration, r(1, 2));494    assert_eq!(errs("const x = 1\nconst x = 2"), vec!["S2002"]);495    assert_eq!(errs("fn len(x: Number) -> Number { return x }"), vec!["S2002"]);496    assert_eq!(errs("const a = b\nconst b = a"), vec!["S2006"]);497    // A module without composition is valid and yields no program.498    let m = go("const x = 1");499    assert!(!m.has_errors() && !m.has_composition && m.program.is_none());500    let two = "composition \"one\" { }\ncomposition \"two\" { tempo 90bpm }";501    let pick = run_with(two, &NoLoader, &Options { composition: Some("two".into()), ..Options::default() });502    assert_eq!(pick.program.unwrap().tempo_map.points[0].bpm, 90.0);503    let miss = run_with(two, &NoLoader, &Options { composition: Some("three".into()), ..Options::default() });504    assert_eq!(miss.diagnostics.iter().filter(|d| d.is_error()).map(|d| d.code.as_str()).collect::<Vec<_>>(), vec!["S2010"]);505}506507#[test]508fn syntax_errors_suppress_semantic_noise() {509    let a = run(&piece("", "play D4 duraton 1/4\nplay undefined_name"));510    assert_eq!(a.diagnostics.iter().map(|d| d.code.as_str()).collect::<Vec<_>>(), vec!["P1007"]);511    assert!(a.program.is_none());512}513514#[test]515fn symbol_index_links_references_to_definitions() {516    let src = format!("{DEFS}const root = D3\nfn up(p: Pitch) -> Pitch {{ return p + 2st }}\ncomposition \"t\" {{\n bus hall {{ }}\n instrument lead: Lead {{\n  let x = up(root)\n  play x\n  send hall\n }}\n}}");517    let a = run(&src);518    assert!(!a.has_errors(), "{:#?}", a.diagnostics);519    let at = |needle: &str, nth: usize| src.match_indices(needle).nth(nth).unwrap().0 as u32;520    let def_of = |offset: u32| a.symbols.definition_at(0, offset).map(|i| &a.symbols.defs[i]);521    let d = def_of(at("root", 1)).unwrap();522    assert_eq!((d.kind, d.span.start), (DefKind::Constant, at("root", 0)));523    assert_eq!(def_of(at("up(root)", 0)).unwrap().detail, "fn up(p: Pitch) -> Pitch");524    assert_eq!(def_of(at("x\n  send", 0)).unwrap().kind, DefKind::Variable);525    assert_eq!(def_of(at("Lead {", 1)).unwrap().kind, DefKind::Instrument);526    assert_eq!(def_of(at("hall\n", 0)).unwrap().kind, DefKind::Bus);527    assert_eq!(def_of(at("p + 2st", 0)).unwrap().kind, DefKind::Parameter);528    let root_def = a.symbols.definition_at(0, at("root", 0)).unwrap();529    assert_eq!(a.symbols.references_to(root_def).len(), 1);530    assert!(a.symbols.defs.iter().any(|d| d.kind == DefKind::Track && d.name == "lead"));531    // Static checks cover code that is never executed.532    assert_eq!(codes("fn never() -> Number { return missing + 1 }"), vec!["S2001"]);533    assert_eq!(codes("fn f(a: Number) -> Number { return a }\nfn g() -> Number { return f(1, 2) }"), vec!["S2005"]);534    assert_eq!(codes("fn f(a: Number) -> Number { return a }\nfn g() -> Number { return f(b: 1) }"), vec!["S2005"]);535}536
Files main
Menu

Theme