num2words2-core 0.1.0

Number-to-words conversion for 120+ languages (Rust port of num2words). 42 -> forty-two.
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
//! Faithful port of num2words2's `base.py` engine.
//!
//! The Python original builds a nested list-of-tuples tree in `splitnum`,
//! then folds it with `clean`/`merge`. The tree shape is load-bearing:
//! `clean` branches on whether an element is a tuple or a list, so `Node`
//! mirrors that distinction exactly rather than flattening it.

use crate::currency::{CurrencyForms, CurrencyValue};
use crate::floatpath::FloatValue;
use crate::strnum::{python_decimal_parse, ParsedNumber};
use bigdecimal::BigDecimal;
use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{One, Signed, Zero};
use std::sync::OnceLock;

/// A grammatical-kwargs value (`case=`, `gender=`, `reading=`, ...).
///
/// Covers every type the library's converter signatures accept: str, bool,
/// int, list-of-str, and an explicit `None`. Python bools are ints, so the
/// binding must try Bool before Int when extracting.
#[derive(Debug, Clone, PartialEq)]
pub enum KwVal {
    Str(String),
    Bool(bool),
    Int(i64),
    List(Vec<String>),
    None,
}

/// The kwargs bag handed to the `*_kw` trait hooks. Order-preserving —
/// insertion order never matters to the converters, but it keeps error
/// messages deterministic.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Kwargs(pub Vec<(String, KwVal)>);

impl Kwargs {
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
    pub fn get(&self, key: &str) -> Option<&KwVal> {
        self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v)
    }
    pub fn str(&self, key: &str) -> Option<&str> {
        match self.get(key) {
            Some(KwVal::Str(s)) => Some(s),
            _ => Option::None,
        }
    }
    pub fn bool(&self, key: &str) -> Option<bool> {
        match self.get(key) {
            Some(KwVal::Bool(b)) => Some(*b),
            _ => Option::None,
        }
    }
    pub fn int(&self, key: &str) -> Option<i64> {
        match self.get(key) {
            Some(KwVal::Int(i)) => Some(*i),
            _ => Option::None,
        }
    }
    pub fn list(&self, key: &str) -> Option<&[String]> {
        match self.get(key) {
            Some(KwVal::List(l)) => Some(l),
            _ => Option::None,
        }
    }
    /// True when every key is in `allowed`. A language's `*_kw` override
    /// starts with this guard: an unexpected key means the Python signature
    /// would raise TypeError, so the hook returns NotImplemented and the
    /// dispatcher falls back to Python, which raises the original error.
    pub fn only(&self, allowed: &[&str]) -> bool {
        self.0.iter().all(|(k, _)| allowed.contains(&k.as_str()))
    }
}

/// A node in the tree `splitnum` produces.
///
/// `Leaf` is Python's `(text, num)` tuple; `List` is a nested list. `clean`
/// distinguishes the two, so collapsing them would change the output.
#[derive(Debug, Clone)]
pub enum Node {
    Leaf(String, BigInt),
    List(Vec<Node>),
}

impl Node {
    fn leaf(text: impl Into<String>, num: BigInt) -> Node {
        Node::Leaf(text.into(), num)
    }
    fn is_leaf(&self) -> bool {
        matches!(self, Node::Leaf(..))
    }
}

/// The ordered card table: value -> word, in descending key order.
///
/// Python uses an `OrderedDict` whose insertion order (high, then mid, then
/// low) happens to be descending. `splitnum` iterates it in that order, so a
/// sorted `Vec` reproduces the semantics while allowing binary search.
#[derive(Debug, Clone, Default)]
pub struct Cards {
    entries: Vec<(BigInt, String)>,
}

impl Cards {
    pub fn new() -> Self {
        Cards {
            entries: Vec::new(),
        }
    }

    pub fn insert(&mut self, key: BigInt, word: impl Into<String>) {
        let word = word.into();
        match self.entries.binary_search_by(|(k, _)| key.cmp(k)) {
            Ok(i) => self.entries[i] = (key, word),
            Err(i) => self.entries.insert(i, (key, word)),
        }
    }

    pub fn get(&self, key: &BigInt) -> Option<&str> {
        self.entries
            .binary_search_by(|(k, _)| key.cmp(k))
            .ok()
            .map(|i| self.entries[i].1.as_str())
    }

    /// Descending iteration, matching the Python insertion order.
    pub fn iter(&self) -> impl Iterator<Item = &(BigInt, String)> {
        self.entries.iter()
    }

    /// Entries from the first card `<= value`, descending.
    ///
    /// Python does `for elem in self.cards: if elem > value: continue`, an
    /// O(n) scan that costs ~100 BigInt comparisons to reach "forty" from
    /// 10^303. Entries are sorted descending, so the first card `<= value`
    /// is a binary-search partition point — identical result, O(log n).
    pub fn iter_from(&self, value: &BigInt) -> impl Iterator<Item = &(BigInt, String)> {
        let start = self.entries.partition_point(|(k, _)| k > value);
        self.entries[start..].iter()
    }

    pub fn highest(&self) -> Option<&BigInt> {
        self.entries.first().map(|(k, _)| k)
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

/// Errors mirroring the exception types the Python original raises.
///
/// `Index`, `Key` and `Value` exist because several language modules crash
/// on edge inputs rather than raising deliberately — e.g. `lang_PL`'s
/// `to_ordinal(0)` pops its last fragment and then indexes an empty list
/// (IndexError), `to_ordinal(-1)` feeds "-" to `int()` (ValueError), and
/// `to_ordinal(10**12)` misses `prefixes_ordinal[4]` (KeyError).
///
/// Those are Python bugs, but they are observable behaviour that callers may
/// catch, so parity requires reproducing the exception *type*. Do not
/// "improve" them into a tidy TypeError.
#[derive(Debug)]
pub enum N2WError {
    Overflow(String),
    Type(String),
    /// Python raised NotImplementedError as a DELIBERATE result — the same
    /// exception the original produces, so it must propagate to the caller.
    /// `to_ordinal(>100)` in Welsh, an unknown Japanese counter, and the
    /// abstract `pluralize` all land here. Distinct from `Fallback`.
    NotImplemented(String),
    /// Not a Python exception: the Rust core declines this specific call and
    /// the binding re-runs the ORIGINAL Python converter, which owns it
    /// (an unported kwarg whose Python path raises the real TypeError; an
    /// Inf/NaN string a language handles in Python; a sentence sub-case).
    /// Kept separate from `NotImplemented` so a genuine NotImplementedError
    /// raise is served natively instead of being swallowed by the shim's
    /// fallback catch.
    Fallback(String),
    ZeroDivision(String),
    /// Python raised IndexError (usually an out-of-range list access).
    Index(String),
    /// Python raised KeyError (usually a missing dict entry).
    Key(String),
    /// Python raised ValueError (usually int()/str parsing of a bad token).
    Value(String),
    /// Python raised AttributeError. Usually the converter simply does not
    /// define the method or attribute at all — `Num2Word_RM` has no
    /// `to_year`/`to_ordinal_num`, and `Num2Word_IT` has no `errmsg_negord`
    /// — so the crash happens on attribute lookup, before any conversion.
    Attribute(String),
    /// Python raised AssertionError. `lang_AR` asserts its bounds instead of
    /// raising deliberately, so `to_ordinal(>=10**51)` and
    /// `to_cardinal(-(10**51))` surface as AssertionError, not OverflowError.
    Assertion(String),
    /// Not an error: Python's function fell off the end and returned `None`.
    ///
    /// `lang_VI` does this past 10^75 — no raise, no string, just an implicit
    /// `None` that propagates to the caller. `None` is a *success* value, so
    /// the binding turns this sentinel into Python `None` rather than an
    /// exception. Modelled as an Err variant purely to avoid rewriting
    /// `Result<String>` to `Result<Option<String>>` across 154 language files.
    ReturnsNone,
    /// Python raised an exception class defined in a language module rather
    /// than a builtin: `(module_path, class_name, message)`.
    ///
    /// `lang_BN.py` is the only case in the library — it defines
    /// `NumberTooLargeError(Exception)` and raises it past `MAX_NUMBER`
    /// (~10^306) instead of `OverflowError`. The binding imports the class
    /// and raises the real thing, so `except NumberTooLargeError` keeps
    /// working.
    Custom {
        module: &'static str,
        class: &'static str,
        msg: String,
    },
}

pub type Result<T> = std::result::Result<T, N2WError>;

/// The per-language behaviour that `base.py` leaves abstract or overridable.
///
/// Defaults mirror `Num2Word_Base`; each language overrides what it needs,
/// exactly as the Python subclasses do.
///
/// Two shapes exist in the wild, and both must be expressible:
///
/// 1. *Engine languages* supply `cards` + `merge` and let the default
///    `to_cardinal` drive `splitnum`/`clean` (as `Num2Word_Base` does).
/// 2. *Self-contained languages* override `to_cardinal` outright and never
///    touch cards or merge — 121 of the 156 Python modules do this.
///
/// So `cards`/`maxval`/`merge` carry defaults rather than being required;
/// a shape-2 language simply ignores them.
pub trait Lang {
    fn cards(&self) -> &Cards {
        static EMPTY: OnceLock<Cards> = OnceLock::new();
        EMPTY.get_or_init(Cards::new)
    }

    fn maxval(&self) -> &BigInt {
        static ZERO: OnceLock<BigInt> = OnceLock::new();
        ZERO.get_or_init(BigInt::zero)
    }

    fn negword(&self) -> &str {
        "(-) "
    }
    fn pointword(&self) -> &str {
        "(.)"
    }
    fn is_title(&self) -> bool {
        false
    }
    fn exclude_title(&self) -> &[String] {
        &[]
    }

    /// `merge` is abstract in Python (`raise NotImplementedError`).
    /// Languages that override `to_cardinal` never reach it.
    fn merge(&self, _l: (&str, &BigInt), _r: (&str, &BigInt)) -> (String, BigInt) {
        unimplemented!("merge not implemented for this language")
    }

    fn title(&self, value: &str) -> String {
        if !self.is_title() {
            return value.to_string();
        }
        let excl = self.exclude_title();
        value
            .split_whitespace()
            .map(|w| {
                if excl.iter().any(|e| e == w) {
                    w.to_string()
                } else {
                    // Python does word[0].upper() + word[1:] — uppercase the
                    // first *character*, not the first byte.
                    let mut c = w.chars();
                    match c.next() {
                        Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
                        None => String::new(),
                    }
                }
            })
            .collect::<Vec<_>>()
            .join(" ")
    }

    fn to_cardinal(&self, value: &BigInt) -> Result<String> {
        default_to_cardinal(self, value)
    }

    fn to_ordinal(&self, value: &BigInt) -> Result<String> {
        self.to_cardinal(value)
    }

    fn to_ordinal_num(&self, value: &BigInt) -> Result<String> {
        Ok(value.to_string())
    }

    fn to_year(&self, value: &BigInt) -> Result<String> {
        self.to_cardinal(value)
    }

    // ---- currency ----------------------------------------------------
    //
    // Every hook Python's currency path can reach is exposed here with a
    // default. A language overrides only what its Python class overrides.

    /// Class name, for the `'X' not implemented for 'Num2Word_Y'` message.
    fn lang_name(&self) -> &str {
        "Num2Word_Base"
    }

    /// `CURRENCY_FORMS[code]`. `None` -> NotImplementedError, as in Python.
    fn currency_forms(&self, _code: &str) -> Option<&CurrencyForms> {
        None
    }

    /// `CURRENCY_ADJECTIVES[code]`.
    fn currency_adjective(&self, _code: &str) -> Option<&str> {
        None
    }

    /// `CURRENCY_PRECISION.get(code, 100)` — subunits per unit. 1000 for
    /// 3-decimal currencies (BHD/KWD/...), 1 for no-subunit currencies.
    fn currency_precision(&self, _code: &str) -> i64 {
        100
    }

    /// `pluralize(n, forms)`. Abstract in Python (`raise NotImplementedError`),
    /// so the default raises rather than guessing a plural rule.
    fn pluralize(&self, _n: &BigInt, _forms: &[String]) -> Result<String> {
        Err(N2WError::NotImplemented("pluralize".into()))
    }

    fn money_verbose(&self, number: &BigInt, _currency: &str) -> Result<String> {
        self.to_cardinal(number)
    }

    fn cents_verbose(&self, number: &BigInt, _currency: &str) -> Result<String> {
        self.to_cardinal(number)
    }

    fn cents_terse(&self, number: &BigInt, currency: &str) -> Result<String> {
        Ok(crate::currency::default_cents_terse(
            number,
            self.currency_precision(currency),
        ))
    }

    /// `Num2Word_Base.to_cardinal_float`. `precision_override` is the
    /// `precision=` kwarg (issue #580).
    fn to_cardinal_float(
        &self,
        value: &FloatValue,
        precision_override: Option<u32>,
    ) -> Result<String> {
        crate::floatpath::default_to_cardinal_float(self, value, precision_override)
    }

    /// Render a non-integral value, for the fractional-cents branch. Python
    /// reaches this as `self.to_cardinal(float(right))`, i.e. through the
    /// float path, so the default routes there rather than raising.
    fn cardinal_from_decimal(&self, value: &BigDecimal) -> Result<String> {
        crate::floatpath::cardinal_from_bigdecimal(self, value)
    }

    /// `separator: None` means the caller omitted the kwarg, so the
    /// language's own default applies. Python expresses this as a per-method
    /// default (`Num2Word_CA.to_currency(..., separator=" amb")`), which a
    /// plain `&str` cannot represent: once the shim substitutes Base's ",",
    /// "caller omitted it" and "caller passed a comma" are indistinguishable.
    fn to_currency(
        &self,
        val: &CurrencyValue,
        currency: &str,
        cents: bool,
        separator: Option<&str>,
        adjective: bool,
    ) -> Result<String> {
        crate::currency::default_to_currency(
            self,
            val,
            currency,
            cents,
            separator.unwrap_or(self.default_separator()),
            adjective,
        )
    }

    /// This language's own `separator=` default. Base's is ",".
    fn default_separator(&self) -> &str {
        ","
    }

    /// This language's own `to_currency(adjective=...)` default. Base's is
    /// False; only Mongolian defaults to True.
    fn default_adjective(&self) -> bool {
        false
    }

    /// This language's own `to_currency(currency=...)` default. Base's is
    /// "EUR", but only 44 of 156 languages actually use it — en_IN defaults
    /// to INR, id to IDR, af to ZAR, and so on. Hardcoding EUR in the
    /// dispatcher silently converts the wrong currency.
    fn default_currency(&self) -> &str {
        "EUR"
    }

    fn to_cheque(&self, val: &BigDecimal, currency: &str) -> Result<String> {
        crate::currency::default_to_cheque(self, val, currency)
    }

    // ---- fractions -----------------------------------------------------

    /// `Num2Word_Base.to_fraction` (issue #584). EN/DE/ES/FR/IT/PT and the
    /// aero profiles override with idiomatic forms (half/quarter/Drittel).
    fn to_fraction(&self, numerator: &BigInt, denominator: &BigInt) -> Result<String> {
        default_to_fraction(self, numerator, denominator)
    }

    // ---- float/Decimal routing ------------------------------------------
    //
    // Python's dispatcher hands a float/Decimal straight to the converter
    // method; where it lands is the *language's* decision. Base semantics:
    // `assert int(value) == value` succeeds for a whole value -> integer
    // path ("one"); fails -> to_cardinal_float. Languages overriding
    // Python's to_cardinal (ru "пять целых ноль десятых", cs, be, ...) make
    // their own call and override these hooks.

    /// `to_cardinal(float/Decimal)` — the full entry, whole values included.
    fn cardinal_float_entry(
        &self,
        value: &FloatValue,
        precision_override: Option<u32>,
    ) -> Result<String> {
        if let Some(i) = value.as_whole_int() {
            return self.to_cardinal(&i);
        }
        self.to_cardinal_float(value, precision_override)
    }

    /// `to_ordinal(float/Decimal)`. Base's to_ordinal is to_cardinal, so the
    /// default routes identically; languages with verify_ordinal-style type
    /// checks (TypeError on non-int) override.
    fn ordinal_float_entry(&self, value: &FloatValue) -> Result<String> {
        self.cardinal_float_entry(value, None)
    }

    /// `to_ordinal_num(float/Decimal)`. Base returns the value unchanged and
    /// the dispatcher str()s it, so the default echoes the Python repr the
    /// binding computed.
    fn ordinal_num_float_entry(&self, _value: &FloatValue, repr_str: &str) -> Result<String> {
        Ok(repr_str.to_string())
    }

    /// `to_year(float/Decimal)`. Base's to_year is to_cardinal.
    fn year_float_entry(&self, value: &FloatValue) -> Result<String> {
        self.cardinal_float_entry(value, None)
    }

    // ---- string inputs ---------------------------------------------------

    /// `converter.str_to_number`. Base is `Decimal(value)`; ES ("1ro" ->
    /// ordinal handshake), PT_BR ("1.50" -> 'ponto'), DV (TypeError instead
    /// of InvalidOperation), BN (abs()) and ID override.
    fn str_to_number(&self, s: &str) -> Result<ParsedNumber> {
        python_decimal_parse(s)
    }

    /// The pt_BR 'ponto' rendering: `to_cardinal(value)` with the pointword
    /// swapped for this one call. Only reachable through
    /// `ParsedNumber::DecPoint`, so only PT_BR implements it.
    fn cardinal_with_pointword(
        &self,
        _value: &FloatValue,
        _pointword: &str,
        _precision_override: Option<u32>,
    ) -> Result<String> {
        Err(N2WError::Fallback("cardinal_with_pointword".into()))
    }

    // ---- grammatical kwargs ----------------------------------------------
    //
    // The `*_kw` hooks receive the caller's kwargs bag. The default accepts
    // only an empty bag; any actual kwarg is NotImplemented, which the
    // binding surfaces as NotImplementedError so the dispatcher falls back
    // to Python — either the original handles the kwarg (port not landed) or
    // it raises the original TypeError (converter doesn't accept it).

    fn to_cardinal_kw(&self, value: &BigInt, kw: &Kwargs) -> Result<String> {
        if kw.is_empty() {
            return self.to_cardinal(value);
        }
        Err(N2WError::Fallback("kwargs".into()))
    }

    fn to_ordinal_kw(&self, value: &BigInt, kw: &Kwargs) -> Result<String> {
        if kw.is_empty() {
            return self.to_ordinal(value);
        }
        Err(N2WError::Fallback("kwargs".into()))
    }

    fn to_ordinal_num_kw(&self, value: &BigInt, kw: &Kwargs) -> Result<String> {
        if kw.is_empty() {
            return self.to_ordinal_num(value);
        }
        Err(N2WError::Fallback("kwargs".into()))
    }

    fn to_year_kw(&self, value: &BigInt, kw: &Kwargs) -> Result<String> {
        if kw.is_empty() {
            return self.to_year(value);
        }
        Err(N2WError::Fallback("kwargs".into()))
    }

    #[allow(clippy::too_many_arguments)]
    fn to_currency_kw(
        &self,
        val: &CurrencyValue,
        currency: &str,
        cents: bool,
        separator: Option<&str>,
        adjective: bool,
        kw: &Kwargs,
    ) -> Result<String> {
        if kw.is_empty() {
            return self.to_currency(val, currency, cents, separator, adjective);
        }
        Err(N2WError::Fallback("kwargs".into()))
    }

    fn to_cardinal_float_kw(
        &self,
        value: &FloatValue,
        precision_override: Option<u32>,
        kw: &Kwargs,
    ) -> Result<String> {
        if kw.is_empty() {
            return self.cardinal_float_entry(value, precision_override);
        }
        Err(N2WError::Fallback("kwargs".into()))
    }

    /// Spanish "1ro" currency: does the stashed ordinal fire? `Num2Word_ES`
    /// apocopates 1 → "un euro" in `to_currency`, bypassing `to_cardinal`, so
    /// the stash never fires (false, the default). The regional `es_XX`
    /// classes inherit `Base.to_currency`, whose `_money_verbose` calls
    /// `to_cardinal(1)` → the stash fires → "primero córdoba" (true).
    fn es_currency_ordinal_fires(&self) -> bool {
        false
    }

    /// Render `Decimal('-0.0')` for mode `to`, which BigDecimal cannot
    /// represent (it has no signed zero). `None` — the default — means the
    /// value coincides with float `-0.0`, so the binding's `Float{-0.0}`
    /// demotion is exact. The ~10 languages that render the Decimal form
    /// differently (ce/cy "dim"/"ноль" via the integer path, pl its float
    /// grammar with the negword, rm a TypeError) override this to serve it
    /// natively instead of leaning on a Python fallback.
    fn neg_zero_decimal(&self, _to: &str) -> Option<Result<String>> {
        None
    }

    /// `str_to_number` produced `Decimal('Infinity')` / `-Infinity`. Base's
    /// integer path does `int(Decimal('Infinity'))` → OverflowError. The many
    /// self-contained converters that feed the raw token to `int("Infinity")`
    /// get ValueError instead and override this. `to` is the requested mode.
    fn inf_result(&self, _negative: bool, _to: &str) -> Result<String> {
        Err(N2WError::Overflow(
            "cannot convert Infinity to integer".into(),
        ))
    }

    /// `str_to_number` produced `Decimal('NaN')`. Base's `int(NaN)` raises
    /// ValueError (caught into the float path, which raises ValueError again).
    /// Languages whose parse raises `decimal.InvalidOperation` first override.
    fn nan_result(&self, _to: &str) -> Result<String> {
        Err(N2WError::Value("cannot convert NaN to integer".into()))
    }

    // ---- introspection ---------------------------------------------------

    /// Python's `getattr(converter, "MAXVAL", None)` — the `maxval()` API.
    /// Engine languages get it from their card table (Base sets
    /// `MAXVAL = 1000 * top_card`); self-contained ones mostly lack the
    /// attribute (None). The zero sentinel in `maxval()` means "unset".
    fn python_maxval(&self) -> Option<BigInt> {
        let m = self.maxval();
        if m.is_zero() {
            None
        } else {
            Some(m.clone())
        }
    }
}

/// Python's `Num2Word_Base.to_fraction`.
pub fn default_to_fraction<L: Lang + ?Sized>(
    lang: &L,
    numerator: &BigInt,
    denominator: &BigInt,
) -> Result<String> {
    if denominator.is_zero() {
        return Err(N2WError::ZeroDivision(
            "denominator must not be zero".into(),
        ));
    }
    if denominator.is_one() || numerator.is_zero() {
        return lang.to_cardinal(numerator);
    }
    let is_negative = numerator.is_negative() ^ denominator.is_negative();
    let abs_n = numerator.abs();
    let abs_d = denominator.abs();
    let sign = if is_negative {
        format!("{} ", lang.negword().trim())
    } else {
        String::new()
    };
    let num_word = lang.to_cardinal(&abs_n)?;
    let mut den_word = lang.to_ordinal(&abs_d)?;
    if !abs_n.is_one() {
        // Python appends a bare "s"; languages override for real plurals.
        den_word.push('s');
    }
    Ok(format!("{}{} {}", sign, num_word, den_word))
}

/// Python's `splitnum`. Returns `None` where Python falls off the loop and
/// implicitly returns `None` (value larger than every card).
pub fn splitnum<L: Lang + ?Sized>(lang: &L, value: &BigInt) -> Option<Vec<Node>> {
    let cards = lang.cards();
    for (elem, word) in cards.iter_from(value) {
        let mut out: Vec<Node> = Vec::new();
        let (div, mod_) = if value.is_zero() {
            (BigInt::one(), BigInt::zero())
        } else {
            value.div_mod_floor(elem)
        };

        if div.is_one() {
            let one = BigInt::one();
            let w = cards.get(&one).unwrap_or("").to_string();
            out.push(Node::leaf(w, one));
        } else {
            if &div == value {
                // Tally systems (e.g. Roman numerals): repeat the word `div`
                // times rather than recursing, matching Python's `div * word`.
                let reps = div.to_string().parse::<usize>().unwrap_or(0);
                return Some(vec![Node::leaf(word.repeat(reps), &div * elem)]);
            }
            out.push(Node::List(splitnum(lang, &div)?));
        }

        out.push(Node::leaf(word.clone(), elem.clone()));

        if !mod_.is_zero() {
            out.push(Node::List(splitnum(lang, &mod_)?));
        }

        return Some(out);
    }
    None
}

/// Python's `clean`: fold the tree down to a single `(text, num)` leaf.
///
/// Mirrors the original's quirk where the tail `val[2:]` is appended as a
/// *nested list* rather than spliced, which changes how the next iteration
/// sees it.
pub fn clean<L: Lang + ?Sized>(lang: &L, val: Vec<Node>) -> Node {
    let mut val = val;
    while val.len() != 1 {
        let mut out: Vec<Node> = Vec::new();
        if val.len() >= 2 && val[0].is_leaf() && val[1].is_leaf() {
            let (lt, ln) = match &val[0] {
                Node::Leaf(t, n) => (t.clone(), n.clone()),
                _ => unreachable!(),
            };
            let (rt, rn) = match &val[1] {
                Node::Leaf(t, n) => (t.clone(), n.clone()),
                _ => unreachable!(),
            };
            let (mt, mn) = lang.merge((&lt, &ln), (&rt, &rn));
            out.push(Node::Leaf(mt, mn));
            if val.len() > 2 {
                out.push(Node::List(val[2..].to_vec()));
            }
        } else {
            for elem in val.into_iter() {
                match elem {
                    Node::List(inner) => {
                        if inner.len() == 1 {
                            out.push(inner.into_iter().next().unwrap());
                        } else {
                            out.push(clean(lang, inner));
                        }
                    }
                    leaf => out.push(leaf),
                }
            }
        }
        val = out;
    }
    val.into_iter().next().unwrap()
}

/// Python's `Num2Word_Base.to_cardinal` for integral input.
pub fn default_to_cardinal<L: Lang + ?Sized>(lang: &L, value: &BigInt) -> Result<String> {
    let mut out = String::new();
    let mut v = value.clone();
    if v.is_negative() {
        v = v.abs();
        out = format!("{} ", lang.negword().trim());
    }

    if &v >= lang.maxval() {
        return Err(N2WError::Overflow(format!(
            "abs({}) must be less than {}.",
            v,
            lang.maxval()
        )));
    }

    let tree = splitnum(lang, &v).ok_or_else(|| {
        N2WError::Overflow(format!("abs({}) must be less than {}.", v, lang.maxval()))
    })?;
    let node = clean(lang, tree);
    let words = match node {
        Node::Leaf(t, _) => t,
        Node::List(_) => return Err(N2WError::Type("clean did not reduce".into())),
    };
    Ok(lang.title(&format!("{}{}", out, words)))
}

/// Python's `set_low_numwords`: words map to descending values ending at 0.
pub fn set_low_numwords(cards: &mut Cards, numwords: &[&str]) {
    let n = numwords.len();
    for (i, word) in numwords.iter().enumerate() {
        cards.insert(BigInt::from(n - 1 - i), *word);
    }
}

pub fn set_mid_numwords(cards: &mut Cards, mid: &[(i64, &str)]) {
    for (k, v) in mid {
        cards.insert(BigInt::from(*k), *v);
    }
}