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 =
92        if let Some((left, right)) = head.split_once(crate::constants::MODULE_SEPARATOR) {
93            if left.is_empty() || !left.chars().all(is_module_char) {
94                return None;
95            }
96            let name = right.trim();
97            if name.is_empty() || !name.chars().all(is_module_char) {
98                return None;
99            }
100            // Qualified heads stay permissive here (runtime spellings
101            // allow `alnum _ -`); resolution validates case later, so an
102            // unknown-case head still fails naming the culprit.
103            // `head` opens `trimmed`, so the name offset inside `head`
104            // is its offset inside `trimmed` too.
105            let colon = head
106                .find(crate::constants::MODULE_SEPARATOR)
107                .expect("split found ::");
108            let leading = head[colon + 2..].len() - head[colon + 2..].trim_start().len();
109            Head::Qualified {
110                name,
111                start: colon + 2 + leading,
112            }
113        } else {
114            if !is_bare_head(head) {
115                return None;
116            }
117            Head::Bare(head)
118        };
119    // The shared atom scan drives depth: quoted runs (including
120    // `"""` blocks) arrive whole as Text, so parens inside strings
121    // never count. Only structural opens and closes move depth.
122    let mut depth: usize = 0;
123    let mut close_at: Option<usize> = None;
124    for atom in scan_atoms(rest) {
125        match atom.kind {
126            // Only parens move depth here, exactly as before: quoted
127            // runs arrive whole as Text, and other brackets never
128            // counted. Unbalanced cross-kind input fails closed below.
129            AtomKind::Open if atom.text == "(" => depth += 1,
130            AtomKind::Close if atom.text == ")" => {
131                if depth == 0 {
132                    return None;
133                }
134                depth -= 1;
135                if depth == 0 {
136                    close_at = Some(atom.start);
137                    break;
138                }
139            }
140            _ => {}
141        }
142    }
143    let close_at = close_at?;
144    if !rest[close_at + 1..].trim().is_empty() {
145        return None;
146    }
147    let args_raw = &rest[1..close_at];
148    match head_parsed {
149        Head::Bare(name) => {
150            let start = base + trimmed.find(name).unwrap_or(0);
151            Some(PlaceholderCall {
152                module: None,
153                name,
154                name_span: start..start + name.len(),
155                args_raw,
156            })
157        }
158        Head::Qualified { name, start } => {
159            let abs = base + start;
160            Some(PlaceholderCall {
161                module: Some(
162                    &head[..head
163                        .find(crate::constants::MODULE_SEPARATOR)
164                        .expect("split found ::")],
165                ),
166                name,
167                name_span: abs..abs + name.len(),
168                args_raw,
169            })
170        }
171    }
172}
173
174/// One lexical atom of placeholder arg text. Bracket depth tracking
175/// and top-level splitting share this single scan, so quote rules —
176/// including `"""` blocks — can never disagree between the splitter
177/// and the paren matcher.
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub enum AtomKind {
180    /// One of `([{`.
181    Open,
182    /// One of `)]}`.
183    Close,
184    /// A separator candidate (`,` or `:`); consumers decide which splits.
185    Sep(char),
186    /// Anything else: a maximal run that is either one quoted string
187    /// (`".."`, `'..'`, or a whole `""".."""` block with backslash
188    /// escapes honored) or unquoted text up to the next structural
189    /// character. Commas and brackets inside a quoted run never surface.
190    Text,
191}
192
193/// A scanned atom with its byte offset in the scanned source.
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub struct Atom<'a> {
196    pub kind: AtomKind,
197    pub text: &'a str,
198    pub start: usize,
199}
200
201/// Scan placeholder arg text into atoms. Unterminated quotes run to
202/// end of input as text; downstream value resolution fails those
203/// closed, exactly as before.
204pub fn scan_atoms(src: &str) -> Vec<Atom<'_>> {
205    let bytes = src.as_bytes();
206    let mut out = Vec::new();
207    let mut i = 0;
208    let mut text_from: Option<usize> = None;
209    while i < bytes.len() {
210        let b = bytes[i];
211        // A `"""` opener consumes through its unescaped closer.
212        if b == b'"' && bytes.get(i + 1) == Some(&b'"') && bytes.get(i + 2) == Some(&b'"') {
213            if let Some(s) = text_from.take()
214                && s != i
215            {
216                out.push(Atom {
217                    kind: AtomKind::Text,
218                    text: &src[s..i],
219                    start: s,
220                });
221            }
222            let start = i;
223            i += 3;
224            let mut escaped = false;
225            while i < bytes.len() {
226                if escaped {
227                    escaped = false;
228                    i += 1;
229                } else if bytes[i] == b'\\' {
230                    escaped = true;
231                    i += 1;
232                } else if bytes[i] == b'"'
233                    && bytes.get(i + 1) == Some(&b'"')
234                    && bytes.get(i + 2) == Some(&b'"')
235                {
236                    i += 3;
237                    break;
238                } else {
239                    i += 1;
240                }
241            }
242            out.push(Atom {
243                kind: AtomKind::Text,
244                text: &src[start..i],
245                start,
246            });
247            continue;
248        }
249        // A single-quote opener consumes through its unescaped closer.
250        if b == b'"' || b == b'\'' {
251            if let Some(s) = text_from.take()
252                && s != i
253            {
254                out.push(Atom {
255                    kind: AtomKind::Text,
256                    text: &src[s..i],
257                    start: s,
258                });
259            }
260            let q = b;
261            let start = i;
262            i += 1;
263            let mut escaped = false;
264            while i < bytes.len() {
265                if escaped {
266                    escaped = false;
267                } else if bytes[i] == b'\\' {
268                    escaped = true;
269                } else if bytes[i] == q {
270                    i += 1;
271                    break;
272                }
273                i += 1;
274            }
275            out.push(Atom {
276                kind: AtomKind::Text,
277                text: &src[start..i],
278                start,
279            });
280            continue;
281        }
282        let kind = match b {
283            b'(' | b'[' | b'{' => Some(AtomKind::Open),
284            b')' | b']' | b'}' => Some(AtomKind::Close),
285            b',' | b':' => Some(AtomKind::Sep(b as char)),
286            _ => None,
287        };
288        if let Some(kind) = kind {
289            if let Some(s) = text_from.take()
290                && s != i
291            {
292                out.push(Atom {
293                    kind: AtomKind::Text,
294                    text: &src[s..i],
295                    start: s,
296                });
297            }
298            out.push(Atom {
299                kind,
300                text: &src[i..i + 1],
301                start: i,
302            });
303            i += 1;
304        } else {
305            if text_from.is_none() {
306                text_from = Some(i);
307            }
308            i += 1;
309        }
310    }
311    if let Some(s) = text_from.take()
312        && s < bytes.len()
313    {
314        out.push(Atom {
315            kind: AtomKind::Text,
316            text: &src[s..],
317            start: s,
318        });
319    }
320    out
321}
322
323/// Split on a top-level separator, keeping quoted strings, `"""`
324/// blocks, and bracket groups intact. Shared by comma arg lists and
325/// map-entry `key: value` pairs; only the separator differs.
326fn split_on(src: &str, sep: char) -> Vec<String> {
327    let mut out = Vec::new();
328    let mut current = String::new();
329    let mut depth: usize = 0;
330    for atom in scan_atoms(src) {
331        match atom.kind {
332            AtomKind::Open => {
333                depth += 1;
334                current.push_str(atom.text);
335            }
336            AtomKind::Close => {
337                depth = depth.saturating_sub(1);
338                current.push_str(atom.text);
339            }
340            AtomKind::Sep(c) if c == sep && depth == 0 => {
341                out.push(current.trim().to_string());
342                current.clear();
343            }
344            _ => current.push_str(atom.text),
345        }
346    }
347    let last = current.trim();
348    if !(out.is_empty() && last.is_empty()) {
349        out.push(last.to_string());
350    }
351    out
352}
353
354/// Split call args on top-level commas, keeping quoted strings,
355/// `"""` blocks, and bracket groups intact.
356pub fn split_placeholder_args(src: &str) -> Vec<String> {
357    split_on(src, ',')
358}
359
360/// Split on a top-level separator character. Only `,` and `:` are
361/// tokenized by [`scan_atoms`]; anything else is a programming error
362/// and fails fast. (A plain assert: the workspace bans `cfg`-based
363/// macros outside the `sys` crates, so no `debug_assert!` here.)
364pub fn split_top_level(src: &str, sep: char) -> Vec<String> {
365    assert!(
366        matches!(sep, ',' | ':'),
367        "scan_atoms only tokenizes ',' and ':' separators"
368    );
369    split_on(src, sep)
370}
371
372/// Parse one string literal in any spelling: `"""` blocks lower
373/// through the shared block lowering, `"..."` and `'...'` unescape
374/// through the shared unescaper. Returns `None` when `src` is not a
375/// single string literal. Single owner for placeholder string syntax:
376/// value and key paths both route here, so a new spelling lands once.
377///
378/// Closer validation rides [`scan_atoms`]: the input must scan as one
379/// quoted text atom spanning all of `src`, and the closer is matched
380/// from the opener with escapes honored. Adjacent literals (`"a" "b"`),
381/// infix expressions (`"a" + "b"`), and trailing-escape inputs (`"foo\"`)
382/// fail closed instead of merging or truncating.
383pub fn parse_string_literal(src: &str) -> Option<anyhow::Result<String>> {
384    let atoms = scan_atoms(src);
385    let [atom] = atoms.as_slice() else {
386        return None;
387    };
388    if atom.kind != AtomKind::Text || atom.start != 0 || atom.text != src {
389        return None;
390    }
391    if src.starts_with("\"\"\"") {
392        return Some(parse_block_literal(src));
393    }
394    for quote in ['"', '\''] {
395        if src.starts_with(quote) {
396            return Some(parse_quoted_literal(src, quote));
397        }
398    }
399    None
400}
401
402/// Match one `"..."` or `'...'` literal from its opener to its first
403/// unescaped closer, which must end the input. `\\` skips the next
404/// byte unconditionally, so a trailing escape fails unterminated.
405fn parse_quoted_literal(src: &str, quote: char) -> anyhow::Result<String> {
406    let bytes = src.as_bytes();
407    let mut i = 1;
408    while i < bytes.len() {
409        if bytes[i] == b'\\' {
410            i += 2;
411            continue;
412        }
413        if bytes[i] == quote as u8 {
414            if i + 1 != src.len() {
415                anyhow::bail!("unexpected text after string literal: {src:?}");
416            }
417            return unescape_literal(&src[1..i], quote);
418        }
419        i += 1;
420    }
421    anyhow::bail!("unterminated string literal: {src:?}")
422}
423
424/// Match one `"""..."""` block from its opener to its first unescaped
425/// closer triple, which must end the input. Lowers through the shared
426/// block lowering, so placeholder blocks read exactly like statement
427/// block strings.
428fn parse_block_literal(src: &str) -> anyhow::Result<String> {
429    let bytes = src.as_bytes();
430    let mut i = 3;
431    while i < bytes.len() {
432        if bytes[i] == b'\\' {
433            i += 2;
434            continue;
435        }
436        if bytes[i] == b'"' && bytes.get(i + 1) == Some(&b'"') && bytes.get(i + 2) == Some(&b'"') {
437            if i + 3 != src.len() {
438                anyhow::bail!("unexpected text after block string literal: {src:?}");
439            }
440            return Ok(crate::command::lower_block_string(src));
441        }
442        i += 1;
443    }
444    anyhow::bail!("unterminated block string literal: {src:?}")
445}
446
447/// Unescape a quoted literal: `\\` and the enclosing quote only.
448/// Anything else keeps its backslash so template text stays predictable.
449fn unescape_literal(src: &str, quote: char) -> anyhow::Result<String> {
450    let mut out = String::with_capacity(src.len());
451    let mut chars = src.chars();
452    while let Some(c) = chars.next() {
453        if c != '\\' {
454            out.push(c);
455            continue;
456        }
457        match chars.next() {
458            Some('\\') => out.push('\\'),
459            Some(q) if q == quote => out.push(quote),
460            Some(other) => {
461                out.push('\\');
462                out.push(other);
463            }
464            None => anyhow::bail!("unterminated escape in placeholder string literal"),
465        }
466    }
467    Ok(out)
468}
469
470/// Strip one wrapping delimiter pair, built on [`scan_atoms`] instead
471/// of a local quote loop: the opener at 0 must match the closer at the
472/// end with no earlier top-level closer. `"""` blocks scan as single
473/// text atoms, so brackets inside them never disturb the depth.
474pub fn strip_wrapped_delimiters(src: &str, open: char, close: char) -> Option<&str> {
475    let atoms = scan_atoms(src);
476    let first = atoms.first()?;
477    if first.kind != AtomKind::Open || first.start != 0 || first.text.chars().count() != 1 {
478        return None;
479    }
480    if !first.text.starts_with(open) {
481        return None;
482    }
483    let mut depth = 0usize;
484    for atom in &atoms {
485        match atom.kind {
486            AtomKind::Open => depth += 1,
487            AtomKind::Close => {
488                depth = depth.saturating_sub(1);
489                if depth == 0 {
490                    if atom.start + atom.text.len() != src.len() {
491                        return None;
492                    }
493                    if !atom.text.starts_with(close) {
494                        return None;
495                    }
496                    return Some(&src[open.len_utf8()..src.len() - close.len_utf8()]);
497                }
498            }
499            AtomKind::Text | AtomKind::Sep(_) => {}
500        }
501    }
502    None
503}
504/// One variable read inside a `{{ ... }}` key: a `$a.b` path as its
505/// dotted parts, or a bare `key` as one literal lookup. Call args
506/// contribute their nested `$` refs; env keys contribute nothing.
507/// Bare `CONST` shapes (`ConstRef`, `KeyPath`, `Var`) still classify
508/// here so phases can name them in the `$`-sigil error; only `$`
509/// paths ever resolve.
510#[derive(Debug, Clone, PartialEq, Eq)]
511pub enum TemplateVar {
512    Path(Vec<String>),
513    Bare(String),
514    ConstRef { alias: String, name: String },
515    KeyPath { base: String, keys: Vec<String> },
516    Var(String),
517}
518
519/// One `{{ ... }}` key, classified. The single grammar behind every
520/// expansion and check phase: parse-time qualification, the static
521/// gate, script-engine expansion, and override-map expansion all route
522/// through this, so the phases can never disagree on what shape a key
523/// is. Payloads stay raw (untrimmed, unsplit): trimming, splitting,
524/// lookup sources, and errors belong to the caller, whose contracts
525/// differ. Input must arrive trimmed: every producer trims at its
526/// boundary (`TemplateSegments` yields trimmed keys; the streaming
527/// expander trims on extract).
528#[derive(Debug, Clone, PartialEq, Eq)]
529pub enum PlaceholderKey<'a> {
530    /// Empty key: every phase rejects it.
531    Empty,
532    /// `$` plus the raw rest: split through [`split_var_path`].
533    /// Never holds `ALIAS::NAME`: those classify as
534    /// [`PlaceholderKey::DollarQualified`].
535    Dollar(&'a str),
536    /// `$ALIAS::NAME` with optional `.key` tail. Single owner for
537    /// the split (see [`parse_dollar_qualified`]), so no call site
538    /// restates [`crate::constants::split_qualified`].
539    /// The empty-tail shape resolves; a `.key` tail fails with
540    /// [`qualified_keypath_error`].
541    DollarQualified {
542        alias: &'a str,
543        name: &'a str,
544        keys: Vec<String>,
545    },
546    /// `env:` plus the raw name.
547    Env(&'a str),
548    /// `script_env:` plus the raw name.
549    ScriptEnv(&'a str),
550    /// One `[MODULE::]FUNC(args)` body, through the shared
551    /// [`parse_placeholder_call`] grammar.
552    Call(PlaceholderCall<'a>),
553    /// Bare `ALIAS::NAME` shape. Never resolves: phases reject it
554    /// with [`bare_sigil_error`] (use `$ALIAS::NAME`).
555    ConstRef { alias: &'a str, name: &'a str },
556    /// Bare `NAME.key...` shape (keys validated non-empty, no
557    /// spaces or commas; base is a bare identifier). Never resolves:
558    /// phases reject it with [`bare_sigil_error`].
559    KeyPath { base: &'a str, keys: Vec<String> },
560    /// Bare identifier shape (`NAME`). Never resolves: phases reject
561    /// it with [`bare_sigil_error`] (use `$NAME`).
562    Var(&'a str),
563    /// Anything else, verbatim: script-var lookup, step-override
564    /// lookup, or a hard error, per the caller's contract.
565    Bare(&'a str),
566}
567
568/// Bare identifier rule shared by every CONST shape: ASCII
569/// alphanumeric plus underscore, non-empty. Dots, commas, spaces,
570/// dashes, and sigils never qualify, so override keys with `-` stay
571/// `Bare` and CONST shapes classify identically everywhere.
572pub fn is_bare_ident(src: &str) -> bool {
573    !src.is_empty() && src.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
574}
575
576/// One `ALIAS::NAME` CONST reference from trimmed source. `None` means
577/// not that shape: the caller keeps its own invalid-syntax error.
578/// Single owner for qualified-CONST syntax; every phase routes here.
579pub fn parse_qualified_const(src: &str) -> Option<(&str, &str)> {
580    let (alias, rest) = crate::constants::split_qualified(src)?;
581    if !is_bare_ident(alias) || !is_bare_ident(rest) {
582        return None;
583    }
584    if rest.contains(['.', ',', ' ', '\t']) {
585        return None;
586    }
587    Some((alias, rest))
588}
589
590/// One `BASE.key...` path from trimmed source. Base and every dot
591/// segment are bare identifiers. `None` means not that shape.
592/// Single owner for key-path syntax; empty segments (`A.`, `A..b`)
593/// and punctuation (`A.foo-bar`, `A.@#$`) never parse here, so
594/// static and runtime agree by construction.
595pub fn parse_bare_key_path(src: &str) -> Option<(&str, Vec<String>)> {
596    let (base, tail) = src.split_once('.')?;
597    if !is_bare_ident(base) {
598        return None;
599    }
600    if tail.is_empty() {
601        return None;
602    }
603    let segs: Vec<String> = tail.split('.').map(|s| s.to_string()).collect();
604    if segs.iter().any(|s| !is_bare_ident(s)) {
605        return None;
606    }
607    Some((base, segs))
608}
609
610/// Error text for a bare word where only `$` reads a binding:
611/// command arguments, `{{ }}` keys, and placeholder call args never
612/// resolve bare words. Single owner for the wording, so the static
613/// gate and runtime expansion agree word for word.
614pub fn bare_sigil_error(src: &str) -> String {
615    format!(
616        "bare `{src}` never reads a binding here; use `{}{src}`",
617        crate::constants::VAR_SIGIL
618    )
619}
620
621/// Error text for a key path on `$ALIAS::NAME`. Qualified reads
622/// never traverse: copy to a local binding first. Single owner for
623/// the wording, so every phase agrees word for word.
624pub fn qualified_keypath_error() -> String {
625    "key paths on $ALIAS::NAME are not supported; copy to a local with LET or CONST first"
626        .to_string()
627}
628
629/// One `$ALIAS::NAME[.key...]` shape from post-`$` rest. Returns the
630/// alias, the name, and the dot tail (possibly empty). `None` means
631/// not that shape. Single owner for the `$`-qualified split (see
632/// [`crate::constants::split_qualified`]), so no call site restates it.
633pub fn parse_dollar_qualified(rest: &str) -> Option<(&str, &str, Vec<String>)> {
634    let (head, tail) = match rest.split_once('.') {
635        Some((h, t)) => (h, Some(t)),
636        None => (rest, None),
637    };
638    let (alias, name) = crate::constants::split_qualified(head)?;
639    if !is_bare_ident(alias) || !is_bare_ident(name) {
640        return None;
641    }
642    let keys = match tail {
643        Some(t) => t.split('.').map(|s| s.to_string()).collect::<Vec<_>>(),
644        None => Vec::new(),
645    };
646    Some((alias, name, keys))
647}
648
649/// Classify one trimmed placeholder key. Shape only, no resolution:
650/// runtimes keep their own check order (e.g. overrides-first) and
651/// their own trimming, sources, and errors.
652pub fn classify_placeholder_key(key: &str) -> PlaceholderKey<'_> {
653    if key.is_empty() {
654        return PlaceholderKey::Empty;
655    }
656    if let Some(rest) = key.strip_prefix('$') {
657        if let Some((alias, name, keys)) = parse_dollar_qualified(rest) {
658            return PlaceholderKey::DollarQualified { alias, name, keys };
659        }
660        return PlaceholderKey::Dollar(rest);
661    }
662    if let Some(rest) = key.strip_prefix("env:") {
663        return PlaceholderKey::Env(rest);
664    }
665    if let Some(rest) = key.strip_prefix("script_env:") {
666        return PlaceholderKey::ScriptEnv(rest);
667    }
668    if let Some(call) = parse_placeholder_call(key) {
669        return PlaceholderKey::Call(call);
670    }
671    if let Some((alias, name)) = parse_qualified_const(key) {
672        return PlaceholderKey::ConstRef { alias, name };
673    }
674    if let Some((base, keys)) = parse_bare_key_path(key) {
675        return PlaceholderKey::KeyPath { base, keys };
676    }
677    if is_bare_ident(key) {
678        return PlaceholderKey::Var(key);
679    }
680    PlaceholderKey::Bare(key)
681}
682
683/// One `$a.b` path split: on `.` with each part trimmed, exactly like
684/// runtime expansion. No validity judgment: callers decide what empty
685/// parts mean under their own contract.
686pub fn split_var_path(rest: &str) -> Vec<String> {
687    rest.split('.')
688        .map(|part| part.trim().to_string())
689        .collect()
690}
691
692/// Variable reads inside one placeholder key, routed through the
693/// single [`classify_placeholder_key`] owner: `$` paths parse through
694/// the single path parser below, env keys contribute nothing, call
695/// shapes contribute their nested arg refs, and bare keys stay
696/// literal.
697/// Call args recurse through the shared literal owners
698/// (`parse_string_literal`, `strip_wrapped_delimiters`,
699/// `split_top_level`), so new arg spellings land once, here.
700pub fn placeholder_vars(key: &str) -> Vec<TemplateVar> {
701    match classify_placeholder_key(key.trim()) {
702        PlaceholderKey::Empty => Vec::new(),
703        PlaceholderKey::Dollar(rest) => parse_dollar_path(rest).into_iter().collect(),
704        PlaceholderKey::DollarQualified { .. } => Vec::new(),
705        PlaceholderKey::Env(_) | PlaceholderKey::ScriptEnv(_) => Vec::new(),
706        PlaceholderKey::Call(call) => {
707            let mut out = Vec::new();
708            for arg in split_placeholder_args(call.args_raw) {
709                collect_call_arg_vars(&arg, &mut out);
710            }
711            out
712        }
713        PlaceholderKey::ConstRef { alias, name } => vec![TemplateVar::ConstRef {
714            alias: alias.to_string(),
715            name: name.to_string(),
716        }],
717        PlaceholderKey::KeyPath { base, keys } => vec![TemplateVar::KeyPath {
718            base: base.to_string(),
719            keys,
720        }],
721        PlaceholderKey::Var(name) => vec![TemplateVar::Var(name.to_string())],
722        PlaceholderKey::Bare(key) => vec![TemplateVar::Bare(key.to_string())],
723    }
724}
725
726/// One `$a.b` path from its post-`$` rest. `None` means malformed:
727/// the caller owns that error. Single owner for `$` path syntax.
728pub fn parse_var_path(rest: &str) -> Option<Vec<String>> {
729    let parts = split_var_path(rest);
730    if parts.iter().any(|part| part.is_empty()) {
731        return None;
732    }
733    Some(parts)
734}
735
736/// Maximum nesting for map and list literals in placeholder call
737/// args. Single depth budget shared by static inference and runtime
738/// resolution.
739pub const MAX_TEMPLATE_ARG_DEPTH: usize = 16;
740
741/// One placeholder call argument's shape. Single owner for the
742/// argument grammar: every path classifies here, then acts on the
743/// result with its own types and errors.
744pub enum TemplateArg<'a> {
745    /// `$` variable path: raw rest after `$` (validate with
746    /// [`parse_var_path`]). Never holds `ALIAS::NAME`: those classify
747    /// as [`TemplateArg::DollarQualified`].
748    Dollar(&'a str),
749    /// `$ALIAS::NAME` with optional `.key` tail: the empty tail
750    /// resolves, a `.key` tail fails with [`qualified_keypath_error`].
751    /// Single owner for the split (see [`parse_dollar_qualified`]),
752    /// so no call site restates [`crate::constants::split_qualified`].
753    DollarQualified {
754        alias: &'a str,
755        name: &'a str,
756        keys: Vec<String>,
757    },
758    /// String literal source in any spelling (parse with
759    /// [`parse_string_literal`]).
760    Str(&'a str),
761    /// `{...}` map inner source.
762    Map(&'a str),
763    /// `[...]` list inner source.
764    List(&'a str),
765    /// Bare scalar source (`true`, `false`, numbers; see
766    /// [`parse_scalar_literal`]).
767    Scalar(&'a str),
768    /// Bare `ALIAS::NAME` shape. Never resolves: phases reject it
769    /// with [`bare_sigil_error`].
770    ConstRef { alias: &'a str, name: &'a str },
771    /// Bare `NAME.key...` path (validated by [`parse_bare_key_path`]).
772    /// Never resolves: phases reject it with [`bare_sigil_error`].
773    KeyPath { base: &'a str, keys: Vec<String> },
774    /// Bare `NAME` identifier. Never resolves: phases reject it with
775    /// [`bare_sigil_error`] (use `$NAME`).
776    Var(&'a str),
777    /// Anything else: the caller owns the invalid-syntax error.
778    Invalid(&'a str),
779}
780
781/// Classify one call argument by shape. Inputs arrive trimmed from
782/// [`split_placeholder_args`].
783pub fn classify_template_arg(src: &str) -> TemplateArg<'_> {
784    let src = src.trim();
785    if let Some(rest) = src.strip_prefix('$') {
786        if let Some((alias, name, keys)) = parse_dollar_qualified(rest) {
787            return TemplateArg::DollarQualified { alias, name, keys };
788        }
789        return TemplateArg::Dollar(rest);
790    }
791    if parse_string_literal(src).is_some() {
792        return TemplateArg::Str(src);
793    }
794    if let Some(inner) = strip_wrapped_delimiters(src, '{', '}') {
795        return TemplateArg::Map(inner);
796    }
797    if let Some(inner) = strip_wrapped_delimiters(src, '[', ']') {
798        return TemplateArg::List(inner);
799    }
800    if parse_scalar_literal(src).is_some() {
801        return TemplateArg::Scalar(src);
802    }
803    if let Some((alias, name)) = parse_qualified_const(src) {
804        return TemplateArg::ConstRef { alias, name };
805    }
806    if let Some((base, keys)) = parse_bare_key_path(src) {
807        return TemplateArg::KeyPath { base, keys };
808    }
809    if is_bare_ident(src) {
810        return TemplateArg::Var(src);
811    }
812    TemplateArg::Invalid(src)
813}
814
815/// One bare scalar literal's value shape. Shared by static inference
816/// (tags) and runtime resolution (values), which map the same shapes
817/// instead of restating the cascade.
818pub enum ScalarLit {
819    Bool(bool),
820    Int(i64),
821    Float(f64),
822}
823
824/// Parse one bare scalar literal: `true`/`false`, then int, then
825/// float. `None` means not scalar-shaped at all.
826pub fn parse_scalar_literal(src: &str) -> Option<ScalarLit> {
827    match src {
828        "true" => Some(ScalarLit::Bool(true)),
829        "false" => Some(ScalarLit::Bool(false)),
830        _ => src
831            .parse::<i64>()
832            .map(ScalarLit::Int)
833            .ok()
834            .or_else(|| src.parse::<f64>().map(ScalarLit::Float).ok()),
835    }
836}
837
838/// One `{key: value}` entry's key and value sources, split once on a
839/// top-level `:`. `None` when the entry is not exactly one pair.
840pub fn split_map_entry(entry: &str) -> Option<(String, String)> {
841    let mut parts = split_top_level(entry, ':');
842    if parts.len() != 2 {
843        return None;
844    }
845    let value = parts.pop().expect("split_map_entry checked len");
846    let key = parts.pop().expect("split_map_entry checked len");
847    Some((key, value))
848}
849
850/// One map literal key: a string literal in any spelling or a bare
851/// ASCII identifier. Shared by static inference and runtime
852/// resolution, which report identical diagnostics.
853pub fn parse_map_key(src: &str) -> anyhow::Result<String> {
854    if let Some(literal) = parse_string_literal(src) {
855        return literal.map_err(|err| anyhow::anyhow!("{err:#}"));
856    }
857    if !src.is_empty() && src.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
858        return Ok(src.to_string());
859    }
860    anyhow::bail!("invalid map literal key '{src}': use a bare name or any string spelling")
861}
862
863fn parse_dollar_path(rest: &str) -> Option<TemplateVar> {
864    parse_var_path(rest).map(TemplateVar::Path)
865}
866
867/// Nested `$` refs inside one call arg, through the shared argument
868/// classifier: strings, scalars, and invalid shapes hold none; maps
869/// and lists recurse into their entries; malformed entries are
870/// runtime-owned invalid syntax and contribute nothing here.
871fn collect_call_arg_vars(src: &str, out: &mut Vec<TemplateVar>) {
872    match classify_template_arg(src) {
873        TemplateArg::Dollar(rest) => {
874            out.extend(parse_dollar_path(rest));
875        }
876        TemplateArg::Map(inner) => {
877            if inner.trim().is_empty() {
878                return;
879            }
880            for entry in split_top_level(inner, ',') {
881                if let Some((_, value)) = split_map_entry(&entry) {
882                    collect_call_arg_vars(&value, out);
883                }
884            }
885        }
886        TemplateArg::List(inner) => {
887            if inner.trim().is_empty() {
888                return;
889            }
890            for item in split_top_level(inner, ',') {
891                collect_call_arg_vars(&item, out);
892            }
893        }
894        TemplateArg::ConstRef { alias, name } => {
895            out.push(TemplateVar::ConstRef {
896                alias: alias.to_string(),
897                name: name.to_string(),
898            });
899        }
900        TemplateArg::KeyPath { base, keys } => {
901            out.push(TemplateVar::KeyPath {
902                base: base.to_string(),
903                keys,
904            });
905        }
906        TemplateArg::Var(name) => {
907            out.push(TemplateVar::Var(name.to_string()));
908        }
909        TemplateArg::DollarQualified { .. } => {}
910        TemplateArg::Str(_) | TemplateArg::Scalar(_) | TemplateArg::Invalid(_) => {}
911    }
912}
913/// Allocation-free segment iterator over template text. See the module
914/// docs for the exact rules; the unit tests below pin every escape
915/// and boundary shape.
916#[derive(Debug, Clone)]
917pub struct TemplateSegments<'a> {
918    text: &'a str,
919    pos: usize,
920    pending: Option<(usize, &'a str, &'a str)>,
921}
922
923impl<'a> TemplateSegments<'a> {
924    /// Scan `text` front to back.
925    pub fn new(text: &'a str) -> Self {
926        Self {
927            text,
928            pos: 0,
929            pending: None,
930        }
931    }
932}
933
934impl<'a> Iterator for TemplateSegments<'a> {
935    type Item = TemplateSegment<'a>;
936
937    fn next(&mut self) -> Option<Self::Item> {
938        if let Some((end, key, raw)) = self.pending.take() {
939            self.pos = end;
940            return Some(TemplateSegment::Placeholder { key, raw });
941        }
942        // Copy out: every slice below then ties to `'a`, never to the
943        // `&mut self` borrow, so staging `pending` never conflicts.
944        let text: &'a str = self.text;
945        let bytes = text.as_bytes();
946        let len = bytes.len();
947        if self.pos >= len {
948            return None;
949        }
950        let start = self.pos;
951        let mut i = start;
952        while i < len {
953            if bytes[i] == b'\\' {
954                // `\\` consumes both (the opener after it stays live);
955                // `\{{` consumes all three as literal text; anything
956                // else consumes only the backslash and reprocesses.
957                if i + 2 < len && bytes[i + 1] == b'{' && bytes[i + 2] == b'{' {
958                    i += 3;
959                } else if i + 1 < len && bytes[i + 1] == b'\\' {
960                    i += 2;
961                } else {
962                    i += 1;
963                }
964                continue;
965            }
966            if bytes[i] == b'{' && i + 1 < len && bytes[i + 1] == b'{' {
967                let mut j = i + 2;
968                while j + 1 < len && !(bytes[j] == b'}' && bytes[j + 1] == b'}') {
969                    j += 1;
970                }
971                if j + 1 >= len {
972                    break;
973                }
974                let key = text[i + 2..j].trim();
975                let raw = &text[i..j + 2];
976                if i > start {
977                    self.pending = Some((j + 2, key, raw));
978                    return Some(TemplateSegment::Text(&text[start..i]));
979                }
980                self.pos = j + 2;
981                return Some(TemplateSegment::Placeholder { key, raw });
982            }
983            i += 1;
984        }
985        self.pos = len;
986        Some(TemplateSegment::Text(&text[start..]))
987    }
988}
989
990#[cfg(test)]
991mod tests {
992    use super::{TemplateSegment, TemplateSegments};
993
994    fn segments(text: &str) -> Vec<TemplateSegment<'_>> {
995        TemplateSegments::new(text).collect()
996    }
997
998    #[test]
999    fn plain_text_is_one_segment() {
1000        assert_eq!(segments("hello"), vec![TemplateSegment::Text("hello")],);
1001    }
1002
1003    #[test]
1004    fn placeholder_splits_around_text() {
1005        assert_eq!(
1006            segments("a{{ $x }}b"),
1007            vec![
1008                TemplateSegment::Text("a"),
1009                TemplateSegment::Placeholder {
1010                    key: "$x",
1011                    raw: "{{ $x }}"
1012                },
1013                TemplateSegment::Text("b"),
1014            ],
1015        );
1016    }
1017
1018    #[test]
1019    fn keys_trim() {
1020        assert_eq!(
1021            segments("{{  env:A  }}"),
1022            vec![TemplateSegment::Placeholder {
1023                key: "env:A",
1024                raw: "{{  env:A  }}"
1025            }],
1026        );
1027    }
1028
1029    #[test]
1030    fn escaped_opener_stays_text() {
1031        assert_eq!(
1032            segments("\\{{ env:A }}"),
1033            vec![TemplateSegment::Text("\\{{ env:A }}")],
1034        );
1035    }
1036
1037    #[test]
1038    fn escaped_backslash_keeps_opener_live() {
1039        assert_eq!(
1040            segments("\\\\{{ env:A }}"),
1041            vec![
1042                TemplateSegment::Text("\\\\"),
1043                TemplateSegment::Placeholder {
1044                    key: "env:A",
1045                    raw: "{{ env:A }}"
1046                },
1047            ],
1048        );
1049    }
1050
1051    #[test]
1052    fn escaped_opener_before_braces_stays_text() {
1053        // `\{{{x}}`: the `\{{` consumes as literal, exactly like the
1054        // historical expansion loop; no placeholder opens inside it.
1055        assert_eq!(
1056            segments("\\{{{x}}"),
1057            vec![TemplateSegment::Text("\\{{{x}}")],
1058        );
1059    }
1060
1061    #[test]
1062    fn unclosed_opener_stays_text() {
1063        assert_eq!(
1064            segments("hi {{ unclosed"),
1065            vec![TemplateSegment::Text("hi {{ unclosed")],
1066        );
1067    }
1068
1069    #[test]
1070    fn empty_and_blank_keys_are_placeholders() {
1071        assert_eq!(
1072            segments("{{}}"),
1073            vec![TemplateSegment::Placeholder {
1074                key: "",
1075                raw: "{{}}"
1076            }],
1077        );
1078        assert_eq!(
1079            segments("{{ }}"),
1080            vec![TemplateSegment::Placeholder {
1081                key: "",
1082                raw: "{{ }}"
1083            }],
1084        );
1085    }
1086
1087    #[test]
1088    fn adjacent_placeholders_emit_no_empty_text() {
1089        assert_eq!(
1090            segments("{{a}}{{b}}"),
1091            vec![
1092                TemplateSegment::Placeholder {
1093                    key: "a",
1094                    raw: "{{a}}"
1095                },
1096                TemplateSegment::Placeholder {
1097                    key: "b",
1098                    raw: "{{b}}"
1099                },
1100            ],
1101        );
1102    }
1103
1104    #[test]
1105    fn call_shapes_parse_once() {
1106        use super::{parse_placeholder_call, split_placeholder_args};
1107        // Bare head: module-less, name span covers the head.
1108        let call = parse_placeholder_call("LEN($x)").expect("bare parses");
1109        assert_eq!(call.module, None);
1110        assert_eq!(call.name, "LEN");
1111        assert_eq!(&"LEN($x)"[call.name_span.clone()], "LEN");
1112        assert_eq!(call.args_raw, "$x");
1113        // Qualified head with gap before parens.
1114        let call = parse_placeholder_call("STD::LEN ($x)").expect("qualified parses");
1115        assert_eq!(call.module, Some("STD"));
1116        assert_eq!(call.name, "LEN");
1117        assert_eq!(call.args_raw, "$x");
1118        // Quoted parens never affect depth, both styles.
1119        assert!(parse_placeholder_call("LEN(\"a(b\")").is_some());
1120        assert!(parse_placeholder_call("LEN('a(b')").is_some());
1121        assert!(parse_placeholder_call("STD::LEN('a(b')").is_some());
1122        // Compounds and trailing garbage are not single calls.
1123        assert!(parse_placeholder_call("LEN($a) + LEN($b)").is_none());
1124        assert!(parse_placeholder_call("LEN($x))").is_none());
1125        // Lowercase bare heads keep non-call handling.
1126        assert!(parse_placeholder_call("foo($x)").is_none());
1127        // Empty and missing parens miss.
1128        assert!(parse_placeholder_call("$x").is_none());
1129        assert!(parse_placeholder_call("").is_none());
1130        // Args split shields commas in both quote styles.
1131        assert_eq!(
1132            split_placeholder_args("$a, \"b,c\", 'd,e'"),
1133            vec!["$a".to_string(), "\"b,c\"".to_string(), "'d,e'".to_string()],
1134        );
1135    }
1136
1137    #[test]
1138    fn placeholder_vars_cover_keys_calls_and_bad_paths() {
1139        use super::{TemplateVar, placeholder_vars};
1140        assert_eq!(
1141            placeholder_vars("$x"),
1142            vec![TemplateVar::Path(vec!["x".to_string()])],
1143        );
1144        assert_eq!(
1145            placeholder_vars(" $a.b.c "),
1146            vec![TemplateVar::Path(vec![
1147                "a".to_string(),
1148                "b".to_string(),
1149                "c".to_string(),
1150            ])],
1151        );
1152        assert_eq!(
1153            placeholder_vars("key"),
1154            vec![TemplateVar::Var("key".to_string())],
1155        );
1156        assert!(placeholder_vars("env:FOO").is_empty());
1157        assert!(placeholder_vars("script_env:BAR").is_empty());
1158        assert!(placeholder_vars("").is_empty());
1159        assert_eq!(
1160            placeholder_vars("M::F($a, {k: [$b, \"ignored\"]}, 'ignored', \"\"\"ignored\"\"\")"),
1161            vec![
1162                TemplateVar::Path(vec!["a".to_string()]),
1163                TemplateVar::Path(vec!["b".to_string()]),
1164            ],
1165        );
1166        assert!(placeholder_vars("$").is_empty());
1167        assert!(placeholder_vars("$a.").is_empty());
1168        assert!(placeholder_vars("$.a").is_empty());
1169    }
1170
1171    #[test]
1172    fn triple_quoted_blocks_split_and_parse_whole() {
1173        use super::{parse_placeholder_call, split_placeholder_args};
1174        // Commas, parens, and brackets inside `"""` never split depth.
1175        assert_eq!(
1176            split_placeholder_args("\"\"\"a, b (c) [d]\"\"\", $x"),
1177            vec!["\"\"\"a, b (c) [d]\"\"\"".to_string(), "$x".to_string()],
1178        );
1179        // A block arg spanning lines survives as one arg.
1180        assert_eq!(
1181            split_placeholder_args("\"\"\"line one\nline two\"\"\""),
1182            vec!["\"\"\"line one\nline two\"\"\"".to_string()],
1183        );
1184        // Parens inside blocks never affect the call paren match.
1185        let call = parse_placeholder_call("M::F(\"\"\"a(b\"\"\", $x)").expect("block parens parse");
1186        assert_eq!(call.name, "F");
1187        assert_eq!(call.args_raw, "\"\"\"a(b\"\"\", $x");
1188    }
1189
1190    #[test]
1191    fn string_literal_spellings_agree() {
1192        use super::parse_string_literal;
1193        let plain = parse_string_literal("\"Release installs\"")
1194            .expect("quoted")
1195            .expect("ok");
1196        let single = parse_string_literal("'Release installs'")
1197            .expect("single")
1198            .expect("ok");
1199        let block = parse_string_literal("\"\"\"Release installs\"\"\"")
1200            .expect("block")
1201            .expect("ok");
1202        assert_eq!(plain, "Release installs");
1203        assert_eq!(single, plain);
1204        assert_eq!(block, plain);
1205    }
1206
1207    #[test]
1208    fn string_literal_rejects_merged_and_unterminated() {
1209        use super::parse_string_literal;
1210        // Adjacent literals and infix expressions scan as several atoms:
1211        // not one literal, so the caller rejects them.
1212        assert!(parse_string_literal("\"a\" \"b\"").is_none());
1213        assert!(parse_string_literal("\"a\" + \"b\"").is_none());
1214        assert!(parse_string_literal("\"\"\"a\"\"\" \"\"\"b\"\"\"").is_none());
1215        // Trailing escapes and missing closers fail closed.
1216        assert!(parse_string_literal("\"foo\\\"").expect("quoted").is_err());
1217        assert!(parse_string_literal("'foo\\'").expect("single").is_err());
1218        assert!(
1219            parse_string_literal("\"\"\"foo\\")
1220                .expect("block escape")
1221                .is_err()
1222        );
1223        assert!(
1224            parse_string_literal("\"\"\"foo\"\"")
1225                .expect("block short")
1226                .is_err()
1227        );
1228        assert!(parse_string_literal("\"foo").expect("open").is_err());
1229        assert!(
1230            parse_string_literal("\"\"\"foo")
1231                .expect("open block")
1232                .is_err()
1233        );
1234    }
1235
1236    #[test]
1237    fn wrapped_delimiters_see_through_block_strings() {
1238        use super::strip_wrapped_delimiters;
1239        assert_eq!(
1240            strip_wrapped_delimiters("[\"\"\"a]b\"\"\"]", '[', ']'),
1241            Some("\"\"\"a]b\"\"\"")
1242        );
1243        assert_eq!(
1244            strip_wrapped_delimiters("{k: \"\"\"a}b\"\"\"}", '{', '}'),
1245            Some("k: \"\"\"a}b\"\"\"")
1246        );
1247        assert_eq!(strip_wrapped_delimiters("[a, b]", '[', ']'), Some("a, b"));
1248        assert!(strip_wrapped_delimiters("[a], [b]", '[', ']').is_none());
1249        assert!(strip_wrapped_delimiters("[a", '[', ']').is_none());
1250    }
1251}