Skip to main content

nmbrs_runtime/
bindings.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Binding expression compiler: parses nosqlbench-style binding chains
5//! into Polydat Kernel node wiring.
6//!
7//! Binding syntax: `FuncA(args); FuncB(args); FuncC(args)`
8//!
9//! This is a semicolon-delimited chain where the output of each
10//! function feeds the input of the next, starting from the `cycle`
11//! coordinate. So `Hash(); Mod(1000000)` becomes:
12//!
13//! ```text
14//! __binding_h_0 := hash(cycle)
15//! binding_name  := mod(__binding_h_0, 1000000)
16//! ```
17
18use std::collections::{HashMap, HashSet};
19
20use crate::scope_kernel::ScopeKernel;
21
22use nmbrs_workload::bindpoints;
23use nmbrs_workload::model::ParsedOp;
24
25/// A parsed function call in a binding chain.
26#[derive(Debug, Clone)]
27struct BindingFunc {
28    name: String,
29    args: Vec<String>,
30}
31
32/// Parse a binding expression into a chain of function calls.
33///
34/// `"Hash(); Mod(1000000)"` → `[BindingFunc{name:"Hash", args:[]}, BindingFunc{name:"Mod", args:["1000000"]}]`
35fn parse_binding_chain(expr: &str) -> Vec<BindingFunc> {
36    let mut funcs = Vec::new();
37
38    for segment in expr.split(';') {
39        let segment = segment.trim();
40        if segment.is_empty() {
41            continue;
42        }
43
44        // Find function name and args
45        if let Some(paren_pos) = segment.find('(') {
46            let name = segment[..paren_pos].trim().to_string();
47            let args_str = &segment[paren_pos + 1..];
48            let args_str = args_str.trim_end_matches(')').trim();
49
50            let args: Vec<String> = if args_str.is_empty() {
51                Vec::new()
52            } else {
53                // Split on commas, respecting nested parens
54                split_args(args_str)
55            };
56
57            funcs.push(BindingFunc { name, args });
58        } else {
59            // No parens — treat as a nullary function
60            funcs.push(BindingFunc {
61                name: segment.trim().to_string(),
62                args: Vec::new(),
63            });
64        }
65    }
66
67    funcs
68}
69
70/// Split comma-separated arguments, respecting nested parentheses and quotes.
71fn split_args(s: &str) -> Vec<String> {
72    let mut args = Vec::new();
73    let mut current = String::new();
74    let mut depth = 0;
75    let mut in_quote = false;
76
77    for c in s.chars() {
78        match c {
79            '\'' if !in_quote => {
80                in_quote = true;
81                current.push(c);
82            }
83            '\'' if in_quote => {
84                in_quote = false;
85                current.push(c);
86            }
87            '(' if !in_quote => {
88                depth += 1;
89                current.push(c);
90            }
91            ')' if !in_quote => {
92                depth -= 1;
93                current.push(c);
94            }
95            ',' if depth == 0 && !in_quote => {
96                args.push(current.trim().to_string());
97                current = String::new();
98            }
99            _ => current.push(c),
100        }
101    }
102    if !current.trim().is_empty() {
103        args.push(current.trim().to_string());
104    }
105    args
106}
107
108// build_chain_node and its helpers have been removed.
109// Legacy semicolon-chain bindings are now translated to Polydat source
110// and compiled through the unified Polydat compiler. See compile_bindings_with_opts.
111
112/// Compile all bindings from a set of ParsedOps into a Polydat Kernel.
113///
114/// Collects all unique binding names and expressions, plus any
115/// unreferenced bind points in op fields (auto-bound to hash+mod).
116/// Wires them through the Polydat assembler as proper node chains.
117/// Probe the compile level of a Polydat function by name.
118///
119/// Instantiates a dummy node and calls its intrinsic `compile_level()`.
120/// This is the single source of truth — no external classification needed.
121/// Probe the compile level of a Polydat function by name.
122///
123/// Instantiates a node with a representative constant and probes
124/// its intrinsic compile level. This is the single source of truth.
125/// Probe the compile level of a Polydat function by name.
126///
127/// Constructs a representative Polydat program containing the function
128/// and inspects the resulting kernel's node for its compile level.
129/// Uses the unified Polydat compiler — no separate dispatch table.
130pub fn probe_compile_level(func_name: &str) -> polydat::ast::CompileLevel {
131    let sig = match polydat::dsl::registry::lookup(func_name) {
132        Some(s) => s,
133        None => return polydat::ast::CompileLevel::Phase1,
134    };
135
136    // Build args from per-parameter example values declared in FuncSig.
137    // Wire params use their example (typically "cycle"), const params
138    // use representative values that pass the node's validation.
139    let mut parts = Vec::new();
140    let mut has_wire = false;
141    for p in sig.params {
142        parts.push(p.example.to_string());
143        if p.slot_type.is_wire() {
144            has_wire = true;
145        }
146    }
147    // Ensure at least one wire input for the coordinates declaration.
148    if !has_wire && parts.is_empty() {
149        parts.push("cycle".to_string());
150    }
151
152    let source = format!("input cycle: u64\nout := {func_name}({})", parts.join(", "));
153
154    // Probe compile level via catch_unwind — fallback is Phase1.
155    // Does not replace the global panic hook (not thread-safe).
156    // The compile level is a property of the interpreter's node graph,
157    // so the probe reads it off the interpreter's program.
158    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
159        polydat::dsl::compile::compile_polydat_interpreter(&source)
160    }));
161
162    match result {
163        Ok(Ok(kernel)) => kernel.program().last_node_compile_level(),
164        _ => polydat::ast::CompileLevel::Phase1,
165    }
166}
167
168pub fn compile_bindings(ops: &[ParsedOp]) -> Result<ScopeKernel, String> {
169    compile_bindings_with_path(ops, None)
170}
171
172/// Scan op params for bind point references (recursively through
173/// JSON values). Fails on a malformed bind point.
174fn collect_param_bindings(
175    params: &HashMap<String, serde_json::Value>,
176    exclude: &[String],
177    required: &mut Vec<String>,
178) -> Result<(), String> {
179    for (key, value) in params.iter() {
180        // `gutter:` templates resolve at RUNTIME — during-forms on the
181        // fiber wires, `final:` at phase end with a status-metric
182        // fallback (`{recall}`, `{latency_p50}`) that has no wire
183        // declaration anywhere. Unresolved names degrade to visible
184        // literal text in the cell, so they must not be collected as
185        // required wire references.
186        if key == "gutter" {
187            continue;
188        }
189        collect_json_bindings(value, exclude, required)
190            .map_err(|e| format!("param '{key}': {e}"))?;
191    }
192    Ok(())
193}
194
195/// Public wrapper for `collect_param_bindings`, used by `scope.rs`.
196pub fn collect_param_bindings_into(
197    params: &HashMap<String, serde_json::Value>,
198    exclude: &[String],
199    required: &mut Vec<String>,
200) -> Result<(), String> {
201    collect_param_bindings(params, exclude, required)
202}
203
204fn collect_json_bindings(
205    value: &serde_json::Value,
206    exclude: &[String],
207    required: &mut Vec<String>,
208) -> Result<(), String> {
209    match value {
210        serde_json::Value::String(s) => {
211            for name in bindpoints::referenced_bindings(s)? {
212                if !required.contains(&name) && !exclude.contains(&name) {
213                    required.push(name);
214                }
215            }
216        }
217        serde_json::Value::Object(map) => {
218            for v in map.values() {
219                collect_json_bindings(v, exclude, required)?;
220            }
221        }
222        serde_json::Value::Array(arr) => {
223            for v in arr {
224                collect_json_bindings(v, exclude, required)?;
225            }
226        }
227        _ => {}
228    }
229    Ok(())
230}
231
232pub fn compile_bindings_with_path(
233    ops: &[ParsedOp],
234    source_dir: Option<&std::path::Path>,
235) -> Result<ScopeKernel, String> {
236    compile_bindings_with_opts(ops, source_dir, false)
237}
238
239/// Compile a Polydat Kernel from a pre-built `BindingScope`.
240///
241/// The scope has already been validated and carries structured
242/// provenance. This function emits the scope to Polydat source, collects
243/// required outputs, and compiles via the standard Polydat compiler.
244///
245/// `pragmas` carries the chain-walked effective pragma state for
246/// the scope (typically obtained from
247/// `ScopeTree::nodes[idx].pragmas`). Pragma directives matching
248/// the effective state are prepended to the emitted source so
249/// the Polydat compiler's existing AST-pragma extraction (SRD 15
250/// §"Module-Level Pragmas") drives the assembler's strict-wire
251/// flags. Pass `&PragmaSet::default()` to disable pragma effects
252/// for legacy callers.
253pub fn compile_from_scope(
254    scope: &crate::scope::BindingScope,
255    source_dir: Option<&std::path::Path>,
256    polydat_lib_paths: Vec<std::path::PathBuf>,
257    strict: bool,
258    context: &str,
259    cursor_limit: Option<u64>,
260    pragmas: &polydat::dsl::pragmas::PragmaSet,
261) -> Result<ScopeKernel, String> {
262    let (source, options) = scope_source_and_options(
263        scope,
264        source_dir,
265        polydat_lib_paths,
266        strict,
267        context,
268        cursor_limit,
269        pragmas,
270    );
271    compile_scope_kernel(&source, &options)
272}
273
274/// The Polydat source and compile options a scope compiles from.
275fn scope_source_and_options(
276    scope: &crate::scope::BindingScope,
277    source_dir: Option<&std::path::Path>,
278    polydat_lib_paths: Vec<std::path::PathBuf>,
279    strict: bool,
280    context: &str,
281    cursor_limit: Option<u64>,
282    pragmas: &polydat::dsl::pragmas::PragmaSet,
283) -> (String, polydat::dsl::compile::CompileOptions) {
284    let body = scope.emit();
285    let required = scope.required_outputs();
286    let source = prepend_effective_pragmas(pragmas, &body);
287    let options = polydat::dsl::compile::CompileOptions {
288        source_dir: source_dir.map(std::path::Path::to_path_buf),
289        lib_paths: polydat_lib_paths,
290        required_outputs: required,
291        strict,
292        context: context.to_string(),
293        cursor_limit,
294        ..Default::default()
295    };
296    (source, options)
297}
298
299/// Compile Polydat source into a root scope kernel — a node of nmbrs's
300/// scope tree with no parent.
301///
302/// The interpreter compiles the program scope synthesis reads; the
303/// running kernel is the fiber engine's image of the same source and
304/// options when it can stand in for that program, and the interpreter
305/// kernel otherwise ([`ScopeKernel::root`]). Children are bound under it
306/// through the engine-neutral `Kernel` surface. Every root scope is
307/// compiled here, in one place, and resolves resources through the pool
308/// ([`crate::resource_pool::pool_resources`]) unless `options` names a
309/// scope of its own; every kernel bound beneath it joins that scope.
310pub fn compile_scope_kernel(
311    source: &str,
312    options: &polydat::dsl::compile::CompileOptions,
313) -> Result<ScopeKernel, String> {
314    let options = polydat::dsl::compile::CompileOptions {
315        resources: Some(
316            options
317                .resources
318                .clone()
319                .unwrap_or_else(crate::resource_pool::pool_resources),
320        ),
321        ..options.clone()
322    };
323    let options = &options;
324    let interpreter =
325        polydat::dsl::compile::compile_polydat_interpreter_with_options(source, options, None)
326            .map_err(|e| e.to_string())?;
327    let image =
328        crate::fiber_engine::source_image(interpreter.program(), source, options, &options.context);
329    Ok(ScopeKernel::root(interpreter, image))
330}
331
332/// Compile Polydat source to the interpreter program scope synthesis
333/// reads, with no running kernel: for a caller that binds the program
334/// under a scope itself.
335pub fn compile_scope_program(
336    source: &str,
337    options: &polydat::dsl::compile::CompileOptions,
338) -> Result<std::sync::Arc<polydat::kernel::PolydatProgram>, String> {
339    polydat::dsl::compile::compile_polydat_interpreter_with_options(source, options, None)
340        .map(|k| k.program().clone())
341        .map_err(|e| e.to_string())
342}
343
344/// Prepend pragma directives matching the chain's effective
345/// state. The resulting Polydat source is functionally equivalent to
346/// having the pragmas declared locally — the compiler's AST walk
347/// picks them up the same way regardless of whether they came
348/// from the original source or were synthesised here.
349///
350/// Provenance (which scope originally declared the pragma) is
351/// flattened by this textualization. That's acceptable for the
352/// runtime-effect path; diagnostic uses query the scope tree
353/// directly via `ScopeTree::ancestors` for path labels.
354pub(crate) fn prepend_effective_pragmas(
355    pragmas: &polydat::dsl::pragmas::PragmaSet,
356    body: &str,
357) -> String {
358    let mut out = String::new();
359    if pragmas.strict_types() && pragmas.strict_values() {
360        out.push_str("pragma strict\n");
361    } else if pragmas.strict_types() {
362        out.push_str("pragma strict_types\n");
363    } else if pragmas.strict_values() {
364        out.push_str("pragma strict_values\n");
365    }
366    if !out.is_empty() {
367        out.push('\n');
368    }
369    out.push_str(body);
370    out
371}
372
373/// The session clock's origin, in epoch milliseconds, declared on the
374/// workload root (see [`build_workload_root_kernel`]).
375pub const SESSION_START: &str = "session_start";
376
377/// Build the workload-root [`ScopeKernel`] as a subscope of the
378/// workload-params kernel.
379///
380/// The workload-root is "just another scope" per SRD-67
381/// §"Composition with SRD-66": it goes through the same
382/// source-matter construction every other scope uses
383/// ([`ScopeKernel::build_under`]). The specialised content for the root is:
384///
385/// - Op-level bindings (rare at root; most workloads put
386///   bindings at the workload or phase level).
387/// - The workload's `bindings:` block, ingested as Inherited
388///   matter.
389/// - Workload params as `const` bindings — descendants pick
390///   them up via the standard manifest auto-extern.
391/// - DCE filter that retains every workload param plus
392///   caller-supplied config refs (`cycles=` etc.).
393///
394/// Replaces the prior `compile_bindings_with_libs_excluding`
395/// function — the "_excluding" suffix referred to a now-defunct
396/// `exclude` parameter, and the function carried a legacy
397/// semicolon-chain Map-bindings branch that no shipped workload
398/// shape exercises (workload params are always present, so the
399/// `needs_scope` gate always picked the modern path).
400// reason: cohesive compile entry point — each argument is an
401// independent compile input (parent scope, ops, lib paths, strictness,
402// required-names, context label, cursor bound); bundling them into a
403// struct would only move the same fields without adding clarity.
404#[allow(clippy::too_many_arguments)]
405pub fn build_workload_root_kernel(
406    parent: &ScopeKernel,
407    ops: &[ParsedOp],
408    source_dir: Option<&std::path::Path>,
409    polydat_lib_paths: Vec<std::path::PathBuf>,
410    strict: bool,
411    extra_required: &[String],
412    context: &str,
413    cursor_limit: Option<u64>,
414    workload_params: &std::collections::HashMap<String, String>,
415    workload_level_polydat: Option<&str>,
416) -> Result<ScopeKernel, String> {
417    // Build the workload-root scope. workload_params get
418    // injected as `const` bindings so descendants resolve them
419    // via the standard manifest auto-extern.
420    let mut scope = crate::scope::build_scope(
421        ops,
422        &std::collections::HashMap::new(), // no iteration vars at outer level
423        &[],                               // no outer manifest (this IS the outer scope)
424        workload_params,
425        &std::collections::HashMap::new(), // phases not needed here
426        None,                              // no phase cycles
427        &[],                               // no excluded names
428        None,                              // workload-root has no parent program for AST mode
429    )?;
430
431    // SRD-13f §"Wire-reference classification" — the workload's
432    // `bindings:` block lives on the workload-root scope as
433    // local matter. Ingest before validate/emit so emit()
434    // produces a single coherent source.
435    if let Some(extra) = workload_level_polydat
436        && !extra.trim().is_empty()
437    {
438        scope.ingest_polydat_source(extra, crate::scope::BindingOrigin::Inherited);
439    }
440    // The session clock's origin: a const over a volatile reading,
441    // captured once when the workload root initializes. It has no
442    // inputs, so scope synthesis inlines that one captured value into
443    // every descendant that names it, and session-elapsed time —
444    // `current_epoch_millis() - session_start` — reads one origin in
445    // every scope, fiber, and engine. The capture reads the clock, and a
446    // const capture is its own acknowledgment, so strict mode accepts it.
447    // A workload param or binding of the same name is the author's own
448    // origin and wins.
449    let session_clock = !workload_params.contains_key(SESSION_START)
450        && !scope.defined_names().contains(SESSION_START);
451    if session_clock {
452        scope.ingest_polydat_source(
453            &format!("const {SESSION_START} := current_epoch_millis()\n"),
454            crate::scope::BindingOrigin::Inherited,
455        );
456    }
457    scope.validate().map_err(|e| format!("{context}: {e}"))?;
458
459    // DCE-keepalive list: caller's config refs plus every
460    // workload param. Param names are sorted so the resulting
461    // output order is deterministic across processes (HashMap
462    // iteration is randomised per-process, and `compile_filtered`
463    // calls `add_output` in iteration order — non-determinism
464    // here would surface as a non-deterministic
465    // `canonical_hash` and break checkpoint resume-skip
466    // matching).
467    let mut scope_required = scope.required_outputs();
468    for name in extra_required {
469        if !scope_required.contains(name) {
470            scope_required.push(name.clone());
471        }
472    }
473    if session_clock && !scope_required.iter().any(|n| n == SESSION_START) {
474        scope_required.push(SESSION_START.to_string());
475    }
476    let mut param_names: Vec<&String> = workload_params.keys().collect();
477    param_names.sort();
478    for name in param_names {
479        if !scope_required.contains(name) {
480            scope_required.push(name.clone());
481        }
482    }
483
484    // Standard scope construction: source matter built under the
485    // parent (ScopeKernel::build_under), identical to every other
486    // scope's build pathway (SRD-67 §"The construction protocol").
487    let mut source = scope.emit();
488    // If the workload's authored matter doesn't declare its
489    // own `input ...: u64` line, default the workload-root
490    // kernel's coordinate input to `cycle`. The wire name is
491    // a CONVENTION the runner-driver contract relies on
492    // (every dispatch path sets the cycle ordinal on slot 0
493    // via set_inputs); workload authors who need a different
494    // shape can declare their own inputs line explicitly. The
495    // default lets inline workloads (`nmbrs run op="c={cycle}"`)
496    // resolve `{cycle}` against the workload-root kernel
497    // without forcing every author to write `input cycle: u64`.
498    if !source.lines().any(|l| l.trim_start().starts_with("input ")) {
499        source = format!("input cycle: u64\n{source}");
500    }
501    let opts = polydat::kernel::subcontext::CompileOptions {
502        workload_dir: source_dir.map(|p| p.to_path_buf()),
503        polydat_lib_paths,
504        strict,
505        required_outputs: scope_required,
506        context_label: Some(context.to_string()),
507        cursor_limit,
508        ..Default::default()
509    };
510    // Mark workload-param names as inherited so their input slots
511    // don't show up in `compute_own_coordinates` (which filters for
512    // `IterationExtern`-kind inputs that aren't marked inherited).
513    // Without this, switching the workload-param cascade from
514    // `const NAME := <literal>` to `extern NAME: T` causes every
515    // workload param to show up as a scope-coordinate on the
516    // workload-root kernel — and downstream code (phase identity
517    // construction, label formatting, scene-tree population) treats
518    // those coordinates as iter-vars belonging to this scope. The
519    // resulting phase-identity drift between pre-map registration
520    // and runtime phase_failed silently breaks checkpoint Failed
521    // recording. Marking them inherited keeps the cascade-pass-
522    // through semantics: descendants still extern these names from
523    // the workload-root's manifest, but the workload-root itself
524    // treats them as inherited rather than as its own iter-vars.
525    let mut inherited_param_names: Vec<String> = workload_params.keys().cloned().collect();
526    inherited_param_names.sort();
527    ScopeKernel::build_under(
528        parent.kernel(),
529        crate::scope_kernel::SourceMatter::source(context, source, opts)
530            .inherited(inherited_param_names),
531    )
532}
533
534/// Compile all bindings from a set of ParsedOps into a Polydat Kernel.
535///
536/// When `strict` is true, the Polydat compiler enforces:
537/// - Explicit `input ...: u64` declaration (no inference)
538/// - All module arguments must be named (no positional)
539/// - All module inputs must be provided by caller (no fallthrough)
540pub fn compile_bindings_with_opts(
541    ops: &[ParsedOp],
542    source_dir: Option<&std::path::Path>,
543    strict: bool,
544) -> Result<ScopeKernel, String> {
545    use nmbrs_workload::model::BindingsDef;
546
547    // Check if any op uses Polydat source mode
548    let polydat_source = ops.iter().find_map(|op| {
549        if let BindingsDef::PolydatSource(src) = &op.bindings {
550            if !src.trim().is_empty() {
551                Some(src.clone())
552            } else {
553                None
554            }
555        } else {
556            None
557        }
558    });
559
560    if let Some(source) = polydat_source {
561        // Native Polydat grammar mode: collect referenced bind points from
562        // op templates for dead code elimination. Only the bindings
563        // actually used by ops are compiled into the kernel.
564        let mut required: Vec<String> = Vec::new();
565        for op in ops {
566            for value in op.op.values() {
567                if let Some(s) = value.as_str() {
568                    for name in bindpoints::referenced_bindings(s)? {
569                        if !required.contains(&name) {
570                            required.push(name);
571                        }
572                    }
573                }
574            }
575        }
576        let options = polydat::dsl::compile::CompileOptions {
577            source_dir: source_dir.map(std::path::Path::to_path_buf),
578            required_outputs: required,
579            strict,
580            ..Default::default()
581        };
582        return compile_scope_kernel(&source, &options);
583    }
584
585    // Legacy mode: translate semicolon-chain bindings into Polydat source
586    // and compile through the unified Polydat compiler. No separate dispatch
587    // table — every node function available in Polydat grammar is automatically
588    // available in legacy chain syntax.
589    let mut all_bindings: HashMap<String, String> = HashMap::new();
590    for op in ops {
591        if let BindingsDef::Map(map) = &op.bindings {
592            for (name, expr) in map {
593                all_bindings
594                    .entry(name.clone())
595                    .or_insert_with(|| expr.clone());
596            }
597        }
598    }
599
600    // Collect required outputs from op templates
601    let mut required: Vec<String> = Vec::new();
602    for op in ops {
603        for value in op.op.values() {
604            if let Some(s) = value.as_str() {
605                for name in bindpoints::referenced_bindings(s)? {
606                    if !required.contains(&name) {
607                        required.push(name);
608                    }
609                }
610            }
611        }
612    }
613
614    // Translate each legacy chain into Polydat source lines
615    let mut polydat_lines: Vec<String> = Vec::new();
616    polydat_lines.push("input cycle: u64".into());
617
618    for (binding_name, expr) in &all_bindings {
619        let chain = parse_binding_chain(expr);
620        if chain.is_empty() {
621            return Err(format!("empty binding expression for '{binding_name}'"));
622        }
623
624        // Convert each chain step into a Polydat binding.
625        // Chain: FuncA(args); FuncB(args) → sequential wiring from cycle.
626        let mut prev_wire = "cycle".to_string();
627
628        for (i, func) in chain.iter().enumerate() {
629            let is_last = i == chain.len() - 1;
630            let target = if is_last {
631                binding_name.clone()
632            } else {
633                format!("__chain_{binding_name}_{i}")
634            };
635
636            // Translate legacy function names to Polydat equivalents
637            let (func_name, extra_args) = translate_legacy_func(&func.name, &func.args);
638            let mut call_args = vec![prev_wire.clone()];
639            for arg in &func.args {
640                call_args.push(strip_java_long_suffix(arg.trim()).to_string());
641            }
642            call_args.extend(extra_args);
643
644            polydat_lines.push(format!(
645                "{target} := {func_name}({args})",
646                args = call_args.join(", ")
647            ));
648
649            prev_wire = target;
650        }
651    }
652
653    // Validate: all bind point references must have a binding or
654    // be a declared coordinate (the Polydat compiler auto-exposes
655    // coordinates as passthrough outputs, so they resolve without
656    // a user-declared binding).
657    let coord_names: HashSet<String> = ["cycle".to_string()].into_iter().collect();
658    let mut missing: Vec<String> = Vec::new();
659    for name in &required {
660        if !all_bindings.contains_key(name) && !coord_names.contains(name) {
661            missing.push(name.clone());
662        }
663    }
664    if !missing.is_empty() {
665        return Err(format!(
666            "undeclared bind point references: {}. Add these to your bindings section.",
667            missing.join(", ")
668        ));
669    }
670
671    let polydat_source = polydat_lines.join("\n");
672    let options = polydat::dsl::compile::CompileOptions {
673        source_dir: source_dir.map(std::path::Path::to_path_buf),
674        required_outputs: required,
675        strict,
676        ..Default::default()
677    };
678    compile_scope_kernel(&polydat_source, &options)
679}
680
681// ---------------------------------------------------------------------------
682// Legacy function name translation (virtdata → GK)
683//
684// This is a compatibility overlay that maps Java nosqlbench function
685// names to their nmbrs Polydat equivalents. It lives ONLY in the binding
686// chain compiler — the Polydat registry and node implementations are not
687// polluted with legacy names.
688// ---------------------------------------------------------------------------
689
690/// Translate a legacy Java nosqlbench function name to its Polydat equivalent.
691///
692/// Returns `(polydat_func_name, extra_args)` where extra_args are additional
693/// arguments to append (e.g., for ToString → format_u64 which needs a radix).
694fn translate_legacy_func(name: &str, args: &[String]) -> (String, Vec<String>) {
695    match name.to_lowercase().as_str() {
696        // Direct name mappings (same semantics, different naming convention)
697        "hash" => ("hash".into(), vec![]),
698        "identity" => ("identity".into(), vec![]),
699        "add" => ("add".into(), vec![]),
700        "mul" => ("mul".into(), vec![]),
701        "div" => ("div".into(), vec![]),
702        "mod" => ("mod".into(), vec![]),
703        "clamp" => ("clamp".into(), vec![]),
704
705        // String conversions
706        "tostring" | "to_string" => ("format_u64".into(), vec!["10".into()]),
707        "tohexstring" => ("format_u64".into(), vec!["16".into()]),
708        "tooctalstring" => ("format_u64".into(), vec!["8".into()]),
709        "tobinarystring" => ("format_u64".into(), vec!["2".into()]),
710
711        // Distributions (Java names → Polydat equivalents)
712        // Uniform(min, max) → hash_range(input, max-min) + add(min)
713        // This is approximate — Java Uniform samples from a distribution;
714        // Polydat hash_range does modular hash. Close enough for key distribution.
715        "uniform" => {
716            if args.len() >= 2 {
717                // Uniform(min, max) → mod(hash(input), range) then add(min)
718                // We approximate with hash_range which takes just max
719                ("hash_range".into(), vec![])
720            } else {
721                ("hash_range".into(), vec![])
722            }
723        }
724
725        // Zipf, Normal, etc. — map to icd_ variants
726        "normal" | "gaussian" => ("icd_normal".into(), vec![]),
727        "zipf" => ("dist_zipf".into(), vec![]),
728
729        // Hash-based
730        "hashrange" | "hash_range" => ("hash_range".into(), vec![]),
731        "hashinterval" | "hash_interval" => ("hash_interval".into(), vec![]),
732
733        // Number formatting
734        "format" | "printf" => ("printf".into(), vec![]),
735        "numbernamesto_string" | "numbernames" => ("number_to_words".into(), vec![]),
736
737        // Shuffle / permutation
738        "shuffle" => ("shuffle".into(), vec![]),
739
740        // Long suffix stripping (Java allows 1000000000L)
741        _ => {
742            // Default: lowercase the name and hope the Polydat registry has it
743            (name.to_lowercase(), vec![])
744        }
745    }
746}
747
748/// Strip Java long literal suffix (e.g., "1000000000L" → "1000000000")
749fn strip_java_long_suffix(arg: &str) -> &str {
750    arg.strip_suffix('L')
751        .or_else(|| arg.strip_suffix('l'))
752        .unwrap_or(arg)
753}
754
755/// SRD-13f Push D: translate a Map-form bindings block (legacy
756/// semicolon-chain syntax, e.g. `{user_id: "Hash(); Mod(1000000)"}`)
757/// into Polydat source lines. Returns one or more `name := func(args)`
758/// lines per entry — multi-step chains expand to intermediate
759/// `__chain_<name>_<i> := ...` wires.
760///
761/// Does NOT prepend `input cycle: u64`; that's owned by the
762/// enclosing scope's emit. Intended for routing workload-level
763/// `bindings:` directly to the workload-root kernel without
764/// going through the parser merge (which retired in Push D).
765pub fn legacy_chain_map_to_polydat_lines(
766    map: &std::collections::HashMap<String, String>,
767) -> Result<String, String> {
768    let mut polydat_lines: Vec<String> = Vec::new();
769    for (binding_name, expr) in map {
770        let chain = parse_binding_chain(expr);
771        if chain.is_empty() {
772            return Err(format!("empty binding expression for '{binding_name}'"));
773        }
774        let mut prev_wire = "cycle".to_string();
775        for (i, func) in chain.iter().enumerate() {
776            let is_last = i == chain.len() - 1;
777            let target = if is_last {
778                binding_name.clone()
779            } else {
780                format!("__chain_{binding_name}_{i}")
781            };
782            let (func_name, extra_args) = translate_legacy_func(&func.name, &func.args);
783            let mut call_args = vec![prev_wire.clone()];
784            for arg in &func.args {
785                call_args.push(strip_java_long_suffix(arg.trim()).to_string());
786            }
787            call_args.extend(extra_args);
788            polydat_lines.push(format!(
789                "{target} := {func_name}({args})",
790                args = call_args.join(", ")
791            ));
792            prev_wire = target;
793        }
794    }
795    Ok(polydat_lines.join("\n"))
796}
797
798#[cfg(test)]
799mod tests {
800    use super::*;
801
802    use polydat::dsl::pragmas::{Pragma, PragmaSet};
803
804    #[test]
805    fn prepend_pragmas_strict_alias() {
806        let pragmas = PragmaSet {
807            entries: vec![Pragma {
808                name: "strict".into(),
809                args: vec![],
810                line: 1,
811            }],
812        };
813        let body = "id := cycle\n";
814        let out = prepend_effective_pragmas(&pragmas, body);
815        // `strict` activates both — emit single combined directive.
816        assert!(out.starts_with("pragma strict\n"));
817        assert!(out.contains("id := cycle"));
818    }
819
820    #[test]
821    fn prepend_pragmas_individual_modes() {
822        let pragmas = PragmaSet {
823            entries: vec![Pragma {
824                name: "strict_values".into(),
825                args: vec![],
826                line: 1,
827            }],
828        };
829        let out = prepend_effective_pragmas(&pragmas, "x := cycle");
830        assert!(out.starts_with("pragma strict_values\n"));
831        assert!(!out.contains("strict_types"));
832    }
833
834    #[test]
835    fn prepend_pragmas_no_op_when_empty() {
836        let pragmas = PragmaSet::default();
837        let out = prepend_effective_pragmas(&pragmas, "x := cycle");
838        assert_eq!(out, "x := cycle");
839    }
840
841    #[test]
842    fn prepend_pragmas_walks_parent_chain() {
843        // Parent declares strict_values. Child declares nothing.
844        // The child's nested set still produces the prepended
845        // directive — that's the load-bearing behavior for SRD 18b
846        // cross-scope propagation.
847        let parent = PragmaSet {
848            entries: vec![Pragma {
849                name: "strict_values".into(),
850                args: vec![],
851                line: 1,
852            }],
853        };
854        let child = parent.nested(&[]);
855        let out = prepend_effective_pragmas(&child, "x := cycle");
856        assert!(
857            out.starts_with("pragma strict_values\n"),
858            "expected pragma to flow from parent chain, got:\n{out}"
859        );
860    }
861
862    #[test]
863    fn parse_simple_chain() {
864        let chain = parse_binding_chain("Hash(); Mod(1000000)");
865        assert_eq!(chain.len(), 2);
866        assert_eq!(chain[0].name, "Hash");
867        assert!(chain[0].args.is_empty());
868        assert_eq!(chain[1].name, "Mod");
869        assert_eq!(chain[1].args, vec!["1000000"]);
870    }
871
872    #[test]
873    fn parse_identity() {
874        let chain = parse_binding_chain("Identity()");
875        assert_eq!(chain.len(), 1);
876        assert_eq!(chain[0].name, "Identity");
877    }
878
879    #[test]
880    fn parse_with_string_arg() {
881        let chain = parse_binding_chain("Template('user-{}', ToString())");
882        assert_eq!(chain.len(), 1);
883        assert_eq!(chain[0].name, "Template");
884        assert_eq!(chain[0].args.len(), 2);
885    }
886
887    #[test]
888    fn parse_long_chain() {
889        let chain = parse_binding_chain("Add(10); Hash(); Mod(100); ToString()");
890        assert_eq!(chain.len(), 4);
891        assert_eq!(chain[0].name, "Add");
892        assert_eq!(chain[1].name, "Hash");
893        assert_eq!(chain[2].name, "Mod");
894        assert_eq!(chain[3].name, "ToString");
895    }
896
897    #[test]
898    fn parse_with_long_suffix() {
899        let chain = parse_binding_chain("Mod(1000000000L)");
900        assert_eq!(chain[0].args, vec!["1000000000L"]);
901        // The L suffix is preserved in the chain parse.
902        // The Polydat compiler handles it during node construction.
903    }
904
905    #[test]
906    fn compile_identity_binding() {
907        let ops = vec![{
908            let mut op = ParsedOp::simple("test", "{myval}");
909            op.bindings.insert("myval".into(), "Identity()".into());
910            op
911        }];
912        let mut kernel = compile_bindings(&ops).unwrap();
913        kernel.set_inputs(&[42]);
914        assert_eq!(kernel.pull("myval").as_u64(), 42);
915    }
916
917    #[test]
918    fn compile_hash_mod_binding() {
919        let ops = vec![{
920            let mut op = ParsedOp::simple("test", "{id}");
921            op.bindings
922                .insert("id".into(), "Hash(); Mod(1000000)".into());
923            op
924        }];
925        let mut kernel = compile_bindings(&ops).unwrap();
926        kernel.set_inputs(&[42]);
927        let val = kernel.pull("id").as_u64();
928        assert!(val < 1_000_000, "got {val}");
929    }
930
931    #[test]
932    fn compile_hash_mod_deterministic() {
933        let ops = vec![{
934            let mut op = ParsedOp::simple("test", "{id}");
935            op.bindings.insert("id".into(), "Hash(); Mod(100)".into());
936            op
937        }];
938        let mut kernel = compile_bindings(&ops).unwrap();
939        kernel.set_inputs(&[42]);
940        let v1 = kernel.pull("id").as_u64();
941        kernel.set_inputs(&[42]);
942        let v2 = kernel.pull("id").as_u64();
943        assert_eq!(v1, v2);
944    }
945
946    #[test]
947    fn compile_multiple_bindings() {
948        let ops = vec![{
949            let mut op = ParsedOp::simple("test", "{a} {b}");
950            op.bindings.insert("a".into(), "Identity()".into());
951            op.bindings.insert("b".into(), "Hash(); Mod(100)".into());
952            op
953        }];
954        let mut kernel = compile_bindings(&ops).unwrap();
955        kernel.set_inputs(&[5]);
956        assert_eq!(kernel.pull("a").as_u64(), 5);
957        assert!(kernel.pull("b").as_u64() < 100);
958    }
959
960    #[test]
961    fn compile_rejects_undeclared_bind_points() {
962        // Op references {mystery} but no binding declared → error
963        let ops = vec![ParsedOp::simple("test", "val={mystery}")];
964        let result = compile_bindings(&ops);
965        assert!(result.is_err());
966        assert!(result.unwrap_err().contains("undeclared bind point"));
967    }
968
969    #[test]
970    fn compile_add_chain() {
971        let ops = vec![{
972            let mut op = ParsedOp::simple("test", "{val}");
973            op.bindings
974                .insert("val".into(), "Add(100); Mod(1000)".into());
975            op
976        }];
977        let mut kernel = compile_bindings(&ops).unwrap();
978        kernel.set_inputs(&[5]);
979        // 5 + 100 = 105, 105 % 1000 = 105
980        assert_eq!(kernel.pull("val").as_u64(), 105);
981    }
982
983    #[test]
984    fn compile_provides_cycle_output() {
985        let ops = vec![ParsedOp::simple("test", "cycle={cycle}")];
986        let mut kernel = compile_bindings(&ops).unwrap();
987        kernel.set_inputs(&[99]);
988        assert_eq!(kernel.pull("cycle").as_u64(), 99);
989    }
990
991    #[test]
992    fn legacy_tostring_translates() {
993        let (name, _) = translate_legacy_func("ToString", &[]);
994        assert_eq!(name, "format_u64");
995    }
996
997    #[test]
998    fn legacy_uniform_translates() {
999        let (name, _) = translate_legacy_func("Uniform", &["0".into(), "1000".into()]);
1000        assert_eq!(name, "hash_range");
1001    }
1002}