//! `cargo xtask unicode `: the character data `pinnacle-text` needs, //! made from the Unicode Character Database's files in `` //! (`extracted/DerivedBidiClass.txt`, `extracted/DerivedGeneralCategory.txt`, //! `ArabicShaping.txt`, `BidiMirroring.txt`, `BidiBrackets.txt`, //! `Scripts.txt`, `emoji/emoji-data.txt`, from //! ), written as //! `text/src/tables.rs`. The tables are data, as the TLS roots are: made //! again when Unicode publishes a new version, and committed. use std::path::Path; type Result = std::result::Result; /// The bidi classes in `pinnacle_text::bidi::Class`'s order. const BIDI: [&str; 23] = [ "L", "R", "AL", "EN", "ES", "ET", "AN", "CS", "NSM", "BN", "B", "S", "WS", "ON", "LRE", "LRO", "RLE", "RLO", "PDF", "LRI", "RLI", "FSI", "PDI", ]; /// The joining types in `pinnacle_text::arabic::Joining`'s order (U first: /// what is not listed). const JOINING: [&str; 6] = ["U", "R", "L", "D", "C", "T"]; /// The scripts in `pinnacle_text::Script`'s order; any other is `Other`. const SCRIPTS: [&str; 14] = [ "Common", "Inherited", "Latin", "Greek", "Cyrillic", "Arabic", "Hebrew", "Syriac", "Thaana", "Nko", "Han", "Hiragana", "Katakana", "Hangul", ]; /// The lines of a UCD file that hold data: comments and blanks gone, /// each as its `;`-separated fields, trimmed. fn records(dir: &Path, file: &str) -> Result>> { let path = dir.join(file); let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?; Ok(text .lines() .map(|l| l.split('#').next().unwrap_or("").trim()) .filter(|l| !l.is_empty()) .map(|l| l.split(';').map(|f| f.trim().to_string()).collect()) .collect()) } /// A code point or a range `XXXX..YYYY`. fn range(field: &str) -> Result<(u32, u32)> { let hex = |s: &str| u32::from_str_radix(s, 16).map_err(|e| format!("{s}: {e}")); Ok(match field.split_once("..") { Some((a, b)) => (hex(a)?, hex(b)?), None => (hex(field)?, hex(field)?), }) } /// `values` (one per code point) as the ranges where it is not `skip`, /// neighbours with the same value merged. fn ranges(values: &[u8], skip: u8) -> Vec<(u32, u32, u8)> { let mut out: Vec<(u32, u32, u8)> = Vec::new(); for (c, &v) in values.iter().enumerate() { if v == skip { continue; } let c = c as u32; match out.last_mut() { Some(last) if last.1 + 1 == c && last.2 == v => last.1 = c, _ => out.push((c, c, v)), } } out } fn table(out: &mut String, name: &str, doc: &str, rows: &[(u32, u32, u8)]) { out.push_str(&format!( "/// {doc}\n#[rustfmt::skip]\npub static {name}: [(u32, u32, u8); {}] = [\n", rows.len() )); for chunk in rows.chunks(4) { out.push_str(" "); for (a, b, v) in chunk { out.push_str(&format!(" (0x{a:x}, 0x{b:x}, {v}),")); } out.push('\n'); } out.push_str("];\n\n"); } pub fn run(dir: &Path, out_path: &Path) -> Result { const ALL: usize = 0x11_0000; // Bidi classes: the file's defaults for unlisted ranges first // (`@missing` lines), then what it lists. let mut bidi = vec![0u8; ALL]; let path = dir.join("extracted/DerivedBidiClass.txt"); let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?; let long = |name: &str| -> Option { let short = match name { "Left_To_Right" => "L", "Right_To_Left" => "R", "Arabic_Letter" => "AL", "European_Number" => "EN", "Arabic_Number" => "AN", "European_Terminator" => "ET", "Boundary_Neutral" => "BN", other => other, }; BIDI.iter().position(|&c| c == short).map(|i| i as u8) }; for line in text.lines() { if let Some(missing) = line.strip_prefix("# @missing: ") { let mut f = missing.split(';').map(str::trim); let (Some(r), Some(class)) = (f.next(), f.next()) else { continue; }; let (a, b) = range(r)?; let class = long(class).ok_or_else(|| format!("bidi class {class}"))?; bidi[a as usize..=b as usize].fill(class); } } for f in records(dir, "extracted/DerivedBidiClass.txt")? { let (a, b) = range(&f[0])?; let class = long(&f[1]).ok_or_else(|| format!("bidi class {}", f[1]))?; bidi[a as usize..=b as usize].fill(class); } // Joining types: listed, or T for the marks and format characters // (Mn, Me, Cf) not listed, U for the rest. let mut joining = vec![0u8; ALL]; for f in records(dir, "extracted/DerivedGeneralCategory.txt")? { if matches!(f[1].as_str(), "Mn" | "Me" | "Cf") { let (a, b) = range(&f[0])?; joining[a as usize..=b as usize].fill(5); } } for f in records(dir, "ArabicShaping.txt")? { let (a, b) = range(&f[0])?; let t = JOINING .iter() .position(|&j| j == f[2]) .ok_or_else(|| format!("joining {}", f[2]))?; joining[a as usize..=b as usize].fill(t as u8); } let mut script = vec![255u8; ALL]; for f in records(dir, "Scripts.txt")? { let (a, b) = range(&f[0])?; let s = SCRIPTS.iter().position(|&s| s == f[1]).map_or(254, |i| i as u8); script[a as usize..=b as usize].fill(s); } let mut emoji = vec![0u8; ALL]; for f in records(dir, "emoji/emoji-data.txt")? { let bit = match f[1].as_str() { "Emoji_Presentation" => 1, "Extended_Pictographic" => 2, _ => continue, }; let (a, b) = range(&f[0])?; for v in &mut emoji[a as usize..=b as usize] { *v |= bit; } } let mut mirror = Vec::new(); for f in records(dir, "BidiMirroring.txt")? { mirror.push((range(&f[0])?.0, range(&f[1])?.0)); } let mut brackets = Vec::new(); for f in records(dir, "BidiBrackets.txt")? { brackets.push((range(&f[0])?.0, range(&f[1])?.0, u8::from(f[2] == "o"))); } let mut out = String::from( "//! Made by `cargo xtask unicode` from the Unicode Character Database;\n\ //! not edited by hand.\n\n", ); table( &mut out, "BIDI", "Bidi classes (`bidi::Class` as `u8`) of the characters that are not L.", &ranges(&bidi, 0), ); table( &mut out, "JOINING", "Joining types (`arabic::Joining` as `u8`) of the characters that are not U.", &ranges(&joining, 0), ); table( &mut out, "SCRIPT", "Scripts (`Script` as `u8`; 254: another script).", &ranges(&script, 255), ); table( &mut out, "EMOJI", "Emoji properties: 1 Emoji_Presentation, 2 Extended_Pictographic.", &ranges(&emoji, 0), ); out.push_str(&format!( "/// Each character with a mirrored glyph, and its mirror.\n#[rustfmt::skip]\npub static MIRROR: [(u32, u32); {}] = [\n", mirror.len() )); for chunk in mirror.chunks(6) { out.push_str(" "); for (a, b) in chunk { out.push_str(&format!(" (0x{a:x}, 0x{b:x}),")); } out.push('\n'); } out.push_str("];\n\n"); out.push_str(&format!( "/// Paired brackets: the bracket, its pair, 1 if it opens.\n#[rustfmt::skip]\npub static BRACKETS: [(u32, u32, u8); {}] = [\n", brackets.len() )); for chunk in brackets.chunks(4) { out.push_str(" "); for (a, b, o) in chunk { out.push_str(&format!(" (0x{a:x}, 0x{b:x}, {o}),")); } out.push('\n'); } out.push_str("];\n"); std::fs::write(out_path, out).map_err(|e| format!("{}: {e}", out_path.display()))?; println!("unicode: {}", out_path.display()); Ok(()) }