Skip to main content

sva_core/
query.rs

1// Concern: the observations both front ends ask for, each written as a call with its own arguments | Non-concern: argv (sva-cli's args/), taking the reading (sva-engine) | IO: (text) -> Asked
2
3use std::path::{Path, PathBuf};
4
5use sva_ast::SpanUnit;
6use sva_ast::score::{Field, Kind, Reading as Folding, Refused, evaluate};
7use sva_engine::harmony::voice_leading::Norm;
8use sva_engine::{
9    Arg, DEFAULT_BUFFER_SECS, DEFAULT_FRAME_SECS, Given, Harmonic, MAX_PINNED_FRAME, READINGS,
10    Reading, Representation, pinned_frame,
11};
12
13use crate::cli_error::CliError;
14
15pub const RETIRED: [(&str, &str); 2] = [
16    ("exact-envelope", "envelope, symbolic on a closed form"),
17    ("exact-derivative", "derivative, symbolic on a closed form"),
18];
19
20/// One reading written as a call, `spectrum(peaks=8, frame=50ms)=out.json`: its name, its
21/// arguments as written, and where it goes.
22#[derive(Clone, Debug, PartialEq)]
23pub struct Call {
24    pub name: String,
25    pub args: Vec<(String, String)>,
26    /// No destination is stdout.
27    pub dest: Option<PathBuf>,
28}
29
30/// Where a reading goes instead of stdout: a path, its extension picking the format, or a
31/// live device named after `alsa:`.
32#[derive(Clone, Debug, PartialEq)]
33pub enum Destination {
34    File(PathBuf),
35    Alsa {
36        /// Any ALSA PCM name: `default`, `hw:1`, `plughw:1,0`.
37        device: String,
38        /// `samples(buffer=50ms)`: how much the device holds ahead of what it plays.
39        buffer_secs: f64,
40    },
41}
42
43/// The most samples a time argument may count: past 2^53 neither an f64 nor its product
44/// with another count is exact.
45const MOST_SAMPLES: f64 = 9_007_199_254_740_992.0;
46
47/// A call resolved to the reading it names and the arguments only a front end reads. Its
48/// times stay as written until a render says what a bar lasts.
49#[derive(Clone, Debug, PartialEq)]
50pub struct Asked {
51    pub name: String,
52    given: Given,
53    times: Vec<(Arg, Time)>,
54    pub dest: Option<Destination>,
55    /// `bindings(node=@voice)`: the instance whose bindings are read.
56    pub node: Option<String>,
57    /// `ledger(brief=1)`: only the rows that clipped.
58    pub brief: bool,
59    /// `ledger(skim=1)`: each row's level alone.
60    pub skim: bool,
61}
62
63pub fn is_wav(path: &Path) -> bool {
64    path.extension()
65        .is_some_and(|e| e.eq_ignore_ascii_case("wav"))
66}
67
68pub fn retired(name: &str) -> Option<&'static str> {
69    RETIRED
70        .iter()
71        .find(|(gone, _)| *gone == name)
72        .map(|(_, write)| *write)
73}
74
75/// A comma list of calls; a comma inside a call's parentheses separates its arguments, and
76/// one in an `alsa:` device name, `hw:1,0`, stays there if no reading follows it.
77pub fn calls(text: &str) -> Result<Vec<Call>, CliError> {
78    let mut joined: Vec<String> = Vec::new();
79    for one in split_outside(text, ',')? {
80        match joined.last_mut() {
81            Some(last) if names_a_device(last) && !names_a_reading(one) => {
82                last.push(',');
83                last.push_str(one);
84            }
85            _ => joined.push(one.to_string()),
86        }
87    }
88    joined.iter().map(|one| call(one.trim())).collect()
89}
90
91fn names_a_device(call: &str) -> bool {
92    let close = call.rfind(')').map_or(0, |at| at + 1);
93    call[close..]
94        .split_once('=')
95        .is_some_and(|(_, dest)| dest.trim_start().starts_with("alsa:"))
96}
97
98fn names_a_reading(text: &str) -> bool {
99    let head = text[..text.find(['(', '=']).unwrap_or(text.len())].trim();
100    READINGS.iter().any(|row| row.name == head) || retired(head).is_some()
101}
102
103/// `name`, `name(k=v, ...)`, either followed by `=path`.
104pub fn call(text: &str) -> Result<Call, CliError> {
105    let head_end = text.find(['(', '=']).unwrap_or(text.len());
106    let name = text[..head_end].trim().to_string();
107    if name.is_empty() {
108        return Err(unwritten(text, "it names no reading"));
109    }
110    let mut rest = &text[head_end..];
111    let mut args = Vec::new();
112    if rest.starts_with('(') {
113        let close = closing(rest).ok_or_else(|| unwritten(text, "its `(` is never closed"))?;
114        let inner = rest[1..close].trim();
115        if !inner.is_empty() {
116            for arg in split_outside(inner, ',')? {
117                let Some((key, value)) = arg.split_once('=') else {
118                    return Err(unwritten(
119                        text,
120                        &format!("`{}` is no named argument; write `key=value`", arg.trim()),
121                    ));
122                };
123                args.push((key.trim().to_string(), value.trim().to_string()));
124            }
125        }
126        rest = &rest[close + 1..];
127    }
128    let dest = match rest.trim_start().strip_prefix('=') {
129        Some("") => {
130            return Err(unwritten(
131                text,
132                "`=` names no destination; drop it to read the reading under \
133                 `data.representations`",
134            ));
135        }
136        Some(path) => Some(PathBuf::from(path)),
137        None if rest.trim().is_empty() => None,
138        None => {
139            return Err(unwritten(
140                text,
141                &format!("`{}` follows the call", rest.trim()),
142            ));
143        }
144    };
145    Ok(Call { name, args, dest })
146}
147
148/// Every call resolved. An answer keys each reading by its name, so a name asked twice
149/// would print one key twice and a JSON reader would keep only the last; it refuses.
150pub fn asked_all(calls: &[Call]) -> Result<Vec<Asked>, CliError> {
151    let mut out: Vec<Asked> = Vec::with_capacity(calls.len());
152    for call in calls {
153        let one = asked(call)?;
154        if out.iter().any(|held| held.name == one.name) {
155            return Err(CliError::usage(
156                "query.duplicate",
157                format!(
158                    "`{}` is asked more than once; ask each reading once, every argument in \
159                 its one call",
160                    one.name
161                ),
162            ));
163        }
164        out.push(one);
165    }
166    Ok(out)
167}
168
169/// A time argument as written: seconds, or bars a tempo counts.
170#[derive(Clone, Debug, PartialEq)]
171struct Time {
172    amount: f64,
173    unit: SpanUnit,
174    written: String,
175}
176
177impl Asked {
178    fn reading(&self) -> &'static Reading {
179        READINGS
180            .iter()
181            .find(|row| row.name == self.name)
182            .expect("an asked reading names a row")
183    }
184
185    /// Whether the reading answers off samples alone, as `Representation::off_samples`.
186    pub fn off_samples(&self, sampled: bool) -> bool {
187        self.reading().reads.off_samples(sampled)
188    }
189
190    /// The reading at `rate`, every time argument in seconds: a bar is `seconds_per_bar`,
191    /// and one written where no tempo is known refuses.
192    pub fn representation(
193        &self,
194        rate: u32,
195        seconds_per_bar: Option<f64>,
196    ) -> Result<Representation, CliError> {
197        let given = self.resolved(rate, seconds_per_bar)?;
198        let representation = self.reading().representation(&given);
199        pinned(representation, rate)?;
200        Ok(representation)
201    }
202
203    /// Every argument the reading takes, in its table's order, as `--representation` spells
204    /// it, each as the reading used it: a default written out, an unwritten `spectrum`
205    /// frame the one fitted to the range. `None` where none applies: a frame read exactly,
206    /// `modulation`'s unwritten `bpm`, `samples`' `buffer` with no device.
207    pub fn args(
208        &self,
209        rate: u32,
210        seconds_per_bar: Option<f64>,
211        taken: Taken,
212    ) -> Result<Vec<(&'static str, Option<Spelled>)>, CliError> {
213        use Representation as R;
214        let count = |n: usize| Some(Spelled::Number(n.to_string()));
215        let secs = |s: f64| Some(Spelled::Text(spelled_secs(s)));
216        let db = |d: f64| Some(Spelled::Text(format!("{d}db")));
217        let switch = |on: bool| Some(Spelled::Number(u8::from(on).to_string()));
218        let text = |t: &str| Some(Spelled::Text(t.to_string()));
219        let frame = |written: Option<f64>, unwritten: Option<f64>| match taken {
220            Taken::Exact => written.and_then(secs),
221            Taken::Measured { .. } => written.or(unwritten).and_then(secs),
222        };
223        let mut held = match self.representation(rate, seconds_per_bar)? {
224            R::Spectrum {
225                max_peaks,
226                frame_secs,
227            } => {
228                let fitted = match taken {
229                    Taken::Measured { fitted_frame } => fitted_frame,
230                    Taken::Exact => None,
231                };
232                let fitted = fitted.map(|samples| samples as f64 / f64::from(rate));
233                vec![
234                    (Arg::Peaks, count(max_peaks)),
235                    (Arg::Frame, frame(frame_secs, fitted)),
236                ]
237            }
238            R::Envelope { frame_secs } => {
239                vec![(Arg::Frame, frame(frame_secs, Some(DEFAULT_FRAME_SECS)))]
240            }
241            R::Ledger { depth } => vec![(Arg::Depth, count(depth))],
242            R::Pitch {
243                max_notes: peaks,
244                frame_secs,
245            }
246            | R::Formants {
247                max_formants: peaks,
248                frame_secs,
249            } => vec![(Arg::Peaks, count(peaks)), (Arg::Frame, secs(frame_secs))],
250            R::Stereo { frame_secs } => vec![(Arg::Frame, secs(frame_secs))],
251            R::Bands => vec![],
252            R::Alias { oversample } => vec![(Arg::Oversample, count(oversample as usize))],
253            R::Harmony {
254                reading,
255                frame_secs,
256                floor_db,
257            } => {
258                let own = match reading {
259                    Harmonic::Dissonance { max_pairs } => Some((Arg::Pairs, count(max_pairs))),
260                    Harmonic::VoiceLeading { norm } => Some((Arg::Norm, text(norm.key()))),
261                    Harmonic::TonalDistance | Harmonic::Inharmonicity => None,
262                };
263                let shared = [(Arg::Frame, secs(frame_secs)), (Arg::Floor, db(floor_db))];
264                shared.into_iter().chain(own).collect()
265            }
266            R::Periodicity {
267                frame_secs,
268                window_secs,
269                curve,
270            } => vec![
271                (Arg::Frame, secs(frame_secs)),
272                (Arg::Window, secs(window_secs)),
273                (Arg::Curve, switch(curve)),
274            ],
275            R::Modulation {
276                frame_secs,
277                window_secs,
278                bpm,
279            } => vec![
280                (Arg::Frame, secs(frame_secs)),
281                (Arg::Window, secs(window_secs)),
282                (Arg::Bpm, bpm.map(|b| Spelled::Number(b.to_string()))),
283            ],
284            R::SelfSimilarity {
285                frame_secs,
286                cell_secs,
287                smooth_secs,
288                window_secs,
289                floor_db,
290                listed,
291                curve,
292            } => vec![
293                (Arg::Frame, secs(frame_secs)),
294                (Arg::Cell, secs(cell_secs)),
295                (Arg::Smooth, secs(smooth_secs)),
296                (Arg::Window, secs(window_secs)),
297                (Arg::Floor, db(floor_db)),
298                (Arg::Peaks, count(listed)),
299                (Arg::Curve, switch(curve)),
300            ],
301            R::Lines
302            | R::Atoms
303            | R::Derivative
304            | R::Samples
305            | R::Crest
306            | R::Loudness
307            | R::Onsets
308            | R::Bindings
309            | R::Arguments => Vec::new(),
310        };
311        let buffer = match &self.dest {
312            Some(Destination::Alsa { buffer_secs, .. }) => secs(*buffer_secs),
313            _ => None,
314        };
315        held.extend([
316            (Arg::Brief, switch(self.brief)),
317            (Arg::Skim, switch(self.skim)),
318            (
319                Arg::Node,
320                self.node.as_ref().and_then(|n| text(&format!("@{n}"))),
321            ),
322            (Arg::Buffer, buffer),
323        ]);
324        Ok(self
325            .reading()
326            .takes
327            .iter()
328            .map(|arg| {
329                let (_, value) = held
330                    .iter()
331                    .find(|(one, _)| one == arg)
332                    .expect("a reading holds every argument it takes");
333                (arg.key(), value.clone())
334            })
335            .collect())
336    }
337
338    /// The arguments at `rate`, every time in seconds.
339    fn resolved(&self, rate: u32, seconds_per_bar: Option<f64>) -> Result<Given, CliError> {
340        let mut given = self.given;
341        for (arg, time) in &self.times {
342            let secs = match (time.unit, seconds_per_bar) {
343                (SpanUnit::Seconds, _) => time.amount,
344                (SpanUnit::Bars, Some(per)) => time.amount * per,
345                (SpanUnit::Bars, None) => {
346                    return Err(CliError::BadTempo(format!(
347                        "`{}({}={})` is written in bars, and this reading has no tempo to \
348                         count them in: a render reads it off `variables/bpm` and \
349                         `variables/meter`, and a file holds none; write seconds",
350                        self.name,
351                        arg.key(),
352                        time.written
353                    )));
354                }
355            };
356            if *arg == Arg::Frame && (secs * f64::from(rate)).round() < 1.0 {
357                return Err(CliError::usage(
358                    "query.bad_value",
359                    format!(
360                        "`{}(frame={})` is {secs}s, under half a sample at {rate} Hz, and a \
361                         frame steps by whole samples, rounded; ask at least {}s, half a sample",
362                        self.name,
363                        time.written,
364                        0.5 / f64::from(rate)
365                    ),
366                ));
367            }
368            let most = MOST_SAMPLES / f64::from(rate);
369            if secs > most {
370                return Err(CliError::usage(
371                    "query.bad_value",
372                    format!(
373                        "`{}({}={})` is {secs}s, past the 2^53 samples a count holds exactly at \
374                         {rate} Hz; ask at most {most}s",
375                        self.name,
376                        arg.key(),
377                        time.written
378                    ),
379                ));
380            }
381            match arg {
382                Arg::Frame => given.frame = Some(secs),
383                Arg::Window => given.window = Some(secs),
384                Arg::Cell => given.cell_secs = secs,
385                Arg::Smooth => given.smooth_secs = secs,
386                _ => unreachable!("only a time argument is held as a time"),
387            }
388        }
389        Ok(given)
390    }
391
392    pub fn path(&self) -> Option<&Path> {
393        match &self.dest {
394            Some(Destination::File(path)) => Some(path),
395            Some(Destination::Alsa { .. }) | None => None,
396        }
397    }
398}
399
400/// The reading a call names, each argument read as that reading takes it.
401pub fn asked(call: &Call) -> Result<Asked, CliError> {
402    let name = call.name.as_str();
403    if let Some(write) = retired(name) {
404        return Err(CliError::usage(
405            "query.retired",
406            format!("`{name}` left the language; write `{write}`"),
407        ));
408    }
409    let Some(row) = READINGS.iter().find(|row| row.name == name) else {
410        let names: Vec<&str> = READINGS.iter().map(|row| row.name).collect();
411        return Err(CliError::usage(
412            "query.unknown_representation",
413            format!(
414                "unknown representation `{name}`; the representations are {}",
415                names.join(", ")
416            ),
417        ));
418    };
419    let (mut given, mut node, mut brief, mut skim) = (Given::default(), None, false, false);
420    let (mut buffer, mut times) = (None, Vec::new());
421    for (key, raw) in &call.args {
422        let Some(arg) = row.takes.iter().find(|arg| arg.key() == key) else {
423            let keys: Vec<&str> = row.takes.iter().map(|arg| arg.key()).collect();
424            return Err(CliError::usage(
425                "query.unknown_argument",
426                match keys[..] {
427                    [] => format!("`{name}` takes no arguments, not `{key}`"),
428                    _ => format!("`{name}` takes {}, not `{key}`", keys.join(", ")),
429                },
430            ));
431        };
432        match arg {
433            Arg::Peaks => given.peaks = count(raw, key)?,
434            Arg::Depth => given.depth = count(raw, key)?,
435            Arg::Frame | Arg::Window | Arg::Cell | Arg::Smooth => {
436                times.push((*arg, time(raw, key)?));
437            }
438            Arg::Oversample => given.oversample = factor(raw)?,
439            Arg::Brief => brief = switch(raw, key)?,
440            Arg::Skim => skim = switch(raw, key)?,
441            Arg::Node => node = Some(self::node(raw)?),
442            Arg::Buffer => buffer = Some(microseconds(raw, key)?),
443            Arg::Floor => given.floor_db = decibels(raw, key)?,
444            Arg::Norm => given.norm = norm(raw)?,
445            Arg::Pairs => given.max_pairs = count(raw, key)?,
446            Arg::Curve => given.curve = switch(raw, key)?,
447            Arg::Bpm => given.bpm = Some(tempo(raw, key)?),
448        }
449    }
450    if row.takes.contains(&Arg::Node) && node.is_none() {
451        return Err(CliError::usage(
452            "query.missing_argument",
453            format!("`{name}` reads one instance's {name}; name it, as `{name}(node=@voice)`"),
454        ));
455    }
456    Ok(Asked {
457        name: call.name.clone(),
458        given,
459        times,
460        dest: destination(name, call.dest.as_deref(), buffer)?,
461        node,
462        brief,
463        skim,
464    })
465}
466
467/// `alsa:` opens a device name, and only a device has a buffer to size.
468fn destination(
469    name: &str,
470    dest: Option<&Path>,
471    buffer: Option<f64>,
472) -> Result<Option<Destination>, CliError> {
473    let device = dest.and_then(|d| d.to_str()?.strip_prefix("alsa:"));
474    match (dest, device, buffer) {
475        (_, Some(""), _) => Err(CliError::usage(
476            "destination.no_device",
477            format!(
478                "`{name}=alsa:` names no device; write an ALSA device after it, as \
479                 `alsa:default` or `alsa:hw:1`"
480            ),
481        )),
482        (_, Some(device), _) => Ok(Some(Destination::Alsa {
483            device: device.to_string(),
484            buffer_secs: buffer.unwrap_or(DEFAULT_BUFFER_SECS),
485        })),
486        (_, None, Some(_)) => Err(CliError::usage(
487            "query.buffer_without_device",
488            format!(
489                "`buffer` sizes a live device's buffer, and `{name}` names none; write \
490                 `{name}(buffer=...)=alsa:<device>`, or drop `buffer`"
491            ),
492        )),
493        (dest, None, None) => Ok(dest.map(|d| Destination::File(d.to_path_buf()))),
494    }
495}
496
497/// `raw` split at each `sep` no parenthesis encloses.
498fn split_outside(raw: &str, sep: char) -> Result<Vec<&str>, CliError> {
499    let (mut depth, mut from, mut out) = (0i32, 0, Vec::new());
500    for (at, c) in raw.char_indices() {
501        match c {
502            '(' => depth += 1,
503            ')' => depth -= 1,
504            c if c == sep && depth == 0 => {
505                out.push(&raw[from..at]);
506                from = at + c.len_utf8();
507            }
508            _ => {}
509        }
510        if depth < 0 {
511            return Err(unwritten(raw, "a `)` closes nothing"));
512        }
513    }
514    out.push(&raw[from..]);
515    Ok(out)
516}
517
518/// The byte of the `)` that closes the `(` `text` opens with.
519fn closing(text: &str) -> Option<usize> {
520    let mut depth = 0i32;
521    for (at, c) in text.char_indices() {
522        match c {
523            '(' => depth += 1,
524            ')' => {
525                depth -= 1;
526                if depth == 0 {
527                    return Some(at);
528                }
529            }
530            _ => {}
531        }
532    }
533    None
534}
535
536fn unwritten(text: &str, why: &str) -> CliError {
537    CliError::usage(
538        "query.malformed",
539        format!(
540            "`{text}` is no reading: {why}. write a call, as `spectrum(peaks=8, frame=50ms)`, \
541             `=path` after it to write it to a file"
542        ),
543    )
544}
545
546fn count(raw: &str, key: &str) -> Result<usize, CliError> {
547    raw.parse::<usize>().map_err(|_| {
548        CliError::usage(
549            "query.bad_value",
550            format!("`{key}` needs a whole count, got `{raw}`"),
551        )
552    })
553}
554
555fn factor(raw: &str) -> Result<u32, CliError> {
556    match raw.parse::<u32>() {
557        Ok(k) if (2..=16).contains(&k) && k.is_power_of_two() => Ok(k),
558        _ => Err(CliError::usage(
559            "query.bad_value",
560            format!("`oversample` needs a power of two from 2 to 16, got `{raw}`"),
561        )),
562    }
563}
564
565/// A positive time as a score folds one, `50ms`, `1b/8` or `2b + 1b/3`; a bare number is
566/// seconds. Bars stay bars until a tempo is known.
567fn time(raw: &str, key: &str) -> Result<Time, CliError> {
568    let bad = |why: String| {
569        CliError::usage(
570            "query.bad_value",
571            format!(
572                "`{key}` needs a positive time, in seconds as `50ms` or `0.05`, or in bars as \
573                 `1b/8`: {why}"
574            ),
575        )
576    };
577    let folding = Folding::<f64> {
578        field: Field::Time,
579        mark: &|_| None,
580        degree: &|_| Err("a reading's time counts no degrees".to_string()),
581        own: None,
582    };
583    let value = evaluate(raw, &folding).map_err(|refused| match refused {
584        Refused::At(_, why) => bad(why),
585        Refused::Mark(name, _) => bad(format!(
586            "`mark({name})` is a score's, and a reading has none"
587        )),
588    })?;
589    let unit = match value.kind {
590        Kind::Bars => SpanUnit::Bars,
591        Kind::Seconds | Kind::Number => SpanUnit::Seconds,
592        other => return Err(bad(format!("`{raw}` is a {}", other.name()))),
593    };
594    match value.amount > 0.0 && value.amount.is_finite() {
595        true => Ok(Time {
596            amount: value.amount,
597            unit,
598            written: raw.to_string(),
599        }),
600        false => Err(bad(format!("`{raw}` is not over zero"))),
601    }
602}
603
604/// How a reading was taken, which decides what an argument it left unwritten took.
605#[derive(Clone, Copy, Debug, PartialEq)]
606pub enum Taken {
607    /// Off the written math: no frame applies.
608    Exact,
609    /// Off samples; `fitted_frame` the samples an unpinned `spectrum` frame held.
610    Measured { fitted_frame: Option<usize> },
611}
612
613/// One argument's value as `--representation` takes it: a plain number, or text, `50ms`.
614#[derive(Clone, Debug, PartialEq)]
615pub enum Spelled {
616    Number(String),
617    Text(String),
618}
619
620impl Spelled {
621    pub fn text(&self) -> &str {
622        match self {
623            Spelled::Number(t) | Spelled::Text(t) => t,
624        }
625    }
626}
627
628/// Seconds as a time argument reads them: under a second in `ms` if exact,
629/// `50ms`, else in `s`, `4s`.
630fn spelled_secs(secs: f64) -> String {
631    let ms = secs * 1000.0;
632    match secs < 1.0 && ms / 1000.0 == secs {
633        true => format!("{ms}ms"),
634        false => format!("{secs}s"),
635    }
636}
637
638/// A transform sized to fit is not the grid two windows asked to share.
639fn pinned(representation: Representation, rate: u32) -> Result<(), CliError> {
640    let Representation::Spectrum {
641        frame_secs: Some(secs),
642        ..
643    } = representation
644    else {
645        return Ok(());
646    };
647    let sr = f64::from(rate);
648    let frame = pinned_frame(secs, sr);
649    match frame > MAX_PINNED_FRAME {
650        true => Err(CliError::usage(
651            "query.bad_value",
652            format!(
653                "`spectrum(frame={secs})` sizes its transform to {frame} samples at {sr} Hz, \
654                 past the {MAX_PINNED_FRAME}-sample bound"
655            ),
656        )),
657        false => Ok(()),
658    }
659}
660
661/// A positive time the language spells, `50ms` or `1.5s`; a bare number is seconds.
662pub fn seconds(raw: &str, key: &str) -> Result<f64, CliError> {
663    let held = match sva_ast::tokenize(raw).as_deref() {
664        Ok([one]) => match one.kind {
665            sva_ast::TokenKind::Num(v)
666            | sva_ast::TokenKind::Time(v, sva_ast::SpanUnit::Seconds) => Some(v),
667            _ => None,
668        },
669        _ => None,
670    };
671    match held {
672        Some(v) if v > 0.0 && v.is_finite() => Ok(v),
673        _ => Err(CliError::usage(
674            "query.bad_value",
675            format!("`{key}` needs a positive time, as `50ms` or `0.05`, got `{raw}`"),
676        )),
677    }
678}
679
680/// A bare positive number of beats per minute.
681fn tempo(raw: &str, key: &str) -> Result<f64, CliError> {
682    let held = match sva_ast::tokenize(raw).as_deref() {
683        Ok([one]) => match one.kind {
684            sva_ast::TokenKind::Num(v) => Some(v),
685            _ => None,
686        },
687        _ => None,
688    };
689    match held {
690        Some(v) if v > 0.0 && v.is_finite() => Ok(v),
691        _ => Err(CliError::usage(
692            "query.bad_value",
693            format!("`{key}` needs a positive tempo in beats per minute, as `140`, got `{raw}`"),
694        )),
695    }
696}
697
698/// A device takes its buffer in whole microseconds, as a C `int`.
699fn microseconds(raw: &str, key: &str) -> Result<f64, CliError> {
700    let secs = seconds(raw, key)?;
701    match (1.0..=f64::from(i32::MAX)).contains(&(secs * 1e6).round()) {
702        true => Ok(secs),
703        false => Err(CliError::usage(
704            "query.bad_value",
705            format!(
706                "`{key}` is a whole number of microseconds from 1us to {}s, got `{raw}`",
707                i32::MAX / 1_000_000
708            ),
709        )),
710    }
711}
712
713/// A level the language spells in decibels, `-40db`; a bare number names no unit.
714fn decibels(raw: &str, key: &str) -> Result<f64, CliError> {
715    use sva_ast::{LogUnit::Decibels, TokenKind};
716    let kinds: Option<Vec<TokenKind>> = sva_ast::tokenize(raw)
717        .ok()
718        .map(|tokens| tokens.into_iter().map(|t| t.kind).collect());
719    let held = match kinds.as_deref() {
720        Some([TokenKind::Log(v, Decibels)]) => Some(*v),
721        Some([TokenKind::Minus, TokenKind::Log(v, Decibels)]) => Some(-v),
722        _ => None,
723    };
724    match held {
725        Some(v) if v.is_finite() => Ok(v),
726        _ => Err(CliError::usage(
727            "query.bad_value",
728            format!("`{key}` needs a level in decibels, as `-40db`, got `{raw}`"),
729        )),
730    }
731}
732
733fn norm(raw: &str) -> Result<Norm, CliError> {
734    [Norm::L1, Norm::L2]
735        .into_iter()
736        .find(|n| n.key() == raw)
737        .ok_or_else(|| {
738            CliError::usage(
739                "query.bad_value",
740                format!("`norm` is `l1` or `l2`, got `{raw}`"),
741            )
742        })
743}
744
745fn switch(raw: &str, key: &str) -> Result<bool, CliError> {
746    match raw {
747        "1" => Ok(true),
748        "0" => Ok(false),
749        _ => Err(CliError::usage(
750            "query.bad_value",
751            format!("`{key}` is `1` or `0`, got `{raw}`"),
752        )),
753    }
754}
755
756/// A ref as the language writes one, `@voice`.
757fn node(raw: &str) -> Result<String, CliError> {
758    match raw.strip_prefix('@') {
759        Some(path) if !path.is_empty() => Ok(path.to_string()),
760        _ => Err(CliError::usage(
761            "query.bad_value",
762            format!("`node` names an instance as a ref, as `@voice`, not `{raw}`"),
763        )),
764    }
765}