Skip to content

Commit caad2ae

Browse files
authored
unicodedata: resolve name aliases and named sequences (#8676)
* unicodedata: resolve name aliases and named sequences Vendor Unicode 17 NameAliases.txt and NamedSequences.txt into rustpython-unicode so unicodedata.lookup matches CPython: formal aliases and named sequences on the modern view, none on ucd_3_2_0. Tangut derived-name lookup is case-insensitive. \N{} still rejects named sequences because they are not a single character. Assisted-by: Claude * test_ucn: drop expectedFailure on test_aliases The name-alias tables make the test pass; leaving the marker fails CI as an unexpected success. Assisted-by: Claude * unicode: reject whitespace in Tangut derived names parse_hex_code does not skip spaces around the hex digits. Assisted-by: Claude
1 parent 2bbb6e6 commit caad2ae

9 files changed

Lines changed: 1417 additions & 12 deletions

File tree

‎Lib/test/test_ucn.py‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,6 @@ def test_misc_symbols(self):
149149
self.checkletter("HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK", "\uFF9F")
150150
self.checkletter("FULLWIDTH LATIN SMALL LETTER A", "\uFF41")
151151

152-
@unittest.expectedFailure # TODO: RUSTPYTHON
153152
def test_aliases(self):
154153
# Check that the aliases defined in the NameAliases.txt file work.
155154
# This should be updated when new aliases are added or the file
@@ -190,7 +189,6 @@ def test_named_sequences_names_in_pua_range(self):
190189
unicodedata.name(chr(cp))
191190
self.assertEqual(str(cm.exception), 'no such name')
192191

193-
@unittest.expectedFailure # TODO: RUSTPYTHON
194192
def test_named_sequences_sample(self):
195193
# Check a few named sequences. See #12753.
196194
sequences = [
@@ -207,7 +205,6 @@ def test_named_sequences_sample(self):
207205
with self.assertRaises(KeyError):
208206
unicodedata.ucd_3_2_0.lookup(seqname)
209207

210-
@unittest.expectedFailure # TODO: RUSTPYTHON
211208
def test_named_sequences_full(self):
212209
# Check all the named sequences
213210
def check_version(testfile):

‎crates/stdlib/src/unicodedata.rs‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,12 @@ mod unicodedata {
101101
#[pymethod]
102102
fn lookup(&self, name: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
103103
if let Some(name_str) = name.to_str()
104-
&& let Some(character) = unicode_core::lookup_character(name_str)
105-
&& self.inner.membership(character)
104+
&& let Some(found) = self.inner.lookup(name_str)
106105
{
107-
return Ok(character.to_string());
106+
return Ok(match found {
107+
unicode_core::LookupResult::Character(ch) => ch.to_string(),
108+
unicode_core::LookupResult::Sequence(seq) => seq.to_string(),
109+
});
108110
}
109111
Err(vm.new_key_error(
110112
vm.ctx

‎crates/unicode/build.rs‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,7 @@ fn full_data_parsers_latest() {
221221

222222
generate_decomp(decomp_lines);
223223
generate_algo_names(algo_names);
224+
generate_name_lookups();
224225
}
225226

226227
fn generate_decomp(decomp_lines: Vec<(u32, String)>) {
@@ -340,6 +341,78 @@ fn generate_algo_names(names: Vec<(u32, Box<str>)>) {
340341
);
341342
}
342343

344+
/// Formal name aliases (`NameAliases.txt`) and named sequences
345+
/// (`NamedSequences.txt`). `unicodedata.lookup` consults both; `\N{}`
346+
/// accepts only a single character, so named sequences stay out of
347+
/// `lookup_character`.
348+
fn generate_name_lookups() {
349+
let mut aliases: Vec<(String, u32)> = Vec::new();
350+
for line in UnicodeLineReader::from_file_name("NameAliases.txt", true) {
351+
let name = line
352+
.field(
353+
NonZeroUsize::new(1).unwrap(),
354+
Some(&format!(
355+
"field 1 (alias) missing from NameAliases.txt: {}",
356+
line.line
357+
)),
358+
)
359+
.to_ascii_uppercase();
360+
aliases.push((name, line.start));
361+
}
362+
aliases.sort_unstable_by(|a, b| a.0.cmp(&b.0));
363+
aliases.dedup_by(|a, b| a.0 == b.0);
364+
365+
let mut sequences: Vec<(String, String)> = Vec::new();
366+
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
367+
.join("unicode")
368+
.join("latest")
369+
.join("NamedSequences.txt");
370+
let file = File::open(&path).unwrap_or_else(|e| {
371+
panic!(
372+
"{e}: vendored Unicode data file should exist: {}",
373+
path.display()
374+
)
375+
});
376+
for raw in BufReader::new(file).lines() {
377+
let raw = raw.unwrap();
378+
let line = raw.trim();
379+
if line.is_empty() || line.starts_with('#') {
380+
continue;
381+
}
382+
let (name, codes) = line
383+
.split_once(';')
384+
.unwrap_or_else(|| panic!("NamedSequences.txt line should be `NAME; HEX HEX`: {line}"));
385+
let name = name.trim().to_ascii_uppercase();
386+
let mut escaped = String::new();
387+
for hex in codes.split_whitespace() {
388+
let cp = u32::from_str_radix(hex, 16).unwrap_or_else(|e| {
389+
panic!("NamedSequences.txt code point should be hex: {hex} ({e})")
390+
});
391+
escaped.push_str("\\u{");
392+
escaped.push_str(&format!("{cp:X}"));
393+
escaped.push('}');
394+
}
395+
sequences.push((name, escaped));
396+
}
397+
sequences.sort_unstable_by(|a, b| a.0.cmp(&b.0));
398+
sequences.dedup_by(|a, b| a.0 == b.0);
399+
400+
let mut writer = open_writer("name_lookups.rs");
401+
writeln!(writer, "static NAME_ALIASES: &[(&str, char)] = &[").unwrap();
402+
for (name, code) in &aliases {
403+
let ch = char::from_u32(*code)
404+
.unwrap_or_else(|| panic!("NameAliases.txt code point should be a scalar: {code:04X}"));
405+
writeln!(writer, " (\"{name}\", '\\u{{{:X}}}'),", ch as u32).unwrap();
406+
}
407+
writeln!(writer, "];").unwrap();
408+
409+
writeln!(writer, "static NAMED_SEQUENCES: &[(&str, &str)] = &[").unwrap();
410+
for (name, escaped) in &sequences {
411+
writeln!(writer, " (\"{name}\", \"{escaped}\"),").unwrap();
412+
}
413+
writeln!(writer, "];").unwrap();
414+
}
415+
343416
/// Drive parsers that require the full 3.2.0 data.
344417
///
345418
/// As the full data set is HUGE, it's more efficient to parse it once then delegate to subparsers.

‎crates/unicode/src/data.rs‎

Lines changed: 134 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use icu_properties::props::{
2020
use rustpython_wtf8::CodePoint;
2121

2222
include!(concat!(env!("OUT_DIR"), "/generated/algo_names.rs"));
23+
include!(concat!(env!("OUT_DIR"), "/generated/name_lookups.rs"));
2324
include!(concat!(env!("OUT_DIR"), "/generated/bidi_class_3_2.rs"));
2425
include!(concat!(env!("OUT_DIR"), "/generated/binary_props_3_2.rs"));
2526
include!(concat!(
@@ -95,8 +96,20 @@ impl AlgorithmicName {
9596
}
9697

9798
fn check_name(search_name: &str) -> Option<char> {
98-
if let Some(without_base) = search_name.strip_prefix(Self::TangutIdeograph.name_base()) {
99-
let cp = u32::from_str_radix(without_base.strip_prefix('-')?.trim(), 16).ok()?;
99+
// CPython compares derived-name prefixes case-insensitively
100+
// (`PyOS_strnicmp` in `_getcode`).
101+
let folded: String = search_name
102+
.chars()
103+
.map(|c| c.to_ascii_uppercase())
104+
.collect();
105+
if let Some(without_base) = folded.strip_prefix(Self::TangutIdeograph.name_base()) {
106+
// `parse_hex_code` does not skip spaces around the digits.
107+
let hex = without_base.strip_prefix('-')?;
108+
// `_getcode` / `parse_hex_code`: 4–6 digits, no leading zero.
109+
if hex.len() < 4 || hex.len() > 6 || hex.starts_with('0') {
110+
return None;
111+
}
112+
let cp = u32::from_str_radix(hex, 16).ok()?;
100113
let ch = char::from_u32(cp)?;
101114
if lookup_table(ALGO_NAMES, ch)? == Self::TangutIdeograph {
102115
return Some(ch);
@@ -107,6 +120,36 @@ impl AlgorithmicName {
107120
}
108121
}
109122

123+
/// Result of `unicodedata.lookup`.
124+
///
125+
/// A named sequence is several characters; `\N{...}` only accepts a
126+
/// single character, so `lookup_character` drops `Sequence`.
127+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128+
pub enum LookupResult {
129+
Character(char),
130+
Sequence(&'static str),
131+
}
132+
133+
fn fold_lookup_name(name: &str) -> String {
134+
name.chars().map(|c| c.to_ascii_uppercase()).collect()
135+
}
136+
137+
fn lookup_alias(name: &str) -> Option<char> {
138+
let key = fold_lookup_name(name);
139+
NAME_ALIASES
140+
.binary_search_by_key(&key.as_str(), |(n, _)| *n)
141+
.ok()
142+
.map(|i| NAME_ALIASES[i].1)
143+
}
144+
145+
fn lookup_named_sequence(name: &str) -> Option<&'static str> {
146+
let key = fold_lookup_name(name);
147+
NAMED_SEQUENCES
148+
.binary_search_by_key(&key.as_str(), |(n, _)| *n)
149+
.ok()
150+
.map(|i| NAMED_SEQUENCES[i].1)
151+
}
152+
110153
fn lookup_table<T: Copy>(table: &[(u32, u32, T)], ch: char) -> Option<T> {
111154
let ch = ch as u32;
112155
table
@@ -170,10 +213,24 @@ pub fn unicode_version() -> String {
170213
)
171214
}
172215

173-
/// Look up a character by its Unicode name (`unicodedata.lookup`).
216+
/// Look up a name in the latest UCD (`unicodedata.lookup`).
217+
///
218+
/// Named sequences are included; `\N{...}` should use [`lookup_character`]
219+
/// so a sequence is reported as unknown.
220+
#[must_use]
221+
pub fn lookup_name(search_name: &str) -> Option<LookupResult> {
222+
Ucd::new(true).lookup(search_name)
223+
}
224+
225+
/// Look up a single character by its Unicode name (`\N{...}`).
226+
///
227+
/// Named sequences are not characters and so do not resolve.
174228
#[must_use]
175229
pub fn lookup_character(search_name: &str) -> Option<char> {
176-
unicode_names2::character(search_name).or_else(|| AlgorithmicName::check_name(search_name))
230+
match lookup_name(search_name) {
231+
Some(LookupResult::Character(ch)) => Some(ch),
232+
Some(LookupResult::Sequence(_)) | None => None,
233+
}
177234
}
178235

179236
/// The Unicode name of `ch` (`unicodedata.name`), if any.
@@ -210,6 +267,26 @@ impl Ucd {
210267
}
211268
}
212269

270+
/// Look up `name` in this UCD view.
271+
///
272+
/// Unicode 3.2.0 has no name aliases and no named sequences
273+
/// (`unicodedata.ucd_3_2_0.lookup`).
274+
#[must_use]
275+
pub fn lookup(self, search_name: &str) -> Option<LookupResult> {
276+
if let Some(ch) = unicode_names2::character(search_name)
277+
.or_else(|| AlgorithmicName::check_name(search_name))
278+
{
279+
return self.membership(ch).then_some(LookupResult::Character(ch));
280+
}
281+
if !self.modern {
282+
return None;
283+
}
284+
if let Some(ch) = lookup_alias(search_name) {
285+
return Some(LookupResult::Character(ch));
286+
}
287+
lookup_named_sequence(search_name).map(LookupResult::Sequence)
288+
}
289+
213290
#[must_use]
214291
pub fn category(&self, c: CodePoint) -> &'static str {
215292
let Some(c) = c.to_char() else {
@@ -414,7 +491,7 @@ impl Ucd {
414491
mod tests {
415492
use rustpython_wtf8::CodePoint;
416493

417-
use super::{Ucd, character_name, lookup_character};
494+
use super::{LookupResult, Ucd, character_name, lookup_character, lookup_name};
418495

419496
fn cp(ch: char) -> CodePoint {
420497
CodePoint::from(ch)
@@ -438,4 +515,56 @@ mod tests {
438515
let legacy = Ucd::new(false);
439516
assert_eq!(legacy.unidata_version(), "3.2.0");
440517
}
518+
519+
#[test]
520+
fn name_aliases_resolve_and_do_not_replace_the_official_name() {
521+
assert_eq!(
522+
lookup_character("LATIN CAPITAL LETTER GHA"),
523+
Some('\u{01A2}')
524+
);
525+
assert_eq!(
526+
lookup_character("latin capital letter gha"),
527+
Some('\u{01A2}')
528+
);
529+
assert_eq!(
530+
character_name('\u{01A2}').as_deref(),
531+
Some("LATIN CAPITAL LETTER OI")
532+
);
533+
assert_eq!(Ucd::new(false).lookup("LATIN CAPITAL LETTER GHA"), None);
534+
}
535+
536+
#[test]
537+
fn named_sequences_resolve_only_on_the_modern_view() {
538+
assert_eq!(
539+
lookup_name("LATIN SMALL LETTER R WITH TILDE"),
540+
Some(LookupResult::Sequence("r\u{0303}"))
541+
);
542+
assert_eq!(
543+
lookup_name("KEYCAP NUMBER SIGN"),
544+
Some(LookupResult::Sequence("#\u{FE0F}\u{20E3}"))
545+
);
546+
assert_eq!(lookup_character("LATIN SMALL LETTER R WITH TILDE"), None);
547+
assert_eq!(
548+
Ucd::new(false).lookup("LATIN SMALL LETTER R WITH TILDE"),
549+
None
550+
);
551+
}
552+
553+
#[test]
554+
fn tangut_derived_names_are_case_insensitive() {
555+
assert_eq!(
556+
lookup_character("TANGUT IDEOGRAPH-17000"),
557+
Some('\u{17000}')
558+
);
559+
assert_eq!(
560+
lookup_character("tangut ideograph-18d08"),
561+
Some('\u{18D08}')
562+
);
563+
assert_eq!(
564+
character_name('\u{17000}').as_deref(),
565+
Some("TANGUT IDEOGRAPH-17000")
566+
);
567+
assert_eq!(lookup_character("TANGUT IDEOGRAPH- 17000"), None);
568+
assert_eq!(lookup_character("TANGUT IDEOGRAPH-17000 "), None);
569+
}
441570
}

‎crates/unicode/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,5 @@ pub mod data;
1515
pub mod identifier;
1616
pub mod normalize;
1717

18-
pub use data::{Ucd, character_name, lookup_character, unicode_version};
18+
pub use data::{LookupResult, Ucd, character_name, lookup_character, lookup_name, unicode_version};
1919
pub use normalize::{NormalizeForm, is_normalized, normalize};

‎crates/unicode/unicode/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,6 @@ The vendored data files come directly from the official [Unicode site](https://w
44

55
The files in `latest` need to be periodically bumped to match `icu4x` and Rust. These files may be found at the [Unicode Character Database](https://www.unicode.org/ucd/).
66

7+
`NameAliases.txt` and `NamedSequences.txt` feed `unicodedata.lookup` (formal aliases and named sequences). They are not used by `unicodedata.name`, which still reports the official character name.
8+
79
RustPython vendors [Unicode 3.2.0](https://www.unicode.org/reports/tr28/tr28-3.html) to match CPython. CPython uses 3.2.0 to ensure backwards compatibility with a few older modules. Unicode 3.2.0 was released in 2002 and does not need periodic refreshes.

0 commit comments

Comments
 (0)