Skip to main content

larust_lang/
lib.rs

1//! Localization - Laravel's `__('messages.welcome')`/`resources/lang/`,
2//! narrowed to what a translation actually needs: a flat, per-locale
3//! key -> string map, `:name`-style placeholder substitution, and a
4//! current-locale/fallback-locale chain. No `@lang(...)` Blade directive -
5//! deliberately: `t(key)`/`t_with(key, params)` are plain functions, so
6//! `{{ t("messages.welcome") }}` already works through the *existing*
7//! `{{ }}` expression mechanism (any real Rust expression), with zero
8//! changes needed to `larust-view`'s parser/AST/codegen - the same
9//! "explicit Rust expression, no new template syntax" reasoning
10//! `@can`/`@role` already established for permission checks. A dedicated
11//! directive is a reasonable later addition, not a blocker for this to be
12//! useful today.
13//!
14//! ## Translation files
15//!
16//! `resources/lang/{locale}.json`, one flat object per locale (dot-
17//! namespaced keys, e.g. `"messages.welcome"`, are just an ordinary key -
18//! there's no real per-file namespacing the way Laravel's PHP-array style
19//! has, keeping the loader a single, simple format instead of two):
20//!
21//! ```json
22//! { "messages.welcome": "Welcome to :app!" }
23//! ```
24//!
25//! Read once, lazily, from disk (CWD-relative - the same convention
26//! `.env` loading already uses elsewhere in this framework, not
27//! `AppPaths`-aware yet) and cached for the rest of the process - an app
28//! with no `resources/lang/` directory at all still works, every [`t`]
29//! call simply returns its own key unchanged (Laravel's own `__()`
30//! behavior for a missing translation - never a blank string).
31//!
32//! ## Pluralization
33//!
34//! A translated template containing `|` is treated as Laravel's own
35//! `trans_choice` syntax, chosen by a `:count` param - see [`t_with`]'s own
36//! doc comment for the two supported forms. Automatic, not a separate
37//! function: a plain string (no `|`) behaves exactly as it always has.
38//!
39//! ## Current locale
40//!
41//! [`current_locale`] reads a task-local override if one's been set (see
42//! [`with_locale_scope`]/[`set_current_locale`] - `larust_http::locale
43//! ::negotiate` sets this from the session, once wired in), falling back
44//! to `Config::app_locale` otherwise. An app that never wires the
45//! negotiation middleware at all still gets a fully working single-locale
46//! [`t`]/[`t_with`] - the scope only matters for *per-request* overrides.
47
48use std::cell::RefCell;
49use std::collections::HashMap;
50use std::future::Future;
51use std::path::Path;
52use std::sync::OnceLock;
53
54tokio::task_local! {
55    static LOCALE_OVERRIDE: RefCell<Option<String>>;
56}
57
58/// Establishes a fresh, unset locale-override scope around `fut` - call
59/// once per HTTP request (see `larust_http::locale::negotiate`, which
60/// wraps this together with its own session lookup). Opt-in, unlike
61/// `larust_view::push_registry`'s own always-on scope: [`current_locale`]
62/// already degrades correctly with no scope established at all (falls
63/// back to `Config::app_locale`), so there's nothing to lose by only
64/// paying for this where an app actually wires locale negotiation in.
65pub async fn with_locale_scope<F: Future>(fut: F) -> F::Output {
66    LOCALE_OVERRIDE.scope(RefCell::new(None), fut).await
67}
68
69/// Overrides the current request's locale for the rest of
70/// [`with_locale_scope`]'s own future - a no-op outside an established
71/// scope (the same "inert outside a scope" contract
72/// `larust_view::push_registry::record` already has).
73pub fn set_current_locale(locale: String) {
74    let _ = LOCALE_OVERRIDE.try_with(|cell| {
75        *cell.borrow_mut() = Some(locale);
76    });
77}
78
79/// `Config::app_locale`/`app_fallback_locale`'s own default - duplicated
80/// here (rather than made `pub` on `Config` itself) since [`current_locale`]
81/// and [`lookup`] both need a locale to resolve against even when
82/// `Application::new()` was never called at all (see their own doc
83/// comments for why that has to keep working, not panic).
84const DEFAULT_LOCALE: &str = "en";
85
86/// The locale [`t`]/[`t_with`] resolve against right now - the current
87/// request's override if [`set_current_locale`] was called inside an
88/// established [`with_locale_scope`], else `Config::app_locale` - falling
89/// back further still to [`DEFAULT_LOCALE`] if `Application::new()` was
90/// never called at all (`larust_core::config()` panics in that case;
91/// `try_config()` doesn't). A validation rule (see `larust-validation`,
92/// the first real caller of [`t_or`]) has to keep working in a bare unit
93/// test that never sets up an `Application` - the exact scenario this
94/// guards.
95pub fn current_locale() -> String {
96    LOCALE_OVERRIDE
97        .try_with(|cell| cell.borrow().clone())
98        .ok()
99        .flatten()
100        .unwrap_or_else(|| {
101            larust_core::try_config()
102                .map(|config| config.app_locale.clone())
103                .unwrap_or_else(|| DEFAULT_LOCALE.to_string())
104        })
105}
106
107fn catalog() -> &'static HashMap<String, HashMap<String, String>> {
108    static CATALOG: OnceLock<HashMap<String, HashMap<String, String>>> = OnceLock::new();
109    CATALOG.get_or_init(|| load_catalog_from(Path::new("resources/lang")))
110}
111
112/// The actual directory scan behind [`catalog`], split out so it's
113/// unit-testable against a real, isolated `tempfile::tempdir()` rather
114/// than the real CWD-relative `resources/lang` every process-wide
115/// [`catalog`] call is stuck with for its own lifetime. A missing
116/// directory, an unreadable file, or a file that isn't a flat
117/// `{"key": "value"}` JSON object are all silently skipped rather than
118/// erroring - a translation file is optional, non-critical content, not
119/// something a bad file should be able to crash boot over.
120fn load_catalog_from(dir: &Path) -> HashMap<String, HashMap<String, String>> {
121    let mut catalog = HashMap::new();
122    let Ok(entries) = std::fs::read_dir(dir) else {
123        return catalog;
124    };
125    for entry in entries.flatten() {
126        let path = entry.path();
127        if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
128            continue;
129        }
130        let Some(locale) = path.file_stem().and_then(|stem| stem.to_str()) else {
131            continue;
132        };
133        let Ok(contents) = std::fs::read_to_string(&path) else {
134            continue;
135        };
136        let Ok(map) = serde_json::from_str::<HashMap<String, String>>(&contents) else {
137            continue;
138        };
139        catalog.insert(locale.to_string(), map);
140    }
141    catalog
142}
143
144/// The raw translated template for `key`, if either the current locale or
145/// `Config::app_fallback_locale` has one - shared lookup behind
146/// [`t_with`]/[`t_or_with`], which only differ in what they fall back to
147/// when this returns `None`.
148fn lookup(key: &str) -> Option<&'static str> {
149    let catalog = catalog();
150    let locale = current_locale();
151    // Same non-panicking fallback as `current_locale` itself, and for the
152    // same reason - see its own doc comment.
153    let fallback_locale = larust_core::try_config()
154        .map(|config| config.app_fallback_locale.clone())
155        .unwrap_or_else(|| DEFAULT_LOCALE.to_string());
156    catalog
157        .get(&locale)
158        .and_then(|entries| entries.get(key))
159        .or_else(|| {
160            catalog
161                .get(&fallback_locale)
162                .and_then(|entries| entries.get(key))
163        })
164        .map(String::as_str)
165}
166
167/// `key` looked up against the current locale, falling back to
168/// `Config::app_fallback_locale`, falling back to `key` itself unchanged -
169/// Laravel's own `__('messages.welcome')` behavior exactly, including
170/// "never a blank string" for a genuinely missing translation.
171pub fn t(key: &str) -> String {
172    t_with(key, &[])
173}
174
175/// [`t`], substituting `:name`-style placeholders from `params` - Laravel's
176/// own `__('messages.greeting', ['name' => 'Alice'])` convention
177/// (`:name` in the translated string, not `{name}`/`{{name}}`).
178///
179/// Also resolves pluralization if the translated template contains a `|`
180/// (see [`pluralize`]'s own doc comment for the two supported forms) -
181/// checked against a `:count` param before any placeholder substitution
182/// happens, so `:count` itself is still available to interpolate into
183/// whichever segment gets picked.
184pub fn t_with(key: &str, params: &[(&str, &str)]) -> String {
185    substitute(pluralize(lookup(key).unwrap_or(key), params), params)
186}
187
188/// Like [`t`], but falls back to `default` - not the bare `key` - when
189/// neither the current nor the fallback locale has a translation for it.
190/// For a caller that already has its own sensible, hardcoded message (a
191/// framework-shipped validation rule, say) and wants it to stay overridable
192/// by a real translation file without an unresolved, literal key ever
193/// reaching a user whose app hasn't defined one - unlike [`t`], where an
194/// app that deliberately wants "no translation yet" to be visibly obvious
195/// relies on the key itself showing through.
196pub fn t_or(key: &str, default: &str) -> String {
197    t_or_with(key, default, &[])
198}
199
200/// [`t_or`], substituting `:name`-style placeholders from `params` - the
201/// same relationship [`t_with`] has to [`t`].
202pub fn t_or_with(key: &str, default: &str, params: &[(&str, &str)]) -> String {
203    substitute(pluralize(lookup(key).unwrap_or(default), params), params)
204}
205
206/// Laravel's `trans_choice` pluralization, folded directly into
207/// [`t_with`]/[`t_or_with`] rather than a separate function - a template
208/// with no `|` in it (the overwhelming majority of keys) is returned
209/// completely unchanged, so this is a no-op for every key this crate
210/// already had before pluralization existed.
211///
212/// Two forms, matching Laravel's own:
213/// - `"apple|apples"` - simple singular/plural, chosen by whether the
214///   `:count` param parses to exactly `1`.
215/// - `"{0} no apples|{1} one apple|[2,*] :count apples"` - explicit
216///   selectors, each segment prefixed by `{n}` (an exact count) or
217///   `[n,*]`/`[n,m]` (an inclusive range, `*` meaning unbounded), checked
218///   in order against `:count`.
219///
220/// Degrades to the *last* segment whenever something doesn't line up (no
221/// `:count` param, a `:count` that doesn't parse as an integer, or no
222/// selector matching it) - the same "never panic, worst case slightly
223/// imprecise text" convention [`t`]'s own missing-key fallback already
224/// established, rather than erroring out over a formatting mistake in a
225/// translation file.
226fn pluralize<'a>(template: &'a str, params: &[(&str, &str)]) -> &'a str {
227    if !template.contains('|') {
228        return template;
229    }
230    let segments: Vec<&str> = template.split('|').collect();
231    let count: Option<i64> = params
232        .iter()
233        .find(|(name, _)| *name == "count")
234        .and_then(|(_, value)| value.parse().ok());
235
236    // The simple two-form shorthand - neither segment uses an explicit
237    // `{n}`/`[n,*]` selector at all.
238    if segments.len() == 2 && parse_selector(segments[0]).is_none() {
239        return match count {
240            Some(1) => segments[0],
241            _ => segments[1],
242        };
243    }
244
245    let Some(count) = count else {
246        return segments
247            .last()
248            .expect("split always yields at least one segment");
249    };
250    for segment in &segments {
251        if let Some((selector, rest)) = parse_selector(segment) {
252            if selector.matches(count) {
253                return rest;
254            }
255        }
256    }
257    segments
258        .last()
259        .expect("split always yields at least one segment")
260}
261
262enum PluralSelector {
263    Exact(i64),
264    Range(i64, Option<i64>),
265}
266
267impl PluralSelector {
268    fn matches(&self, count: i64) -> bool {
269        match self {
270            PluralSelector::Exact(n) => count == *n,
271            PluralSelector::Range(min, Some(max)) => count >= *min && count <= *max,
272            PluralSelector::Range(min, None) => count >= *min,
273        }
274    }
275}
276
277/// Parses one segment's leading `{n}`/`[n,*]`/`[n,m]` selector, returning
278/// it alongside the rest of the segment (whitespace-trimmed) - or `None`
279/// if this segment has no selector at all.
280fn parse_selector(segment: &str) -> Option<(PluralSelector, &str)> {
281    let segment = segment.trim_start();
282    if let Some(rest) = segment.strip_prefix('{') {
283        let (num, rest) = rest.split_once('}')?;
284        let n: i64 = num.trim().parse().ok()?;
285        return Some((PluralSelector::Exact(n), rest.trim_start()));
286    }
287    if let Some(rest) = segment.strip_prefix('[') {
288        let (range, rest) = rest.split_once(']')?;
289        let (min_str, max_str) = range.split_once(',')?;
290        let min: i64 = min_str.trim().parse().ok()?;
291        let max = match max_str.trim() {
292            "*" => None,
293            bound => Some(bound.parse().ok()?),
294        };
295        return Some((PluralSelector::Range(min, max), rest.trim_start()));
296    }
297    None
298}
299
300fn substitute(template: &str, params: &[(&str, &str)]) -> String {
301    let mut result = template.to_string();
302    for (name, value) in params {
303        result = result.replace(&format!(":{name}"), value);
304    }
305    result
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    fn write_locale_file(dir: &Path, locale: &str, contents: &str) {
313        std::fs::write(dir.join(format!("{locale}.json")), contents).unwrap();
314    }
315
316    #[test]
317    fn load_catalog_from_a_missing_directory_is_empty() {
318        let catalog = load_catalog_from(Path::new("/nonexistent/path/that/does/not/exist"));
319        assert!(catalog.is_empty());
320    }
321
322    #[test]
323    fn load_catalog_reads_every_json_file_by_its_own_stem_as_the_locale() {
324        let dir = tempfile::tempdir().unwrap();
325        write_locale_file(dir.path(), "en", r#"{"messages.welcome": "Welcome!"}"#);
326        write_locale_file(dir.path(), "es", r#"{"messages.welcome": "¡Bienvenido!"}"#);
327        std::fs::write(dir.path().join("README.md"), "not json, ignored").unwrap();
328
329        let catalog = load_catalog_from(dir.path());
330        assert_eq!(
331            catalog.get("en").unwrap().get("messages.welcome").unwrap(),
332            "Welcome!"
333        );
334        assert_eq!(
335            catalog.get("es").unwrap().get("messages.welcome").unwrap(),
336            "¡Bienvenido!"
337        );
338        assert_eq!(catalog.len(), 2);
339    }
340
341    #[test]
342    fn load_catalog_skips_a_file_that_isnt_a_flat_string_map() {
343        let dir = tempfile::tempdir().unwrap();
344        write_locale_file(dir.path(), "broken", r#"{"nested": {"not": "flat"}}"#);
345
346        let catalog = load_catalog_from(dir.path());
347        assert!(catalog.is_empty());
348    }
349
350    #[test]
351    fn substitute_replaces_every_named_placeholder() {
352        assert_eq!(
353            substitute(
354                "Hello, :name! You have :count messages.",
355                &[("name", "Alice"), ("count", "3"),]
356            ),
357            "Hello, Alice! You have 3 messages."
358        );
359    }
360
361    #[test]
362    fn substitute_with_no_params_leaves_the_template_unchanged() {
363        assert_eq!(substitute("Welcome!", &[]), "Welcome!");
364    }
365
366    #[test]
367    fn pluralize_leaves_a_plain_template_with_no_pipe_untouched() {
368        assert_eq!(pluralize("Welcome!", &[("count", "5")]), "Welcome!");
369    }
370
371    #[test]
372    fn pluralize_simple_form_picks_singular_for_exactly_one() {
373        assert_eq!(pluralize("apple|apples", &[("count", "1")]), "apple");
374    }
375
376    #[test]
377    fn pluralize_simple_form_picks_plural_for_zero_and_for_many() {
378        assert_eq!(pluralize("apple|apples", &[("count", "0")]), "apples");
379        assert_eq!(pluralize("apple|apples", &[("count", "2")]), "apples");
380    }
381
382    #[test]
383    fn pluralize_explicit_selectors_pick_the_matching_exact_or_range_segment() {
384        let template = "{0} no apples|{1} one apple|[2,*] :count apples";
385        assert_eq!(pluralize(template, &[("count", "0")]), "no apples");
386        assert_eq!(pluralize(template, &[("count", "1")]), "one apple");
387        assert_eq!(pluralize(template, &[("count", "2")]), ":count apples");
388        assert_eq!(pluralize(template, &[("count", "100")]), ":count apples");
389    }
390
391    #[test]
392    fn pluralize_closed_range_selector_only_matches_within_bounds() {
393        let template = "[0,1] a few|[2,5] several|[6,*] many";
394        assert_eq!(pluralize(template, &[("count", "1")]), "a few");
395        assert_eq!(pluralize(template, &[("count", "4")]), "several");
396        assert_eq!(pluralize(template, &[("count", "6")]), "many");
397        assert_eq!(pluralize(template, &[("count", "1000")]), "many");
398    }
399
400    #[test]
401    fn pluralize_degrades_to_the_last_segment_when_count_is_missing() {
402        assert_eq!(pluralize("apple|apples", &[]), "apples");
403    }
404
405    #[test]
406    fn pluralize_degrades_to_the_last_segment_when_count_does_not_parse() {
407        assert_eq!(
408            pluralize("apple|apples", &[("count", "not-a-number")]),
409            "apples"
410        );
411    }
412
413    #[test]
414    fn pluralize_end_to_end_through_t_with_also_substitutes_count() {
415        // Proves the real call path, not just the pure `pluralize` helper -
416        // `:count` must still be available to interpolate *after* the
417        // right segment is chosen.
418        let dir = tempfile::tempdir().unwrap();
419        write_locale_file(
420            dir.path(),
421            "en",
422            r#"{"cart.items": "{0} no items|{1} one item|[2,*] :count items"}"#,
423        );
424        let catalog = load_catalog_from(dir.path());
425        let template = catalog
426            .get("en")
427            .and_then(|entries| entries.get("cart.items"))
428            .unwrap();
429        assert_eq!(
430            substitute(pluralize(template, &[("count", "3")]), &[("count", "3")]),
431            "3 items"
432        );
433    }
434
435    // `Application::new`'s config publish is a process-wide `OnceLock` -
436    // only the *first* call in this test binary actually takes effect, so
437    // every test below shares the same `app_locale: "en"` rather than each
438    // asserting its own value (calling it again with the same value is
439    // safe and idempotent, matching `Application::new`'s own contract).
440    fn init_config() {
441        larust_core::Application::new(|| serde_json::json!({"app_locale": "en"})).unwrap();
442    }
443
444    #[tokio::test]
445    async fn current_locale_falls_back_to_config_default_outside_a_scope() {
446        init_config();
447        assert_eq!(current_locale(), "en");
448    }
449
450    #[tokio::test]
451    async fn set_current_locale_overrides_only_within_its_own_scope() {
452        init_config();
453
454        with_locale_scope(async {
455            assert_eq!(current_locale(), "en");
456            set_current_locale("es".to_string());
457            assert_eq!(current_locale(), "es");
458        })
459        .await;
460
461        // A separate scope (simulating the next request) starts fresh.
462        with_locale_scope(async {
463            assert_eq!(current_locale(), "en");
464        })
465        .await;
466    }
467
468    #[tokio::test]
469    async fn set_current_locale_outside_a_scope_is_a_no_op() {
470        init_config();
471        set_current_locale("es".to_string());
472        assert_eq!(current_locale(), "en");
473    }
474
475    #[tokio::test]
476    async fn t_or_falls_back_to_the_given_default_not_the_bare_key() {
477        init_config();
478        // No `resources/lang` directory exists relative to this crate's own
479        // test binary CWD, so `nonexistent.key` can never resolve - `t()`
480        // itself would return the key unchanged here; `t_or` must return
481        // `default` instead.
482        assert_eq!(
483            t_or("nonexistent.key", "a sensible default"),
484            "a sensible default"
485        );
486    }
487
488    #[tokio::test]
489    async fn t_or_with_substitutes_placeholders_in_the_default_too() {
490        init_config();
491        assert_eq!(
492            t_or_with("nonexistent.key", "Hello, :name!", &[("name", "Alice")]),
493            "Hello, Alice!"
494        );
495    }
496}