Skip to main content

oxdock_parser/
template.rs

1//! Template placeholder scanning shared by expansion and static
2//! checks: one implementation of the `{{ ... }}` rules, so the two
3//! can never disagree on what counts as a read.
4//!
5//! Rules (mirroring the historical `expand_string` loop one for one):
6//! - `\{{` is literal text, never an opener. `\\` is a literal
7//!   backslash and never escapes what follows it.
8//! - A lone backslash escapes nothing for scanning: only the
9//!   backslash is literal, the next character reprocesses normally.
10//! - `{{` opens only when a matching `}}` follows; otherwise the rest
11//!   is literal text, exactly as expansion renders it verbatim.
12//! - Placeholder keys arrive trimmed; closers never nest.
13//! - Byte-oriented and allocation-free: braces and the backslash are
14//!   ASCII, so no multibyte character can match, and every cut lands
15//!   on an ASCII boundary.
16
17/// One raw segment of template text: literal bytes, or one unescaped
18/// `{{ ... }}` with its trimmed key plus the verbatim raw slice.
19/// Escapes are NOT processed here; consumers apply them to
20/// [`TemplateSegment::Text`] themselves.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum TemplateSegment<'a> {
23    /// Literal text up to the next placeholder (may hold backslashes
24    /// and unclosed `{{`, verbatim).
25    Text(&'a str),
26    /// An unescaped placeholder; `key` is the trimmed interior and
27    /// `raw` is the full `{{ ... }}` slice verbatim (braces plus the
28    /// original inner spacing), so rewriters can splice the key
29    /// without touching surrounding bytes.
30    Placeholder { key: &'a str, raw: &'a str },
31}
32
33/// One parsed `{{ ... }}` call body: `[MODULE::]FUNC(args_raw)`.
34///
35/// Single grammar behind every phase: parse-time qualification,
36/// static checking, and runtime dispatch all read the same shape,
37/// so the three can never disagree on what counts as a call.
38/// `module` is `None` for bare `FUNC(...)` heads (statement-scope
39/// resolution decides those); `name_span` is the byte range of
40/// `name` inside the input `key`, so rewriters can splice exactly
41/// the head without touching surrounding spacing.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct PlaceholderCall<'a> {
44    /// `MODULE` in `MODULE::FUNC(...)`, or `None` for bare heads.
45    pub module: Option<&'a str>,
46    /// Function head (`FUNC`).
47    pub name: &'a str,
48    /// Byte range of `name` inside the input `key`.
49    pub name_span: std::ops::Range<usize>,
50    /// Raw bytes between the parens (untrimmed, unsplit).
51    pub args_raw: &'a str,
52}
53
54fn is_module_char(c: char) -> bool {
55    c.is_ascii_alphanumeric() || c == '_' || c == '-'
56}
57
58fn is_bare_head(name: &str) -> bool {
59    let mut chars = name.chars();
60    if !chars.next().is_some_and(|c| c.is_ascii_uppercase()) {
61        return false;
62    }
63    chars.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
64}
65
66/// Parse one placeholder key as `[MODULE::]FUNC(args)`.
67///
68/// Returns `None` when the key is not exactly one call: missing
69/// parens, lowercase bare heads, bad `MODULE`/`FUNC` spellings, an
70/// unbalanced paren group, or trailing bytes past the closer
71/// (compounds like `LEN($a) + LEN($b)` stay untouched). The paren
72/// scan tracks both quote styles with backslash escapes, so a paren
73/// inside `'a(b'` or `"a(b"` never affects depth; whether the arg
74/// grammar accepts that style is the caller's decision.
75pub fn parse_placeholder_call(key: &str) -> Option<PlaceholderCall<'_>> {
76    let trimmed = key.trim();
77    if trimmed.is_empty() {
78        return None;
79    }
80    let base = key.find(trimmed).unwrap_or(0);
81    let paren = trimmed.find('(')?;
82    let (head_raw, rest) = trimmed.split_at(paren);
83    let head = head_raw.trim_end();
84    if head.is_empty() {
85        return None;
86    }
87    enum Head<'a> {
88        Bare(&'a str),
89        Qualified { name: &'a str, start: usize },
90    }
91    let head_parsed = if let Some((left, right)) = head.split_once("::") {
92        if left.is_empty() || !left.chars().all(is_module_char) {
93            return None;
94        }
95        let name = right.trim();
96        if name.is_empty() || !name.chars().all(is_module_char) {
97            return None;
98        }
99        // Qualified heads stay permissive here (runtime spellings
100        // allow `alnum _ -`); resolution validates case later, so an
101        // unknown-case head still fails naming the culprit.
102        // `head` opens `trimmed`, so the name offset inside `head`
103        // is its offset inside `trimmed` too.
104        let colon = head.find("::").expect("split found ::");
105        let leading = head[colon + 2..].len() - head[colon + 2..].trim_start().len();
106        Head::Qualified {
107            name,
108            start: colon + 2 + leading,
109        }
110    } else {
111        if !is_bare_head(head) {
112            return None;
113        }
114        Head::Bare(head)
115    };
116    // The shared atom scan drives depth: quoted runs (including
117    // `"""` blocks) arrive whole as Text, so parens inside strings
118    // never count. Only structural opens and closes move depth.
119    let mut depth: usize = 0;
120    let mut close_at: Option<usize> = None;
121    for atom in scan_atoms(rest) {
122        match atom.kind {
123            // Only parens move depth here, exactly as before: quoted
124            // runs arrive whole as Text, and other brackets never
125            // counted. Unbalanced cross-kind input fails closed below.
126            AtomKind::Open if atom.text == "(" => depth += 1,
127            AtomKind::Close if atom.text == ")" => {
128                if depth == 0 {
129                    return None;
130                }
131                depth -= 1;
132                if depth == 0 {
133                    close_at = Some(atom.start);
134                    break;
135                }
136            }
137            _ => {}
138        }
139    }
140    let close_at = close_at?;
141    if !rest[close_at + 1..].trim().is_empty() {
142        return None;
143    }
144    let args_raw = &rest[1..close_at];
145    match head_parsed {
146        Head::Bare(name) => {
147            let start = base + trimmed.find(name).unwrap_or(0);
148            Some(PlaceholderCall {
149                module: None,
150                name,
151                name_span: start..start + name.len(),
152                args_raw,
153            })
154        }
155        Head::Qualified { name, start } => {
156            let abs = base + start;
157            Some(PlaceholderCall {
158                module: Some(&head[..head.find("::").expect("split found ::")]),
159                name,
160                name_span: abs..abs + name.len(),
161                args_raw,
162            })
163        }
164    }
165}
166
167/// One lexical atom of placeholder arg text. Bracket depth tracking
168/// and top-level splitting share this single scan, so quote rules —
169/// including `"""` blocks — can never disagree between the splitter
170/// and the paren matcher.
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub enum AtomKind {
173    /// One of `([{`.
174    Open,
175    /// One of `)]}`.
176    Close,
177    /// A separator candidate (`,` or `:`); consumers decide which splits.
178    Sep(char),
179    /// Anything else: a maximal run that is either one quoted string
180    /// (`".."`, `'..'`, or a whole `""".."""` block with backslash
181    /// escapes honored) or unquoted text up to the next structural
182    /// character. Commas and brackets inside a quoted run never surface.
183    Text,
184}
185
186/// A scanned atom with its byte offset in the scanned source.
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub struct Atom<'a> {
189    pub kind: AtomKind,
190    pub text: &'a str,
191    pub start: usize,
192}
193
194/// Scan placeholder arg text into atoms. Unterminated quotes run to
195/// end of input as text; downstream value resolution fails those
196/// closed, exactly as before.
197pub fn scan_atoms(src: &str) -> Vec<Atom<'_>> {
198    let bytes = src.as_bytes();
199    let mut out = Vec::new();
200    let mut i = 0;
201    let mut text_from: Option<usize> = None;
202    while i < bytes.len() {
203        let b = bytes[i];
204        // A `"""` opener consumes through its unescaped closer.
205        if b == b'"' && bytes.get(i + 1) == Some(&b'"') && bytes.get(i + 2) == Some(&b'"') {
206            if let Some(s) = text_from.take()
207                && s != i
208            {
209                out.push(Atom {
210                    kind: AtomKind::Text,
211                    text: &src[s..i],
212                    start: s,
213                });
214            }
215            let start = i;
216            i += 3;
217            let mut escaped = false;
218            while i < bytes.len() {
219                if escaped {
220                    escaped = false;
221                    i += 1;
222                } else if bytes[i] == b'\\' {
223                    escaped = true;
224                    i += 1;
225                } else if bytes[i] == b'"'
226                    && bytes.get(i + 1) == Some(&b'"')
227                    && bytes.get(i + 2) == Some(&b'"')
228                {
229                    i += 3;
230                    break;
231                } else {
232                    i += 1;
233                }
234            }
235            out.push(Atom {
236                kind: AtomKind::Text,
237                text: &src[start..i],
238                start,
239            });
240            continue;
241        }
242        // A single-quote opener consumes through its unescaped closer.
243        if b == b'"' || b == b'\'' {
244            if let Some(s) = text_from.take()
245                && s != i
246            {
247                out.push(Atom {
248                    kind: AtomKind::Text,
249                    text: &src[s..i],
250                    start: s,
251                });
252            }
253            let q = b;
254            let start = i;
255            i += 1;
256            let mut escaped = false;
257            while i < bytes.len() {
258                if escaped {
259                    escaped = false;
260                } else if bytes[i] == b'\\' {
261                    escaped = true;
262                } else if bytes[i] == q {
263                    i += 1;
264                    break;
265                }
266                i += 1;
267            }
268            out.push(Atom {
269                kind: AtomKind::Text,
270                text: &src[start..i],
271                start,
272            });
273            continue;
274        }
275        let kind = match b {
276            b'(' | b'[' | b'{' => Some(AtomKind::Open),
277            b')' | b']' | b'}' => Some(AtomKind::Close),
278            b',' | b':' => Some(AtomKind::Sep(b as char)),
279            _ => None,
280        };
281        if let Some(kind) = kind {
282            if let Some(s) = text_from.take()
283                && s != i
284            {
285                out.push(Atom {
286                    kind: AtomKind::Text,
287                    text: &src[s..i],
288                    start: s,
289                });
290            }
291            out.push(Atom {
292                kind,
293                text: &src[i..i + 1],
294                start: i,
295            });
296            i += 1;
297        } else {
298            if text_from.is_none() {
299                text_from = Some(i);
300            }
301            i += 1;
302        }
303    }
304    if let Some(s) = text_from.take()
305        && s < bytes.len()
306    {
307        out.push(Atom {
308            kind: AtomKind::Text,
309            text: &src[s..],
310            start: s,
311        });
312    }
313    out
314}
315
316/// Split on a top-level separator, keeping quoted strings, `"""`
317/// blocks, and bracket groups intact. Shared by comma arg lists and
318/// map-entry `key: value` pairs; only the separator differs.
319fn split_on(src: &str, sep: char) -> Vec<String> {
320    let mut out = Vec::new();
321    let mut current = String::new();
322    let mut depth: usize = 0;
323    for atom in scan_atoms(src) {
324        match atom.kind {
325            AtomKind::Open => {
326                depth += 1;
327                current.push_str(atom.text);
328            }
329            AtomKind::Close => {
330                depth = depth.saturating_sub(1);
331                current.push_str(atom.text);
332            }
333            AtomKind::Sep(c) if c == sep && depth == 0 => {
334                out.push(current.trim().to_string());
335                current.clear();
336            }
337            _ => current.push_str(atom.text),
338        }
339    }
340    let last = current.trim();
341    if !(out.is_empty() && last.is_empty()) {
342        out.push(last.to_string());
343    }
344    out
345}
346
347/// Split call args on top-level commas, keeping quoted strings,
348/// `"""` blocks, and bracket groups intact.
349pub fn split_placeholder_args(src: &str) -> Vec<String> {
350    split_on(src, ',')
351}
352
353/// Split on a top-level separator character. Only `,` and `:` are
354/// tokenized by [`scan_atoms`]; anything else is a programming error
355/// and fails fast. (A plain assert: the workspace bans `cfg`-based
356/// macros outside the `sys` crates, so no `debug_assert!` here.)
357pub fn split_top_level(src: &str, sep: char) -> Vec<String> {
358    assert!(
359        matches!(sep, ',' | ':'),
360        "scan_atoms only tokenizes ',' and ':' separators"
361    );
362    split_on(src, sep)
363}
364
365/// Parse one string literal in any spelling: `"""` blocks lower
366/// through the shared block lowering, `"..."` and `'...'` unescape
367/// through the shared unescaper. Returns `None` when `src` is not a
368/// single string literal. Single owner for placeholder string syntax:
369/// value and key paths both route here, so a new spelling lands once.
370///
371/// Closer validation rides [`scan_atoms`]: the input must scan as one
372/// quoted text atom spanning all of `src`, and the closer is matched
373/// from the opener with escapes honored. Adjacent literals (`"a" "b"`),
374/// infix expressions (`"a" + "b"`), and trailing-escape inputs (`"foo\"`)
375/// fail closed instead of merging or truncating.
376pub fn parse_string_literal(src: &str) -> Option<anyhow::Result<String>> {
377    let atoms = scan_atoms(src);
378    let [atom] = atoms.as_slice() else {
379        return None;
380    };
381    if atom.kind != AtomKind::Text || atom.start != 0 || atom.text != src {
382        return None;
383    }
384    if src.starts_with("\"\"\"") {
385        return Some(parse_block_literal(src));
386    }
387    for quote in ['"', '\''] {
388        if src.starts_with(quote) {
389            return Some(parse_quoted_literal(src, quote));
390        }
391    }
392    None
393}
394
395/// Match one `"..."` or `'...'` literal from its opener to its first
396/// unescaped closer, which must end the input. `\\` skips the next
397/// byte unconditionally, so a trailing escape fails unterminated.
398fn parse_quoted_literal(src: &str, quote: char) -> anyhow::Result<String> {
399    let bytes = src.as_bytes();
400    let mut i = 1;
401    while i < bytes.len() {
402        if bytes[i] == b'\\' {
403            i += 2;
404            continue;
405        }
406        if bytes[i] == quote as u8 {
407            if i + 1 != src.len() {
408                anyhow::bail!("unexpected text after string literal: {src:?}");
409            }
410            return unescape_literal(&src[1..i], quote);
411        }
412        i += 1;
413    }
414    anyhow::bail!("unterminated string literal: {src:?}")
415}
416
417/// Match one `"""..."""` block from its opener to its first unescaped
418/// closer triple, which must end the input. Lowers through the shared
419/// block lowering, so placeholder blocks read exactly like statement
420/// block strings.
421fn parse_block_literal(src: &str) -> anyhow::Result<String> {
422    let bytes = src.as_bytes();
423    let mut i = 3;
424    while i < bytes.len() {
425        if bytes[i] == b'\\' {
426            i += 2;
427            continue;
428        }
429        if bytes[i] == b'"' && bytes.get(i + 1) == Some(&b'"') && bytes.get(i + 2) == Some(&b'"') {
430            if i + 3 != src.len() {
431                anyhow::bail!("unexpected text after block string literal: {src:?}");
432            }
433            return Ok(crate::command::lower_block_string(src));
434        }
435        i += 1;
436    }
437    anyhow::bail!("unterminated block string literal: {src:?}")
438}
439
440/// Unescape a quoted literal: `\\` and the enclosing quote only.
441/// Anything else keeps its backslash so template text stays predictable.
442fn unescape_literal(src: &str, quote: char) -> anyhow::Result<String> {
443    let mut out = String::with_capacity(src.len());
444    let mut chars = src.chars();
445    while let Some(c) = chars.next() {
446        if c != '\\' {
447            out.push(c);
448            continue;
449        }
450        match chars.next() {
451            Some('\\') => out.push('\\'),
452            Some(q) if q == quote => out.push(quote),
453            Some(other) => {
454                out.push('\\');
455                out.push(other);
456            }
457            None => anyhow::bail!("unterminated escape in placeholder string literal"),
458        }
459    }
460    Ok(out)
461}
462
463/// Strip one wrapping delimiter pair, built on [`scan_atoms`] instead
464/// of a local quote loop: the opener at 0 must match the closer at the
465/// end with no earlier top-level closer. `"""` blocks scan as single
466/// text atoms, so brackets inside them never disturb the depth.
467pub fn strip_wrapped_delimiters(src: &str, open: char, close: char) -> Option<&str> {
468    let atoms = scan_atoms(src);
469    let first = atoms.first()?;
470    if first.kind != AtomKind::Open || first.start != 0 || first.text.chars().count() != 1 {
471        return None;
472    }
473    if !first.text.starts_with(open) {
474        return None;
475    }
476    let mut depth = 0usize;
477    for atom in &atoms {
478        match atom.kind {
479            AtomKind::Open => depth += 1,
480            AtomKind::Close => {
481                depth = depth.saturating_sub(1);
482                if depth == 0 {
483                    if atom.start + atom.text.len() != src.len() {
484                        return None;
485                    }
486                    if !atom.text.starts_with(close) {
487                        return None;
488                    }
489                    return Some(&src[open.len_utf8()..src.len() - close.len_utf8()]);
490                }
491            }
492            AtomKind::Text | AtomKind::Sep(_) => {}
493        }
494    }
495    None
496}
497/// One variable read inside a `{{ ... }}` key: a `$a.b` path as its
498/// dotted parts, or a bare `key` as one literal lookup. Call args
499/// contribute their nested `$` refs; env keys contribute nothing.
500#[derive(Debug, Clone, PartialEq, Eq)]
501pub enum TemplateVar {
502    Path(Vec<String>),
503    Bare(String),
504}
505
506/// One `{{ ... }}` key, classified. The single grammar behind every
507/// expansion and check phase: parse-time qualification, the static
508/// gate, script-engine expansion, and override-map expansion all route
509/// through this, so the phases can never disagree on what shape a key
510/// is. Payloads stay raw (untrimmed, unsplit): trimming, splitting,
511/// lookup sources, and errors belong to the caller, whose contracts
512/// differ. Input must arrive trimmed: every producer trims at its
513/// boundary (`TemplateSegments` yields trimmed keys; the streaming
514/// expander trims on extract).
515#[derive(Debug, Clone, PartialEq, Eq)]
516pub enum PlaceholderKey<'a> {
517    /// Empty key: every phase rejects it.
518    Empty,
519    /// `$` plus the raw rest: split through [`split_var_path`].
520    Dollar(&'a str),
521    /// `env:` plus the raw name.
522    Env(&'a str),
523    /// `script_env:` plus the raw name.
524    ScriptEnv(&'a str),
525    /// One `[MODULE::]FUNC(args)` body, through the shared
526    /// [`parse_placeholder_call`] grammar.
527    Call(PlaceholderCall<'a>),
528    /// Anything else, verbatim: script-var lookup, step-override
529    /// lookup, or a hard error, per the caller's contract.
530    Bare(&'a str),
531}
532
533/// Classify one trimmed placeholder key. Shape only, no resolution:
534/// runtimes keep their own check order (e.g. overrides-first) and
535/// their own trimming, sources, and errors.
536pub fn classify_placeholder_key(key: &str) -> PlaceholderKey<'_> {
537    if key.is_empty() {
538        return PlaceholderKey::Empty;
539    }
540    if let Some(rest) = key.strip_prefix('$') {
541        return PlaceholderKey::Dollar(rest);
542    }
543    if let Some(rest) = key.strip_prefix("env:") {
544        return PlaceholderKey::Env(rest);
545    }
546    if let Some(rest) = key.strip_prefix("script_env:") {
547        return PlaceholderKey::ScriptEnv(rest);
548    }
549    if let Some(call) = parse_placeholder_call(key) {
550        return PlaceholderKey::Call(call);
551    }
552    PlaceholderKey::Bare(key)
553}
554
555/// One `$a.b` path split: on `.` with each part trimmed, exactly like
556/// runtime expansion. No validity judgment: callers decide what empty
557/// parts mean under their own contract.
558pub fn split_var_path(rest: &str) -> Vec<String> {
559    rest.split('.')
560        .map(|part| part.trim().to_string())
561        .collect()
562}
563
564/// Variable reads inside one placeholder key, routed through the
565/// single [`classify_placeholder_key`] owner: `$` paths parse through
566/// the single path parser below, env keys contribute nothing, call
567/// shapes contribute their nested arg refs, and bare keys stay
568/// literal.
569/// Call args recurse through the shared literal owners
570/// (`parse_string_literal`, `strip_wrapped_delimiters`,
571/// `split_top_level`), so new arg spellings land once, here.
572pub fn placeholder_vars(key: &str) -> Vec<TemplateVar> {
573    match classify_placeholder_key(key.trim()) {
574        PlaceholderKey::Empty => Vec::new(),
575        PlaceholderKey::Dollar(rest) => parse_dollar_path(rest).into_iter().collect(),
576        PlaceholderKey::Env(_) | PlaceholderKey::ScriptEnv(_) => Vec::new(),
577        PlaceholderKey::Call(call) => {
578            let mut out = Vec::new();
579            for arg in split_placeholder_args(call.args_raw) {
580                collect_call_arg_vars(&arg, &mut out);
581            }
582            out
583        }
584        PlaceholderKey::Bare(key) => vec![TemplateVar::Bare(key.to_string())],
585    }
586}
587
588/// One `$a.b` path from its post-`$` rest. `None` means malformed:
589/// the caller owns that error. Single owner for `$` path syntax.
590pub fn parse_var_path(rest: &str) -> Option<Vec<String>> {
591    let parts = split_var_path(rest);
592    if parts.iter().any(|part| part.is_empty()) {
593        return None;
594    }
595    Some(parts)
596}
597
598/// Maximum nesting for map and list literals in placeholder call
599/// args. Single depth budget shared by static inference and runtime
600/// resolution.
601pub const MAX_TEMPLATE_ARG_DEPTH: usize = 16;
602
603/// One placeholder call argument's shape. Single owner for the
604/// argument grammar: every path classifies here, then acts on the
605/// result with its own types and errors.
606pub enum TemplateArg<'a> {
607    /// `$` variable path: raw rest after `$` (validate with
608    /// [`parse_var_path`]).
609    Dollar(&'a str),
610    /// String literal source in any spelling (parse with
611    /// [`parse_string_literal`]).
612    Str(&'a str),
613    /// `{...}` map inner source.
614    Map(&'a str),
615    /// `[...]` list inner source.
616    List(&'a str),
617    /// Bare scalar source (`true`, `false`, numbers; see
618    /// [`parse_scalar_literal`]).
619    Scalar(&'a str),
620    /// Anything else: the caller owns the invalid-syntax error.
621    Invalid(&'a str),
622}
623
624/// Classify one call argument by shape. Inputs arrive trimmed from
625/// [`split_placeholder_args`].
626pub fn classify_template_arg(src: &str) -> TemplateArg<'_> {
627    let src = src.trim();
628    if let Some(rest) = src.strip_prefix('$') {
629        return TemplateArg::Dollar(rest);
630    }
631    if parse_string_literal(src).is_some() {
632        return TemplateArg::Str(src);
633    }
634    if let Some(inner) = strip_wrapped_delimiters(src, '{', '}') {
635        return TemplateArg::Map(inner);
636    }
637    if let Some(inner) = strip_wrapped_delimiters(src, '[', ']') {
638        return TemplateArg::List(inner);
639    }
640    if parse_scalar_literal(src).is_some() {
641        return TemplateArg::Scalar(src);
642    }
643    TemplateArg::Invalid(src)
644}
645
646/// One bare scalar literal's value shape. Shared by static inference
647/// (tags) and runtime resolution (values), which map the same shapes
648/// instead of restating the cascade.
649pub enum ScalarLit {
650    Bool(bool),
651    Int(i64),
652    Float(f64),
653}
654
655/// Parse one bare scalar literal: `true`/`false`, then int, then
656/// float. `None` means not scalar-shaped at all.
657pub fn parse_scalar_literal(src: &str) -> Option<ScalarLit> {
658    match src {
659        "true" => Some(ScalarLit::Bool(true)),
660        "false" => Some(ScalarLit::Bool(false)),
661        _ => src
662            .parse::<i64>()
663            .map(ScalarLit::Int)
664            .ok()
665            .or_else(|| src.parse::<f64>().map(ScalarLit::Float).ok()),
666    }
667}
668
669/// One `{key: value}` entry's key and value sources, split once on a
670/// top-level `:`. `None` when the entry is not exactly one pair.
671pub fn split_map_entry(entry: &str) -> Option<(String, String)> {
672    let mut parts = split_top_level(entry, ':');
673    if parts.len() != 2 {
674        return None;
675    }
676    let value = parts.pop().expect("split_map_entry checked len");
677    let key = parts.pop().expect("split_map_entry checked len");
678    Some((key, value))
679}
680
681/// One map literal key: a string literal in any spelling or a bare
682/// ASCII identifier. Shared by static inference and runtime
683/// resolution, which report identical diagnostics.
684pub fn parse_map_key(src: &str) -> anyhow::Result<String> {
685    if let Some(literal) = parse_string_literal(src) {
686        return literal.map_err(|err| anyhow::anyhow!("{err:#}"));
687    }
688    if !src.is_empty() && src.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
689        return Ok(src.to_string());
690    }
691    anyhow::bail!("invalid map literal key '{src}': use a bare name or any string spelling")
692}
693
694fn parse_dollar_path(rest: &str) -> Option<TemplateVar> {
695    parse_var_path(rest).map(TemplateVar::Path)
696}
697
698/// Nested `$` refs inside one call arg, through the shared argument
699/// classifier: strings, scalars, and invalid shapes hold none; maps
700/// and lists recurse into their entries; malformed entries are
701/// runtime-owned invalid syntax and contribute nothing here.
702fn collect_call_arg_vars(src: &str, out: &mut Vec<TemplateVar>) {
703    match classify_template_arg(src) {
704        TemplateArg::Dollar(rest) => {
705            out.extend(parse_dollar_path(rest));
706        }
707        TemplateArg::Map(inner) => {
708            if inner.trim().is_empty() {
709                return;
710            }
711            for entry in split_top_level(inner, ',') {
712                if let Some((_, value)) = split_map_entry(&entry) {
713                    collect_call_arg_vars(&value, out);
714                }
715            }
716        }
717        TemplateArg::List(inner) => {
718            if inner.trim().is_empty() {
719                return;
720            }
721            for item in split_top_level(inner, ',') {
722                collect_call_arg_vars(&item, out);
723            }
724        }
725        TemplateArg::Str(_) | TemplateArg::Scalar(_) | TemplateArg::Invalid(_) => {}
726    }
727}
728/// Allocation-free segment iterator over template text. See the module
729/// docs for the exact rules; the unit tests below pin every escape
730/// and boundary shape.
731#[derive(Debug, Clone)]
732pub struct TemplateSegments<'a> {
733    text: &'a str,
734    pos: usize,
735    pending: Option<(usize, &'a str, &'a str)>,
736}
737
738impl<'a> TemplateSegments<'a> {
739    /// Scan `text` front to back.
740    pub fn new(text: &'a str) -> Self {
741        Self {
742            text,
743            pos: 0,
744            pending: None,
745        }
746    }
747}
748
749impl<'a> Iterator for TemplateSegments<'a> {
750    type Item = TemplateSegment<'a>;
751
752    fn next(&mut self) -> Option<Self::Item> {
753        if let Some((end, key, raw)) = self.pending.take() {
754            self.pos = end;
755            return Some(TemplateSegment::Placeholder { key, raw });
756        }
757        // Copy out: every slice below then ties to `'a`, never to the
758        // `&mut self` borrow, so staging `pending` never conflicts.
759        let text: &'a str = self.text;
760        let bytes = text.as_bytes();
761        let len = bytes.len();
762        if self.pos >= len {
763            return None;
764        }
765        let start = self.pos;
766        let mut i = start;
767        while i < len {
768            if bytes[i] == b'\\' {
769                // `\\` consumes both (the opener after it stays live);
770                // `\{{` consumes all three as literal text; anything
771                // else consumes only the backslash and reprocesses.
772                if i + 2 < len && bytes[i + 1] == b'{' && bytes[i + 2] == b'{' {
773                    i += 3;
774                } else if i + 1 < len && bytes[i + 1] == b'\\' {
775                    i += 2;
776                } else {
777                    i += 1;
778                }
779                continue;
780            }
781            if bytes[i] == b'{' && i + 1 < len && bytes[i + 1] == b'{' {
782                let mut j = i + 2;
783                while j + 1 < len && !(bytes[j] == b'}' && bytes[j + 1] == b'}') {
784                    j += 1;
785                }
786                if j + 1 >= len {
787                    break;
788                }
789                let key = text[i + 2..j].trim();
790                let raw = &text[i..j + 2];
791                if i > start {
792                    self.pending = Some((j + 2, key, raw));
793                    return Some(TemplateSegment::Text(&text[start..i]));
794                }
795                self.pos = j + 2;
796                return Some(TemplateSegment::Placeholder { key, raw });
797            }
798            i += 1;
799        }
800        self.pos = len;
801        Some(TemplateSegment::Text(&text[start..]))
802    }
803}
804
805#[cfg(test)]
806mod tests {
807    use super::{TemplateSegment, TemplateSegments};
808
809    fn segments(text: &str) -> Vec<TemplateSegment<'_>> {
810        TemplateSegments::new(text).collect()
811    }
812
813    #[test]
814    fn plain_text_is_one_segment() {
815        assert_eq!(segments("hello"), vec![TemplateSegment::Text("hello")],);
816    }
817
818    #[test]
819    fn placeholder_splits_around_text() {
820        assert_eq!(
821            segments("a{{ $x }}b"),
822            vec![
823                TemplateSegment::Text("a"),
824                TemplateSegment::Placeholder {
825                    key: "$x",
826                    raw: "{{ $x }}"
827                },
828                TemplateSegment::Text("b"),
829            ],
830        );
831    }
832
833    #[test]
834    fn keys_trim() {
835        assert_eq!(
836            segments("{{  env:A  }}"),
837            vec![TemplateSegment::Placeholder {
838                key: "env:A",
839                raw: "{{  env:A  }}"
840            }],
841        );
842    }
843
844    #[test]
845    fn escaped_opener_stays_text() {
846        assert_eq!(
847            segments("\\{{ env:A }}"),
848            vec![TemplateSegment::Text("\\{{ env:A }}")],
849        );
850    }
851
852    #[test]
853    fn escaped_backslash_keeps_opener_live() {
854        assert_eq!(
855            segments("\\\\{{ env:A }}"),
856            vec![
857                TemplateSegment::Text("\\\\"),
858                TemplateSegment::Placeholder {
859                    key: "env:A",
860                    raw: "{{ env:A }}"
861                },
862            ],
863        );
864    }
865
866    #[test]
867    fn escaped_opener_before_braces_stays_text() {
868        // `\{{{x}}`: the `\{{` consumes as literal, exactly like the
869        // historical expansion loop; no placeholder opens inside it.
870        assert_eq!(
871            segments("\\{{{x}}"),
872            vec![TemplateSegment::Text("\\{{{x}}")],
873        );
874    }
875
876    #[test]
877    fn unclosed_opener_stays_text() {
878        assert_eq!(
879            segments("hi {{ unclosed"),
880            vec![TemplateSegment::Text("hi {{ unclosed")],
881        );
882    }
883
884    #[test]
885    fn empty_and_blank_keys_are_placeholders() {
886        assert_eq!(
887            segments("{{}}"),
888            vec![TemplateSegment::Placeholder {
889                key: "",
890                raw: "{{}}"
891            }],
892        );
893        assert_eq!(
894            segments("{{ }}"),
895            vec![TemplateSegment::Placeholder {
896                key: "",
897                raw: "{{ }}"
898            }],
899        );
900    }
901
902    #[test]
903    fn adjacent_placeholders_emit_no_empty_text() {
904        assert_eq!(
905            segments("{{a}}{{b}}"),
906            vec![
907                TemplateSegment::Placeholder {
908                    key: "a",
909                    raw: "{{a}}"
910                },
911                TemplateSegment::Placeholder {
912                    key: "b",
913                    raw: "{{b}}"
914                },
915            ],
916        );
917    }
918
919    #[test]
920    fn call_shapes_parse_once() {
921        use super::{parse_placeholder_call, split_placeholder_args};
922        // Bare head: module-less, name span covers the head.
923        let call = parse_placeholder_call("LEN($x)").expect("bare parses");
924        assert_eq!(call.module, None);
925        assert_eq!(call.name, "LEN");
926        assert_eq!(&"LEN($x)"[call.name_span.clone()], "LEN");
927        assert_eq!(call.args_raw, "$x");
928        // Qualified head with gap before parens.
929        let call = parse_placeholder_call("STD::LEN ($x)").expect("qualified parses");
930        assert_eq!(call.module, Some("STD"));
931        assert_eq!(call.name, "LEN");
932        assert_eq!(call.args_raw, "$x");
933        // Quoted parens never affect depth, both styles.
934        assert!(parse_placeholder_call("LEN(\"a(b\")").is_some());
935        assert!(parse_placeholder_call("LEN('a(b')").is_some());
936        assert!(parse_placeholder_call("STD::LEN('a(b')").is_some());
937        // Compounds and trailing garbage are not single calls.
938        assert!(parse_placeholder_call("LEN($a) + LEN($b)").is_none());
939        assert!(parse_placeholder_call("LEN($x))").is_none());
940        // Lowercase bare heads keep non-call handling.
941        assert!(parse_placeholder_call("foo($x)").is_none());
942        // Empty and missing parens miss.
943        assert!(parse_placeholder_call("$x").is_none());
944        assert!(parse_placeholder_call("").is_none());
945        // Args split shields commas in both quote styles.
946        assert_eq!(
947            split_placeholder_args("$a, \"b,c\", 'd,e'"),
948            vec!["$a".to_string(), "\"b,c\"".to_string(), "'d,e'".to_string()],
949        );
950    }
951
952    #[test]
953    fn placeholder_vars_cover_keys_calls_and_bad_paths() {
954        use super::{TemplateVar, placeholder_vars};
955        assert_eq!(
956            placeholder_vars("$x"),
957            vec![TemplateVar::Path(vec!["x".to_string()])],
958        );
959        assert_eq!(
960            placeholder_vars(" $a.b.c "),
961            vec![TemplateVar::Path(vec![
962                "a".to_string(),
963                "b".to_string(),
964                "c".to_string(),
965            ])],
966        );
967        assert_eq!(
968            placeholder_vars("key"),
969            vec![TemplateVar::Bare("key".to_string())],
970        );
971        assert!(placeholder_vars("env:FOO").is_empty());
972        assert!(placeholder_vars("script_env:BAR").is_empty());
973        assert!(placeholder_vars("").is_empty());
974        assert_eq!(
975            placeholder_vars("M::F($a, {k: [$b, \"ignored\"]}, 'ignored', \"\"\"ignored\"\"\")"),
976            vec![
977                TemplateVar::Path(vec!["a".to_string()]),
978                TemplateVar::Path(vec!["b".to_string()]),
979            ],
980        );
981        assert!(placeholder_vars("$").is_empty());
982        assert!(placeholder_vars("$a.").is_empty());
983        assert!(placeholder_vars("$.a").is_empty());
984    }
985
986    #[test]
987    fn triple_quoted_blocks_split_and_parse_whole() {
988        use super::{parse_placeholder_call, split_placeholder_args};
989        // Commas, parens, and brackets inside `"""` never split depth.
990        assert_eq!(
991            split_placeholder_args("\"\"\"a, b (c) [d]\"\"\", $x"),
992            vec!["\"\"\"a, b (c) [d]\"\"\"".to_string(), "$x".to_string()],
993        );
994        // A block arg spanning lines survives as one arg.
995        assert_eq!(
996            split_placeholder_args("\"\"\"line one\nline two\"\"\""),
997            vec!["\"\"\"line one\nline two\"\"\"".to_string()],
998        );
999        // Parens inside blocks never affect the call paren match.
1000        let call = parse_placeholder_call("M::F(\"\"\"a(b\"\"\", $x)").expect("block parens parse");
1001        assert_eq!(call.name, "F");
1002        assert_eq!(call.args_raw, "\"\"\"a(b\"\"\", $x");
1003    }
1004
1005    #[test]
1006    fn string_literal_spellings_agree() {
1007        use super::parse_string_literal;
1008        let plain = parse_string_literal("\"Release installs\"")
1009            .expect("quoted")
1010            .expect("ok");
1011        let single = parse_string_literal("'Release installs'")
1012            .expect("single")
1013            .expect("ok");
1014        let block = parse_string_literal("\"\"\"Release installs\"\"\"")
1015            .expect("block")
1016            .expect("ok");
1017        assert_eq!(plain, "Release installs");
1018        assert_eq!(single, plain);
1019        assert_eq!(block, plain);
1020    }
1021
1022    #[test]
1023    fn string_literal_rejects_merged_and_unterminated() {
1024        use super::parse_string_literal;
1025        // Adjacent literals and infix expressions scan as several atoms:
1026        // not one literal, so the caller rejects them.
1027        assert!(parse_string_literal("\"a\" \"b\"").is_none());
1028        assert!(parse_string_literal("\"a\" + \"b\"").is_none());
1029        assert!(parse_string_literal("\"\"\"a\"\"\" \"\"\"b\"\"\"").is_none());
1030        // Trailing escapes and missing closers fail closed.
1031        assert!(parse_string_literal("\"foo\\\"").expect("quoted").is_err());
1032        assert!(parse_string_literal("'foo\\'").expect("single").is_err());
1033        assert!(
1034            parse_string_literal("\"\"\"foo\\")
1035                .expect("block escape")
1036                .is_err()
1037        );
1038        assert!(
1039            parse_string_literal("\"\"\"foo\"\"")
1040                .expect("block short")
1041                .is_err()
1042        );
1043        assert!(parse_string_literal("\"foo").expect("open").is_err());
1044        assert!(
1045            parse_string_literal("\"\"\"foo")
1046                .expect("open block")
1047                .is_err()
1048        );
1049    }
1050
1051    #[test]
1052    fn wrapped_delimiters_see_through_block_strings() {
1053        use super::strip_wrapped_delimiters;
1054        assert_eq!(
1055            strip_wrapped_delimiters("[\"\"\"a]b\"\"\"]", '[', ']'),
1056            Some("\"\"\"a]b\"\"\"")
1057        );
1058        assert_eq!(
1059            strip_wrapped_delimiters("{k: \"\"\"a}b\"\"\"}", '{', '}'),
1060            Some("k: \"\"\"a}b\"\"\"")
1061        );
1062        assert_eq!(strip_wrapped_delimiters("[a, b]", '[', ']'), Some("a, b"));
1063        assert!(strip_wrapped_delimiters("[a], [b]", '[', ']').is_none());
1064        assert!(strip_wrapped_delimiters("[a", '[', ']').is_none());
1065    }
1066}