calnexus 0.1.4

A command-line math expression evaluator with 11 core and 4 optional (numerical/time/unit/fx) computation domains, symbolic calculus, REPL, and batch processing
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
// Copyright (c) 2026 Kirky.X. Licensed under the MIT License.

//! ICU4X 国际化模块:中英双语消息目录。
//!
//! 设计依据:design.md §4 (ICU4X 设计)
//! - `I18n` 结构体始终可用(不受 feature gate 限制)
//! - `icu` feature 仅控制是否使用 `icu::locale` 解析 BCP-47 语言标签
//! - 无 `icu` feature 时,`from_str` 使用简单字符串匹配
//! - 消息目录外部化到 `locales/{en,zh}.json`,编译时通过 `include_str!` 嵌入
//! - 简单消息用 `t(key)`,参数化消息用 `tf(key, args)`(`{name}` 占位符)
//! - 未知键返回键本身(fail-loud)

use std::collections::HashMap;
use std::sync::OnceLock;

/// 支持的语言。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Lang {
    /// 英语(默认回退语言)
    #[default]
    En,
    /// 中文
    Zh,
}

/// 国际化上下文:持有当前语言,提供消息目录查询。
///
/// `Clone` 派生:`cli::run_repl_mode` 需要 `I18n::clone()` 传入 ReplSession(REPL 持有
/// 自己的实例以便长期运行),而 `Lang` 是 `Copy` 类型,clone 成本为零。
#[derive(Clone)]
pub struct I18n {
    lang: Lang,
}

// 静态消息表:编译时嵌入 JSON,运行时解析一次后缓存。
// `HashMap<&'static str, &'static str>` 借用 `include_str!` 的 'static 数据,
// 零拷贝(JSON 中无转义字符,serde_json 可直接借用原始字节)。
static EN_MESSAGES: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
static ZH_MESSAGES: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();

/// 加载英文消息表(首次调用解析 JSON,后续直接返回缓存)。
fn en_messages() -> &'static HashMap<&'static str, &'static str> {
    EN_MESSAGES.get_or_init(|| {
        let json = include_str!("../locales/en.json");
        // 编译时 JSON 损坏是开发期错误,panic 提示修复(规则12 失败显性化)
        serde_json::from_str(json).unwrap_or_else(|e| panic!("locales/en.json 解析失败: {e}"))
    })
}

/// 加载中文消息表(首次调用解析 JSON,后续直接返回缓存)。
fn zh_messages() -> &'static HashMap<&'static str, &'static str> {
    ZH_MESSAGES.get_or_init(|| {
        let json = include_str!("../locales/zh.json");
        serde_json::from_str(json).unwrap_or_else(|e| panic!("locales/zh.json 解析失败: {e}"))
    })
}

impl I18n {
    /// 创建指定语言的 i18n 上下文。
    pub fn new(lang: Lang) -> Self {
        Self { lang }
    }

    /// 从 BCP-47 语言标签字符串解析语言。
    ///
    /// - "en"/"en-US"/"en-GB" → `Lang::En`
    /// - "zh"/"zh-CN"/"zh-TW" → `Lang::Zh`
    /// - 未知语言 → 回退 `Lang::En`
    ///
    /// 注意:不实现 `std::str::FromStr`,因为此方法不会失败(总是回退到 En),
    /// 而 `FromStr` 要求返回 `Result`。
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Self {
        let lang = parse_lang(s);
        Self::new(lang)
    }

    /// 获取当前语言。
    pub fn lang(&self) -> Lang {
        self.lang
    }

    /// 查询简单消息目录(无占位符)。
    ///
    /// 已知键返回对应语言的翻译文本;未知键返回键本身(fail-loud)。
    pub fn t<'a>(&self, key: &'a str) -> &'a str {
        let table = match self.lang {
            Lang::En => en_messages(),
            Lang::Zh => zh_messages(),
        };
        table.get(key).copied().unwrap_or(key)
    }

    /// 查询参数化消息目录(含 `{name}` 占位符)。
    ///
    /// 占位符格式:`{name}`,`args` 提供 `(name, value)` 键值对。
    /// - 已知键:替换所有匹配的占位符后返回 `String`
    /// - 未知键:返回键本身(fail-loud,不进行替换)
    /// - 占位符未提供值:保留原样(便于调试缺失的参数)
    pub fn tf(&self, key: &str, args: &[(&str, &str)]) -> String {
        let template = self.t(key);
        if args.is_empty() {
            return template.to_string();
        }
        let mut result = template.to_string();
        for (name, value) in args {
            let placeholder = format!("{{{}}}", name);
            result = result.replace(&placeholder, value);
        }
        result
    }
}

impl Default for I18n {
    fn default() -> Self {
        Self::new(Lang::default())
    }
}

/// 解析 BCP-47 语言标签为 `Lang`。
///
/// 有 `icu` feature 时使用 `icu::locale` 解析;否则使用简单字符串匹配。
fn parse_lang(s: &str) -> Lang {
    #[cfg(feature = "icu")]
    {
        parse_lang_icu(s)
    }
    #[cfg(not(feature = "icu"))]
    {
        parse_lang_simple(s)
    }
}

/// 使用 `icu::locale` 解析 BCP-47 语言标签。
#[cfg(feature = "icu")]
fn parse_lang_icu(s: &str) -> Lang {
    use icu::locale::Locale;

    match Locale::try_from_str(s) {
        Ok(locale) => {
            let lang = locale.id.language;
            if lang.as_str() == "zh" {
                Lang::Zh
            } else {
                Lang::En
            }
        }
        Err(_) => Lang::En,
    }
}

/// 使用简单字符串匹配解析语言标签(无 `icu` feature 时的回退)。
///
/// BUG-I-M-001 修复:按 BCP-47 标准以 `-` 分割子标签,取第一段作为 language primary subtag。
/// 此前仅精确匹配 `zh`/`zh-CN`/`zh-TW`,不识别 `zh-Hans`/`zh-Hant`/`zh-Hans-CN` 等
/// 带脚本子标签的标准标签。现按 primary subtag 识别,覆盖所有 `zh-*` 变体
/// (包括 `zh-Hans`/`zh-Hant`/`zh-Hans-CN`/`zh-Latn-pinyin`/`zh-x-*` 私有用标签)。
///
/// 通过 split('-') 而非 starts_with("zh") 避免误匹配 `zhongwen` 等字符串
/// (`zhongwen` 的 primary subtag 是 `zhongwen` 而非 `zh`)。
#[cfg(not(feature = "icu"))]
fn parse_lang_simple(s: &str) -> Lang {
    let lower = s.to_ascii_lowercase();
    // BCP-47 标签结构:language [-script] [-region] [-variant]
    // 取第一段作为 language primary subtag(如 "zh-Hans-CN" → "zh")
    let primary = lower.split('-').next().unwrap_or("");
    match primary {
        "zh" => Lang::Zh,
        _ => Lang::En,
    }
}

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

    // ===== Lang 默认值 =====

    #[test]
    fn test_lang_default_is_english() {
        assert_eq!(Lang::default(), Lang::En);
    }

    // ===== I18n::new =====

    #[test]
    fn test_new_creates_with_specified_lang() {
        let en = I18n::new(Lang::En);
        assert_eq!(en.lang(), Lang::En);

        let zh = I18n::new(Lang::Zh);
        assert_eq!(zh.lang(), Lang::Zh);
    }

    #[test]
    fn test_default_is_english() {
        let i18n = I18n::default();
        assert_eq!(i18n.lang(), Lang::En);
    }

    // ===== I18n::from_str — 基本解析 =====

    #[test]
    fn test_from_str_en() {
        assert_eq!(I18n::from_str("en").lang(), Lang::En);
    }

    #[test]
    fn test_from_str_zh() {
        assert_eq!(I18n::from_str("zh").lang(), Lang::Zh);
    }

    // ===== I18n::from_str — BCP-47 变体 =====

    #[test]
    fn test_from_str_en_us() {
        assert_eq!(I18n::from_str("en-US").lang(), Lang::En);
    }

    #[test]
    fn test_from_str_en_gb() {
        assert_eq!(I18n::from_str("en-GB").lang(), Lang::En);
    }

    #[test]
    fn test_from_str_zh_cn() {
        assert_eq!(I18n::from_str("zh-CN").lang(), Lang::Zh);
    }

    #[test]
    fn test_from_str_zh_tw() {
        assert_eq!(I18n::from_str("zh-TW").lang(), Lang::Zh);
    }

    // ===== I18n::from_str — 未知语言回退 =====

    #[test]
    fn test_from_str_french_fallback_to_en() {
        assert_eq!(I18n::from_str("fr").lang(), Lang::En);
    }

    #[test]
    fn test_from_str_japanese_fallback_to_en() {
        assert_eq!(I18n::from_str("ja").lang(), Lang::En);
    }

    #[test]
    fn test_from_str_empty_string_fallback_to_en() {
        assert_eq!(I18n::from_str("").lang(), Lang::En);
    }

    #[test]
    fn test_from_str_invalid_string_fallback_to_en() {
        assert_eq!(I18n::from_str("!!!").lang(), Lang::En);
    }

    /// T010 Red: "zhongwen" 以 "zh" 开头但不是有效的中文语言代码,应回退到 En
    #[test]
    fn test_from_str_zhongwen_falls_back_to_en() {
        let i18n = I18n::from_str("zhongwen");
        assert_eq!(
            i18n.lang(),
            Lang::En,
            "zhongwen should fall back to En, not Zh"
        );
    }

    // ===== BUG-I-M-001: BCP-47 脚本子标签解析 =====
    // parse_lang_simple 此前仅精确匹配 "zh"/"zh-CN"/"zh-TW",
    // 不识别 "zh-Hans"/"zh-Hant"/"zh-Hans-CN" 等带脚本的标准 BCP-47 标签。

    #[test]
    fn test_from_str_zh_hans() {
        assert_eq!(I18n::from_str("zh-Hans").lang(), Lang::Zh);
    }

    #[test]
    fn test_from_str_zh_hant() {
        assert_eq!(I18n::from_str("zh-Hant").lang(), Lang::Zh);
    }

    #[test]
    fn test_from_str_zh_hans_cn() {
        assert_eq!(I18n::from_str("zh-Hans-CN").lang(), Lang::Zh);
    }

    #[test]
    fn test_from_str_zh_hant_tw() {
        assert_eq!(I18n::from_str("zh-Hant-TW").lang(), Lang::Zh);
    }

    #[test]
    fn test_from_str_zh_hans_sg() {
        assert_eq!(I18n::from_str("zh-Hans-SG").lang(), Lang::Zh);
    }

    #[test]
    fn test_from_str_zh_hant_hk() {
        assert_eq!(I18n::from_str("zh-Hant-HK").lang(), Lang::Zh);
    }

    #[test]
    fn test_from_str_zh_hans_mixed_case() {
        assert_eq!(I18n::from_str("ZH-hans").lang(), Lang::Zh);
        assert_eq!(I18n::from_str("zh-HANS").lang(), Lang::Zh);
    }

    /// "zh-x-calnexus" 是合法 BCP-47 私有用标签,应识别为 Zh。
    #[test]
    fn test_from_str_zh_private_use() {
        assert_eq!(I18n::from_str("zh-x-calnexus").lang(), Lang::Zh);
    }

    /// "zh-Latn-pinyin" 是合法 BCP-47 标签(拼音罗马化),应识别为 Zh。
    #[test]
    fn test_from_str_zh_latn_pinyin() {
        assert_eq!(I18n::from_str("zh-Latn-pinyin").lang(), Lang::Zh);
    }

    /// "zhongwen-Hans" 不是合法 BCP-47 language(primary subtag "zhongwen" 非短码),应回退到 En。
    #[test]
    fn test_from_str_zhongwen_hans_falls_back_to_en() {
        assert_eq!(I18n::from_str("zhongwen-Hans").lang(), Lang::En);
    }

    // ===== I18n::from_str — 大小写不敏感 =====

    #[test]
    fn test_from_str_case_insensitive_zh() {
        assert_eq!(I18n::from_str("ZH").lang(), Lang::Zh);
        assert_eq!(I18n::from_str("Zh").lang(), Lang::Zh);
    }

    #[test]
    fn test_from_str_case_insensitive_en() {
        assert_eq!(I18n::from_str("EN").lang(), Lang::En);
        assert_eq!(I18n::from_str("En").lang(), Lang::En);
    }

    // ===== I18n::t — 全消息键中英双语 =====

    #[test]
    fn test_all_message_keys_have_english_translation() {
        let i18n = I18n::new(Lang::En);
        let keys = [
            "error.parse",
            "error.eval",
            "error.overflow",
            "error.division_by_zero",
            "error.domain",
            "error.depth",
            "error.nan_or_inf",
            "error.undefined_symbol",
            "error.timeout",
            "error.usage",
            "label.position",
            "label.hint",
            "label.error_kind",
            "label.exit_code",
            "label.suggestion",
            // 参数化消息键(含占位符,但 t() 返回原始模板)
            "msg.unbound_variable",
            "msg.invalid_bignumber",
            "msg.matrix_dim_mismatch",
            "msg.function_arg_count",
            "msg.unknown_function",
            "msg.unknown_variable",
        ];
        for key in &keys {
            let msg = i18n.t(key);
            assert!(
                msg != *key,
                "key '{}' has no English translation (returned key itself)",
                key
            );
            assert!(
                !msg.is_empty(),
                "key '{}' has empty English translation",
                key
            );
        }
    }

    #[test]
    fn test_all_message_keys_have_chinese_translation() {
        let i18n = I18n::new(Lang::Zh);
        let keys = [
            "error.parse",
            "error.eval",
            "error.overflow",
            "error.division_by_zero",
            "error.domain",
            "error.depth",
            "error.nan_or_inf",
            "error.undefined_symbol",
            "error.timeout",
            "error.usage",
            "label.position",
            "label.hint",
            "label.error_kind",
            "label.exit_code",
            "label.suggestion",
            "msg.unbound_variable",
            "msg.invalid_bignumber",
            "msg.matrix_dim_mismatch",
            "msg.function_arg_count",
            "msg.unknown_function",
            "msg.unknown_variable",
        ];
        for key in &keys {
            let msg = i18n.t(key);
            assert!(
                msg != *key,
                "key '{}' has no Chinese translation (returned key itself)",
                key
            );
            assert!(
                !msg.is_empty(),
                "key '{}' has empty Chinese translation",
                key
            );
        }
    }

    // ===== I18n::t — 中英翻译不同 =====

    #[test]
    fn test_en_and_zh_translations_differ() {
        let en = I18n::new(Lang::En);
        let zh = I18n::new(Lang::Zh);
        let keys = [
            "error.parse",
            "error.eval",
            "error.overflow",
            "error.division_by_zero",
            "error.domain",
            "error.depth",
            "error.nan_or_inf",
            "error.undefined_symbol",
            "error.timeout",
            "error.usage",
            "label.position",
            "label.hint",
            "label.error_kind",
            "label.exit_code",
            "label.suggestion",
            "msg.unbound_variable",
            "msg.invalid_bignumber",
            "msg.matrix_dim_mismatch",
            "msg.function_arg_count",
            "msg.unknown_function",
            "msg.unknown_variable",
        ];
        for key in &keys {
            assert_ne!(
                en.t(key),
                zh.t(key),
                "key '{}' has identical en/zh translations",
                key
            );
        }
    }

    // ===== I18n::t — 未知键 fail-loud =====

    #[test]
    fn test_unknown_key_returns_key_itself() {
        let en = I18n::new(Lang::En);
        assert_eq!(en.t("nonexistent.key"), "nonexistent.key");

        let zh = I18n::new(Lang::Zh);
        assert_eq!(zh.t("nonexistent.key"), "nonexistent.key");
    }

    #[test]
    fn test_empty_key_returns_empty_string() {
        let en = I18n::new(Lang::En);
        assert_eq!(en.t(""), "");
    }

    // ===== I18n::t — 具体翻译内容验证 =====

    #[test]
    fn test_specific_english_translations() {
        let en = I18n::new(Lang::En);
        assert_eq!(en.t("error.parse"), "Parse error");
        assert_eq!(en.t("error.eval"), "Evaluation error");
        assert_eq!(en.t("error.overflow"), "Arithmetic overflow");
        assert_eq!(en.t("error.division_by_zero"), "Division by zero");
        assert_eq!(en.t("error.domain"), "Domain error");
        assert_eq!(en.t("error.depth"), "Maximum recursion depth exceeded");
        assert_eq!(en.t("error.nan_or_inf"), "Result is NaN or infinity");
        assert_eq!(en.t("error.undefined_symbol"), "Undefined symbol");
        assert_eq!(en.t("error.timeout"), "Evaluation timed out");
        assert_eq!(en.t("error.usage"), "Usage error");
        // 5 个标签键(T002 diting HIGH-1 修复)
        assert_eq!(en.t("label.position"), "Position");
        assert_eq!(en.t("label.hint"), "Hint");
        assert_eq!(en.t("label.error_kind"), "Error Kind");
        assert_eq!(en.t("label.exit_code"), "Exit Code");
        assert_eq!(en.t("label.suggestion"), "Suggestion");
    }

    #[test]
    fn test_specific_chinese_translations() {
        let zh = I18n::new(Lang::Zh);
        assert_eq!(zh.t("error.parse"), "解析错误");
        assert_eq!(zh.t("error.eval"), "求值错误");
        assert_eq!(zh.t("error.overflow"), "算术溢出");
        assert_eq!(zh.t("error.division_by_zero"), "除以零");
        assert_eq!(zh.t("error.domain"), "定义域错误");
        assert_eq!(zh.t("error.depth"), "超过最大递归深度");
        assert_eq!(zh.t("error.nan_or_inf"), "结果为 NaN 或无穷大");
        assert_eq!(zh.t("error.undefined_symbol"), "未定义符号");
        assert_eq!(zh.t("error.timeout"), "求值超时");
        assert_eq!(zh.t("error.usage"), "用法错误");
        // 5 个标签键(T002 diting HIGH-1 修复)
        assert_eq!(zh.t("label.position"), "位置");
        assert_eq!(zh.t("label.hint"), "提示");
        assert_eq!(zh.t("label.error_kind"), "错误类别");
        assert_eq!(zh.t("label.exit_code"), "退出码");
        assert_eq!(zh.t("label.suggestion"), "建议");
    }

    // ===== I18n::tf — 参数化消息 =====

    #[test]
    fn test_tf_single_placeholder_en() {
        let i18n = I18n::new(Lang::En);
        assert_eq!(
            i18n.tf("msg.unbound_variable", &[("name", "x")]),
            "Unbound variable: x"
        );
        assert_eq!(
            i18n.tf("msg.unknown_function", &[("name", "sin")]),
            "Unknown function: sin"
        );
    }

    #[test]
    fn test_tf_single_placeholder_zh() {
        let i18n = I18n::new(Lang::Zh);
        assert_eq!(
            i18n.tf("msg.unbound_variable", &[("name", "x")]),
            "未绑定变量: x"
        );
        assert_eq!(
            i18n.tf("msg.unknown_function", &[("name", "sin")]),
            "未知函数: sin"
        );
    }

    #[test]
    fn test_tf_multiple_placeholders_en() {
        let i18n = I18n::new(Lang::En);
        assert_eq!(
            i18n.tf(
                "msg.matrix_dim_mismatch",
                &[("expected", "3x3"), ("actual", "2x2")]
            ),
            "Matrix dimension mismatch: expected 3x3, got 2x2"
        );
        assert_eq!(
            i18n.tf(
                "msg.function_arg_count",
                &[("name", "sin"), ("expected", "1"), ("actual", "2")]
            ),
            "Function sin expects 1 args, got 2"
        );
    }

    #[test]
    fn test_tf_multiple_placeholders_zh() {
        let i18n = I18n::new(Lang::Zh);
        assert_eq!(
            i18n.tf(
                "msg.matrix_dim_mismatch",
                &[("expected", "3x3"), ("actual", "2x2")]
            ),
            "矩阵维度不匹配: 期望 3x3, 实际 2x2"
        );
        assert_eq!(
            i18n.tf(
                "msg.function_arg_count",
                &[("name", "sin"), ("expected", "1"), ("actual", "2")]
            ),
            "函数 sin 期望 1 个参数, 实际 2"
        );
    }

    // ===== I18n::tf — 未知键与边界 =====

    #[test]
    fn test_tf_unknown_key_returns_key_itself() {
        let en = I18n::new(Lang::En);
        // 未知键:返回键本身,不进行替换
        assert_eq!(
            en.tf("nonexistent.key", &[("name", "x")]),
            "nonexistent.key"
        );

        let zh = I18n::new(Lang::Zh);
        assert_eq!(
            zh.tf("nonexistent.key", &[("name", "x")]),
            "nonexistent.key"
        );
    }

    #[test]
    fn test_tf_missing_placeholder_preserved() {
        let i18n = I18n::new(Lang::En);
        // 模板 "Function {name} expects {expected} args, got {actual}"
        // 只提供 name,缺失 expected 和 actual —— 占位符保留原样
        assert_eq!(
            i18n.tf("msg.function_arg_count", &[("name", "sin")]),
            "Function sin expects {expected} args, got {actual}"
        );
    }

    #[test]
    fn test_tf_empty_args_equivalent_to_t() {
        let en = I18n::new(Lang::En);
        // 空参数:tf 等价于 t(返回模板字符串)
        assert_eq!(
            en.tf("msg.unbound_variable", &[]),
            "Unbound variable: {name}"
        );
        assert_eq!(en.tf("error.parse", &[]), en.t("error.parse"));

        let zh = I18n::new(Lang::Zh);
        assert_eq!(zh.tf("msg.unbound_variable", &[]), "未绑定变量: {name}");
        assert_eq!(zh.tf("error.parse", &[]), zh.t("error.parse"));
    }

    #[test]
    fn test_tf_repeated_placeholder_replaces_all() {
        let i18n = I18n::new(Lang::En);
        // 如果模板中同一占位符出现多次,replace 会替换所有匹配
        // 当前 JSON 中没有这种键,构造一个临时键验证逻辑(用未知键 + 自定义模板不可行,
        // 改为验证已知键的单次替换行为)
        let result = i18n.tf("msg.unknown_variable", &[("name", "y")]);
        assert_eq!(result, "Unknown variable: y");
        // 确保替换后没有残留占位符
        assert!(!result.contains('{') || result.contains("got"));
    }

    // ===== 静态消息表加载 =====

    #[test]
    fn test_en_messages_table_not_empty() {
        let table = en_messages();
        assert!(!table.is_empty(), "English message table must not be empty");
        // 至少包含 15 个原有键 + 6 个参数化键 = 21 个
        assert!(
            table.len() >= 21,
            "English table should have at least 21 entries, got {}",
            table.len()
        );
    }

    #[test]
    fn test_zh_messages_table_not_empty() {
        let table = zh_messages();
        assert!(!table.is_empty(), "Chinese message table must not be empty");
        assert!(
            table.len() >= 21,
            "Chinese table should have at least 21 entries, got {}",
            table.len()
        );
    }

    #[test]
    fn test_en_and_zh_tables_have_same_keys() {
        let en = en_messages();
        let zh = zh_messages();
        // 两表键集必须一致(避免遗漏翻译)
        assert_eq!(
            en.len(),
            zh.len(),
            "en/zh tables have different key counts: en={}, zh={}",
            en.len(),
            zh.len()
        );
        for key in en.keys() {
            assert!(
                zh.contains_key(key),
                "key '{}' exists in en.json but missing in zh.json",
                key
            );
        }
    }
}