1use std::collections::{HashMap, HashSet};
19
20use crate::scope_kernel::ScopeKernel;
21
22use nmbrs_workload::bindpoints;
23use nmbrs_workload::model::ParsedOp;
24
25#[derive(Debug, Clone)]
27struct BindingFunc {
28 name: String,
29 args: Vec<String>,
30}
31
32fn 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 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_args(args_str)
55 };
56
57 funcs.push(BindingFunc { name, args });
58 } else {
59 funcs.push(BindingFunc {
61 name: segment.trim().to_string(),
62 args: Vec::new(),
63 });
64 }
65 }
66
67 funcs
68}
69
70fn 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
108pub 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 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 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 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
172fn 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 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
195pub 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
239pub 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
274fn 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
299pub 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
332pub 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
344pub(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
373pub const SESSION_START: &str = "session_start";
376
377#[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 let mut scope = crate::scope::build_scope(
421 ops,
422 &std::collections::HashMap::new(), &[], workload_params,
425 &std::collections::HashMap::new(), None, &[], None, )?;
430
431 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 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 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 let mut source = scope.emit();
488 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 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
534pub 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 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 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 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 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 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 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 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 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
681fn translate_legacy_func(name: &str, args: &[String]) -> (String, Vec<String>) {
695 match name.to_lowercase().as_str() {
696 "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 "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 "uniform" => {
716 if args.len() >= 2 {
717 ("hash_range".into(), vec![])
720 } else {
721 ("hash_range".into(), vec![])
722 }
723 }
724
725 "normal" | "gaussian" => ("icd_normal".into(), vec![]),
727 "zipf" => ("dist_zipf".into(), vec![]),
728
729 "hashrange" | "hash_range" => ("hash_range".into(), vec![]),
731 "hashinterval" | "hash_interval" => ("hash_interval".into(), vec![]),
732
733 "format" | "printf" => ("printf".into(), vec![]),
735 "numbernamesto_string" | "numbernames" => ("number_to_words".into(), vec![]),
736
737 "shuffle" => ("shuffle".into(), vec![]),
739
740 _ => {
742 (name.to_lowercase(), vec![])
744 }
745 }
746}
747
748fn 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
755pub 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 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 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 }
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 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 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}