Repository Public
1//! ORIX Sonata2//! File: crates/sonata-compiler/tests/manual_examples.rs3//! Description: Keeps the manual honest. Every ```sonata block of Documentation/manual is4//! compiled, every example of Examples/ compiles, the generated parameter reference is up to5//! date, the manifest lists every chapter, and links between chapters resolve.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai9//!10//! Block tags (the text after the opening fence):11//! * `sonata` — a complete program, or definitions alone (instruments, functions, patterns):12//! must compile with zero errors and zero warnings.13//! * `sonata,error=CODE` — must fail with that diagnostic code.14//! * `sonata,warning=CODE` — must compile with that warning and no error.15//! * `sonata,fragment` — track statements, wrapped as16//! `composition "Fragment" { instrument fragment: GrandPiano { … } }`.17//! * `sonata,fragment=composition` — composition statements, wrapped as18//! `composition "Fragment" { … }`.19//! * `sonata,module=NAME` — a module; it compiles on its own and later blocks of the same20//! chapter can `import NAME`.2122use sonata_compiler::{compile, CompileOptions, MapLoader};23use std::collections::BTreeSet;24use std::path::{Path, PathBuf};2526#[allow(dead_code)]27#[path = "../../sonata-cli/examples/gen_reference.rs"]28mod gen_reference;2930fn repo() -> PathBuf {31 Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").canonicalize().unwrap()32}3334fn manual() -> PathBuf {35 repo().join("Documentation/manual")36}3738fn markdown_files(dir: &Path, out: &mut Vec<PathBuf>) {39 let mut entries: Vec<PathBuf> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().path()).collect();40 entries.sort();41 for p in entries {42 if p.is_dir() {43 markdown_files(&p, out);44 } else if p.extension().is_some_and(|e| e == "md") {45 out.push(p);46 }47 }48}4950/// A fenced code block: its tag, its text and the line of its opening fence.51pub struct Block {52 pub tag: String,53 pub text: String,54 pub line: usize,55}5657pub fn blocks(markdown: &str) -> Vec<Block> {58 let mut out = Vec::new();59 let mut current: Option<Block> = None;60 for (i, line) in markdown.lines().enumerate() {61 match current.as_mut() {62 None => {63 if let Some(tag) = line.strip_prefix("```") {64 current = Some(Block { tag: tag.trim().to_string(), text: String::new(), line: i + 1 });65 }66 }67 Some(b) => {68 if line.trim_end() == "```" {69 out.push(current.take().unwrap());70 } else {71 b.text.push_str(line);72 b.text.push('\n');73 }74 }75 }76 }77 assert!(current.is_none(), "unterminated code block");78 out79}8081fn indent(text: &str, by: usize) -> String {82 text.lines().map(|l| if l.is_empty() { String::new() } else { format!("{}{l}", " ".repeat(by)) }).collect::<Vec<_>>().join("\n")83}8485#[test]86fn every_sonata_block_of_the_manual_behaves_as_tagged() {87 let mut files = Vec::new();88 markdown_files(&manual(), &mut files);89 let (mut programs, mut failing, mut fragments, mut definitions) = (0, 0, 0, 0);90 for file in &files {91 let rel = file.strip_prefix(repo()).unwrap().display().to_string();92 let text = std::fs::read_to_string(file).unwrap();93 let mut loader = MapLoader::default();94 for b in blocks(&text) {95 let mut parts = b.tag.split(',');96 if parts.next() != Some("sonata") {97 continue;98 }99 let option = parts.next().unwrap_or("");100 assert!(parts.next().is_none(), "{rel}:{}: one option per block", b.line);101 let at = format!("{rel}:{}", b.line);102 let (source, expect_error, expect_warning) = match option.split_once('=').unwrap_or((option, "")) {103 ("", _) => (b.text.clone(), None, None),104 ("error", code) => (b.text.clone(), Some(code.to_string()), None),105 ("warning", code) => (b.text.clone(), None, Some(code.to_string())),106 ("fragment", "") => {107 (format!("composition \"Fragment\" {{\n instrument fragment: GrandPiano {{\n{}\n }}\n}}\n", indent(&b.text, 8)), None, None)108 }109 ("fragment", "composition") => (format!("composition \"Fragment\" {{\n{}\n}}\n", indent(&b.text, 4)), None, None),110 ("module", name) => {111 assert!(!name.is_empty(), "{at}: module needs a name");112 loader = loader.with(name, &b.text);113 (b.text.clone(), None, None)114 }115 (other, _) => panic!("{at}: unknown block option '{other}'"),116 };117 let out = compile(&at, &source, &loader, &CompileOptions::default());118 let errors: Vec<&str> = out.diagnostics.iter().filter(|d| d.is_error()).map(|d| d.code.as_str()).collect();119 let all: Vec<&str> = out.diagnostics.iter().map(|d| d.code.as_str()).collect();120 if let Some(code) = expect_error {121 assert!(errors.contains(&code.as_str()), "{at}: expected error {code}, got {errors:?}\n{}", out.render_diagnostics());122 failing += 1;123 } else if let Some(code) = expect_warning {124 assert!(125 errors.is_empty() && all.contains(&code.as_str()),126 "{at}: expected warning {code} and no error, got {all:?}\n{}",127 out.render_diagnostics()128 );129 programs += 1;130 } else {131 assert!(out.diagnostics.is_empty(), "{at}: the block does not compile cleanly:\n{}\n{source}", out.render_diagnostics());132 if option.starts_with("module") {133 assert!(out.program.is_none(), "{at}: a module has no composition");134 } else if option.starts_with("fragment") {135 assert!(out.program.is_some(), "{at}: the fragment produced no composition");136 fragments += 1;137 } else if out.program.is_some() {138 programs += 1;139 } else {140 // Definitions alone: valid Sonata, with nothing to play.141 definitions += 1;142 }143 }144 }145 }146 assert!(programs >= 40, "only {programs} complete programs in the manual");147 assert!(failing >= 5, "only {failing} documented errors in the manual");148 println!("manual: {programs} programs, {fragments} fragments, {definitions} definition blocks, {failing} documented errors in {} files", files.len());149}150151#[test]152fn every_example_compiles_cleanly_and_there_are_enough() {153 let dir = repo().join("Examples");154 let mut count = 0;155 let mut titles = BTreeSet::new();156 for entry in std::fs::read_dir(&dir).unwrap() {157 let path = entry.unwrap().path();158 if path.extension().is_none_or(|e| e != "sonata") {159 continue;160 }161 let source = std::fs::read_to_string(&path).unwrap();162 let name = path.file_name().unwrap().to_string_lossy().to_string();163 let out = compile(&name, &source, &sonata_compiler::DirLoader::new(&dir), &CompileOptions::default());164 assert!(out.diagnostics.is_empty(), "{name}:\n{}", out.render_diagnostics());165 let program = out.program.as_ref().unwrap_or_else(|| panic!("{name} has no composition"));166 assert!(program.stats.notes > 0 && program.end_sec > 1.0, "{name} is not a piece of music");167 assert!(source.starts_with("// ORIX Sonata\n// File: Examples/"), "{name} has no header");168 assert!(titles.insert(program.title.clone()), "two examples are titled '{}'", program.title);169 count += 1;170 }171 assert!(count >= 30, "only {count} examples");172}173174#[test]175fn the_generated_reference_is_up_to_date() {176 let source = std::fs::read_to_string(repo().join("StandardLibrary/std/instruments.sonata")).unwrap();177 for (name, content) in gen_reference::generate(sonata_compiler::registry(), &source) {178 let path = manual().join("reference").join(&name);179 let committed = std::fs::read_to_string(&path).unwrap_or_default();180 assert!(committed == content, "Documentation/manual/reference/{name} is stale: run Scripts/gen-reference.sh");181 }182 // The std parser found every instrument the compiler knows from the standard library.183 let listed = gen_reference::std_instruments(&source);184 assert!(listed.len() >= 80, "{} standard instruments parsed", listed.len());185 for (name, model, preset, _) in &listed {186 let engine = sonata_compiler::registry().engine(model).unwrap_or_else(|| panic!("{name}: unknown model {model}"));187 assert!(engine.presets.iter().any(|p| &p.name == preset), "{name}: unknown preset {preset}");188 }189}190191#[derive(Debug)]192struct Chapter {193 id: String,194 file: String,195 language: String,196}197198fn manifest() -> Vec<Chapter> {199 let text = std::fs::read_to_string(manual().join("manifest.json")).expect("Documentation/manual/manifest.json exists");200 let v: serde_json::Value = serde_json::from_str(&text).expect("the manifest is JSON");201 let mut orders = BTreeSet::new();202 v["chapters"]203 .as_array()204 .expect("chapters")205 .iter()206 .map(|c| {207 let s = |k: &str| c[k].as_str().unwrap_or_else(|| panic!("chapter without {k}: {c}")).to_string();208 assert!(!s("title").is_empty() && !s("section").is_empty());209 assert!(orders.insert(c["order"].as_i64().expect("order")), "duplicate order in the manifest");210 Chapter { id: s("id"), file: s("file"), language: s("language") }211 })212 .collect()213}214215#[test]216fn the_manifest_lists_every_chapter_and_only_existing_files() {217 let chapters = manifest();218 let mut ids = BTreeSet::new();219 let mut listed = BTreeSet::new();220 for c in &chapters {221 assert!(ids.insert(c.id.clone()), "duplicate chapter id {}", c.id);222 assert!(["en", "fr-CA"].contains(&c.language.as_str()), "{}: language {}", c.id, c.language);223 assert!(!c.file.contains("..") && !c.file.starts_with('/'), "{}: unsafe path", c.id);224 // Chapters written by other owners may not have landed yet; everything else must exist.225 let pending = ["wavelab.md", "instrument-lab.md", "score.md", "compiler.md", "library.md"];226 assert!(manual().join(&c.file).is_file() || pending.contains(&c.file.as_str()), "{} is listed but missing", c.file);227 listed.insert(c.file.clone());228 }229 let mut files = Vec::new();230 markdown_files(&manual(), &mut files);231 for f in files {232 let rel = f.strip_prefix(manual()).unwrap().to_string_lossy().to_string();233 assert!(rel == "README.md" || listed.contains(&rel), "{rel} is not in the manifest");234 }235 assert!(chapters.iter().any(|c| c.language == "fr-CA"));236}237238#[test]239fn links_between_chapters_resolve() {240 let mut files = Vec::new();241 markdown_files(&manual(), &mut files);242 let pending = ["wavelab.md", "instrument-lab.md", "score.md", "compiler.md", "library.md"];243 for file in &files {244 let text = std::fs::read_to_string(file).unwrap();245 let rel = file.strip_prefix(repo()).unwrap().display().to_string();246 let mut in_code = false;247 for (n, line) in text.lines().enumerate() {248 if line.starts_with("```") {249 in_code = !in_code;250 }251 if in_code {252 continue;253 }254 let mut rest = line;255 while let Some(i) = rest.find("](") {256 let target = &rest[i + 2..];257 let Some(end) = target.find(')') else { break };258 let link = &target[..end];259 rest = &target[end..];260 if link.starts_with("http://") || link.starts_with("https://") || link.starts_with('#') || link.starts_with("sonata:") {261 continue;262 }263 let (path, anchor) = link.split_once('#').unwrap_or((link, ""));264 let resolved = file.parent().unwrap().join(path);265 if pending.iter().any(|p| path.ends_with(p)) && !resolved.exists() {266 continue;267 }268 assert!(resolved.is_file(), "{rel}:{}: broken link to {path}", n + 1);269 if !anchor.is_empty() && path.ends_with(".md") {270 let target_text = std::fs::read_to_string(&resolved).unwrap();271 let found = target_text.lines().filter(|l| l.starts_with('#')).any(|l| slug(l.trim_start_matches('#').trim()) == anchor);272 assert!(found, "{rel}:{}: no heading '{anchor}' in {path}", n + 1);273 }274 }275 }276 }277}278279/// Anchor of a heading: lower case, letters and digits kept, spaces and underscores to hyphens.280pub fn slug(heading: &str) -> String {281 let mut out = String::new();282 for c in heading.chars() {283 if c.is_alphanumeric() {284 out.extend(c.to_lowercase());285 } else if c == ' ' || c == '-' || c == '_' {286 out.push('-');287 }288 }289 out290}291