Algorithm Search⌘K

Algorithmcore

Unicode normalization algorithm

Also called UAX 15 normalization.

Normalize a string by full decomposition, a stable sort by combining class inside each run of combining marks, and, for NFC and NFKC, a left-to-right canonical composition.

Time
Θ(n^2) worstΘ(n) best
Space
O(n) extra
Where
n = the number of code points of the input
Properties
deterministicofflinerecursive

The Unicode normalization algorithm computes the four normalization forms of a string in three passes. It first replaces every code point by its full decomposition, then sorts each run of combining marks by canonical combining class with a stable sort that never moves a starter, and, for NFC and NFKC, it then composes pairs of a starter and a later mark back into precomposed characters from left to right. The data are a decomposition mapping and a combining class for each code point, a list of composition exclusions, and the arithmetic of Hangul syllables. Section 3.11 of the core specification defines the steps, and Unicode Standard Annex 15 explains them.

In plain words

A letter with accents can be stored in several ways: as one ready-made letter, or as a plain letter followed by accent marks, and the marks can come in different orders. Normalization picks one of these ways, so that the same text is always stored the same way.

First, take every ready-made letter apart, all the way down to the plain letter and its marks. Second, put the marks after each letter in a fixed order. Marks that sit in different places, such as one below the letter and one above, are put in order by a number that each mark has. Marks in the same place keep their order, because there the order changes what the reader sees.

For the composed form, go through the result once more and join each letter with its marks into a ready-made letter wherever such a letter exists.

The problem

The input is a string XX of nn code points and a form: NFD, NFC, NFKD or NFKC. The output is the string of that form that is equivalent to XX, as D118 to D121 define it.

The data come from the Unicode Character Database:

  • ccc(c)\mathrm{ccc}(c), the canonical combining class, a number in 0..254. A starter has class 0.
  • The decomposition mapping of cc. It is canonical unless it starts with a tag such as <compat>, and the forms NFKD and NFKC also use the tagged mappings.
  • The full composition exclusions (D113): the 67 script-specific and 14 post composition version exclusions that CompositionExclusions.txt lists, plus the 1,035 singletons and the 4 non-starter decompositions, which can be derived from the mappings. A primary composite (D114) is a character with a canonical mapping that is not in this set.
  • PAIR(a,b)(a, b): the primary composite whose canonical mapping is a ba\,b, or none. For Hangul it is computed. The implementation builds a hash table with the 1,360 other pairs.

The algorithm

  1. NORMALIZE(form, X)
  2. 1d <- empty list
  3. 2for each code point c of X do append FULL-DECOMPOSE(c, form is NFKD or NFKC) to d
  4. 3CANONICAL-ORDER(d)
  5. 4if form is NFC or NFKC then d <- COMPOSE(d)
  6. 5return d
  7. FULL-DECOMPOSE(c, compat)
  8. 6if c is a Hangul syllable then return its jamo, by the arithmetic of section 3.12.2
  9. 7m <- the canonical decomposition mapping of c, or its compatibility mapping if compat and it has one
  10. 8if c has no such mapping then return [c]
  11. 9return the concatenation of FULL-DECOMPOSE(x, compat) for each x of m
  12. CANONICAL-ORDER(d)
  13. 10for i <- 1 to |d| - 1 do
  14. 11j <- i
  15. 12while j > 0 and ccc(d[j - 1]) > ccc(d[j]) > 0 do
  16. 13swap d[j - 1] and d[j]; j <- j - 1
  17. COMPOSE(d)
  18. 14out <- empty list; starter <- -1; last <- -1
  19. 15for each c of d, in order do
  20. 16k <- ccc(c)
  21. 17if starter >= 0 and (last = -1 or 0 < last < k) and PAIR(out[starter], c) exists then
  22. 18out[starter] <- PAIR(out[starter], c); continue with the next c
  23. 19if k = 0 then starter <- |out|; last <- -1
  24. 20else last <- k
  25. 21append c to out
  26. 22return out

Decomposition (lines L6 to L9). The mappings in the data are one level deep. U+1E69 maps to U+1E63 U+0307, and U+1E63 maps again to U+0073 U+0323, so line L9 must recurse. The recursion always stops, because the mappings have no cycle.

Canonical ordering (lines L10 to L13). The swap condition of line L12 is the reorderable pair of D108. Because both characters must have a class above 0, a starter never moves and a mark never crosses a starter, and because the condition is a strict >>, marks of the same class keep their order. So this is an insertion sort inside each run of non-starters, and it is stable.

Composition (lines L14 to L22). starterstarter is the index of the last starter in outout, and lastlast is the class of the last mark after it, or −1-1 if there is none. By D115, a character CC is blocked from the starter when some character between them is a starter or has a class at least ccc(C)\mathrm{ccc}(C). After canonical ordering, the classes of the marks after the starter do not decrease, so the largest of them is lastlast, and the test of line L17 is exactly "not blocked". A starter CC can compose only when it comes right after the last starter, with last=−1last = -1. That case covers the Hangul pairs L+VL + V and LV+TLV + T, and vowel signs of Indic scripts, such as U+0B47 U+0B3E, which compose to U+0B4B ORIYA VOWEL SIGN O. The composite always has class 0, so line L18 keeps the invariant.

Example

NFC of U+1E61 U+0323, the letter ṡ followed by a dot below.

step sequence reason
L2 0073 0307 0323 U+1E61 maps to s and U+0307 DOT ABOVE
L3 0073 0323 0307 ccc(0307) = 230 > ccc(0323) = 220 > 0, so line L13 swaps them
L17, L18 1E63 0307 PAIR(0073, 0323) is U+1E63 ṣ, and nothing lies between
L17, L18 1E69 PAIR(1E63, 0307) is U+1E69 ṩ, and last=−1last = -1

The NFD is 0073 0323 0307, the line L3 row. The input U+1E63 U+0307 and the input s U+0307 U+0323 give the same results, because all three strings are canonically equivalent.

Two cases where composition stops:

  • a U+0301 U+0301: the first acute composes to U+00E1. PAIR(00E1, 0301) does not exist, so the second acute is appended, and the NFC is 00E1 0301.
  • a U+0305 U+0301: there is no a with overline, so U+0305 is appended with last=230last = 230. The acute also has class 230, so it is blocked, and the NFC is 0061 0305 0301, although U+00E1 exists.

A singleton is never composed back. U+212B ANGSTROM SIGN decomposes to U+00C5 and then to 0041 030A, and NFC gives U+00C5, not U+212B.

Correctness

The proof in proofs/correctness.md shows that the three parts compute D68 (or D65), D109 and D117. Line L9 applies the mappings until none is left, which is the full decomposition. CANONICAL-ORDER removes all reorderable pairs and only swaps such pairs, and since each swap keeps the starters and the order of equal classes, the result is the unique sequence with each run sorted stably, which is what D109 produces. COMPOSE keeps the invariant on starterstarter and lastlast described above, so its test is the blocking condition of D115, and PAIR finds exactly the primary composites. The proof relies on three facts about the data that the definitions do not imply: the mappings have no cycle, every primary composite is a starter, and the composite of a pair is found by its two-part mapping. The tests compare the whole procedure with unicodedata.normalize on every decomposable character of Unicode 3.2 in the Basic Multilingual Plane and on random strings, so an error in one of these facts would show up there.

Proof: The normalization procedure computes NFD, NFC, NFKD and NFKC as defined in the core specificationfull

Claim. For every string XX of code points, NORMALIZE (lines L1 to L5) stops, and it returns toNFD(X)(X), toNFKD(X)(X), toNFC(X)(X) or toNFKC(X)(X) for the four forms. These are defined in section 3.11 of the core specification: NFD is the full canonical decomposition of each character (D68) followed by the Canonical Ordering Algorithm (D109), NFKD is the same with the full compatibility decomposition (D65), and NFC and NFKC apply the Canonical Composition Algorithm (D117) to the result of NFD and NFKD.

Data facts. The proof uses three properties of the Unicode Character Database. They are facts about the data, not consequences of the definitions. The tests do not prove them, but they compare the whole procedure with an independent implementation on every decomposable character of Unicode 3.2 and on random strings, so an error in one of them would show up there.

  • (F1) The decomposition mappings form no cycle, so the full decomposition of every code point exists (D68 and D65 assume this). Its longest case under NFKD has 18 code points.
  • (F2) Every primary composite (D114) has canonical combining class 0. This is why the non-starter decompositions are full composition exclusions.
  • (F3) Let LL be a starter that the composition has produced and CC a character after it. A primary composite PP is canonically equivalent to ⟨L,C⟩\langle L, C \rangle exactly when the canonical decomposition mapping of PP is the pair (L,C)(L, C), or LL, CC are a Hangul L,VL, V or LV,TLV, T pair. This is the pair table that UAX 15 describes and that the implementation builds from the two-part mappings of the characters that are not full composition exclusions.

Lemma 1 (decomposition, lines L6 to L9). FULL-DECOMPOSE(c)(c) returns the full canonical decomposition of cc, or the full compatibility decomposition if the form is NFKD or NFKC.

Proof. By induction on the depth of the mapping graph, which is finite by (F1). A Hangul syllable gets the jamo of section 3.12.2 at line L6, and jamo do not decompose further. A code point without a mapping of the selected kind is its own full decomposition (line L8). Otherwise line L9 replaces each code point of the mapping by its full decomposition, which is the definition. For canonical decomposition, compatibility mappings (those with a tag such as <compat>) are skipped. For compatibility decomposition, both kinds are applied, as D65 requires. □\square

So after line L2, dd is the concatenation of the full decompositions of the characters of XX.

Lemma 2 (ordering, lines L10 to L13). CANONICAL-ORDER(d)(d) leaves the starters in place and stably sorts each maximal run of non-starters by canonical combining class. The result has no reorderable pair (D108), and it is the unique result of D109.

Proof. Line L12 swaps d[j−1]d[j-1] and d[j]d[j] only if ccc(d[j−1])>ccc(d[j])>0\mathrm{ccc}(d[j-1]) > \mathrm{ccc}(d[j]) > 0, that is, only a reorderable pair. Both characters are non-starters, so a starter never moves and a mark never crosses a starter. Invariant of the loop of line L10: before step ii, d[0…i−1]d[0 \ldots i-1] has no reorderable pair, so each run of non-starters in it is sorted by ccc. Step ii moves d[i]d[i] left while the character before it is a non-starter with a larger class, and stops at a starter, at a mark with a class at most ccc(d[i])\mathrm{ccc}(d[i]), or at the start. If ccc(d[i])=0\mathrm{ccc}(d[i]) = 0, nothing moves. This is one step of insertion sort inside the last run, so the invariant holds for i+1i + 1. Marks with equal classes are never swapped, so the sort is stable.

Uniqueness: D109 swaps reorderable pairs until none remain. Every such swap keeps the positions of the starters and the relative order of two marks with equal classes. So in any final result, each run holds the same marks, in nondecreasing class order, with equal classes in their input order, and only one sequence has these properties. □\square

After line L3, dd is therefore toNFD(X)(X) or toNFKD(X)(X), and line L5 returns it for the forms NFD and NFKD.

Lemma 3 (composition, lines L14 to L22). For a canonically ordered sequence dd, COMPOSE(d)(d) returns the result of D117.

Proof. D117 visits the characters CC from left to right. For each one, it finds the last starter SS before CC, and if CC is not blocked from SS and a primary composite PP is canonically equivalent to ⟨S,C⟩\langle S, C \rangle, it replaces SS by PP and deletes CC. By D115, CC is blocked from SS when some character BB between them has ccc(B)=0\mathrm{ccc}(B) = 0 or ccc(B)≥ccc(C)\mathrm{ccc}(B) \ge \mathrm{ccc}(C).

The procedure keeps the processed prefix in outout. Invariant: starterstarter is the index in outout of the last starter, or −1-1 if there is none, and lastlast is the class of the last character after it in outout, or −1-1 if there is no such character. Every character after out[starter]out[starter] is a non-starter, because each starter that is appended becomes the new starterstarter (line L20). These non-starters come from one run of the canonically ordered input, so their classes do not decrease, and the largest of them is lastlast. So some character between SS and CC blocks CC exactly when last≠−1last \ne -1 and last≥ccc(C)last \ge \mathrm{ccc}(C). Line L17 tests the opposite, so it allows composition exactly when D117 does. For a starter CC this means that CC must come right after SS. By (F3), COMPOSE-PAIR finds PP when it exists. If it does (line L18), PP replaces SS and CC is dropped. By (F2), PP is a starter, so the invariant still holds, and lastlast does not change because CC is gone. If it does not, line L21 appends CC and lines L19 and L20 update the invariant. □\square

Proof of the claim. By Lemmas 1 and 2, lines L1 to L3 compute toNFD(X)(X) or toNFKD(X)(X). For the forms NFC and NFKC, line L4 applies COMPOSE, which by Lemma 3 is D117. That is the definition of toNFC and toNFKC.

Termination. FULL-DECOMPOSE stops by (F1). Each step of CANONICAL-ORDER moves one mark left at most ii times, so the sort stops after O(m2)O(m^2) comparisons for m=∣d∣m = |d|, and in fact after O(∑rkr2)O(\sum_r k_r^2) for runs of lengths krk_r. COMPOSE runs its loop once per element of dd. So NORMALIZE stops. ■\blacksquare

Complexity

In the word-RAM model, with the data in tables of constant access time, line L2 takes O(n)O(n) time, because one code point expands to at most 18 code points (under NFKD) and the recursion has constant depth. Canonical ordering takes O(∑rkr2)O(\sum_r k_r^2) time for runs of krk_r non-starters, and composition takes O(∣d∣)O(|d|) time.

claim value
decomposition O(n)O(n), at most 18 code points per input code point
canonical ordering O(∑rkr2)O(\sum_r k_r^2), which is Θ(n2)\Theta(n^2) for one long run in decreasing class order
composition O(n)O(n)
text in Stream-Safe Text Format O(n)O(n) in total, since every run has at most 30 non-starters

The worst case is a string of many marks with decreasing classes. Real text has short runs, so the time is linear in practice, and the Stream-Safe Text Format of section 13 of UAX 15 makes the bound linear for every input that follows it.

Properties

  • Idempotent. NORMALIZE(form, NORMALIZE(form, X)) = NORMALIZE(form, X).
  • Decides the equivalences. Two strings are canonically equivalent exactly when their NFD outputs are equal, and the test test_canonical_equivalence checks this.
  • Starters stay in place. The test test_starters_never_move_and_order_is_stable checks that canonical ordering moves only marks and keeps the order of equal classes.
  • Not closed under concatenation. NFC("a") NFC(U+0301) is not in NFC. The test test_not_closed_under_concatenation checks this.
  • Recursive. FULL-DECOMPOSE calls itself on the parts of a mapping. An implementation can store the full decompositions instead and avoid the recursion.

Variants and improvements

  • Quick check. Section 9 of UAX 15 gives the properties NFC_Quick_Check and the like. A string whose characters all have the value Yes and whose marks are in order is already normalized, so most text needs no work. A value No means that the string is not normalized, and Maybe means that the algorithm must run.
  • Incremental normalization. The work can be split at characters that start a new segment, such as starters with the quick check value Yes, and each segment normalized alone. This keeps the buffer small for streams.
  • Counting sort for ordering. The classes are in 0..254, so a run of marks can also be sorted with a stable counting sort in O(k+255)O(k + 255) time. For the usual runs of one to three marks, insertion sort is faster.
  • Precomputed tables. Libraries such as ICU store the full decompositions and the pair table in compact tables, which removes the recursion of line L9 and the search of PAIR.
  • Stream-Safe Text Format. Insert U+034F COMBINING GRAPHEME JOINER after every 30 non-starters, as section 13 of UAX 15 describes, to bound the buffer and the time.

When to use it

Normalize text before you compare, hash, index or search it, so that equivalent strings give the same result. NFC is the usual form for storing and exchanging text, and it is what the web and most file formats expect. NFD is convenient for processing that looks at the marks, such as removing accents. Use NFKC or NFKD only for matching, as in identifiers and search, because they change the meaning of text such as ½ and superscripts. For comparison without case, combine normalization with case folding. For sorting, the collation algorithm handles equivalent strings by itself.

Pitfalls

  • Sorting across starters. A sort of all the marks of a string, or a sort that is not stable, gives wrong results. The test test_starters_never_move_and_order_is_stable checks this.
  • Missing exclusions. The derived exclusions, the 1,035 singletons such as U+212B and the 4 non-starter decompositions such as U+0344, are not in the list that CompositionExclusions.txt gives as data. The test test_exclusion_table checks the 81 listed exclusions and that the implementation derives exactly the 1,035 singletons and the 4 non-starter decompositions.
  • Composing with the wrong starter. The composition must use the last starter in the output, which can be a composite that line L18 made, not the last starter in the input.
  • One level of decomposition. Applying the mappings once leaves characters such as U+1E69 half decomposed.
  • Different Unicode versions. A code point that is unassigned in one version can be assigned with a mapping or a class in a later one, so two systems with different data can give different results for it. The tests pin the data to version 16.0.0 and check the 35 lines of NormalizationTest.txt that test_conformance_lines includes.
  • Long runs of marks. A string of thousands of marks makes the sort quadratic and the buffer large. Limit runs as the Stream-Safe Text Format does.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

unicode_normalization_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-normalization-algorithm/. The authors are listed in prov/ZG8A1R.jsonl.

"""The four Unicode normalization forms (UAX 15 revision 56; core spec 16.0.0, section 3.11).

The code uses unicodedata only as data: decomposition() for the decomposition mappings and
combining() for the canonical combining class (ccc). It does not call unicodedata.normalize
or unicodedata.is_normalized. Hangul syllables use the arithmetic of core spec section 3.12.
"""

import unicodedata

# The code point fields of the data lines of sections 1 (script specifics, 67 code points)
# and 2 (post composition version, 14 code points) of CompositionExclusions-16.0.0.txt
# (Date: 2024-02-02), https://www.unicode.org/Public/16.0.0/ucd/CompositionExclusions.txt.
# Sections 3 (1035 singletons) and 4 (4 non-starter decompositions) are listed in the file
# "for reference" only, because they can be derived; full_composition_exclusions() derives them.
SCRIPT_SPECIFIC = """
0958 0959 095A 095B 095C 095D 095E 095F 09DC 09DD 09DF 0A33 0A36 0A59 0A5A 0A5B 0A5E
0B5C 0B5D 0F43 0F4D 0F52 0F57 0F5C 0F69 0F76 0F78 0F93 0F9D 0FA2 0FA7 0FAC 0FB9 FB1D
FB1F FB2A FB2B FB2C FB2D FB2E FB2F FB30 FB31 FB32 FB33 FB34 FB35 FB36 FB38 FB39 FB3A
FB3B FB3C FB3E FB40 FB41 FB43 FB44 FB46 FB47 FB48 FB49 FB4A FB4B FB4C FB4D FB4E
"""
POST_COMPOSITION_VERSION = """
2ADC 1D15E 1D15F 1D160 1D161 1D162 1D163 1D164 1D1BB 1D1BC 1D1BD 1D1BE 1D1BF 1D1C0
"""
COMPOSITION_EXCLUSIONS = frozenset(int(x, 16) for x in (SCRIPT_SPECIFIC + POST_COMPOSITION_VERSION).split())

SBASE, LBASE, VBASE, TBASE = 0xAC00, 0x1100, 0x1161, 0x11A7
LCOUNT, VCOUNT, TCOUNT = 19, 21, 28
NCOUNT, SCOUNT = VCOUNT * TCOUNT, LCOUNT * VCOUNT * TCOUNT


def ccc(c: int) -> int:
    return unicodedata.combining(chr(c))


def mapping(c: int, compat: bool) -> tuple[int, ...] | None:
    """The decomposition mapping of c from UnicodeData.txt, or None.

    A compatibility mapping starts with a tag such as <compat>; it is used only when compat holds.
    """
    d = unicodedata.decomposition(chr(c))
    if not d:
        return None
    if d.startswith("<"):
        if not compat:
            return None
        d = d.split(">", 1)[1]
    return tuple(int(x, 16) for x in d.split())


def full_decompose(c: int, compat: bool) -> list[int]:
    """The full canonical (or compatibility) decomposition of one code point, before reordering."""
    s = c - SBASE
    if 0 <= s < SCOUNT:  # @line L6
        jamo = [LBASE + s // NCOUNT, VBASE + (s % NCOUNT) // TCOUNT]
        return jamo + [TBASE + s % TCOUNT] if s % TCOUNT else jamo
    m = mapping(c, compat)  # @line L7
    if m is None:  # @line L8
        return [c]
    out: list[int] = []
    for d in m:  # @line L9
        out.extend(full_decompose(d, compat))
    return out


def canonical_order(d: list[int]) -> None:
    """Sort each run of non-starters by ccc, stably, in place (D108, D109)."""
    for i in range(1, len(d)):  # @line L10
        j = i  # @line L11
        while j > 0 and ccc(d[j - 1]) > ccc(d[j]) > 0:  # @line L12
            d[j - 1], d[j] = d[j], d[j - 1]  # @line L13
            j -= 1


def full_composition_exclusions() -> frozenset[int]:
    """Full_Composition_Exclusion: the listed exclusions, the singletons and the non-starter decompositions."""
    out = set(COMPOSITION_EXCLUSIONS)
    for c in range(0x110000):
        m = mapping(c, False)
        if m is None:
            continue
        if len(m) == 1 or ccc(c) != 0 or ccc(m[0]) != 0:
            out.add(c)
    return frozenset(out)


def build_primary_composites() -> dict[tuple[int, int], int]:
    """Map each pair (first, second) to its primary composite (D114). Hangul is done by arithmetic."""
    excluded = full_composition_exclusions()
    table = {}
    for c in range(0x110000):
        m = mapping(c, False)
        if m is not None and len(m) == 2 and c not in excluded:
            table[m] = c
    return table


PRIMARY = build_primary_composites()


def compose_pair(a: int, b: int) -> int | None:
    """The primary composite of a and b, or None."""
    if LBASE <= a < LBASE + LCOUNT and VBASE <= b < VBASE + VCOUNT:
        return SBASE + ((a - LBASE) * VCOUNT + (b - VBASE)) * TCOUNT
    s = a - SBASE
    if 0 <= s < SCOUNT and s % TCOUNT == 0 and TBASE < b < TBASE + TCOUNT:
        return a + (b - TBASE)
    return PRIMARY.get((a, b))


def compose(d: list[int]) -> list[int]:
    """The canonical composition algorithm (D117) on a canonically ordered sequence."""
    out: list[int] = []
    starter, last = -1, -1  # @line L14
    for c in d:  # @line L15
        k = ccc(c)  # @line L16
        # c is not blocked from out[starter] when nothing lies between them (last = -1),
        # or when every character between them is a non-starter with a smaller ccc.
        p = compose_pair(out[starter], c) if starter >= 0 and (last == -1 or 0 < last < k) else None  # @line L17
        if p is not None:
            out[starter] = p  # @line L18
            continue
        if k == 0:  # @line L19
            starter, last = len(out), -1
        else:
            last = k  # @line L20
        out.append(c)  # @line L21
    return out  # @line L22


def normalize(form: str, s: str) -> str:
    """toNFD, toNFC, toNFKD or toNFKC of s."""
    if form not in ("NFC", "NFD", "NFKC", "NFKD"):
        raise ValueError(form)
    compat = form.startswith("NFK")
    d: list[int] = []  # @line L1
    for ch in s:  # @line L2
        d.extend(full_decompose(ord(ch), compat))
    canonical_order(d)  # @line L3
    if form in ("NFC", "NFKC"):  # @line L4
        d = compose(d)
    return "".join(map(chr, d))  # @line L5


def canonically_equivalent(x: str, y: str) -> bool:
    """D70: equal full canonical decompositions (after canonical ordering)."""
    return normalize("NFD", x) == normalize("NFD", y)
test_unicode_normalization_algorithm.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-normalization-algorithm/. The authors are listed in prov/ZG8A1R.jsonl.

# Oracle: unicodedata.normalize. Written against Python 3.14, unicodedata.unidata_version
# 16.0.0. Random tests use only characters assigned in Unicode 3.2, whose decompositions and
# ccc values the stability policy fixes.

import random
import unicodedata

from unicode_normalization_algorithm import (
    COMPOSITION_EXCLUSIONS, PRIMARY, canonical_order, canonically_equivalent, ccc, full_composition_exclusions,
    mapping, normalize)

FORMS = ("NFC", "NFD", "NFKC", "NFKD")

# NormalizationTest-16.0.0.txt (Date: 2024-04-30, 21:48:23 GMT),
# https://www.unicode.org/Public/16.0.0/ucd/NormalizationTest.txt. The fields c1;c2;c3;c4;c5;
# of the first 25 data lines after "@Part0 # Specific cases" and the first 10 after
# "@Part1 # Character by character test", without the comments.
PART0 = """\
1E0A;1E0A;0044 0307;1E0A;0044 0307;
1E0C;1E0C;0044 0323;1E0C;0044 0323;
1E0A 0323;1E0C 0307;0044 0323 0307;1E0C 0307;0044 0323 0307;
1E0C 0307;1E0C 0307;0044 0323 0307;1E0C 0307;0044 0323 0307;
0044 0307 0323;1E0C 0307;0044 0323 0307;1E0C 0307;0044 0323 0307;
0044 0323 0307;1E0C 0307;0044 0323 0307;1E0C 0307;0044 0323 0307;
1E0A 031B;1E0A 031B;0044 031B 0307;1E0A 031B;0044 031B 0307;
1E0C 031B;1E0C 031B;0044 031B 0323;1E0C 031B;0044 031B 0323;
1E0A 031B 0323;1E0C 031B 0307;0044 031B 0323 0307;1E0C 031B 0307;0044 031B 0323 0307;
1E0C 031B 0307;1E0C 031B 0307;0044 031B 0323 0307;1E0C 031B 0307;0044 031B 0323 0307;
0044 031B 0307 0323;1E0C 031B 0307;0044 031B 0323 0307;1E0C 031B 0307;0044 031B 0323 0307;
0044 031B 0323 0307;1E0C 031B 0307;0044 031B 0323 0307;1E0C 031B 0307;0044 031B 0323 0307;
00C8;00C8;0045 0300;00C8;0045 0300;
0112;0112;0045 0304;0112;0045 0304;
0045 0300;00C8;0045 0300;00C8;0045 0300;
0045 0304;0112;0045 0304;0112;0045 0304;
1E14;1E14;0045 0304 0300;1E14;0045 0304 0300;
0112 0300;1E14;0045 0304 0300;1E14;0045 0304 0300;
1E14 0304;1E14 0304;0045 0304 0300 0304;1E14 0304;0045 0304 0300 0304;
0045 0304 0300;1E14;0045 0304 0300;1E14;0045 0304 0300;
0045 0300 0304;00C8 0304;0045 0300 0304;00C8 0304;0045 0300 0304;
05B8 05B9 05B1 0591 05C3 05B0 05AC 059F;05B1 05B8 05B9 0591 05C3 05B0 05AC 059F;05B1 05B8 05B9 0591 05C3 05B0 05AC 059F;05B1 05B8 05B9 0591 05C3 05B0 05AC 059F;05B1 05B8 05B9 0591 05C3 05B0 05AC 059F;
0592 05B7 05BC 05A5 05B0 05C0 05C4 05AD;05B0 05B7 05BC 05A5 0592 05C0 05AD 05C4;05B0 05B7 05BC 05A5 0592 05C0 05AD 05C4;05B0 05B7 05BC 05A5 0592 05C0 05AD 05C4;05B0 05B7 05BC 05A5 0592 05C0 05AD 05C4;
1100 AC00 11A8;1100 AC01;1100 1100 1161 11A8;1100 AC01;1100 1100 1161 11A8;
1100 AC00 11A8 11A8;1100 AC01 11A8;1100 1100 1161 11A8 11A8;1100 AC01 11A8;1100 1100 1161 11A8 11A8;
"""
PART1 = """\
00A0;00A0;00A0;0020;0020;
00A8;00A8;00A8;0020 0308;0020 0308;
00AA;00AA;00AA;0061;0061;
00AF;00AF;00AF;0020 0304;0020 0304;
00B2;00B2;00B2;0032;0032;
00B3;00B3;00B3;0033;0033;
00B4;00B4;00B4;0020 0301;0020 0301;
00B5;00B5;00B5;03BC;03BC;
00B8;00B8;00B8;0020 0327;0020 0327;
00B9;00B9;00B9;0031;0031;
"""


def parse(block: str) -> list[list[str]]:
    rows = []
    for line in block.splitlines():
        fields = line.split("#", 1)[0].split(";")[:5]
        rows.append(["".join(chr(int(x, 16)) for x in f.split()) for f in fields])
    return rows


def hexs(s: str) -> str:
    return " ".join("%04X" % ord(ch) for ch in s)


def test_conformance_lines() -> None:
    # The invariants of the header of NormalizationTest.txt (conformance clause UAX15-C3).
    rows = parse(PART0) + parse(PART1)
    assert len(rows) == 35
    nfc = lambda s: normalize("NFC", s)  # noqa: E731
    nfd = lambda s: normalize("NFD", s)  # noqa: E731
    nfkc = lambda s: normalize("NFKC", s)  # noqa: E731
    nfkd = lambda s: normalize("NFKD", s)  # noqa: E731
    for c1, c2, c3, c4, c5 in rows:
        assert c2 == nfc(c1) == nfc(c2) == nfc(c3)
        assert c4 == nfc(c4) == nfc(c5)
        assert c3 == nfd(c1) == nfd(c2) == nfd(c3)
        assert c5 == nfd(c4) == nfd(c5)
        assert c4 == nfkc(c1) == nfkc(c2) == nfkc(c3) == nfkc(c4) == nfkc(c5)
        assert c5 == nfkd(c1) == nfkd(c2) == nfkd(c3) == nfkd(c4) == nfkd(c5)


def test_check_values() -> None:
    cases = {
        "ḍ̇": ("1E0D 0307", "0064 0323 0307", "1E0D 0307", "0064 0323 0307"),
        "Å": ("00C5", "0041 030A", "00C5", "0041 030A"),
        "fi": ("FB01", "FB01", "0066 0069", "0066 0069"),
        "Å": ("00C5", "0041 030A", "00C5", "0041 030A"),
        "ẛ̣": ("1E9B 0323", "017F 0323 0307", "1E69", "0073 0323 0307"),
    }
    for s, want in cases.items():
        assert tuple(hexs(normalize(f, s)) for f in FORMS) == want
    assert [ccc(c) for c in (0x0323, 0x0307, 0x0301, 0x031B)] == [220, 230, 230, 216]


def test_starters_never_move_and_order_is_stable() -> None:
    d = [0x0061, 0x0301, 0x0323, 0x0062, 0x0308, 0x0301, 0x0327]
    canonical_order(d)
    assert d == [0x0061, 0x0323, 0x0301, 0x0062, 0x0327, 0x0308, 0x0301]


def test_not_closed_under_concatenation() -> None:
    x, y = "a", "́"
    assert normalize("NFC", x) == x and normalize("NFC", y) == y
    assert normalize("NFC", x + y) == "á" != x + y


def test_exclusion_table() -> None:
    assert len(COMPOSITION_EXCLUSIONS) == 81
    for c in COMPOSITION_EXCLUSIONS:
        m = mapping(c, False)
        assert m is not None and len(m) == 2
        assert unicodedata.normalize("NFC", "".join(map(chr, m))) != chr(c)
        assert c not in PRIMARY.values()
    full = full_composition_exclusions()
    singletons = [c for c in full if (m := mapping(c, False)) is not None and len(m) == 1]
    assert len(singletons) == 1035
    assert sorted(full - COMPOSITION_EXCLUSIONS - set(singletons)) == [0x0344, 0x0F73, 0x0F75, 0x0F81]


def pool_3_2() -> list[str]:
    rng = random.Random(7)
    marks = [chr(c) for c in range(0x0300, 0x0370) if unicodedata.ucd_3_2_0.category(chr(c)) == "Mn"]
    decomposable = [chr(c) for c in range(0x00A0, 0x3400) if unicodedata.ucd_3_2_0.category(chr(c)) != "Cn"
                    and unicodedata.decomposition(chr(c))]
    hangul = [chr(c) for c in list(range(0x1100, 0x1113)) + list(range(0x1161, 0x1176)) + list(range(0x11A8, 0x11C3))]
    hangul += [chr(rng.randrange(0xAC00, 0xD7A4)) for _ in range(30)]
    plain = list("aeiouACEOUnsdk ")
    return plain + marks + rng.sample(decomposable, 400) + hangul + [chr(c) for c in COMPOSITION_EXCLUSIONS]


def test_random_strings_against_unicodedata() -> None:
    pool = pool_3_2()
    assert all(unicodedata.ucd_3_2_0.category(ch) != "Cn" for ch in pool)
    rng = random.Random(8)
    for _ in range(3000):
        s = "".join(rng.choice(pool) for _ in range(rng.randrange(1, 9)))
        for f in FORMS:
            assert normalize(f, s) == unicodedata.normalize(f, s), (f, hexs(s))


def test_each_decomposable_3_2_character() -> None:
    for c in range(0x00A0, 0x10000):
        ch = chr(c)
        if unicodedata.ucd_3_2_0.category(ch) == "Cn" or not unicodedata.decomposition(ch):
            continue
        for f in FORMS:
            assert normalize(f, ch) == unicodedata.normalize(f, ch), (f, "%04X" % c)


def test_canonical_equivalence() -> None:
    assert canonically_equivalent("Å", "Å")
    assert canonically_equivalent("q̣̇", "q̣̇")
    assert not canonically_equivalent("fi", "fi")

History

The normalization forms were defined in UAX 15 in the years around Unicode 3.0, and the composition step was then fixed by a stability policy: when a new character is added whose decomposition uses existing characters, it is excluded from composition, so that the NFC of existing text does not change. The 14 post composition version exclusions in CompositionExclusions.txt are such characters. NormalizationTest.txt gives conformance test data for every version, and the clauses UAX15-C1 to UAX15-C5 state what an implementation must do.

References

  1. The Unicode Consortium, The Unicode Standard, Version 16.0.0, 2024, Chapter 3: Section 3.7 Decomposition (D65, D68), Section 3.11 Normalization Forms (3.11.5 Canonical Ordering Algorithm, D108 and D109; 3.11.6 Canonical Composition Algorithm, D110 to D117; 3.11.7 Definition of Normalization Forms, D118 to D121) and Section 3.12 Conjoining Jamo Behavior
  2. Mark Davis and Ken Whistler, Unicode Standard Annex 15, Unicode Normalization Forms, revision 56, Section 1.3 (canonical ordering and composition), Section 4 (conformance, UAX15-C1 to C5), Section 5 (composition exclusion, 5.1 and its four types), Section 9 (detecting normalization forms) and Section 13 (Stream-Safe Text Format)
  3. Unicode Character Database 16.0.0, CompositionExclusions.txt (2024-02-02), Sections 1 to 4 (67 script-specific exclusions, 14 post composition version exclusions, 1035 singletons, 4 non-starter decompositions)
  4. Unicode Character Database 16.0.0, NormalizationTest.txt (2024-04-30), The conformance test lines c1 to c5 and their invariants

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example