1use oxdock_diagnostics::DiagnosticResult;
18
19use crate::constants::{KEY_PATH_SEPARATOR, VAR_SIGIL_CHAR};
20use crate::diagnostics as template_diag;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum TemplateSegment<'a> {
28 Text(&'a str),
31 Placeholder { key: &'a str, raw: &'a str },
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct PlaceholderCall<'a> {
49 pub module: Option<&'a str>,
51 pub name: &'a str,
53 pub name_span: std::ops::Range<usize>,
55 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
71pub 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub enum AtomKind {
185 Open,
187 Close,
189 Sep(char),
191 Text,
196}
197
198#[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
206pub 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 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 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
328fn 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
359pub fn split_placeholder_args(src: &str) -> Vec<String> {
362 split_on(src, ',')
363}
364
365pub 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
377pub 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
407fn 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
429fn 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
452fn 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
477pub 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#[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#[derive(Debug, Clone, PartialEq, Eq)]
536pub enum PlaceholderKey<'a> {
537 Empty,
539 Dollar(&'a str),
545 DollarQualified {
551 alias: &'a str,
552 name: &'a str,
553 keys: Vec<String>,
554 },
555 Env(&'a str),
557 ScriptEnv(&'a str),
559 Call(PlaceholderCall<'a>),
562 ConstRef { alias: &'a str, name: &'a str },
565 KeyPath { base: &'a str, keys: Vec<String> },
569 Var(&'a str),
572 Invalid(&'a str),
578 Bare(&'a str),
581}
582
583pub fn is_bare_ident(src: &str) -> bool {
588 !src.is_empty() && src.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
589}
590
591pub 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
605pub 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
628pub 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
639pub 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
653pub 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
681pub fn is_malformed_dollar_qualified(rest: &str) -> bool {
690 rest.contains(crate::constants::MODULE_SEPARATOR) && parse_dollar_qualified(rest).is_none()
691}
692
693pub 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
715pub 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 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
759pub 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
768pub 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
803pub 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
813pub const MAX_TEMPLATE_ARG_DEPTH: usize = 16;
817
818pub enum TemplateArg<'a> {
822 Dollar(&'a str),
827 DollarQualified {
832 alias: &'a str,
833 name: &'a str,
834 keys: Vec<String>,
835 },
836 Str(&'a str),
839 Map(&'a str),
841 List(&'a str),
843 Scalar(&'a str),
846 ConstRef { alias: &'a str, name: &'a str },
849 KeyPath { base: &'a str, keys: Vec<String> },
852 Var(&'a str),
855 Invalid(&'a str),
857}
858
859pub 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 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
903pub enum ScalarLit {
907 Bool(bool),
908 Int(i64),
909 Float(f64),
910}
911
912pub 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
926fn 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
955pub 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
977pub 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
994fn 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#[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 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 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 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 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 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 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 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 assert!(parse_placeholder_call("LEN($a) + LEN($b)").is_none());
1251 assert!(parse_placeholder_call("LEN($x))").is_none());
1252 assert!(parse_placeholder_call("foo($x)").is_none());
1254 assert!(parse_placeholder_call("$x").is_none());
1256 assert!(parse_placeholder_call("").is_none());
1257 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 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 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 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 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 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 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 assert_eq!(
1400 split_map_entry("\"k\": {inner: $LIB::X}"),
1401 Some(("\"k\"".to_string(), "{inner: $LIB::X}".to_string()))
1402 );
1403 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 assert_eq!(
1415 split_placeholder_args("\"\"\"a, b (c) [d]\"\"\", $x"),
1416 vec!["\"\"\"a, b (c) [d]\"\"\"".to_string(), "$x".to_string()],
1417 );
1418 assert_eq!(
1420 split_placeholder_args("\"\"\"line one\nline two\"\"\""),
1421 vec!["\"\"\"line one\nline two\"\"\"".to_string()],
1422 );
1423 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 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 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}