Skip to main content

nmbrs_runtime/scope_synth/
helpers.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Surface #7 helpers — pure utilities for translating between
5//! typed runtime values and Polydat source-text form.
6//!
7//! These functions encode nmbrs-runtime's Polydat source conventions:
8//! - how a [`polydat::ast::Value`] becomes a fold-eligible GK
9//!   literal,
10//! - how a workload-param string becomes a quoted-or-numeric GK
11//!   literal,
12//! - how a [`polydat::ast::PortType`] becomes an `extern`
13//!   declaration type name,
14//! - how `{name}` placeholders are scanned out of clause / body
15//!   text.
16//!
17//! They're pure functions with no comprehension- or scope-
18//! specific knowledge; the scope builders import them as walking
19//! primitives. The polydat side retains parallel copies during
20//! the cutover (still used by `polydat::iteration::comprehension::synthesize_for_each_scope`);
21//! those copies retire when the legacy synthesis module is
22//! deleted at the end of PR 9c-1b.
23
24use std::collections::HashSet;
25
26use polydat::ast::{PortType, Value};
27
28/// The `extern` type a scope declares for a workload-param string
29/// value: the type of the literal the workload params kernel emits for
30/// it (`crate::params::render_workload_params_source`), which is
31/// the parent every such extern reads through. The two must agree, or
32/// the binding is refused at construction.
33///
34/// Numeric values are `u64` / `f64`; everything else, `true` and
35/// `false` included, is a string literal there and so `str` here.
36/// The type prints as its keyword where the declaration is written.
37pub fn workload_param_port_type(value: &str) -> PortType {
38    let trimmed = value.trim();
39    if trimmed.parse::<u64>().is_ok() {
40        PortType::U64
41    } else if trimmed.parse::<f64>().is_ok() {
42        PortType::F64
43    } else {
44        PortType::Str
45    }
46}
47
48/// Format a typed [`Value`] as a Polydat source literal — strict
49/// variant. Returns `None` when the value isn't representable as
50/// a literal (`Bytes`, `Json`, `Ext`, `Handle`, vectors). Used
51/// by the for_each scope synthesizer when inlining const-folded
52/// parent outputs; falls back to extern cascade in `None` cases.
53pub fn format_value_as_final_literal(v: &Value) -> Option<String> {
54    match v {
55        Value::U64(n) => Some(n.to_string()),
56        Value::F64(f) => {
57            if f.fract() == 0.0 && f.is_finite() {
58                Some(format!("{f:.1}"))
59            } else {
60                Some(format!("{f}"))
61            }
62        }
63        Value::Bool(b) => Some(b.to_string()),
64        Value::Str(s) => {
65            let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
66            Some(format!("\"{escaped}\""))
67        }
68        _ => None,
69    }
70}
71
72/// Format a typed [`Value`] as a Polydat source literal.
73///
74/// Used when emitting `final <name> := <literal>` lines for
75/// per-iteration scope synthesis. Falls back to a quoted-display
76/// form for non-scalar variants (acceptable for iter-vars, which
77/// are scalar in practice).
78pub fn format_value_as_polydat_literal(v: &Value) -> String {
79    match v {
80        Value::U64(n) => n.to_string(),
81        Value::F64(f) => {
82            // Always include decimal point so the parser sees an
83            // f64 literal, not an integer.
84            if f.fract() == 0.0 && f.is_finite() {
85                format!("{f:.1}")
86            } else {
87                format!("{f}")
88            }
89        }
90        Value::Bool(b) => b.to_string(),
91        Value::Str(s) => {
92            let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
93            format!("\"{escaped}\"")
94        }
95        _ => {
96            let display = v.to_display_string();
97            let escaped = display.replace('\\', "\\\\").replace('"', "\\\"");
98            format!("\"{escaped}\"")
99        }
100    }
101}
102
103/// Format a workload-param string value as a Polydat literal.
104///
105/// Numeric inputs pass through untouched; non-numeric inputs get
106/// wrapped in double quotes (with `\` / `"` escaping). The lexer
107/// has no boolean token kind, so a bare `false` would parse as
108/// an identifier (wire reference) and break kernel compilation;
109/// this routes through the string path.
110pub fn format_workload_param_as_polydat_literal(value: &str) -> String {
111    let trimmed = value.trim();
112    if trimmed.parse::<u64>().is_ok() || trimmed.parse::<f64>().is_ok() {
113        trimmed.to_string()
114    } else {
115        let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
116        format!("\"{escaped}\"")
117    }
118}
119
120/// Convert a scalar [`Value`] to its workload-param string form.
121///
122/// Returns `None` for non-scalar variants (vectors, JSON,
123/// handles, bytes, ext) — those aren't representable as GK
124/// source literals.
125pub fn value_to_param_string(v: &Value) -> Option<String> {
126    match v {
127        Value::U64(n) => Some(n.to_string()),
128        Value::F64(n) => Some(n.to_string()),
129        Value::Bool(b) => Some(b.to_string()),
130        Value::Str(s) => Some(s.to_string()),
131        _ => None,
132    }
133}
134
135/// Collect every leaf `{name}` placeholder from a list of clause
136/// spec texts.
137///
138/// "Leaf" means a `{...}` whose body contains no further `{` —
139/// the dynamic case (`{a_{b}_c}`) is handled at runtime by the
140/// iterative interpolator. Honors `\{` / `\}` escapes (same
141/// escape syntax `interpolate` uses).
142pub fn collect_leaf_placeholders(texts: &[String]) -> HashSet<String> {
143    let mut out = HashSet::new();
144    for text in texts {
145        scan_one(text, &mut out);
146    }
147    out
148}
149
150/// Scan one text for leaf `{name}` placeholders, inserting each
151/// into `out`. Companion to [`collect_leaf_placeholders`] for
152/// callers that already have a [`HashSet`] to grow incrementally.
153pub fn scan_one(text: &str, out: &mut HashSet<String>) {
154    let bytes = text.as_bytes();
155    let n = bytes.len();
156    let mut i = 0;
157    while i < n {
158        if bytes[i] == b'\\' && i + 1 < n && (bytes[i + 1] == b'{' || bytes[i + 1] == b'}') {
159            i += 2;
160            continue;
161        }
162        if bytes[i] == b'{' {
163            let mut j = i + 1;
164            let mut nested = false;
165            while j < n {
166                if bytes[j] == b'\\' && j + 1 < n && (bytes[j + 1] == b'{' || bytes[j + 1] == b'}')
167                {
168                    j += 2;
169                    continue;
170                }
171                if bytes[j] == b'{' {
172                    nested = true;
173                    break;
174                }
175                if bytes[j] == b'}' {
176                    break;
177                }
178                j += 1;
179            }
180            if !nested && j < n && bytes[j] == b'}' {
181                let name = &text[i + 1..j];
182                if !name.is_empty() {
183                    out.insert(name.to_string());
184                }
185                i = j + 1;
186                continue;
187            }
188            i += 1;
189            continue;
190        }
191        i += 1;
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    #[test]
200    fn workload_param_port_type_classifies_basic_scalars() {
201        assert_eq!(workload_param_port_type("42"), PortType::U64);
202        assert_eq!(workload_param_port_type("3.14"), PortType::F64);
203        assert_eq!(workload_param_port_type("true"), PortType::Str);
204        assert_eq!(workload_param_port_type("false"), PortType::Str);
205        assert_eq!(workload_param_port_type("hello"), PortType::Str);
206    }
207
208    /// Every class of param value is declared with the type the
209    /// params kernel actually gives it, so a descendant's extern
210    /// always binds (regression: `enable_hierarchy: "false"` was
211    /// declared `bool` over a `str` parent and refused every run).
212    #[test]
213    fn workload_param_port_type_matches_the_params_kernel() {
214        let params: std::collections::HashMap<String, String> = [
215            ("count", "100"),
216            ("ratio", "0.95"),
217            ("flag_t", "true"),
218            ("flag_f", "false"),
219            ("name", "example"),
220        ]
221        .into_iter()
222        .map(|(k, v)| (k.to_string(), v.to_string()))
223        .collect();
224        let kernel = crate::params::build_workload_params_kernel(&params).unwrap();
225        for (name, value) in &params {
226            let produced = kernel
227                .lookup(name)
228                .unwrap_or_else(|| panic!("{name} must resolve"))
229                .port_type();
230            assert_eq!(
231                workload_param_port_type(value),
232                produced,
233                "{name} = {value}"
234            );
235        }
236    }
237
238    #[test]
239    fn format_value_as_polydat_literal_renders_scalars() {
240        assert_eq!(format_value_as_polydat_literal(&Value::U64(42)), "42");
241        assert_eq!(format_value_as_polydat_literal(&Value::Bool(true)), "true");
242        assert_eq!(
243            format_value_as_polydat_literal(&Value::Str("x".into())),
244            "\"x\""
245        );
246        // f64 with integral value still gets decimal point so the
247        // parser doesn't see it as u64.
248        assert_eq!(format_value_as_polydat_literal(&Value::F64(2.0)), "2.0");
249    }
250
251    #[test]
252    fn format_workload_param_quotes_non_numeric() {
253        assert_eq!(format_workload_param_as_polydat_literal("42"), "42");
254        assert_eq!(
255            format_workload_param_as_polydat_literal("hello"),
256            "\"hello\""
257        );
258        // Bool string routes through quoted path (lexer has no
259        // bool keyword).
260        assert_eq!(format_workload_param_as_polydat_literal("true"), "\"true\"");
261    }
262
263    #[test]
264    fn value_to_param_string_handles_scalars_only() {
265        assert_eq!(value_to_param_string(&Value::U64(7)), Some("7".to_string()));
266        assert_eq!(
267            value_to_param_string(&Value::Str("y".into())),
268            Some("y".to_string())
269        );
270        // Non-scalar variants return None — caller falls back.
271        assert_eq!(value_to_param_string(&Value::None), None);
272    }
273
274    #[test]
275    fn collect_leaf_placeholders_extracts_simple_names() {
276        let names = collect_leaf_placeholders(&[
277            "k in 1..{n}".to_string(),
278            "{profile} matches {prefix}".to_string(),
279        ]);
280        assert!(names.contains("n"));
281        assert!(names.contains("profile"));
282        assert!(names.contains("prefix"));
283    }
284
285    #[test]
286    fn collect_leaf_placeholders_skips_nested() {
287        // Dynamic `{a_{b}_c}` form — outer placeholder skipped
288        // (resolved at runtime), inner is extracted.
289        let names = collect_leaf_placeholders(&["{a_{b}_c}".to_string()]);
290        assert!(names.contains("b"));
291        assert!(!names.contains("a_{b}_c"));
292    }
293
294    #[test]
295    fn collect_leaf_placeholders_honors_escapes() {
296        let names = collect_leaf_placeholders(&["\\{not_a_placeholder\\}".to_string()]);
297        assert!(names.is_empty());
298    }
299}