nmbrs_runtime/scope_synth/for_each.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! [`build_for_each_scope_kernel`] — synthesize the kernel for
5//! a for-each scope.
6//!
7//! Activity-side replacement for
8//! `polydat::iteration::comprehension::synthesize_for_each_scope`. The
9//! comprehension-specific walking lives here; the broad
10//! parent-program cascade is delegated to the shared
11//! [`super::cascade::cascade_parent_into_source`] walker.
12//!
13//! ## What lives here (comprehension-specific)
14//!
15//! - Probe pre-evaluation of clause spec expressions to detect
16//! each iter-var's native type (so the emitted extern uses
17//! the right `u64` / `f64` / `str` / `bool` / `ext`).
18//! - Cross-clause placeholder discovery — earlier iter-vars'
19//! probe values may substitute into later clauses' spec
20//! expressions, surfacing additional names the cascade
21//! needs to resolve.
22//! - Phase-bindings appendage (SRD-13f Push E) — when a phase
23//! carries both `for_each:` and `bindings:`, the bindings
24//! source lives on the for-each scope's kernel.
25//!
26//! ## What's delegated (generic cascade)
27//!
28//! Everything else — parent-output cascade with provenance-
29//! aware inlining, parent-input cascade, workload-params
30//! cascade, local-inclusion-chain inlining — runs through the
31//! shared walker.
32
33use std::collections::HashSet;
34
35use crate::scope_kernel::ScopeKernel;
36use polydat::iteration::comprehension::pre_evaluate_clause;
37use polydat::kernel::ManifestEntry;
38
39use super::cascade::{CascadeInputs, CascadeOutputs, cascade_parent_into_source};
40use super::helpers::{collect_leaf_placeholders, scan_one};
41
42/// Synthesize and compile a Polydat Kernel for a for-each scope.
43///
44/// `bindings` is `[(iter_var, spec_expr)]` per scalar variable
45/// (parallel-iter clauses contribute one entry per scalar).
46/// `parent_manifest` describes the parent kernel's typed
47/// outputs (use `polydat::kernel::extract_manifest` on the
48/// parent's program). `parent_kernel` provides the in-scope
49/// name space for clause pre-evaluation.
50/// `phase_bindings` is optional Polydat source folded in after the
51/// extern cascade (SRD-13f Push E — when a phase declares both
52/// `for_each:` and `bindings:`, the bindings live on this scope).
53///
54/// Returns a kernel with:
55/// - One extern per iter-var, typed via probe pre-evaluation.
56/// - Cascade-extern declarations for every parent-visible
57/// name the spec expressions reference and the parent
58/// exposes.
59/// - `materialize_wiring_from_outer(parent)` already called.
60/// - Parent input-slot values propagated via
61/// `polydat::kernel::propagate_inputs` ([`ScopeKernel::synthesize_under`]).
62///
63/// The caller's responsibility: per-iteration, install the
64/// tuple's typed values on this kernel's input slots before
65/// evaluating children.
66#[allow(clippy::too_many_arguments)]
67pub fn build_for_each_scope_kernel(
68 bindings: &[(String, String)],
69 parent_manifest: &[ManifestEntry],
70 parent_kernel: &ScopeKernel,
71 workload_params: &std::collections::HashMap<String, String>,
72 polydat_lib_paths: Vec<std::path::PathBuf>,
73 workload_dir: Option<&std::path::Path>,
74 strict: bool,
75 context: &str,
76 phase_bindings: Option<&str>,
77) -> Result<ScopeKernel, String> {
78 let iter_vars: Vec<String> = bindings.iter().map(|(v, _)| v.clone()).collect();
79 let spec_exprs: Vec<String> = bindings.iter().map(|(_, e)| e.clone()).collect();
80
81 let mut source = String::new();
82 let mut emitted: HashSet<String> = HashSet::new();
83 let mut inherited_names: Vec<String> = Vec::new();
84
85 // Probe each clause's spec expression to detect the iter-
86 // var's native Polydat type and discover any additional
87 // placeholders that surface after earlier-iter-vars'
88 // values substitute into later specs.
89 //
90 // `probes` holds the first probe-value per iter-var (used
91 // for cross-clause substitution); `all_referenced` accumulates
92 // every placeholder discovered along the way.
93 let mut probes: std::collections::HashMap<String, String> = std::collections::HashMap::new();
94 let mut all_referenced: HashSet<String> = collect_leaf_placeholders(&spec_exprs);
95 for (idx, var) in iter_vars.iter().enumerate() {
96 if emitted.contains(var) {
97 continue;
98 }
99 let spec_text = spec_exprs.get(idx).map(String::as_str).unwrap_or("");
100 // A clause that fails to probe is an error with its own
101 // diagnostic — unless it reads a name the parent declares
102 // but can't value yet (an outer for_each's iter-var), which
103 // only gets a value per iteration. See
104 // [`probe_waits_on_outer_iteration`].
105 let values = match pre_evaluate_clause(spec_text, parent_kernel, workload_params, &probes) {
106 Ok(values) => values,
107 Err(_)
108 if probe_waits_on_outer_iteration(
109 spec_text,
110 parent_kernel,
111 workload_params,
112 &probes,
113 ) =>
114 {
115 Vec::new()
116 }
117 Err(e) => return Err(format!("{context}: for_each `{var} in {spec_text}`: {e}")),
118 };
119 // No probe value — an empty source (zero iterations) or one
120 // that waits on an outer iteration — declares `str`: the
121 // clause's text is interpolated per iteration, so its
122 // values arrive as strings.
123 let detected_type = values
124 .first()
125 .map(polydat::ast::Value::port_type)
126 .unwrap_or(polydat::ast::PortType::Str);
127 source.push_str(&format!("extern {var}: {detected_type}\n"));
128 emitted.insert(var.clone());
129
130 // Discover placeholders that emerge after substituting
131 // this iter-var's first value into later specs.
132 for v in &values {
133 let v_str = v.to_display_string();
134 for next_spec in &spec_exprs[idx + 1..] {
135 let mut substituted = next_spec.clone();
136 substituted = substituted.replace(&format!("{{{var}}}"), &v_str);
137 let mut emergent = HashSet::new();
138 scan_one(&substituted, &mut emergent);
139 all_referenced.extend(emergent);
140 }
141 }
142 if let Some(first) = values.into_iter().next() {
143 probes.insert(var.clone(), first.to_display_string());
144 }
145 }
146
147 // The iter-vars are pre-emitted; we don't want the cascade
148 // to re-emit them.
149 let pre_emitted: HashSet<String> = iter_vars.iter().cloned().collect();
150 // Drive the shared cascade walker. include_referenced_cascade
151 // is true for for_each — its spec expressions are narrow
152 // Polydat source where every referenced name needs an extern.
153 cascade_parent_into_source(
154 CascadeInputs {
155 parent_kernel,
156 workload_params,
157 parent_manifest,
158 referenced: &all_referenced,
159 pre_emitted: &pre_emitted,
160 shadow_names: &pre_emitted,
161 include_referenced_cascade: true,
162 },
163 CascadeOutputs {
164 source: &mut source,
165 emitted: &mut emitted,
166 inherited_names: &mut inherited_names,
167 },
168 );
169
170 // SRD-13f Push E — append phase-level `bindings:` source
171 // after the extern cascade. Phase bindings can reference
172 // iter vars (now externs above) and any cascaded parent
173 // name; the Polydat compiler resolves both.
174 if let Some(body) = phase_bindings {
175 let trimmed = body.trim();
176 if !trimmed.is_empty() {
177 if !source.ends_with('\n') && !source.is_empty() {
178 source.push('\n');
179 }
180 source.push_str(body);
181 if !source.ends_with('\n') {
182 source.push('\n');
183 }
184 }
185 }
186
187 if source.is_empty() {
188 source.push_str("const __empty := 0\n");
189 }
190
191 // SRD-67 Phase 3 — finalize through the SubcontextBuilder
192 // bridge. The for_each synthesiser threads polydat_lib_paths /
193 // workload_dir / strict through CompileOptions so the
194 // underlying compile invocation matches the legacy call.
195 let compile_options = polydat::kernel::subcontext::CompileOptions {
196 workload_dir: workload_dir.map(|p| p.to_path_buf()),
197 polydat_lib_paths,
198 strict,
199 required_outputs: Vec::new(),
200 context_label: Some(context.to_string()),
201 cursor_limit: None,
202 ..Default::default()
203 };
204 crate::scope_kernel::ScopeKernel::synthesize_under(
205 parent_kernel,
206 crate::scope_kernel::SourceMatter::source(context, source, compile_options)
207 .inherited(inherited_names),
208 )
209 .map_err(|e| format!("{context}: for_each scope synthesis: {e}"))
210}
211
212/// Whether a clause that failed to probe is waiting on an outer
213/// iteration rather than wrong: it references (as a `{name}`
214/// placeholder or as a bare-identifier source) a name the parent
215/// kernel declares but has no value for at synthesis, and that no
216/// earlier clause probe or workload param supplies. That is an
217/// outer for_each's iter-var: its value is installed per
218/// iteration, so the clause can only be evaluated then.
219///
220/// Any other failure — a malformed spec, a name nothing declares —
221/// is not deferred, and the caller reports it.
222fn probe_waits_on_outer_iteration(
223 spec_text: &str,
224 parent_kernel: &ScopeKernel,
225 workload_params: &std::collections::HashMap<String, String>,
226 probes: &std::collections::HashMap<String, String>,
227) -> bool {
228 let mut names = collect_leaf_placeholders(&[spec_text.to_string()]);
229 let bare = spec_text.trim();
230 if !bare.is_empty() && bare.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
231 names.insert(bare.to_string());
232 }
233 let kernel = parent_kernel.kernel();
234 names.iter().any(|name| {
235 !probes.contains_key(name)
236 && !workload_params.contains_key(name)
237 && parent_kernel.lookup(name).is_none()
238 && (kernel.input_port_type(name).is_some() || kernel.output_type(name).is_some())
239 })
240}
241
242#[cfg(test)]
243mod tests {
244 use super::build_for_each_scope_kernel;
245 use crate::scope_kernel::ScopeKernel;
246 use polydat::ast::PortType;
247 use std::collections::HashMap;
248
249 fn synth(parent: &ScopeKernel, var: &str, spec: &str) -> Result<ScopeKernel, String> {
250 build_for_each_scope_kernel(
251 &[(var.to_string(), spec.to_string())],
252 &[],
253 parent,
254 &HashMap::new(),
255 Vec::new(),
256 None,
257 false,
258 "test_for_each",
259 None,
260 )
261 }
262
263 /// A source nothing declares fails at synthesis with the clause
264 /// and polydat's own diagnostic, instead of typing the iter-var
265 /// as a string and failing later on a type mismatch.
266 #[test]
267 fn unresolvable_clause_fails_with_its_own_diagnostic() {
268 let parent = ScopeKernel::compile("\n").unwrap();
269 for (spec, why) in [
270 ("nope_values", "did not resolve"),
271 ("pre_{nobody}", "unresolved placeholder"),
272 ] {
273 let err = synth(&parent, "k", spec).expect_err("must fail at synthesis");
274 assert!(
275 err.contains(&format!("for_each `k in {spec}`")) && err.contains(why),
276 "{spec}: {err}"
277 );
278 }
279 }
280
281 /// A clause reading an outer for_each's iter-var — declared by
282 /// the parent, valued only per iteration — is deferred, and its
283 /// iter-var is declared `str`.
284 #[test]
285 fn clause_on_an_outer_iter_var_waits_for_the_iteration() {
286 let parent = ScopeKernel::compile("extern outer: str\n").unwrap();
287 let kernel = synth(&parent, "inner", "pre_{outer}").expect("deferred, not an error");
288 assert_eq!(
289 kernel.kernel().input_port_type("inner"),
290 Some(PortType::Str)
291 );
292 }
293}