quickjs/normalize.rs
1//! Unicode normalization: the four forms `String.prototype.normalize` offers.
2//!
3//! §22.1.3.13 defines the method only by pointing at Unicode Standard Annex #15, so this is
4//! that annex's algorithm and nothing else. It is the same computation four times with two
5//! switches — whether compatibility mappings apply, and whether the result is recomposed:
6//!
7//! | form | compatibility mappings | recomposes |
8//! |------|------------------------|------------|
9//! | NFD | no | no |
10//! | NFC | no | yes |
11//! | NFKD | yes | no |
12//! | NFKC | yes | yes |
13//!
14//! # Why the tables are separate from this
15//!
16//! [`crate::normalize_tables`] is generated from the Unicode Character Database, and it
17//! stores the *single-step* mappings `UnicodeData.txt` spells — `U+1E0B` maps to
18//! `U+0064 U+0307`, not to the fully expanded sequence. Expanding a chain is [`expand`]'s
19//! job. A precomputed closure in the table would be a derived artifact: it would agree with
20//! the UCD only as long as the generator's closure rule did, and a bug there would be
21//! invisible in the table.
22//!
23//! # Hangul is arithmetic
24//!
25//! The 11172 Hangul syllables decompose to jamo and recompose from them by formula, so they
26//! have no entries anywhere in the tables — `UnicodeData.txt` does not list them either.
27//! Both directions are handled before any table is consulted.
28//!
29//! # What is deliberately absent: the quick-check tables
30//!
31//! UAX #15 publishes `NFC_Quick_Check` and friends so an implementation can answer "is this
32//! already normalized?" without doing the work, and real engines ship them. They are a pure
33//! optimisation: skipping them changes no result. The other half of that fast path costs
34//! nothing to keep — **ASCII is in all four normal forms** — and it covers the case that
35//! shows up in real code. Carrying ~1400 more ranges for the rest would add a second
36//! mechanism whose only failure mode is being slow, when calling it "slow" means a few
37//! allocations on a string that is not ASCII. The generator asserts the ASCII property
38//! instead of this module assuming it.
39
40use crate::normalize_tables::{
41 CANONICAL_DECOMPOSITION, COMBINING_CLASS, COMPATIBILITY_DECOMPOSITION, COMPOSITION,
42 HANGUL_SBASE, HANGUL_SCOUNT,
43};
44use crate::value::Wtf8;
45
46/// One of the four Unicode Normalization Forms.
47#[derive(Clone, Copy, PartialEq, Eq, Debug)]
48pub enum Form {
49 /// Canonical decomposition followed by canonical composition.
50 Nfc,
51 /// Canonical decomposition.
52 Nfd,
53 /// Compatibility decomposition followed by canonical composition.
54 Nfkc,
55 /// Compatibility decomposition.
56 Nfkd,
57}
58
59impl Form {
60 /// The form a `normalize` argument names.
61 ///
62 /// The spellings are exact and case-sensitive: `"nfc"` is a `RangeError`, not a
63 /// synonym. `None` means the caller should throw.
64 pub fn parse(name: &str) -> Option<Form> {
65 match name {
66 "NFC" => Some(Form::Nfc),
67 "NFD" => Some(Form::Nfd),
68 "NFKC" => Some(Form::Nfkc),
69 "NFKD" => Some(Form::Nfkd),
70 _ => None,
71 }
72 }
73
74 /// Whether this form applies the `<compat>` mappings — the only difference between the
75 /// `K` forms and the others.
76 fn compatibility(self) -> bool {
77 matches!(self, Form::Nfkc | Form::Nfkd)
78 }
79
80 /// Whether this form recomposes after decomposing, which is exactly "not `D`".
81 fn composes(self) -> bool {
82 matches!(self, Form::Nfc | Form::Nfkc)
83 }
84}
85
86/// Normalize `text` into `form`.
87///
88/// A lone surrogate is not a code point and has no decomposition, so it passes through as
89/// itself — `"\uD800".normalize() === "\uD800"`. That is what the reference does, and it is
90/// why this takes and returns [`Wtf8`] rather than `&str`.
91pub fn normalize(text: &Wtf8, form: Form) -> Wtf8 {
92 // Every ASCII code point is a starter with no decomposition, and no two ASCII code points
93 // compose — all three are asserted where the tables are generated. So an ASCII string is
94 // already in all four forms, and the common call allocates nothing.
95 if text.as_bytes().is_ascii() {
96 return text.clone();
97 }
98 let mut points = text.code_point_values();
99 decompose(&mut points, form.compatibility());
100 canonical_order(&mut points);
101 if form.composes() {
102 compose(&mut points);
103 }
104 encode(&points)
105}
106
107// -- decomposition ---------------------------------------------------------
108
109/// Replace every code point with its full decomposition, in place.
110fn decompose(points: &mut Vec<u32>, compatibility: bool) {
111 let mut out = Vec::with_capacity(points.len());
112 for &point in points.iter() {
113 expand(point, compatibility, &mut out, 0);
114 }
115 *points = out;
116}
117
118/// Push the full decomposition of `point`.
119///
120/// `depth` only guards against a cycle in a generated table: the UCD's decomposition is
121/// acyclic and at most three steps deep, so a recursion that reaches the guard means the
122/// data is corrupt and the right answer is a loud failure rather than a hang.
123fn expand(point: u32, compatibility: bool, out: &mut Vec<u32>, depth: u32) {
124 debug_assert!(depth < 8, "decomposition must be acyclic");
125 if let Some((lead, vowel, tail)) = hangul_decompose(point) {
126 out.push(lead);
127 out.push(vowel);
128 if let Some(tail) = tail {
129 out.push(tail);
130 }
131 return;
132 }
133 // The two mappings are disjoint — a code point has one or the other — so trying the
134 // compatibility table first cannot shadow a canonical mapping.
135 let mapping = if compatibility {
136 lookup(COMPATIBILITY_DECOMPOSITION, point)
137 .or_else(|| lookup(CANONICAL_DECOMPOSITION, point))
138 } else {
139 lookup(CANONICAL_DECOMPOSITION, point)
140 };
141 match mapping {
142 Some(members) => {
143 for &member in members {
144 expand(member, compatibility, out, depth + 1);
145 }
146 }
147 None => out.push(point),
148 }
149}
150
151fn lookup(table: &'static [(u32, &'static [u32])], point: u32) -> Option<&'static [u32]> {
152 table
153 .binary_search_by_key(&point, |&(key, _)| key)
154 .ok()
155 .map(|index| table[index].1)
156}
157
158// -- canonical ordering ----------------------------------------------------
159
160/// Put each run of combining marks into canonical order, in place.
161///
162/// Only runs of non-starters are reordered: a starter both ends a run and keeps its
163/// position, which is why `a ◌̇ ◌̣` and `◌̇ a` sort differently.
164fn canonical_order(points: &mut [u32]) {
165 let mut start = 0;
166 while start < points.len() {
167 if combining_class(points[start]) == 0 {
168 start += 1;
169 continue;
170 }
171 let mut end = start;
172 while end < points.len() && combining_class(points[end]) != 0 {
173 end += 1;
174 }
175 sort_run(&mut points[start..end]);
176 start = end;
177 }
178}
179
180/// A stable insertion sort by combining class.
181///
182/// A run is a handful of marks in any real text, so the quadratic term is on a constant of
183/// about three; the alternative — `sort_by_key` — allocates or drags in a full sort for each
184/// run, and stability has to be argued for either way.
185fn sort_run(run: &mut [u32]) {
186 for index in 1..run.len() {
187 let point = run[index];
188 let class = combining_class(point);
189 let mut position = index;
190 // `>` rather than `>=`: equal classes keep their relative order, which is what
191 // "stable" means and what the annex requires.
192 while position > 0 && combining_class(run[position - 1]) > class {
193 run[position] = run[position - 1];
194 position -= 1;
195 }
196 run[position] = point;
197 }
198}
199
200// -- composition -----------------------------------------------------------
201
202/// Recompose the canonically ordered decomposition, in place.
203///
204/// The state is one starter position and one combining class: a mark can compose with the
205/// starter before it unless something between them blocks it, and anything that blocks is
206/// either a starter (which became the new starter) or a mark whose class is at least as
207/// large (which is the class just recorded). So the last kept class decides, and no scan
208/// back over the marks is needed.
209fn compose(points: &mut Vec<u32>) {
210 let mut out: Vec<u32> = Vec::with_capacity(points.len());
211 let mut starter: Option<usize> = None;
212 let mut last_class: u8 = 0;
213 for &point in points.iter() {
214 let class = combining_class(point);
215 if let Some(at) = starter
216 && (last_class == 0 || last_class < class)
217 && let Some(composite) = compose_pair(out[at], point)
218 {
219 out[at] = composite;
220 // The mark is gone, so the next one is adjacent to the composite again:
221 // `a ◌̣ ◌́` collapses to `ạ ◌́` and then to `ậ`, which is why the class is
222 // re-read rather than left at the mark's.
223 last_class = combining_class(composite);
224 continue;
225 }
226 if class == 0 {
227 starter = Some(out.len());
228 }
229 last_class = class;
230 out.push(point);
231 }
232 *points = out;
233}
234
235/// The composite of two code points, if they form one.
236///
237/// Hangul first: its pairs are arithmetic and appear in no table.
238fn compose_pair(first: u32, second: u32) -> Option<u32> {
239 if let Some(composite) = hangul_compose(first, second) {
240 return Some(composite);
241 }
242 // Code points are 21 bits, so the pair packs into one key and the table can be a sorted
243 // array rather than a hash — a few hundred comparisons at most, no hashing.
244 let key = u64::from(first) << 21 | u64::from(second);
245 COMPOSITION
246 .binary_search_by_key(&key, |&(candidate, _)| candidate)
247 .ok()
248 .map(|index| COMPOSITION[index].1)
249}
250
251// -- Hangul ----------------------------------------------------------------
252//
253// UAX #15 §4 gives the syllable as `SBase + (LIndex * VCount + VIndex) * TCount + TIndex`.
254// A syllable with a trailing consonant is `LVT` and one without is `LV`, which is why a
255// tail index of zero has to be `None` rather than `TBase`.
256
257const HANGUL_LBASE: u32 = 0x1100;
258const HANGUL_VBASE: u32 = 0x1161;
259const HANGUL_TBASE: u32 = 0x11a7;
260const HANGUL_LCOUNT: u32 = 19;
261const HANGUL_VCOUNT: u32 = 21;
262const HANGUL_TCOUNT: u32 = 28;
263const HANGUL_NCOUNT: u32 = HANGUL_VCOUNT * HANGUL_TCOUNT;
264
265fn hangul_decompose(point: u32) -> Option<(u32, u32, Option<u32>)> {
266 if !(HANGUL_SBASE..HANGUL_SBASE + HANGUL_SCOUNT).contains(&point) {
267 return None;
268 }
269 let index = point - HANGUL_SBASE;
270 let lead = HANGUL_LBASE + index / HANGUL_NCOUNT;
271 let vowel = HANGUL_VBASE + (index % HANGUL_NCOUNT) / HANGUL_TCOUNT;
272 let tail = index % HANGUL_TCOUNT;
273 Some((lead, vowel, (tail != 0).then(|| HANGUL_TBASE + tail)))
274}
275
276fn hangul_compose(first: u32, second: u32) -> Option<u32> {
277 // Lead + vowel: any `LV` or `LVT` syllable begins this way.
278 if (HANGUL_LBASE..HANGUL_LBASE + HANGUL_LCOUNT).contains(&first)
279 && (HANGUL_VBASE..HANGUL_VBASE + HANGUL_VCOUNT).contains(&second)
280 {
281 let lead = first - HANGUL_LBASE;
282 let vowel = second - HANGUL_VBASE;
283 return Some(HANGUL_SBASE + (lead * HANGUL_VCOUNT + vowel) * HANGUL_TCOUNT);
284 }
285 // `LV` + trailing consonant. The index is a multiple of `TCount` exactly when the
286 // syllable has no tail yet.
287 if (HANGUL_SBASE..HANGUL_SBASE + HANGUL_SCOUNT).contains(&first)
288 && (first - HANGUL_SBASE) % HANGUL_TCOUNT == 0
289 && (HANGUL_TBASE + 1..HANGUL_TBASE + HANGUL_TCOUNT).contains(&second)
290 {
291 return Some(first + (second - HANGUL_TBASE));
292 }
293 None
294}
295
296// -- tables ----------------------------------------------------------------
297
298/// A code point's canonical combining class — 0 for a starter, and 0 for the many code
299/// points the table does not mention.
300fn combining_class(point: u32) -> u8 {
301 let found = COMBINING_CLASS.binary_search_by(|&(lo, hi, _)| {
302 if hi < point {
303 std::cmp::Ordering::Less
304 } else if lo > point {
305 std::cmp::Ordering::Greater
306 } else {
307 std::cmp::Ordering::Equal
308 }
309 });
310 match found {
311 Ok(index) => COMBINING_CLASS[index].2,
312 Err(_) => 0,
313 }
314}
315
316/// Turn code points back into a `Wtf8`.
317///
318/// Above the BMP a code point becomes a surrogate pair, which [`Wtf8::from_units`] folds
319/// back into the single astral sequence the encoding requires. A lone surrogate in the input
320/// survives as itself.
321fn encode(points: &[u32]) -> Wtf8 {
322 Wtf8::from_code_points(points)
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 fn nfc(text: &str) -> String {
330 normalize(&Wtf8::new(text), Form::Nfc)
331 .to_string_lossy()
332 .into_owned()
333 }
334
335 fn nfd(text: &str) -> String {
336 normalize(&Wtf8::new(text), Form::Nfd)
337 .to_string_lossy()
338 .into_owned()
339 }
340
341 fn nfkc(text: &str) -> String {
342 normalize(&Wtf8::new(text), Form::Nfkc)
343 .to_string_lossy()
344 .into_owned()
345 }
346
347 fn nfkd(text: &str) -> String {
348 normalize(&Wtf8::new(text), Form::Nfkd)
349 .to_string_lossy()
350 .into_owned()
351 }
352
353 /// The case test262 uses, and the one every implementation gets wrong first: a
354 /// `<compat>` decomposition whose canonical form is *not* what `NFKD` produces.
355 #[test]
356 fn the_four_forms_differ_as_the_annex_says() {
357 let text = "\u{1E9B}\u{0323}";
358 assert_eq!(nfc(text), "\u{1E9B}\u{0323}");
359 assert_eq!(nfd(text), "\u{017F}\u{0323}\u{0307}");
360 assert_eq!(nfkc(text), "\u{1E69}");
361 assert_eq!(nfkd(text), "s\u{0323}\u{0307}");
362 }
363
364 #[test]
365 fn a_starter_and_a_mark_compose() {
366 assert_eq!(nfc("e\u{0301}"), "\u{00E9}");
367 assert_eq!(nfd("\u{00E9}"), "e\u{0301}");
368 }
369
370 /// Canonical ordering: 0x0323 (class 220) must sort before 0x0301 (class 230), so the
371 /// composition that happens is the one with the dot below inside.
372 #[test]
373 fn marks_are_reordered_by_combining_class() {
374 assert_eq!(nfc("a\u{0301}\u{0323}"), "\u{1EA1}\u{0301}");
375 assert_eq!(nfd("\u{1EA1}\u{0301}"), "a\u{0323}\u{0301}");
376 assert_eq!(nfd("\u{1EAD}"), "a\u{0323}\u{0302}");
377 }
378
379 /// Two marks of the *same* class keep their order — the sort is stable, so this is not
380 /// the same string as the swapped one.
381 #[test]
382 fn equal_classes_stay_in_order() {
383 assert_eq!(nfd("a\u{0301}\u{0300}"), "a\u{0301}\u{0300}");
384 }
385
386 /// Blocking: a mark of the same class stands between the starter and the next mark, so
387 /// the next one cannot compose. A mark of a *smaller* class does not block, and then the
388 /// composite is printed before the mark that came first — the mark order changed because
389 /// composing removed the mark that was between them.
390 #[test]
391 fn a_mark_of_the_same_class_blocks_the_next() {
392 assert_eq!(nfc("a\u{0301}\u{0301}"), "\u{00E1}\u{0301}");
393 assert_eq!(nfc("a\u{0334}\u{0301}"), "\u{00E1}\u{0334}");
394 // And a starter between them blocks unconditionally.
395 assert_eq!(nfc("a\u{0301}b"), "\u{00E1}b");
396 }
397
398 /// Hangul, both directions, including the `LV` + `T` step that only applies when the
399 /// syllable has no tail yet.
400 #[test]
401 fn hangul_composes_and_decomposes_arithmetically() {
402 assert_eq!(nfc("\u{1100}\u{1161}"), "\u{AC00}");
403 assert_eq!(nfc("\u{1100}\u{1161}\u{11A8}"), "\u{AC01}");
404 // An `LVT` syllable must not accept a second tail.
405 assert_eq!(nfc("\u{AC01}\u{11A8}"), "\u{AC01}\u{11A8}");
406 assert_eq!(nfd("\u{AC01}"), "\u{1100}\u{1161}\u{11A8}");
407 assert_eq!(nfd("\u{AC00}"), "\u{1100}\u{1161}");
408 }
409
410 /// A tree of round trips: decomposing then recomposing is the identity, for every form.
411 #[test]
412 fn decomposition_and_composition_agree() {
413 for text in [
414 "\u{1E9B}\u{0323}",
415 "\u{00C5}",
416 "\u{AC01}",
417 "\u{212B}", // ANGSTROM SIGN: a singleton canonical decomposition
418 "\u{FB01}", // fi, compatibility only
419 "plain text",
420 "",
421 ] {
422 assert_eq!(nfc(&nfd(text)), nfc(text));
423 assert_eq!(nfkc(&nfkd(text)), nfkc(text));
424 }
425 }
426
427 /// Normalizing twice changes nothing, in every form.
428 #[test]
429 fn normalization_is_idempotent() {
430 for text in [
431 "\u{1E9B}\u{0323}",
432 "\u{0041}\u{030A}",
433 "\u{AC01}",
434 "\u{212B}",
435 "ascii",
436 ] {
437 for form in [Form::Nfc, Form::Nfd, Form::Nfkc, Form::Nfkd] {
438 let once = normalize(&Wtf8::new(text), form);
439 let twice = normalize(&once, form);
440 assert_eq!(once, twice);
441 }
442 }
443 }
444
445 /// A lone surrogate is not a code point: it has no decomposition, is its own starter,
446 /// and survives every form.
447 #[test]
448 fn a_lone_surrogate_passes_through() {
449 let text = Wtf8::from_units(&[0xD800, b'e' as u16, 0x0301]);
450 for form in [Form::Nfc, Form::Nfd, Form::Nfkc, Form::Nfkd] {
451 let units = normalize(&text, form).to_units();
452 // The surrogate is untouched, and `e` + acute still compose where the form
453 // composes: a starter does not block what follows it.
454 assert_eq!(units[0], 0xD800);
455 let expected: &[u16] = if form.composes() {
456 &[0xD800, 0x00E9]
457 } else {
458 &[0xD800, b'e' as u16, 0x0301]
459 };
460 assert_eq!(units, expected, "{form:?}");
461 }
462 }
463
464 /// The argument spellings are exact.
465 #[test]
466 fn only_the_four_names_parse() {
467 assert_eq!(Form::parse("NFC"), Some(Form::Nfc));
468 assert_eq!(Form::parse("NFD"), Some(Form::Nfd));
469 assert_eq!(Form::parse("NFKC"), Some(Form::Nfkc));
470 assert_eq!(Form::parse("NFKD"), Some(Form::Nfkd));
471 assert_eq!(Form::parse("nfc"), None);
472 assert_eq!(Form::parse("NFCC"), None);
473 assert_eq!(Form::parse(""), None);
474 }
475}