es-fluent-shared 0.18.1

Shared runtime-safe types and helpers for the es-fluent ecosystem
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! This module provides types for representing FTL variants and type information.

use crate::fluent::{
    FluentArgumentName, FluentDomain, FluentEntryId, FluentIdentifierError, FluentMessageId,
    FluentVariantKey,
};
use crate::meta::TypeKind;
pub use crate::namespace::{NamespacePathError, NamespaceRule, ResolvedNamespace};
use crate::source::{SourceFile, SourceLine, SourceLocation};
use std::borrow::Borrow;
use std::path::Path;

/// Static Fluent domain emitted by derive macros.
#[derive(derive_more::AsRef, Clone, Copy, Debug, derive_more::Display, Eq, Hash, PartialEq)]
#[as_ref(str)]
pub struct StaticFluentDomain(&'static str);

impl StaticFluentDomain {
    /// Creates a static domain from a caller-validated value.
    ///
    /// Derive macros emit this only after validating the domain during macro
    /// expansion. Manual callers should prefer [`Self::try_new`].
    pub(crate) const fn new_unchecked(value: &'static str) -> Self {
        Self(value)
    }

    /// Validates and creates a static domain.
    pub fn try_new(value: &'static str) -> Result<Self, FluentIdentifierError> {
        FluentDomain::try_new(value)?;
        Ok(Self(value))
    }

    /// Validates and creates the default domain derived from `CARGO_PKG_NAME`.
    ///
    /// Generated code uses this for implicit current-package domains because
    /// the package name is only known in the consuming crate.
    #[allow(
        clippy::panic,
        clippy::unwrap_used,
        reason = "invalid package names should fail immediately when generated localization code is used"
    )]
    pub fn from_package_name(value: &'static str) -> Self {
        Self::try_new(value).unwrap_or_else(|error| {
            panic!("CARGO_PKG_NAME '{value}' is not a valid Fluent domain: {error}")
        })
    }

    pub fn as_str(self) -> &'static str {
        self.0
    }

    pub fn domain_name(self) -> FluentDomain {
        FluentDomain::from_valid_static(self.0)
    }
}

impl Borrow<str> for StaticFluentDomain {
    fn borrow(&self) -> &str {
        self.0
    }
}

impl PartialEq<&str> for StaticFluentDomain {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

/// Static Fluent message identifier emitted by derive macros.
#[derive(derive_more::AsRef, Clone, Copy, Debug, derive_more::Display, Eq, Hash, PartialEq)]
#[as_ref(str)]
pub struct StaticFluentEntryId(&'static str);

impl StaticFluentEntryId {
    /// Creates a static message id from a caller-validated value.
    ///
    /// Derive macros emit this only after validating the message id during macro
    /// expansion. Manual callers should prefer [`Self::try_new`].
    pub(crate) const fn new_unchecked(value: &'static str) -> Self {
        Self(value)
    }

    /// Validates and creates a static message id.
    pub fn try_new(value: &'static str) -> Result<Self, FluentIdentifierError> {
        FluentMessageId::try_new(value)?;
        Ok(Self(value))
    }

    pub fn as_str(self) -> &'static str {
        self.0
    }

    pub fn message_id(self) -> FluentMessageId {
        FluentMessageId::from_valid_static(self.0)
    }

    pub fn entry_id(self) -> FluentEntryId {
        FluentEntryId::from_valid_static(self.0)
    }
}

impl Borrow<str> for StaticFluentEntryId {
    fn borrow(&self) -> &str {
        self.0
    }
}

impl PartialEq<&str> for StaticFluentEntryId {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

/// Static Fluent argument name emitted by derive macros.
#[derive(derive_more::AsRef, Clone, Copy, Debug, derive_more::Display, Eq, Hash, PartialEq)]
#[as_ref(str)]
pub struct StaticFluentArgumentName(&'static str);

impl StaticFluentArgumentName {
    /// Creates a static argument name from a caller-validated value.
    ///
    /// Derive macros emit this only after validating the name during macro
    /// expansion. Manual callers should prefer [`Self::try_new`].
    pub(crate) const fn new_unchecked(value: &'static str) -> Self {
        Self(value)
    }

    /// Validates and creates a static argument name.
    pub fn try_new(value: &'static str) -> Result<Self, FluentIdentifierError> {
        FluentArgumentName::try_new(value)?;
        Ok(Self(value))
    }

    pub fn as_str(self) -> &'static str {
        self.0
    }

    pub fn argument_name(self) -> FluentArgumentName {
        FluentArgumentName::from_valid_static(self.0)
    }
}

impl Borrow<str> for StaticFluentArgumentName {
    fn borrow(&self) -> &str {
        self.0
    }
}

impl PartialEq<&str> for StaticFluentArgumentName {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

/// Static Fluent select variant key emitted by derive macros.
#[derive(derive_more::AsRef, Clone, Copy, Debug, derive_more::Display, Eq, Hash, PartialEq)]
#[as_ref(str)]
pub struct StaticFluentVariantKey(&'static str);

impl StaticFluentVariantKey {
    /// Creates a static variant key from a caller-validated value.
    ///
    /// Derive macros emit this only after validating the key during macro
    /// expansion. Manual callers should prefer [`Self::try_new`].
    pub(crate) const fn new_unchecked(value: &'static str) -> Self {
        Self(value)
    }

    /// Validates and creates a static select variant key.
    pub fn try_new(value: &'static str) -> Result<Self, FluentIdentifierError> {
        FluentVariantKey::try_new(value)?;
        Ok(Self(value))
    }

    pub fn as_str(self) -> &'static str {
        self.0
    }

    pub fn variant_key(self) -> FluentVariantKey {
        FluentVariantKey::from_valid_static(self.0)
    }
}

impl Borrow<str> for StaticFluentVariantKey {
    fn borrow(&self) -> &str {
        self.0
    }
}

impl PartialEq<&str> for StaticFluentVariantKey {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

/// A variant representing a single FTL key entry.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct FtlVariant {
    name: &'static str,
    ftl_key: StaticFluentEntryId,
    args: &'static [StaticFluentArgumentName],
    /// The module path from `module_path!()`.
    module_path: &'static str,
    /// The line number from `line!()` macro.
    line: u32,
}

impl FtlVariant {
    /// Creates static variant metadata from validated static parts.
    pub const fn new(
        name: &'static str,
        ftl_key: StaticFluentEntryId,
        args: &'static [StaticFluentArgumentName],
        module_path: &'static str,
        line: u32,
    ) -> Self {
        Self {
            name,
            ftl_key,
            args,
            module_path,
            line,
        }
    }

    pub fn name(&self) -> &'static str {
        self.name
    }

    pub fn args(&self) -> &'static [StaticFluentArgumentName] {
        self.args
    }

    pub fn module_path(&self) -> &'static str {
        self.module_path
    }

    pub fn entry_id(&self) -> FluentEntryId {
        self.ftl_key.entry_id()
    }

    /// Returns the validated Fluent message id for this variant.
    pub fn message_id(&self) -> FluentMessageId {
        self.ftl_key.message_id()
    }

    /// Returns the validated Fluent argument names for this variant.
    pub fn argument_names(&self) -> Vec<FluentArgumentName> {
        self.args.iter().map(|arg| arg.argument_name()).collect()
    }

    /// Returns typed source line metadata for this variant.
    pub fn source_line(&self) -> SourceLine {
        SourceLine::new(self.line)
    }
}

/// Type information for FTL registration, used by derive macros and the CLI.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct FtlTypeInfo {
    type_kind: TypeKind,
    type_name: &'static str,
    variants: &'static [FtlVariant],
    /// The file path where this type is defined (from `file!()` macro).
    file_path: &'static str,
    /// The module path where this type is defined (from `module_path!()` macro).
    module_path: &'static str,
    /// Optional namespace for FTL file output. If Some, the type will be written to
    /// `{lang}/{crate}/{namespace}.ftl` instead of `{lang}/{crate}.ftl`.
    namespace: Option<NamespaceRule>,
}

impl AsRef<FtlTypeInfo> for FtlTypeInfo {
    fn as_ref(&self) -> &FtlTypeInfo {
        self
    }
}

impl FtlTypeInfo {
    /// Creates static type metadata from validated static parts.
    pub const fn new(
        type_kind: TypeKind,
        type_name: &'static str,
        variants: &'static [FtlVariant],
        file_path: &'static str,
        module_path: &'static str,
        namespace: Option<NamespaceRule>,
    ) -> Self {
        Self {
            type_kind,
            type_name,
            variants,
            file_path,
            module_path,
            namespace,
        }
    }

    pub fn type_kind(&self) -> &TypeKind {
        &self.type_kind
    }

    pub fn type_name(&self) -> &'static str {
        self.type_name
    }

    pub fn variants(&self) -> &'static [FtlVariant] {
        self.variants
    }

    pub fn file_path(&self) -> &'static str {
        self.file_path
    }

    pub fn module_path(&self) -> &'static str {
        self.module_path
    }

    pub fn namespace(&self) -> Option<&NamespaceRule> {
        self.namespace.as_ref()
    }

    /// Returns typed source file metadata when this type has a recorded file path.
    pub fn source_file(&self) -> Option<SourceFile> {
        SourceFile::new(self.file_path)
    }

    /// Returns typed source location metadata for the given variant.
    pub fn source_location_for(&self, variant: &FtlVariant) -> Option<SourceLocation> {
        SourceLocation::new(self.file_path, variant.line)
    }

    /// Returns a stable human-readable source description for diagnostics.
    pub fn source_description_for(&self, variant: &FtlVariant) -> String {
        let item = format!("type '{}' variant '{}'", self.type_name, variant.name);
        match self.source_location_for(variant) {
            Some(location) => format!(
                "{item} at {}:{}",
                location.file().as_str(),
                location.line().get()
            ),
            None => format!("{item} at line {}", variant.source_line().get()),
        }
    }

    /// Resolve the namespace for this type, if configured.
    pub fn resolved_namespace(&self, manifest_dir: &Path) -> Option<String> {
        self.namespace
            .as_ref()
            .map(|rule| rule.resolve(self.file_path, Some(manifest_dir)))
    }

    /// Resolve and validate the namespace for this type, if configured.
    pub fn try_resolved_namespace(
        &self,
        manifest_dir: &Path,
    ) -> Result<Option<ResolvedNamespace>, NamespacePathError> {
        self.namespace
            .as_ref()
            .map(|rule| rule.try_resolve(self.file_path, Some(manifest_dir)))
            .transpose()
    }
}

/// Constructors used by generated macro output.
///
/// These functions keep generated metadata on a narrow construction surface
/// while the public structs expose read-only accessors.
#[doc(hidden)]
pub mod __macro {
    use super::{
        FtlTypeInfo, FtlVariant, NamespaceRule, ResolvedNamespace, StaticFluentArgumentName,
        StaticFluentDomain, StaticFluentEntryId, StaticFluentVariantKey,
    };
    use crate::meta::TypeKind;

    pub const fn static_domain(value: &'static str) -> StaticFluentDomain {
        StaticFluentDomain::new_unchecked(value)
    }

    pub const fn static_entry_id(value: &'static str) -> StaticFluentEntryId {
        StaticFluentEntryId::new_unchecked(value)
    }

    pub const fn static_argument_name(value: &'static str) -> StaticFluentArgumentName {
        StaticFluentArgumentName::new_unchecked(value)
    }

    pub const fn static_variant_key(value: &'static str) -> StaticFluentVariantKey {
        StaticFluentVariantKey::new_unchecked(value)
    }

    pub const fn namespace_literal(value: &'static str) -> NamespaceRule {
        NamespaceRule::Literal(ResolvedNamespace::from_static_unchecked(value))
    }

    pub const fn ftl_variant(
        name: &'static str,
        ftl_key: StaticFluentEntryId,
        args: &'static [StaticFluentArgumentName],
        module_path: &'static str,
        line: u32,
    ) -> FtlVariant {
        FtlVariant::new(name, ftl_key, args, module_path, line)
    }

    pub const fn ftl_type_info(
        type_kind: TypeKind,
        type_name: &'static str,
        variants: &'static [FtlVariant],
        file_path: &'static str,
        module_path: &'static str,
        namespace: Option<NamespaceRule>,
    ) -> FtlTypeInfo {
        FtlTypeInfo::new(
            type_kind,
            type_name,
            variants,
            file_path,
            module_path,
            namespace,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::{
        FtlTypeInfo, NamespacePathError, NamespaceRule, StaticFluentArgumentName,
        StaticFluentDomain, StaticFluentEntryId, StaticFluentVariantKey,
    };
    use crate::meta::TypeKind;
    use crate::registry::FtlVariant;
    use std::path::PathBuf;

    fn test_manifest_dir() -> PathBuf {
        if cfg!(windows) {
            PathBuf::from(r"C:\repo\app")
        } else {
            PathBuf::from("/repo/app")
        }
    }

    #[test]
    fn static_variant_key_validates_and_exposes_typed_value() {
        let key = StaticFluentVariantKey::try_new("very-high").expect("valid variant key");

        assert_eq!(key.as_str(), "very-high");
        assert_eq!(key.variant_key().as_str(), "very-high");
        assert!(StaticFluentVariantKey::try_new("not valid").is_err());
    }

    #[test]
    fn file_namespace_uses_stem() {
        let manifest_dir = test_manifest_dir();
        let file_path = manifest_dir.join("src").join("lib.rs");
        let namespace = NamespaceRule::File.resolve(
            file_path.to_str().expect("utf-8 test path"),
            Some(&manifest_dir),
        );
        assert_eq!(namespace, "lib");
    }

    #[test]
    fn file_relative_strips_manifest_and_src() {
        let manifest_dir = test_manifest_dir();
        let file_path = manifest_dir.join("src").join("ui").join("button.rs");
        let namespace = NamespaceRule::FileRelative.resolve(
            file_path.to_str().expect("utf-8 test path"),
            Some(&manifest_dir),
        );
        assert_eq!(namespace, "ui/button");
    }

    #[test]
    fn file_relative_falls_back_to_stem_outside_manifest() {
        let manifest_dir = test_manifest_dir();
        let file_path = if cfg!(windows) {
            PathBuf::from(r"C:\other\src\lib.rs")
        } else {
            PathBuf::from("/other/src/lib.rs")
        };
        let namespace = NamespaceRule::FileRelative.resolve(
            file_path.to_str().expect("utf-8 test path"),
            Some(&manifest_dir),
        );
        assert_eq!(namespace, "lib");
    }

    #[test]
    fn folder_namespace_uses_parent_folder_name() {
        let manifest_dir = test_manifest_dir();
        let file_path = manifest_dir
            .join("src")
            .join("ui")
            .join("forms")
            .join("button.rs");
        let namespace = NamespaceRule::Folder.resolve(
            file_path.to_str().expect("utf-8 test path"),
            Some(&manifest_dir),
        );
        assert_eq!(namespace, "forms");
    }

    #[test]
    fn folder_relative_strips_manifest_and_src() {
        let manifest_dir = test_manifest_dir();
        let file_path = manifest_dir
            .join("src")
            .join("ui")
            .join("forms")
            .join("button.rs");
        let namespace = NamespaceRule::FolderRelative.resolve(
            file_path.to_str().expect("utf-8 test path"),
            Some(&manifest_dir),
        );
        assert_eq!(namespace, "ui/forms");
    }

    #[test]
    fn folder_relative_keeps_src_for_root_module() {
        let manifest_dir = test_manifest_dir();
        let file_path = manifest_dir.join("src").join("lib.rs");
        let namespace = NamespaceRule::FolderRelative.resolve(
            file_path.to_str().expect("utf-8 test path"),
            Some(&manifest_dir),
        );
        assert_eq!(namespace, "src");
    }

    #[test]
    fn folder_relative_falls_back_to_parent_outside_manifest() {
        let manifest_dir = test_manifest_dir();
        let file_path = if cfg!(windows) {
            PathBuf::from(r"C:\other\src\lib.rs")
        } else {
            PathBuf::from("/other/src/lib.rs")
        };
        let namespace = NamespaceRule::FolderRelative.resolve(
            file_path.to_str().expect("utf-8 test path"),
            Some(&manifest_dir),
        );
        assert_eq!(namespace, "src");
    }

    #[test]
    fn ftl_type_info_try_resolved_namespace_returns_validated_namespace() {
        let manifest_dir = test_manifest_dir();
        let info = FtlTypeInfo::new(
            TypeKind::Enum,
            "ButtonCopy",
            &[],
            "src/ui/button.rs",
            "demo",
            Some(NamespaceRule::FileRelative),
        );

        let namespace = info
            .try_resolved_namespace(&manifest_dir)
            .expect("namespace should resolve")
            .expect("namespace configured");

        assert_eq!(namespace.as_str(), "ui/button");
        assert_eq!(
            namespace.try_resource_key("demo").unwrap().as_str(),
            "demo/ui/button"
        );
    }

    #[test]
    fn ftl_type_info_try_resolved_namespace_rejects_invalid_literal() {
        let manifest_dir = test_manifest_dir();
        let info = FtlTypeInfo::new(
            TypeKind::Enum,
            "EscapingCopy",
            &[],
            "src/lib.rs",
            "demo",
            Some(super::__macro::namespace_literal("../escape")),
        );

        let err = info
            .try_resolved_namespace(&manifest_dir)
            .expect_err("invalid literal should fail");

        assert_eq!(err, NamespacePathError::CurrentOrParentSegment);
    }

    #[test]
    fn ftl_type_info_exposes_typed_source_metadata() {
        static VARIANTS: &[FtlVariant] = &[FtlVariant::new(
            "Ready",
            StaticFluentEntryId::new_unchecked("status-Ready"),
            &[],
            "demo",
            42,
        )];
        let info = FtlTypeInfo::new(
            TypeKind::Enum,
            "Status",
            VARIANTS,
            "src/status.rs",
            "demo",
            None,
        );

        assert_eq!(info.source_file().unwrap().as_str(), "src/status.rs");
        assert_eq!(VARIANTS[0].entry_id().as_str(), "status-Ready");
        assert_eq!(VARIANTS[0].message_id().as_str(), "status-Ready");
        assert_eq!(VARIANTS[0].argument_names(), Vec::new());
        assert_eq!(VARIANTS[0].source_line().get(), 42);

        let location = info.source_location_for(&VARIANTS[0]).unwrap();
        assert_eq!(location.file().as_str(), "src/status.rs");
        assert_eq!(location.line().get(), 42);
    }

    #[test]
    fn empty_type_file_path_has_no_typed_source_location() {
        static VARIANTS: &[FtlVariant] = &[FtlVariant::new(
            "Ready",
            StaticFluentEntryId::new_unchecked("status-Ready"),
            &[],
            "demo",
            42,
        )];
        let info = FtlTypeInfo::new(TypeKind::Enum, "Status", VARIANTS, "", "demo", None);

        assert!(info.source_file().is_none());
        assert!(info.source_location_for(&VARIANTS[0]).is_none());
    }

    #[test]
    fn static_fluent_wrappers_validate_manual_construction() {
        assert_eq!(
            StaticFluentEntryId::try_new("_invalid")
                .unwrap_err()
                .to_string(),
            "Fluent message id must start with an ASCII letter"
        );
        assert_eq!(
            StaticFluentEntryId::try_new("-shared-term")
                .unwrap_err()
                .to_string(),
            "Fluent message id must start with an ASCII letter"
        );
        assert_eq!(
            StaticFluentDomain::try_new("app-domain")
                .expect("domain")
                .domain_name()
                .as_str(),
            "app-domain"
        );
        assert_eq!(
            StaticFluentDomain::try_new("app-domain")
                .expect("domain")
                .as_str(),
            "app-domain"
        );
        assert_eq!(
            StaticFluentDomain::from_package_name("package-domain").as_str(),
            "package-domain"
        );
        assert_eq!(
            StaticFluentArgumentName::try_new("not valid")
                .unwrap_err()
                .to_string(),
            "Fluent argument name contains invalid character ' '; use ASCII letters, digits, '_' or '-'"
        );
    }
}