Repository Public
1//! ORIX Sonata2//! File: crates/sonata-compiler/src/lib.rs3//! Description: Compiler driver: source to Program and DspGraph, optimisation, content-hash cache, incremental compilation.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78mod graph;9mod loader;10pub mod services;1112pub use graph::{build_graph_with, GraphOptions};13pub use loader::DirLoader;14pub use sonata_parser::format;15pub use sonata_semantics::{Def, DefKind, MapLoader, NoLoader, Quotas, SourceLoader, SymbolIndex};1617use serde::Serialize;18use sonata_ir::{Diagnostic, DspGraph, FileId, LineCol, LineIndex, Program, Registry, Severity, Span};19use sonata_parser::{parse_timed, Parsed};20use sonata_semantics::{analyze, load_modules_with, ModuleSet, Options};21use std::collections::HashMap;22use std::hash::{Hash, Hasher};23use std::sync::{Arc, OnceLock};24use std::time::{Duration, Instant};2526/// The registry of this build: every instrument engine, effect and patch node, as published27/// by the DSP crates. The compiler validates against it; the documentation is generated from it.28pub fn registry() -> &'static Registry {29 static R: OnceLock<Registry> = OnceLock::new();30 R.get_or_init(|| Registry {31 engines: sonata_instruments::engine_registry(),32 effects: sonata_dsp::effect_registry(),33 patch_nodes: sonata_instruments::patch_node_registry(),34 })35}3637/// Options of one compilation.38#[derive(Clone, Debug, Default, PartialEq)]39pub struct CompileOptions {40 /// Sample rate of the graph; the project rate (`master { sample_rate … }`) when `None`.41 pub sample_rate: Option<u32>,42 pub quotas: Quotas,43 /// Title of the composition to compile; the first of the root file when `None`.44 pub composition: Option<String>,45 pub graph: GraphOptions,46}4748/// One source file of a compilation.49#[derive(Clone, Debug)]50pub struct SourceEntry {51 /// Root file name as given by the caller, or the dotted module path (`std.music`).52 pub name: String,53 pub text: Arc<str>,54 pub lines: Arc<LineIndex>,55 pub is_std: bool,56}5758/// Maps spans back to files, lines and columns. `FileId` indexes `files`; 0 is the root.59#[derive(Clone, Debug, Default)]60pub struct SourceMap {61 pub files: Vec<SourceEntry>,62}6364/// A span resolved to human coordinates (1-based, columns in Unicode scalar values).65#[derive(Clone, Debug, PartialEq, Eq, Serialize)]66pub struct Location {67 pub file: String,68 pub file_id: FileId,69 pub start: u32,70 pub end: u32,71 pub line: u32,72 pub column: u32,73 pub end_line: u32,74 pub end_column: u32,75}7677impl SourceMap {78 pub fn file(&self, id: FileId) -> Option<&SourceEntry> {79 self.files.get(id as usize)80 }81 pub fn line_col(&self, file: FileId, offset: u32) -> LineCol {82 match self.file(file) {83 Some(f) => f.lines.line_col(&f.text, offset),84 None => LineCol { line: 1, column: 1 },85 }86 }87 pub fn locate(&self, span: Span) -> Location {88 let (a, b) = (self.line_col(span.file, span.start), self.line_col(span.file, span.end));89 Location {90 file: self.file(span.file).map(|f| f.name.clone()).unwrap_or_default(),91 file_id: span.file,92 start: span.start,93 end: span.end,94 line: a.line,95 column: a.column,96 end_line: b.line,97 end_column: b.column,98 }99 }100 /// Text of a span, when it is valid.101 pub fn snippet(&self, span: Span) -> Option<&str> {102 self.file(span.file).and_then(|f| f.text.get(span.start as usize..span.end as usize))103 }104105 /// Renders a diagnostic for a terminal: location, code, message, the source line with a106 /// caret underline, then the suggestion.107 pub fn render(&self, d: &Diagnostic) -> String {108 let loc = self.locate(d.span);109 let sev = match d.severity {110 Severity::Error => "error",111 Severity::Warning => "warning",112 Severity::Info => "info",113 Severity::Hint => "hint",114 };115 let mut out = format!("{}:{}:{}: {sev}[{}]: {}\n", loc.file, loc.line, loc.column, d.code, d.message);116 if let Some(f) = self.file(d.span.file) {117 if let Some(start) = f.lines.line_start(loc.line as usize - 1) {118 let rest = &f.text[(start as usize).min(f.text.len())..];119 let line = rest.lines().next().unwrap_or("");120 let width = if loc.end_line == loc.line {121 (loc.end_column.saturating_sub(loc.column)).max(1)122 } else {123 (line.chars().count() as u32 + 1).saturating_sub(loc.column).max(1)124 };125 let gutter = loc.line.to_string();126 out.push_str(&format!("{gutter} | {}\n", line.replace('\t', " ")));127 out.push_str(&format!("{} | {}{}\n", " ".repeat(gutter.len()), " ".repeat(loc.column as usize - 1), "^".repeat(width as usize)));128 }129 }130 if let Some(s) = &d.suggestion {131 out.push_str(&format!(" help: {s}\n"));132 }133 for r in &d.related {134 let rl = self.locate(r.span);135 out.push_str(&format!(" note: {} ({}:{}:{})\n", r.message, rl.file, rl.line, rl.column));136 }137 out138 }139}140141/// Measured and counted facts about one compilation.142#[derive(Clone, Debug, Default, PartialEq, Serialize)]143pub struct CompileStats {144 /// Phase times in microseconds, measured on this run (all 0 on a cache hit).145 pub lex_us: f64,146 pub parse_us: f64,147 pub sema_us: f64,148 pub graph_us: f64,149 pub total_us: f64,150 /// The whole result came from the content-hash cache.151 pub cache_hit: bool,152 /// Source files of the compilation, and how many were reused without parsing.153 pub modules: u32,154 pub modules_reused: u32,155 /// Notes of the program.156 pub events: u64,157 /// Largest number of simultaneously sounding notes (before release tails).158 pub voices: u32,159 pub tracks: u32,160 /// Nodes of the mixing graph.161 pub nodes: u32,162 /// Evaluation steps consumed.163 pub steps: u64,164 /// Estimate, not a measurement: size of the Program in memory plus the mixing buffers of165 /// the graph at the largest block (4096 frames, stereo, float32). Engine and effect state166 /// are not known to the compiler and are not included.167 pub estimated_memory_bytes: u64,168}169170/// Result of a compilation. Cheap to clone (the heavy parts are shared).171#[derive(Clone, Debug)]172pub struct CompileOutput {173 /// `None` when there is an error, or when the root file has no composition.174 pub program: Option<Arc<Program>>,175 /// Mixing graph at the requested rate; `None` with the program, or on a graph error.176 pub graph: Option<Arc<DspGraph>>,177 /// Every diagnostic, ordered by file and position.178 pub diagnostics: Arc<Vec<Diagnostic>>,179 pub sources: SourceMap,180 pub stats: CompileStats,181 pub symbols: Arc<SymbolIndex>,182 /// False when the root file is a module without a composition.183 pub has_composition: bool,184 modules: Arc<ModuleSet>,185}186187impl CompileOutput {188 pub fn has_errors(&self) -> bool {189 self.diagnostics.iter().any(|d| d.is_error())190 }191 pub fn errors(&self) -> impl Iterator<Item = &Diagnostic> {192 self.diagnostics.iter().filter(|d| d.is_error())193 }194 /// The AST of the root file as JSON (debugging, golden tests).195 pub fn ast_json(&self) -> String {196 self.modules.files.first().map(|f| serde_json::to_string_pretty(&f.parsed.file).unwrap_or_else(|_| "null".into())).unwrap_or_else(|| "null".into())197 }198 /// The Musical IR as JSON; `"null"` without a program.199 pub fn program_json(&self) -> String {200 serde_json::to_string_pretty(&self.program.as_deref()).unwrap_or_else(|_| "null".into())201 }202 /// The DSP IR as JSON; `"null"` without a graph.203 pub fn graph_json(&self) -> String {204 serde_json::to_string_pretty(&self.graph.as_deref()).unwrap_or_else(|_| "null".into())205 }206 /// Diagnostics with resolved locations, as a JSON array.207 pub fn diagnostics_json(&self) -> String {208 #[derive(Serialize)]209 struct Row<'a> {210 #[serde(flatten)]211 diagnostic: &'a Diagnostic,212 location: Location,213 }214 let rows: Vec<Row> = self.diagnostics.iter().map(|d| Row { diagnostic: d, location: self.sources.locate(d.span) }).collect();215 serde_json::to_string_pretty(&rows).unwrap_or_else(|_| "[]".into())216 }217 /// Every diagnostic rendered for a terminal.218 pub fn render_diagnostics(&self) -> String {219 self.diagnostics.iter().map(|d| self.sources.render(d)).collect::<Vec<_>>().join("\n")220 }221}222223/// Builds the mixing graph of a program with the registry of this build.224pub fn build_graph(program: &Program, sample_rate: u32) -> Result<DspGraph, Vec<Diagnostic>> {225 build_graph_with(program, sample_rate, registry(), GraphOptions::default())226}227228/// Compiles a source text once, without any cache. See [`Compiler`] for repeated compilation.229pub fn compile(root_name: &str, source: &str, loader: &dyn SourceLoader, options: &CompileOptions) -> CompileOutput {230 Compiler::new().compile(root_name, source, loader, options)231}232233/// Compiles against an explicit registry (tests, tools). No cache.234pub fn compile_with_registry(root_name: &str, source: &str, loader: &dyn SourceLoader, options: &CompileOptions, registry: &Registry) -> CompileOutput {235 Compiler::new().run(root_name, source, loader, options, registry)236}237238/// Stack of the thread that parses and analyses. Reserved, not committed: only what a239/// compilation really uses is ever touched.240const COMPILER_STACK_BYTES: usize = 256 * 1024 * 1024;241242/// Runs `f` on a dedicated thread with a large stack, so a compilation never depends on the243/// stack of its caller (secondary threads on macOS have 512 KiB). The recursion of the parser244/// and of the evaluator is bounded (`MAX_NESTING`, `MAX_NEST`, `Quotas::max_recursion`); this245/// makes those bounds safe everywhere. Falls back to the current thread if none can be created.246pub(crate) fn on_big_stack<T: Send>(f: impl FnOnce() -> T + Send) -> T {247 // The job sits in a slot so it can still run here if the thread cannot be created.248 let slot = std::sync::Mutex::new(Some(f));249 let take = || slot.lock().ok().and_then(|mut s| s.take());250 let spawned = std::thread::scope(|scope| {251 let run = || take().map(|job| job());252 std::thread::Builder::new().name("sonata-compiler".into()).stack_size(COMPILER_STACK_BYTES).spawn_scoped(scope, run).ok().map(|handle| handle.join())253 });254 match spawned {255 Some(Ok(Some(value))) => value,256 Some(Err(panic)) => std::panic::resume_unwind(panic),257 Some(Ok(None)) | None => match take() {258 Some(job) => job(),259 None => unreachable!("the compilation job ran without producing a result"),260 },261 }262}263264fn hash_of(parts: &[&str]) -> u64 {265 let mut h = std::collections::hash_map::DefaultHasher::new();266 for p in parts {267 p.hash(&mut h);268 }269 h.finish()270}271272struct CachedOutput {273 key: u64,274 options: CompileOptions,275 output: CompileOutput,276}277278/// A compilation session: reuses parsed modules whose text did not change, and returns the279/// previous result when nothing changed at all.280///281/// Reuse never changes a result: a parsed module is keyed by its name, file id and full text,282/// and a whole result by the names and full texts of every module plus the options. Hash283/// matches are confirmed by comparing the texts.284pub struct Compiler {285 parsed: HashMap<u64, (String, FileId, Arc<str>, Arc<Parsed>)>,286 outputs: Vec<CachedOutput>,287 /// Number of whole results kept.288 pub capacity: usize,289}290291impl Default for Compiler {292 fn default() -> Self {293 Compiler::new()294 }295}296297impl Compiler {298 pub fn new() -> Compiler {299 Compiler { parsed: HashMap::new(), outputs: Vec::new(), capacity: 8 }300 }301302 /// Forgets every cached module and result.303 pub fn clear(&mut self) {304 self.parsed.clear();305 self.outputs.clear();306 }307308 pub fn compile(&mut self, root_name: &str, source: &str, loader: &dyn SourceLoader, options: &CompileOptions) -> CompileOutput {309 self.run(root_name, source, loader, options, registry())310 }311312 fn run(&mut self, root_name: &str, source: &str, loader: &dyn SourceLoader, options: &CompileOptions, registry: &Registry) -> CompileOutput {313 on_big_stack(|| self.run_here(root_name, source, loader, options, registry))314 }315316 fn run_here(&mut self, root_name: &str, source: &str, loader: &dyn SourceLoader, options: &CompileOptions, registry: &Registry) -> CompileOutput {317 let started = Instant::now();318 let (mut lex, mut parse) = (Duration::ZERO, Duration::ZERO);319 let mut reused = 0u32;320 let parsed_cache = &mut self.parsed;321 let mut used: Vec<u64> = Vec::new();322 let set = load_modules_with(root_name, source, loader, options.quotas.max_import_depth, &mut |name, id, text| {323 let key = hash_of(&[name, &id.to_string(), text]);324 used.push(key);325 if let Some((n, i, t, p)) = parsed_cache.get(&key) {326 if n == name && *i == id && t.as_ref() == text {327 reused += 1;328 return p.clone();329 }330 }331 let (p, l, pt) = parse_timed(text, id);332 lex += l;333 parse += pt;334 let p = Arc::new(p);335 parsed_cache.insert(key, (name.to_string(), id, Arc::from(text), p.clone()));336 p337 });338 // Keep only the modules of this compilation and of the cached results.339 if self.parsed.len() > 256 {340 self.parsed.retain(|k, _| used.contains(k));341 }342343 // Whole-result cache.344 let mut parts: Vec<&str> = Vec::with_capacity(set.files.len() * 2);345 for f in &set.files {346 parts.push(&f.name);347 parts.push(&f.text);348 }349 let key = hash_of(&parts);350 if let Some(pos) = self.outputs.iter().position(|c| {351 c.key == key352 && c.options == *options353 && c.output.sources.files.len() == set.files.len()354 && c.output.sources.files.iter().zip(&set.files).all(|(a, b)| a.name == b.name && a.text.as_ref() == b.text.as_ref())355 }) {356 let hit = self.outputs.remove(pos);357 let mut output = hit.output.clone();358 self.outputs.push(hit);359 let total = started.elapsed().as_secs_f64() * 1e6;360 output.stats = CompileStats {361 lex_us: 0.0,362 parse_us: 0.0,363 sema_us: 0.0,364 graph_us: 0.0,365 total_us: total,366 cache_hit: true,367 modules_reused: set.files.len() as u32,368 ..output.stats369 };370 return output;371 }372373 let t_sema = Instant::now();374 let analysis = analyze(&set, registry, &Options { quotas: options.quotas.clone(), composition: options.composition.clone() });375 let sema = t_sema.elapsed();376 let mut diagnostics = analysis.diagnostics;377 let t_graph = Instant::now();378 let mut graph = None;379 let program = analysis.program.map(Arc::new);380 if let Some(p) = &program {381 let rate = options.sample_rate.unwrap_or(p.master.sample_rate);382 match build_graph_with(p, rate, registry, options.graph) {383 Ok(g) => graph = Some(Arc::new(g)),384 Err(mut e) => diagnostics.append(&mut e),385 }386 }387 let graph_time = t_graph.elapsed();388 let program = if diagnostics.iter().any(|d| d.is_error()) { None } else { program };389 let sources = SourceMap {390 files: set.files.iter().map(|f| SourceEntry { name: f.name.clone(), text: f.text.clone(), lines: f.lines.clone(), is_std: f.is_std }).collect(),391 };392 let us = |d: Duration| d.as_secs_f64() * 1e6;393 let mut stats = CompileStats {394 lex_us: us(lex),395 parse_us: us(parse),396 sema_us: us(sema),397 graph_us: us(graph_time),398 cache_hit: false,399 modules: set.files.len() as u32,400 modules_reused: reused,401 steps: analysis.steps,402 ..CompileStats::default()403 };404 if let Some(p) = &program {405 stats.events = p.stats.notes;406 stats.voices = p.stats.max_polyphony;407 stats.tracks = p.stats.tracks;408 stats.estimated_memory_bytes = estimate_program_bytes(p);409 }410 if let Some(g) = &graph {411 stats.nodes = g.nodes.len() as u32;412 stats.estimated_memory_bytes += g.nodes.len() as u64 * 2 * 4096 * 4;413 }414 stats.total_us = us(started.elapsed());415 let output = CompileOutput {416 program,417 graph,418 diagnostics: Arc::new(diagnostics),419 sources,420 stats,421 symbols: Arc::new(analysis.symbols),422 has_composition: analysis.has_composition,423 modules: Arc::new(set),424 };425 self.outputs.push(CachedOutput { key, options: options.clone(), output: output.clone() });426 if self.outputs.len() > self.capacity.max(1) {427 self.outputs.remove(0);428 }429 output430 }431}432433/// Bytes held by a Program: its fixed part plus notes, automation points, clips and effects.434fn estimate_program_bytes(p: &Program) -> u64 {435 use std::mem::size_of;436 let mut n = size_of::<Program>() as u64;437 for t in &p.tracks {438 n += size_of::<sonata_ir::Track>() as u64;439 n += t.notes.len() as u64 * size_of::<sonata_ir::NoteEvent>() as u64;440 n += t.notes.iter().map(|x| x.bend.len() as u64 * size_of::<sonata_ir::BendPoint>() as u64).sum::<u64>();441 n += t.clips.len() as u64 * size_of::<sonata_ir::AudioClip>() as u64;442 n += t.effects.len() as u64 * size_of::<sonata_ir::EffectSpec>() as u64;443 n += t.automation.iter().map(|a| a.points.len() as u64 * size_of::<sonata_ir::AutomationPoint>() as u64).sum::<u64>();444 }445 n += p.buses.len() as u64 * size_of::<sonata_ir::Bus>() as u64;446 n += p.markers.len() as u64 * size_of::<sonata_ir::Marker>() as u64;447 n += p.tempo_map.points.len() as u64 * size_of::<sonata_ir::TempoPoint>() as u64;448 n449}450