1pub mod detect;
23
24use std::collections::{BTreeMap, HashMap};
25
26use serde::{Deserialize, Deserializer, Serialize};
27
28use crate::core::signatures::ExpectedDomain;
29
30pub const CATALOG_DATA: &str = include_str!("data/catalog.json");
32
33#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
35pub struct Locale(String);
36
37impl Locale {
38 pub fn new(value: &str) -> Locale {
40 Locale(value.trim().to_ascii_lowercase())
41 }
42
43 pub fn as_str(&self) -> &str {
45 &self.0
46 }
47}
48
49impl<'de> Deserialize<'de> for Locale {
50 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
51 where
52 D: Deserializer<'de>,
53 {
54 let value = String::deserialize(deserializer)?;
55 Ok(Self::new(&value))
56 }
57}
58
59impl std::fmt::Display for Locale {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 f.write_str(&self.0)
62 }
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67pub enum Kind {
68 Structural = 0,
70 Action = 1,
72 Value = 2,
74 Event = 3,
76 Operator = 4,
78 Enum = 5,
80 Setting = 6,
82}
83
84impl Kind {
85 pub const NUM_KINDS: usize = 7;
86
87 pub const fn as_index(self) -> usize {
88 self as usize
89 }
90
91 pub fn as_str(self) -> &'static str {
92 match self {
93 Kind::Structural => "structural",
94 Kind::Action => "action",
95 Kind::Value => "value",
96 Kind::Event => "event",
97 Kind::Operator => "operator",
98 Kind::Enum => "enum",
99 Kind::Setting => "setting",
100 }
101 }
102}
103
104#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
111#[serde(rename_all = "camelCase")]
112#[non_exhaustive]
113pub struct ParamCoercions {
114 #[serde(default)]
116 pub false_as_number: bool,
117 #[serde(default)]
119 pub true_as_number: bool,
120 #[serde(default)]
122 pub zero_as_null: bool,
123 #[serde(default)]
125 pub null_vector_as_null: bool,
126 #[serde(default)]
128 pub empty_array_as_string: bool,
129}
130
131#[derive(Debug, Clone)]
133pub struct CatalogEntry {
134 pub id: String,
135 pub kind: Kind,
136 pub(crate) params: Vec<String>,
138 pub(crate) param_names: Option<Vec<String>>,
140 pub(crate) param_aliases: Vec<HashMap<Locale, Vec<String>>>,
142 pub(crate) param_domains: Vec<Option<String>>,
150 pub(crate) param_defaults: Vec<Option<String>>,
154 pub(crate) param_types: Vec<Option<String>>,
157 pub(crate) param_coercions: Vec<Option<ParamCoercions>>,
159 pub(crate) return_type: Option<String>,
162 pub(crate) reevaluation_coverage: Option<BTreeMap<String, Vec<usize>>>,
169 pub(crate) variadic: bool,
171 pub(crate) aliases: HashMap<Locale, Vec<String>>,
172}
173
174#[derive(Debug, Clone)]
178pub struct LocalizedStringEntry {
179 pub id: String,
180 pub(crate) aliases: HashMap<Locale, Vec<String>>,
181}
182
183fn spelling<'a>(aliases: &'a HashMap<Locale, Vec<String>>, locale: &Locale) -> Option<&'a str> {
184 aliases
185 .get(locale)
186 .and_then(|spellings| spellings.first())
187 .map(String::as_str)
188}
189
190fn spellings_for<'a>(aliases: &'a HashMap<Locale, Vec<String>>, locale: &Locale) -> &'a [String] {
191 aliases.get(locale).map(Vec::as_slice).unwrap_or_default()
192}
193
194impl LocalizedStringEntry {
195 pub fn spelling(&self, locale: &Locale) -> Option<&str> {
197 spelling(&self.aliases, locale)
198 }
199
200 pub fn spellings(&self, locale: &Locale) -> &[String] {
202 spellings_for(&self.aliases, locale)
203 }
204}
205
206impl CatalogEntry {
207 pub fn spelling(&self, locale: &Locale) -> Option<&str> {
209 spelling(&self.aliases, locale)
210 }
211
212 pub fn spellings(&self, locale: &Locale) -> &[String] {
215 spellings_for(&self.aliases, locale)
216 }
217
218 pub fn resolve_param(&self, locale: &Locale, spelling: &str) -> Option<usize> {
221 let matches = self
222 .params
223 .iter()
224 .enumerate()
225 .filter(|(index, canonical)| {
226 canonical == &spelling
227 || self
228 .param_aliases
229 .get(*index)
230 .and_then(|aliases| aliases.get(locale))
231 .is_some_and(|aliases| aliases.iter().any(|alias| alias == spelling))
232 })
233 .map(|(index, _)| index)
234 .collect::<Vec<_>>();
235 (matches.len() == 1).then(|| matches[0])
236 }
237
238 pub fn params(&self) -> &[String] {
240 &self.params
241 }
242
243 pub fn param_count(&self) -> usize {
245 self.params.len()
246 }
247
248 pub fn param_name(&self, index: usize) -> Option<&str> {
250 let names = self.param_names.as_deref().unwrap_or(&self.params);
251 param_at(names, index, self.variadic).map(String::as_str)
252 }
253
254 pub fn required_param_count(&self) -> usize {
258 (0..self.params.len())
259 .rev()
260 .find(|index| {
261 self.param_defaults
262 .get(*index)
263 .and_then(Option::as_ref)
264 .is_none()
265 })
266 .map_or(0, |index| index + 1)
267 }
268
269 pub fn has_param_defaults(&self) -> bool {
271 self.param_defaults.iter().any(Option::is_some)
272 }
273
274 pub fn param_default(&self, index: usize) -> Option<&str> {
276 param_at(&self.param_defaults, index, self.variadic).and_then(Option::as_deref)
277 }
278
279 pub fn param_domain(&self, index: usize) -> Option<&str> {
281 param_at(&self.param_domains, index, self.variadic).and_then(Option::as_deref)
282 }
283
284 pub fn reevaluation_coverage(&self, member: &str) -> Option<&[usize]> {
293 self.reevaluation_coverage
294 .as_ref()
295 .and_then(|coverage| coverage.get(member).map(Vec::as_slice))
296 }
297
298 pub fn has_reevaluation_coverage(&self) -> bool {
301 self.reevaluation_coverage.is_some()
302 }
303
304 pub fn param_type(&self, index: usize) -> Option<&str> {
307 param_at(&self.param_types, index, self.variadic).and_then(Option::as_deref)
308 }
309
310 pub fn param_coercions(&self, index: usize) -> Option<&ParamCoercions> {
312 param_at(&self.param_coercions, index, self.variadic).and_then(Option::as_ref)
313 }
314
315 pub fn return_type(&self) -> Option<&str> {
317 self.return_type.as_deref()
318 }
319
320 pub fn is_variadic(&self) -> bool {
322 self.variadic
323 }
324}
325
326fn param_at<T>(values: &[T], index: usize, variadic: bool) -> Option<&T> {
327 values
328 .get(index)
329 .or_else(|| variadic.then(|| values.last()).flatten())
330}
331
332#[derive(Debug, Clone)]
334pub struct EnumMember {
335 pub member: String,
336 pub(crate) aliases: HashMap<Locale, Vec<String>>,
337}
338
339impl EnumMember {
340 pub fn spelling(&self, locale: &Locale) -> Option<&str> {
342 spelling(&self.aliases, locale)
343 }
344
345 pub fn spellings(&self, locale: &Locale) -> &[String] {
348 spellings_for(&self.aliases, locale)
349 }
350}
351
352#[derive(Debug, Clone)]
354pub struct EnumDomain {
355 pub domain: String,
356 pub(crate) aliases: HashMap<Locale, Vec<String>>,
357 pub members: Vec<EnumMember>,
358}
359
360impl EnumDomain {
361 pub fn spelling(&self, locale: &Locale) -> Option<&str> {
362 spelling(&self.aliases, locale)
363 }
364}
365
366#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
368#[non_exhaustive]
369pub struct TargetMeta {
370 pub game: String,
371 pub format: String,
372 pub surface: String,
373}
374
375#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
377#[serde(rename_all = "camelCase")]
378#[non_exhaustive]
379pub struct Provenance {
380 pub generator: String,
381 pub generator_version: String,
382 pub source: String,
383 pub license: String,
384 pub reviewed: bool,
385 #[serde(default, skip_serializing_if = "Vec::is_empty")]
388 pub source_notes: Vec<String>,
389}
390
391#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
395#[non_exhaustive]
396pub struct LocaleCoverage {
397 pub locale: Locale,
398 pub mapped: usize,
400 pub total: usize,
402}
403
404#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
410#[serde(rename_all = "kebab-case")]
411#[non_exhaustive]
412pub struct CatalogIdentity {
413 pub implementation_version: String,
415 pub catalog_version: String,
417 pub catalog_digest: Option<String>,
420 pub locale_coverage: Vec<LocaleCoverage>,
422 pub target: TargetMeta,
424 pub provenance: Provenance,
426}
427
428pub(crate) type MemberIndexMap = HashMap<String, HashMap<String, (usize, usize)>>;
429
430#[derive(Debug, Clone)]
432pub struct Catalog {
433 detection_index: Option<detect::AliasIndex>,
434 pub(crate) schema_version: u32,
435 pub(crate) locales: Vec<Locale>,
438 pub(crate) target: TargetMeta,
439 pub(crate) provenance: Provenance,
440 pub(crate) catalog_version: String,
442 pub(crate) catalog_digest: Option<String>,
445 pub(crate) entries: Vec<CatalogEntry>,
446 pub(crate) localized_strings: Vec<LocalizedStringEntry>,
447 pub(crate) enums: Vec<EnumDomain>,
448 pub(crate) by_id: [HashMap<String, usize>; Kind::NUM_KINDS],
449 pub(crate) alias_to_entry: HashMap<Locale, [HashMap<String, usize>; Kind::NUM_KINDS]>,
450 pub(crate) localized_string_by_id: HashMap<String, usize>,
451 pub(crate) localized_string_alias: HashMap<Locale, HashMap<String, usize>>,
452 pub(crate) enum_by_domain: HashMap<String, usize>,
453 pub(crate) enum_alias_to_domain: HashMap<Locale, HashMap<String, String>>,
454 pub(crate) enum_alias_to_member: HashMap<Locale, MemberIndexMap>,
455 pub(crate) bare_member_index: HashMap<Locale, HashMap<String, Vec<(String, String)>>>,
456}
457
458mod load;
460
461pub use load::{build_canonical, canonicalize, content_digest};
462
463impl Catalog {
464 pub(crate) fn schema_version(&self) -> u32 {
465 self.schema_version
466 }
467
468 pub fn locales(&self) -> &[Locale] {
470 &self.locales
471 }
472
473 pub fn primary_locale(&self) -> &Locale {
476 &self.locales[0]
477 }
478
479 pub fn supports(&self, locale: &Locale) -> bool {
481 self.locales.contains(locale)
482 }
483
484 pub fn catalog_version(&self) -> &str {
486 &self.catalog_version
487 }
488
489 pub fn catalog_digest(&self) -> Option<&str> {
492 self.catalog_digest.as_deref()
493 }
494
495 pub fn implementation_version() -> &'static str {
497 env!("CARGO_PKG_VERSION")
498 }
499
500 pub fn identity(&self) -> CatalogIdentity {
503 CatalogIdentity {
504 implementation_version: Self::implementation_version().to_string(),
505 catalog_version: self.catalog_version.clone(),
506 catalog_digest: self.catalog_digest.clone(),
507 locale_coverage: self
508 .locales
509 .iter()
510 .map(|locale| self.locale_coverage(locale))
511 .collect(),
512 target: self.target.clone(),
513 provenance: self.provenance.clone(),
514 }
515 }
516
517 pub fn locale_coverage(&self, locale: &Locale) -> LocaleCoverage {
522 let member_total: usize = self.enums.iter().map(|domain| domain.members.len()).sum();
523 let total = self.entries.len() + self.localized_strings.len() + member_total;
524 let mapped = self
525 .entries
526 .iter()
527 .filter(|entry| entry.aliases.contains_key(locale))
528 .count()
529 + self
530 .localized_strings
531 .iter()
532 .filter(|entry| entry.aliases.contains_key(locale))
533 .count()
534 + self
535 .enums
536 .iter()
537 .flat_map(|domain| &domain.members)
538 .filter(|member| member.aliases.contains_key(locale))
539 .count();
540 LocaleCoverage {
541 locale: locale.clone(),
542 mapped,
543 total,
544 }
545 }
546
547 pub fn locale_coverage_all(&self) -> Vec<LocaleCoverage> {
549 self.locales
550 .iter()
551 .map(|locale| self.locale_coverage(locale))
552 .collect()
553 }
554
555 pub fn entry(&self, kind: Kind, id: &str) -> Option<&CatalogEntry> {
557 self.by_id[kind.as_index()]
558 .get(id)
559 .map(|i| &self.entries[*i])
560 }
561
562 pub fn resolve(&self, kind: Kind, locale: &Locale, spelling: &str) -> Option<&CatalogEntry> {
564 self.alias_to_entry
565 .get(locale)
566 .and_then(|by_kind| by_kind[kind.as_index()].get(spelling))
567 .map(|i| &self.entries[*i])
568 }
569
570 pub fn spelling(&self, kind: Kind, locale: &Locale, id: &str) -> Option<&str> {
572 self.entry(kind, id)?.spelling(locale)
573 }
574
575 pub fn entries_of(&self, kind: Kind) -> impl Iterator<Item = &CatalogEntry> {
577 self.entries.iter().filter(move |entry| entry.kind == kind)
578 }
579
580 pub fn resolve_localized_string(
582 &self,
583 locale: &Locale,
584 spelling: &str,
585 ) -> Option<&LocalizedStringEntry> {
586 self.localized_string_alias
587 .get(locale)
588 .and_then(|map| map.get(spelling))
589 .map(|index| &self.localized_strings[*index])
590 }
591
592 pub fn localized_string_spelling(&self, locale: &Locale, id: &str) -> Option<&str> {
594 self.localized_string_by_id
595 .get(id)
596 .and_then(|i| self.localized_strings.get(*i))
597 .and_then(|entry| entry.spelling(locale))
598 }
599
600 pub fn localized_strings(&self) -> impl Iterator<Item = &LocalizedStringEntry> {
602 self.localized_strings.iter()
603 }
604
605 pub fn entry_count(&self) -> usize {
607 self.entries.len()
608 }
609
610 pub fn enum_domains_count(&self) -> usize {
612 self.enums.len()
613 }
614
615 pub fn enum_domain(&self, domain: &str) -> Option<&EnumDomain> {
617 self.enum_by_domain.get(domain).map(|i| &self.enums[*i])
618 }
619
620 pub fn resolve_enum_domain(&self, locale: &Locale, spelling: &str) -> Option<&str> {
622 self.enum_by_domain
623 .get_key_value(spelling)
624 .map(|(domain, _)| domain.as_str())
625 .or_else(|| {
626 self.enum_alias_to_domain
627 .get(locale)
628 .and_then(|map| map.get(spelling))
629 .map(String::as_str)
630 })
631 }
632
633 pub fn enum_domains(&self) -> impl Iterator<Item = &EnumDomain> {
635 self.enums.iter()
636 }
637
638 pub fn resolve_enum_member(
640 &self,
641 domain: &str,
642 locale: &Locale,
643 spelling: &str,
644 ) -> Option<(String, String)> {
645 let &(domain_index, member_index) = self
646 .enum_alias_to_member
647 .get(locale)?
648 .get(domain)?
649 .get(spelling)?;
650 Some((
651 domain.to_string(),
652 self.enums[domain_index].members[member_index]
653 .member
654 .clone(),
655 ))
656 }
657
658 pub fn enum_spelling(&self, domain: &str, locale: &Locale, member: &str) -> Option<&str> {
660 let domain_index = self.enum_by_domain.get(domain)?;
661 let domain = &self.enums[*domain_index];
662 domain
663 .members
664 .iter()
665 .find(|candidate| candidate.member == member)?
666 .spelling(locale)
667 }
668
669 pub fn localized_enum_spelling(
673 &self,
674 domain: &str,
675 locale: &Locale,
676 member: &str,
677 ) -> Option<&str> {
678 self.enum_spelling(domain, locale, member).or_else(|| {
679 (domain == "Color" && member == "WHITE").then_some(match locale.as_str() {
680 "de-de" => "Weiß",
681 "es-es" | "es-mx" => "Blanco",
682 "fr-fr" => "Blanc",
683 "it-it" => "Bianco",
684 "ja-jp" => "白",
685 "ko-kr" => "흰색",
686 "pl-pl" => "Biały",
687 "pt-br" => "Branco",
688 "ru-ru" => "Белый",
689 "th-th" => "สีขาว",
690 "tr-tr" => "Beyaz",
691 "zh-tw" => "白色",
692 _ => return None,
693 })
694 })
695 }
696
697 pub fn bare_member_matches(&self, locale: &Locale, spelling: &str) -> Vec<(String, String)> {
702 self.bare_member_index
703 .get(locale)
704 .and_then(|map| map.get(spelling))
705 .cloned()
706 .unwrap_or_default()
707 }
708
709 pub(crate) fn canonical_spellings<'a>(
714 &'a self,
715 kind: Kind,
716 locale: &'a Locale,
717 ) -> impl Iterator<Item = &'a str> {
718 self.entries_of(kind).flat_map(move |entry| {
719 std::iter::once(entry.id.as_str())
720 .chain(entry.spellings(locale).iter().map(String::as_str))
721 })
722 }
723
724 pub(crate) fn enum_member_form(
729 &self,
730 domain: &str,
731 member_spelling: &str,
732 locale: &Locale,
733 ) -> String {
734 if matches!(domain, "Hero" | "Button" | "Color" | "Map") {
735 let domain_display = self
736 .enum_domain(domain)
737 .and_then(|entry| entry.spelling(locale))
738 .unwrap_or(domain);
739 format!("{domain_display}({member_spelling})")
740 } else {
741 member_spelling.to_string()
742 }
743 }
744
745 pub(crate) fn canonical_member_spellings<'a>(
748 &'a self,
749 domain: &'a str,
750 locale: &'a Locale,
751 ) -> impl Iterator<Item = &'a str> {
752 self.enum_domain(domain)
753 .into_iter()
754 .flat_map(move |domain| {
755 domain.members.iter().flat_map(move |member| {
756 std::iter::once(member.member.as_str())
757 .chain(member.spellings(locale).iter().map(String::as_str))
758 })
759 })
760 }
761}
762
763impl ExpectedDomain for Catalog {
770 fn expected_domain(&self, catalog_id: &str, arg_index: usize) -> Option<&str> {
771 for kind in [Kind::Action, Kind::Value] {
772 if let Some(entry) = self.entry(kind, catalog_id) {
773 if let Some(domain) = entry.param_domain(arg_index) {
774 return Some(domain);
775 }
776 }
777 }
778 None
779 }
780}