1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
//! Port of `lang_TT.py` (Tatar).
//!
//! Shape: **self-contained**. `Num2Word_TT` subclasses `Num2Word_Base`, but
//! its `setup` defines only flat `ones`/`tens` lists plus three scale words —
//! no `high_numwords`/`mid_numwords`/`low_numwords`. Python therefore never
//! builds `self.cards` and never sets `MAXVAL`, and `to_cardinal` is
//! overridden outright to drive a hand-written `_int_to_word` recursion.
//! Consequently `cards`/`maxval`/`merge` stay at their trait defaults here,
//! and there is **no overflow check at all** — see bug 2 below for what
//! happens past the top of the scale table.
//!
//! Inheritance chain: `Num2Word_TT` -> `Num2Word_Base`. Every one of the four
//! in-scope methods is overridden by TT, so nothing is inherited from
//! `Num2Word_Base` on the in-scope paths:
//! * `to_cardinal` — overridden (below)
//! * `to_ordinal` — overridden: `to_cardinal(n) + "-нче"`
//! * `to_ordinal_num` — overridden: `str(n) + "."` (the base returns `n`
//! bare, so the trait default is *not* correct here)
//! * `to_year` — overridden: `to_cardinal(val)`, ignoring `longval`
//!
//! No cross-call mutable state: `setup` only populates constant tables, and
//! none of the four methods writes to `self`. Nothing for the dispatcher to
//! skip.
//!
//! # Faithfully reproduced Python bugs
//!
//! This is a port, not a rewrite. All of the following look wrong and are
//! exactly what Python emits — each is confirmed against the frozen corpus:
//!
//! 1. **Zero is English.** `_int_to_word` opens with
//! `return self.ones[0] if self.ones[0] else "zero"`. `ones[0]` is the
//! empty string (a placeholder so the list can be indexed by digit), which
//! is falsy, so the guard *always* takes the fallback branch and every
//! Tatar zero comes out as the English "zero". Hence `to_cardinal(0)` ==
//! "zero" and `to_ordinal(0)` == "zero-нче" (corpus rows confirm both).
//! The `if self.ones[0]` test is dead code that can never fire.
//! 2. **Numbers >= 10^9 come back as digits.** The `elif` ladder in
//! `_int_to_word` stops at `number < 1000000000` and the trailing `else`
//! is `return str(number)` — a "fallback for very large numbers" that
//! emits no words whatsoever. So `to_cardinal(10**9)` == "1000000000" and
//! `to_ordinal(10**12)` == "1000000000000-нче". No exception, no billion
//! word: the scale table simply has no entry above `million`. This is why
//! the value must stay a `BigInt` — the fallback is `str()` on an
//! unbounded int.
//! 3. **The negative word is English too.** `setup` sets
//! `negword = "minus "`, not a Tatar form, so `to_cardinal(-1)` ==
//! "minus бер".
//! 4. **`бер йөз` for 100.** Hundreds always carry an explicit "бер" ("one"),
//! including the bare hundred: `result = self.ones[hundreds_val] + " " +
//! self.hundred` with no `hundreds_val == 1` special case. Likewise
//! `to_cardinal(1000)` == "бер мең" and `to_cardinal(10**6)` ==
//! "бер миллион". Idiomatic or not, it is what ships.
//! 5. **Ordinals are cardinal + a hyphenated suffix, unconditionally.** No
//! stem changes, no vowel harmony, no special-casing of the digit-fallback
//! range — `to_ordinal` is a bare string concatenation, so the digit
//! fallback of bug 2 flows straight through it.
//!
//! # Error variants
//!
//! For integer input every one of the four integer paths is total:
//! `to_cardinal` cannot raise (the `else` fallback of bug 2 catches everything
//! the ladder misses, and there is no `MAXVAL` check to overflow), and
//! `to_ordinal` / `to_ordinal_num` / `to_year` are pure concatenation over it.
//! The corpus agrees: every `cardinal`/`ordinal`/`ordinal_num`/`year` row for
//! "tt" is `"ok": true`. The remaining `ok: false` rows are `fraction`
//! (TypeError, out of scope) and `cheque` (NotImplementedError, handled below).
//!
//! The currency surface adds exactly two error paths, both ported below:
//! `NotImplemented` out of `to_cheque` for a code outside `CURRENCY_FORMS`,
//! and `Value` out of `to_currency` for a float whose `repr` is exponential
//! (see [`python_str_float`]). `to_currency` itself can never raise
//! NotImplementedError — see bug 6.
//!
//! # Currency: what Python actually defines
//!
//! `Num2Word_TT` declares its **own** three-entry `CURRENCY_FORMS` as a class
//! attribute. It does *not* descend from `Num2Word_EUR`, so the shared-dict
//! mutation `Num2Word_EN.__init__` performs (`self.CURRENCY_FORMS["EUR"] =
//! ...`, which rewrites EUR's table in place for the 16 classes that read it)
//! cannot reach TT. Its EUR entry is its own literal. Confirmed against the
//! live interpreter rather than the source:
//!
//! ```text
//! CONVERTER_CLASSES['tt'].CURRENCY_FORMS
//! {'RUB': (('сум', 'сум'), ('тиен', 'тиен')),
//! 'USD': (('dollar', 'dollars'), ('cent', 'cents')),
//! 'EUR': (('euro', 'euros'), ('cent', 'cents'))}
//! insertion order: ['RUB', 'USD', 'EUR']
//! CONVERTER_CLASSES['tt'].CURRENCY_PRECISION {}
//! CONVERTER_CLASSES['tt'].CURRENCY_ADJECTIVES {}
//! ```
//!
//! `to_currency` is overridden **wholesale** and shares no code with
//! `Num2Word_Base.to_currency`: it never reaches `pluralize`,
//! `_money_verbose`, `_cents_verbose`, `_cents_terse`,
//! `parse_currency_parts`, `prefix_currency` or `CURRENCY_PRECISION`. Those
//! hooks are therefore left at their trait defaults here.
//!
//! `to_cheque` is *not* overridden, so `Num2Word_Base.to_cheque` runs and
//! [`crate::currency::default_to_cheque`] serves it unchanged. It needs only
//! [`Lang::currency_forms`] (whose `None` is what turns Python's `KeyError`
//! into `NotImplementedError`), [`Lang::lang_name`] (for that message), the
//! default `currency_precision` of 100 — `CURRENCY_PRECISION` is the empty
//! dict inherited from `Num2Word_Base`, never mutated, so `.get(code, 100)` is
//! 100 for every code — and the default `money_verbose`, which routes back
//! through TT's own `to_cardinal`.
//!
//! # Faithfully reproduced Python bugs, currency edition
//!
//! 6. **An unknown currency code silently becomes roubles.**
//! `self.CURRENCY_FORMS.get(currency, list(self.CURRENCY_FORMS.values())[0])`
//! falls back to the *first* entry instead of raising, so `to_currency` has
//! no NotImplementedError path at all and GBP/JPY/CHF/... all render with
//! Tatar `сум`/`тиен`. The corpus pins this:
//! `{"lang": "tt", "to": "currency:GBP", "arg": "1", "out": "бер сум"}`.
//! `to_cheque` — which is base's, not TT's — does *not* share the fallback
//! and raises for those same codes, so the two surfaces disagree about
//! which codes exist.
//! 7. **`CURRENCY_PRECISION` is ignored by `to_currency`.** `parts[1][:2]` is
//! hardcoded, so a 3-decimal currency loses its mils and a 0-decimal one
//! gains cents that cannot exist. Both follow from bug 6 anyway (neither
//! KWD nor JPY is in the table), and TT's dict is empty regardless, so even
//! base's `to_cheque` uses divisor 100 for them.
//! 8. **A float with zero cents drops the segment; base would print it.**
//! `if cents and right:` is a truthiness test on the *number*, so `1.0`
//! (`parts[1] == "0"` -> `right == 0`) renders "бер euro", exactly like int
//! `1`. Base reaches the same output for `1` by a different route
//! (`isinstance(val, int)`) but renders `1.0` as "one euro, zero cents".
//! The `CurrencyValue` arms are still kept distinct here because they
//! produce different `str(val)` strings ("1" vs "1.0"), which is what the
//! code branches on.
//! 9. **`cents=False` omits the cents, it does not abbreviate them.** Base's
//! `cents=False` means "render the subunit as digits" via `_cents_terse`;
//! TT's `if cents and right:` drops the whole segment.
//! 10. **`adjective` is accepted and completely ignored** — no
//! `prefix_currency` call, and `CURRENCY_ADJECTIVES` is empty regardless.
use crate;
use crate;
use crateFloatValue;
use crate;
use BigDecimal;
use BigInt;
use Integer;
use ;
use HashMap;
use FromStr;
/// `self.ones`. Index 0 is the empty string — see bug 1; it is never read as
/// a word, only as the (always-falsy) zero guard.
const ONES: = ;
/// `self.tens`. Index 0 is an unused placeholder (the `number < 10` arm of
/// the ladder catches every value that would index it).
const TENS: = ;
const HUNDRED: &str = "йөз";
const THOUSAND: &str = "мең";
const MILLION: &str = "миллион";
/// `self.negword`. Trailing space is significant: Python concatenates it
/// directly onto the number word (`ret + self._int_to_word(...)`).
const NEGWORD: &str = "minus ";
/// `self.pointword`. Only reachable on the float path, which is out of scope;
/// kept so `Lang::pointword` reports what `setup` actually assigns.
const POINTWORD: &str = "point";
/// `Num2Word_TT.to_currency`'s own default: `separator=" "`. Note this is
/// *not* `Num2Word_Base`'s `","` — see [`BASE_DEFAULT_SEPARATOR`].
const SEPARATOR: &str = " ";
/// `Num2Word_Base.to_currency`'s default separator, which both callers use as
/// a de-facto "caller said nothing" sentinel.
///
/// Python resolves a default argument at the *call site*: omit `separator=`
/// and `Num2Word_TT.to_currency` binds its own `" "`. The `Lang` trait takes
/// `separator: &str` unconditionally, so that resolution has already happened
/// by the time we are called — and both callers hardcode **base**'s default
/// rather than the language's:
///
/// * `num2words2/__init__.py`'s Rust fast path: `kwargs.get("separator", ",")`
/// * `bench/diff_test.py`: `_rust.to_currency(lang, arg, is_int, code, True, ",", False)`
///
/// This matters more for TT than for base, because the two apply the separator
/// differently: base emits `separator + " "` (so `","` gives `"euros, thirty"`)
/// while TT emits the separator *alone* as the whole joint
/// (`result += separator + cents_str`). TT's `" "` default is what supplies
/// that space at all.
///
/// The frozen corpus was generated through the *Python* converter with no
/// `separator=` kwarg, so every "tt" currency row shows TT's `" "`:
///
/// ```text
/// {"lang": "tt", "to": "currency:EUR", "arg": "12.34",
/// "out": "ун ике euros утыз дүрт cents"}
/// ```
///
/// Taking the incoming `","` at face value would render
/// `"ун ике euros,утыз дүрт cents"` — no space at all — and fail all 54 rows
/// that carry cents. So `","` is read back as "unset" and TT's own default
/// restored. This is right across the whole reachable input space bar one
/// case: an explicit `separator=","`, which Python renders with a comma and
/// this renders with a space. A real fix belongs at the boundary (pass
/// `Option<&str>` and let the language supply its default), which is
/// `base.rs` / `currency.rs` / `__init__.py` and out of scope for this file;
/// it is flagged in the report. `lang_oc.rs`, `lang_as.rs`, `lang_ba.rs` and
/// `lang_br.rs` — the other languages whose Python signature carries a
/// non-`","` default — resolve it the same way.
const BASE_DEFAULT_SEPARATOR: &str = ",";
/// Python's `str(value)` for a **non-negative float**, reconstructed from the
/// `BigDecimal` the shim parsed out of that very string.
///
/// `to_currency` does `parts = str(val).split(".")` and then `int()`s the
/// pieces, so it branches on the *notation* `repr` chose, not on the value.
/// `BigDecimal`'s own `Display` is not that function and disagrees in three
/// ways that are reachable here:
///
/// | input `str(v)` | `BigDecimal::to_string()` | Python `str(v)` |
/// |---|---|---|
/// | `1e-05` | `0.00001` | `1e-05` |
/// | `5e-324` | `5E-324` | `5e-324` |
/// | `0.0` | `0` | `0.0` |
///
/// The first is the damaging one: Python feeds `"1e-05"` to `int()` and raises
/// ValueError, where `Display` would hand back a clean `"0.00001"` and invent
/// an answer Python never produces.
///
/// So the notation is derived rather than borrowed. CPython's float repr emits
/// the shortest round-tripping digit string plus a decimal-point position
/// `decpt`, and switches to exponential form iff `decpt <= -4 || decpt > 16`.
/// `as_bigint_and_exponent()` yields `(int_val, scale)` with
/// `value == int_val * 10^-scale`; `int_val` carries no leading zeros, so
/// `decpt == len(int_val) - scale` — invariant to the trailing zeros a literal
/// like `"1.0"` contributes, since they lift `len` and `scale` in lockstep.
/// Verified to round-trip `str(abs(float))` on 10,026 values spanning the
/// subnormals, both notation thresholds and 1e±300.
///
/// Caveat: this is `str(float)`. `__init__.py` also lets a `decimal.Decimal`
/// reach `CurrencyValue::Decimal`, and `str(Decimal)` follows different rules
/// (it preserves the declared scale and uses `E+` notation on other
/// thresholds). No corpus row exercises it; flagged in the report.
/// Python's bare `int(token)` over a `str(val)` fragment.
///
/// The tokens reaching this are digit runs in every plain-notation case; the
/// only way it fails is an exponential `repr` reaching `to_currency`, where
/// Python raises ValueError with this exact message — `int("1e-05")` for the
/// whole string, or `int("5e")` once `parts[1][:2]` has sliced `"5e-05"` down.
/// `BigInt::from_str`'s own error text is a num-bigint string ("invalid digit
/// found in string"), so the message is built here instead of borrowed.
/// Python's `str(number)` for the value that reaches `Num2Word_TT.to_cardinal`
/// on the float/Decimal path.
///
/// TT overrides `to_cardinal` and handles non-integers **inline**, from the
/// *string* form of the number:
///
/// ```python
/// n = str(number).strip()
/// ...
/// left, right = n.split(".", 1)
/// ret += self._int_to_word(int(left)) + " " + self.pointword + " "
/// for digit in right:
/// ret += self._int_to_word(int(digit)) + " "
/// ```
///
/// It never touches `base.float2tuple`, `self.precision`, `round()` or the
/// `< 0.01` artefact heuristic — the fractional digits are read *literally* off
/// `str(number)`. So the two float-path traps (banker's rounding, the
/// `674.9999...` rescue) do **not** apply here: `2.675` renders "алты җиде биш"
/// (repr digits 6·7·5), not the reconstructed-integer 675, and `1.005` keeps
/// its literal "zero zero биш". The whole behaviour therefore hinges on
/// reproducing `str(number)` byte for byte, which is what this does.
///
/// * **Float arm** — reproduce CPython's `repr`/`str(float)`. Rust's
/// `format!("{}", f)` is the same shortest-round-trip digit string (never in
/// exponent form for f64), so parsing it into a `BigDecimal` and running it
/// through [`python_str_float`] yields exactly `str(abs(f))`; the sign is put
/// back from the f64's sign bit so `str(-0.0)` stays "-0.0" as in Python.
/// * **Decimal arm** — reproduce `str(Decimal)`, which *preserves the declared
/// scale* (trailing zeros): `Decimal("1.10")` is "1.10", not "1.1". Neither
/// [`python_str_float`] (shortest, trims zeros) nor `BigDecimal::Display`
/// (collapses `0.00` to `0`) does that, so it is rebuilt from
/// `(int_val, scale)` directly. `scale <= 0` is an integer-valued Decimal
/// (e.g. `Decimal("5")` -> "5"), which then flows down the dotless `int(n)`
/// branch, exactly like Python.