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::{KEY_PATH_SEPARATOR, 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    /// Valid `ALIAS::NAME` shapes classify as
541    /// [`PlaceholderKey::DollarQualified`]; malformed qualified tails
542    /// (see [`is_malformed_dollar_qualified`]) classify as
543    /// [`PlaceholderKey::Invalid`], never here.
544    Dollar(&'a str),
545    /// `$ALIAS::NAME` with optional `.key` tail. Single owner for
546    /// the split (see [`parse_dollar_qualified`]), so no call site
547    /// restates [`crate::constants::split_qualified`].
548    /// Both shapes resolve: the tail traverses the CONST value
549    /// exactly like `$base.key`.
550    DollarQualified {
551        alias: &'a str,
552        name: &'a str,
553        keys: Vec<String>,
554    },
555    /// `env:` plus the raw name.
556    Env(&'a str),
557    /// `script_env:` plus the raw name.
558    ScriptEnv(&'a str),
559    /// One `[MODULE::]FUNC(args)` body, through the shared
560    /// [`parse_placeholder_call`] grammar.
561    Call(PlaceholderCall<'a>),
562    /// Bare `ALIAS::NAME` shape. Never resolves: phases reject it
563    /// with [`bare_sigil_error`] (use `$ALIAS::NAME`).
564    ConstRef { alias: &'a str, name: &'a str },
565    /// Bare `NAME.key...` shape (keys validated non-empty, no
566    /// spaces or commas; base is a bare identifier). Never resolves:
567    /// phases reject it with [`bare_sigil_error`].
568    KeyPath { base: &'a str, keys: Vec<String> },
569    /// Bare identifier shape (`NAME`). Never resolves: phases reject
570    /// it with [`bare_sigil_error`] (use `$NAME`).
571    Var(&'a str),
572    /// Malformed `$ALIAS::NAME` shape (see
573    /// [`is_malformed_dollar_qualified`]). Never resolves and never
574    /// masquerades as [`PlaceholderKey::Dollar`]: phases reject it
575    /// with the invalid-placeholder-key diagnostic, exactly like
576    /// [`TemplateArg::Invalid`] does for call args.
577    Invalid(&'a str),
578    /// Anything else, verbatim: script-var lookup, step-override
579    /// lookup, or a hard error, per the caller's contract.
580    Bare(&'a str),
581}
582
583/// Bare identifier rule shared by every CONST shape: ASCII
584/// alphanumeric plus underscore, non-empty. Dots, commas, spaces,
585/// dashes, and sigils never qualify, so override keys with `-` stay
586/// `Bare` and CONST shapes classify identically everywhere.
587pub fn is_bare_ident(src: &str) -> bool {
588    !src.is_empty() && src.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
589}
590
591/// One `ALIAS::NAME` CONST reference from trimmed source. `None` means
592/// not that shape: the caller keeps its own invalid-syntax error.
593/// Single owner for qualified-CONST syntax; every phase routes here.
594pub fn parse_qualified_const(src: &str) -> Option<(&str, &str)> {
595    let (alias, rest) = crate::constants::split_qualified(src)?;
596    if !is_bare_ident(alias) || !is_bare_ident(rest) {
597        return None;
598    }
599    if rest.contains(['.', ',', ' ', '\t']) {
600        return None;
601    }
602    Some((alias, rest))
603}
604
605/// One `BASE.key...` path from trimmed source. Base and every dot
606/// segment are bare identifiers. `None` means not that shape.
607/// Single owner for key-path syntax; empty segments (`A.`, `A..b`)
608/// and punctuation (`A.foo-bar`, `A.@#$`) never parse here, so
609/// static and runtime agree by construction.
610pub fn parse_bare_key_path(src: &str) -> Option<(&str, Vec<String>)> {
611    let (base, tail) = src.split_once(KEY_PATH_SEPARATOR)?;
612    if !is_bare_ident(base) {
613        return None;
614    }
615    if tail.is_empty() {
616        return None;
617    }
618    let segs: Vec<String> = tail
619        .split(KEY_PATH_SEPARATOR)
620        .map(|s| s.to_string())
621        .collect();
622    if segs.iter().any(|s| !is_bare_ident(s)) {
623        return None;
624    }
625    Some((base, segs))
626}
627
628/// Error text for a bare word where only `$` reads a binding:
629/// command arguments, `{{ }}` keys, and placeholder call args never
630/// resolve bare words. Single owner for the wording, so the static
631/// gate and runtime expansion agree word for word.
632pub fn bare_sigil_error(src: &str) -> String {
633    format!(
634        "bare `{src}` never reads a binding here; use `{}{src}`",
635        crate::constants::VAR_SIGIL
636    )
637}
638
639/// One `.key` segment spelling, shared with the token parser:
640/// digits-only indices (`0`) or `alpha/_`-start identifiers. Single
641/// owner for dot-tail validity, so `{{ }}` splits and token loops
642/// agree on every segment.
643pub fn is_key_segment_str(s: &str) -> bool {
644    !s.is_empty()
645        && (s.chars().all(|c| c.is_ascii_digit())
646            || (s
647                .chars()
648                .next()
649                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
650                && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')))
651}
652
653/// One `$ALIAS::NAME[.key...]` shape from post-`$` rest. Returns the
654/// alias, the name, and the dot tail (possibly empty). `None` means
655/// not that shape (including malformed dot tails: trailing dots,
656/// empty segments, and invalid segment characters never produce
657/// entries here). Single owner for the `$`-qualified split (see
658/// [`crate::constants::split_qualified`]), so no call site restates it.
659pub fn parse_dollar_qualified(rest: &str) -> Option<(&str, &str, Vec<String>)> {
660    let (head, tail) = match rest.split_once(KEY_PATH_SEPARATOR) {
661        Some((h, t)) => (h, Some(t)),
662        None => (rest, None),
663    };
664    let (alias, name) = crate::constants::split_qualified(head)?;
665    if !is_bare_ident(alias) || !is_bare_ident(name) {
666        return None;
667    }
668    let keys = match tail {
669        Some(t) => {
670            let segs: Vec<String> = t.split(KEY_PATH_SEPARATOR).map(|s| s.to_string()).collect();
671            if segs.iter().any(|s| !is_key_segment_str(s)) {
672                return None;
673            }
674            segs
675        }
676        None => Vec::new(),
677    };
678    Some((alias, name, keys))
679}
680
681/// Whether post-`$` rest names a malformed `$ALIAS::NAME` shape: any
682/// string containing `::` that is not a valid qualified read (dangling
683/// qualifier, empty segments, invalid characters). No valid local
684/// `$` variable can ever contain `::`, so such shapes never resolve
685/// and never classify as bare `$` paths: callers reject them
686/// deterministically as invalid placeholder/call-arg key paths in
687/// both static check and eval. Single owner for the distinction, so
688/// classifiers never restate it.
689pub fn is_malformed_dollar_qualified(rest: &str) -> bool {
690    rest.contains(crate::constants::MODULE_SEPARATOR) && parse_dollar_qualified(rest).is_none()
691}
692
693/// Single owner for `$` shape split: qualified `$A::B[.k]` vs bare
694/// `$rest`. Both placeholder and arg classifiers route here, then
695/// re-route malformed qualified tails (see
696/// [`is_malformed_dollar_qualified`]) to their invalid arms, so a new
697/// `$` shape lands once.
698pub enum DollarShape<'a> {
699    Qualified {
700        alias: &'a str,
701        name: &'a str,
702        keys: Vec<String>,
703    },
704    Bare(&'a str),
705}
706
707pub fn dollar_shape(rest: &str) -> DollarShape<'_> {
708    if let Some((alias, name, keys)) = parse_dollar_qualified(rest) {
709        DollarShape::Qualified { alias, name, keys }
710    } else {
711        DollarShape::Bare(rest)
712    }
713}
714
715/// Classify one trimmed placeholder key. Shape only, no resolution:
716/// runtimes keep their own check order (e.g. overrides-first) and
717/// their own trimming, sources, and errors.
718pub fn classify_placeholder_key(key: &str) -> PlaceholderKey<'_> {
719    if key.is_empty() {
720        return PlaceholderKey::Empty;
721    }
722    if let Some(rest) = key.strip_prefix(VAR_SIGIL_CHAR) {
723        match dollar_shape(rest) {
724            DollarShape::Qualified { alias, name, keys } => {
725                return PlaceholderKey::DollarQualified { alias, name, keys };
726            }
727            // Malformed `$ALIAS::NAME` shapes never masquerade as bare
728            // `$` paths: reject them as invalid placeholders here,
729            // exactly like call args reject them as invalid args.
730            DollarShape::Bare(bare) => {
731                if is_malformed_dollar_qualified(bare) {
732                    return PlaceholderKey::Invalid(bare);
733                }
734                return PlaceholderKey::Dollar(bare);
735            }
736        }
737    }
738    if let Some(rest) = key.strip_prefix("env:") {
739        return PlaceholderKey::Env(rest);
740    }
741    if let Some(rest) = key.strip_prefix("script_env:") {
742        return PlaceholderKey::ScriptEnv(rest);
743    }
744    if let Some(call) = parse_placeholder_call(key) {
745        return PlaceholderKey::Call(call);
746    }
747    if let Some((alias, name)) = parse_qualified_const(key) {
748        return PlaceholderKey::ConstRef { alias, name };
749    }
750    if let Some((base, keys)) = parse_bare_key_path(key) {
751        return PlaceholderKey::KeyPath { base, keys };
752    }
753    if is_bare_ident(key) {
754        return PlaceholderKey::Var(key);
755    }
756    PlaceholderKey::Bare(key)
757}
758
759/// One `$a.b` path split: on `.` with each part trimmed, exactly like
760/// runtime expansion. No validity judgment: callers decide what empty
761/// parts mean under their own contract.
762pub fn split_var_path(rest: &str) -> Vec<String> {
763    rest.split(KEY_PATH_SEPARATOR)
764        .map(|part| part.trim().to_string())
765        .collect()
766}
767
768/// Variable reads inside one placeholder key, routed through the
769/// single [`classify_placeholder_key`] owner: `$` paths parse through
770/// the single path parser below, env keys contribute nothing, call
771/// shapes contribute their nested arg refs, and bare keys stay
772/// literal.
773/// Call args recurse through the shared literal owners
774/// (`parse_string_literal`, `strip_wrapped_delimiters`,
775/// `split_top_level`), so new arg spellings land once, here.
776pub fn placeholder_vars(key: &str) -> Vec<TemplateVar> {
777    match classify_placeholder_key(key.trim()) {
778        PlaceholderKey::Empty => Vec::new(),
779        PlaceholderKey::Dollar(rest) => parse_dollar_path(rest).into_iter().collect(),
780        PlaceholderKey::DollarQualified { .. } => Vec::new(),
781        PlaceholderKey::Invalid(_) => Vec::new(),
782        PlaceholderKey::Env(_) | PlaceholderKey::ScriptEnv(_) => Vec::new(),
783        PlaceholderKey::Call(call) => {
784            let mut out = Vec::new();
785            for arg in split_placeholder_args(call.args_raw) {
786                collect_call_arg_vars(&arg, &mut out);
787            }
788            out
789        }
790        PlaceholderKey::ConstRef { alias, name } => vec![TemplateVar::ConstRef {
791            alias: alias.to_string(),
792            name: name.to_string(),
793        }],
794        PlaceholderKey::KeyPath { base, keys } => vec![TemplateVar::KeyPath {
795            base: base.to_string(),
796            keys,
797        }],
798        PlaceholderKey::Var(name) => vec![TemplateVar::Var(name.to_string())],
799        PlaceholderKey::Bare(key) => vec![TemplateVar::Bare(key.to_string())],
800    }
801}
802
803/// One `$a.b` path from its post-`$` rest. `None` means malformed:
804/// the caller owns that error. Single owner for `$` path syntax.
805pub fn parse_var_path(rest: &str) -> Option<Vec<String>> {
806    let parts = split_var_path(rest);
807    if parts.iter().any(|part| part.is_empty()) {
808        return None;
809    }
810    Some(parts)
811}
812
813/// Maximum nesting for map and list literals in placeholder call
814/// args. Single depth budget shared by static inference and runtime
815/// resolution.
816pub const MAX_TEMPLATE_ARG_DEPTH: usize = 16;
817
818/// One placeholder call argument's shape. Single owner for the
819/// argument grammar: every path classifies here, then acts on the
820/// result with its own types and errors.
821pub enum TemplateArg<'a> {
822    /// `$` variable path: raw rest after `$` (validate with
823    /// [`parse_var_path`]). Never holds `ALIAS::NAME`: valid shapes
824    /// classify as [`TemplateArg::DollarQualified`], malformed ones
825    /// as [`TemplateArg::Invalid`].
826    Dollar(&'a str),
827    /// `$ALIAS::NAME` with optional `.key` tail: both resolve, the
828    /// tail traversing the CONST value exactly like `$base.key`.
829    /// Single owner for the split (see [`parse_dollar_qualified`]),
830    /// so no call site restates [`crate::constants::split_qualified`].
831    DollarQualified {
832        alias: &'a str,
833        name: &'a str,
834        keys: Vec<String>,
835    },
836    /// String literal source in any spelling (parse with
837    /// [`parse_string_literal`]).
838    Str(&'a str),
839    /// `{...}` map inner source.
840    Map(&'a str),
841    /// `[...]` list inner source.
842    List(&'a str),
843    /// Bare scalar source (`true`, `false`, numbers; see
844    /// [`parse_scalar_literal`]).
845    Scalar(&'a str),
846    /// Bare `ALIAS::NAME` shape. Never resolves: phases reject it
847    /// with [`bare_sigil_error`].
848    ConstRef { alias: &'a str, name: &'a str },
849    /// Bare `NAME.key...` path (validated by [`parse_bare_key_path`]).
850    /// Never resolves: phases reject it with [`bare_sigil_error`].
851    KeyPath { base: &'a str, keys: Vec<String> },
852    /// Bare `NAME` identifier. Never resolves: phases reject it with
853    /// [`bare_sigil_error`] (use `$NAME`).
854    Var(&'a str),
855    /// Anything else: the caller owns the invalid-syntax error.
856    Invalid(&'a str),
857}
858
859/// Classify one call argument by shape. Inputs arrive trimmed from
860/// [`split_placeholder_args`].
861pub fn classify_template_arg(src: &str) -> TemplateArg<'_> {
862    let src = src.trim();
863    if let Some(rest) = src.strip_prefix(VAR_SIGIL_CHAR) {
864        match dollar_shape(rest) {
865            DollarShape::Qualified { alias, name, keys } => {
866                return TemplateArg::DollarQualified { alias, name, keys };
867            }
868            // Malformed `$ALIAS::NAME.` tails never masquerade as bare
869            // `$` paths: reject them as invalid args here, exactly like
870            // static check and eval do.
871            DollarShape::Bare(bare) => {
872                if is_malformed_dollar_qualified(bare) {
873                    return TemplateArg::Invalid(src);
874                }
875                return TemplateArg::Dollar(bare);
876            }
877        }
878    }
879    if parse_string_literal(src).is_some() {
880        return TemplateArg::Str(src);
881    }
882    if let Some(inner) = strip_wrapped_delimiters(src, '{', '}') {
883        return TemplateArg::Map(inner);
884    }
885    if let Some(inner) = strip_wrapped_delimiters(src, '[', ']') {
886        return TemplateArg::List(inner);
887    }
888    if parse_scalar_literal(src).is_some() {
889        return TemplateArg::Scalar(src);
890    }
891    if let Some((alias, name)) = parse_qualified_const(src) {
892        return TemplateArg::ConstRef { alias, name };
893    }
894    if let Some((base, keys)) = parse_bare_key_path(src) {
895        return TemplateArg::KeyPath { base, keys };
896    }
897    if is_bare_ident(src) {
898        return TemplateArg::Var(src);
899    }
900    TemplateArg::Invalid(src)
901}
902
903/// One bare scalar literal's value shape. Shared by static inference
904/// (tags) and runtime resolution (values), which map the same shapes
905/// instead of restating the cascade.
906pub enum ScalarLit {
907    Bool(bool),
908    Int(i64),
909    Float(f64),
910}
911
912/// Parse one bare scalar literal: `true`/`false`, then int, then
913/// float. `None` means not scalar-shaped at all.
914pub fn parse_scalar_literal(src: &str) -> Option<ScalarLit> {
915    match src {
916        "true" => Some(ScalarLit::Bool(true)),
917        "false" => Some(ScalarLit::Bool(false)),
918        _ => src
919            .parse::<i64>()
920            .map(ScalarLit::Int)
921            .ok()
922            .or_else(|| src.parse::<f64>().map(ScalarLit::Float).ok()),
923    }
924}
925
926/// Top-level single-`:` separator indices in one atom scan. A `::`
927/// qualified separator never counts: an index fires only when neither
928/// neighbor is a `:` at depth zero. Single owner for colon logic;
929/// [`split_map_entry`] pulls the first index and rejects a second,
930/// so no call site restates the depth or `::` rule.
931fn single_colon_indices(atoms: &[Atom<'_>]) -> Vec<usize> {
932    let mut out = Vec::new();
933    let mut depth: usize = 0;
934    let mut i = 0;
935    while i < atoms.len() {
936        match atoms[i].kind {
937            AtomKind::Open => depth += 1,
938            AtomKind::Close => depth = depth.saturating_sub(1),
939            AtomKind::Sep(':') if depth == 0 => {
940                let prev_double = i > 0 && matches!(atoms[i - 1].kind, AtomKind::Sep(':'));
941                let next_double = atoms
942                    .get(i + 1)
943                    .is_some_and(|a| matches!(a.kind, AtomKind::Sep(':')));
944                if !prev_double && !next_double {
945                    out.push(i);
946                }
947            }
948            _ => {}
949        }
950        i += 1;
951    }
952    out
953}
954
955/// One `{key: value}` entry's key and value sources, split once on
956/// the first top-level single `:`. A `::` qualified separator never
957/// splits: `$LIB::NAME` values stay whole, so nested qualified refs
958/// survive map literals in both static inference and runtime
959/// resolution. `None` when the entry is not exactly one pair.
960pub fn split_map_entry(entry: &str) -> Option<(String, String)> {
961    let atoms = scan_atoms(entry);
962    let indices = single_colon_indices(&atoms);
963    if indices.len() != 1 {
964        return None;
965    }
966    let i = indices[0];
967    let key: String = atoms[..i].iter().map(|a| a.text).collect();
968    let value: String = atoms[i + 1..].iter().map(|a| a.text).collect();
969    let key = key.trim().to_string();
970    let value = value.trim().to_string();
971    if key.is_empty() || value.is_empty() {
972        return None;
973    }
974    Some((key, value))
975}
976
977/// One map literal key: a string literal in any spelling or a bare
978/// ASCII identifier. Shared by static inference and runtime
979/// resolution, which report identical diagnostics.
980pub fn parse_map_key(src: &str) -> DiagnosticResult<String> {
981    if let Some(literal) = parse_string_literal(src) {
982        return literal;
983    }
984    if !src.is_empty() && src.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
985        return Ok(src.to_string());
986    }
987    Err(template_diag::template_map_key_invalid(src))
988}
989
990fn parse_dollar_path(rest: &str) -> Option<TemplateVar> {
991    parse_var_path(rest).map(TemplateVar::Path)
992}
993
994/// Nested `$` refs inside one call arg, through the shared argument
995/// classifier: strings, scalars, and invalid shapes hold none; maps
996/// and lists recurse into their entries; malformed entries are
997/// runtime-owned invalid syntax and contribute nothing here.
998fn collect_call_arg_vars(src: &str, out: &mut Vec<TemplateVar>) {
999    match classify_template_arg(src) {
1000        TemplateArg::Dollar(rest) => {
1001            out.extend(parse_dollar_path(rest));
1002        }
1003        TemplateArg::Map(inner) => {
1004            if inner.trim().is_empty() {
1005                return;
1006            }
1007            for entry in split_top_level(inner, ',') {
1008                if let Some((_, value)) = split_map_entry(&entry) {
1009                    collect_call_arg_vars(&value, out);
1010                }
1011            }
1012        }
1013        TemplateArg::List(inner) => {
1014            if inner.trim().is_empty() {
1015                return;
1016            }
1017            for item in split_top_level(inner, ',') {
1018                collect_call_arg_vars(&item, out);
1019            }
1020        }
1021        TemplateArg::ConstRef { alias, name } => {
1022            out.push(TemplateVar::ConstRef {
1023                alias: alias.to_string(),
1024                name: name.to_string(),
1025            });
1026        }
1027        TemplateArg::KeyPath { base, keys } => {
1028            out.push(TemplateVar::KeyPath {
1029                base: base.to_string(),
1030                keys,
1031            });
1032        }
1033        TemplateArg::Var(name) => {
1034            out.push(TemplateVar::Var(name.to_string()));
1035        }
1036        TemplateArg::DollarQualified { .. } => {}
1037        TemplateArg::Str(_) | TemplateArg::Scalar(_) | TemplateArg::Invalid(_) => {}
1038    }
1039}
1040/// Allocation-free segment iterator over template text. See the module
1041/// docs for the exact rules; the unit tests below pin every escape
1042/// and boundary shape.
1043#[derive(Debug, Clone)]
1044pub struct TemplateSegments<'a> {
1045    text: &'a str,
1046    pos: usize,
1047    pending: Option<(usize, &'a str, &'a str)>,
1048}
1049
1050impl<'a> TemplateSegments<'a> {
1051    /// Scan `text` front to back.
1052    pub fn new(text: &'a str) -> Self {
1053        Self {
1054            text,
1055            pos: 0,
1056            pending: None,
1057        }
1058    }
1059}
1060
1061impl<'a> Iterator for TemplateSegments<'a> {
1062    type Item = TemplateSegment<'a>;
1063
1064    fn next(&mut self) -> Option<Self::Item> {
1065        if let Some((end, key, raw)) = self.pending.take() {
1066            self.pos = end;
1067            return Some(TemplateSegment::Placeholder { key, raw });
1068        }
1069        // Copy out: every slice below then ties to `'a`, never to the
1070        // `&mut self` borrow, so staging `pending` never conflicts.
1071        let text: &'a str = self.text;
1072        let bytes = text.as_bytes();
1073        let len = bytes.len();
1074        if self.pos >= len {
1075            return None;
1076        }
1077        let start = self.pos;
1078        let mut i = start;
1079        while i < len {
1080            if bytes[i] == b'\\' {
1081                // `\\` consumes both (the opener after it stays live);
1082                // `\{{` consumes all three as literal text; anything
1083                // else consumes only the backslash and reprocesses.
1084                if i + 2 < len && bytes[i + 1] == b'{' && bytes[i + 2] == b'{' {
1085                    i += 3;
1086                } else if i + 1 < len && bytes[i + 1] == b'\\' {
1087                    i += 2;
1088                } else {
1089                    i += 1;
1090                }
1091                continue;
1092            }
1093            if bytes[i] == b'{' && i + 1 < len && bytes[i + 1] == b'{' {
1094                let mut j = i + 2;
1095                while j + 1 < len && !(bytes[j] == b'}' && bytes[j + 1] == b'}') {
1096                    j += 1;
1097                }
1098                if j + 1 >= len {
1099                    break;
1100                }
1101                let key = text[i + 2..j].trim();
1102                let raw = &text[i..j + 2];
1103                if i > start {
1104                    self.pending = Some((j + 2, key, raw));
1105                    return Some(TemplateSegment::Text(&text[start..i]));
1106                }
1107                self.pos = j + 2;
1108                return Some(TemplateSegment::Placeholder { key, raw });
1109            }
1110            i += 1;
1111        }
1112        self.pos = len;
1113        Some(TemplateSegment::Text(&text[start..]))
1114    }
1115}
1116
1117#[cfg(test)]
1118mod tests {
1119    use super::{TemplateSegment, TemplateSegments};
1120
1121    fn segments(text: &str) -> Vec<TemplateSegment<'_>> {
1122        TemplateSegments::new(text).collect()
1123    }
1124
1125    #[test]
1126    fn plain_text_is_one_segment() {
1127        assert_eq!(segments("hello"), vec![TemplateSegment::Text("hello")],);
1128    }
1129
1130    #[test]
1131    fn placeholder_splits_around_text() {
1132        assert_eq!(
1133            segments("a{{ $x }}b"),
1134            vec![
1135                TemplateSegment::Text("a"),
1136                TemplateSegment::Placeholder {
1137                    key: "$x",
1138                    raw: "{{ $x }}"
1139                },
1140                TemplateSegment::Text("b"),
1141            ],
1142        );
1143    }
1144
1145    #[test]
1146    fn keys_trim() {
1147        assert_eq!(
1148            segments("{{  env:A  }}"),
1149            vec![TemplateSegment::Placeholder {
1150                key: "env:A",
1151                raw: "{{  env:A  }}"
1152            }],
1153        );
1154    }
1155
1156    #[test]
1157    fn escaped_opener_stays_text() {
1158        assert_eq!(
1159            segments("\\{{ env:A }}"),
1160            vec![TemplateSegment::Text("\\{{ env:A }}")],
1161        );
1162    }
1163
1164    #[test]
1165    fn escaped_backslash_keeps_opener_live() {
1166        assert_eq!(
1167            segments("\\\\{{ env:A }}"),
1168            vec![
1169                TemplateSegment::Text("\\\\"),
1170                TemplateSegment::Placeholder {
1171                    key: "env:A",
1172                    raw: "{{ env:A }}"
1173                },
1174            ],
1175        );
1176    }
1177
1178    #[test]
1179    fn escaped_opener_before_braces_stays_text() {
1180        // `\{{{x}}`: the `\{{` consumes as literal, exactly like the
1181        // historical expansion loop; no placeholder opens inside it.
1182        assert_eq!(
1183            segments("\\{{{x}}"),
1184            vec![TemplateSegment::Text("\\{{{x}}")],
1185        );
1186    }
1187
1188    #[test]
1189    fn unclosed_opener_stays_text() {
1190        assert_eq!(
1191            segments("hi {{ unclosed"),
1192            vec![TemplateSegment::Text("hi {{ unclosed")],
1193        );
1194    }
1195
1196    #[test]
1197    fn empty_and_blank_keys_are_placeholders() {
1198        assert_eq!(
1199            segments("{{}}"),
1200            vec![TemplateSegment::Placeholder {
1201                key: "",
1202                raw: "{{}}"
1203            }],
1204        );
1205        assert_eq!(
1206            segments("{{ }}"),
1207            vec![TemplateSegment::Placeholder {
1208                key: "",
1209                raw: "{{ }}"
1210            }],
1211        );
1212    }
1213
1214    #[test]
1215    fn adjacent_placeholders_emit_no_empty_text() {
1216        assert_eq!(
1217            segments("{{a}}{{b}}"),
1218            vec![
1219                TemplateSegment::Placeholder {
1220                    key: "a",
1221                    raw: "{{a}}"
1222                },
1223                TemplateSegment::Placeholder {
1224                    key: "b",
1225                    raw: "{{b}}"
1226                },
1227            ],
1228        );
1229    }
1230
1231    #[test]
1232    fn call_shapes_parse_once() {
1233        use super::{parse_placeholder_call, split_placeholder_args};
1234        // Bare head: module-less, name span covers the head.
1235        let call = parse_placeholder_call("LEN($x)").expect("bare parses");
1236        assert_eq!(call.module, None);
1237        assert_eq!(call.name, "LEN");
1238        assert_eq!(&"LEN($x)"[call.name_span.clone()], "LEN");
1239        assert_eq!(call.args_raw, "$x");
1240        // Qualified head with gap before parens.
1241        let call = parse_placeholder_call("STD::LEN ($x)").expect("qualified parses");
1242        assert_eq!(call.module, Some("STD"));
1243        assert_eq!(call.name, "LEN");
1244        assert_eq!(call.args_raw, "$x");
1245        // Quoted parens never affect depth, both styles.
1246        assert!(parse_placeholder_call("LEN(\"a(b\")").is_some());
1247        assert!(parse_placeholder_call("LEN('a(b')").is_some());
1248        assert!(parse_placeholder_call("STD::LEN('a(b')").is_some());
1249        // Compounds and trailing garbage are not single calls.
1250        assert!(parse_placeholder_call("LEN($a) + LEN($b)").is_none());
1251        assert!(parse_placeholder_call("LEN($x))").is_none());
1252        // Lowercase bare heads keep non-call handling.
1253        assert!(parse_placeholder_call("foo($x)").is_none());
1254        // Empty and missing parens miss.
1255        assert!(parse_placeholder_call("$x").is_none());
1256        assert!(parse_placeholder_call("").is_none());
1257        // Args split shields commas in both quote styles.
1258        assert_eq!(
1259            split_placeholder_args("$a, \"b,c\", 'd,e'"),
1260            vec!["$a".to_string(), "\"b,c\"".to_string(), "'d,e'".to_string()],
1261        );
1262    }
1263
1264    #[test]
1265    fn placeholder_vars_cover_keys_calls_and_bad_paths() {
1266        use super::{TemplateVar, placeholder_vars};
1267        assert_eq!(
1268            placeholder_vars("$x"),
1269            vec![TemplateVar::Path(vec!["x".to_string()])],
1270        );
1271        assert_eq!(
1272            placeholder_vars(" $a.b.c "),
1273            vec![TemplateVar::Path(vec![
1274                "a".to_string(),
1275                "b".to_string(),
1276                "c".to_string(),
1277            ])],
1278        );
1279        assert_eq!(
1280            placeholder_vars("key"),
1281            vec![TemplateVar::Var("key".to_string())],
1282        );
1283        assert!(placeholder_vars("env:FOO").is_empty());
1284        assert!(placeholder_vars("script_env:BAR").is_empty());
1285        assert!(placeholder_vars("").is_empty());
1286        assert_eq!(
1287            placeholder_vars("M::F($a, {k: [$b, \"ignored\"]}, 'ignored', \"\"\"ignored\"\"\")"),
1288            vec![
1289                TemplateVar::Path(vec!["a".to_string()]),
1290                TemplateVar::Path(vec!["b".to_string()]),
1291            ],
1292        );
1293        assert!(placeholder_vars("$").is_empty());
1294        assert!(placeholder_vars("$a.").is_empty());
1295        assert!(placeholder_vars("$.a").is_empty());
1296    }
1297
1298    #[test]
1299    fn qualified_dot_tails_validate_every_segment() {
1300        use super::{
1301            PlaceholderKey, TemplateArg, classify_placeholder_key, classify_template_arg,
1302            is_malformed_dollar_qualified, parse_dollar_qualified,
1303        };
1304        // Valid shapes split with intact keys, including chained numerics.
1305        assert_eq!(
1306            parse_dollar_qualified("LIB::M"),
1307            Some(("LIB", "M", Vec::new()))
1308        );
1309        assert_eq!(
1310            parse_dollar_qualified("LIB::M.a"),
1311            Some(("LIB", "M", vec!["a".to_string()]))
1312        );
1313        assert_eq!(
1314            parse_dollar_qualified("LIB::M.a.0.1"),
1315            Some((
1316                "LIB",
1317                "M",
1318                vec!["a".to_string(), "0".to_string(), "1".to_string()]
1319            ))
1320        );
1321        // Malformed tails never produce entries.
1322        assert_eq!(parse_dollar_qualified("LIB::M."), None);
1323        assert_eq!(parse_dollar_qualified("LIB::M..c"), None);
1324        assert_eq!(parse_dollar_qualified("LIB::M.nested."), None);
1325        assert_eq!(parse_dollar_qualified("LIB::M.bad-seg"), None);
1326        assert_eq!(parse_dollar_qualified("LIB::M.a b"), None);
1327        assert_eq!(parse_dollar_qualified("LIB::"), None);
1328        assert_eq!(parse_dollar_qualified("::M"), None);
1329        // The malformed distinction fires on any `::` string that is
1330        // not a valid qualified read, with zero gaps.
1331        for rest in [
1332            "LIB::M.",
1333            "LIB::M..c",
1334            "LIB::M.nested.",
1335            "LIB::M.bad-seg",
1336            "LIB::",
1337            "::M",
1338            "LIB:::M",
1339        ] {
1340            assert!(is_malformed_dollar_qualified(rest), "{rest}");
1341        }
1342        for rest in ["LIB::M", "LIB::M.a.0", "foo.bar", "M", "LIB::M.a_b2"] {
1343            assert!(!is_malformed_dollar_qualified(rest), "{rest}");
1344        }
1345        // Leading-digit names parse as shapes (both token and template
1346        // sides agree) and fail closed at resolve time, never as
1347        // malformed tails.
1348        assert!(!is_malformed_dollar_qualified("LIB::0bad.a"));
1349        assert!(matches!(
1350            classify_template_arg("$LIB::0bad.a"),
1351            TemplateArg::DollarQualified { .. }
1352        ));
1353        assert!(matches!(
1354            classify_template_arg("$LIB::M."),
1355            TemplateArg::Invalid(_)
1356        ));
1357        assert!(matches!(
1358            classify_template_arg("$LIB::M.bad-seg"),
1359            TemplateArg::Invalid(_)
1360        ));
1361        assert!(matches!(
1362            classify_template_arg("$LIB::M.a"),
1363            TemplateArg::DollarQualified { .. }
1364        ));
1365        // Placeholders reject malformed tails as invalid too, never as
1366        // bare `$` paths.
1367        assert!(matches!(
1368            classify_placeholder_key("$LIB::M."),
1369            PlaceholderKey::Invalid(_)
1370        ));
1371        assert!(matches!(
1372            classify_placeholder_key("$LIB::M.bad-seg"),
1373            PlaceholderKey::Invalid(_)
1374        ));
1375        assert!(matches!(
1376            classify_placeholder_key("$LIB::"),
1377            PlaceholderKey::Invalid(_)
1378        ));
1379        assert!(matches!(
1380            classify_placeholder_key("$LIB::M.a"),
1381            PlaceholderKey::DollarQualified { .. }
1382        ));
1383    }
1384
1385    #[test]
1386    fn map_entries_keep_qualified_separators_whole() {
1387        use super::split_map_entry;
1388        // `::` never splits: qualified values stay whole in both
1389        // static inference and runtime resolution.
1390        assert_eq!(
1391            split_map_entry("k: $LIB::ITEMS.0"),
1392            Some(("k".to_string(), "$LIB::ITEMS.0".to_string()))
1393        );
1394        assert_eq!(
1395            split_map_entry("k: $LIB::M.a.0"),
1396            Some(("k".to_string(), "$LIB::M.a.0".to_string()))
1397        );
1398        // Quoted keys and nested literals keep their separators too.
1399        assert_eq!(
1400            split_map_entry("\"k\": {inner: $LIB::X}"),
1401            Some(("\"k\"".to_string(), "{inner: $LIB::X}".to_string()))
1402        );
1403        // Genuine multi-pair entries still fail: exactly one pair.
1404        assert_eq!(split_map_entry("k: a: b"), None);
1405        assert_eq!(split_map_entry("k:"), None);
1406        assert_eq!(split_map_entry(": v"), None);
1407        assert_eq!(split_map_entry("k"), None);
1408    }
1409
1410    #[test]
1411    fn triple_quoted_blocks_split_and_parse_whole() {
1412        use super::{parse_placeholder_call, split_placeholder_args};
1413        // Commas, parens, and brackets inside `"""` never split depth.
1414        assert_eq!(
1415            split_placeholder_args("\"\"\"a, b (c) [d]\"\"\", $x"),
1416            vec!["\"\"\"a, b (c) [d]\"\"\"".to_string(), "$x".to_string()],
1417        );
1418        // A block arg spanning lines survives as one arg.
1419        assert_eq!(
1420            split_placeholder_args("\"\"\"line one\nline two\"\"\""),
1421            vec!["\"\"\"line one\nline two\"\"\"".to_string()],
1422        );
1423        // Parens inside blocks never affect the call paren match.
1424        let call = parse_placeholder_call("M::F(\"\"\"a(b\"\"\", $x)").expect("block parens parse");
1425        assert_eq!(call.name, "F");
1426        assert_eq!(call.args_raw, "\"\"\"a(b\"\"\", $x");
1427    }
1428
1429    #[test]
1430    fn string_literal_spellings_agree() {
1431        use super::parse_string_literal;
1432        let plain = parse_string_literal("\"Release installs\"")
1433            .expect("quoted")
1434            .expect("ok");
1435        let single = parse_string_literal("'Release installs'")
1436            .expect("single")
1437            .expect("ok");
1438        let block = parse_string_literal("\"\"\"Release installs\"\"\"")
1439            .expect("block")
1440            .expect("ok");
1441        assert_eq!(plain, "Release installs");
1442        assert_eq!(single, plain);
1443        assert_eq!(block, plain);
1444    }
1445
1446    #[test]
1447    fn string_literal_rejects_merged_and_unterminated() {
1448        use super::parse_string_literal;
1449        // Adjacent literals and infix expressions scan as several atoms:
1450        // not one literal, so the caller rejects them.
1451        assert!(parse_string_literal("\"a\" \"b\"").is_none());
1452        assert!(parse_string_literal("\"a\" + \"b\"").is_none());
1453        assert!(parse_string_literal("\"\"\"a\"\"\" \"\"\"b\"\"\"").is_none());
1454        // Trailing escapes and missing closers fail closed.
1455        assert!(parse_string_literal("\"foo\\\"").expect("quoted").is_err());
1456        assert!(parse_string_literal("'foo\\'").expect("single").is_err());
1457        assert!(
1458            parse_string_literal("\"\"\"foo\\")
1459                .expect("block escape")
1460                .is_err()
1461        );
1462        assert!(
1463            parse_string_literal("\"\"\"foo\"\"")
1464                .expect("block short")
1465                .is_err()
1466        );
1467        assert!(parse_string_literal("\"foo").expect("open").is_err());
1468        assert!(
1469            parse_string_literal("\"\"\"foo")
1470                .expect("open block")
1471                .is_err()
1472        );
1473    }
1474
1475    #[test]
1476    fn wrapped_delimiters_see_through_block_strings() {
1477        use super::strip_wrapped_delimiters;
1478        assert_eq!(
1479            strip_wrapped_delimiters("[\"\"\"a]b\"\"\"]", '[', ']'),
1480            Some("\"\"\"a]b\"\"\"")
1481        );
1482        assert_eq!(
1483            strip_wrapped_delimiters("{k: \"\"\"a}b\"\"\"}", '{', '}'),
1484            Some("k: \"\"\"a}b\"\"\"")
1485        );
1486        assert_eq!(strip_wrapped_delimiters("[a, b]", '[', ']'), Some("a, b"));
1487        assert!(strip_wrapped_delimiters("[a], [b]", '[', ']').is_none());
1488        assert!(strip_wrapped_delimiters("[a", '[', ']').is_none());
1489    }
1490}