use std::collections::HashSet;
use crate::ast::Value;
use crate::kernel::PolydatKernel;
pub trait Lookup {
fn lookup(&self, name: &str) -> Option<Value>;
fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger>;
}
impl Lookup for PolydatKernel {
fn lookup(&self, name: &str) -> Option<Value> {
PolydatKernel::lookup(self, name)
}
fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
self.program().ledger()
}
}
pub struct KernelLookup<'a>(&'a dyn crate::kernel::Kernel);
impl<'a> KernelLookup<'a> {
pub fn new(kernel: &'a dyn crate::kernel::Kernel) -> Self {
KernelLookup(kernel)
}
}
impl Lookup for KernelLookup<'_> {
fn lookup(&self, name: &str) -> Option<Value> {
if self.0.output_modifier(name) == crate::dsl::ast::BindingModifier::CONST
&& let Some(v) = self.0.folded_value(name)
&& !matches!(v, Value::None)
{
return Some(v);
}
if let Some(v) = self.0.input_value(name)
&& !matches!(v, Value::None)
{
return Some(v);
}
if let Some(v) = self.0.folded_value(name)
&& !matches!(v, Value::None)
{
return Some(v);
}
if name.contains('.') {
return self.lookup(&name.replace('.', "__"));
}
None
}
fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
crate::kernel::Kernel::ledger(self.0)
}
}
pub struct NoScope {
ledger: std::sync::Arc<crate::kernel::CompileLedger>,
}
impl NoScope {
pub fn new() -> Self {
Self::charged_to(crate::kernel::CompileLedger::new())
}
pub fn charged_to(ledger: std::sync::Arc<crate::kernel::CompileLedger>) -> Self {
Self { ledger }
}
}
impl Default for NoScope {
fn default() -> Self {
Self::new()
}
}
impl Lookup for NoScope {
fn lookup(&self, _name: &str) -> Option<Value> {
None
}
fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
&self.ledger
}
}
pub struct Layered<'a> {
pub prefix: &'a [(String, Value)],
pub inner: &'a dyn Lookup,
}
impl Lookup for Layered<'_> {
fn lookup(&self, name: &str) -> Option<Value> {
if let Some((_, v)) = self.prefix.iter().find(|(n, _)| n == name) {
return Some(v.clone());
}
self.inner.lookup(name)
}
fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
self.inner.ledger()
}
}
const ROUND_WARN: usize = 100;
const ROUND_HARD: usize = 1000;
pub fn interpolate_via_kernel(
text: &str,
kernel: &dyn Lookup,
) -> Result<String, crate::dsl::compile::EmbeddingError> {
interpolate_with_lookup(text, |name| {
kernel.lookup(name).map(|v| v.to_display_string())
})
.map_err(|msg| classify_interpolate_error(text, msg))
}
fn classify_interpolate_error(text: &str, msg: String) -> crate::dsl::compile::EmbeddingError {
if let Some(rest) = msg.strip_prefix("interpolation: unresolved placeholder '{")
&& let Some(end) = rest.find('}')
{
let name = rest[..end].to_string();
return crate::dsl::compile::EmbeddingError::UnresolvedPlaceholder {
name,
source: text.to_string(),
};
}
crate::dsl::compile::EmbeddingError::Parse {
source: text.to_string(),
message: msg,
position: None,
}
}
pub fn interpolate_with_lookup<F>(text: &str, lookup: F) -> Result<String, String>
where
F: Fn(&str) -> Option<String>,
{
let mut s = text.to_string();
let mut warned = false;
for round in 1..=ROUND_HARD {
if round == ROUND_WARN && !warned {
crate::library::support::audit::warn(&format!(
"interpolation: '{text}' has run {ROUND_WARN} substitution rounds — likely cyclic"
));
warned = true;
}
let progress = one_pass(&mut s, &lookup)?;
if !progress {
break;
}
if round == ROUND_HARD {
return Err(format!(
"interpolation: '{text}' did not stabilize in {ROUND_HARD} rounds — \
cyclic placeholders?"
));
}
}
if let Some(unresolved) = first_unresolved(&s) {
return Err(format!(
"interpolation: unresolved placeholder '{{{unresolved}}}' in '{text}' — \
not bound by any outer for_each var or workload param. \
Use \\{{ \\}} to write literal braces."
));
}
Ok(unescape(&s))
}
pub fn whole_placeholder(text: &str) -> Option<&str> {
let t = text.trim();
let bytes = t.as_bytes();
let n = bytes.len();
if n < 3 || bytes[0] != b'{' || bytes[n - 1] != b'}' {
return None;
}
let mut depth = 0usize;
let mut i = 0;
while i < n {
if bytes[i] == b'\\' && i + 1 < n && (bytes[i + 1] == b'{' || bytes[i + 1] == b'}') {
i += 2;
continue;
}
match bytes[i] {
b'{' => depth += 1,
b'}' => {
depth = depth.checked_sub(1)?;
if depth == 0 && i != n - 1 {
return None;
}
}
_ => {}
}
i += 1;
}
let body = &t[1..n - 1];
(depth == 0 && !body.trim().is_empty()).then_some(body)
}
pub(crate) fn is_name_path(body: &str) -> bool {
let mut chars = body.chars();
chars
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
}
pub fn interpolate_operands<F>(text: &str, lookup: F) -> Result<String, String>
where
F: Fn(&str) -> Option<Value>,
{
let as_text = |name: &str| lookup(name).map(|v| v.to_display_string());
let spans = operand_spans(text);
if spans.is_empty() {
return interpolate_with_lookup(text, as_text);
}
let mut out = String::with_capacity(text.len());
let mut at = 0;
let whole_text_error = || match interpolate_with_lookup(text, as_text) {
Err(message) => message,
Ok(_) => format!("interpolation: '{text}' could not be read"),
};
for span in spans {
out.push_str(
&interpolate_with_lookup(&text[at..span.start], as_text)
.map_err(|_| whole_text_error())?,
);
let placeholder = &text[span.clone()];
let body = &placeholder[1..placeholder.len() - 1];
let value = interpolate_with_lookup(body, as_text)
.ok()
.filter(|name| is_name_path(name.trim()))
.and_then(|name| lookup(name.trim()));
match value {
Some(value) => out.push_str(&operand_literal(&value)),
None => out.push_str(
&interpolate_with_lookup(placeholder, as_text).map_err(|_| whole_text_error())?,
),
}
at = span.end;
}
out.push_str(&interpolate_with_lookup(&text[at..], as_text).map_err(|_| whole_text_error())?);
Ok(out)
}
fn operand_literal(value: &Value) -> String {
let Value::Str(s) = value else {
return value.to_display_string();
};
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'{' => out.push_str("{{"),
'}' => out.push_str("}}"),
other => out.push(other),
}
}
out.push('"');
out
}
fn operand_spans(text: &str) -> Vec<std::ops::Range<usize>> {
let joins =
|c: char| c.is_alphanumeric() || matches!(c, '_' | '.' | '{' | '}' | '\'' | '"' | '\\');
let bytes = text.as_bytes();
let n = bytes.len();
let escaped_brace =
|i: usize| bytes[i] == b'\\' && i + 1 < n && (bytes[i + 1] == b'{' || bytes[i + 1] == b'}');
let mut spans = Vec::new();
let mut quote: Option<u8> = None;
let mut i = 0;
while i < n {
let c = bytes[i];
if let Some(q) = quote {
if c == b'\\' && i + 1 < n {
i += 2;
continue;
}
if c == q {
quote = None;
}
i += 1;
continue;
}
if escaped_brace(i) {
i += 2;
continue;
}
if c == b'"' || c == b'\'' {
quote = Some(c);
i += 1;
continue;
}
if c != b'{' {
i += 1;
continue;
}
let mut depth = 0usize;
let mut j = i;
let mut close = None;
while j < n {
if escaped_brace(j) {
j += 2;
continue;
}
match bytes[j] {
b'{' => depth += 1,
b'}' => {
depth -= 1;
if depth == 0 {
close = Some(j);
break;
}
}
_ => {}
}
j += 1;
}
let Some(close) = close else {
break;
};
let before = text[..i].chars().next_back();
let after = text[close + 1..].chars().next();
if !before.is_some_and(joins) && !after.is_some_and(joins) && close > i + 1 {
spans.push(i..close + 1);
}
i = close + 1;
}
spans
}
pub fn collect_string_interp_refs(src: &str, refs: &mut HashSet<String>) {
let chars: Vec<char> = src.chars().collect();
let mut i = 0;
let mut in_str: Option<char> = None;
while i < chars.len() {
let c = chars[i];
match in_str {
Some(quote) if c == quote => {
in_str = None;
i += 1;
}
Some(_) if c == '\\' && i + 1 < chars.len() => {
i += 2;
}
Some(_) if c == '{' => {
let body_start = i + 1;
let mut body_end = body_start;
while body_end < chars.len() && chars[body_end] != '}' {
body_end += 1;
}
let body: String = chars[body_start..body_end].iter().collect();
let trimmed = body.trim();
if !trimmed.is_empty()
&& !trimmed.starts_with('\'')
&& !trimmed.starts_with('"')
&& trimmed
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_')
&& !trimmed.bytes().next().unwrap().is_ascii_digit()
{
refs.insert(trimmed.to_string());
}
i = body_end + 1;
}
Some(_) => {
i += 1;
}
None if c == '"' || c == '\'' => {
in_str = Some(c);
i += 1;
}
None => {
i += 1;
}
}
}
}
fn one_pass<F>(s: &mut String, lookup: &F) -> Result<bool, String>
where
F: Fn(&str) -> Option<String>,
{
let bytes = s.as_bytes();
let n = bytes.len();
let mut out = String::with_capacity(n);
let mut i = 0;
let mut replaced_any = false;
while i < n {
let c = bytes[i];
if c == b'\\' && i + 1 < n && (bytes[i + 1] == b'{' || bytes[i + 1] == b'}') {
out.push('\\');
out.push(bytes[i + 1] as char);
i += 2;
continue;
}
if c == b'{' {
let mut j = i + 1;
let mut has_inner_open = false;
let mut end: Option<usize> = None;
while j < n {
let cj = bytes[j];
if cj == b'\\' && j + 1 < n && (bytes[j + 1] == b'{' || bytes[j + 1] == b'}') {
j += 2;
continue;
}
if cj == b'{' {
has_inner_open = true;
break;
}
if cj == b'}' {
end = Some(j);
break;
}
j += 1;
}
if has_inner_open {
out.push('{');
i += 1;
continue;
}
let Some(end_idx) = end else {
return Err(format!(
"interpolation: unmatched '{{' in '{s}' starting at byte {i} — \
write \\{{ for a literal opening brace"
));
};
let name = std::str::from_utf8(&bytes[i + 1..end_idx])
.map_err(|e| format!("interpolation: non-utf8 placeholder in '{s}': {e}"))?
.to_string();
if name.is_empty() {
return Err(format!(
"interpolation: empty placeholder '{{}}' in '{s}' — \
write \\{{\\}} for literal braces"
));
}
let value = lookup(&name);
let Some(value) = value else {
out.push_str(&s[i..=end_idx]);
i = end_idx + 1;
continue;
};
out.push_str(&value);
i = end_idx + 1;
replaced_any = true;
continue;
}
if c < 0x80 {
out.push(c as char);
i += 1;
} else {
let ch = s[i..].chars().next().expect("byte index at char boundary");
out.push(ch);
i += ch.len_utf8();
}
}
*s = out;
Ok(replaced_any)
}
fn first_unresolved(s: &str) -> Option<String> {
let bytes = s.as_bytes();
let n = bytes.len();
let mut i = 0;
while i < n {
if bytes[i] == b'\\' && i + 1 < n && (bytes[i + 1] == b'{' || bytes[i + 1] == b'}') {
i += 2;
continue;
}
if bytes[i] == b'{' {
let mut j = i + 1;
while j < n {
if bytes[j] == b'\\' && j + 1 < n && (bytes[j + 1] == b'{' || bytes[j + 1] == b'}')
{
j += 2;
continue;
}
if bytes[j] == b'}' {
return Some(s[i + 1..j].to_string());
}
if bytes[j] == b'{' {
break;
}
j += 1;
}
}
i += 1;
}
None
}
fn unescape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '\\'
&& let Some(&next) = chars.peek()
&& (next == '{' || next == '}')
{
out.push(next);
chars.next();
continue;
}
out.push(c);
}
out
}
#[cfg(test)]
mod tests {
#[test]
fn a_whole_placeholder_is_one_placeholder_and_nothing_else() {
use super::whole_placeholder;
assert_eq!(whole_placeholder("{name}"), Some("name"));
assert_eq!(whole_placeholder(" {name} "), Some("name"));
assert_eq!(whole_placeholder("{a_{b}}"), Some("a_{b}"));
assert_eq!(whole_placeholder("{a_{b}_{c}}"), Some("a_{b}_{c}"));
for not_whole in [
"name", "x_{name}", "{name}_x", "{a}{b}", "{a}, {b}", "{}", "{ }", "{", "}", "{a",
"\\{a\\}", "{a\\}", "[{a}]", "'{a}'",
] {
assert_eq!(whole_placeholder(not_whole), None, "{not_whole}");
}
}
#[test]
fn operands_read_values_and_everything_else_substitutes_text() {
use super::{Value, interpolate_operands};
let lookup = |name: &str| match name {
"size" => Some(Value::Str("1m".into())),
"n" => Some(Value::U64(2)),
"f" => Some(Value::F64(3.0)),
"quoted" => Some(Value::Str("a\"b\\c{d}".into())),
"lt_1m" => Some(Value::Str("30m".into())),
_ => None,
};
for (text, expected) in [
("f({size}, 1)", "f(\"1m\", 1)"),
("f( {size} )", "f( \"1m\" )"),
("{size}", "\"1m\""),
("u64_add({n}, 1)", "u64_add(2, 1)"),
("{n} + {f}", "2 + 3.0"),
("-{n}", "-2"),
("f({lt_{size}})", "f(\"30m\")"),
("f({quoted})", "f(\"a\\\"b\\\\c{{d}}\")"),
("x_{size}", "x_1m"),
("{size}_x", "1m_x"),
("{n}.{n}", "2.2"),
("{n}k", "2k"),
("{size}{n}", "1m2"),
("f(\"{size}\", '{size}')", "f(\"1m\", '1m')"),
("f(\"a {size} b\", {size})", "f(\"a 1m b\", \"1m\")"),
("f(1)", "f(1)"),
("f(\\{size\\})", "f({size})"),
] {
assert_eq!(
interpolate_operands(text, lookup).as_deref(),
Ok(expected),
"{text}"
);
}
let err = interpolate_operands("f({nope}, {size})", lookup).unwrap_err();
assert!(
err.starts_with(
"interpolation: unresolved placeholder '{nope}' in 'f({nope}, {size})'"
),
"{err}"
);
}
use super::*;
use std::collections::HashMap;
fn h(pairs: &[(&str, &str)]) -> HashMap<String, String> {
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
}
#[test]
fn interpolate_with_lookup_resolves_leaves() {
let m = h(&[("name", "Alice"), ("count", "42")]);
let s = interpolate_with_lookup("hello {name}, you have {count} items", |n| {
m.get(n).cloned()
})
.unwrap();
assert_eq!(s, "hello Alice, you have 42 items");
}
#[test]
fn interpolate_with_lookup_handles_escapes() {
let m = h(&[("x", "1")]);
let s = interpolate_with_lookup("\\{literal\\} and {x}", |n| m.get(n).cloned()).unwrap();
assert_eq!(s, "{literal} and 1");
}
#[test]
fn interpolate_with_lookup_resolves_dynamic_via_iteration() {
let m = h(&[("b", "X"), ("a_X_c", "RESULT")]);
let s = interpolate_with_lookup("got {a_{b}_c}", |n| m.get(n).cloned()).unwrap();
assert_eq!(s, "got RESULT");
}
#[test]
fn interpolate_with_lookup_errors_on_unresolved() {
let m = h(&[]);
let err = interpolate_with_lookup("missing: {nope}", |n| m.get(n).cloned()).unwrap_err();
assert!(err.contains("unresolved placeholder"));
}
#[test]
fn collect_string_interp_refs_picks_quoted_placeholders() {
let mut refs = HashSet::new();
collect_string_interp_refs(r#"do "x = {var}" and "{another}""#, &mut refs);
assert!(refs.contains("var"));
assert!(refs.contains("another"));
}
#[test]
fn collect_string_interp_refs_skips_outside_strings() {
let mut refs = HashSet::new();
collect_string_interp_refs("bare {not_picked} and \"yes {picked}\"", &mut refs);
assert!(refs.contains("picked"));
assert!(!refs.contains("not_picked"));
}
}