yarer 0.2.0

Yarer (Yet Another Rust Expression Resolver) is a library for resolving mathematical expressions. Internally it uses the shunting yard algorithm.
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
use num_bigint::BigInt;
use num_rational::BigRational;
use num_traits::{One, ToPrimitive, Zero};
use std::{
    fmt::Display,
    ops::{Add, Div, Mul, Sub},
};

/// Enum Type [Number]. Either an BigInt integer [`Number::NaturalNumber`]
/// or a [`BigRational`] rational number [`Number::DecimalNumber`]
///
#[derive(Debug, PartialEq, Clone)]
pub enum Number {
    /// an Integer [BigInt]
    NaturalNumber(BigInt),
    /// a Rational number [BigRational]
    DecimalNumber(BigRational),
}

/// A binary or unary Math [`Operator`]
///
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Operator {
    /// Binary Add ('1+1')
    Add,
    /// Binary Sub ('2-1')
    Sub,
    /// Binary Mul ('2*2')
    Mul,
    /// Binary Div ('3/3')
    Div,
    /// Binary Pow ('base^exponent')
    Pow,
    /// Unary Neg ('-1')
    Une,
    /// Factorial ('0!')
    Fac,
    /// Binary Assignment ('A=1')
    Eql,
}

/// The "associativity" of an operator dictates the direction
/// in which operations of equal precedence are evaluated when they appear
///
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Associate {
    /// If an operator is left-associative, then operations are evaluated from left to right.
    /// Example: -a^b, -1, -(-3)
    ///
    LeftAssociative,
    /// If an operator is right-associative, then operations are evaluated from right to left.
    /// Example: A=1
    ///
    RightAssociative,
}

/// Just [`Token::Bracket`]s. They change the order of evaluation of an expression.
///
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Bracket {
    /// either '(' or '['
    Open,
    /// either ')' or ']'
    Close,
}

/// The [Token] enum. It represents the smallest chunk of a math expression
///
/// It can be a
/// [`Token::Operand`] as 1,2,3,-4,-5,6.66 ...
/// [`Token::Operator`] as +,-,*,/ ...
/// [`Token::Bracket`] as [] or ()
/// [`Token::Function`] as sin,cos,tan,ln ...
/// [`Token::Variable`] as any variable name such as x,y,ab,foo,... whatever
///
#[derive(Debug, PartialEq, Clone)]
pub enum Token<'a> {
    /// Natural numbers (1,2,3,4...) or their decimals (1.1, 2.3, 4.4 ...)
    Operand(Number),
    /// Operators +,-,/,*,^...
    Operator(Operator),
    /// ( ) [ ]
    Bracket(Bracket),
    /// sin cos tan ln log...
    Function(MathFunction),
    /// comma separator for function arguments
    Comma,
    /// a b c x y ...
    Variable(&'a str),
    /// Semicolon ';' separator for chained expressions
    SemiColon,
}

/// The [`MathFunction`] enum. It represents a common math function.
///
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum MathFunction {
    /// Trigonometric Sine
    Sin,
    /// Trigonometric Cosine
    Cos,
    /// Trigonometric Tangent
    Tan,
    /// Arcsine
    ASin,
    /// Arccosine
    ACos,
    /// Arctangent
    ATan,
    /// Natural logarithm
    Ln,
    /// Base 10 logarithm
    Log,
    /// Absolute value
    Abs,
    /// Square root
    Sqrt,
    /// Max value
    Max,
    /// Min value
    Min,
    /// Rounds down
    Floor,
    /// Rounds up
    Ceil,
    /// Rounds to nearest integer
    Round,
    /// e^x exponentiation
    Exp,
    /// Standard Normal probability density function
    Pdf,
    /// Standard Normal cumulative distribution function
    Cdf,
    /// No function expected
    None,
}

impl Token<'_> {
    /// Converts a char to a [`Token::Operator`]
    /// or just returns [`None`] if nothing matches.
    ///
    const fn from_operator(c: char) -> Option<Token<'static>> {
        match c {
            '+' => Some(Token::Operator(Operator::Add)),
            '-' => Some(Token::Operator(Operator::Sub)),
            '*' | '×' => Some(Token::Operator(Operator::Mul)),
            '/' | '÷' => Some(Token::Operator(Operator::Div)),
            '^' => Some(Token::Operator(Operator::Pow)),
            '#' => Some(Token::Operator(Operator::Une)),
            '!' => Some(Token::Operator(Operator::Fac)),
            '=' => Some(Token::Operator(Operator::Eql)),
            _ => None,
        }
    }

    /// Converts a char to a [`Token::Bracket`]
    /// or just returns [`None`] if nothing matches.
    ///
    const fn from_bracket(c: char) -> Option<Token<'static>> {
        match c {
            '(' | '[' => Some(Token::Bracket(Bracket::Open)),
            ')' | ']' => Some(Token::Bracket(Bracket::Close)),
            _ => None,
        }
    }

    /// Converts a &str to a [`Token::Function(MathFunction)`]
    /// or just returns [`None`] if nothing matches.
    ///
    fn get_some(fun: &str) -> Option<MathFunction> {
        match fun.to_lowercase().as_str() {
            "sin" => Some(MathFunction::Sin),
            "cos" => Some(MathFunction::Cos),
            "tan" => Some(MathFunction::Tan),
            "asin" => Some(MathFunction::ASin),
            "acos" => Some(MathFunction::ACos),
            "atan" => Some(MathFunction::ATan),
            "ln" => Some(MathFunction::Ln),
            "log" | "log10" => Some(MathFunction::Log),
            "abs" => Some(MathFunction::Abs),
            "sqrt" => Some(MathFunction::Sqrt),
            "max" => Some(MathFunction::Max),
            "min" => Some(MathFunction::Min),
            "floor" => Some(MathFunction::Floor),
            "ceil" => Some(MathFunction::Ceil),
            "round" => Some(MathFunction::Round),
            "exp" => Some(MathFunction::Exp),
            "pdf" => Some(MathFunction::Pdf),
            "cdf" => Some(MathFunction::Cdf),
            &_ => None,
        }
    }

    /// Transforms a specific chunk of chars into a specific [Token]. i.e.
    ///
    /// "+"   -> [`Token::Operator`]
    /// "("   -> [`Token::Bracket`]
    /// "42"  -> [`Token::Operand(Token::NaturalNumber)`]
    /// "6.6" -> [`Token::Operand(Token::DecimalNumber)`]
    /// "sin" -> [`Token::Function`]
    /// "x"   -> [`Token::Variable`]
    ///
    #[must_use]
    pub fn tokenize(t: &str) -> Option<Token<'_>> {
        match t.chars().next() {
            Some(s) => match s {
                c @ ('+' | '-' | '*' | '/' | '^' | '!' | '=' | '×' | '÷') => {
                    return Some(Token::from_operator(c).unwrap())
                }
                b @ ('(' | ')' | '[' | ']') => return Some(Token::from_bracket(b).unwrap()),
                ',' => return Some(Token::Comma),
                ';' => return Some(Token::SemiColon),
                _ => (), // continue the flow
            },
            None => return None,
        }

        if let Ok(v) = t.parse::<BigInt>() {
            return Some(Token::Operand(Number::NaturalNumber(v)));
        }

        if let Some(v) = parse_decimal_literal(t) {
            return Some(Token::Operand(Number::DecimalNumber(v)));
        }

        if let Some(fun) = Token::get_some(t) {
            return Some(Token::Function(fun));
        }

        Some(Token::Variable(t))
    }

    /// Founding out the priority and the associative precedence of an operator
    ///
    fn operator_priority(o: Token) -> (u8, Associate) {
        match o {
            Token::Operator(Operator::Add | Operator::Sub) => (1, Associate::LeftAssociative),
            Token::Operator(Operator::Mul | Operator::Div) => (2, Associate::LeftAssociative),
            Token::Operator(Operator::Pow) => (3, Associate::RightAssociative),
            Token::Operator(Operator::Une) => (4, Associate::RightAssociative),
            Token::Operator(Operator::Fac) => (5, Associate::LeftAssociative),
            Token::Operator(Operator::Eql) => (0, Associate::RightAssociative),
            _ => panic!("Operator '{o}' not recognised. This must not happen!"),
        }
    }

    /// Checks if an operator has priority over another one
    ///
    /// i.e.
    /// * has priority over +
    /// ^ has priority over *
    /// unary - has priority over ^
    ///
    #[must_use]
    pub fn compare_operator_priority(op1: Token, op2: Token) -> bool {
        let v_op1: (u8, Associate) = self::Token::operator_priority(op1);
        let v_op2: (u8, Associate) = self::Token::operator_priority(op2);

        v_op1.1 == Associate::LeftAssociative && v_op1.0 <= v_op2.0
            || v_op1.1 == Associate::RightAssociative && v_op1.0 < v_op2.0
    }
}

/// Let's display a [`Number::NaturalNumber`] or a [`Number::DecimalNumber`] properly
///
impl Display for Number {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Number::NaturalNumber(v) => write!(f, "{v}"),
            Number::DecimalNumber(v) => {
                if v.denom().is_one() {
                    write!(f, "{}", v.to_integer())
                } else if let Some(fl) = v.to_f64() {
                    write!(f, "{fl}")
                } else {
                    write!(f, "{}/{}", v.numer(), v.denom())
                }
            }
        }
    }
}

/// The main operational functional closure. It handles 4 different cases:
///
/// 1. Natural (op) Natural returns Natural
/// 2. Natural (op) Decimal returns Decimal
/// 3. Decimal (op) Decimal returns Decimal
/// 4. Decimal (op) Natural returns Decimal
///
/// (op) can be [Add], [Mul], [Sub], [Div], [BitXor], ...
///
/// We define 2 closures: 1 specialised for Natural Numbers and the other one specialised for Decimals.
///
fn apply_functional_token_operation<NF, DF>(ln: Number, rn: Number, nf: NF, df: DF) -> Number
where
    NF: Fn(BigInt, BigInt) -> BigInt,
    DF: Fn(BigRational, BigRational) -> BigRational,
{
    match (ln, rn.clone()) {
        (Number::NaturalNumber(v1), Number::NaturalNumber(v2)) => Number::NaturalNumber(nf(v1, v2)),
        (Number::NaturalNumber(v1), Number::DecimalNumber(v2)) => {
            Number::DecimalNumber(df(BigRational::from(v1), v2))
        }
        (Number::DecimalNumber(v1), Number::NaturalNumber(v2)) => {
            Number::DecimalNumber(df(v1, BigRational::from(v2)))
        }
        (Number::DecimalNumber(v1), Number::DecimalNumber(v2)) => Number::DecimalNumber(df(v1, v2)),
    }
}

impl Add for Number {
    type Output = Number;

    fn add(self, rhs: Self) -> Self::Output {
        apply_functional_token_operation(self, rhs, |a, b| a + b, |a, b| a + b)
    }
}

impl Sub for Number {
    type Output = Number;

    fn sub(self, rhs: Self) -> Self::Output {
        apply_functional_token_operation(self, rhs, |a, b| a - b, |a, b| a - b)
    }
}

impl Mul for Number {
    type Output = Number;

    fn mul(self, rhs: Self) -> Self::Output {
        apply_functional_token_operation(self, rhs, |a, b| a * b, |a, b| a * b)
    }
}

impl Div for Number {
    type Output = Number;

    fn div(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (Number::NaturalNumber(v1), Number::NaturalNumber(v2)) => {
                Number::DecimalNumber(BigRational::new(v1, v2))
            }
            (Number::NaturalNumber(v1), Number::DecimalNumber(v2)) => {
                Number::DecimalNumber(BigRational::from(v1) / v2)
            }
            (Number::DecimalNumber(v1), Number::NaturalNumber(v2)) => {
                Number::DecimalNumber(v1 / BigRational::from(v2))
            }
            (Number::DecimalNumber(v1), Number::DecimalNumber(v2)) => {
                Number::DecimalNumber(v1 / v2)
            }
        }
    }
}

/// PartialOrd between [Number]s with the required conversions.
///
impl PartialOrd for Number {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        match (self, other) {
            (Number::NaturalNumber(v1), Number::NaturalNumber(v2)) => v1.partial_cmp(&v2),
            (Number::NaturalNumber(v1), Number::DecimalNumber(v2)) => {
                BigRational::from(v1.clone()).partial_cmp(v2)
            }
            (Number::DecimalNumber(v1), Number::NaturalNumber(v2)) => {
                v1.partial_cmp(&BigRational::from(v2.clone()))
            }
            (Number::DecimalNumber(v1), Number::DecimalNumber(v2)) => v1.partial_cmp(&v2),
        }
    }
}

/// Error returned when a [`Number`] cannot be converted into a fixed-size
/// numeric type because the value falls outside that type's representable range.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ConversionError {
    /// The value does not fit in the requested target type.
    #[error("value '{value}' is out of range for target type {target}")]
    OutOfRange {
        /// The offending value, rendered as a decimal string.
        value: String,
        /// The name of the target type that could not hold the value.
        target: &'static str,
    },
}

/// Converts a [`Number`] into a [`BigInt`], truncating any fractional part
/// toward zero. This is exact and infallible: a [`BigInt`] holds any integer.
impl From<Number> for BigInt {
    fn from(n: Number) -> BigInt {
        match n {
            Number::NaturalNumber(v) => v,
            // `to_integer` truncates the exact rational toward zero — no lossy f64 round-trip.
            Number::DecimalNumber(v) => v.to_integer(),
        }
    }
}

/// Fallible conversion to [`f64`]. Fails when the value cannot be represented
/// as a finite double (e.g. it exceeds [`f64::MAX`]).
impl TryFrom<Number> for f64 {
    type Error = ConversionError;

    fn try_from(n: Number) -> Result<Self, Self::Error> {
        let value = match &n {
            Number::NaturalNumber(v) => v.to_f64(),
            Number::DecimalNumber(v) => v.to_f64(),
        };
        value
            .filter(|f| f.is_finite())
            .ok_or_else(|| ConversionError::OutOfRange {
                value: n.to_string(),
                target: "f64",
            })
    }
}

/// Fallible conversion to [`i32`]: the fractional part is truncated toward zero,
/// then the integer must fit in the target type.
impl TryFrom<Number> for i32 {
    type Error = ConversionError;

    fn try_from(n: Number) -> Result<Self, Self::Error> {
        let value: BigInt = n.into();
        value.to_i32().ok_or_else(|| ConversionError::OutOfRange {
            value: value.to_string(),
            target: "i32",
        })
    }
}

/// Fallible conversion to [`i64`]: the fractional part is truncated toward zero,
/// then the integer must fit in the target type.
impl TryFrom<Number> for i64 {
    type Error = ConversionError;

    fn try_from(n: Number) -> Result<Self, Self::Error> {
        let value: BigInt = n.into();
        value.to_i64().ok_or_else(|| ConversionError::OutOfRange {
            value: value.to_string(),
            target: "i64",
        })
    }
}

/// Fallible conversion to [`i128`]: the fractional part is truncated toward zero,
/// then the integer must fit in the target type.
impl TryFrom<Number> for i128 {
    type Error = ConversionError;

    fn try_from(n: Number) -> Result<Self, Self::Error> {
        let value: BigInt = n.into();
        value.to_i128().ok_or_else(|| ConversionError::OutOfRange {
            value: value.to_string(),
            target: "i128",
        })
    }
}

impl Display for Operator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            Operator::Add => write!(f, "+"),
            Operator::Sub => write!(f, "-"),
            Operator::Mul => write!(f, "*"),
            Operator::Div => write!(f, "/"),
            Operator::Pow => write!(f, "^"),
            Operator::Une => write!(f, "#"),
            Operator::Fac => write!(f, "!"),
            Operator::Eql => write!(f, "="),
        }
    }
}

impl Display for Bracket {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            Self::Open => write!(f, "("),
            Self::Close => write!(f, ")"),
        }
    }
}

impl Display for MathFunction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", *self)
    }
}

impl Display for Token<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Token::Operand(v) => write!(f, "({v})"),
            Token::Operator(v) => write!(f, "({v})"),
            Token::Bracket(v) => write!(f, "({v})"),
            Token::Function(v) => write!(f, "({v})"),
            Token::Variable(v) => write!(f, "({v})"),
            Token::Comma => write!(f, "(,)"),
            Token::SemiColon => write!(f, "(;)"),
        }
    }
}

fn parse_decimal_literal(literal: &str) -> Option<BigRational> {
    let (whole, fractional) = literal.split_once('.')?;

    let whole = if whole.is_empty() {
        BigInt::zero()
    } else {
        whole.parse::<BigInt>().ok()?
    };
    let fractional = if fractional.is_empty() {
        BigInt::zero()
    } else {
        fractional.parse::<BigInt>().ok()?
    };
    let fractional_digits = literal
        .split_once('.')
        .map_or(0, |(_, digits)| digits.len());
    let mut exact_scale = BigInt::one();
    for _ in 0..fractional_digits {
        exact_scale *= 10_u8;
    }

    Some(BigRational::new(
        whole * exact_scale.clone() + fractional,
        exact_scale,
    ))
}

#[cfg(test)]
mod tests {
    use num::One;

    use super::*;

    #[test]
    fn test_tokenise_operators() {
        let v = vec!["1", "+", "2.1"];
        assert_eq!(Token::tokenize(v[1]), Some(Token::Operator(Operator::Add)));
        assert_eq!(
            Token::tokenize(v[0]),
            Some(Token::Operand(Number::NaturalNumber(One::one())))
        );
        assert_eq!(
            Token::tokenize(v[2]),
            Some(Token::Operand(Number::DecimalNumber(BigRational::new(
                BigInt::from(21),
                BigInt::from(10)
            ))))
        );
    }

    #[test]
    fn test_from_operator_valid() {
        assert_eq!(
            Token::from_operator('+'),
            Some(Token::Operator(Operator::Add))
        );
        assert_eq!(
            Token::from_operator('-'),
            Some(Token::Operator(Operator::Sub))
        );
        assert_eq!(
            Token::from_operator('*'),
            Some(Token::Operator(Operator::Mul))
        );
        assert_eq!(
            Token::from_operator('×'),
            Some(Token::Operator(Operator::Mul))
        );
        assert_eq!(
            Token::from_operator('/'),
            Some(Token::Operator(Operator::Div))
        );
        assert_eq!(
            Token::from_operator('÷'),
            Some(Token::Operator(Operator::Div))
        );
        assert_eq!(
            Token::from_operator('!'),
            Some(Token::Operator(Operator::Fac))
        );
    }

    #[test]
    fn test_from_operator_invalid() {
        assert_eq!(Token::from_operator('a'), None);
        assert_eq!(Token::from_operator('1'), None);
        assert_eq!(Token::from_operator('~'), None);
    }

    #[test]
    fn test_tokenize_valid() {
        assert_eq!(Token::tokenize("+"), Some(Token::Operator(Operator::Add)));
        assert_eq!(
            Token::tokenize("100"),
            Some(Token::Operand(Number::NaturalNumber(BigInt::from(100))))
        );
        assert_eq!(
            Token::tokenize("3.14"),
            Some(Token::Operand(Number::DecimalNumber(BigRational::new(
                BigInt::from(157),
                BigInt::from(50)
            ))))
        );
        assert_eq!(Token::tokenize("("), Some(Token::Bracket(Bracket::Open)));
    }

    #[test]
    fn test_tokenize_vec_valid() {
        assert_eq!(Token::tokenize("+"), Some(Token::Operator(Operator::Add)));
        assert_eq!(
            Token::tokenize("100"),
            Some(Token::Operand(Number::NaturalNumber(BigInt::from(100))))
        );
        assert_eq!(
            Token::tokenize("3.14"),
            Some(Token::Operand(Number::DecimalNumber(BigRational::new(
                BigInt::from(157),
                BigInt::from(50)
            ))))
        );
        assert_eq!(Token::tokenize("("), Some(Token::Bracket(Bracket::Open)));
    }

    #[test]
    fn test_tryfrom_i32_out_of_range_is_err_not_panic() {
        // 2^100 is a valid NaturalNumber that does not fit in i32:
        // the conversion must return Err, never panic.
        let big = Number::NaturalNumber(BigInt::from(2).pow(100));
        assert!(i32::try_from(big).is_err());
    }

    #[test]
    fn test_tryfrom_i64_in_range_ok() {
        let n = Number::NaturalNumber(BigInt::from(3_265_920));
        assert_eq!(i64::try_from(n).unwrap(), 3_265_920_i64);
    }

    #[test]
    fn test_decimal_to_bigint_is_exact_for_large_values() {
        // f64 cannot represent 10^30 + 1 exactly, so a round-trip through f64
        // would lose the +1. Exact conversion via to_integer() must preserve it.
        let big = BigInt::from(10).pow(30) + BigInt::from(1);
        let n = Number::DecimalNumber(BigRational::from_integer(big.clone()));
        assert_eq!(BigInt::from(n), big);
    }

    #[test]
    fn test_decimal_to_bigint_truncates_toward_zero() {
        let pos = Number::DecimalNumber(BigRational::new(BigInt::from(7), BigInt::from(2)));
        assert_eq!(BigInt::from(pos), BigInt::from(3));
        let neg = Number::DecimalNumber(BigRational::new(BigInt::from(-7), BigInt::from(2)));
        assert_eq!(BigInt::from(neg), BigInt::from(-3));
    }

    #[test]
    fn test_tryfrom_f64_ok_and_overflow_is_err() {
        let half = Number::DecimalNumber(BigRational::new(BigInt::from(1), BigInt::from(2)));
        assert!((f64::try_from(half).unwrap() - 0.5_f64).abs() < f64::EPSILON);
        // 10^400 exceeds f64::MAX: must error, not silently become infinity.
        let huge = Number::NaturalNumber(BigInt::from(10).pow(400));
        assert!(f64::try_from(huge).is_err());
    }

    #[test]
    fn test_operator_priority() {
        assert_eq!(
            Token::operator_priority(Token::Operator(Operator::Add)),
            (1, Associate::LeftAssociative)
        );
        assert_eq!(
            Token::operator_priority(Token::Operator(Operator::Sub)),
            (1, Associate::LeftAssociative)
        );
        assert_eq!(
            Token::operator_priority(Token::Operator(Operator::Mul)),
            (2, Associate::LeftAssociative)
        );
        assert_eq!(
            Token::operator_priority(Token::Operator(Operator::Div)),
            (2, Associate::LeftAssociative)
        );
        assert_eq!(
            Token::operator_priority(Token::Operator(Operator::Pow)),
            (3, Associate::RightAssociative)
        );
        assert_eq!(
            Token::operator_priority(Token::Operator(Operator::Une)),
            (4, Associate::RightAssociative)
        );
        assert_eq!(
            Token::operator_priority(Token::Operator(Operator::Fac)),
            (5, Associate::LeftAssociative)
        );
    }

    #[test]
    fn test_operator_priority_for_assignment() {
        assert_eq!(
            Token::operator_priority(Token::Operator(Operator::Eql)),
            (0, Associate::RightAssociative)
        );
    }

    #[test]
    fn test_tokenize_edge_cases() {
        assert_eq!(Token::tokenize(""), None);
        assert_eq!(Token::tokenize("["), Some(Token::Bracket(Bracket::Open)));
        assert_eq!(Token::tokenize("]"), Some(Token::Bracket(Bracket::Close)));
        assert_eq!(Token::tokenize(";"), Some(Token::SemiColon));
        assert_eq!(Token::tokenize(","), Some(Token::Comma));
        assert_eq!(Token::tokenize("×"), Some(Token::Operator(Operator::Mul)));
        assert_eq!(Token::tokenize("÷"), Some(Token::Operator(Operator::Div)));
        assert_eq!(Token::tokenize("foo"), Some(Token::Variable("foo")));
    }

    #[test]
    fn test_tokenize_functions_are_case_insensitive() {
        assert_eq!(
            Token::tokenize("SIN"),
            Some(Token::Function(MathFunction::Sin))
        );
        assert_eq!(
            Token::tokenize("Cos"),
            Some(Token::Function(MathFunction::Cos))
        );
        assert_eq!(
            Token::tokenize("log10"),
            Some(Token::Function(MathFunction::Log))
        );
    }

    #[test]
    fn test_parse_decimal_literal_variants() {
        assert_eq!(
            parse_decimal_literal(".5"),
            Some(BigRational::new(BigInt::from(1), BigInt::from(2)))
        );
        assert_eq!(
            parse_decimal_literal("1."),
            Some(BigRational::from_integer(BigInt::from(1)))
        );
        assert_eq!(
            parse_decimal_literal("3.14"),
            Some(BigRational::new(BigInt::from(157), BigInt::from(50)))
        );
        assert_eq!(
            parse_decimal_literal("0.001"),
            Some(BigRational::new(BigInt::from(1), BigInt::from(1000)))
        );
        // a token without a '.' is not a decimal literal
        assert_eq!(parse_decimal_literal("42"), None);
    }

    #[test]
    fn test_number_display() {
        assert_eq!(Number::NaturalNumber(BigInt::from(5)).to_string(), "5");
        // a rational that reduces to a whole number prints as an integer
        assert_eq!(
            Number::DecimalNumber(BigRational::new(BigInt::from(4), BigInt::from(2))).to_string(),
            "2"
        );
        assert_eq!(
            Number::DecimalNumber(BigRational::new(BigInt::from(1), BigInt::from(2))).to_string(),
            "0.5"
        );
        // 1/3 is not a finite decimal, so it is rendered via its f64 approximation
        let third = Number::DecimalNumber(BigRational::new(BigInt::from(1), BigInt::from(3)));
        assert_eq!(third.to_string(), format!("{}", 1.0_f64 / 3.0));
    }

    #[test]
    fn test_conversion_error_reports_target_type() {
        let big = Number::NaturalNumber(BigInt::from(2).pow(100));
        let msg = i32::try_from(big).unwrap_err().to_string();
        assert!(msg.contains("i32"), "message was: {msg}");
        assert!(msg.contains("out of range"), "message was: {msg}");
    }

    #[test]
    fn test_tryfrom_ok_paths() {
        assert_eq!(
            i32::try_from(Number::NaturalNumber(BigInt::from(42))).unwrap(),
            42_i32
        );
        // a decimal is truncated toward zero before the range check
        assert_eq!(
            i32::try_from(Number::DecimalNumber(BigRational::new(
                BigInt::from(7),
                BigInt::from(2)
            )))
            .unwrap(),
            3_i32
        );
        assert_eq!(
            i128::try_from(Number::NaturalNumber(BigInt::from(2).pow(70))).unwrap(),
            1_180_591_620_717_411_303_424_i128
        );
        assert!(
            (f64::try_from(Number::NaturalNumber(BigInt::from(10))).unwrap() - 10.0).abs()
                < f64::EPSILON
        );
    }
}