calnexus 0.1.0

A command-line math expression evaluator with 11 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
// Copyright (c) 2026 Kirky.X. Licensed under the MIT License.

//! Scientific 计算域:三角函数、反三角函数、对数、指数、双曲函数、特殊函数。
//!
//! 设计依据:
//! - scientific-domain spec:10 个 requirements / 31 个 scenarios
//! - design.md D4:实现 `CalculationDomain` trait
//!
//! priority = 20(高于 Arithmetic 的 10),含科学函数或 pi/e 常量的表达式
//! 路由至本域。本域内含完整算术求值能力,以处理混合表达式如 `sin(x)+2*3`。

use crate::core::domain::CalculationDomain;
use crate::core::types::{AstNode, BinaryOp, CalcError, EvalContext, EvalResult, UnaryOp};

/// 科学函数白名单。
const SCIENTIFIC_FUNCTIONS: &[&str] = &[
    "sin", "cos", "tan", "asin", "acos", "atan", "ln", "log10", "log2", "log", "exp", "sinh",
    "cosh", "tanh", "gamma", "erf",
];

/// Lanczos 逼近系数(g=7, n=9),用于 gamma 函数。
const LANCZOS_G: f64 = 7.0;
const LANCZOS_COEF: [f64; 9] = [
    0.999_999_999_999_809_9,
    676.5203681218851,
    -1259.1392167224028,
    771.323_428_777_653_1,
    -176.615_029_162_140_6,
    12.507343278686905,
    -0.13857109526572012,
    9.984_369_578_019_572e-6,
    1.5056327351493116e-7,
];

/// Abramowitz & Stegun 7.1.26 逼近系数,用于 erf 函数(最大误差 ~1.5e-7)。
const ERF_A1: f64 = 0.254829592;
const ERF_A2: f64 = -0.284496736;
const ERF_A3: f64 = 1.421413741;
const ERF_A4: f64 = -1.453152027;
const ERF_A5: f64 = 1.061405429;
const ERF_P: f64 = 0.3275911;

/// Scientific 计算域。
///
/// 支持三角/反三角/对数/指数/双曲/特殊函数,内置 pi/e 常量。
/// priority=20,高于 ArithmeticDomain,含科学函数的表达式路由至本域。
pub struct ScientificDomain;

impl CalculationDomain for ScientificDomain {
    fn domain_name(&self) -> &str {
        "scientific"
    }

    fn priority(&self) -> u8 {
        20
    }

    fn supports(&self, ast: &AstNode) -> bool {
        contains_scientific(ast)
    }

    fn evaluate(&self, ast: &AstNode, ctx: &EvalContext) -> Result<EvalResult, CalcError> {
        // 预绑定 pi/e(若上下文未提供)
        let mut ctx = ctx.clone();
        if ctx.get_var("pi").is_none() {
            ctx = ctx.with_var("pi", std::f64::consts::PI);
        }
        if ctx.get_var("e").is_none() {
            ctx = ctx.with_var("e", std::f64::consts::E);
        }
        let value = self.eval_node(ast, &ctx)?;
        Ok(EvalResult::Scalar(value))
    }
}

impl ScientificDomain {
    /// 递归求值 AST 节点。
    fn eval_node(&self, ast: &AstNode, ctx: &EvalContext) -> Result<f64, CalcError> {
        match ast {
            AstNode::Number(n) => Ok(*n),
            AstNode::Variable(name) => ctx
                .get_var(name)
                .ok_or_else(|| CalcError::EvalError(format!("unbound variable: {}", name))),
            AstNode::BinaryOp(op, l, r) => {
                let a = self.eval_node(l, ctx)?;
                let b = self.eval_node(r, ctx)?;
                self.eval_binary(*op, a, b)
            }
            AstNode::UnaryOp(op, e) => {
                let v = self.eval_node(e, ctx)?;
                match op {
                    UnaryOp::Neg => Ok(-v),
                    UnaryOp::Factorial => self.eval_factorial(v),
                    UnaryOp::Abs => Ok(v.abs()),
                }
            }
            AstNode::FunctionCall(name, args) => self.eval_function(name, args, ctx),
            AstNode::Complex(_, _)
            | AstNode::Matrix(_)
            | AstNode::List(_)
            | AstNode::BigNumber(_) => Err(CalcError::DomainError(format!(
                "scientific domain does not support this node type: {:?}",
                ast
            ))),
        }
    }

    /// 求值二元运算(与 ArithmeticDomain 等价,保持域自包含)。
    fn eval_binary(&self, 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 {
                    if a == 0.0 {
                        return Err(CalcError::NaNOrInf);
                    }
                    return Err(CalcError::DivisionByZero);
                }
                a / b
            }
            BinaryOp::Pow => {
                if a == 0.0 && b == 0.0 {
                    return Ok(1.0);
                }
                a.powf(b)
            }
            BinaryOp::Mod => {
                if b == 0.0 {
                    return Err(CalcError::DivisionByZero);
                }
                a % b
            }
        };
        if !result.is_finite() {
            return Err(CalcError::NaNOrInf);
        }
        Ok(result)
    }

    /// 求值阶乘(与 ArithmeticDomain 等价)。
    fn eval_factorial(&self, n: f64) -> Result<f64, CalcError> {
        if n < 0.0 || n.fract() != 0.0 {
            return Err(CalcError::DomainError(format!(
                "factorial requires non-negative integer, got {}",
                n
            )));
        }
        let n = n as u64;
        if n > 10_000 {
            return Err(CalcError::Overflow);
        }
        let mut result: f64 = 1.0;
        for i in 2..=n {
            result *= i as f64;
            if result.is_infinite() {
                return Err(CalcError::Overflow);
            }
        }
        Ok(result)
    }

    /// 求值科学函数调用。
    fn eval_function(
        &self,
        name: &str,
        args: &[AstNode],
        ctx: &EvalContext,
    ) -> Result<f64, CalcError> {
        match name {
            // ===== 三角函数 =====
            "sin" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                self.check_finite(x.sin(), name)
            }
            "cos" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                self.check_finite(x.cos(), name)
            }
            "tan" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                self.check_finite(x.tan(), name)
            }
            // ===== 反三角函数 =====
            "asin" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                if !(-1.0..=1.0).contains(&x) {
                    return Err(CalcError::DomainError(format!(
                        "asin requires argument in [-1, 1], got {}",
                        x
                    )));
                }
                self.check_finite(x.asin(), name)
            }
            "acos" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                if !(-1.0..=1.0).contains(&x) {
                    return Err(CalcError::DomainError(format!(
                        "acos requires argument in [-1, 1], got {}",
                        x
                    )));
                }
                self.check_finite(x.acos(), name)
            }
            "atan" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                self.check_finite(x.atan(), name)
            }
            // ===== 对数函数 =====
            "ln" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                if x <= 0.0 {
                    return Err(CalcError::DomainError(format!(
                        "ln requires positive argument, got {}",
                        x
                    )));
                }
                self.check_finite(x.ln(), name)
            }
            "log10" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                if x <= 0.0 {
                    return Err(CalcError::DomainError(format!(
                        "log10 requires positive argument, got {}",
                        x
                    )));
                }
                self.check_finite(x.log10(), name)
            }
            "log2" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                if x <= 0.0 {
                    return Err(CalcError::DomainError(format!(
                        "log2 requires positive argument, got {}",
                        x
                    )));
                }
                self.check_finite(x.log2(), name)
            }
            "log" => {
                // log(value, base) = log_base(value)
                if args.len() != 2 {
                    return Err(CalcError::EvalError(format!(
                        "log expects 2 arguments (value, base), got {}",
                        args.len()
                    )));
                }
                let value = self.eval_node(&args[0], ctx)?;
                let base = self.eval_node(&args[1], ctx)?;
                if value <= 0.0 {
                    return Err(CalcError::DomainError(format!(
                        "log requires positive value, got {}",
                        value
                    )));
                }
                if base <= 0.0 || base == 1.0 {
                    return Err(CalcError::DomainError(format!(
                        "log requires positive base != 1, got {}",
                        base
                    )));
                }
                self.check_finite(value.log(base), name)
            }
            // ===== 指数函数 =====
            "exp" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                self.check_finite(x.exp(), name)
            }
            // ===== 双曲函数 =====
            "sinh" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                self.check_finite(x.sinh(), name)
            }
            "cosh" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                self.check_finite(x.cosh(), name)
            }
            "tanh" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                self.check_finite(x.tanh(), name)
            }
            // ===== 特殊函数 =====
            "gamma" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                let result = lanczos_gamma(x);
                self.check_finite(result, name)
            }
            "erf" => {
                let x = self.eval_one_arg(name, args, ctx)?;
                let result = erf(x);
                self.check_finite(result, name)
            }
            _ => Err(CalcError::EvalError(format!("unknown function: {}", name))),
        }
    }

    /// 求值单参数函数的参数。
    fn eval_one_arg(
        &self,
        name: &str,
        args: &[AstNode],
        ctx: &EvalContext,
    ) -> Result<f64, CalcError> {
        if args.len() != 1 {
            return Err(CalcError::EvalError(format!(
                "{} expects 1 argument, got {}",
                name,
                args.len()
            )));
        }
        self.eval_node(&args[0], ctx)
    }

    /// 检查结果是否有限,非有限返回 NaNOrInf。
    fn check_finite(&self, value: f64, _name: &str) -> Result<f64, CalcError> {
        if !value.is_finite() {
            return Err(CalcError::NaNOrInf);
        }
        Ok(value)
    }
}

impl Default for ScientificDomain {
    fn default() -> Self {
        Self
    }
}

/// 检查 AST 是否包含科学函数或 pi/e 常量。
fn contains_scientific(ast: &AstNode) -> bool {
    match ast {
        AstNode::Number(_) | AstNode::Complex(_, _) | AstNode::BigNumber(_) => false,
        AstNode::Variable(name) => name == "pi" || name == "e",
        AstNode::BinaryOp(_, l, r) => contains_scientific(l) || contains_scientific(r),
        AstNode::UnaryOp(_, e) => contains_scientific(e),
        AstNode::FunctionCall(name, args) => {
            SCIENTIFIC_FUNCTIONS.contains(&name.as_str()) || args.iter().any(contains_scientific)
        }
        AstNode::Matrix(rows) => rows
            .iter()
            .flat_map(|row| row.iter())
            .any(contains_scientific),
        AstNode::List(elements) => elements.iter().any(contains_scientific),
    }
}

/// Lanczos 逼近计算 gamma 函数。
///
/// 对 x > 0.5 使用 Lanczos 逼近;对 x < 0.5 使用反射公式 Γ(z)Γ(1-z) = π/sin(πz)。
fn lanczos_gamma(x: f64) -> f64 {
    if x < 0.5 {
        std::f64::consts::PI / ((std::f64::consts::PI * x).sin() * lanczos_gamma(1.0 - x))
    } else {
        let x = x - 1.0;
        let mut a = LANCZOS_COEF[0];
        let t = x + LANCZOS_G + 0.5;
        for (i, coef) in LANCZOS_COEF.iter().enumerate().skip(1) {
            a += coef / (x + i as f64);
        }
        (2.0 * std::f64::consts::PI).sqrt() * t.powf(x + 0.5) * (-t).exp() * a
    }
}

/// Abramowitz & Stegun 7.1.26 逼近计算 erf 函数(最大误差 ~1.5e-7)。
fn erf(x: f64) -> f64 {
    // erf(0) = 0 数学上精确,A&S 逼近在此点有 ~1e-7 误差,特判以保证 spec 精确匹配。
    if x == 0.0 {
        return 0.0;
    }
    let sign = if x < 0.0 { -1.0 } else { 1.0 };
    let x = x.abs();
    let t = 1.0 / (1.0 + ERF_P * x);
    let y = 1.0
        - (((((ERF_A5 * t + ERF_A4) * t) + ERF_A3) * t + ERF_A2) * t + ERF_A1) * t * (-x * x).exp();
    sign * y
}

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

    /// 辅助函数:解析 + 求值,返回 f64
    fn eval(input: &str) -> Result<f64, CalcError> {
        let ast = parse(input).unwrap();
        let domain = ScientificDomain;
        let ctx = EvalContext::new();
        domain
            .evaluate(&ast, &ctx)
            .map(|r| r.as_scalar().expect("expected scalar result"))
    }

    /// 辅助函数:近似比较
    fn approx(a: f64, b: f64) -> bool {
        (a - b).abs() < 1e-10
    }

    // ===== Requirement 1: Trigonometric Functions in Radians =====

    #[test]
    fn test_sin_zero() {
        // sin(0) → 0.0 (Req 1 Scen 1)
        assert!(approx(eval("sin(0)").unwrap(), 0.0));
    }

    #[test]
    fn test_cos_zero() {
        // cos(0) → 1.0 (Req 1 Scen 2)
        assert!(approx(eval("cos(0)").unwrap(), 1.0));
    }

    #[test]
    fn test_sin_pi_over_two() {
        // sin(pi/2) → 1.0 (Req 1 Scen 3)
        assert!(approx(eval("sin(pi/2)").unwrap(), 1.0));
    }

    #[test]
    fn test_tan_pi_over_four() {
        // tan(pi/4) → ≈1.0 (Req 1 Scen 4)
        assert!(approx(eval("tan(pi/4)").unwrap(), 1.0));
    }

    // ===== Requirement 2: Inverse Trigonometric Functions =====

    #[test]
    fn test_asin_one() {
        // asin(1) → ≈pi/2 (Req 2 Scen 1)
        assert!(approx(
            eval("asin(1)").unwrap(),
            std::f64::consts::FRAC_PI_2
        ));
    }

    #[test]
    fn test_acos_zero() {
        // acos(0) → ≈pi/2 (Req 2 Scen 2)
        assert!(approx(
            eval("acos(0)").unwrap(),
            std::f64::consts::FRAC_PI_2
        ));
    }

    #[test]
    fn test_atan_one() {
        // atan(1) → ≈pi/4 (Req 2 Scen 3)
        assert!(approx(
            eval("atan(1)").unwrap(),
            std::f64::consts::FRAC_PI_4
        ));
    }

    // ===== Requirement 3: Inverse Trigonometric Domain Validation =====

    #[test]
    fn test_asin_out_of_range() {
        // asin(2) → DomainError (Req 3 Scen 1)
        let result = eval("asin(2)");
        assert!(result.is_err());
        assert!(
            matches!(result, Err(CalcError::DomainError(_))),
            "expected DomainError, got {:?}",
            result
        );
    }

    #[test]
    fn test_acos_out_of_range_negative() {
        // acos(-1.5) → DomainError (Req 3 Scen 2)
        let result = eval("acos(-1.5)");
        assert!(result.is_err());
        assert!(
            matches!(result, Err(CalcError::DomainError(_))),
            "expected DomainError, got {:?}",
            result
        );
    }

    // ===== Requirement 4: Logarithmic Functions =====

    #[test]
    fn test_ln_e() {
        // ln(e) → 1.0 (Req 4 Scen 1)
        assert!(approx(eval("ln(e)").unwrap(), 1.0));
    }

    #[test]
    fn test_ln_one() {
        // ln(1) → 0.0 (Req 4 Scen 2)
        assert!(approx(eval("ln(1)").unwrap(), 0.0));
    }

    #[test]
    fn test_log10_100() {
        // log10(100) → 2.0 (Req 4 Scen 3)
        assert!(approx(eval("log10(100)").unwrap(), 2.0));
    }

    #[test]
    fn test_log2_8() {
        // log2(8) → 3.0 (Req 4 Scen 4)
        assert!(approx(eval("log2(8)").unwrap(), 3.0));
    }

    #[test]
    fn test_log_arbitrary_base() {
        // log(100, 10) → 2.0 (Req 4 Scen 5)
        assert!(approx(eval("log(100, 10)").unwrap(), 2.0));
    }

    // ===== Requirement 5: Logarithmic Domain Validation =====

    #[test]
    fn test_ln_negative() {
        // ln(-1) → DomainError (Req 5 Scen 1)
        let result = eval("ln(-1)");
        assert!(result.is_err());
        assert!(
            matches!(result, Err(CalcError::DomainError(_))),
            "expected DomainError, got {:?}",
            result
        );
    }

    #[test]
    fn test_ln_zero() {
        // ln(0) → DomainError (Req 5 Scen 2)
        let result = eval("ln(0)");
        assert!(result.is_err());
        assert!(
            matches!(result, Err(CalcError::DomainError(_))),
            "expected DomainError, got {:?}",
            result
        );
    }

    #[test]
    fn test_log10_negative() {
        // log10(-5) → DomainError (Req 5 Scen 3)
        let result = eval("log10(-5)");
        assert!(result.is_err());
        assert!(
            matches!(result, Err(CalcError::DomainError(_))),
            "expected DomainError, got {:?}",
            result
        );
    }

    // ===== Requirement 6: Exponential Function =====

    #[test]
    fn test_exp_zero() {
        // exp(0) → 1.0 (Req 6 Scen 1)
        assert!(approx(eval("exp(0)").unwrap(), 1.0));
    }

    #[test]
    fn test_exp_one() {
        // exp(1) → ≈e (Req 6 Scen 2)
        assert!(approx(eval("exp(1)").unwrap(), std::f64::consts::E));
    }

    #[test]
    fn test_exp_ten() {
        // exp(10) → ≈22026.465794806718 (Req 6 Scen 3)
        assert!(approx(eval("exp(10)").unwrap(), 22026.465794806718));
    }

    // ===== Requirement 7: Hyperbolic Functions =====

    #[test]
    fn test_sinh_zero() {
        // sinh(0) → 0.0 (Req 7 Scen 1)
        assert!(approx(eval("sinh(0)").unwrap(), 0.0));
    }

    #[test]
    fn test_cosh_zero() {
        // cosh(0) → 1.0 (Req 7 Scen 2)
        assert!(approx(eval("cosh(0)").unwrap(), 1.0));
    }

    #[test]
    fn test_tanh_zero() {
        // tanh(0) → 0.0 (Req 7 Scen 3)
        assert!(approx(eval("tanh(0)").unwrap(), 0.0));
    }

    // ===== Requirement 8: Special Mathematical Functions =====

    #[test]
    fn test_gamma_five() {
        // gamma(5) → 24.0 (Req 8 Scen 1, Γ(5) = 4! = 24)
        assert!(approx(eval("gamma(5)").unwrap(), 24.0));
    }

    #[test]
    fn test_gamma_one() {
        // gamma(1) → 1.0 (Req 8 Scen 2)
        assert!(approx(eval("gamma(1)").unwrap(), 1.0));
    }

    #[test]
    fn test_erf_zero() {
        // erf(0) → 0.0 (Req 8 Scen 3)
        assert!(approx(eval("erf(0)").unwrap(), 0.0));
    }

    #[test]
    fn test_erf_large() {
        // erf(100) → ≈1.0 (Req 8 Scen 4)
        assert!(approx(eval("erf(100)").unwrap(), 1.0));
    }

    // ===== Requirement 9: Mathematical Constants pi and e =====

    #[test]
    fn test_constant_pi() {
        // pi → ≈3.141592653589793 (Req 9 Scen 1)
        assert!(approx(eval("pi").unwrap(), std::f64::consts::PI));
    }

    #[test]
    fn test_constant_e() {
        // e → ≈2.718281828459045 (Req 9 Scen 2)
        assert!(approx(eval("e").unwrap(), std::f64::consts::E));
    }

    // ===== Requirement 10: Mixed Scientific Computation =====

    #[test]
    fn test_sin_pi_over_two_plus_cos_zero() {
        // sin(pi/2) + cos(0) → 2.0 (Req 10 Scen 1)
        assert!(approx(eval("sin(pi/2) + cos(0)").unwrap(), 2.0));
    }

    #[test]
    fn test_exp_one_plus_ln_e() {
        // exp(1) + ln(e) → ≈e + 1 (Req 10 Scen 2)
        assert!(approx(
            eval("exp(1) + ln(e)").unwrap(),
            std::f64::consts::E + 1.0
        ));
    }

    // ===== supports() 方法测试 =====

    #[test]
    fn test_supports_scientific() {
        let domain = ScientificDomain;
        assert!(domain.supports(&parse("sin(x)").unwrap()));
        assert!(domain.supports(&parse("log(100,10)").unwrap()));
        assert!(domain.supports(&parse("gamma(5) + erf(1)").unwrap()));
        assert!(domain.supports(&parse("sinh(1) + cosh(1)").unwrap()));
        assert!(domain.supports(&parse("sin(x) + 2*3").unwrap()));
        assert!(domain.supports(&parse("pi").unwrap()));
        assert!(domain.supports(&parse("e").unwrap()));
    }

    #[test]
    fn test_does_not_support_pure_arithmetic() {
        let domain = ScientificDomain;
        assert!(!domain.supports(&parse("2+3*4").unwrap()));
        assert!(!domain.supports(&parse("42").unwrap()));
        assert!(!domain.supports(&parse("factorial(5)").unwrap()));
        assert!(!domain.supports(&parse("mod(10,3) + abs(-2)").unwrap()));
    }

    #[test]
    fn test_priority_higher_than_arithmetic() {
        let scientific = ScientificDomain;
        let arithmetic = crate::ArithmeticDomain;
        assert!(scientific.priority() > arithmetic.priority());
    }

    // ===== 覆盖未覆盖分支的补充测试 =====

    #[test]
    fn test_pi_e_auto_binding() {
        // lines 63-68: pi/e 自动绑定(EvalContext::new() 无 pi/e)
        let ast = parse("sin(pi/2) + ln(e)").unwrap();
        let domain = ScientificDomain;
        let ctx = EvalContext::new();
        let result = domain.evaluate(&ast, &ctx).unwrap();
        assert!(approx(result.as_scalar().unwrap(), 2.0));
    }

    #[test]
    fn test_unary_factorial_manual_ast() {
        // line 91: UnaryOp::Factorial(parser 不产生此节点,需手动构造)
        let ast = AstNode::UnaryOp(UnaryOp::Factorial, Box::new(AstNode::Number(5.0)));
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new()).unwrap();
        assert!(approx(result.as_scalar().unwrap(), 120.0));
    }

    #[test]
    fn test_unary_abs_manual_ast() {
        // line 92: UnaryOp::Abs(parser 不产生此节点,需手动构造)
        let ast = AstNode::UnaryOp(UnaryOp::Abs, Box::new(AstNode::Number(-3.5)));
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new()).unwrap();
        assert!(approx(result.as_scalar().unwrap(), 3.5));
    }

    #[test]
    fn test_domain_error_complex_node() {
        // lines 97-100: Complex 节点 DomainError
        let ast = AstNode::Complex(1.0, 2.0);
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::DomainError(_))));
    }

    #[test]
    fn test_domain_error_matrix_node() {
        // lines 97-100: Matrix 节点 DomainError
        let ast = AstNode::Matrix(vec![vec![AstNode::Number(1.0)]]);
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::DomainError(_))));
    }

    #[test]
    fn test_domain_error_list_node() {
        // lines 97-100: List 节点 DomainError
        let ast = AstNode::List(vec![AstNode::Number(1.0)]);
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::DomainError(_))));
    }

    #[test]
    fn test_domain_error_bignumber_node() {
        // lines 97-100: BigNumber 节点 DomainError
        let ast = AstNode::BigNumber("123".to_string());
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::DomainError(_))));
    }

    #[test]
    fn test_scalar_mul_finite() {
        // line 110: BinaryOp::Mul 正常路径
        let ast = AstNode::BinaryOp(
            BinaryOp::Mul,
            Box::new(AstNode::Number(3.0)),
            Box::new(AstNode::Number(4.0)),
        );
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new()).unwrap();
        assert!(approx(result.as_scalar().unwrap(), 12.0));
    }

    #[test]
    fn test_scalar_zero_div_zero() {
        // lines 113-115: 0/0 → NaNOrInf
        let ast = AstNode::BinaryOp(
            BinaryOp::Div,
            Box::new(AstNode::Number(0.0)),
            Box::new(AstNode::Number(0.0)),
        );
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::NaNOrInf)));
    }

    #[test]
    fn test_scalar_div_by_zero() {
        // line 116: x/0 (x≠0) → DivisionByZero
        let ast = AstNode::BinaryOp(
            BinaryOp::Div,
            Box::new(AstNode::Number(5.0)),
            Box::new(AstNode::Number(0.0)),
        );
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::DivisionByZero)));
    }

    #[test]
    fn test_scalar_zero_pow_zero() {
        // line 122: 0^0 → 1.0
        let ast = AstNode::BinaryOp(
            BinaryOp::Pow,
            Box::new(AstNode::Number(0.0)),
            Box::new(AstNode::Number(0.0)),
        );
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new()).unwrap();
        assert!(approx(result.as_scalar().unwrap(), 1.0));
    }

    #[test]
    fn test_scalar_mod_by_zero() {
        // lines 127-130: mod by zero → DivisionByZero
        let ast = AstNode::BinaryOp(
            BinaryOp::Mod,
            Box::new(AstNode::Number(10.0)),
            Box::new(AstNode::Number(0.0)),
        );
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::DivisionByZero)));
    }

    #[test]
    fn test_scalar_mod_normal() {
        // line 130: mod 正常路径
        let ast = AstNode::BinaryOp(
            BinaryOp::Mod,
            Box::new(AstNode::Number(10.0)),
            Box::new(AstNode::Number(3.0)),
        );
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new()).unwrap();
        assert!(approx(result.as_scalar().unwrap(), 1.0));
    }

    #[test]
    fn test_scalar_result_not_finite() {
        // line 134: 标量运算结果非有限 → NaNOrInf
        let ast = AstNode::BinaryOp(
            BinaryOp::Add,
            Box::new(AstNode::Number(1e308)),
            Box::new(AstNode::Number(1e308)),
        );
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::NaNOrInf)));
    }

    #[test]
    fn test_factorial_negative_input() {
        // lines 141-146: factorial 负数输入 → DomainError
        let ast = AstNode::UnaryOp(UnaryOp::Factorial, Box::new(AstNode::Number(-1.0)));
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::DomainError(_))));
    }

    #[test]
    fn test_factorial_fractional_input() {
        // lines 141-146: factorial 小数输入 → DomainError
        let ast = AstNode::UnaryOp(UnaryOp::Factorial, Box::new(AstNode::Number(2.5)));
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::DomainError(_))));
    }

    #[test]
    fn test_factorial_overflow_input_too_large() {
        // lines 148-149: factorial 输入超过 10000 → Overflow
        let ast = AstNode::UnaryOp(UnaryOp::Factorial, Box::new(AstNode::Number(10001.0)));
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::Overflow)));
    }

    #[test]
    fn test_factorial_overflow_during_computation() {
        // lines 154-156: factorial 计算过程中溢出 → Overflow
        let ast = AstNode::UnaryOp(UnaryOp::Factorial, Box::new(AstNode::Number(171.0)));
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::Overflow)));
    }

    #[test]
    fn test_factorial_normal_computation() {
        // lines 151-158: factorial 正常计算路径
        let ast = AstNode::UnaryOp(UnaryOp::Factorial, Box::new(AstNode::Number(6.0)));
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new()).unwrap();
        assert!(approx(result.as_scalar().unwrap(), 720.0));
    }

    #[test]
    fn test_log2_non_positive() {
        // lines 230-234: log2(0) → DomainError
        let result = eval("log2(0)");
        assert!(matches!(result, Err(CalcError::DomainError(_))));
    }

    #[test]
    fn test_log_wrong_arg_count() {
        // lines 240-244: log() 参数数量错误
        let ast = AstNode::FunctionCall("log".to_string(), vec![AstNode::Number(100.0)]);
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::EvalError(_))));
    }

    #[test]
    fn test_log_non_positive_value() {
        // lines 248-252: log(-1, 10) → DomainError
        let ast = AstNode::FunctionCall(
            "log".to_string(),
            vec![AstNode::Number(-1.0), AstNode::Number(10.0)],
        );
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::DomainError(_))));
    }

    #[test]
    fn test_log_non_positive_base() {
        // lines 254-258: log(100, -1) → DomainError
        let ast = AstNode::FunctionCall(
            "log".to_string(),
            vec![AstNode::Number(100.0), AstNode::Number(-1.0)],
        );
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::DomainError(_))));
    }

    #[test]
    fn test_log_base_equal_one() {
        // lines 254-258: log(100, 1) → DomainError
        let ast = AstNode::FunctionCall(
            "log".to_string(),
            vec![AstNode::Number(100.0), AstNode::Number(1.0)],
        );
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::DomainError(_))));
    }

    #[test]
    fn test_unknown_function() {
        // line 291: unknown function
        let ast = AstNode::FunctionCall("unknown_func".to_string(), vec![AstNode::Number(1.0)]);
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::EvalError(_))));
    }

    #[test]
    fn test_eval_one_arg_wrong_count() {
        // lines 302-307: eval_one_arg 参数数量错误
        let ast = AstNode::FunctionCall(
            "sin".to_string(),
            vec![AstNode::Number(1.0), AstNode::Number(2.0)],
        );
        let domain = ScientificDomain;
        let result = domain.evaluate(&ast, &EvalContext::new());
        assert!(matches!(result, Err(CalcError::EvalError(_))));
    }

    #[test]
    fn test_check_finite_nan_or_inf() {
        // line 315: check_finite 返回 NaNOrInf
        let result = eval("exp(1000)");
        assert!(matches!(result, Err(CalcError::NaNOrInf)));
    }

    #[test]
    fn test_default_impl() {
        // lines 322-324: Default impl
        let domain = ScientificDomain;
        assert_eq!(domain.domain_name(), "scientific");
        assert_eq!(domain.priority(), 20);
    }

    #[test]
    fn test_contains_scientific_matrix() {
        // lines 337-341: contains_scientific for Matrix
        let ast = AstNode::Matrix(vec![vec![AstNode::FunctionCall(
            "sin".to_string(),
            vec![AstNode::Number(1.0)],
        )]]);
        let domain = ScientificDomain;
        assert!(domain.supports(&ast));
    }

    #[test]
    fn test_contains_scientific_list() {
        // line 341: contains_scientific for List
        let ast = AstNode::List(vec![AstNode::FunctionCall(
            "cos".to_string(),
            vec![AstNode::Number(1.0)],
        )]);
        let domain = ScientificDomain;
        assert!(domain.supports(&ast));
    }

    #[test]
    fn test_lanczos_gamma_reflection() {
        // line 350: lanczos_gamma 反射公式(x < 0.5)
        // gamma(-0.5) = -2*sqrt(pi) ≈ -3.5449077018
        let result = eval("gamma(-0.5)").unwrap();
        assert!(approx(result, -2.0 * std::f64::consts::PI.sqrt()));
    }

    // ===== proptest 属性测试 =====

    use proptest::prelude::*;

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

        // 三角恒等式:sin(x)^2 + cos(x)^2 == 1
        #[test]
        fn prop_sin_cos_identity(x in -100.0f64..100.0) {
            let r = eval(&format!("sin({})^2 + cos({})^2", x, x)).unwrap();
            prop_assert!((r - 1.0).abs() < 1e-9, "sin(x)^2+cos(x)^2 should be 1, got {}", r);
        }

        // 对数恒等式:exp(ln(x)) ≈ x for x > 0
        #[test]
        fn prop_exp_ln_identity(x in 0.001f64..1000.0) {
            let r = eval(&format!("exp(ln({}))", x)).unwrap();
            prop_assert!((r - x).abs() < 1e-9 * x.abs().max(1.0), "exp(ln(x)) should be {}, got {}", x, r);
        }

        // 双曲恒等式:cosh(x)^2 - sinh(x)^2 == 1
        // 范围限制在 [-5, 5]:cosh(5)^2 ≈ 5500,f64 精度足以恢复差值 1。
        // 更大范围时 cosh²/sinh² 超出 f64 有效位数,差值退化为 0。
        #[test]
        fn prop_cosh_sinh_identity(x in -5.0f64..5.0) {
            let r = eval(&format!("cosh({})^2 - sinh({})^2", x, x)).unwrap();
            prop_assert!((r - 1.0).abs() < 1e-9, "cosh(x)^2-sinh(x)^2 should be 1, got {}", r);
        }
    }
}