Skip to main content

bilingua_model/
pytext.rs

1//! Python's character tests, exactly: `str.isalpha`, `str.isalnum` and `str.isspace` of Python 3.13 (Unicode
2//! 15.1), which Localization OS uses for its "has a letter or digit" and whitespace rules.
3//!
4//! Rust's `char::is_alphanumeric` and friends follow a newer Unicode and differ: they count combining marks
5//! (U+0301, U+0903, ...) and Unicode 16 letters as alphanumeric where Python does not, and `is_whitespace` leaves
6//! out U+001C..U+001F, which Python treats as whitespace. A format crate that must skip or keep the same values as
7//! Localization OS calls these instead. The tables come from `tools/gen_pytables.py`.
8
9use crate::pytables::{ALNUM, ALPHA, DECIMAL, PUNCT_SYMBOL, SPACE};
10
11fn in_table(t: &[(u32, u32)], c: char) -> bool {
12    let c = c as u32;
13    t.binary_search_by(|&(lo, hi)| {
14        if c < lo {
15            std::cmp::Ordering::Greater
16        } else if c > hi {
17            std::cmp::Ordering::Less
18        } else {
19            std::cmp::Ordering::Equal
20        }
21    })
22    .is_ok()
23}
24
25/// `str.isalpha` for one character: a letter (category L*).
26pub fn py_isalpha_char(c: char) -> bool {
27    if c.is_ascii() {
28        return c.is_ascii_alphabetic();
29    }
30    in_table(ALPHA, c)
31}
32
33/// `str.isalnum` for one character: a letter or a number (decimal, digit or numeric).
34pub fn py_isalnum_char(c: char) -> bool {
35    if c.is_ascii() {
36        return c.is_ascii_alphanumeric();
37    }
38    in_table(ALNUM, c)
39}
40
41/// `str.isdecimal` for one character: a decimal digit (category Nd), what `\d` matches in a Python `re` pattern.
42pub fn py_isdecimal_char(c: char) -> bool {
43    if c.is_ascii() {
44        return c.is_ascii_digit();
45    }
46    in_table(DECIMAL, c)
47}
48
49/// What `\w` matches in a Python `re` pattern on a `str`: [`py_isalnum_char`] or `_`.
50pub fn py_is_word_char(c: char) -> bool {
51    c == '_' || py_isalnum_char(c)
52}
53
54/// What `[^\W\d]` matches: a word character that is not a decimal digit (a letter, `_`, or a number such as a
55/// superscript or roman numeral). The first character of a Python `re` identifier pattern.
56pub fn py_is_word_start_char(c: char) -> bool {
57    py_is_word_char(c) && !py_isdecimal_char(c)
58}
59
60/// `str.isspace` for one character.
61pub fn py_isspace_char(c: char) -> bool {
62    if c.is_ascii() {
63        return matches!(c, '\t'..='\r' | '\x1c'..='\x1f' | ' ');
64    }
65    in_table(SPACE, c)
66}
67
68/// `unicodedata.category(c)[0] in "PS"`: a punctuation or symbol character (CommonMark's Unicode punctuation, as
69/// Localization OS's Markdown emphasis repair tests it).
70#[doc(hidden)]
71pub fn py_is_punct_or_symbol_char(c: char) -> bool {
72    if c.is_ascii() {
73        return c.is_ascii_punctuation();
74    }
75    in_table(PUNCT_SYMBOL, c)
76}
77
78/// Python `s.isalpha()`: not empty and every character a letter.
79pub fn py_isalpha(s: &str) -> bool {
80    !s.is_empty() && s.chars().all(py_isalpha_char)
81}
82
83/// Python `s.isalnum()`: not empty and every character a letter or number.
84pub fn py_isalnum(s: &str) -> bool {
85    !s.is_empty() && s.chars().all(py_isalnum_char)
86}
87
88/// Python `s.isspace()`: not empty and every character whitespace.
89pub fn py_isspace(s: &str) -> bool {
90    !s.is_empty() && s.chars().all(py_isspace_char)
91}
92
93/// Python `any(ch.isalnum() for ch in s)`: the string has a letter or digit anywhere. This is the usual
94/// "does this value carry text" test; combining marks, punctuation and symbols alone do not count.
95pub fn py_has_alnum(s: &str) -> bool {
96    s.chars().any(py_isalnum_char)
97}
98
99/// Python `any(ch.isalpha() for ch in s)`.
100pub fn py_has_alpha(s: &str) -> bool {
101    s.chars().any(py_isalpha_char)
102}
103
104/// Python `s.strip()` (no argument): strips [`py_isspace_char`] characters from both ends.
105pub fn py_strip(s: &str) -> &str {
106    s.trim_matches(py_isspace_char)
107}
108
109/// Python `s.lstrip()`.
110pub fn py_lstrip(s: &str) -> &str {
111    s.trim_start_matches(py_isspace_char)
112}
113
114/// Python `s.rstrip()`.
115pub fn py_rstrip(s: &str) -> &str {
116    s.trim_end_matches(py_isspace_char)
117}
118
119/// True for the characters Python's `str.splitlines` breaks at (`\r\n` counts as one break): `\n`, `\r`, `\x0b`,
120/// `\x0c`, `\x1c`, `\x1d`, `\x1e`, U+0085, U+2028, U+2029.
121#[doc(hidden)]
122pub fn py_is_line_break(c: char) -> bool {
123    matches!(c, '\n' | '\r' | '\u{0b}' | '\u{0c}' | '\u{1c}' | '\u{1d}' | '\u{1e}' | '\u{85}' | '\u{2028}' | '\u{2029}')
124}
125
126/// Python `s.splitlines(keepends=True)`: every line with its own terminator (`\r\n` counts as one).
127#[doc(hidden)]
128pub fn py_splitlines_keepends(s: &str) -> Vec<&str> {
129    let mut out = Vec::new();
130    let mut start = 0;
131    let mut it = s.char_indices().peekable();
132    while let Some((i, c)) = it.next() {
133        if py_is_line_break(c) {
134            let mut end = i + c.len_utf8();
135            if c == '\r' && matches!(it.peek(), Some(&(_, '\n'))) {
136                it.next();
137                end += 1;
138            }
139            out.push(&s[start..end]);
140            start = end;
141        }
142    }
143    if start < s.len() {
144        out.push(&s[start..]);
145    }
146    out
147}
148
149/// Splits one line of [`py_splitlines_keepends`] into its body and its terminator (`""`, one break, or `\r\n`).
150#[doc(hidden)]
151pub fn py_split_line_end(line: &str) -> (&str, &str) {
152    if let Some(body) = line.strip_suffix("\r\n") {
153        return (body, "\r\n");
154    }
155    match line.chars().next_back() {
156        Some(c) if py_is_line_break(c) => line.split_at(line.len() - c.len_utf8()),
157        _ => (line, ""),
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    #[test]
166    fn splitlines_is_pythons() {
167        assert_eq!(py_splitlines_keepends("a\r\nb\rc\u{2028}d\x0ce\n\nf"), ["a\r\n", "b\r", "c\u{2028}", "d\x0c", "e\n", "\n", "f"]);
168        assert!(py_splitlines_keepends("").is_empty());
169        assert_eq!(py_split_line_end("x\r\n"), ("x", "\r\n"));
170        assert_eq!(py_split_line_end("\n"), ("", "\n"));
171        assert_eq!(py_split_line_end("x\u{85}"), ("x", "\u{85}"));
172        assert_eq!(py_split_line_end("x"), ("x", ""));
173    }
174
175    #[test]
176    fn combining_marks_are_not_alphanumeric() {
177        assert!(!py_has_alnum("\u{0301}"));
178        assert!(!py_has_alnum("\u{0903}\u{200D}"));
179        assert!(!py_isalnum("\u{0301}"));
180        assert!(py_has_alnum("e\u{0301}"));
181        // Rust says alphanumeric, Python does not
182        assert!('\u{0345}'.is_alphabetic() && !py_isalpha_char('\u{0345}'));
183        assert!('\u{05B0}'.is_alphabetic() && !py_isalpha_char('\u{05B0}'));
184    }
185
186    #[test]
187    fn numbers_count_as_alnum_but_not_alpha() {
188        for c in ['5', '\u{0665}', '\u{00B2}', '\u{00BD}', '\u{2160}', '\u{4E00}', '\u{3007}'] {
189            assert!(py_isalnum_char(c), "{c:?}");
190        }
191        assert!(!py_isalpha_char('5') && !py_isalpha_char('\u{00BD}'));
192        assert!(py_isalpha_char('\u{4E00}') && !py_isalpha_char('\u{3007}') );
193    }
194
195    #[test]
196    fn word_chars_follow_python_re() {
197        assert!(py_is_word_char('_') && py_is_word_char('\u{00B2}') && !py_is_word_char('-'));
198        // superscript two is \w but not \d, so it may start a JSON5 identifier; an Arabic-Indic digit may not
199        assert!(py_is_word_start_char('\u{00B2}') && !py_is_word_start_char('\u{0665}') && !py_is_word_start_char('7'));
200        assert!(!py_is_word_char('\u{0301}'));
201    }
202
203    #[test]
204    fn whitespace_matches_python() {
205        for c in ['\t', '\n', '\x0b', '\x0c', '\r', '\x1c', '\x1d', '\x1e', '\x1f', ' ', '\u{85}', '\u{A0}', '\u{1680}', '\u{2003}', '\u{2028}', '\u{2029}', '\u{202F}', '\u{205F}', '\u{3000}'] {
206            assert!(py_isspace_char(c), "{c:?}");
207        }
208        for c in ['\u{200B}', '\u{FEFF}', '\u{180E}', '\u{2060}', 'a', '\u{0}'] {
209            assert!(!py_isspace_char(c), "{c:?}");
210        }
211        assert!(!'\x1c'.is_whitespace());
212        assert_eq!(py_strip("\x1c a \u{3000}"), "a");
213        assert!(!py_isspace("") && !py_isalnum("") && !py_isalpha(""));
214    }
215
216    #[test]
217    fn rust_and_python_differ_on_unicode_16_letters() {
218        // Garay (Unicode 16) is not in Python 3.13's Unicode 15.1
219        assert!(!py_isalpha_char('\u{10D4A}'));
220        assert!(py_isalpha_char('\u{1E900}'));
221    }
222
223    #[test]
224    fn tables_are_sorted_and_the_ascii_fast_path_agrees() {
225        for t in [ALPHA, ALNUM, DECIMAL, SPACE] {
226            assert!(t.windows(2).all(|w| w[0].1 < w[1].0 && w[0].0 <= w[0].1));
227        }
228        for c in (0u8..128).map(char::from) {
229            assert_eq!(py_isalpha_char(c), in_table(ALPHA, c), "{c:?}");
230            assert_eq!(py_isalnum_char(c), in_table(ALNUM, c), "{c:?}");
231            assert_eq!(py_isspace_char(c), in_table(SPACE, c), "{c:?}");
232        }
233        // every letter is alphanumeric
234        for &(lo, hi) in ALPHA {
235            assert!(in_table(ALNUM, char::from_u32(lo).unwrap()) && in_table(ALNUM, char::from_u32(hi).unwrap()));
236        }
237    }
238}