Skip to main content

polydat_core/kernel/
interp.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! `{name}`-style template interpolation against a Polydat Kernel.
5//!
6//! Polydat's one name-resolution surface (expression_engine.md §3.2).
7//! It lives in the kernel module because the operation is a general
8//! kernel facility, not a comprehension concern: the comprehension
9//! runtime uses it, synthesisers use it, and the executor uses it,
10//! and none of them depends on the comprehension AST's shape.
11//!
12//! ## Functions
13//!
14//! - [`interpolate_via_kernel`] — looks up `{name}` placeholders
15//!   against the kernel's chain-aware bindings via
16//!   [`PolydatKernel::lookup`].
17//! - [`interpolate_with_lookup`] — the generic engine; the
18//!   `lookup` closure decides where each leaf's value comes
19//!   from. Used by callers that compose their own lookup over
20//!   the kernel plus workload params plus synthesis-time
21//!   probes.
22//! - [`interpolate_operands`] — for an expression: a placeholder
23//!   that is a whole operand reads its value with its type, and
24//!   every other placeholder substitutes text.
25//! - [`whole_placeholder`] — whether a text is one placeholder
26//!   and nothing else.
27//! - [`collect_string_interp_refs`] — extracts the placeholder
28//!   names from a text without doing substitution.
29//!
30//! ## Semantics
31//!
32//! Iterative leaf-placeholder substitution with escape handling
33//! and a round cap:
34//!
35//! - **Leaf**: `{name}` whose body contains no further `{`. The
36//!   dynamic form `{a_{b}_c}` is resolved by first substituting
37//!   `{b}`, then re-scanning for the resulting `{a_<b-value>_c}`
38//!   as a leaf.
39//! - **Escape**: `\{` and `\}` pass through as literal `{` /
40//!   `}` and are removed from the final string.
41//! - **Round cap**: if substitution doesn't stabilize in
42//!   `ROUND_HARD` iterations, returns Err (the input had
43//!   cyclic placeholders).
44//! - **Unresolved name**: any `{name}` that survives the
45//!   substitution rounds errors with a diagnostic naming the
46//!   missing binding.
47
48use std::collections::HashSet;
49
50use crate::ast::Value;
51use crate::kernel::PolydatKernel;
52
53/// Name resolution for comprehension sources and predicates: what a
54/// `{name}` placeholder or a bare identifier reads. The interpreter
55/// kernel is one; a [`Layered`] view puts a tuple's bindings in front of
56/// another, so opening a traversal needs no kernel of the engine that
57/// opens it (engines.md §3.6).
58pub trait Lookup {
59    /// The value `name` denotes here, if any.
60    fn lookup(&self, name: &str) -> Option<Value>;
61
62    /// The compile ledger of the program tree this scope belongs to:
63    /// what a source or predicate that has to compile is charged to.
64    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
76/// A kernel of any engine, as a scope names resolve in.
77///
78/// A host holding a `Box<dyn Kernel>` interpolates `{k} > 5` against
79/// the kernel it has through this wrapper, without compiling the
80/// program a second time on the interpreter. It is a wrapper rather
81/// than an `impl Lookup for dyn Kernel` because one trait object
82/// cannot become another.
83///
84/// Distinct from
85/// [`comprehension::surfaces::KernelScope`](crate::iteration::comprehension::surfaces::KernelScope),
86/// the algebra layer's trait for the parent a comprehension scopes
87/// under; this is a `Lookup` over a kernel that already exists.
88pub struct KernelLookup<'a>(&'a dyn crate::kernel::Kernel);
89
90impl<'a> KernelLookup<'a> {
91    /// The kernel as a scope.
92    pub fn new(kernel: &'a dyn crate::kernel::Kernel) -> Self {
93        KernelLookup(kernel)
94    }
95}
96
97impl Lookup for KernelLookup<'_> {
98    /// A name resolves to what the kernel holds for it now — an input
99    /// the host wrote, a coordinate it was positioned at — and
100    /// otherwise to what the build folded for it. The live answer
101    /// comes first because it is the later one: a coordinate has a
102    /// folded value on some engines, and it is the value the program
103    /// was built with, not the value the kernel is at.
104    ///
105    /// A `const` binding is the exception. Its value is the scope's for
106    /// the name, and an input slot of the same name, which a const that
107    /// reads a parameter it shadows is given (none_semantics.md,
108    /// "Conditional-shadow semantics for `const`"), holds only the
109    /// value from the scope above. So the const's own value comes
110    /// first, and the slot answers only while that value is `None`: the
111    /// two-tier read of a conditional shadow.
112    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        // `a.b` lowers to the wire `a__b`, so a text reference like
130        // `{q.cursor.idx}` resolves through the same flattening the
131        // compiler applies.
132        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
142/// The empty scope: no name resolves in it, and what has to compile
143/// under it is charged to the ledger it holds. A context-free source,
144/// one whose expression references no name, evaluates in this scope
145/// (comprehension_forms.md §10.7.0), at compile time or wherever no
146/// kernel is at hand.
147pub struct NoScope {
148    ledger: std::sync::Arc<crate::kernel::CompileLedger>,
149}
150
151impl NoScope {
152    /// An empty scope charging to a fresh ledger of its own.
153    pub fn new() -> Self {
154        Self::charged_to(crate::kernel::CompileLedger::new())
155    }
156
157    /// An empty scope charging to `ledger`: the program tree's, when
158    /// the evaluation is part of that tree's compile.
159    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
179/// Bindings in front of another lookup: a tuple's elements over the
180/// scope they were drawn in.
181pub struct Layered<'a> {
182    /// The bindings consulted first, in order.
183    pub prefix: &'a [(String, Value)],
184    /// Where every other name resolves.
185    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
200/// Round count at which we warn about possible cycles in the
201/// substitution stream.
202const ROUND_WARN: usize = 100;
203
204/// Hard round-count limit. Errors out if substitution doesn't
205/// stabilize in this many iterations.
206const ROUND_HARD: usize = 1000;
207
208/// Interpolate `{name}` placeholders against `kernel`.
209///
210/// `{name}` resolves to `kernel.lookup(name).map(|v| v.to_display_string())`.
211/// `Value::None` (an unset extern slot) doesn't match — falls
212/// through to the unresolved-name error path at the fixed
213/// point.
214///
215/// Returns a typed [`crate::dsl::compile::EmbeddingError`] per
216/// E7 of the spec; the underlying string-form
217/// [`interpolate_with_lookup`] is kept for callers that
218/// compose their own lookup and don't want the
219/// typed-error overhead.
220pub 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    // "interpolation: unresolved placeholder '{name}' in '...'"
232    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    // Cyclic placeholder fall-through: classify as Parse since
242    // the text didn't stabilise.
243    crate::dsl::compile::EmbeddingError::Parse {
244        source: text.to_string(),
245        message: msg,
246        position: None,
247    }
248}
249
250/// Iterative leaf-placeholder substitution with escape handling,
251/// round cap, and final unresolved-name check. The `lookup`
252/// closure decides where each leaf's value comes from.
253///
254/// Public so callers like the synthesis-time clause probe can
255/// compose their own lookup (parent kernel + workload params +
256/// clause probes) without reimplementing the iterative loop.
257pub 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
291/// The body of `text` when it is one placeholder and nothing else:
292/// `{name}` gives `name`, and `{a_{b}}` gives `a_{b}`. `None` for text
293/// with anything beside the placeholder (`x_{name}`, `{a}{b}`), for an
294/// escaped brace, and for an empty body.
295///
296/// A placeholder that is a whole operand reads the value its name is
297/// bound to, with its type, as the bare name does
298/// (comprehension_forms.md §3.1.5); any other placeholder substitutes
299/// text.
300pub 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
330/// Whether a placeholder body is a name: an identifier, or a dotted
331/// path (`q.cursor.idx`, or `t_0.5_vals` composed from a float), and
332/// not an expression or a format specifier.
333pub(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
341/// Interpolate an expression's placeholders, reading each placeholder
342/// that is a whole operand as the value its name is bound to
343/// (comprehension_forms.md §3.1.5).
344///
345/// A placeholder is a whole operand when it stands outside a quoted
346/// string and no character of a larger token touches it: in
347/// `f({size}, 1)` and `{n} + 1` it is one, and in `x_{size}`,
348/// `{a}.{b}` and `"{size}"` it is not. A whole operand whose name
349/// (composed from its leaves first, for `{a_{b}}`) is bound is written
350/// as a literal the language reads back as that value: a string is
351/// quoted, and every other value is written as it displays. Every
352/// other placeholder substitutes text, as [`interpolate_with_lookup`]
353/// does, and a whole operand whose name is not bound is left to that
354/// rule, so an unresolved name is reported the same way.
355pub 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    // A piece that fails is reported as the whole text's failure, which
367    // names the text the author wrote.
368    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
395/// `value` as a literal of the language that reads back as `value`: a
396/// string quoted, with its quotes, backslashes and braces escaped, and
397/// any other value as it displays.
398fn 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
419/// The byte ranges of the placeholders of `text` that are whole
420/// operands ([`interpolate_operands`]), in order.
421fn operand_spans(text: &str) -> Vec<std::ops::Range<usize>> {
422    // A character that makes a placeholder beside it part of a larger
423    // token: a name or number, a path, another placeholder, a quote.
424    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        // The brace that closes this one.
460        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
494/// Extract every leaf `{name}` placeholder mentioned inside
495/// string-literal contexts in `src` into `refs`.
496///
497/// Used by the synthesiser to discover names the body
498/// references via `{name}` interpolation that don't appear as
499/// bare identifiers in the Polydat source. The detection is
500/// quote-aware: leading non-identifier chars (`'`, `"`) skip
501/// the placeholder, matching the binding compiler's
502/// `string_lit_has_real_placeholder` disambiguation.
503pub 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
551/// One sweep over `s`: replaces every **leaf** placeholder
552/// (`{NAME}` whose body contains no `{` or `}`) with its
553/// resolved value via the supplied `lookup` closure. Returns
554/// `Ok(true)` if any replacement happened, `Ok(false)` if the
555/// pass was a no-op (fixed point reached).
556fn 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        // Passthrough. ASCII bytes copy directly; a non-ASCII
626        // lead byte starts a multi-byte UTF-8 char that must be
627        // copied whole (`c as char` would split it into mojibake).
628        // `i` is always at a char boundary here — the scanner only
629        // advances past ASCII specials (`{` `}` `\`) or whole
630        // placeholders.
631        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
644/// Locate the first unresolved leaf placeholder name (after
645/// fixed-point iteration) for the diagnostic message. Returns
646/// `None` if every `{...}` is escaped or already resolved.
647fn 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
678/// Strip `\{` → `{` and `\}` → `}`. Other escapes pass through
679/// untouched so the substituted text doesn't gain newlines or
680/// other surprises the user didn't ask for.
681fn unescape(s: &str) -> String {
682    // Char-based, not byte-based: `bytes[i] as char` would split
683    // any multi-byte UTF-8 sequence (e.g. `…` U+2026) into
684    // mojibake. Only `\{` and `\}` are unescaped; every other
685    // character — ASCII or not — passes through intact.
686    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            // A whole operand: a string is quoted, a number is itself.
732            ("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            // Part of a larger token, or inside quotes: text.
741            ("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            // No placeholder, and an escaped brace.
749            ("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        // An unbound whole operand is reported as the text rule does.
759        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        // `{a_{b}_c}` resolves by first substituting {b} = "X",
798        // then re-scanning to find `{a_X_c}` as a leaf.
799        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}