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