1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum TemplateSegment<'a> {
23 Text(&'a str),
26 Placeholder { key: &'a str, raw: &'a str },
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct PlaceholderCall<'a> {
44 pub module: Option<&'a str>,
46 pub name: &'a str,
48 pub name_span: std::ops::Range<usize>,
50 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
66pub 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 =
92 if let Some((left, right)) = head.split_once(crate::constants::MODULE_SEPARATOR) {
93 if left.is_empty() || !left.chars().all(is_module_char) {
94 return None;
95 }
96 let name = right.trim();
97 if name.is_empty() || !name.chars().all(is_module_char) {
98 return None;
99 }
100 let colon = head
106 .find(crate::constants::MODULE_SEPARATOR)
107 .expect("split found ::");
108 let leading = head[colon + 2..].len() - head[colon + 2..].trim_start().len();
109 Head::Qualified {
110 name,
111 start: colon + 2 + leading,
112 }
113 } else {
114 if !is_bare_head(head) {
115 return None;
116 }
117 Head::Bare(head)
118 };
119 let mut depth: usize = 0;
123 let mut close_at: Option<usize> = None;
124 for atom in scan_atoms(rest) {
125 match atom.kind {
126 AtomKind::Open if atom.text == "(" => depth += 1,
130 AtomKind::Close if atom.text == ")" => {
131 if depth == 0 {
132 return None;
133 }
134 depth -= 1;
135 if depth == 0 {
136 close_at = Some(atom.start);
137 break;
138 }
139 }
140 _ => {}
141 }
142 }
143 let close_at = close_at?;
144 if !rest[close_at + 1..].trim().is_empty() {
145 return None;
146 }
147 let args_raw = &rest[1..close_at];
148 match head_parsed {
149 Head::Bare(name) => {
150 let start = base + trimmed.find(name).unwrap_or(0);
151 Some(PlaceholderCall {
152 module: None,
153 name,
154 name_span: start..start + name.len(),
155 args_raw,
156 })
157 }
158 Head::Qualified { name, start } => {
159 let abs = base + start;
160 Some(PlaceholderCall {
161 module: Some(
162 &head[..head
163 .find(crate::constants::MODULE_SEPARATOR)
164 .expect("split found ::")],
165 ),
166 name,
167 name_span: abs..abs + name.len(),
168 args_raw,
169 })
170 }
171 }
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub enum AtomKind {
180 Open,
182 Close,
184 Sep(char),
186 Text,
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub struct Atom<'a> {
196 pub kind: AtomKind,
197 pub text: &'a str,
198 pub start: usize,
199}
200
201pub fn scan_atoms(src: &str) -> Vec<Atom<'_>> {
205 let bytes = src.as_bytes();
206 let mut out = Vec::new();
207 let mut i = 0;
208 let mut text_from: Option<usize> = None;
209 while i < bytes.len() {
210 let b = bytes[i];
211 if b == b'"' && bytes.get(i + 1) == Some(&b'"') && bytes.get(i + 2) == Some(&b'"') {
213 if let Some(s) = text_from.take()
214 && s != i
215 {
216 out.push(Atom {
217 kind: AtomKind::Text,
218 text: &src[s..i],
219 start: s,
220 });
221 }
222 let start = i;
223 i += 3;
224 let mut escaped = false;
225 while i < bytes.len() {
226 if escaped {
227 escaped = false;
228 i += 1;
229 } else if bytes[i] == b'\\' {
230 escaped = true;
231 i += 1;
232 } else if bytes[i] == b'"'
233 && bytes.get(i + 1) == Some(&b'"')
234 && bytes.get(i + 2) == Some(&b'"')
235 {
236 i += 3;
237 break;
238 } else {
239 i += 1;
240 }
241 }
242 out.push(Atom {
243 kind: AtomKind::Text,
244 text: &src[start..i],
245 start,
246 });
247 continue;
248 }
249 if b == b'"' || b == b'\'' {
251 if let Some(s) = text_from.take()
252 && s != i
253 {
254 out.push(Atom {
255 kind: AtomKind::Text,
256 text: &src[s..i],
257 start: s,
258 });
259 }
260 let q = b;
261 let start = i;
262 i += 1;
263 let mut escaped = false;
264 while i < bytes.len() {
265 if escaped {
266 escaped = false;
267 } else if bytes[i] == b'\\' {
268 escaped = true;
269 } else if bytes[i] == q {
270 i += 1;
271 break;
272 }
273 i += 1;
274 }
275 out.push(Atom {
276 kind: AtomKind::Text,
277 text: &src[start..i],
278 start,
279 });
280 continue;
281 }
282 let kind = match b {
283 b'(' | b'[' | b'{' => Some(AtomKind::Open),
284 b')' | b']' | b'}' => Some(AtomKind::Close),
285 b',' | b':' => Some(AtomKind::Sep(b as char)),
286 _ => None,
287 };
288 if let Some(kind) = kind {
289 if let Some(s) = text_from.take()
290 && s != i
291 {
292 out.push(Atom {
293 kind: AtomKind::Text,
294 text: &src[s..i],
295 start: s,
296 });
297 }
298 out.push(Atom {
299 kind,
300 text: &src[i..i + 1],
301 start: i,
302 });
303 i += 1;
304 } else {
305 if text_from.is_none() {
306 text_from = Some(i);
307 }
308 i += 1;
309 }
310 }
311 if let Some(s) = text_from.take()
312 && s < bytes.len()
313 {
314 out.push(Atom {
315 kind: AtomKind::Text,
316 text: &src[s..],
317 start: s,
318 });
319 }
320 out
321}
322
323fn split_on(src: &str, sep: char) -> Vec<String> {
327 let mut out = Vec::new();
328 let mut current = String::new();
329 let mut depth: usize = 0;
330 for atom in scan_atoms(src) {
331 match atom.kind {
332 AtomKind::Open => {
333 depth += 1;
334 current.push_str(atom.text);
335 }
336 AtomKind::Close => {
337 depth = depth.saturating_sub(1);
338 current.push_str(atom.text);
339 }
340 AtomKind::Sep(c) if c == sep && depth == 0 => {
341 out.push(current.trim().to_string());
342 current.clear();
343 }
344 _ => current.push_str(atom.text),
345 }
346 }
347 let last = current.trim();
348 if !(out.is_empty() && last.is_empty()) {
349 out.push(last.to_string());
350 }
351 out
352}
353
354pub fn split_placeholder_args(src: &str) -> Vec<String> {
357 split_on(src, ',')
358}
359
360pub fn split_top_level(src: &str, sep: char) -> Vec<String> {
365 assert!(
366 matches!(sep, ',' | ':'),
367 "scan_atoms only tokenizes ',' and ':' separators"
368 );
369 split_on(src, sep)
370}
371
372pub fn parse_string_literal(src: &str) -> Option<anyhow::Result<String>> {
384 let atoms = scan_atoms(src);
385 let [atom] = atoms.as_slice() else {
386 return None;
387 };
388 if atom.kind != AtomKind::Text || atom.start != 0 || atom.text != src {
389 return None;
390 }
391 if src.starts_with("\"\"\"") {
392 return Some(parse_block_literal(src));
393 }
394 for quote in ['"', '\''] {
395 if src.starts_with(quote) {
396 return Some(parse_quoted_literal(src, quote));
397 }
398 }
399 None
400}
401
402fn parse_quoted_literal(src: &str, quote: char) -> anyhow::Result<String> {
406 let bytes = src.as_bytes();
407 let mut i = 1;
408 while i < bytes.len() {
409 if bytes[i] == b'\\' {
410 i += 2;
411 continue;
412 }
413 if bytes[i] == quote as u8 {
414 if i + 1 != src.len() {
415 anyhow::bail!("unexpected text after string literal: {src:?}");
416 }
417 return unescape_literal(&src[1..i], quote);
418 }
419 i += 1;
420 }
421 anyhow::bail!("unterminated string literal: {src:?}")
422}
423
424fn parse_block_literal(src: &str) -> anyhow::Result<String> {
429 let bytes = src.as_bytes();
430 let mut i = 3;
431 while i < bytes.len() {
432 if bytes[i] == b'\\' {
433 i += 2;
434 continue;
435 }
436 if bytes[i] == b'"' && bytes.get(i + 1) == Some(&b'"') && bytes.get(i + 2) == Some(&b'"') {
437 if i + 3 != src.len() {
438 anyhow::bail!("unexpected text after block string literal: {src:?}");
439 }
440 return Ok(crate::command::lower_block_string(src));
441 }
442 i += 1;
443 }
444 anyhow::bail!("unterminated block string literal: {src:?}")
445}
446
447fn unescape_literal(src: &str, quote: char) -> anyhow::Result<String> {
450 let mut out = String::with_capacity(src.len());
451 let mut chars = src.chars();
452 while let Some(c) = chars.next() {
453 if c != '\\' {
454 out.push(c);
455 continue;
456 }
457 match chars.next() {
458 Some('\\') => out.push('\\'),
459 Some(q) if q == quote => out.push(quote),
460 Some(other) => {
461 out.push('\\');
462 out.push(other);
463 }
464 None => anyhow::bail!("unterminated escape in placeholder string literal"),
465 }
466 }
467 Ok(out)
468}
469
470pub fn strip_wrapped_delimiters(src: &str, open: char, close: char) -> Option<&str> {
475 let atoms = scan_atoms(src);
476 let first = atoms.first()?;
477 if first.kind != AtomKind::Open || first.start != 0 || first.text.chars().count() != 1 {
478 return None;
479 }
480 if !first.text.starts_with(open) {
481 return None;
482 }
483 let mut depth = 0usize;
484 for atom in &atoms {
485 match atom.kind {
486 AtomKind::Open => depth += 1,
487 AtomKind::Close => {
488 depth = depth.saturating_sub(1);
489 if depth == 0 {
490 if atom.start + atom.text.len() != src.len() {
491 return None;
492 }
493 if !atom.text.starts_with(close) {
494 return None;
495 }
496 return Some(&src[open.len_utf8()..src.len() - close.len_utf8()]);
497 }
498 }
499 AtomKind::Text | AtomKind::Sep(_) => {}
500 }
501 }
502 None
503}
504#[derive(Debug, Clone, PartialEq, Eq)]
511pub enum TemplateVar {
512 Path(Vec<String>),
513 Bare(String),
514 ConstRef { alias: String, name: String },
515 KeyPath { base: String, keys: Vec<String> },
516 Var(String),
517}
518
519#[derive(Debug, Clone, PartialEq, Eq)]
529pub enum PlaceholderKey<'a> {
530 Empty,
532 Dollar(&'a str),
536 DollarQualified {
542 alias: &'a str,
543 name: &'a str,
544 keys: Vec<String>,
545 },
546 Env(&'a str),
548 ScriptEnv(&'a str),
550 Call(PlaceholderCall<'a>),
553 ConstRef { alias: &'a str, name: &'a str },
556 KeyPath { base: &'a str, keys: Vec<String> },
560 Var(&'a str),
563 Bare(&'a str),
566}
567
568pub fn is_bare_ident(src: &str) -> bool {
573 !src.is_empty() && src.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
574}
575
576pub fn parse_qualified_const(src: &str) -> Option<(&str, &str)> {
580 let (alias, rest) = crate::constants::split_qualified(src)?;
581 if !is_bare_ident(alias) || !is_bare_ident(rest) {
582 return None;
583 }
584 if rest.contains(['.', ',', ' ', '\t']) {
585 return None;
586 }
587 Some((alias, rest))
588}
589
590pub fn parse_bare_key_path(src: &str) -> Option<(&str, Vec<String>)> {
596 let (base, tail) = src.split_once('.')?;
597 if !is_bare_ident(base) {
598 return None;
599 }
600 if tail.is_empty() {
601 return None;
602 }
603 let segs: Vec<String> = tail.split('.').map(|s| s.to_string()).collect();
604 if segs.iter().any(|s| !is_bare_ident(s)) {
605 return None;
606 }
607 Some((base, segs))
608}
609
610pub fn bare_sigil_error(src: &str) -> String {
615 format!(
616 "bare `{src}` never reads a binding here; use `{}{src}`",
617 crate::constants::VAR_SIGIL
618 )
619}
620
621pub fn qualified_keypath_error() -> String {
625 "key paths on $ALIAS::NAME are not supported; copy to a local with LET or CONST first"
626 .to_string()
627}
628
629pub fn parse_dollar_qualified(rest: &str) -> Option<(&str, &str, Vec<String>)> {
634 let (head, tail) = match rest.split_once('.') {
635 Some((h, t)) => (h, Some(t)),
636 None => (rest, None),
637 };
638 let (alias, name) = crate::constants::split_qualified(head)?;
639 if !is_bare_ident(alias) || !is_bare_ident(name) {
640 return None;
641 }
642 let keys = match tail {
643 Some(t) => t.split('.').map(|s| s.to_string()).collect::<Vec<_>>(),
644 None => Vec::new(),
645 };
646 Some((alias, name, keys))
647}
648
649pub fn classify_placeholder_key(key: &str) -> PlaceholderKey<'_> {
653 if key.is_empty() {
654 return PlaceholderKey::Empty;
655 }
656 if let Some(rest) = key.strip_prefix('$') {
657 if let Some((alias, name, keys)) = parse_dollar_qualified(rest) {
658 return PlaceholderKey::DollarQualified { alias, name, keys };
659 }
660 return PlaceholderKey::Dollar(rest);
661 }
662 if let Some(rest) = key.strip_prefix("env:") {
663 return PlaceholderKey::Env(rest);
664 }
665 if let Some(rest) = key.strip_prefix("script_env:") {
666 return PlaceholderKey::ScriptEnv(rest);
667 }
668 if let Some(call) = parse_placeholder_call(key) {
669 return PlaceholderKey::Call(call);
670 }
671 if let Some((alias, name)) = parse_qualified_const(key) {
672 return PlaceholderKey::ConstRef { alias, name };
673 }
674 if let Some((base, keys)) = parse_bare_key_path(key) {
675 return PlaceholderKey::KeyPath { base, keys };
676 }
677 if is_bare_ident(key) {
678 return PlaceholderKey::Var(key);
679 }
680 PlaceholderKey::Bare(key)
681}
682
683pub fn split_var_path(rest: &str) -> Vec<String> {
687 rest.split('.')
688 .map(|part| part.trim().to_string())
689 .collect()
690}
691
692pub fn placeholder_vars(key: &str) -> Vec<TemplateVar> {
701 match classify_placeholder_key(key.trim()) {
702 PlaceholderKey::Empty => Vec::new(),
703 PlaceholderKey::Dollar(rest) => parse_dollar_path(rest).into_iter().collect(),
704 PlaceholderKey::DollarQualified { .. } => Vec::new(),
705 PlaceholderKey::Env(_) | PlaceholderKey::ScriptEnv(_) => Vec::new(),
706 PlaceholderKey::Call(call) => {
707 let mut out = Vec::new();
708 for arg in split_placeholder_args(call.args_raw) {
709 collect_call_arg_vars(&arg, &mut out);
710 }
711 out
712 }
713 PlaceholderKey::ConstRef { alias, name } => vec![TemplateVar::ConstRef {
714 alias: alias.to_string(),
715 name: name.to_string(),
716 }],
717 PlaceholderKey::KeyPath { base, keys } => vec![TemplateVar::KeyPath {
718 base: base.to_string(),
719 keys,
720 }],
721 PlaceholderKey::Var(name) => vec![TemplateVar::Var(name.to_string())],
722 PlaceholderKey::Bare(key) => vec![TemplateVar::Bare(key.to_string())],
723 }
724}
725
726pub fn parse_var_path(rest: &str) -> Option<Vec<String>> {
729 let parts = split_var_path(rest);
730 if parts.iter().any(|part| part.is_empty()) {
731 return None;
732 }
733 Some(parts)
734}
735
736pub const MAX_TEMPLATE_ARG_DEPTH: usize = 16;
740
741pub enum TemplateArg<'a> {
745 Dollar(&'a str),
749 DollarQualified {
754 alias: &'a str,
755 name: &'a str,
756 keys: Vec<String>,
757 },
758 Str(&'a str),
761 Map(&'a str),
763 List(&'a str),
765 Scalar(&'a str),
768 ConstRef { alias: &'a str, name: &'a str },
771 KeyPath { base: &'a str, keys: Vec<String> },
774 Var(&'a str),
777 Invalid(&'a str),
779}
780
781pub fn classify_template_arg(src: &str) -> TemplateArg<'_> {
784 let src = src.trim();
785 if let Some(rest) = src.strip_prefix('$') {
786 if let Some((alias, name, keys)) = parse_dollar_qualified(rest) {
787 return TemplateArg::DollarQualified { alias, name, keys };
788 }
789 return TemplateArg::Dollar(rest);
790 }
791 if parse_string_literal(src).is_some() {
792 return TemplateArg::Str(src);
793 }
794 if let Some(inner) = strip_wrapped_delimiters(src, '{', '}') {
795 return TemplateArg::Map(inner);
796 }
797 if let Some(inner) = strip_wrapped_delimiters(src, '[', ']') {
798 return TemplateArg::List(inner);
799 }
800 if parse_scalar_literal(src).is_some() {
801 return TemplateArg::Scalar(src);
802 }
803 if let Some((alias, name)) = parse_qualified_const(src) {
804 return TemplateArg::ConstRef { alias, name };
805 }
806 if let Some((base, keys)) = parse_bare_key_path(src) {
807 return TemplateArg::KeyPath { base, keys };
808 }
809 if is_bare_ident(src) {
810 return TemplateArg::Var(src);
811 }
812 TemplateArg::Invalid(src)
813}
814
815pub enum ScalarLit {
819 Bool(bool),
820 Int(i64),
821 Float(f64),
822}
823
824pub fn parse_scalar_literal(src: &str) -> Option<ScalarLit> {
827 match src {
828 "true" => Some(ScalarLit::Bool(true)),
829 "false" => Some(ScalarLit::Bool(false)),
830 _ => src
831 .parse::<i64>()
832 .map(ScalarLit::Int)
833 .ok()
834 .or_else(|| src.parse::<f64>().map(ScalarLit::Float).ok()),
835 }
836}
837
838pub fn split_map_entry(entry: &str) -> Option<(String, String)> {
841 let mut parts = split_top_level(entry, ':');
842 if parts.len() != 2 {
843 return None;
844 }
845 let value = parts.pop().expect("split_map_entry checked len");
846 let key = parts.pop().expect("split_map_entry checked len");
847 Some((key, value))
848}
849
850pub fn parse_map_key(src: &str) -> anyhow::Result<String> {
854 if let Some(literal) = parse_string_literal(src) {
855 return literal.map_err(|err| anyhow::anyhow!("{err:#}"));
856 }
857 if !src.is_empty() && src.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
858 return Ok(src.to_string());
859 }
860 anyhow::bail!("invalid map literal key '{src}': use a bare name or any string spelling")
861}
862
863fn parse_dollar_path(rest: &str) -> Option<TemplateVar> {
864 parse_var_path(rest).map(TemplateVar::Path)
865}
866
867fn collect_call_arg_vars(src: &str, out: &mut Vec<TemplateVar>) {
872 match classify_template_arg(src) {
873 TemplateArg::Dollar(rest) => {
874 out.extend(parse_dollar_path(rest));
875 }
876 TemplateArg::Map(inner) => {
877 if inner.trim().is_empty() {
878 return;
879 }
880 for entry in split_top_level(inner, ',') {
881 if let Some((_, value)) = split_map_entry(&entry) {
882 collect_call_arg_vars(&value, out);
883 }
884 }
885 }
886 TemplateArg::List(inner) => {
887 if inner.trim().is_empty() {
888 return;
889 }
890 for item in split_top_level(inner, ',') {
891 collect_call_arg_vars(&item, out);
892 }
893 }
894 TemplateArg::ConstRef { alias, name } => {
895 out.push(TemplateVar::ConstRef {
896 alias: alias.to_string(),
897 name: name.to_string(),
898 });
899 }
900 TemplateArg::KeyPath { base, keys } => {
901 out.push(TemplateVar::KeyPath {
902 base: base.to_string(),
903 keys,
904 });
905 }
906 TemplateArg::Var(name) => {
907 out.push(TemplateVar::Var(name.to_string()));
908 }
909 TemplateArg::DollarQualified { .. } => {}
910 TemplateArg::Str(_) | TemplateArg::Scalar(_) | TemplateArg::Invalid(_) => {}
911 }
912}
913#[derive(Debug, Clone)]
917pub struct TemplateSegments<'a> {
918 text: &'a str,
919 pos: usize,
920 pending: Option<(usize, &'a str, &'a str)>,
921}
922
923impl<'a> TemplateSegments<'a> {
924 pub fn new(text: &'a str) -> Self {
926 Self {
927 text,
928 pos: 0,
929 pending: None,
930 }
931 }
932}
933
934impl<'a> Iterator for TemplateSegments<'a> {
935 type Item = TemplateSegment<'a>;
936
937 fn next(&mut self) -> Option<Self::Item> {
938 if let Some((end, key, raw)) = self.pending.take() {
939 self.pos = end;
940 return Some(TemplateSegment::Placeholder { key, raw });
941 }
942 let text: &'a str = self.text;
945 let bytes = text.as_bytes();
946 let len = bytes.len();
947 if self.pos >= len {
948 return None;
949 }
950 let start = self.pos;
951 let mut i = start;
952 while i < len {
953 if bytes[i] == b'\\' {
954 if i + 2 < len && bytes[i + 1] == b'{' && bytes[i + 2] == b'{' {
958 i += 3;
959 } else if i + 1 < len && bytes[i + 1] == b'\\' {
960 i += 2;
961 } else {
962 i += 1;
963 }
964 continue;
965 }
966 if bytes[i] == b'{' && i + 1 < len && bytes[i + 1] == b'{' {
967 let mut j = i + 2;
968 while j + 1 < len && !(bytes[j] == b'}' && bytes[j + 1] == b'}') {
969 j += 1;
970 }
971 if j + 1 >= len {
972 break;
973 }
974 let key = text[i + 2..j].trim();
975 let raw = &text[i..j + 2];
976 if i > start {
977 self.pending = Some((j + 2, key, raw));
978 return Some(TemplateSegment::Text(&text[start..i]));
979 }
980 self.pos = j + 2;
981 return Some(TemplateSegment::Placeholder { key, raw });
982 }
983 i += 1;
984 }
985 self.pos = len;
986 Some(TemplateSegment::Text(&text[start..]))
987 }
988}
989
990#[cfg(test)]
991mod tests {
992 use super::{TemplateSegment, TemplateSegments};
993
994 fn segments(text: &str) -> Vec<TemplateSegment<'_>> {
995 TemplateSegments::new(text).collect()
996 }
997
998 #[test]
999 fn plain_text_is_one_segment() {
1000 assert_eq!(segments("hello"), vec![TemplateSegment::Text("hello")],);
1001 }
1002
1003 #[test]
1004 fn placeholder_splits_around_text() {
1005 assert_eq!(
1006 segments("a{{ $x }}b"),
1007 vec![
1008 TemplateSegment::Text("a"),
1009 TemplateSegment::Placeholder {
1010 key: "$x",
1011 raw: "{{ $x }}"
1012 },
1013 TemplateSegment::Text("b"),
1014 ],
1015 );
1016 }
1017
1018 #[test]
1019 fn keys_trim() {
1020 assert_eq!(
1021 segments("{{ env:A }}"),
1022 vec![TemplateSegment::Placeholder {
1023 key: "env:A",
1024 raw: "{{ env:A }}"
1025 }],
1026 );
1027 }
1028
1029 #[test]
1030 fn escaped_opener_stays_text() {
1031 assert_eq!(
1032 segments("\\{{ env:A }}"),
1033 vec![TemplateSegment::Text("\\{{ env:A }}")],
1034 );
1035 }
1036
1037 #[test]
1038 fn escaped_backslash_keeps_opener_live() {
1039 assert_eq!(
1040 segments("\\\\{{ env:A }}"),
1041 vec![
1042 TemplateSegment::Text("\\\\"),
1043 TemplateSegment::Placeholder {
1044 key: "env:A",
1045 raw: "{{ env:A }}"
1046 },
1047 ],
1048 );
1049 }
1050
1051 #[test]
1052 fn escaped_opener_before_braces_stays_text() {
1053 assert_eq!(
1056 segments("\\{{{x}}"),
1057 vec![TemplateSegment::Text("\\{{{x}}")],
1058 );
1059 }
1060
1061 #[test]
1062 fn unclosed_opener_stays_text() {
1063 assert_eq!(
1064 segments("hi {{ unclosed"),
1065 vec![TemplateSegment::Text("hi {{ unclosed")],
1066 );
1067 }
1068
1069 #[test]
1070 fn empty_and_blank_keys_are_placeholders() {
1071 assert_eq!(
1072 segments("{{}}"),
1073 vec![TemplateSegment::Placeholder {
1074 key: "",
1075 raw: "{{}}"
1076 }],
1077 );
1078 assert_eq!(
1079 segments("{{ }}"),
1080 vec![TemplateSegment::Placeholder {
1081 key: "",
1082 raw: "{{ }}"
1083 }],
1084 );
1085 }
1086
1087 #[test]
1088 fn adjacent_placeholders_emit_no_empty_text() {
1089 assert_eq!(
1090 segments("{{a}}{{b}}"),
1091 vec![
1092 TemplateSegment::Placeholder {
1093 key: "a",
1094 raw: "{{a}}"
1095 },
1096 TemplateSegment::Placeholder {
1097 key: "b",
1098 raw: "{{b}}"
1099 },
1100 ],
1101 );
1102 }
1103
1104 #[test]
1105 fn call_shapes_parse_once() {
1106 use super::{parse_placeholder_call, split_placeholder_args};
1107 let call = parse_placeholder_call("LEN($x)").expect("bare parses");
1109 assert_eq!(call.module, None);
1110 assert_eq!(call.name, "LEN");
1111 assert_eq!(&"LEN($x)"[call.name_span.clone()], "LEN");
1112 assert_eq!(call.args_raw, "$x");
1113 let call = parse_placeholder_call("STD::LEN ($x)").expect("qualified parses");
1115 assert_eq!(call.module, Some("STD"));
1116 assert_eq!(call.name, "LEN");
1117 assert_eq!(call.args_raw, "$x");
1118 assert!(parse_placeholder_call("LEN(\"a(b\")").is_some());
1120 assert!(parse_placeholder_call("LEN('a(b')").is_some());
1121 assert!(parse_placeholder_call("STD::LEN('a(b')").is_some());
1122 assert!(parse_placeholder_call("LEN($a) + LEN($b)").is_none());
1124 assert!(parse_placeholder_call("LEN($x))").is_none());
1125 assert!(parse_placeholder_call("foo($x)").is_none());
1127 assert!(parse_placeholder_call("$x").is_none());
1129 assert!(parse_placeholder_call("").is_none());
1130 assert_eq!(
1132 split_placeholder_args("$a, \"b,c\", 'd,e'"),
1133 vec!["$a".to_string(), "\"b,c\"".to_string(), "'d,e'".to_string()],
1134 );
1135 }
1136
1137 #[test]
1138 fn placeholder_vars_cover_keys_calls_and_bad_paths() {
1139 use super::{TemplateVar, placeholder_vars};
1140 assert_eq!(
1141 placeholder_vars("$x"),
1142 vec![TemplateVar::Path(vec!["x".to_string()])],
1143 );
1144 assert_eq!(
1145 placeholder_vars(" $a.b.c "),
1146 vec![TemplateVar::Path(vec![
1147 "a".to_string(),
1148 "b".to_string(),
1149 "c".to_string(),
1150 ])],
1151 );
1152 assert_eq!(
1153 placeholder_vars("key"),
1154 vec![TemplateVar::Var("key".to_string())],
1155 );
1156 assert!(placeholder_vars("env:FOO").is_empty());
1157 assert!(placeholder_vars("script_env:BAR").is_empty());
1158 assert!(placeholder_vars("").is_empty());
1159 assert_eq!(
1160 placeholder_vars("M::F($a, {k: [$b, \"ignored\"]}, 'ignored', \"\"\"ignored\"\"\")"),
1161 vec![
1162 TemplateVar::Path(vec!["a".to_string()]),
1163 TemplateVar::Path(vec!["b".to_string()]),
1164 ],
1165 );
1166 assert!(placeholder_vars("$").is_empty());
1167 assert!(placeholder_vars("$a.").is_empty());
1168 assert!(placeholder_vars("$.a").is_empty());
1169 }
1170
1171 #[test]
1172 fn triple_quoted_blocks_split_and_parse_whole() {
1173 use super::{parse_placeholder_call, split_placeholder_args};
1174 assert_eq!(
1176 split_placeholder_args("\"\"\"a, b (c) [d]\"\"\", $x"),
1177 vec!["\"\"\"a, b (c) [d]\"\"\"".to_string(), "$x".to_string()],
1178 );
1179 assert_eq!(
1181 split_placeholder_args("\"\"\"line one\nline two\"\"\""),
1182 vec!["\"\"\"line one\nline two\"\"\"".to_string()],
1183 );
1184 let call = parse_placeholder_call("M::F(\"\"\"a(b\"\"\", $x)").expect("block parens parse");
1186 assert_eq!(call.name, "F");
1187 assert_eq!(call.args_raw, "\"\"\"a(b\"\"\", $x");
1188 }
1189
1190 #[test]
1191 fn string_literal_spellings_agree() {
1192 use super::parse_string_literal;
1193 let plain = parse_string_literal("\"Release installs\"")
1194 .expect("quoted")
1195 .expect("ok");
1196 let single = parse_string_literal("'Release installs'")
1197 .expect("single")
1198 .expect("ok");
1199 let block = parse_string_literal("\"\"\"Release installs\"\"\"")
1200 .expect("block")
1201 .expect("ok");
1202 assert_eq!(plain, "Release installs");
1203 assert_eq!(single, plain);
1204 assert_eq!(block, plain);
1205 }
1206
1207 #[test]
1208 fn string_literal_rejects_merged_and_unterminated() {
1209 use super::parse_string_literal;
1210 assert!(parse_string_literal("\"a\" \"b\"").is_none());
1213 assert!(parse_string_literal("\"a\" + \"b\"").is_none());
1214 assert!(parse_string_literal("\"\"\"a\"\"\" \"\"\"b\"\"\"").is_none());
1215 assert!(parse_string_literal("\"foo\\\"").expect("quoted").is_err());
1217 assert!(parse_string_literal("'foo\\'").expect("single").is_err());
1218 assert!(
1219 parse_string_literal("\"\"\"foo\\")
1220 .expect("block escape")
1221 .is_err()
1222 );
1223 assert!(
1224 parse_string_literal("\"\"\"foo\"\"")
1225 .expect("block short")
1226 .is_err()
1227 );
1228 assert!(parse_string_literal("\"foo").expect("open").is_err());
1229 assert!(
1230 parse_string_literal("\"\"\"foo")
1231 .expect("open block")
1232 .is_err()
1233 );
1234 }
1235
1236 #[test]
1237 fn wrapped_delimiters_see_through_block_strings() {
1238 use super::strip_wrapped_delimiters;
1239 assert_eq!(
1240 strip_wrapped_delimiters("[\"\"\"a]b\"\"\"]", '[', ']'),
1241 Some("\"\"\"a]b\"\"\"")
1242 );
1243 assert_eq!(
1244 strip_wrapped_delimiters("{k: \"\"\"a}b\"\"\"}", '{', '}'),
1245 Some("k: \"\"\"a}b\"\"\"")
1246 );
1247 assert_eq!(strip_wrapped_delimiters("[a, b]", '[', ']'), Some("a, b"));
1248 assert!(strip_wrapped_delimiters("[a], [b]", '[', ']').is_none());
1249 assert!(strip_wrapped_delimiters("[a", '[', ']').is_none());
1250 }
1251}