1use std::fmt::Write;
4
5use xur_runtime::{Context, RunResult, RuntimeError, Value};
6
7pub fn format(cx: &dyn Context, template: &str, args: &[Value]) -> RunResult<String> {
11 let mut out = String::with_capacity(template.len());
12 let mut args = args.iter();
13 let mut chars = template.chars().peekable();
14 while let Some(c) = chars.next() {
15 match (c, chars.peek()) {
16 ('{', Some('{')) | ('}', Some('}')) => {
17 chars.next();
18 out.push(c);
19 }
20 ('{', Some('}')) => {
21 chars.next();
22 let arg = args.next().ok_or_else(|| {
23 RuntimeError::new("the format string has more `{}` than arguments")
24 })?;
25 out.push_str(&cx.display(arg));
26 }
27 ('{', Some(':')) => {
28 chars.next(); let spec = chars
30 .next()
31 .ok_or_else(|| RuntimeError::new("unexpected end of format spec after `{:`"))?;
32 let close = chars.next().ok_or_else(|| {
33 RuntimeError::new("unexpected end of format spec, expected `}`")
34 })?;
35 if close != '}' {
36 return Err(RuntimeError::new(format!(
37 "expected `}}` after format spec `:{spec}`, found `{close}`"
38 )));
39 }
40 let arg = args.next().ok_or_else(|| {
41 RuntimeError::new("the format string has more format specifiers than arguments")
42 })?;
43 match spec {
44 'x' => match arg {
45 Value::Int(n) => write!(out, "{:x}", n.to_i128()).unwrap(),
46 _ => {
47 return Err(RuntimeError::new(
48 "format spec `:x` requires an integer argument",
49 ));
50 }
51 },
52 'X' => match arg {
53 Value::Int(n) => write!(out, "{:X}", n.to_i128()).unwrap(),
54 _ => {
55 return Err(RuntimeError::new(
56 "format spec `:X` requires an integer argument",
57 ));
58 }
59 },
60 _ => {
61 return Err(RuntimeError::new(format!(
62 "unknown format spec `:{spec}`; supported: `:x`, `:X`"
63 )));
64 }
65 }
66 }
67 ('{' | '}', _) => {
68 return Err(RuntimeError::new(format!(
69 "unmatched `{c}` in format string; write `{c}{c}` for a literal brace"
70 )));
71 }
72 _ => out.push(c),
73 }
74 }
75 if args.next().is_some() {
76 return Err(RuntimeError::new(
77 "more arguments than `{}` in the format string",
78 ));
79 }
80 Ok(out)
81}
82
83#[cfg(test)]
84mod tests {
85 use xur_runtime::Value;
86 use xur_runtime::testing::{TestCx, fn_id};
87
88 use crate::registry;
89
90 #[test]
91 fn format_errors() {
92 let registry = registry();
93 let mut cx = TestCx::new(®istry, crate::PRELUDE);
94 let print = fn_id(®istry, "std::io::print");
95 let error = |cx: &mut TestCx<'_>, args: &[Value]| cx.call(print, args).unwrap_err().message;
96 assert_eq!(
97 error(&mut cx, &[Value::str("x"), Value::int(1)]),
98 "more arguments than `{}` in the format string"
99 );
100 }
101
102 #[test]
103 fn hex_format() {
104 let registry = registry();
105 let cx = TestCx::new(®istry, crate::PRELUDE);
106 let result = super::format(&cx, "addr: {:x}", &[Value::int(0xDEAD)]).unwrap();
107 assert_eq!(result, "addr: dead");
108 let result = super::format(&cx, "ADDR: {:X}", &[Value::int(0xBEEF)]).unwrap();
109 assert_eq!(result, "ADDR: BEEF");
110 let result =
111 super::format(&cx, "{} at {:x}", &[Value::str("foo"), Value::int(255)]).unwrap();
112 assert_eq!(result, "foo at ff");
113 }
114
115 #[test]
116 fn hex_format_requires_int() {
117 let registry = registry();
118 let cx = TestCx::new(®istry, crate::PRELUDE);
119 let err = super::format(&cx, "{:x}", &[Value::str("nope")]).unwrap_err();
120 assert!(err.message.contains("integer"), "{}", err.message);
121 }
122
123 #[test]
124 fn no_args_passes_through_literal() {
125 let registry = registry();
126 let mut cx = TestCx::new(®istry, crate::PRELUDE);
127 let print = fn_id(®istry, "std::io::print");
128 cx.call(print, &[Value::str("{}")]).unwrap();
130 cx.call(print, &[Value::str("{")]).unwrap();
131 cx.call(print, &[Value::str("hello {world}")]).unwrap();
132 }
133}