Skip to main content

cortiq_engine/
chat_template.rs

1//! The Jinja environment chat templates render in — transformers'
2//! semantics, not minijinja's defaults.
3//!
4//! `transformers` renders `chat_template` in a jinja2 sandbox with
5//! `trim_blocks` + `lstrip_blocks`, loop controls, and a handful of
6//! helpers it injects. The one that matters most is `tojson`: it is NOT
7//! jinja2's built-in (which HTML-escapes), but
8//!
9//! ```python
10//! def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False):
11//!     return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent,
12//!                       separators=separators, sort_keys=sort_keys)
13//! ```
14//!
15//! minijinja's own `tojson` differs on every axis a tool prompt touches:
16//! compact separators (`{"a":1}` against `{"a": 1}`), `<`/`>`/`&`/`'`
17//! escaped as `\u003c`…, no `ensure_ascii`/`separators`/`sort_keys`
18//! keywords (MiniCPM5's `tojson(ensure_ascii=False)` was a hard render
19//! error), and — without minijinja's `preserve_order` — map keys sorted.
20//! Every tool declaration therefore reached the model in a shape it was
21//! never trained on, or not at all. [`py_json_dumps`] reproduces
22//! `json.dumps` byte for byte, including float `repr` and the
23//! `ensure_ascii` surrogate-pair escapes.
24
25use minijinja::value::{Kwargs, Rest, Value, ValueKind};
26use minijinja::{Environment, Error, ErrorKind};
27
28/// Options of Python's `json.dumps` that transformers' `tojson` exposes.
29#[derive(Debug, Clone, Default)]
30pub struct DumpsOptions {
31    pub ensure_ascii: bool,
32    /// `None` = single line. `Some(s)` = newline + `s` per level (Python
33    /// turns an int `n` into `n` spaces; a string is used verbatim).
34    pub indent: Option<String>,
35    /// `(item_separator, key_separator)`; `None` = Python's default,
36    /// which depends on `indent`: `(", ", ": ")` single-line,
37    /// `(",", ": ")` indented.
38    pub separators: Option<(String, String)>,
39    pub sort_keys: bool,
40}
41
42/// Build the environment every chat template renders in.
43pub(crate) fn environment<'a>() -> Environment<'a> {
44    let mut env = Environment::new();
45    env.set_trim_blocks(true);
46    env.set_lstrip_blocks(true);
47    // HF templates use python string/dict methods (.startswith, .get …).
48    env.set_unknown_method_callback(minijinja_contrib::pycompat::unknown_method_callback);
49    env.add_filter("tojson", tojson_filter);
50    // `{{ x }}` and `x | string` print the way Python's `str()` does:
51    // `True`/`False`/`None`, float `repr`, and containers as Python
52    // literals (`['a', 1]`, `{'k': True}`). minijinja's own spelling
53    // (`true`, `none`, `["a", 1]`) reached tool-call HISTORY: MiniCPM5
54    // renders a non-string argument with `{{ param_value }}`, Qwen3.5 /
55    // Qwen3-coder with `args_value | string`, and a boolean argument came
56    // back as a token sequence the model never saw in training. Strings,
57    // integers and every other kind keep minijinja's default path.
58    env.set_formatter(|out, state, value| {
59        if needs_py_str(value) {
60            write!(out, "{}", py_str(value))
61                .map_err(|_| Error::new(ErrorKind::WriteFailure, "formatter write failed"))
62        } else {
63            minijinja::escape_formatter(out, state, value)
64        }
65    });
66    env.add_filter("string", |value: Value| -> Value {
67        if value.kind() == ValueKind::String {
68            value
69        } else if needs_py_str(&value) {
70            Value::from(py_str(&value))
71        } else {
72            Value::from(value.to_string())
73        }
74    });
75    // `raise_exception` is another transformers helper: templates call it
76    // to reject a malformed conversation. Unregistered, the render still
77    // fails, but with "unknown function" instead of the template's reason.
78    env.add_function("raise_exception", |msg: String| -> Result<Value, Error> {
79        Err(Error::new(ErrorKind::InvalidOperation, msg))
80    });
81    // `strftime_now(fmt)` is transformers' clock helper (Llama-3.x,
82    // Aion): templates stamp "Current date" with it when the caller sets
83    // no `current_date`. Unregistered, the render fails and the caller
84    // falls back to a ChatML approximation the model was not tuned on.
85    env.add_function("strftime_now", |fmt: String| -> Result<Value, Error> {
86        let secs = std::time::SystemTime::now()
87            .duration_since(std::time::UNIX_EPOCH)
88            .map(|d| d.as_secs() as i64)
89            .unwrap_or(0);
90        strftime_utc(&fmt, secs).map(Value::from)
91    });
92    // `visible_text` is a helper transformers injects into its template
93    // env (it flattens multimodal content to its text). Nanbeige's
94    // template calls it unconditionally in the tools branch; without it
95    // the render errors and the fallback quietly serves a TOOLLESS prompt.
96    env.add_function("visible_text", |v: Value| -> String {
97        if let Some(s) = v.as_str() {
98            return s.to_string();
99        }
100        if let Ok(iter) = v.try_iter() {
101            let mut out = Vec::new();
102            for item in iter {
103                if let Some(s) = item.as_str() {
104                    out.push(s.to_string());
105                } else if let Ok(t) = item.get_attr("text") {
106                    if let Some(s) = t.as_str() {
107                        out.push(s.to_string());
108                    }
109                }
110            }
111            return out.join("\n");
112        }
113        String::new()
114    });
115    env
116}
117
118/// Python `strftime` over a UTC unix time, for the directives chat
119/// templates use (`%Y %m %d %e %H %M %S %y %j %b %B %a %A %%`). Any other
120/// directive is an error rather than a silently wrong date.
121pub(crate) fn strftime_utc(fmt: &str, secs: i64) -> Result<String, Error> {
122    const MON: [&str; 12] = [
123        "January", "February", "March", "April", "May", "June", "July", "August", "September",
124        "October", "November", "December",
125    ];
126    const DAY: [&str; 7] =
127        ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
128    let days = secs.div_euclid(86_400);
129    let sod = secs.rem_euclid(86_400);
130    // Civil date from days since 1970-01-01 (H. Hinnant's algorithm).
131    let z = days + 719_468;
132    let era = z.div_euclid(146_097);
133    let doe = z - era * 146_097;
134    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
135    let doy_mar = doe - (365 * yoe + yoe / 4 - yoe / 100);
136    let mp = (5 * doy_mar + 2) / 153;
137    let d = doy_mar - (153 * mp + 2) / 5 + 1;
138    let m = if mp < 10 { mp + 3 } else { mp - 9 };
139    let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };
140    let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
141    const CUM: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
142    let yday = CUM[(m - 1) as usize] + d + if leap && m > 2 { 1 } else { 0 };
143    // 1970-01-01 was a Thursday (index 3 with Monday = 0).
144    let wday = (days + 3).rem_euclid(7) as usize;
145    let mut out = String::with_capacity(fmt.len() + 8);
146    let mut it = fmt.chars();
147    while let Some(c) = it.next() {
148        if c != '%' {
149            out.push(c);
150            continue;
151        }
152        match it.next() {
153            Some('Y') => out.push_str(&format!("{y:04}")),
154            Some('y') => out.push_str(&format!("{:02}", y.rem_euclid(100))),
155            Some('m') => out.push_str(&format!("{m:02}")),
156            Some('d') => out.push_str(&format!("{d:02}")),
157            Some('e') => out.push_str(&format!("{d:>2}")),
158            Some('j') => out.push_str(&format!("{yday:03}")),
159            Some('H') => out.push_str(&format!("{:02}", sod / 3600)),
160            Some('M') => out.push_str(&format!("{:02}", sod / 60 % 60)),
161            Some('S') => out.push_str(&format!("{:02}", sod % 60)),
162            Some('B') => out.push_str(MON[(m - 1) as usize]),
163            Some('b') => out.push_str(&MON[(m - 1) as usize][..3]),
164            Some('A') => out.push_str(DAY[wday]),
165            Some('a') => out.push_str(&DAY[wday][..3]),
166            Some('%') => out.push('%'),
167            other => {
168                return Err(Error::new(
169                    ErrorKind::InvalidOperation,
170                    format!(
171                        "strftime_now: unsupported directive %{}",
172                        other.map(String::from).unwrap_or_default()
173                    ),
174                ));
175            }
176        }
177    }
178    Ok(out)
179}
180
181/// `x | tojson(ensure_ascii=False, indent=None, separators=None, sort_keys=False)`.
182///
183/// Positional arguments bind in that order, exactly as in the Python
184/// signature — so `tojson(2)` sets `ensure_ascii`, not an indent, the
185/// same as it does under transformers.
186fn tojson_filter(value: &Value, args: Rest<Value>) -> Result<Value, Error> {
187    // minijinja passes keyword arguments as a trailing kwargs value.
188    let mut positional: Vec<Value> = args.0;
189    let kwargs = match positional.last() {
190        Some(last) if last.is_kwargs() => Kwargs::try_from(positional.pop().unwrap())?,
191        _ => Kwargs::from_iter(std::iter::empty::<(String, Value)>()),
192    };
193    if positional.len() > 4 {
194        return Err(Error::new(
195            ErrorKind::TooManyArguments,
196            "tojson() takes at most 4 positional arguments",
197        ));
198    }
199    let mut positional = positional.into_iter();
200    let ensure_ascii = positional.next();
201    let indent = positional.next();
202    let separators = positional.next();
203    let sort_keys = positional.next();
204    let pick = |pos: Option<Value>, name: &str| -> Result<Option<Value>, Error> {
205        let kw: Option<Value> = kwargs.get(name)?;
206        match (pos, kw) {
207            (Some(_), Some(_)) => Err(Error::new(
208                ErrorKind::InvalidOperation,
209                format!("tojson() got multiple values for argument '{name}'"),
210            )),
211            (p, k) => Ok(p.or(k).filter(|v| !v.is_none() && !v.is_undefined())),
212        }
213    };
214    let ensure_ascii = pick(ensure_ascii, "ensure_ascii")?;
215    let indent = pick(indent, "indent")?;
216    let separators = pick(separators, "separators")?;
217    let sort_keys = pick(sort_keys, "sort_keys")?;
218    kwargs.assert_all_used()?;
219
220    let indent = match indent {
221        None => None,
222        Some(v) if v.kind() == ValueKind::String => Some(v.as_str().unwrap_or("").to_string()),
223        Some(v) if v.kind() == ValueKind::Bool => Some(" ".repeat(v.is_true() as usize)),
224        Some(v) => {
225            let n = v.as_i64().ok_or_else(|| {
226                Error::new(
227                    ErrorKind::InvalidOperation,
228                    format!("tojson(): indent must be an int or a string, got {v}"),
229                )
230            })?;
231            Some(" ".repeat(n.max(0) as usize))
232        }
233    };
234    let separators = match separators {
235        None => None,
236        Some(v) => {
237            let items: Vec<Value> = v.try_iter().map(|it| it.collect()).map_err(|_| {
238                Error::new(
239                    ErrorKind::InvalidOperation,
240                    "tojson(): separators must be a (item, key) pair",
241                )
242            })?;
243            match items.as_slice() {
244                [a, b] if a.as_str().is_some() && b.as_str().is_some() => Some((
245                    a.as_str().unwrap().to_string(),
246                    b.as_str().unwrap().to_string(),
247                )),
248                _ => {
249                    return Err(Error::new(
250                        ErrorKind::InvalidOperation,
251                        "tojson(): separators must be a pair of strings",
252                    ));
253                }
254            }
255        }
256    };
257    let opts = DumpsOptions {
258        ensure_ascii: ensure_ascii.is_some_and(|v| v.is_true()),
259        indent,
260        separators,
261        sort_keys: sort_keys.is_some_and(|v| v.is_true()),
262    };
263    // Not HTML-escaped (transformers returns a plain str) and marked safe
264    // so an autoescaping template would not escape it again either.
265    py_json_dumps(value, &opts).map(Value::from_safe_string)
266}
267
268/// Kinds whose Python `str()` differs from minijinja's `Display`.
269fn needs_py_str(v: &Value) -> bool {
270    match v.kind() {
271        ValueKind::None | ValueKind::Bool | ValueKind::Seq | ValueKind::Map => true,
272        ValueKind::Number => !v.is_integer(),
273        _ => false,
274    }
275}
276
277/// Python `str(x)` for template values (strings verbatim, the rest `repr`).
278pub fn py_str(v: &Value) -> String {
279    match v.kind() {
280        ValueKind::String => v.as_str().unwrap_or("").to_string(),
281        ValueKind::Undefined => String::new(),
282        _ => py_repr(v),
283    }
284}
285
286/// Python `repr(x)` for template values.
287pub fn py_repr(v: &Value) -> String {
288    match v.kind() {
289        ValueKind::Undefined | ValueKind::None => "None".into(),
290        ValueKind::Bool => (if v.is_true() { "True" } else { "False" }).into(),
291        ValueKind::Number if v.is_integer() => v.to_string(),
292        ValueKind::Number => {
293            let f = f64::try_from(v.clone()).unwrap_or(f64::NAN);
294            if f.is_nan() {
295                "nan".into()
296            } else if f.is_infinite() {
297                (if f > 0.0 { "inf" } else { "-inf" }).into()
298            } else {
299                py_float_repr(f)
300            }
301        }
302        ValueKind::String => py_str_repr(v.as_str().unwrap_or("")),
303        ValueKind::Seq => {
304            let items: Vec<String> = v
305                .try_iter()
306                .map(|it| it.map(|x| py_repr(&x)).collect())
307                .unwrap_or_default();
308            format!("[{}]", items.join(", "))
309        }
310        ValueKind::Map => {
311            let mut items = Vec::new();
312            if let Ok(keys) = v.try_iter() {
313                for k in keys {
314                    let item = v.get_item(&k).unwrap_or(Value::UNDEFINED);
315                    items.push(format!("{}: {}", py_repr(&k), py_repr(&item)));
316                }
317            }
318            format!("{{{}}}", items.join(", "))
319        }
320        _ => v.to_string(),
321    }
322}
323
324/// Python `repr(str)`: single quotes unless the text holds a `'` and no
325/// `"`; backslash escapes for that quote, the backslash, newline, CR,
326/// tab and other control characters.
327fn py_str_repr(s: &str) -> String {
328    let quote = if s.contains('\'') && !s.contains('"') {
329        '"'
330    } else {
331        '\''
332    };
333    let mut out = String::with_capacity(s.len() + 2);
334    out.push(quote);
335    for c in s.chars() {
336        match c {
337            '\\' => out.push_str("\\\\"),
338            '\n' => out.push_str("\\n"),
339            '\r' => out.push_str("\\r"),
340            '\t' => out.push_str("\\t"),
341            c if c == quote => {
342                out.push('\\');
343                out.push(c);
344            }
345            c if (c as u32) < 0x20 || (0x7f..0xa0).contains(&(c as u32)) => {
346                out.push_str(&format!("\\x{:02x}", c as u32));
347            }
348            c => out.push(c),
349        }
350    }
351    out.push(quote);
352    out
353}
354
355/// Python `json.dumps(value, **opts)` over a template value.
356pub fn py_json_dumps(value: &Value, opts: &DumpsOptions) -> Result<String, Error> {
357    let (item_sep, key_sep) = match &opts.separators {
358        Some((i, k)) => (i.as_str(), k.as_str()),
359        None if opts.indent.is_some() => (",", ": "),
360        None => (", ", ": "),
361    };
362    let mut out = String::new();
363    let mut d = Dumper {
364        opts,
365        item_sep,
366        key_sep,
367        out: &mut out,
368    };
369    d.value(value, 0)?;
370    Ok(out)
371}
372
373struct Dumper<'o> {
374    opts: &'o DumpsOptions,
375    item_sep: &'o str,
376    key_sep: &'o str,
377    out: &'o mut String,
378}
379
380impl Dumper<'_> {
381    fn newline(&mut self, level: usize) {
382        if let Some(ind) = &self.opts.indent {
383            self.out.push('\n');
384            for _ in 0..level {
385                self.out.push_str(ind);
386            }
387        }
388    }
389
390    fn value(&mut self, v: &Value, level: usize) -> Result<(), Error> {
391        match v.kind() {
392            // json.dumps(None) → null. An undefined value cannot reach
393            // Python's json.dumps at all (jinja2 raises); null is the
394            // forgiving spelling rather than a failed render.
395            ValueKind::Undefined | ValueKind::None => self.out.push_str("null"),
396            ValueKind::Bool => self
397                .out
398                .push_str(if v.is_true() { "true" } else { "false" }),
399            ValueKind::Number => {
400                if v.is_integer() {
401                    self.out.push_str(&v.to_string());
402                } else {
403                    let f = f64::try_from(v.clone()).map_err(|_| {
404                        Error::new(ErrorKind::InvalidOperation, "tojson(): bad number")
405                    })?;
406                    self.out.push_str(&py_float_repr(f));
407                }
408            }
409            ValueKind::String => self.string(v.as_str().unwrap_or("")),
410            ValueKind::Seq | ValueKind::Iterable => {
411                let items: Vec<Value> = v.try_iter()?.collect();
412                if items.is_empty() {
413                    self.out.push_str("[]");
414                    return Ok(());
415                }
416                self.out.push('[');
417                for (i, item) in items.iter().enumerate() {
418                    if i > 0 {
419                        self.out.push_str(self.item_sep);
420                    }
421                    self.newline(level + 1);
422                    self.value(item, level + 1)?;
423                }
424                self.newline(level);
425                self.out.push(']');
426            }
427            ValueKind::Map | ValueKind::Plain => {
428                let mut entries: Vec<(String, Value)> = Vec::new();
429                for key in v.try_iter()? {
430                    let item = v.get_item(&key)?;
431                    entries.push((self.key_text(&key)?, item));
432                }
433                if self.opts.sort_keys {
434                    entries.sort_by(|a, b| a.0.cmp(&b.0));
435                }
436                if entries.is_empty() {
437                    self.out.push_str("{}");
438                    return Ok(());
439                }
440                self.out.push('{');
441                for (i, (k, item)) in entries.iter().enumerate() {
442                    if i > 0 {
443                        self.out.push_str(self.item_sep);
444                    }
445                    self.newline(level + 1);
446                    self.string(k);
447                    self.out.push_str(self.key_sep);
448                    self.value(item, level + 1)?;
449                }
450                self.newline(level);
451                self.out.push('}');
452            }
453            other => {
454                return Err(Error::new(
455                    ErrorKind::InvalidOperation,
456                    format!("tojson(): object of type {other} is not JSON serializable"),
457                ));
458            }
459        }
460        Ok(())
461    }
462
463    /// Python coerces non-string keys: int → "1", float → repr, bool →
464    /// "true", None → "null".
465    fn key_text(&self, k: &Value) -> Result<String, Error> {
466        Ok(match k.kind() {
467            ValueKind::String => k.as_str().unwrap_or("").to_string(),
468            ValueKind::None | ValueKind::Undefined => "null".into(),
469            ValueKind::Bool => (if k.is_true() { "true" } else { "false" }).into(),
470            ValueKind::Number if k.is_integer() => k.to_string(),
471            ValueKind::Number => py_float_repr(f64::try_from(k.clone()).unwrap_or(f64::NAN)),
472            other => {
473                return Err(Error::new(
474                    ErrorKind::InvalidOperation,
475                    format!("tojson(): keys must be str, int, float, bool or None, not {other}"),
476                ));
477            }
478        })
479    }
480
481    fn string(&mut self, s: &str) {
482        self.out.push('"');
483        for c in s.chars() {
484            match c {
485                '"' => self.out.push_str("\\\""),
486                '\\' => self.out.push_str("\\\\"),
487                '\n' => self.out.push_str("\\n"),
488                '\r' => self.out.push_str("\\r"),
489                '\t' => self.out.push_str("\\t"),
490                '\u{08}' => self.out.push_str("\\b"),
491                '\u{0c}' => self.out.push_str("\\f"),
492                c if (c as u32) < 0x20 => {
493                    self.out.push_str(&format!("\\u{:04x}", c as u32));
494                }
495                // ensure_ascii escapes everything outside printable ASCII
496                // (space..~), DEL included; astral chars as a UTF-16
497                // surrogate pair, lower-case hex — Python's spelling.
498                c if self.opts.ensure_ascii && !(' '..='~').contains(&c) => {
499                    let mut buf = [0u16; 2];
500                    for unit in c.encode_utf16(&mut buf) {
501                        self.out.push_str(&format!("\\u{:04x}", unit));
502                    }
503                }
504                c => self.out.push(c),
505            }
506        }
507        self.out.push('"');
508    }
509}
510
511/// Python's `float.__repr__`: the shortest round-trip digits, fixed
512/// notation for decimal exponents in (-4, 16], otherwise `d.ddde±XX`
513/// with at least two exponent digits; `json.dumps` spells the
514/// non-finite values `NaN` / `Infinity` / `-Infinity`.
515pub fn py_float_repr(f: f64) -> String {
516    if f.is_nan() {
517        return "NaN".into();
518    }
519    if f.is_infinite() {
520        return if f > 0.0 { "Infinity" } else { "-Infinity" }.into();
521    }
522    if f == 0.0 {
523        return if f.is_sign_negative() { "-0.0" } else { "0.0" }.into();
524    }
525    // Rust's `{:e}` is the shortest round-trip representation too.
526    let e = format!("{:e}", f.abs());
527    let (mant, exp) = e.split_once('e').expect("LowerExp has an exponent");
528    let exp: i32 = exp.parse().expect("LowerExp exponent");
529    let digits: String = mant.chars().filter(|c| c.is_ascii_digit()).collect();
530    let decpt = exp + 1; // value = 0.DIGITS × 10^decpt
531    let mut s = String::new();
532    if f < 0.0 {
533        s.push('-');
534    }
535    if -4 < decpt && decpt <= 16 {
536        let n = digits.len() as i32;
537        if decpt <= 0 {
538            s.push_str("0.");
539            for _ in 0..(-decpt) {
540                s.push('0');
541            }
542            s.push_str(&digits);
543        } else if decpt >= n {
544            s.push_str(&digits);
545            for _ in 0..(decpt - n) {
546                s.push('0');
547            }
548            s.push_str(".0");
549        } else {
550            s.push_str(&digits[..decpt as usize]);
551            s.push('.');
552            s.push_str(&digits[decpt as usize..]);
553        }
554    } else {
555        s.push_str(&digits[..1]);
556        if digits.len() > 1 {
557            s.push('.');
558            s.push_str(&digits[1..]);
559        }
560        s.push('e');
561        s.push(if exp < 0 { '-' } else { '+' });
562        s.push_str(&format!("{:02}", exp.abs()));
563    }
564    s
565}
566
567#[cfg(test)]
568mod tests {
569    use super::*;
570
571    fn render(tpl: &str, ctx: serde_json::Value) -> Result<String, Error> {
572        let mut env = environment();
573        env.add_template("t", tpl)?;
574        env.get_template("t")?.render(Value::from_serialize(&ctx))
575    }
576
577    fn tool() -> serde_json::Value {
578        // Deliberately NOT alphabetical: insertion order must survive.
579        serde_json::json!({
580            "type": "function",
581            "function": {
582                "name": "get_weather",
583                "description": "Погода <city> & \"quotes\" 🌧",
584                "parameters": {
585                    "type": "object",
586                    "properties": {"unit": {"type": "string"}, "city": {"type": "string"}},
587                    "required": ["city"]
588                }
589            }
590        })
591    }
592
593    /// Default call: Python's `", "` / `": "` separators, insertion
594    /// order, non-ASCII verbatim, and NO HTML escaping of `<`, `&`, `'`.
595    /// Expected strings are `json.dumps(tool)` from CPython 3.12.
596    #[test]
597    fn default_matches_python_json_dumps() {
598        let got = render("{{ t | tojson }}", serde_json::json!({"t": tool()})).unwrap();
599        assert_eq!(
600            got,
601            r#"{"type": "function", "function": {"name": "get_weather", "description": "Погода <city> & \"quotes\" 🌧", "parameters": {"type": "object", "properties": {"unit": {"type": "string"}, "city": {"type": "string"}}, "required": ["city"]}}}"#
602        );
603        // MiniCPM5 spells the default out — it was a hard error before.
604        let explicit = render(
605            "{{ t | tojson(ensure_ascii=False) }}",
606            serde_json::json!({"t": tool()}),
607        )
608        .unwrap();
609        assert_eq!(explicit, got);
610    }
611
612    #[test]
613    fn ensure_ascii_escapes_like_python() {
614        let got = render(
615            "{{ s | tojson(ensure_ascii=True) }}",
616            serde_json::json!({"s": "é\u{7f}🌧\u{1}\t'"}),
617        )
618        .unwrap();
619        // json.dumps("é\x7f🌧\x01\t'", ensure_ascii=True)
620        assert_eq!(got, r#""\u00e9\u007f\ud83c\udf27\u0001\t'""#);
621    }
622
623    #[test]
624    fn sort_keys_indent_and_separators() {
625        let v = serde_json::json!({"b": [1, 2], "a": {}, "c": []});
626        let ctx = serde_json::json!({"v": v});
627        assert_eq!(
628            render("{{ v | tojson(sort_keys=True) }}", ctx.clone()).unwrap(),
629            r#"{"a": {}, "b": [1, 2], "c": []}"#
630        );
631        // json.dumps(v, indent=2): item separator loses its space.
632        assert_eq!(
633            render("{{ v | tojson(indent=2) }}", ctx.clone()).unwrap(),
634            "{\n  \"b\": [\n    1,\n    2\n  ],\n  \"a\": {},\n  \"c\": []\n}"
635        );
636        assert_eq!(
637            render(
638                "{{ v | tojson(indent='\\t', sort_keys=true) }}",
639                ctx.clone()
640            )
641            .unwrap(),
642            "{\n\t\"a\": {},\n\t\"b\": [\n\t\t1,\n\t\t2\n\t],\n\t\"c\": []\n}"
643        );
644        assert_eq!(
645            render("{{ v | tojson(separators=(',', ':')) }}", ctx.clone()).unwrap(),
646            r#"{"b":[1,2],"a":{},"c":[]}"#
647        );
648        // indent=0: newlines, no indentation.
649        assert_eq!(
650            render("{{ [1] | tojson(indent=0) }}", ctx.clone()).unwrap(),
651            "[\n1\n]"
652        );
653        // Positional arguments follow the Python signature: the first
654        // one is ensure_ascii, not an indent.
655        assert_eq!(
656            render("{{ 'é' | tojson(true) }}", ctx.clone()).unwrap(),
657            r#""\u00e9""#
658        );
659    }
660
661    #[test]
662    fn unknown_keyword_is_an_error() {
663        assert!(render("{{ 1 | tojson(bogus=1) }}", serde_json::json!({})).is_err());
664    }
665
666    #[test]
667    fn scalars_follow_python() {
668        let got = render(
669            "{{ v | tojson }}",
670            serde_json::json!({"v": [1, -7, 1.5, 18.0, 1e16, 1.0e-5, 0.0001, 123456789012345678u64, true, null]}),
671        )
672        .unwrap();
673        // json.dumps([1, -7, 1.5, 18.0, 1e16, 1e-05, 0.0001, 123456789012345678, True, None])
674        assert_eq!(
675            got,
676            "[1, -7, 1.5, 18.0, 1e+16, 1e-05, 0.0001, 123456789012345678, true, null]"
677        );
678    }
679
680    #[test]
681    fn float_repr_table() {
682        for (f, want) in [
683            (0.1, "0.1"),
684            (1.0 / 3.0, "0.3333333333333333"),
685            (1234567890123456.0, "1234567890123456.0"),
686            (12345678901234567.0, "1.2345678901234568e+16"),
687            (-2.5e-7, "-2.5e-07"),
688            (1e100, "1e+100"),
689            (-0.0, "-0.0"),
690            (f64::INFINITY, "Infinity"),
691        ] {
692            assert_eq!(py_float_repr(f), want, "{f:e}");
693        }
694    }
695
696    /// Template-level iteration keeps request order too (Python dicts
697    /// are insertion-ordered; minijinja sorted them before
698    /// `preserve_order`).
699    #[test]
700    fn dict_items_keep_insertion_order() {
701        let got = render(
702            "{% for k, v in d.items() %}{{ k }}={{ v }};{% endfor %}",
703            serde_json::json!({"d": {"zeta": 1, "alpha": 2, "mid": 3}}),
704        )
705        .unwrap();
706        assert_eq!(got, "zeta=1;alpha=2;mid=3;");
707    }
708
709    /// `{{ x }}` / `x | string` print Python's `str()`; the expected
710    /// strings are CPython's output for the same values.
711    #[test]
712    fn printing_follows_python_str() {
713        let ctx = serde_json::json!({
714            "b": true, "n": null, "f": 1.5e-7, "i": 42, "s": "plain",
715            "l": ["a", "it's", 2, false, null], "d": {"k": true, "z": [1.0]}
716        });
717        let got = render(
718            "{{ b }}|{{ n }}|{{ f }}|{{ i }}|{{ s }}|{{ l }}|{{ d }}|{{ b | string }}|{{ 'x' ~ i }}",
719            ctx,
720        )
721        .unwrap();
722        assert_eq!(
723            got,
724            r#"True|None|1.5e-07|42|plain|['a', "it's", 2, False, None]|{'k': True, 'z': [1.0]}|True|x42"#
725        );
726        // repr("a\nb'\"\\") == 'a\nb\'"\\'
727        assert_eq!(py_str_repr("a\nb'\"\\"), r#"'a\nb\'"\\'"#);
728    }
729
730    #[test]
731    fn strftime_utc_matches_python() {
732        // 2026-11-20 10:53:30 UTC, a Friday.
733        let t = 1_795_172_010;
734        assert_eq!(strftime_utc("%Y-%m-%d", t).unwrap(), "2026-11-20");
735        assert_eq!(strftime_utc("%d %b %Y", t).unwrap(), "20 Nov 2026");
736        assert_eq!(
737            strftime_utc("%A, %B %e %H:%M:%S %j %y %%", t).unwrap(),
738            "Friday, November 20 10:53:30 324 26 %"
739        );
740        // Leap day and the epoch itself.
741        assert_eq!(strftime_utc("%Y-%m-%d %a %j", 951_782_400).unwrap(), "2000-02-29 Tue 060");
742        assert_eq!(strftime_utc("%Y-%m-%d %a", 0).unwrap(), "1970-01-01 Thu");
743        assert!(strftime_utc("%Q", t).is_err());
744        let r = render("{{ strftime_now('%Y') | length }}", serde_json::json!({})).unwrap();
745        assert_eq!(r, "4");
746    }
747
748    #[test]
749    fn raise_exception_carries_the_template_message() {
750        let err = render(
751            "{{ raise_exception('roles must alternate') }}",
752            serde_json::json!({}),
753        )
754        .unwrap_err();
755        assert!(
756            format!("{err:#}").contains("roles must alternate"),
757            "{err:#}"
758        );
759    }
760}