quickjs-pure 0.12.0

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Unicode normalization: the four forms `String.prototype.normalize` offers.
//!
//! §22.1.3.13 defines the method only by pointing at Unicode Standard Annex #15, so this is
//! that annex's algorithm and nothing else. It is the same computation four times with two
//! switches — whether compatibility mappings apply, and whether the result is recomposed:
//!
//! | form | compatibility mappings | recomposes |
//! |------|------------------------|------------|
//! | NFD  | no                     | no         |
//! | NFC  | no                     | yes        |
//! | NFKD | yes                    | no         |
//! | NFKC | yes                    | yes        |
//!
//! # Why the tables are separate from this
//!
//! [`crate::normalize_tables`] is generated from the Unicode Character Database, and it
//! stores the *single-step* mappings `UnicodeData.txt` spells — `U+1E0B` maps to
//! `U+0064 U+0307`, not to the fully expanded sequence. Expanding a chain is [`expand`]'s
//! job. A precomputed closure in the table would be a derived artifact: it would agree with
//! the UCD only as long as the generator's closure rule did, and a bug there would be
//! invisible in the table.
//!
//! # Hangul is arithmetic
//!
//! The 11172 Hangul syllables decompose to jamo and recompose from them by formula, so they
//! have no entries anywhere in the tables — `UnicodeData.txt` does not list them either.
//! Both directions are handled before any table is consulted.
//!
//! # What is deliberately absent: the quick-check tables
//!
//! UAX #15 publishes `NFC_Quick_Check` and friends so an implementation can answer "is this
//! already normalized?" without doing the work, and real engines ship them. They are a pure
//! optimisation: skipping them changes no result. The other half of that fast path costs
//! nothing to keep — **ASCII is in all four normal forms** — and it covers the case that
//! shows up in real code. Carrying ~1400 more ranges for the rest would add a second
//! mechanism whose only failure mode is being slow, when calling it "slow" means a few
//! allocations on a string that is not ASCII. The generator asserts the ASCII property
//! instead of this module assuming it.

use crate::normalize_tables::{
    CANONICAL_DECOMPOSITION, COMBINING_CLASS, COMPATIBILITY_DECOMPOSITION, COMPOSITION,
    HANGUL_SBASE, HANGUL_SCOUNT,
};
use crate::value::Wtf8;

/// One of the four Unicode Normalization Forms.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Form {
    /// Canonical decomposition followed by canonical composition.
    Nfc,
    /// Canonical decomposition.
    Nfd,
    /// Compatibility decomposition followed by canonical composition.
    Nfkc,
    /// Compatibility decomposition.
    Nfkd,
}

impl Form {
    /// The form a `normalize` argument names.
    ///
    /// The spellings are exact and case-sensitive: `"nfc"` is a `RangeError`, not a
    /// synonym. `None` means the caller should throw.
    pub fn parse(name: &str) -> Option<Form> {
        match name {
            "NFC" => Some(Form::Nfc),
            "NFD" => Some(Form::Nfd),
            "NFKC" => Some(Form::Nfkc),
            "NFKD" => Some(Form::Nfkd),
            _ => None,
        }
    }

    /// Whether this form applies the `<compat>` mappings — the only difference between the
    /// `K` forms and the others.
    fn compatibility(self) -> bool {
        matches!(self, Form::Nfkc | Form::Nfkd)
    }

    /// Whether this form recomposes after decomposing, which is exactly "not `D`".
    fn composes(self) -> bool {
        matches!(self, Form::Nfc | Form::Nfkc)
    }
}

/// Normalize `text` into `form`.
///
/// A lone surrogate is not a code point and has no decomposition, so it passes through as
/// itself — `"\uD800".normalize() === "\uD800"`. That is what the reference does, and it is
/// why this takes and returns [`Wtf8`] rather than `&str`.
pub fn normalize(text: &Wtf8, form: Form) -> Wtf8 {
    // Every ASCII code point is a starter with no decomposition, and no two ASCII code points
    // compose — all three are asserted where the tables are generated. So an ASCII string is
    // already in all four forms, and the common call allocates nothing.
    if text.as_bytes().is_ascii() {
        return text.clone();
    }
    let mut points = text.code_point_values();
    decompose(&mut points, form.compatibility());
    canonical_order(&mut points);
    if form.composes() {
        compose(&mut points);
    }
    encode(&points)
}

// -- decomposition ---------------------------------------------------------

/// Replace every code point with its full decomposition, in place.
fn decompose(points: &mut Vec<u32>, compatibility: bool) {
    let mut out = Vec::with_capacity(points.len());
    for &point in points.iter() {
        expand(point, compatibility, &mut out, 0);
    }
    *points = out;
}

/// Push the full decomposition of `point`.
///
/// `depth` only guards against a cycle in a generated table: the UCD's decomposition is
/// acyclic and at most three steps deep, so a recursion that reaches the guard means the
/// data is corrupt and the right answer is a loud failure rather than a hang.
fn expand(point: u32, compatibility: bool, out: &mut Vec<u32>, depth: u32) {
    debug_assert!(depth < 8, "decomposition must be acyclic");
    if let Some((lead, vowel, tail)) = hangul_decompose(point) {
        out.push(lead);
        out.push(vowel);
        if let Some(tail) = tail {
            out.push(tail);
        }
        return;
    }
    // The two mappings are disjoint — a code point has one or the other — so trying the
    // compatibility table first cannot shadow a canonical mapping.
    let mapping = if compatibility {
        lookup(COMPATIBILITY_DECOMPOSITION, point)
            .or_else(|| lookup(CANONICAL_DECOMPOSITION, point))
    } else {
        lookup(CANONICAL_DECOMPOSITION, point)
    };
    match mapping {
        Some(members) => {
            for &member in members {
                expand(member, compatibility, out, depth + 1);
            }
        }
        None => out.push(point),
    }
}

fn lookup(table: &'static [(u32, &'static [u32])], point: u32) -> Option<&'static [u32]> {
    table
        .binary_search_by_key(&point, |&(key, _)| key)
        .ok()
        .map(|index| table[index].1)
}

// -- canonical ordering ----------------------------------------------------

/// Put each run of combining marks into canonical order, in place.
///
/// Only runs of non-starters are reordered: a starter both ends a run and keeps its
/// position, which is why `a ◌̇ ◌̣` and `◌̇ a` sort differently.
fn canonical_order(points: &mut [u32]) {
    let mut start = 0;
    while start < points.len() {
        if combining_class(points[start]) == 0 {
            start += 1;
            continue;
        }
        let mut end = start;
        while end < points.len() && combining_class(points[end]) != 0 {
            end += 1;
        }
        sort_run(&mut points[start..end]);
        start = end;
    }
}

/// A stable insertion sort by combining class.
///
/// A run is a handful of marks in any real text, so the quadratic term is on a constant of
/// about three; the alternative — `sort_by_key` — allocates or drags in a full sort for each
/// run, and stability has to be argued for either way.
fn sort_run(run: &mut [u32]) {
    for index in 1..run.len() {
        let point = run[index];
        let class = combining_class(point);
        let mut position = index;
        // `>` rather than `>=`: equal classes keep their relative order, which is what
        // "stable" means and what the annex requires.
        while position > 0 && combining_class(run[position - 1]) > class {
            run[position] = run[position - 1];
            position -= 1;
        }
        run[position] = point;
    }
}

// -- composition -----------------------------------------------------------

/// Recompose the canonically ordered decomposition, in place.
///
/// The state is one starter position and one combining class: a mark can compose with the
/// starter before it unless something between them blocks it, and anything that blocks is
/// either a starter (which became the new starter) or a mark whose class is at least as
/// large (which is the class just recorded). So the last kept class decides, and no scan
/// back over the marks is needed.
fn compose(points: &mut Vec<u32>) {
    let mut out: Vec<u32> = Vec::with_capacity(points.len());
    let mut starter: Option<usize> = None;
    let mut last_class: u8 = 0;
    for &point in points.iter() {
        let class = combining_class(point);
        if let Some(at) = starter
            && (last_class == 0 || last_class < class)
            && let Some(composite) = compose_pair(out[at], point)
        {
            out[at] = composite;
            // The mark is gone, so the next one is adjacent to the composite again:
            // `a ◌̣ ◌́` collapses to `ạ ◌́` and then to `ậ`, which is why the class is
            // re-read rather than left at the mark's.
            last_class = combining_class(composite);
            continue;
        }
        if class == 0 {
            starter = Some(out.len());
        }
        last_class = class;
        out.push(point);
    }
    *points = out;
}

/// The composite of two code points, if they form one.
///
/// Hangul first: its pairs are arithmetic and appear in no table.
fn compose_pair(first: u32, second: u32) -> Option<u32> {
    if let Some(composite) = hangul_compose(first, second) {
        return Some(composite);
    }
    // Code points are 21 bits, so the pair packs into one key and the table can be a sorted
    // array rather than a hash — a few hundred comparisons at most, no hashing.
    let key = u64::from(first) << 21 | u64::from(second);
    COMPOSITION
        .binary_search_by_key(&key, |&(candidate, _)| candidate)
        .ok()
        .map(|index| COMPOSITION[index].1)
}

// -- Hangul ----------------------------------------------------------------
//
// UAX #15 §4 gives the syllable as `SBase + (LIndex * VCount + VIndex) * TCount + TIndex`.
// A syllable with a trailing consonant is `LVT` and one without is `LV`, which is why a
// tail index of zero has to be `None` rather than `TBase`.

const HANGUL_LBASE: u32 = 0x1100;
const HANGUL_VBASE: u32 = 0x1161;
const HANGUL_TBASE: u32 = 0x11a7;
const HANGUL_LCOUNT: u32 = 19;
const HANGUL_VCOUNT: u32 = 21;
const HANGUL_TCOUNT: u32 = 28;
const HANGUL_NCOUNT: u32 = HANGUL_VCOUNT * HANGUL_TCOUNT;

fn hangul_decompose(point: u32) -> Option<(u32, u32, Option<u32>)> {
    if !(HANGUL_SBASE..HANGUL_SBASE + HANGUL_SCOUNT).contains(&point) {
        return None;
    }
    let index = point - HANGUL_SBASE;
    let lead = HANGUL_LBASE + index / HANGUL_NCOUNT;
    let vowel = HANGUL_VBASE + (index % HANGUL_NCOUNT) / HANGUL_TCOUNT;
    let tail = index % HANGUL_TCOUNT;
    Some((lead, vowel, (tail != 0).then(|| HANGUL_TBASE + tail)))
}

fn hangul_compose(first: u32, second: u32) -> Option<u32> {
    // Lead + vowel: any `LV` or `LVT` syllable begins this way.
    if (HANGUL_LBASE..HANGUL_LBASE + HANGUL_LCOUNT).contains(&first)
        && (HANGUL_VBASE..HANGUL_VBASE + HANGUL_VCOUNT).contains(&second)
    {
        let lead = first - HANGUL_LBASE;
        let vowel = second - HANGUL_VBASE;
        return Some(HANGUL_SBASE + (lead * HANGUL_VCOUNT + vowel) * HANGUL_TCOUNT);
    }
    // `LV` + trailing consonant. The index is a multiple of `TCount` exactly when the
    // syllable has no tail yet.
    if (HANGUL_SBASE..HANGUL_SBASE + HANGUL_SCOUNT).contains(&first)
        && (first - HANGUL_SBASE) % HANGUL_TCOUNT == 0
        && (HANGUL_TBASE + 1..HANGUL_TBASE + HANGUL_TCOUNT).contains(&second)
    {
        return Some(first + (second - HANGUL_TBASE));
    }
    None
}

// -- tables ----------------------------------------------------------------

/// A code point's canonical combining class — 0 for a starter, and 0 for the many code
/// points the table does not mention.
fn combining_class(point: u32) -> u8 {
    let found = COMBINING_CLASS.binary_search_by(|&(lo, hi, _)| {
        if hi < point {
            std::cmp::Ordering::Less
        } else if lo > point {
            std::cmp::Ordering::Greater
        } else {
            std::cmp::Ordering::Equal
        }
    });
    match found {
        Ok(index) => COMBINING_CLASS[index].2,
        Err(_) => 0,
    }
}

/// Turn code points back into a `Wtf8`.
///
/// Above the BMP a code point becomes a surrogate pair, which [`Wtf8::from_units`] folds
/// back into the single astral sequence the encoding requires. A lone surrogate in the input
/// survives as itself.
fn encode(points: &[u32]) -> Wtf8 {
    Wtf8::from_code_points(points)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn nfc(text: &str) -> String {
        normalize(&Wtf8::new(text), Form::Nfc)
            .to_string_lossy()
            .into_owned()
    }

    fn nfd(text: &str) -> String {
        normalize(&Wtf8::new(text), Form::Nfd)
            .to_string_lossy()
            .into_owned()
    }

    fn nfkc(text: &str) -> String {
        normalize(&Wtf8::new(text), Form::Nfkc)
            .to_string_lossy()
            .into_owned()
    }

    fn nfkd(text: &str) -> String {
        normalize(&Wtf8::new(text), Form::Nfkd)
            .to_string_lossy()
            .into_owned()
    }

    /// The case test262 uses, and the one every implementation gets wrong first: a
    /// `<compat>` decomposition whose canonical form is *not* what `NFKD` produces.
    #[test]
    fn the_four_forms_differ_as_the_annex_says() {
        let text = "\u{1E9B}\u{0323}";
        assert_eq!(nfc(text), "\u{1E9B}\u{0323}");
        assert_eq!(nfd(text), "\u{017F}\u{0323}\u{0307}");
        assert_eq!(nfkc(text), "\u{1E69}");
        assert_eq!(nfkd(text), "s\u{0323}\u{0307}");
    }

    #[test]
    fn a_starter_and_a_mark_compose() {
        assert_eq!(nfc("e\u{0301}"), "\u{00E9}");
        assert_eq!(nfd("\u{00E9}"), "e\u{0301}");
    }

    /// Canonical ordering: 0x0323 (class 220) must sort before 0x0301 (class 230), so the
    /// composition that happens is the one with the dot below inside.
    #[test]
    fn marks_are_reordered_by_combining_class() {
        assert_eq!(nfc("a\u{0301}\u{0323}"), "\u{1EA1}\u{0301}");
        assert_eq!(nfd("\u{1EA1}\u{0301}"), "a\u{0323}\u{0301}");
        assert_eq!(nfd("\u{1EAD}"), "a\u{0323}\u{0302}");
    }

    /// Two marks of the *same* class keep their order — the sort is stable, so this is not
    /// the same string as the swapped one.
    #[test]
    fn equal_classes_stay_in_order() {
        assert_eq!(nfd("a\u{0301}\u{0300}"), "a\u{0301}\u{0300}");
    }

    /// Blocking: a mark of the same class stands between the starter and the next mark, so
    /// the next one cannot compose. A mark of a *smaller* class does not block, and then the
    /// composite is printed before the mark that came first — the mark order changed because
    /// composing removed the mark that was between them.
    #[test]
    fn a_mark_of_the_same_class_blocks_the_next() {
        assert_eq!(nfc("a\u{0301}\u{0301}"), "\u{00E1}\u{0301}");
        assert_eq!(nfc("a\u{0334}\u{0301}"), "\u{00E1}\u{0334}");
        // And a starter between them blocks unconditionally.
        assert_eq!(nfc("a\u{0301}b"), "\u{00E1}b");
    }

    /// Hangul, both directions, including the `LV` + `T` step that only applies when the
    /// syllable has no tail yet.
    #[test]
    fn hangul_composes_and_decomposes_arithmetically() {
        assert_eq!(nfc("\u{1100}\u{1161}"), "\u{AC00}");
        assert_eq!(nfc("\u{1100}\u{1161}\u{11A8}"), "\u{AC01}");
        // An `LVT` syllable must not accept a second tail.
        assert_eq!(nfc("\u{AC01}\u{11A8}"), "\u{AC01}\u{11A8}");
        assert_eq!(nfd("\u{AC01}"), "\u{1100}\u{1161}\u{11A8}");
        assert_eq!(nfd("\u{AC00}"), "\u{1100}\u{1161}");
    }

    /// A tree of round trips: decomposing then recomposing is the identity, for every form.
    #[test]
    fn decomposition_and_composition_agree() {
        for text in [
            "\u{1E9B}\u{0323}",
            "\u{00C5}",
            "\u{AC01}",
            "\u{212B}", // ANGSTROM SIGN: a singleton canonical decomposition
            "\u{FB01}", // fi, compatibility only
            "plain text",
            "",
        ] {
            assert_eq!(nfc(&nfd(text)), nfc(text));
            assert_eq!(nfkc(&nfkd(text)), nfkc(text));
        }
    }

    /// Normalizing twice changes nothing, in every form.
    #[test]
    fn normalization_is_idempotent() {
        for text in [
            "\u{1E9B}\u{0323}",
            "\u{0041}\u{030A}",
            "\u{AC01}",
            "\u{212B}",
            "ascii",
        ] {
            for form in [Form::Nfc, Form::Nfd, Form::Nfkc, Form::Nfkd] {
                let once = normalize(&Wtf8::new(text), form);
                let twice = normalize(&once, form);
                assert_eq!(once, twice);
            }
        }
    }

    /// A lone surrogate is not a code point: it has no decomposition, is its own starter,
    /// and survives every form.
    #[test]
    fn a_lone_surrogate_passes_through() {
        let text = Wtf8::from_units(&[0xD800, b'e' as u16, 0x0301]);
        for form in [Form::Nfc, Form::Nfd, Form::Nfkc, Form::Nfkd] {
            let units = normalize(&text, form).to_units();
            // The surrogate is untouched, and `e` + acute still compose where the form
            // composes: a starter does not block what follows it.
            assert_eq!(units[0], 0xD800);
            let expected: &[u16] = if form.composes() {
                &[0xD800, 0x00E9]
            } else {
                &[0xD800, b'e' as u16, 0x0301]
            };
            assert_eq!(units, expected, "{form:?}");
        }
    }

    /// The argument spellings are exact.
    #[test]
    fn only_the_four_names_parse() {
        assert_eq!(Form::parse("NFC"), Some(Form::Nfc));
        assert_eq!(Form::parse("NFD"), Some(Form::Nfd));
        assert_eq!(Form::parse("NFKC"), Some(Form::Nfkc));
        assert_eq!(Form::parse("NFKD"), Some(Form::Nfkd));
        assert_eq!(Form::parse("nfc"), None);
        assert_eq!(Form::parse("NFCC"), None);
        assert_eq!(Form::parse(""), None);
    }
}