Skip to main content

sva_engine/
typing.rs

1// Concern: gives every node one Ty and the value it lowered to | Non-concern: the per-term judgment (sva-formula), lowering (lower/) | IO: (Instances, Order) -> Ty per node
2
3use std::cell::RefCell;
4use std::collections::{BTreeMap, BTreeSet};
5use std::sync::Arc;
6
7use sva_formula::filter::Shape;
8use sva_formula::{C64, ClosedForm, Codomain, Env, Held, NodeId, Origin, ParamId, Ty, Var, infer};
9use sva_samples::Params;
10
11use crate::arguments::{Arguments, Called, Chosen};
12use crate::cache::Stored;
13use crate::cast::Cast;
14use crate::error::{Diagnostic, EngineError, Located};
15use crate::instantiate::Instances;
16use crate::lower;
17use crate::schedule::Order;
18use crate::time::Grid;
19
20/// A closed form is cast-free on one axis; every crossing is its own node.
21#[derive(Clone, Debug, PartialEq)]
22pub enum Value {
23    ClosedForm(ClosedForm),
24    Cast(Cast, NodeId),
25    Op {
26        name: String,
27        args: Vec<NodeId>,
28    },
29    SelfAt {
30        at: When,
31    },
32    Read {
33        source: NodeId,
34        at: When,
35        site: Origin,
36    },
37    Noise(u64),
38    /// The signal and its three arguments, each a node of its own.
39    Filter {
40        shape: Shape,
41        x: NodeId,
42        cutoff: NodeId,
43        q: NodeId,
44        gain: NodeId,
45    },
46    Solver {
47        params: Box<Params>,
48        varying: Vec<(&'static str, NodeId)>,
49    },
50    /// Samples the store answered in place of the node's own source, which is never typed.
51    Stored(Arc<Stored>),
52}
53
54/// A read's instant: the exact time `k*t + s` written; a closed form of `t` held as a node;
55/// or an integer each sample evaluates.
56#[derive(Clone, Debug, PartialEq)]
57pub enum When {
58    At(crate::time::Affine),
59    Moving(NodeId),
60    Index(crate::index::Index),
61    Step(Step),
62}
63
64/// An integer no one map spells: exact indices, `idx(time, round)` of a time that moves, and
65/// sums, negations and products of them.
66#[derive(Clone, Debug, PartialEq)]
67pub enum Step {
68    Index(crate::index::Index),
69    Nearest(NodeId, crate::index::Round),
70    Add(Vec<Step>),
71    Neg(Box<Step>),
72    Mul(Vec<Step>),
73}
74
75impl Step {
76    /// Every time that moves in it.
77    pub(crate) fn times(&self, out: &mut Vec<NodeId>) {
78        match self {
79            Step::Index(_) => {}
80            Step::Nearest(time, _) => out.push(*time),
81            Step::Add(parts) | Step::Mul(parts) => parts.iter().for_each(|p| p.times(out)),
82            Step::Neg(p) => p.times(out),
83        }
84    }
85}
86
87impl When {
88    /// Every node it evaluates each sample.
89    pub(crate) fn moving(&self) -> Vec<NodeId> {
90        let mut out = Vec::new();
91        match self {
92            When::Moving(id) => out.push(*id),
93            When::Step(step) => step.times(&mut out),
94            When::At(_) | When::Index(_) => {}
95        }
96        out
97    }
98}
99
100#[derive(Clone, Debug, PartialEq)]
101pub struct Node {
102    pub name: String,
103    pub ty: Ty,
104    pub var: Var,
105    pub value: Value,
106    pub grid: Grid,
107}
108
109#[derive(Clone, Debug, Default, PartialEq)]
110pub struct Typing {
111    nodes: Vec<Node>,
112    arguments: BTreeMap<String, Arguments>,
113    by_path: BTreeMap<String, NodeId>,
114    copies: BTreeMap<(String, Grid), NodeId>,
115    lowering: BTreeSet<String>,
116    files: BTreeMap<String, Vec<NodeId>>,
117    origins: Vec<(u32, Option<sva_ast::ByteSpan>)>,
118    sites: Vec<String>,
119    site_ids: BTreeMap<String, u32>,
120    pending: BTreeSet<NodeId>,
121    indices: u32,
122    sum: Option<(NodeId, Vec<SumSlot>)>,
123    numbers: Numbers,
124    /// Every node lowered from its source, in order.
125    lowered: Vec<String>,
126}
127
128/// Each node's folded number, derived from the nodes alone; a settle evicts it all.
129#[derive(Clone, Debug, Default)]
130struct Numbers(RefCell<BTreeMap<NodeId, Option<C64>>>);
131
132impl PartialEq for Numbers {
133    fn eq(&self, _: &Numbers) -> bool {
134        true
135    }
136}
137
138/// One term of a stream's note sum: its node, or the identity it had before it ended.
139#[derive(Clone, Copy, Debug, PartialEq)]
140pub(crate) enum SumSlot {
141    Node(NodeId),
142    Retired(sva_formula::Hash),
143}
144
145impl Typing {
146    /// `node` named by its terms in place, an ended one by the identity it had.
147    pub(crate) fn name_sum(&mut self, node: NodeId, slots: Vec<SumSlot>) {
148        self.sum = Some((node, slots));
149    }
150
151    pub(crate) fn sum_slots(&self, node: NodeId) -> Option<&[SumSlot]> {
152        self.sum
153            .as_ref()
154            .filter(|(held, _)| *held == node)
155            .map(|(_, slots)| slots.as_slice())
156    }
157
158    pub(crate) fn lowering(&mut self, path: &str) {
159        self.lowered.push(path.to_string());
160    }
161
162    pub(crate) fn lowered(&self) -> &[String] {
163        &self.lowered
164    }
165
166    pub(crate) fn next_index(&mut self) -> sva_formula::IndexId {
167        self.indices += 1;
168        sva_formula::IndexId(self.indices)
169    }
170
171    /// A call lowered twice is noted once, at its latest lowering.
172    pub(crate) fn note(&mut self, node: &str, call: Option<Called>, chosen: Vec<Chosen>) {
173        let held = self
174            .arguments
175            .entry(node.to_string())
176            .or_insert_with(|| Arguments {
177                node: node.to_string(),
178                ..Arguments::default()
179            });
180        if let Some(call) = call {
181            held.calls
182                .retain(|c| (c.at.start, &c.name) != (call.at.start, &call.name));
183            held.calls.push(call);
184        }
185        for one in chosen {
186            held.chosen.retain(|c| c.at.start != one.at.start);
187            held.chosen.push(one);
188        }
189    }
190
191    pub fn arguments(&self, node: &str) -> Option<&Arguments> {
192        self.arguments.get(node)
193    }
194
195    pub fn ty(&self, n: NodeId) -> Ty {
196        self.at(n).ty
197    }
198
199    pub fn var(&self, n: NodeId) -> Var {
200        self.at(n).var
201    }
202
203    pub fn value(&self, n: NodeId) -> &Value {
204        &self.at(n).value
205    }
206
207    pub fn name(&self, n: NodeId) -> &str {
208        &self.at(n).name
209    }
210
211    pub fn grid(&self, n: NodeId) -> Grid {
212        self.at(n).grid
213    }
214
215    pub(crate) fn copy(&self, path: &str, grid: Grid) -> Option<NodeId> {
216        self.copies.get(&(path.to_string(), grid)).copied()
217    }
218
219    pub(crate) fn copied(&mut self, path: &str, grid: Grid, id: NodeId) {
220        self.copies.insert((path.to_string(), grid), id);
221    }
222
223    /// `false` where a copy of `path` is already being lowered: a loop of refs.
224    pub(crate) fn opened(&mut self, path: &str) -> bool {
225        self.lowering.insert(path.to_string())
226    }
227
228    pub(crate) fn closed(&mut self, path: &str) {
229        self.lowering.remove(path);
230    }
231
232    pub fn at(&self, n: NodeId) -> &Node {
233        &self.nodes[n.0 as usize]
234    }
235
236    pub(crate) fn len(&self) -> usize {
237        self.nodes.len()
238    }
239
240    pub fn id(&self, path: &str) -> Option<NodeId> {
241        self.by_path.get(path).copied()
242    }
243
244    pub fn paths(&self) -> impl Iterator<Item = (&str, NodeId)> {
245        self.by_path.iter().map(|(p, id)| (p.as_str(), *id))
246    }
247
248    /// The node a reading asks for, by instance path or by the file a composer wrote.
249    pub fn resolve(&self, path: &str) -> Result<NodeId, EngineError> {
250        if let Some(id) = self.id(path) {
251            return Ok(id);
252        }
253        let held = self.files.get(path).cloned().unwrap_or_default();
254        crate::instantiate::sole(
255            path,
256            held.into_iter()
257                .map(|id| (self.name(id).to_string(), id))
258                .collect(),
259        )
260    }
261
262    /// Every `Origin` a term carries was stamped here.
263    pub fn locate(&self, origin: Origin) -> Located {
264        self.origins
265            .get(origin.token() as usize)
266            .map(|&(site, span)| Located::at(self.sites[site as usize].as_str(), span))
267            .unwrap_or_default()
268    }
269
270    pub(crate) fn mark(&mut self, node: &str, span: Option<sva_ast::ByteSpan>) -> Origin {
271        let site = match self.site_ids.get(node) {
272            Some(&site) => site,
273            None => {
274                let site = self.sites.len() as u32;
275                self.sites.push(node.to_string());
276                self.site_ids.insert(node.to_string(), site);
277                site
278            }
279        };
280        self.origins.push((site, span));
281        Origin::new((self.origins.len() - 1) as u32)
282    }
283
284    pub(crate) fn seed(&mut self, path: &str, held: Held, grid: Grid) -> NodeId {
285        if let Some(id) = self.id(path) {
286            return id;
287        }
288        let id = self.push(
289            Node {
290                name: path.to_string(),
291                ty: Ty {
292                    dual: held.is_closed_form(),
293                    ..Ty::discrete(held, Codomain::Real)
294                },
295                var: Var::T,
296                value: Value::Op {
297                    name: "loop".to_string(),
298                    args: Vec::new(),
299                },
300                grid,
301            },
302            Some(path),
303        );
304        self.pending.insert(id);
305        id
306    }
307
308    pub(crate) fn pending(&self, id: NodeId) -> bool {
309        self.pending.contains(&id)
310    }
311
312    pub(crate) fn settle(&mut self, id: NodeId, node: Node) {
313        self.nodes[id.0 as usize] = node;
314        self.pending.remove(&id);
315        self.numbers.0.get_mut().clear();
316    }
317
318    pub(crate) fn folded_number(&self, id: NodeId) -> Option<Option<C64>> {
319        self.numbers.0.borrow().get(&id).copied()
320    }
321
322    pub(crate) fn fold_number(&self, id: NodeId, number: Option<C64>) {
323        self.numbers.0.borrow_mut().insert(id, number);
324    }
325
326    pub(crate) fn alias(&mut self, path: &str, id: NodeId) {
327        self.by_path.insert(path.to_string(), id);
328    }
329
330    pub(crate) fn push(&mut self, node: Node, path: Option<&str>) -> NodeId {
331        let id = NodeId(self.nodes.len() as u32);
332        self.nodes.push(node);
333        if let Some(path) = path {
334            self.by_path.insert(path.to_string(), id);
335        }
336        id
337    }
338
339    pub(crate) fn infer_closed_form(&self, form: &ClosedForm) -> Result<Ty, EngineError> {
340        infer(form, &Table(&self.nodes)).map_err(|r| {
341            EngineError::of_closed_form(
342                &r,
343                self.locate(r.origin),
344                "write the subterm inside sample(...) to leave A deliberately",
345            )
346        })
347    }
348}
349
350struct Table<'a>(&'a [Node]);
351
352impl Env for Table<'_> {
353    fn node(&self, id: NodeId) -> Ty {
354        self.0[id.0 as usize].ty
355    }
356
357    /// Substituted per instance before a closed form reaches sva-formula, so no term holds one.
358    fn param(&self, _: ParamId) -> Ty {
359        Ty::form(Var::T, true, Codomain::Real)
360    }
361}
362
363/// Dependencies first, so a ref reads a type already decided.
364pub fn infer_all(inst: &Instances, order: &Order) -> Result<Typing, EngineError> {
365    infer_over(inst, order, &BTreeMap::new())
366}
367
368/// Each node `stored` names stands as its samples, and nothing under it is typed.
369pub(crate) fn infer_over(
370    inst: &Instances,
371    order: &Order,
372    stored: &BTreeMap<String, Arc<Stored>>,
373) -> Result<Typing, EngineError> {
374    let mut typing = Typing::default();
375    for group in &order.groups {
376        match (order.is_loop(group), group.as_slice()) {
377            (false, [path]) if let Some(held) = stored.get(path) => {
378                typing.push(standing(path, held), Some(path));
379            }
380            (true, _) => settle_loop(&mut typing, inst, group)?,
381            (false, _) => {
382                for path in group {
383                    lower::node(path, inst, &mut typing)?;
384                }
385            }
386        }
387    }
388    name_files(&mut typing, inst);
389    Ok(typing)
390}
391
392fn standing(path: &str, held: &Arc<Stored>) -> Node {
393    Node {
394        name: path.to_string(),
395        ty: Ty {
396            width: held.width,
397            rate: held.rate,
398            ..Ty::discrete(Held::Sampled, held.codomain)
399        },
400        var: Var::T,
401        value: Value::Stored(Arc::clone(held)),
402        grid: held.grid,
403    }
404}
405
406const SEEDS: [Held; 2] = [Held::Form(Var::T), Held::Sampled];
407
408/// A group's members type together, so the seed a pass starts from is a guess the pass
409/// either reaches again or replaces with what its members held.
410fn settle_loop(typing: &mut Typing, inst: &Instances, group: &[String]) -> Result<(), EngineError> {
411    let mut seed = SEEDS[0];
412    let mut refusal = None;
413    for _ in 0..=SEEDS.len() {
414        let mut attempt = typing.clone();
415        for path in group {
416            attempt.seed(path, seed, inst.grid());
417        }
418        let walked = group
419            .iter()
420            .try_for_each(|path| lower::node(path, inst, &mut attempt).map(|_| ()));
421        match walked {
422            Ok(()) => match held_by(&attempt, group) {
423                reached if reached == seed => {
424                    *typing = attempt;
425                    return Ok(());
426                }
427                reached => seed = reached,
428            },
429            Err(e) => {
430                refusal = Some(e);
431                seed = elsewhere(seed);
432            }
433        }
434    }
435    Err(refusal.unwrap_or_else(|| mixed(group)))
436}
437
438/// The seed a refused pass did not try.
439fn elsewhere(seed: Held) -> Held {
440    match seed {
441        Held::Sampled => Held::Form(Var::T),
442        _ => Held::Sampled,
443    }
444}
445
446/// One representation for the whole group: samples where any member reached them.
447fn held_by(typing: &Typing, group: &[String]) -> Held {
448    let sampled = group
449        .iter()
450        .filter_map(|path| typing.id(path))
451        .any(|id| !typing.ty(id).is_closed_form());
452    match sampled {
453        true => Held::Sampled,
454        false => Held::Form(Var::T),
455    }
456}
457
458/// A group that settles in no representation holds both.
459fn mixed(group: &[String]) -> EngineError {
460    let at = group.first().map_or("", String::as_str);
461    EngineError::refused(Diagnostic {
462        code: "type.samples_in_closed_form".to_string(),
463        message: format!(
464            "the loop over `{}` holds a closed form and samples at once.",
465            group.join("`, `")
466        ),
467        location: Located::at(at, None),
468        help: "write sample(...) on the members that are closed forms, so the whole loop runs \
469               on the grid"
470            .to_string(),
471    })
472}
473
474/// A file with one instance answers to its own name too.
475fn name_files(typing: &mut Typing, inst: &Instances) {
476    let files: Vec<String> = inst
477        .paths()
478        .filter_map(|p| inst.origin(p))
479        .map(str::to_string)
480        .collect();
481    for file in files {
482        if typing.files.contains_key(&file) {
483            continue;
484        }
485        let held: Vec<NodeId> = inst
486            .instances_of(&file)
487            .filter_map(|p| typing.id(&p))
488            .collect();
489        if let ([only], None) = (held.as_slice(), typing.id(&file)) {
490            typing.alias(&file, *only);
491        }
492        typing.files.insert(file, held);
493    }
494}