nmbrs_runtime/scope_synth/cascade.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shared cascade walker — the single implementation of "given
5//! a parent kernel, decide what cascade-extern and inline-const
6//! lines to emit for a child scope's Polydat source."
7//!
8//! Pre-walker, each of the four sister scope builders
9//! (`build_phase_scope_kernel`, `build_do_loop_scope_kernel`,
10//! `build_op_template_scope_kernel`, and the forthcoming
11//! `build_for_each_scope_kernel`) reinvented this walk with
12//! subtly different precision. This module consolidates the
13//! walk so:
14//!
15//! 1. The cascade rules live in one place. Bug fixes apply
16//! everywhere.
17//! 2. The most-rigorous version (phase scope's SRD-13f
18//! provenance-aware inlining) becomes the canonical
19//! behavior for every scope kind.
20//! 3. Scope-specific bits stay in the per-scope builder —
21//! each builder contributes only what's unique to it
22//! (body source, iter-var declarations, counter, etc.).
23//!
24//! ## What this walker is NOT for
25//!
26//! `build_op_template_scope_kernel` is intentionally **not**
27//! refactored onto this walker. The op-template uses a
28//! deliberately narrow "lazy cascade" policy — emit externs
29//! only for names the op references, never a broad parent-
30//! output / parent-input sweep. That keeps the op-template
31//! kernel narrow at the cost of more bookkeeping in the
32//! caller. Forcing it onto a broad-cascade walker would
33//! either bloat the walker with op-template-specific knobs or
34//! widen the op-template kernel; neither is desirable. The
35//! op-template stays self-contained.
36//!
37//! ## What the walker does (in order)
38//!
39//! 1. **Coord-set detection.** Walks `parent.program().coord_count()`
40//! and `input_names()` to discover which names are parent-
41//! coord-slots — those propagate via the kernel chain, not via
42//! extern cascade. They're added to a skip set.
43//! 2. **Local-inclusion-chain inline.** For each `referenced`
44//! name that resolves to a non-final cycle binding in the
45//! parent's AST (i.e., would have to be re-computed at this
46//! scope), pretty-prints the parent's inclusion chain and
47//! emits it as local matter. Names included this way are
48//! marked as `emitted`. (SRD-13f §"Wire-reference
49//! classification" case 3.)
50//! 3. **Referenced-name cascade.** For each remaining
51//! `referenced` name, looks it up in `parent_manifest` for
52//! its typed port; emits `extern NAME: TYPE` and marks
53//! inherited.
54//! 4. **Workload-params cascade.** For each entry in
55//! `workload_params` not yet emitted and not pre-emitted,
56//! emits `extern NAME: TYPE` (type detected from value
57//! shape). Marks inherited.
58//! 5. **Parent-output cascade with provenance-aware inlining.**
59//! For each `parent.program().output_names()` not yet
60//! emitted: if the upstream's value is statically known
61//! (provenance == 0), inlines as `const NAME := <literal>`;
62//! otherwise cascades as `extern NAME: TYPE`. (SRD-13f
63//! §"Materialization gradient".)
64//! 6. **Parent-input cascade.** For each
65//! `parent.program().input_names()` not yet emitted, emits
66//! `extern NAME: TYPE`. Closes the chain so cascade-extern'd
67//! inputs propagate transitively.
68//!
69//! ## What the walker does NOT do
70//!
71//! - Emit the scope's own body / iter-var / counter
72//! declarations — those come from the per-scope builder and
73//! are passed in as `pre_emitted` so the walker doesn't
74//! re-emit them.
75//! - Call `finalize` — that's the per-scope builder's
76//! responsibility (it threads scope-specific `CompileOptions`
77//! and context labels).
78
79use std::collections::{HashMap, HashSet};
80
81use crate::scope_kernel::ScopeKernel;
82use polydat::kernel::ManifestEntry;
83
84use super::helpers::{format_value_as_final_literal, workload_param_port_type};
85
86/// Per-scope context the walker needs from its caller.
87///
88/// Each scope-kind builder constructs this with its own pre-
89/// emitted set, referenced-placeholder set, and shadow-name
90/// set, then passes it through to the walker.
91pub struct CascadeInputs<'a> {
92 /// Parent kernel — the chain root for all walks.
93 pub parent_kernel: &'a ScopeKernel,
94 /// Workload params (CLI / params: block defaults).
95 pub workload_params: &'a HashMap<String, String>,
96 /// Typed manifest of the parent's outputs — used to look up
97 /// port types for referenced-name cascade. The runner
98 /// already extracts this for the per-scope synthesisers;
99 /// passing it in saves a re-walk.
100 pub parent_manifest: &'a [ManifestEntry],
101 /// Names referenced in the scope's body / spec exprs (the
102 /// `{name}` placeholders + identifier scan of Polydat body
103 /// source). Drives steps 2 + 3 of the walker.
104 pub referenced: &'a HashSet<String>,
105 /// Names already declared by the per-scope builder before
106 /// the walker runs (iter vars, counter, body-locally-
107 /// declared idents). The walker won't re-emit these.
108 pub pre_emitted: &'a HashSet<String>,
109 /// Additional names the per-scope builder wants to shadow
110 /// from the parent-output cascade — body-locally-declared
111 /// idents that aren't externs. Without this, the cascade
112 /// could re-emit a name the body locally assigns, causing
113 /// a duplicate-binding compile error.
114 pub shadow_names: &'a HashSet<String>,
115 /// Whether to run the referenced-name cascade pass (step
116 /// 3 in the walker's order). do-loop and for-each opt in:
117 /// their bodies are tightly scoped (a condition expression
118 /// or a comprehension spec) where every referenced name is
119 /// expected to flow in as an extern. phase opts out: its
120 /// body is arbitrary Polydat source that may already declare
121 /// the same names as `input` / `extern`, and a step-3
122 /// emission would collide.
123 pub include_referenced_cascade: bool,
124}
125
126/// Per-scope outputs the walker mutates.
127pub struct CascadeOutputs<'a> {
128 /// Polydat source string the walker appends to.
129 pub source: &'a mut String,
130 /// Names the walker has emitted, including any pre-emitted
131 /// names that flowed in via [`CascadeInputs::pre_emitted`].
132 /// Grows across the walk's six steps.
133 pub emitted: &'a mut HashSet<String>,
134 /// Names whose outputs are inherited from a parent (cascade-
135 /// extern'd, not this scope's own iter-coord). The per-scope
136 /// builder threads this into `PolydatMatter::inherited_outputs`
137 /// so `compute_own_coordinates` excludes them when reporting
138 /// this scope's own iteration position.
139 pub inherited_names: &'a mut Vec<String>,
140}
141
142/// Run the shared cascade walk. See module docs for the six
143/// steps and their order.
144pub fn cascade_parent_into_source(inputs: CascadeInputs<'_>, outputs: CascadeOutputs<'_>) {
145 let CascadeInputs {
146 parent_kernel,
147 workload_params,
148 parent_manifest,
149 referenced,
150 pre_emitted,
151 shadow_names,
152 include_referenced_cascade,
153 } = inputs;
154
155 // Seed `emitted` with the caller's pre-emitted set so the
156 // walker's skip predicates respect them.
157 outputs.emitted.extend(pre_emitted.iter().cloned());
158
159 let parent_program = parent_kernel.program();
160
161 // Step 1 — coord-set detection.
162 let coord_names: HashSet<String> = {
163 let coord_count = parent_program.coord_count();
164 parent_program
165 .input_names()
166 .into_iter()
167 .take(coord_count)
168 .collect()
169 };
170
171 // Step 2 — local-inclusion-chain inline.
172 let already_satisfied_for_inclusion: HashSet<String> = pre_emitted
173 .iter()
174 .chain(coord_names.iter())
175 .cloned()
176 .collect();
177 {
178 let mut already_satisfied = already_satisfied_for_inclusion.clone();
179 let mut refs_sorted: Vec<&String> = referenced.iter().collect();
180 refs_sorted.sort();
181 for name in refs_sorted {
182 if already_satisfied.contains(name.as_str()) {
183 continue;
184 }
185 // FINAL/SHARED go through the parent-output cascade
186 // (step 5 handles their emission); only cycle
187 // bindings reach the local-inclusion-chain path.
188 let modifier = parent_program.output_modifier(name);
189 if modifier == polydat::dsl::ast::BindingModifier::CONST
190 || modifier == polydat::dsl::ast::BindingModifier::SHARED
191 {
192 continue;
193 }
194 let chain = parent_program.local_inclusion_chain(name, &already_satisfied);
195 if chain.is_empty() {
196 continue;
197 }
198 for stmt in chain {
199 let line = polydat::dsl::pprint::pp_statement(stmt);
200 outputs.source.push_str(&line);
201 outputs.source.push('\n');
202 if let polydat::dsl::ast::Statement::Binding(b) = stmt {
203 for t in &b.targets {
204 outputs.emitted.insert(t.clone());
205 already_satisfied.insert(t.clone());
206 }
207 }
208 }
209 }
210 }
211
212 // Step 3 — referenced-name cascade against parent_manifest.
213 // Opt-in per scope kind (see `include_referenced_cascade`
214 // doc). Always skips coord names; the kernel chain
215 // propagates those, not extern cascade.
216 if include_referenced_cascade {
217 let manifest_by_name: HashMap<&str, &ManifestEntry> = parent_manifest
218 .iter()
219 .map(|e| (e.name.as_str(), e))
220 .collect();
221 let mut refs_sorted: Vec<&String> = referenced.iter().collect();
222 refs_sorted.sort();
223 for name in refs_sorted {
224 if outputs.emitted.contains(name) {
225 continue;
226 }
227 if pre_emitted.contains(name) {
228 continue;
229 }
230 if coord_names.contains(name) {
231 continue;
232 }
233 if let Some(entry) = manifest_by_name.get(name.as_str()) {
234 outputs
235 .source
236 .push_str(&format!("extern {name}: {}\n", entry.port_type));
237 outputs.emitted.insert(name.clone());
238 outputs.inherited_names.push(name.clone());
239 } else if let Some(value) = workload_params.get(name) {
240 super::cascade_emit::emit_workload_param_chain_aware(
241 name,
242 value,
243 parent_kernel,
244 outputs.source,
245 outputs.emitted,
246 None,
247 );
248 }
249 }
250 } else {
251 // Suppress unused warning when this scope kind opts out.
252 let _ = parent_manifest;
253 }
254
255 // Step 4 — workload-params cascade.
256 for (name, value) in workload_params {
257 if outputs.emitted.contains(name) {
258 continue;
259 }
260 if shadow_names.contains(name) {
261 continue;
262 }
263 let port_type = workload_param_port_type(value);
264 outputs
265 .source
266 .push_str(&format!("extern {name}: {port_type}\n"));
267 outputs.emitted.insert(name.clone());
268 outputs.inherited_names.push(name.clone());
269 }
270
271 // Skip predicate for the parent-output / parent-input passes
272 // — covers everything `emitted` so far + coord names +
273 // internal underscore-prefixed names (with the cursor-extent
274 // auxiliary exception).
275 let skip_cascade = |emitted: &HashSet<String>, name: &str| -> bool {
276 if emitted.contains(name) {
277 return true;
278 }
279 if coord_names.contains(name) {
280 return true;
281 }
282 if name.starts_with("__") && !name.starts_with("__cursor_extent_") {
283 return true;
284 }
285 false
286 };
287
288 // Step 5 — parent-output cascade with provenance-aware
289 // inlining.
290 for name in parent_program.output_names() {
291 let owned = name.to_string();
292 if skip_cascade(outputs.emitted, &owned) {
293 continue;
294 }
295 if shadow_names.contains(&owned) {
296 continue;
297 }
298 // SRD-13f §"Materialization gradient" — only truly-
299 // input-independent values (provenance == 0) are safe
300 // to inline as literals into the cached downstream
301 // program. Everything else cascades as `extern`; per-
302 // activation materialization delivers the correct value.
303 //
304 // A `shared` output is NEVER statically known, whatever its
305 // initializer's provenance: the cell is mutable at runtime
306 // (captures write it). Const-inlining one freezes the
307 // initializer AND makes the child the name's local final,
308 // which `materialize_wiring_from_outer` honors by DROPPING
309 // the ancestral cell — descendants then read the frozen
310 // initializer forever and a writer's update is never
311 // visible to them.
312 let Some(output_idx) = parent_program.output_index(&owned) else {
313 continue;
314 };
315 let (node_idx, port_idx) = parent_program.resolve_output_by_index(output_idx);
316 let is_shared =
317 parent_program.output_modifier(&owned) == polydat::dsl::ast::BindingModifier::SHARED;
318 let upstream_is_statically_known = !is_shared
319 && parent_program
320 .input_provenance_for(node_idx)
321 .is_none_or(|p| p.is_zero());
322 if upstream_is_statically_known
323 && let Some(value) = parent_kernel.lookup(&owned)
324 && let Some(literal) = format_value_as_final_literal(&value)
325 {
326 outputs
327 .source
328 .push_str(&format!("const {owned} := {literal}\n"));
329 outputs.emitted.insert(owned);
330 continue;
331 }
332 let port_type = parent_program.node_meta(node_idx).outs[port_idx].typ;
333 outputs
334 .source
335 .push_str(&format!("extern {owned}: {port_type}\n"));
336 outputs.emitted.insert(owned.clone());
337 outputs.inherited_names.push(owned);
338 }
339
340 // Step 6 — parent-input cascade.
341 for name in parent_program.input_names() {
342 if skip_cascade(outputs.emitted, &name) {
343 continue;
344 }
345 if shadow_names.contains(&name) {
346 continue;
347 }
348 // input_names() returns names that exist as inputs;
349 // input_port_type on the same name therefore can't be
350 // None unless the kernel's program shape is broken.
351 let port_type = parent_program
352 .input_port_type(&name)
353 .expect("input_names() returned a name with no port type");
354 let type_name = port_type.to_keyword();
355 outputs
356 .source
357 .push_str(&format!("extern {name}: {type_name}\n"));
358 outputs.emitted.insert(name.clone());
359 outputs.inherited_names.push(name);
360 }
361}