Skip to main content

sva_core/
lib.rs

1// Concern: the parse->tempo->render pipeline shared by both front ends | Non-concern: argv (sva-cli), JS bindings (sva-wasm) | IO: (a Source, a target) -> Rendered, a Stream or CliError
2
3mod answer;
4mod builtins;
5mod cli_error;
6pub mod encode;
7pub mod json;
8mod lint_code;
9mod outline;
10mod output;
11mod query;
12mod target;
13mod tempo;
14mod until;
15
16pub use answer::{
17    Printed, Report, SAMPLE_LIMIT, answer_json, counters_json, label_json, query_data, stats_json,
18    stream_stats_json, value_json, work_json,
19};
20pub use builtins::{Builtins, Callable, Crossing, builtins, builtins_data};
21pub use cli_error::{CliError, LintViolation, lint_diagnostic};
22pub use lint_code::LintCode;
23pub use outline::outline_data;
24pub use output::{Diagnostic, Severity, diagnostics_json, error_envelope, success_envelope};
25pub use query::{
26    Asked, Call, DEFAULT_LEDGER_DEPTH, DEFAULT_MAX_PEAKS, DEFAULT_OVERSAMPLE, REPRESENTATIONS,
27    RETIRED, asked, call, calls, is_wav, retired, seconds, wav_path,
28};
29pub use target::{Edge, Target, target};
30pub use tempo::{Tempo, refuse_unresolved_bars, resolved as tempo};
31pub use until::until;
32
33use std::cell::RefCell;
34use std::path::Path;
35
36use sva_ast::{Dir, Graph, Refusal, Source};
37use sva_engine::{
38    Ask, Change, Changed, DEFAULT_SAMPLE_RATE, EngineError, Range, RenderConfig, StreamConfig,
39    render, render_in,
40};
41
42pub use sva_engine::{Abandon, Handle, Never, Out, Placed, Session, Stream, Until};
43
44pub use sva_engine::{Answer, Extent, Label, Output, Representation};
45pub use sva_engine::{
46    Backend, CacheStats, Counters, DEFAULT_CACHE_BYTES, DEFAULT_STORE_BYTES, FETCH_READS, Nothing,
47    Persisted, Store, Tier,
48};
49
50pub const ROOT: &str = "master";
51pub const PROBE: &str = "probe";
52
53pub struct Rendered {
54    pub config: RenderConfig,
55    pub expression: String,
56    pub target: String,
57    pub render: sva_engine::Render,
58    /// So a structural check needs no second parse, and an ad-hoc target is the same `probe`.
59    pub graph: Graph,
60}
61
62impl Rendered {
63    pub fn answer(&self, node: &str, representation: Representation) -> Result<Answer, CliError> {
64        let written = |e| CliError::Engine(as_written(e, &self.expression));
65        let id = self.render.node(node).map_err(written)?;
66        let mut answer = sva_engine::answer(&self.render, id, representation).map_err(written)?;
67        self.attribute(&mut answer)?;
68        Ok(answer)
69    }
70
71    /// An alias score reads beside how many instances the render holds.
72    fn attribute(&self, answer: &mut Answer) -> Result<(), CliError> {
73        let Output::Alias(alias) = &mut answer.value else {
74            return Ok(());
75        };
76        alias.instances = self.render.tys.paths().count();
77        Ok(())
78    }
79
80    pub fn label(&self) -> Option<&sva_engine::Label> {
81        self.render.labels.get(&self.render.root)
82    }
83}
84
85/// One render: `target` an expression over the composition `source` holds, its own ref
86/// read over an interval where it writes one.
87pub struct Job<'a> {
88    pub source: &'a dyn Source,
89    pub target: &'a str,
90    /// `None` ends the render where the interval or the target's support ends.
91    pub until: Option<&'a str>,
92    pub rate: Option<u32>,
93    pub bits: Option<i32>,
94    pub asked: &'a [Asked],
95    /// The operation count the caller acknowledges paying; the profile's own where `None`.
96    pub flop_budget: Option<u128>,
97    pub volatile: &'a [String],
98    pub out: Out,
99    pub abandon: &'a dyn Abandon,
100}
101
102impl<'a> Job<'a> {
103    pub fn over(source: &'a dyn Source, target: &'a str) -> Job<'a> {
104        Job {
105            source,
106            target,
107            until: None,
108            rate: None,
109            bits: None,
110            asked: &[],
111            flop_budget: None,
112            volatile: &[],
113            out: Out::Kept,
114            abandon: &Never,
115        }
116    }
117}
118
119fn settle(job: &Job) -> Result<(Graph, RenderConfig), CliError> {
120    let Target { expr, interval } = target(job.target)?;
121    let roots = roots_of(job.source, &expr)?;
122    let mut graph = settled(sva_ast::load_reaching(
123        job.source,
124        &roots.iter().map(String::as_str).collect::<Vec<_>>(),
125    ))?;
126    let parsed = sva_ast::parse_expr(&expr).map_err(|d| {
127        CliError::BadProbe(format!(
128            "`{}` does not parse as an expression: {}",
129            job.target, d.message
130        ))
131    })?;
132    define_probe(&mut graph, parsed)?;
133    let rate = job.rate.unwrap_or(DEFAULT_SAMPLE_RATE);
134    let per_bar = graph.seconds_per_bar();
135    let range = match interval {
136        None => Range::default(),
137        Some((start, end)) => Range {
138            start: start.sample(rate, per_bar)?,
139            end: end.sample(rate, per_bar)?,
140        },
141    };
142    if let Range {
143        start: Some(start),
144        end: Some(end),
145    } = range
146        && end <= start
147    {
148        return Err(CliError::Usage(format!(
149            "`{}` reads an interval from sample {start} to {end}, which holds none",
150            job.target
151        )));
152    }
153    let until = match job.until {
154        Some(text) => Some(until(text, rate, per_bar)?),
155        None => None,
156    };
157    let mut config = RenderConfig {
158        range,
159        until,
160        ..RenderConfig::at(rate)
161    };
162    config.flop_budget = job.flop_budget;
163    if let Some(bits) = job.bits {
164        config.profile.precision_bits = precision(bits)?;
165    }
166    config.volatile = job.volatile.to_vec();
167    config.out = job.out;
168    config.asks = job
169        .asked
170        .iter()
171        .map(|asked| Ask {
172            node: asked.node.clone().unwrap_or_else(|| PROBE.to_string()),
173            representation: asked.representation,
174        })
175        .collect();
176    Ok((graph, config))
177}
178
179/// `trace` names one instance of a parameterized file as `<path>(<name>=<value>, ..)`.
180fn instance_call(text: &str) -> Option<(&str, &str)> {
181    let (path, rest) = text.split_once('(')?;
182    let binds = rest.strip_suffix(')')?.trim();
183    (!binds.is_empty() && all_named(binds)).then_some((path, binds))
184}
185
186/// Only commas and equals outside a bind's own parens count: a bind's value may be a call.
187fn all_named(binds: &str) -> bool {
188    let mut depth = 0i32;
189    let mut named = false;
190    for c in binds.chars() {
191        match c {
192            '(' => depth += 1,
193            ')' if depth == 0 => return false,
194            ')' => depth -= 1,
195            '=' if depth == 0 => named = true,
196            ',' if depth == 0 && !std::mem::take(&mut named) => return false,
197            _ => {}
198        }
199    }
200    named && depth == 0
201}
202
203/// The ref an instance name stands for, so `lint` and `trace` answer for the same node.
204fn instance_read(graph: &Graph, text: &str) -> Option<sva_ast::Expr> {
205    let (path, binds) = instance_call(text)?;
206    if !graph.defines(path) {
207        return None;
208    }
209    sva_ast::parse_expr(&format!("@{path}(t, {binds})")).ok()
210}
211
212pub fn execute(job: Job, tier: &Tier) -> Result<Rendered, CliError> {
213    let (graph, config) = settle(&job)?;
214    let render = render(&graph, PROBE, config, tier);
215    rendered(&job, graph, render)
216}
217
218/// `job` over `tier`, typing anew only what `session` typed otherwise; only `persist` commits
219/// what it offers a disk beneath.
220pub async fn execute_over<B: Backend>(
221    job: Job<'_>,
222    tier: &Tier<B>,
223    session: &mut Session,
224) -> Result<Rendered, CliError> {
225    let (graph, config) = settle(&job)?;
226    let render = render_in(session, &graph, PROBE, config, tier, job.abandon).await;
227    rendered(&job, graph, render)
228}
229
230fn rendered(
231    job: &Job,
232    graph: Graph,
233    render: Result<sva_engine::Render, EngineError>,
234) -> Result<Rendered, CliError> {
235    let render = render.map_err(|e| CliError::Engine(as_written(e, job.target)))?;
236    Ok(Rendered {
237        config: render.config.clone(),
238        expression: job.target.to_string(),
239        target: PROBE.to_string(),
240        render,
241        graph,
242    })
243}
244
245pub fn plan(job: &Job) -> Result<sva_engine::Render, CliError> {
246    let (graph, config) = settle(job)?;
247    sva_engine::plan(&graph, PROBE, config).map_err(|e| CliError::Engine(as_written(e, job.target)))
248}
249
250/// Every refusal typing the target reaches, and no render's.
251pub fn types(job: &Job) -> Result<(), CliError> {
252    let (graph, config) = settle(job)?;
253    sva_engine::types_at(&graph, PROBE, config.rate)
254        .map(|_| ())
255        .map_err(|e| CliError::Engine(as_written(e, job.target)))
256}
257
258/// `channels`: what it plays, the target's own where `None`.
259pub async fn stream<B: Backend>(
260    job: &Job<'_>,
261    (block, channels): (usize, Option<usize>),
262    tier: &Tier<B>,
263) -> Result<Stream, CliError> {
264    let (graph, config) = settle(job)?;
265    let target = graph
266        .expr(PROBE)
267        .cloned()
268        .expect("the target was defined as the probe");
269    let config = StreamConfig {
270        block,
271        channels,
272        render: config,
273    };
274    Stream::open(&graph, &target, config, tier)
275        .await
276        .map_err(|e| CliError::Engine(as_written(e, job.target)))
277}
278
279/// `target`, an expression over `source` with no interval of its own, in place of what
280/// `stream` plays. Each edit here is `sva_engine::change`'s: the stream plays on meanwhile.
281pub async fn edit<B: Backend>(
282    stream: &RefCell<Stream>,
283    source: &dyn Source,
284    target: &str,
285    tier: &Tier<B>,
286) -> Result<(), CliError> {
287    let build = |s: &Stream| {
288        let (graph, expr) = streamed(s, source, target)?;
289        Ok(Change::Target(graph, expr))
290    };
291    changed(stream, build, Some(target), tier).await.map(|_| ())
292}
293
294/// `term` summed into the stream's `@notes`, its sample 0 placed `at`.
295pub async fn add<B: Backend>(
296    stream: &RefCell<Stream>,
297    source: &dyn Source,
298    (term, at): (&str, Placed),
299    tier: &Tier<B>,
300) -> Result<Handle, CliError> {
301    let build = |s: &Stream| {
302        let (graph, expr) = streamed(s, source, term)?;
303        Ok(Change::Add(graph, expr, at))
304    };
305    match changed(stream, build, Some(term), tier).await? {
306        Changed::Added(handle) => Ok(handle),
307        _ => unreachable!("an add answers its handle"),
308    }
309}
310
311/// False where the stream no longer holds `handle`.
312pub async fn replace<B: Backend>(
313    stream: &RefCell<Stream>,
314    source: &dyn Source,
315    (handle, term, at): (Handle, &str, Placed),
316    tier: &Tier<B>,
317) -> Result<bool, CliError> {
318    let build = |s: &Stream| {
319        let (graph, expr) = streamed(s, source, term)?;
320        Ok(Change::Replace(handle, graph, expr, at))
321    };
322    Ok(changed(stream, build, Some(term), tier).await? == Changed::Held(true))
323}
324
325/// False where the stream no longer holds `handle`.
326pub async fn remove<B: Backend>(
327    stream: &RefCell<Stream>,
328    handle: Handle,
329    tier: &Tier<B>,
330) -> Result<bool, CliError> {
331    let build = |_: &Stream| Ok(Change::Remove(handle));
332    Ok(changed(stream, build, None, tier).await? == Changed::Held(true))
333}
334
335async fn changed<B: Backend>(
336    stream: &RefCell<Stream>,
337    build: impl FnMut(&Stream) -> Result<Change, CliError>,
338    text: Option<&str>,
339    tier: &Tier<B>,
340) -> Result<Changed, CliError> {
341    let changed = sva_engine::change(stream, build, tier).await;
342    changed.map_err(|e| match (e, text) {
343        (CliError::Engine(e), Some(text)) => CliError::Engine(as_written(e, text)),
344        (e, _) => e,
345    })
346}
347
348pub async fn fetch<B: Backend>(stream: &RefCell<Stream>, tier: &Tier<B>) {
349    sva_engine::fetch(stream, tier).await;
350}
351
352/// `text` with no interval, and each node it reads that `stream` does not hold yet, read and
353/// parsed off `source`: a node the stream holds plays as it first read it.
354fn streamed(
355    stream: &Stream,
356    source: &dyn Source,
357    text: &str,
358) -> Result<(Graph, sva_ast::Expr), CliError> {
359    let Target { expr, interval } = target(text)?;
360    if interval.is_some() {
361        return Err(CliError::Usage(format!(
362            "`{text}` reads an interval, and a stream keeps its own"
363        )));
364    }
365    let held = stream.graph();
366    let roots = roots_of(source, &expr)?;
367    let roots: Vec<&str> = roots.iter().map(String::as_str).collect();
368    let mut delta = sva_ast::load_beside(source, &roots, held).map_err(CliError::Refusals)?;
369    if let Some(per_bar) = held.per_bar() {
370        delta.resolve_bar_spans(per_bar);
371    }
372    delta
373        .desugar_arrangement_beside(held)
374        .map_err(CliError::Refusals)?;
375    let parsed = sva_ast::parse_expr(&expr).map_err(|d| {
376        CliError::BadProbe(format!(
377            "`{text}` does not parse as an expression: {}",
378            d.message
379        ))
380    })?;
381    let defined = delta
382        .define_arranged_beside(held, PROBE, parsed)
383        .map_err(|r| CliError::Refusals(vec![r]))?;
384    if !defined {
385        return Err(CliError::BadProbe(format!(
386            "this composition already has a node named `{PROBE}`"
387        )));
388    }
389    tempo::refuse_unresolved_bars(&delta)?;
390    let expr = delta
391        .expr(PROBE)
392        .cloned()
393        .expect("the target was defined as the probe");
394    Ok((delta, expr))
395}
396
397/// A double holds no bit past its own mantissa, and one bit writes only zero.
398fn precision(bits: i32) -> Result<i32, CliError> {
399    match (2..=52).contains(&bits) {
400        true => Ok(bits),
401        false => Err(CliError::Usage(format!(
402            "`--bits` takes a precision from 2 to 52 bits, not {bits}"
403        ))),
404    }
405}
406
407/// The engine knows a target only as the node it was defined as, so a refusal that names
408/// that node names the target as the caller wrote it instead.
409fn as_written(refused: EngineError, target: &str) -> EngineError {
410    match refused {
411        EngineError::Refused(mut d) => {
412            if d.location.node == PROBE {
413                d.location.node = target.to_string();
414            }
415            d.message = d
416                .message
417                .replace(&format!("`{PROBE}`"), &format!("`{target}`"));
418            EngineError::Refused(d)
419        }
420        EngineError::Binding { node, span, fault } if node == PROBE => EngineError::Binding {
421            node: target.to_string(),
422            span,
423            fault,
424        },
425        other => other,
426    }
427}
428
429pub fn probe(dir: &Path, expression: &str) -> Result<Rendered, CliError> {
430    execute(Job::over(&Dir::at(dir), expression), &Tier::default())
431}
432
433pub fn cwd() -> Result<std::path::PathBuf, CliError> {
434    std::env::current_dir()
435        .map_err(|e| CliError::Io(format!("could not read the current directory: {e}")))
436}
437
438pub fn prepared(source: &dyn Source) -> Result<Graph, CliError> {
439    settled(sva_ast::load(source))
440}
441
442/// Argv math: `trace` and `lint` each refuse a target no node answers for here, under one
443/// code and one message.
444pub fn define_probe_for(graph: &mut Graph, text: &str) -> Result<(), CliError> {
445    let expr = match instance_read(graph, text) {
446        Some(read) => read,
447        None if names_a_missing_node(text) => {
448            return Err(CliError::NotFound(format!(
449                "`{text}` is not a node this composition defines"
450            )));
451        }
452        None => sva_ast::parse_expr(text).map_err(|d| {
453            CliError::BadProbe(format!(
454                "`{text}` is not a node in this composition, and does not parse as an \
455                 expression: {}",
456                d.message
457            ))
458        })?,
459    };
460    define_probe(graph, expr)
461}
462
463/// Only a path, or instance syntax, is a node; the rest is math the parser and engine answer
464/// for. `t` and `A4` are spelled like paths and read as values.
465fn names_a_missing_node(text: &str) -> bool {
466    match instance_call(text) {
467        Some((path, _)) => sva_ast::names_a_node(path),
468        None => !text.contains('(') && sva_ast::names_a_node(text) && !reads_as_a_value(text),
469    }
470}
471
472fn reads_as_a_value(text: &str) -> bool {
473    match sva_ast::parse_expr(text) {
474        Ok(sva_ast::Expr::Lit(_)) => true,
475        Ok(sva_ast::Expr::Var(name)) => sva_ast::is_reserved(&name),
476        _ => false,
477    }
478}
479
480/// Argv math settled the way a file is; `concat` is no file-only dialect.
481fn define_probe(graph: &mut Graph, expr: sva_ast::Expr) -> Result<(), CliError> {
482    let defined = graph
483        .define_arranged(PROBE, expr)
484        .map_err(|r| CliError::Refusals(vec![r]))?;
485    if !defined {
486        return Err(CliError::BadProbe(format!(
487            "this composition already has a node named `{PROBE}`"
488        )));
489    }
490    tempo::refuse_unresolved_bars(graph)
491}
492
493pub fn settled(loaded: Result<Graph, Vec<Refusal>>) -> Result<Graph, CliError> {
494    let mut graph = loaded.map_err(CliError::Refusals)?;
495    tempo::resolve(&mut graph)?;
496    graph.desugar_arrangement().map_err(CliError::Refusals)?;
497    Ok(graph)
498}
499
500/// Read by name rather than through a ref.
501pub const RESERVED_VARIABLES: [&str; 3] = ["bpm", "meter", "key"];
502
503/// A node path the source answers for is a node; anything else is math, and its reads are
504/// roots. Only a node path is asked of the source: math is never looked up as a file.
505pub fn roots_of(source: &dyn Source, target: &str) -> Result<Vec<String>, CliError> {
506    let mut roots: Vec<String> = RESERVED_VARIABLES
507        .iter()
508        .flat_map(|n| [(*n).to_string(), format!("{}/{n}", sva_ast::VARIABLES)])
509        .collect();
510    let held = |path: &str| -> Result<bool, CliError> {
511        Ok(sva_ast::whole_ref_path(path) && source.get(path).map_err(CliError::Io)?.is_some())
512    };
513    match target {
514        target if held(target)? => {
515            roots.push(target.to_string());
516        }
517        text => match instance_call(text).map(|(path, _)| path) {
518            Some(path) if held(path)? => {
519                roots.push(path.to_string());
520            }
521            _ => {
522                if let Ok(expr) = sva_ast::parse_expr(text) {
523                    roots.extend(sva_ast::reads_of(PROBE, &expr));
524                }
525            }
526        },
527    }
528    Ok(roots)
529}