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 and support it had before it
139/// ended.
140#[derive(Clone, Copy, Debug, PartialEq)]
141pub(crate) enum SumSlot {
142    Node(NodeId),
143    Retired(sva_formula::Hash, sva_samples::Extent),
144}
145
146impl Typing {
147    /// `node` named by its terms in place, an ended one by the identity it had.
148    pub(crate) fn name_sum(&mut self, node: NodeId, slots: Vec<SumSlot>) {
149        self.sum = Some((node, slots));
150    }
151
152    pub(crate) fn sum_slots(&self, node: NodeId) -> Option<&[SumSlot]> {
153        self.sum
154            .as_ref()
155            .filter(|(held, _)| *held == node)
156            .map(|(_, slots)| slots.as_slice())
157    }
158
159    pub(crate) fn lowering(&mut self, path: &str) {
160        self.lowered.push(path.to_string());
161    }
162
163    pub(crate) fn lowered(&self) -> &[String] {
164        &self.lowered
165    }
166
167    pub(crate) fn next_index(&mut self) -> sva_formula::IndexId {
168        self.indices += 1;
169        sva_formula::IndexId(self.indices)
170    }
171
172    /// A call lowered twice is noted once, at its latest lowering.
173    pub(crate) fn note(&mut self, node: &str, call: Option<Called>, chosen: Vec<Chosen>) {
174        let held = self
175            .arguments
176            .entry(node.to_string())
177            .or_insert_with(|| Arguments {
178                node: node.to_string(),
179                ..Arguments::default()
180            });
181        if let Some(call) = call {
182            held.calls
183                .retain(|c| (c.at.start, &c.name) != (call.at.start, &call.name));
184            held.calls.push(call);
185        }
186        for one in chosen {
187            held.chosen.retain(|c| c.at.start != one.at.start);
188            held.chosen.push(one);
189        }
190    }
191
192    pub fn arguments(&self, node: &str) -> Option<&Arguments> {
193        self.arguments.get(node)
194    }
195
196    pub fn ty(&self, n: NodeId) -> Ty {
197        self.at(n).ty
198    }
199
200    pub fn var(&self, n: NodeId) -> Var {
201        self.at(n).var
202    }
203
204    pub fn value(&self, n: NodeId) -> &Value {
205        &self.at(n).value
206    }
207
208    pub fn name(&self, n: NodeId) -> &str {
209        &self.at(n).name
210    }
211
212    pub fn grid(&self, n: NodeId) -> Grid {
213        self.at(n).grid
214    }
215
216    pub(crate) fn copy(&self, path: &str, grid: Grid) -> Option<NodeId> {
217        self.copies.get(&(path.to_string(), grid)).copied()
218    }
219
220    pub(crate) fn copied(&mut self, path: &str, grid: Grid, id: NodeId) {
221        self.copies.insert((path.to_string(), grid), id);
222    }
223
224    /// `false` where a copy of `path` is already being lowered: a loop of refs.
225    pub(crate) fn opened(&mut self, path: &str) -> bool {
226        self.lowering.insert(path.to_string())
227    }
228
229    pub(crate) fn closed(&mut self, path: &str) {
230        self.lowering.remove(path);
231    }
232
233    pub fn at(&self, n: NodeId) -> &Node {
234        &self.nodes[n.0 as usize]
235    }
236
237    pub(crate) fn len(&self) -> usize {
238        self.nodes.len()
239    }
240
241    pub fn id(&self, path: &str) -> Option<NodeId> {
242        self.by_path.get(path).copied()
243    }
244
245    pub fn paths(&self) -> impl Iterator<Item = (&str, NodeId)> {
246        self.by_path.iter().map(|(p, id)| (p.as_str(), *id))
247    }
248
249    /// The node a reading asks for, by instance path or by the file a composer wrote.
250    pub fn resolve(&self, path: &str) -> Result<NodeId, EngineError> {
251        if let Some(id) = self.id(path) {
252            return Ok(id);
253        }
254        let held = self.files.get(path).cloned().unwrap_or_default();
255        crate::instantiate::sole(
256            path,
257            held.into_iter()
258                .map(|id| (self.name(id).to_string(), id))
259                .collect(),
260        )
261    }
262
263    /// Every `Origin` a term carries was stamped here.
264    pub fn locate(&self, origin: Origin) -> Located {
265        self.origins
266            .get(origin.token() as usize)
267            .map(|&(site, span)| Located::at(self.sites[site as usize].as_str(), span))
268            .unwrap_or_default()
269    }
270
271    pub(crate) fn mark(&mut self, node: &str, span: Option<sva_ast::ByteSpan>) -> Origin {
272        let site = match self.site_ids.get(node) {
273            Some(&site) => site,
274            None => {
275                let site = self.sites.len() as u32;
276                self.sites.push(node.to_string());
277                self.site_ids.insert(node.to_string(), site);
278                site
279            }
280        };
281        self.origins.push((site, span));
282        Origin::new((self.origins.len() - 1) as u32)
283    }
284
285    pub(crate) fn seed(&mut self, path: &str, held: Held, grid: Grid) -> NodeId {
286        if let Some(id) = self.id(path) {
287            return id;
288        }
289        let id = self.push(
290            Node {
291                name: path.to_string(),
292                ty: Ty {
293                    dual: held.is_closed_form(),
294                    ..Ty::discrete(held, Codomain::Real)
295                },
296                var: Var::T,
297                value: Value::Op {
298                    name: "loop".to_string(),
299                    args: Vec::new(),
300                },
301                grid,
302            },
303            Some(path),
304        );
305        self.pending.insert(id);
306        id
307    }
308
309    pub(crate) fn pending(&self, id: NodeId) -> bool {
310        self.pending.contains(&id)
311    }
312
313    pub(crate) fn settle(&mut self, id: NodeId, node: Node) {
314        self.nodes[id.0 as usize] = node;
315        self.pending.remove(&id);
316        self.numbers.0.get_mut().clear();
317    }
318
319    pub(crate) fn folded_number(&self, id: NodeId) -> Option<Option<C64>> {
320        self.numbers.0.borrow().get(&id).copied()
321    }
322
323    pub(crate) fn fold_number(&self, id: NodeId, number: Option<C64>) {
324        self.numbers.0.borrow_mut().insert(id, number);
325    }
326
327    pub(crate) fn alias(&mut self, path: &str, id: NodeId) {
328        self.by_path.insert(path.to_string(), id);
329    }
330
331    pub(crate) fn push(&mut self, node: Node, path: Option<&str>) -> NodeId {
332        let id = NodeId(self.nodes.len() as u32);
333        self.nodes.push(node);
334        if let Some(path) = path {
335            self.by_path.insert(path.to_string(), id);
336        }
337        id
338    }
339
340    pub(crate) fn infer_closed_form(&self, form: &ClosedForm) -> Result<Ty, EngineError> {
341        infer(form, &Table(&self.nodes)).map_err(|r| {
342            EngineError::of_closed_form(
343                &r,
344                self.locate(r.origin),
345                "write the subterm inside sample(...) to leave A deliberately",
346            )
347        })
348    }
349}
350
351struct Table<'a>(&'a [Node]);
352
353impl Env for Table<'_> {
354    fn node(&self, id: NodeId) -> Ty {
355        self.0[id.0 as usize].ty
356    }
357
358    /// Substituted per instance before a closed form reaches sva-formula, so no term holds one.
359    fn param(&self, _: ParamId) -> Ty {
360        Ty::form(Var::T, true, Codomain::Real)
361    }
362}
363
364/// Dependencies first, so a ref reads a type already decided.
365pub fn infer_all(inst: &Instances, order: &Order) -> Result<Typing, EngineError> {
366    infer_over(inst, order, &BTreeMap::new())
367}
368
369/// Each node `stored` names stands as its samples, and nothing under it is typed.
370pub(crate) fn infer_over(
371    inst: &Instances,
372    order: &Order,
373    stored: &BTreeMap<String, Arc<Stored>>,
374) -> Result<Typing, EngineError> {
375    let mut typing = Typing::default();
376    for group in &order.groups {
377        match (order.is_loop(group), group.as_slice()) {
378            (false, [path]) if let Some(held) = stored.get(path) => {
379                typing.push(standing(path, held), Some(path));
380            }
381            (true, _) => settle_loop(&mut typing, inst, group)?,
382            (false, _) => {
383                for path in group {
384                    lower::node(path, inst, &mut typing)?;
385                }
386            }
387        }
388    }
389    name_files(&mut typing, inst);
390    Ok(typing)
391}
392
393fn standing(path: &str, held: &Arc<Stored>) -> Node {
394    Node {
395        name: path.to_string(),
396        ty: Ty {
397            width: held.width,
398            rate: held.rate,
399            ..Ty::discrete(Held::Sampled, held.codomain)
400        },
401        var: Var::T,
402        value: Value::Stored(Arc::clone(held)),
403        grid: held.grid,
404    }
405}
406
407const SEEDS: [Held; 2] = [Held::Form(Var::T), Held::Sampled];
408
409/// A group's members type together, so the seed a pass starts from is a guess the pass
410/// either reaches again or replaces with what its members held.
411fn settle_loop(typing: &mut Typing, inst: &Instances, group: &[String]) -> Result<(), EngineError> {
412    let mut seed = SEEDS[0];
413    let mut refusal = None;
414    for _ in 0..=SEEDS.len() {
415        let mut attempt = typing.clone();
416        for path in group {
417            attempt.seed(path, seed, inst.grid());
418        }
419        let walked = group
420            .iter()
421            .try_for_each(|path| lower::node(path, inst, &mut attempt).map(|_| ()));
422        match walked {
423            Ok(()) => match held_by(&attempt, group) {
424                reached if reached == seed => {
425                    *typing = attempt;
426                    return Ok(());
427                }
428                reached => seed = reached,
429            },
430            Err(e) => {
431                refusal = Some(e);
432                seed = elsewhere(seed);
433            }
434        }
435    }
436    Err(refusal.unwrap_or_else(|| mixed(group)))
437}
438
439/// The seed a refused pass did not try.
440fn elsewhere(seed: Held) -> Held {
441    match seed {
442        Held::Sampled => Held::Form(Var::T),
443        _ => Held::Sampled,
444    }
445}
446
447/// One representation for the whole group: samples where any member reached them.
448fn held_by(typing: &Typing, group: &[String]) -> Held {
449    let sampled = group
450        .iter()
451        .filter_map(|path| typing.id(path))
452        .any(|id| !typing.ty(id).is_closed_form());
453    match sampled {
454        true => Held::Sampled,
455        false => Held::Form(Var::T),
456    }
457}
458
459/// A group that settles in no representation holds both.
460fn mixed(group: &[String]) -> EngineError {
461    let at = group.first().map_or("", String::as_str);
462    EngineError::refused(Diagnostic {
463        code: "type.samples_in_closed_form".to_string(),
464        message: format!(
465            "the loop over `{}` holds a closed form and samples at once.",
466            group.join("`, `")
467        ),
468        location: Located::at(at, None),
469        help: "write sample(...) on the members that are closed forms, so the whole loop runs \
470               on the grid"
471            .to_string(),
472    })
473}
474
475/// A file with one instance answers to its own name too.
476fn name_files(typing: &mut Typing, inst: &Instances) {
477    let files: Vec<String> = inst
478        .paths()
479        .filter_map(|p| inst.origin(p))
480        .map(str::to_string)
481        .collect();
482    for file in files {
483        if typing.files.contains_key(&file) {
484            continue;
485        }
486        let held: Vec<NodeId> = inst
487            .instances_of(&file)
488            .filter_map(|p| typing.id(&p))
489            .collect();
490        if let ([only], None) = (held.as_slice(), typing.id(&file)) {
491            typing.alias(&file, *only);
492        }
493        typing.files.insert(file, held);
494    }
495}