Skip to main content

Locale

Struct Locale 

Source
pub struct Locale {
Show 19 fields pub locale: String, pub dates: DateTerms, pub roles: HashMap<ContributorRole, ContributorTerm>, pub role_combinations: HashMap<String, ContributorTerm>, pub locators: HashMap<LocatorType, LocatorTerm>, pub terms: Terms, pub punctuation_in_quote: bool, pub sort_articles: Vec<String>, pub locale_schema_version: Option<String>, pub evaluation: EvaluationConfig, pub messages: HashMap<String, String>, pub date_formats: HashMap<String, String>, pub number_formats: NumberFormats, pub grammar_options: GrammarOptions, pub punctuation_realization: Option<PunctuationRealization>, pub legacy_term_aliases: HashMap<String, String>, pub vocab: VocabMap, pub type_terms: HashMap<String, SimpleTerm>, pub evaluator: Arc<dyn MessageEvaluator>,
}
Expand description

A locale definition containing language-specific terms and formatting rules.

The evaluator field holds the message evaluation engine, selected based on evaluation.message_syntax. This allows for trait-based swapping to ICU4X implementations in the future without changing call sites.

Fields§

§locale: String

The locale identifier (e.g., “en-US”, “de-DE”).

§dates: DateTerms

Date-related terms (months, seasons).

§roles: HashMap<ContributorRole, ContributorTerm>

Contributor role terms (editor, translator, etc.).

§role_combinations: HashMap<String, ContributorTerm>

Authored terms for combinations such as writer-director.

§locators: HashMap<LocatorType, LocatorTerm>

Locator terms (page, chapter, etc.).

§terms: Terms

General terms (and, et al., etc.).

§punctuation_in_quote: bool

Whether to place periods/commas inside quotation marks. true = American style (“text.”), false = British style (“text”.)

§sort_articles: Vec<String>

Articles to strip from titles when sorting (e.g., “the”, “a”, “an” for English). These should be lowercase and will be matched case-insensitively.

§locale_schema_version: Option<String>

Schema version from the source locale file (None = legacy v1).

§evaluation: EvaluationConfig

Runtime evaluation configuration.

§messages: HashMap<String, String>

ICU MF1 messages keyed by message ID (populated for v2 locales).

§date_formats: HashMap<String, String>

Named date format presets: symbolic name → CLDR pattern.

§number_formats: NumberFormats

Number formatting options.

§grammar_options: GrammarOptions

Grammar options.

§punctuation_realization: Option<PunctuationRealization>

Partial semantic punctuation realization table owned by this locale.

§legacy_term_aliases: HashMap<String, String>

Backwards-compatibility aliases: old term key → new message ID.

§vocab: VocabMap

Vocabulary maps for genre and medium display text.

§type_terms: HashMap<String, SimpleTerm>

Reference-type description terms, keyed by CSL-style ref_type spelling (e.g. "dataset", "article-journal"). Used by the type-label template component to resolve a localized fallback label when a reference has no genre/medium override. See docs/specs/TYPE_CLASSIFICATION_CENTRALIZATION.md.

§evaluator: Arc<dyn MessageEvaluator>

Message evaluator implementation (not serialized; set during load).

Implementations§

Source§

impl Locale

Source

pub fn resolve_date_pattern( &self, message_id: &str, year: Option<&str>, month: Option<&str>, day: Option<u32>, ) -> Option<String>

Resolve a pattern.date-* message with locale-specific year/month/day components.

Returns Some(rendered) only when the locale carries an MF2 message at message_id and the evaluator produces output. Callers fall back to the engine’s hardcoded English assembly on None.

A component is forwarded to the evaluator only when non-empty; an authored pattern that references {$day} therefore yields None if the input date carries no day, letting the caller pick a shorter form.

The day argument is taken as Option<u32> rather than a pre-formatted string so the digit-to-string allocation is deferred until after the message lookup succeeds - the common case for legacy locales (en-US, every v1 file) is the lookup miss, which now incurs zero allocation.

Source

pub fn resolve_date_range_pattern( &self, message_id: &str, start: &str, end: &str, year: Option<&str>, ) -> Option<String>

Resolve a shared-year pattern.date-range-* message with pre-formatted endpoint fragments and their common year.

The message is evaluated only for MF2 locales. Callers fall back to their established date-form assembly when a locale has not authored the requested interval pattern.

Source§

impl Locale

Source

pub fn resolve_message( &self, message_id: &str, args: &MessageArgs<'_>, ) -> Option<String>

Resolve a locale message by ID with caller-supplied MF2 arguments.

This is the public boundary for style-template message components: templates select the message ID and pass named arguments, while the active locale owns the message body and evaluator.

Source

pub fn resolve_template_message( &self, message_id: &str, args: &MessageArgs<'_>, form: Option<&TermForm>, gender: Option<GrammaticalGender>, ) -> Option<String>

Resolve a style-template message call, including term-backed message IDs.

term.* IDs are allowed to fall through to the structured locale term resolver so checked-in styles can use the message component surface without duplicating legacy term data into every locale’s messages map.

Source§

impl Locale

Source

pub fn from_yaml_str(yaml: &str) -> Result<Locale, String>

Load a locale from a YAML string.

§Errors

Returns an error when the YAML cannot be parsed into a locale.

Source

pub fn load(locale_id: &str, locales_dir: &Path) -> Locale

Load a locale by ID (e.g., “en-US”, “de-DE”) from a locales directory. Falls back to en-US if the locale file is not found.

Source

pub fn from_file(path: &Path) -> Result<Locale, String>

Load locale from a file path directly (detects format).

§Errors

Returns an error when the file cannot be read or its contents cannot be parsed as a supported locale format.

Source

pub fn parse_general_term(name: &str) -> Option<GeneralTerm>

Parse a locale term key into a structured general-term identifier.

Source

pub fn apply_override(&mut self, ov: &LocaleOverride)

Apply a partial override, merging its fields into this locale.

Performs key-by-key insertion or replacement for:

  • messages: new or updated message IDs
  • grammar_options: if Some, replaces the entire block and syncs punctuation_in_quote field
  • legacy_term_aliases: new or updated term aliases
Source§

impl Locale

Source

pub fn strip_sort_articles<'a>(&self, s: &'a str) -> &'a str

Strip leading articles from a string for sorting.

Uses locale-specific articles (e.g., “the”, “a”, “an” for English; “der”, “die”, “das” for German). Falls back to English articles if no locale-specific articles are defined.

Source§

impl Locale

Source

pub fn role_term( &self, role: &ContributorRole, plural: bool, form: &TermForm, requested_gender: Option<GrammaticalGender>, ) -> Option<&str>

Get a contributor role term.

Source

pub fn role_term_neutral( &self, role: &ContributorRole, plural: bool, form: &TermForm, ) -> Option<&str>

Resolve a contributor role term using only neutral/common values.

Source

pub fn resolved_role_term( &self, role: &ContributorRole, plural: bool, form: &TermForm, requested_gender: Option<GrammaticalGender>, ) -> Option<String>

Resolve a contributor role term, evaluating MF2 messages when configured.

Source

pub fn resolved_role_term_neutral( &self, role: &ContributorRole, plural: bool, form: &TermForm, ) -> Option<String>

Resolve a contributor role term using only neutral/common values.

Source

pub fn resolved_role_combination_term( &self, roles: &[ContributorRole], plural: bool, form: &TermForm, requested_gender: Option<GrammaticalGender>, ) -> Option<String>

Resolve an authored term for an ordered combination of contributor roles.

Source

pub fn role_conjunction(&self) -> &str

Return the locale connector used to compose a missing combined-role term.

Source

pub fn locator_term( &self, locator: &LocatorType, plural: bool, form: &TermForm, requested_gender: Option<GrammaticalGender>, ) -> Option<&str>

Get a locator term.

Source

pub fn resolved_locator_term( &self, locator: &LocatorType, plural: bool, form: &TermForm, requested_gender: Option<GrammaticalGender>, ) -> Option<String>

Resolve a locator term, evaluating MF2 messages when configured.

Source

pub fn general_term( &self, term: &GeneralTerm, form: &TermForm, requested_gender: Option<GrammaticalGender>, ) -> Option<&str>

Resolve a general term to a borrowed string.

Source

pub fn resolved_general_term( &self, term: &GeneralTerm, form: &TermForm, requested_gender: Option<GrammaticalGender>, ) -> Option<String>

Resolve a general term, evaluating MF2 messages when configured.

Source

pub fn resolved_type_term( &self, ref_type: &str, form: &TermForm, ) -> Option<String>

Resolve a reference-type description term (e.g. "dataset", "article-journal") for the type-label template component.

Looks up ref_type in Locale::type_terms directly — unlike Self::resolved_general_term, there is no MF2 message path for these terms yet, since they are dynamically keyed by an open ref_type string rather than the closed GeneralTerm enum.

Source

pub fn resolved_archive_term( &self, field: ArchiveHierarchyField, ) -> Option<String>

Resolve an archive hierarchy label, using MF2 messages. Returns singular form (count=1) by default.

Source

pub fn and_term(&self, use_symbol: bool) -> &str

Get the “and” term based on style preference.

Source

pub fn et_al(&self) -> &str

Get the “et al.” term.

Source

pub fn month_name(&self, month: u8, short: bool) -> &str

Get a month name.

Source§

impl Locale

Source

pub fn lookup_genre(&self, key: &str) -> String

Look up display text for a genre canonical key.

Falls back to a readable form of the key if no translation found.

Source

pub fn lookup_medium(&self, key: &str) -> String

Look up display text for a medium canonical key.

Falls back to a readable form of the key if no translation found.

Source§

impl Locale

Source

pub fn en_us() -> Locale

Create the English (US) locale, the fallback baseline every other locale inherits from and the default for the majority of embedded styles (which declare no info.default-locale).

This parses the embedded canonical asset (embedded/locales/en-US.yaml) so the YAML is the single source of truth — there is no separate hand-maintained Rust copy to drift out of sync with it. The parse is memoized in a std::sync::OnceLock since it is pure and immutable; callers get a clone() of the cached result (still a deep copy of its maps/vecs, but far cheaper than re-parsing the YAML) rather than re-parsing on every call.

Seeds from Locale::default() (not from_raw’s usual Locale::en_us() seed) via from_raw_with_base to avoid infinite recursion through this very function.

§Panics

Panics if the embedded en-US.yaml asset is missing, not valid UTF-8, or fails to parse. This cannot happen at runtime: the asset is embedded at compile time and covered by bundled_ar_ar_and_eu_es_locales_are_embedded_and_parseable-style tests, so a failure here indicates a broken build, not bad input.

Source

pub fn fr_ca() -> Locale

Create the Québec French locale by applying its regional typography to the bundled French lexical locale.

§Panics

Panics if either embedded French locale asset fails to parse, which indicates a broken build rather than invalid runtime input.

Source

pub fn with_term_surfaces_from(&self, item: &Locale) -> Locale

Build a rendering locale that speaks item’s terms, roles, locators, messages, and date names/patterns inside self’s (the style’s) typography and identity.

This is the options.multilingual.term-locale: item hybrid: “terms are the item speaking; typography is the document speaking” (see docs/specs/PER_ITEM_TERM_LOCALE.md §4). The field list is written out explicitly, not built by cloning self and overwriting a few fields, so that a field added to Locale later must be placed on one side of the split deliberately rather than silently inheriting the wrong one.

Trait Implementations§

Source§

impl Clone for Locale

Source§

fn clone(&self) -> Locale

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Locale

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Locale

Source§

fn default() -> Locale

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Locale

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<Locale, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<&Locale> for QuoteMarks

Source§

fn from(locale: &Locale) -> Self

Converts to this type from the input type.
Source§

impl Serialize for Locale

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.