1use std::collections::HashSet;
49
50use crate::ast::Value;
51use crate::kernel::PolydatKernel;
52
53pub trait Lookup {
59 fn lookup(&self, name: &str) -> Option<Value>;
61
62 fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger>;
65}
66
67impl Lookup for PolydatKernel {
68 fn lookup(&self, name: &str) -> Option<Value> {
69 PolydatKernel::lookup(self, name)
70 }
71 fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
72 self.program().ledger()
73 }
74}
75
76pub struct KernelLookup<'a>(&'a dyn crate::kernel::Kernel);
89
90impl<'a> KernelLookup<'a> {
91 pub fn new(kernel: &'a dyn crate::kernel::Kernel) -> Self {
93 KernelLookup(kernel)
94 }
95}
96
97impl Lookup for KernelLookup<'_> {
98 fn lookup(&self, name: &str) -> Option<Value> {
113 if self.0.output_modifier(name) == crate::dsl::ast::BindingModifier::CONST
114 && let Some(v) = self.0.folded_value(name)
115 && !matches!(v, Value::None)
116 {
117 return Some(v);
118 }
119 if let Some(v) = self.0.input_value(name)
120 && !matches!(v, Value::None)
121 {
122 return Some(v);
123 }
124 if let Some(v) = self.0.folded_value(name)
125 && !matches!(v, Value::None)
126 {
127 return Some(v);
128 }
129 if name.contains('.') {
133 return self.lookup(&name.replace('.', "__"));
134 }
135 None
136 }
137 fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
138 crate::kernel::Kernel::ledger(self.0)
139 }
140}
141
142pub struct NoScope {
148 ledger: std::sync::Arc<crate::kernel::CompileLedger>,
149}
150
151impl NoScope {
152 pub fn new() -> Self {
154 Self::charged_to(crate::kernel::CompileLedger::new())
155 }
156
157 pub fn charged_to(ledger: std::sync::Arc<crate::kernel::CompileLedger>) -> Self {
160 Self { ledger }
161 }
162}
163
164impl Default for NoScope {
165 fn default() -> Self {
166 Self::new()
167 }
168}
169
170impl Lookup for NoScope {
171 fn lookup(&self, _name: &str) -> Option<Value> {
172 None
173 }
174 fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
175 &self.ledger
176 }
177}
178
179pub struct Layered<'a> {
182 pub prefix: &'a [(String, Value)],
184 pub inner: &'a dyn Lookup,
186}
187
188impl Lookup for Layered<'_> {
189 fn lookup(&self, name: &str) -> Option<Value> {
190 if let Some((_, v)) = self.prefix.iter().find(|(n, _)| n == name) {
191 return Some(v.clone());
192 }
193 self.inner.lookup(name)
194 }
195 fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
196 self.inner.ledger()
197 }
198}
199
200const ROUND_WARN: usize = 100;
203
204const ROUND_HARD: usize = 1000;
207
208pub fn interpolate_via_kernel(
221 text: &str,
222 kernel: &dyn Lookup,
223) -> Result<String, crate::dsl::compile::EmbeddingError> {
224 interpolate_with_lookup(text, |name| {
225 kernel.lookup(name).map(|v| v.to_display_string())
226 })
227 .map_err(|msg| classify_interpolate_error(text, msg))
228}
229
230fn classify_interpolate_error(text: &str, msg: String) -> crate::dsl::compile::EmbeddingError {
231 if let Some(rest) = msg.strip_prefix("interpolation: unresolved placeholder '{")
233 && let Some(end) = rest.find('}')
234 {
235 let name = rest[..end].to_string();
236 return crate::dsl::compile::EmbeddingError::UnresolvedPlaceholder {
237 name,
238 source: text.to_string(),
239 };
240 }
241 crate::dsl::compile::EmbeddingError::Parse {
244 source: text.to_string(),
245 message: msg,
246 position: None,
247 }
248}
249
250pub fn interpolate_with_lookup<F>(text: &str, lookup: F) -> Result<String, String>
258where
259 F: Fn(&str) -> Option<String>,
260{
261 let mut s = text.to_string();
262 let mut warned = false;
263 for round in 1..=ROUND_HARD {
264 if round == ROUND_WARN && !warned {
265 crate::library::support::audit::warn(&format!(
266 "interpolation: '{text}' has run {ROUND_WARN} substitution rounds — likely cyclic"
267 ));
268 warned = true;
269 }
270 let progress = one_pass(&mut s, &lookup)?;
271 if !progress {
272 break;
273 }
274 if round == ROUND_HARD {
275 return Err(format!(
276 "interpolation: '{text}' did not stabilize in {ROUND_HARD} rounds — \
277 cyclic placeholders?"
278 ));
279 }
280 }
281 if let Some(unresolved) = first_unresolved(&s) {
282 return Err(format!(
283 "interpolation: unresolved placeholder '{{{unresolved}}}' in '{text}' — \
284 not bound by any outer for_each var or workload param. \
285 Use \\{{ \\}} to write literal braces."
286 ));
287 }
288 Ok(unescape(&s))
289}
290
291pub fn whole_placeholder(text: &str) -> Option<&str> {
301 let t = text.trim();
302 let bytes = t.as_bytes();
303 let n = bytes.len();
304 if n < 3 || bytes[0] != b'{' || bytes[n - 1] != b'}' {
305 return None;
306 }
307 let mut depth = 0usize;
308 let mut i = 0;
309 while i < n {
310 if bytes[i] == b'\\' && i + 1 < n && (bytes[i + 1] == b'{' || bytes[i + 1] == b'}') {
311 i += 2;
312 continue;
313 }
314 match bytes[i] {
315 b'{' => depth += 1,
316 b'}' => {
317 depth = depth.checked_sub(1)?;
318 if depth == 0 && i != n - 1 {
319 return None;
320 }
321 }
322 _ => {}
323 }
324 i += 1;
325 }
326 let body = &t[1..n - 1];
327 (depth == 0 && !body.trim().is_empty()).then_some(body)
328}
329
330pub(crate) fn is_name_path(body: &str) -> bool {
334 let mut chars = body.chars();
335 chars
336 .next()
337 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
338 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
339}
340
341pub fn interpolate_operands<F>(text: &str, lookup: F) -> Result<String, String>
356where
357 F: Fn(&str) -> Option<Value>,
358{
359 let as_text = |name: &str| lookup(name).map(|v| v.to_display_string());
360 let spans = operand_spans(text);
361 if spans.is_empty() {
362 return interpolate_with_lookup(text, as_text);
363 }
364 let mut out = String::with_capacity(text.len());
365 let mut at = 0;
366 let whole_text_error = || match interpolate_with_lookup(text, as_text) {
369 Err(message) => message,
370 Ok(_) => format!("interpolation: '{text}' could not be read"),
371 };
372 for span in spans {
373 out.push_str(
374 &interpolate_with_lookup(&text[at..span.start], as_text)
375 .map_err(|_| whole_text_error())?,
376 );
377 let placeholder = &text[span.clone()];
378 let body = &placeholder[1..placeholder.len() - 1];
379 let value = interpolate_with_lookup(body, as_text)
380 .ok()
381 .filter(|name| is_name_path(name.trim()))
382 .and_then(|name| lookup(name.trim()));
383 match value {
384 Some(value) => out.push_str(&operand_literal(&value)),
385 None => out.push_str(
386 &interpolate_with_lookup(placeholder, as_text).map_err(|_| whole_text_error())?,
387 ),
388 }
389 at = span.end;
390 }
391 out.push_str(&interpolate_with_lookup(&text[at..], as_text).map_err(|_| whole_text_error())?);
392 Ok(out)
393}
394
395fn operand_literal(value: &Value) -> String {
399 let Value::Str(s) = value else {
400 return value.to_display_string();
401 };
402 let mut out = String::with_capacity(s.len() + 2);
403 out.push('"');
404 for c in s.chars() {
405 match c {
406 '"' => out.push_str("\\\""),
407 '\\' => out.push_str("\\\\"),
408 '\n' => out.push_str("\\n"),
409 '\t' => out.push_str("\\t"),
410 '{' => out.push_str("{{"),
411 '}' => out.push_str("}}"),
412 other => out.push(other),
413 }
414 }
415 out.push('"');
416 out
417}
418
419fn operand_spans(text: &str) -> Vec<std::ops::Range<usize>> {
422 let joins =
425 |c: char| c.is_alphanumeric() || matches!(c, '_' | '.' | '{' | '}' | '\'' | '"' | '\\');
426 let bytes = text.as_bytes();
427 let n = bytes.len();
428 let escaped_brace =
429 |i: usize| bytes[i] == b'\\' && i + 1 < n && (bytes[i + 1] == b'{' || bytes[i + 1] == b'}');
430 let mut spans = Vec::new();
431 let mut quote: Option<u8> = None;
432 let mut i = 0;
433 while i < n {
434 let c = bytes[i];
435 if let Some(q) = quote {
436 if c == b'\\' && i + 1 < n {
437 i += 2;
438 continue;
439 }
440 if c == q {
441 quote = None;
442 }
443 i += 1;
444 continue;
445 }
446 if escaped_brace(i) {
447 i += 2;
448 continue;
449 }
450 if c == b'"' || c == b'\'' {
451 quote = Some(c);
452 i += 1;
453 continue;
454 }
455 if c != b'{' {
456 i += 1;
457 continue;
458 }
459 let mut depth = 0usize;
461 let mut j = i;
462 let mut close = None;
463 while j < n {
464 if escaped_brace(j) {
465 j += 2;
466 continue;
467 }
468 match bytes[j] {
469 b'{' => depth += 1,
470 b'}' => {
471 depth -= 1;
472 if depth == 0 {
473 close = Some(j);
474 break;
475 }
476 }
477 _ => {}
478 }
479 j += 1;
480 }
481 let Some(close) = close else {
482 break;
483 };
484 let before = text[..i].chars().next_back();
485 let after = text[close + 1..].chars().next();
486 if !before.is_some_and(joins) && !after.is_some_and(joins) && close > i + 1 {
487 spans.push(i..close + 1);
488 }
489 i = close + 1;
490 }
491 spans
492}
493
494pub fn collect_string_interp_refs(src: &str, refs: &mut HashSet<String>) {
504 let chars: Vec<char> = src.chars().collect();
505 let mut i = 0;
506 let mut in_str: Option<char> = None;
507 while i < chars.len() {
508 let c = chars[i];
509 match in_str {
510 Some(quote) if c == quote => {
511 in_str = None;
512 i += 1;
513 }
514 Some(_) if c == '\\' && i + 1 < chars.len() => {
515 i += 2;
516 }
517 Some(_) if c == '{' => {
518 let body_start = i + 1;
519 let mut body_end = body_start;
520 while body_end < chars.len() && chars[body_end] != '}' {
521 body_end += 1;
522 }
523 let body: String = chars[body_start..body_end].iter().collect();
524 let trimmed = body.trim();
525 if !trimmed.is_empty()
526 && !trimmed.starts_with('\'')
527 && !trimmed.starts_with('"')
528 && trimmed
529 .bytes()
530 .all(|b| b.is_ascii_alphanumeric() || b == b'_')
531 && !trimmed.bytes().next().unwrap().is_ascii_digit()
532 {
533 refs.insert(trimmed.to_string());
534 }
535 i = body_end + 1;
536 }
537 Some(_) => {
538 i += 1;
539 }
540 None if c == '"' || c == '\'' => {
541 in_str = Some(c);
542 i += 1;
543 }
544 None => {
545 i += 1;
546 }
547 }
548 }
549}
550
551fn one_pass<F>(s: &mut String, lookup: &F) -> Result<bool, String>
557where
558 F: Fn(&str) -> Option<String>,
559{
560 let bytes = s.as_bytes();
561 let n = bytes.len();
562 let mut out = String::with_capacity(n);
563 let mut i = 0;
564 let mut replaced_any = false;
565
566 while i < n {
567 let c = bytes[i];
568 if c == b'\\' && i + 1 < n && (bytes[i + 1] == b'{' || bytes[i + 1] == b'}') {
569 out.push('\\');
570 out.push(bytes[i + 1] as char);
571 i += 2;
572 continue;
573 }
574 if c == b'{' {
575 let mut j = i + 1;
576 let mut has_inner_open = false;
577 let mut end: Option<usize> = None;
578 while j < n {
579 let cj = bytes[j];
580 if cj == b'\\' && j + 1 < n && (bytes[j + 1] == b'{' || bytes[j + 1] == b'}') {
581 j += 2;
582 continue;
583 }
584 if cj == b'{' {
585 has_inner_open = true;
586 break;
587 }
588 if cj == b'}' {
589 end = Some(j);
590 break;
591 }
592 j += 1;
593 }
594 if has_inner_open {
595 out.push('{');
596 i += 1;
597 continue;
598 }
599 let Some(end_idx) = end else {
600 return Err(format!(
601 "interpolation: unmatched '{{' in '{s}' starting at byte {i} — \
602 write \\{{ for a literal opening brace"
603 ));
604 };
605 let name = std::str::from_utf8(&bytes[i + 1..end_idx])
606 .map_err(|e| format!("interpolation: non-utf8 placeholder in '{s}': {e}"))?
607 .to_string();
608 if name.is_empty() {
609 return Err(format!(
610 "interpolation: empty placeholder '{{}}' in '{s}' — \
611 write \\{{\\}} for literal braces"
612 ));
613 }
614 let value = lookup(&name);
615 let Some(value) = value else {
616 out.push_str(&s[i..=end_idx]);
617 i = end_idx + 1;
618 continue;
619 };
620 out.push_str(&value);
621 i = end_idx + 1;
622 replaced_any = true;
623 continue;
624 }
625 if c < 0x80 {
632 out.push(c as char);
633 i += 1;
634 } else {
635 let ch = s[i..].chars().next().expect("byte index at char boundary");
636 out.push(ch);
637 i += ch.len_utf8();
638 }
639 }
640 *s = out;
641 Ok(replaced_any)
642}
643
644fn first_unresolved(s: &str) -> Option<String> {
648 let bytes = s.as_bytes();
649 let n = bytes.len();
650 let mut i = 0;
651 while i < n {
652 if bytes[i] == b'\\' && i + 1 < n && (bytes[i + 1] == b'{' || bytes[i + 1] == b'}') {
653 i += 2;
654 continue;
655 }
656 if bytes[i] == b'{' {
657 let mut j = i + 1;
658 while j < n {
659 if bytes[j] == b'\\' && j + 1 < n && (bytes[j + 1] == b'{' || bytes[j + 1] == b'}')
660 {
661 j += 2;
662 continue;
663 }
664 if bytes[j] == b'}' {
665 return Some(s[i + 1..j].to_string());
666 }
667 if bytes[j] == b'{' {
668 break;
669 }
670 j += 1;
671 }
672 }
673 i += 1;
674 }
675 None
676}
677
678fn unescape(s: &str) -> String {
682 let mut out = String::with_capacity(s.len());
687 let mut chars = s.chars().peekable();
688 while let Some(c) = chars.next() {
689 if c == '\\'
690 && let Some(&next) = chars.peek()
691 && (next == '{' || next == '}')
692 {
693 out.push(next);
694 chars.next();
695 continue;
696 }
697 out.push(c);
698 }
699 out
700}
701
702#[cfg(test)]
703mod tests {
704 #[test]
705 fn a_whole_placeholder_is_one_placeholder_and_nothing_else() {
706 use super::whole_placeholder;
707 assert_eq!(whole_placeholder("{name}"), Some("name"));
708 assert_eq!(whole_placeholder(" {name} "), Some("name"));
709 assert_eq!(whole_placeholder("{a_{b}}"), Some("a_{b}"));
710 assert_eq!(whole_placeholder("{a_{b}_{c}}"), Some("a_{b}_{c}"));
711 for not_whole in [
712 "name", "x_{name}", "{name}_x", "{a}{b}", "{a}, {b}", "{}", "{ }", "{", "}", "{a",
713 "\\{a\\}", "{a\\}", "[{a}]", "'{a}'",
714 ] {
715 assert_eq!(whole_placeholder(not_whole), None, "{not_whole}");
716 }
717 }
718
719 #[test]
720 fn operands_read_values_and_everything_else_substitutes_text() {
721 use super::{Value, interpolate_operands};
722 let lookup = |name: &str| match name {
723 "size" => Some(Value::Str("1m".into())),
724 "n" => Some(Value::U64(2)),
725 "f" => Some(Value::F64(3.0)),
726 "quoted" => Some(Value::Str("a\"b\\c{d}".into())),
727 "lt_1m" => Some(Value::Str("30m".into())),
728 _ => None,
729 };
730 for (text, expected) in [
731 ("f({size}, 1)", "f(\"1m\", 1)"),
733 ("f( {size} )", "f( \"1m\" )"),
734 ("{size}", "\"1m\""),
735 ("u64_add({n}, 1)", "u64_add(2, 1)"),
736 ("{n} + {f}", "2 + 3.0"),
737 ("-{n}", "-2"),
738 ("f({lt_{size}})", "f(\"30m\")"),
739 ("f({quoted})", "f(\"a\\\"b\\\\c{{d}}\")"),
740 ("x_{size}", "x_1m"),
742 ("{size}_x", "1m_x"),
743 ("{n}.{n}", "2.2"),
744 ("{n}k", "2k"),
745 ("{size}{n}", "1m2"),
746 ("f(\"{size}\", '{size}')", "f(\"1m\", '1m')"),
747 ("f(\"a {size} b\", {size})", "f(\"a 1m b\", \"1m\")"),
748 ("f(1)", "f(1)"),
750 ("f(\\{size\\})", "f({size})"),
751 ] {
752 assert_eq!(
753 interpolate_operands(text, lookup).as_deref(),
754 Ok(expected),
755 "{text}"
756 );
757 }
758 let err = interpolate_operands("f({nope}, {size})", lookup).unwrap_err();
760 assert!(
761 err.starts_with(
762 "interpolation: unresolved placeholder '{nope}' in 'f({nope}, {size})'"
763 ),
764 "{err}"
765 );
766 }
767
768 use super::*;
769 use std::collections::HashMap;
770
771 fn h(pairs: &[(&str, &str)]) -> HashMap<String, String> {
772 pairs
773 .iter()
774 .map(|(k, v)| (k.to_string(), v.to_string()))
775 .collect()
776 }
777
778 #[test]
779 fn interpolate_with_lookup_resolves_leaves() {
780 let m = h(&[("name", "Alice"), ("count", "42")]);
781 let s = interpolate_with_lookup("hello {name}, you have {count} items", |n| {
782 m.get(n).cloned()
783 })
784 .unwrap();
785 assert_eq!(s, "hello Alice, you have 42 items");
786 }
787
788 #[test]
789 fn interpolate_with_lookup_handles_escapes() {
790 let m = h(&[("x", "1")]);
791 let s = interpolate_with_lookup("\\{literal\\} and {x}", |n| m.get(n).cloned()).unwrap();
792 assert_eq!(s, "{literal} and 1");
793 }
794
795 #[test]
796 fn interpolate_with_lookup_resolves_dynamic_via_iteration() {
797 let m = h(&[("b", "X"), ("a_X_c", "RESULT")]);
800 let s = interpolate_with_lookup("got {a_{b}_c}", |n| m.get(n).cloned()).unwrap();
801 assert_eq!(s, "got RESULT");
802 }
803
804 #[test]
805 fn interpolate_with_lookup_errors_on_unresolved() {
806 let m = h(&[]);
807 let err = interpolate_with_lookup("missing: {nope}", |n| m.get(n).cloned()).unwrap_err();
808 assert!(err.contains("unresolved placeholder"));
809 }
810
811 #[test]
812 fn collect_string_interp_refs_picks_quoted_placeholders() {
813 let mut refs = HashSet::new();
814 collect_string_interp_refs(r#"do "x = {var}" and "{another}""#, &mut refs);
815 assert!(refs.contains("var"));
816 assert!(refs.contains("another"));
817 }
818
819 #[test]
820 fn collect_string_interp_refs_skips_outside_strings() {
821 let mut refs = HashSet::new();
822 collect_string_interp_refs("bare {not_picked} and \"yes {picked}\"", &mut refs);
823 assert!(refs.contains("picked"));
824 assert!(!refs.contains("not_picked"));
825 }
826}