Skip to main content

sva_engine/
schedule.rs

1// Concern: orders nodes dependencies-first and picks which a reading materializes | Non-concern: what a held node contains (render.rs), reading one (refs.rs) | IO: (Instances, asks) -> Schedule
2
3use std::collections::{BTreeMap, BTreeSet, HashMap};
4
5use sva_ast::{Arg, Expr};
6use sva_formula::NodeId;
7
8use crate::cast::Cast;
9use crate::error::EngineError;
10use crate::instantiate::{Cx, Instances, Node};
11use crate::query::Ask;
12use crate::typing::{Typing, Value};
13
14/// One-hop instance names. `self(...)` is a same-node read, never an edge.
15fn direct_refs(inst: &Instances, e: &Expr, cx: Cx, out: &mut Vec<String>) {
16    if inst
17        .follow(e, cx, |e2, cx2| direct_refs(inst, e2, cx2, out))
18        .is_some()
19    {
20        return;
21    }
22    match inst.node(e, cx) {
23        Node::Lit(_) | Node::Name(_) => {}
24        Node::Bin(_, l, r) => {
25            direct_refs(inst, l, cx, out);
26            direct_refs(inst, r, cx, out);
27        }
28        Node::Call { args, .. } => {
29            for a in args {
30                let (Arg::Pos(x) | Arg::Named(_, x)) = a;
31                direct_refs(inst, x, cx, out);
32            }
33        }
34        Node::Read { path, arg, .. } => {
35            out.push(path.to_string());
36            direct_refs(inst, arg, cx, out);
37        }
38        Node::Own { arg, .. } => direct_refs(inst, arg, cx, out),
39    }
40}
41
42/// One dependencies-first walk: the groups, what each node reads, and which are loops.
43pub struct Order {
44    pub groups: Vec<Vec<String>>,
45    deps: BTreeMap<String, Vec<String>>,
46}
47
48impl Order {
49    pub fn deps(&self, path: &str) -> &[String] {
50        self.deps.get(path).map_or(&[], Vec::as_slice)
51    }
52
53    /// A group of one whose node does not ref itself is an ordinary node; anything else is a loop.
54    pub fn is_loop(&self, group: &[String]) -> bool {
55        match group {
56            [only] => self.deps(only).iter().any(|d| d == only),
57            _ => true,
58        }
59    }
60}
61
62pub fn direct_deps(inst: &Instances, path: &str) -> Result<Vec<String>, EngineError> {
63    let (e, cx) = inst
64        .at(path)
65        .ok_or_else(|| EngineError::UnknownNode(path.to_string()))?;
66    let mut out = Vec::new();
67    direct_refs(inst, e, cx, &mut out);
68    out.sort();
69    out.dedup();
70    for target in &out {
71        if !inst.holds(target) {
72            return Err(EngineError::UnknownNode(target.clone()));
73        }
74    }
75    Ok(out)
76}
77
78struct Frame {
79    node: String,
80    refs: Vec<String>,
81    idx: usize,
82}
83
84/// A node two roots reach is grouped once, whichever reached it first.
85pub fn schedule_from(inst: &Instances, roots: &[String]) -> Result<Order, EngineError> {
86    let mut walk = Walk {
87        inst,
88        deps: BTreeMap::new(),
89        index: HashMap::new(),
90        low: HashMap::new(),
91        open: Vec::new(),
92        next: 0,
93        groups: Vec::new(),
94    };
95    for root in roots {
96        walk.from(root)?;
97    }
98    Ok(Order {
99        groups: walk.groups,
100        deps: walk.deps,
101    })
102}
103
104struct Walk<'a> {
105    inst: &'a Instances<'a>,
106    deps: BTreeMap<String, Vec<String>>,
107    index: HashMap<String, usize>,
108    low: HashMap<String, usize>,
109    open: Vec<String>,
110    next: usize,
111    groups: Vec<Vec<String>>,
112}
113
114impl Walk<'_> {
115    fn from(&mut self, root: &str) -> Result<(), EngineError> {
116        if !self.inst.holds(root) {
117            return Err(EngineError::UnknownNode(root.to_string()));
118        }
119        if self.index.contains_key(root) {
120            return Ok(());
121        }
122        self.index.insert(root.to_string(), self.next);
123        self.low.insert(root.to_string(), self.next);
124        self.next += 1;
125        self.open.push(root.to_string());
126        let seed = direct_deps(self.inst, root)?;
127        self.deps.insert(root.to_string(), seed.clone());
128        let mut stack = vec![Frame {
129            node: root.to_string(),
130            refs: seed,
131            idx: 0,
132        }];
133
134        while let Some(frame) = stack.last_mut() {
135            if frame.idx < frame.refs.len() {
136                let target = frame.refs[frame.idx].clone();
137                let node = frame.node.clone();
138                frame.idx += 1;
139                match self.index.get(&target).copied() {
140                    None => {
141                        self.index.insert(target.clone(), self.next);
142                        self.low.insert(target.clone(), self.next);
143                        self.next += 1;
144                        self.open.push(target.clone());
145                        let refs = direct_deps(self.inst, &target)?;
146                        self.deps.insert(target.clone(), refs.clone());
147                        stack.push(Frame {
148                            node: target,
149                            refs,
150                            idx: 0,
151                        });
152                    }
153                    Some(at) if self.open.contains(&target) => {
154                        let mine = self.low[&node];
155                        self.low.insert(node, mine.min(at));
156                    }
157                    Some(_) => {}
158                }
159                continue;
160            }
161
162            let node = frame.node.clone();
163            let mine = self.low[&node];
164            stack.pop();
165            if let Some(parent) = stack.last() {
166                let above = self.low[&parent.node];
167                self.low.insert(parent.node.clone(), above.min(mine));
168            }
169            if mine == self.index[&node] {
170                let at = self
171                    .open
172                    .iter()
173                    .rposition(|n| *n == node)
174                    .expect("a root of its group is still open");
175                let mut group = self.open.split_off(at);
176                group.sort();
177                self.groups.push(group);
178            }
179        }
180        Ok(())
181    }
182}
183
184/// What a render has to hold, and what it can leave as a closed form.
185#[derive(Clone, Debug, Default, PartialEq)]
186pub struct Schedule {
187    pub materialize: Vec<NodeId>,
188    pub symbolic: Vec<NodeId>,
189    /// The nodes a reading asked a closed form of, each named once however many asked
190    /// and none of them already materialized.
191    pub compose: Vec<NodeId>,
192}
193
194/// A closed form is materialized only under a buffer reading, a `sample(...)`, or the render root.
195pub fn plan(typing: &Typing, order: &Order, root: NodeId, asks: &[Ask]) -> Schedule {
196    let mut wanted: BTreeSet<NodeId> = BTreeSet::new();
197    let mut compose: Vec<NodeId> = Vec::new();
198    let audio = asks.is_empty();
199    for ask in asks {
200        let Some(id) = typing.id(&ask.node) else {
201            continue;
202        };
203        // FORMAT 14.2: `bindings` is structural and `flops` counts; neither composes.
204        if matches!(
205            ask.representation,
206            crate::query::Representation::Bindings | crate::query::Representation::Flops
207        ) {
208            continue;
209        }
210        match ask.representation.consumes(typing.ty(id).is_closed_form()) {
211            sva_samples::Consumes::ClosedForm if !compose.contains(&id) => compose.push(id),
212            sva_samples::Consumes::ClosedForm => {}
213            _ => {
214                wanted.insert(id);
215            }
216        }
217        if let crate::query::Representation::Ledger { depth } = ask.representation {
218            attributed(typing, id, depth, &mut wanted);
219        }
220    }
221    if audio || !wanted.is_empty() {
222        wanted.insert(root);
223    }
224
225    let mut reached: BTreeSet<NodeId> = BTreeSet::new();
226    let mut work: Vec<NodeId> = wanted.iter().copied().collect();
227    while let Some(id) = work.pop() {
228        if !reached.insert(id) {
229            continue;
230        }
231        work.extend(materialized_operands(typing, id));
232    }
233
234    let held: Vec<NodeId> = order
235        .groups
236        .concat()
237        .iter()
238        .filter_map(|path| typing.id(path))
239        .collect();
240    let mut materialize: Vec<NodeId> = Vec::new();
241    let mut seen: BTreeSet<NodeId> = BTreeSet::new();
242    for id in held {
243        for member in dependencies_first(typing, id, &mut seen) {
244            if reached.contains(&member) {
245                materialize.push(member);
246            }
247        }
248    }
249    let symbolic = typing
250        .paths()
251        .map(|(_, id)| id)
252        .filter(|id| !materialize.contains(id))
253        .collect();
254    compose.retain(|id| !materialize.contains(id));
255    Schedule {
256        materialize,
257        symbolic,
258        compose,
259    }
260}
261
262/// A ledger names every ref under its target, so each is a buffer of its own.
263fn attributed(typing: &Typing, id: NodeId, depth: usize, wanted: &mut BTreeSet<NodeId>) {
264    // Level by level, as the reading walks: a node is held at its shortest chain's depth.
265    let mut seen = BTreeSet::from([id]);
266    let mut level = vec![id];
267    for _ in 0..depth {
268        let mut next = Vec::new();
269        for held in level {
270            for operand in read_operands(typing, held) {
271                if seen.insert(operand) {
272                    wanted.insert(operand);
273                    next.push(operand);
274                }
275            }
276        }
277        level = next;
278    }
279}
280
281/// A node reading its own output is one program, whatever its width: a component lowered on
282/// its own would read the loop at that component's width instead of the node's.
283fn holds_self(typing: &Typing, id: NodeId, seen: &mut BTreeSet<NodeId>) -> bool {
284    if !seen.insert(id) {
285        return false;
286    }
287    match typing.value(id) {
288        Value::SelfAt(_) => true,
289        Value::Cast(Cast::Sample, _) | Value::Read { .. } => false,
290        Value::Cast(_, source) => holds_self(typing, *source, seen),
291        Value::Op { args, .. } => args.iter().any(|a| holds_self(typing, *a, seen)),
292        Value::Filter {
293            x, cutoff, q, gain, ..
294        } => [x, cutoff, q, gain]
295            .into_iter()
296            .any(|operand| holds_self(typing, *operand, seen)),
297        Value::ClosedForm(_) | Value::Solver(_) | Value::Grid(_) => false,
298    }
299}
300
301/// Which nodes under `id` a render has to hold before it can hold `id` itself.
302pub(crate) fn materialized_operands(typing: &Typing, id: NodeId) -> Vec<NodeId> {
303    let sampled = |set: Vec<NodeId>| -> Vec<NodeId> {
304        let mut out = Vec::new();
305        for op in set {
306            if typing.ty(op).is_closed_form() || matches!(typing.value(op), Value::Grid(_)) {
307                continue;
308            }
309            match holds_self(typing, op, &mut BTreeSet::new()) {
310                true => out.extend(materialized_operands(typing, op)),
311                false => out.push(op),
312            }
313        }
314        out
315    };
316    match typing.value(id) {
317        Value::ClosedForm(_) | Value::SelfAt(_) | Value::Solver(_) | Value::Grid(_) => Vec::new(),
318        Value::Cast(Cast::Sample, source) => vec![*source],
319        Value::Read { source, .. } => vec![*source],
320        Value::Cast(_, source) => sampled(vec![*source]),
321        Value::Op { args, .. } => sampled(args.clone()),
322        Value::Filter {
323            x, cutoff, q, gain, ..
324        } => sampled(vec![*x, *cutoff, *q, *gain]),
325    }
326}
327
328/// Operands before the node, so a run never reads a buffer it has not filled.
329fn dependencies_first(typing: &Typing, id: NodeId, seen: &mut BTreeSet<NodeId>) -> Vec<NodeId> {
330    if !seen.insert(id) {
331        return Vec::new();
332    }
333    let mut out = Vec::new();
334    for operand in materialized_operands(typing, id) {
335        out.extend(dependencies_first(typing, operand, seen));
336    }
337    out.push(id);
338    out
339}
340
341/// Every ref one node reads; `materialized_operands` answers a narrower one.
342pub(crate) fn read_operands(typing: &Typing, id: NodeId) -> Vec<NodeId> {
343    match typing.value(id) {
344        Value::ClosedForm(form) => crate::refs::nodes_in(&form.body),
345        _ if typing.ty(id).is_closed_form() => {
346            let mut out = Vec::new();
347            reads_under(typing, id, &mut BTreeSet::new(), &mut out);
348            out.dedup();
349            out
350        }
351        _ => materialized_operands(typing, id),
352    }
353}
354
355/// A closed-form-typed node that holds no written one still reads refs through its operands.
356fn reads_under(typing: &Typing, id: NodeId, seen: &mut BTreeSet<NodeId>, out: &mut Vec<NodeId>) {
357    if !seen.insert(id) {
358        return;
359    }
360    match typing.value(id) {
361        Value::ClosedForm(form) => out.extend(crate::refs::nodes_in(&form.body)),
362        Value::Read { source, .. } => out.push(*source),
363        Value::Cast(_, source) => read_through(typing, *source, seen, out),
364        Value::Op { args, .. } => {
365            for arg in args {
366                read_through(typing, *arg, seen, out);
367            }
368        }
369        Value::Filter {
370            x, cutoff, q, gain, ..
371        } => {
372            for operand in [x, cutoff, q, gain] {
373                read_through(typing, *operand, seen, out);
374            }
375        }
376        Value::SelfAt(_) | Value::Grid(_) | Value::Solver(_) => {}
377    }
378}
379
380/// A written form under an operand is the term read, whatever transform sits between.
381fn read_through(typing: &Typing, id: NodeId, seen: &mut BTreeSet<NodeId>, out: &mut Vec<NodeId>) {
382    let Value::ClosedForm(_) = typing.value(id) else {
383        return reads_under(typing, id, seen, out);
384    };
385    if seen.insert(id) {
386        out.push(id);
387    }
388}