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
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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
// Copyright (c) 2026 Kirky.X. Licensed under the MIT License.

//! AST 规范化器:将解析后的 `AstNode` 转换为规范形式,用于 L1 缓存去重。
//!
//! 三大变换(design.md / tasks 3.3):
//! 1. **SortCommutative**:对 `+`/`*` 操作数按规范顺序排列(数值升序,变量字典序)
//! 2. **ConstantFolder**:全常量子表达式预计算,检测溢出/NaN/Inf/除零
//! 3. **UnaryNormalizer**:双重负号 `--x` 消除为 `x`
//!
//! 规范形式序列化为 S-表达式字符串(`CanonicalForm`)。
//!
//! **Spec 冲突说明**:Req 1 Scen 1-2 期望 `3+2` → `(+ 2 3)`(仅排序),
//! 但 Req 3 Scen 1 和 Req 7 Scen 1 期望 `2+3` → `5`(折叠)。
//! 由于 Req 5 Scen 2 要求 `2*3+1` 与 `1+6` 同形式(必须折叠),
//! 本实现以**常量折叠优先**解决冲突:全常量表达式折叠为单个 Number。

use crate::core::types::{AstNode, BinaryOp, CalcError, CanonicalForm, UnaryOp};
use std::cmp::Ordering;

/// AST 规范化器。
///
/// 无状态,所有方法均为关联函数。
pub struct AstCanonicalizer;

impl AstCanonicalizer {
    /// 规范化 AST 并生成 `CanonicalForm`。
    ///
    /// 返回 `(canonical_ast, canonical_form)`:
    /// - `canonical_ast`:规范化后的 AST(常量折叠、操作数排序、一元归一化)
    /// - `canonical_form`:S-表达式字符串(用于缓存键生成)
    pub fn canonicalize(ast: &AstNode) -> Result<(AstNode, CanonicalForm), CalcError> {
        let canonical_ast = Self::transform(ast)?;
        let s_expr = Self::serialize(&canonical_ast);
        Ok((canonical_ast, CanonicalForm::new(s_expr)))
    }

    /// 规范化 AST(**不折叠常量**)并生成 `CanonicalForm`。
    ///
    /// 与 `canonicalize` 的区别:仅做交换律排序与一元归一化,不做常量折叠。
    /// 用于 `--canonical` 标志输出,满足 PRD §3.2.4 示例 `3+2` → `(+ 2 3)`。
    /// 缓存键仍使用 `canonicalize`(折叠版本),此方法仅供展示。
    pub fn canonicalize_no_fold(ast: &AstNode) -> Result<(AstNode, CanonicalForm), CalcError> {
        let canonical_ast = Self::transform_no_fold(ast)?;
        let s_expr = Self::serialize(&canonical_ast);
        Ok((canonical_ast, CanonicalForm::new(s_expr)))
    }

    /// 递归变换 AST(排序 + 折叠 + 一元归一化)。
    ///
    /// 变换顺序(bottom-up):先递归变换子节点,再对当前节点应用:
    /// 1. 常量折叠(全常量子树 → 单个 Number,仅当 `fold_constants = true`)
    /// 2. 交换律排序(Add/Mul 操作数按规范顺序)
    /// 3. 一元归一化(双重负号消除始终执行;一元常量折叠仅当 `fold_unary = true`)
    ///
    /// `transform` 与 `transform_no_fold` 的全部差异通过两个布尔参数控制:
    /// - `transform`           = `transform_inner(ast, true,  true)`
    /// - `transform_no_fold`   = `transform_inner(ast, false, false)`
    ///
    /// 双重负号消除(`--x → x`)属于结构性归一化,两个公开入口均执行,
    /// 因此**不**由 `fold_unary` 控制。
    fn transform_inner(
        ast: &AstNode,
        fold_constants: bool,
        fold_unary: bool,
    ) -> Result<AstNode, CalcError> {
        match ast {
            // Leaf 节点:直接克隆(无变换)
            AstNode::Number(_)
            | AstNode::Variable(_)
            | AstNode::Complex(_, _)
            | AstNode::BigNumber(_)
            | AstNode::Str(_) => Ok(ast.clone()),
            AstNode::BinaryOp(op, l, r) => {
                Self::transform_binary(*op, l, r, fold_constants, fold_unary)
            }
            AstNode::UnaryOp(op, e) => Self::transform_unary(*op, e, fold_constants, fold_unary),
            AstNode::FunctionCall(name, args) => {
                Self::transform_function(name, args, fold_constants, fold_unary)
            }
            AstNode::Matrix(rows) => Self::transform_matrix(rows, fold_constants, fold_unary),
            AstNode::List(elements) => Self::transform_list(elements, fold_constants, fold_unary),
        }
    }

    /// 变换 BinaryOp:递归变换子节点 + 常量折叠 + 交换律排序。
    fn transform_binary(
        op: BinaryOp,
        l: &AstNode,
        r: &AstNode,
        fold_constants: bool,
        fold_unary: bool,
    ) -> Result<AstNode, CalcError> {
        let l = Self::transform_inner(l, fold_constants, fold_unary)?;
        let r = Self::transform_inner(r, fold_constants, fold_unary)?;
        // 常量折叠:两操作数均为 Number(仅当 fold_constants = true)
        if fold_constants {
            if let (AstNode::Number(a), AstNode::Number(b)) = (&l, &r) {
                return Self::eval_binary(op, *a, *b).map(AstNode::Number);
            }
        }
        // 交换律排序:仅 Add 和 Mul
        let (l, r) = match op {
            BinaryOp::Add | BinaryOp::Mul => {
                if Self::compare_nodes(&l, &r) == Ordering::Greater {
                    (r, l)
                } else {
                    (l, r)
                }
            }
            _ => (l, r),
        };
        Ok(AstNode::BinaryOp(op, Box::new(l), Box::new(r)))
    }

    /// 变换 UnaryOp:递归变换子节点 + 双重负号消除 + 一元常量折叠。
    fn transform_unary(
        op: UnaryOp,
        e: &AstNode,
        fold_constants: bool,
        fold_unary: bool,
    ) -> Result<AstNode, CalcError> {
        let e = Self::transform_inner(e, fold_constants, fold_unary)?;
        // 双重负号消除:--x → x(结构性归一化,始终执行)
        if op == UnaryOp::Neg {
            if let AstNode::UnaryOp(UnaryOp::Neg, inner) = &e {
                return Ok((**inner).clone());
            }
        }
        // 一元常量折叠:Neg(Number(n)) → Number(-n)(仅当 fold_unary = true)
        if fold_unary && op == UnaryOp::Neg {
            if let AstNode::Number(n) = &e {
                return Ok(AstNode::Number(-*n));
            }
        }
        Ok(AstNode::UnaryOp(op, Box::new(e)))
    }

    /// 变换 FunctionCall:递归变换所有参数。
    ///
    /// **precision 函数白名单**(BUG-C-002 修复):
    /// 当 `name == "precision"` 且 `args.len() == 2` 时,对 `args[1]`(expr)
    /// 跳过常量折叠,保留 `BinaryOp` 结构交由 Precision 域内部 `BigRational` 求值。
    ///
    /// 否则 canonicalizer 会把 `precision(20, 1/3)` 中的 `1/3` 折叠为 f64 的
    /// `0.333...`,Precision 域收到的是 f64 近似值而非精确分数 `1/3`,
    /// 导致 `precision(20, 1/3)` 输出 20 位 `0.3333...` 中包含 f64 误差而非精确 `1/3`。
    ///
    /// `args[0]`(N)仍按常量折叠处理:N 应为字面量正整数,折叠不影响其语义
    /// (`extract_precision_value` 接受 `Number`/`BigNumber`,折叠后 `2+3 → 5`
    /// 仍可被识别为 N=5)。
    ///
    /// 仅在 `fold_constants = true` 时启用白名单(即 `transform` 入口生效);
    /// `transform_no_fold` 本就不折叠,无需特殊处理。
    fn transform_function(
        name: &str,
        args: &[AstNode],
        fold_constants: bool,
        fold_unary: bool,
    ) -> Result<AstNode, CalcError> {
        // precision 函数白名单:args[1] 跳过常量折叠(保留精确分数结构)
        let precision_whitelist = fold_constants && name == "precision" && args.len() == 2;

        let mut transformed_args = Vec::with_capacity(args.len());
        for (i, arg) in args.iter().enumerate() {
            if precision_whitelist && i == 1 {
                // args[1] 跳过常量折叠,但保留交换律排序与一元归一化
                transformed_args.push(Self::transform_inner(arg, false, fold_unary)?);
            } else {
                transformed_args.push(Self::transform_inner(arg, fold_constants, fold_unary)?);
            }
        }
        Ok(AstNode::FunctionCall(name.to_string(), transformed_args))
    }

    /// 变换 Matrix:递归变换所有元素(双重循环)。
    fn transform_matrix(
        rows: &[Vec<AstNode>],
        fold_constants: bool,
        fold_unary: bool,
    ) -> Result<AstNode, CalcError> {
        let mut transformed_rows = Vec::with_capacity(rows.len());
        for row in rows {
            let mut transformed_row = Vec::with_capacity(row.len());
            for elem in row {
                transformed_row.push(Self::transform_inner(elem, fold_constants, fold_unary)?);
            }
            transformed_rows.push(transformed_row);
        }
        Ok(AstNode::Matrix(transformed_rows))
    }

    /// 变换 List:递归变换所有元素。
    fn transform_list(
        elements: &[AstNode],
        fold_constants: bool,
        fold_unary: bool,
    ) -> Result<AstNode, CalcError> {
        let mut transformed = Vec::with_capacity(elements.len());
        for elem in elements {
            transformed.push(Self::transform_inner(elem, fold_constants, fold_unary)?);
        }
        Ok(AstNode::List(transformed))
    }

    /// 递归变换 AST(排序 + 折叠 + 一元归一化)。
    fn transform(ast: &AstNode) -> Result<AstNode, CalcError> {
        Self::transform_inner(ast, true, true)
    }

    /// 递归变换 AST(**仅排序 + 一元归一化,不折叠常量**)。
    ///
    /// 与 `transform` 的区别:跳过常量折叠步骤,保留 `2+3`、`3+2` 为
    /// `(+ 2 3)`、`(+ 2 3)`(排序后相同),用于 `--canonical` 展示。
    fn transform_no_fold(ast: &AstNode) -> Result<AstNode, CalcError> {
        Self::transform_inner(ast, false, false)
    }

    /// 求值二元运算(常量折叠用),检测除零与 NaN/Inf。
    fn eval_binary(op: BinaryOp, a: f64, b: f64) -> Result<f64, CalcError> {
        let result = match op {
            BinaryOp::Add => a + b,
            BinaryOp::Sub => a - b,
            BinaryOp::Mul => a * b,
            BinaryOp::Div => {
                if b == 0.0 {
                    return Err(CalcError::division_by_zero());
                }
                a / b
            }
            // BUG-C-M-004 修复:显式处理 0^0 → 1.0(IEEE 754 约定)。
            // 原代码 `a.powf(b)` 隐式依赖 f64 的 0^0=1.0 行为,意图不显式,
            // 且与 scientific.rs/statistics.rs 的显式处理不一致。
            // 此处显式 case 使意图清晰,与所有 domain 行为统一。
            // 注意:负零 -0.0 ^ 0.0 也应返回 1.0(IEEE 754:0^0 与符号无关)。
            BinaryOp::Pow if a == 0.0 && b == 0.0 => 1.0,
            BinaryOp::Pow => a.powf(b),
            BinaryOp::Mod => {
                if b == 0.0 {
                    return Err(CalcError::division_by_zero());
                }
                a % b
            }
        };
        if result.is_nan() || result.is_infinite() {
            return Err(CalcError::nan_or_inf());
        }
        Ok(result)
    }

    /// 比较两个 AST 节点的规范顺序。
    ///
    /// 排序规则:
    /// - 两 Number:按数值升序(使用 `f64::total_cmp` 提供 IEEE 754 totalOrder 全序,
    ///   保证 NaN 排序稳定,BUG-C-M-003 修复)
    /// - 两 Variable:按字典序
    /// - Number 与非 Number:Number 优先(Less)
    /// - 其他组合(如 Variable 与复合表达式):保持原始顺序(Equal,不交换)
    fn compare_nodes(a: &AstNode, b: &AstNode) -> Ordering {
        match (a, b) {
            // BUG-C-M-003 修复:用 total_cmp 替代 partial_cmp + unwrap_or(Equal)。
            // 原代码对 NaN 返回 Equal(因 partial_cmp 返回 None),违反全序的反对称性。
            // total_cmp 遵循 IEEE 754 totalOrder:NaN 排在所有数值之前(负 NaN < 负 Inf < ... < 正 NaN)。
            (AstNode::Number(x), AstNode::Number(y)) => x.total_cmp(y),
            (AstNode::Number(_), _) => Ordering::Less,
            (_, AstNode::Number(_)) => Ordering::Greater,
            (AstNode::Variable(x), AstNode::Variable(y)) => x.cmp(y),
            _ => Ordering::Equal,
        }
    }

    /// 将 AST 序列化为 S-表达式字符串。
    ///
    /// 格式:`(op arg1 arg2 ...)`,常量直接输出数值,变量输出变量名。
    fn serialize(ast: &AstNode) -> String {
        match ast {
            AstNode::Number(n) => Self::format_number(*n),
            AstNode::BigNumber(s) => s.clone(),
            AstNode::Complex(re, im) => {
                format!(
                    "(complex {} {})",
                    Self::format_number(*re),
                    Self::format_number(*im)
                )
            }
            AstNode::Variable(v) => v.clone(),
            AstNode::BinaryOp(op, l, r) => {
                let op_str = match op {
                    BinaryOp::Add => "+",
                    BinaryOp::Sub => "-",
                    BinaryOp::Mul => "*",
                    BinaryOp::Div => "/",
                    BinaryOp::Pow => "^",
                    BinaryOp::Mod => "mod",
                };
                format!("({} {} {})", op_str, Self::serialize(l), Self::serialize(r))
            }
            AstNode::UnaryOp(op, e) => {
                let op_str = match op {
                    UnaryOp::Neg => "-",
                    UnaryOp::Factorial => "factorial",
                    UnaryOp::Abs => "abs",
                };
                format!("({} {})", op_str, Self::serialize(e))
            }
            AstNode::FunctionCall(name, args) => {
                if args.is_empty() {
                    format!("({})", name)
                } else {
                    let args_str: Vec<String> = args.iter().map(Self::serialize).collect();
                    format!("({} {})", name, args_str.join(" "))
                }
            }
            AstNode::Matrix(rows) => {
                let rows_str: Vec<String> = rows
                    .iter()
                    .map(|row| {
                        let elems: Vec<String> = row.iter().map(Self::serialize).collect();
                        format!("({})", elems.join(" "))
                    })
                    .collect();
                format!("(matrix {})", rows_str.join(" "))
            }
            AstNode::List(elements) => {
                let elems_str: Vec<String> = elements.iter().map(Self::serialize).collect();
                format!("(list {})", elems_str.join(" "))
            }
            // Str 节点:按字节序列参与 CanonicalForm 哈希(R-esl-004)。
            // 用 (str ...) 包装使不同字符串产生不同规范形式,且与变量/函数名空间隔离,
            // 避免被误识别为其他 AST 节点。
            AstNode::Str(s) => format!("(str {})", s),
        }
    }

    /// 格式化数字:整数输出无小数点,浮点数保留原样。
    fn format_number(n: f64) -> String {
        if n.fract() == 0.0 && n.abs() < 9e15 {
            format!("{}", n as i64)
        } else {
            format!("{}", n)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::parser::parse;
    use crate::core::ErrorKind;

    // 辅助函数:解析 + 规范化,返回 CanonicalForm 字符串
    fn canon(input: &str) -> Result<String, CalcError> {
        let ast = parse(input)?;
        let (_, cf) = AstCanonicalizer::canonicalize(&ast)?;
        Ok(cf.as_str().to_string())
    }

    // ===== Requirement 1: 交换律排序 =====

    #[test]
    fn test_variable_sort_addition() {
        // y+x → (+ x y)(变量字典序)
        assert_eq!(canon("y+x").unwrap(), "(+ x y)");
    }

    #[test]
    fn test_variable_sort_order_independent() {
        // x+y 和 y+x 同规范形式
        assert_eq!(canon("x+y").unwrap(), canon("y+x").unwrap());
    }

    #[test]
    fn test_number_before_variable_in_mul() {
        // 5*x 和 x*5 → (* 5 x)(数值优先于变量)
        assert_eq!(canon("5*x").unwrap(), "(* 5 x)");
        assert_eq!(canon("x*5").unwrap(), "(* 5 x)");
    }

    #[test]
    fn test_mixed_sort_number_before_variable() {
        // x+2 → (+ 2 x)(数值优先于变量)
        assert_eq!(canon("x+2").unwrap(), "(+ 2 x)");
        assert_eq!(canon("2+x").unwrap(), "(+ 2 x)");
    }

    // ===== Requirement 2: 交换律适用运算符范围 =====

    #[test]
    fn test_subtraction_not_commutative() {
        // x-2 → (- x 2)(顺序不变)
        assert_eq!(canon("x-2").unwrap(), "(- x 2)");
    }

    #[test]
    fn test_division_not_commutative() {
        // x/2 → (/ x 2)
        assert_eq!(canon("x/2").unwrap(), "(/ x 2)");
    }

    #[test]
    fn test_power_not_commutative() {
        // x^2 → (^ x 2)
        assert_eq!(canon("x^2").unwrap(), "(^ x 2)");
    }

    #[test]
    fn test_non_commutative_not_equivalent() {
        // x-2 与 2-x 不同
        assert_ne!(canon("x-2").unwrap(), canon("2-x").unwrap());
    }

    // ===== Requirement 3: 常量折叠 =====

    #[test]
    fn test_simple_constant_folding() {
        // 2+3 → 5
        assert_eq!(canon("2+3").unwrap(), "5");
    }

    #[test]
    fn test_nested_constant_folding() {
        // 2*3+1 → 7
        assert_eq!(canon("2*3+1").unwrap(), "7");
    }

    #[test]
    fn test_partial_folding_preserves_variable() {
        // 2*3+x → (+ 6 x)
        assert_eq!(canon("2*3+x").unwrap(), "(+ 6 x)");
    }

    #[test]
    fn test_division_by_zero_folding_error() {
        // 1/0 → 错误
        let result = canon("1/0");
        assert!(result.is_err());
        let err = result.unwrap_err();
        // 分别求值每个 matches! 分支,避免 || 短路导致 lines 312-313 未覆盖
        let is_div_zero = err.kind == ErrorKind::DivisionByZero;
        let is_eval_err = err.kind == ErrorKind::Eval;
        let is_nan_inf = err.kind == ErrorKind::NaNOrInf;
        assert!(
            is_div_zero || is_eval_err || is_nan_inf,
            "expected division by zero error, got {:?}",
            err
        );
    }

    // ===== Requirement 4: 一元运算归一化 =====

    #[test]
    fn test_double_negation_constant() {
        // --5 → 5(双重负号消除 + 常量折叠)
        assert_eq!(canon("--5").unwrap(), "5");
    }

    #[test]
    fn test_double_negation_variable() {
        // -(-x) → x
        assert_eq!(canon("-(-x)").unwrap(), "x");
    }

    #[test]
    fn test_single_negation_variable() {
        // -x → (- x)
        assert_eq!(canon("-x").unwrap(), "(- x)");
    }

    #[test]
    fn test_negation_with_constant_folding() {
        // -(2+3) → -5
        assert_eq!(canon("-(2+3)").unwrap(), "-5");
    }

    // ===== Requirement 5: 等价表达式生成相同规范形式 =====

    #[test]
    fn test_commutative_equivalent() {
        // 3+2 与 2+3 同形式(均折叠为 5)
        assert_eq!(canon("3+2").unwrap(), "5");
        assert_eq!(canon("2+3").unwrap(), "5");
    }

    #[test]
    fn test_folding_equivalent() {
        // 2*3+1 与 1+6 同形式(均折叠为 7)
        assert_eq!(canon("2*3+1").unwrap(), "7");
        assert_eq!(canon("1+6").unwrap(), "7");
    }

    #[test]
    fn test_composite_equivalent() {
        // x+2*3 与 6+x 同形式 → (+ 6 x)
        assert_eq!(canon("x+2*3").unwrap(), "(+ 6 x)");
        assert_eq!(canon("6+x").unwrap(), "(+ 6 x)");
    }

    #[test]
    fn test_non_commutative_not_equivalent_constants() {
        // 2-3 与 3-2 不同(折叠后 -1 与 1)
        assert_ne!(canon("2-3").unwrap(), canon("3-2").unwrap());
    }

    // ===== Requirement 6: 规范形式幂等性 =====

    #[test]
    fn test_idempotent_simple() {
        // 2+3*x 规范化后再规范化,结果不变
        let ast = parse("2+3*x").unwrap();
        let (canon_ast1, cf1) = AstCanonicalizer::canonicalize(&ast).unwrap();
        let (_, cf2) = AstCanonicalizer::canonicalize(&canon_ast1).unwrap();
        assert_eq!(cf1, cf2);
    }

    #[test]
    fn test_idempotent_after_folding() {
        // 2*3+1 → 7,再规范化 7 → 7
        let ast = parse("2*3+1").unwrap();
        let (canon_ast1, _) = AstCanonicalizer::canonicalize(&ast).unwrap();
        let (_, cf2) = AstCanonicalizer::canonicalize(&canon_ast1).unwrap();
        assert_eq!(cf2.as_str(), "7");
    }

    #[test]
    fn test_idempotent_nested() {
        // (x+y)*2 规范化两次
        let ast = parse("(x+y)*2").unwrap();
        let (canon_ast1, cf1) = AstCanonicalizer::canonicalize(&ast).unwrap();
        let (_, cf2) = AstCanonicalizer::canonicalize(&canon_ast1).unwrap();
        assert_eq!(cf1, cf2);
    }

    // ===== Requirement 7: 规范形式序列化 =====

    #[test]
    fn test_serialize_folded_constant() {
        // 2+3 → "5"
        assert_eq!(canon("2+3").unwrap(), "5");
    }

    #[test]
    fn test_serialize_variable_with_folded() {
        // x*(1+2) → (* 3 x)(常量 1+2 折叠为 3,数值优先于变量)
        // 注:spec Req 7 Scen 2 原写 `(* x 3)`,与 Req 1 Scen 4 的"数值优先"规则矛盾,
        // 本实现遵循 Req 1 的排序规则(数值优先于变量)。
        assert_eq!(canon("x*(1+2)").unwrap(), "(* 3 x)");
    }

    #[test]
    fn test_serialize_function_call() {
        // sin(pi/2) → (sin (/ pi 2))
        assert_eq!(canon("sin(pi/2)").unwrap(), "(sin (/ pi 2))");
    }

    #[test]
    fn test_serialize_nested_structure() {
        // (x+y)*z → (* (+ x y) z)
        assert_eq!(canon("(x+y)*z").unwrap(), "(* (+ x y) z)");
    }

    // ===== Requirement 8: 规范化深度限制 =====

    #[test]
    fn test_folding_reduces_depth() {
        // ((((1+2)+3)+4)+5) → 15(深度 1)
        let ast = parse("((((1+2)+3)+4)+5)").unwrap();
        let (canon_ast, _) = AstCanonicalizer::canonicalize(&ast).unwrap();
        assert_eq!(canon_ast, AstNode::Number(15.0));
    }

    #[test]
    fn test_variable_depth_not_increased() {
        // 深度 100 的变量嵌套表达式,规范化后深度 ≤ 100
        let expr = format!("1{}", "+x".repeat(99));
        let ast = parse(&expr).unwrap();
        let (canon_ast, _) = AstCanonicalizer::canonicalize(&ast).unwrap();
        let original_depth = ast_depth(&ast);
        let canon_depth = ast_depth(&canon_ast);
        assert!(
            canon_depth <= original_depth,
            "canonical depth {} > original depth {}",
            canon_depth,
            original_depth
        );
    }

    #[test]
    fn test_canonicalize_depth_256_succeeds() {
        // 深度 256 的合法 AST 规范化成功
        let expr = format!("1{}", "+x".repeat(255));
        let ast = parse(&expr).unwrap();
        let result = AstCanonicalizer::canonicalize(&ast);
        assert!(
            result.is_ok(),
            "expected ok for depth 256, got {:?}",
            result
        );
    }

    // 辅助函数:计算 AST 深度
    fn ast_depth(ast: &AstNode) -> usize {
        match ast {
            AstNode::Number(_)
            | AstNode::Variable(_)
            | AstNode::Complex(_, _)
            | AstNode::BigNumber(_)
            | AstNode::Str(_) => 1,
            AstNode::BinaryOp(_, l, r) => 1 + ast_depth(l).max(ast_depth(r)),
            AstNode::UnaryOp(_, e) => 1 + ast_depth(e),
            AstNode::FunctionCall(_, args) => 1 + args.iter().map(ast_depth).max().unwrap_or(0),
            AstNode::Matrix(rows) => {
                1 + rows
                    .iter()
                    .flat_map(|row| row.iter())
                    .map(ast_depth)
                    .max()
                    .unwrap_or(0)
            }
            AstNode::List(elements) => 1 + elements.iter().map(ast_depth).max().unwrap_or(0),
        }
    }

    // ===== 覆盖 Matrix/List transform 与 serialize =====

    #[test]
    fn test_canonicalize_matrix_literal() {
        // 矩阵字面量规范化:覆盖 Matrix 分支(transform + serialize)
        let cf = canon("[[1,2],[3,4]]").unwrap();
        assert_eq!(cf, "(matrix (1 2) (3 4))");
    }

    #[test]
    fn test_canonicalize_list_literal() {
        // 列表字面量规范化:覆盖 List 分支(transform + serialize)
        let cf = canon("[1,2,3]").unwrap();
        assert_eq!(cf, "(list 1 2 3)");
    }

    #[test]
    fn test_canonicalize_list_with_nested_expr() {
        // 列表元素为表达式:覆盖 List transform 递归
        let cf = canon("[2+3, x]").unwrap();
        assert_eq!(cf, "(list 5 x)");
    }

    #[test]
    fn test_canonicalize_matrix_with_nested_expr() {
        // 矩阵元素为表达式:覆盖 Matrix transform 递归
        let cf = canon("[[2+3, x]]").unwrap();
        assert_eq!(cf, "(matrix (5 x))");
    }

    // ===== 覆盖 Div/Mod 常量折叠 =====

    #[test]
    fn test_division_non_zero_folds() {
        // 6/3 → 2(覆盖 eval_binary Div 分支 b != 0)
        assert_eq!(canon("6/3").unwrap(), "2");
    }

    #[test]
    fn test_modulo_by_zero_folding_error_manual_ast() {
        // 手动构造 BinaryOp::Mod(... , 0) — parser 不会产生此 AST
        // 覆盖 eval_binary Mod 分支 b == 0 的错误路径
        let ast = AstNode::BinaryOp(
            BinaryOp::Mod,
            Box::new(AstNode::Number(5.0)),
            Box::new(AstNode::Number(0.0)),
        );
        let result = AstCanonicalizer::canonicalize(&ast);
        assert!(result.is_err());
        assert!(result.unwrap_err().kind == ErrorKind::DivisionByZero);
    }

    #[test]
    fn test_modulo_non_zero_folds_manual_ast() {
        // 手动构造 BinaryOp::Mod(5, 3) → 2(覆盖 eval_binary Mod 分支 b != 0)
        let ast = AstNode::BinaryOp(
            BinaryOp::Mod,
            Box::new(AstNode::Number(5.0)),
            Box::new(AstNode::Number(3.0)),
        );
        let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
        assert_eq!(cf.as_str(), "2");
    }

    #[test]
    fn test_pow_overflow_error() {
        // 2^99999 → Inf → NaNOrInf 错误
        let result = canon("2^99999");
        assert!(result.is_err());
        assert!(result.unwrap_err().kind == ErrorKind::NaNOrInf);
    }

    // ===== 覆盖 BigNumber/Complex 序列化 =====

    #[test]
    fn test_canonicalize_big_number_literal() {
        // 16+ 位整数 → BigNumber 节点,序列化为原始字符串
        let cf = canon("1234567890123456").unwrap();
        assert_eq!(cf, "1234567890123456");
    }

    #[test]
    fn test_canonicalize_complex_literal() {
        // 3+4i → Complex(3,4),序列化为 (complex 3 4)
        let cf = canon("3+4i").unwrap();
        assert_eq!(cf, "(complex 3 4)");
    }

    #[test]
    fn test_canonicalize_complex_negative_imaginary() {
        // 3-4i → Complex(3,-4)
        let cf = canon("3-4i").unwrap();
        assert_eq!(cf, "(complex 3 -4)");
    }

    // ===== 覆盖 BinaryOp::Mod / UnaryOp::Factorial/Abs 序列化 =====

    #[test]
    fn test_serialize_binary_mod_op() {
        // 手动构造 BinaryOp::Mod(x, 2) → "(mod x 2)"
        let ast = AstNode::BinaryOp(
            BinaryOp::Mod,
            Box::new(AstNode::Variable("x".to_string())),
            Box::new(AstNode::Number(2.0)),
        );
        let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
        assert_eq!(cf.as_str(), "(mod x 2)");
    }

    #[test]
    fn test_serialize_unary_factorial_op() {
        // 手动构造 UnaryOp::Factorial(x) → "(factorial x)"
        let ast = AstNode::UnaryOp(
            UnaryOp::Factorial,
            Box::new(AstNode::Variable("x".to_string())),
        );
        let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
        assert_eq!(cf.as_str(), "(factorial x)");
    }

    #[test]
    fn test_serialize_unary_abs_op() {
        // 手动构造 UnaryOp::Abs(x) → "(abs x)"
        let ast = AstNode::UnaryOp(UnaryOp::Abs, Box::new(AstNode::Variable("x".to_string())));
        let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
        assert_eq!(cf.as_str(), "(abs x)");
    }

    #[test]
    fn test_serialize_unary_factorial_on_number_no_fold() {
        // UnaryOp::Factorial(Number(5)) — 不折叠(Factorial 不在折叠规则中)
        // 覆盖 UnaryOp 分支中 op != Neg 的路径
        let ast = AstNode::UnaryOp(UnaryOp::Factorial, Box::new(AstNode::Number(5.0)));
        let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
        assert_eq!(cf.as_str(), "(factorial 5)");
    }

    #[test]
    fn test_serialize_unary_abs_on_number_no_fold() {
        // UnaryOp::Abs(Number(5)) — 不折叠
        let ast = AstNode::UnaryOp(UnaryOp::Abs, Box::new(AstNode::Number(5.0)));
        let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
        assert_eq!(cf.as_str(), "(abs 5)");
    }

    // ===== 覆盖空参数函数与浮点数格式化 =====

    #[test]
    fn test_serialize_empty_args_function() {
        // 手动构造无参数函数调用:覆盖 serialize 中 args.is_empty() 分支
        let ast = AstNode::FunctionCall("foo".to_string(), vec![]);
        let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
        assert_eq!(cf.as_str(), "(foo)");
    }

    #[test]
    fn test_format_number_float() {
        // 3.14 → "3.14"(覆盖 format_number 浮点分支)
        let cf = canon("3.14").unwrap();
        assert_eq!(cf, "3.14");
    }

    #[test]
    fn test_format_number_float_in_expr() {
        // 1.5+x → "(+ 1.5 x)"(覆盖 format_number 浮点分支 + 排序)
        let cf = canon("1.5+x").unwrap();
        assert_eq!(cf, "(+ 1.5 x)");
    }

    // ===== 覆盖 ast_depth 各分支 =====

    #[test]
    fn test_ast_depth_unary_op_branch() {
        // 覆盖 ast_depth 的 UnaryOp 分支
        let ast = AstNode::UnaryOp(UnaryOp::Neg, Box::new(AstNode::Number(5.0)));
        assert_eq!(ast_depth(&ast), 2);
    }

    #[test]
    fn test_ast_depth_function_call_branch() {
        // 覆盖 ast_depth 的 FunctionCall 分支
        let ast =
            AstNode::FunctionCall("sin".to_string(), vec![AstNode::Variable("x".to_string())]);
        assert_eq!(ast_depth(&ast), 2);
    }

    #[test]
    fn test_ast_depth_matrix_branch() {
        // 覆盖 ast_depth 的 Matrix 分支
        let ast = AstNode::Matrix(vec![vec![AstNode::Number(1.0), AstNode::Number(2.0)]]);
        assert_eq!(ast_depth(&ast), 2);
    }

    #[test]
    fn test_ast_depth_list_branch() {
        // 覆盖 ast_depth 的 List 分支
        let ast = AstNode::List(vec![AstNode::Number(1.0), AstNode::Number(2.0)]);
        assert_eq!(ast_depth(&ast), 2);
    }

    #[test]
    fn test_ast_depth_list_empty_branch() {
        // 覆盖 ast_depth 的 List 空列表分支(unwrap_or(0))
        let ast = AstNode::List(vec![]);
        assert_eq!(ast_depth(&ast), 1);
    }

    #[test]
    fn test_ast_depth_matrix_empty_branch() {
        // 覆盖 ast_depth 的 Matrix 空矩阵分支(unwrap_or(0))
        let ast = AstNode::Matrix(vec![vec![]]);
        assert_eq!(ast_depth(&ast), 1);
    }

    // ===== 覆盖 compare_nodes 的 Number-Number 分支 =====

    #[test]
    fn test_compare_nodes_number_vs_number() {
        // 覆盖 compare_nodes 中 (Number, Number) 分支(lines 143-144)
        // 该分支在常规规范化流程中不可达(常量折叠优先于排序),
        // 通过直接调用 compare_nodes 验证其正确性
        use std::cmp::Ordering;
        let a = AstNode::Number(1.0);
        let b = AstNode::Number(2.0);
        assert_eq!(AstCanonicalizer::compare_nodes(&a, &b), Ordering::Less);
        assert_eq!(AstCanonicalizer::compare_nodes(&b, &a), Ordering::Greater);
        assert_eq!(AstCanonicalizer::compare_nodes(&a, &a), Ordering::Equal);
    }

    // ===== BUG-C-M-003 回归测试:NaN 比较必须稳定 =====
    //
    // 原始 bug:`x.partial_cmp(y).unwrap_or(Ordering::Equal)` 对 NaN 返回 Equal,
    // 导致 NaN 与任何数比较都"相等",违反全序关系。
    // 修复:用 `x.total_cmp(y)` 替代,提供 IEEE 754 totalOrder 全序。
    #[test]
    fn test_compare_nodes_nan_is_consistent_total_order() {
        use std::cmp::Ordering;
        let nan = AstNode::Number(f64::NAN);
        let one = AstNode::Number(1.0);

        // total_cmp 对 NaN 提供稳定全序:NAN < 1.0(IEEE 754 totalOrder 约定)
        // 关键不变量:比较的对称性 — 若 a < b 则 b > a
        let ord_nan_to_one = AstCanonicalizer::compare_nodes(&nan, &one);
        let ord_one_to_nan = AstCanonicalizer::compare_nodes(&one, &nan);

        // 不论具体顺序,二者必须相反(不能同时 Equal,也不能同时 Less/Greater)
        assert_ne!(
            ord_nan_to_one, ord_one_to_nan,
            "NaN comparison must be asymmetric: nan vs 1 = {:?}, 1 vs nan = {:?}",
            ord_nan_to_one, ord_one_to_nan
        );

        // NaN 与自身的比较必须 Equal(自反性)
        assert_eq!(
            AstCanonicalizer::compare_nodes(&nan, &nan),
            Ordering::Equal,
            "NaN compared to itself must be Equal (reflexivity)"
        );
    }

    // ===== BUG-C-M-004 回归测试:0^0 显式处理为 1.0 =====
    //
    // 原始代码:`BinaryOp::Pow => a.powf(b)` 隐式依赖 f64::powf(0.0, 0.0) = 1.0。
    // 虽然结果正确,但意图不显式,且与 scientific.rs/statistics.rs 的显式处理不一致。
    // 修复:显式 case 处理 0^0 → 1.0(IEEE 754 约定),与所有 domain 行为一致。
    #[test]
    fn test_canonicalize_zero_pow_zero_is_one() {
        // 0^0 → 1.0(IEEE 754 约定,与 scientific.rs / statistics.rs 一致)
        let ast = AstNode::BinaryOp(
            BinaryOp::Pow,
            Box::new(AstNode::Number(0.0)),
            Box::new(AstNode::Number(0.0)),
        );
        let (canon_ast, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
        assert_eq!(canon_ast, AstNode::Number(1.0));
        assert_eq!(cf.as_str(), "1");
    }

    #[test]
    fn test_canonicalize_zero_pow_zero_negative_zero() {
        // -0.0 ^ 0.0 也应返回 1.0(IEEE 754:0^0 = 1 与符号无关)
        let ast = AstNode::BinaryOp(
            BinaryOp::Pow,
            Box::new(AstNode::Number(-0.0)),
            Box::new(AstNode::Number(0.0)),
        );
        let (canon_ast, _) = AstCanonicalizer::canonicalize(&ast).unwrap();
        assert_eq!(canon_ast, AstNode::Number(1.0));
    }

    // ===== 覆盖 canonicalize_no_fold(transform_no_fold 分支) =====

    #[test]
    fn test_no_fold_double_negation_variable() {
        // -(-x) → x(transform_no_fold 双重负号消除,lines 154-157)
        let ast = parse("-(-x)").unwrap();
        let (canon_ast, _) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
        assert_eq!(canon_ast, AstNode::Variable("x".to_string()));
    }

    #[test]
    fn test_no_fold_matrix_literal() {
        // 矩阵字面量:覆盖 transform_no_fold Matrix 分支(lines 168-177)
        let ast = parse("[[1,2],[3,4]]").unwrap();
        let (canon_ast, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
        assert_eq!(cf.as_str(), "(matrix (1 2) (3 4))");
        // 验证不折叠:矩阵元素仍为 Number
        match canon_ast {
            AstNode::Matrix(rows) => assert_eq!(rows.len(), 2),
            _ => panic!("expected matrix"),
        }
    }

    #[test]
    fn test_no_fold_list_literal() {
        // 列表字面量:覆盖 transform_no_fold List 分支(lines 179-184)
        let ast = parse("[1,2,3]").unwrap();
        let (canon_ast, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
        assert_eq!(cf.as_str(), "(list 1 2 3)");
        match canon_ast {
            AstNode::List(elems) => assert_eq!(elems.len(), 3),
            _ => panic!("expected list"),
        }
    }

    #[test]
    fn test_no_fold_preserves_constants() {
        // 2+3 → (+ 2 3)(不折叠为 5,仅排序)
        let ast = parse("3+2").unwrap();
        let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
        assert_eq!(cf.as_str(), "(+ 2 3)");
    }

    // ===== proptest 属性测试(任务 3.5) =====

    use proptest::prelude::*;

    /// 生成单字母变量名
    fn var_strategy() -> impl Strategy<Value = String> {
        (0u8..26u8).prop_map(|i| ((b'a' + i) as char).to_string())
    }

    proptest! {
        #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]

        // 交换律:a+b 与 b+a 同规范形式(使用变量避免常量折叠)
        #[test]
        fn prop_commutativity_add(a in var_strategy(), b in var_strategy()) {
            let cf1 = canon(&format!("{}+{}", a, b)).unwrap();
            let cf2 = canon(&format!("{}+{}", b, a)).unwrap();
            prop_assert_eq!(cf1, cf2);
        }

        // 交换律:a*b 与 b*a 同规范形式
        #[test]
        fn prop_commutativity_mul(a in var_strategy(), b in var_strategy()) {
            let cf1 = canon(&format!("{}*{}", a, b)).unwrap();
            let cf2 = canon(&format!("{}*{}", b, a)).unwrap();
            prop_assert_eq!(cf1, cf2);
        }

        // 结合律(常量):(a+b)+c 与 a+(b+c) 同规范形式(通过常量折叠实现)
        #[test]
        fn prop_associativity_constants(
            a in 1u32..1000, b in 1u32..1000, c in 1u32..1000
        ) {
            let cf1 = canon(&format!("({}+{})+{}", a, b, c)).unwrap();
            let cf2 = canon(&format!("{}+({}+{})", a, b, c)).unwrap();
            prop_assert_eq!(cf1, cf2);
        }

        // 幂等性:规范化已规范化的 AST 结果不变
        #[test]
        fn prop_idempotent(a in 1u32..1000, b in 1u32..1000, c in var_strategy()) {
            let expr = format!("{}*{}+{}", a, b, c);
            let ast = parse(&expr).unwrap();
            let (canon_ast, cf1) = AstCanonicalizer::canonicalize(&ast).unwrap();
            let (_, cf2) = AstCanonicalizer::canonicalize(&canon_ast).unwrap();
            prop_assert_eq!(cf1, cf2);
        }
    }

    // ===== T022: transform_inner per-variant 回归测试(Phase 7 Red)=====
    //
    // 目的:重构 transform_inner(cyc=24 → ≤15)前后行为不变。
    // 覆盖所有 AstNode variant:Leaf(Number/Variable/Complex/BigNumber)、
    // BinaryOp(Add/Sub/Mul/Div/Pow/Mod + fold + sort)、
    // UnaryOp(Neg 双重消除/Neg fold/Factorial/Abs)、
    // FunctionCall(有参/空参)、Matrix(嵌套表达式)、List(嵌套表达式)。
    // 同时覆盖 fold=true 和 fold=false 两条路径。
    #[test]
    fn test_transform_inner_per_variant() {
        // ----- 1. Leaf 节点(不变)-----
        assert_eq!(canon("42").unwrap(), "42");
        assert_eq!(canon("x").unwrap(), "x");
        assert_eq!(canon("3+4i").unwrap(), "(complex 3 4)");
        assert_eq!(canon("1234567890123456").unwrap(), "1234567890123456");

        // ----- 2. BinaryOp -----
        // 2a. Add: fold + sort(3+2 → 5)
        assert_eq!(canon("3+2").unwrap(), "5");
        // 2b. Add: sort only(y+x → (+ x y))
        assert_eq!(canon("y+x").unwrap(), "(+ x y)");
        // 2c. Sub: no sort(x-2 → (- x 2))
        assert_eq!(canon("x-2").unwrap(), "(- x 2)");
        // 2d. Mul: fold + sort(2*3 → 6)
        assert_eq!(canon("2*3").unwrap(), "6");
        // 2e. Mul: sort only(x*5 → (* 5 x))
        assert_eq!(canon("x*5").unwrap(), "(* 5 x)");
        // 2f. Div: fold(6/3 → 2)
        assert_eq!(canon("6/3").unwrap(), "2");
        // 2g. Pow: fold(2^3 → 8)
        assert_eq!(canon("2^3").unwrap(), "8");
        // 2h. Mod: fold(10%3 → 1)— 用手动 AST 避免 parser 限制
        {
            let ast = AstNode::BinaryOp(
                BinaryOp::Mod,
                Box::new(AstNode::Number(10.0)),
                Box::new(AstNode::Number(3.0)),
            );
            let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
            assert_eq!(cf.as_str(), "1");
        }
        // 2i. BinaryOp div by zero → error
        assert!(canon("1/0").is_err());

        // ----- 3. UnaryOp -----
        // 3a. Neg: double neg elimination(--x → x)
        assert_eq!(canon("-(-x)").unwrap(), "x");
        // 3b. Neg: fold(-(5) → -5)
        assert_eq!(canon("-(5)").unwrap(), "-5");
        // 3c. Neg: double neg + fold(--5 → 5)
        assert_eq!(canon("--5").unwrap(), "5");
        // 3d. Factorial: no fold(5! → (factorial 5))
        {
            let ast = AstNode::UnaryOp(UnaryOp::Factorial, Box::new(AstNode::Number(5.0)));
            let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
            assert_eq!(cf.as_str(), "(factorial 5)");
        }
        // 3e. Abs: no fold(abs(x) → (abs x))— 通过 FunctionCall 而非 UnaryOp
        //     UnaryOp::Abs 手动构造
        {
            let ast = AstNode::UnaryOp(UnaryOp::Abs, Box::new(AstNode::Variable("x".to_string())));
            let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
            assert_eq!(cf.as_str(), "(abs x)");
        }

        // ----- 4. FunctionCall -----
        // 4a. 有参函数(sin(x) → (sin x))
        assert_eq!(canon("sin(x)").unwrap(), "(sin x)");
        // 4b. 空参函数(foo() → (foo))
        {
            let ast = AstNode::FunctionCall("foo".to_string(), vec![]);
            let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
            assert_eq!(cf.as_str(), "(foo)");
        }
        // 4c. 嵌套表达式参数(sin(2+3) → (sin 5))
        assert_eq!(canon("sin(2+3)").unwrap(), "(sin 5)");

        // ----- 5. Matrix -----
        // 5a. 简单矩阵
        assert_eq!(canon("[[1,2],[3,4]]").unwrap(), "(matrix (1 2) (3 4))");
        // 5b. 嵌套表达式矩阵
        assert_eq!(canon("[[2+3, x]]").unwrap(), "(matrix (5 x))");

        // ----- 6. List -----
        // 6a. 简单列表
        assert_eq!(canon("[1,2,3]").unwrap(), "(list 1 2 3)");
        // 6b. 嵌套表达式列表
        assert_eq!(canon("[2+3, x]").unwrap(), "(list 5 x)");

        // ----- 7. fold=false 路径(canonicalize_no_fold)-----
        // 7a. 不折叠常量:3+2 → (+ 2 3)(仅排序)
        {
            let ast = parse("3+2").unwrap();
            let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
            assert_eq!(cf.as_str(), "(+ 2 3)");
        }
        // 7b. 双重负号仍消除(--x → x,结构性归一化不受 fold 影响)
        {
            let ast = parse("-(-x)").unwrap();
            let (canon_ast, _) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
            assert_eq!(canon_ast, AstNode::Variable("x".to_string()));
        }
        // 7c. 一元常量不折叠:-(5) → (- 5)(fold_unary=false)
        {
            let ast = AstNode::UnaryOp(UnaryOp::Neg, Box::new(AstNode::Number(5.0)));
            let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
            assert_eq!(cf.as_str(), "(- 5)");
        }
        // 7d. Matrix/List 在 no_fold 下仍递归变换
        {
            let ast = parse("[[1,2],[3,4]]").unwrap();
            let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
            assert_eq!(cf.as_str(), "(matrix (1 2) (3 4))");
        }
    }
}