1use super::Locale;
14use super::message::{MessageEvaluator, Mf2MessageEvaluator, NoOpEvaluator};
15use super::raw;
16use super::types::{
17 ContributorTerm, DateTerms, LocaleOverride, LocatorTerm, MaybeGendered, MessageSyntax,
18 MonthNames, SimpleTerm, SingularPlural, TermForm,
19};
20use crate::citation::LocatorType;
21use crate::template::ContributorRole;
22use std::collections::HashMap;
23use std::sync::Arc;
24
25impl Locale {
26 pub fn from_yaml_str(yaml: &str) -> Result<Self, String> {
32 let raw: raw::RawLocale = serde_yaml::from_str(yaml)
33 .map_err(|e| format!("Failed to parse locale YAML: {}", e))?;
34
35 Ok(Self::from_raw(raw))
36 }
37
38 pub fn load(locale_id: &str, locales_dir: &std::path::Path) -> Self {
41 let extensions = ["yaml", "yml", "json", "cbor"];
42
43 for ext in &extensions {
44 let file_name = format!("{}.{}", locale_id, ext);
45 let file_path = locales_dir.join(&file_name);
46
47 if file_path.exists() {
48 match Self::from_file(&file_path) {
49 Ok(locale) => return locale,
50 Err(e) => {
51 eprintln!(
52 "Warning: Failed to load locale {}.{}: {}",
53 locale_id, ext, e
54 );
55 }
56 }
57 }
58 }
59
60 if locale_id.contains('-') {
61 let base = locale_id.split('-').next().unwrap_or("en");
62 if let Ok(entries) = std::fs::read_dir(locales_dir) {
63 for entry in entries.flatten() {
64 let name = entry.file_name();
65 let name_str = name.to_string_lossy();
66 if (name_str.starts_with(base)
67 && extensions.iter().any(|ext| name_str.ends_with(ext)))
68 && let Ok(locale) = Self::from_file(&entry.path())
69 {
70 return locale;
71 }
72 }
73 }
74 }
75
76 Self::en_us()
77 }
78
79 pub fn from_file(path: &std::path::Path) -> Result<Self, String> {
86 let bytes =
87 std::fs::read(path).map_err(|e| format!("Failed to read locale file: {}", e))?;
88 let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("yaml");
89
90 match ext {
91 "cbor" => ciborium::de::from_reader::<raw::RawLocale, _>(std::io::Cursor::new(&bytes))
92 .map(Self::from_raw)
93 .map_err(|e| format!("Failed to parse CBOR locale: {}", e)),
94 "json" => serde_json::from_slice::<raw::RawLocale>(&bytes)
95 .map(Self::from_raw)
96 .map_err(|e| format!("Failed to parse JSON locale: {}", e)),
97 _ => {
98 let content = String::from_utf8_lossy(&bytes);
99 Self::from_yaml_str(&content)
100 }
101 }
102 }
103
104 fn from_raw(raw: raw::RawLocale) -> Self {
116 Self::from_raw_with_base(raw, Locale::en_us())
117 }
118
119 #[allow(
129 clippy::too_many_lines,
130 reason = "Complex parsing of raw locale data with multiple term types"
131 )]
132 pub(super) fn from_raw_with_base(raw: raw::RawLocale, base: Self) -> Self {
133 let punctuation_in_quote = raw.locale.starts_with("en-US")
134 || (raw.locale.starts_with("en") && !raw.locale.starts_with("en-GB"));
135
136 let mut locale = base;
137 locale.locale = raw.locale.clone();
138 Self::remove_base_messages_shadowed_by_raw_terms(&raw, &mut locale.messages);
139 locale.dates = DateTerms {
140 months: MonthNames {
141 long: raw.dates.months.long,
142 short: raw.dates.months.short,
143 },
144 seasons: raw.dates.seasons,
145 uncertainty_term: raw.dates.uncertainty_term,
146 open_ended_term: raw.dates.open_ended_term,
147 am: raw.dates.am,
148 pm: raw.dates.pm,
149 timezone_utc: raw.dates.timezone_utc,
150 before_era: raw.dates.before_era,
151 ad: raw.dates.ad,
152 bc: raw.dates.bc,
153 bce: raw.dates.bce,
154 ce: raw.dates.ce,
155 };
156 locale.punctuation_in_quote = punctuation_in_quote;
157 locale.sort_articles = Self::default_articles_for_locale(&raw.locale);
158
159 locale.locale_schema_version = raw.locale_schema_version;
160 locale.evaluation = raw.evaluation.unwrap_or_default();
161 locale.messages.extend(raw.messages);
162 locale.date_formats.extend(raw.date_formats);
163 locale.legacy_term_aliases.extend(raw.legacy_term_aliases);
164
165 if let Some(raw_vocab) = raw.vocab {
166 locale.vocab.genre.extend(raw_vocab.genre);
167 locale.vocab.medium.extend(raw_vocab.medium);
168 }
169
170 if let Some(go) = raw.grammar_options {
171 locale.grammar_options = go;
172 } else {
173 locale.grammar_options.punctuation_in_quote = locale.punctuation_in_quote;
174 }
175 locale.punctuation_in_quote = locale.grammar_options.punctuation_in_quote;
176
177 if let Some(nf) = raw.number_formats {
178 locale.number_formats = nf;
179 }
180
181 let explicit_locator_keys: std::collections::HashSet<LocatorType> = raw
182 .locators
183 .keys()
184 .filter_map(|key| Self::parse_builtin_locator_type(key))
185 .collect();
186
187 for (key, value) in &raw.locators {
188 if let Some(locator_type) = Self::parse_locator_type(key) {
189 let locator_term = LocatorTerm {
190 long: Self::extract_singular_plural(value.long.as_ref().as_ref()),
191 short: Self::extract_singular_plural(value.short.as_ref().as_ref()),
192 symbol: Self::extract_singular_plural(value.symbol.as_ref().as_ref()),
193 gender: value.gender.clone(),
194 };
195 locale.locators.insert(locator_type, locator_term);
196 }
197 }
198
199 for (key, value) in &raw.terms {
200 if let Some(locator_type) = Self::parse_builtin_locator_type(key)
201 && !explicit_locator_keys.contains(&locator_type)
202 && let Some(forms) = Self::get_forms(value)
203 {
204 let locator_term = LocatorTerm {
205 long: Self::extract_singular_plural(forms.get("long").as_ref()),
206 short: Self::extract_singular_plural(forms.get("short").as_ref()),
207 symbol: Self::extract_singular_plural(forms.get("symbol").as_ref()),
208 gender: None,
209 };
210 locale.locators.insert(locator_type, locator_term);
211 continue;
212 }
213
214 match key.as_str() {
215 "and" => {
216 if let Some(forms) = Self::get_forms(value) {
217 if let Some(v) = forms.get("long").and_then(|v| v.as_string()) {
218 locale.terms.and = Some(v.to_string());
219 }
220 if let Some(v) = forms.get("symbol").and_then(|v| v.as_string()) {
221 locale.terms.and_symbol = Some(v.to_string());
222 }
223 }
224 }
225 "et_al" => {
226 if let Some(forms) = Self::get_forms(value)
227 && let Some(v) = forms.get("long").and_then(|v| v.as_string())
228 {
229 locale.terms.et_al = Some(v.to_string());
230 }
231 }
232 "and others" | "and_others" => {
233 if let Some(forms) = Self::get_forms(value)
234 && let Some(v) = forms.get("long").and_then(|v| v.as_string())
235 {
236 locale.terms.and_others = Some(v.to_string());
237 }
238 }
239 "accessed" => {
240 if let Some(forms) = Self::get_forms(value)
241 && let Some(v) = forms.get("long").and_then(|v| v.as_string())
242 {
243 locale.terms.accessed = Some(v.to_string());
244 }
245 }
246 "ibid" => {
247 if let Some(forms) = Self::get_forms(value)
248 && let Some(v) = forms.get("long").and_then(|v| v.as_string())
249 {
250 locale.terms.ibid = Some(v.to_string());
251 }
252 }
253 "no date" => {
254 let simple = Self::extract_simple_term_from_raw(value);
255 let short_fallback = simple.short.as_default_str().to_string();
256 locale
257 .terms
258 .general
259 .insert(super::types::GeneralTerm::NoDate, simple);
260 locale.terms.no_date.get_or_insert(short_fallback);
261 }
262 "no_date" => {
263 let simple = Self::extract_simple_term_from_raw(value);
264 locale.terms.no_date = Some(simple.short.as_str().to_string());
265 locale
266 .terms
267 .general
268 .entry(super::types::GeneralTerm::NoDate)
269 .or_insert(simple);
270 }
271 _ => {
272 if let Some(general_term) = Self::parse_general_term(key) {
273 let simple = Self::extract_simple_term_from_raw(value);
274 locale.terms.general.insert(general_term, simple);
275 } else {
276 let normalized = Self::normalize_term_key(key);
277 if Self::is_known_type_term_key(&normalized) {
278 let simple = Self::extract_simple_term_from_raw(value);
279 locale.type_terms.insert(normalized, simple);
280 }
281 }
282 }
283 }
284 }
285
286 for (key, role_term) in &raw.roles {
287 if let Some(role) = Self::parse_role_name(key) {
288 let contributor_term = ContributorTerm {
289 singular: Self::extract_simple_term(&role_term.long, &role_term.short, false),
290 plural: Self::extract_simple_term(&role_term.long, &role_term.short, true),
291 verb: Self::extract_verb_term(&role_term.verb, &role_term.verb_short),
292 };
293 locale.roles.insert(role, contributor_term);
294 }
295 }
296
297 locale.evaluator = match locale.evaluation.message_syntax {
298 MessageSyntax::Mf2 => Arc::new(Mf2MessageEvaluator) as Arc<dyn MessageEvaluator>,
299 MessageSyntax::Static => Arc::new(NoOpEvaluator),
300 };
301
302 locale
303 }
304
305 fn default_articles_for_locale(locale_id: &str) -> Vec<String> {
307 #[allow(clippy::string_slice, reason = "locale_id is expected to be ASCII")]
308 let lang = &locale_id[..2.min(locale_id.len())];
309 match lang {
310 "en" => vec!["the".into(), "a".into(), "an".into()],
311 "de" => vec![
312 "der".into(),
313 "die".into(),
314 "das".into(),
315 "ein".into(),
316 "eine".into(),
317 ],
318 "fr" => vec![
319 "le".into(),
320 "la".into(),
321 "les".into(),
322 "l'".into(),
323 "un".into(),
324 "une".into(),
325 ],
326 "es" => vec![
327 "el".into(),
328 "la".into(),
329 "los".into(),
330 "las".into(),
331 "un".into(),
332 "una".into(),
333 ],
334 "it" => vec![
335 "il".into(),
336 "lo".into(),
337 "la".into(),
338 "i".into(),
339 "gli".into(),
340 "le".into(),
341 "un".into(),
342 "una".into(),
343 ],
344 "pt" => vec![
345 "o".into(),
346 "a".into(),
347 "os".into(),
348 "as".into(),
349 "um".into(),
350 "uma".into(),
351 ],
352 "nl" => vec!["de".into(), "het".into(), "een".into()],
353 _ => vec![],
354 }
355 }
356
357 fn get_forms(value: &raw::RawTermValue) -> Option<&HashMap<String, raw::RawTermValue>> {
358 match value {
359 raw::RawTermValue::Forms(forms) => Some(forms),
360 _ => None,
361 }
362 }
363
364 fn parse_locator_type(name: &str) -> Option<LocatorType> {
365 LocatorType::from_key(name).ok()
366 }
367
368 fn parse_builtin_locator_type(name: &str) -> Option<LocatorType> {
369 match Self::parse_locator_type(name)? {
370 LocatorType::Custom(_) => None,
371 locator => Some(locator),
372 }
373 }
374
375 fn parse_role_name(name: &str) -> Option<ContributorRole> {
376 match name {
377 "author" => Some(ContributorRole::Author),
378 "chair" => Some(ContributorRole::Chair),
379 "editor" => Some(ContributorRole::Editor),
380 "translator" => Some(ContributorRole::Translator),
381 "director" => Some(ContributorRole::Director),
382 "compiler" => Some(ContributorRole::Composer),
383 "illustrator" => Some(ContributorRole::Illustrator),
384 "collection-editor" => Some(ContributorRole::CollectionEditor),
385 "container-author" => Some(ContributorRole::ContainerAuthor),
386 "editorial-director" => Some(ContributorRole::EditorialDirector),
387 "textual-editor" | "textual_editor" => Some(ContributorRole::TextualEditor),
388 "interviewer" => Some(ContributorRole::Interviewer),
389 "original-author" => Some(ContributorRole::OriginalAuthor),
390 "recipient" => Some(ContributorRole::Recipient),
391 "reviewed-author" => Some(ContributorRole::ReviewedAuthor),
392 "performer" => Some(ContributorRole::Performer),
393 "composer" => Some(ContributorRole::Composer),
394 "writer" => Some(ContributorRole::Writer),
395 _ => None,
396 }
397 }
398
399 fn remove_base_messages_shadowed_by_raw_terms(
400 raw: &raw::RawLocale,
401 messages: &mut HashMap<String, String>,
402 ) {
403 for key in raw.locators.keys() {
404 if let Some(locator) = Self::parse_builtin_locator_type(key) {
405 for form in [TermForm::Long, TermForm::Short] {
406 if let Some(message_id) = Self::locator_message_id(&locator, &form) {
407 messages.remove(message_id);
408 }
409 }
410 }
411 }
412
413 for key in raw.roles.keys() {
414 if let Some(role) = Self::parse_role_name(key) {
415 for form in [
416 TermForm::Long,
417 TermForm::Short,
418 TermForm::Verb,
419 TermForm::VerbShort,
420 ] {
421 if let Some(message_id) = Self::role_message_id(&role, &form) {
422 messages.remove(message_id);
423 }
424 }
425 }
426 }
427
428 for key in raw.terms.keys() {
429 if let Some(term) = Self::parse_general_term(key) {
430 for form in [TermForm::Long, TermForm::Short] {
431 if let Some(message_id) = Self::general_message_id(&term, &form) {
432 messages.remove(message_id);
433 }
434 }
435 }
436 }
437 }
438
439 fn extract_singular_plural(value: Option<&&raw::RawTermValue>) -> Option<SingularPlural> {
440 match value {
441 Some(raw::RawTermValue::SingularPlural { singular, plural }) => Some(SingularPlural {
442 singular: Self::from_raw_gendered_string(singular),
443 plural: Self::from_raw_gendered_string(plural),
444 }),
445 Some(raw::RawTermValue::Simple(s)) => Some(SingularPlural {
446 singular: MaybeGendered::Plain(s.clone()),
447 plural: MaybeGendered::Plain(s.clone()),
448 }),
449 Some(raw::RawTermValue::Gendered {
450 masculine,
451 feminine,
452 neuter,
453 common,
454 }) => Some(SingularPlural {
455 singular: MaybeGendered::Gendered {
456 masculine: masculine.clone(),
457 feminine: feminine.clone(),
458 neuter: neuter.clone(),
459 common: common.clone(),
460 },
461 plural: MaybeGendered::Gendered {
462 masculine: masculine.clone(),
463 feminine: feminine.clone(),
464 neuter: neuter.clone(),
465 common: common.clone(),
466 },
467 }),
468 Some(raw::RawTermValue::Forms(forms)) => {
469 let singular = forms
470 .get("singular")
471 .map(Self::extract_maybe_gendered_string);
472 let plural = forms.get("plural").map(Self::extract_maybe_gendered_string);
473
474 singular.map(|s| SingularPlural {
475 plural: plural.unwrap_or_else(|| s.clone()),
476 singular: s,
477 })
478 }
479 _ => None,
480 }
481 }
482
483 fn extract_simple_term(
484 long: &Option<raw::RawTermValue>,
485 short: &Option<raw::RawTermValue>,
486 plural: bool,
487 ) -> SimpleTerm {
488 let long_str = long
489 .as_ref()
490 .map(|v| Self::extract_simple_gendered_term(v, plural))
491 .unwrap_or_default();
492
493 let short_str = short
494 .as_ref()
495 .map(|v| Self::extract_simple_gendered_term(v, plural))
496 .unwrap_or_default();
497
498 SimpleTerm {
499 long: long_str,
500 short: short_str,
501 }
502 }
503
504 fn extract_verb_term(
505 verb: &Option<raw::RawTermValue>,
506 verb_short: &Option<raw::RawTermValue>,
507 ) -> SimpleTerm {
508 let long_str = verb
509 .as_ref()
510 .and_then(|v| v.as_string())
511 .unwrap_or("")
512 .into();
513
514 let short_str = verb_short
515 .as_ref()
516 .and_then(|v| v.as_string())
517 .unwrap_or("")
518 .into();
519
520 SimpleTerm {
521 long: long_str,
522 short: short_str,
523 }
524 }
525
526 fn normalize_term_key(s: &str) -> String {
534 s.replace(['_', ' '], "-")
535 }
536
537 pub fn parse_general_term(name: &str) -> Option<super::types::GeneralTerm> {
539 use super::types::GeneralTerm;
540 match Self::normalize_term_key(name).as_str() {
541 "in" => Some(GeneralTerm::In),
542 "accessed" => Some(GeneralTerm::Accessed),
543 "cited" => Some(GeneralTerm::Cited),
544 "retrieved" => Some(GeneralTerm::Retrieved),
545 "at" => Some(GeneralTerm::At),
546 "from" => Some(GeneralTerm::From),
547 "of" => Some(GeneralTerm::Of),
548 "to" => Some(GeneralTerm::To),
549 "by" => Some(GeneralTerm::By),
550 "no-date" => Some(GeneralTerm::NoDate),
551 "anonymous" => Some(GeneralTerm::Anonymous),
552 "circa" => Some(GeneralTerm::Circa),
553 "available-at" => Some(GeneralTerm::AvailableAt),
554 "ibid" => Some(GeneralTerm::Ibid),
555 "and" => Some(GeneralTerm::And),
556 "et-al" => Some(GeneralTerm::EtAl),
557 "and-others" => Some(GeneralTerm::AndOthers),
558 "forthcoming" => Some(GeneralTerm::Forthcoming),
559 "online" => Some(GeneralTerm::Online),
560 "here" => Some(GeneralTerm::Here),
561 "deposited" => Some(GeneralTerm::Deposited),
562 "review-of" => Some(GeneralTerm::ReviewOf),
563 "original-work-published" => Some(GeneralTerm::OriginalWorkPublished),
564 "personal-communication" => Some(GeneralTerm::PersonalCommunication),
565 "patent" => Some(GeneralTerm::Patent),
566 "issued" => Some(GeneralTerm::Issued),
567 "volume" => Some(GeneralTerm::Volume),
568 "issue" => Some(GeneralTerm::Issue),
569 "page" => Some(GeneralTerm::Page),
570 "chapter" => Some(GeneralTerm::Chapter),
571 "edition" => Some(GeneralTerm::Edition),
572 "section" => Some(GeneralTerm::Section),
573 "version" => Some(GeneralTerm::Version),
574 _ => None,
575 }
576 }
577
578 fn is_known_type_term_key(normalized_key: &str) -> bool {
604 const KNOWN_TYPE_TERM_KEYS: &[&str] = &[
605 "article-journal",
606 "article-magazine",
607 "article-newspaper",
608 "broadcast",
609 "classic",
610 "collection",
611 "dataset",
612 "document",
613 "entry",
614 "entry-dictionary",
615 "entry-encyclopedia",
616 "event",
617 "graphic",
618 "hearing",
619 "interview",
620 "legal-case",
621 "legislation",
622 "manuscript",
623 "map",
624 "motion-picture",
625 "musical-score",
626 "pamphlet",
627 "paper-conference",
628 "performance",
629 "periodical",
630 "personal-communication",
631 "post",
632 "post-weblog",
633 "preprint",
634 "regulation",
635 "report",
636 "review",
637 "review-book",
638 "software",
639 "song",
640 "speech",
641 "standard",
642 "thesis",
643 "treaty",
644 "webpage",
645 ];
646 KNOWN_TYPE_TERM_KEYS.contains(&normalized_key)
647 }
648
649 fn extract_simple_term_from_raw(value: &raw::RawTermValue) -> SimpleTerm {
650 match value {
651 raw::RawTermValue::Simple(s) => SimpleTerm {
652 long: s.clone().into(),
653 short: s.clone().into(),
654 },
655 raw::RawTermValue::Gendered {
656 masculine,
657 feminine,
658 neuter,
659 common,
660 } => SimpleTerm {
661 long: MaybeGendered::Gendered {
662 masculine: masculine.clone(),
663 feminine: feminine.clone(),
664 neuter: neuter.clone(),
665 common: common.clone(),
666 },
667 short: MaybeGendered::Gendered {
668 masculine: masculine.clone(),
669 feminine: feminine.clone(),
670 neuter: neuter.clone(),
671 common: common.clone(),
672 },
673 },
674 raw::RawTermValue::Forms(forms) => {
675 let long = forms
676 .get("long")
677 .map(Self::extract_maybe_gendered_string)
678 .unwrap_or_default();
679 let short = forms
680 .get("short")
681 .map(Self::extract_maybe_gendered_string)
682 .unwrap_or_else(|| long.clone());
683 SimpleTerm { long, short }
684 }
685 raw::RawTermValue::SingularPlural { singular, .. } => SimpleTerm {
686 long: Self::from_raw_gendered_string(singular),
687 short: Self::from_raw_gendered_string(singular),
688 },
689 }
690 }
691
692 fn from_raw_gendered_string(value: &raw::RawGenderedString) -> MaybeGendered<String> {
693 match value {
694 raw::RawGenderedString::Simple(value) => MaybeGendered::Plain(value.clone()),
695 raw::RawGenderedString::Gendered {
696 masculine,
697 feminine,
698 neuter,
699 common,
700 } => MaybeGendered::Gendered {
701 masculine: masculine.clone(),
702 feminine: feminine.clone(),
703 neuter: neuter.clone(),
704 common: common.clone(),
705 },
706 }
707 }
708
709 fn extract_maybe_gendered_string(value: &raw::RawTermValue) -> MaybeGendered<String> {
710 match value {
711 raw::RawTermValue::Simple(value) => MaybeGendered::Plain(value.clone()),
712 raw::RawTermValue::Gendered {
713 masculine,
714 feminine,
715 neuter,
716 common,
717 } => MaybeGendered::Gendered {
718 masculine: masculine.clone(),
719 feminine: feminine.clone(),
720 neuter: neuter.clone(),
721 common: common.clone(),
722 },
723 raw::RawTermValue::SingularPlural { singular, .. } => {
724 Self::from_raw_gendered_string(singular)
725 }
726 raw::RawTermValue::Forms(forms) => forms
727 .get("long")
728 .or_else(|| forms.get("singular"))
729 .map(Self::extract_maybe_gendered_string)
730 .unwrap_or_default(),
731 }
732 }
733
734 fn extract_simple_gendered_term(
735 value: &raw::RawTermValue,
736 plural: bool,
737 ) -> MaybeGendered<String> {
738 match value {
739 raw::RawTermValue::Simple(value) => MaybeGendered::Plain(value.clone()),
740 raw::RawTermValue::Gendered {
741 masculine,
742 feminine,
743 neuter,
744 common,
745 } => MaybeGendered::Gendered {
746 masculine: masculine.clone(),
747 feminine: feminine.clone(),
748 neuter: neuter.clone(),
749 common: common.clone(),
750 },
751 raw::RawTermValue::SingularPlural {
752 singular,
753 plural: plural_value,
754 } => {
755 if plural {
756 Self::from_raw_gendered_string(plural_value)
757 } else {
758 Self::from_raw_gendered_string(singular)
759 }
760 }
761 raw::RawTermValue::Forms(forms) => {
762 let key = if plural { "plural" } else { "singular" };
763 forms
764 .get(key)
765 .or_else(|| forms.get("long"))
766 .map(Self::extract_maybe_gendered_string)
767 .unwrap_or_default()
768 }
769 }
770 }
771
772 pub fn apply_override(&mut self, ov: &LocaleOverride) {
780 for (k, v) in &ov.messages {
781 self.messages.insert(k.clone(), v.clone());
782 }
783 if let Some(go) = &ov.grammar_options {
784 self.grammar_options = go.clone();
785 self.punctuation_in_quote = go.punctuation_in_quote;
786 }
787 for (k, v) in &ov.legacy_term_aliases {
788 self.legacy_term_aliases.insert(k.clone(), v.clone());
789 }
790 }
791}