1#[allow(
26 unused_imports,
27 clippy::wildcard_imports,
28 reason = "Standard workspace crate prelude"
29)]
30pub(crate) use ctb_utilities::*;
31
32use std::collections::HashSet;
33use std::sync::LazyLock;
34
35pub mod character_description;
36pub mod cli;
37pub(crate) mod data;
38
39pub use character_description::{
40 ControlNameFormat, DescriptionMode, DescriptionOptions, UnicodeVersion,
41 describe, describe_codepoint, describe_codepoint_with_options,
42 describe_with_options,
43};
44pub use data::{
45 UnicodeDataTables, find_block, find_block_with_version, get_tables,
46 is_assigned_unicode,
47};
48
49#[doc(inline)]
51pub use ctb_utilities::circular_dep_unicode::*;
52
53pub use icu_properties::props::GeneralCategory;
54
55#[must_use]
57pub fn describe_general_category(type_code: &str) -> String {
58 match type_code {
59 "Cc" => "Control".to_string(),
60 "Cf" => "Format".to_string(),
61 "Cs" => "Surrogate".to_string(),
62 "Co" => "Private Use".to_string(),
63 "Cn" => "Noncharacter".to_string(),
64 "Lu" => "Letter: Uppercase".to_string(),
65 "Ll" => "Letter: Lowercase".to_string(),
66 "Lt" => "Letter: Titlecase".to_string(),
67 "Lm" => "Letter: Modifier".to_string(),
68 "Lo" => "Letter: Other".to_string(),
69 "Mn" => "Mark: Nonspacing".to_string(),
70 "Mc" => "Mark: Spacing Combining".to_string(),
71 "Me" => "Mark: Enclosing".to_string(),
72 "Nd" => "Number: Decimal".to_string(),
73 "Nl" => "Number: Letter".to_string(),
74 "No" => "Number: Other".to_string(),
75 "Pc" => "Punctuation: Connector".to_string(),
76 "Pd" => "Punctuation: Dash".to_string(),
77 "Ps" => "Punctuation: Open".to_string(),
78 "Pe" => "Punctuation: Close".to_string(),
79 "Pi" => "Punctuation: Initial Quote".to_string(),
80 "Pf" => "Punctuation: Final Quote".to_string(),
81 "Po" => "Punctuation: Other".to_string(),
82 "Sm" => "Symbol: Math".to_string(),
83 "Sc" => "Symbol: Currency".to_string(),
84 "Sk" => "Symbol: Modifier".to_string(),
85 "So" => "Symbol: Other".to_string(),
86 "Zs" => "Separator: Space".to_string(),
87 "Zl" => "Separator: Line".to_string(),
88 "Zp" => "Separator: Paragraph".to_string(),
89 other => other.to_string(),
90 }
91}
92
93#[must_use]
95pub fn general_category(c: char) -> GeneralCategory {
96 icu_properties::CodePointMapData::<GeneralCategory>::new().get(c)
97}
98
99#[must_use]
101pub fn is_format_char(c: char) -> bool {
102 general_category(c) == GeneralCategory::Format
103}
104
105#[must_use]
107pub fn is_deprecated_unicode(cp: u32) -> bool {
108 icu_properties::CodePointSetData::new::<icu_properties::props::Deprecated>()
109 .contains32(cp)
110}
111
112#[must_use]
114pub fn normalize_nfc(text: &str) -> String {
115 icu_normalizer::ComposingNormalizerBorrowed::new_nfc()
116 .normalize(text)
117 .into_owned()
118}
119
120#[must_use]
122pub fn is_nfc_normalized(text: &str) -> bool {
123 icu_normalizer::ComposingNormalizerBorrowed::new_nfc().is_normalized(text)
124}
125
126#[must_use]
130pub fn get_unicode_name_for_version(
131 cp: u32,
132 version: UnicodeVersion,
133) -> Option<String> {
134 let tables = data::get_tables(version);
135 character_description::get_unicode_character_name(
136 tables,
137 cp,
138 DescriptionMode::Standard,
139 )
140}
141
142#[must_use]
146pub fn get_unicode_name(cp: u32) -> Option<String> {
147 get_unicode_name_for_version(cp, UnicodeVersion::V17_0)
148}
149
150pub use icu_properties::props::{BidiClass, CanonicalCombiningClass};
151
152#[must_use]
154pub fn general_category_code(cp: u32) -> &'static str {
155 match icu_properties::CodePointMapData::<GeneralCategory>::new().get32(cp) {
156 GeneralCategory::UppercaseLetter => "Lu",
157 GeneralCategory::LowercaseLetter => "Ll",
158 GeneralCategory::TitlecaseLetter => "Lt",
159 GeneralCategory::ModifierLetter => "Lm",
160 GeneralCategory::OtherLetter => "Lo",
161 GeneralCategory::NonspacingMark => "Mn",
162 GeneralCategory::SpacingMark => "Mc",
163 GeneralCategory::EnclosingMark => "Me",
164 GeneralCategory::DecimalNumber => "Nd",
165 GeneralCategory::LetterNumber => "Nl",
166 GeneralCategory::OtherNumber => "No",
167 GeneralCategory::SpaceSeparator => "Zs",
168 GeneralCategory::LineSeparator => "Zl",
169 GeneralCategory::ParagraphSeparator => "Zp",
170 GeneralCategory::Control => "Cc",
171 GeneralCategory::Format => "Cf",
172 GeneralCategory::PrivateUse => "Co",
173 GeneralCategory::Surrogate => "Cs",
174 GeneralCategory::DashPunctuation => "Pd",
175 GeneralCategory::OpenPunctuation => "Ps",
176 GeneralCategory::ClosePunctuation => "Pe",
177 GeneralCategory::ConnectorPunctuation => "Pc",
178 GeneralCategory::InitialPunctuation => "Pi",
179 GeneralCategory::FinalPunctuation => "Pf",
180 GeneralCategory::OtherPunctuation => "Po",
181 GeneralCategory::MathSymbol => "Sm",
182 GeneralCategory::CurrencySymbol => "Sc",
183 GeneralCategory::ModifierSymbol => "Sk",
184 GeneralCategory::OtherSymbol => "So",
185 GeneralCategory::Unassigned => "Cn",
186 }
187}
188
189#[must_use]
191pub fn bidi_class_code(cp: u32) -> &'static str {
192 match icu_properties::CodePointMapData::<BidiClass>::new().get32(cp) {
193 BidiClass::LeftToRight => "L",
194 BidiClass::RightToLeft => "R",
195 BidiClass::EuropeanNumber => "EN",
196 BidiClass::EuropeanSeparator => "ES",
197 BidiClass::EuropeanTerminator => "ET",
198 BidiClass::ArabicNumber => "AN",
199 BidiClass::CommonSeparator => "CS",
200 BidiClass::ParagraphSeparator => "B",
201 BidiClass::SegmentSeparator => "S",
202 BidiClass::WhiteSpace => "WS",
203 BidiClass::OtherNeutral => "ON",
204 BidiClass::LeftToRightEmbedding => "LRE",
205 BidiClass::LeftToRightOverride => "LRO",
206 BidiClass::ArabicLetter => "AL",
207 BidiClass::RightToLeftEmbedding => "RLE",
208 BidiClass::RightToLeftOverride => "RLO",
209 BidiClass::PopDirectionalFormat => "PDF",
210 BidiClass::NonspacingMark => "NSM",
211 BidiClass::BoundaryNeutral => "BN",
212 BidiClass::FirstStrongIsolate => "FSI",
213 BidiClass::LeftToRightIsolate => "LRI",
214 BidiClass::RightToLeftIsolate => "RLI",
215 BidiClass::PopDirectionalIsolate => "PDI",
216 _ => "ON",
217 }
218}
219
220#[must_use]
222pub fn combining_class(cp: u32) -> u8 {
223 icu_properties::CodePointMapData::<CanonicalCombiningClass>::new()
224 .get32(cp)
225 .to_icu4c_value()
226}
227
228#[must_use]
230pub fn script_name(cp: u32) -> Option<&'static str> {
231 let script_map = icu_properties::CodePointMapData::<
232 icu_properties::props::Script,
233 >::new();
234 let script_names = icu_properties::PropertyNamesLong::<
235 icu_properties::props::Script,
236 >::new();
237 let script_val = script_map.get32(cp);
238 script_names.get(script_val)
239}
240
241static ALL_UNICODE_SCRIPTS: LazyLock<HashSet<&'static str>> =
242 LazyLock::new(|| {
243 let script_names = icu_properties::PropertyNamesLong::<
244 icu_properties::props::Script,
245 >::new();
246 let mut scripts = HashSet::new();
247 for i in 0..=1000 {
248 if let Some(name) = script_names
249 .get(icu_properties::props::Script::from_icu4c_value(i))
250 {
251 scripts.insert(name);
252 }
253 }
254 scripts
255 });
256
257#[must_use]
259pub fn is_valid_unicode_script(name: &str) -> bool {
260 ALL_UNICODE_SCRIPTS.contains(name)
261}
262
263#[derive(Debug, Clone, PartialEq, Eq)]
265pub struct UnicodeCharRecord {
266 pub cp: u32,
267 pub name: String,
268 pub combining_class: u8,
269 pub bidi_class: &'static str,
270 pub general_category: &'static str,
271 pub script: String,
272 pub aliases: String,
273 pub description: String,
274 pub is_deprecated: bool,
275}
276
277static ALL_UNICODE_NAMES: LazyLock<HashSet<String>> = LazyLock::new(|| {
278 let tables = data::get_tables(UnicodeVersion::V17_0);
279 let mut names = HashSet::new();
280
281 for cp in 0..=0x10_FFFF {
282 if let Some(n) = character_description::get_unicode_character_name(
283 tables,
284 cp,
285 DescriptionMode::Standard,
286 ) {
287 names.insert(n.to_lowercase());
288 }
289 if let Some(entry) = tables.name_aliases.get(&cp) {
290 if let Some(ref c) = entry.correction {
291 names.insert(c.to_lowercase());
292 }
293 if let Some(ref c) = entry.control {
294 names.insert(c.to_lowercase());
295 }
296 if let Some(ref alt) = entry.alternate {
297 names.insert(alt.to_lowercase());
298 }
299 }
300 }
301 names
302});
303
304#[must_use]
306pub fn is_known_unicode_name(name: &str) -> bool {
307 ALL_UNICODE_NAMES.contains(&name.trim().to_lowercase())
308}
309
310pub fn get_assigned_unicode_records() -> Vec<UnicodeCharRecord> {
312 let tables = data::get_tables(UnicodeVersion::V17_0);
313 let mut records = Vec::new();
314
315 let gc_map = icu_properties::CodePointMapData::<GeneralCategory>::new();
316 let bidi_map = icu_properties::CodePointMapData::<BidiClass>::new();
317 let ccc_map =
318 icu_properties::CodePointMapData::<CanonicalCombiningClass>::new();
319 let script_map = icu_properties::CodePointMapData::<
320 icu_properties::props::Script,
321 >::new();
322 let script_names = icu_properties::PropertyNamesLong::<
323 icu_properties::props::Script,
324 >::new();
325
326 let sample_17_cp = 0x088F; assert_ne!(
329 gc_map.get32(sample_17_cp),
330 GeneralCategory::Unassigned,
331 "Compiled ICU Unicode properties must match inlined Unicode 17.0 tables"
332 );
333
334 for cp in 0..=0x10_FFFF {
335 if !tables.is_assigned(cp) {
336 continue;
337 }
338
339 let name = if let Some(n) =
340 character_description::get_unicode_character_name(
341 tables,
342 cp,
343 DescriptionMode::Standard,
344 ) {
345 n
346 } else if (0xE000..=0xF8FF).contains(&cp)
347 || (0xF0000..=0xFFFFD).contains(&cp)
348 || (0x100000..=0x10FFFD).contains(&cp)
349 {
350 format!("<private-use-{cp:04X}>")
351 } else {
352 continue;
353 };
354
355 let gc = match gc_map.get32(cp) {
356 GeneralCategory::UppercaseLetter => "Lu",
357 GeneralCategory::LowercaseLetter => "Ll",
358 GeneralCategory::TitlecaseLetter => "Lt",
359 GeneralCategory::ModifierLetter => "Lm",
360 GeneralCategory::OtherLetter => "Lo",
361 GeneralCategory::NonspacingMark => "Mn",
362 GeneralCategory::SpacingMark => "Mc",
363 GeneralCategory::EnclosingMark => "Me",
364 GeneralCategory::DecimalNumber => "Nd",
365 GeneralCategory::LetterNumber => "Nl",
366 GeneralCategory::OtherNumber => "No",
367 GeneralCategory::SpaceSeparator => "Zs",
368 GeneralCategory::LineSeparator => "Zl",
369 GeneralCategory::ParagraphSeparator => "Zp",
370 GeneralCategory::Control => "Cc",
371 GeneralCategory::Format => "Cf",
372 GeneralCategory::PrivateUse => "Co",
373 GeneralCategory::Surrogate => "Cs",
374 GeneralCategory::DashPunctuation => "Pd",
375 GeneralCategory::OpenPunctuation => "Ps",
376 GeneralCategory::ClosePunctuation => "Pe",
377 GeneralCategory::ConnectorPunctuation => "Pc",
378 GeneralCategory::InitialPunctuation => "Pi",
379 GeneralCategory::FinalPunctuation => "Pf",
380 GeneralCategory::OtherPunctuation => "Po",
381 GeneralCategory::MathSymbol => "Sm",
382 GeneralCategory::CurrencySymbol => "Sc",
383 GeneralCategory::ModifierSymbol => "Sk",
384 GeneralCategory::OtherSymbol => "So",
385 GeneralCategory::Unassigned => "Cn",
386 };
387
388 let bidi = match bidi_map.get32(cp) {
389 BidiClass::LeftToRight => "L",
390 BidiClass::RightToLeft => "R",
391 BidiClass::EuropeanNumber => "EN",
392 BidiClass::EuropeanSeparator => "ES",
393 BidiClass::EuropeanTerminator => "ET",
394 BidiClass::ArabicNumber => "AN",
395 BidiClass::CommonSeparator => "CS",
396 BidiClass::ParagraphSeparator => "B",
397 BidiClass::SegmentSeparator => "S",
398 BidiClass::WhiteSpace => "WS",
399 BidiClass::OtherNeutral => "ON",
400 BidiClass::LeftToRightEmbedding => "LRE",
401 BidiClass::LeftToRightOverride => "LRO",
402 BidiClass::ArabicLetter => "AL",
403 BidiClass::RightToLeftEmbedding => "RLE",
404 BidiClass::RightToLeftOverride => "RLO",
405 BidiClass::PopDirectionalFormat => "PDF",
406 BidiClass::NonspacingMark => "NSM",
407 BidiClass::BoundaryNeutral => "BN",
408 BidiClass::FirstStrongIsolate => "FSI",
409 BidiClass::LeftToRightIsolate => "LRI",
410 BidiClass::RightToLeftIsolate => "RLI",
411 BidiClass::PopDirectionalIsolate => "PDI",
412 _ => "ON",
413 };
414
415 let combining = ccc_map.get32(cp).to_icu4c_value();
416
417 let script_val = script_map.get32(cp);
418 let script =
420 script_names.get(script_val).unwrap_or("Common").to_string();
421
422 let mut alias_parts = Vec::new();
423 let mut seen_aliases = HashSet::new();
424
425 if let Some(entry) = tables.name_aliases.get(&cp) {
427 for c in &entry.corrections {
428 alias_parts.push(format!("@formalAliasCorrection(\"{c}\")"));
429 seen_aliases.insert(c.to_lowercase());
430 }
431 for c in &entry.controls {
432 alias_parts.push(format!("@formalAliasControl(\"{c}\")"));
433 seen_aliases.insert(c.to_lowercase());
434 }
435 for a in &entry.alternates {
436 alias_parts.push(format!("@formalAliasAlternate(\"{a}\")"));
437 seen_aliases.insert(a.to_lowercase());
438 }
439 for f in &entry.figments {
440 alias_parts.push(format!("@formalAliasFigment(\"{f}\")"));
441 seen_aliases.insert(f.to_lowercase());
442 }
443 for ab in &entry.abbreviations {
444 alias_parts.push(format!("@formalAliasAbbreviation(\"{ab}\")"));
445 seen_aliases.insert(ab.to_lowercase());
446 }
447 }
448 seen_aliases.insert(name.to_lowercase());
449
450 if let Some(info) = tables.char_data.get(&cp) {
451 for alias_line in &info.informative_aliases {
453 for alias in alias_line.split(", ") {
454 let s = alias.trim();
455 if !s.is_empty() && seen_aliases.insert(s.to_lowercase()) {
456 alias_parts.push(s.to_string());
457 }
458 }
459 }
460
461 let mut seen_xrefs = HashSet::new();
463 for xref_cp in &info.cross_references {
464 if seen_xrefs.insert(*xref_cp) {
465 alias_parts.push(format!("@xref(u{xref_cp:x})"));
466 }
467 }
468
469 for annot in &info.annotations {
471 let escaped = escape_directive_string(annot);
472 alias_parts.push(format!("@annotation(\"{escaped}\")"));
473 }
474 }
475
476 let aliases = alias_parts.join(", ");
477
478 let is_deprecated = is_deprecated_unicode(cp);
479
480 records.push(UnicodeCharRecord {
481 cp,
482 name,
483 combining_class: combining,
484 bidi_class: bidi,
485 general_category: gc,
486 script,
487 aliases,
488 description: String::new(),
489 is_deprecated,
490 });
491 }
492
493 records
494}
495
496fn escape_directive_string(s: &str) -> String {
498 let mut res = String::with_capacity(s.len().saturating_add(4));
499 for c in s.chars() {
500 match c {
501 '\\' => res.push_str("\\\\"),
502 '"' => res.push_str("\\\""),
503 other => res.push(other),
504 }
505 }
506 res
507}
508
509#[cfg(test)]
510#[allow(
511 clippy::panic,
512 clippy::expect_used,
513 clippy::unwrap_used,
514 clippy::unwrap_in_result,
515 clippy::panic_in_result_fn,
516 clippy::indexing_slicing,
517 clippy::arithmetic_side_effects,
518 reason = "Standard repository test boilerplate"
519)]
520mod tests {
521 use super::*;
522
523 #[crate::ctb_test]
524 fn test_format_char_detection() {
525 assert!(is_format_char('\u{00AD}')); assert!(is_format_char('\u{200E}')); assert!(is_format_char('\u{200F}')); assert!(is_format_char('\u{061C}')); assert!(is_format_char('\u{200B}')); assert!(is_format_char('\u{202A}')); assert!(is_format_char('\u{2060}')); assert!(!is_format_char('a'));
536 assert!(!is_format_char(' '));
537 assert!(!is_format_char('\n'));
538 assert!(!is_format_char('1'));
539 assert!(!is_format_char('\u{2028}')); }
541
542 #[crate::ctb_test]
543 fn test_general_category_lookup() {
544 assert_eq!(general_category('A'), GeneralCategory::UppercaseLetter);
545 assert_eq!(general_category('a'), GeneralCategory::LowercaseLetter);
546 assert_eq!(general_category('1'), GeneralCategory::DecimalNumber);
547 assert_eq!(general_category('\u{200E}'), GeneralCategory::Format);
548 assert_eq!(general_category('\n'), GeneralCategory::Control);
549 }
550
551 #[crate::ctb_test]
552 fn test_deprecated_unicode_detection() {
553 assert!(is_deprecated_unicode(0x0149)); assert!(is_deprecated_unicode(0x17A3)); assert!(is_deprecated_unicode(0x206A)); assert!(is_deprecated_unicode(0x2329)); assert!(!is_deprecated_unicode(0x0041)); assert!(!is_deprecated_unicode(0x0020)); assert!(!is_deprecated_unicode(0x2212)); assert!(!is_deprecated_unicode(0xFFFD)); }
565
566 #[crate::ctb_test]
567 fn test_get_unicode_name() {
568 assert_eq!(get_unicode_name(0x0000).as_deref(), Some("<control> NULL"));
569 assert_eq!(
570 get_unicode_name(0x000A).as_deref(),
571 Some("<control, Unicode-semantic-defined> LINE FEED")
572 );
573 assert_eq!(
574 get_unicode_name(0x000B).as_deref(),
575 Some("<control, Unicode-semantic-defined> LINE TABULATION")
576 );
577 assert_eq!(
578 get_unicode_name(0x000D).as_deref(),
579 Some("<control, Unicode-semantic-defined> CARRIAGE RETURN")
580 );
581 assert_eq!(get_unicode_name(0x002D).as_deref(), Some("HYPHEN-MINUS"));
582 assert_eq!(get_unicode_name(0x002E).as_deref(), Some("FULL STOP"));
583 assert_eq!(
584 get_unicode_name(0x0085).as_deref(),
585 Some("<control, Unicode-semantic-defined> NEXT LINE")
586 );
587 assert_eq!(
588 get_unicode_name(0x0041).as_deref(),
589 Some("LATIN CAPITAL LETTER A")
590 );
591 assert_eq!(
592 get_unicode_name(0xAC00).as_deref(),
593 Some("HANGUL SYLLABLE GA")
594 );
595 assert_eq!(
596 get_unicode_name(0x4E00).as_deref(),
597 Some("CJK UNIFIED IDEOGRAPH-4E00")
598 );
599 assert_eq!(
600 get_unicode_name(0x13460).as_deref(),
601 Some("EGYPTIAN HIEROGLYPH A001F")
602 );
603 assert_eq!(get_unicode_name(0x11_0000), None);
604
605 assert_eq!(
607 get_unicode_name_for_version(0x0041, UnicodeVersion::V15_0)
608 .as_deref(),
609 Some("LATIN CAPITAL LETTER A")
610 );
611 }
612
613 #[crate::ctb_test]
614 fn test_icu_unicode_version_matches_tables() {
615 let gc_map = icu_properties::CodePointMapData::<GeneralCategory>::new();
616 assert_ne!(gc_map.get32(0x088F), GeneralCategory::Unassigned);
617 assert_ne!(gc_map.get32(0x0C5C), GeneralCategory::Unassigned);
618 assert_ne!(gc_map.get32(0x0CDC), GeneralCategory::Unassigned);
619 }
620
621 #[crate::ctb_test]
622 fn test_normalize_nfc() {
623 assert!(is_nfc_normalized("caf\u{00E9}"));
624 assert!(!is_nfc_normalized("cafe\u{0301}"));
625 assert_eq!(normalize_nfc("cafe\u{0301}"), "caf\u{00E9}");
626 }
627}