Skip to main content

oxdock_parser/
template.rs

1//! Template placeholder scanning shared by expansion and static
2//! checks: one implementation of the `{{ ... }}` rules, so the two
3//! can never disagree on what counts as a read.
4//!
5//! Rules (mirroring the historical `expand_string` loop one for one):
6//! - `\{{` is literal text, never an opener. `\\` is a literal
7//!   backslash and never escapes what follows it.
8//! - A lone backslash escapes nothing for scanning: only the
9//!   backslash is literal, the next character reprocesses normally.
10//! - `{{` opens only when a matching `}}` follows; otherwise the rest
11//!   is literal text, exactly as expansion renders it verbatim.
12//! - Placeholder keys arrive trimmed; closers never nest.
13//! - Byte-oriented and allocation-free: braces and the backslash are
14//!   ASCII, so no multibyte character can match, and every cut lands
15//!   on an ASCII boundary.
16
17/// One raw segment of template text: literal bytes, or one unescaped
18/// `{{ ... }}` with its trimmed key plus the verbatim raw slice.
19/// Escapes are NOT processed here; consumers apply them to
20/// [`TemplateSegment::Text`] themselves.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum TemplateSegment<'a> {
23    /// Literal text up to the next placeholder (may hold backslashes
24    /// and unclosed `{{`, verbatim).
25    Text(&'a str),
26    /// An unescaped placeholder; `key` is the trimmed interior and
27    /// `raw` is the full `{{ ... }}` slice verbatim (braces plus the
28    /// original inner spacing), so rewriters can splice the key
29    /// without touching surrounding bytes.
30    Placeholder { key: &'a str, raw: &'a str },
31}
32
33/// One parsed `{{ ... }}` call body: `[MODULE::]FUNC(args_raw)`.
34///
35/// Single grammar behind every phase: parse-time qualification,
36/// static checking, and runtime dispatch all read the same shape,
37/// so the three can never disagree on what counts as a call.
38/// `module` is `None` for bare `FUNC(...)` heads (statement-scope
39/// resolution decides those); `name_span` is the byte range of
40/// `name` inside the input `key`, so rewriters can splice exactly
41/// the head without touching surrounding spacing.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct PlaceholderCall<'a> {
44    /// `MODULE` in `MODULE::FUNC(...)`, or `None` for bare heads.
45    pub module: Option<&'a str>,
46    /// Function head (`FUNC`).
47    pub name: &'a str,
48    /// Byte range of `name` inside the input `key`.
49    pub name_span: std::ops::Range<usize>,
50    /// Raw bytes between the parens (untrimmed, unsplit).
51    pub args_raw: &'a str,
52}
53
54fn is_module_char(c: char) -> bool {
55    c.is_ascii_alphanumeric() || c == '_' || c == '-'
56}
57
58fn is_bare_head(name: &str) -> bool {
59    let mut chars = name.chars();
60    if !chars.next().is_some_and(|c| c.is_ascii_uppercase()) {
61        return false;
62    }
63    chars.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
64}
65
66/// Parse one placeholder key as `[MODULE::]FUNC(args)`.
67///
68/// Returns `None` when the key is not exactly one call: missing
69/// parens, lowercase bare heads, bad `MODULE`/`FUNC` spellings, an
70/// unbalanced paren group, or trailing bytes past the closer
71/// (compounds like `LEN($a) + LEN($b)` stay untouched). The paren
72/// scan tracks both quote styles with backslash escapes, so a paren
73/// inside `'a(b'` or `"a(b"` never affects depth; whether the arg
74/// grammar accepts that style is the caller's decision.
75pub fn parse_placeholder_call(key: &str) -> Option<PlaceholderCall<'_>> {
76    let trimmed = key.trim();
77    if trimmed.is_empty() {
78        return None;
79    }
80    let base = key.find(trimmed).unwrap_or(0);
81    let paren = trimmed.find('(')?;
82    let (head_raw, rest) = trimmed.split_at(paren);
83    let head = head_raw.trim_end();
84    if head.is_empty() {
85        return None;
86    }
87    enum Head<'a> {
88        Bare(&'a str),
89        Qualified { name: &'a str, start: usize },
90    }
91    let head_parsed = if let Some((left, right)) = head.split_once("::") {
92        if left.is_empty() || !left.chars().all(is_module_char) {
93            return None;
94        }
95        let name = right.trim();
96        if name.is_empty() || !name.chars().all(is_module_char) {
97            return None;
98        }
99        // Qualified heads stay permissive here (runtime spellings
100        // allow `alnum _ -`); resolution validates case later, so an
101        // unknown-case head still fails naming the culprit.
102        // `head` opens `trimmed`, so the name offset inside `head`
103        // is its offset inside `trimmed` too.
104        let colon = head.find("::").expect("split found ::");
105        let leading = head[colon + 2..].len() - head[colon + 2..].trim_start().len();
106        Head::Qualified {
107            name,
108            start: colon + 2 + leading,
109        }
110    } else {
111        if !is_bare_head(head) {
112            return None;
113        }
114        Head::Bare(head)
115    };
116    let bytes = rest.as_bytes();
117    let mut depth: usize = 0;
118    let mut quote: u8 = 0;
119    let mut escaped = false;
120    let mut close_at: Option<usize> = None;
121    let mut i = 0;
122    while i < bytes.len() {
123        let b = bytes[i];
124        if quote != 0 {
125            if escaped {
126                escaped = false;
127            } else if b == b'\\' {
128                escaped = true;
129            } else if b == quote {
130                quote = 0;
131            }
132            i += 1;
133            continue;
134        }
135        match b {
136            b'"' | b'\'' => quote = b,
137            b'(' => depth += 1,
138            b')' => {
139                if depth == 0 {
140                    return None;
141                }
142                depth -= 1;
143                if depth == 0 {
144                    close_at = Some(i);
145                    break;
146                }
147            }
148            _ => {}
149        }
150        i += 1;
151    }
152    let close_at = close_at?;
153    if !rest[close_at + 1..].trim().is_empty() {
154        return None;
155    }
156    let args_raw = &rest[1..close_at];
157    match head_parsed {
158        Head::Bare(name) => {
159            let start = base + trimmed.find(name).unwrap_or(0);
160            Some(PlaceholderCall {
161                module: None,
162                name,
163                name_span: start..start + name.len(),
164                args_raw,
165            })
166        }
167        Head::Qualified { name, start } => {
168            let abs = base + start;
169            Some(PlaceholderCall {
170                module: Some(&head[..head.find("::").expect("split found ::")]),
171                name,
172                name_span: abs..abs + name.len(),
173                args_raw,
174            })
175        }
176    }
177}
178
179/// Split call args on top-level commas, keeping quoted strings and
180/// `{...}` / `[...]` / `(...)` literals intact. Both quote styles
181/// shield commas (with backslash escapes); depth applies to all
182/// three bracket shapes so nested literals never split.
183pub fn split_placeholder_args(src: &str) -> Vec<String> {
184    let mut out = Vec::new();
185    let mut current = String::new();
186    let mut quote: u8 = 0;
187    let mut escaped = false;
188    let mut depth: usize = 0;
189    for c in src.chars() {
190        if quote != 0 {
191            current.push(c);
192            if escaped {
193                escaped = false;
194            } else if c == '\\' {
195                escaped = true;
196            } else if c == quote as char {
197                quote = 0;
198            }
199            continue;
200        }
201        match c {
202            '"' | '\'' => {
203                quote = c as u8;
204                current.push(c);
205            }
206            '{' | '[' | '(' => {
207                depth += 1;
208                current.push(c);
209            }
210            '}' | ']' | ')' => {
211                depth = depth.saturating_sub(1);
212                current.push(c);
213            }
214            ',' if depth == 0 => {
215                out.push(current.trim().to_string());
216                current.clear();
217            }
218            _ => current.push(c),
219        }
220    }
221    let last = current.trim();
222    if !(out.is_empty() && last.is_empty()) {
223        out.push(last.to_string());
224    }
225    out
226}
227/// Allocation-free segment iterator over template text. See the module
228/// docs for the exact rules; the unit tests below pin every escape
229/// and boundary shape.
230#[derive(Debug, Clone)]
231pub struct TemplateSegments<'a> {
232    text: &'a str,
233    pos: usize,
234    pending: Option<(usize, &'a str, &'a str)>,
235}
236
237impl<'a> TemplateSegments<'a> {
238    /// Scan `text` front to back.
239    pub fn new(text: &'a str) -> Self {
240        Self {
241            text,
242            pos: 0,
243            pending: None,
244        }
245    }
246}
247
248impl<'a> Iterator for TemplateSegments<'a> {
249    type Item = TemplateSegment<'a>;
250
251    fn next(&mut self) -> Option<Self::Item> {
252        if let Some((end, key, raw)) = self.pending.take() {
253            self.pos = end;
254            return Some(TemplateSegment::Placeholder { key, raw });
255        }
256        // Copy out: every slice below then ties to `'a`, never to the
257        // `&mut self` borrow, so staging `pending` never conflicts.
258        let text: &'a str = self.text;
259        let bytes = text.as_bytes();
260        let len = bytes.len();
261        if self.pos >= len {
262            return None;
263        }
264        let start = self.pos;
265        let mut i = start;
266        while i < len {
267            if bytes[i] == b'\\' {
268                // `\\` consumes both (the opener after it stays live);
269                // `\{{` consumes all three as literal text; anything
270                // else consumes only the backslash and reprocesses.
271                if i + 2 < len && bytes[i + 1] == b'{' && bytes[i + 2] == b'{' {
272                    i += 3;
273                } else if i + 1 < len && bytes[i + 1] == b'\\' {
274                    i += 2;
275                } else {
276                    i += 1;
277                }
278                continue;
279            }
280            if bytes[i] == b'{' && i + 1 < len && bytes[i + 1] == b'{' {
281                let mut j = i + 2;
282                while j + 1 < len && !(bytes[j] == b'}' && bytes[j + 1] == b'}') {
283                    j += 1;
284                }
285                if j + 1 >= len {
286                    break;
287                }
288                let key = text[i + 2..j].trim();
289                let raw = &text[i..j + 2];
290                if i > start {
291                    self.pending = Some((j + 2, key, raw));
292                    return Some(TemplateSegment::Text(&text[start..i]));
293                }
294                self.pos = j + 2;
295                return Some(TemplateSegment::Placeholder { key, raw });
296            }
297            i += 1;
298        }
299        self.pos = len;
300        Some(TemplateSegment::Text(&text[start..]))
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use super::{TemplateSegment, TemplateSegments};
307
308    fn segments(text: &str) -> Vec<TemplateSegment<'_>> {
309        TemplateSegments::new(text).collect()
310    }
311
312    #[test]
313    fn plain_text_is_one_segment() {
314        assert_eq!(segments("hello"), vec![TemplateSegment::Text("hello")],);
315    }
316
317    #[test]
318    fn placeholder_splits_around_text() {
319        assert_eq!(
320            segments("a{{ $x }}b"),
321            vec![
322                TemplateSegment::Text("a"),
323                TemplateSegment::Placeholder {
324                    key: "$x",
325                    raw: "{{ $x }}"
326                },
327                TemplateSegment::Text("b"),
328            ],
329        );
330    }
331
332    #[test]
333    fn keys_trim() {
334        assert_eq!(
335            segments("{{  env:A  }}"),
336            vec![TemplateSegment::Placeholder {
337                key: "env:A",
338                raw: "{{  env:A  }}"
339            }],
340        );
341    }
342
343    #[test]
344    fn escaped_opener_stays_text() {
345        assert_eq!(
346            segments("\\{{ env:A }}"),
347            vec![TemplateSegment::Text("\\{{ env:A }}")],
348        );
349    }
350
351    #[test]
352    fn escaped_backslash_keeps_opener_live() {
353        assert_eq!(
354            segments("\\\\{{ env:A }}"),
355            vec![
356                TemplateSegment::Text("\\\\"),
357                TemplateSegment::Placeholder {
358                    key: "env:A",
359                    raw: "{{ env:A }}"
360                },
361            ],
362        );
363    }
364
365    #[test]
366    fn escaped_opener_before_braces_stays_text() {
367        // `\{{{x}}`: the `\{{` consumes as literal, exactly like the
368        // historical expansion loop; no placeholder opens inside it.
369        assert_eq!(
370            segments("\\{{{x}}"),
371            vec![TemplateSegment::Text("\\{{{x}}")],
372        );
373    }
374
375    #[test]
376    fn unclosed_opener_stays_text() {
377        assert_eq!(
378            segments("hi {{ unclosed"),
379            vec![TemplateSegment::Text("hi {{ unclosed")],
380        );
381    }
382
383    #[test]
384    fn empty_and_blank_keys_are_placeholders() {
385        assert_eq!(
386            segments("{{}}"),
387            vec![TemplateSegment::Placeholder {
388                key: "",
389                raw: "{{}}"
390            }],
391        );
392        assert_eq!(
393            segments("{{ }}"),
394            vec![TemplateSegment::Placeholder {
395                key: "",
396                raw: "{{ }}"
397            }],
398        );
399    }
400
401    #[test]
402    fn adjacent_placeholders_emit_no_empty_text() {
403        assert_eq!(
404            segments("{{a}}{{b}}"),
405            vec![
406                TemplateSegment::Placeholder {
407                    key: "a",
408                    raw: "{{a}}"
409                },
410                TemplateSegment::Placeholder {
411                    key: "b",
412                    raw: "{{b}}"
413                },
414            ],
415        );
416    }
417
418    #[test]
419    fn call_shapes_parse_once() {
420        use super::{parse_placeholder_call, split_placeholder_args};
421        // Bare head: module-less, name span covers the head.
422        let call = parse_placeholder_call("LEN($x)").expect("bare parses");
423        assert_eq!(call.module, None);
424        assert_eq!(call.name, "LEN");
425        assert_eq!(&"LEN($x)"[call.name_span.clone()], "LEN");
426        assert_eq!(call.args_raw, "$x");
427        // Qualified head with gap before parens.
428        let call = parse_placeholder_call("STD::LEN ($x)").expect("qualified parses");
429        assert_eq!(call.module, Some("STD"));
430        assert_eq!(call.name, "LEN");
431        assert_eq!(call.args_raw, "$x");
432        // Quoted parens never affect depth, both styles.
433        assert!(parse_placeholder_call("LEN(\"a(b\")").is_some());
434        assert!(parse_placeholder_call("LEN('a(b')").is_some());
435        assert!(parse_placeholder_call("STD::LEN('a(b')").is_some());
436        // Compounds and trailing garbage are not single calls.
437        assert!(parse_placeholder_call("LEN($a) + LEN($b)").is_none());
438        assert!(parse_placeholder_call("LEN($x))").is_none());
439        // Lowercase bare heads keep non-call handling.
440        assert!(parse_placeholder_call("foo($x)").is_none());
441        // Empty and missing parens miss.
442        assert!(parse_placeholder_call("$x").is_none());
443        assert!(parse_placeholder_call("").is_none());
444        // Args split shields commas in both quote styles.
445        assert_eq!(
446            split_placeholder_args("$a, \"b,c\", 'd,e'"),
447            vec!["$a".to_string(), "\"b,c\"".to_string(), "'d,e'".to_string()],
448        );
449    }
450}