i18n_next/i18n.rs
1//! `I18n`, its builder and views (DESIGN 3, 4.1, 4.2, 4.5).
2//!
3//! Reads go through a snapshot: `Inner.version` is one atomic load, and each thread keeps
4//! up to four `(instance, version, Arc<Snapshot>)` in a `thread_local!` cache (spike S1),
5//! so a hit takes no lock and touches no reference count. A write builds a new snapshot,
6//! swaps it under the write lock and bumps the version; a reader holding the old `Arc`
7//! never sees a change. A locale switch shares the data and chain maps of the previous
8//! snapshot (`Arc` clones): only the active pointer changes.
9
10use crate::args::{Args, Count};
11use crate::catalog::{Entry, Msg, Tree, WithCount, interpolate_once};
12use crate::change::{Change, Listeners};
13use crate::check::{self, CheckReport};
14use crate::error::Error;
15use crate::hash::FastMap;
16use crate::lazy::{Layer, LazyCtl};
17use crate::loader::{self, Config};
18use crate::plural::{self, Plural};
19use crate::source::{self, Pair, Sources};
20use std::cell::RefCell;
21use std::fmt;
22use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
23use std::sync::{Arc, Mutex, RwLock};
24
25type Missing = Box<dyn Fn(&str, &str, &str) + Send + Sync>;
26
27/// One locale's chunks: the root (`index`) and its pages, ready or lazy.
28#[derive(Debug, Default, Clone)]
29pub(crate) struct LocaleData {
30 pub(crate) root: Option<Layer>,
31 pub(crate) pages: FastMap<Arc<str>, Layer>,
32}
33
34impl LocaleData {
35 /// Page layer, then root layer.
36 fn get(&self, page: Option<&str>, key: &crate::key::Probe<'_>) -> Option<&Entry> {
37 if let Some(p) = page
38 && let Some(e) = self
39 .pages
40 .get(p)
41 .and_then(Layer::chunk)
42 .and_then(|c| c.find(key))
43 {
44 return Some(e);
45 }
46 self.root
47 .as_ref()
48 .and_then(Layer::chunk)
49 .and_then(|c| c.find(key))
50 }
51
52 /// The root (`None`) or page layer, as stored.
53 pub(crate) fn layer(&self, page: Option<&str>) -> Option<&Layer> {
54 match page {
55 None => self.root.as_ref(),
56 Some(p) => self.pages.get(p),
57 }
58 }
59
60 /// What `has` reads: page then root, own keys only (no texts `linked.rs` stored).
61 fn has(&self, page: Option<&str>, key: &str) -> bool {
62 let has = |l: Option<&Layer>| l.and_then(Layer::chunk).is_some_and(|c| c.has(key));
63 has(page.and_then(|p| self.pages.get(p))) || has(self.root.as_ref())
64 }
65}
66
67type Chain = Arc<[Arc<LocaleData>]>;
68
69/// What the builder fixed: it does not change after `build`.
70#[derive(Debug, Default)]
71pub(crate) struct Meta {
72 fallback: Option<Arc<str>>,
73 links: FastMap<Arc<str>, Arc<str>>,
74 iso: FastMap<Arc<str>, Arc<str>>,
75 /// `i18n.json` `locales[]`, in file order.
76 configured: Vec<loader::LocaleEntry>,
77 /// Locales the app named itself: the start locale, `defaultLocale`, both ends of every
78 /// fallback link, the global fallback and `iso` codes. Each is known, with its chain.
79 declared: Vec<Arc<str>>,
80 aliases: FastMap<Arc<str>, Arc<str>>,
81 /// Named number formats by locale code (`numberFormats`, [`Builder::formats`]).
82 #[cfg(feature = "format")]
83 pub(crate) numbers: crate::format::Formats,
84 /// Named date formats by locale code (`datetimeFormats`, [`Builder::datetime_formats`]).
85 #[cfg(feature = "format")]
86 dates: crate::format::DateFormats,
87 /// [`Builder::time_zone`]; else the system's, found on first use.
88 #[cfg(feature = "format")]
89 zone: Option<crate::format::Zone>,
90 /// The IANA name of [`Builder::time_zone`].
91 #[cfg(feature = "format")]
92 zone_name: Option<Box<str>>,
93 #[cfg(feature = "format")]
94 system_zone: std::sync::OnceLock<crate::format::Zone>,
95 /// The IANA name of a system zone given by [`I18n::set_system_time_zone`].
96 #[cfg(feature = "format")]
97 system_zone_name: std::sync::OnceLock<Box<str>>,
98 /// Number data of view locales outside the snapshot's table, resolved once each
99 /// ([`Meta::cold_number`]); filled in order, first come first kept.
100 // ponytail: 8 codes; past them a code resolves on every call (~90 ns), grow if apps
101 // format in more unknown locales than that
102 #[cfg(feature = "format")]
103 cold_numbers: [std::sync::OnceLock<(Box<str>, &'static crate::format::Loc)>; 8],
104 /// [`Builder::clock`]; else the system clock.
105 #[cfg(feature = "format")]
106 clock: Option<crate::format::api::Clock>,
107 /// What `check()` reads besides the chunks (M3); its `reference` is `defaultLocale`.
108 pub(crate) check: check::Facts,
109 /// `linked_messages(true)`: `build` and `reload` resolve links with it.
110 linked: Option<ResolveLinked>,
111 /// `numberFormats` and `datetimeFormats` (`i18n.json`, then the builder's calls, a name
112 /// given again wins), merged on first use: what the payload sends the front end.
113 #[cfg(feature = "payload")]
114 pub(crate) formats: crate::payload::Formats,
115}
116
117impl Meta {
118 /// `linked_messages(true)`.
119 pub(crate) fn linked(&self) -> bool {
120 self.linked.is_some()
121 }
122
123 fn disabled(&self, code: &str) -> bool {
124 self.configured.iter().any(|l| l.disabled && l.code == code)
125 }
126
127 /// The page chunk a name reads: `""` and `index` are the root, an alias its target.
128 pub(crate) fn page<'a>(&'a self, page: Option<&'a str>) -> Option<&'a str> {
129 let p = page.filter(|p| !p.is_empty() && *p != "index")?;
130 let p = self.aliases.get(p).map_or(p, |t| &**t);
131 (p != "index").then_some(p)
132 }
133
134 /// `code` and its `fallback_for` links to their end, then the global fallback alone,
135 /// never expanded through its own links (`utils` `buildFallbackLocaleChain`). A cycle
136 /// (`a → b → a`) stops at the first repeat.
137 fn chain(&self, data: &FastMap<Arc<str>, Arc<LocaleData>>, code: &str) -> Chain {
138 self.chain_codes(code)
139 .iter()
140 .filter_map(|c| data.get(*c).cloned())
141 .collect()
142 }
143
144 /// The locale codes of [`Meta::chain`], with or without data.
145 pub(crate) fn chain_codes<'a>(&'a self, code: &'a str) -> Vec<&'a str> {
146 let mut codes: Vec<&str> = Vec::new();
147 let mut next = Some(code);
148 while let Some(c) = next {
149 if codes.contains(&c) {
150 break;
151 }
152 codes.push(c);
153 next = self.links.get(c).map(|s| &**s);
154 }
155 if let Some(fb) = self.fallback.as_deref()
156 && !codes.contains(&fb)
157 {
158 codes.push(fb);
159 }
160 codes
161 }
162
163 /// `fallbackLocale` (the builder's, else `i18n.json`'s).
164 #[cfg(feature = "payload")]
165 pub(crate) fn fallback(&self) -> Option<&str> {
166 self.fallback.as_deref()
167 }
168}
169
170pub(crate) type DataMap = FastMap<Arc<str>, Arc<LocaleData>>;
171
172pub(crate) struct Snapshot {
173 /// The cache key of the thread caches: + 1 per snapshot, an eviction too.
174 pub(crate) version: u64,
175 /// [`I18n::version`]: + 1 per change of what lookups answer (not an eviction).
176 pub(crate) public: u64,
177 pub(crate) locale: Arc<str>,
178 /// Shared between snapshots that differ only in the active locale.
179 pub(crate) data: Arc<DataMap>,
180 /// Chains of every known locale, disabled ones too (`with_locale` reads them, as a
181 /// configured locale in `buildFallbackLocaleChain`); `set_locale` refuses the disabled.
182 chains: Arc<FastMap<Arc<str>, Chain>>,
183 active: Chain,
184 /// The active locale's own chunks (what `has` reads), `None` when it has no data.
185 own: Option<Arc<LocaleData>>,
186 /// The global fallback's layer alone, never its links: what a locale that is not known
187 /// reads (`buildFallbackLocaleChain` of an unconfigured code is `[fallback]`).
188 fallback: Chain,
189 pub(crate) meta: Arc<Meta>,
190 /// Plural rules of the active locale (its `iso`, else its code); `None`: index rule.
191 pub(crate) plural: Option<&'static Plural>,
192 /// The same for every known locale, resolved once: a view in another locale reads
193 /// them with one hash lookup instead of resolving its tag on every `tc` (~130 ns).
194 plurals: Arc<FastMap<Arc<str>, Option<&'static Plural>>>,
195 /// CLDR number data of the active locale (its `iso`, else its code; `en` when unknown).
196 #[cfg(feature = "format")]
197 pub(crate) number: &'static crate::format::Loc,
198 /// The same for every known locale, resolved once.
199 #[cfg(feature = "format")]
200 numbers: Arc<FastMap<Arc<str>, &'static crate::format::Loc>>,
201}
202
203impl Meta {
204 /// Plural rules of `code`: by its `iso` when it has one (`ua` → `uk-UA`), else the code.
205 fn plural(&self, code: &str) -> Option<&'static Plural> {
206 plural::for_tag(self.tag(code))
207 }
208
209 /// The BCP 47 tag of `code`: its `iso`, else the code (`isoTag` of `BaseI18n`).
210 pub(crate) fn tag<'a>(&'a self, code: &'a str) -> &'a str {
211 self.iso.get(code).map_or(code, |t| &**t)
212 }
213
214 /// CLDR number data of `code`, as `FormatService` resolves `isoTag(code)`.
215 #[cfg(feature = "format")]
216 fn number(&self, code: &str) -> &'static crate::format::Loc {
217 crate::format::locale::resolve(self.tag(code))
218 }
219
220 /// [`Meta::number`] of a view locale the snapshot's table lacks, kept for the next call.
221 #[cfg(feature = "format")]
222 fn cold_number(&self, code: &str) -> &'static crate::format::Loc {
223 for slot in &self.cold_numbers {
224 match slot.get() {
225 Some((c, loc)) if **c == *code => return loc,
226 Some(_) => {}
227 None => {
228 let loc = self.number(code);
229 // another thread may have taken the slot meanwhile: then this one is
230 // not kept, the answer is the same
231 let _ = slot.set((code.into(), loc));
232 return loc;
233 }
234 }
235 }
236 self.number(code)
237 }
238
239 /// The named number format `name` of locale `code`: by the code, then shorter
240 /// (`zh-Hant-TW` → `zh-Hant` → `zh`), as `FormatService` looks it up.
241 #[cfg(feature = "format")]
242 pub(crate) fn named_number(
243 &self,
244 code: &str,
245 name: &str,
246 ) -> Option<&crate::format::NumberOptions> {
247 let mut at = code;
248 while !at.is_empty() {
249 if let Some(o) = self.numbers.get(at).and_then(|m| m.get(name)) {
250 return Some(o);
251 }
252 at = at.get(..at.rfind('-').unwrap_or(0)).unwrap_or("");
253 }
254 None
255 }
256
257 /// The named date format `name` of locale `code`, looked up as [`Meta::named_number`].
258 #[cfg(feature = "format")]
259 pub(crate) fn named_date(&self, code: &str, name: &str) -> Option<&crate::format::DateOptions> {
260 let mut at = code;
261 while !at.is_empty() {
262 if let Some(o) = self.dates.get(at).and_then(|m| m.get(name)) {
263 return Some(o);
264 }
265 at = at.get(..at.rfind('-').unwrap_or(0)).unwrap_or("");
266 }
267 None
268 }
269
270 /// The IANA name of the zone dates show in, when it is known by name: the builder's, or
271 /// the one [`I18n::set_system_time_zone`] gave. What the payload sends the front end.
272 #[cfg(all(feature = "format", feature = "payload"))]
273 pub(crate) fn zone_name(&self) -> Option<&str> {
274 self.zone_name
275 .as_deref()
276 .or_else(|| self.system_zone_name.get().map(|n| &**n))
277 }
278
279 /// Takes `iana` as the system zone: only without a builder zone and before the system's
280 /// was looked up (dates already shown keep their zone).
281 #[cfg(feature = "format")]
282 pub(crate) fn set_system_zone(&self, iana: &str) -> bool {
283 if self.zone.is_some() || iana.is_empty() {
284 return false;
285 }
286 let Some(zone) = crate::format::date::zone_named(iana) else {
287 return false;
288 };
289 if self.system_zone.set(zone).is_err() {
290 return false;
291 }
292 let _ = self.system_zone_name.set(Box::from(iana));
293 true
294 }
295
296 /// The zone dates show in: [`Builder::time_zone`], else the system's.
297 #[cfg(feature = "format")]
298 pub(crate) fn zone(&self) -> &crate::format::Zone {
299 match &self.zone {
300 Some(z) => z,
301 None => self.system_zone.get_or_init(crate::format::Zone::system),
302 }
303 }
304
305 /// Now in milliseconds: [`Builder::clock`], else the system clock; `None` without one or
306 /// out of a date's range.
307 #[cfg(feature = "format")]
308 pub(crate) fn now(&self) -> Option<i64> {
309 match &self.clock {
310 Some(c) => crate::format::Timestamp::from((c.0)()).millis(),
311 None => crate::format::api::system_now(),
312 }
313 }
314}
315
316impl Snapshot {
317 pub(crate) fn new(meta: Arc<Meta>, data: DataMap, locale: Arc<str>, version: u64) -> Snapshot {
318 let mut chains = FastMap::default();
319 let names = meta
320 .configured
321 .iter()
322 .map(|l| &*l.code)
323 .chain(data.keys().map(|k| &**k))
324 .chain(meta.declared.iter().map(|k| &**k))
325 .chain(std::iter::once(&*locale));
326 let mut plurals = FastMap::default();
327 #[cfg(feature = "format")]
328 let mut numbers = FastMap::default();
329 for code in names {
330 if !chains.contains_key(code) {
331 let code: Arc<str> = Arc::from(code);
332 let chain = meta.chain(&data, &code);
333 plurals.insert(code.clone(), meta.plural(&code));
334 #[cfg(feature = "format")]
335 numbers.insert(code.clone(), meta.number(&code));
336 chains.insert(code, chain);
337 }
338 }
339 let active = chains
340 .get(&*locale)
341 .cloned()
342 .unwrap_or_else(|| meta.chain(&data, &locale));
343 let fallback = meta
344 .fallback
345 .as_deref()
346 .and_then(|fb| data.get(fb).cloned())
347 .into_iter()
348 .collect();
349 Snapshot {
350 version,
351 public: version,
352 own: data.get(&*locale).cloned(),
353 plural: meta.plural(&locale),
354 #[cfg(feature = "format")]
355 number: meta.number(&locale),
356 #[cfg(feature = "format")]
357 numbers: Arc::new(numbers),
358 locale,
359 data: Arc::new(data),
360 chains: Arc::new(chains),
361 plurals: Arc::new(plurals),
362 active,
363 fallback,
364 meta,
365 }
366 }
367
368 /// Plural rules of `code` (a view's locale): known ones from the table, others resolved.
369 pub(crate) fn plural_of(&self, code: &str) -> Option<&'static Plural> {
370 match self.plurals.get(code) {
371 Some(p) => *p,
372 None => self.meta.plural(code),
373 }
374 }
375
376 /// CLDR number data of `code` (a view's locale): known ones from the table.
377 #[cfg(feature = "format")]
378 pub(crate) fn number_of(&self, code: &str) -> &'static crate::format::Loc {
379 match self.numbers.get(code) {
380 Some(n) => n,
381 None => self.meta.cold_number(code),
382 }
383 }
384
385 /// The layers of `locale` (the active one when `None`). A locale that is not known has
386 /// nothing of its own: it reads the global fallback alone.
387 pub(crate) fn layers(&self, locale: Option<&str>) -> &[Arc<LocaleData>] {
388 match locale {
389 None => &self.active,
390 Some(code) => self.chains.get(code).unwrap_or(&self.fallback),
391 }
392 }
393
394 pub(crate) fn lookup(
395 &self,
396 locale: Option<&str>,
397 page: Option<&str>,
398 key: &str,
399 ) -> Option<&Entry> {
400 let page = self.meta.page(page);
401 let key = crate::key::Probe::new(key);
402 self.layers(locale)
403 .iter()
404 .find_map(|layer| layer.get(page, &key))
405 }
406
407 /// Only the locale itself, page then root: no fallback (JS `has`).
408 fn has(&self, locale: Option<&str>, page: Option<&str>, key: &str) -> bool {
409 let own = match locale {
410 None => self.own.as_deref(),
411 Some(code) if self.chains.contains_key(code) => self.data.get(code).map(|d| &**d),
412 Some(_) => None,
413 };
414 own.is_some_and(|d| d.has(self.meta.page(page), key))
415 }
416}
417
418impl Snapshot {
419 /// [`I18n::locales`] of this snapshot.
420 pub(crate) fn locale_infos(&self) -> Vec<LocaleInfo> {
421 let s = self;
422 let meta = &s.meta;
423 let mut rest: Vec<&str> = s
424 .data
425 .keys()
426 .map(|k| &**k)
427 .chain(meta.declared.iter().map(|k| &**k))
428 .filter(|c| !meta.configured.iter().any(|l| l.code == *c))
429 .collect();
430 rest.sort_unstable();
431 rest.dedup();
432 let info = |code: &str, entry: Option<&loader::LocaleEntry>| LocaleInfo {
433 code: code.to_owned(),
434 iso: meta
435 .iso
436 .get(code)
437 .map(|s| String::from(&**s))
438 .or_else(|| entry.and_then(|e| e.iso.clone())),
439 dir: entry.and_then(|e| e.dir.clone()),
440 display_name: entry.and_then(|e| e.display_name.clone()),
441 };
442 meta.configured
443 .iter()
444 .filter(|l| !l.disabled)
445 .map(|l| info(&l.code, Some(l)))
446 .chain(rest.into_iter().map(|c| info(c, None)))
447 .collect()
448 }
449}
450
451/// One cached snapshot of this thread.
452struct Slot {
453 id: u64,
454 version: u64,
455 snap: Arc<Snapshot>,
456 /// Cleared when the instance is dropped.
457 alive: Arc<AtomicBool>,
458}
459
460/// Cached snapshots of this thread, the slot to evict next, and the [`DROPS`] value the
461/// slots were last checked against.
462struct Cache {
463 slots: [Option<Slot>; 4],
464 next: usize,
465 drops: u64,
466}
467
468thread_local! {
469 #[allow(
470 clippy::missing_const_for_thread_local,
471 reason = "already `const`: clippy misreads the expansion on targets without native TLS (Android)"
472 )]
473 static CACHE: RefCell<Cache> = const {
474 RefCell::new(Cache { slots: [const { None }; 4], next: 0, drops: 0 })
475 };
476}
477
478static NEXT_ID: AtomicU64 = AtomicU64::new(0);
479
480/// Bumped by every dropped instance: the next read on a thread that sees a new value drops
481/// the cached snapshots of dead instances.
482static DROPS: AtomicU64 = AtomicU64::new(0);
483
484pub(crate) struct Inner {
485 id: u64,
486 version: AtomicU64,
487 state: RwLock<Arc<Snapshot>>,
488 /// Serializes writers; readers never take it.
489 writer: Mutex<()>,
490 missing: Option<Missing>,
491 alive: Arc<AtomicBool>,
492 /// What `build` read: `reload` reads it again.
493 pub(crate) sources: Sources,
494 /// Lazy loads, eviction and remote fetches of this instance.
495 pub(crate) ctl: Arc<LazyCtl>,
496 /// `remote` manifest path → its pair (`add_file` accepts only these).
497 pub(crate) remote: FastMap<Box<str>, Pair>,
498 pub(crate) listeners: Listeners,
499}
500
501impl Drop for Inner {
502 fn drop(&mut self) {
503 self.alive.store(false, Ordering::Relaxed);
504 // Release: a reader that sees the new count sees `alive` cleared.
505 DROPS.fetch_add(1, Ordering::Release);
506 }
507}
508
509impl Inner {
510 /// The current snapshot (one read lock).
511 pub(crate) fn current(&self) -> Arc<Snapshot> {
512 self.load()
513 }
514
515 fn load(&self) -> Arc<Snapshot> {
516 match self.state.read() {
517 Ok(g) => g.clone(),
518 Err(poisoned) => poisoned.into_inner().clone(),
519 }
520 }
521
522 /// `f` on the current snapshot: the thread cache when it is fresh, else one read lock.
523 /// A hit is two atomic loads and a scan of four slots, no reference count.
524 pub(crate) fn read<R>(&self, mut f: impl FnMut(&Snapshot) -> R) -> R {
525 let version = self.version.load(Ordering::Acquire);
526 // Relaxed: only compared here (a plain load on ARM); `refresh` acquires it.
527 let drops = DROPS.load(Ordering::Relaxed);
528 let hit = CACHE.try_with(|cell| {
529 let cache = cell.try_borrow().ok()?;
530 if cache.drops != drops {
531 return None;
532 }
533 let slot = cache
534 .slots
535 .iter()
536 .flatten()
537 .find(|s| s.id == self.id && s.version == version)?;
538 Some(f(&slot.snap))
539 });
540 if let Ok(Some(r)) = hit {
541 return r;
542 }
543 let (snap, gone) = self.refresh();
544 let r = f(&snap);
545 // Slots that left the cache are dropped after `f`: freeing an old catalog does
546 // not delay the read.
547 drop(gone);
548 r
549 }
550
551 /// The miss path of [`Inner::read`], not generic: loads the snapshot under the read
552 /// lock, caches it, and hands back the slots that left the cache (a stale version of
553 /// this instance, an evicted one, those of dropped instances).
554 #[inline(never)]
555 fn refresh(&self) -> (Arc<Snapshot>, [Option<Slot>; 4]) {
556 // Acquire: pairs with the release in `Inner::drop`, so `alive` reads below see it.
557 let drops = DROPS.load(Ordering::Acquire);
558 let snap = self.load();
559 let mut gone: [Option<Slot>; 4] = [const { None }; 4];
560 // Thread-local storage can be gone (a thread-exit destructor calls in): no caching.
561 let _ = CACHE.try_with(|cell| {
562 let Ok(mut cache) = cell.try_borrow_mut() else {
563 return;
564 };
565 let cache = &mut *cache;
566 if cache.drops != drops {
567 for (slot, out) in cache.slots.iter_mut().zip(&mut gone) {
568 if slot
569 .as_ref()
570 .is_some_and(|s| !s.alive.load(Ordering::Relaxed))
571 {
572 *out = slot.take();
573 }
574 }
575 cache.drops = drops;
576 }
577 let slots = &mut cache.slots;
578 let at = slots
579 .iter()
580 .position(|s| s.as_ref().is_some_and(|s| s.id == self.id))
581 .or_else(|| slots.iter().position(Option::is_none))
582 .unwrap_or_else(|| {
583 let at = cache.next;
584 cache.next = (at + 1) % slots.len();
585 at
586 });
587 let new = Slot {
588 id: self.id,
589 version: snap.version,
590 snap: snap.clone(),
591 alive: self.alive.clone(),
592 };
593 if let Some(old) = slots[at].replace(new) {
594 gone[at] = Some(old);
595 }
596 });
597 (snap, gone)
598 }
599
600 /// Builds the next snapshot from the current one and publishes it (`None`: no change);
601 /// what changed when something did.
602 pub(crate) fn write(
603 &self,
604 f: impl FnOnce(&Snapshot) -> Result<Option<Snapshot>, Error>,
605 ) -> Result<Option<Change>, Error> {
606 let _writer = match self.writer.lock() {
607 Ok(g) => g,
608 Err(poisoned) => poisoned.into_inner(),
609 };
610 let current = self.load();
611 let Some(mut next) = f(¤t)? else {
612 return Ok(None);
613 };
614 next.version = current.version + 1;
615 next.public = current.public + 1;
616 let change = Change {
617 locale: next.locale.clone(),
618 version: next.public,
619 };
620 self.publish(next);
621 // queued under the writer lock: the queue is in version order
622 self.listeners.push(change.clone());
623 drop(_writer);
624 self.listeners.drain();
625 Ok(Some(change))
626 }
627
628 fn publish(&self, next: Snapshot) -> u64 {
629 let version = next.version;
630 let mut state = match self.state.write() {
631 Ok(g) => g,
632 Err(poisoned) => poisoned.into_inner(),
633 };
634 *state = Arc::new(next);
635 self.version.store(version, Ordering::Release);
636 version
637 }
638
639 /// Evicts the oldest loaded pages past the limit (8b.16), called after a lazy load.
640 /// Skipped when a writer is busy, this thread included: a later load evicts then.
641 pub(crate) fn try_evict(&self) {
642 let Some(limit) = self.ctl.limit else {
643 return;
644 };
645 let _writer = match self.writer.try_lock() {
646 Ok(g) => g,
647 Err(std::sync::TryLockError::Poisoned(p)) => p.into_inner(),
648 Err(std::sync::TryLockError::WouldBlock) => return,
649 };
650 let current = self.load();
651 if let Some(data) = crate::evict::plan(¤t.data, limit, &self.ctl) {
652 let mut next = Snapshot::new(
653 current.meta.clone(),
654 data,
655 current.locale.clone(),
656 current.version + 1,
657 );
658 // the same answers: the public version stays, only the cache key moves
659 next.public = current.public;
660 self.publish(next);
661 }
662 }
663}
664
665/// What a lookup found, carried out of the snapshot closure.
666enum Found {
667 Text(String),
668 /// A subtree: the key comes back, `missing` is not called.
669 Node,
670 /// Nothing in any layer: the locale to report.
671 Miss(Option<Arc<str>>),
672}
673
674/// The translation catalog: `Arc` inside, cheap to clone, `Send + Sync + 'static`.
675///
676/// Each thread caches up to four snapshots (one per instance it read last), so a read
677/// takes no lock. When the last handle is dropped, the next read on every other thread
678/// frees that thread's cached snapshot of it; a thread that never reads again keeps at
679/// most four snapshots until it reads or exits.
680///
681/// Texts are stored once for the life of the process, shared by every instance (equal
682/// texts are one copy): [`I18n::t`] and [`I18n::get`] return them as plain `&str` with no
683/// reference count. Dropping an instance, a `reload` or an evicted page frees the maps,
684/// not the texts; a reload adds only texts not seen before.
685///
686/// ```
687/// use i18n_next::I18n;
688///
689/// let i18n = I18n::builder()
690/// .locale("de")
691/// .fallback("en")
692/// .messages("en", None, r#"{"nav": {"home": "Home", "about": "About"}}"#)
693/// .messages("de", None, r#"{"nav": {"home": "Startseite"}}"#)
694/// .messages("de", Some("settings"), r#"{"title": "Einstellungen"}"#)
695/// .build()?;
696/// assert_eq!(i18n.t("nav.home"), "Startseite");
697/// assert_eq!(i18n.t("nav.about"), "About"); // from the fallback
698/// assert_eq!(i18n.page("settings").t("title"), "Einstellungen");
699/// assert_eq!(i18n.get("nav.nope"), None);
700/// # Ok::<(), i18n_next::Error>(())
701/// ```
702#[derive(Clone)]
703pub struct I18n {
704 pub(crate) inner: Arc<Inner>,
705}
706
707/// Public facts about one locale: from `i18n.json`, builder calls and the files found.
708#[derive(Debug, Clone, PartialEq, Eq)]
709#[non_exhaustive]
710pub struct LocaleInfo {
711 /// The locale code, as in file names (`de-at`).
712 pub code: String,
713 /// The BCP 47 tag for plurals and formats (`de-AT`), when set.
714 pub iso: Option<String>,
715 /// Text direction for the frontend (`rtl`), when set.
716 pub dir: Option<String>,
717 /// `displayName` from `i18n.json`, when set.
718 pub display_name: Option<String>,
719}
720
721impl fmt::Debug for I18n {
722 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723 let snap = self.inner.load();
724 f.debug_struct("I18n")
725 .field("locale", &snap.locale)
726 .field("version", &snap.public)
727 .field("loads", &self.inner.ctl.loads.load(Ordering::Relaxed))
728 .finish_non_exhaustive()
729 }
730}
731
732/// Validates a name passed in code for a chunk: not empty, not `__proto__`.
733pub(crate) fn chunk_names(locale: &str, page: Option<&str>) -> Result<(), Error> {
734 if locale.is_empty() || locale == "__proto__" {
735 return Err(Error::UnknownLocale(locale.to_owned()));
736 }
737 match page {
738 Some("__proto__") => Err(Error::UnknownPage("__proto__".to_owned())),
739 _ => Ok(()),
740 }
741}
742
743/// `messages:<locale>/<page>`: the path of text passed in code, in errors.
744pub(crate) fn messages_path(locale: &str, page: Option<&str>) -> String {
745 let page = page.filter(|p| !p.is_empty()).unwrap_or("index");
746 let mut path = String::with_capacity(10 + locale.len() + page.len());
747 path.push_str("messages:");
748 path.push_str(locale);
749 path.push('/');
750 path.push_str(page);
751 path
752}
753
754impl I18n {
755 /// Starts a builder.
756 #[must_use]
757 pub fn builder() -> Builder {
758 Builder::default()
759 }
760
761 /// `resolve` without parameters: the stored text (interned, [`crate::intern`]), the key
762 /// on a miss or a subtree.
763 fn translate<'k>(&self, locale: Option<&str>, page: Option<&str>, key: &'k str) -> &'k str {
764 if key.is_empty() {
765 return key;
766 }
767 let report = self.inner.missing.is_some() || crate::trace::MISSES;
768 let found = self.inner.read(|s| match s.lookup(locale, page, key) {
769 // a subtree has no text: the key, not reported
770 Some(e) => Ok(e.text()),
771 None => Err((report && locale.is_none()).then(|| s.locale.clone())),
772 });
773 match found {
774 Ok(text) => text.unwrap_or(key),
775 Err(active) => {
776 self.report(locale.or(active.as_deref()), page, key);
777 key
778 }
779 }
780 }
781
782 fn resolve(
783 &self,
784 locale: Option<&str>,
785 page: Option<&str>,
786 key: &str,
787 args: Option<&Args<'_>>,
788 ) -> String {
789 if key.is_empty() {
790 return String::new();
791 }
792 let report = self.inner.missing.is_some() || crate::trace::MISSES;
793 let found = self.inner.read(|s| match s.lookup(locale, page, key) {
794 Some(Entry::Msg(Msg::Text(t))) => Found::Text(match args {
795 Some(a) => t.interpolate(a),
796 None => String::from(t.raw),
797 }),
798 // `t` reads the whole string, pipes and all (JS `t`)
799 Some(Entry::Msg(Msg::Plural(p))) => Found::Text(match args {
800 Some(a) => p.text.interpolate(a),
801 None => String::from(p.text.raw),
802 }),
803 Some(Entry::Value(v)) => Found::Text(String::from(&**v)),
804 Some(Entry::Node) => Found::Node,
805 None => Found::Miss((report && locale.is_none()).then(|| s.locale.clone())),
806 });
807 match found {
808 Found::Text(s) => s,
809 Found::Node => key.to_owned(),
810 Found::Miss(active) => {
811 self.report(locale.or(active.as_deref()), page, key);
812 match args.and_then(|a| a.default_text().map(|d| (a, d))) {
813 Some((a, d)) => interpolate_once(d, a),
814 None => key.to_owned(),
815 }
816 }
817 }
818 }
819
820 /// A miss: the `missing` handler and, with `tracing`, a `warn!`.
821 #[cold]
822 pub(crate) fn report(&self, locale: Option<&str>, page: Option<&str>, key: &str) {
823 let code = locale.unwrap_or("");
824 let page = page.filter(|p| !p.is_empty()).unwrap_or("index");
825 if let Some(missing) = &self.inner.missing {
826 missing(code, key, page);
827 }
828 crate::trace::missing(code, page, key);
829 }
830
831 /// `tc` of `core/src/base.ts` with the default plural rule (`defaultPlural`).
832 fn resolve_count(
833 &self,
834 locale: Option<&str>,
835 page: Option<&str>,
836 key: &str,
837 count: Count,
838 args: Option<&Args<'_>>,
839 ) -> String {
840 let report = self.inner.missing.is_some() || crate::trace::MISSES;
841 let params = WithCount { args, count };
842 let found = self.inner.read(|s| {
843 let plural = match locale {
844 None => s.plural,
845 Some(code) => s.plural_of(code),
846 };
847 match s.lookup(locale, page, key) {
848 Some(Entry::Msg(Msg::Text(t))) => Found::Text(t.single_form(¶ms)),
849 Some(Entry::Msg(Msg::Plural(p))) => Found::Text(p.pick(count, plural, ¶ms)),
850 // A number is its own one form; a boolean or a subtree has no plural.
851 Some(Entry::Value(v)) if !matches!(&**v, "true" | "false") => {
852 Found::Text(String::from(&**v))
853 }
854 Some(_) => Found::Node,
855 None => Found::Miss((report && locale.is_none()).then(|| s.locale.clone())),
856 }
857 });
858 match found {
859 Found::Text(s) => s,
860 Found::Node => count_fallback(key, ¶ms),
861 Found::Miss(active) => {
862 self.report(locale.or(active.as_deref()), page, key);
863 count_fallback(key, ¶ms)
864 }
865 }
866 }
867
868 fn peek(&self, locale: Option<&str>, page: Option<&str>, key: &str) -> Option<&'static str> {
869 self.inner
870 .read(|s| s.lookup(locale, page, key).and_then(Entry::text))
871 }
872
873 fn has_in(&self, locale: Option<&str>, page: Option<&str>, key: &str) -> bool {
874 self.inner.read(|s| s.has(locale, page, key))
875 }
876
877 /// The text of `key` in the active locale: page layers, root, then the fallback chain.
878 ///
879 /// No interpolation (`{name}` stays as written). A number or boolean comes back as JS
880 /// prints it. A miss calls `missing(locale, key, "index")` and returns the key; a
881 /// subtree returns the key without calling it; `t("")` is `""`.
882 ///
883 /// No allocation and no reference count: catalog texts are stored once for the life of
884 /// the process ([`I18n`] notes the memory this keeps), so the `&str` stays valid
885 /// through `set_locale`, `reload` and page eviction.
886 ///
887 /// ```
888 /// use i18n_next::I18n;
889 /// let i18n = I18n::builder().messages("en", None, r#"{"hi": "Hello"}"#).build()?;
890 /// assert_eq!(i18n.t("hi"), "Hello");
891 /// assert_eq!(i18n.t("nope"), "nope");
892 /// # Ok::<(), i18n_next::Error>(())
893 /// ```
894 #[must_use]
895 pub fn t<'k>(&self, key: &'k str) -> &'k str {
896 self.translate(None, None, key)
897 }
898
899 /// [`I18n::t`] with parameters and an optional default ([`Args::or`]). Strings are
900 /// interpolated; numbers and booleans are returned as is. On a miss the default is
901 /// interpolated, else the key comes back as written.
902 #[must_use]
903 pub fn t_with(&self, key: &str, args: &Args<'_>) -> String {
904 self.resolve(None, None, key, Some(args))
905 }
906
907 /// The plural form of `key` for `count`, with `{count}` filled (JS `tc(key, count)`).
908 ///
909 /// A value `a | b | c` is split once at load; the form goes by the plural rules of the
910 /// locale's `iso` (else its code), as `@i18n-micro/core` `pluralForm` picks it:
911 /// - `=0 none | one | many`: the first form for 0, the others by CLDR category;
912 /// - `none | {count} apple | {count} apples`-like templates with a zero form and one
913 /// form per category the locale's small counts reach (≥ 3 of them, as in `ru`): by
914 /// category;
915 /// - anything else by index: form `count`, the last one past the end.
916 ///
917 /// A negative, fractional or non-finite count takes the last form; an unknown tag the
918 /// index rule. Forms are trimmed. A string without `|` is its own one form, a number
919 /// is returned as JS prints it. A boolean or a subtree returns the key, a miss calls
920 /// `missing` and returns the key. Exactly one allocation: the result.
921 ///
922 /// ```
923 /// use i18n_next::I18n;
924 ///
925 /// let i18n = I18n::builder()
926 /// .locale("ru")
927 /// .messages("ru", None, r#"{"apples": "нет яблок | {count} яблоко | {count} яблока | {count} яблок",
928 /// "cars": "car | cars"}"#)
929 /// .build()?;
930 /// assert_eq!(i18n.tc("apples", 0), "нет яблок");
931 /// assert_eq!(i18n.tc("apples", 21), "21 яблоко");
932 /// assert_eq!(i18n.tc("apples", 3), "3 яблока");
933 /// assert_eq!(i18n.tc("apples", 11), "11 яблок");
934 /// assert_eq!(i18n.tc("cars", 1), "cars"); // index rule: form 1
935 /// # Ok::<(), i18n_next::Error>(())
936 /// ```
937 #[must_use]
938 pub fn tc(&self, key: &str, count: impl Into<Count>) -> String {
939 self.resolve_count(None, None, key, count.into(), None)
940 }
941
942 /// [`I18n::tc`] with parameters and an optional default (JS `tc(key, { count, ...params },
943 /// default)`). `{count}` is always `count`. On a miss, a boolean or a subtree the default
944 /// is interpolated (an empty one stays empty, unlike `t_with`), else the key comes back.
945 ///
946 /// ```
947 /// use i18n_next::{Args, I18n};
948 ///
949 /// let i18n = I18n::builder()
950 /// .messages("en", None, r#"{"inbox": "{name}, no mail | {name}, one mail | {name}, {count} mails"}"#)
951 /// .build()?;
952 /// assert_eq!(i18n.tc_with("inbox", 5, &Args::new().str("name", "Ann")), "Ann, 5 mails");
953 /// assert_eq!(i18n.tc_with("nope", 2, &Args::new().or("{count} items")), "2 items");
954 /// # Ok::<(), i18n_next::Error>(())
955 /// ```
956 #[must_use]
957 pub fn tc_with(&self, key: &str, count: impl Into<Count>, args: &Args<'_>) -> String {
958 self.resolve_count(None, None, key, count.into(), Some(args))
959 }
960
961 /// The raw stored text of `key` (no interpolation), `None` on a miss or a subtree.
962 /// Never calls `missing`; no allocation, no reference count (as [`I18n::t`]).
963 #[must_use]
964 pub fn get(&self, key: &str) -> Option<&'static str> {
965 self.peek(None, None, key)
966 }
967
968 /// Whether the active locale itself has `key` (a subtree counts), not its fallbacks.
969 #[must_use]
970 pub fn has(&self, key: &str) -> bool {
971 self.has_in(None, None, key)
972 }
973
974 /// A cheap view of one page: page layer first, then the root, down the chain.
975 /// `""` and `"index"` are the root; a page with no chunk reads the root only.
976 #[must_use]
977 pub fn page(&self, name: &str) -> View {
978 View {
979 i18n: self.clone(),
980 locale: None,
981 page: Some(Arc::from(name)),
982 }
983 }
984
985 /// A cheap view in another locale, without switching the active one. A locale that
986 /// is not known has nothing of its own: lookups go to the global fallback alone, misses
987 /// call `missing` with that code. A disabled locale reads its own chain, as in Nuxt.
988 #[must_use]
989 pub fn with_locale(&self, code: &str) -> View {
990 View {
991 i18n: self.clone(),
992 locale: Some(Arc::from(code)),
993 page: None,
994 }
995 }
996
997 /// Switches the active locale for every reader (a new snapshot, version + 1; the same
998 /// locale is no change).
999 ///
1000 /// # Errors
1001 /// [`Error::DisabledLocale`] for a locale `i18n.json` disables, [`Error::UnknownLocale`]
1002 /// for one no file, config or builder call names. Nothing changes then.
1003 pub fn set_locale(&self, code: &str) -> Result<(), Error> {
1004 self.inner.write(|s| {
1005 if s.meta.disabled(code) {
1006 return Err(Error::DisabledLocale(code.to_owned()));
1007 }
1008 let Some((locale, active)) = s.chains.get_key_value(code) else {
1009 return Err(Error::UnknownLocale(code.to_owned()));
1010 };
1011 if &*s.locale == code {
1012 return Ok(None);
1013 }
1014 // Same data, same chains: only the active pointer moves (no rebuild).
1015 Ok(Some(Snapshot {
1016 version: s.version + 1,
1017 public: s.public + 1,
1018 locale: locale.clone(),
1019 data: s.data.clone(),
1020 chains: s.chains.clone(),
1021 active: active.clone(),
1022 own: s.data.get(code).cloned(),
1023 fallback: s.fallback.clone(),
1024 plural: s.plural_of(code),
1025 plurals: s.plurals.clone(),
1026 #[cfg(feature = "format")]
1027 number: s.number_of(code),
1028 #[cfg(feature = "format")]
1029 numbers: s.numbers.clone(),
1030 meta: s.meta.clone(),
1031 }))
1032 })?;
1033 Ok(())
1034 }
1035
1036 /// The active locale, shared: no allocation.
1037 #[must_use]
1038 pub fn locale(&self) -> Arc<str> {
1039 self.inner.read(|s| s.locale.clone())
1040 }
1041
1042 /// Known locales that are not disabled: `i18n.json` order first, then the rest by code.
1043 #[must_use]
1044 pub fn locales(&self) -> Vec<LocaleInfo> {
1045 self.inner.read(Snapshot::locale_infos)
1046 }
1047
1048 /// Known page names (from files, `messages` and aliases), sorted.
1049 #[must_use]
1050 pub fn pages(&self) -> Vec<String> {
1051 self.inner.read(|s| {
1052 let mut pages: Vec<String> = s
1053 .data
1054 .values()
1055 .flat_map(|d| d.pages.keys())
1056 .chain(s.meta.aliases.keys())
1057 .map(|p| String::from(&**p))
1058 .collect();
1059 pages.sort_unstable();
1060 pages.dedup();
1061 pages
1062 })
1063 }
1064
1065 /// Whether `code` is one of [`I18n::locales`] (known, not disabled), without building
1066 /// the list: what a name from the front end is checked against (8b.2).
1067 ///
1068 /// ```
1069 /// let i18n = i18n_next::I18n::builder()
1070 /// .config_json(r#"{"locales": [{"code": "en"}, {"code": "es", "disabled": true}]}"#)
1071 /// .messages("de", None, "{}")
1072 /// .build()?;
1073 /// assert!(i18n.has_locale("en") && i18n.has_locale("de"));
1074 /// assert!(!i18n.has_locale("es") && !i18n.has_locale("fr"));
1075 /// # Ok::<(), i18n_next::Error>(())
1076 /// ```
1077 #[must_use]
1078 pub fn has_locale(&self, code: &str) -> bool {
1079 self.inner.read(|s| {
1080 let meta = &s.meta;
1081 match meta.configured.iter().find(|l| l.code == code) {
1082 Some(l) => !l.disabled,
1083 None => s.data.contains_key(code) || meta.declared.iter().any(|d| &**d == code),
1084 }
1085 })
1086 }
1087
1088 /// Whether `name` is one of [`I18n::pages`], without building the list.
1089 ///
1090 /// ```
1091 /// let i18n = i18n_next::I18n::builder()
1092 /// .messages("en", Some("settings"), "{}")
1093 /// .page_alias("prefs", "settings")
1094 /// .build()?;
1095 /// assert!(i18n.has_page("settings") && i18n.has_page("prefs"));
1096 /// assert!(!i18n.has_page("index") && !i18n.has_page("about"));
1097 /// # Ok::<(), i18n_next::Error>(())
1098 /// ```
1099 #[must_use]
1100 pub fn has_page(&self, name: &str) -> bool {
1101 self.inner.read(|s| {
1102 s.meta.aliases.contains_key(name) || s.data.values().any(|d| d.pages.contains_key(name))
1103 })
1104 }
1105
1106 /// Deep-merges a JSON object into the `(locale, page)` chunk (`None`, `""` or `"index"`
1107 /// = the root; an alias writes to its target). Incoming values win, objects merge.
1108 /// Readers see it in a new snapshot (version + 1); a new locale becomes known.
1109 ///
1110 /// A lazy pair is loaded first, so the messages go over its files; a remote pair
1111 /// that is not in yet keeps them until its files arrive. Messages added here are not
1112 /// kept by [`I18n::reload`]: it rebuilds from the builder's sources.
1113 ///
1114 /// # Errors
1115 /// [`Error::Json`] / [`Error::NotObject`] with the path `messages:<locale>/<page>`,
1116 /// [`Error::UnknownLocale`] / [`Error::UnknownPage`] for an empty or `__proto__` name.
1117 pub fn add_messages(&self, locale: &str, page: Option<&str>, json: &str) -> Result<(), Error> {
1118 chunk_names(locale, page)?;
1119 let tree = Tree::parse(json.as_bytes(), &messages_path(locale, page))?;
1120 self.inner.write(|s| {
1121 let mut data = DataMap::clone(&s.data);
1122 let mut slot = data
1123 .get(locale)
1124 .map(|d| LocaleData::clone(d))
1125 .unwrap_or_default();
1126 merge_into(&mut slot, s.meta.page(page), tree);
1127 data.insert(Arc::from(locale), Arc::new(slot));
1128 Ok(Some(Snapshot::new(
1129 s.meta.clone(),
1130 data,
1131 s.locale.clone(),
1132 s.version + 1,
1133 )))
1134 })?;
1135 Ok(())
1136 }
1137
1138 /// Reads every source of the builder again (`dir` files, `files`, `extend`,
1139 /// `messages`; lazy pairs start unloaded, remote files are missing again until the
1140 /// next `ensure_async` / `add_file`) and publishes the result: version + 1,
1141 /// subscribers notified. Readers keep answering from the old snapshot until the new one
1142 /// is in. The active locale stays; messages added with `add_messages` are dropped.
1143 ///
1144 /// ```
1145 /// use i18n_next::I18n;
1146 ///
1147 /// let i18n = I18n::builder().messages("en", None, r#"{"a": "A"}"#).build()?;
1148 /// i18n.add_messages("en", None, r#"{"a": "patched"}"#)?;
1149 /// i18n.reload()?;
1150 /// assert_eq!((i18n.t("a"), i18n.version()), ("A".into(), 2));
1151 /// # Ok::<(), i18n_next::Error>(())
1152 /// ```
1153 ///
1154 /// # Errors
1155 /// What [`Builder::build`] returns for a source that cannot be read; the catalog stays
1156 /// as it was.
1157 pub fn reload(&self) -> Result<(), Error> {
1158 let timer = crate::trace::Timer::start();
1159 let inner = &*self.inner;
1160 let mut broken = Vec::new();
1161 inner.write(|s| {
1162 let mut data = source::load(&inner.sources, &s.meta, &inner.ctl)?;
1163 // linked messages again, over what was read again (M3, linked.rs)
1164 if let Some(resolve) = s.meta.linked {
1165 broken = resolve(&mut data, &s.meta);
1166 check::lock(&s.meta.check.broken).clone_from(&broken);
1167 }
1168 let data = data.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
1169 Ok(Some(Snapshot::new(
1170 s.meta.clone(),
1171 data,
1172 s.locale.clone(),
1173 s.version + 1,
1174 )))
1175 })?;
1176 timer.done("reload", "", 0);
1177 // after the writer is released: a handler may write to the catalog
1178 report_broken(inner.missing.as_ref(), &broken);
1179 Ok(())
1180 }
1181
1182 /// The catalog version: 0 after `build`, + 1 per change of what lookups answer (the
1183 /// [`Change::version`] listeners get). A page eviction changes no answer and keeps it.
1184 /// Only grows.
1185 #[must_use]
1186 pub fn version(&self) -> u64 {
1187 self.inner.read(|s| s.public)
1188 }
1189}
1190
1191#[cfg(feature = "payload")]
1192impl I18n {
1193 /// Replaces each `(locale, page)` chunk with its tree (`payload::apply`) and switches to
1194 /// `locale` unless it is disabled: one new snapshot, subscribers notified.
1195 /// The loaded root (`None`) or page chunk of `locale` as stored: a guest that connects
1196 /// again moves the chunks it had into its new instance instead of reading them.
1197 #[cfg(all(feature = "tauri-guest", target_arch = "wasm32", target_os = "unknown"))]
1198 pub(crate) fn ready_chunk(&self, locale: &str, page: Option<&str>) -> Option<Arc<Tree>> {
1199 self.inner
1200 .read(|s| match s.data.get(locale)?.layer(s.meta.page(page))? {
1201 Layer::Ready(c) => Some(c.clone()),
1202 Layer::Lazy(_) => None,
1203 })
1204 }
1205
1206 pub(crate) fn replace_chunks(
1207 &self,
1208 chunks: Vec<(Arc<str>, Option<String>, Arc<Tree>)>,
1209 locale: Option<&str>,
1210 ) -> Result<(), Error> {
1211 self.inner.write(|s| {
1212 let mut data = DataMap::clone(&s.data);
1213 // one copy of a locale's data however many of its chunks come
1214 let mut slots: Vec<(Arc<str>, LocaleData)> = Vec::new();
1215 for (code, page, tree) in &chunks {
1216 let at = match slots.iter().position(|(c, _)| c == code) {
1217 Some(at) => at,
1218 None => {
1219 let slot = data.get(code).map(|d| LocaleData::clone(d));
1220 slots.push((code.clone(), slot.unwrap_or_default()));
1221 slots.len() - 1
1222 }
1223 };
1224 put(
1225 &mut slots[at].1,
1226 s.meta.page(page.as_deref()),
1227 Layer::Ready(tree.clone()),
1228 );
1229 }
1230 for (code, slot) in slots {
1231 data.insert(code, Arc::new(slot));
1232 }
1233 let active = match locale {
1234 Some(l) if !s.meta.disabled(l) => Arc::from(l),
1235 _ => s.locale.clone(),
1236 };
1237 Ok(Some(Snapshot::new(
1238 s.meta.clone(),
1239 data,
1240 active,
1241 s.version + 1,
1242 )))
1243 })?;
1244 Ok(())
1245 }
1246}
1247
1248/// What `tc` returns without a plural: the default interpolated (an empty one stays, JS
1249/// `defaultValue ? interpolate(defaultValue, values) : defaultValue ?? key`), else the key.
1250fn count_fallback(key: &str, params: &WithCount<'_, '_>) -> String {
1251 match params.args.and_then(Args::default_raw) {
1252 Some("") => String::new(),
1253 Some(d) => interpolate_once(d, params),
1254 None => key.to_owned(),
1255 }
1256}
1257
1258/// Merges `tree` into a copy of the root (`None`) or page chunk of `slot`: the old chunk
1259/// stays as it is for readers of older snapshots. A lazy chunk is loaded first and becomes
1260/// a ready one (never evicted: nothing would restore the messages); a remote one that is
1261/// not in yet keeps the tree until its files arrive.
1262fn merge_into(slot: &mut LocaleData, page: Option<&str>, tree: Tree) {
1263 let layer = slot.layer(page);
1264 let chunk = match layer {
1265 // A remote pair answers its partial view before its files are in: not loaded.
1266 Some(Layer::Lazy(cell)) => match if cell.remote {
1267 cell.loaded()
1268 } else {
1269 cell.get()
1270 } {
1271 Some(loaded) => Some(loaded),
1272 None => {
1273 let waiting = Layer::Lazy(Arc::new(cell.with_over(tree)));
1274 put(slot, page, waiting);
1275 return;
1276 }
1277 },
1278 Some(Layer::Ready(c)) => Some(&**c),
1279 None => None,
1280 };
1281 let mut merged = chunk.cloned().unwrap_or_default();
1282 merged.merge(tree);
1283 put(slot, page, Layer::Ready(Arc::new(merged)));
1284}
1285
1286fn put(slot: &mut LocaleData, page: Option<&str>, chunk: Layer) {
1287 match page {
1288 None => slot.root = Some(chunk),
1289 Some(p) => {
1290 slot.pages.insert(Arc::from(p), chunk);
1291 }
1292 }
1293}
1294
1295/// A cheap view of an [`I18n`]: one page and/or another locale, with the same lookups.
1296/// `Clone + Send + Sync + 'static`; it reads the live catalog, so it sees later changes.
1297///
1298/// ```
1299/// use i18n_next::I18n;
1300///
1301/// let i18n = I18n::builder()
1302/// .locale("en")
1303/// .messages("en", None, r#"{"title": "App", "ok": "OK"}"#)
1304/// .messages("en", Some("settings"), r#"{"title": "Settings"}"#)
1305/// .messages("de", Some("settings"), r#"{"title": "Einstellungen"}"#)
1306/// .build()?;
1307/// let settings = i18n.page("settings");
1308/// assert_eq!(settings.t("title"), "Settings");
1309/// assert_eq!(settings.t("ok"), "OK"); // page → root
1310/// assert_eq!(i18n.with_locale("de").page("settings").t("title"), "Einstellungen");
1311/// # Ok::<(), i18n_next::Error>(())
1312/// ```
1313#[derive(Clone)]
1314pub struct View {
1315 pub(crate) i18n: I18n,
1316 pub(crate) locale: Option<Arc<str>>,
1317 pub(crate) page: Option<Arc<str>>,
1318}
1319
1320impl fmt::Debug for View {
1321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1322 f.debug_struct("View")
1323 .field("locale", &self.locale)
1324 .field("page", &self.page)
1325 .finish_non_exhaustive()
1326 }
1327}
1328
1329impl View {
1330 fn parts(&self) -> (Option<&str>, Option<&str>) {
1331 (self.locale.as_deref(), self.page.as_deref())
1332 }
1333
1334 /// [`I18n::t`] in this view.
1335 #[must_use]
1336 pub fn t<'k>(&self, key: &'k str) -> &'k str {
1337 let (l, p) = self.parts();
1338 self.i18n.translate(l, p, key)
1339 }
1340
1341 /// [`I18n::t_with`] in this view.
1342 #[must_use]
1343 pub fn t_with(&self, key: &str, args: &Args<'_>) -> String {
1344 let (l, p) = self.parts();
1345 self.i18n.resolve(l, p, key, Some(args))
1346 }
1347
1348 /// [`I18n::tc`] in this view: the plural rules of this view's locale.
1349 #[must_use]
1350 pub fn tc(&self, key: &str, count: impl Into<Count>) -> String {
1351 let (l, p) = self.parts();
1352 self.i18n.resolve_count(l, p, key, count.into(), None)
1353 }
1354
1355 /// [`I18n::tc_with`] in this view.
1356 #[must_use]
1357 pub fn tc_with(&self, key: &str, count: impl Into<Count>, args: &Args<'_>) -> String {
1358 let (l, p) = self.parts();
1359 self.i18n.resolve_count(l, p, key, count.into(), Some(args))
1360 }
1361
1362 /// [`I18n::get`] in this view.
1363 #[must_use]
1364 pub fn get(&self, key: &str) -> Option<&'static str> {
1365 let (l, p) = self.parts();
1366 self.i18n.peek(l, p, key)
1367 }
1368
1369 /// [`I18n::has`] in this view: this view's locale only, page then root.
1370 #[must_use]
1371 pub fn has(&self, key: &str) -> bool {
1372 let (l, p) = self.parts();
1373 self.i18n.has_in(l, p, key)
1374 }
1375
1376 /// The same view on another page.
1377 #[must_use]
1378 pub fn page(&self, name: &str) -> View {
1379 View {
1380 page: Some(Arc::from(name)),
1381 ..self.clone()
1382 }
1383 }
1384
1385 /// The same view in another locale (see [`I18n::with_locale`]).
1386 #[must_use]
1387 pub fn with_locale(&self, code: &str) -> View {
1388 View {
1389 locale: Some(Arc::from(code)),
1390 ..self.clone()
1391 }
1392 }
1393
1394 /// The locale this view reads: its own, or the active one. Shared: no allocation.
1395 #[must_use]
1396 pub fn locale(&self) -> Arc<str> {
1397 match &self.locale {
1398 Some(l) => l.clone(),
1399 None => self.i18n.locale(),
1400 }
1401 }
1402}
1403
1404enum ConfigSource {
1405 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
1406 Path(std::path::PathBuf),
1407 Json(String),
1408}
1409
1410/// Builds an [`I18n`]. Every call is optional; later calls of the same kind add to or
1411/// override earlier ones, builder calls override `i18n.json`.
1412///
1413/// ```
1414/// use i18n_next::I18n;
1415///
1416/// let i18n = I18n::builder()
1417/// .config_json(r#"{"defaultLocale": "de-at", "fallbackLocale": "en",
1418/// "locales": [{"code": "de-at", "fallbackLocale": "de"}]}"#)
1419/// .files([
1420/// ("en.json", br#"{"a": "en", "b": "en", "c": "en"}"#.as_slice()),
1421/// ("de.json", br#"{"a": "de", "b": "de"}"#),
1422/// ("de-at.json", br#"{"a": "at"}"#),
1423/// ])
1424/// .build()?;
1425/// assert_eq!([i18n.t("a"), i18n.t("b"), i18n.t("c")], ["at", "de", "en"]);
1426/// # Ok::<(), i18n_next::Error>(())
1427/// ```
1428#[derive(Default)]
1429pub struct Builder {
1430 locale: Option<String>,
1431 fallback: Option<String>,
1432 links: Vec<(String, String)>,
1433 iso: Vec<(String, String)>,
1434 sources: Sources,
1435 aliases: Vec<(String, String)>,
1436 config: Option<ConfigSource>,
1437 missing: Option<Missing>,
1438 /// `linked_messages(true)`: the resolver, as a pointer so an app that never turns links
1439 /// on links none of their code (no case tables in its `.wasm`).
1440 linked: Option<ResolveLinked>,
1441 /// `formats(json)` texts, in call order.
1442 #[cfg(feature = "format")]
1443 pub(crate) formats: Vec<String>,
1444 /// `datetime_formats(json)` texts, in call order.
1445 #[cfg(feature = "format")]
1446 pub(crate) datetime_formats: Vec<String>,
1447 #[cfg(feature = "format")]
1448 time_zone: Option<String>,
1449 #[cfg(feature = "format")]
1450 clock: Option<crate::format::api::Clock>,
1451 /// [`setup_dates`], set by the calls that can bring date formats or a zone: a builder
1452 /// that never does links none of the date options or zones (`.wasm` size).
1453 #[cfg(feature = "format")]
1454 dates: Option<SetupDates>,
1455}
1456
1457#[cfg(feature = "format")]
1458type SetupDates =
1459 fn(&Builder, &Config, &mut Meta, &mut crate::format::options::Numbering) -> Result<(), Error>;
1460
1461/// Reads the named date formats (`i18n.json`, then the builder's) and the builder's zone.
1462#[cfg(feature = "format")]
1463fn setup_dates(
1464 b: &Builder,
1465 config: &Config,
1466 meta: &mut Meta,
1467 numbering: &mut crate::format::options::Numbering,
1468) -> Result<(), Error> {
1469 if let Some(json) = &config.datetime_formats {
1470 let path = b.config_path();
1471 crate::format::parse_date_formats(json, &path, &mut meta.dates, numbering)?;
1472 }
1473 for json in &b.datetime_formats {
1474 crate::format::parse_date_formats(json, "datetime_formats", &mut meta.dates, numbering)?;
1475 }
1476 // an empty zone is none, as `FormatService({ timeZone: "" })` (the system's)
1477 if let Some(name) = b.time_zone.as_ref().filter(|n| !n.is_empty()) {
1478 let zone = crate::format::date::zone_named(name)
1479 .ok_or_else(|| Error::UnknownTimeZone(name.clone()))?;
1480 meta.zone = Some(zone);
1481 meta.zone_name = Some(Box::from(name.as_str()));
1482 }
1483 Ok(())
1484}
1485
1486impl fmt::Debug for Builder {
1487 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1488 f.debug_struct("Builder")
1489 .field("locale", &self.locale)
1490 .field("fallback", &self.fallback)
1491 .field("files", &self.sources.files.len())
1492 .finish_non_exhaustive()
1493 }
1494}
1495
1496impl Builder {
1497 /// The active locale at start (else `defaultLocale` of `i18n.json`, else `en`). It is a
1498 /// known locale even with no file of its own: it reads its chain.
1499 #[must_use]
1500 pub fn locale(mut self, code: &str) -> Self {
1501 self.locale = Some(code.to_owned());
1502 self
1503 }
1504
1505 /// Named number formats, `numberFormats` of Vue I18n and `i18n.json`: `{"<locale>":
1506 /// {"<name>": {<Intl.NumberFormat options>}}}`, for [`I18n::tn_as`]. Over the ones of
1507 /// `i18n.json` (a name given again wins). A name is looked up by the locale code, then
1508 /// shorter (`zh-Hant-TW` → `zh-Hant` → `zh`); the number formats by the locale's `iso`.
1509 /// Options outside the supported subset fail `build` with
1510 /// [`Error::UnsupportedFormat`]. Feature `format`.
1511 ///
1512 /// ```
1513 /// use i18n_next::I18n;
1514 ///
1515 /// let i18n = I18n::builder()
1516 /// .iso("de", "de-DE")
1517 /// .locale("de")
1518 /// .formats(r#"{"de": {"price": {"style": "currency", "currency": "EUR"}}}"#)
1519 /// .build()?;
1520 /// assert_eq!(i18n.tn_as(1234.5, "price"), "1.234,50\u{a0}€");
1521 /// assert!(I18n::builder().formats(r#"{"de": {"x": {"signDisplay": "always"}}}"#).build().is_err());
1522 /// # Ok::<(), i18n_next::Error>(())
1523 /// ```
1524 #[cfg(feature = "format")]
1525 #[must_use]
1526 pub fn formats(mut self, number_formats: &str) -> Self {
1527 self.formats.push(number_formats.to_owned());
1528 self
1529 }
1530
1531 /// Named date formats, `datetimeFormats` of Vue I18n and `i18n.json`: `{"<locale>":
1532 /// {"<name>": {<Intl.DateTimeFormat options>}}}`, for [`I18n::td_as`]. Over the ones of
1533 /// `i18n.json` (a name given again wins), looked up like [`Builder::formats`]. Supported
1534 /// (DESIGN 5.3): `dateStyle`, `timeStyle` (`medium`, `short`), `weekday`, `year`,
1535 /// `month`, `day`, `hour`, `minute`, `second`, `hour12`, `hourCycle`, `timeZone` (IANA;
1536 /// UTC only without the `tz` feature), `calendar: "gregory"`; anything else (`timeStyle:
1537 /// "full"`, `timeZoneName`, `era`, …) and values `Intl` throws on fail `build` with
1538 /// [`Error::UnsupportedFormat`]. Feature `format`.
1539 ///
1540 /// ```
1541 /// use i18n_next::I18n;
1542 ///
1543 /// let i18n = I18n::builder()
1544 /// .time_zone("UTC")
1545 /// .locale("de")
1546 /// .datetime_formats(r#"{"de": {"short": {"day": "numeric", "month": "short"}}}"#)
1547 /// .build()?;
1548 /// assert_eq!(i18n.td_as(1_704_428_640_000i64, "short"), "5. Jan.");
1549 /// assert!(I18n::builder().datetime_formats(r#"{"de": {"x": {"timeStyle": "full"}}}"#).build().is_err());
1550 /// # Ok::<(), i18n_next::Error>(())
1551 /// ```
1552 #[cfg(feature = "format")]
1553 #[must_use]
1554 pub fn datetime_formats(mut self, datetime_formats: &str) -> Self {
1555 self.datetime_formats.push(datetime_formats.to_owned());
1556 self.with_dates()
1557 }
1558
1559 /// Links [`setup_dates`] into `build` (a no-op without `format`).
1560 #[allow(unused_mut, reason = "mutates with `format` only")]
1561 fn with_dates(mut self) -> Self {
1562 #[cfg(feature = "format")]
1563 {
1564 self.dates = Some(setup_dates);
1565 }
1566 self
1567 }
1568
1569 /// The IANA time zone of dates (JS `FormatService({ timeZone })`); a named format's own
1570 /// `timeZone` wins. Default: the system's (`TZ`, `/etc/localtime`, the browser's); an
1571 /// empty name is the default too, as in JS. Names are taken as `Intl` takes them: in any
1572 /// ASCII case (`europe/berlin`), IANA links and ICU's legacy aliases (`US/Pacific-New`),
1573 /// offsets `+05:30` / `-0800` / `+05`. Without the `tz` feature only UTC is known. An
1574 /// unknown zone fails `build` with [`Error::UnknownTimeZone`]. Feature `format`.
1575 ///
1576 /// ```
1577 /// use i18n_next::I18n;
1578 ///
1579 /// let i18n = I18n::builder().time_zone("UTC").build()?;
1580 /// assert_eq!(i18n.td(0), "1/1/1970");
1581 /// assert!(I18n::builder().time_zone("Mars/Olympus").build().is_err());
1582 /// # Ok::<(), i18n_next::Error>(())
1583 /// ```
1584 #[cfg(feature = "format")]
1585 #[must_use]
1586 pub fn time_zone(mut self, iana: &str) -> Self {
1587 self.time_zone = Some(iana.to_owned());
1588 self.with_dates()
1589 }
1590
1591 /// The clock of [`I18n::tdr`] in milliseconds since 1970 (JS `FormatService({ now })`):
1592 /// a test pins it, a server hands the client its time. Default: the system clock
1593 /// (`SystemTime`; in the browser `Date.now()` with the `tz` feature). Its range is a JS
1594 /// `Date`'s, ±8.64e15 ms: outside it there is no now, and [`I18n::tdr`] shows
1595 /// `Invalid Date`, as JS does with an `Invalid Date` clock. Feature `format`.
1596 ///
1597 /// ```
1598 /// use i18n_next::I18n;
1599 ///
1600 /// let i18n = I18n::builder().clock(|| 1_704_428_640_000).build()?;
1601 /// assert_eq!(i18n.tdr(1_704_428_640_000i64 + 61_000), "in 1 minute");
1602 /// # Ok::<(), i18n_next::Error>(())
1603 /// ```
1604 #[cfg(feature = "format")]
1605 #[must_use]
1606 pub fn clock(mut self, now: impl Fn() -> i64 + Send + Sync + 'static) -> Self {
1607 self.clock = Some(crate::format::api::Clock(Arc::new(now)));
1608 self
1609 }
1610
1611 /// The global fallback: the weakest layer of every chain. The code becomes a known
1612 /// locale (listed by `locales`, accepted by `set_locale`).
1613 #[must_use]
1614 pub fn fallback(mut self, code: &str) -> Self {
1615 self.fallback = Some(code.to_owned());
1616 self
1617 }
1618
1619 /// A chain step: `locale` falls back to `fallback` before the global fallback
1620 /// (`de-at → de → en`). Both codes become known locales, so a regional locale with no
1621 /// file of its own (`de-ch → de`) can be the active one. A cycle (`a → b → a`) stops
1622 /// at the first repeat.
1623 #[must_use]
1624 pub fn fallback_for(mut self, locale: &str, fallback: &str) -> Self {
1625 self.links.push((locale.to_owned(), fallback.to_owned()));
1626 self
1627 }
1628
1629 /// The BCP 47 tag of a locale code (`ua` → `uk-UA`) for plurals and formats: `tc` goes
1630 /// by its rules. Without one, the code itself is the tag; a tag `Intl.PluralRules`
1631 /// rejects or does not know (`en_US`, `xx`) gets the index rule. The code becomes a
1632 /// known locale.
1633 #[must_use]
1634 pub fn iso(mut self, code: &str, tag: &str) -> Self {
1635 self.iso.push((code.to_owned(), tag.to_owned()));
1636 self
1637 }
1638
1639 /// Reads every root and page file under `path` at `build` (not on
1640 /// `wasm32-unknown-unknown`: use [`Builder::files`] there).
1641 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
1642 #[must_use]
1643 pub fn dir(mut self, path: impl AsRef<std::path::Path>) -> Self {
1644 self.sources.dirs.push(path.as_ref().to_path_buf());
1645 self
1646 }
1647
1648 /// Embedded files with the same layout as a directory (`en.json`,
1649 /// `pages/settings/en.json`): the way to ship locales on Android and in the browser.
1650 #[must_use]
1651 pub fn files<I, P, B>(mut self, files: I) -> Self
1652 where
1653 I: IntoIterator<Item = (P, B)>,
1654 P: AsRef<str>,
1655 B: AsRef<[u8]>,
1656 {
1657 self.sources.files.extend(embedded(files));
1658 self
1659 }
1660
1661 /// Lists the root and page files under `path` at `build` without reading them: each
1662 /// `(locale, page)` file is read on the first lookup that reaches its layer, once (not
1663 /// on `wasm32-unknown-unknown`). A file that cannot be read then is skipped and
1664 /// reported (stderr in debug builds, or `tracing`): its layer stays empty.
1665 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
1666 #[must_use]
1667 pub fn lazy_dir(mut self, path: impl AsRef<std::path::Path>) -> Self {
1668 self.sources.lazy_dirs.push(path.as_ref().to_path_buf());
1669 self.sources.lazy = Some(source::LAZY);
1670 self
1671 }
1672
1673 /// Embedded files like [`Builder::files`], parsed on first use of their
1674 /// `(locale, page)` pair instead of at `build`, once.
1675 ///
1676 /// ```
1677 /// use i18n_next::I18n;
1678 ///
1679 /// let i18n = I18n::builder()
1680 /// .lazy_files([("en.json", br#"{"a": "A"}"#.as_slice()), ("pages/big/en.json", br#"{"b": "B"}"#)])
1681 /// .build()?;
1682 /// assert_eq!(i18n.pages(), ["big"]); // known from the name, not read yet
1683 /// assert_eq!(i18n.page("big").t("b"), "B"); // read now
1684 /// # Ok::<(), i18n_next::Error>(())
1685 /// ```
1686 #[must_use]
1687 pub fn lazy_files<I, P, B>(mut self, files: I) -> Self
1688 where
1689 I: IntoIterator<Item = (P, B)>,
1690 P: AsRef<str>,
1691 B: AsRef<[u8]>,
1692 {
1693 self.sources.lazy_files.extend(embedded(files));
1694 self.sources.lazy = Some(source::LAZY);
1695 self
1696 }
1697
1698 /// The files the app will bring itself, as paths in the locales layout (`de.json`,
1699 /// `pages/settings/de.json`): known pairs, nothing loaded. A lookup answers from what
1700 /// is in; [`I18n::ensure_async`] fetches what a locale and page lack,
1701 /// [`I18n::add_file`] adds bytes fetched by hand. Paths outside the layout are ignored.
1702 #[must_use]
1703 pub fn remote<I>(mut self, manifest: I) -> Self
1704 where
1705 I: IntoIterator,
1706 I::Item: AsRef<str>,
1707 {
1708 self.sources
1709 .remote
1710 .extend(manifest.into_iter().map(|p| source::normalize(p.as_ref())));
1711 self.sources.lazy = Some(source::LAZY);
1712 self
1713 }
1714
1715 /// Locale files of a library (8b.4), merged under the app's own: every `extend` call is
1716 /// one layer, later calls over earlier ones, and the app's files and messages over all
1717 /// of them, deep-merged per `(locale, page)`. The app can override any library string.
1718 ///
1719 /// ```
1720 /// use i18n_next::I18n;
1721 ///
1722 /// let i18n = I18n::builder()
1723 /// .extend([("en.json", br#"{"ui": {"ok": "OK", "cancel": "Cancel"}}"#.as_slice())])
1724 /// .files([("en.json", br#"{"ui": {"ok": "Fine"}}"#.as_slice())])
1725 /// .build()?;
1726 /// assert_eq!((i18n.t("ui.ok"), i18n.t("ui.cancel")), ("Fine".into(), "Cancel".into()));
1727 /// # Ok::<(), i18n_next::Error>(())
1728 /// ```
1729 #[must_use]
1730 pub fn extend<I, P, B>(mut self, files: I) -> Self
1731 where
1732 I: IntoIterator<Item = (P, B)>,
1733 P: AsRef<str>,
1734 B: AsRef<[u8]>,
1735 {
1736 self.sources.extend.push(embedded(files).collect());
1737 self
1738 }
1739
1740 /// Keeps at most `n` lazily loaded pages (at least 1) and evicts the least recently
1741 /// used beyond that (8b.16). Never evicted: root chunks, pairs with `messages` /
1742 /// `add_messages`, ready (eager) chunks and pinned pages. An evicted local page loads
1743 /// again on its next use, with the same answers; a remote one is missing until the next
1744 /// `ensure_async`. Off by default.
1745 #[must_use]
1746 pub fn evict_pages(mut self, n: usize) -> Self {
1747 self.sources.evict = Some(n.max(1));
1748 self
1749 }
1750
1751 /// Never evicts page `name` (Rust-only pages of the native UI: `tray`, `menu`).
1752 #[must_use]
1753 pub fn pin_page(mut self, name: &str) -> Self {
1754 self.sources.pins.push(name.to_owned());
1755 self
1756 }
1757
1758 /// A JSON object for the `(locale, page)` chunk (`None` = root), merged after files.
1759 #[must_use]
1760 pub fn messages(mut self, locale: &str, page: Option<&str>, json: &str) -> Self {
1761 self.sources
1762 .messages
1763 .push((locale.to_owned(), page.map(str::to_owned), json.to_owned()));
1764 self
1765 }
1766
1767 /// `false` folds page files into the root chunk (`disablePageLocales`): files merge in
1768 /// path order (JS `<`), and a page file wins over the root file on the same key in
1769 /// either order. A [`Builder::page_alias`] then names nothing: it reads the root.
1770 #[must_use]
1771 pub fn pages(mut self, enabled: bool) -> Self {
1772 self.sources.no_pages = !enabled;
1773 self
1774 }
1775
1776 /// Page `from` reads the chunk of page `to` (`routesLocaleLinks`).
1777 #[must_use]
1778 pub fn page_alias(mut self, from: &str, to: &str) -> Self {
1779 self.aliases.push((from.to_owned(), to.to_owned()));
1780 self
1781 }
1782
1783 /// Reads `i18n.json` from `path` at `build` (not on `wasm32-unknown-unknown`).
1784 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
1785 #[must_use]
1786 pub fn config(mut self, path: impl AsRef<std::path::Path>) -> Self {
1787 self.config = Some(ConfigSource::Path(path.as_ref().to_path_buf()));
1788 self.with_dates()
1789 }
1790
1791 /// `i18n.json` as text: `defaultLocale`, `fallbackLocale`, `locales[]` (`code`, `iso`,
1792 /// `dir`, `displayName`, `fallbackLocale`, `disabled`); formats are kept for later.
1793 #[must_use]
1794 pub fn config_json(mut self, json: &str) -> Self {
1795 self.config = Some(ConfigSource::Json(json.to_owned()));
1796 self.with_dates()
1797 }
1798
1799 /// Called on every miss of `t` / `t_with` / `tc` / `tc_with` with `(locale, key, page)`;
1800 /// the root page is `"index"`. Not called for `get`, `has`, a subtree, a
1801 /// boolean under `tc` or `t("")`. It runs with no lock held, so it may call the
1802 /// catalog, writes included (`add_messages`).
1803 ///
1804 /// The instance owns the handler: a handler that captures a clone of the same [`I18n`]
1805 /// makes a reference cycle and the catalog is never freed. Keep the instance in an
1806 /// `Arc<I18n>` and capture `Arc::downgrade` of it instead.
1807 #[must_use]
1808 pub fn missing(mut self, handler: impl Fn(&str, &str, &str) + Send + Sync + 'static) -> Self {
1809 self.missing = Some(Box::new(handler));
1810 self
1811 }
1812
1813 /// Resolves linked messages at `build` (`@:key`, `@.upper:key`, `@.lower:key`,
1814 /// `@.capitalize:key`, `@:{'key'}`), as the Nuxt module's `linkedMessages: true`: each
1815 /// `(locale, page)` view is resolved over everything it reads (its page, root and fallback
1816 /// locales), the case modifiers by the locale's `iso`. Lookups then read plain text: no
1817 /// cost at `t`. A link to a missing key, a subtree or a cycle leaves the whole message as
1818 /// written and calls `missing(locale, key, page)` once; [`I18n::check`] lists it. Off by
1819 /// default: `@:` may be plain text. Text added later with `add_messages` is not resolved.
1820 ///
1821 /// ```
1822 /// use i18n_next::I18n;
1823 ///
1824 /// let i18n = I18n::builder()
1825 /// .linked_messages(true)
1826 /// .messages("en", None, r#"{"brand": "acme", "title": "Welcome to @:brand",
1827 /// "shout": "@.upper:brand", "intro": "@.capitalize:{'brand'}."}"#)
1828 /// .build()?;
1829 /// assert_eq!(i18n.t("title"), "Welcome to acme");
1830 /// assert_eq!(i18n.t("shout"), "ACME");
1831 /// assert_eq!(i18n.t("intro"), "Acme.");
1832 /// # Ok::<(), i18n_next::Error>(())
1833 /// ```
1834 #[must_use]
1835 pub fn linked_messages(mut self, enabled: bool) -> Self {
1836 self.linked = enabled.then_some(resolve_linked as ResolveLinked);
1837 self
1838 }
1839
1840 /// How errors name the config.
1841 #[cfg(feature = "format")]
1842 fn config_path(&self) -> String {
1843 match &self.config {
1844 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
1845 Some(ConfigSource::Path(path)) => path.to_string_lossy().into_owned(),
1846 _ => "i18n.json".to_owned(),
1847 }
1848 }
1849
1850 fn read_config(&self) -> Result<Config, Error> {
1851 match &self.config {
1852 None => Ok(Config::default()),
1853 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
1854 Some(ConfigSource::Path(path)) => {
1855 let shown = path.to_string_lossy();
1856 let bytes = std::fs::read(path).map_err(|source| Error::Io {
1857 path: shown.clone().into_owned(),
1858 source,
1859 })?;
1860 Config::parse(&bytes, &shown)
1861 }
1862 Some(ConfigSource::Json(json)) => Config::parse(json.as_bytes(), "i18n.json"),
1863 }
1864 }
1865
1866 /// [`Builder::build`], then [`install`](crate::install) as the global instance.
1867 ///
1868 /// # Errors
1869 /// What `build` returns, or [`Error::AlreadyInstalled`].
1870 #[cfg(feature = "global")]
1871 pub fn install(self) -> Result<&'static I18n, Error> {
1872 crate::scope::install(self.build()?)?;
1873 crate::scope::global().ok_or(Error::NotInstalled)
1874 }
1875
1876 /// Reads everything and builds the catalog.
1877 ///
1878 /// # Errors
1879 /// [`Error::Io`], [`Error::Json`], [`Error::NotObject`] with the file path (a broken
1880 /// file is never skipped), [`Error::Config`] for a malformed `i18n.json`,
1881 /// [`Error::DisabledLocale`] when the start locale is disabled, [`Error::UnknownPage`]
1882 /// for an alias to a page nothing defines, [`Error::UnknownLocale`] for an empty or
1883 /// `__proto__` locale in `messages`.
1884 pub fn build(mut self) -> Result<I18n, Error> {
1885 let config = self.read_config()?;
1886 let mut meta = Meta {
1887 fallback: self
1888 .fallback
1889 .as_deref()
1890 .or(config.fallback_locale.as_deref())
1891 .map(Arc::from),
1892 ..Meta::default()
1893 };
1894 #[cfg(feature = "format")]
1895 let mut numbering = Vec::new();
1896 #[cfg(feature = "format")]
1897 {
1898 if let Some(json) = &config.number_formats {
1899 let path = self.config_path();
1900 crate::format::parse_formats(json, &path, &mut meta.numbers, &mut numbering)?;
1901 }
1902 for json in &self.formats {
1903 crate::format::parse_formats(json, "formats", &mut meta.numbers, &mut numbering)?;
1904 }
1905 if let Some(setup) = self.dates {
1906 setup(&self, &config, &mut meta, &mut numbering)?;
1907 }
1908 meta.clock = self.clock.take();
1909 }
1910 for l in &config.locales {
1911 if let Some(fb) = &l.fallback {
1912 meta.links.insert(Arc::from(&*l.code), Arc::from(&**fb));
1913 }
1914 if let Some(iso) = &l.iso {
1915 meta.iso.insert(Arc::from(&*l.code), Arc::from(&**iso));
1916 }
1917 }
1918 for (l, fb) in &self.links {
1919 meta.links.insert(Arc::from(&**l), Arc::from(&**fb));
1920 }
1921 for (code, tag) in &self.iso {
1922 meta.iso.insert(Arc::from(&**code), Arc::from(&**tag));
1923 }
1924 #[cfg(feature = "format")]
1925 crate::format::options::check_numbering(&numbering, |code| meta.number(code))?;
1926 #[cfg(feature = "payload")]
1927 {
1928 meta.formats = crate::payload::Formats::new(&self, &config);
1929 }
1930 meta.configured = config.locales;
1931 let locale: Arc<str> = Arc::from(
1932 self.locale
1933 .as_deref()
1934 .or(config.default_locale.as_deref())
1935 .unwrap_or("en"),
1936 );
1937 let mut declared = Vec::new();
1938 let mut declare = |code: &str| {
1939 if !declared.iter().any(|d: &Arc<str>| &**d == code) {
1940 declared.push(Arc::from(code));
1941 }
1942 };
1943 for code in [self.locale.as_deref(), config.default_locale.as_deref()]
1944 .into_iter()
1945 .flatten()
1946 {
1947 declare(code);
1948 }
1949 declare(&locale);
1950 for (code, fallback) in &meta.links {
1951 declare(code);
1952 declare(fallback);
1953 }
1954 for code in meta.fallback.iter().chain(meta.iso.keys()) {
1955 declare(code);
1956 }
1957 meta.declared = declared;
1958 if meta.disabled(&locale) {
1959 return Err(Error::DisabledLocale(String::from(&*locale)));
1960 }
1961
1962 for (from, to) in &self.aliases {
1963 meta.aliases.insert(Arc::from(&**from), Arc::from(&**to));
1964 }
1965 let ctl = Arc::new(LazyCtl::new(self.sources.evict));
1966 self.sources.parse_files()?;
1967 let mut data = source::load(&self.sources, &meta, &ctl)?;
1968 // Folded pages: an alias resolves to a page with no chunk, which reads the root.
1969 if !self.sources.no_pages {
1970 for to in meta.aliases.values() {
1971 let defined = &**to == "index" || data.values().any(|d| d.pages.contains_key(to));
1972 if !defined {
1973 return Err(Error::UnknownPage(String::from(&**to)));
1974 }
1975 }
1976 }
1977
1978 // ---- linked messages and check() (M3, linked.rs / check.rs) ----
1979 meta.check.reference = Some(
1980 config
1981 .default_locale
1982 .as_deref()
1983 .map_or_else(|| locale.clone(), Arc::from),
1984 );
1985 meta.linked = self.linked;
1986 if let Some(resolve) = self.linked {
1987 let broken = resolve(&mut data, &meta);
1988 report_broken(self.missing.as_ref(), &broken);
1989 *check::lock(&meta.check.broken) = broken;
1990 }
1991
1992 let data = data.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
1993 let snapshot = Snapshot::new(Arc::new(meta), data, locale, 0);
1994 let inner = Arc::new(Inner {
1995 id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
1996 version: AtomicU64::new(0),
1997 state: RwLock::new(Arc::new(snapshot)),
1998 writer: Mutex::new(()),
1999 missing: self.missing,
2000 alive: Arc::new(AtomicBool::new(true)),
2001 remote: source::remote_index(&self.sources),
2002 sources: self.sources,
2003 ctl: ctl.clone(),
2004 listeners: Listeners::default(),
2005 });
2006 let _ = ctl.owner.set(Arc::downgrade(&inner));
2007 Ok(I18n { inner })
2008 }
2009}
2010
2011// ---- linked messages and check() (M3, linked.rs / check.rs) ----
2012
2013/// [`resolve_linked`] as the builder keeps it.
2014type ResolveLinked = fn(&mut FastMap<Arc<str>, LocaleData>, &Meta) -> Vec<crate::linked::Broken>;
2015
2016/// Reports each message `broken` left as written once through `missing`. Called with no
2017/// lock held: the handler may write to the catalog.
2018fn report_broken(missing: Option<&Missing>, broken: &[crate::linked::Broken]) {
2019 let Some(missing) = missing else { return };
2020 let mut last = None;
2021 for b in broken {
2022 let at = (&b.locale, &b.page, &b.key);
2023 if last != Some(at) {
2024 missing(&b.locale, &b.key, b.page.as_deref().unwrap_or("index"));
2025 last = Some(at);
2026 }
2027 }
2028}
2029
2030/// Resolves the linked messages of `data` (`linked.rs`): the ready chunks go into one ordered
2031/// map and back; each lazy or remote pair gets what it needs to resolve its own messages when
2032/// it loads ([`crate::lazy::LinkCtx`]). Returns the links that left a message as written.
2033fn resolve_linked(
2034 data: &mut FastMap<Arc<str>, LocaleData>,
2035 meta: &Meta,
2036) -> Vec<crate::linked::Broken> {
2037 let mut chunks = crate::linked::Chunks::new();
2038 for (code, d) in data.iter_mut() {
2039 if let Some(Layer::Ready(c)) = d.root.take_if(|l| matches!(l, Layer::Ready(_))) {
2040 chunks.push(((code.clone(), None), c));
2041 }
2042 let ready: Vec<Arc<str>> = d
2043 .pages
2044 .iter()
2045 .filter(|(_, l)| matches!(l, Layer::Ready(_)))
2046 .map(|(p, _)| p.clone())
2047 .collect();
2048 for p in ready {
2049 if let Some(Layer::Ready(c)) = d.pages.remove(&p) {
2050 chunks.push(((code.clone(), Some(p)), c));
2051 }
2052 }
2053 }
2054 chunks.sort_unstable_by(|a, b| a.0.cmp(&b.0));
2055 let setup = crate::linked::Setup {
2056 links: &meta.links,
2057 fallback: meta.fallback.as_deref(),
2058 iso: &meta.iso,
2059 };
2060 let mut broken = crate::linked::resolve(&mut chunks, &setup);
2061 // a lazy pair keeps its cell: what was stored for its view is dropped, it resolves its
2062 // own messages when it loads
2063 for ((code, page), chunk) in chunks {
2064 let d = data.entry(code).or_default();
2065 match page {
2066 None if matches!(d.root, Some(Layer::Lazy(_))) => {}
2067 None => d.root = Some(Layer::Ready(chunk)),
2068 Some(p) if matches!(d.pages.get(&p), Some(Layer::Lazy(_))) => {}
2069 Some(p) => {
2070 d.pages.insert(p, Layer::Ready(chunk));
2071 }
2072 }
2073 }
2074 crate::linked::lazy_contexts(data, &setup);
2075 crate::linked::mark_lazy(&mut broken, data, &setup);
2076 broken
2077}
2078
2079impl I18n {
2080 /// Checks the catalog (DESIGN 8b.8): pages with a file in only some locales, keys of
2081 /// the default locale missing elsewhere, `{placeholders}` that differ from the default
2082 /// locale's, plural form counts that do not fit the locale's CLDR categories, links that
2083 /// left a linked message as written. Disabled locales are skipped. Meant for tests:
2084 /// `assert!(i18n.check().is_clean(), "{}", i18n.check())`.
2085 #[must_use]
2086 pub fn check(&self) -> CheckReport {
2087 self.inner.read(|s| {
2088 let meta = &s.meta;
2089 let chunks = s
2090 .data
2091 .iter()
2092 .filter(|(code, _)| !meta.disabled(code))
2093 .flat_map(|(code, d)| {
2094 let root = d
2095 .root
2096 .iter()
2097 .filter_map(move |l| Some((code, None, l.chunk()?)));
2098 let pages = d.pages.iter();
2099 root.chain(pages.filter_map(move |(p, l)| Some((code, Some(p), l.chunk()?))))
2100 });
2101 check::run(chunks, &meta.check, |code| s.plural_of(code))
2102 })
2103 }
2104}
2105
2106/// `(path with '/', shared bytes)` of embedded files.
2107fn embedded<I, P, B>(files: I) -> impl Iterator<Item = (String, source::Bytes)>
2108where
2109 I: IntoIterator<Item = (P, B)>,
2110 P: AsRef<str>,
2111 B: AsRef<[u8]>,
2112{
2113 files
2114 .into_iter()
2115 .map(|(p, b)| (source::normalize(p.as_ref()), Arc::from(b.as_ref())))
2116}