-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathw2n_sentence.rs
More file actions
2336 lines (2184 loc) · 81 KB
/
Copy pathw2n_sentence.rs
File metadata and controls
2336 lines (2184 loc) · 81 KB
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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Port of the words2num2 **sentence-level API**.
//!
//! Sources (the specification — bugs included):
//! - `words2num2/__init__.py`: `_resolve_lang`, `words2num_sentence`, `convert_sentence`, `sentence_to_words`
//! - `words2num2/converters/sentence.py`: `SentenceConverter`
//! - `words2num2/converters/auto.py`: `UNITS`, `CURRENCIES`, `Quantity`, `auto_parse`, `auto_parse_sentence`
//!
//! Every per-language `Words2Num_*` converter is dispatched **in Rust** by the
//! [`Converter`] abstraction below: `en` uses the hand-written grammar
//! ([`crate::w2n_lang_en`]); every other locale uses the generic reverse-table
//! lookup ([`crate::lookup`]) plus the `_parse_literal` tail — exactly what
//! `Words2Num_Base` does in Python, but without leaving Rust.
//!
//! # Fidelity notes — behaviour reproduced on purpose
//!
//! Verified against the live interpreter. These all look wrong and are all
//! correct ports:
//!
//! * `words2num_sentence("nineteen ninety nine")` → `"118"`, **not** `"1999"`.
//! The sentence walker calls `to_cardinal` (19 + 99), never `to_year`.
//! * `words2num_sentence("minus forty two")` → `"minus 42"`. A run may not
//! *start* with a connector, and `to_cardinal("minus")` raises, so "minus"
//! is not a run head. Same for `"a hundred and one dogs"` → `"a 101 dogs"`.
//! * `words2num_sentence("point five")` → `"0.5"`. `to_cardinal("point")`
//! returns `Decimal(0)` rather than raising, so "point" *is* a valid head.
//! * `words2num_sentence("\"forty-two\"")` → `"42\""`. Only *trailing*
//! punctuation is stripped, and the trailing quote is re-appended.
//! * `words2num_sentence("zero point zero zero zero zero zero zero one")`
//! → `"1E-7"` — Python's `Decimal.__str__` flips to scientific notation
//! once the adjusted exponent drops below -6. See [`py_decimal_str`].
//! * `auto_parse("$5kn")` raises **KeyError**, not `Words2NumError`: the
//! regex accepts `[kKmMbBtT][nN]?` but `SCALE_SUFFIXES` only holds
//! `k K m M b B bn t T tn`. It escapes `auto_parse_sentence` uncaught
//! because `_replace` only catches `Words2NumError`. See [`W2nError::Key`].
//! * `parse_number_string("0.5", lang="fr")` → `5`. French decimal is `,`,
//! so the dot is dropped as a stray separator and `"05"` parses as an int.
//! * `_try_word_unit`'s `long_name = info.long` assignment is dead — it is
//! unconditionally overwritten by the `next(...)` scan below it. Not ported.
//! * `word_units["pound sterling"]` is unreachable: the key holds a space but
//! the lookup token comes from `rsplit(None, 1)`, so it never contains one.
//! * The `°[CF]?` alternative appears **twice** in `_try_digit_unit`'s regex.
//! Harmless; the second is dead. Kept in the comment, folded in the code.
use bigdecimal::num_traits::FromPrimitive;
use bigdecimal::BigDecimal;
use num_bigint::BigInt;
use std::collections::HashMap;
use std::str::FromStr;
// ===========================================================================
// Errors
// ===========================================================================
/// The exception kinds this layer can produce, each carrying the *exact*
/// message Python formats. The PyO3 binder maps each variant onto the matching
/// Python exception class.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum W2nError {
/// `words2num2.base.Words2NumError` — a `ValueError` subclass.
Words2Num(String),
/// `NotImplementedError` — raised by `_resolve_lang`.
NotImplemented(String),
/// `KeyError` — `SCALE_SUFFIXES[scale_str]` misses (e.g. `"$5kn"`).
/// Python's `KeyError` stringifies as `repr(key)`, hence the odd quoting.
Key(String),
}
impl W2nError {
/// The message text Python would carry (`str(exc)`).
///
/// Note `KeyError` is special-cased: `str(KeyError("kn"))` is `"'kn'"`,
/// not `"kn"`.
pub fn message(&self) -> String {
match self {
W2nError::Words2Num(m) | W2nError::NotImplemented(m) => m.clone(),
W2nError::Key(k) => py_repr_str(k),
}
}
}
// ===========================================================================
// Values — words2num2 returns int | float | Decimal
// ===========================================================================
/// A value as words2num2 produces it.
///
/// `Dec` mirrors Python's `decimal.Decimal` as the (coefficient, exponent)
/// pair that `Decimal.as_tuple()` exposes: `BigDecimal`'s
/// `as_bigint_and_exponent()` returns `(digits, scale)` where the value is
/// `digits * 10^-scale`, i.e. `_int = digits.abs()` and `_exp = -scale`.
/// Keeping the *unnormalised* scale is load-bearing — `Decimal("2.0")` and
/// `Decimal("2")` are equal but stringify differently.
#[derive(Debug, Clone, PartialEq)]
pub enum W2nValue {
Int(BigInt),
Float(f64),
Dec(BigDecimal),
}
impl W2nValue {
/// Python's `str(value)`.
pub fn py_str(&self) -> String {
match self {
W2nValue::Int(i) => i.to_string(),
W2nValue::Float(f) => py_float_repr(*f),
W2nValue::Dec(d) => {
let (digits, scale) = d.as_bigint_and_exponent();
py_decimal_str(&digits, scale)
}
}
}
/// Python's `repr(value)`. Differs from `str` only for `Decimal`.
pub fn py_repr(&self) -> String {
match self {
W2nValue::Dec(_) => format!("Decimal('{}')", self.py_str()),
_ => self.py_str(),
}
}
/// `value == 1 or value == -1`, as Python's `value in (1, -1, 1.0, -1.0)`
/// evaluates it (membership uses `==`, so `Decimal("1")` matches).
fn is_unit_magnitude(&self) -> bool {
match self {
W2nValue::Int(i) => {
let one = BigInt::from(1);
*i == one || *i == -one
}
W2nValue::Float(f) => *f == 1.0 || *f == -1.0,
W2nValue::Dec(d) => {
let one = BigDecimal::from(1);
*d == one || *d == -one
}
}
}
}
/// Convert an English-grammar value ([`crate::w2n_lang_en::W2nValue`]) into a
/// sentence-layer [`W2nValue`].
///
/// LIMITATION: `PyDec` carries a signed zero (`Decimal('-0.0')`), which
/// `BigDecimal` cannot; a negative-zero decimal therefore loses its sign here.
/// It is unreachable through the sentence walker (a run cannot start with
/// "minus", so a negative decimal never heads a run) and through the tested
/// `auto_parse` paths.
fn en_to_sentence_value(v: crate::w2n_lang_en::W2nValue) -> W2nValue {
use crate::w2n_lang_en::W2nValue as E;
match v {
E::Int(i) => W2nValue::Int(i),
E::Float(f) => W2nValue::Float(f),
E::Dec(d) => W2nValue::Dec(d.to_bigdecimal()),
}
}
// ===========================================================================
// Python string / number formatting primitives
// ===========================================================================
/// Python's `repr()` for `str`, used by every `%r` in the source.
///
/// Quote selection matches CPython: single quotes unless the string contains
/// a single quote and no double quote.
///
/// LIMITATION: CPython escapes non-printable *non-ASCII* (per the unicodedata
/// category) as `\xXX` / `\uXXXX` / `\UXXXXXXXX`. Here non-ASCII passes
/// through verbatim. Every `%r` reachable in this module formats a locale code,
/// a unit token or a type name, so the gap is unreachable in practice.
pub fn py_repr_str(s: &str) -> String {
let quote = if s.contains('\'') && !s.contains('"') {
'"'
} else {
'\''
};
let mut out = String::with_capacity(s.len() + 2);
out.push(quote);
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c == quote => {
out.push('\\');
out.push(c);
}
c if (c as u32) < 0x20 || (c as u32) == 0x7f => {
out.push_str(&format!("\\x{:02x}", c as u32));
}
c => out.push(c),
}
}
out.push(quote);
out
}
/// Python's `repr()`/`str()` for `float` (they are the same in Python 3).
///
/// CPython's `format_float_short(..., 'r', ...)`: take the shortest digit
/// string that round-trips, then switch to exponential iff
/// `decpt <= -4 || decpt > 16`, where `decpt` is the decimal point position
/// (`value = 0.<digits> * 10^decpt`). `Py_DTSF_ADD_DOT_0` appends `.0` in the
/// fixed branch only.
///
/// Rust's `{:e}` already yields the shortest round-tripping digits, so it is
/// used purely as a digit/exponent source and then reformatted Python-style.
/// This matters: Rust's own `{}` would print `1e16` as `10000000000000000`
/// and `1e-5` as `0.00001`, where Python prints `1e+16` and `1e-05`.
pub fn py_float_repr(v: f64) -> String {
if v.is_nan() {
return "nan".to_string();
}
if v.is_infinite() {
return if v > 0.0 { "inf" } else { "-inf" }.to_string();
}
let sci = format!("{:e}", v); // e.g. "-1.2345e3", "0e0", "1e-7"
let (mant, exp) = sci.split_once('e').expect("{:e} always emits an exponent");
let exp: i32 = exp.parse().expect("{:e} exponent is an integer");
let neg = mant.starts_with('-');
let mant = mant.trim_start_matches('-');
let digits: String = mant.chars().filter(|c| *c != '.').collect();
let decpt = exp + 1;
let sign = if neg { "-" } else { "" };
let nd = digits.len() as i32;
if decpt <= -4 || decpt > 16 {
// Exponential: d[.ddd]e{+,-}XX, exponent at least two digits.
let mut m = String::from(&digits[..1]);
if nd > 1 {
m.push('.');
m.push_str(&digits[1..]);
}
let e = decpt - 1;
let (esign, eabs) = if e < 0 { ("-", -e) } else { ("+", e) };
return format!("{}{}e{}{:02}", sign, m, esign, eabs);
}
if decpt <= 0 {
format!("{}0.{}{}", sign, "0".repeat((-decpt) as usize), digits)
} else if decpt >= nd {
// ADD_DOT_0
format!(
"{}{}{}.0",
sign,
digits,
"0".repeat((decpt - nd) as usize)
)
} else {
format!(
"{}{}.{}",
sign,
&digits[..decpt as usize],
&digits[decpt as usize..]
)
}
}
/// Python's `Decimal.__str__` (from `_pydecimal.__str__`, `eng=False`,
/// `context.capitals = 1`), reconstructed from the coefficient and exponent:
///
/// ```text
/// leftdigits = _exp + len(_int)
/// if _exp <= 0 and leftdigits > -6: dotplace = leftdigits # plain
/// else: dotplace = 1 # scientific
/// ```
///
/// This is what turns `Decimal("0.0000001")` into `"1E-7"`.
///
/// `digits`/`scale` come from `BigDecimal::as_bigint_and_exponent()`:
/// value = `digits * 10^-scale`, so `_exp = -scale` and `_int = |digits|`.
pub fn py_decimal_str(digits: &BigInt, scale: i64) -> String {
let neg = digits.sign() == num_bigint::Sign::Minus;
let int_str = digits.magnitude().to_string(); // _int, unsigned
let exp: i64 = -scale; // _exp
let len_int = int_str.chars().count() as i64;
let leftdigits = exp + len_int;
let dotplace = if exp <= 0 && leftdigits > -6 {
leftdigits
} else {
1
};
let (intpart, fracpart) = if dotplace <= 0 {
(
String::from("0"),
format!(".{}{}", "0".repeat((-dotplace) as usize), int_str),
)
} else if dotplace >= len_int {
(
format!("{}{}", int_str, "0".repeat((dotplace - len_int) as usize)),
String::new(),
)
} else {
let cut = dotplace as usize;
(int_str[..cut].to_string(), format!(".{}", &int_str[cut..]))
};
let expo = if leftdigits == dotplace {
String::new()
} else {
format!("E{:+}", leftdigits - dotplace)
};
format!(
"{}{}{}{}",
if neg { "-" } else { "" },
intpart,
fracpart,
expo
)
}
// ===========================================================================
// Unicode / Python text primitives
// ===========================================================================
/// Starts of every 10-codepoint run in Unicode category `Nd`, which is exactly
/// what Python's `\d` matches for `str` patterns (and what `int()` / `float()`
/// accept). Every `Nd` block is a contiguous ten with digit value 0 at the
/// start, so a block start plus an offset is all that is needed.
///
/// Generated from the local interpreter (`unicodedata.unidata_version` 13.0.0,
/// CPython 3.9). A newer CPython knows a few more blocks; regenerate if the
/// oracle moves. Without this, `auto_parse("٤٢")` would fail where Python
/// returns `42`.
const ND_BLOCKS: [u32; 65] = [
0x0030, 0x0660, 0x06F0, 0x07C0, 0x0966, 0x09E6, 0x0A66, 0x0AE6, 0x0B66, 0x0BE6, 0x0C66, 0x0CE6,
0x0D66, 0x0DE6, 0x0E50, 0x0ED0, 0x0F20, 0x1040, 0x1090, 0x17E0, 0x1810, 0x1946, 0x19D0, 0x1A80,
0x1A90, 0x1B50, 0x1BB0, 0x1C40, 0x1C50, 0xA620, 0xA8D0, 0xA900, 0xA9D0, 0xA9F0, 0xAA50, 0xABF0,
0xFF10, 0x104A0, 0x10D30, 0x11066, 0x110F0, 0x11136, 0x111D0, 0x112F0, 0x11450, 0x114D0,
0x11650, 0x116C0, 0x11730, 0x118E0, 0x11950, 0x11C50, 0x11D50, 0x11DA0, 0x16A60, 0x16B50,
0x1D7CE, 0x1D7D8, 0x1D7E2, 0x1D7EC, 0x1D7F6, 0x1E140, 0x1E2F0, 0x1E950, 0x1FBF0,
];
/// The digit value of `c` if it is in category `Nd`, else `None`.
pub fn digit_value(c: char) -> Option<u32> {
let cp = c as u32;
match ND_BLOCKS.binary_search(&cp) {
Ok(_) => Some(0),
Err(0) => None,
Err(i) => {
let start = ND_BLOCKS[i - 1];
if cp - start < 10 {
Some(cp - start)
} else {
None
}
}
}
}
/// Python's regex `\d` for `str` patterns.
pub fn is_unicode_digit(c: char) -> bool {
digit_value(c).is_some()
}
/// Fold every `Nd` digit down to ASCII, which is what `int()` / `float()` do
/// internally before parsing.
fn to_ascii_digits(s: &str) -> String {
s.chars()
.map(|c| match digit_value(c) {
Some(v) if !c.is_ascii_digit() => char::from_digit(v, 10).unwrap_or(c),
_ => c,
})
.collect()
}
/// Python's `str.isspace()` per character — equivalently the regex `\s` for
/// `str` patterns. Rust's `char::is_whitespace` agrees except for the four
/// C0 separators `\x1c-\x1f`, which Python counts and Rust does not.
pub fn py_is_space(c: char) -> bool {
c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
}
/// Python's `str.isspace()` — all characters are space, and the string is
/// non-empty.
fn py_str_isspace(s: &str) -> bool {
!s.is_empty() && s.chars().all(py_is_space)
}
/// Python's `str.strip()` (no argument).
fn py_strip(s: &str) -> &str {
s.trim_matches(py_is_space)
}
/// Python's `str.split()` (no argument): split on runs of whitespace,
/// discarding empty fields.
fn py_split_whitespace(s: &str) -> Vec<&str> {
s.split(py_is_space).filter(|p| !p.is_empty()).collect()
}
/// Python's `str.rsplit(None, 1)`.
///
/// Trailing whitespace is skipped, the last whitespace-free run becomes the
/// tail, and the head keeps *its own* leading whitespace but loses the
/// separator run — `" a b ".rsplit(None, 1) == [" a", "b"]`.
fn py_rsplit_once_ws(s: &str) -> Vec<&str> {
let chars: Vec<(usize, char)> = s.char_indices().collect();
let mut end = chars.len();
while end > 0 && py_is_space(chars[end - 1].1) {
end -= 1;
}
if end == 0 {
return Vec::new();
}
let mut tail_start = end;
while tail_start > 0 && !py_is_space(chars[tail_start - 1].1) {
tail_start -= 1;
}
let byte_end = if end == chars.len() {
s.len()
} else {
chars[end].0
};
let tail = &s[chars[tail_start].0..byte_end];
let mut head_end = tail_start;
while head_end > 0 && py_is_space(chars[head_end - 1].1) {
head_end -= 1;
}
if head_end == 0 {
return vec![tail];
}
vec![&s[..chars[head_end].0], tail]
}
/// Python's `str.rstrip(chars)` for a single-character set.
fn py_rstrip_char(s: &str, ch: char) -> &str {
s.trim_end_matches(ch)
}
/// `re.sub(r"[\.,;:!\?\"']+$", "", s)` — drop the trailing punctuation run.
fn rstrip_punct(s: &str) -> &str {
s.trim_end_matches(['.', ',', ';', ':', '!', '?', '"', '\''])
}
/// `re.search(r"[\.,;:!\?\"']+$", s)` → `m.group()`, or `""`.
///
/// The leftmost match of `[...]+$` is exactly the maximal trailing run.
fn trailing_punct(s: &str) -> &str {
let kept = rstrip_punct(s);
&s[kept.len()..]
}
/// `re.search(r"[\.,;:!\?]$", tok)` — note this class has **no** quote
/// characters, unlike the strip above: `forty-two"` does not close a run.
fn ends_with_terminal_punct(s: &str) -> bool {
matches!(
s.chars().next_back(),
Some('.') | Some(',') | Some(';') | Some(':') | Some('!') | Some('?')
)
}
/// `re.findall(r"\S+|\s+", sentence)` — alternating runs of non-space and
/// space. The two branches are complementary, so this is a simple run split
/// and `parts.concat() == sentence` always holds.
fn tokenize(sentence: &str) -> Vec<String> {
let chars: Vec<char> = sentence.chars().collect();
let mut parts = Vec::new();
let mut i = 0;
while i < chars.len() {
let space = py_is_space(chars[i]);
let start = i;
while i < chars.len() && py_is_space(chars[i]) == space {
i += 1;
}
parts.push(chars[start..i].iter().collect());
}
parts
}
// ===========================================================================
// `_resolve_lang`
// ===========================================================================
/// The keys of `CONVERTER_CLASSES` in `words2num2/__init__.py`, in source
/// order. Membership in *this* set is what `_resolve_lang` tests, which is
/// **not** the same set as `num2words2_core::supported_lang_keys()` — the
/// aliases `jp` and `cn` live only here.
///
/// Must stay in sync with `__init__.py`.
pub const CONVERTER_LANGS: [&str; 120] = [
"af", "am", "ar", "as", "az", "ba", "be", "bg", "bn", "bo", "br", "bs", "ca", "ce", "cs", "cy",
"da", "de", "el", "en", "en_IN", "en_NG", "eo", "es", "es_CO", "es_CR", "es_GT", "es_NI",
"es_VE", "et", "eu", "fa", "fi", "fo", "fr", "fr_BE", "fr_CH", "fr_DZ", "gl", "gu", "ha", "haw",
"he", "hi", "hr", "ht", "hu", "hy", "id", "is", "it", "ja", "jw", "ka", "kk", "km", "kn", "ko",
"kz", "la", "lb", "ln", "lo", "lt", "lv", "mg", "mi", "mk", "ml", "mn", "mr", "ms", "mt", "my",
"ne", "nl", "nn", "no", "oc", "pa", "pl", "ps", "pt", "pt_BR", "ro", "ru", "sa", "sd", "si",
"sk", "sl", "sn", "so", "sq", "sr", "su", "sv", "sw", "ta", "te", "tet", "tg", "th", "tk", "tl",
"tr", "tt", "uk", "ur", "uz", "vi", "wo", "yi", "yo", "zh", "zh_CN", "zh_HK", "zh_TW", "jp",
"cn",
];
fn is_known_lang(k: &str) -> bool {
CONVERTER_LANGS.contains(&k)
}
/// Port of `words2num2._resolve_lang`.
///
/// ```python
/// if lang in CONVERTER_CLASSES: return lang
/// normalized = lang.replace("-", "_")
/// if normalized in CONVERTER_CLASSES: return normalized
/// parts = normalized.split("_")
/// if len(parts) >= 2:
/// candidate = "{}_{}".format(parts[0].lower(), parts[1].upper())
/// if candidate in CONVERTER_CLASSES: return candidate
/// if parts[0] in CONVERTER_CLASSES: return parts[0]
/// if normalized[:2] in CONVERTER_CLASSES: return normalized[:2]
/// raise NotImplementedError("language %r is not supported" % lang)
/// ```
///
/// `normalized[:2]` is a *character* slice and never panics on a short string
/// — `_resolve_lang("e")` falls through to the raise, it does not blow up.
/// That last rule is why `"eng"` resolves to `"en"` and `"en_US"` to `"en"`.
pub fn resolve_lang(lang: &str) -> Result<String, W2nError> {
if is_known_lang(lang) {
return Ok(lang.to_string());
}
let normalized = lang.replace('-', "_");
if is_known_lang(&normalized) {
return Ok(normalized);
}
// Python's str.split("_") keeps empty fields, unlike split(None).
let parts: Vec<&str> = normalized.split('_').collect();
if parts.len() >= 2 {
let candidate = format!("{}_{}", parts[0].to_lowercase(), parts[1].to_uppercase());
if is_known_lang(&candidate) {
return Ok(candidate);
}
if is_known_lang(parts[0]) {
return Ok(parts[0].to_string());
}
}
let two: String = normalized.chars().take(2).collect();
if is_known_lang(&two) {
return Ok(two);
}
Err(W2nError::NotImplemented(format!(
"language {} is not supported",
py_repr_str(lang)
)))
}
// ===========================================================================
// Converter — the per-locale dispatch, entirely in Rust
// ===========================================================================
/// `Words2Num_Base.NEGATIVE_WORDS` — every generic locale inherits this; no
/// locale module overrides it.
const BASE_NEGATIVE_WORDS: [&str; 2] = ["minus", "negative"];
/// A per-locale converter, standing in for `CONVERTER_CLASSES[lang]`.
enum Converter {
/// `Words2Num_EN` — the one hand-written grammar.
En,
/// A `Words2Num_Base` subclass; the field is the num2words2 core key its
/// `LANG` attribute carries (e.g. `"fr"`, `"zh_CN"`).
Table(&'static str),
}
/// Resolve a `CONVERTER_CLASSES` key (as produced by [`resolve_lang`]) to its
/// [`Converter`].
///
/// Most keys map to the same `LANG`, but three do not — matching the Python
/// registry: `"zh"`/`"cn"` both use `Words2Num_ZH_CN` (`LANG="zh_CN"`) and
/// `"jp"` uses `Words2Num_JA` (`LANG="ja"`).
fn converter_for(resolved: &str) -> Converter {
match resolved {
"en" => Converter::En,
"zh" | "cn" => Converter::Table("zh_CN"),
"jp" => Converter::Table("ja"),
// `resolved` is guaranteed to be one of CONVERTER_LANGS.
other => {
let key = CONVERTER_LANGS
.iter()
.copied()
.find(|k| *k == other)
.unwrap_or("en");
Converter::Table(key)
}
}
}
impl Converter {
/// `converter.to_cardinal(token)` did not raise? (`_token_is_number_word`).
fn is_number_word(&self, token: &str) -> bool {
self.to_cardinal(token).is_ok()
}
fn to_cardinal(&self, text: &str) -> Result<W2nValue, W2nError> {
match self {
Converter::En => en_convert(crate::en_to_cardinal(text)),
Converter::Table(lang) => base_convert(lang, text, false),
}
}
fn to_ordinal(&self, text: &str) -> Result<W2nValue, W2nError> {
match self {
Converter::En => en_convert(crate::en_to_ordinal(text)),
Converter::Table(lang) => base_convert(lang, text, true),
}
}
fn to_year(&self, text: &str) -> Result<W2nValue, W2nError> {
match self {
Converter::En => en_convert(crate::en_to_year(text)),
// `Words2Num_Base.to_year` == `self.to_cardinal`.
Converter::Table(lang) => base_convert(lang, text, false),
}
}
/// `Words2Num_Base.to_ordinal_num` — EN inherits it unchanged.
fn to_ordinal_num(&self, text: &str) -> Result<W2nValue, W2nError> {
base_ordinal_num(text)
}
/// `Words2Num_Base.to_currency` == `self.to_cardinal` (polymorphic, so EN
/// currency uses EN cardinal).
fn to_currency(&self, text: &str) -> Result<W2nValue, W2nError> {
self.to_cardinal(text)
}
/// Dispatch `getattr(converter, "to_{to}")(token, **kwargs)`.
///
/// `has_kwargs` models the sentence walker passing `**kwargs` through: the
/// standard converters accept none, so Python raises `TypeError` there,
/// which the walker swallows as "not a number word". An unknown `to`
/// raises `AttributeError` in Python (`getattr` miss) — also swallowed.
/// Both are represented here as an `Err` the caller drops.
fn convert(&self, to: &str, text: &str, has_kwargs: bool) -> Result<W2nValue, W2nError> {
if has_kwargs {
// TypeError: to_*() takes no keyword arguments.
return Err(W2nError::Words2Num(
"unexpected keyword argument".to_string(),
));
}
match to {
"cardinal" => self.to_cardinal(text),
"ordinal" => self.to_ordinal(text),
"year" => self.to_year(text),
"ordinal_num" => self.to_ordinal_num(text),
"currency" => self.to_currency(text),
// AttributeError: converter has no to_<to>.
_ => Err(W2nError::NotImplemented(format!(
"'Words2Num' object has no attribute 'to_{}'",
to
))),
}
}
}
/// Wrap the English grammar's `Result` into the sentence-layer types.
fn en_convert(
r: Result<crate::w2n_lang_en::W2nValue, crate::w2n_lang_en::W2nError>,
) -> Result<W2nValue, W2nError> {
match r {
Ok(v) => Ok(en_to_sentence_value(v)),
Err(e) => Err(W2nError::Words2Num(e.msg)),
}
}
/// Port of `Words2Num_Base._convert`: reverse-table lookup, then the
/// sign/digit/error tail (`_parse_literal`).
fn base_convert(lang: &str, text: &str, ordinal: bool) -> Result<W2nValue, W2nError> {
// `_rust_lookup`: guarded on `LANG in _RUST_LANGS`, and any error from the
// core is swallowed to `None` (`except Exception: return None`).
if crate::supported_langs().contains(&lang) {
let neg = [
BASE_NEGATIVE_WORDS[0].to_string(),
BASE_NEGATIVE_WORDS[1].to_string(),
];
if let Ok(Some(v)) = crate::lookup(lang, text, ordinal, &neg) {
return Ok(W2nValue::Int(BigInt::from(v)));
}
}
parse_literal(text)
}
/// Port of `Words2Num_Base._parse_literal` — a bare digit string, a leading
/// sign word, or genuinely unparseable input.
///
/// `errmsg_unparseable` is `"cannot parse %r as a number"`.
fn parse_literal(text: &str) -> Result<W2nValue, W2nError> {
let normalized = crate::normalize(text);
let unparseable = |s: &str| W2nError::Words2Num(format!("cannot parse {} as a number", py_repr_str(s)));
if normalized.is_empty() {
return Err(unparseable(&normalized));
}
for neg in BASE_NEGATIVE_WORDS {
if let Some(rest) = normalized.strip_prefix(&format!("{} ", neg)) {
return finish_parse_literal(rest, -1);
}
if normalized == neg {
return Err(unparseable(&normalized));
}
}
finish_parse_literal(&normalized, 1)
}
/// The `try: … except ValueError: pass; raise` tail of `_parse_literal`.
fn finish_parse_literal(normalized: &str, sign: i64) -> Result<W2nValue, W2nError> {
if normalized.contains('.') {
if let Some(f) = py_float(normalized) {
return Ok(W2nValue::Float(if sign < 0 { -f } else { f }));
}
} else if let Some(i) = py_int(normalized) {
return Ok(W2nValue::Int(if sign < 0 { -i } else { i }));
}
Err(W2nError::Words2Num(format!(
"cannot parse {} as a number",
py_repr_str(normalized)
)))
}
/// Port of `Words2Num_Base.to_ordinal_num`.
///
/// ```python
/// m = re.search(r"-?\d+", text)
/// if not m: raise Words2NumError("cannot parse %r as a number" % text)
/// return int(m.group())
/// ```
fn base_ordinal_num(text: &str) -> Result<W2nValue, W2nError> {
let chars: Vec<char> = text.chars().collect();
for i in 0..chars.len() {
// `-?\d+`: a '-' counts only when a digit follows it.
if chars[i] == '-' && chars.get(i + 1).copied().is_some_and(is_unicode_digit) {
let mut j = i + 1;
while j < chars.len() && is_unicode_digit(chars[j]) {
j += 1;
}
let group: String = chars[i..j].iter().collect();
return py_int(&group)
.map(W2nValue::Int)
.ok_or_else(|| W2nError::Words2Num(unparseable_msg(text)));
}
if is_unicode_digit(chars[i]) {
let mut j = i;
while j < chars.len() && is_unicode_digit(chars[j]) {
j += 1;
}
let group: String = chars[i..j].iter().collect();
return py_int(&group)
.map(W2nValue::Int)
.ok_or_else(|| W2nError::Words2Num(unparseable_msg(text)));
}
}
Err(W2nError::Words2Num(unparseable_msg(text)))
}
fn unparseable_msg(text: &str) -> String {
format!("cannot parse {} as a number", py_repr_str(text))
}
/// Python's `int(str)` over a `_normalize`-shaped string (optional sign, then
/// Unicode `Nd` digits). Returns `None` where Python raises `ValueError`.
fn py_int(s: &str) -> Option<BigInt> {
let t = s.trim_matches(py_is_space);
let (neg, body) = match t.strip_prefix('-') {
Some(r) => (true, r),
None => (false, t.strip_prefix('+').unwrap_or(t)),
};
if body.is_empty() || !body.chars().all(is_unicode_digit) {
return None;
}
let ascii = to_ascii_digits(body);
let v = BigInt::from_str(&ascii).ok()?;
Some(if neg { -v } else { v })
}
/// Python's `float(str)` over a `_normalize`-shaped decimal string.
fn py_float(s: &str) -> Option<f64> {
let t = s.trim_matches(py_is_space);
let ascii = to_ascii_digits(t);
ascii.parse::<f64>().ok()
}
/// `from .. import words2num; words2num(text, lang=lang)` — resolve the locale
/// and run its `to_cardinal`.
fn call_words2num(text: &str, lang: &str) -> Result<W2nValue, W2nError> {
let resolved = resolve_lang(lang)?;
converter_for(&resolved).to_cardinal(text)
}
/// Port of the public `words2num2.words2num(text, lang, to)` — the single-token
/// entry point, dispatch and all.
///
/// ```python
/// def words2num(text, lang="en", to="cardinal", **kwargs):
/// resolved = _resolve_lang(lang)
/// converter = CONVERTER_CLASSES[resolved]
/// if to not in CONVERTER_TYPES:
/// raise NotImplementedError("conversion type %r unsupported" % to)
/// return getattr(converter, "to_{}".format(to))(text, **kwargs)
/// ```
///
/// Returns the English grammar's [`crate::w2n_lang_en::W2nValue`] rather than
/// this module's [`W2nValue`], so the `en` decimal path keeps its `PyDec`
/// backing: a signed-zero decimal (`Decimal('-0.0')`) and the exact
/// 28-significant-digit `str()` both survive, neither of which `BigDecimal` can
/// carry. The 119 reverse-table locales only ever produce an `int` or `float`,
/// so mapping their result back through [`sentence_to_en_value`] is lossless.
pub fn words2num(
text: &str,
lang: &str,
to: &str,
) -> Result<crate::w2n_lang_en::W2nValue, W2nError> {
let resolved = resolve_lang(lang)?;
let converter = converter_for(&resolved);
// `CONVERTER_TYPES` in `words2num2/__init__.py`. An unknown `to` is a
// `NotImplementedError`, distinct from the reverse table declining a word.
const CONVERTER_TYPES: [&str; 5] = ["cardinal", "ordinal", "ordinal_num", "year", "currency"];
if !CONVERTER_TYPES.contains(&to) {
return Err(W2nError::NotImplemented(format!(
"conversion type {} unsupported",
py_repr_str(to)
)));
}
// `getattr(converter, "to_{to}")(text)`. The English grammar path returns
// its native value directly; every other path is `int`/`float` and is
// promoted to the English value type.
match &converter {
Converter::En => match to {
// `Words2Num_Base.to_currency` == `self.to_cardinal` (polymorphic).
"cardinal" | "currency" => {
crate::en_to_cardinal(text).map_err(|e| W2nError::Words2Num(e.msg))
}
"ordinal" => crate::en_to_ordinal(text).map_err(|e| W2nError::Words2Num(e.msg)),
"year" => crate::en_to_year(text).map_err(|e| W2nError::Words2Num(e.msg)),
// `Words2Num_EN` inherits `Words2Num_Base.to_ordinal_num`.
_ => base_ordinal_num(text).map(sentence_to_en_value),
},
Converter::Table(_) => {
let v = match to {
// `Words2Num_Base.to_year`/`to_currency` == `self.to_cardinal`.
"cardinal" | "year" | "currency" => converter.to_cardinal(text),
"ordinal" => converter.to_ordinal(text),
_ => converter.to_ordinal_num(text),
}?;
Ok(sentence_to_en_value(v))
}
}
}
/// Promote a reverse-table / `ordinal_num` result into the English grammar's
/// value type. Those paths never yield a `Decimal`, so the `Dec` arm is
/// unreachable in practice; it is mapped losslessly (rather than panicked on —
/// the crate builds `panic = "abort"`) via [`crate::w2n_lang_en::PyDec`].
fn sentence_to_en_value(v: W2nValue) -> crate::w2n_lang_en::W2nValue {
use crate::w2n_lang_en::W2nValue as EnV;
match v {
W2nValue::Int(i) => EnV::Int(i),
W2nValue::Float(f) => EnV::Float(f),
W2nValue::Dec(d) => EnV::Dec(crate::w2n_lang_en::PyDec::from_bigdecimal(&d)),
}
}
// ===========================================================================
// `words2num_sentence` / `convert_sentence` / `sentence_to_words`
// ===========================================================================
/// `SentenceConverter._starts_run` — a run must open with a real number word,
/// never with `"and"` / `"point"` / `"minus"`.
fn starts_run(converter: &Converter, token: &str) -> bool {
if token.is_empty() {
return false;
}
let dehyphened = token.replace('-', " ");
py_split_whitespace(&dehyphened)
.iter()
.any(|sub| converter.is_number_word(sub))
}
/// `SentenceConverter._is_candidate` — cheap pre-filter for run growth.
fn is_candidate(converter: &Converter, token: &str, includable: &[&str]) -> bool {
if token.is_empty() {
return false;
}
if includable.contains(&token) {
return true;
}
let dehyphened = token.replace('-', " ");
py_split_whitespace(&dehyphened)
.iter()
.any(|sub| converter.is_number_word(sub))
}
/// `SentenceConverter.INCLUDABLE` — tokens allowed *inside* a run though they
/// are not numbers. Keyed by the **resolved** code, so only exactly `"en"`
/// gets them: `words2num_sentence(..., lang="en_IN")` resolves to `"en_IN"`
/// and therefore runs with an empty includable set.
const INCLUDABLE_EN: [&str; 7] = ["and", "point", "dot", "minus", "negative", "a", "an"];
/// Port of `words2num2.words2num_sentence` → `SentenceConverter.convert`.
///
/// Walks the sentence and, at each position that opens with a real number
/// word, grows the longest run of tokens the per-language converter accepts.
///
/// `has_kwargs` is whether the Python caller passed extra keyword arguments
/// through (`kwargs or None` was truthy). The standard converters accept none,
/// so any such call fails every conversion — matching Python's swallowed
/// `TypeError`.
pub fn words2num_sentence(
sentence: &str,
lang: &str,
to: &str,
has_kwargs: bool,
) -> Result<String, W2nError> {
let resolved = resolve_lang(lang)?;
let converter = converter_for(&resolved);
let includable: &[&str] = if resolved == "en" { &INCLUDABLE_EN } else { &[] };
let parts = tokenize(sentence);
let n = parts.len();
let mut out = String::new();
let mut i = 0usize;
while i < n {
let piece = &parts[i];
if py_str_isspace(piece) {
out.push_str(piece);
i += 1;
continue;
}
// A run must START with a real number word.
let head = rstrip_punct(piece).to_lowercase();
if !starts_run(&converter, &head) {
out.push_str(piece);
i += 1;
continue;
}
// Grow a number run starting at i.
let mut best_value: Option<W2nValue> = None;
let mut best_end = i;
let mut j = i;
while j < n {
let tok = &parts[j];
if py_str_isspace(tok) {
j += 1;
continue;
}
let clean = rstrip_punct(tok).to_lowercase();
if !is_candidate(&converter, &clean, includable) {
break;
}
let run = parts[i..=j].concat();
let stripped = rstrip_punct(py_strip(&run)).to_string();
// The standard converters never return `None`, so a successful
// parse always both records the value and advances best_end. A
// raised error is Python's `except Exception` — swallow and keep
// growing.
if let Ok(v) = converter.convert(to, &stripped, has_kwargs) {
best_value = Some(v);
best_end = j;
}
// A token ending in terminal punctuation closes the run.
if ends_with_terminal_punct(tok) {
break;
}
j += 1;
}
if let Some(v) = best_value {
// Preserve trailing punctuation that was stripped during parse.
let run = parts[i..=best_end].concat();
let trailing = trailing_punct(&run);
out.push_str(&v.py_str());
out.push_str(trailing);
i = best_end + 1;
} else {
out.push_str(piece);
i += 1;
}
}
Ok(out)
}
/// `convert_sentence = words2num_sentence` (alias, parity with num2words2).
pub fn convert_sentence(
sentence: &str,
lang: &str,
to: &str,
has_kwargs: bool,
) -> Result<String, W2nError> {
words2num_sentence(sentence, lang, to, has_kwargs)
}
/// `sentence_to_words = words2num_sentence` (alias, parity with num2words2).
pub fn sentence_to_words(
sentence: &str,
lang: &str,
to: &str,
has_kwargs: bool,
) -> Result<String, W2nError> {
words2num_sentence(sentence, lang, to, has_kwargs)
}
// ===========================================================================
// Registries — `UNITS`, `CURRENCIES`, `SCALE_SUFFIXES`
// ===========================================================================