ctb_formats_math/
parsing.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Mathematical expression and numeric string tokenization, analysis, and parsing.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::{Result, ensure};
30use malachite::base::num::arithmetic::traits::UnsignedAbs;
31use malachite::base::num::basic::traits::Zero;
32use malachite::base::num::conversion::traits::RoundingFrom;
33use malachite::base::rounding_modes::RoundingMode;
34use malachite::{Integer, Natural, Rational};
35
36use crate::base::{Base, format_natural, parse_natural};
37use crate::calculator_classic::{CONST_E, CONST_PI, divide, power};
38
39/// Returns the numerator and denominator for Unicode vulgar fraction characters.
40#[must_use]
41pub fn unicode_vulgar_fraction(c: char) -> Option<(u64, u64)> {
42    match c {
43        '↉' => Some((0, 3)),
44        '½' => Some((1, 2)),
45        '⅓' => Some((1, 3)),
46        '⅔' => Some((2, 3)),
47        '¼' => Some((1, 4)),
48        '¾' => Some((3, 4)),
49        '⅕' => Some((1, 5)),
50        '⅖' => Some((2, 5)),
51        '⅗' => Some((3, 5)),
52        '⅘' => Some((4, 5)),
53        '⅙' => Some((1, 6)),
54        '⅚' => Some((5, 6)),
55        '⅛' => Some((1, 8)),
56        '⅜' => Some((3, 8)),
57        '⅝' => Some((5, 8)),
58        '⅞' => Some((7, 8)),
59        '⅐' => Some((1, 7)),
60        '⅑' => Some((1, 9)),
61        '⅒' => Some((1, 10)),
62        _ => None,
63    }
64}
65
66/// The semantic value of a parsed number or mathematical constant.
67#[derive(Debug, Clone, Eq)]
68pub enum NumberValue {
69    /// Exact rational value.
70    Rational(Rational),
71    /// Named constant $\pi$.
72    Pi,
73    /// Named constant $e$ (Euler's number).
74    E,
75    /// Imaginary unit with rational coefficient: $k \cdot i$.
76    Imaginary(Rational),
77    /// Imaginary unit constant $i$.
78    ImaginaryI,
79    /// Positive infinity $\infty$.
80    Infinity,
81    /// Negative infinity $-\infty$.
82    NegativeInfinity,
83}
84
85impl PartialEq for NumberValue {
86    fn eq(&self, other: &Self) -> bool {
87        match (self, other) {
88            (Self::Rational(a), Self::Rational(b)) => a == b,
89            (Self::Pi, Self::Pi) | (Self::E, Self::E) => true,
90            (Self::Infinity, Self::Infinity)
91            | (Self::NegativeInfinity, Self::NegativeInfinity) => true,
92            (Self::ImaginaryI, Self::ImaginaryI) => true,
93            (Self::Imaginary(a), Self::Imaginary(b)) => a == b,
94            (Self::ImaginaryI, Self::Imaginary(b))
95            | (Self::Imaginary(b), Self::ImaginaryI) => {
96                b == &Rational::from(1u8)
97            }
98            _ => false,
99        }
100    }
101}
102
103impl std::ops::Mul<i64> for NumberValue {
104    type Output = Self;
105
106    #[expect(
107        clippy::arithmetic_side_effects,
108        reason = "Rational is arbitrary-precision"
109    )]
110    fn mul(self, rhs: i64) -> Self {
111        match self {
112            Self::ImaginaryI => {
113                if rhs == 1 {
114                    Self::ImaginaryI
115                } else {
116                    Self::Imaginary(Rational::from(rhs))
117                }
118            }
119            Self::Imaginary(r) => Self::Imaginary(r * Rational::from(rhs)),
120            Self::Infinity => {
121                if rhs < 0 {
122                    Self::NegativeInfinity
123                } else {
124                    Self::Infinity
125                }
126            }
127            Self::NegativeInfinity => {
128                if rhs < 0 {
129                    Self::Infinity
130                } else {
131                    Self::NegativeInfinity
132                }
133            }
134            Self::Rational(r) => Self::Rational(r * Rational::from(rhs)),
135            Self::Pi | Self::E => self,
136        }
137    }
138}
139
140impl std::ops::Mul<i32> for NumberValue {
141    type Output = Self;
142
143    #[expect(
144        clippy::arithmetic_side_effects,
145        reason = "Rational is arbitrary-precision"
146    )]
147    fn mul(self, rhs: i32) -> Self {
148        self * i64::from(rhs)
149    }
150}
151
152impl NumberValue {
153    /// Converts this number value to an `f64`.
154    #[must_use]
155    pub fn to_f64(&self) -> f64 {
156        match self {
157            Self::Rational(r) => f64::rounding_from(r, RoundingMode::Nearest).0,
158            Self::Pi => CONST_PI,
159            Self::E => CONST_E,
160            Self::Infinity => f64::INFINITY,
161            Self::NegativeInfinity => f64::NEG_INFINITY,
162            Self::ImaginaryI | Self::Imaginary(_) => f64::NAN,
163        }
164    }
165}
166
167/// Represents a parsed numerical value with formatting metadata and optional units.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct ParsedNumber {
170    /// Numerical value or named symbolic constant.
171    pub value: NumberValue,
172    /// Number base in which the number was parsed.
173    pub base: Base,
174    /// Indicates whether the input had an explicit negative sign.
175    pub is_negative: bool,
176    /// Width of the integer digits in the original input string.
177    pub int_width: usize,
178    /// Number of fractional digits after decimal point in the original input string.
179    pub frac_len: usize,
180    /// Indicates whether a decimal point was explicitly present in the input.
181    pub has_decimal: bool,
182    /// Optional unit suffix (e.g. "lb", "g", "oz"), if present.
183    pub unit_suffix: Option<String>,
184}
185
186impl ParsedNumber {
187    /// Parses a string into a [`ParsedNumber`], supporting integers, fixed-point decimals,
188    /// mixed numbers, Unicode vulgar fractions (`½`, `¾`), ASCII fractions (`3 1/2`),
189    /// named constants (`pi`, `e`, `i`), and optional unit suffixes.
190    #[expect(
191        clippy::arithmetic_side_effects,
192        reason = "Natural, Integer, and Rational are arbitrary-precision"
193    )]
194    pub fn parse(s: &str, base: Base) -> Result<Self> {
195        let trimmed = s.trim();
196        ensure!(!trimmed.is_empty(), "Cannot parse empty number string");
197
198        let (is_negative, s_no_sign) =
199            if let Some(stripped) = trimmed.strip_prefix('-') {
200                (true, stripped.trim_start())
201            } else if let Some(stripped) = trimmed.strip_prefix('+') {
202                (false, stripped.trim_start())
203            } else {
204                (false, trimmed)
205            };
206
207        ensure!(
208            !s_no_sign.is_empty(),
209            "Cannot parse empty number string after sign"
210        );
211
212        if s_no_sign.eq_ignore_ascii_case("pi") || s_no_sign == "π" {
213            return Ok(Self {
214                value: NumberValue::Pi,
215                base,
216                is_negative,
217                int_width: 0,
218                frac_len: 0,
219                has_decimal: false,
220                unit_suffix: None,
221            });
222        }
223        if s_no_sign.eq_ignore_ascii_case("e") {
224            return Ok(Self {
225                value: NumberValue::E,
226                base,
227                is_negative,
228                int_width: 0,
229                frac_len: 0,
230                has_decimal: false,
231                unit_suffix: None,
232            });
233        }
234        if s_no_sign == "∞"
235            || s_no_sign.eq_ignore_ascii_case("inf")
236            || s_no_sign.eq_ignore_ascii_case("infinity")
237        {
238            let val = if is_negative {
239                NumberValue::NegativeInfinity
240            } else {
241                NumberValue::Infinity
242            };
243            return Ok(Self {
244                value: val,
245                base,
246                is_negative,
247                int_width: 0,
248                frac_len: 0,
249                has_decimal: false,
250                unit_suffix: None,
251            });
252        }
253        if s_no_sign.eq_ignore_ascii_case("i") {
254            let val = if is_negative {
255                NumberValue::Imaginary(Rational::from(-1i8))
256            } else {
257                NumberValue::ImaginaryI
258            };
259            return Ok(Self {
260                value: val,
261                base,
262                is_negative,
263                int_width: 0,
264                frac_len: 0,
265                has_decimal: false,
266                unit_suffix: None,
267            });
268        }
269
270        // Check for imaginary number with coefficient like "5i", "-5i"
271        if base == Base::Decimal
272            && let Some(coeff_str) = s_no_sign.strip_suffix(['i', 'I'])
273        {
274            let trimmed_coeff = coeff_str.trim();
275            if !trimmed_coeff.is_empty() {
276                let parsed_coeff = Self::parse(trimmed_coeff, base)?;
277                if let Some(r) = parsed_coeff.to_rational() {
278                    let signed_r =
279                        if is_negative { -r.clone() } else { r.clone() };
280                    return Ok(Self {
281                        value: NumberValue::Imaginary(signed_r),
282                        base,
283                        is_negative,
284                        int_width: parsed_coeff.int_width,
285                        frac_len: parsed_coeff.frac_len,
286                        has_decimal: parsed_coeff.has_decimal,
287                        unit_suffix: None,
288                    });
289                }
290            }
291        }
292
293        // Separate attached or whitespace-delimited unit suffixes if present
294        let (num_part_raw, unit_suffix) = separate_unit_suffix(s_no_sign, base);
295        let num_part = match base {
296            // Reason for fallback: numbers without base prefix retain original string representation.
297            Base::Hex => num_part_raw
298                .strip_prefix("0x")
299                .or_else(|| num_part_raw.strip_prefix("0X"))
300                .unwrap_or(num_part_raw),
301            // Reason for fallback: numbers without base prefix retain original string representation.
302            Base::Binary => num_part_raw
303                .strip_prefix("0b")
304                .or_else(|| num_part_raw.strip_prefix("0B"))
305                .unwrap_or(num_part_raw),
306            // Reason for fallback: numbers without base prefix retain original string representation.
307            Base::Octal => num_part_raw
308                .strip_prefix("0o")
309                .or_else(|| num_part_raw.strip_prefix("0O"))
310                .unwrap_or(num_part_raw),
311            _ => num_part_raw,
312        };
313
314        let int_width;
315        let mut frac_len = 0usize;
316        let mut has_decimal = false;
317
318        // Check for Unicode vulgar fraction (e.g. "3½", "½")
319        let mut vulgar_frac = None;
320        for (i, c) in num_part.char_indices() {
321            if let Some(frac) = unicode_vulgar_fraction(c) {
322                vulgar_frac = Some((i, frac));
323                break;
324            }
325        }
326
327        let rational_mag: Rational = if let Some((idx, (num, den))) =
328            vulgar_frac
329        {
330            // Reason for fallback: vulgar fraction starting at index 0 has empty integer prefix.
331            let prefix = num_part.get(..idx).unwrap_or("").trim();
332            let frac_rat =
333                Rational::from_naturals(Natural::from(num), Natural::from(den));
334            if prefix.is_empty() {
335                int_width = 0;
336                frac_rat
337            } else {
338                let int_nat = parse_natural(prefix, base)?;
339                int_width = prefix.len();
340                Rational::from(int_nat) + frac_rat
341            }
342        } else if let Some((prefix, den_str)) = num_part.split_once('⅟') {
343            // Fraction numerator one ⅟ (e.g. "⅟2" or "3 ⅟2")
344            let den_nat = parse_natural(den_str.trim(), base)?;
345            ensure!(
346                den_nat > Natural::ZERO,
347                "Fraction denominator cannot be zero"
348            );
349            let frac_rat = Rational::from_naturals(Natural::from(1u8), den_nat);
350            let trimmed_prefix = prefix.trim();
351            if trimmed_prefix.is_empty() {
352                int_width = 0;
353                frac_rat
354            } else {
355                let int_nat = parse_natural(trimmed_prefix, base)?;
356                int_width = trimmed_prefix.len();
357                Rational::from(int_nat) + frac_rat
358            }
359        } else if base.radix() != 64
360            && (num_part.contains('/') || num_part.contains('⁄'))
361        {
362            let (num_str, den_str) =
363                if let Some(parts) = num_part.split_once('⁄') {
364                    parts
365                } else if let Some(parts) = num_part.split_once('/') {
366                    parts
367                } else {
368                    unreachable!("contains verified");
369                };
370
371            let den_nat = parse_natural(den_str.trim(), base)?;
372            ensure!(
373                den_nat > Natural::ZERO,
374                "Fraction denominator cannot be zero"
375            );
376
377            let trimmed_num = num_str.trim();
378            if let Some((int_str, frac_num_str)) =
379                trimmed_num.rsplit_once([' ', '-'])
380            {
381                let int_nat = parse_natural(int_str.trim(), base)?;
382                let f_num_nat = parse_natural(frac_num_str.trim(), base)?;
383                int_width = int_str.trim().len();
384                Rational::from(int_nat)
385                    + Rational::from_naturals(f_num_nat, den_nat)
386            } else {
387                let f_num_nat = parse_natural(trimmed_num, base)?;
388                int_width = 0;
389                Rational::from_naturals(f_num_nat, den_nat)
390            }
391        } else if let Some((int_part, frac_part)) = num_part.split_once('.') {
392            // Fixed-point decimal
393            has_decimal = true;
394            int_width = int_part.len();
395            frac_len = frac_part.len();
396
397            let int_nat = if int_part.is_empty() {
398                Natural::ZERO
399            } else {
400                parse_natural(int_part, base)?
401            };
402
403            let frac_nat = if frac_part.is_empty() {
404                Natural::ZERO
405            } else {
406                parse_natural(frac_part, base)?
407            };
408
409            let radix_nat = Natural::from(base.radix());
410            let mut scale_pow = Natural::from(1u8);
411            for _ in 0..frac_len {
412                scale_pow *= &radix_nat;
413            }
414
415            let fraction_rational =
416                Rational::from_naturals(frac_nat, scale_pow);
417            Rational::from(int_nat) + fraction_rational
418        } else {
419            // Pure integer
420            int_width = num_part.len();
421            let int_nat = parse_natural(num_part, base)?;
422            Rational::from(int_nat)
423        };
424
425        let final_rat = if is_negative {
426            -rational_mag
427        } else {
428            rational_mag
429        };
430
431        Ok(Self {
432            value: NumberValue::Rational(final_rat),
433            base,
434            is_negative,
435            int_width,
436            frac_len,
437            has_decimal,
438            unit_suffix,
439        })
440    }
441
442    /// Converts this parsed number to an `f64`.
443    #[must_use]
444    pub fn to_f64(&self) -> f64 {
445        let val = self.value.to_f64();
446        if self.unit_suffix.as_deref() == Some("%") {
447            val / 100.0
448        } else {
449            val
450        }
451    }
452
453    /// Scales the number value by $base^{dec\_places}$ and returns the resulting exact signed [`Integer`].
454    #[expect(
455        clippy::arithmetic_side_effects,
456        reason = "Natural, Integer, and Rational are arbitrary-precision"
457    )]
458    pub fn to_scaled_integer(&self, dec_places: usize) -> Result<Integer> {
459        match &self.value {
460            NumberValue::Rational(rat) => {
461                let radix_nat = Natural::from(self.base.radix());
462                let mut scale_pow = Natural::from(1u8);
463                for _ in 0..dec_places {
464                    scale_pow *= &radix_nat;
465                }
466                let is_neg = rat < &Rational::ZERO;
467                let abs_rat = if is_neg { -rat.clone() } else { rat.clone() };
468                let scaled = abs_rat * Rational::from(scale_pow);
469                let (num, den) = scaled.into_numerator_and_denominator();
470                let int_nat = &num / &den;
471                let int_val = Integer::from(int_nat);
472                if is_neg { Ok(-int_val) } else { Ok(int_val) }
473            }
474            _ => {
475                bail!("Cannot convert symbolic constant to scaled integer")
476            }
477        }
478    }
479
480    /// Returns a reference to the exact rational value, if not a symbolic constant.
481    #[must_use]
482    pub fn to_rational(&self) -> Option<&Rational> {
483        match &self.value {
484            NumberValue::Rational(r) => Some(r),
485            _ => None,
486        }
487    }
488}
489
490/// Helper function to separate trailing unit identifiers from a numeric substring.
491fn separate_unit_suffix(s: &str, base: Base) -> (&str, Option<String>) {
492    if let Some((num, unit)) = s.rsplit_once(' ') {
493        let trimmed_unit = unit.trim();
494        let is_fraction_part = trimmed_unit.contains('/')
495            || trimmed_unit.contains('⁄')
496            || trimmed_unit.starts_with('⅟')
497            || trimmed_unit.chars().all(|c| {
498                c.is_ascii_digit() || unicode_vulgar_fraction(c).is_some()
499            });
500        if !trimmed_unit.is_empty() && !is_fraction_part {
501            return (num.trim(), Some(trimmed_unit.to_owned()));
502        }
503    }
504
505    if let Some(stripped) = s.strip_suffix('"') {
506        return (stripped.trim_end(), Some("\"".to_owned()));
507    }
508
509    if let Some(stripped) = s.strip_suffix('%') {
510        return (stripped.trim_end(), Some("%".to_owned()));
511    }
512
513    // Attached unit letters for Base10
514    if base == Base::Decimal {
515        let mut split_idx = s.len();
516        for (i, c) in s.char_indices().rev() {
517            if c.is_alphabetic() || c.is_ascii_digit() {
518                // Check if starting a unit like "mm2" or "lb"
519                if c.is_alphabetic() {
520                    split_idx = i;
521                }
522            } else {
523                break;
524            }
525        }
526        if split_idx > 0 && split_idx < s.len() {
527            let (num, unit) = s.split_at(split_idx);
528            // Don't split if it's purely digits or imaginary
529            if !num.is_empty() && unit != "i" && unit != "I" {
530                return (num.trim(), Some(unit.to_owned()));
531            }
532        }
533    }
534
535    (s, None)
536}
537
538/// Backward-compatible wrapper parsing a numeric string to `f64`.
539pub fn parse_number(s: &str) -> Result<f64> {
540    let parsed = ParsedNumber::parse(s, Base::Decimal)?;
541    Ok(parsed.to_f64())
542}
543
544/// Metadata regarding a parsed numeric input string.
545#[derive(Debug, Clone, PartialEq, Eq)]
546pub struct ParsedInput {
547    /// Width of the integer portion of the string.
548    pub int_width: usize,
549    /// Width of the fractional portion of the string.
550    pub frac_width: usize,
551    /// Indicates whether a decimal point was present in the input.
552    pub has_decimal: bool,
553    /// Number of fractional digits.
554    pub frac_len: usize,
555}
556
557/// Backward-compatible wrapper analyzing layout of a numeric string.
558#[must_use]
559pub fn analyze_input(s: &str) -> ParsedInput {
560    if let Ok(num) = ParsedNumber::parse(s, Base::Decimal) {
561        ParsedInput {
562            int_width: num.int_width,
563            frac_width: num.frac_len,
564            has_decimal: num.has_decimal,
565            frac_len: num.frac_len,
566        }
567    } else {
568        // Reason for fallback: unsigned numeric strings retain original representation.
569        let s_clean = s
570            .strip_prefix('+')
571            .or_else(|| s.strip_prefix('-'))
572            .unwrap_or(s);
573        if let Some((int_part, frac_part)) = s_clean.split_once('.') {
574            ParsedInput {
575                int_width: int_part.len(),
576                frac_width: frac_part.len(),
577                has_decimal: true,
578                frac_len: frac_part.len(),
579            }
580        } else {
581            ParsedInput {
582                int_width: s_clean.len(),
583                frac_width: 0,
584                has_decimal: false,
585                frac_len: 0,
586            }
587        }
588    }
589}
590
591/// Backward-compatible wrapper parsing a scaled number.
592pub fn parse_scaled(s: &str, base: Base, dec_places: usize) -> Result<Integer> {
593    let num = ParsedNumber::parse(s, base)?;
594    num.to_scaled_integer(dec_places)
595}
596
597/// Formats a scaled [`Integer`] back into a string in the given base, respecting
598/// decimal places, integer width, and fractional width.
599#[expect(
600    clippy::arithmetic_side_effects,
601    reason = "Natural is arbitrary-precision and cannot overflow"
602)]
603pub fn format_scaled(
604    val: &Integer,
605    base: Base,
606    dec_places: usize,
607    int_width: usize,
608    frac_width: usize,
609    has_decimal: bool,
610) -> Result<String> {
611    let is_negative = *val < Integer::ZERO;
612    let abs_nat = val.unsigned_abs();
613
614    let formatted_mag = if dec_places == 0 && !has_decimal {
615        format_natural(&abs_nat, base, int_width)?
616    } else {
617        let radix_nat = Natural::from(base.radix());
618        let mut scale_pow = Natural::from(1u8);
619        for _ in 0..dec_places {
620            scale_pow *= &radix_nat;
621        }
622
623        let int_part = &abs_nat / &scale_pow;
624        let frac_part = &abs_nat % &scale_pow;
625
626        let int_str = format_natural(&int_part, base, int_width)?;
627        let frac_str =
628            format_natural(&frac_part, base, frac_width.max(dec_places))?;
629        format!("{int_str}.{frac_str}")
630    };
631
632    if is_negative {
633        Ok(format!("-{formatted_mag}"))
634    } else {
635        Ok(formatted_mag)
636    }
637}
638
639/// Token representation in a mathematical expression.
640#[derive(Debug, Clone, PartialEq)]
641pub enum MathToken {
642    /// Parsed numeric literal or constant.
643    Number(ParsedNumber),
644    /// Addition operator `+`.
645    Plus,
646    /// Subtraction operator `-`.
647    Minus,
648    /// Multiplication operator `*`.
649    Multiply,
650    /// Division operator `/`.
651    Divide,
652    /// Integer division operator `\`.
653    IntDivide,
654    /// Exponentiation operator `^`.
655    Power,
656    /// Modulo operator `%` or `Mod`.
657    Modulo,
658    /// Left parenthesis `(`.
659    LParen,
660    /// Right parenthesis `)`.
661    RParen,
662}
663
664/// Tokenizes a mathematical expression string into a sequence of [`MathToken`]s.
665pub fn tokenize_expression(expr: &str) -> Result<Vec<MathToken>> {
666    let mut tokens = Vec::new();
667    let mut chars = expr.chars().peekable();
668    while let Some(&c) = chars.peek() {
669        if c.is_whitespace() {
670            chars.next();
671            continue;
672        }
673        if c.is_ascii_digit()
674            || c == '.'
675            || unicode_vulgar_fraction(c).is_some()
676            || c == '⅟'
677        {
678            let mut num_str = String::new();
679            while let Some(&nc) = chars.peek() {
680                if nc.is_ascii_digit()
681                    || nc == '.'
682                    || unicode_vulgar_fraction(nc).is_some()
683                    || nc == '⅟'
684                {
685                    num_str.push(nc);
686                    chars.next();
687                } else {
688                    break;
689                }
690            }
691            let parsed = ParsedNumber::parse(&num_str, Base::Decimal)?;
692            tokens.push(MathToken::Number(parsed));
693            continue;
694        }
695        if c.is_alphabetic() || c == 'π' || c == '∞' {
696            let mut word = String::new();
697            while let Some(&wc) = chars.peek() {
698                if wc.is_alphabetic() || wc == 'π' || wc == '∞' {
699                    word.push(wc);
700                    chars.next();
701                } else {
702                    break;
703                }
704            }
705            if word.eq_ignore_ascii_case("mod") {
706                tokens.push(MathToken::Modulo);
707            } else if let Ok(parsed) = ParsedNumber::parse(&word, Base::Decimal)
708            {
709                tokens.push(MathToken::Number(parsed));
710            } else {
711                bail!("Unknown identifier in expression: {word}");
712            }
713            continue;
714        }
715        match c {
716            '+' => {
717                tokens.push(MathToken::Plus);
718                chars.next();
719            }
720            '-' => {
721                tokens.push(MathToken::Minus);
722                chars.next();
723            }
724            '*' => {
725                tokens.push(MathToken::Multiply);
726                chars.next();
727            }
728            '/' => {
729                tokens.push(MathToken::Divide);
730                chars.next();
731            }
732            '\\' => {
733                tokens.push(MathToken::IntDivide);
734                chars.next();
735            }
736            '^' => {
737                tokens.push(MathToken::Power);
738                chars.next();
739            }
740            '%' => {
741                tokens.push(MathToken::Modulo);
742                chars.next();
743            }
744            '(' => {
745                tokens.push(MathToken::LParen);
746                chars.next();
747            }
748            ')' => {
749                tokens.push(MathToken::RParen);
750                chars.next();
751            }
752            _ => bail!("Unexpected character in expression: {c}"),
753        }
754    }
755    Ok(tokens)
756}
757
758/// Parses an expression with addition and subtraction.
759pub fn parse_expr(tokens: &[MathToken], pos: &mut usize) -> Result<f64> {
760    let mut left = parse_term(tokens, pos)?;
761    while let Some(tok) = tokens.get(*pos) {
762        match tok {
763            MathToken::Plus => {
764                *pos = pos.saturating_add(1);
765                let right = parse_term(tokens, pos)?;
766                left += right;
767            }
768            MathToken::Minus => {
769                *pos = pos.saturating_add(1);
770                let right = parse_term(tokens, pos)?;
771                left -= right;
772            }
773            _ => break,
774        }
775    }
776    Ok(left)
777}
778
779/// Parses a term with multiplication, division, integer division, and modulo.
780pub fn parse_term(tokens: &[MathToken], pos: &mut usize) -> Result<f64> {
781    let mut left = parse_power(tokens, pos)?;
782    while let Some(tok) = tokens.get(*pos) {
783        match tok {
784            MathToken::Multiply => {
785                *pos = pos.saturating_add(1);
786                let right = parse_power(tokens, pos)?;
787                left *= right;
788            }
789            MathToken::Divide => {
790                *pos = pos.saturating_add(1);
791                let right = parse_power(tokens, pos)?;
792                left = divide(left, right)?;
793            }
794            MathToken::IntDivide => {
795                *pos = pos.saturating_add(1);
796                let right = parse_power(tokens, pos)?;
797                if right == 0.0 {
798                    bail!("Division by zero");
799                }
800                left = (left / right).trunc();
801            }
802            MathToken::Modulo => {
803                *pos = pos.saturating_add(1);
804                let right = parse_power(tokens, pos)?;
805                if right == 0.0 {
806                    bail!("Modulo by zero");
807                }
808                left %= right;
809            }
810            _ => break,
811        }
812    }
813    Ok(left)
814}
815
816/// Parses exponentiation operations (right-associative).
817pub fn parse_power(tokens: &[MathToken], pos: &mut usize) -> Result<f64> {
818    let left = parse_unary(tokens, pos)?;
819    if let Some(MathToken::Power) = tokens.get(*pos) {
820        *pos = pos.saturating_add(1);
821        let right = parse_power(tokens, pos)?;
822        Ok(power(left, right))
823    } else {
824        Ok(left)
825    }
826}
827
828/// Parses unary operators (`+` or `-`).
829pub fn parse_unary(tokens: &[MathToken], pos: &mut usize) -> Result<f64> {
830    if let Some(tok) = tokens.get(*pos) {
831        match tok {
832            MathToken::Plus => {
833                *pos = pos.saturating_add(1);
834                parse_unary(tokens, pos)
835            }
836            MathToken::Minus => {
837                *pos = pos.saturating_add(1);
838                let val = parse_unary(tokens, pos)?;
839                Ok(-val)
840            }
841            _ => parse_primary(tokens, pos),
842        }
843    } else {
844        bail!("Unexpected end of expression");
845    }
846}
847
848/// Parses primary tokens (numbers or parenthesized expressions).
849pub fn parse_primary(tokens: &[MathToken], pos: &mut usize) -> Result<f64> {
850    let Some(tok) = tokens.get(*pos) else {
851        bail!("Unexpected end of expression");
852    };
853    match tok {
854        MathToken::Number(n) => {
855            *pos = pos.saturating_add(1);
856            Ok(n.to_f64())
857        }
858        MathToken::LParen => {
859            *pos = pos.saturating_add(1);
860            let val = parse_expr(tokens, pos)?;
861            let Some(MathToken::RParen) = tokens.get(*pos) else {
862                bail!("Missing closing parenthesis");
863            };
864            *pos = pos.saturating_add(1);
865            Ok(val)
866        }
867        _ => bail!("Unexpected token in expression"),
868    }
869}
870
871/// Evaluates a math expression string with standard operator precedence.
872pub fn evaluate_expression(expr: &str) -> Result<f64> {
873    let tokens = tokenize_expression(expr)?;
874    let mut pos = 0usize;
875    let result = parse_expr(&tokens, &mut pos)?;
876    if pos < tokens.len() {
877        bail!("Unexpected trailing token in expression");
878    }
879    Ok(result)
880}
881
882/// Result of identifying a mathematical expression, relation, or numeral format.
883#[derive(Debug, Clone, PartialEq, Eq)]
884pub struct MathDetection {
885    /// Format identifier (e.g. `FormatId::Equation`, `FormatId::ArithmeticExpression`, etc.).
886    pub format_id: FormatId,
887    /// Human-readable format description.
888    pub description: String,
889}
890
891/// Detects whether `s` represents a numeric or base numeral format (Integer,
892/// Float, `HexadecimalNumeral`, `BinaryNumeral`, or `OctalNumeral`).
893#[must_use]
894pub fn detect_numeric_format(s: &str) -> Option<MathDetection> {
895    let trimmed = s.trim();
896    if trimmed.is_empty() {
897        return None;
898    }
899
900    // 1. Hexadecimal numeral prefix `0x` / `0X`
901    if let Some(rest) = trimmed
902        .strip_prefix("0x")
903        .or_else(|| trimmed.strip_prefix("0X"))
904    {
905        if !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_hexdigit()) {
906            return Some(MathDetection {
907                format_id: FormatId::HexadecimalNumeral,
908                description: "Hexadecimal numeral (base 16)".to_string(),
909            });
910        }
911    }
912
913    // 2. Binary numeral prefix `0b` / `0B`
914    if let Some(rest) = trimmed
915        .strip_prefix("0b")
916        .or_else(|| trimmed.strip_prefix("0B"))
917    {
918        if !rest.is_empty() && rest.bytes().all(|b| b == b'0' || b == b'1') {
919            return Some(MathDetection {
920                format_id: FormatId::BinaryNumeral,
921                description: "Binary numeral (base 2)".to_string(),
922            });
923        }
924    }
925
926    // 3. Octal numeral prefix `0o` / `0O`
927    if let Some(rest) = trimmed
928        .strip_prefix("0o")
929        .or_else(|| trimmed.strip_prefix("0O"))
930    {
931        if !rest.is_empty() && rest.bytes().all(|b| (b'0'..=b'7').contains(&b))
932        {
933            return Some(MathDetection {
934                format_id: FormatId::OctalNumeral,
935                description: "Octal numeral (base 8)".to_string(),
936            });
937        }
938    }
939
940    // Reason for fallback: if no leading sign is present, the trimmed string is already unsigned
941    let clean = trimmed
942        .strip_prefix('+')
943        .or_else(|| trimmed.strip_prefix('-'))
944        .unwrap_or(trimmed);
945
946    // 4. Integer (strictly digits)
947    if !clean.is_empty() && clean.bytes().all(|b| b.is_ascii_digit()) {
948        return Some(MathDetection {
949            format_id: FormatId::Integer,
950            description: "Integer number".to_string(),
951        });
952    }
953
954    // 5. Floating-point number (has decimal point or exponent notation)
955    if clean.contains('.') || clean.contains('e') || clean.contains('E') {
956        if clean.parse::<f64>().is_ok() {
957            return Some(MathDetection {
958                format_id: FormatId::Float,
959                description: "Floating-point number".to_string(),
960            });
961        }
962    }
963
964    None
965}
966
967/// Helper checking if a string looks like code or config assignment rather than math.
968fn looks_like_code_or_config(s: &str) -> bool {
969    let lower = s.to_ascii_lowercase();
970    lower.starts_with("let ")
971        || lower.starts_with("const ")
972        || lower.starts_with("var ")
973        || lower.starts_with("fn ")
974        || lower.starts_with("def ")
975        || lower.starts_with("import ")
976        || lower.starts_with("#define ")
977        || lower.starts_with("#!")
978        || lower.starts_with("//")
979        || lower.contains("/*")
980        || lower.contains("*/")
981        || lower.contains("<?xml")
982        || lower.contains("<html")
983        || lower.starts_with("md5 (")
984        || lower.starts_with("sha256 (")
985        || lower.starts_with("sha1 (")
986}
987
988/// Known mathematical identifier tokens, functions, and standard units.
989fn is_math_ident(w: &str) -> bool {
990    let lower = w.to_ascii_lowercase();
991    matches!(
992        lower.as_str(),
993        "x" | "y"
994            | "z"
995            | "a"
996            | "b"
997            | "c"
998            | "d"
999            | "f"
1000            | "g"
1001            | "h"
1002            | "k"
1003            | "m"
1004            | "n"
1005            | "p"
1006            | "q"
1007            | "r"
1008            | "s"
1009            | "t"
1010            | "u"
1011            | "v"
1012            | "w"
1013            | "sin"
1014            | "cos"
1015            | "tan"
1016            | "cot"
1017            | "sec"
1018            | "csc"
1019            | "arcsin"
1020            | "arccos"
1021            | "arctan"
1022            | "sinh"
1023            | "cosh"
1024            | "tanh"
1025            | "log"
1026            | "ln"
1027            | "exp"
1028            | "sqrt"
1029            | "pi"
1030            | "theta"
1031            | "phi"
1032            | "psi"
1033            | "omega"
1034            | "alpha"
1035            | "beta"
1036            | "gamma"
1037            | "delta"
1038            | "sigma"
1039            | "lambda"
1040            | "mu"
1041            | "mod"
1042            | "solve"
1043            | "for"
1044            | "oz"
1045            | "lb"
1046            | "kg"
1047            | "cm"
1048            | "mm"
1049            | "in"
1050            | "ft"
1051            | "yd"
1052            | "min"
1053            | "hr"
1054    )
1055}
1056
1057fn is_word_non_math(w: &str) -> bool {
1058    if w.is_empty() {
1059        return false;
1060    }
1061    let lower = w.to_ascii_lowercase();
1062    if is_math_ident(&lower) {
1063        return false;
1064    }
1065    // Words of length >= 4 that are not math identifiers are non-math words
1066    if w.len() >= 4 {
1067        return true;
1068    }
1069    // Common 2-3 char natural language words and paths
1070    matches!(
1071        lower.as_str(),
1072        "is" | "an"
1073            | "at"
1074            | "by"
1075            | "to"
1076            | "in"
1077            | "on"
1078            | "or"
1079            | "the"
1080            | "and"
1081            | "not"
1082            | "all"
1083            | "any"
1084            | "cmd"
1085            | "usr"
1086            | "bin"
1087            | "who"
1088            | "how"
1089            | "what"
1090    )
1091}
1092
1093/// Checks if string contains words that indicate natural language or code rather than math.
1094fn has_non_math_words(s: &str) -> bool {
1095    let mut current_word = String::new();
1096    for c in s.chars() {
1097        if c.is_ascii_alphabetic() {
1098            current_word.push(c);
1099        } else {
1100            if is_word_non_math(&current_word) {
1101                return true;
1102            }
1103            current_word.clear();
1104        }
1105    }
1106    if is_word_non_math(&current_word) {
1107        return true;
1108    }
1109    false
1110}
1111
1112/// Detects whether `s` represents a mathematical expression (arithmetic,
1113/// symbolic) or relation (equation, inequality, approximation, system).
1114#[must_use]
1115pub fn detect_math_format(s: &str) -> Option<MathDetection> {
1116    let trimmed = s.trim();
1117    if trimmed.is_empty()
1118        || looks_like_code_or_config(trimmed)
1119        || has_non_math_words(trimmed)
1120    {
1121        return None;
1122    }
1123
1124    // Pure numbers are handled by detect_numeric_format, not math expressions/relations
1125    if detect_numeric_format(trimmed).is_some() {
1126        return None;
1127    }
1128
1129    // 1. Equation system: multiple clauses separated by ';' or newlines
1130    let segments: Vec<&str> = trimmed
1131        .split([';', '\n'])
1132        .map(str::trim)
1133        .filter(|seg| !seg.is_empty())
1134        .collect();
1135
1136    if trimmed.contains('\n') || segments.len() > 1 {
1137        let all_relations = segments.iter().all(|seg| {
1138            seg.contains('=')
1139                || seg.contains('<')
1140                || seg.contains('>')
1141                || seg.contains("!=")
1142                || seg.contains('≠')
1143                || seg.contains("~=")
1144                || seg.contains('≈')
1145        });
1146        if all_relations && segments.len() > 1 {
1147            return Some(MathDetection {
1148                format_id: FormatId::EquationSystem,
1149                description: "System of mathematical equations/relations"
1150                    .to_string(),
1151            });
1152        }
1153        if trimmed.contains('\n') {
1154            return None;
1155        }
1156    }
1157
1158    // 2. Approximation predicates: ~=, ≈, ≅
1159    if trimmed.contains("~=") || trimmed.contains('≈') || trimmed.contains('≅')
1160    {
1161        let (left, right) = if let Some((l, r)) = trimmed.split_once("~=") {
1162            (l.trim(), r.trim())
1163        } else if let Some((l, r)) = trimmed.split_once('≈') {
1164            (l.trim(), r.trim())
1165        } else if let Some((l, r)) = trimmed.split_once('≅') {
1166            (l.trim(), r.trim())
1167        } else {
1168            ("", "")
1169        };
1170        if !left.is_empty() && !right.is_empty() {
1171            return Some(MathDetection {
1172                format_id: FormatId::Approximation,
1173                description: "Mathematical approximation".to_string(),
1174            });
1175        }
1176    }
1177
1178    // 3. Inequality predicates: <=, >=, !=, ≠, ≤, ≥, <, >
1179    let has_inequality_op = trimmed.contains("<=")
1180        || trimmed.contains(">=")
1181        || trimmed.contains("!=")
1182        || trimmed.contains('≠')
1183        || trimmed.contains('≤')
1184        || trimmed.contains('≥')
1185        || (trimmed.contains('<')
1186            && !trimmed.contains("</")
1187            && !trimmed.contains("<xml"))
1188        || (trimmed.contains('>')
1189            && !trimmed.contains("->")
1190            && !trimmed.contains("=>"));
1191
1192    if has_inequality_op {
1193        let op_match = if trimmed.contains("<=") {
1194            trimmed.split_once("<=")
1195        } else if trimmed.contains(">=") {
1196            trimmed.split_once(">=")
1197        } else if trimmed.contains("!=") {
1198            trimmed.split_once("!=")
1199        } else if trimmed.contains('≠') {
1200            trimmed.split_once('≠')
1201        } else if trimmed.contains('≤') {
1202            trimmed.split_once('≤')
1203        } else if trimmed.contains('≥') {
1204            trimmed.split_once('≥')
1205        } else if trimmed.contains('<') {
1206            trimmed.split_once('<')
1207        } else {
1208            trimmed.split_once('>')
1209        };
1210
1211        if let Some((left, right)) = op_match {
1212            let (l_clean, r_clean) = (left.trim(), right.trim());
1213            if !l_clean.is_empty() && !r_clean.is_empty() {
1214                return Some(MathDetection {
1215                    format_id: FormatId::Inequality,
1216                    description: "Mathematical inequality".to_string(),
1217                });
1218            }
1219        }
1220    }
1221
1222    // 4. Equation predicates: `=` or `==`
1223    if (trimmed.contains('=') || trimmed.contains("=="))
1224        && !trimmed.starts_with('=')
1225    {
1226        let op_match =
1227            trimmed.split_once("==").or_else(|| trimmed.split_once('='));
1228
1229        if let Some((left, right)) = op_match {
1230            let (l, r) = (left.trim(), right.trim());
1231            // Filter out shell assignments like `FOO=bar` where left has no spaces and right has no spaces
1232            let is_shell_assign = !trimmed.contains(' ')
1233                && !l.is_empty()
1234                && l.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
1235            if !is_shell_assign && !l.is_empty() && !r.is_empty() {
1236                // Ensure at least one side looks like a math expression or quantity
1237                let has_math_tokens = l.contains('+')
1238                    || l.contains('-')
1239                    || l.contains('*')
1240                    || l.contains('/')
1241                    || l.contains('^')
1242                    || l.contains('%')
1243                    || r.contains('+')
1244                    || r.contains('-')
1245                    || r.contains('*')
1246                    || r.contains('/')
1247                    || r.contains('^')
1248                    || r.contains('%')
1249                    || l.bytes().any(|b| b.is_ascii_digit())
1250                    || r.bytes().any(|b| b.is_ascii_digit());
1251
1252                if has_math_tokens {
1253                    return Some(MathDetection {
1254                        format_id: FormatId::Equation,
1255                        description: "Mathematical equation".to_string(),
1256                    });
1257                }
1258            }
1259        }
1260    }
1261
1262    // 5. Arithmetic expression (evaluates with numeric arithmetic)
1263    if evaluate_expression(trimmed).is_ok() {
1264        // Reason for fallback: space character safely returns None from unicode_vulgar_fraction on empty input
1265        let has_ops = trimmed.contains('+')
1266            || trimmed.contains('-')
1267            || trimmed.contains('*')
1268            || trimmed.contains('/')
1269            || trimmed.contains('^')
1270            || trimmed.contains('%')
1271            || trimmed.contains("mod")
1272            || unicode_vulgar_fraction(trimmed.chars().next().unwrap_or(' '))
1273                .is_some();
1274        if has_ops {
1275            return Some(MathDetection {
1276                format_id: FormatId::ArithmeticExpression,
1277                description: "Arithmetic expression".to_string(),
1278            });
1279        }
1280    }
1281
1282    // 6. Symbolic expression with algebraic variables (e.g. `1 + 2x`, `x^2 - 4x + 4`)
1283    let has_algebraic_ops = trimmed.contains('+')
1284        || trimmed.contains('-')
1285        || trimmed.contains('*')
1286        || trimmed.contains('/')
1287        || trimmed.contains('^');
1288
1289    if has_algebraic_ops {
1290        let has_vars = trimmed.chars().any(|c| c.is_ascii_alphabetic());
1291        let has_numbers = trimmed.chars().any(|c| c.is_ascii_digit());
1292        if has_vars
1293            && (has_numbers || trimmed.contains('^') || trimmed.contains('*'))
1294        {
1295            return Some(MathDetection {
1296                format_id: FormatId::SymbolicExpression,
1297                description: "Symbolic mathematical expression".to_string(),
1298            });
1299        }
1300    }
1301
1302    None
1303}
1304
1305#[cfg(test)]
1306#[allow(
1307    clippy::panic,
1308    clippy::expect_used,
1309    clippy::unwrap_used,
1310    clippy::unwrap_in_result,
1311    clippy::panic_in_result_fn,
1312    clippy::indexing_slicing,
1313    clippy::arithmetic_side_effects,
1314    reason = "Standard repository test boilerplate"
1315)]
1316mod tests {
1317    use super::*;
1318
1319    #[crate::ctb_test]
1320    #[expect(
1321        clippy::approx_constant,
1322        reason = "Testing parse_number on -3.14 literal rather than pi"
1323    )]
1324    fn test_parse_number() {
1325        assert_eq!(parse_number("123").unwrap(), 123.0);
1326        assert_eq!(parse_number("12.34").unwrap(), 12.34);
1327        assert_eq!(parse_number("pi").unwrap(), CONST_PI);
1328        assert_eq!(parse_number("PI").unwrap(), CONST_PI);
1329        assert_eq!(parse_number("e").unwrap(), CONST_E);
1330        assert_eq!(parse_number("E").unwrap(), CONST_E);
1331        parse_number("abc").unwrap_err();
1332        assert_eq!(parse_number("42").unwrap(), 42.0);
1333        assert!(approx_eq!(f64, parse_number("-3.14").unwrap(), -3.14));
1334        assert_eq!(parse_number("-3.25").unwrap(), -3.25);
1335        assert_eq!(parse_number("100%").unwrap(), 1.0);
1336        assert_eq!(parse_number("50%").unwrap(), 0.5);
1337    }
1338
1339    #[crate::ctb_test]
1340    fn test_parsed_number_fractions_and_units() {
1341        let p1 = ParsedNumber::parse("3½", Base::Decimal).unwrap();
1342        assert_eq!(p1.to_f64(), 3.5);
1343        assert_eq!(
1344            p1.to_rational().unwrap(),
1345            &Rational::from_naturals(Natural::from(7u8), Natural::from(2u8))
1346        );
1347
1348        let p2 = ParsedNumber::parse("3 1/2 oz", Base::Decimal).unwrap();
1349        assert_eq!(p2.to_f64(), 3.5);
1350        assert_eq!(p2.unit_suffix.as_deref(), Some("oz"));
1351
1352        let p2 = ParsedNumber::parse("3 1⁄2\"", Base::Decimal).unwrap();
1353        assert_eq!(p2.to_f64(), 3.5);
1354        assert_eq!(p2.unit_suffix.as_deref(), Some("\""));
1355
1356        let p2 = ParsedNumber::parse("⅟2 mm2", Base::Decimal).unwrap();
1357        assert_eq!(p2.to_f64(), 0.5);
1358        assert_eq!(p2.unit_suffix.as_deref(), Some("mm2"));
1359
1360        let p3 = ParsedNumber::parse("3lb", Base::Decimal).unwrap();
1361        assert_eq!(p3.to_f64(), 3.0);
1362        assert_eq!(p3.unit_suffix.as_deref(), Some("lb"));
1363
1364        let p4 = ParsedNumber::parse("3½ g", Base::Decimal).unwrap();
1365        assert_eq!(p4.to_f64(), 3.5);
1366        assert_eq!(p4.unit_suffix.as_deref(), Some("g"));
1367
1368        let p4 = ParsedNumber::parse("↉ g", Base::Decimal).unwrap();
1369        assert_eq!(p4.to_f64(), 0.0);
1370        assert_eq!(p4.unit_suffix.as_deref(), Some("g"));
1371    }
1372
1373    #[crate::ctb_test]
1374    fn test_symbolic_constants_preserved() {
1375        let pi = ParsedNumber::parse("PI", Base::Decimal).unwrap();
1376        assert_eq!(pi.value, NumberValue::Pi);
1377        assert_eq!(pi.to_f64(), CONST_PI);
1378        let pi = ParsedNumber::parse("π", Base::Decimal).unwrap();
1379        assert_eq!(pi.value, NumberValue::Pi);
1380
1381        let e = ParsedNumber::parse("e", Base::Decimal).unwrap();
1382        assert_eq!(e.value, NumberValue::E);
1383        assert_eq!(e.to_f64(), CONST_E);
1384
1385        let i = ParsedNumber::parse("i", Base::Decimal).unwrap();
1386        assert_eq!(i.value, NumberValue::ImaginaryI);
1387
1388        let i = ParsedNumber::parse("5i", Base::Decimal).unwrap();
1389        assert_eq!(i.value, NumberValue::ImaginaryI * 5);
1390
1391        let i = ParsedNumber::parse("-i", Base::Decimal).unwrap();
1392        assert_eq!(i.value, NumberValue::ImaginaryI * -1);
1393
1394        let i = ParsedNumber::parse("∞", Base::Decimal).unwrap();
1395        assert_eq!(i.value, NumberValue::Infinity);
1396        let i = ParsedNumber::parse("-∞", Base::Decimal).unwrap();
1397        assert_eq!(i.value, NumberValue::Infinity * -1);
1398    }
1399
1400    #[crate::ctb_test]
1401    fn test_analyze_and_scaled() {
1402        let info = analyze_input("-0.010");
1403        assert_eq!(info.int_width, 1);
1404        assert_eq!(info.frac_width, 3);
1405        assert!(info.has_decimal);
1406        assert_eq!(info.frac_len, 3);
1407
1408        let scaled = parse_scaled("-0.010", Base::Decimal, 3).unwrap();
1409        assert_eq!(scaled, Integer::from(-10));
1410        let formatted =
1411            format_scaled(&scaled, Base::Decimal, 3, 1, 3, true).unwrap();
1412        assert_eq!(formatted, "-0.010");
1413    }
1414
1415    #[crate::ctb_test]
1416    fn test_evaluate_expression() {
1417        assert_eq!(evaluate_expression("2 + 3 * 4").unwrap(), 14.0);
1418        assert_eq!(evaluate_expression("(2 + 3) * 4").unwrap(), 20.0);
1419        assert_eq!(evaluate_expression("10 - 4 - 2").unwrap(), 4.0);
1420        assert_eq!(evaluate_expression("2 ^ 3").unwrap(), 8.0);
1421        assert_eq!(evaluate_expression("10 \\ 3").unwrap(), 3.0);
1422        assert_eq!(evaluate_expression("10 Mod 3").unwrap(), 1.0);
1423        assert_eq!(evaluate_expression("10 % 3").unwrap(), 1.0);
1424        assert_eq!(evaluate_expression("-5 + 10").unwrap(), 5.0);
1425        assert_eq!(evaluate_expression("pi * 2").unwrap(), CONST_PI * 2.0);
1426        assert_eq!(evaluate_expression("3½ / 5").unwrap(), 0.7);
1427        evaluate_expression("10 / 0").unwrap_err();
1428        evaluate_expression("2 + (3 *").unwrap_err();
1429        evaluate_expression("2 + +").unwrap_err();
1430    }
1431
1432    #[crate::ctb_test]
1433    fn test_detect_math_and_numeric_formats() {
1434        // Numeric formats
1435        assert_eq!(
1436            detect_numeric_format("12345").unwrap().format_id,
1437            FormatId::Integer
1438        );
1439        assert_eq!(
1440            detect_numeric_format("-42").unwrap().format_id,
1441            FormatId::Integer
1442        );
1443        assert_eq!(
1444            detect_numeric_format("3.14159").unwrap().format_id,
1445            FormatId::Float
1446        );
1447        assert_eq!(
1448            detect_numeric_format("-0.05").unwrap().format_id,
1449            FormatId::Float
1450        );
1451        assert_eq!(
1452            detect_numeric_format("0xDEADBEEF").unwrap().format_id,
1453            FormatId::HexadecimalNumeral
1454        );
1455        assert_eq!(
1456            detect_numeric_format("0b101010").unwrap().format_id,
1457            FormatId::BinaryNumeral
1458        );
1459        assert_eq!(
1460            detect_numeric_format("0o755").unwrap().format_id,
1461            FormatId::OctalNumeral
1462        );
1463
1464        // Equations
1465        assert_eq!(
1466            detect_math_format("2x = 6").unwrap().format_id,
1467            FormatId::Equation
1468        );
1469        assert_eq!(
1470            detect_math_format("E = mc^2").unwrap().format_id,
1471            FormatId::Equation
1472        );
1473        assert_eq!(
1474            detect_math_format("y = 2x + 1").unwrap().format_id,
1475            FormatId::Equation
1476        );
1477
1478        // Inequalities
1479        assert_eq!(
1480            detect_math_format("x^2 + y^2 <= 1").unwrap().format_id,
1481            FormatId::Inequality
1482        );
1483        assert_eq!(
1484            detect_math_format("x > 0").unwrap().format_id,
1485            FormatId::Inequality
1486        );
1487        assert_eq!(
1488            detect_math_format("1 != 2").unwrap().format_id,
1489            FormatId::Inequality
1490        );
1491
1492        // Approximations
1493        assert_eq!(
1494            detect_math_format("1 oz ~= 28 g").unwrap().format_id,
1495            FormatId::Approximation
1496        );
1497        assert_eq!(
1498            detect_math_format("pi ≈ 3.14159").unwrap().format_id,
1499            FormatId::Approximation
1500        );
1501
1502        // Equation systems
1503        assert_eq!(
1504            detect_math_format("2x + y = 5; x - y = 1")
1505                .unwrap()
1506                .format_id,
1507            FormatId::EquationSystem
1508        );
1509
1510        // Arithmetic expressions
1511        assert_eq!(
1512            detect_math_format("(23 mod 2) + 6").unwrap().format_id,
1513            FormatId::ArithmeticExpression
1514        );
1515        assert_eq!(
1516            detect_math_format("2 + 3 * 4").unwrap().format_id,
1517            FormatId::ArithmeticExpression
1518        );
1519
1520        // Symbolic expressions
1521        assert_eq!(
1522            detect_math_format("1 + 2x").unwrap().format_id,
1523            FormatId::SymbolicExpression
1524        );
1525        assert_eq!(
1526            detect_math_format("x^2 - 4x + 4").unwrap().format_id,
1527            FormatId::SymbolicExpression
1528        );
1529
1530        // Non-math / code / config
1531        assert!(detect_math_format("let x = 5;").is_none());
1532        assert!(detect_math_format("import math").is_none());
1533        assert!(detect_math_format("hello world").is_none());
1534    }
1535}