polydat-core 0.13.1

Polydat runtime: value model, graph compiler, execution engines, kernels
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! `{name}`-style template interpolation against a Polydat Kernel.
//!
//! Polydat's one name-resolution surface (expression_engine.md §3.2).
//! It lives in the kernel module because the operation is a general
//! kernel facility, not a comprehension concern: the comprehension
//! runtime uses it, synthesisers use it, and the executor uses it,
//! and none of them depends on the comprehension AST's shape.
//!
//! ## Functions
//!
//! - [`interpolate_via_kernel`] — looks up `{name}` placeholders
//!   against the kernel's chain-aware bindings via
//!   [`PolydatKernel::lookup`].
//! - [`interpolate_with_lookup`] — the generic engine; the
//!   `lookup` closure decides where each leaf's value comes
//!   from. Used by callers that compose their own lookup over
//!   the kernel plus workload params plus synthesis-time
//!   probes.
//! - [`interpolate_operands`] — for an expression: a placeholder
//!   that is a whole operand reads its value with its type, and
//!   every other placeholder substitutes text.
//! - [`whole_placeholder`] — whether a text is one placeholder
//!   and nothing else.
//! - [`collect_string_interp_refs`] — extracts the placeholder
//!   names from a text without doing substitution.
//!
//! ## Semantics
//!
//! Iterative leaf-placeholder substitution with escape handling
//! and a round cap:
//!
//! - **Leaf**: `{name}` whose body contains no further `{`. The
//!   dynamic form `{a_{b}_c}` is resolved by first substituting
//!   `{b}`, then re-scanning for the resulting `{a_<b-value>_c}`
//!   as a leaf.
//! - **Escape**: `\{` and `\}` pass through as literal `{` /
//!   `}` and are removed from the final string.
//! - **Round cap**: if substitution doesn't stabilize in
//!   `ROUND_HARD` iterations, returns Err (the input had
//!   cyclic placeholders).
//! - **Unresolved name**: any `{name}` that survives the
//!   substitution rounds errors with a diagnostic naming the
//!   missing binding.

use std::collections::HashSet;

use crate::ast::Value;
use crate::kernel::PolydatKernel;

/// Name resolution for comprehension sources and predicates: what a
/// `{name}` placeholder or a bare identifier reads. The interpreter
/// kernel is one; a [`Layered`] view puts a tuple's bindings in front of
/// another, so opening a traversal needs no kernel of the engine that
/// opens it (engines.md §3.6).
pub trait Lookup {
    /// The value `name` denotes here, if any.
    fn lookup(&self, name: &str) -> Option<Value>;

    /// The compile ledger of the program tree this scope belongs to:
    /// what a source or predicate that has to compile is charged to.
    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()
    }
}

/// A kernel of any engine, as a scope names resolve in.
///
/// A host holding a `Box<dyn Kernel>` interpolates `{k} > 5` against
/// the kernel it has through this wrapper, without compiling the
/// program a second time on the interpreter. It is a wrapper rather
/// than an `impl Lookup for dyn Kernel` because one trait object
/// cannot become another.
///
/// Distinct from
/// [`comprehension::surfaces::KernelScope`](crate::iteration::comprehension::surfaces::KernelScope),
/// the algebra layer's trait for the parent a comprehension scopes
/// under; this is a `Lookup` over a kernel that already exists.
pub struct KernelLookup<'a>(&'a dyn crate::kernel::Kernel);

impl<'a> KernelLookup<'a> {
    /// The kernel as a scope.
    pub fn new(kernel: &'a dyn crate::kernel::Kernel) -> Self {
        KernelLookup(kernel)
    }
}

impl Lookup for KernelLookup<'_> {
    /// A name resolves to what the kernel holds for it now — an input
    /// the host wrote, a coordinate it was positioned at — and
    /// otherwise to what the build folded for it. The live answer
    /// comes first because it is the later one: a coordinate has a
    /// folded value on some engines, and it is the value the program
    /// was built with, not the value the kernel is at.
    ///
    /// A `const` binding is the exception. Its value is the scope's for
    /// the name, and an input slot of the same name, which a const that
    /// reads a parameter it shadows is given (none_semantics.md,
    /// "Conditional-shadow semantics for `const`"), holds only the
    /// value from the scope above. So the const's own value comes
    /// first, and the slot answers only while that value is `None`: the
    /// two-tier read of a conditional shadow.
    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);
        }
        // `a.b` lowers to the wire `a__b`, so a text reference like
        // `{q.cursor.idx}` resolves through the same flattening the
        // compiler applies.
        if name.contains('.') {
            return self.lookup(&name.replace('.', "__"));
        }
        None
    }
    fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
        crate::kernel::Kernel::ledger(self.0)
    }
}

/// The empty scope: no name resolves in it, and what has to compile
/// under it is charged to the ledger it holds. A context-free source,
/// one whose expression references no name, evaluates in this scope
/// (comprehension_forms.md §10.7.0), at compile time or wherever no
/// kernel is at hand.
pub struct NoScope {
    ledger: std::sync::Arc<crate::kernel::CompileLedger>,
}

impl NoScope {
    /// An empty scope charging to a fresh ledger of its own.
    pub fn new() -> Self {
        Self::charged_to(crate::kernel::CompileLedger::new())
    }

    /// An empty scope charging to `ledger`: the program tree's, when
    /// the evaluation is part of that tree's compile.
    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
    }
}

/// Bindings in front of another lookup: a tuple's elements over the
/// scope they were drawn in.
pub struct Layered<'a> {
    /// The bindings consulted first, in order.
    pub prefix: &'a [(String, Value)],
    /// Where every other name resolves.
    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()
    }
}

/// Round count at which we warn about possible cycles in the
/// substitution stream.
const ROUND_WARN: usize = 100;

/// Hard round-count limit. Errors out if substitution doesn't
/// stabilize in this many iterations.
const ROUND_HARD: usize = 1000;

/// Interpolate `{name}` placeholders against `kernel`.
///
/// `{name}` resolves to `kernel.lookup(name).map(|v| v.to_display_string())`.
/// `Value::None` (an unset extern slot) doesn't match — falls
/// through to the unresolved-name error path at the fixed
/// point.
///
/// Returns a typed [`crate::dsl::compile::EmbeddingError`] per
/// E7 of the spec; the underlying string-form
/// [`interpolate_with_lookup`] is kept for callers that
/// compose their own lookup and don't want the
/// typed-error overhead.
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 {
    // "interpolation: unresolved placeholder '{name}' in '...'"
    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(),
        };
    }
    // Cyclic placeholder fall-through: classify as Parse since
    // the text didn't stabilise.
    crate::dsl::compile::EmbeddingError::Parse {
        source: text.to_string(),
        message: msg,
        position: None,
    }
}

/// Iterative leaf-placeholder substitution with escape handling,
/// round cap, and final unresolved-name check. The `lookup`
/// closure decides where each leaf's value comes from.
///
/// Public so callers like the synthesis-time clause probe can
/// compose their own lookup (parent kernel + workload params +
/// clause probes) without reimplementing the iterative loop.
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))
}

/// The body of `text` when it is one placeholder and nothing else:
/// `{name}` gives `name`, and `{a_{b}}` gives `a_{b}`. `None` for text
/// with anything beside the placeholder (`x_{name}`, `{a}{b}`), for an
/// escaped brace, and for an empty body.
///
/// A placeholder that is a whole operand reads the value its name is
/// bound to, with its type, as the bare name does
/// (comprehension_forms.md §3.1.5); any other placeholder substitutes
/// text.
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)
}

/// Whether a placeholder body is a name: an identifier, or a dotted
/// path (`q.cursor.idx`, or `t_0.5_vals` composed from a float), and
/// not an expression or a format specifier.
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 == '.')
}

/// Interpolate an expression's placeholders, reading each placeholder
/// that is a whole operand as the value its name is bound to
/// (comprehension_forms.md §3.1.5).
///
/// A placeholder is a whole operand when it stands outside a quoted
/// string and no character of a larger token touches it: in
/// `f({size}, 1)` and `{n} + 1` it is one, and in `x_{size}`,
/// `{a}.{b}` and `"{size}"` it is not. A whole operand whose name
/// (composed from its leaves first, for `{a_{b}}`) is bound is written
/// as a literal the language reads back as that value: a string is
/// quoted, and every other value is written as it displays. Every
/// other placeholder substitutes text, as [`interpolate_with_lookup`]
/// does, and a whole operand whose name is not bound is left to that
/// rule, so an unresolved name is reported the same way.
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;
    // A piece that fails is reported as the whole text's failure, which
    // names the text the author wrote.
    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)
}

/// `value` as a literal of the language that reads back as `value`: a
/// string quoted, with its quotes, backslashes and braces escaped, and
/// any other value as it displays.
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
}

/// The byte ranges of the placeholders of `text` that are whole
/// operands ([`interpolate_operands`]), in order.
fn operand_spans(text: &str) -> Vec<std::ops::Range<usize>> {
    // A character that makes a placeholder beside it part of a larger
    // token: a name or number, a path, another placeholder, a quote.
    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;
        }
        // The brace that closes this one.
        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
}

/// Extract every leaf `{name}` placeholder mentioned inside
/// string-literal contexts in `src` into `refs`.
///
/// Used by the synthesiser to discover names the body
/// references via `{name}` interpolation that don't appear as
/// bare identifiers in the Polydat source. The detection is
/// quote-aware: leading non-identifier chars (`'`, `"`) skip
/// the placeholder, matching the binding compiler's
/// `string_lit_has_real_placeholder` disambiguation.
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;
            }
        }
    }
}

/// One sweep over `s`: replaces every **leaf** placeholder
/// (`{NAME}` whose body contains no `{` or `}`) with its
/// resolved value via the supplied `lookup` closure. Returns
/// `Ok(true)` if any replacement happened, `Ok(false)` if the
/// pass was a no-op (fixed point reached).
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;
        }
        // Passthrough. ASCII bytes copy directly; a non-ASCII
        // lead byte starts a multi-byte UTF-8 char that must be
        // copied whole (`c as char` would split it into mojibake).
        // `i` is always at a char boundary here — the scanner only
        // advances past ASCII specials (`{` `}` `\`) or whole
        // placeholders.
        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)
}

/// Locate the first unresolved leaf placeholder name (after
/// fixed-point iteration) for the diagnostic message. Returns
/// `None` if every `{...}` is escaped or already resolved.
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
}

/// Strip `\{` → `{` and `\}` → `}`. Other escapes pass through
/// untouched so the substituted text doesn't gain newlines or
/// other surprises the user didn't ask for.
fn unescape(s: &str) -> String {
    // Char-based, not byte-based: `bytes[i] as char` would split
    // any multi-byte UTF-8 sequence (e.g. `…` U+2026) into
    // mojibake. Only `\{` and `\}` are unescaped; every other
    // character — ASCII or not — passes through intact.
    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 [
            // A whole operand: a string is quoted, a number is itself.
            ("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}}\")"),
            // Part of a larger token, or inside quotes: text.
            ("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\")"),
            // No placeholder, and an escaped brace.
            ("f(1)", "f(1)"),
            ("f(\\{size\\})", "f({size})"),
        ] {
            assert_eq!(
                interpolate_operands(text, lookup).as_deref(),
                Ok(expected),
                "{text}"
            );
        }
        // An unbound whole operand is reported as the text rule does.
        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() {
        // `{a_{b}_c}` resolves by first substituting {b} = "X",
        // then re-scanning to find `{a_X_c}` as a leaf.
        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"));
    }
}