1use 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
14fn 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
42pub 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 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
84pub 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#[derive(Clone, Debug, Default, PartialEq)]
186pub struct Schedule {
187 pub materialize: Vec<NodeId>,
188 pub symbolic: Vec<NodeId>,
189 pub compose: Vec<NodeId>,
192}
193
194pub 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 if matches!(
205 ask.representation,
206 crate::query::Representation::Bindings
207 | crate::query::Representation::Arguments
208 | crate::query::Representation::Flops
209 ) {
210 continue;
211 }
212 match ask.representation.consumes(typing.ty(id).is_closed_form()) {
213 sva_samples::Consumes::ClosedForm if !compose.contains(&id) => compose.push(id),
214 sva_samples::Consumes::ClosedForm => {}
215 _ => {
216 wanted.insert(id);
217 }
218 }
219 if let crate::query::Representation::Ledger { depth } = ask.representation {
220 attributed(typing, id, depth, &mut wanted);
221 }
222 }
223 if audio || !wanted.is_empty() {
224 wanted.insert(root);
225 }
226
227 let mut reached: BTreeSet<NodeId> = BTreeSet::new();
228 let mut work: Vec<NodeId> = wanted.iter().copied().collect();
229 while let Some(id) = work.pop() {
230 if !reached.insert(id) {
231 continue;
232 }
233 work.extend(materialized_operands(typing, id));
234 }
235
236 let held: Vec<NodeId> = order
237 .groups
238 .concat()
239 .iter()
240 .filter_map(|path| typing.id(path))
241 .collect();
242 let mut materialize: Vec<NodeId> = Vec::new();
243 let mut seen: BTreeSet<NodeId> = BTreeSet::new();
244 for id in held {
245 for member in dependencies_first(typing, id, &mut seen) {
246 if reached.contains(&member) {
247 materialize.push(member);
248 }
249 }
250 }
251 let symbolic = typing
252 .paths()
253 .map(|(_, id)| id)
254 .filter(|id| !materialize.contains(id))
255 .collect();
256 compose.retain(|id| !materialize.contains(id));
257 Schedule {
258 materialize,
259 symbolic,
260 compose,
261 }
262}
263
264fn attributed(typing: &Typing, id: NodeId, depth: usize, wanted: &mut BTreeSet<NodeId>) {
266 let mut seen = BTreeSet::from([id]);
268 let mut level = vec![id];
269 for _ in 0..depth {
270 let mut next = Vec::new();
271 for held in level {
272 for operand in read_operands(typing, held) {
273 if seen.insert(operand) {
274 wanted.insert(operand);
275 next.push(operand);
276 }
277 }
278 }
279 level = next;
280 }
281}
282
283pub(crate) fn holds_self(typing: &Typing, id: NodeId, seen: &mut BTreeSet<NodeId>) -> bool {
286 if !seen.insert(id) {
287 return false;
288 }
289 match typing.value(id) {
290 Value::SelfAt(_) => true,
291 Value::Cast(Cast::Sample, _) | Value::Read { .. } => false,
292 Value::Cast(_, source) => holds_self(typing, *source, seen),
293 Value::Op { args, .. } => args.iter().any(|a| holds_self(typing, *a, seen)),
294 Value::Filter {
295 x, cutoff, q, gain, ..
296 } => [x, cutoff, q, gain]
297 .into_iter()
298 .any(|operand| holds_self(typing, *operand, seen)),
299 Value::ClosedForm(_) | Value::Solver(_) | Value::Grid(_) => false,
300 }
301}
302
303pub(crate) fn materialized_operands(typing: &Typing, id: NodeId) -> Vec<NodeId> {
305 let sampled = |set: Vec<NodeId>| -> Vec<NodeId> {
306 let mut out = Vec::new();
307 for op in set {
308 if typing.ty(op).is_closed_form() || matches!(typing.value(op), Value::Grid(_)) {
309 continue;
310 }
311 match holds_self(typing, op, &mut BTreeSet::new()) {
312 true => out.extend(materialized_operands(typing, op)),
313 false => out.push(op),
314 }
315 }
316 out
317 };
318 match typing.value(id) {
319 Value::ClosedForm(_) | Value::SelfAt(_) | Value::Solver(_) | Value::Grid(_) => Vec::new(),
320 Value::Cast(Cast::Sample, source) => vec![*source],
321 Value::Read { source, .. } => vec![*source],
322 Value::Cast(_, source) => sampled(vec![*source]),
323 Value::Op { args, .. } => sampled(args.clone()),
324 Value::Filter {
325 x, cutoff, q, gain, ..
326 } => sampled(vec![*x, *cutoff, *q, *gain]),
327 }
328}
329
330pub(crate) fn dependencies_first(
332 typing: &Typing,
333 id: NodeId,
334 seen: &mut BTreeSet<NodeId>,
335) -> Vec<NodeId> {
336 if !seen.insert(id) {
337 return Vec::new();
338 }
339 let mut out = Vec::new();
340 for operand in materialized_operands(typing, id) {
341 out.extend(dependencies_first(typing, operand, seen));
342 }
343 out.push(id);
344 out
345}
346
347pub(crate) fn read_operands(typing: &Typing, id: NodeId) -> Vec<NodeId> {
349 match typing.value(id) {
350 Value::ClosedForm(form) => crate::refs::nodes_in(&form.body),
351 _ if typing.ty(id).is_closed_form() => {
352 let mut out = Vec::new();
353 reads_under(typing, id, &mut BTreeSet::new(), &mut out);
354 out.dedup();
355 out
356 }
357 _ => materialized_operands(typing, id),
358 }
359}
360
361fn reads_under(typing: &Typing, id: NodeId, seen: &mut BTreeSet<NodeId>, out: &mut Vec<NodeId>) {
363 if !seen.insert(id) {
364 return;
365 }
366 match typing.value(id) {
367 Value::ClosedForm(form) => out.extend(crate::refs::nodes_in(&form.body)),
368 Value::Read { source, .. } => out.push(*source),
369 Value::Cast(_, source) => read_through(typing, *source, seen, out),
370 Value::Op { args, .. } => {
371 for arg in args {
372 read_through(typing, *arg, seen, out);
373 }
374 }
375 Value::Filter {
376 x, cutoff, q, gain, ..
377 } => {
378 for operand in [x, cutoff, q, gain] {
379 read_through(typing, *operand, seen, out);
380 }
381 }
382 Value::SelfAt(_) | Value::Grid(_) | Value::Solver(_) => {}
383 }
384}
385
386fn read_through(typing: &Typing, id: NodeId, seen: &mut BTreeSet<NodeId>, out: &mut Vec<NodeId>) {
388 let Value::ClosedForm(_) = typing.value(id) else {
389 return reads_under(typing, id, seen, out);
390 };
391 if seen.insert(id) {
392 out.push(id);
393 }
394}