Skip to main content

nmbrs_workload/
inline.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Inline workload synthesis from the `op=` command-line parameter.
5//!
6//! Parses an inline op template string into a [`Workload`] — the same
7//! type that [`parse_workload()`](crate::parse::parse_workload) returns
8//! from YAML. Inline `{{expr}}` bindings are extracted, assigned
9//! synthetic Polydat output names, and compiled to a Polydat source block.
10//!
11//! See SRD 35 for design details.
12
13use std::collections::HashMap;
14
15use crate::model::{BindingsDef, ParsedOp, Workload};
16
17/// Synthesize a [`Workload`] from an inline `op=` string.
18///
19/// # Inline binding syntax
20///
21/// - `{{expr}}` — inline Polydat expression. Compiled into the GK
22///   kernel at init time, then invoked per cycle like any other
23///   Polydat output. Extracted and replaced with `{__inline_N}`.
24/// - `{name}` — reference bind point, resolved by the standard
25///   bind point pipeline (GK output, coordinate, capture).
26///
27/// # Multiple ops
28///
29/// Semicolons separate multiple ops. An optional `N:` prefix sets
30/// the ratio:
31///
32/// ```text
33/// "3:read {{cycle}};1:write {{mod(cycle, 100)}}"
34/// ```
35///
36/// # Examples
37///
38/// ```
39/// use nmbrs_workload::inline::synthesize_inline_workload;
40///
41/// let w = synthesize_inline_workload("hello {{cycle}}").unwrap();
42/// assert_eq!(w.ops.len(), 1);
43/// assert_eq!(w.ops[0].name, "inline_0");
44/// ```
45pub fn synthesize_inline_workload(op_template: &str) -> Result<Workload, String> {
46    if op_template.trim().is_empty() {
47        return Err("op= value is empty".into());
48    }
49
50    // Polydat bindings-block form: `op='a := ...; b := ...'`. When the
51    // whole value is a set of `name := expr` assignments that compiles
52    // as valid Polydat, treat it as a bindings block whose binding
53    // names become the op's fields — so any adapter consumes the named
54    // outputs (stdout prints them, plotter plots them). Falls through
55    // to the text-template form when it isn't valid Polydat.
56    if let Some(w) = try_polydat_block_workload(op_template) {
57        return Ok(w);
58    }
59
60    // Split on unquoted semicolons into individual op segments.
61    let segments = split_ops(op_template);
62
63    // Collect all inline expressions across all segments to build
64    // a single shared Polydat source block.
65    let mut inline_exprs: Vec<String> = Vec::new();
66    let mut expr_index: HashMap<String, usize> = HashMap::new();
67
68    // First pass: discover all inline expressions across all segments:
69    // `{{expr}}`, `{:=expr}`, `{:=expr:=}` and a `{expr}` group the
70    // bind-point scanner reads as an expression.
71    for seg in &segments {
72        for bp in crate::bindpoints::extract_bind_points(&seg.template)? {
73            if let crate::bindpoints::BindPoint::InlineDefinition(expr) = bp
74                && !expr_index.contains_key(&expr)
75            {
76                let idx = inline_exprs.len();
77                expr_index.insert(expr.clone(), idx);
78                inline_exprs.push(expr);
79            }
80        }
81    }
82
83    // Build Polydat source. The `input cycle: u64` line is always emitted
84    // for inline mode: `cycle` is the wire name CLI users reference
85    // (via `{cycle}` placeholders) without writing any explicit
86    // bindings block, so the inline parser makes that convention
87    // explicit in the generated model. Without this declaration the
88    // workload-level placeholder validator can't see `cycle` as a
89    // known wire name and rejects `{cycle}` as undeclared.
90    let mut polydat_source = String::from("input cycle: u64\n");
91    for (i, expr) in inline_exprs.iter().enumerate() {
92        polydat_source.push_str(&format!("__inline_{i} := {expr}\n"));
93    }
94
95    // Second pass: rewrite templates and build ParsedOps.
96    let mut ops = Vec::with_capacity(segments.len());
97    for (i, seg) in segments.iter().enumerate() {
98        let rewritten = rewrite_template(&seg.template, &expr_index);
99
100        let mut op = ParsedOp::simple(&format!("inline_{i}"), &rewritten);
101
102        if seg.ratio != 1 {
103            op.params.insert(
104                "ratio".to_string(),
105                serde_json::Value::Number(serde_json::Number::from(seg.ratio)),
106            );
107        }
108
109        op.tags.insert("name".to_string(), op.name.clone());
110        op.tags.insert("op".to_string(), op.name.clone());
111        op.tags.insert("block".to_string(), "inline".to_string());
112
113        op.bindings = BindingsDef::PolydatSource(polydat_source.clone());
114
115        ops.push(op);
116    }
117
118    Ok(Workload {
119        description: Some("inline workload".into()),
120        scenarios: HashMap::new(),
121        stop_when: Vec::new(),
122        ops,
123        bindings: crate::model::BindingsDef::default(),
124        params: HashMap::new(),
125        phases: HashMap::new(),
126        phase_order: Vec::new(),
127        declared_params: Vec::new(),
128        report: crate::report::Report::default(),
129        report_warnings: Vec::new(),
130        resolution_warnings: Vec::new(),
131        scenario_parse_errors: Vec::new(),
132        status_metrics: Vec::new(),
133        readouts: crate::model::ReadoutsBindings::default(),
134        wrappers: None,
135        implements: None,
136        stick_session: None,
137    })
138}
139
140// ─── Polydat-block form ─────────────────────────────────────
141
142/// Interpret `op=` as a Polydat program when it is one. The rule is
143/// uniform — there are no special syntactic cases for `name := …`
144/// vs `{…}` vs a bare expression: a candidate Polydat source is built
145/// and handed to the compiler, and if it compiles, that's a Polydat
146/// block. Its compiled OUTPUTS become the op's fields, so every
147/// adapter consumes them (stdout prints them, plotter plots them).
148/// Returns `None` when it doesn't compile, so the caller falls back
149/// to the text-template form (which still resolves `{ref}` /
150/// `{{expr}}` interpolation, i.e. the string-composite form).
151fn try_polydat_block_workload(op_template: &str) -> Option<Workload> {
152    let source = build_polydat_candidate(op_template);
153    // The compiler is the sole arbiter of "is this Polydat?".
154    polydat::dsl::compile::compile_polydat(&source).ok()?;
155    // Fields are the declared wire names (`name := …`) — taken from the
156    // source, since the compiler mangles *output* names with `__anon`
157    // suffixes whereas the wires keep their declared names (what
158    // `{name}` placeholders resolve against).
159    let names = binding_wire_names(&source);
160    if names.is_empty() {
161        return None;
162    }
163    let mut op_fields: HashMap<String, serde_json::Value> = HashMap::new();
164    for n in &names {
165        // `{name}` resolves to wire `name` via the adapter's
166        // `resolve_op_fields_via_wires`.
167        op_fields.insert(n.clone(), serde_json::Value::String(format!("{{{n}}}")));
168    }
169    let mut op = ParsedOp::simple("inline_0", "");
170    op.op = op_fields;
171    op.bindings = BindingsDef::PolydatSource(source);
172    op.tags.insert("name".to_string(), "inline_0".to_string());
173    op.tags.insert("op".to_string(), "inline_0".to_string());
174    op.tags.insert("block".to_string(), "inline".to_string());
175
176    Some(Workload {
177        description: Some("inline polydat workload".into()),
178        scenarios: HashMap::new(),
179        stop_when: Vec::new(),
180        ops: vec![op],
181        bindings: crate::model::BindingsDef::default(),
182        params: HashMap::new(),
183        phases: HashMap::new(),
184        phase_order: Vec::new(),
185        declared_params: Vec::new(),
186        report: crate::report::Report::default(),
187        report_warnings: Vec::new(),
188        resolution_warnings: Vec::new(),
189        scenario_parse_errors: Vec::new(),
190        status_metrics: Vec::new(),
191        readouts: crate::model::ReadoutsBindings::default(),
192        wrappers: None,
193        implements: None,
194        stick_session: None,
195    })
196}
197
198/// Build a candidate Polydat source from an `op=` spec: split on
199/// top-level `;` into statements, declare `cycle`, and give any bare
200/// trailing expression an `out :=` so the program has an output. An
201/// already-complete `name := …` statement is kept verbatim. This is
202/// pure source construction — whether the result is Polydat is decided
203/// by the compiler, not by inspecting the shape here.
204fn build_polydat_candidate(op_template: &str) -> String {
205    let segs: Vec<String> = split_top_level_semicolons(op_template)
206        .into_iter()
207        .map(|s| s.trim().to_string())
208        .filter(|s| !s.is_empty())
209        .collect();
210    let mut lines = vec!["input cycle: u64".to_string()];
211    let last = segs.len().saturating_sub(1);
212    for (i, seg) in segs.iter().enumerate() {
213        if has_top_level_assignment(seg) {
214            lines.push(seg.clone());
215        } else if i == last {
216            lines.push(format!("out := {seg}"));
217        } else {
218            lines.push(format!("__expr_{i} := {seg}"));
219        }
220    }
221    lines.join("\n") + "\n"
222}
223
224/// Declared wire names from a built candidate source: the LHS
225/// identifier of each `name := …` line (last whitespace token, so
226/// `const x` → `x`), skipping the `input` line and internal
227/// `__`-prefixed wraps.
228pub(crate) fn binding_wire_names(source: &str) -> Vec<String> {
229    source
230        .lines()
231        .filter_map(|line| {
232            let line = line.trim();
233            if line.starts_with("input ") || !line.contains(":=") {
234                return None;
235            }
236            let lhs = line.split(":=").next()?.trim();
237            let name = lhs.split_whitespace().last()?;
238            let is_ident = !name.is_empty()
239                && name.chars().all(|c| c.is_alphanumeric() || c == '_')
240                && name
241                    .chars()
242                    .next()
243                    .is_some_and(|c| c.is_alphabetic() || c == '_');
244            if is_ident && !name.starts_with("__") {
245                Some(name.to_string())
246            } else {
247                None
248            }
249        })
250        .collect()
251}
252
253/// True when `s` contains a `:=` at brace-depth 0 (a real statement
254/// boundary, not one buried inside `{{expr}}` / `{ref}`).
255fn has_top_level_assignment(s: &str) -> bool {
256    let bytes = s.as_bytes();
257    let mut depth = 0i32;
258    let mut i = 0;
259    while i < bytes.len() {
260        match bytes[i] {
261            b'{' => depth += 1,
262            b'}' => depth = (depth - 1).max(0),
263            b':' if depth == 0 && i + 1 < bytes.len() && bytes[i + 1] == b'=' => {
264                return true;
265            }
266            _ => {}
267        }
268        i += 1;
269    }
270    false
271}
272
273/// Split `s` on `;` at brace-depth 0.
274fn split_top_level_semicolons(s: &str) -> Vec<String> {
275    let mut out = Vec::new();
276    let mut cur = String::new();
277    let mut depth = 0i32;
278    for c in s.chars() {
279        match c {
280            '{' => {
281                depth += 1;
282                cur.push(c);
283            }
284            '}' => {
285                depth = (depth - 1).max(0);
286                cur.push(c);
287            }
288            ';' if depth == 0 => {
289                out.push(std::mem::take(&mut cur));
290            }
291            _ => cur.push(c),
292        }
293    }
294    if !cur.trim().is_empty() {
295        out.push(cur);
296    }
297    out
298}
299
300// ─── Internal Types ─────────────────────────────────────────
301
302struct OpSegment {
303    template: String,
304    ratio: u64,
305}
306
307// ─── Helpers ────────────────────────────────────────────────
308
309/// Split an op string on unquoted semicolons, extracting optional
310/// ratio prefixes (`3:template`).
311fn split_ops(input: &str) -> Vec<OpSegment> {
312    let mut segments = Vec::new();
313    let mut current = String::new();
314    let mut in_braces = 0u32;
315
316    for c in input.chars() {
317        match c {
318            '{' => {
319                in_braces += 1;
320                current.push(c);
321            }
322            '}' => {
323                in_braces = in_braces.saturating_sub(1);
324                current.push(c);
325            }
326            ';' if in_braces == 0 => {
327                let seg = current.trim().to_string();
328                if !seg.is_empty() {
329                    segments.push(parse_segment(&seg));
330                }
331                current.clear();
332            }
333            _ => current.push(c),
334        }
335    }
336    let seg = current.trim().to_string();
337    if !seg.is_empty() {
338        segments.push(parse_segment(&seg));
339    }
340    segments
341}
342
343/// Parse a single segment, extracting an optional `N:` ratio prefix.
344fn parse_segment(s: &str) -> OpSegment {
345    // Look for `N:` at the start, but don't confuse with `{{...}}`.
346    if let Some(colon_pos) = s.find(':') {
347        let prefix = &s[..colon_pos];
348        // Only treat as ratio if prefix is all digits.
349        if !prefix.is_empty()
350            && prefix.chars().all(|c| c.is_ascii_digit())
351            && let Ok(ratio) = prefix.parse::<u64>()
352        {
353            return OpSegment {
354                template: s[colon_pos + 1..].trim().to_string(),
355                ratio,
356            };
357        }
358    }
359    OpSegment {
360        template: s.to_string(),
361        ratio: 1,
362    }
363}
364
365/// Rewrite a template by replacing each inline expression with
366/// `{__inline_N}`.
367fn rewrite_template(template: &str, expr_index: &HashMap<String, usize>) -> String {
368    crate::bindpoints::rewrite_inline_definitions(template, |expr| {
369        expr_index.get(expr).map(|idx| format!("__inline_{idx}"))
370    })
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn simple_inline_binding() {
379        let w = synthesize_inline_workload("hello {{cycle}}").unwrap();
380        assert_eq!(w.ops.len(), 1);
381        assert_eq!(w.ops[0].name, "inline_0");
382        let stmt = w.ops[0].op.get("stmt").unwrap().as_str().unwrap();
383        assert_eq!(stmt, "hello {__inline_0}");
384        match &w.ops[0].bindings {
385            BindingsDef::PolydatSource(src) => {
386                assert!(src.contains("input cycle: u64"));
387                assert!(src.contains("__inline_0 := cycle"));
388            }
389            _ => panic!("expected PolydatSource bindings"),
390        }
391    }
392
393    #[test]
394    fn multiple_inline_bindings() {
395        let w = synthesize_inline_workload(
396            "id={{mod(hash(cycle), 100000)}} name={{number_to_words(cycle)}}",
397        )
398        .unwrap();
399        assert_eq!(w.ops.len(), 1);
400        let stmt = w.ops[0].op.get("stmt").unwrap().as_str().unwrap();
401        assert_eq!(stmt, "id={__inline_0} name={__inline_1}");
402        match &w.ops[0].bindings {
403            BindingsDef::PolydatSource(src) => {
404                assert!(src.contains("__inline_0 := mod(hash(cycle), 100000)"));
405                assert!(src.contains("__inline_1 := number_to_words(cycle)"));
406            }
407            _ => panic!("expected PolydatSource bindings"),
408        }
409    }
410
411    #[test]
412    fn bindings_block_op_becomes_polydat_fields() {
413        // A valid Polydat bindings block → one op whose fields are the
414        // bound wire names, each resolved via `{name}`.
415        let w =
416            synthesize_inline_workload("x := cos(to_f64(cycle)); y := sin(to_f64(cycle))").unwrap();
417        assert_eq!(w.ops.len(), 1);
418        let keys: std::collections::BTreeSet<&str> =
419            w.ops[0].op.keys().map(|s| s.as_str()).collect();
420        assert!(keys.contains("x") && keys.contains("y"), "fields: {keys:?}");
421        assert!(!w.ops[0].op.contains_key("stmt"), "should not be a text op");
422        assert_eq!(w.ops[0].op.get("x").unwrap().as_str().unwrap(), "{x}");
423        assert!(matches!(w.ops[0].bindings, BindingsDef::PolydatSource(_)));
424    }
425
426    #[test]
427    fn bare_polydat_expr_becomes_out_field() {
428        let w = synthesize_inline_workload("cos(to_f64(cycle))").unwrap();
429        assert_eq!(w.ops.len(), 1);
430        assert!(
431            w.ops[0].op.contains_key("out"),
432            "fields: {:?}",
433            w.ops[0].op.keys().collect::<Vec<_>>()
434        );
435    }
436
437    #[test]
438    fn invalid_polydat_falls_back_to_text_template() {
439        // Has `:=` but doesn't compile → NOT adopted as Polydat; the
440        // text-template form handles it instead (no panic, one op).
441        let w = synthesize_inline_workload("x := not_a_real_fn(@@@)").unwrap();
442        assert_eq!(w.ops.len(), 1);
443        assert!(w.ops[0].op.contains_key("stmt"));
444    }
445
446    #[test]
447    fn detection_is_compile_driven_not_syntactic() {
448        // `{ref}` composite text isn't valid standalone Polydat → text
449        // template (which still interpolates the ref).
450        let w = synthesize_inline_workload("id-{cycle}").unwrap();
451        assert!(w.ops[0].op.contains_key("stmt"));
452    }
453
454    #[test]
455    fn helpers_split_and_name_bindings() {
456        assert!(has_top_level_assignment("x := 1"));
457        assert!(!has_top_level_assignment("hello {{x := 1}}")); // inside braces
458        assert_eq!(split_top_level_semicolons("a := 1; b := 2").len(), 2);
459        let src = build_polydat_candidate("a := 1; sin(cycle)");
460        assert!(src.contains("a := 1"));
461        assert!(src.contains("out := sin(cycle)")); // bare last → out
462        assert_eq!(
463            binding_wire_names("input cycle: u64\nt := 1\n__expr_0 := 2\nx := 3\n"),
464            vec!["t".to_string(), "x".to_string()]
465        ); // skips input + __
466    }
467
468    #[test]
469    fn no_inline_bindings_plain_text() {
470        let w = synthesize_inline_workload("hello world").unwrap();
471        assert_eq!(w.ops.len(), 1);
472        let stmt = w.ops[0].op.get("stmt").unwrap().as_str().unwrap();
473        assert_eq!(stmt, "hello world");
474        // Inline mode always emits the `input cycle: u64` line so
475        // workloads referencing `{cycle}` validate cleanly. With no
476        // inline expressions the bindings carry just that declaration
477        // and nothing else.
478        let bindings = match &w.ops[0].bindings {
479            crate::model::BindingsDef::PolydatSource(s) => s.clone(),
480            _ => panic!("expected PolydatSource"),
481        };
482        assert_eq!(bindings, "input cycle: u64\n");
483    }
484
485    #[test]
486    fn reference_bind_points_preserved() {
487        let w = synthesize_inline_workload("value={cycle}").unwrap();
488        assert_eq!(w.ops.len(), 1);
489        let stmt = w.ops[0].op.get("stmt").unwrap().as_str().unwrap();
490        assert_eq!(stmt, "value={cycle}");
491        // Same as `no_inline_bindings_plain_text`: a bare `{cycle}`
492        // reference doesn't introduce inline expressions, but the
493        // `input cycle: u64` convention line still gets emitted so
494        // the workload-level placeholder validator recognises the
495        // wire name.
496        let bindings = match &w.ops[0].bindings {
497            crate::model::BindingsDef::PolydatSource(s) => s.clone(),
498            _ => panic!("expected PolydatSource"),
499        };
500        assert_eq!(bindings, "input cycle: u64\n");
501    }
502
503    #[test]
504    fn semicolon_split_multiple_ops() {
505        let w = synthesize_inline_workload("read {{cycle}};write {{mod(cycle, 100)}}").unwrap();
506        assert_eq!(w.ops.len(), 2);
507        assert_eq!(w.ops[0].name, "inline_0");
508        assert_eq!(w.ops[1].name, "inline_1");
509    }
510
511    #[test]
512    fn ratio_prefix() {
513        let w = synthesize_inline_workload("3:read {{cycle}};1:write {{cycle}}").unwrap();
514        assert_eq!(w.ops.len(), 2);
515        assert_eq!(w.ops[0].params.get("ratio").unwrap().as_u64().unwrap(), 3);
516        // ratio=1 is the default, so it's not stored explicitly.
517        assert!(!w.ops[1].params.contains_key("ratio"));
518    }
519
520    #[test]
521    fn ratio_one_not_stored() {
522        let w = synthesize_inline_workload("hello {{cycle}}").unwrap();
523        assert!(!w.ops[0].params.contains_key("ratio"));
524    }
525
526    #[test]
527    fn duplicate_expressions_share_output() {
528        let w = synthesize_inline_workload("a={{hash(cycle)}};b={{hash(cycle)}}").unwrap();
529        // Both ops should reference the same __inline_0.
530        let stmt0 = w.ops[0].op.get("stmt").unwrap().as_str().unwrap();
531        let stmt1 = w.ops[1].op.get("stmt").unwrap().as_str().unwrap();
532        assert_eq!(stmt0, "a={__inline_0}");
533        assert_eq!(stmt1, "b={__inline_0}");
534        match &w.ops[0].bindings {
535            BindingsDef::PolydatSource(src) => {
536                // Only one output for hash(cycle).
537                let count = src.matches("__inline_").count();
538                assert_eq!(count, 1);
539            }
540            _ => panic!("expected PolydatSource"),
541        }
542    }
543
544    #[test]
545    fn empty_op_is_error() {
546        assert!(synthesize_inline_workload("").is_err());
547        assert!(synthesize_inline_workload("   ").is_err());
548    }
549
550    #[test]
551    fn mixed_reference_and_inline() {
552        let w = synthesize_inline_workload("id={{mod(hash(cycle), 1000)}} raw={cycle}").unwrap();
553        let stmt = w.ops[0].op.get("stmt").unwrap().as_str().unwrap();
554        assert_eq!(stmt, "id={__inline_0} raw={cycle}");
555    }
556}