1use std::collections::HashMap;
14
15use crate::model::{BindingsDef, ParsedOp, Workload};
16
17pub 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 if let Some(w) = try_polydat_block_workload(op_template) {
57 return Ok(w);
58 }
59
60 let segments = split_ops(op_template);
62
63 let mut inline_exprs: Vec<String> = Vec::new();
66 let mut expr_index: HashMap<String, usize> = HashMap::new();
67
68 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 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 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
140fn try_polydat_block_workload(op_template: &str) -> Option<Workload> {
152 let source = build_polydat_candidate(op_template);
153 polydat::dsl::compile::compile_polydat(&source).ok()?;
155 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 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
198fn 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
224pub(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
253fn 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
273fn 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
300struct OpSegment {
303 template: String,
304 ratio: u64,
305}
306
307fn 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
343fn parse_segment(s: &str) -> OpSegment {
345 if let Some(colon_pos) = s.find(':') {
347 let prefix = &s[..colon_pos];
348 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
365fn 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 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 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 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}}")); 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)")); 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 ); }
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 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 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 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 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 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}