Skip to main content

zu_common/
unicode.rs

1//! Unicode normalization: the four normal forms of ISO 20.24 and 19.7.
2//!
3//! GQL's `NORMALIZE` and `IS NORMALIZED` both defer to Unicode Standard
4//! Annex 15, which is one algorithm read four ways. Decompose the string,
5//! sort the combining marks into canonical order, and for the two
6//! composed forms put it back together again; whether the decomposition
7//! is canonical or compatibility is the only difference between NFC and
8//! NFKC, and between NFD and NFKD.
9//!
10//! The tables are the Unicode Character Database's, machine-written into
11//! `generated.rs` from the artifacts checked in beside it, the same way
12//! the GQLSTATUS table is written from the conditions artifact. They are
13//! fully expanded, so a decomposition is one lookup rather than a
14//! recursion: the standard guarantees the expansion terminates, and
15//! doing it once at generation time means the runtime never asks.
16//!
17//! Hangul is not in the tables at all. Eleven thousand syllables
18//! decompose and compose by arithmetic, which UAX 15 spells out, and a
19//! table of them would be four fifths of the data for none of the
20//! meaning.
21//!
22//! A dependency would have been the other way to get this. The reason it
23//! is here instead is the reason `docs/10` gives for owning the line
24//! editor: what arrives with a normalization crate is not one algorithm
25//! but a set of opinions about Unicode versions, feature flags and table
26//! layouts, and the algorithm itself is two hundred lines against a
27//! database whose correctness on this point is checked by the Unicode
28//! Consortium's own conformance file.
29
30mod generated;
31
32use generated::{CANONICAL, CCC, COMPATIBILITY, COMPOSITION, DECOMPOSED};
33
34pub use generated::UNICODE_VERSION;
35
36/// The four normal forms. `K` is for compatibility, which the standard
37/// spells with a K because C was taken.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub enum NormalForm {
40    Nfc,
41    Nfd,
42    Nfkc,
43    Nfkd,
44}
45
46impl NormalForm {
47    /// The spelling GQL uses, which is also the spelling UAX 15 uses.
48    pub fn name(self) -> &'static str {
49        match self {
50            NormalForm::Nfc => "NFC",
51            NormalForm::Nfd => "NFD",
52            NormalForm::Nfkc => "NFKC",
53            NormalForm::Nfkd => "NFKD",
54        }
55    }
56
57    /// The form a word names, or `None` for a word that names none. The
58    /// comparison is case-insensitive because the parser hands over what
59    /// the statement wrote and GQL keywords are not case-sensitive.
60    pub fn from_name(word: &str) -> Option<NormalForm> {
61        match word.to_ascii_uppercase().as_str() {
62            "NFC" => Some(NormalForm::Nfc),
63            "NFD" => Some(NormalForm::Nfd),
64            "NFKC" => Some(NormalForm::Nfkc),
65            "NFKD" => Some(NormalForm::Nfkd),
66            _ => None,
67        }
68    }
69
70    /// Whether the form composes after decomposing.
71    fn composes(self) -> bool {
72        matches!(self, NormalForm::Nfc | NormalForm::Nfkc)
73    }
74
75    /// Whether the form decomposes by compatibility rather than only
76    /// canonically.
77    fn compatibility(self) -> bool {
78        matches!(self, NormalForm::Nfkc | NormalForm::Nfkd)
79    }
80}
81
82/// The first Hangul syllable, the first leading jamo, the first vowel
83/// jamo, and the trailing jamo base, which sits one below the first
84/// trailing jamo so that a zero index means no trailing jamo at all.
85const S_BASE: u32 = 0xAC00;
86const L_BASE: u32 = 0x1100;
87const V_BASE: u32 = 0x1161;
88const T_BASE: u32 = 0x11A7;
89const L_COUNT: u32 = 19;
90const V_COUNT: u32 = 21;
91const T_COUNT: u32 = 28;
92const N_COUNT: u32 = V_COUNT * T_COUNT;
93const S_COUNT: u32 = L_COUNT * N_COUNT;
94
95/// The canonical combining class of a character, zero for a starter.
96fn ccc(c: char) -> u8 {
97    match CCC.binary_search_by_key(&c, |&(k, _)| k) {
98        Ok(i) => CCC[i].1,
99        Err(_) => 0,
100    }
101}
102
103/// The fully expanded decomposition of a character, or `None` for a
104/// character that is its own decomposition.
105fn decomposition(c: char, compatibility: bool) -> Option<&'static [char]> {
106    let table = if compatibility {
107        COMPATIBILITY
108    } else {
109        CANONICAL
110    };
111    let i = table.binary_search_by_key(&c, |&(k, _, _)| k).ok()?;
112    let (_, at, len) = table[i];
113    Some(&DECOMPOSED[at as usize..at as usize + len as usize])
114}
115
116/// The primary composite of a starter and a following character, or
117/// `None` when the pair does not compose. Hangul is arithmetic; the rest
118/// is the table, which already has the composition exclusions taken out
119/// of it, so a pair that is in it composes.
120fn compose_pair(first: char, second: char) -> Option<char> {
121    let (a, b) = (first as u32, second as u32);
122    if (L_BASE..L_BASE + L_COUNT).contains(&a) && (V_BASE..V_BASE + V_COUNT).contains(&b) {
123        let syllable = S_BASE + ((a - L_BASE) * V_COUNT + (b - V_BASE)) * T_COUNT;
124        return char::from_u32(syllable);
125    }
126    if (S_BASE..S_BASE + S_COUNT).contains(&a)
127        && (a - S_BASE).is_multiple_of(T_COUNT)
128        && (T_BASE + 1..T_BASE + T_COUNT).contains(&b)
129    {
130        return char::from_u32(a + (b - T_BASE));
131    }
132    COMPOSITION
133        .binary_search_by_key(&(first, second), |&(x, y, _)| (x, y))
134        .ok()
135        .map(|i| COMPOSITION[i].2)
136}
137
138/// Writes the decomposition of one character, Hangul by arithmetic and
139/// everything else by table.
140fn decompose_char(out: &mut Vec<char>, c: char, compatibility: bool) {
141    let u = c as u32;
142    if (S_BASE..S_BASE + S_COUNT).contains(&u) {
143        let index = u - S_BASE;
144        let (l, v, t) = (
145            L_BASE + index / N_COUNT,
146            V_BASE + (index % N_COUNT) / T_COUNT,
147            index % T_COUNT,
148        );
149        out.extend(char::from_u32(l));
150        out.extend(char::from_u32(v));
151        if t != 0 {
152            out.extend(char::from_u32(T_BASE + t));
153        }
154        return;
155    }
156    match decomposition(c, compatibility) {
157        Some(chars) => out.extend_from_slice(chars),
158        None => out.push(c),
159    }
160}
161
162/// Sorts each run of combining marks by combining class, stably, which
163/// is what makes two strings that differ only in the order they wrote
164/// their marks in normalize to the same string. A starter ends a run,
165/// and marks of equal class keep their order, so the sort has to be an
166/// insertion sort and cannot be a general one.
167fn canonical_order(chars: &mut [char]) {
168    for i in 1..chars.len() {
169        let class = ccc(chars[i]);
170        if class == 0 {
171            continue;
172        }
173        let mut j = i;
174        while j > 0 && ccc(chars[j - 1]) > class {
175            chars.swap(j - 1, j);
176            j -= 1;
177        }
178    }
179}
180
181/// The canonical composition algorithm of UAX 15. Each character is
182/// tried against the last starter, and a character is blocked from that
183/// starter when something already stands between them whose combining
184/// class is not lower than its own. A character that composes is folded
185/// into the starter and does not stand between anything.
186fn compose(chars: Vec<char>) -> Vec<char> {
187    let mut out: Vec<char> = Vec::with_capacity(chars.len());
188    let mut starter: Option<usize> = None;
189    let mut previous = 0u8;
190    let mut anything_since_starter = false;
191    for c in chars {
192        let class = ccc(c);
193        if let Some(at) = starter
194            && !(anything_since_starter && previous >= class)
195            && let Some(composed) = compose_pair(out[at], c)
196        {
197            out[at] = composed;
198            continue;
199        }
200        if class == 0 {
201            starter = Some(out.len());
202            anything_since_starter = false;
203        } else {
204            anything_since_starter = true;
205        }
206        previous = class;
207        out.push(c);
208    }
209    out
210}
211
212/// The string in the normal form asked for.
213///
214/// A string of ASCII is in every normal form already, and that is the
215/// common case in a database, so it is the case that costs a scan and no
216/// allocation beyond the answer.
217pub fn normalize(s: &str, form: NormalForm) -> String {
218    if s.is_ascii() {
219        return s.to_string();
220    }
221    let mut chars = Vec::with_capacity(s.len());
222    for c in s.chars() {
223        decompose_char(&mut chars, c, form.compatibility());
224    }
225    canonical_order(&mut chars);
226    if form.composes() {
227        chars = compose(chars);
228    }
229    chars.into_iter().collect()
230}
231
232/// Whether the string is already in the normal form asked for.
233///
234/// The standard defines the predicate as the string being equal to its
235/// own normalization, and that is how it is answered here rather than
236/// through the quick-check properties. A quick check is a fourth table
237/// and a second algorithm to be wrong in, and it answers `maybe` often
238/// enough that the normalization runs anyway.
239pub fn is_normalized(s: &str, form: NormalForm) -> bool {
240    if s.is_ascii() {
241        return true;
242    }
243    normalize(s, form) == s
244}
245
246/// Whether a character may begin a regular identifier (ISO 21.3).
247///
248/// The standard writes the set as Unicode general category classes and
249/// the underscore, and that is what the table holds, so this is a
250/// lookup and not a judgement. ASCII is answered without touching the
251/// table, because nearly every identifier anybody writes is ASCII and
252/// the table is there for the ones that are not.
253pub fn is_ident_start(c: char) -> bool {
254    if c.is_ascii() {
255        return c.is_ascii_alphabetic() || c == '_';
256    }
257    in_ranges(generated::IDENT_START, c)
258}
259
260/// Whether a character may continue a regular identifier (ISO 21.3):
261/// every start, and the marks, digits, connectors and format
262/// characters that go with them.
263pub fn is_ident_extend(c: char) -> bool {
264    if c.is_ascii() {
265        return c.is_ascii_alphanumeric() || c == '_';
266    }
267    in_ranges(generated::IDENT_EXTEND, c)
268}
269
270/// Whether a character falls in one of a sorted list of inclusive
271/// ranges. The ranges do not touch or overlap, the generator having
272/// merged the ones that did, so the search is over the starts alone.
273fn in_ranges(ranges: &[(char, char)], c: char) -> bool {
274    match ranges.binary_search_by(|(from, _)| from.cmp(&c)) {
275        Ok(_) => true,
276        Err(0) => false,
277        Err(at) => ranges[at - 1].1 >= c,
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    #[test]
286    fn ascii_is_already_in_every_form() {
287        for form in [
288            NormalForm::Nfc,
289            NormalForm::Nfd,
290            NormalForm::Nfkc,
291            NormalForm::Nfkd,
292        ] {
293            assert_eq!(normalize("ab", form), "ab");
294            assert!(is_normalized("ab", form));
295        }
296    }
297
298    #[test]
299    fn a_letter_and_its_accent_are_one_character_composed_and_two_decomposed() {
300        assert_eq!(normalize("e\u{301}", NormalForm::Nfc), "\u{e9}");
301        assert_eq!(normalize("\u{e9}", NormalForm::Nfd), "e\u{301}");
302        assert!(is_normalized("\u{e9}", NormalForm::Nfc));
303        assert!(!is_normalized("\u{e9}", NormalForm::Nfd));
304    }
305
306    #[test]
307    fn compatibility_is_the_only_form_that_loses_the_formatting() {
308        // U+FB01 is the fi ligature and U+00BD is one half. Neither has
309        // a canonical decomposition, because a ligature is not the same
310        // character as the letters it draws.
311        assert_eq!(normalize("\u{fb01}", NormalForm::Nfc), "\u{fb01}");
312        assert_eq!(normalize("\u{fb01}", NormalForm::Nfkc), "fi");
313        assert_eq!(normalize("\u{bd}", NormalForm::Nfkd), "1\u{2044}2");
314    }
315
316    #[test]
317    fn marks_sort_by_combining_class_and_keep_their_order_inside_a_class() {
318        // U+0328 is ogonek, class 202, and U+0301 is acute, class 230.
319        // Written the other way round they normalize to the same string.
320        assert_eq!(
321            normalize("a\u{301}\u{328}", NormalForm::Nfd),
322            "a\u{328}\u{301}"
323        );
324        assert_eq!(
325            normalize("a\u{301}\u{328}", NormalForm::Nfc),
326            normalize("a\u{328}\u{301}", NormalForm::Nfc)
327        );
328    }
329
330    #[test]
331    fn a_hangul_syllable_is_arithmetic_in_both_directions() {
332        assert_eq!(normalize("\u{ac00}", NormalForm::Nfd), "\u{1100}\u{1161}");
333        assert_eq!(normalize("\u{1100}\u{1161}", NormalForm::Nfc), "\u{ac00}");
334        assert_eq!(
335            normalize("\u{d4db}", NormalForm::Nfd),
336            "\u{1111}\u{1171}\u{11b6}"
337        );
338        assert_eq!(
339            normalize("\u{1111}\u{1171}\u{11b6}", NormalForm::Nfc),
340            "\u{d4db}"
341        );
342    }
343
344    #[test]
345    fn an_excluded_composition_stays_apart() {
346        // U+0958 is in the composition exclusion list, so NFC leaves the
347        // decomposed pair alone rather than putting it back together.
348        assert_eq!(normalize("\u{958}", NormalForm::Nfc), "\u{915}\u{93c}");
349        assert_eq!(
350            normalize("\u{915}\u{93c}", NormalForm::Nfc),
351            "\u{915}\u{93c}"
352        );
353    }
354
355    #[test]
356    fn a_blocked_mark_does_not_reach_the_starter() {
357        // U+0344 decomposes to two marks of the same class, and the
358        // second cannot compose with the a because the first blocks it.
359        assert_eq!(
360            normalize("a\u{308}\u{301}", NormalForm::Nfc),
361            "\u{e4}\u{301}"
362        );
363        assert_eq!(
364            normalize("a\u{328}\u{301}", NormalForm::Nfc),
365            "\u{105}\u{301}"
366        );
367    }
368
369    #[test]
370    fn every_form_has_a_name_and_answers_to_it() {
371        for form in [
372            NormalForm::Nfc,
373            NormalForm::Nfd,
374            NormalForm::Nfkc,
375            NormalForm::Nfkd,
376        ] {
377            assert_eq!(NormalForm::from_name(form.name()), Some(form));
378            assert_eq!(
379                NormalForm::from_name(&form.name().to_ascii_lowercase()),
380                Some(form)
381            );
382        }
383        assert_eq!(NormalForm::from_name("NFX"), None);
384    }
385}