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
// Copyright (c) 2026 Kirky.X. Licensed under the MIT License.

//! LaTeX 输出格式化器(v1.1 新增)。
//!
//! 将 `EvalResult` 渲染为 LaTeX 字符串,覆盖所有变体:
//! - 标量 → `42` 或 `3.14`
//! - 复数 → `3 + 4i`
//! - 矩阵 → `\begin{pmatrix}1 & 2 \\ 3 & 4\end{pmatrix}`
//! - 向量 → `\left[1, 2, 3\right]`
//! - 多项式 → `x^{2} + 2x + 1`
//! - BigInt → 数字字符串
//! - BigRational → `\frac{p}{q}`
//! - 复根列表 → `\left[1 + 2i, 3 + 4i\right]`
//! - 符号运算 → `\frac{d}{dx}\left(...\right) = result` 等
//!
//! 设计依据:
//! - PRD §3.2.4 / §4.1.1:`--latex "diff(x^2,x)"` → `\frac{d}{dx}\left(x^{2}\right) = 2x`
//! - ADD §3.4:`CalcResult::LaTeX(String)` 变体
//! - design.md D3:LaTeX 由 SymbolicDomain 直接产出(domain 拥有 AST 上下文)

use crate::core::{AstNode, EvalResult};
use num_traits::Signed;

/// 格式化标量为 LaTeX。
///
/// - NaN/Inf 渲染为 `\text{NaN}` / `\infty` / `-\infty`
/// - 整数值(在 i64 安全范围内)渲染为整数(`42`)
/// - 大整数(超出 i64 范围)渲染为不带小数点的数字串(`100000000000000000000`),
///   避免触发科学计数法
/// - 浮点数渲染为最简小数(`3.14`),并消除浮点精度噪声
///   (如 `0.1+0.2=0.30000000000000004` → `0.3`)
pub fn format_latex_scalar(v: f64) -> String {
    if v.is_nan() {
        return "\\text{NaN}".to_string();
    }
    if v.is_infinite() {
        return if v > 0.0 {
            "\\infty".to_string()
        } else {
            "-\\infty".to_string()
        };
    }
    if v.fract() == 0.0 {
        // Integer value: render without decimal point
        if v.abs() < 9e15 {
            return format!("{}", v as i64);
        }
        // Large integer outside i64 safe range: {:.0} avoids scientific notation
        return format!("{:.0}", v);
    }
    let default = format!("{}", v);
    if has_floating_point_noise(&default) {
        let rounded = format!("{:.10}", v);
        let trimmed = rounded.trim_end_matches('0').trim_end_matches('.');
        if !trimmed.is_empty() && trimmed != "-" {
            return trimmed.to_string();
        }
    }
    default
}

/// 检测浮点精度噪声:连续 7 个 0 或 9 表示二进制浮点误差。
fn has_floating_point_noise(s: &str) -> bool {
    s.contains("0000000") || s.contains("9999999")
}

/// 格式化复数为 LaTeX。
///
/// 简化规则(避免冗余的 `0 + 0i` 或 `1i` 形式):
/// - 虚部为 0 → 仅实部(`3`)
/// - 实部为 0 → 仅虚部(`4i`),虚部为 ±1 时进一步简化为 `i` / `-i`
/// - 一般形式 → `re + im i` 或 `re - im i`(虚部为 ±1 时简化为 `re + i` / `re - i`)
pub fn format_latex_complex(re: f64, im: f64) -> String {
    // Case 1: imaginary part is zero → just real part
    if im == 0.0 {
        return format_latex_scalar(re);
    }
    // Case 2: real part is zero → just imaginary part
    if re == 0.0 {
        if im == 1.0 {
            return "i".to_string();
        }
        if im == -1.0 {
            return "-i".to_string();
        }
        return format!("{}i", format_latex_scalar(im));
    }
    // Case 3: general form re ± im i
    let re_s = format_latex_scalar(re);
    if im == 1.0 {
        format!("{} + i", re_s)
    } else if im == -1.0 {
        format!("{} - i", re_s)
    } else if im > 0.0 {
        format!("{} + {}i", re_s, format_latex_scalar(im))
    } else {
        format!("{} - {}i", re_s, format_latex_scalar(-im))
    }
}

/// 格式化矩阵为 LaTeX `\begin{pmatrix}...\end{pmatrix}`。
///
/// 行内元素以 ` & ` 分隔,行间以 ` \\ ` 分隔。
pub fn format_latex_matrix(m: &[Vec<f64>]) -> String {
    let rows: Vec<String> = m
        .iter()
        .map(|row| {
            let elems: Vec<String> = row.iter().map(|v| format_latex_scalar(*v)).collect();
            elems.join(" & ")
        })
        .collect();
    format!("\\begin{{pmatrix}}{}\\end{{pmatrix}}", rows.join(" \\\\ "))
}

/// 格式化向量为 LaTeX `\left[a, b, c\right]`。
pub fn format_latex_vector(v: &[f64]) -> String {
    let elems: Vec<String> = v.iter().map(|x| format_latex_scalar(*x)).collect();
    format!("\\left[{}\\right]", elems.join(", "))
}

/// 格式化多项式系数向量(升幂存储)为 LaTeX 降幂字符串 `a x^{2} + b x + c`。
pub fn format_latex_polynomial(p: &[f64]) -> String {
    if p.is_empty() {
        return "0".to_string();
    }
    let terms: Vec<String> = p
        .iter()
        .enumerate()
        .rev()
        .filter_map(|(i, &coef)| format_latex_polynomial_term(coef, i))
        .collect();
    if terms.is_empty() {
        return "0".to_string();
    }
    join_latex_polynomial_terms(&terms)
}

/// 格式化 LaTeX 多项式单项:零系数返回 None(跳过),其他返回 `Some(term)`。
fn format_latex_polynomial_term(coef: f64, i: usize) -> Option<String> {
    if coef == 0.0 {
        return None;
    }
    let term = match i {
        0 => format_latex_scalar(coef),
        1 => {
            if coef == 1.0 {
                "x".to_string()
            } else if coef == -1.0 {
                "-x".to_string()
            } else {
                format!("{}x", format_latex_scalar(coef))
            }
        }
        _ => {
            if coef == 1.0 {
                format!("x^{{{}}}", i)
            } else if coef == -1.0 {
                format!("-x^{{{}}}", i)
            } else {
                format!("{}x^{{{}}}", format_latex_scalar(coef), i)
            }
        }
    };
    Some(term)
}

/// 合并 LaTeX 多项式单项列表。
///
/// 第一项原样输出(即使以 `-` 开头),后续项:
/// - 正项用 ` + ` 分隔
/// - 负项用 ` - ` 分隔并去除其前导 `-`(与正项对称,避免 `x^{2}-2x` 的紧凑形式)
fn join_latex_polynomial_terms(terms: &[String]) -> String {
    let mut result = terms[0].clone();
    for term in &terms[1..] {
        if let Some(stripped) = term.strip_prefix('-') {
            result.push_str(" - ");
            result.push_str(stripped);
        } else {
            result.push_str(" + ");
            result.push_str(term);
        }
    }
    result
}

/// 格式化 BigInt 为 LaTeX 数字字符串(直接 `to_string()`,无需特殊转义)。
pub fn format_latex_bigint(b: &num_bigint::BigInt) -> String {
    b.to_string()
}

/// 格式化 BigRational 为 LaTeX `\frac{p}{q}`。
///
/// `fmt_prec` 为 `Some(n)` 时格式化为 `n` 位小数(`p.q...`)。
pub fn format_latex_bigrational(r: &num_rational::BigRational, fmt_prec: Option<usize>) -> String {
    if let Some(prec) = fmt_prec {
        let neg = r.is_negative();
        let abs = r.abs();
        let numer = abs.numer();
        let denom = abs.denom();
        // 整数部分
        let int_part = numer / denom;
        let remainder = numer % denom;
        // 小数部分:remainder * 10^prec / denom
        let mut scale = num_bigint::BigInt::from(1);
        let ten = num_bigint::BigInt::from(10);
        for _ in 0..prec {
            scale *= &ten;
        }
        let scaled = remainder * &scale;
        let frac_digits = scaled / denom;
        let int_str = int_part.to_string();
        let frac_str = format!("{:0>width$}", frac_digits.to_string(), width = prec);
        let sign = if neg { "-" } else { "" };
        if prec == 0 {
            format!("{}{}", sign, int_str)
        } else {
            format!("{}{}.{}", sign, int_str, frac_str)
        }
    } else {
        format!("\\frac{{{}}}{{{}}}", r.numer(), r.denom())
    }
}

/// 格式化复根列表为 LaTeX `\left[a + bi, c + di\right]`。
pub fn format_latex_complex_list(c: &[(f64, f64)]) -> String {
    let elems: Vec<String> = c
        .iter()
        .map(|(re, im)| format_latex_complex(*re, *im))
        .collect();
    format!("\\left[{}\\right]", elems.join(", "))
}

/// 格式化符号运算结果为 LaTeX。
///
/// 根据 `op_name` 选择合适的 LaTeX 包装:
/// - `diff(f, x)` → `\frac{d}{dx}\left(f\right) = result`
/// - `integrate(f, x)` → `\int f \, dx = result`
/// - `limit(f, x, a)` → `\lim_{x \to a} f = result`
/// - `series(f, x, a, n)` → `\sum_{k=0}^{n} \frac{f^{(k)}(a)}{k!}(x-a)^k`
/// - `taylor(f, x, a, n)` → 同 series
///
/// `result_str` 为已求值的符号结果字符串(如 `2*x`)。在 LaTeX 中乘号需转义为 `\cdot`。
pub fn format_latex_symbolic(op_name: &str, ast: &AstNode, result_str: &str) -> String {
    let result_latex = symbolic_str_to_latex(result_str);
    let args = match ast {
        AstNode::FunctionCall(_, args) => args,
        _ => return result_latex,
    };
    match op_name {
        "diff" => {
            let var = args
                .get(1)
                .and_then(ast_to_latex_expr)
                .unwrap_or_else(|| "x".to_string());
            let body = args
                .first()
                .and_then(ast_to_latex_expr)
                .unwrap_or_else(|| result_latex.clone());
            format!(
                "\\frac{{d}}{{d{var}}}\\left({body}\\right) = {result_latex}",
                var = var,
                body = body,
                result_latex = result_latex
            )
        }
        "integrate" => {
            let var = args
                .get(1)
                .and_then(ast_to_latex_expr)
                .unwrap_or_else(|| "x".to_string());
            let body = args
                .first()
                .and_then(ast_to_latex_expr)
                .unwrap_or_else(|| "".to_string());
            format!(
                "\\int {body} \\, d{var} = {result_latex}",
                body = body,
                var = var,
                result_latex = result_latex
            )
        }
        "limit" => {
            let var = args
                .get(1)
                .and_then(ast_to_latex_expr)
                .unwrap_or_else(|| "x".to_string());
            let point = args
                .get(2)
                .and_then(ast_to_latex_expr)
                .unwrap_or_else(|| "0".to_string());
            let body = args
                .first()
                .and_then(ast_to_latex_expr)
                .unwrap_or_else(|| "".to_string());
            format!(
                "\\lim_{{{var} \\to {point}}} {body} = {result_latex}",
                var = var,
                point = point,
                body = body,
                result_latex = result_latex
            )
        }
        "series" | "taylor" => {
            let body = args
                .first()
                .and_then(ast_to_latex_expr)
                .unwrap_or_else(|| "".to_string());
            format!(
                "\\text{{Taylor series of}} {body} = {result_latex}",
                body = body,
                result_latex = result_latex
            )
        }
        _ => result_latex,
    }
}

/// 将 `AstNode` 表达式转换为 LaTeX 字符串(仅支持常见运算符)。
fn ast_to_latex_expr(node: &AstNode) -> Option<String> {
    match node {
        AstNode::Number(n) => Some(format_latex_scalar(*n)),
        AstNode::BigNumber(s) => Some(s.clone()),
        AstNode::Variable(name) => Some(name.clone()),
        AstNode::BinaryOp(op, lhs, rhs) => {
            let l = ast_to_latex_expr(lhs)?;
            let r = ast_to_latex_expr(rhs)?;
            let op_str = match op {
                crate::core::BinaryOp::Add => format!("{} + {}", l, r),
                crate::core::BinaryOp::Sub => format!("{} - {}", l, r),
                crate::core::BinaryOp::Mul => format!("{} \\cdot {}", l, r),
                crate::core::BinaryOp::Div => format!("\\frac{{{}}}{{{}}}", l, r),
                crate::core::BinaryOp::Pow => format!("{}^{{{}}}", l, r),
                crate::core::BinaryOp::Mod => format!("{} \\bmod {}", l, r),
            };
            Some(op_str)
        }
        AstNode::UnaryOp(op, expr) => {
            let e = ast_to_latex_expr(expr)?;
            Some(match op {
                crate::core::UnaryOp::Neg => format!("-{}", e),
                crate::core::UnaryOp::Factorial => format!("{}!", e),
                crate::core::UnaryOp::Abs => format!("\\left|{}\\right|", e),
            })
        }
        AstNode::FunctionCall(name, args) => {
            let args_latex: Vec<String> = args.iter().filter_map(ast_to_latex_expr).collect();
            Some(format!("{}({})", name, args_latex.join(", ")))
        }
        _ => None,
    }
}

/// 将符号结果字符串(如 `2*x` 或 `x^2`)转换为 LaTeX(`2 \cdot x`、`x^{2}`)。
///
/// 替换规则:
/// - `*` → ` \cdot `(LaTeX 乘号)
/// - `^N` → `^{N}`(N 为整数指数,可能带前导 `-`;LaTeX 要求指数用花括号包裹)
/// - 其他字符原样保留
fn symbolic_str_to_latex(s: &str) -> String {
    let chars: Vec<char> = s.chars().collect();
    let mut result = String::with_capacity(s.len() * 2);
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        match c {
            '*' => {
                result.push_str(" \\cdot ");
                i += 1;
            }
            '^' => {
                result.push_str("^{");
                i += 1;
                // Capture optional negative sign for exponent
                if i < chars.len() && chars[i] == '-' {
                    result.push('-');
                    i += 1;
                }
                // Capture digit sequence as exponent
                while i < chars.len() && chars[i].is_ascii_digit() {
                    result.push(chars[i]);
                    i += 1;
                }
                result.push('}');
            }
            _ => {
                result.push(c);
                i += 1;
            }
        }
    }
    result
}

/// 顶层 LaTeX 格式化器:根据 `EvalResult` 变体分发到具体格式化函数。
///
/// `ast` 用于符号运算的包装(`\frac{d}{dx}\left(...\right)`)。
/// `expr` 为原始表达式字符串,用于回退显示。
/// `fmt_prec` 为 `Some(n)` 时用于 BigRational 的 `n` 位小数格式化。
pub fn format_latex(
    result: &EvalResult,
    ast: &AstNode,
    _expr: &str,
    fmt_prec: Option<usize>,
) -> String {
    match result {
        EvalResult::Scalar(v) => format_latex_scalar(*v),
        EvalResult::Complex(re, im) => format_latex_complex(*re, *im),
        EvalResult::Matrix(m) => format_latex_matrix(m),
        EvalResult::BigInt(b) => format_latex_bigint(b),
        EvalResult::BigRational(r) => format_latex_bigrational(r, fmt_prec),
        EvalResult::Vector(v) => format_latex_vector(v),
        EvalResult::Polynomial(p) => format_latex_polynomial(p),
        EvalResult::ComplexList(c) => format_latex_complex_list(c),
        EvalResult::Symbolic(s) => {
            // 符号运算:根据 AST 顶层 FunctionCall 名选择包装
            if let AstNode::FunctionCall(name, _) = ast {
                if matches!(
                    name.as_str(),
                    "diff" | "integrate" | "limit" | "series" | "taylor"
                ) {
                    return format_latex_symbolic(name, ast, s);
                }
            }
            symbolic_str_to_latex(s)
        }
        EvalResult::LaTeX(s) => s.clone(),
        EvalResult::Steps(v) => v.join(" \\to "),
        // Json 是结构化复合结果(lu/qr/eig/svd 分解),LaTeX 无标准矩阵分解表示形式;
        // 主要走 --json 输出,此处 fallback 输出 JSON 字符串。
        EvalResult::Json(v) => v.to_string(),
        // DateTime(time-unit-fx-domains D2):RFC3339 字符串用 \text{} 包装,
        // 避免 LaTeX 数学模式将日期/时间中的 `-`、`:` 解释为减法/除法。
        EvalResult::DateTime(s) => format!("\\text{{{}}}", s),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{BinaryOp, UnaryOp};

    #[test]
    fn latex_scalar_integer() {
        assert_eq!(format_latex_scalar(42.0), "42");
        assert_eq!(format_latex_scalar(-7.0), "-7");
    }

    #[test]
    fn latex_scalar_decimal() {
        assert_eq!(format_latex_scalar(3.14), "3.14");
    }

    #[test]
    fn latex_scalar_nan_inf() {
        assert_eq!(format_latex_scalar(f64::NAN), "\\text{NaN}");
        assert_eq!(format_latex_scalar(f64::INFINITY), "\\infty");
        assert_eq!(format_latex_scalar(f64::NEG_INFINITY), "-\\infty");
    }

    #[test]
    fn latex_complex_positive_im() {
        assert_eq!(format_latex_complex(3.0, 4.0), "3 + 4i");
    }

    #[test]
    fn latex_complex_negative_im() {
        assert_eq!(format_latex_complex(3.0, -4.0), "3 - 4i");
    }

    #[test]
    fn latex_matrix_2x2() {
        let m = vec![vec![1.0, 2.0], vec![3.0, 4.0]];
        assert_eq!(
            format_latex_matrix(&m),
            "\\begin{pmatrix}1 & 2 \\\\ 3 & 4\\end{pmatrix}"
        );
    }

    #[test]
    fn latex_vector() {
        assert_eq!(
            format_latex_vector(&[1.0, 2.0, 3.0]),
            "\\left[1, 2, 3\\right]"
        );
    }

    #[test]
    fn latex_polynomial_simple() {
        assert_eq!(format_latex_polynomial(&[1.0, 2.0, 1.0]), "x^{2} + 2x + 1");
    }

    #[test]
    fn latex_polynomial_negative_coef() {
        // [1, -1] → -x + 1
        assert_eq!(format_latex_polynomial(&[1.0, -1.0]), "-x + 1");
    }

    #[test]
    fn latex_polynomial_zero() {
        assert_eq!(format_latex_polynomial(&[]), "0");
        assert_eq!(format_latex_polynomial(&[0.0, 0.0]), "0");
    }

    #[test]
    fn latex_bigint() {
        let b = num_bigint::BigInt::from(123456789);
        assert_eq!(format_latex_bigint(&b), "123456789");
    }

    #[test]
    fn latex_bigrational_fraction() {
        let r = num_rational::BigRational::new(
            num_bigint::BigInt::from(1),
            num_bigint::BigInt::from(3),
        );
        assert_eq!(format_latex_bigrational(&r, None), "\\frac{1}{3}");
    }

    #[test]
    fn latex_bigrational_decimal() {
        let r = num_rational::BigRational::new(
            num_bigint::BigInt::from(1),
            num_bigint::BigInt::from(2),
        );
        assert_eq!(format_latex_bigrational(&r, Some(3)), "0.500");
    }

    #[test]
    fn latex_complex_list() {
        let c = vec![(1.0, 2.0), (3.0, -4.0)];
        assert_eq!(
            format_latex_complex_list(&c),
            "\\left[1 + 2i, 3 - 4i\\right]"
        );
    }

    #[test]
    fn latex_symbolic_diff() {
        let ast = AstNode::FunctionCall(
            "diff".to_string(),
            vec![
                AstNode::BinaryOp(
                    BinaryOp::Pow,
                    Box::new(AstNode::Variable("x".to_string())),
                    Box::new(AstNode::Number(2.0)),
                ),
                AstNode::Variable("x".to_string()),
            ],
        );
        let s = format_latex_symbolic("diff", &ast, "2*x");
        assert_eq!(s, "\\frac{d}{dx}\\left(x^{2}\\right) = 2 \\cdot x");
    }

    #[test]
    fn latex_symbolic_integrate() {
        let ast = AstNode::FunctionCall(
            "integrate".to_string(),
            vec![
                AstNode::Variable("x".to_string()),
                AstNode::Variable("x".to_string()),
            ],
        );
        let s = format_latex_symbolic("integrate", &ast, "x^2/2");
        assert!(s.contains("\\int"));
        assert!(s.contains("\\, dx"));
    }

    #[test]
    fn latex_symbolic_limit() {
        let ast = AstNode::FunctionCall(
            "limit".to_string(),
            vec![
                AstNode::Variable("x".to_string()),
                AstNode::Variable("x".to_string()),
                AstNode::Number(0.0),
            ],
        );
        let s = format_latex_symbolic("limit", &ast, "1");
        assert!(s.contains("\\lim_{x \\to 0}"));
    }

    #[test]
    fn latex_top_level_scalar() {
        let r = EvalResult::Scalar(5.0);
        let ast = AstNode::Number(5.0);
        assert_eq!(format_latex(&r, &ast, "2+3", None), "5");
    }

    #[test]
    fn latex_top_level_matrix() {
        let r = EvalResult::Matrix(vec![vec![1.0, 2.0], vec![3.0, 4.0]]);
        let ast = AstNode::Number(0.0); // 占位
        assert_eq!(
            format_latex(&r, &ast, "[[1,2],[3,4]]", None),
            "\\begin{pmatrix}1 & 2 \\\\ 3 & 4\\end{pmatrix}"
        );
    }

    #[test]
    fn latex_top_level_symbolic_diff() {
        let r = EvalResult::Symbolic("2*x".to_string());
        let ast = AstNode::FunctionCall(
            "diff".to_string(),
            vec![
                AstNode::BinaryOp(
                    BinaryOp::Pow,
                    Box::new(AstNode::Variable("x".to_string())),
                    Box::new(AstNode::Number(2.0)),
                ),
                AstNode::Variable("x".to_string()),
            ],
        );
        let s = format_latex(&r, &ast, "diff(x^2,x)", None);
        assert_eq!(s, "\\frac{d}{dx}\\left(x^{2}\\right) = 2 \\cdot x");
    }

    #[test]
    fn latex_top_level_latex_passthrough() {
        let r = EvalResult::LaTeX("\\alpha".to_string());
        let ast = AstNode::Number(0.0);
        assert_eq!(format_latex(&r, &ast, "", None), "\\alpha");
    }

    #[test]
    fn latex_top_level_steps_join() {
        let r = EvalResult::Steps(vec!["2+9=11".to_string(), "11*7=77".to_string()]);
        let ast = AstNode::Number(0.0);
        assert_eq!(format_latex(&r, &ast, "", None), "2+9=11 \\to 11*7=77");
    }

    #[test]
    fn latex_symbolic_str_to_latex_multiplies() {
        assert_eq!(symbolic_str_to_latex("2*x*y"), "2 \\cdot x \\cdot y");
    }

    #[test]
    fn latex_ast_to_latex_expr_pow() {
        let node = AstNode::BinaryOp(
            BinaryOp::Pow,
            Box::new(AstNode::Variable("x".to_string())),
            Box::new(AstNode::Number(2.0)),
        );
        assert_eq!(ast_to_latex_expr(&node), Some("x^{2}".to_string()));
    }

    #[test]
    fn latex_ast_to_latex_expr_div() {
        let node = AstNode::BinaryOp(
            BinaryOp::Div,
            Box::new(AstNode::Number(1.0)),
            Box::new(AstNode::Number(2.0)),
        );
        assert_eq!(ast_to_latex_expr(&node), Some("\\frac{1}{2}".to_string()));
    }

    #[test]
    fn latex_ast_to_latex_expr_unary_neg() {
        let node = AstNode::UnaryOp(UnaryOp::Neg, Box::new(AstNode::Variable("x".to_string())));
        assert_eq!(ast_to_latex_expr(&node), Some("-x".to_string()));
    }

    #[test]
    fn latex_ast_to_latex_expr_factorial() {
        let node = AstNode::UnaryOp(UnaryOp::Factorial, Box::new(AstNode::Number(5.0)));
        assert_eq!(ast_to_latex_expr(&node), Some("5!".to_string()));
    }

    // ===== 覆盖 format_latex_polynomial 各分支 =====

    #[test]
    fn latex_polynomial_leading_coef_one_x() {
        // i==1, coef==1.0 → "x"(line 89)
        assert_eq!(format_latex_polynomial(&[5.0, 1.0]), "x + 5");
    }

    #[test]
    fn latex_polynomial_high_degree_neg_one_coef() {
        // i>1, coef==-1.0 → "-x^{i}"(lines 99-100)
        assert_eq!(format_latex_polynomial(&[0.0, 0.0, -1.0]), "-x^{2}");
    }

    #[test]
    fn latex_polynomial_high_degree_general_coef() {
        // i>1, coef 非 ±1.0 → "cx^{i}"(line 102)
        assert_eq!(format_latex_polynomial(&[0.0, 0.0, 3.0]), "3x^{2}");
    }

    #[test]
    fn latex_polynomial_negative_term_concatenation() {
        // BUG-O-M-011 修复后:非首项以 '-' 开头时用 " - " 分隔(与 " + " 对称)
        // [1, -2, 1] → "x^{2} - 2x + 1"
        assert_eq!(format_latex_polynomial(&[1.0, -2.0, 1.0]), "x^{2} - 2x + 1");
    }

    // ===== 覆盖 format_latex_bigrational prec==0 分支 =====

    #[test]
    fn latex_bigrational_zero_precision() {
        // prec==0 → 仅整数部分(line 152)
        let r = num_rational::BigRational::new(
            num_bigint::BigInt::from(7),
            num_bigint::BigInt::from(2),
        );
        assert_eq!(format_latex_bigrational(&r, Some(0)), "3");
    }

    // ===== 覆盖 format_latex_symbolic 非 FunctionCall 与 series/taylor/unknown =====

    #[test]
    fn latex_symbolic_non_functioncall_ast() {
        // ast 非 FunctionCall → 直接返回 result_latex(line 184)
        let ast = AstNode::Number(0.0);
        let s = format_latex_symbolic("diff", &ast, "2*x");
        assert_eq!(s, "2 \\cdot x");
    }

    #[test]
    fn latex_symbolic_series_branch() {
        // series/taylor 分支(lines 240-245)
        let ast = AstNode::FunctionCall(
            "series".to_string(),
            vec![AstNode::Variable("x".to_string())],
        );
        let s = format_latex_symbolic("series", &ast, "1+x+x^2");
        assert!(s.contains("\\text{Taylor series of}"));
        assert!(s.contains("x"));
    }

    #[test]
    fn latex_symbolic_taylor_branch() {
        // taylor 分支(lines 240-245)
        let ast = AstNode::FunctionCall(
            "taylor".to_string(),
            vec![AstNode::Variable("x".to_string())],
        );
        let s = format_latex_symbolic("taylor", &ast, "1+x");
        assert!(s.contains("\\text{Taylor series of}"));
    }

    #[test]
    fn latex_symbolic_unknown_op() {
        // 未知 op_name → 返回 result_latex(line 251)
        let ast = AstNode::FunctionCall(
            "unknown".to_string(),
            vec![AstNode::Variable("x".to_string())],
        );
        let s = format_latex_symbolic("unknown", &ast, "42");
        assert_eq!(s, "42");
    }

    // ===== 覆盖 ast_to_latex_expr 各分支 =====

    #[test]
    fn latex_ast_to_latex_expr_bignumber() {
        // BigNumber → 原始字符串(line 259)
        let node = AstNode::BigNumber("1234567890123456".to_string());
        assert_eq!(
            ast_to_latex_expr(&node),
            Some("1234567890123456".to_string())
        );
    }

    #[test]
    fn latex_ast_to_latex_expr_add_sub_mul_mod() {
        // Add/Sub/Mul/Mod 分支(lines 265-267, 270)
        let add = AstNode::BinaryOp(
            BinaryOp::Add,
            Box::new(AstNode::Variable("a".to_string())),
            Box::new(AstNode::Variable("b".to_string())),
        );
        assert_eq!(ast_to_latex_expr(&add), Some("a + b".to_string()));

        let sub = AstNode::BinaryOp(
            BinaryOp::Sub,
            Box::new(AstNode::Variable("a".to_string())),
            Box::new(AstNode::Variable("b".to_string())),
        );
        assert_eq!(ast_to_latex_expr(&sub), Some("a - b".to_string()));

        let mul = AstNode::BinaryOp(
            BinaryOp::Mul,
            Box::new(AstNode::Variable("a".to_string())),
            Box::new(AstNode::Variable("b".to_string())),
        );
        assert_eq!(ast_to_latex_expr(&mul), Some("a \\cdot b".to_string()));

        let modulo = AstNode::BinaryOp(
            BinaryOp::Mod,
            Box::new(AstNode::Variable("a".to_string())),
            Box::new(AstNode::Variable("b".to_string())),
        );
        assert_eq!(ast_to_latex_expr(&modulo), Some("a \\bmod b".to_string()));
    }

    #[test]
    fn latex_ast_to_latex_expr_abs() {
        // UnaryOp::Abs → \left|...\right|(line 279)
        let node = AstNode::UnaryOp(UnaryOp::Abs, Box::new(AstNode::Variable("x".to_string())));
        assert_eq!(
            ast_to_latex_expr(&node),
            Some("\\left|x\\right|".to_string())
        );
    }

    #[test]
    fn latex_ast_to_latex_expr_function_call() {
        // FunctionCall → name(args)(lines 282-284)
        let node = AstNode::FunctionCall(
            "sin".to_string(),
            vec![AstNode::Number(0.0), AstNode::Variable("x".to_string())],
        );
        assert_eq!(ast_to_latex_expr(&node), Some("sin(0, x)".to_string()));
    }

    #[test]
    fn latex_ast_to_latex_expr_unsupported_returns_none() {
        // 不支持的节点类型 → None(line 286)
        let node = AstNode::Complex(1.0, 2.0);
        assert_eq!(ast_to_latex_expr(&node), None);

        let node = AstNode::Matrix(vec![vec![AstNode::Number(1.0)]]);
        assert_eq!(ast_to_latex_expr(&node), None);

        let node = AstNode::List(vec![AstNode::Number(1.0)]);
        assert_eq!(ast_to_latex_expr(&node), None);
    }

    // ===== 覆盖 format_latex 顶层分发各变体 =====

    #[test]
    fn latex_top_level_complex() {
        // Complex 变体(line 310)
        let r = EvalResult::Complex(3.0, 4.0);
        let ast = AstNode::Number(0.0);
        assert_eq!(format_latex(&r, &ast, "", None), "3 + 4i");
    }

    #[test]
    fn latex_top_level_bigint() {
        // BigInt 变体(line 312)
        let r = EvalResult::BigInt(num_bigint::BigInt::from(42));
        let ast = AstNode::Number(0.0);
        assert_eq!(format_latex(&r, &ast, "", None), "42");
    }

    #[test]
    fn latex_top_level_bigrational() {
        // BigRational 变体(line 313)
        let r = EvalResult::BigRational(num_rational::BigRational::new(
            num_bigint::BigInt::from(1),
            num_bigint::BigInt::from(3),
        ));
        let ast = AstNode::Number(0.0);
        assert_eq!(format_latex(&r, &ast, "", None), "\\frac{1}{3}");
    }

    #[test]
    fn latex_top_level_vector() {
        // Vector 变体(line 314)
        let r = EvalResult::Vector(vec![1.0, 2.0, 3.0]);
        let ast = AstNode::Number(0.0);
        assert_eq!(format_latex(&r, &ast, "", None), "\\left[1, 2, 3\\right]");
    }

    #[test]
    fn latex_top_level_polynomial() {
        // Polynomial 变体(line 315)
        let r = EvalResult::Polynomial(vec![1.0, 2.0, 1.0]);
        let ast = AstNode::Number(0.0);
        assert_eq!(format_latex(&r, &ast, "", None), "x^{2} + 2x + 1");
    }

    #[test]
    fn latex_top_level_complex_list() {
        // ComplexList 变体(line 316)
        let r = EvalResult::ComplexList(vec![(1.0, 2.0), (3.0, -4.0)]);
        let ast = AstNode::Number(0.0);
        assert_eq!(
            format_latex(&r, &ast, "", None),
            "\\left[1 + 2i, 3 - 4i\\right]"
        );
    }

    // ===== 覆盖 Symbolic fallthrough 路径 =====

    #[test]
    fn latex_top_level_symbolic_non_matching_function() {
        // Symbolic 变体,ast 为 FunctionCall 但 name 不在白名单(lines 325-327)
        let r = EvalResult::Symbolic("2*x".to_string());
        let ast = AstNode::FunctionCall("foo".to_string(), vec![]);
        assert_eq!(format_latex(&r, &ast, "", None), "2 \\cdot x");
    }

    #[test]
    fn latex_top_level_symbolic_non_function() {
        // Symbolic 变体,ast 非 FunctionCall(line 327)
        let r = EvalResult::Symbolic("2*x".to_string());
        let ast = AstNode::Number(0.0);
        assert_eq!(format_latex(&r, &ast, "", None), "2 \\cdot x");
    }

    // ===== BUG-O-M-007: format_latex_scalar 浮点精度噪声 =====

    #[test]
    fn latex_scalar_floating_point_noise() {
        // BUG-O-M-007: 0.1+0.2 = 0.30000000000000004,应显示为 0.3
        assert_eq!(format_latex_scalar(0.1 + 0.2), "0.3");
    }

    #[test]
    fn latex_scalar_preserves_precision_for_irreducible() {
        // 确保修复不破坏完整精度表示
        assert_eq!(format_latex_scalar(1.0 / 3.0), "0.3333333333333333");
        assert_eq!(
            format_latex_scalar(std::f64::consts::PI),
            "3.141592653589793"
        );
    }

    // ===== BUG-O-M-008: format_latex_scalar 大整数科学计数法 =====

    #[test]
    fn latex_scalar_large_integer_no_scientific() {
        // BUG-O-M-008: 大整数不应输出科学计数法
        assert_eq!(format_latex_scalar(1e15), "1000000000000000");
        assert_eq!(format_latex_scalar(1e20), "100000000000000000000");
        assert_eq!(format_latex_scalar(1e21), "1000000000000000000000");
    }

    // ===== BUG-O-M-009 / M-010: format_latex_complex 简化 =====

    #[test]
    fn latex_complex_zero_imaginary_simplified() {
        // BUG-O-M-009: 虚部为 0 时应简化为实部(不输出 "+ 0i")
        assert_eq!(format_latex_complex(3.0, 0.0), "3");
        assert_eq!(format_latex_complex(-3.0, 0.0), "-3");
    }

    #[test]
    fn latex_complex_zero_real_simplified() {
        // BUG-O-M-010: 实部为 0 时应简化为虚部(不输出 "0 + 4i")
        assert_eq!(format_latex_complex(0.0, 4.0), "4i");
        assert_eq!(format_latex_complex(0.0, -4.0), "-4i");
    }

    #[test]
    fn latex_complex_both_zero_simplified() {
        // 边界:实部和虚部都为 0 → "0"
        assert_eq!(format_latex_complex(0.0, 0.0), "0");
    }

    #[test]
    fn latex_complex_one_imaginary_simplified() {
        // 边界:虚部为 ±1 时不输出系数("i" 而非 "1i")
        assert_eq!(format_latex_complex(2.0, 1.0), "2 + i");
        assert_eq!(format_latex_complex(2.0, -1.0), "2 - i");
        assert_eq!(format_latex_complex(0.0, 1.0), "i");
        assert_eq!(format_latex_complex(0.0, -1.0), "-i");
    }

    #[test]
    fn latex_complex_general_form_preserved() {
        // 确保修复不破坏一般形式
        assert_eq!(format_latex_complex(3.0, 4.0), "3 + 4i");
        assert_eq!(format_latex_complex(3.0, -4.0), "3 - 4i");
    }

    // ===== BUG-O-M-011: join_latex_polynomial_terms 负项空格 =====

    #[test]
    fn latex_polynomial_negative_terms_with_spaces() {
        // BUG-O-M-011: 负项应统一用 " - " 分隔(与正项 " + " 对称)
        // [1, -2, 1] → "x^{2} - 2x + 1"(不是 "x^{2}-2x + 1")
        assert_eq!(format_latex_polynomial(&[1.0, -2.0, 1.0]), "x^{2} - 2x + 1");
        // [-1, 2] → "2x - 1"
        assert_eq!(format_latex_polynomial(&[-1.0, 2.0]), "2x - 1");
    }

    // ===== BUG-O-M-012: symbolic_str_to_latex 幂运算 =====

    #[test]
    fn latex_symbolic_str_to_latex_pow() {
        // BUG-O-M-012: "x^2" 应转换为 "x^{2}"(LaTeX 规范)
        assert_eq!(symbolic_str_to_latex("x^2"), "x^{2}");
        assert_eq!(symbolic_str_to_latex("x^10"), "x^{10}");
    }

    #[test]
    fn latex_symbolic_str_to_latex_combined_ops() {
        // 综合测试:乘法和幂混合
        assert_eq!(symbolic_str_to_latex("2*x^2"), "2 \\cdot x^{2}");
        assert_eq!(symbolic_str_to_latex("x^2*y"), "x^{2} \\cdot y");
    }

    #[test]
    fn latex_symbolic_str_to_latex_preserves_plain() {
        // 确保修复不破坏无幂运算的字符串
        assert_eq!(symbolic_str_to_latex("2*x"), "2 \\cdot x");
        assert_eq!(symbolic_str_to_latex("42"), "42");
    }
}