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