oxblade 0.2.0

Laravel Blade templates for Rust: Blade's markup and directives with Rust expressions, rendering the same HTML as Laravel. Community package, not affiliated with Laravel.
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
//! Translations: Laravel's translator, ported from `illuminate/translation` (MIT).
//!
//! [`Translator`] is what the template helpers call: `__()`, `trans()` and `@lang` for
//! [`get`](Translator::get), `trans_choice()` and `@choice` for [`choice`](Translator::choice), and
//! `Lang::has()` for [`has`](Translator::has). Laravel for Rust has no translator, so the engine
//! ships [`JsonTranslator`], which reads a `lang` directory of JSON files where Laravel reads PHP
//! arrays. [`MessageSelector`] chooses the plural form by Laravel's rules for every locale it lists.
//!
//! PHP's casing, number printing and `==` come from `laravel-rust-format-core`.
//!
//! `conformance/translate/` proves the behaviour against Laravel 13: its generator runs PHP 8.4
//! with Laravel's own `Translator` and `MessageSelector`, and `tests/wp13_translate.rs` compares
//! the recorded output byte for byte.

mod replacements;
pub(crate) use replacements::MIN_MATCHER_STATES;
mod selector;
mod table;

use std::{
    borrow::Cow,
    path::Path,
    sync::{Arc, LazyLock},
};

use laravel_rust_format_core::{PhpNumber, php};
use serde_json::Value;

use crate::error::{Error, ErrorKind, Result};
use table::{Line, Table};

pub use selector::MessageSelector;

/// The number a plural form is chosen for, represented as a PHP `int` or `float`.
///
/// They are kept apart because Laravel treats them differently: a fraction never matches `{1}`, an
/// integer keeps every digit where a float would round, and `abs(PHP_INT_MIN)` becomes a float.
///
/// ```
/// use oxblade::translate::{MessageSelector, Number};
///
/// let selector = MessageSelector;
/// assert_eq!(selector.choose("{1} one|other", Number::from(1.0), "en"), "one");
/// assert_eq!(selector.choose("{1} one|other", Number::from(1.5), "en"), "other");
/// assert_eq!(selector.choose("{1} one|[2,4] few|other", Number::from(2), "ru"), "few");
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Number {
    /// A PHP `int`: a signed 64-bit integer.
    Int(i64),
    /// A PHP `float`: an IEEE 754 double.
    Float(f64),
}

impl Number {
    /// The number as PHP holds it.
    pub(crate) fn php(self) -> PhpNumber {
        match self {
            Self::Int(value) => PhpNumber::Int(value),
            Self::Float(value) => PhpNumber::Float(value),
        }
    }
}

impl From<i32> for Number {
    fn from(value: i32) -> Self {
        Self::Int(i64::from(value))
    }
}

impl From<i64> for Number {
    fn from(value: i64) -> Self {
        Self::Int(value)
    }
}

impl From<u32> for Number {
    fn from(value: u32) -> Self {
        Self::Int(i64::from(value))
    }
}

impl From<u64> for Number {
    /// A value above `i64::MAX` becomes a float, as integer overflow does in PHP.
    fn from(value: u64) -> Self {
        match i64::try_from(value) {
            Ok(value) => Self::Int(value),
            Err(_) => Self::Float(value as f64),
        }
    }
}

impl From<usize> for Number {
    fn from(value: usize) -> Self {
        Self::from(value as u64)
    }
}

impl From<f32> for Number {
    fn from(value: f32) -> Self {
        Self::Float(f64::from(value))
    }
}

impl From<f64> for Number {
    fn from(value: f64) -> Self {
        Self::Float(value)
    }
}

/// A translation returned to the template evaluator.
pub enum TranslationLine {
    /// Ordinary text, escaped in a Blade escaped echo.
    Text(String),
    /// An explicitly trusted static line supplied by the application's translator.
    Trusted(&'static str),
}

/// Laravel's translator contract, as far as templates use it.
///
/// `replace` holds the `(name, value)` pairs of Laravel's `$replace` array, in its order. A `locale`
/// of `None` uses the default locale.
pub trait Translator {
    /// Laravel's `trans()` and `__()`: the translation of `key` with the placeholders replaced.
    /// A missing key is its own translation, placeholders replaced.
    fn get(&self, key: &str, replace: &[(&str, &str)], locale: Option<&str>) -> String;

    /// Laravel's `trans_choice()`: [`get`](Self::get) for `key`, with the form for `number` and
    /// `:count` replaced by it, unless `replace` has a `count`.
    fn choice(
        &self,
        key: &str,
        number: Number,
        replace: &[(&str, &str)],
        locale: Option<&str>,
    ) -> String;

    /// Looks up a line for a template with an output byte limit.
    ///
    /// The default treats every line as plain text. Override to enforce the limit during
    /// allocation, or to return explicitly trusted, application-owned static markup.
    fn get_for_template(
        &self,
        key: &str,
        replace: &[(&str, &str)],
        locale: Option<&str>,
        max_bytes: usize,
    ) -> Result<TranslationLine> {
        let text = self.get(key, replace, locale);
        check_bytes(text.len(), max_bytes)?;
        Ok(TranslationLine::Text(text))
    }

    /// Chooses a plural form for a template with an output byte limit.
    ///
    /// Override to enforce the limit during allocation.
    fn choice_for_template(
        &self,
        key: &str,
        number: Number,
        replace: &[(&str, &str)],
        locale: Option<&str>,
        max_bytes: usize,
    ) -> Result<String> {
        let text = self.choice(key, number, replace, locale);
        check_bytes(text.len(), max_bytes)?;
        Ok(text)
    }

    /// Laravel's `Lang::has()`: whether a translation exists for `key` in the locale or, when it
    /// has one, the fallback locale.
    fn has(&self, key: &str, locale: Option<&str>) -> bool;
}

/// Laravel's translator over a `lang` directory of JSON files.
///
/// Where Laravel reads PHP arrays, this reads JSON with the same keys, values and nesting:
///
/// | File | Laravel reads | Looked up by |
/// | --- | --- | --- |
/// | `lang/<locale>.json` | `lang/<locale>.json` | the key itself: `__('Welcome back, :name')` |
/// | `lang/<locale>/<group>.json` | `lang/<locale>/<group>.php` | `<group>.<item>`: `__('messages.welcome')`, nested groups as `auth/passwords.reset` |
///
/// Lookup follows Laravel's `Translator`:
///
/// - The JSON file of the requested locale is checked first and is never taken from the fallback
///   locale. Then the group file of the requested locale, then that of the fallback locale.
/// - A missing key is its own translation, with its placeholders replaced.
/// - In a group file only a string is a translation. A number, a boolean or an empty array counts
///   as missing, as in Laravel.
/// - In a JSON file `null` counts as absent. An empty string, `"0"`, `0`, `false` or `[]` gives
///   the key, yet counts as present for [`has`](Translator::has) and hides the group files, as in
///   Laravel. A number or `true` prints as PHP prints it.
/// - Where Laravel returns an array, which a template cannot print, [`get`](Translator::get) gives
///   the key and [`has`](Translator::has) is `true`.
///
/// Every file is read once, by [`load`](Self::load): nothing is read while templates render.
///
/// ```
/// use oxblade::translate::{JsonTranslator, Number, Translator};
///
/// # fn main() -> Result<(), oxblade::error::Error> {
/// let translator = JsonTranslator::load("lang", "en")?.with_fallback("en");
/// let name = "Ana";
/// assert_eq!(translator.get("Welcome back, :name", &[("name", name)], None), "Welcome back, Ana");
/// let line = "{0} No cities|{1} One city|[2,*] :count cities";
/// assert_eq!(translator.choice(line, Number::from(14), &[], None), "14 cities");
/// assert_eq!(translator.choice(line, Number::from(1), &[], None), "One city");
/// // A directory that is not there holds no lines, as in Laravel.
/// assert!(!translator.has("messages.welcome", None));
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct JsonTranslator {
    /// The lines, shared by every locale of one directory.
    table: Arc<Table>,
    /// The default locale: Laravel's `$locale`.
    locale: String,
    /// Laravel's `$fallback`, which Laravel leaves unset until `setFallback`.
    fallback: Option<String>,
}

pub(crate) static EMPTY: LazyLock<JsonTranslator> = LazyLock::new(|| JsonTranslator {
    table: Arc::default(),
    locale: "en".into(),
    fallback: Some("en".into()),
});

fn check_bytes(size: usize, max_bytes: usize) -> Result<()> {
    if size > max_bytes {
        return Err(Error::new(
            ErrorKind::Limit,
            "render output limit exceeded while evaluating a translation",
            None,
        ));
    }
    Ok(())
}

impl JsonTranslator {
    /// Reads every translation file under `dir`, for the default `locale`.
    ///
    /// A directory that does not exist holds no lines, as in Laravel. A file that is not valid
    /// JSON, or whose top level is not an array or an object, is an error. The scan reads regular
    /// files and directories and skips symlinks below `dir`. As in Laravel's
    /// `setLocale`, the locale may not contain `/`, `\`, `..` or a NUL byte.
    pub fn load(dir: impl AsRef<Path>, locale: impl Into<String>) -> Result<Self> {
        let locale = check_locale(&locale.into())?;
        Ok(Self {
            table: Arc::new(Table::load(dir.as_ref())?),
            locale,
            fallback: None,
        })
    }

    /// The same lines with another default locale: Laravel's `setLocale`, on a copy, so a
    /// request can use its own locale while the translator is shared.
    pub fn with_locale(self, locale: impl Into<String>) -> Result<Self> {
        Ok(Self {
            locale: check_locale(&locale.into())?,
            ..self
        })
    }

    /// The same lines with Laravel's fallback locale, `setFallback`.
    pub fn with_fallback(self, locale: impl Into<String>) -> Self {
        Self {
            fallback: Some(locale.into()),
            ..self
        }
    }

    /// The default locale.
    pub fn locale(&self) -> &str {
        &self.locale
    }

    /// The fallback locale.
    pub fn fallback(&self) -> Option<&str> {
        self.fallback.as_deref()
    }

    /// Laravel's `hasForLocale`: [`has`](Translator::has) for the locale alone, without the
    /// fallback locale.
    pub fn has_for_locale(&self, key: &str, locale: Option<&str>) -> bool {
        self.exists(key, locale, false)
    }

    /// Checks whether a dictionary supplies a line, even when its text equals the key.
    pub fn contains_line(&self, key: &str, locale: Option<&str>) -> bool {
        !matches!(self.resolve(key, locale, true).source, LineSource::Missing)
    }

    /// Laravel's `has`: [`get`](Self::get) with the fallback locale, then the JSON check.
    fn exists(&self, key: &str, locale: Option<&str>, fallback: bool) -> bool {
        let resolved = self.resolve(key, locale, fallback);
        matches!(resolved.source, LineSource::Json)
            || !matches!(resolved.text, Some(text) if text == key)
    }

    /// Laravel's `Translator::choice`.
    fn choose(
        &self,
        key: &str,
        number: Number,
        replace: &[(&str, &str)],
        locale: Option<&str>,
        max_bytes: Option<usize>,
    ) -> Result<String> {
        // `localeForChoice`: the fallback locale pluralizes a key the requested locale lacks.
        let requested = self.locale_or_default(locale);
        let locale = if self.has_for_locale(key, Some(requested)) {
            Some(requested)
        } else {
            self.fallback_locale()
        };
        let resolved = self.resolve(key, locale, true);
        let chosen = selector::select(resolved.text.as_deref().unwrap_or(key), number, locale);
        if !chosen.contains(':') {
            check_bytes(chosen.len(), max_bytes.unwrap_or(usize::MAX))?;
            return Ok(chosen.to_owned());
        }
        let count = php::echo(number.php());
        replacements::make_with_count(chosen, replace, &count, max_bytes).map(Cow::into_owned)
    }

    fn translated(
        &self,
        key: &str,
        replace: &[(&str, &str)],
        locale: Option<&str>,
        max_bytes: Option<usize>,
    ) -> Result<String> {
        let resolved = self.resolve(key, locale, true);
        replacements::make(resolved.text.as_deref().unwrap_or(key), replace, max_bytes)
            .map(Cow::into_owned)
    }

    /// `Translator::get` for one locale, as far as a string can hold the result: `text` is `None`
    /// where Laravel returns an array.
    fn resolve<'a>(&'a self, key: &'a str, locale: Option<&str>, fallback: bool) -> Resolved<'a> {
        let locale = self.locale_or_default(locale);
        // JSON translations are checked for the requested locale only: they never fall back.
        if let Some(value) = self.table.json_line(locale, key) {
            return Resolved {
                text: Some(json_text(value).unwrap_or(Cow::Borrowed(key))),
                source: LineSource::Json,
            };
        }
        if let Some((group, item)) = parse_key(key) {
            let locales = [Some(locale), self.fallback_for(locale).filter(|_| fallback)];
            for locale in locales.into_iter().flatten() {
                match self.table.group(group, locale, item) {
                    Line::Text(line) => {
                        return Resolved {
                            text: Some(Cow::Borrowed(line)),
                            source: LineSource::Group,
                        };
                    }
                    // Laravel returns the array and stops looking.
                    Line::Table => {
                        return Resolved {
                            text: None,
                            source: LineSource::Group,
                        };
                    }
                    Line::Missing => {}
                }
            }
        }
        Resolved {
            text: Some(Cow::Borrowed(key)),
            source: LineSource::Missing,
        }
    }

    /// `$locale ?: $this->locale`: Laravel treats an empty locale and `"0"` as not given.
    fn locale_or_default<'a>(&'a self, locale: Option<&'a str>) -> &'a str {
        locale
            .filter(|locale| !matches!(*locale, "" | "0"))
            .unwrap_or(&self.locale)
    }

    /// The fallback locale as `array_filter` keeps it: Laravel drops an empty one.
    fn fallback_locale(&self) -> Option<&str> {
        self.fallback
            .as_deref()
            .filter(|fallback| !matches!(*fallback, "" | "0"))
    }

    /// `localeArray`: the fallback locale, unless it is the locale being tried.
    fn fallback_for<'a>(&'a self, locale: &str) -> Option<&'a str> {
        self.fallback_locale()
            .filter(|fallback| *fallback != locale)
    }
}

impl Translator for JsonTranslator {
    fn get(&self, key: &str, replace: &[(&str, &str)], locale: Option<&str>) -> String {
        self.translated(key, replace, locale, None)
            .unwrap_or_default()
    }

    fn choice(
        &self,
        key: &str,
        number: Number,
        replace: &[(&str, &str)],
        locale: Option<&str>,
    ) -> String {
        self.choose(key, number, replace, locale, None)
            .unwrap_or_default()
    }

    fn get_for_template(
        &self,
        key: &str,
        replace: &[(&str, &str)],
        locale: Option<&str>,
        max_bytes: usize,
    ) -> Result<TranslationLine> {
        self.translated(key, replace, locale, Some(max_bytes))
            .map(TranslationLine::Text)
    }

    fn choice_for_template(
        &self,
        key: &str,
        number: Number,
        replace: &[(&str, &str)],
        locale: Option<&str>,
        max_bytes: usize,
    ) -> Result<String> {
        self.choose(key, number, replace, locale, Some(max_bytes))
    }

    fn has(&self, key: &str, locale: Option<&str>) -> bool {
        self.exists(key, locale, true)
    }
}

/// What Laravel's `Translator::get` returns for one lookup.
struct Resolved<'a> {
    /// The text, or `None` where Laravel returns an array.
    text: Option<Cow<'a, str>>,
    source: LineSource,
}

enum LineSource {
    /// Laravel's `has` reports a JSON line as present even when it returns the key.
    Json,
    Group,
    Missing,
}

/// Laravel's `$line ?: $key` for a value of a JSON file, as far as a string goes: a falsy value
/// gives the key (`None`), a truthy number or `true` prints as PHP prints it, and an array is
/// never a string.
fn json_text(value: &Value) -> Option<Cow<'_, str>> {
    match value {
        Value::String(text) if !text.is_empty() && text != "0" => Some(Cow::Borrowed(text)),
        Value::Number(number) => {
            let number = php_number(number);
            (number.as_f64() != 0.0).then(|| Cow::Owned(php::echo(number)))
        }
        Value::Bool(true) => Some(Cow::Borrowed("1")),
        _ => None,
    }
}

/// A decoded JSON number as PHP decoded it: an integer that fits in `i64`, otherwise a float.
fn php_number(number: &serde_json::Number) -> PhpNumber {
    match number.as_i64() {
        Some(value) => PhpNumber::Int(value),
        None => PhpNumber::Float(number.as_f64().unwrap_or(f64::NAN)),
    }
}

/// Laravel's `Translator::parseKey`: the group and the item of a key. A key of one segment names
/// a whole group, so it has an item of `None`. `None` altogether for a namespaced key:
/// `JsonTranslator` loads no namespace, so those have no lines. `*::` is Laravel's spelling of no
/// namespace.
fn parse_key(key: &str) -> Option<(&str, Option<&str>)> {
    let key = match key.split_once("::") {
        Some(("*", rest)) => rest.split_once("::").map_or(rest, |(second, _)| second),
        Some(_) => return None,
        None => key,
    };
    match key.split_once('.') {
        Some((group, item)) => Some((group, Some(item))),
        None => Some((key, None)),
    }
}

/// Laravel's `setLocale`: the characters it refuses in a locale.
fn check_locale(locale: &str) -> Result<String> {
    if locale.contains(['/', '\\', '\0']) || locale.contains("..") {
        return Err(Error::new(
            ErrorKind::Load,
            "Invalid characters present in locale.",
            None,
        ));
    }
    Ok(locale.to_owned())
}

#[cfg(test)]
mod tests {
    use super::*;

    const APPLES: &str = "{0} No apples|{1} One apple|[2,*] :count apples";

    fn with_files(files: &[(&str, &str)], locale: &str, fallback: Option<&str>) -> JsonTranslator {
        let dir = table::TempDir::new("translator");
        for (file, contents) in files {
            dir.write(file, contents);
        }
        let translator = JsonTranslator::load(dir.path(), locale).expect("the files load");
        match fallback {
            Some(fallback) => translator.with_fallback(fallback),
            None => translator,
        }
    }

    /// The files of an application: English with a Dutch group.
    fn app(fallback: Option<&str>) -> JsonTranslator {
        with_files(
            &[
                (
                    "en.json",
                    r#"{"Welcome back, :name": "Welcome back, :name", "messages.welcome": "JSON :name", "empty": "", "zero": "0", "number": 5, "real": 1.5, "yes": true, "no": false, "nothing": null, "list": [], "table": {"a": 1}, "same": "same", "big": 9223372036854775808}"#,
                ),
                (
                    "en/messages.json",
                    r#"{"welcome": "Hello :name", "only_en": "English", "count": 7, "flag": true, "none": [], "table": {"a": "x"}, "apples": "{0} none|{1} one|[2,*] :count many", "pears": "{0} none|{1} one|[2,*] :count many", "plums": "one|many", "counts": ":count and :Count and :COUNT"}"#,
                ),
                (
                    "nl/messages.json",
                    r#"{"welcome": "Hallo :name", "apples": "{0} geen appel|{1} één appel|[2,*] :count appels"}"#,
                ),
                (
                    "ru/messages.json",
                    r#"{"apples": "{0} нет|{1} яблоко|[2,*] :count яблок", "pears": "нет|груша|груш"}"#,
                ),
                ("en/auth/passwords.json", r#"{"reset": "Reset :name"}"#),
                ("vendor/pkg/en/messages.json", r#"{"welcome": "Package"}"#),
            ],
            "en",
            fallback,
        )
    }

    #[test]
    fn the_spec_example() {
        let translator = app(Some("en"));
        assert_eq!(
            translator.get("Welcome back, :name", &[("name", "Ana")], None),
            "Welcome back, Ana"
        );
        assert_eq!(
            translator.choice(APPLES, Number::from(14), &[], None),
            "14 apples"
        );
        assert_eq!(
            translator.choice(APPLES, Number::from(1), &[], None),
            "One apple"
        );
        assert_eq!(
            translator.choice(APPLES, Number::from(0), &[], None),
            "No apples"
        );
        assert!(!translator.has(APPLES, None));
        assert_eq!(translator.locale(), "en");
        assert_eq!(translator.fallback(), Some("en"));
    }

    #[test]
    fn json_wins_over_the_groups_and_never_falls_back() {
        let translator = app(Some("en"));
        assert_eq!(
            translator.get("messages.welcome", &[("name", "Ana")], None),
            "JSON Ana"
        );
        assert_eq!(
            translator.get("messages.welcome", &[("name", "Ana")], Some("nl")),
            "Hallo Ana"
        );
        // The Dutch JSON file is not there and is not taken from English: the group file is used.
        assert_eq!(translator.get("empty", &[], Some("nl")), "empty");
        assert!(
            translator.has("empty", None),
            "an empty JSON translation is set"
        );
        assert!(!translator.has_for_locale("empty", Some("nl")));
        assert_eq!(
            translator.get("vendor/pkg/en/messages.welcome", &[], None),
            "vendor/pkg/en/messages.welcome"
        );
    }

    #[test]
    fn groups_fall_back_to_the_fallback_locale() {
        let translator = app(Some("en"));
        assert_eq!(
            translator.get("messages.only_en", &[], Some("nl")),
            "English"
        );
        assert!(translator.has("messages.only_en", Some("nl")));
        assert!(!translator.has_for_locale("messages.only_en", Some("nl")));
        assert!(translator.has_for_locale("messages.welcome", Some("nl")));
        assert_eq!(
            translator.get("messages.only_en", &[], Some("nl")),
            "English"
        );
        // Without a fallback, the other locale has nothing.
        let translator = app(None);
        assert_eq!(
            translator.get("messages.only_en", &[], Some("nl")),
            "messages.only_en"
        );
        assert_eq!(translator.fallback(), None);
        assert_eq!(
            translator.get("auth/passwords.reset", &[("name", "Bo")], None),
            "Reset Bo"
        );
    }

    #[test]
    fn a_missing_key_is_its_own_translation() {
        let translator = app(Some("en"));
        assert_eq!(
            translator.get("Missing :name", &[("name", "ana")], None),
            "Missing ana"
        );
        assert_eq!(
            translator.get("messages.missing", &[("name", "ana")], None),
            "messages.missing"
        );
        assert_eq!(
            translator.get("messages.welcome.", &[], None),
            "messages.welcome."
        );
        assert_eq!(
            translator.get("MESSAGES.welcome", &[], None),
            "MESSAGES.welcome"
        );
        assert_eq!(
            translator.get("en/messages.welcome", &[], None),
            "en/messages.welcome"
        );
        assert_eq!(
            translator.get("../messages.welcome", &[], None),
            "../messages.welcome"
        );
        assert_eq!(
            translator.get("mes\\sages.welcome", &[], None),
            "mes\\sages.welcome"
        );
        assert_eq!(
            translator.get("messages\0welcome", &[], None),
            "messages\0welcome"
        );
        assert_eq!(translator.get("", &[("name", "ana")], None), "");
        assert_eq!(translator.get(".", &[], None), ".");
        assert!(!translator.has("messages.missing", None));
        // Laravel looks up the group `messages` of a namespaced key only for `*::`.
        assert_eq!(
            translator.get("ns::messages.welcome", &[], None),
            "ns::messages.welcome"
        );
        assert!(!translator.has("ns::messages.welcome", None));
        assert_eq!(
            translator.get("*::messages.welcome", &[("name", "Ana")], None),
            "Hello Ana"
        );
        assert_eq!(
            translator.get("*.messages.welcome", &[], None),
            "JSON :name"
        );
    }

    #[test]
    fn values_that_are_not_strings() {
        let translator = app(Some("en"));
        // In a group file only a string is a translation.
        assert_eq!(
            translator.get("messages.count", &[], None),
            "messages.count"
        );
        assert_eq!(translator.get("messages.flag", &[], None), "messages.flag");
        assert_eq!(translator.get("messages.none", &[], None), "messages.none");
        assert_eq!(
            translator.get("messages.table", &[], None),
            "messages.table"
        );
        assert!(!translator.has("messages.count", None));
        assert!(
            translator.has("messages.table", None),
            "an array is not the key"
        );
        assert!(
            translator.has("messages", None),
            "a key of one segment gives the whole group"
        );
        assert_eq!(translator.get("messages", &[], None), "messages");
        // In a JSON file a falsy value gives the key and still hides the group file.
        assert_eq!(translator.get("empty", &[], None), "empty");
        assert_eq!(translator.get("zero", &[], None), "zero");
        assert_eq!(translator.get("no", &[], None), "no");
        assert_eq!(translator.get("list", &[], None), "list");
        assert_eq!(translator.get("table", &[], None), "table");
        assert_eq!(translator.get("nothing", &[], None), "nothing");
        assert!(!translator.has("nothing", None), "null is not set");
        assert!(translator.has("list", None));
        // A number or `true` in a JSON file prints as PHP prints it.
        assert_eq!(translator.get("number", &[], None), "5");
        assert_eq!(translator.get("real", &[], None), "1.5");
        assert_eq!(translator.get("yes", &[], None), "1");
        assert_eq!(translator.get("big", &[], None), "9.2233720368548E+18");
        // A line equal to its key is not `has`, unless the JSON file holds it.
        assert_eq!(translator.get("same", &[], None), "same");
        assert!(translator.has("same", None));
        let translator = with_files(
            &[(
                "en/messages.json",
                r#"{"messages.welcome": "messages.welcome"}"#,
            )],
            "en",
            None,
        );
        assert_eq!(
            translator.get("messages.welcome", &[], None),
            "messages.welcome"
        );
        assert!(!translator.has("messages.welcome", None));
    }

    #[test]
    fn choice_follows_laravel() {
        let translator = app(Some("en"));
        assert_eq!(
            translator.choice("messages.apples", Number::from(1), &[], Some("nl")),
            "één appel"
        );
        assert_eq!(
            translator.choice("messages.apples", Number::from(2), &[], Some("nl")),
            "2 appels"
        );
        assert_eq!(
            translator.choice("messages.apples", Number::from(2.5), &[], Some("nl")),
            "2.5 appels"
        );
        assert_eq!(
            translator.choice("messages.apples", Number::from(1.0), &[], None),
            "one"
        );
        // The conditions of the line come first, whatever the locale's rule says.
        assert_eq!(
            translator.choice("messages.apples", Number::from(21), &[], Some("ru")),
            "21 яблок"
        );
        assert_eq!(
            translator.choice("messages.apples", Number::from(2), &[], Some("ru")),
            "2 яблок"
        );
        assert_eq!(
            translator.choice("messages.apples", Number::from(21), &[], Some("de")),
            "21 many"
        );
        // A line without conditions takes the rule of the locale that holds it.
        assert_eq!(
            translator.choice("messages.pears", Number::from(21), &[], Some("ru")),
            "нет"
        );
        assert_eq!(
            translator.choice("messages.pears", Number::from(2), &[], Some("ru")),
            "груша"
        );
        assert_eq!(
            translator.choice("messages.pears", Number::from(5), &[], Some("ru")),
            "груш"
        );
        // That is the fallback locale for a key it lacks, not the requested one.
        assert_eq!(
            translator.choice("messages.plums", Number::from(21), &[], Some("ru")),
            "many"
        );
        assert_eq!(
            translator.choice("messages.plums", Number::from(1), &[], Some("ru")),
            "one"
        );
        // Without the key anywhere the key is the line.
        assert_eq!(
            translator.choice("{1} one|many", Number::from(21), &[], Some("ru")),
            "many"
        );
        assert_eq!(
            translator.choice("{1} one|many", Number::from(21), &[], None),
            "many"
        );
        let translator = app(None);
        // Without a fallback locale, Laravel pluralizes by index 0.
        assert_eq!(
            translator.choice("{1} one|many", Number::from(21), &[], None),
            " one"
        );
        assert_eq!(
            translator.choice("one|many", Number::from(21), &[], None),
            "one"
        );
        // `:count` is the number as PHP prints it, unless `replace` has a `count`.
        assert_eq!(
            translator.choice("messages.counts", Number::from(3), &[], None),
            "3 and 3 and 3"
        );
        assert_eq!(
            translator.choice("messages.counts", Number::from(3), &[("count", "X")], None),
            "X and X and X"
        );
        assert_eq!(
            translator.choice("messages.counts", Number::from(3), &[("Count", "X")], None),
            "3 and 3 and 3"
        );
        assert_eq!(
            translator.choice("messages.counts", Number::from(1e15), &[], None),
            "1.0E+15 and 1.0E+15 and 1.0E+15"
        );
        assert_eq!(
            translator.choice("messages.counts", Number::from(2.0), &[], None),
            "2 and 2 and 2"
        );
    }

    #[test]
    fn locales() {
        let translator = app(Some("en"));
        // Laravel treats an empty locale and `"0"` as not given.
        assert_eq!(
            translator.get("messages.welcome", &[], Some("")),
            "JSON :name"
        );
        assert_eq!(
            translator.get("messages.welcome", &[], Some("0")),
            "JSON :name"
        );
        assert_eq!(
            translator.get("messages.welcome", &[], Some("nl")),
            "Hallo :name"
        );
        assert_eq!(
            translator.get("messages.welcome", &[], Some("NL")),
            "Hello :name"
        );
        // A fallback equal to the locale is tried once; an empty fallback is none.
        assert_eq!(
            translator
                .clone()
                .with_fallback("nl")
                .get("messages.only_en", &[], None),
            "English"
        );
        assert_eq!(
            translator
                .clone()
                .with_fallback("")
                .get("messages.only_en", &[], Some("nl")),
            "messages.only_en"
        );
        assert_eq!(translator.clone().with_fallback("0").fallback(), Some("0"));
        // Another default locale reads the same lines.
        let dutch = translator
            .clone()
            .with_locale("nl")
            .expect("a valid locale");
        assert_eq!(dutch.locale(), "nl");
        assert_eq!(dutch.get("messages.welcome", &[], None), "Hallo :name");
        assert_eq!(translator.locale(), "en");
    }

    #[test]
    fn invalid_locales_are_errors() {
        let missing = table::TempDir::new("no-lang");
        for locale in ["en/nl", "a\\b", "..", "a..b", "en\0"] {
            assert!(
                JsonTranslator::load(missing.path(), locale).is_err(),
                "{locale:?}"
            );
            assert!(
                JsonTranslator::load(missing.path(), "en")
                    .expect("valid")
                    .with_locale(locale)
                    .is_err(),
                "{locale:?}"
            );
        }
        // A directory that is not there holds no lines: every key is its own translation.
        let translator = JsonTranslator::load(missing.path(), "en").expect("a valid locale");
        assert_eq!(
            translator.get("Welcome, :name", &[("name", "Ana")], None),
            "Welcome, Ana"
        );
        assert!(!translator.has("messages.welcome", None));
        assert_eq!(
            translator.choice("{1} one|many", Number::from(1), &[], None),
            "one"
        );
    }

    #[test]
    fn the_trait_is_object_safe_and_the_translator_is_shared() {
        fn render(translator: &dyn Translator) -> String {
            translator.get("messages.welcome", &[("name", "Ana")], None)
        }
        let translator = app(Some("en"));
        assert_eq!(render(&translator), "JSON Ana");
        fn assert_shared<T: Send + Sync>() {}
        assert_shared::<JsonTranslator>();
        assert_shared::<Box<dyn Translator + Send + Sync>>();
        assert_eq!(Number::from(3usize), Number::Int(3));
        assert_eq!(
            Number::from(u64::MAX),
            Number::Float(18446744073709551616.0)
        );
        assert_eq!(Number::from(2.5_f32), Number::Float(2.5));
    }
}