embedded_i18n/lib.rs
1//! Compile-time internationalization for embedded and `no_std` Rust, with a
2//! [rust-i18n](https://crates.io/crates/rust-i18n) style API.
3//!
4//! Translations are read from locale files at build time by procedural macros
5//! and embedded in the binary as `&'static str` literals: no runtime parsing, no
6//! allocator, no file system, and a missing translation is a compile error at
7//! the call site.
8//!
9//! # Quick start
10//!
11//! Put locale files in a `locales/` directory next to `Cargo.toml`:
12//!
13//! ```json
14//! {
15//! "greeting": "Hello",
16//! "files": { "one": "{count} file", "other": "{count} files" }
17//! }
18//! ```
19//!
20//! Call [`i18n!`] once at the crate root, before any `mod` declaration, then
21//! translate with [`t!`]:
22//!
23//! ```
24//! embedded_i18n::i18n!("locales");
25//! use core::fmt::Write;
26//! use embedded_i18n::t;
27//!
28//! const GREETING: &str = t!("greeting");
29//! assert_eq!(GREETING, "Hello");
30//!
31//! let mut output = String::new();
32//! write!(output, "{}", t!("with_arg", value = 42))?;
33//! assert_eq!(output, "Value: 42");
34//!
35//! assert_eq!(t!("files", count = 2).to_string(), "2 files");
36//! # Ok::<(), core::fmt::Error>(())
37//! ```
38//!
39//! # Macros
40//!
41//! | Macro | Result |
42//! | --- | --- |
43//! | [`i18n!`] | Configures the translations of the crate, once at its root |
44//! | [`t!`] | `&'static str` (or `&'static CStr`) without arguments, a [`core::fmt::Display`] value with arguments or `count` |
45//! | [`locale!`] | Name of the locale the crate translates into |
46//! | [`available_locales!`] | Locales embedded in the crate |
47//!
48//! # Configuration
49//!
50//! [`i18n!`] takes the locale directory and options, read from
51//! `[package.metadata.i18n]` in `Cargo.toml` when not given:
52//!
53//! | `i18n!` argument | `[package.metadata.i18n]` key | Default | Meaning |
54//! | --- | --- | --- | --- |
55//! | first positional string | `load-path` | `"locales"` | Locale directory, relative to `Cargo.toml` |
56//! | `fallback = "en"` or `["en", "es"]` | `fallback` | `["en"]` | Fallback chain after the locale and its parents |
57//! | `default_locale = "fr"` | `default-locale` | `"en"` | Locale active at startup |
58//! | `available_locales = [..]` | `available-locales` | `[default_locale]` | Embedded locales; more than one enables runtime selection |
59//! | `strict = true` | `strict` | `false` | Forbids falling back for messages missing from the primary locale |
60//! | `bidi_isolation = true` | `bidi-isolation` | `false` | Isolates placeholders of right-to-left locales |
61//!
62//! The `EMBEDDED_I18N_LOCALE` and `EMBEDDED_I18N_LOCALES` (comma separated)
63//! environment variables override `default_locale` and `available_locales` in
64//! every crate of the build, to build one firmware per language. Cargo rebuilds the crate when a locale
65//! file, `Cargo.toml` or one of these variables changes.
66//!
67//! Locales are normalized like BCP 47 tags and resolved from the most specific
68//! to the most generic (`fr-CA`, `fr`, then the fallbacks). The special locale
69//! `pseudo` generates a pseudo-localization of the fallback locales.
70//!
71//! # Runtime locales
72//!
73//! With several `available_locales`, [`set_locale`] selects the locale at
74//! runtime, for every crate of the program: each one translates into its
75//! closest embedded locale, or its `default_locale`. `t!("key", locale =
76//! "fr")` translates into a given locale without touching the global one.
77//!
78//! ```rust,standalone_crate
79//! embedded_i18n::i18n!("locales", available_locales = ["en", "fr"]);
80//! use embedded_i18n::{locale, set_locale, t};
81//!
82//! fn main() {
83//! assert_eq!(t!("greeting", locale = "fr-CA"), "Bonjour");
84//! set_locale("fr");
85//! assert_eq!(t!("greeting"), "Bonjour");
86//! assert_eq!(locale!(), "fr");
87//! set_locale("de");
88//! assert_eq!(t!("greeting"), "Hello");
89//! }
90//! ```
91//!
92//! # Locale file formats
93//!
94//! Each format is enabled by a Cargo feature; all parsing happens in the
95//! procedural macro, so formats add nothing to the binary.
96//!
97//! | Feature | Files |
98//! | --- | --- |
99//! | `backend-json` (default) | `.json`, nested objects flattened to dotted keys |
100//! | `backend-yaml` | `.yaml`, `.yml` |
101//! | `backend-toml` | `.toml` |
102//! | `backend-po` | GNU gettext `.po`, with `msgctxt`, plural forms and `Plural-Forms` |
103//! | `backend-mo` | Compiled GNU gettext `.mo` |
104//! | `backend-fluent` | Fluent `.ftl` simple messages and whole-message selects |
105//!
106//! # Runtime helpers
107//!
108//! - [`DateTimeFormatter`] and [`write_unix_timestamp`]: localized `strftime`-style
109//! formatting without allocation.
110//! - [`is_right_to_left`]: text direction.
111//! - [`get_locale_ranges`] and [`write_ranges`]: Unicode ranges to subset fonts.
112//! - [`Locale`] and [`set_locale`]: runtime locale selection when several
113//! locales are embedded.
114//!
115//! # Features
116//!
117//! - `alloc`: `String` and `Vec` returning variants of the helpers.
118//! - `std`: enables `alloc` and `system_locale()`, the locale of the operating
119//! system.
120//!
121//! # Guide
122//!
123//! The [`guide`] follows the [Diátaxis](https://diataxis.fr) structure:
124//!
125//! - **Tutorial**: [getting started](guide::tutorials::getting_started), from
126//! an empty project to a program translated into two languages.
127//! - **How-to guides**:
128//! [switch language at runtime](guide::how_to::switch_language_at_runtime),
129//! [localize per request](guide::how_to::localize_per_request),
130//! [build one firmware per language](guide::how_to::build_one_firmware_per_language),
131//! [use gettext PO files and other formats](guide::how_to::use_gettext_po_files),
132//! [ship complete translations](guide::how_to::ship_complete_translations),
133//! [pseudo-localize](guide::how_to::pseudo_localize),
134//! [support right-to-left languages](guide::how_to::support_right_to_left_languages),
135//! [format dates and times](guide::how_to::format_dates_and_times),
136//! [subset fonts](guide::how_to::subset_fonts),
137//! [migrate from rust-i18n](guide::how_to::migrate_from_rust_i18n) and
138//! [migrate from 0.1](guide::how_to::migrate_from_0_1).
139//! - **Reference**: [the `t!` macro](guide::reference::t_macro),
140//! [configuration](guide::reference::configuration),
141//! [locale files](guide::reference::locale_files),
142//! [plural rules](guide::reference::plural_rules),
143//! [runtime API](guide::reference::runtime_api),
144//! [date and time](guide::reference::date_time),
145//! [Unicode ranges](guide::reference::unicode_ranges) and
146//! [features and `no_std`](guide::reference::features_and_no_std).
147//! - **Explanation**: [how it works](guide::explanation::how_it_works),
148//! [the runtime locale model](guide::explanation::runtime_locale_model),
149//! [design choices](guide::explanation::design_choices) and a
150//! [comparison with other crates](guide::explanation::comparison).
151#![no_std]
152#![allow(clippy::needless_doctest_main)]
153#![deny(missing_docs)]
154
155extern crate self as embedded_i18n;
156
157#[cfg(feature = "alloc")]
158extern crate alloc;
159
160#[cfg(feature = "std")]
161extern crate std;
162
163mod date_time;
164mod direction;
165pub mod guide;
166mod locale;
167mod range;
168mod time;
169
170pub use date_time::*;
171pub use direction::*;
172pub use locale::*;
173pub use range::*;
174pub use time::*;
175
176/// Configures the translations of the calling crate.
177///
178/// Invoke it once, at the crate root (`lib.rs` or `main.rs`), before the `mod`
179/// declarations that use [`t!`], as with rust-i18n. Each crate, integration
180/// test, example and doctest that translates calls it once; a second call in
181/// the same crate is a compile error. The arguments and the
182/// `[package.metadata.i18n]` keys are listed in the
183/// [crate documentation](crate#configuration).
184///
185/// ```
186/// // Everything from `[package.metadata.i18n]`, or the defaults:
187/// embedded_i18n::i18n!();
188/// ```
189///
190/// ```
191/// embedded_i18n::i18n!("locales", fallback = ["en"], strict = false);
192/// ```
193///
194/// With more than one available locale, `i18n!` also generates the crate's
195/// function resolving the [current locale](set_locale) to one of its locales:
196/// the same tag, else the same language, else `default_locale`.
197///
198/// Errors are reported on the call: unknown option, wrong value type, empty
199/// locale name, `default_locale` not in `available_locales`, more than 255
200/// available locales, two available locales with the same [`Locale`]
201/// identifier, missing locale directory.
202///
203/// ```compile_fail
204/// embedded_i18n::i18n!(available_locales = ["fr-CA", "fr_ca"], default_locale = "fr-CA");
205/// ```
206pub use embedded_i18n_macros::i18n;
207
208#[doc(hidden)]
209pub use embedded_i18n_macros::__expand;
210
211/// Translates a message key, at compile time.
212///
213/// `t!(KEY, items...)` where `KEY` is a string literal, or a C string literal
214/// to get a `&'static CStr` for FFI, and each item is one of:
215///
216/// - `context = "menu"`: a message context, to disambiguate identical source
217/// strings (gettext `msgctxt`, or the `menu.Open` key);
218/// - `locale = <expr>`: translates into this locale instead of the current one;
219/// - `count = <integer>`: selects the plural form, and is the `{count}`
220/// placeholder;
221/// - `select = <expr>`: selects a variant (`replied.male`, `replied.other`) by
222/// `AsRef<str>`, `other` being the default. When both `select` and `count`
223/// are given, `select` picks the variant and `count` is an ordinary
224/// argument (the `{count}` placeholder): it selects no plural form;
225/// - `name = <expr>` or `"name" => <expr>`: an argument, the value of the
226/// `{name}` (or rust-i18n `%{name}`) placeholder, optionally followed by a
227/// format specification: `sn = 123 : {:08}`.
228///
229/// Without arguments nor `count`, the result is a `&'static str`: in
230/// single-locale mode, a literal usable in `const` items.
231///
232/// ```
233/// use core::ffi::CStr;
234/// embedded_i18n::i18n!();
235/// use embedded_i18n::t;
236///
237/// const GREETING: &str = t!("greeting");
238/// assert_eq!(GREETING, "Hello");
239///
240/// let greeting: &'static CStr = t!(c"greeting");
241/// assert_eq!(greeting.to_bytes(), b"Hello");
242///
243/// assert_eq!(t!("Open", context = "menu"), "Open (menu)");
244/// assert_eq!(t!("replied", select = "female"), "She replied");
245/// ```
246///
247/// With arguments or `count`, the result implements [`core::fmt::Display`]
248/// and formats on demand, without allocation. Arguments are evaluated once and
249/// borrowed, as by `format_args!`.
250///
251/// ```
252/// embedded_i18n::i18n!();
253/// use embedded_i18n::t;
254///
255/// let name = "Ada";
256/// assert_eq!(
257/// t!("with_named_args", name = name, count = 3).to_string(),
258/// "Hello Ada, you have 3 messages"
259/// );
260/// assert_eq!(t!("files", count = 1).to_string(), "1 file");
261/// assert_eq!(t!("with_arg", "value" => 7 : {:03}).to_string(), "Value: 007");
262/// ```
263///
264/// A placeholder without an argument, a key missing from every locale of the
265/// chain, arguments given to a C string key, or a crate without [`i18n!`] are
266/// compile errors:
267///
268/// ```compile_fail
269/// embedded_i18n::i18n!();
270/// // The translation uses {count}.
271/// let _ = embedded_i18n::t!("with_named_args", name = "Ada");
272/// ```
273///
274/// ```compile_fail
275/// embedded_i18n::i18n!();
276/// let _ = embedded_i18n::t!("no such key");
277/// ```
278///
279/// ```compile_fail
280/// embedded_i18n::i18n!();
281/// let _ = embedded_i18n::t!(c"greeting", name = 1);
282/// ```
283///
284/// ```compile_fail
285/// // No `embedded_i18n::i18n!()` in this crate.
286/// let _ = embedded_i18n::t!("greeting");
287/// ```
288#[macro_export]
289macro_rules! t {
290 ($($tokens:tt)*) => {
291 embedded_i18n_requires_i18n_at_the_crate_root!(@t $($tokens)*)
292 };
293}
294
295/// Returns the name of the locale the calling crate translates into, as a
296/// `&'static str`.
297///
298/// In single-locale mode it is the `default_locale` literal; with several
299/// available locales, the one the [current locale](set_locale) resolves to.
300///
301/// ```
302/// embedded_i18n::i18n!();
303///
304/// assert_eq!(embedded_i18n::locale!(), "en");
305/// assert!(!embedded_i18n::is_right_to_left(embedded_i18n::locale!()));
306/// ```
307#[macro_export]
308macro_rules! locale {
309 () => {
310 embedded_i18n_requires_i18n_at_the_crate_root!(@locale)
311 };
312}
313
314/// Lists the locales embedded in the calling crate, as
315/// `&'static [&'static str]`, in configuration order.
316///
317/// ```
318/// embedded_i18n::i18n!();
319///
320/// assert_eq!(embedded_i18n::available_locales!(), ["en"]);
321/// ```
322#[macro_export]
323macro_rules! available_locales {
324 () => {
325 embedded_i18n_requires_i18n_at_the_crate_root!(@available)
326 };
327}
328
329/// Returns the locale of the operating system, from the `LC_ALL`,
330/// `LC_MESSAGES` and `LANG` environment variables, as a BCP 47 style tag
331/// (`fr_FR.UTF-8` becomes `fr-FR`). Available with the `std` feature.
332///
333/// The first variable that holds a usable value wins; empty values and the
334/// `C` and `POSIX` locales are ignored. Returns `None` when no variable holds a
335/// usable value: each one is unset, empty, `C` or `POSIX`.
336///
337/// This reads the POSIX environment only. Windows and macOS GUI applications
338/// should use the [`sys-locale`](https://crates.io/crates/sys-locale) crate
339/// instead, and pass its result to [`set_locale`].
340///
341/// ```
342/// # #[cfg(feature = "std")]
343/// if let Some(locale) = embedded_i18n::system_locale() {
344/// embedded_i18n::set_locale(&locale);
345/// }
346/// ```
347#[cfg(feature = "std")]
348pub fn system_locale() -> Option<std::string::String> {
349 ["LC_ALL", "LC_MESSAGES", "LANG"]
350 .into_iter()
351 .find_map(|name| normalize_system_locale(&std::env::var(name).ok()?))
352}
353
354/// Turns a POSIX locale value (`fr_FR.UTF-8@euro`) into a tag (`fr-FR`).
355#[cfg(feature = "std")]
356fn normalize_system_locale(value: &str) -> Option<std::string::String> {
357 let end = value.find(['.', '@']).unwrap_or(value.len());
358 let base = value[..end].trim();
359 if base.is_empty() || base == "C" || base == "POSIX" {
360 return None;
361 }
362 Some(base.replace('_', "-"))
363}
364
365#[cfg(test)]
366mod tests {
367 use super::*;
368
369 #[test]
370 fn get_locale_ranges_supported_locales() {
371 for locale in &[
372 "en", "fr", "de", "es", "it", "pt", "nl", "pl", "ru", "ja", "zh",
373 ] {
374 assert!(
375 get_locale_ranges(locale).is_some(),
376 "{} should have ranges",
377 locale
378 );
379 }
380 }
381
382 #[test]
383 fn get_locale_ranges_unsupported_locale() {
384 assert!(get_locale_ranges("unsupported").is_none());
385 assert!(get_locale_ranges("xx").is_none());
386 assert!(get_locale_ranges("").is_none());
387 }
388}
389
390#[cfg(all(test, feature = "std"))]
391mod system_locale_tests {
392 use super::*;
393
394 #[test]
395 fn normalizes_system_locales() {
396 assert_eq!(
397 normalize_system_locale("fr_FR.UTF-8@euro").as_deref(),
398 Some("fr-FR")
399 );
400 assert_eq!(normalize_system_locale("de_DE").as_deref(), Some("de-DE"));
401 assert_eq!(normalize_system_locale("C"), None);
402 assert_eq!(normalize_system_locale("POSIX"), None);
403 assert_eq!(normalize_system_locale(""), None);
404 assert_eq!(normalize_system_locale("C.UTF-8"), None);
405 }
406}