formal-ai 0.222.0

Formal symbolic AI implementation with OpenAI-compatible APIs
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
//! Precedence-climbing arithmetic evaluator for the universal solver.
//!
//! Used by the universal solver's `try_arithmetic` handler. The evaluator is
//! pure (no I/O, no allocations beyond the token vector) and shared across
//! every interface so "what is 2 + 2?" produces the same trace from CLI,
//! HTTP, Telegram and the demo.
//!
//! When every literal in the expression is an integer (no decimal point),
//! the evaluator uses arbitrary-precision integer arithmetic so results like
//! `123123980921093128 * 2348023048230429324` are exact rather than
//! overflowing to `inf`. Expressions that mix integers and decimals (e.g.
//! `1.5 + 2`) fall back to `f64`.
//!
//! The module is `no_std` + `alloc` compatible so it can be `#[path]`-included
//! by `src/web/wasm-worker/src/lib.rs` without dragging in the standard
//! library. Issue #133 (R194) calls for the symbolic core to live in Rust→WASM
//! so the browser worker and the offline solver agree on every reasoning step.

#![allow(clippy::module_name_repetitions)]

use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

// Issue #386: the spelled digit/operator → value mapping is derived from the
// seed (the `cardinal_number` and `arithmetic_operation` meanings), not
// hardcoded here. Because this module is compiled into the no_std wasm worker —
// which cannot reach the seed loader at runtime and is built by plain `rustc`
// with no `build.rs` — the tables are materialized into a no_std static at
// author time and included here, exposing `WORD_VALUE_TOKENS` and
// `WORD_VALUE_PHRASES`. Regenerate after editing the seed with
// `cargo run -p formal-ai --example issue_386_gen_arith_table`;
// `arithmetic_word_tables_match_seed` (src/calculation.rs) keeps them in parity.
include!("arithmetic_word_tables.rs");

/// Errors produced when a calculation evaluator cannot produce a numeric value
/// for the requested expression.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArithmeticError {
    Empty,
    Unparseable,
    DivisionByZero,
    Overflow,
    UnbalancedParens,
    Calculator(String),
}

impl core::fmt::Display for ArithmeticError {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.write_str(match self {
            Self::Empty => "no expression provided",
            Self::Unparseable => "expression could not be parsed",
            Self::DivisionByZero => "division by zero",
            Self::Overflow => "numeric overflow",
            Self::UnbalancedParens => "unbalanced parentheses",
            Self::Calculator(error) => error,
        })
    }
}

// ---------------------------------------------------------------------------
// Arbitrary-precision non-negative integer (base 10^9, little-endian limbs).
// ---------------------------------------------------------------------------

const BASE: u64 = 1_000_000_000;
const EXACT_EXPONENT_LIMIT: u32 = 10_000;

/// A non-negative arbitrary-precision integer stored as base-10^9 limbs in
/// little-endian order (least-significant limb first).
#[derive(Debug, Clone, PartialEq, Eq)]
struct BigUint(Vec<u64>);

impl BigUint {
    fn zero() -> Self {
        Self(vec![0])
    }

    fn one() -> Self {
        Self(vec![1])
    }

    fn from_u64(value: u64) -> Self {
        if value < BASE {
            Self(vec![value])
        } else {
            Self(vec![value % BASE, value / BASE])
        }
    }

    fn is_zero(&self) -> bool {
        self.0.iter().all(|&limb| limb == 0)
    }

    fn add(&self, other: &Self) -> Self {
        let len = self.0.len().max(other.0.len());
        let mut result = Vec::with_capacity(len + 1);
        let mut carry: u64 = 0;
        for i in 0..len {
            let a = if i < self.0.len() { self.0[i] } else { 0 };
            let b = if i < other.0.len() { other.0[i] } else { 0 };
            let sum = a + b + carry;
            result.push(sum % BASE);
            carry = sum / BASE;
        }
        if carry > 0 {
            result.push(carry);
        }
        Self(result)
    }

    fn mul(&self, other: &Self) -> Self {
        let mut result = vec![0u64; self.0.len() + other.0.len()];
        for (i, &a) in self.0.iter().enumerate() {
            let mut carry: u64 = 0;
            for (j, &b) in other.0.iter().enumerate() {
                let prod =
                    u128::from(a) * u128::from(b) + u128::from(result[i + j]) + u128::from(carry);
                // Remainder and quotient both fit in u64: BASE = 10^9 < 2^30.
                #[allow(clippy::cast_possible_truncation)]
                {
                    result[i + j] = (prod % u128::from(BASE)) as u64;
                    carry = (prod / u128::from(BASE)) as u64;
                }
            }
            if carry > 0 {
                result[i + other.0.len()] += carry;
            }
        }
        while result.len() > 1 && *result.last().unwrap() == 0 {
            result.pop();
        }
        Self(result)
    }

    fn pow_u32(&self, mut exponent: u32) -> Self {
        let mut result = Self::one();
        let mut base = self.clone();
        while exponent > 0 {
            if exponent % 2 == 1 {
                result = result.mul(&base);
            }
            exponent /= 2;
            if exponent > 0 {
                base = base.mul(&base);
            }
        }
        result
    }

    fn to_u32(&self) -> Option<u32> {
        let mut value = 0_u32;
        for &limb in self.0.iter().rev() {
            if limb > u64::from(u32::MAX) {
                return None;
            }
            #[allow(clippy::cast_possible_truncation)]
            let limb_u32 = limb as u32;
            value = value.checked_mul(1_000_000_000)?;
            value = value.checked_add(limb_u32)?;
        }
        Some(value)
    }

    fn to_decimal_string(&self) -> String {
        if self.is_zero() {
            return String::from("0");
        }
        let mut parts = Vec::with_capacity(self.0.len());
        let last = self.0.len() - 1;
        for (i, &limb) in self.0.iter().enumerate().rev() {
            if i == last {
                parts.push(format!("{limb}"));
            } else {
                parts.push(format!("{limb:09}"));
            }
        }
        parts.concat()
    }

    #[allow(clippy::cast_precision_loss, clippy::suboptimal_flops)]
    fn to_f64(&self) -> f64 {
        let base_f = BASE as f64;
        let mut result = 0.0_f64;
        for &limb in self.0.iter().rev() {
            // `mul_add` would be one fused FMA instruction but it lives in
            // `std` (or behind `libm`) which the WASM core cannot link.
            // The plain `mul + add` form gives an identical result for the
            // value ranges this evaluator produces (all limbs < 10^9).
            result = result * base_f + (limb as f64);
        }
        result
    }
}

// ---------------------------------------------------------------------------
// Value type: either an exact big integer or a floating-point approximation.
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
enum ArithValue {
    Integer { negative: bool, magnitude: BigUint },
    Float(f64),
}

impl ArithValue {
    const fn from_f64(value: f64) -> Self {
        Self::Float(value)
    }

    fn negate(self) -> Self {
        match self {
            Self::Integer {
                negative,
                magnitude,
            } => {
                if magnitude.is_zero() {
                    Self::Integer {
                        negative: false,
                        magnitude,
                    }
                } else {
                    Self::Integer {
                        negative: !negative,
                        magnitude,
                    }
                }
            }
            Self::Float(f) => Self::Float(-f),
        }
    }

    fn to_f64(&self) -> f64 {
        match self {
            Self::Integer {
                negative,
                magnitude,
            } => {
                let f = magnitude.to_f64();
                if *negative {
                    -f
                } else {
                    f
                }
            }
            Self::Float(f) => *f,
        }
    }
}

// ---------------------------------------------------------------------------
// Arithmetic operations on ArithValue.
// ---------------------------------------------------------------------------

fn arith_add(left: ArithValue, right: ArithValue) -> Result<ArithValue, ArithmeticError> {
    match (left, right) {
        (
            ArithValue::Integer {
                negative: neg_l,
                magnitude: mag_l,
            },
            ArithValue::Integer {
                negative: neg_r,
                magnitude: mag_r,
            },
        ) => {
            if neg_l == neg_r {
                Ok(ArithValue::Integer {
                    negative: neg_l,
                    magnitude: mag_l.add(&mag_r),
                })
            } else {
                // Different signs: result = |larger| - |smaller|, sign from larger.
                let (larger, smaller, result_neg) = if big_gte(&mag_l, &mag_r) {
                    (mag_l, mag_r, neg_l)
                } else {
                    (mag_r, mag_l, neg_r)
                };
                let magnitude = big_sub(&larger, &smaller);
                Ok(ArithValue::Integer {
                    negative: if magnitude.is_zero() {
                        false
                    } else {
                        result_neg
                    },
                    magnitude,
                })
            }
        }
        (l, r) => {
            let result = l.to_f64() + r.to_f64();
            if result.is_finite() {
                Ok(ArithValue::Float(result))
            } else {
                Err(ArithmeticError::Overflow)
            }
        }
    }
}

fn arith_sub(left: ArithValue, right: ArithValue) -> Result<ArithValue, ArithmeticError> {
    arith_add(left, right.negate())
}

fn arith_mul(left: ArithValue, right: ArithValue) -> Result<ArithValue, ArithmeticError> {
    match (left, right) {
        (
            ArithValue::Integer {
                negative: neg_l,
                magnitude: mag_l,
            },
            ArithValue::Integer {
                negative: neg_r,
                magnitude: mag_r,
            },
        ) => Ok(ArithValue::Integer {
            negative: neg_l != neg_r && !(mag_l.is_zero() || mag_r.is_zero()),
            magnitude: mag_l.mul(&mag_r),
        }),
        (l, r) => {
            let result = l.to_f64() * r.to_f64();
            if result.is_finite() {
                Ok(ArithValue::Float(result))
            } else {
                Err(ArithmeticError::Overflow)
            }
        }
    }
}

fn arith_pow(left: &ArithValue, right: &ArithValue) -> Result<ArithValue, ArithmeticError> {
    if let (
        ArithValue::Integer {
            negative,
            magnitude,
        },
        ArithValue::Integer {
            negative: false,
            magnitude: exponent,
        },
    ) = (left, right)
    {
        let Some(exponent) = exponent.to_u32() else {
            return Err(ArithmeticError::Overflow);
        };
        if exponent > EXACT_EXPONENT_LIMIT {
            return Err(ArithmeticError::Overflow);
        }
        let result = magnitude.pow_u32(exponent);
        Ok(ArithValue::Integer {
            negative: *negative && exponent % 2 == 1 && !result.is_zero(),
            magnitude: result,
        })
    } else {
        let Some(exponent) = integer_exponent_i32(right) else {
            return Err(ArithmeticError::Unparseable);
        };
        Ok(ArithValue::Float(pow_f64_integer(left.to_f64(), exponent)?))
    }
}

fn integer_exponent_i32(value: &ArithValue) -> Option<i32> {
    match value {
        ArithValue::Integer {
            negative,
            magnitude,
        } => {
            let exponent = magnitude.to_u32()?;
            if exponent > EXACT_EXPONENT_LIMIT {
                return None;
            }
            #[allow(clippy::cast_possible_wrap)]
            let exponent = exponent as i32;
            Some(if *negative { -exponent } else { exponent })
        }
        ArithValue::Float(exponent) => {
            if !exponent.is_finite() {
                return None;
            }
            let limit = f64::from(EXACT_EXPONENT_LIMIT);
            if *exponent < -limit || *exponent > limit {
                return None;
            }
            #[allow(clippy::cast_possible_truncation)]
            let integer = *exponent as i32;
            #[allow(clippy::float_cmp)]
            (f64::from(integer) == *exponent).then_some(integer)
        }
    }
}

fn pow_f64_integer(base: f64, exponent: i32) -> Result<f64, ArithmeticError> {
    let negative_exponent = exponent < 0;
    let mut remaining = exponent.unsigned_abs();
    let mut factor = base;
    let mut result = 1.0_f64;
    while remaining > 0 {
        if remaining % 2 == 1 {
            result *= factor;
            if !result.is_finite() {
                return Err(ArithmeticError::Overflow);
            }
        }
        remaining /= 2;
        if remaining > 0 {
            factor *= factor;
            if !factor.is_finite() {
                return Err(ArithmeticError::Overflow);
            }
        }
    }
    if negative_exponent {
        if result == 0.0 {
            return Err(ArithmeticError::DivisionByZero);
        }
        result = 1.0 / result;
    }
    if result.is_finite() {
        Ok(result)
    } else {
        Err(ArithmeticError::Overflow)
    }
}

fn arith_div(left: &ArithValue, right: &ArithValue) -> Result<ArithValue, ArithmeticError> {
    if right.to_f64() == 0.0 {
        return Err(ArithmeticError::DivisionByZero);
    }
    let result = left.to_f64() / right.to_f64();
    if result.is_finite() {
        Ok(ArithValue::Float(result))
    } else {
        Err(ArithmeticError::Overflow)
    }
}

fn arith_rem(left: &ArithValue, right: &ArithValue) -> Result<ArithValue, ArithmeticError> {
    if right.to_f64() == 0.0 {
        return Err(ArithmeticError::DivisionByZero);
    }
    let result = left.to_f64() % right.to_f64();
    if result.is_finite() {
        Ok(ArithValue::Float(result))
    } else {
        Err(ArithmeticError::Overflow)
    }
}

/// Returns true if `a >= b`.
fn big_gte(a: &BigUint, b: &BigUint) -> bool {
    if a.0.len() != b.0.len() {
        return a.0.len() > b.0.len();
    }
    for (al, bl) in a.0.iter().rev().zip(b.0.iter().rev()) {
        if al != bl {
            return al > bl;
        }
    }
    true // equal
}

/// Subtract `smaller` from `larger` (assumes `larger >= smaller`).
fn big_sub(larger: &BigUint, smaller: &BigUint) -> BigUint {
    let mut result = larger.0.clone();
    let mut borrow: u64 = 0;
    for (i, limb) in result.iter_mut().enumerate() {
        let s = if i < smaller.0.len() { smaller.0[i] } else { 0 };
        if *limb >= s + borrow {
            *limb -= s + borrow;
            borrow = 0;
        } else {
            *limb = *limb + BASE - s - borrow;
            borrow = 1;
        }
    }
    while result.len() > 1 && *result.last().unwrap() == 0 {
        result.pop();
    }
    BigUint(result)
}

// ---------------------------------------------------------------------------
// Tokenizer.
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
enum ArithmeticToken {
    Number(ArithValue),
    Plus,
    Minus,
    Star,
    Slash,
    Percent,
    Caret,
    LParen,
    RParen,
}

fn tokenize_arithmetic(input: &str) -> Result<Vec<ArithmeticToken>, ArithmeticError> {
    let mut tokens = Vec::new();
    let mut chars = input.chars().peekable();
    while let Some(&character) = chars.peek() {
        if character.is_whitespace() {
            chars.next();
            continue;
        }
        match character {
            '+' => {
                chars.next();
                tokens.push(ArithmeticToken::Plus);
            }
            '-' | '−' => {
                chars.next();
                tokens.push(ArithmeticToken::Minus);
            }
            '*' | '×' | '·' => {
                chars.next();
                tokens.push(ArithmeticToken::Star);
            }
            '/' | '÷' => {
                chars.next();
                tokens.push(ArithmeticToken::Slash);
            }
            '%' => {
                chars.next();
                tokens.push(ArithmeticToken::Percent);
            }
            '^' => {
                chars.next();
                tokens.push(ArithmeticToken::Caret);
            }
            '(' => {
                chars.next();
                tokens.push(ArithmeticToken::LParen);
            }
            ')' => {
                chars.next();
                tokens.push(ArithmeticToken::RParen);
            }
            digit if digit.is_ascii_digit() || digit == '.' => {
                let mut number = String::new();
                let mut has_dot = false;
                while let Some(&next) = chars.peek() {
                    if next.is_ascii_digit() {
                        number.push(next);
                        chars.next();
                    } else if next == '.' && !has_dot {
                        has_dot = true;
                        number.push(next);
                        chars.next();
                    } else if next == '_' {
                        chars.next();
                    } else {
                        break;
                    }
                }
                let value = if has_dot {
                    let parsed: f64 = number.parse().map_err(|_| ArithmeticError::Unparseable)?;
                    ArithValue::from_f64(parsed)
                } else {
                    parse_integer_literal(&number)?
                };
                tokens.push(ArithmeticToken::Number(value));
            }
            _ => return Err(ArithmeticError::Unparseable),
        }
    }
    Ok(tokens)
}

/// Parse a decimal integer string into a `BigUint`-backed `ArithValue`.
fn parse_integer_literal(s: &str) -> Result<ArithValue, ArithmeticError> {
    if s.is_empty() {
        return Err(ArithmeticError::Unparseable);
    }
    // Build BigUint by repeated multiply-by-10 + add-digit.
    let mut magnitude = BigUint::zero();
    let ten = BigUint::from_u64(10);
    for ch in s.chars() {
        let digit = u64::from(ch.to_digit(10).ok_or(ArithmeticError::Unparseable)?);
        magnitude = magnitude.mul(&ten);
        magnitude = magnitude.add(&BigUint::from_u64(digit));
    }
    Ok(ArithValue::Integer {
        negative: false,
        magnitude,
    })
}

// ---------------------------------------------------------------------------
// Parser.
// ---------------------------------------------------------------------------

struct ArithmeticParser<'a> {
    tokens: &'a [ArithmeticToken],
    cursor: usize,
}

impl<'a> ArithmeticParser<'a> {
    const fn new(tokens: &'a [ArithmeticToken]) -> Self {
        Self { tokens, cursor: 0 }
    }

    fn peek(&self) -> Option<&ArithmeticToken> {
        self.tokens.get(self.cursor)
    }

    fn advance(&mut self) -> Option<&ArithmeticToken> {
        let current = self.tokens.get(self.cursor);
        if current.is_some() {
            self.cursor += 1;
        }
        current
    }

    fn parse(&mut self) -> Result<ArithValue, ArithmeticError> {
        let value = self.parse_additive()?;
        if self.cursor != self.tokens.len() {
            return Err(ArithmeticError::Unparseable);
        }
        Ok(value)
    }

    fn parse_additive(&mut self) -> Result<ArithValue, ArithmeticError> {
        let mut left = self.parse_multiplicative()?;
        while let Some(token) = self.peek() {
            let is_plus = match token {
                ArithmeticToken::Plus => true,
                ArithmeticToken::Minus => false,
                _ => break,
            };
            self.advance();
            let right = self.parse_multiplicative()?;
            left = if is_plus {
                arith_add(left, right)?
            } else {
                arith_sub(left, right)?
            };
        }
        Ok(left)
    }

    fn parse_multiplicative(&mut self) -> Result<ArithValue, ArithmeticError> {
        let mut left = self.parse_unary()?;
        while let Some(token) = self.peek() {
            let op = match token {
                ArithmeticToken::Star => '*',
                ArithmeticToken::Slash => '/',
                ArithmeticToken::Percent => '%',
                _ => break,
            };
            self.advance();
            let right = self.parse_unary()?;
            left = match op {
                '*' => arith_mul(left, right)?,
                '/' => arith_div(&left, &right)?,
                _ => arith_rem(&left, &right)?,
            };
        }
        Ok(left)
    }

    fn parse_unary(&mut self) -> Result<ArithValue, ArithmeticError> {
        match self.peek() {
            Some(ArithmeticToken::Minus) => {
                self.advance();
                Ok(self.parse_unary()?.negate())
            }
            Some(ArithmeticToken::Plus) => {
                self.advance();
                self.parse_unary()
            }
            _ => self.parse_power(),
        }
    }

    fn parse_power(&mut self) -> Result<ArithValue, ArithmeticError> {
        let left = self.parse_primary()?;
        if matches!(self.peek(), Some(ArithmeticToken::Caret)) {
            self.advance();
            let right = self.parse_unary()?;
            arith_pow(&left, &right)
        } else {
            Ok(left)
        }
    }

    fn parse_primary(&mut self) -> Result<ArithValue, ArithmeticError> {
        match self.advance() {
            Some(ArithmeticToken::Number(value)) => Ok(value.clone()),
            Some(ArithmeticToken::LParen) => {
                let inner = self.parse_additive()?;
                match self.advance() {
                    Some(ArithmeticToken::RParen) => Ok(inner),
                    _ => Err(ArithmeticError::UnbalancedParens),
                }
            }
            _ => Err(ArithmeticError::Unparseable),
        }
    }
}

// ---------------------------------------------------------------------------
// Public API.
// ---------------------------------------------------------------------------

fn normalize_expression(expression: &str) -> String {
    let lower = expression.to_lowercase();
    // Multi-word operator phrases ("multiplied by", "разделить на") are rewritten
    // first, longest-first, so a phrase is replaced before any shorter phrase it
    // contains. Each is padded with spaces so it only matches on a token
    // boundary, exactly as the former literal `" умножить на " -> " * "` map did.
    let normalized_phrases = WORD_VALUE_PHRASES
        .iter()
        .fold(format!(" {lower} "), |current, (phrase, value)| {
            current.replace(&format!(" {phrase} "), &format!(" {value} "))
        });
    let mapped = normalized_phrases
        .split_whitespace()
        .map(|token| normalize_word_token(token).unwrap_or(token))
        .collect::<Vec<_>>()
        .join(" ");
    rewrite_percent_of(&mapped)
}

/// True when `token` is a bare decimal number (digits with an optional dot).
fn is_number_token(token: &str) -> bool {
    !token.is_empty() && token.chars().all(|c| c.is_ascii_digit() || c == '.')
}

/// Recognise a percentage value at `index`, returning its numeric text and the
/// number of tokens it spans. Handles both the glued `8%` form and the spaced
/// `8 %` form. Returns `None` when `index` is not a percentage value.
fn match_percent_value(tokens: &[&str], index: usize) -> Option<(String, usize)> {
    let token = *tokens.get(index)?;
    if let Some(prefix) = token.strip_suffix('%') {
        if is_number_token(prefix) {
            return Some((prefix.to_string(), 1));
        }
    }
    if is_number_token(token) && tokens.get(index + 1).copied() == Some("%") {
        return Some((token.to_string(), 2));
    }
    None
}

/// Rewrite "N% of M" percentage-of phrases into explicit arithmetic the
/// recursive-descent parser can evaluate: `8% of 500` becomes `( 8 * 500 / 100 )`.
///
/// This mirrors the link-calculator semantics used on the native CLI path, where
/// "55 * 8% of 500" evaluates to 2200 (issue #334). A bare `%` that is *not*
/// followed by `of` is left untouched so it still parses as the modulo operator.
fn rewrite_percent_of(expression: &str) -> String {
    let tokens: Vec<&str> = expression.split_whitespace().collect();
    let mut out: Vec<String> = Vec::new();
    let mut index = 0;
    while index < tokens.len() {
        if let Some((percent, consumed)) = match_percent_value(&tokens, index) {
            let after = index + consumed;
            if tokens.get(after).copied() == Some("of") {
                if let Some(base) = tokens.get(after + 1) {
                    if is_number_token(base) {
                        out.push("(".to_string());
                        out.push(percent);
                        out.push("*".to_string());
                        out.push((*base).to_string());
                        out.push("/".to_string());
                        out.push("100".to_string());
                        out.push(")".to_string());
                        index = after + 2;
                        continue;
                    }
                }
            }
        }
        out.push(tokens[index].to_string());
        index += 1;
    }
    out.join(" ")
}

/// Map a single whitespace token to its value surface, or `None` if unknown.
///
/// A spelled digit maps to its numeral ("two" becomes "2") and a spelled
/// operator to its symbol ("plus" becomes "+"). The map is derived from the seed
/// cardinal and operator meanings; see the generated `arithmetic_word_tables.rs`.
fn normalize_word_token(token: &str) -> Option<&'static str> {
    WORD_VALUE_TOKENS
        .iter()
        .find_map(|&(surface, value)| (surface == token).then_some(value))
}

pub fn evaluate_fallback_formatted(expression: &str) -> Result<String, ArithmeticError> {
    let normalized = normalize_expression(expression);
    let tokens = tokenize_arithmetic(&normalized)?;
    if tokens.is_empty() {
        return Err(ArithmeticError::Empty);
    }
    let value = ArithmeticParser::new(&tokens).parse()?;
    Ok(format_arith_value(&value))
}

/// Render an `ArithValue` as a string. Exact integers are shown without
/// scientific notation; floats use the minimal sufficient surface form.
fn format_arith_value(value: &ArithValue) -> String {
    match value {
        ArithValue::Integer {
            negative,
            magnitude,
        } => {
            let s = magnitude.to_decimal_string();
            if *negative && s != "0" {
                format!("-{s}")
            } else {
                s
            }
        }
        ArithValue::Float(f) => format_f64(*f),
    }
}

// `f64::fract` lives in `std`; the WASM core is `no_std`, so we recover the
// "is whole" check via a bounded `i64` round-trip. Inside `value.abs() < 1e15`
// the cast is lossless (well within the 2^63 i64 range and below the f64
// mantissa precision boundary), so the bit-for-bit equality is intentional.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::float_cmp
)]
fn format_f64(value: f64) -> String {
    if !value.is_finite() {
        return String::from("non-finite");
    }
    let is_whole = value.abs() < 1e15 && value == (value as i64) as f64;
    if is_whole {
        format!("{value:.0}")
    } else {
        let rendered = format!("{value:.10}");
        let trimmed = rendered.trim_end_matches('0').trim_end_matches('.');
        if trimmed.is_empty() || trimmed == "-" {
            String::from("0")
        } else {
            String::from(trimmed)
        }
    }
}