Skip to main content

num2words2_core/
lang_pt.rs

1//! Port of `lang_PT.py` (European Portuguese), via its
2//! `Num2Word_EUR` → `Num2Word_Base` ancestry.
3//!
4//! Shape: **engine**. `Num2Word_PT.setup` supplies `high_numwords` /
5//! `mid_numwords` / `low_numwords` and overrides `merge`, so `cards` is built
6//! and the default `to_cardinal` (`splitnum`/`clean`/`merge`) drives the
7//! conversion. PT then *post-processes* the engine's output with a regex loop
8//! (see [`LangPt::to_cardinal`]), which is the only reason `to_cardinal` is
9//! overridden here at all.
10//!
11//! Inheritance chain actually used:
12//!   * `Num2Word_EUR.set_high_numwords` — long-scale illiard/illion pairing.
13//!     PT sets `GIGA_SUFFIX = None`, so **only** the `MEGA_SUFFIX` ("ilião")
14//!     half of that method fires: one card per `10^(n-3)` for
15//!     `n in range(57, 3, -6)`, i.e. 10^54 … 10^6.
16//!   * `Num2Word_EUR.gen_high_numwords(units, tens, lows)` — PT calls it as
17//!     `gen_high_numwords([], [], lows)`. With `tens == []` the comprehension
18//!     `[u + t for t in tens for u in units]` is empty, so the Latin elision
19//!     table never runs and the result is simply `lows`. Inlined below.
20//!   * `Num2Word_Base.verify_ordinal` — the negative-input `TypeError`.
21//!   * `Num2Word_Base.to_cardinal` — overflow check + `splitnum`/`clean`.
22//!
23//! The currency surface is ported; see [`LangPt::to_currency`]. `to_fraction`
24//! is PT's own override (issue #584): idiomatic "meio"/"terço" for halves and
25//! thirds, `cardinal(n) + ordinal(d)` (+"s" unless it already ends in "s")
26//! otherwise — see [`Lang::to_fraction`] below. PT_BR inherits it (and ports
27//! it separately, dispatching to its own cardinal/ordinal).
28//!
29//! # float/Decimal entry points (corpus: wholefloat slice)
30//!
31//! * `to_cardinal(float/Decimal)` — Base routing: whole -> int path,
32//!   fractional -> `to_cardinal_float`. The trait default already does this;
33//!   only the trailing EXTS sweep needed porting (see
34//!   [`LangPt::to_cardinal_float`]).
35//! * `to_ordinal(float/Decimal)` — **`value = int(value)` truncates toward
36//!   zero before `verify_ordinal`**, so `to_ordinal(2.5)` == "segundo",
37//!   `to_ordinal(0.5)` == "", `to_ordinal(-0.0)` == "" and `to_ordinal(-1.5)`
38//!   raises the *negative* TypeError, never the float one.
39//! * `to_ordinal_num(float/Decimal)` — `verify_ordinal` on the **raw** value:
40//!   fractional -> TypeError (`errmsg_floatord`), numerically negative ->
41//!   TypeError (`errmsg_negord`). `-0.0` passes both checks
42//!   (`abs(-0.0) == -0.0` numerically) and yields "-0.0º".
43//! * `to_year(float/Decimal)` — `val < 0` is a numeric test (so -0.0 takes
44//!   the positive branch), and the negative branch renders
45//!   `to_cardinal(abs(val)) + " antes de Cristo"`, floats included:
46//!   `to_year(-1.5)` == "um vírgula cinco antes de Cristo".
47//!
48//! `cardinal_from_decimal` is deliberately left at its trait default, which
49//! now routes to the shared `floatpath` module rather than raising. That is
50//! what PT wants: Python reaches the fractional-cents branch as
51//! `self.to_cardinal(float(right))`, i.e. straight through the float path, and
52//! the default reproduces it using this language's own `pointword`
53//! ("vírgula") — `to_currency(1.011, currency="EUR")` gives
54//! "um euro e um vírgula um cêntimos" in both. No corpus row exercises it
55//! (every pt currency value has ≤ 2 decimals), so it is checked by hand only.
56//!
57//! # Faithfully reproduced Python oddities
58//!
59//! This is a port, not a rewrite. All of the following are what Python emits,
60//! verified against the interpreter:
61//!
62//! 1. **`cards[10^6]` is literally `"milião"`** — a typo for "milhão". The
63//!    library patches it up inside `merge` with an explicit
64//!    `if ntext == "milião": ntext = "milhão"`. Reproduced verbatim rather
65//!    than fixed at the table, because the *unpatched* spelling is observable:
66//!    the `nnum % 1000000` branch rewrites it to "milhões" by string surgery
67//!    (`ntext[:-4] + "lhões"` → "mi" + "lhões") **before** that correction
68//!    would ever apply.
69//! 2. **`merge`'s `if nnum < cnum` has two identical arms.** Python tests
70//!    `if cnum < 100` and then returns the exact same expression in both the
71//!    `if` and the fall-through. Collapsed into one branch here — this is the
72//!    single place the Rust is not a statement-for-statement transcription,
73//!    and it is provably behaviour-preserving.
74//! 3. **Nonstandard ordinal spellings**, kept as-is: `ords[2][4]` is
75//!    "quadrigentésimo" (standard PT is "quadringentésimo") and `ords[2][7]`
76//!    is "septigentésimo" (standard is "septingentésimo"). The frozen corpus
77//!    confirms both (`ordinal(700)` == "septigentésimo").
78//! 4. **`to_ordinal(0)` returns the empty string** — every digit maps through
79//!    `ords[idx % 3][0]` == `""`, and the join/strip collapses to "".
80//! 5. **`to_ordinal` drops a leading "primeiro "** whenever the value is not
81//!    exactly 1 (`result[9:]`), to avoid "primeiro milésimo". This is why
82//!    `ordinal(1000)` == "milésimo" but `ordinal(2000)` == "segundo milésimo".
83//! 6. **`to_ordinal` raises `KeyError` for values with ≥ 19 digits**, because
84//!    `thousand_separators` stops at key 15; `idx == 18` misses. Note the
85//!    lookup happens *before* the `char != "0"` guard, so even a bare 10^18
86//!    raises. Mapped to [`N2WError::Key`] — see the corpus rows for 10^18
87//!    and 10^21.
88//!
89//! # Cross-call mutable state: `to_currency` leaks `self.negword`
90//!
91//! **This port deliberately diverges from the frozen corpus on two rows.**
92//! Read this before "fixing" them.
93//!
94//! `Num2Word_PT.to_currency` chops a character off `self.negword` and restores
95//! it afterwards — with no `try/finally`:
96//!
97//! ```python
98//! backup_negword = self.negword
99//! self.negword = self.negword[:-1]          # "menos " -> "menos"
100//! result = super().to_currency(val, ...)    # raises for an unknown code
101//! self.negword = backup_negword             # never runs on the raise
102//! ```
103//!
104//! `CONVERTER_CLASSES` holds one shared instance, so every float-path call
105//! that raises eats one more character, permanently and process-wide:
106//!
107//! ```text
108//! >>> num2words(-12.34, lang='pt', to='currency', currency='INR')
109//! 'menos doze rupias e trinta e quatro paisas'
110//! >>> for _ in range(6):                     # 6 x NotImplementedError
111//! ...     try: num2words(1.0, lang='pt', to='currency', currency='KWD')
112//! ...     except NotImplementedError: pass   # negword: "menos " -> ""
113//! >>> num2words(-12.34, lang='pt', to='currency', currency='INR')
114//! ' doze rupias e trinta e quatro paisas'    # same input, minus sign gone
115//! >>> num2words(-1, lang='pt')
116//! ' um'                                      # cardinal is corrupted too
117//! ```
118//!
119//! This is `lang_SL`'s `ordflag` bug (FINDINGS.md §8a) with a different
120//! attribute, and the fix upstream is the same one line: `try/finally`.
121//!
122//! The corpus **bakes the corruption in**, because `gen_corpus.py` walks
123//! currencies in the order EUR, USD, GBP, JPY, KWD, BHD, INR, CNY, CHF on one
124//! shared instance: KWD and BHD contribute 7 raising float rows each, which is
125//! more than enough to erode "menos " to "" before INR is reached. Two rows
126//! record the damage —
127//!
128//! ```text
129//! {"lang":"pt","to":"currency:INR","arg":"-12.34","out":" doze rupias e trinta e quatro paisas"}
130//! {"lang":"pt","to":"currency:CNY","arg":"-12.34","out":" doze yuans e trinta e quatro fen"}
131//! ```
132//!
133//! — and the tail `w2n_cardinal` rows corroborate it independently: pt's are
134//! recorded as `" um"` / `" sete"`, not `"menos um"` / `"menos sete"`, because
135//! by then the same instance had lost its negword.
136//!
137//! Reproducing this would mean giving `LangPt` process-global mutable state
138//! (an atomic — the trait hands out `&self` and `get_lang` returns a
139//! `&'static (dyn Lang + Sync)`), making output depend on how many earlier
140//! calls happened to fail, and on thread interleaving where Python at least
141//! has the GIL. It would also silently corrupt `to_cardinal`, a path the
142//! contract freezes. So this port stays stateless and matches a **pristine**
143//! `Num2Word_PT`, per the precedent set for 8a/8b: "the Rust port declines to
144//! reproduce the leak ... This is the one accepted divergence."
145//!
146//! Net: 115/117 pt currency+cheque corpus rows match; the 2 above are the
147//! leak. Flagged rather than silently absorbed — see the agent report.
148//!
149//! `float2tuple` writes `self.precision`, but that one is genuinely restored
150//! (a `finally` in `to_cardinal_float`) and is unreachable from
151//! cardinal/ordinal/ordinal_num/year on integer input.
152
153use crate::base::{
154    default_to_cardinal, set_low_numwords, set_mid_numwords, Cards, Lang, N2WError, Result,
155};
156use crate::currency::{CurrencyForms, CurrencyValue};
157use crate::floatpath::{default_to_cardinal_float, FloatValue};
158use num_bigint::BigInt;
159use num_traits::{FromPrimitive, One, Signed, ToPrimitive, Zero};
160use std::collections::HashMap;
161
162/// `self.hundreds`, keys 1..=9. Index 0 is absent in Python.
163const HUNDREDS: [&str; 9] = [
164    "cento",
165    "duzentos",
166    "trezentos",
167    "quatrocentos",
168    "quinhentos",
169    "seiscentos",
170    "setecentos",
171    "oitocentos",
172    "novecentos",
173];
174
175/// `self.ords`: three dicts (units, tens, hundreds), keys 0..=9 with 0 → "".
176///
177/// "quadrigentésimo" and "septigentésimo" are the library's spellings; see the
178/// module docs.
179const ORDS: [[&str; 10]; 3] = [
180    [
181        "", "primeiro", "segundo", "terceiro", "quarto", "quinto", "sexto", "sétimo", "oitavo",
182        "nono",
183    ],
184    [
185        "",
186        "décimo",
187        "vigésimo",
188        "trigésimo",
189        "quadragésimo",
190        "quinquagésimo",
191        "sexagésimo",
192        "septuagésimo",
193        "octogésimo",
194        "nonagésimo",
195    ],
196    [
197        "",
198        "centésimo",
199        "ducentésimo",
200        "tricentésimo",
201        "quadrigentésimo",
202        "quingentésimo",
203        "seiscentésimo",
204        "septigentésimo",
205        "octigentésimo",
206        "nongentésimo",
207    ],
208];
209
210/// The `ext` list `to_cardinal` sweeps, in Python's tuple order. Order is
211/// load-bearing: "mil" runs before "milhões", and each pass rewrites the
212/// string the next pass sees.
213const EXTS: [&str; 7] = [
214    "mil",
215    "milhão",
216    "milhões",
217    "mil milhões",
218    "bilião",
219    "biliões",
220    "mil biliões",
221];
222
223/// The `ext` list `to_currency` sweeps to insert "de", in Python's tuple
224/// order. Distinct from [`EXTS`], which `to_cardinal` uses: no "mil", no
225/// "mil milhões", but "trilião"/"triliões" instead.
226const CURRENCY_EXTS: [&str; 6] = [
227    "milhão",
228    "milhões",
229    "bilião",
230    "biliões",
231    "trilião",
232    "triliões",
233];
234
235/// `Num2Word_PT.CURRENCY_FORMS` — PT's **own** class-body dict.
236///
237/// PT *defines* `CURRENCY_FORMS`, so it shadows `Num2Word_EUR`'s rather than
238/// sharing it. That is what saves it from the trap `Num2Word_EN.__init__`
239/// sets: EN mutates EUR's dict *in place* at import time, and the 16 classes
240/// that merely inherit it silently pick up English plurals ("två euros") plus
241/// ~24 extra codes. PT sees none of that — its EUR entry is its own
242/// `("euro", "euros")`, and CHF/KWD/BHD/... stay absent. Dumped from the live
243/// interpreter rather than transcribed, per the porting contract.
244///
245/// Every entry is a 2-tuple on both sides, which is why the `cr1[1]` index in
246/// `to_currency` and `pluralize`'s `forms[1]` can never raise IndexError here.
247fn build_currency_forms() -> HashMap<&'static str, CurrencyForms> {
248    // Python module-level: DOLLAR = ("dólar", "dólares"); CENTS = (...)
249    const DOLLAR: [&str; 2] = ["dólar", "dólares"];
250    const CENTS: [&str; 2] = ["cêntimo", "cêntimos"];
251
252    let mut m: HashMap<&'static str, CurrencyForms> = HashMap::new();
253    m.insert("AUD", CurrencyForms::new(&DOLLAR, &CENTS));
254    m.insert(
255        "BRL",
256        CurrencyForms::new(&["real", "reais"], &["centavo", "centavos"]),
257    );
258    m.insert("CAD", CurrencyForms::new(&DOLLAR, &CENTS));
259    m.insert("NZD", CurrencyForms::new(&DOLLAR, &CENTS));
260    m.insert("HKD", CurrencyForms::new(&DOLLAR, &CENTS));
261    m.insert("EUR", CurrencyForms::new(&["euro", "euros"], &CENTS));
262    m.insert(
263        "GBP",
264        CurrencyForms::new(&["libra", "libras"], &["péni", "pence"]),
265    );
266    m.insert("CNY", CurrencyForms::new(&["yuan", "yuans"], &["fen", "fen"]));
267    m.insert("JPY", CurrencyForms::new(&["iene", "ienes"], &["sen", "sen"]));
268    m.insert(
269        "INR",
270        CurrencyForms::new(&["rupia", "rupias"], &["paisa", "paisas"]),
271    );
272    m.insert(
273        "RUB",
274        CurrencyForms::new(&["rublo", "rublos"], &["copeque", "copeques"]),
275    );
276    m.insert("KRW", CurrencyForms::new(&["won", "wons"], &["jeon", "jeons"]));
277    m.insert(
278        "MXN",
279        CurrencyForms::new(&["peso", "pesos"], &["centavo", "centavos"]),
280    );
281    m.insert("USD", CurrencyForms::new(&DOLLAR, &CENTS));
282    m
283}
284
285/// `Num2Word_EUR.CURRENCY_ADJECTIVES`, inherited unchanged — PT defines none.
286///
287/// Unlike `CURRENCY_FORMS` this really is the shared EUR dict, but nothing
288/// mutates it (verified against the live interpreter: it still matches the
289/// `lang_EUR.py` literal), so the source is what runs.
290///
291/// Mostly dead weight, kept because it is what PT inherits. Only AUD, CAD,
292/// USD, RUB, MXN, INR, JPY and KRW are reachable — `to_currency` looks the
293/// *forms* up first and raises for any code PT lacks — and even those are
294/// reachable only on the float path, since PT's int path ignores `adjective`
295/// outright (see [`LangPt::to_currency`]).
296fn build_currency_adjectives() -> HashMap<&'static str, &'static str> {
297    [
298        ("AUD", "Australian"),
299        ("BYN", "Belarusian"),
300        ("CAD", "Canadian"),
301        ("EEK", "Estonian"),
302        ("USD", "US"),
303        ("RUB", "Russian"),
304        ("NOK", "Norwegian"),
305        ("MXN", "Mexican"),
306        ("RON", "Romanian"),
307        ("INR", "Indian"),
308        ("HUF", "Hungarian"),
309        ("ISK", "íslenskar"),
310        ("UZS", "Uzbekistan"),
311        ("SAR", "Saudi"),
312        ("JPY", "Japanese"),
313        ("KRW", "Korean"),
314    ]
315    .into_iter()
316    .collect()
317}
318
319/// `to_currency`'s "milhões euros" → "milhões de euros" sweep, shared by both
320/// its int and float paths.
321///
322/// Python, with `unit` being `currency_str` (int path) or `cr1[1]` (float):
323///
324/// ```python
325/// for ext in ("milhão", "milhões", "bilião", "biliões", "trilião", "triliões"):
326///     if re.match(".*{} (?={})".format(ext, unit), result):
327///         result = result.replace("{}".format(ext), "{} de".format(ext), 1)
328/// ```
329///
330/// The test is a plain substring search, not a regex, and that is exact rather
331/// than approximate:
332///
333/// * `re.match(".*X (?=Y)")` — the leading `.*` backtracks over any prefix
334///   (and the subject never contains a newline, which `.` would not cross), so
335///   the pattern succeeds iff `"X Y"` occurs somewhere in `result`.
336/// * Neither the six `ext` literals nor any word in PT's `CURRENCY_FORMS`
337///   contains a regex metacharacter, so interpolating `unit` into a pattern —
338///   which is what Python does — cannot change the meaning.
339///
340/// Checked against the real `re.match` over 2,016 (currency, value, adjective)
341/// combinations spanning all 14 PT codes plus 4 unknown ones: 0 mismatches.
342///
343/// Note `replacen(ext, ..., 1)` rewrites the **first** `ext` in the string,
344/// which need not be the occurrence the test matched. That is exactly what
345/// `str.replace(old, new, 1)` does, and it is preserved rather than tightened.
346fn insert_de(mut result: String, unit: &str) -> String {
347    for ext in CURRENCY_EXTS.iter() {
348        if result.contains(&format!("{} {}", ext, unit)) {
349            result = result.replacen(ext, &format!("{} de", ext), 1);
350        }
351    }
352    result
353}
354
355/// `self.thousand_separators`. Missing keys are a `KeyError` in Python.
356fn thousand_separator(idx: usize) -> Option<&'static str> {
357    match idx {
358        3 => Some("milésimo"),
359        6 => Some("milionésimo"),
360        9 => Some("milésimo milionésimo"),
361        12 => Some("bilionésimo"),
362        15 => Some("milésimo bilionésimo"),
363        _ => None,
364    }
365}
366
367/// `self.hundreds[n]` for n in 1..=9.
368fn hundreds_word(n: &BigInt) -> Option<&'static str> {
369    let i = n.to_u32()?;
370    if (1..=9).contains(&i) {
371        Some(HUNDREDS[(i - 1) as usize])
372    } else {
373        None
374    }
375}
376
377/// Python's `s[:-4]` — a **character** slice, not a byte slice.
378///
379/// Every string this is applied to ends in "ilião", whose "ã" is two bytes in
380/// UTF-8, so byte slicing would split a codepoint and corrupt the stem
381/// ("trilião" → "tri", "bilião" → "bi", "milião" → "mi"). Python returns ""
382/// when the string is 4 chars or shorter.
383fn drop_last_4_chars(s: &str) -> String {
384    let cs: Vec<char> = s.chars().collect();
385    if cs.len() <= 4 {
386        String::new()
387    } else {
388        cs[..cs.len() - 4].iter().collect()
389    }
390}
391
392/// Python `\w` for `str` patterns: Unicode alphanumerics plus underscore.
393fn is_word_char(c: char) -> bool {
394    c.is_alphanumeric() || c == '_'
395}
396
397/// Python's `int(value)` on a float/Decimal: truncation toward zero
398/// (`int(-1.5) == -1`, `int(-0.0) == 0`). NaN/inf raise what CPython raises —
399/// unreachable through the shim (its `_finite` guard keeps them on the Python
400/// side), kept for fidelity.
401fn float_trunc_int(value: &FloatValue) -> Result<BigInt> {
402    match value {
403        FloatValue::Float { value: f, .. } => {
404            if f.is_nan() {
405                return Err(N2WError::Value(
406                    "cannot convert float NaN to integer".into(),
407                ));
408            }
409            if f.is_infinite() {
410                return Err(N2WError::Overflow(
411                    "cannot convert float infinity to integer".into(),
412                ));
413            }
414            // Exact: every whole f64 is exactly representable as an integer.
415            Ok(BigInt::from_f64(f.trunc()).expect("finite whole f64 converts exactly"))
416        }
417        FloatValue::Decimal { value: d, .. } => {
418            // int(Decimal): with_scale(0) divides the mantissa by 10^scale in
419            // BigInt, which truncates toward zero — exactly Python's int().
420            Ok(d.with_scale(0).as_bigint_and_exponent().0)
421        }
422    }
423}
424
425/// Python's `val < 0` on a float/Decimal — a *numeric* comparison, unlike
426/// `FloatValue::is_negative()` which is sign-bit aware. `-0.0 < 0` is False,
427/// so `to_year(-0.0)` renders through the positive branch.
428fn fv_numeric_negative(v: &FloatValue) -> bool {
429    match v {
430        FloatValue::Float { value, .. } => *value < 0.0,
431        FloatValue::Decimal { value, .. } => value.is_negative(),
432    }
433}
434
435/// Python's `abs(val)` in the value's own domain (float stays float,
436/// Decimal stays Decimal), keeping the recorded precision.
437fn fv_abs(v: &FloatValue) -> FloatValue {
438    match v {
439        FloatValue::Float { value, precision } => FloatValue::Float {
440            value: value.abs(),
441            precision: *precision,
442        },
443        FloatValue::Decimal { value, precision } => FloatValue::Decimal {
444            value: value.abs(),
445            precision: *precision,
446        },
447    }
448}
449
450/// Python's `re.sub("\\s+", " ", s)`.
451fn collapse_ws(s: &str) -> String {
452    let mut out = String::new();
453    let mut in_ws = false;
454    for c in s.chars() {
455        if c.is_whitespace() {
456            if !in_ws {
457                out.push(' ');
458                in_ws = true;
459            }
460        } else {
461            out.push(c);
462            in_ws = false;
463        }
464    }
465    out
466}
467
468/// Evaluates `re.match(".*{ext} e \\w*entos? (?=.*e)", result)` as a boolean,
469/// without a regex engine (the crate takes no regex dependency).
470///
471/// Reasoning behind the hand-rolled matcher:
472///
473/// * `re.match(".*P")` is equivalent to `re.search(P)` here — the leading `.*`
474///   backtracks over any prefix and the subject never contains a newline (the
475///   one character `.` will not cross). So this scans every occurrence of the
476///   literal `"{ext} e "` rather than anchoring at 0.
477/// * `\w*entos?` cannot match a space, and it is followed by a mandatory
478///   literal `" "`. So it must consume *exactly* the word sitting between that
479///   occurrence and the next space. Letting `\w*` backtrack, such a word
480///   matches iff it is all word characters and ends in "ento" or "entos".
481///   (If there is no following space — i.e. the word ends the string — the
482///   mandatory `" "` fails and the occurrence is rejected. That is precisely
483///   why `to_cardinal(1100)` keeps its "e": "mil e cem" has no trailing space.)
484/// * The trailing `(?=.*e)` is a lookahead applied *after* that space, so it
485///   asks only whether some 'e' character occurs later in the string.
486fn re_match_ext(result: &str, ext: &str) -> bool {
487    let hay: Vec<char> = result.chars().collect();
488    let needle: Vec<char> = format!("{} e ", ext).chars().collect();
489    if needle.len() > hay.len() {
490        return false;
491    }
492    for i in 0..=(hay.len() - needle.len()) {
493        if hay[i..i + needle.len()] != needle[..] {
494            continue;
495        }
496        let j = i + needle.len();
497        // `\w*entos?` runs to the next space; that space is the literal " ".
498        let k = match hay[j..].iter().position(|c| *c == ' ') {
499            Some(off) => j + off,
500            None => continue,
501        };
502        let w = &hay[j..k];
503        if !w.iter().all(|c| is_word_char(*c)) {
504            continue;
505        }
506        let word: String = w.iter().collect();
507        if !(word.ends_with("ento") || word.ends_with("entos")) {
508            continue;
509        }
510        // Lookahead `(?=.*e)` at the position just past the literal space.
511        if hay[k + 1..].iter().any(|c| *c == 'e') {
512            return true;
513        }
514    }
515    false
516}
517
518pub struct LangPt {
519    cards: Cards,
520    maxval: BigInt,
521    exclude_title: Vec<String>,
522    /// Built once here, not per call — a per-call table cost an earlier
523    /// version of this port 10x against the Python it replaces.
524    currency_forms: HashMap<&'static str, CurrencyForms>,
525    currency_adjectives: HashMap<&'static str, &'static str>,
526}
527
528impl Default for LangPt {
529    fn default() -> Self {
530        Self::new()
531    }
532}
533
534impl LangPt {
535    pub fn new() -> Self {
536        // setup(): high_numwords = gen_high_numwords([], [], lows) == lows,
537        // because `tens` is empty (see module docs). Note "quatr", not the
538        // "quadr" that lang_EUR's own setup() uses — PT overrides the list.
539        let high = ["non", "oct", "sept", "sext", "quint", "quatr", "tr", "b", "m"];
540
541        let mut cards = Cards::new();
542
543        // Num2Word_EUR.set_high_numwords, with GIGA_SUFFIX = None:
544        //   cap = 3 + 6*len(high) = 57
545        //   for word, n in zip(high, range(cap, 3, -6)):
546        //       cards[10**(n-3)] = word + MEGA_SUFFIX      # "ilião"
547        // zip stops at the shorter side; here both are 9 long, and the
548        // `n <= 3` break mirrors the range running out.
549        let cap = 3 + 6 * high.len() as i64;
550        let mut n = cap;
551        for word in high.iter() {
552            if n <= 3 {
553                break;
554            }
555            cards.insert(
556                BigInt::from(10u8).pow((n - 3) as u32),
557                format!("{}ilião", word),
558            );
559            n -= 6;
560        }
561
562        set_mid_numwords(
563            &mut cards,
564            &[
565                (1000, "mil"),
566                (100, "cem"),
567                (90, "noventa"),
568                (80, "oitenta"),
569                (70, "setenta"),
570                (60, "sessenta"),
571                (50, "cinquenta"),
572                (40, "quarenta"),
573                (30, "trinta"),
574            ],
575        );
576        set_low_numwords(
577            &mut cards,
578            &[
579                "vinte",
580                "dezanove",
581                "dezoito",
582                "dezassete",
583                "dezasseis",
584                "quinze",
585                "catorze",
586                "treze",
587                "doze",
588                "onze",
589                "dez",
590                "nove",
591                "oito",
592                "sete",
593                "seis",
594                "cinco",
595                "quatro",
596                "três",
597                "dois",
598                "um",
599                "zero",
600            ],
601        );
602
603        // MAXVAL = 1000 * list(self.cards.keys())[0]. The OrderedDict's first
604        // key is the first inserted, i.e. the 10^54 card, so MAXVAL == 10^57.
605        let maxval = cards.highest().cloned().unwrap_or_else(BigInt::zero) * BigInt::from(1000);
606
607        LangPt {
608            cards,
609            maxval,
610            exclude_title: vec!["e".into(), "vírgula".into(), "menos".into()],
611            currency_forms: build_currency_forms(),
612            currency_adjectives: build_currency_adjectives(),
613        }
614    }
615
616    /// `Num2Word_Base.verify_ordinal`. The float check is unreachable for
617    /// integer input, so only the negative check survives.
618    fn verify_ordinal(&self, value: &BigInt) -> Result<()> {
619        if value.is_negative() {
620            return Err(N2WError::Type(format!(
621                "Cannot treat negative num {} as ordinal.",
622                value
623            )));
624        }
625        Ok(())
626    }
627}
628
629impl Lang for LangPt {
630    /// This language's own `to_currency(currency=...)` default,
631    /// read from the live Python signature. Only 44 of 156 use EUR.
632    fn default_currency(&self) -> &str {
633        "EUR"
634    }
635
636    /// This language's own `to_currency(separator=...)` default,
637    /// read from the live Python signature. Base's is ",", but only
638    /// 36 of 149 languages actually use it — most default to " " or a
639    /// conjunction, so inheriting Base's comma silently corrupts them.
640    fn default_separator(&self) -> &str {
641        " e"
642    }
643
644    fn cards(&self) -> &Cards {
645        &self.cards
646    }
647    fn maxval(&self) -> &BigInt {
648        &self.maxval
649    }
650    fn negword(&self) -> &str {
651        "menos "
652    }
653    fn pointword(&self) -> &str {
654        "vírgula"
655    }
656    fn exclude_title(&self) -> &[String] {
657        &self.exclude_title
658    }
659
660    fn merge(&self, l: (&str, &BigInt), r: (&str, &BigInt)) -> (String, BigInt) {
661        let (ctext0, cnum) = l;
662        let (ntext0, nnum) = r;
663        let mut ctext = ctext0.to_string();
664        let mut ntext = ntext0.to_string();
665
666        let hundred = BigInt::from(100);
667        let thousand = BigInt::from(1000);
668        let million = BigInt::from(1_000_000);
669        let billion = BigInt::from(1_000_000_000);
670
671        if cnum.is_one() {
672            if nnum < &million {
673                return (ntext, nnum.clone());
674            }
675            ctext = "um".to_string();
676        } else if cnum == &hundred && !(nnum % &thousand).is_zero() {
677            // Python: `cnum == 100 and not nnum % 1000 == 0`, which parses as
678            // `cnum == 100 and not (nnum % 1000 == 0)` — `==` binds tighter
679            // than `not`. So: "cem" becomes "cento" only when what follows is
680            // not a whole thousand ("cento e um", but "cem mil").
681            ctext = "cento".to_string();
682        }
683
684        if nnum < cnum {
685            // Python branches on `cnum < 100` and returns the identical
686            // expression either way; see module docs, item 2.
687            return (format!("{} e {}", ctext, ntext), cnum + nnum);
688        } else if (nnum % &billion).is_zero() && cnum > &BigInt::one() {
689            ntext = format!("{}liões", drop_last_4_chars(&ntext));
690        } else if (nnum % &million).is_zero() && cnum > &BigInt::one() {
691            ntext = format!("{}lhões", drop_last_4_chars(&ntext));
692        }
693
694        // Corrects the "milião" card typo — but only when the plural surgery
695        // above did not already rewrite it. See module docs, item 1.
696        if ntext == "milião" {
697            ntext = "milhão".to_string();
698        }
699        if nnum == &hundred {
700            // `self.hundreds[cnum]`. Reachable only with cnum in 2..=9:
701            // ("cem", 100) is emitted solely by the `elem == 100` arm of
702            // splitnum, which requires 100 <= value < 1000, so the sibling
703            // carries div = value/100 in 1..=9 — and div == 1 already
704            // returned above. Larger cnum (e.g. 1000 for "mil e cem") takes
705            // the `nnum < cnum` return and never reaches here. Verified by
706            // instrumenting the real dict over ~80k values: only 2..=9 hit.
707            ctext = hundreds_word(cnum)
708                .unwrap_or_else(|| {
709                    panic!(
710                        "lang_pt merge: self.hundreds[{}] missing (Python raises KeyError)",
711                        cnum
712                    )
713                })
714                .to_string();
715            ntext = String::new();
716        } else {
717            ntext = format!(" {}", ntext);
718        }
719
720        (format!("{}{}", ctext, ntext), cnum * nnum)
721    }
722
723    /// `Num2Word_Base.to_cardinal`, then PT's regex clean-up sweep.
724    ///
725    /// The engine renders every junction with "e", giving
726    /// "mil e cento e catorze"; this loop deletes the "e" after a scale word
727    /// when a *hundreds* group follows and something ("... e ...") still
728    /// follows that. Hence "mil cento e catorze", but "mil e cem" and
729    /// "mil e um" keep theirs.
730    fn to_cardinal(&self, value: &BigInt) -> Result<String> {
731        let mut result = default_to_cardinal(self, value)?;
732
733        for ext in EXTS.iter() {
734            if re_match_ext(&result, ext) {
735                // Python's str.replace with no count: every occurrence goes.
736                // That is deliberate — it is what turns
737                // "cem milhões e duzentos mil e duzentos e dez" into
738                // "cem milhões duzentos mil duzentos e dez".
739                result = result.replace(&format!("{} e", ext), ext);
740            }
741        }
742
743        Ok(result)
744    }
745
746    /// `Num2Word_PT.to_cardinal` on **float / Decimal** input.
747    ///
748    /// Python routes non-integers through `to_cardinal`, whose `super()` call
749    /// lands on `Num2Word_Base.to_cardinal` → `to_cardinal_float` (neither PT
750    /// nor EUR overrides the latter, so the shared [`default_to_cardinal_float`]
751    /// reproduces it exactly). The catch is that `PT.to_cardinal` then runs its
752    /// EXTS sweep over the **whole** returned string — fraction included — and
753    /// that trailing sweep is *not* a no-op:
754    ///
755    /// The recursive `to_cardinal(pre)` already swept the integer part in
756    /// isolation, but a "…{scale} e {…}entos" junction sitting at the very end
757    /// of that part is left untouched, because the pattern's mandatory trailing
758    /// space is missing (nothing follows the "entos" word). Once the fraction
759    /// is appended, that word gains a following space, and any fractional digit
760    /// word carrying an 'e' — "zero", "sete", "nove" — satisfies the pattern's
761    /// `(?=.*e)` lookahead. So the second, whole-string sweep can fire where the
762    /// first could not: `1200.7` → "mil duzentos vírgula sete", while `1200.5`
763    /// stays "mil e duzentos vírgula cinco" and the integer `1200` stays
764    /// "mil e duzentos". Verified against the live interpreter.
765    ///
766    /// This outer sweep is the *sole* reason PT diverges from the shared float
767    /// path. Everything upstream of it — `float2tuple`, the banker's-rounding
768    /// heuristic, the `precision_override` handling, the zero-`pre` negword
769    /// insertion — is inherited unchanged, so it is delegated rather than
770    /// re-derived. The sweep body is identical to [`LangPt::to_cardinal`]'s and
771    /// is inlined here to leave that frozen integer path untouched.
772    fn to_cardinal_float(
773        &self,
774        value: &FloatValue,
775        precision_override: Option<u32>,
776    ) -> Result<String> {
777        let mut result = default_to_cardinal_float(self, value, precision_override)?;
778
779        for ext in EXTS.iter() {
780            if re_match_ext(&result, ext) {
781                result = result.replace(&format!("{} e", ext), ext);
782            }
783        }
784
785        Ok(result)
786    }
787
788    fn to_ordinal(&self, value: &BigInt) -> Result<String> {
789        self.verify_ordinal(value)?;
790
791        // Python reassigns `value = str(value)` and later compares it to "1".
792        let value_str = value.to_string();
793        let mut result: Vec<&str> = Vec::new();
794        let mut thousand_sep: &str = "";
795
796        for (idx, ch) in value_str.chars().rev().enumerate() {
797            if idx != 0 && idx % 3 == 0 {
798                // `self.thousand_separators[idx]` — KeyError past 15. This
799                // runs before the `char != "0"` guard below, so 10^18 raises
800                // even though its digit here is a 1.
801                thousand_sep = match thousand_separator(idx) {
802                    Some(s) => s,
803                    None => return Err(N2WError::Key(format!("{}", idx))),
804                };
805            }
806
807            if ch != '0' && !thousand_sep.is_empty() {
808                // Held back until a non-zero digit turns up, so that 6000000
809                // is "sexto milionésimo" and not "sexto milionésimo milésimo".
810                result.push(thousand_sep);
811                thousand_sep = "";
812            }
813
814            let d = ch.to_digit(10).expect("BigInt renders as digits only") as usize;
815            result.push(ORDS[idx % 3][d]);
816        }
817
818        result.reverse();
819        let joined = result.join(" ");
820        let collapsed = collapse_ws(joined.trim());
821
822        if collapsed.starts_with("primeiro") && value_str != "1" {
823            // Python's `result[9:]` drops "primeiro " — a char slice, and the
824            // tail routinely starts with "milésimo"/"bilionésimo", so this
825            // must not be a byte slice.
826            return Ok(collapsed.chars().skip(9).collect());
827        }
828
829        Ok(collapsed)
830    }
831
832    fn to_ordinal_num(&self, value: &BigInt) -> Result<String> {
833        self.verify_ordinal(value)?;
834        Ok(format!("{}º", value))
835    }
836
837    fn to_year(&self, value: &BigInt) -> Result<String> {
838        if value.is_negative() {
839            return Ok(format!(
840                "{} antes de Cristo",
841                self.to_cardinal(&value.abs())?
842            ));
843        }
844        self.to_cardinal(value)
845    }
846
847    // ---- float/Decimal entry points --------------------------------------
848    //
849    // `cardinal_float_entry` stays at the trait default (Base's
850    // `assert int(value) == value` routing: whole -> int path, fractional ->
851    // to_cardinal_float), which is exactly what PT inherits from
852    // Num2Word_Base. Only ordinal / ordinal_num / year need overrides.
853
854    /// `Num2Word_PT.to_ordinal` on float/Decimal input.
855    ///
856    /// The first statement is `value = int(value)` — truncation toward zero —
857    /// and `verify_ordinal` runs on the *truncated* int. So `2.5` ->
858    /// "segundo", `0.5` -> "", `-0.0` -> "", and `-1.5` raises the
859    /// negative-num TypeError (never the float one). Values of 10^18 and up
860    /// still hit the `thousand_separators` KeyError (module docs, item 6):
861    /// `to_ordinal(1e+20)` raises KeyError.
862    fn ordinal_float_entry(&self, value: &FloatValue) -> Result<String> {
863        self.to_ordinal(&float_trunc_int(value)?)
864    }
865
866    /// `Num2Word_PT.to_ordinal_num` on float/Decimal input:
867    /// `verify_ordinal(value)` on the **raw** value, then `"%sº" % value`.
868    ///
869    /// Check order is Python's: the float test (`value == int(value)`) comes
870    /// first, so `-1.5` raises `errmsg_floatord`, not `errmsg_negord`. Both
871    /// messages interpolate `str(value)` — the binding's `repr_str`. The
872    /// negative test is `not abs(value) == value`, a numeric comparison:
873    /// `-0.0` passes (abs(-0.0) == -0.0) and yields "-0.0º".
874    fn ordinal_num_float_entry(&self, value: &FloatValue, repr_str: &str) -> Result<String> {
875        match value.as_whole_int() {
876            None => Err(N2WError::Type(format!(
877                "Cannot treat float {} as ordinal.",
878                repr_str
879            ))),
880            Some(i) if i.is_negative() => Err(N2WError::Type(format!(
881                "Cannot treat negative num {} as ordinal.",
882                repr_str
883            ))),
884            Some(_) => Ok(format!("{}º", repr_str)),
885        }
886    }
887
888    /// `Num2Word_PT.to_year` on float/Decimal input. `val < 0` is numeric
889    /// (-0.0 goes positive), and the negative branch renders
890    /// `to_cardinal(abs(val))` — whole floats through the int path,
891    /// fractional ones through the float grammar: `to_year(-1.5)` ==
892    /// "um vírgula cinco antes de Cristo".
893    fn year_float_entry(&self, value: &FloatValue) -> Result<String> {
894        if fv_numeric_negative(value) {
895            return Ok(format!(
896                "{} antes de Cristo",
897                self.cardinal_float_entry(&fv_abs(value), None)?
898            ));
899        }
900        self.cardinal_float_entry(value, None)
901    }
902
903    // ---- fractions --------------------------------------------------------
904
905    /// `Num2Word_PT.to_fraction` (issue #584).
906    ///
907    /// Deviations from the Base default, all transcribed:
908    ///   * idiomatic halves/thirds: "meio"/"meios", "terço"/"terços";
909    ///   * the "s" plural is appended only when the ordinal does not already
910    ///     end in "s" (Base appends unconditionally);
911    ///   * `abs_n == 1` short-circuits the numerator to the literal "um".
912    /// `denominator == 1` / `numerator == 0` return the *signed* cardinal,
913    /// before any of that. `self.to_ordinal(abs_d)` can still raise (KeyError
914    /// at 10^18+), which propagates exactly as in Python.
915    fn to_fraction(&self, numerator: &BigInt, denominator: &BigInt) -> Result<String> {
916        if denominator.is_zero() {
917            return Err(N2WError::ZeroDivision(
918                "denominator must not be zero".into(),
919            ));
920        }
921        if denominator.is_one() || numerator.is_zero() {
922            return self.to_cardinal(numerator);
923        }
924        let is_negative = numerator.is_negative() ^ denominator.is_negative();
925        let abs_n = numerator.abs();
926        let abs_d = denominator.abs();
927
928        let den_word = if abs_d == BigInt::from(2) {
929            if abs_n.is_one() { "meio" } else { "meios" }.to_string()
930        } else if abs_d == BigInt::from(3) {
931            if abs_n.is_one() { "terço" } else { "terços" }.to_string()
932        } else {
933            let mut w = self.to_ordinal(&abs_d)?;
934            if !abs_n.is_one() && !w.ends_with('s') {
935                w.push('s');
936            }
937            w
938        };
939        let num_word = if abs_n.is_one() {
940            "um".to_string()
941        } else {
942            self.to_cardinal(&abs_n)?
943        };
944        let sign = if is_negative {
945            format!("{} ", self.negword().trim())
946        } else {
947            String::new()
948        };
949        Ok(format!("{}{} {}", sign, num_word, den_word))
950    }
951
952    // ---- currency -------------------------------------------------------
953    //
954    // PT inherits `to_cheque`, `_money_verbose`, `_cents_verbose` and
955    // `_cents_terse` unchanged from `Num2Word_Base` (the trait defaults
956    // already mirror those), and `pluralize` from `Num2Word_EUR`. It defines
957    // its own `CURRENCY_FORMS` and its own `to_currency`.
958    //
959    // `currency_precision` is deliberately NOT overridden: neither PT nor EUR
960    // defines `CURRENCY_PRECISION`, so it is Base's empty dict and *every*
961    // code divides by 100 — including JPY, which therefore keeps a sen
962    // subunit here ("doze ienes e trinta e quatro sen") instead of being the
963    // 0-decimal currency it is elsewhere. The corpus pins that. It also means
964    // `default_to_currency`'s `divisor == 1` branch is unreachable for PT, and
965    // that KWD/BHD are not 3-decimal here — they are simply absent from the
966    // table, which is a different code path entirely (see `to_currency`).
967
968    fn lang_name(&self) -> &str {
969        "Num2Word_PT"
970    }
971
972    fn currency_forms(&self, code: &str) -> Option<&CurrencyForms> {
973        self.currency_forms.get(code)
974    }
975
976    fn currency_adjective(&self, code: &str) -> Option<&str> {
977        self.currency_adjectives.get(code).copied()
978    }
979
980    /// `Num2Word_EUR.pluralize`: `forms[0 if n == 1 else 1]`.
981    ///
982    /// Reached only from the float path — PT's int path inlines the same rule
983    /// instead of calling this. Python indexes the tuple directly, so a
984    /// one-form entry with `n != 1` raises IndexError; every PT entry has two
985    /// forms, so that is unreachable, but it is mapped to `Index` rather than
986    /// left to panic in case the table ever changes.
987    fn pluralize(&self, n: &BigInt, forms: &[String]) -> Result<String> {
988        let form = if n.is_one() { 0 } else { 1 };
989        forms
990            .get(form)
991            .cloned()
992            .ok_or_else(|| N2WError::Index("tuple index out of range".into()))
993    }
994
995    /// `Num2Word_PT.to_currency`.
996    ///
997    /// Two entirely separate paths, split on `isinstance(val, int)`:
998    ///
999    /// * **int** — hand-rolled here, and it never shows cents. Two quirks
1000    ///   worth naming, both preserved:
1001    ///   1. An unknown currency code does **not** raise. Python's
1002    ///      `except KeyError: return self.to_cardinal(val)` silently drops the
1003    ///      currency name, so `num2words(100, lang="pt", to="currency",
1004    ///      currency="KWD")` is just `"cem"`. The corpus pins this for
1005    ///      KWD/BHD/CHF, which is why those codes have *passing* int rows and
1006    ///      *raising* float rows.
1007    ///   2. `adjective` is ignored outright — the int branch never consults
1008    ///      `CURRENCY_ADJECTIVES`, so `adjective=True` is a no-op on ints
1009    ///      while it works on floats.
1010    /// * **float/Decimal** — delegated to `Num2Word_Base.to_currency`, then
1011    ///   post-processed with the same "de" sweep.
1012    ///
1013    /// Python also chops and restores `self.negword` around both paths. That
1014    /// is not modelled: every read goes through `.strip()`, so "menos " and
1015    /// "menos" are indistinguishable and the chop is dead — *except* when the
1016    /// wrapped call raises and the restore is skipped, which is the leak the
1017    /// module docs describe and this port declines to reproduce.
1018    fn to_currency(
1019        &self,
1020        val: &CurrencyValue,
1021        currency: &str,
1022        cents: bool,
1023        separator: Option<&str>,
1024        adjective: bool,
1025    ) -> Result<String> {
1026        if let CurrencyValue::Int(v) = val {
1027            let forms = match self.currency_forms(currency) {
1028                Some(f) => f,
1029                // `except KeyError: return self.to_cardinal(val)` — note it
1030                // takes the *signed* value, so -5 KWD is "menos cinco".
1031                None => return self.to_cardinal(v),
1032            };
1033
1034            let minus_str = if v.is_negative() {
1035                format!("{} ", self.negword().trim())
1036            } else {
1037                String::new()
1038            };
1039            let abs_val = v.abs();
1040            let money_str = self.to_cardinal(&abs_val)?;
1041
1042            // PT re-implements EUR's `pluralize` inline rather than calling
1043            // it. Same rule, so the duplication is only historical — but the
1044            // `len(cr1) > 1` guard it carries is real, and transcribed.
1045            let currency_str = if abs_val.is_one() {
1046                &forms.unit[0]
1047            } else {
1048                forms.unit.get(1).unwrap_or(&forms.unit[0])
1049            };
1050
1051            let result = insert_de(
1052                format!("{}{} {}", minus_str, money_str, currency_str),
1053                currency_str,
1054            );
1055            // `return result.strip()`. The float path below has no strip().
1056            return Ok(result.trim().to_string());
1057        }
1058
1059        // `super().to_currency(...)` — Num2Word_EUR does not override it, so
1060        // this lands on Num2Word_Base. `separator=None` means the caller
1061        // omitted the kwarg; resolving it is the default body's job, and this
1062        // override replaces that body, so it is done here.
1063        let result = crate::currency::default_to_currency(
1064            self,
1065            val,
1066            currency,
1067            cents,
1068            separator.unwrap_or(self.default_separator()),
1069            adjective,
1070        )?;
1071
1072        // `cr1, _ = self.CURRENCY_FORMS[currency]`, *after* the super() call —
1073        // so an unknown code has already raised NotImplementedError above and
1074        // this KeyError is unreachable.
1075        let forms = match self.currency_forms(currency) {
1076            Some(f) => f,
1077            None => return Err(N2WError::Key(format!("'{}'", currency))),
1078        };
1079        // Python indexes `cr1[1]` unconditionally: the plural form, whatever
1080        // `pluralize` actually picked. So at val=1.0 the sweep tests against
1081        // "euros" while the rendered string says "euro" — harmless, since a
1082        // value of exactly 1 can never contain "milhão". Unreachable
1083        // IndexError, as every PT entry is a 2-tuple.
1084        let plural = match forms.unit.get(1) {
1085            Some(p) => p,
1086            None => return Err(N2WError::Index("tuple index out of range".into())),
1087        };
1088        Ok(insert_de(result, plural))
1089    }
1090}