SPB Git

Repository Public

main.rs 58.3 KB 1,322 lines rust

1//! ORIX Sonata2//! File: crates/sonata-cli/src/main.rs3//! Description: The `sonata` command-line tool: check, build, render, play, fmt, inspect, test,4//! benchmark, docs, export and import. Uses the same compiler, renderer and tables as the app.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use serde_json::{json, Value};10use sonata_ffi::adapter::{self, ModuleSource, RenderRequest, Session};11use sonata_ffi::compiler::{diagnostic_json, write_atomic, ProjectAssets};12use sonata_ir::{Diagnostic, Program, Severity};13use std::collections::BTreeMap;14use std::io::Write;15use std::path::{Path, PathBuf};16use std::process::ExitCode;17use std::sync::atomic::{AtomicBool, Ordering};1819/// Exit codes (stable):20/// 0 success · 1 the source has errors (or a check/test failed) · 2 usage error ·21/// 3 input/output error · 4 internal error · 130 interrupted.22const EXIT_OK: u8 = 0;23const EXIT_DIAGNOSTICS: u8 = 1;24const EXIT_USAGE: u8 = 2;25const EXIT_IO: u8 = 3;26const EXIT_INTERNAL: u8 = 4;27const EXIT_INTERRUPTED: u8 = 130;2829static INTERRUPTED: AtomicBool = AtomicBool::new(false);30/// Set by `--no-studio`: compile a project's code without its studio edits.31static NO_STUDIO: AtomicBool = AtomicBool::new(false);3233extern "C" {34    fn signal(signum: i32, handler: extern "C" fn(i32)) -> usize;35}3637extern "C" fn on_sigint(_: i32) {38    // Only an atomic store: async-signal-safe.39    INTERRUPTED.store(true, Ordering::SeqCst);40}4142const USAGE: &str = "\43sonata — the ORIX Sonata command-line tool4445USAGE46  sonata check <file> [--json]47  sonata build <file> [--emit ast|ir|graph|timeline|score] [--output <path>] [--force]48  sonata render <file> --output <path> [--format wav|aiff|flac] [--bits 16|24|32] [--float]49                       [--rate <Hz>] [--from <s>] [--to <s>] [--no-tail] [--no-dither]50                       [--normalize peak|lufs] [--target <dB|LUFS>] [--stems] [--force] [--json]51  sonata play <file>52  sonata fmt <file>... [--check] [--stdout]53  sonata inspect <file> [--json]54  sonata export <file> --output <path.mid|path.musicxml> [--force]55  sonata import <file.mid> [--instrument <Name>] [--output <path>] [--force]56  sonata test [<dir-or-file>...] [--json]57  sonata benchmark [<file>] [--seconds <n>] [--json]58  sonata docs [engines|effects|nodes|<name>] [--json]59  sonata pkg pack <dir> [--output <file.sonatapkg>] [--force]60  sonata pkg verify <file.sonatapkg>61  sonata pkg install <file.sonatapkg>... [--project <dir>] [--force]62  sonata pkg resolve [<name>@<requirement>...] --from <dir-of-packages> [--project <dir>]63  sonata pkg list|check [--project <dir>]64  sonata pkg remove <name> [--project <dir>]65  sonata version6667Diagnostics go to standard error (or to standard output as JSON with --json); results go to68standard output. Files are written atomically and never replaced without --force.69A file inside a .sonataproject resolves imports and assets from that project, and the project's70studio edits (studio.json) are applied as in the app; --no-studio compiles the code alone.7172EXIT CODES73  0 success   1 errors in the source or a failed check   2 usage   3 input/output   4 internal   130 interrupted74";7576struct Args {77    positional: Vec<String>,78    flags: BTreeMap<String, Option<String>>,79}8081/// Parses `--flag`, `--flag value` and `--flag=value`. Flags that take a value are listed.82fn parse_args(raw: &[String]) -> Result<Args, String> {83    const WITH_VALUE: [&str; 13] =84        ["emit", "output", "format", "bits", "rate", "from", "to", "normalize", "target", "instrument", "seconds", "composition", "project"];85    const SWITCHES: [&str; 10] = ["json", "force", "float", "no-tail", "no-dither", "stems", "check", "stdout", "help", "no-studio"];86    let mut positional = Vec::new();87    let mut flags = BTreeMap::new();88    let mut i = 0;89    while i < raw.len() {90        let a = &raw[i];91        if let Some(rest) = a.strip_prefix("--") {92            let (name, inline) = match rest.split_once('=') {93                Some((n, v)) => (n, Some(v.to_string())),94                None => (rest, None),95            };96            if WITH_VALUE.contains(&name) {97                let value = match inline {98                    Some(v) => v,99                    None => {100                        i += 1;101                        raw.get(i).cloned().ok_or(format!("--{name} needs a value"))?102                    }103                };104                flags.insert(name.to_string(), Some(value));105            } else if SWITCHES.contains(&name) {106                if inline.is_some() {107                    return Err(format!("--{name} takes no value"));108                }109                flags.insert(name.to_string(), None);110            } else {111                return Err(format!("unknown option --{name}"));112            }113        } else if a == "-o" {114            i += 1;115            flags.insert("output".into(), Some(raw.get(i).cloned().ok_or("-o needs a value")?));116        } else if a == "-h" {117            flags.insert("help".into(), None);118        } else if a.starts_with('-') && a.len() > 1 {119            return Err(format!("unknown option {a}"));120        } else {121            positional.push(a.clone());122        }123        i += 1;124    }125    Ok(Args { positional, flags })126}127128impl Args {129    fn has(&self, name: &str) -> bool {130        self.flags.contains_key(name)131    }132    fn value(&self, name: &str) -> Option<&str> {133        self.flags.get(name).and_then(|v| v.as_deref())134    }135    fn number(&self, name: &str) -> Result<Option<f64>, String> {136        match self.value(name) {137            None => Ok(None),138            Some(v) => v.parse::<f64>().ok().filter(|x| x.is_finite()).map(Some).ok_or(format!("--{name}: '{v}' is not a number")),139        }140    }141}142143enum Failure {144    Usage(String),145    Io(String),146    Diagnostics,147    Internal(String),148    Interrupted,149}150151type Outcome = Result<(), Failure>;152153/// A compiled source file with everything needed to report on it.154struct Unit {155    name: String,156    root: Option<PathBuf>,157    compiled: adapter::Compiled,158}159160/// The project a file belongs to: the nearest ancestor directory named `*.sonataproject`.161fn project_root(path: &Path) -> Option<PathBuf> {162    let abs = path.canonicalize().ok()?;163    abs.ancestors().find(|a| a.extension().is_some_and(|e| e == "sonataproject") && a.is_dir()).map(|p| p.to_path_buf())164}165166fn read_source(path: &Path) -> Result<String, Failure> {167    let meta = std::fs::metadata(path).map_err(|e| Failure::Io(format!("{}: {e}", path.display())))?;168    if meta.len() > 4 * 1024 * 1024 {169        return Err(Failure::Io(format!("{}: larger than 4 MiB", path.display())));170    }171    std::fs::read_to_string(path).map_err(|e| Failure::Io(format!("{}: {e}", path.display())))172}173174fn compile_file(path: &Path, composition: Option<&str>) -> Result<Unit, Failure> {175    // A project is compiled from its main source.176    let (file, root) = if path.is_dir() && path.extension().is_some_and(|e| e == "sonataproject") {177        let manifest = std::fs::read_to_string(path.join("project.json")).map_err(|e| Failure::Io(format!("{}: {e}", path.join("project.json").display())))?;178        let main = serde_json::from_str::<Value>(&manifest)179            .ok()180            .and_then(|v| v.get("main").and_then(|m| m.as_str()).map(|s| s.to_string()))181            .unwrap_or_else(|| "src/main.sonata".into());182        if main.starts_with('/') || main.split('/').any(|c| c == "..") {183            return Err(Failure::Io(format!("{}: the manifest's main path leaves the project", path.display())));184        }185        (path.join(&main), path.canonicalize().ok())186    } else {187        (path.to_path_buf(), project_root(path))188    };189    let source = read_source(&file)?;190    let in_project = root.is_some();191    // A lone file resolves its imports from its own folder; a project from the project.192    let (root, name) = match root {193        Some(r) => {194            let name = file195                .canonicalize()196                .ok()197                .and_then(|f| f.strip_prefix(&r).ok().map(|p| p.to_string_lossy().to_string()))198                .unwrap_or_else(|| file.display().to_string());199            (Some(r), name)200        }201        None => {202            let dir = file.parent().filter(|p| !p.as_os_str().is_empty()).map(|p| p.to_path_buf()).unwrap_or_else(|| PathBuf::from("."));203            (Some(dir), file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| file.display().to_string()))204        }205    };206    let overlays = BTreeMap::new();207    let modules = ModuleSource::new(root.as_ref(), &overlays, &name);208    let mut session = Session::default();209    let mut compiled = adapter::compile(&mut session, &name, &source, &modules, composition);210    // A project's studio edits (studio.json) are part of what the app plays and renders: apply211    // them here too, so the command line and the app agree. Skipped edits are reported.212    if in_project && !NO_STUDIO.load(Ordering::Relaxed) {213        if let (Some(program), Some(r)) = (compiled.program.as_mut(), root.as_ref()) {214            if let Ok(data) = std::fs::read(r.join("studio.json")) {215                match serde_json::from_slice::<Value>(&data).ok().and_then(|v| v.get("overrides").cloned()).map(serde_json::from_value::<sonata_ir::Overrides>)216                {217                    Some(Ok(overrides)) => {218                        for c in overrides.apply(program) {219                            eprintln!("warning: studio edit skipped: {}", c.reason);220                        }221                    }222                    Some(Err(e)) => eprintln!("warning: studio.json could not be read and was ignored: {e}"),223                    None => {}224                }225            }226        }227    }228    Ok(Unit { name, root, compiled })229}230231fn severity_word(s: Severity) -> &'static str {232    match s {233        Severity::Error => "error",234        Severity::Warning => "warning",235        Severity::Info => "info",236        Severity::Hint => "hint",237    }238}239240/// `file:line:col: severity[CODE]: message` with the source line and a caret underline.241fn render_diagnostic(d: &Diagnostic, sources: &[(String, String)]) -> String {242    let j = diagnostic_json(d, sources);243    let (file, line, col) = (j["file"].as_str().unwrap_or(""), j["line"].as_u64().unwrap_or(1), j["column"].as_u64().unwrap_or(1));244    let mut out = format!("{file}:{line}:{col}: {}[{}]: {}\n", severity_word(d.severity), d.code, d.message);245    if let Some((_, text)) = sources.get(d.span.file as usize) {246        if let Some(src_line) = text.lines().nth(line as usize - 1) {247            let end_col = if j["end_line"] == j["line"] { j["end_column"].as_u64().unwrap_or(col + 1) } else { src_line.chars().count() as u64 + 1 };248            let gutter = line.to_string();249            out.push_str(&format!("{gutter} | {}\n", src_line.replace('\t', " ")));250            out.push_str(&format!(251                "{} | {}{}\n",252                " ".repeat(gutter.len()),253                " ".repeat(col as usize - 1),254                "^".repeat((end_col.saturating_sub(col)).max(1) as usize)255            ));256        }257    }258    if let Some(s) = &d.suggestion {259        out.push_str(&format!("  help: {s}\n"));260    }261    out262}263264/// Prints diagnostics (text to stderr, or one JSON document to stdout). Returns the error count.265fn report(unit: &Unit, as_json: bool, extra: Value) -> usize {266    let errors = unit.compiled.diagnostics.iter().filter(|d| d.is_error()).count();267    let warnings = unit.compiled.diagnostics.iter().filter(|d| d.severity == Severity::Warning).count();268    if as_json {269        let list: Vec<Value> = unit.compiled.diagnostics.iter().map(|d| diagnostic_json(d, &unit.compiled.sources)).collect();270        let mut doc = json!({ "file": unit.name, "ok": errors == 0, "errors": errors, "warnings": warnings, "diagnostics": list });271        if let (Some(o), Some(e)) = (doc.as_object_mut(), extra.as_object()) {272            for (k, v) in e {273                o.insert(k.clone(), v.clone());274            }275        }276        println!("{}", serde_json::to_string_pretty(&doc).unwrap_or_default());277    } else {278        for d in &unit.compiled.diagnostics {279            eprint!("{}", render_diagnostic(d, &unit.compiled.sources));280        }281        if errors + warnings > 0 {282            eprintln!("{}: {errors} error(s), {warnings} warning(s)", unit.name);283        }284    }285    errors286}287288fn program_of(unit: &Unit) -> Option<&Program> {289    if unit.compiled.diagnostics.iter().any(|d| d.is_error()) {290        None291    } else {292        unit.compiled.program.as_ref()293    }294}295296fn one_file(args: &Args, command: &str) -> Result<PathBuf, Failure> {297    match args.positional.as_slice() {298        [f] => Ok(PathBuf::from(f)),299        [] => Err(Failure::Usage(format!("sonata {command}: no input file"))),300        _ => Err(Failure::Usage(format!("sonata {command}: expected one input file"))),301    }302}303304fn output_text(args: &Args, text: &str) -> Outcome {305    match args.value("output") {306        Some(path) => write_atomic(Path::new(path), text.as_bytes(), args.has("force")).map_err(Failure::Io),307        None => {308            let mut out = std::io::stdout().lock();309            // A closed pipe (`| head`) is not an error worth reporting.310            let _ = out.write_all(text.as_bytes());311            if !text.ends_with('\n') {312                let _ = out.write_all(b"\n");313            }314            Ok(())315        }316    }317}318319fn summary(p: &Program) -> Value {320    json!({321        "title": p.title,322        "duration_sec": p.end_sec,323        "tracks": p.tracks.len(),324        "buses": p.buses.len(),325        "notes": p.stats.notes,326        "max_polyphony": p.stats.max_polyphony,327        "sample_rate": p.master.sample_rate,328        "seed": p.seed,329    })330}331332fn cmd_check(args: &Args) -> Outcome {333    let unit = compile_file(&one_file(args, "check")?, args.value("composition"))?;334    let extra = program_of(&unit).map(|p| json!({ "summary": summary(p) })).unwrap_or(json!({}));335    let errors = report(&unit, args.has("json"), extra);336    if errors > 0 {337        return Err(Failure::Diagnostics);338    }339    if !args.has("json") {340        match program_of(&unit) {341            Some(p) => println!("{}: ok — \"{}\", {} tracks, {} notes, {:.3} s", unit.name, p.title, p.tracks.len(), p.stats.notes, p.end_sec),342            None => println!("{}: ok — module without a composition", unit.name),343        }344    }345    Ok(())346}347348fn cmd_build(args: &Args) -> Outcome {349    let unit = compile_file(&one_file(args, "build")?, args.value("composition"))?;350    if report(&unit, false, json!({})) > 0 {351        return Err(Failure::Diagnostics);352    }353    let emit = args.value("emit").unwrap_or("ir");354    if emit == "ast" {355        return output_text(args, &unit.compiled.ast_json);356    }357    let Some(p) = program_of(&unit) else { return Err(Failure::Usage(format!("{}: the file has no composition to build", unit.name))) };358    let text = match emit {359        "ir" => serde_json::to_string_pretty(p).map_err(|e| Failure::Internal(e.to_string()))?,360        "graph" => {361            let g = adapter::build_graph(p, p.master.sample_rate).map_err(Failure::Internal)?;362            serde_json::to_string_pretty(&g).map_err(|e| Failure::Internal(e.to_string()))?363        }364        "timeline" => {365            let sources = &unit.compiled.sources;366            serde_json::to_string_pretty(&sonata_ffi::timeline::timeline_json(p, &|s| sources.get(s.file as usize).map(|x| x.0.clone()).unwrap_or_default()))367                .unwrap_or_default()368        }369        "score" => serde_json::to_string_pretty(&sonata_interop::build_score(p)).map_err(|e| Failure::Internal(e.to_string()))?,370        other => return Err(Failure::Usage(format!("--emit {other}: expected ast, ir, graph, timeline or score"))),371    };372    output_text(args, &text)373}374375fn render_request(args: &Args, program: &Program, path: PathBuf) -> Result<RenderRequest, Failure> {376    let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase());377    let format = match args.value("format") {378        Some(f) => f.to_string(),379        None => match ext.as_deref() {380            Some("aif") | Some("aiff") => "aiff".into(),381            Some("flac") => "flac".into(),382            _ => "wav".into(),383        },384    };385    let bits = match args.value("bits") {386        None => {387            if args.has("float") {388                32389            } else {390                24391            }392        }393        Some(b) => b.parse::<u32>().map_err(|_| Failure::Usage(format!("--bits {b}: expected 16, 24, 32 or 64")))?,394    };395    let rate = match args.number("rate").map_err(Failure::Usage)? {396        Some(r) => r as u32,397        None => program.master.sample_rate,398    };399    let normalize = args.value("normalize").unwrap_or("none").to_string();400    Ok(RenderRequest {401        path,402        format,403        bit_depth: bits,404        float: args.has("float"),405        sample_rate: rate,406        start_sec: args.number("from").map_err(Failure::Usage)?,407        end_sec: args.number("to").map_err(Failure::Usage)?,408        tail: !args.has("no-tail"),409        dither: !args.has("no-dither"),410        normalize,411        target: args.number("target").map_err(Failure::Usage)?,412        stems: args.has("stems"),413        overwrite: args.has("force"),414    })415}416417fn do_render(unit: &Unit, program: &Program, req: &RenderRequest, quiet: bool) -> Result<(adapter::RenderOutcome, f64), Failure> {418    let assets = ProjectAssets::new(unit.root.clone());419    let started = std::time::Instant::now();420    let mut last = -1i64;421    let tty = !quiet && std::io::IsTerminal::is_terminal(&std::io::stderr());422    let mut progress = |f: f64| {423        let pct = (f * 100.0) as i64;424        if tty && pct != last {425            last = pct;426            eprint!("\rrendering {pct:3} %");427        }428    };429    let out = adapter::render(program, &assets, req, &mut progress, &|| INTERRUPTED.load(Ordering::SeqCst)).map_err(|m| {430        if tty {431            eprintln!();432        }433        if m.contains("already exists") {434            Failure::Io(format!("{m} (use --force to replace it)"))435        } else {436            Failure::Io(m)437        }438    })?;439    if tty {440        eprint!("\r                 \r");441    }442    if out.cancelled {443        return Err(Failure::Interrupted);444    }445    Ok((out, started.elapsed().as_secs_f64()))446}447448fn cmd_render(args: &Args) -> Outcome {449    let Some(output) = args.value("output") else { return Err(Failure::Usage("sonata render: --output <path> is required".into())) };450    let unit = compile_file(&one_file(args, "render")?, args.value("composition"))?;451    if report(&unit, false, json!({})) > 0 {452        return Err(Failure::Diagnostics);453    }454    let Some(program) = program_of(&unit) else { return Err(Failure::Usage(format!("{}: the file has no composition to render", unit.name))) };455    let req = render_request(args, program, PathBuf::from(output))?;456    let (out, seconds) = do_render(&unit, program, &req, args.has("json"))?;457    let files: Vec<Value> = out458        .files459        .iter()460        .map(|f| json!({ "path": f.path.to_string_lossy(), "frames": f.frames, "sample_rate": f.sample_rate, "channels": f.channels, "peak_db": f.peak_db, "true_peak_db": f.true_peak_db, "lufs": f.lufs }))461        .collect();462    let audio = out.files.first().map(|f| f.frames as f64 / f.sample_rate.max(1) as f64).unwrap_or(0.0);463    if args.has("json") {464        println!(465            "{}",466            serde_json::to_string_pretty(467                &json!({ "ok": true, "files": files, "seconds": seconds, "realtime_factor": if seconds > 0.0 { audio / seconds } else { 0.0 } })468            )469            .unwrap_or_default()470        );471    } else {472        for f in &out.files {473            println!(474                "{}: {:.3} s, {} Hz, {} ch, peak {:.2} dBFS, true peak {:.2} dBTP, {:.1} LUFS",475                f.path.display(),476                f.frames as f64 / f.sample_rate.max(1) as f64,477                f.sample_rate,478                f.channels,479                f.peak_db,480                f.true_peak_db,481                f.lufs482            );483        }484        println!("rendered in {seconds:.2} s ({:.0}x real time)", if seconds > 0.0 { audio / seconds } else { 0.0 });485    }486    Ok(())487}488489/// Renders to a temporary file and plays it with the system player (`afplay`), at the level the490/// composition's master produces. Ctrl-C stops playback.491fn cmd_play(args: &Args) -> Outcome {492    let unit = compile_file(&one_file(args, "play")?, args.value("composition"))?;493    if report(&unit, false, json!({})) > 0 {494        return Err(Failure::Diagnostics);495    }496    let Some(program) = program_of(&unit) else { return Err(Failure::Usage(format!("{}: the file has no composition to play", unit.name))) };497    let dir = std::env::temp_dir().join(format!("sonata-play-{}", std::process::id()));498    std::fs::create_dir_all(&dir).map_err(|e| Failure::Io(e.to_string()))?;499    let path = dir.join("play.wav");500    let req = RenderRequest {501        path: path.clone(),502        format: "wav".into(),503        bit_depth: 24,504        float: false,505        sample_rate: program.master.sample_rate,506        start_sec: args.number("from").map_err(Failure::Usage)?,507        end_sec: args.number("to").map_err(Failure::Usage)?,508        tail: true,509        dither: true,510        normalize: "none".into(),511        target: None,512        stems: false,513        overwrite: true,514    };515    let result = (|| {516        let (out, _) = do_render(&unit, program, &req, false)?;517        let f = out.files.first().ok_or(Failure::Internal("nothing was rendered".into()))?;518        eprintln!("playing \"{}\" — {:.1} s, peak {:.1} dBFS (Ctrl-C to stop)", program.title, f.frames as f64 / f.sample_rate.max(1) as f64, f.peak_db);519        let mut child = std::process::Command::new("/usr/bin/afplay").arg(&path).spawn().map_err(|e| Failure::Io(format!("cannot start afplay: {e}")))?;520        loop {521            match child.try_wait() {522                Ok(Some(_)) => return Ok(()),523                Ok(None) => {524                    if INTERRUPTED.load(Ordering::SeqCst) {525                        let _ = child.kill();526                        let _ = child.wait();527                        return Err(Failure::Interrupted);528                    }529                    std::thread::sleep(std::time::Duration::from_millis(40));530                }531                Err(e) => return Err(Failure::Io(e.to_string())),532            }533        }534    })();535    let _ = std::fs::remove_dir_all(&dir);536    result537}538539fn cmd_fmt(args: &Args) -> Outcome {540    if args.positional.is_empty() {541        return Err(Failure::Usage("sonata fmt: no input file".into()));542    }543    let mut unformatted = 0;544    let mut failed = false;545    for f in &args.positional {546        let path = Path::new(f);547        let source = read_source(path)?;548        match adapter::format(&source) {549            Ok(text) => {550                if args.has("stdout") {551                    print!("{text}");552                } else if text != source {553                    if args.has("check") {554                        unformatted += 1;555                        println!("{f}: would be reformatted");556                    } else {557                        // Formatting replaces the file it was asked to format; the write is atomic.558                        write_atomic(path, text.as_bytes(), true).map_err(Failure::Io)?;559                        println!("{f}: formatted");560                    }561                }562            }563            Err(ds) => {564                failed = true;565                let sources = vec![(f.clone(), source.clone())];566                for d in &ds {567                    eprint!("{}", render_diagnostic(d, &sources));568                }569            }570        }571    }572    if failed || unformatted > 0 {573        Err(Failure::Diagnostics)574    } else {575        Ok(())576    }577}578579fn cmd_inspect(args: &Args) -> Outcome {580    let unit = compile_file(&one_file(args, "inspect")?, args.value("composition"))?;581    if report(&unit, false, json!({})) > 0 {582        return Err(Failure::Diagnostics);583    }584    let Some(p) = program_of(&unit) else { return Err(Failure::Usage(format!("{}: the file has no composition to inspect", unit.name))) };585    let graph = adapter::build_graph(p, p.master.sample_rate).map_err(Failure::Internal)?;586    let tracks: Vec<Value> = p587        .tracks588        .iter()589        .map(|t| {590            let (lo, hi) = t.notes.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), n| (a.min(n.pitch), b.max(n.pitch)));591            json!({592                "id": t.id, "name": t.name,593                "instrument": t.instrument.as_ref().map(|i| i.name.clone()), "model": t.instrument.as_ref().map(|i| i.model.clone()),594                "notes": t.notes.len(), "clips": t.clips.len(),595                "lowest_pitch": if lo.is_finite() { json!(lo) } else { Value::Null }, "highest_pitch": if hi.is_finite() { json!(hi) } else { Value::Null },596                "gain_db": t.gain_db, "pan": t.pan, "mute": t.mute, "solo": t.solo,597                "effects": t.effects.iter().map(|e| e.kind.clone()).collect::<Vec<_>>(),598                "automation_lanes": t.automation.len(),599            })600        })601        .collect();602    let doc = json!({603        "file": unit.name,604        "title": p.title, "language_version": p.language_version, "seed": p.seed, "tuning_hz": p.tuning_hz,605        "key": sonata_ffi::timeline::key_name(p),606        "duration_sec": p.end_sec,607        "tempo": p.tempo_map.points.iter().map(|t| json!({ "at": t.at.to_string(), "bpm": t.bpm, "ramp": t.ramp })).collect::<Vec<_>>(),608        "signatures": p.signatures.iter().map(|s| json!({ "at": s.at.to_string(), "signature": format!("{}/{}", s.numerator, s.denominator) })).collect::<Vec<_>>(),609        "tracks": tracks,610        "buses": p.buses.iter().map(|b| json!({ "id": b.id, "name": b.name, "effects": b.effects.iter().map(|e| e.kind.clone()).collect::<Vec<_>>() })).collect::<Vec<_>>(),611        "master": { "sample_rate": p.master.sample_rate, "gain_db": p.master.gain_db, "peak_limit_db": p.master.peak_limit_db, "effects": p.master.effects.iter().map(|e| e.kind.clone()).collect::<Vec<_>>() },612        "notes": p.stats.notes, "max_polyphony": p.stats.max_polyphony, "automation_points": p.stats.automation_points,613        "graph": { "sample_rate": graph.sample_rate, "nodes": graph.nodes.len(), "edges": graph.edges.len(), "latency_frames": graph.total_latency },614        "compile_us": { "lex": unit.compiled.lex_us, "parse": unit.compiled.parse_us, "semantics": unit.compiled.sema_us },615    });616    if args.has("json") {617        println!("{}", serde_json::to_string_pretty(&doc).unwrap_or_default());618        return Ok(());619    }620    println!("\"{}\" — {:.3} s, {} Hz, seed {}", p.title, p.end_sec, p.master.sample_rate, p.seed);621    if let Some(k) = sonata_ffi::timeline::key_name(p) {622        println!("key {k}, A4 = {} Hz", p.tuning_hz);623    }624    for t in &p.tempo_map.points {625        println!("tempo {} bpm at {}{}", t.bpm, t.at, if t.ramp { " (ramp)" } else { "" });626    }627    println!("{:<4}{:<18}{:<20}{:<18}{:>7}{:>9}  effects", "id", "track", "instrument", "model", "notes", "gain");628    for t in &p.tracks {629        println!(630            "{:<4}{:<18}{:<20}{:<18}{:>7}{:>7.1}dB  {}",631            t.id,632            t.name,633            t.instrument.as_ref().map(|i| i.name.as_str()).unwrap_or("-"),634            t.instrument.as_ref().map(|i| i.model.as_str()).unwrap_or("audio"),635            t.notes.len(),636            t.gain_db,637            t.effects.iter().map(|e| e.kind.as_str()).collect::<Vec<_>>().join(", ")638        );639    }640    println!("{} notes, {} voices at most, graph of {} nodes, latency {} frames", p.stats.notes, p.stats.max_polyphony, graph.nodes.len(), graph.total_latency);641    Ok(())642}643644fn cmd_export(args: &Args) -> Outcome {645    let Some(output) = args.value("output") else { return Err(Failure::Usage("sonata export: --output <path> is required".into())) };646    let unit = compile_file(&one_file(args, "export")?, args.value("composition"))?;647    if report(&unit, false, json!({})) > 0 {648        return Err(Failure::Diagnostics);649    }650    let Some(p) = program_of(&unit) else { return Err(Failure::Usage(format!("{}: the file has no composition to export", unit.name))) };651    let path = Path::new(output);652    let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();653    let (bytes, warnings) = match ext.as_str() {654        "mid" | "midi" => sonata_interop::program_to_midi(p),655        "musicxml" | "xml" => {656            let (xml, w) = sonata_interop::program_to_musicxml(p);657            (xml.into_bytes(), w)658        }659        other => return Err(Failure::Usage(format!("cannot export to '.{other}': use .mid or .musicxml"))),660    };661    write_atomic(path, &bytes, args.has("force"))662        .map_err(|m| Failure::Io(if m.contains("already exists") { format!("{m} (use --force to replace it)") } else { m }))?;663    for w in &warnings {664        eprintln!("warning: {w}");665    }666    println!("{}: {} bytes", path.display(), bytes.len());667    Ok(())668}669670fn cmd_import(args: &Args) -> Outcome {671    let input = one_file(args, "import")?;672    let meta = std::fs::metadata(&input).map_err(|e| Failure::Io(format!("{}: {e}", input.display())))?;673    if meta.len() > sonata_interop::midi::MAX_MIDI_BYTES as u64 {674        return Err(Failure::Io(format!("{}: too large", input.display())));675    }676    let data = std::fs::read(&input).map_err(|e| Failure::Io(format!("{}: {e}", input.display())))?;677    let file = sonata_interop::parse_midi(&data).map_err(|m| Failure::Io(format!("{}: {m}", input.display())))?;678    let instrument = args.value("instrument").unwrap_or("GrandPiano");679    if !instrument.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') || instrument.is_empty() {680        return Err(Failure::Usage("--instrument must be an instrument name".into()));681    }682    output_text(args, &sonata_interop::midi_to_sonata(&file, instrument))683}684685fn collect_sonata_files(path: &Path, out: &mut Vec<PathBuf>, depth: usize) {686    if depth > 12 {687        return;688    }689    if path.is_dir() {690        let mut entries: Vec<PathBuf> = std::fs::read_dir(path).map(|r| r.filter_map(|e| e.ok().map(|e| e.path())).collect()).unwrap_or_default();691        entries.sort();692        for e in entries {693            let hidden = e.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.'));694            if !hidden && !e.is_symlink() {695                collect_sonata_files(&e, out, depth + 1);696            }697        }698    } else if path.extension().is_some_and(|e| e == "sonata") {699        out.push(path.to_path_buf());700    }701}702703/// Compiles every `.sonata` file given (default: the current directory, recursively) and checks704/// the expectations written in its comments:705/// `// expect: ok` (default), `// expect: error CODE`, `// expect: notes N`, `// expect: duration S`706/// (seconds, ±1 ms), `// expect: tracks N`. A file renders deterministically: it is rendered twice707/// for 0.25 s when it has `// expect: deterministic`.708fn cmd_test(args: &Args) -> Outcome {709    let mut files = Vec::new();710    let roots: Vec<String> = if args.positional.is_empty() { vec![".".into()] } else { args.positional.clone() };711    for r in &roots {712        let p = Path::new(r);713        if !p.exists() {714            return Err(Failure::Io(format!("{r}: no such file or directory")));715        }716        collect_sonata_files(p, &mut files, 0);717    }718    if files.is_empty() {719        return Err(Failure::Usage("sonata test: no .sonata file found".into()));720    }721    let mut results = Vec::new();722    let mut failures = 0usize;723    for f in &files {724        if INTERRUPTED.load(Ordering::SeqCst) {725            return Err(Failure::Interrupted);726        }727        let unit = compile_file(f, None)?;728        let source = read_source(f)?;729        let expectations: Vec<String> = source.lines().filter_map(|l| l.trim().strip_prefix("// expect:").map(|e| e.trim().to_string())).collect();730        let codes: Vec<&str> = unit.compiled.diagnostics.iter().filter(|d| d.is_error()).map(|d| d.code.as_str()).collect();731        let program = program_of(&unit);732        let mut problems: Vec<String> = Vec::new();733        let expects_error = expectations.iter().any(|e| e.starts_with("error"));734        if !expects_error && !codes.is_empty() {735            problems.push(format!("unexpected errors: {}", codes.join(", ")));736        }737        for e in &expectations {738            let mut words = e.split_whitespace();739            match (words.next(), words.next()) {740                (Some("ok"), _) => {}741                (Some("error"), Some(code)) => {742                    if !codes.contains(&code) {743                        problems.push(format!("expected error {code}, got [{}]", codes.join(", ")));744                    }745                }746                (Some("error"), None) => {747                    if codes.is_empty() {748                        problems.push("expected an error".into());749                    }750                }751                (Some("notes"), Some(n)) => {752                    let got = program.map(|p| p.stats.notes);753                    if n.parse::<u64>().ok() != got {754                        problems.push(format!("expected {n} notes, got {got:?}"));755                    }756                }757                (Some("tracks"), Some(n)) => {758                    let got = program.map(|p| p.tracks.len() as u64);759                    if n.parse::<u64>().ok() != got {760                        problems.push(format!("expected {n} tracks, got {got:?}"));761                    }762                }763                (Some("duration"), Some(s)) => {764                    let want = s.trim_end_matches('s').parse::<f64>().unwrap_or(f64::NAN);765                    let got = program.map(|p| p.end_sec).unwrap_or(f64::NAN);766                    if (want - got).abs() > 1e-3 || got.is_nan() {767                        problems.push(format!("expected a duration of {want} s, got {got}"));768                    }769                }770                (Some("deterministic"), _) => match program {771                    Some(p) => {772                        let hash = |p: &Program| -> Result<u64, String> {773                            let graph = adapter::build_graph(p, 48_000)?;774                            let opts = sonata_render::render::RenderOptions { range: Some((0.0, p.end_sec.clamp(0.05, 0.25))), ..Default::default() };775                            let flag = AtomicBool::new(false);776                            let out =777                                sonata_render::render::render(p, &graph, &sonata_runtime::NoAssets, &opts, &mut |_| {}, &flag).map_err(|e| e.to_string())?;778                            let mut h = 0xcbf29ce484222325u64;779                            for c in &out.audio.channels {780                                for s in c {781                                    h = (h ^ s.to_bits() as u64).wrapping_mul(0x100000001b3);782                                }783                            }784                            Ok(h)785                        };786                        match (hash(p), hash(p)) {787                            (Ok(a), Ok(b)) if a == b => {}788                            (Ok(_), Ok(_)) => problems.push("two renders of the same program differ".into()),789                            (Err(m), _) | (_, Err(m)) => problems.push(format!("render failed: {m}")),790                        }791                    }792                    None => problems.push("expected a deterministic render but there is no program".into()),793                },794                (Some(other), _) => problems.push(format!("unknown expectation '{other}'")),795                (None, _) => {}796            }797        }798        let ok = problems.is_empty();799        if !ok {800            failures += 1;801        }802        if !args.has("json") {803            println!("{} {}", if ok { "ok  " } else { "FAIL" }, f.display());804            for p in &problems {805                println!("       {p}");806            }807        }808        results.push(json!({ "file": f.to_string_lossy(), "ok": ok, "problems": problems }));809    }810    if args.has("json") {811        println!(812            "{}",813            serde_json::to_string_pretty(&json!({ "ok": failures == 0, "files": results.len(), "failures": failures, "results": results })).unwrap_or_default()814        );815    } else {816        println!("{} file(s), {} failure(s)", results.len(), failures);817    }818    if failures > 0 {819        Err(Failure::Diagnostics)820    } else {821        Ok(())822    }823}824825/// Built-in benchmark program: `voices` simultaneous notes of one engine held for `seconds`.826fn bench_source(model_instrument: &str, voices: usize, seconds: f64) -> String {827    let bars = (seconds / 2.0).ceil().max(1.0) as usize;828    let mut s = String::from("import std.music\nimport std.instruments\n\ncomposition \"Benchmark\" {\n    tempo 120bpm\n    signature 4/4\n");829    s.push_str(&format!("    instrument bench: {model_instrument} {{\n        gain -24dB\n"));830    for v in 0..voices {831        // Spread over three octaves so voices are not unisons.832        let midi = 36 + (v * 7) % 37;833        let names = ["C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"];834        let note = format!("{}{}", names[midi % 12], midi / 12 - 1);835        s.push_str(&format!("        voice {{ repeat {bars} {{ play {note} duration 1/1 velocity 0.6 }} }}\n"));836    }837    s.push_str("    }\n}\n");838    s839}840841fn time_program(program: &Program, sample_rate: u32, block: usize, seconds: f64) -> Result<Value, String> {842    use sonata_runtime::{engine, EngineConfig, Limits, NoAssets, PreparedProgram};843    let graph = adapter::build_graph(program, sample_rate)?;844    let limits = Limits { max_voices: Limits::default().max_voices.max(program.stats.max_polyphony as usize + 8).min(4096), ..Limits::default() };845    let prepared = PreparedProgram::prepare(program, &graph, sample_rate, block, &NoAssets, &limits)?;846    let (controller, mut processor) = engine(EngineConfig::realtime(sample_rate));847    controller.load(prepared).map_err(|_| "the engine refused the program".to_string())?;848    controller.play();849    let mut l = vec![0.0f32; block];850    let mut r = vec![0.0f32; block];851    let blocks = ((seconds * sample_rate as f64) / block as f64).ceil() as usize;852    // Warm-up: let the swap crossfade and the attacks pass.853    for _ in 0..(sample_rate as usize / block / 4).max(4) {854        processor.process(&mut l, &mut r);855    }856    controller.shared().reset_timing();857    let mut peak_voices = 0u32;858    let mut peak = 0.0f32;859    let started = std::time::Instant::now();860    for _ in 0..blocks {861        processor.process(&mut l, &mut r);862        peak_voices = peak_voices.max(controller.shared().active_voices());863        for i in 0..block {864            peak = peak.max(l[i].abs()).max(r[i].abs());865        }866    }867    let wall = started.elapsed().as_secs_f64();868    let t = controller.shared().timing();869    let budget_us = block as f64 / sample_rate as f64 * 1e6;870    Ok(json!({871        "sample_rate": sample_rate, "block": block, "budget_us": budget_us,872        "callbacks": t.callbacks, "mean_us": t.mean_us, "p50_us": t.p50_us, "p95_us": t.p95_us, "p99_us": t.p99_us, "p999_us": t.p999_us, "max_us": t.max_us,873        "missed_deadlines": t.missed_deadlines,874        "load_percent_p99": t.p99_us / budget_us * 100.0,875        "realtime_factor": blocks as f64 * block as f64 / sample_rate as f64 / wall,876        "peak_voices": peak_voices,877        "peak_dbfs": if peak > 0.0 { 20.0 * (peak as f64).log10() } else { -200.0 },878        "scrubbed_samples": controller.shared().scrubbed_samples(),879    }))880}881882/// Measures compile time and callback-time percentiles through the real-time processor.883/// With a file: that composition at 48 kHz, blocks of 128 and 256. Without: a ladder of884/// simultaneous voices of a simple synth and of the piano. Results describe THIS machine now;885/// they are measurements, not guarantees.886fn cmd_benchmark(args: &Args) -> Outcome {887    let seconds = args.number("seconds").map_err(Failure::Usage)?.unwrap_or(4.0).clamp(0.5, 120.0);888    let mut rows: Vec<Value> = Vec::new();889    let overlays = BTreeMap::new();890    let compile = |name: &str, source: &str| -> Result<(Program, f64), Failure> {891        let modules = ModuleSource::new(None, &overlays, name);892        let mut session = Session::default();893        let started = std::time::Instant::now();894        let c = adapter::compile(&mut session, name, source, &modules, None);895        let us = started.elapsed().as_secs_f64() * 1e6;896        if let Some(d) = c.diagnostics.iter().find(|d| d.is_error()) {897            return Err(Failure::Internal(format!("{name}: {}: {}", d.code, d.message)));898        }899        c.program.map(|p| (p, us)).ok_or(Failure::Internal(format!("{name}: no program")))900    };901    if let Some(f) = args.positional.first() {902        let unit = compile_file(Path::new(f), None)?;903        if report(&unit, false, json!({})) > 0 {904            return Err(Failure::Diagnostics);905        }906        let Some(p) = program_of(&unit) else { return Err(Failure::Usage(format!("{f}: no composition"))) };907        let compile_us = unit.compiled.lex_us + unit.compiled.parse_us + unit.compiled.sema_us;908        for block in [128usize, 256] {909            let mut row = time_program(p, 48_000, block, seconds.min(p.end_sec.max(0.5))).map_err(Failure::Internal)?;910            row["case"] = json!(unit.name);911            row["compile_us"] = json!(compile_us);912            rows.push(row);913        }914    } else {915        for (instrument, ladder) in [("SynthLead", &[1usize, 8, 16, 32, 64, 128, 256][..]), ("GrandPiano", &[1usize, 8, 16, 32, 64][..])] {916            for &voices in ladder {917                if INTERRUPTED.load(Ordering::SeqCst) {918                    return Err(Failure::Interrupted);919                }920                let (p, compile_us) = compile("benchmark", &bench_source(instrument, voices, seconds + 1.0))?;921                for block in [128usize, 256] {922                    let mut row = time_program(&p, 48_000, block, seconds).map_err(Failure::Internal)?;923                    row["case"] = json!(format!("{instrument} x{voices}"));924                    row["voices_requested"] = json!(voices);925                    row["compile_us"] = json!(compile_us);926                    rows.push(row);927                }928            }929        }930    }931    let machine = machine_description();932    if args.has("json") {933        println!(934            "{}",935            serde_json::to_string_pretty(936                &json!({ "machine": machine, "build": if cfg!(debug_assertions) { "debug" } else { "release" }, "seconds_per_case": seconds, "results": rows })937            )938            .unwrap_or_default()939        );940        return Ok(());941    }942    println!("machine: {machine}");943    println!(944        "build: {} — {seconds} s per case, 48 kHz, single thread, offline clock (no audio device)",945        if cfg!(debug_assertions) { "DEBUG (numbers are not representative)" } else { "release" }946    );947    println!("{:<22}{:>6}{:>9}{:>9}{:>9}{:>9}{:>9}{:>8}{:>8}{:>8}", "case", "block", "budget", "mean", "p50", "p99", "max", "load99", "missed", "voices");948    for r in &rows {949        let f = |k: &str| r[k].as_f64().unwrap_or(0.0);950        println!(951            "{:<22}{:>6}{:>7.0}us{:>7.1}us{:>7.1}us{:>7.1}us{:>7.1}us{:>7.1}%{:>8}{:>8}",952            r["case"].as_str().unwrap_or(""),953            r["block"].as_u64().unwrap_or(0),954            f("budget_us"),955            f("mean_us"),956            f("p50_us"),957            f("p99_us"),958            f("max_us"),959            f("load_percent_p99"),960            r["missed_deadlines"].as_u64().unwrap_or(0),961            r["peak_voices"].as_u64().unwrap_or(0)962        );963    }964    println!("percentiles are upper bounds of 5 us buckets; load99 = p99 / buffer duration");965    Ok(())966}967968fn sysctl(name: &str) -> Option<String> {969    let out = std::process::Command::new("/usr/sbin/sysctl").arg("-n").arg(name).output().ok()?;970    Some(String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|s| !s.is_empty())971}972973fn machine_description() -> String {974    let cpu = sysctl("machdep.cpu.brand_string").unwrap_or_else(|| "unknown CPU".into());975    let cores = sysctl("hw.ncpu").unwrap_or_default();976    let mem = sysctl("hw.memsize").and_then(|m| m.parse::<u64>().ok()).map(|b| format!("{} GB", b >> 30)).unwrap_or_default();977    let os = sysctl("kern.osproductversion").unwrap_or_default();978    format!("{cpu}, {cores} cores, {mem}, macOS {os}")979}980981fn unit_name(u: sonata_ir::Unit) -> &'static str {982    use sonata_ir::Unit::*;983    match u {984        Scalar => "",985        Ratio => "ratio",986        Decibel => "dB",987        Hertz => "Hz",988        Seconds => "s",989        Semitones => "st",990        Count => "count",991        Degrees => "deg",992        HertzList => "Hz list",993        ScalarList => "list",994        Choice => "choice",995    }996}997998fn params_table(params: &[sonata_ir::ParamDesc]) -> String {999    let mut s = String::new();1000    for p in params {1001        if p.unit == sonata_ir::Unit::Choice {1002            s.push_str(&format!("  {:<26} {} (default {})\n      {}\n", p.name, p.choices.join(" | "), p.default_choice.clone().unwrap_or_default(), p.doc));1003        } else if matches!(p.unit, sonata_ir::Unit::HertzList | sonata_ir::Unit::ScalarList) {1004            s.push_str(&format!("  {:<26} {}\n      {}\n", p.name, unit_name(p.unit), p.doc));1005        } else {1006            s.push_str(&format!(1007                "  {:<26} {} .. {} {} (default {}){}\n      {}\n",1008                p.name,1009                p.min,1010                p.max,1011                unit_name(p.unit),1012                p.default,1013                if p.automatable { ", automatable" } else { "" },1014                p.doc1015            ));1016        }1017    }1018    s1019}10201021/// The parameter reference, generated from the same registry the compiler validates against.1022fn cmd_docs(args: &Args) -> Outcome {1023    let r = adapter::registry();1024    if args.has("json") {1025        println!("{}", serde_json::to_string_pretty(r).unwrap_or_default());1026        return Ok(());1027    }1028    let topic = args.positional.first().map(|s| s.as_str()).unwrap_or("");1029    let mut out = String::new();1030    match topic {1031        "" => {1032            out.push_str(&format!(1033                "Sonata {} — {} instrument engines, {} effects, {} patch nodes\n\n",1034                sonata_ir::LANGUAGE_VERSION,1035                r.engines.len(),1036                r.effects.len(),1037                r.patch_nodes.len()1038            ));1039            out.push_str("ENGINES (model)\n");1040            for e in &r.engines {1041                out.push_str(&format!("  {:<18} {:<12} {} presets  {}\n", e.model, e.family, e.presets.len(), e.title));1042            }1043            out.push_str("\nEFFECTS\n");1044            for e in &r.effects {1045                out.push_str(&format!("  {:<18} {:<12} {} presets  {}\n", e.kind, e.category, e.presets.len(), e.title));1046            }1047            out.push_str("\nPATCH NODES\n");1048            for n in &r.patch_nodes {1049                out.push_str(&format!("  {:<18} {:<12} {}\n", n.kind, n.category, n.title));1050            }1051            out.push_str("\nsonata docs <name> shows parameters, ranges, units and presets.\n");1052        }1053        "engines" => r.engines.iter().for_each(|e| out.push_str(&format!("{:<18} {}\n", e.model, e.title))),1054        "effects" => r.effects.iter().for_each(|e| out.push_str(&format!("{:<18} {}\n", e.kind, e.title))),1055        "nodes" => r.patch_nodes.iter().for_each(|e| out.push_str(&format!("{:<18} {}\n", e.kind, e.title))),1056        name => {1057            if let Some(e) = r.engine(name) {1058                out.push_str(&format!(1059                    "{} — engine `{}` ({})\n{}\nMethod: {}\nRange: MIDI {}..{}{}\nArticulations: {}\n\nPARAMETERS\n{}",1060                    e.title,1061                    e.model,1062                    e.family,1063                    e.doc,1064                    e.method,1065                    e.range.0,1066                    e.range.1,1067                    if e.pitched { "" } else { " (unpitched)" },1068                    e.articulations.join(", "),1069                    params_table(&e.params)1070                ));1071                out.push_str("\nPRESETS\n");1072                for p in &e.presets {1073                    out.push_str(&format!("  {:<20} {}\n", p.name, p.doc));1074                }1075            } else if let Some(e) = r.effect(name) {1076                out.push_str(&format!(1077                    "{} — effect `{}` ({})\n{}\nDefault mix: {}   Latency: {} s + {} samples\n\nPARAMETERS\n{}",1078                    e.title,1079                    e.kind,1080                    e.category,1081                    e.doc,1082                    e.default_mix,1083                    e.latency.seconds,1084                    e.latency.samples,1085                    params_table(&e.params)1086                ));1087                out.push_str("\nPRESETS\n");1088                for p in &e.presets {1089                    out.push_str(&format!("  {:<20} {}\n", p.name, p.doc));1090                }1091            } else if let Some(n) = r.patch_node(name) {1092                out.push_str(&format!("{} — patch node `{}` ({})\n{}\n\nPORTS\n", n.title, n.kind, n.category, n.doc));1093                for p in &n.ports {1094                    out.push_str(&format!(1095                        "  {:<14} {} .. {} {} (default {}){}\n      {}\n",1096                        p.name,1097                        p.min,1098                        p.max,1099                        unit_name(p.unit),1100                        p.default,1101                        if p.constant_only { ", constant only" } else { "" },1102                        p.doc1103                    ));1104                }1105            } else {1106                return Err(Failure::Usage(format!("sonata docs: nothing named '{name}' (try `sonata docs`)")));1107            }1108        }1109    }1110    let _ = std::io::stdout().lock().write_all(out.as_bytes());1111    Ok(())1112}11131114/// Packages. A package holds Sonata sources and documentation only; nothing in it is executed.1115/// `--project` is the folder that receives `packages/` and `sonata.lock` (default: the current1116/// folder; for a .sonataproject, the package itself). Once installed, `import name.module` works1117/// from any source compiled with that folder as its root.1118fn cmd_pkg(args: &Args) -> Outcome {1119    let Some(sub) = args.positional.first().map(|s| s.as_str()) else {1120        return Err(Failure::Usage("sonata pkg: pack, verify, install, resolve, list, check or remove".into()));1121    };1122    let rest = &args.positional[1..];1123    let project = PathBuf::from(args.value("project").unwrap_or("."));1124    let read_package = |path: &str| -> Result<sonata_pkg::Package, Failure> {1125        let meta = std::fs::metadata(path).map_err(|e| Failure::Io(format!("{path}: {e}")))?;1126        if meta.len() as usize > sonata_pkg::archive::MAX_ARCHIVE_BYTES {1127            return Err(Failure::Io(format!("{path}: larger than a package may be")));1128        }1129        let data = std::fs::read(path).map_err(|e| Failure::Io(format!("{path}: {e}")))?;1130        sonata_pkg::verify(&data).map_err(|e| Failure::Io(format!("{path}: {e}")))1131    };1132    match sub {1133        "pack" => {1134            let [dir] = rest else { return Err(Failure::Usage("sonata pkg pack <dir>".into())) };1135            let bytes = sonata_pkg::pack(Path::new(dir)).map_err(Failure::Io)?;1136            let package = sonata_pkg::verify(&bytes).map_err(Failure::Internal)?;1137            // Every module of the package must compile before it can be shipped.1138            for (name, content) in package.files.iter().filter(|(n, _)| n.starts_with("src/") && n.ends_with(".sonata")) {1139                let text = String::from_utf8_lossy(content).to_string();1140                let overlays: BTreeMap<String, String> =1141                    package.files.iter().filter(|(n, _)| n.ends_with(".sonata")).map(|(n, c)| (n.clone(), String::from_utf8_lossy(c).to_string())).collect();1142                let modules = ModuleSource::new(None, &overlays, name);1143                let mut session = Session::default();1144                let compiled = adapter::compile(&mut session, name, &text, &modules, None);1145                if compiled.diagnostics.iter().any(|d| d.is_error()) {1146                    for d in &compiled.diagnostics {1147                        eprint!("{}", render_diagnostic(d, &compiled.sources));1148                    }1149                    return Err(Failure::Diagnostics);1150                }1151            }1152            let default = format!("{}-{}.sonatapkg", package.manifest.name, package.manifest.version);1153            let out = args.value("output").unwrap_or(&default);1154            write_atomic(Path::new(out), &bytes, args.has("force"))1155                .map_err(|m| Failure::Io(if m.contains("already exists") { format!("{m} (use --force to replace it)") } else { m }))?;1156            println!(1157                "{out}: {} {} — {} files, {} bytes, sha256 {}",1158                package.manifest.name,1159                package.manifest.version,1160                package.files.len(),1161                bytes.len(),1162                package.archive_sha2561163            );1164            Ok(())1165        }1166        "verify" => {1167            let [file] = rest else { return Err(Failure::Usage("sonata pkg verify <file.sonatapkg>".into())) };1168            let p = read_package(file)?;1169            println!("{file}: ok — {} {} ({}), {} files, sha256 {}", p.manifest.name, p.manifest.version, p.manifest.license, p.files.len(), p.archive_sha256);1170            for (dep, req) in &p.manifest.dependencies {1171                println!("  needs {dep} {req}");1172            }1173            Ok(())1174        }1175        "install" => {1176            if rest.is_empty() {1177                return Err(Failure::Usage("sonata pkg install <file.sonatapkg>...".into()));1178            }1179            // Verify everything first: nothing is installed if one archive is bad.1180            let packages: Vec<sonata_pkg::Package> = rest.iter().map(|f| read_package(f)).collect::<Result<_, _>>()?;1181            for p in &packages {1182                let dest = sonata_pkg::install(p, &project, args.has("force")).map_err(Failure::Io)?;1183                println!("installed {} {} in {}", p.manifest.name, p.manifest.version, dest.display());1184            }1185            report_package_problems(&project)1186        }1187        "resolve" => {1188            let Some(from) = args.value("from") else { return Err(Failure::Usage("sonata pkg resolve --from <dir-of-packages>".into())) };1189            let mut roots: BTreeMap<String, String> = match std::fs::read(project.join("dependencies.json")) {1190                Ok(data) => serde_json::from_slice(&data).map_err(|e| Failure::Io(format!("dependencies.json: {e}")))?,1191                Err(_) => BTreeMap::new(),1192            };1193            for spec in rest {1194                let (name, req) = spec.split_once('@').unwrap_or((spec.as_str(), "*"));1195                roots.insert(name.to_string(), req.to_string());1196            }1197            if roots.is_empty() {1198                return Err(Failure::Usage("sonata pkg resolve: give name@requirement arguments or a dependencies.json in the project".into()));1199            }1200            let mut files: Vec<PathBuf> = std::fs::read_dir(from)1201                .map_err(|e| Failure::Io(format!("{from}: {e}")))?1202                .filter_map(|e| e.ok().map(|e| e.path()))1203                .filter(|p| p.extension().is_some_and(|e| e == "sonatapkg"))1204                .collect();1205            files.sort();1206            let mut available = Vec::new();1207            for f in &files {1208                match read_package(&f.to_string_lossy()) {1209                    Ok(p) => available.push(p),1210                    Err(Failure::Io(m)) => eprintln!("warning: ignored {m}"),1211                    Err(e) => return Err(e),1212                }1213            }1214            let chosen = sonata_pkg::resolve(&roots, &available).map_err(Failure::Io)?;1215            for p in &chosen {1216                sonata_pkg::install(p, &project, true).map_err(Failure::Io)?;1217                println!("installed {} {} (sha256 {})", p.manifest.name, p.manifest.version, p.archive_sha256);1218            }1219            report_package_problems(&project)1220        }1221        "list" => {1222            let lock = sonata_pkg::Lock::read(&project).map_err(Failure::Io)?;1223            for p in &lock.packages {1224                println!("{} {} sha256 {}", p.name, p.version, p.sha256);1225            }1226            if lock.packages.is_empty() {1227                println!("no package is installed in {}", project.display());1228            }1229            Ok(())1230        }1231        "check" => report_package_problems(&project),1232        "remove" => {1233            let [name] = rest else { return Err(Failure::Usage("sonata pkg remove <name>".into())) };1234            sonata_pkg::remove(name, &project).map_err(Failure::Io)?;1235            println!("removed {name}");1236            Ok(())1237        }1238        other => Err(Failure::Usage(format!("sonata pkg: unknown subcommand '{other}'"))),1239    }1240}12411242fn report_package_problems(project: &Path) -> Outcome {1243    let problems = sonata_pkg::check_installed(project).map_err(Failure::Io)?;1244    for p in &problems {1245        eprintln!("{}: {}", p.package, p.message);1246    }1247    if problems.is_empty() {1248        println!("packages: ok");1249        Ok(())1250    } else {1251        Err(Failure::Diagnostics)1252    }1253}12541255fn run(raw: &[String]) -> Outcome {1256    let Some(command) = raw.first() else {1257        print!("{USAGE}");1258        return Err(Failure::Usage(String::new()));1259    };1260    let args = parse_args(&raw[1..]).map_err(Failure::Usage)?;1261    NO_STUDIO.store(args.has("no-studio"), Ordering::Relaxed);1262    if args.has("help") || command == "help" || command == "--help" || command == "-h" {1263        print!("{USAGE}");1264        return Ok(());1265    }1266    match command.as_str() {1267        "check" => cmd_check(&args),1268        "build" => cmd_build(&args),1269        "render" => cmd_render(&args),1270        "play" => cmd_play(&args),1271        "fmt" => cmd_fmt(&args),1272        "inspect" => cmd_inspect(&args),1273        "export" => cmd_export(&args),1274        "import" => cmd_import(&args),1275        "test" => cmd_test(&args),1276        "benchmark" => cmd_benchmark(&args),1277        "docs" => cmd_docs(&args),1278        "pkg" => cmd_pkg(&args),1279        "version" | "--version" | "-V" => {1280            println!("sonata {} (language {}, IR {})", env!("CARGO_PKG_VERSION"), sonata_ir::LANGUAGE_VERSION, sonata_ir::IR_VERSION);1281            Ok(())1282        }1283        other => Err(Failure::Usage(format!("unknown command '{other}'"))),1284    }1285}12861287fn main() -> ExitCode {1288    // SAFETY: installs an async-signal-safe handler (one atomic store) for SIGINT (2).1289    unsafe {1290        signal(2, on_sigint);1291    }1292    let raw: Vec<String> = std::env::args().skip(1).collect();1293    let result = std::panic::catch_unwind(|| run(&raw));1294    let code = match result {1295        Ok(Ok(())) => EXIT_OK,1296        Ok(Err(Failure::Diagnostics)) => EXIT_DIAGNOSTICS,1297        Ok(Err(Failure::Usage(m))) => {1298            if !m.is_empty() {1299                eprintln!("sonata: {m}\nTry `sonata help`.");1300            }1301            EXIT_USAGE1302        }1303        Ok(Err(Failure::Io(m))) => {1304            eprintln!("sonata: {m}");1305            EXIT_IO1306        }1307        Ok(Err(Failure::Internal(m))) => {1308            eprintln!("sonata: internal error: {m}");1309            EXIT_INTERNAL1310        }1311        Ok(Err(Failure::Interrupted)) => {1312            eprintln!("sonata: interrupted");1313            EXIT_INTERRUPTED1314        }1315        Err(_) => {1316            eprintln!("sonata: internal error (panic); please report this with the input that caused it");1317            EXIT_INTERNAL1318        }1319    };1320    ExitCode::from(code)1321}1322
Files main
Menu

Theme