From b8ec31dc58c56d7ee9accae0a446e01667355ba5 Mon Sep 17 00:00:00 2001 From: Mason Lyons Date: Sat, 17 Oct 2026 23:57:28 +0000 Subject: [PATCH 1/2] Native {% blocktranslate %}, {% static %} and humanize naturaltime These three were the largest Python-bound pieces left on a realistic backend+request page (benchmarks/realworld.py). - {% blocktranslate %} / {% blocktrans %} compile to a native node (src/tags/i18n.rs): count/context/with/trimmed/asvar, plural forms and the stock missing-key and bad-format fallbacks. gettext, pgettext, ngettext and npgettext go through a shared filters::Translator. - {% static %} renders natively when handle_simple is stock. With the exact StaticFilesStorage, storage.url results are memoized per (base_url, path); other storages (Manifest, custom) still call url(). - humanize naturaltime is native. Msgids are read from the stock lazy proxies rather than hardcoded (they contain U+00A0). realworld page: 2.6x -> 3.5x over stock (2.9 ms -> 2.2 ms). blocktranslate 1.1x -> 6-7x, static 1.3x -> 10x, naturaltime 1.2x -> 4.2x. Co-Authored-By: Claude Opus 5.5 --- README.md | 14 +- src/filters/humanize.rs | 353 +++++++++++++++++++++++++++++++++++++++ src/filters/mod.rs | 187 +++++++++++++++++++++ src/nodes_py.rs | 2 + src/parser.rs | 24 +++ src/tags/blocks.rs | 5 + src/tags/i18n.rs | 360 ++++++++++++++++++++++++++++++++++++++++ src/tags/mod.rs | 27 +++ src/tags/parse.rs | 51 ++++++ src/tags/simple.rs | 188 +++++++++++++++++++++ tests/test_realpage.py | 254 ++++++++++++++++++++++++++++ 11 files changed, 1458 insertions(+), 7 deletions(-) create mode 100644 src/tags/i18n.rs diff --git a/README.md b/README.md index bc16bd3..51dab27 100644 --- a/README.md +++ b/README.md @@ -119,12 +119,12 @@ template.render(Context({"user": {"name": "ada lovelace"}})) # 'Hello Ada Lovel [open an issue](https://github.com/MasonLyons/rust-django-template-engine/issues). - **Built-in tags and filters** run natively, including `extends`/`block`, `include`, `for`, `if`, `with`, `cycle`, `url`, `csrf_token`, Django 6.1 - `partialdef`/`partial`, `{% translate "literal" %}`, and filters such as - `date`, `floatformat`, `urlize`, `join` and `striptags`, plus humanize's - `intcomma` on integers. + `partialdef`/`partial`, `{% translate "literal" %}`, `{% blocktranslate %}`, + `{% static %}`, and filters such as `date`, `floatformat`, `urlize`, `join` + and `striptags`, plus humanize's `intcomma` on integers and `naturaltime`. - **Custom and third-party tag libraries** keep working. `simple_tag` and `inclusion_tag` run on native helper nodes. Other tags (custom compile - functions, `simple_block_tag`, `{% blocktranslate %}`, `{% static %}`) are + functions, `simple_block_tag`) are bridged to their Python implementation, so their own code runs at Python speed while the rest of the template stays native. When a bridged *block* tag (e.g. `{% localtime %}`, `{% cache %}`, `simple_block_tag`) calls @@ -200,9 +200,9 @@ production. - [`benchmarks/realworld.py`](benchmarks/realworld.py) renders a full page through the backend with a request: context processors, `{% static %}`, `{% url %}`, i18n tags, messages, a form and humanize filters. Python code - that the page calls (context processors, `naturaltime`, form and widget - classes, `{% static %}` storage lookups, bridged tags) runs at the same - speed on both engines, so this page is about 2.6× faster rather than 14×. + that the page calls (context processors, form and widget classes, + translation catalog lookups, bridged tags) runs at the same speed on both + engines, so this page is about 3.5× faster rather than 14×. HTML escaping and the lexer's tag scanner use portable SIMD: `fearless_simd` picks SSE2 on x86_64 and NEON on aarch64, and `memchr` picks the best diff --git a/src/filters/humanize.rs b/src/filters/humanize.rs index 3addd99..bb34ca0 100644 --- a/src/filters/humanize.rs +++ b/src/filters/humanize.rs @@ -119,3 +119,356 @@ fn native_intcomma(py: Python<'_>, n: i64) -> PyResult> { out.extend(gd.chars().rev()); Ok(Some(out)) } + +/// `(context, singular, plural)` of an `ngettext_lazy` / `npgettext_lazy` +/// proxy (the msgids carry U+00A0 and may change between releases, so they +/// are read from the stock objects rather than restated here). +type NMsg = (Option, String, String); + +/// Msgids of `NaturalTimeFormatter`'s lazy strings, index 0 = past, +/// 1 = future. +struct NtMsgs { + /// `"%(delta)s ago"` / `"%(delta)s from now"` (`gettext_lazy`). + day: [String; 2], + /// `past-second` … `past-hour` / `future-*` (`ngettext_lazy`, number + /// key `"count"`). + second: [NMsg; 2], + minute: [NMsg; 2], + hour: [NMsg; 2], + /// `past_substrings` / `future_substrings` in `TIME_STRINGS_KEYS` order + /// (`npgettext_lazy`, number key `"num"`). + units: [Vec; 2], +} + +/// Stock objects the native `naturaltime` checks against or calls. +struct NaturalTime { + /// `django.contrib.humanize.templatetags.humanize` globals (the live + /// `datetime` class, patched by the humanize tests, is read per call). + globals: Py, + /// `NaturalTimeFormatter` as imported (a replaced class → Python). + formatter: Py, + /// `NaturalTimeFormatter.string_for` (patched → Python). + string_for: Py, + /// `NaturalTimeFormatter.time_strings` (its `"now"` entry is returned + /// as is, a lazy string, like stock). + time_strings: Py, + /// `django.template.defaultfilters` globals: humanize calls + /// `defaultfilters.timesince` / `.timeuntil`. + defaultfilters: Py, + timesince: Py, + timeuntil: Py, + utc: Py, + /// `None` when the lazy strings don't have the expected shape + /// (native path disabled). + msgs: Option, +} + +const TIME_STRINGS_KEYS: [&str; 6] = ["year", "month", "week", "day", "hour", "minute"]; + +fn nt_msgs(formatter: &Bound<'_, PyAny>) -> Option { + let ts = formatter.getattr("time_strings").ok()?; + let kw = |p: Bound<'_, PyAny>| -> Option { + let kw = p.getattr("_kw").ok()?.cast_into::().ok()?; + let get = |k: &str| -> Option { kw.get_item(k).ok()??.extract().ok() }; + let n = kw.len(); + let ctx = get("context"); + if n != 2 + usize::from(ctx.is_some()) { + return None; + } + Some((ctx, get("singular")?, get("plural")?)) + }; + let nmsg = |k: &str| -> Option { + let m = kw(ts.get_item(k).ok()?)?; + m.0.is_none().then_some(m) + }; + let gmsg = |k: &str| -> Option { + let p = ts.get_item(k).ok()?; + let args = p.getattr("_args").ok()?.cast_into::().ok()?; + let kw = p.getattr("_kw").ok()?.cast_into::().ok()?; + if args.len() != 1 || !kw.is_empty() { + return None; + } + args.get_item(0).ok()?.extract().ok() + }; + let units = |attr: &str| -> Option> { + let d = formatter.getattr(attr).ok()?; + TIME_STRINGS_KEYS + .iter() + .map(|k| kw(d.get_item(k).ok()?).filter(|m| m.0.is_some())) + .collect() + }; + Some(NtMsgs { + day: [gmsg("past-day")?, gmsg("future-day")?], + second: [nmsg("past-second")?, nmsg("future-second")?], + minute: [nmsg("past-minute")?, nmsg("future-minute")?], + hour: [nmsg("past-hour")?, nmsg("future-hour")?], + units: [units("past_substrings")?, units("future_substrings")?], + }) +} + +fn natural_time(py: Python<'_>) -> PyResult<&NaturalTime> { + static NT: PyOnceLock = PyOnceLock::new(); + NT.get_or_try_init(py, || -> PyResult { + let m = py.import("django.contrib.humanize.templatetags.humanize")?; + let formatter = m.getattr("NaturalTimeFormatter")?; + let ts = py.import("django.utils.timesince")?; + Ok(NaturalTime { + globals: m.dict().unbind(), + string_for: formatter.getattr("string_for")?.unbind(), + time_strings: formatter.getattr("time_strings")?.unbind(), + msgs: nt_msgs(&formatter), + formatter: formatter.unbind(), + defaultfilters: py.import("django.template.defaultfilters")?.dict().unbind(), + timesince: ts.getattr("timesince")?.unbind(), + timeuntil: ts.getattr("timeuntil")?.unbind(), + utc: py.import("datetime")?.getattr("timezone")?.getattr("utc")?.unbind(), + }) + }) +} +/// The stock Python `naturaltime`. +fn py_naturaltime(py: Python<'_>) -> PyResult<&Bound<'_, PyAny>> { + static F: PyOnceLock> = PyOnceLock::new(); + Ok(F.get_or_try_init(py, || -> PyResult> { + Ok(py + .import("django.contrib.humanize.templatetags.humanize")? + .getattr("naturaltime")? + .unbind()) + })? + .bind(py)) +} + +/// `naturaltime(value)` (`NaturalTimeFormatter.string_for`) for an exact +/// `datetime.datetime`: the branch logic and `timesince` run natively, the +/// datetime arithmetic and comparisons through the real (possibly mocked) +/// `datetime` objects, and the lazy `ngettext_lazy`/`npgettext_lazy` +/// strings become direct catalog lookups (`filters::ngettext` & co.) with +/// the stock msgids, identical on 5.2 and 6.1. Anything else (non-datetime +/// values, subclasses, a patched formatter or `timesince`) takes the +/// Python function. +pub(crate) fn naturaltime<'py>( + _rc: &mut Rctx<'py>, + input: &Bound<'py, PyAny>, + args: &[Bound<'py, PyAny>], + _ae: Option, +) -> PyResult> { + let py = input.py(); + if args.is_empty() && input.is_exact_instance_of::() { + if let Some(r) = native_naturaltime(py, input)? { + return Ok(r); + } + } + py_naturaltime(py)?.call1((input,).into_pyobject(py)?.add_args(args)?) +} + +/// `django.utils.timezone.is_aware`. +fn is_aware(v: &Bound<'_, PyAny>) -> PyResult { + Ok(!v.call_method0(pyo3::intern!(v.py(), "utcoffset"))?.is_none()) +} + +/// `ngettext_lazy(singular, plural, key) % {key: n}` / +/// `npgettext_lazy(...)` (`NumberAwareString.__mod__`): translate for `n`, +/// then `%`-format, keeping the translation when it has no placeholder +/// (`TypeError`). +fn n_format<'py>( + tr: &super::Translator<'py>, + msg: &NMsg, + key: &str, + n: i64, +) -> PyResult> { + let py = tr.py(); + let num = PyInt::new(py, n).into_any(); + let (context, singular, plural) = msg; + let translated = match context { + Some(c) => tr.npgettext(c, singular, plural, &num)?, + None => tr.ngettext(singular, plural, &num)?, + }; + let rhs = pyo3::types::PyDict::new(py); + rhs.set_item(key, &num)?; + match translated.rem(&rhs) { + Ok(r) => Ok(r), + Err(e) if super::is_te(py, &e) => Ok(translated), + Err(e) => Err(e), + } +} + +/// `gettext_lazy(message) % {key: value}`. +fn g_format<'py>( + tr: &super::Translator<'py>, + message: &str, + key: &str, + value: &Bound<'py, PyAny>, +) -> PyResult> { + let rhs = pyo3::types::PyDict::new(tr.py()); + rhs.set_item(key, value)?; + tr.gettext(message)?.rem(&rhs) +} + +/// Python `float.__floordiv__` (the quotient half of `_float_div_mod`). +fn py_float_floordiv(vx: f64, wx: f64) -> f64 { + let m = vx % wx; + let mut div = (vx - m) / wx; + if m != 0.0 && (wx < 0.0) != (m < 0.0) { + div -= 1.0; + } + if div == 0.0 { + return 0.0_f64.copysign(vx / wx); + } + let mut fd = div.floor(); + if div - fd > 0.5 { + fd += 1.0; + } + fd +} + +fn native_naturaltime<'py>( + py: Python<'py>, + value: &Bound<'py, PyAny>, +) -> PyResult>> { + use pyo3::types::{PyDeltaAccess, PyTzInfoAccess}; + let nt = natural_time(py)?; + let globals = nt.globals.bind(py); + let Some(formatter) = globals.get_item("NaturalTimeFormatter")? else { + return Ok(None); + }; + if !formatter.is(nt.formatter.bind(py)) + || !formatter.getattr("string_for")?.eq(nt.string_for.bind(py))? + { + return Ok(None); + } + let df = nt.defaultfilters.bind(py); + let same = |name: &str, f: &Py| -> PyResult { + Ok(df.get_item(name)?.is_some_and(|g| g.is(f.bind(py)))) + }; + if !same("timesince", &nt.timesince)? || !same("timeuntil", &nt.timeuntil)? { + return Ok(None); + } + let Some(dt_cls) = globals.get_item("datetime")? else { + return Ok(None); + }; + let dt = value.cast::()?; + // `is_aware(value)`; tzinfo None ⇒ utcoffset() None. + let aware = dt.get_tzinfo().is_some() && is_aware(value)?; + let tz = if aware { nt.utc.bind(py).clone() } else { py.None().into_bound(py) }; + let now = dt_cls.call_method1(pyo3::intern!(py, "now"), (tz,))?; + let past = value.lt(&now)?; + let delta = if past { now.sub(value)? } else { value.sub(&now)? }; + let delta = delta.cast_into::()?; + let (days, seconds) = (delta.get_days(), i64::from(delta.get_seconds())); + let Some(msgs) = nt.msgs.as_ref() else { + return Ok(None); + }; + let side = usize::from(!past); + let tr = super::Translator::new(py); + if days != 0 { + let joined = timesince(&tr, value, &now, !past, &msgs.units[side])?; + return g_format(&tr, &msgs.day[side], "delta", &joined).map(Some); + } + if seconds == 0 { + return nt.time_strings.bind(py).get_item("now").map(Some); + } + let (msg, count) = if seconds < 60 { + (&msgs.second[side], seconds) + } else if seconds / 60 < 60 { + (&msgs.minute[side], seconds / 60) + } else { + (&msgs.hour[side], seconds / 60 / 60) + }; + n_format(&tr, msg, "count", count).map(Some) +} + +/// `django.utils.timesince.timesince(d, now, reversed, time_strings)` with +/// the default `depth=2`; `units` are the `time_strings` msgids in +/// `TIME_STRINGS_KEYS` order, `d` is an exact datetime and `now` a +/// (possibly mocked) datetime. +fn timesince<'py>( + tr: &super::Translator<'py>, + d: &Bound<'py, PyAny>, + now: &Bound<'py, PyAny>, + reversed: bool, + units: &[NMsg], +) -> PyResult> { + use pyo3::types::{PyDateAccess, PyDateTime, PyDelta, PyDeltaAccess, PyTimeAccess, PyTzInfoAccess}; + const CHUNKS: [f64; 4] = [604_800.0, 86_400.0, 3_600.0, 60.0]; + const MONTHS_DAYS: [u8; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + let py = tr.py(); + let unit = |i: usize, n: i64| -> PyResult { + let s = n_format(tr, &units[i], "num", n)?; + // `avoid_wrapping`. + Ok(s.str()?.to_str()?.replace(' ', "\u{a0}")) + }; + let mut now = now.clone(); + if is_aware(&now)? && is_aware(d)? { + let tzinfo = d.cast::()?.get_tzinfo(); + now = now.call_method1(pyo3::intern!(py, "astimezone"), (tzinfo,))?; + } + let (d, now) = if reversed { (now, d.clone()) } else { (d.clone(), now) }; + let delta = now.sub(&d)?.cast_into::()?; + let since = i64::from(delta.get_days()) * 86_400 + i64::from(delta.get_seconds()); + if since <= 0 { + return Ok(PyString::new(py, &unit(5, 0)?).into_any()); + } + let dd = d.cast::()?; + let nd = now.cast::()?; + let mut total_months = (i64::from(nd.get_year()) - i64::from(dd.get_year())) * 12 + + (i64::from(nd.get_month()) - i64::from(dd.get_month())); + let dtime = (dd.get_hour(), dd.get_minute(), dd.get_second(), dd.get_microsecond()); + let ntime = (nd.get_hour(), nd.get_minute(), nd.get_second(), nd.get_microsecond()); + if dd.get_day() > nd.get_day() || (dd.get_day() == nd.get_day() && dtime > ntime) { + total_months -= 1; + } + let (years, months) = (total_months.div_euclid(12), total_months.rem_euclid(12)); + let pivot = if years != 0 || months != 0 { + let mut pivot_year = i64::from(dd.get_year()) + years; + let mut pivot_month = i64::from(dd.get_month()) + months; + if pivot_month > 12 { + pivot_month -= 12; + pivot_year += 1; + } + let (Ok(py_year), Ok(py_month)) = (i32::try_from(pivot_year), u8::try_from(pivot_month)) + else { + return Err(pyo3::exceptions::PyValueError::new_err("year is out of range")); + }; + let day = MONTHS_DAYS[usize::from(py_month) - 1].min(dd.get_day()); + PyDateTime::new( + py, + py_year, + py_month, + day, + dd.get_hour(), + dd.get_minute(), + dd.get_second(), + 0, + dd.get_tzinfo().as_ref(), + )? + .into_any() + } else { + d.clone() + }; + let mut remaining: f64 = now + .sub(&pivot)? + .call_method0(pyo3::intern!(py, "total_seconds"))? + .extract()?; + let mut partials: [i64; 6] = [years, months, 0, 0, 0, 0]; + for (i, chunk) in CHUNKS.iter().enumerate() { + let q = py_float_floordiv(remaining, *chunk); + // `int(q)`: truncation of an integral float. + #[allow(clippy::cast_possible_truncation)] + let count = q as i64; + partials[i + 2] = count; + remaining -= chunk * q; + } + let Some(mut i) = partials.iter().position(|&v| v != 0) else { + return Ok(PyString::new(py, &unit(5, 0)?).into_any()); + }; + let mut parts: Vec = Vec::with_capacity(2); + while i < TIME_STRINGS_KEYS.len() && parts.len() < 2 { + let v = partials[i]; + if v == 0 { + break; + } + parts.push(unit(i, v)?); + i += 1; + } + let sep = tr.gettext(", ")?; + sep.call_method1(pyo3::intern!(py, "join"), (parts,)) +} diff --git a/src/filters/mod.rs b/src/filters/mod.rs index 8b79109..82feb9d 100644 --- a/src/filters/mod.rs +++ b/src/filters/mod.rs @@ -155,6 +155,7 @@ fn humanize_native(func: &Bound<'_, PyAny>) -> Option { let qualname: String = func.getattr("__qualname__").and_then(|m| m.extract()).ok()?; match qualname.as_str() { "intcomma" => Some(humanize::intcomma), + "naturaltime" => Some(humanize::naturaltime), _ => None, } } @@ -388,6 +389,192 @@ fn fast_gettext<'py>(py: Python<'py>, eol: &str) -> PyResult` would consult. +enum TransObj<'py> { + /// `_trans.` is `trans_real.`: the active translation + /// object (else `_default`). + Real(Bound<'py, PyAny>), + /// `_trans.` is `trans_null.` (no translation at all). + Null, +} + +/// The public `django.utils.translation` module functions (Python path). +fn translation_fn<'py>(py: Python<'py>, name: &str) -> PyResult> { + static MOD: PyOnceLock> = PyOnceLock::new(); + MOD.get_or_try_init(py, || -> PyResult> { + Ok(py.import("django.utils.translation")?.into_any().unbind()) + })? + .bind(py) + .getattr(name) +} + +/// `CONTEXT_SEPARATOR in result` for a translation result. +fn has_ctx_sep(r: &Bound<'_, PyAny>) -> PyResult { + r.contains("\x04") +} + +/// Native `django.utils.translation.gettext` / `pgettext` / `ngettext` / +/// `npgettext` for plain `str` messages: once `_trans` has resolved the +/// function to `trans_real`, the active translation object's own method is +/// called directly (skipping the module functions and the asgiref `Local` +/// chain); `trans_null` is answered natively; anything else (unresolved, +/// patched, unreadable state) calls the real module function. The active +/// translation is read once per `Translator`, so callers making several +/// lookups for one value share it. +#[allow(clippy::option_option)] // not read / unreadable / set, like `local_value` +pub(crate) struct Translator<'py> { + py: Python<'py>, + /// `_active.value` read from its contextvar: outer `None` = not read + /// yet, `Some(None)` = unreadable. + active: std::cell::OnceCell>>>, +} + +impl<'py> Translator<'py> { + pub(crate) fn new(py: Python<'py>) -> Self { + Self { + py, + active: std::cell::OnceCell::new(), + } + } + + pub(crate) fn py(&self) -> Python<'py> { + self.py + } + + /// The translation `trans_real.` would use: `_active.value` when + /// set, else `_default`. An `_active.value` explicitly set to `None` is + /// skipped by `do_ntranslate` (`ntranslate`) but crashes `gettext`, so + /// the latter takes the Python path. `None` also for a patched `_trans`, + /// an unreadable `_active` or an unset `_default` (the Python function + /// then initializes it). + fn obj(&self, fname: &str, ntranslate: bool) -> PyResult>> { + static REAL: PyOnceLock> = PyOnceLock::new(); + let py = self.py; + match trans_impl(py, fname) { + None => return Ok(None), + Some(TransImpl::Null) => return Ok(Some(TransObj::Null)), + Some(TransImpl::Real) => {} + } + let active = self.active.get_or_init(|| { + let cvar = TRANS_ACTIVE.cvar(py)?; + local_value(py, &cvar) + }); + let Some(active) = active else { + return Ok(None); + }; + match active { + Some(a) if !a.is_none() => return Ok(Some(TransObj::Real(a.clone()))), + Some(_) if !ntranslate => return Ok(None), + _ => {} + } + let real = REAL + .get_or_try_init(py, || -> PyResult> { + Ok(py.import("django.utils.translation.trans_real")?.dict().unbind()) + })? + .bind(py); + Ok(match real.get_item("_default")? { + Some(d) if !d.is_none() => Some(TransObj::Real(d)), + _ => None, + }) + } + + /// `gettext(message)`. + pub(crate) fn gettext(&self, message: &str) -> PyResult> { + let py = self.py; + let eol = eol_normalize(message); + if !eol.is_empty() { + match self.obj("gettext", false)? { + Some(TransObj::Real(t)) => { + return t.call_method1(pyo3::intern!(py, "gettext"), (eol.as_ref(),)); + } + Some(TransObj::Null) => return Ok(PyString::new(py, message).into_any()), + None => {} + } + } + translation_fn(py, "gettext")?.call1((message,)) + } + + /// `pgettext(context, message)`. + pub(crate) fn pgettext(&self, context: &str, message: &str) -> PyResult> { + let py = self.py; + match self.obj("pgettext", false)? { + Some(TransObj::Null) => Ok(PyString::new(py, message).into_any()), + // `trans_real.pgettext` → its module-global `gettext` (never an + // empty message: it holds the separator). + Some(TransObj::Real(t)) => { + let ctxt = format!("{context}\x04{message}"); + let r = t.call_method1( + pyo3::intern!(py, "gettext"), + (eol_normalize(&ctxt).as_ref(),), + )?; + if has_ctx_sep(&r)? { + return Ok(PyString::new(py, message).into_any()); + } + Ok(r) + } + None => translation_fn(py, "pgettext")?.call1((context, message)), + } + } + + /// `ngettext(singular, plural, number)`. + pub(crate) fn ngettext( + &self, + singular: &str, + plural: &str, + number: &Bound<'py, PyAny>, + ) -> PyResult> { + let py = self.py; + match self.obj("ngettext", true)? { + Some(TransObj::Real(t)) => { + t.call_method1(pyo3::intern!(py, "ngettext"), (singular, plural, number)) + } + Some(TransObj::Null) => Ok(PyString::new( + py, + if number.eq(1)? { singular } else { plural }, + ) + .into_any()), + None => translation_fn(py, "ngettext")?.call1((singular, plural, number)), + } + } + + /// `npgettext(context, singular, plural, number)`. + pub(crate) fn npgettext( + &self, + context: &str, + singular: &str, + plural: &str, + number: &Bound<'py, PyAny>, + ) -> PyResult> { + let py = self.py; + match self.obj("npgettext", true)? { + // `trans_real.npgettext` → its module-global `ngettext` + // (`do_ntranslate`): the contextual pair, then the bare one when + // the result still holds the separator (untranslated). + Some(TransObj::Real(t)) => { + let name = pyo3::intern!(py, "ngettext"); + let r = t.call_method1( + name, + ( + format!("{context}\x04{singular}"), + format!("{context}\x04{plural}"), + number, + ), + )?; + if has_ctx_sep(&r)? { + return t.call_method1(name, (singular, plural, number)); + } + Ok(r) + } + Some(TransObj::Null) => Ok(PyString::new( + py, + if number.eq(1)? { singular } else { plural }, + ) + .into_any()), + None => translation_fn(py, "npgettext")?.call1((context, singular, plural, number)), + } + } +} + fn eol_normalize(s: &str) -> std::borrow::Cow<'_, str> { if s.contains('\r') { std::borrow::Cow::Owned(s.replace("\r\n", "\n").replace('\r', "\n")) diff --git a/src/nodes_py.rs b/src/nodes_py.rs index 9ff8fbf..a978b71 100644 --- a/src/nodes_py.rs +++ b/src/nodes_py.rs @@ -44,6 +44,8 @@ fn kind_name(kind: crate::tags::TagKind) -> &'static str { K::SimpleTag => "simple_tag", K::InclusionTag => "inclusion_tag", K::Translate => "translate", + K::Static => "static", + K::BlockTranslate => "blocktranslate", } } diff --git a/src/parser.rs b/src/parser.rs index 23376be..fe440db 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -225,6 +225,12 @@ impl<'a> Parser<'a> { .map(|f| f.clone_ref(py)) } + /// The remaining tokens in stream order (next first), for tag handlers + /// that validate a raw-token body before consuming it. + pub(crate) fn upcoming(&self) -> impl Iterator { + self.tokens.iter().rev() + } + /// `next_token` for tag handlers consuming their closing tags. pub(crate) fn next_token_pub(&mut self) -> Option { self.next_token() @@ -1018,6 +1024,24 @@ impl<'a> Parser<'a> { id, }); } + if let Some(payload) = crate::tags::parse::static_tag(py, self, func, token) { + let id = self.next_id; + self.next_id += 1; + return Ok(Node::Tag { + kind: TagKind::Static, + payload: Box::new(payload), + id, + }); + } + if let Some(payload) = crate::tags::i18n::parse(py, self, func, token) { + let id = self.next_id; + self.next_id += 1; + return Ok(Node::Tag { + kind: TagKind::BlockTranslate, + payload: Box::new(payload), + id, + }); + } if let Some(spec) = crate::tags::helper::helper_spec(py, func, self.ver) { if let Some(payload) = crate::tags::helper::parse(py, self, &spec, token) { let kind = match spec.kind { diff --git a/src/tags/blocks.rs b/src/tags/blocks.rs index 708cd0c..6223a78 100644 --- a/src/tags/blocks.rs +++ b/src/tags/blocks.rs @@ -151,6 +151,11 @@ fn simple_node(node: &Node) -> bool { TagPayload::Spaceless { body, .. } => body_is_simple(body), TagPayload::FirstOf { vars, asvar, .. } => asvar.is_none() && vars.iter().all(expr_ok), TagPayload::Lorem { count, .. } => expr_ok(count), + TagPayload::Static { path, varname, .. } => varname.is_none() && expr_ok(path), + // Pushes (and pops) its own layer; body keys are read verbatim. + TagPayload::BlockTranslate(bt) => { + bt.asvar.is_none() && !bt.reads_key("block") && bt.exprs().all(expr_ok) + } TagPayload::WidthRatio { val, max, width, asvar, .. } => { asvar.is_none() && expr_ok(val) && expr_ok(max) && expr_ok(width) } diff --git a/src/tags/i18n.rs b/src/tags/i18n.rs new file mode 100644 index 0000000..9ffa5d4 --- /dev/null +++ b/src/tags/i18n.rs @@ -0,0 +1,360 @@ +//! i18n `{% blocktranslate %}` / `{% blocktrans %}`: native port of +//! `django.templatetags.i18n.do_block_translate` and `BlockTranslateNode`, +//! taken only when the registered compile function is the stock one. +//! +//! Parsing is a dry run over the upcoming raw tokens first: any form that +//! would make the stock parser raise (or that it accepts by accident, such +//! as running out of tokens) compiles bridged instead, so every error comes +//! from the stock code. The message ids are fixed at parse time; rendering +//! resolves the `with`/`count`/`context` expressions, looks the messages up +//! through `filters::Translator` and `%`-formats with Python's own `%`. + +use pyo3::prelude::*; +use pyo3::sync::PyOnceLock; +use pyo3::types::{PyDict, PyString}; + +use super::{annotate, expr, expr_res_ign, with_scoped, Expr, TagPayload}; +use crate::error::syntax_error; +use crate::lexer::{split_contents, SplitContents, Token, TokenKind}; +use crate::parser::{token_kwargs, Parser}; +use crate::render::context::Rctx; +use crate::render::value; + +use super::simple::py_ws; + +/// Parsed `BlockTranslateNode`. +pub struct BlockTranslate { + /// `with` keyword arguments (`extra_context`), in order. + pub extra: Vec<(String, Expr)>, + /// Singular message id (`render_token_list(self.singular)`, trimmed). + pub singular: String, + /// Variable names of the singular message. + pub vars: Vec, + /// `count`: present only when the stock node would pluralize + /// (`self.plural and self.countervar and self.counter`). + pub plural: Option, + /// `context` expression (`message_context`). + pub context: Option, + pub asvar: Option, + /// `bits[0]` (`blocktranslate` or `blocktrans`). + pub tag_name: String, + pub token: Token, +} + +pub struct Plural { + pub countervar: String, + pub counter: Expr, + pub msg: String, + pub vars: Vec, +} + +impl BlockTranslate { + /// Every expression the node resolves. + pub(crate) fn exprs(&self) -> impl Iterator { + self.extra + .iter() + .map(|(_, e)| e) + .chain(self.plural.iter().map(|p| &p.counter)) + .chain(self.context.iter()) + } + + /// Whether rendering reads the context key `key` verbatim (message + /// variables are looked up with `key in context` / `context[key]`). + pub(crate) fn reads_key(&self, key: &str) -> bool { + self.vars + .iter() + .chain(self.plural.iter().flat_map(|p| p.vars.iter())) + .any(|v| v == key) + } +} + +fn py_strip(s: &str) -> &str { + s.trim_matches(py_ws) +} + +/// `render_token_list`: TEXT `%` doubled, VAR → `%(name)s`; `trimmed` +/// applies the real `translation.trim_whitespace`. +fn token_list(py: Python<'_>, tokens: &[&Token], trimmed: bool) -> PyResult<(String, Vec)> { + let mut msg = String::new(); + let mut vars = Vec::new(); + for t in tokens { + match t.kind { + TokenKind::Text => msg.push_str(&t.contents.replace('%', "%%")), + TokenKind::Var => { + msg.push_str("%("); + msg.push_str(&t.contents); + msg.push_str(")s"); + vars.push(t.contents.clone()); + } + _ => {} + } + } + if trimmed { + msg = py + .import("django.utils.translation")? + .getattr("trim_whitespace")? + .call1((msg,))? + .extract()?; + } + Ok((msg, vars)) +} + +/// Native `do_block_translate` for the stock compile function; `None` → +/// compile bridged (unsupported or erroneous forms). +#[allow(clippy::too_many_lines)] // one linear port of the stock function +pub(crate) fn parse( + py: Python<'_>, + p: &mut Parser<'_>, + func: &Bound<'_, PyAny>, + token: &Token, +) -> Option { + static DO_BLOCK_TRANSLATE: PyOnceLock>> = PyOnceLock::new(); + let (module, name) = ("django.templatetags.i18n", "do_block_translate"); + if !super::parse::is_stock_func(py, &DO_BLOCK_TRANSLATE, module, name, func) { + return None; + } + let SplitContents::Ok(bits) = split_contents(&token.contents) else { + return None; + }; + let mut remaining: Vec = bits[1..].to_vec(); + let mut seen: Vec = Vec::new(); + let mut extra = Vec::new(); + let mut count = None; + let mut context = None; + let mut trimmed = false; + let mut asvar = None; + while !remaining.is_empty() { + let option = remaining.remove(0); + if seen.contains(&option) { + return None; + } + match option.as_str() { + "with" => { + let v = token_kwargs(py, p, &mut remaining, true).ok()?; + if v.is_empty() { + return None; + } + extra = v; + } + "count" => { + let mut v = token_kwargs(py, p, &mut remaining, true).ok()?; + if v.len() != 1 { + return None; + } + count = v.pop(); + } + "context" => { + if remaining.is_empty() { + return None; + } + let v = remaining.remove(0); + context = Some(p.compile_filter(py, &v).ok()?); + } + "trimmed" => trimmed = true, + "asvar" => { + if remaining.is_empty() { + return None; + } + asvar = Some(remaining.remove(0)); + } + _ => return None, + } + seen.push(option); + } + let tag_name = bits[0].clone(); + let end_tag = format!("end{tag_name}"); + // Dry run over the raw tokens: (singular, [plural]) then the end tag. + let up: Vec<&Token> = p.upcoming().collect(); + let mut i = 0; + let body = |i: &mut usize| -> Option<(Vec<&Token>, &Token)> { + let start = *i; + loop { + let t = *up.get(*i)?; + *i += 1; + if matches!(t.kind, TokenKind::Var | TokenKind::Text) { + continue; + } + // Comment tokens compare their text in stock; stay bridged. + if t.kind != TokenKind::Block { + return None; + } + return Some((up[start..*i - 1].to_vec(), t)); + } + }; + let (singular, mut term) = body(&mut i)?; + let mut plural_tokens = Vec::new(); + if count.is_some() { + if py_strip(&term.contents) != "plural" { + return None; + } + let (pl, t) = body(&mut i)?; + plural_tokens = pl; + term = t; + } + if py_strip(&term.contents) != end_tag { + return None; + } + let (singular, vars) = token_list(py, &singular, trimmed).ok()?; + let plural = match count { + Some((countervar, counter)) if !plural_tokens.is_empty() => { + let (msg, pvars) = token_list(py, &plural_tokens, trimmed).ok()?; + Some(Plural { + countervar, + counter: expr(counter), + msg, + vars: pvars, + }) + } + _ => None, + }; + for _ in 0..i { + p.next_token_pub(); + } + Some(TagPayload::BlockTranslate(Box::new(BlockTranslate { + extra: extra.into_iter().map(|(k, c)| (k, expr(c))).collect(), + singular, + vars, + plural, + context: context.map(expr), + asvar, + tag_name, + token: token.clone(), + }))) +} + +fn decimal_type(py: Python<'_>) -> PyResult<&Bound<'_, PyAny>> { + static D: PyOnceLock> = PyOnceLock::new(); + Ok(D.get_or_try_init(py, || -> PyResult> { + Ok(py.import("decimal")?.getattr("Decimal")?.unbind()) + })? + .bind(py)) +} + +fn repr(py: Python<'_>, s: &str) -> PyResult { + Ok(PyString::new(py, s).repr()?.to_string()) +} + +/// `BlockTranslateNode.render(context, nested)`. +#[allow(clippy::too_many_lines)] // one linear port of the stock method +fn render<'py>(rctx: &mut Rctx<'py>, bt: &BlockTranslate, nested: bool) -> PyResult { + let py = rctx.py(); + let tr = crate::filters::Translator::new(py); + let message_context = match &bt.context { + Some(c) => Some(expr_res_ign(rctx, c, false)?), + None => None, + }; + let message_context = match message_context { + Some(mc) if mc.is_truthy()? => Some(mc.str()?.to_string()), + _ => None, + }; + let extra = PyDict::new(py); + for (k, e) in &bt.extra { + extra.set_item(k, expr_res_ign(rctx, e, false)?)?; + } + let mut result: Option> = None; + let data = PyDict::new(py); + with_scoped(rctx, &Some(extra.into_any()), |rctx| { + let mut vars: Vec<&String> = bt.vars.iter().collect(); + let translated = if let Some(pl) = &bt.plural { + let count = expr_res_ign(rctx, &pl.counter, false)?; + let numeric = count.is_instance(decimal_type(py)?)? + || count.is_instance_of::() + || count.is_instance_of::(); + if !numeric { + return Err(syntax_error( + py, + &format!( + "{} argument to {} tag must be a number.", + repr(py, &pl.countervar)?, + repr(py, &bt.tag_name)? + ), + )); + } + rctx.set_item(&pl.countervar, &count)?; + vars.extend(pl.vars.iter()); + match &message_context { + Some(c) => tr.npgettext(c, &bt.singular, &pl.msg, &count)?, + None => tr.ngettext(&bt.singular, &pl.msg, &count)?, + } + } else { + match &message_context { + Some(c) => tr.pgettext(c, &bt.singular)?, + None => tr.gettext(&bt.singular)?, + } + }; + let default_value = rctx.engine.getattr(pyo3::intern!(py, "string_if_invalid"))?; + for v in vars { + let val = if rctx.context_has(v)? { + rctx.get_item(v)?.unwrap_or_else(|| py.None().into_bound(py)) + } else if default_value.contains("%s")? { + default_value.rem(v)? + } else { + default_value.clone() + }; + let s = value::render_value_in_context(rctx, &val)?; + data.set_item(v, s)?; + } + result = Some(translated); + Ok(()) + })?; + let result = result.unwrap_or_else(|| PyString::new(py, "").into_any()); + let formatted = match result.rem(&data) { + Ok(r) => r.str()?.to_string(), + Err(e) + if e.is_instance_of::(py) + || e.is_instance_of::(py) => + { + if nested { + return Err(syntax_error( + py, + &format!( + "{} is unable to format string returned by gettext: {} using {}", + repr(py, &bt.tag_name)?, + result.repr()?, + data.repr()? + ), + )); + } + let ov = py + .import("django.utils.translation")? + .getattr("override")? + .call1((py.None(),))?; + ov.call_method0("__enter__")?; + let r = render(rctx, bt, true); + match &r { + Ok(_) => { + ov.call_method1("__exit__", (py.None(), py.None(), py.None()))?; + } + Err(e) => { + let exc = e.value(py); + ov.call_method1("__exit__", (exc.get_type(), exc, exc.getattr("__traceback__")?))?; + } + } + r? + } + Err(e) => return Err(e), + }; + if let Some(name) = &bt.asvar { + let v = value::mark_safe_bound(&PyString::new(py, &formatted).into_any())?; + rctx.set_item(name, &v)?; + return Ok(String::new()); + } + Ok(formatted) +} + +/// `BlockTranslateNode.render`. +pub(crate) fn block_translate(rctx: &mut Rctx<'_>, p: &TagPayload, out: &mut String) -> PyResult<()> { + let TagPayload::BlockTranslate(bt) = p else { + return Ok(()); + }; + match render(rctx, bt, false) { + Ok(s) => { + out.push_str(&s); + Ok(()) + } + Err(e) => { + annotate(rctx, &e, &bt.token); + Err(e) + } + } +} diff --git a/src/tags/mod.rs b/src/tags/mod.rs index e8932c9..b1dc8bd 100644 --- a/src/tags/mod.rs +++ b/src/tags/mod.rs @@ -15,6 +15,7 @@ pub(crate) mod blocks; pub(crate) mod cycle; pub(crate) mod fold; pub(crate) mod helper; +pub(crate) mod i18n; pub(crate) mod iter; pub(crate) mod loader; pub(crate) mod loadtags; @@ -75,6 +76,8 @@ pub enum TagKind { SimpleTag, InclusionTag, Translate, + Static, + BlockTranslate, } pub enum TagPayload { Block { @@ -186,6 +189,15 @@ pub enum TagPayload { asvar: Option, token: Token, }, + /// `{% static path [as varname] %}` (stock `do_static`). + Static { + path: Expr, + varname: Option, + token: Token, + }, + /// i18n `{% blocktranslate %}` / `{% blocktrans %}` (stock + /// `do_block_translate`), see `tags::i18n`. + BlockTranslate(Box), Lorem { count: Expr, method: String, @@ -520,6 +532,17 @@ fn scan_payload(p: &TagPayload, scan: &mut ForloopScan, depth: usize) { } } TagPayload::Lorem { count, .. } => scan_expr(count, scan, depth), + TagPayload::Static { path, .. } => scan_expr(path, scan, depth), + // Body variables are context keys looked up verbatim: only a bare + // `forloop` key reads the loop dict (all of it, when rendered). + TagPayload::BlockTranslate(bt) => { + for e in bt.exprs() { + scan_expr(e, scan, depth); + } + if bt.reads_key("forloop") { + scan.all(); + } + } TagPayload::Spaceless { body, .. } | TagPayload::PartialDef { body, .. } => { scan_nodelist(body, scan, depth); } @@ -722,6 +745,8 @@ fn payload_never_touches_rc(p: &TagPayload) -> bool { | TagPayload::Templatetag { .. } | TagPayload::Load { .. } | TagPayload::Translate { .. } + | TagPayload::Static { .. } + | TagPayload::BlockTranslate(_) | TagPayload::FirstOf { .. } | TagPayload::Now { .. } | TagPayload::Url { .. } @@ -903,6 +928,8 @@ fn dispatch( TagKind::Debug => simple::debug(rctx, p, out), TagKind::Now => simple::now(rctx, p, out), TagKind::Translate => simple::translate(rctx, p, out), + TagKind::Static => simple::static_tag(rctx, p, out), + TagKind::BlockTranslate => i18n::block_translate(rctx, p, out), TagKind::Lorem => simple::lorem(rctx, p, out), TagKind::Spaceless => simple::spaceless(rctx, p, out), TagKind::Templatetag => { diff --git a/src/tags/parse.rs b/src/tags/parse.rs index 2ad6050..a208cb7 100644 --- a/src/tags/parse.rs +++ b/src/tags/parse.rs @@ -978,3 +978,54 @@ pub(crate) fn debug(_py: Python<'_>, _p: &mut Parser<'_>, token: &Token) -> Res }) } + +/// `true` iff `func` is the stock compile function `module.name`. +pub(crate) fn is_stock_func( + py: Python<'_>, + cell: &'static pyo3::sync::PyOnceLock>>, + module: &str, + name: &str, + func: &Bound<'_, PyAny>, +) -> bool { + let stock = cell.get_or_init(py, || { + py.import(module) + .and_then(|m| m.getattr(name)) + .ok() + .map(Bound::unbind) + }); + stock.as_ref().is_some_and(|f| func.is(f.bind(py))) +} + +/// `{% static path [as varname] %}` when `func` is the stock `do_static` +/// (`StaticNode.handle_token`); `None` (compile bridged, which raises the +/// stock errors) for a missing path, an `as` without a name or a path that +/// does not compile. +pub(crate) fn static_tag( + py: Python<'_>, + p: &Parser<'_>, + func: &Bound<'_, PyAny>, + token: &Token, +) -> Option { + static DO_STATIC: pyo3::sync::PyOnceLock>> = pyo3::sync::PyOnceLock::new(); + if !is_stock_func(py, &DO_STATIC, "django.templatetags.static", "do_static", func) { + return None; + } + let SplitContents::Ok(bits) = split_contents(&token.contents) else { + return None; + }; + if bits.len() < 2 { + return None; + } + let path = p.compile_filter(py, &bits[1]).ok()?; + // `if len(bits) >= 2 and bits[-2] == "as": varname = bits[3]`. + let varname = if bits[bits.len() - 2] == "as" { + Some(bits.get(3)?.clone()) + } else { + None + }; + Some(TagPayload::Static { + path: expr(path), + varname, + token: token.clone(), + }) +} diff --git a/src/tags/simple.rs b/src/tags/simple.rs index 0d46592..c26b6b3 100644 --- a/src/tags/simple.rs +++ b/src/tags/simple.rs @@ -897,3 +897,191 @@ pub(crate) fn regroup(rctx: &mut Rctx<'_>, p: &TagPayload, out: &mut String) -> } } } + +/// Stock objects behind `StaticNode.handle_simple`. +struct StaticBits { + /// `StaticNode.__dict__` (a live view): `handle_simple` must still be + /// the stock classmethod. + node_dict: Py, + handle_simple_raw: Py, + /// Bound `StaticNode.handle_simple` (the Python path). + handle_simple: Py, + apps: Py, + /// `FileSystemStorage.url` and the exact `StaticFilesStorage` class. + fs_url: Py, + sf_storage_cls: Py, + sf_module: Py, +} + +fn static_bits(py: Python<'_>) -> PyResult<&'static StaticBits> { + static B: PyOnceLock = PyOnceLock::new(); + B.get_or_try_init(py, || -> PyResult { + let node = py.import("django.templatetags.static")?.getattr("StaticNode")?; + let node_dict = node.getattr("__dict__")?; + let sf = py.import("django.contrib.staticfiles.storage")?; + Ok(StaticBits { + handle_simple_raw: node_dict.get_item("handle_simple")?.unbind(), + node_dict: node_dict.unbind(), + handle_simple: node.getattr("handle_simple")?.unbind(), + apps: py.import("django.apps")?.getattr("apps")?.unbind(), + fs_url: py + .import("django.core.files.storage")? + .getattr("FileSystemStorage")? + .getattr("url")? + .unbind(), + sf_storage_cls: sf.getattr("StaticFilesStorage")?.unbind(), + sf_module: sf.dict().unbind(), + }) + }) +} + +/// `apps.is_installed("django.contrib.staticfiles")`, cached per +/// `apps.app_configs` dict (`set_installed_apps` / `unset_installed_apps` +/// swap the dict; the cache holds a reference so identity is reliable). +struct InstalledCache { + configs: Py, + len: usize, + installed: bool, +} + +/// `staticfiles_storage.url(path)` results for the stock +/// `StaticFilesStorage`, keyed by `(base_url, path)`: its `url` is +/// `FileSystemStorage.url`, a pure function of those two once the +/// `base_url` cached property is populated (`setting_changed` deletes it, +/// which changes the key). +struct StaticUrlMemo { + map: HashMap<(String, String), Py>, +} + +const STATIC_URL_MEMO_CAP: usize = 4096; + +/// `StaticNode.handle_simple(path)`: the real classmethod unless it is the +/// stock one, staticfiles is installed and `staticfiles_storage` is the +/// stock `StaticFilesStorage`, whose `url` results are memoized (first use +/// of each `(base_url, path)` still calls the real `storage.url`). +fn static_handle_simple<'py>(py: Python<'py>, path: &Bound<'py, PyAny>) -> PyResult> { + static INSTALLED: std::sync::Mutex> = std::sync::Mutex::new(None); + static MEMO: std::sync::Mutex> = std::sync::Mutex::new(None); + let Ok(b) = static_bits(py) else { + return py + .import("django.templatetags.static")? + .getattr("StaticNode")? + .call_method1("handle_simple", (path,)); + }; + let python = || b.handle_simple.bind(py).call1((path,)); + let stock = b + .node_dict + .bind(py) + .get_item("handle_simple") + .is_ok_and(|h| h.is(b.handle_simple_raw.bind(py))); + // Exact `str` or `SafeString` (template literals): `FileSystemStorage.url` + // only uses `str` operations whose results are plain `str` either way. + let path_str = match path.cast_exact::() { + Ok(s) => s.clone(), + Err(_) if path.get_type().is(helpers(py)?.safe_string.bind(py)) => { + path.cast::()?.clone() + } + Err(_) => return python(), + }; + if !stock { + return python(); + } + // `apps.is_installed("django.contrib.staticfiles")`. + let apps = b.apps.bind(py); + let configs = apps.getattr(pyo3::intern!(py, "app_configs"))?; + let len = configs.len()?; + let installed = { + let cached = INSTALLED.lock().ok().and_then(|g| { + g.as_ref() + .filter(|c| c.configs.bind(py).is(&configs) && c.len == len) + .map(|c| c.installed) + }); + if let Some(v) = cached { + v + } else { + let v = apps + .call_method1("is_installed", ("django.contrib.staticfiles",))? + .is_truthy()?; + if let Ok(mut g) = INSTALLED.lock() { + *g = Some(InstalledCache { + configs: configs.unbind(), + len, + installed: v, + }); + } + v + } + }; + if !installed { + return python(); + } + // `from django.contrib.staticfiles.storage import staticfiles_storage` + // (the module global, read live), then the LazyObject's `_wrapped`. + let Some(lazy) = b.sf_module.bind(py).get_item("staticfiles_storage")? else { + return python(); + }; + let storage = lazy + .getattr(pyo3::intern!(py, "__dict__")) + .ok() + .and_then(|d| d.get_item("_wrapped").ok()); + let key = storage.as_ref().and_then(|s| { + if !s.get_type().is(b.sf_storage_cls.bind(py)) { + return None; + } + if !s.get_type().getattr("url").ok()?.is(b.fs_url.bind(py)) { + return None; + } + let d = s.getattr(pyo3::intern!(py, "__dict__")).ok()?; + if d.contains("url").ok()? { + return None; + } + let base = d.get_item("base_url").ok()?; + let base = base.cast_exact::().ok()?.to_str().ok()?.to_owned(); + Some((base, path_str.to_str().ok()?.to_owned())) + }); + if let Some(key) = &key { + if let Ok(g) = MEMO.lock() { + if let Some(v) = g.as_ref().and_then(|m| m.map.get(key)) { + return Ok(v.bind(py).clone()); + } + } + } + let url = lazy.call_method1(pyo3::intern!(py, "url"), (path,))?; + if let Some(key) = key { + if let Ok(mut g) = MEMO.lock() { + let m = g.get_or_insert_with(|| StaticUrlMemo { map: HashMap::new() }); + if m.map.len() >= STATIC_URL_MEMO_CAP { + m.map.clear(); + } + m.map.insert(key, url.clone().unbind()); + } + } + Ok(url) +} + +/// `StaticNode.render`. +pub(crate) fn static_tag(rctx: &mut Rctx<'_>, p: &TagPayload, out: &mut String) -> PyResult<()> { + let TagPayload::Static { path, varname, token } = p else { + return Ok(()); + }; + let res = (|| -> PyResult<()> { + let py = rctx.py(); + let path = expr_res(rctx, path)?; + let url = static_handle_simple(py, &path)?; + let ae = rctx.autoescape()?; + match varname { + None if ae => out.push_str(&value::conditional_escape_str(&url)?), + None => out.push_str(&py_str_of(&url)?), + Some(name) => { + let v = if ae { + helpers(py)?.conditional_escape.bind(py).call1((url,))? + } else { + url + }; + rctx.set_item(name, &v)?; + } + } + Ok(()) + })(); + res.inspect_err(|e| annotate(rctx, e, token)) +} diff --git a/tests/test_realpage.py b/tests/test_realpage.py index 6501681..d04040d 100644 --- a/tests/test_realpage.py +++ b/tests/test_realpage.py @@ -15,6 +15,7 @@ from django.template.engine import Engine as StockEngine from django.test.utils import override_settings from django.utils import timezone, translation +from django.utils.functional import empty from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy, pgettext_lazy @@ -25,6 +26,7 @@ LIBS = { "i18n": "django.templatetags.i18n", "humanize": "django.contrib.humanize.templatetags.humanize", + "static": "django.templatetags.static", } ENGINES = {"stock": StockEngine(libraries=LIBS), "rust": RustEngine(libraries=LIBS)} LANGS = [None, "de", "fr", "es", "ja"] @@ -224,3 +226,255 @@ def test_dates_mixed_trans_resolution(): finally: _trans.__dict__.clear() _trans.__dict__.update(saved) + + +NT_NOW = datetime.datetime(2012, 3, 9, 22, 30) + + +class MockDateTime(datetime.datetime): + """humanize_tests' fixed clock (`humanize.datetime` is patched).""" + + @classmethod + def now(cls, tz=None): + if tz is None or tz.utcoffset(NT_NOW) is None: + return NT_NOW + return NT_NOW.replace(tzinfo=tz) + tz.utcoffset(NT_NOW) + + +class NaiveTZ(datetime.tzinfo): + def utcoffset(self, dt): + return None + + +NT_DELTAS = [ + datetime.timedelta(0), + datetime.timedelta(microseconds=1), + datetime.timedelta(seconds=1), + datetime.timedelta(seconds=30), + datetime.timedelta(minutes=1, seconds=30), + datetime.timedelta(minutes=2), + datetime.timedelta(hours=1, minutes=30, seconds=30), + datetime.timedelta(hours=23, minutes=50, seconds=50), + datetime.timedelta(days=1), + datetime.timedelta(days=2, hours=6), + datetime.timedelta(days=9, seconds=1), + datetime.timedelta(days=30), + datetime.timedelta(days=61, minutes=3), + datetime.timedelta(days=500), + datetime.timedelta(days=865, microseconds=999999), + datetime.timedelta(days=3653), +] + + +def naturaltime_values(): + vals = [] + for d in NT_DELTAS: + vals += [NT_NOW - d, NT_NOW + d] + chicago = zoneinfo.ZoneInfo("America/Chicago") + for d in NT_DELTAS[::3]: + vals += [ + (NT_NOW - d).replace(tzinfo=datetime.timezone.utc), + (NT_NOW + d).replace(tzinfo=chicago), + (NT_NOW - d).replace(tzinfo=zoneinfo.ZoneInfo("Asia/Kolkata")), + ] + vals += [ + NT_NOW.replace(tzinfo=NaiveTZ()), + datetime.datetime(2012, 1, 31, 12), + datetime.datetime(2011, 2, 28, 23, 59, 59, 999999), + datetime.datetime(2012, 2, 29, 22, 30), + datetime.date(2012, 3, 1), + "test", + None, + 0, + ] + return vals + + +@pytest.mark.parametrize("use_tz", [True, False]) +@pytest.mark.parametrize("lang", [None, "de", "cs", "fr", "ja", "ru", "ar"]) +def test_naturaltime(lang, use_tz): + from django.contrib.humanize.templatetags import humanize + + src = "{% load humanize %}{% for v in vals %}[{{ v|naturaltime }}|{{ v|naturaltime|length }}]{% endfor %}" + orig = humanize.datetime + humanize.datetime = MockDateTime + try: + with override_settings(USE_TZ=use_tz): + for v in naturaltime_values(): + assert_parity(src, {"vals": [v]}, lang=lang) + finally: + humanize.datetime = orig + + +def test_naturaltime_real_clock(): + now = timezone.now() + vals = [now - datetime.timedelta(days=3, hours=5, seconds=30), now + datetime.timedelta(days=40, seconds=30), + timezone.make_naive(now) - datetime.timedelta(hours=5, seconds=30)] + src = "{% load humanize %}{% for v in vals %}[{{ v|naturaltime }}]{% endfor %}" + for lang in [None, "de", "pl"]: + assert_parity(src, {"vals": vals}, lang=lang) + + +def test_naturaltime_i18n_off(): + from django.contrib.humanize.templatetags import humanize + + orig = humanize.datetime + humanize.datetime = MockDateTime + try: + with override_settings(USE_I18N=False): + src = "{% load humanize %}{% for v in vals %}[{{ v|naturaltime }}]{% endfor %}" + assert_parity(src, {"vals": naturaltime_values()}, lang="de") + finally: + humanize.datetime = orig + + +BT_ENGINES = { + name: { + "stock": StockEngine(libraries=LIBS, string_if_invalid=sii), + "rust": RustEngine(libraries=LIBS, string_if_invalid=sii), + } + for name, sii in [("blank", ""), ("invalid", "INV(%s)"), ("plain-invalid", "INV")] +} + +BLOCKTRANS_CASES = { + "plain": "{% blocktranslate %}Hello & {{ name }}!{% endblocktranslate %}", + "with": "{% blocktranslate with n=name|upper m=html %}{{ n }}: {{ m }}{% endblocktranslate %}", + "legacy-with": "{% blocktrans with name as n and html as m %}{{ n }}/{{ m }}{% endblocktrans %}", + "count": ( + "{% for c in counts %}{% blocktranslate count n=c %}{{ n }} item{% plural %}{{ n }} items" + "{% endblocktranslate %};{% endfor %}" + ), + "legacy-count": "{% blocktrans count counts|length as n %}one {{ n }}{% plural %}{{ n }} many{% endblocktrans %}", + "count-with": ( + "{% blocktranslate with who=name count n=counts.2 %}{{ who }} has {{ n }} cat" + "{% plural %}{{ who }} has {{ n }} cats{% endblocktranslate %}" + ), + "catalog-plural": ( + "{% for c in counts %}{% blocktranslate count max=c %}Ensure that there are no more than " + "{{ max }} digit in total.{% plural %}Ensure that there are no more than {{ max }} digits " + "in total.{% endblocktranslate %}|{% endfor %}" + ), + "catalog": ( + "{% blocktranslate with model_name=name field_label='x' %}{{ model_name }} with this " + "{{ field_label }} already exists.{% endblocktranslate %}" + ), + "context": "{% blocktranslate context 'abbrev. month' %}May{% endblocktranslate %}", + "context-var": "{% blocktranslate context ctx %}May{% endblocktranslate %}", + "context-empty": "{% blocktranslate context '' %}May{% endblocktranslate %}", + "context-count": ( + "{% blocktranslate context 'month name' count n=1 %}May{% plural %}Mays" + "{% endblocktranslate %}" + ), + "trimmed": ( + "{% blocktranslate trimmed with n=name %}\n Hello\n {{ n }} \n\n world\n" + "{% endblocktranslate %}" + ), + "asvar": "{% blocktranslate asvar v with n=html %}<{{ n }}>{% endblocktranslate %}[{{ v }}|{{ v|upper }}]", + "asvar-count": ( + "{% blocktranslate count n=3 asvar v %}a{% plural %}{{ n }} b{% endblocktranslate %}" + "[{{ v }}]{{ n }}" + ), + "percent": "{% blocktranslate %}100% of {{ pct }}%% done{% endblocktranslate %}", + "missing": "{% blocktranslate %}[{{ nope }}][{{ name.upper }}][{{ a.b }}]{% endblocktranslate %}", + "values": ( + "{% blocktranslate with d=day f=flt dt=aware %}{{ d }} {{ f }} {{ dt }} {{ lazy }} {{ none }}" + "{% endblocktranslate %}" + ), + "autoescape-off": ( + "{% autoescape off %}{% blocktranslate with h=html %}{{ h }} {{ name }}{% endblocktranslate %}" + "{% endautoescape %}" + ), + "empty": "[{% blocktranslate %}{% endblocktranslate %}]", + "empty-plural": "{% blocktranslate count n=2 %}one {{ n }}{% plural %}{% endblocktranslate %}[{{ n }}]", + "forloop": "{% for x in counts %}{% blocktranslate %}{{ forloop }}{{ x }}{% endblocktranslate %}{% endfor %}", + "nested-in-with": ( + "{% with name='inner' %}{% blocktranslate with name=name|add:'!' %}{{ name }}" + "{% endblocktranslate %}{{ name }}{% endwith %}{{ name }}" + ), + "decimal-count": ( + "{% blocktranslate count n=dec %}{{ n }} unit{% plural %}{{ n }} units{% endblocktranslate %}" + "{% blocktranslate count n=flt %}{{ n }} unit{% plural %}{{ n }} units{% endblocktranslate %}" + ), + # Render-time errors. + "count-not-number": "{% blocktranslate count n=name %}a{% plural %}b{% endblocktranslate %}", + "bad-format": "{% blocktranslate %}x {{ a) }}{% endblocktranslate %}", + "bad-format-asvar": "{% blocktranslate asvar v %}x {{ a) }}{% endblocktranslate %}[{{ v }}]", + # Compile errors (stock parser messages). + "unknown-option": "{% blocktranslate foo %}x{% endblocktranslate %}", + "dup-option": "{% blocktranslate trimmed trimmed %}x{% endblocktranslate %}", + "with-empty": "{% blocktranslate with %}x{% endblocktranslate %}", + "count-two": "{% blocktranslate count a=1 b=2 %}x{% plural %}y{% endblocktranslate %}", + "context-missing": "{% blocktranslate context %}x{% endblocktranslate %}", + "asvar-missing": "{% blocktranslate asvar %}x{% endblocktranslate %}", + "no-plural": "{% blocktranslate count n=1 %}x{% endblocktranslate %}", + "inner-tag": "{% blocktranslate %}x{% if 1 %}y{% endif %}{% endblocktranslate %}", + "plural-without-count": "{% blocktranslate %}x{% plural %}y{% endblocktranslate %}", + "comment": "{% blocktranslate %}x{# c #}y{% endblocktranslate %}", + "unclosed": "{% blocktranslate %}x {{ name }}", + "unclosed-plural": "{% blocktranslate count n=1 %}x{% plural %}y", + "wrong-end": "{% blocktrans %}x{% endblocktranslate %}", + "bad-filter": "{% blocktranslate with a=b|nofilter %}x{% endblocktranslate %}", +} + + +@pytest.mark.parametrize("sii", BT_ENGINES) +@pytest.mark.parametrize("lang", LANGS + ["pl"]) +@pytest.mark.parametrize("src", BLOCKTRANS_CASES.values(), ids=BLOCKTRANS_CASES.keys()) +def test_blocktranslate(src, lang, sii): + ctx = { + "name": "Ann", + "html": "&", + "counts": [0, 1, 2, 5, 21, 112], + "ctx": "abbrev. month", + "pct": 50, + "day": datetime.date(2024, 2, 29), + "flt": 1.5, + "dec": Decimal("1.0"), + "aware": AWARE, + "lazy": gettext_lazy("Yes"), + "none": None, + } + engines = BT_ENGINES[sii] + + def run(engine): + with translation.override(lang): + return engine.from_string("{% load i18n %}" + src).render(Context(ctx)) + + assert capture(lambda: run(engines["rust"])) == capture(lambda: run(engines["stock"])) + + +def test_blocktranslate_i18n_off(): + with override_settings(USE_I18N=False): + for src in list(BLOCKTRANS_CASES.values())[:14]: + assert_parity("{% load i18n %}" + src, {"name": "Ann", "counts": [1, 2, 3], "ctx": "x"}, lang="de") + + +STATIC_CASES = [ + "{% static 'css/site.css' %}", + "{% static path %}|{% static path %}", + "{% static 'a b/ü?x=1&y=2#f' %}", + "{% static '/abs/x.js' %}|{% static '' %}|{% static '../up.css' %}", + "{% static 'x.css' as u %}[{{ u }}]{% autoescape off %}{% static amp %}{% endautoescape %}", + "{% static amp as u %}[{{ u }}]", + "{% static amp %}", + "{% static missing %}", + "{% static num %}", + "{% static %}", + "{% static 'x' as %}", + "{% static 'x' extra bits %}", + "{% static 'x'|upper %}", +] + + +@pytest.mark.parametrize("installed", [True, False]) +@pytest.mark.parametrize("static_url", ["/static/", "https://cdn.example.com/s/", "/st&tic/"]) +@pytest.mark.parametrize("src", STATIC_CASES) +def test_static(src, static_url, installed): + from django.contrib.staticfiles.storage import staticfiles_storage + + apps = ["django.contrib.staticfiles"] if installed else [] + ctx = {"path": "img/logo.png", "amp": "a&b.css", "num": 7} + with override_settings(INSTALLED_APPS=apps, STATIC_URL=static_url): + # `STATIC_URL` is read when the storage is set up. + staticfiles_storage._wrapped = empty + assert_parity("{% load static %}" + src, ctx) From 42eac21d4d86544b1e6f3535588e23444fdd6746 Mon Sep 17 00:00:00 2001 From: Mason Lyons Date: Sat, 17 Oct 2026 23:57:28 +0000 Subject: [PATCH 2/2] Release 0.4.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 +- Cargo.toml | 2 +- pyproject.toml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 972a241..0a5ae28 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -212,7 +212,7 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "dtl" -version = "0.3.3" +version = "0.4.0" dependencies = [ "chrono", "criterion", diff --git a/Cargo.toml b/Cargo.toml index 31bdfec..171d006 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ members = ["."] [workspace.package] -version = "0.3.3" +version = "0.4.0" edition = "2021" [package] diff --git a/pyproject.toml b/pyproject.toml index 52a2260..8b4b14d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "maturin" [project] name = "django-rust-templates" -version = "0.3.3" +version = "0.4.0" description = "A drop-in Django template engine implemented natively in Rust" readme = "README.md" requires-python = ">=3.12"