ferrocat-po 0.13.0

Performance-first PO parsing, serialization, and catalog update primitives for ferrocat.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
use std::collections::BTreeMap;

use super::{
    ApiError, CatalogMessageKey, CatalogSemantics, NormalizedParsedCatalog,
    compile::{
        compiled_catalog_translation_kind_for_message, compiled_key_for,
        describe_compiled_id_catalogs,
    },
};

/// Translation value stored in a compiled runtime catalog.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CompiledTranslation {
    /// Singular runtime value.
    Singular(String),
    /// Structured plural runtime value.
    Plural(BTreeMap<String, String>),
}

/// Built-in key strategy used when compiling runtime catalogs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CompiledKeyStrategy {
    /// `ferrocat` v1 key format: SHA-256 over a versioned, length-delimited
    /// `msgctxt`/`msgid` payload, truncated to 64 bits and encoded as unpadded
    /// `Base64URL`.
    #[default]
    FerrocatV1,
}

/// Options controlling runtime catalog compilation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileCatalogOptions<'a> {
    /// Built-in strategy used to derive stable runtime keys.
    pub key_strategy: CompiledKeyStrategy,
    /// Whether empty source-locale values should be filled from the source text.
    pub source_fallback: bool,
    /// Source locale used when `source_fallback` is enabled.
    pub source_locale: Option<&'a str>,
    /// High-level semantics used by the input catalog set.
    pub semantics: CatalogSemantics,
}

impl Default for CompileCatalogOptions<'_> {
    fn default() -> Self {
        Self {
            key_strategy: CompiledKeyStrategy::FerrocatV1,
            source_fallback: false,
            source_locale: None,
            semantics: CatalogSemantics::IcuNative,
        }
    }
}

impl CompileCatalogOptions<'_> {
    /// Creates runtime catalog compile options with default behavior.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

/// Options controlling high-level compiled catalog artifact generation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileCatalogArtifactOptions<'a> {
    /// Locale for which the runtime artifact should be produced.
    pub requested_locale: &'a str,
    /// Source locale used for explicit source fallback behavior.
    pub source_locale: &'a str,
    /// Ordered fallback locales consulted after the requested locale.
    pub fallback_chain: &'a [String],
    /// Built-in strategy used to derive stable runtime keys.
    pub key_strategy: CompiledKeyStrategy,
    /// Whether source text should be used when no non-source translation exists.
    pub source_fallback: bool,
    /// Whether invalid final ICU messages should fail compilation instead of producing diagnostics.
    pub strict_icu: bool,
    /// Whether final ICU messages should be checked against source ICU structure.
    pub icu_compatibility: bool,
    /// High-level semantics used by the input catalog set.
    pub semantics: CatalogSemantics,
}

impl Default for CompileCatalogArtifactOptions<'_> {
    fn default() -> Self {
        Self {
            requested_locale: "",
            source_locale: "",
            fallback_chain: &[],
            key_strategy: CompiledKeyStrategy::FerrocatV1,
            source_fallback: false,
            strict_icu: false,
            icu_compatibility: false,
            semantics: CatalogSemantics::IcuNative,
        }
    }
}

impl<'a> CompileCatalogArtifactOptions<'a> {
    /// Creates artifact compile options with required locales set.
    ///
    /// Optional fields use the same defaults as [`CompileCatalogArtifactOptions::default`].
    #[must_use]
    pub fn new(requested_locale: &'a str, source_locale: &'a str) -> Self {
        Self {
            requested_locale,
            source_locale,
            ..Self::default()
        }
    }
}

/// Options controlling selected-subset compiled catalog artifact generation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileSelectedCatalogArtifactOptions<'a> {
    /// Locale for which the runtime artifact should be produced.
    pub requested_locale: &'a str,
    /// Source locale used for explicit source fallback behavior.
    pub source_locale: &'a str,
    /// Ordered fallback locales consulted after the requested locale.
    pub fallback_chain: &'a [String],
    /// Built-in strategy used to derive stable runtime keys.
    pub key_strategy: CompiledKeyStrategy,
    /// Whether source text should be used when no non-source translation exists.
    pub source_fallback: bool,
    /// Whether invalid final ICU messages should fail compilation instead of producing diagnostics.
    pub strict_icu: bool,
    /// Whether final ICU messages should be checked against source ICU structure.
    pub icu_compatibility: bool,
    /// High-level semantics used by the input catalog set.
    pub semantics: CatalogSemantics,
    /// Requested compiled runtime IDs to include in the artifact.
    pub compiled_ids: &'a [String],
}

impl Default for CompileSelectedCatalogArtifactOptions<'_> {
    fn default() -> Self {
        Self {
            requested_locale: "",
            source_locale: "",
            fallback_chain: &[],
            key_strategy: CompiledKeyStrategy::FerrocatV1,
            source_fallback: false,
            strict_icu: false,
            icu_compatibility: false,
            semantics: CatalogSemantics::IcuNative,
            compiled_ids: &[],
        }
    }
}

impl<'a> CompileSelectedCatalogArtifactOptions<'a> {
    /// Creates selected artifact compile options with required locales and IDs set.
    ///
    /// Optional fields use the same defaults as [`CompileSelectedCatalogArtifactOptions::default`].
    #[must_use]
    pub fn new(
        requested_locale: &'a str,
        source_locale: &'a str,
        compiled_ids: &'a [String],
    ) -> Self {
        Self {
            requested_locale,
            source_locale,
            compiled_ids,
            ..Self::default()
        }
    }

    pub(super) fn artifact_options(&self) -> CompileCatalogArtifactOptions<'_> {
        CompileCatalogArtifactOptions {
            requested_locale: self.requested_locale,
            source_locale: self.source_locale,
            fallback_chain: self.fallback_chain,
            key_strategy: self.key_strategy,
            source_fallback: self.source_fallback,
            strict_icu: self.strict_icu,
            icu_compatibility: self.icu_compatibility,
            semantics: self.semantics,
        }
    }
}

/// High-level translation kind associated with a compiled runtime ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompiledCatalogTranslationKind {
    /// Translation is a single string value.
    Singular,
    /// Translation is a plural/category map.
    Plural,
}

/// A compiled runtime message keyed by a derived lookup key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompiledMessage {
    /// Stable runtime key derived from the source identity.
    pub key: String,
    /// Original gettext identity preserved for diagnostics and tooling.
    pub source_key: CatalogMessageKey,
    /// Materialized translation payload for runtime lookup.
    pub translation: CompiledTranslation,
}

/// Runtime-oriented lookup structure compiled from a normalized catalog.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CompiledCatalog {
    pub(super) entries: BTreeMap<String, CompiledMessage>,
}

impl CompiledCatalog {
    /// Returns the compiled message for `key`, if present.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&CompiledMessage> {
        self.entries.get(key)
    }

    /// Returns the number of compiled entries.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` when the compiled catalog has no entries.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Iterates over compiled entries in key order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &CompiledMessage)> + '_ {
        self.entries
            .iter()
            .map(|(key, message)| (key.as_str(), message))
    }
}

/// Stable compiled runtime ID index built from one or more normalized catalogs.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CompiledCatalogIdIndex {
    pub(super) ids: BTreeMap<String, CatalogMessageKey>,
}

/// Metadata describing one compiled runtime ID for a specific catalog set.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompiledCatalogIdDescription {
    /// Stable runtime ID derived from the source identity.
    pub compiled_id: String,
    /// Original gettext identity preserved for diagnostics and tooling.
    pub source_key: CatalogMessageKey,
    /// Locales from the provided catalog set that contain this non-obsolete message.
    pub available_locales: Vec<String>,
    /// Whether the message is singular or plural in the provided catalog set.
    pub translation_kind: CompiledCatalogTranslationKind,
}

/// Report returned by [`CompiledCatalogIdIndex::describe_compiled_ids`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DescribeCompiledIdsReport {
    /// Metadata for requested IDs that were known to the index and present in the provided catalogs.
    pub described: Vec<CompiledCatalogIdDescription>,
    /// Requested compiled IDs that were not known to the index at all.
    pub unknown_compiled_ids: Vec<String>,
    /// Requested compiled IDs that were known to the index but not present in the provided catalogs.
    pub unavailable_compiled_ids: Vec<CompiledCatalogUnavailableId>,
}

/// Known compiled runtime ID that was not present in the provided catalog set.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompiledCatalogUnavailableId {
    /// Stable runtime ID derived from the source identity.
    pub compiled_id: String,
    /// Original gettext identity preserved for diagnostics and tooling.
    pub source_key: CatalogMessageKey,
}

impl CompiledCatalogIdIndex {
    /// Builds a deterministic compiled-ID index for the union of non-obsolete messages.
    ///
    /// # Errors
    ///
    /// Returns [`ApiError::Conflict`] when two different source identities compile to the same ID.
    pub fn new(
        catalogs: &[&NormalizedParsedCatalog],
        key_strategy: CompiledKeyStrategy,
    ) -> Result<Self, ApiError> {
        Self::new_with_key_generator(catalogs, key_strategy, compiled_key_for)
    }

    pub(super) fn new_with_key_generator<F>(
        catalogs: &[&NormalizedParsedCatalog],
        key_strategy: CompiledKeyStrategy,
        mut key_generator: F,
    ) -> Result<Self, ApiError>
    where
        F: FnMut(CompiledKeyStrategy, &CatalogMessageKey) -> String,
    {
        let mut ids = BTreeMap::<String, CatalogMessageKey>::new();

        for catalog in catalogs {
            for (source_key, message) in catalog.iter() {
                if message.obsolete {
                    continue;
                }
                let compiled_id = key_generator(key_strategy, source_key);
                if let Some(existing) = ids.get(&compiled_id) {
                    if existing != source_key {
                        return Err(ApiError::Conflict(format!(
                            "compiled catalog key collision for {:?} / {:?} and {:?} / {:?} using key {}",
                            existing.msgctxt,
                            existing.msgid,
                            source_key.msgctxt,
                            source_key.msgid,
                            compiled_id
                        )));
                    }
                    continue;
                }
                ids.insert(compiled_id, source_key.clone());
            }
        }

        Ok(Self { ids })
    }

    /// Returns the source key for `compiled_id`, if present.
    #[must_use]
    pub fn get(&self, compiled_id: &str) -> Option<&CatalogMessageKey> {
        self.ids.get(compiled_id)
    }

    /// Returns `true` when the index contains `compiled_id`.
    #[must_use]
    pub fn contains_id(&self, compiled_id: &str) -> bool {
        self.ids.contains_key(compiled_id)
    }

    /// Returns the number of indexed compiled IDs.
    #[must_use]
    pub fn len(&self) -> usize {
        self.ids.len()
    }

    /// Returns `true` when the index contains no compiled IDs.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.ids.is_empty()
    }

    /// Iterates over compiled IDs in sorted order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &CatalogMessageKey)> + '_ {
        self.ids
            .iter()
            .map(|(compiled_id, source_key)| (compiled_id.as_str(), source_key))
    }

    /// Returns the underlying ordered compiled-ID map by reference.
    #[must_use]
    pub fn as_btreemap(&self) -> &BTreeMap<String, CatalogMessageKey> {
        &self.ids
    }

    /// Consumes the index and returns the underlying ordered compiled-ID map.
    #[must_use]
    pub fn into_btreemap(self) -> BTreeMap<String, CatalogMessageKey> {
        self.ids
    }

    /// Describes selected compiled IDs against a provided catalog set.
    ///
    /// # Errors
    ///
    /// Returns [`ApiError::InvalidArguments`] when a provided catalog does not declare
    /// a locale, or [`ApiError::Conflict`] when the same compiled ID maps to different
    /// translation kinds across the provided catalogs.
    pub fn describe_compiled_ids(
        &self,
        catalogs: &[&NormalizedParsedCatalog],
        compiled_ids: &[String],
    ) -> Result<DescribeCompiledIdsReport, ApiError> {
        let locales = describe_compiled_id_catalogs(catalogs)?;
        let mut report = DescribeCompiledIdsReport::default();

        for compiled_id in std::collections::BTreeSet::from_iter(compiled_ids.iter().cloned()) {
            let Some(source_key) = self.get(&compiled_id).cloned() else {
                report.unknown_compiled_ids.push(compiled_id);
                continue;
            };

            let mut available_locales = Vec::new();
            let mut translation_kind = None;

            for (locale, catalog) in &locales {
                let Some(message) = catalog.get(&source_key) else {
                    continue;
                };
                if message.obsolete {
                    continue;
                }
                let next_kind = compiled_catalog_translation_kind_for_message(
                    catalog.parsed_catalog().semantics,
                    message,
                );
                if let Some(existing_kind) = translation_kind {
                    if existing_kind != next_kind {
                        return Err(ApiError::Conflict(format!(
                            "compiled ID {:?} resolves to inconsistent translation shapes across the provided catalogs",
                            compiled_id
                        )));
                    }
                } else {
                    translation_kind = Some(next_kind);
                }
                available_locales.push(locale.clone());
            }

            if let Some(translation_kind) = translation_kind {
                report.described.push(CompiledCatalogIdDescription {
                    compiled_id,
                    source_key,
                    available_locales,
                    translation_kind,
                });
            } else {
                report
                    .unavailable_compiled_ids
                    .push(CompiledCatalogUnavailableId {
                        compiled_id,
                        source_key,
                    });
            }
        }

        Ok(report)
    }
}

/// Host-neutral compiled runtime artifact for one requested locale.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CompiledCatalogArtifact {
    /// Final runtime message map keyed by the derived lookup key.
    pub messages: BTreeMap<String, String>,
    /// Messages that were missing from the requested locale and had to fall back.
    pub missing: Vec<CompiledCatalogMissingMessage>,
    /// Diagnostics collected while validating final runtime messages.
    pub diagnostics: Vec<CompiledCatalogDiagnostic>,
}

/// Missing-message record emitted by [`super::compile_catalog_artifact`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompiledCatalogMissingMessage {
    /// Stable runtime key derived from the source identity.
    pub key: String,
    /// Original gettext identity preserved for diagnostics and tooling.
    pub source_key: CatalogMessageKey,
    /// Requested locale for this artifact compilation.
    pub requested_locale: String,
    /// Locale that ultimately provided the runtime value, if any.
    pub resolved_locale: Option<String>,
}

/// Diagnostic emitted by [`super::compile_catalog_artifact`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompiledCatalogDiagnostic {
    /// Severity for the collected diagnostic.
    pub severity: super::DiagnosticSeverity,
    /// Stable machine-readable diagnostic code.
    pub code: String,
    /// Human-readable explanation of the problem.
    pub message: String,
    /// Stable runtime key derived from the source identity.
    pub key: String,
    /// Source `msgid` associated with the diagnostic.
    pub msgid: String,
    /// Source `msgctxt` associated with the diagnostic.
    pub msgctxt: Option<String>,
    /// Locale whose final runtime message produced the diagnostic.
    pub locale: String,
}

#[cfg(test)]
mod tests {
    use super::{
        CompileCatalogArtifactOptions, CompileCatalogOptions,
        CompileSelectedCatalogArtifactOptions, CompiledKeyStrategy,
    };
    use crate::api::CatalogSemantics;

    #[test]
    fn compile_option_constructors_set_required_fields_and_keep_defaults() {
        let compile = CompileCatalogOptions::new();
        assert_eq!(compile.key_strategy, CompiledKeyStrategy::FerrocatV1);
        assert!(!compile.source_fallback);

        let artifact = CompileCatalogArtifactOptions::new("de", "en");
        assert_eq!(artifact.requested_locale, "de");
        assert_eq!(artifact.source_locale, "en");
        assert_eq!(artifact.key_strategy, CompiledKeyStrategy::FerrocatV1);
        assert_eq!(artifact.semantics, CatalogSemantics::IcuNative);

        let selected_ids = vec!["abc123".to_owned()];
        let selected = CompileSelectedCatalogArtifactOptions::new("de", "en", &selected_ids);
        assert_eq!(selected.requested_locale, "de");
        assert_eq!(selected.source_locale, "en");
        assert_eq!(selected.compiled_ids, selected_ids.as_slice());
        assert_eq!(selected.key_strategy, CompiledKeyStrategy::FerrocatV1);
    }
}