feat(parsing): ISO-2022-JP decoding

Add the WHATWG iso-2022-jp decoder, the first stateful encoding: escape
sequences switch between ASCII, JIS X 0201 Roman (yen, overline), JIS X 0201
katakana, and the JIS X 0208 plane, resolved through the shared jis0208 table
(no new data). Tested across all four modes, with the JIS X 0208 kanji
cross-checked against the EUC-JP decoder (same table, same pointer). EUC-TW and
the streaming form of ISO-2022-JP remain.

Part of #108, #105
This commit is contained in:
Mihaela Mihaljevic 2026-06-09 10:55:34 +02:00
parent 051ef02fdb
commit 1e815d6309
6 changed files with 127 additions and 1 deletions

View File

@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- ISO-2022-JP decoding (#108, in progress): the byte decoder gains the WHATWG `iso-2022-jp` algorithm, selected by the `iso-2022-jp` declaration name. Unlike the other CJK encodings this one is stateful, escape sequences switch between ASCII, JIS X 0201 Roman (with the yen sign and overline), JIS X 0201 katakana, and the JIS X 0208 plane, which is resolved through the shared `jis0208` table (no new data). EUC-TW and the streaming form of ISO-2022-JP remain on the issue.
- Streaming (reader-driven) DTD validation (#107, in progress): `PureXML.validate(streaming:dtd:)` and `PureXML.Validation.StreamingDTDValidator` validate a document against a DTD while it is pulled event by event (the libxml2 `xmlTextReader` validation model), holding only the open-element stack rather than the whole tree. Each element's content model and attributes are checked the moment it closes, by applying the exact per-element DTD rules to a shallow element synthesized from the streamed child names. Document-scoped ID/IDREF integrity is tracked in bounded sets (the identifier values, not the tree): a duplicate ID is reported at its repeat occurrence, and forward IDREFs resolve at the end of the stream. Streaming and tree validation report the same problems (a test asserts matching reasons), and errors carry a libxml2 `xmlGetNodePath`-style coding path. RELAX NG streaming is also available via `RelaxNG.validate(streaming:)`: the Brzozowski derivative is itself incremental, so it is driven directly from the event stream, retaining only the residual pattern (the `after`-threaded chain is the validation stack) and a light per-element frame for ignorable-whitespace handling; a differential test asserts it agrees with the tree engine across valid, invalid, whitespace, and mixed-content documents. XSD streaming remains on the issue.
- Output encoding (#106): `Serializer.serialize(_:encoding:)` and `PureXML.serialize(_:encoding:)` now emit bytes in a chosen encoding (the libxml2 `xmlSaveToFilename(..., encoding)` model), not only UTF-8. A new `PureXML.Parsing.ByteEncoder` covers the Unicode transformation formats, the single-byte legacy families (ISO-8859, Windows code pages, KOI8), and the multi-byte CJK encodings (Shift-JIS, EUC-JP, EUC-KR, GBK, GB18030, Big5). The CJK and single-byte inverses are built by running the existing, tested decoders over every valid byte sequence and recording the shortest sequence per scalar, so each encoder is by construction the exact inverse of its decoder (no new data, no separately maintained encode tables); GB18030's astral range uses the four-byte pointer formula. The declaration carries the encoding's canonical name, a UTF-16/32 stream is preceded by a byte-order mark, and any scalar the target encoding cannot represent is written as a decimal numeric character reference, so output always round-trips.
- Big5 (#103): the byte decoder gains the WHATWG `big5` algorithm, for both the whole-buffer and streaming decoders, selected by the `big5` declaration name (and the `big5-hkscs` / `cn-big5` aliases). A lead in `0x81`-`0xFE` followed by a trail in `0x40`-`0x7E` or `0xA1`-`0xFE` resolves through the index, covering Traditional Chinese and the HKSCS extensions including the astral CJK ideographs (Extension B and the Compatibility Supplement). Four pointers decode to a base letter plus a combining mark (a two-scalar sequence). The 18,590-entry index is vendored verbatim from the WHATWG `index-big5.txt`. Big5 completes the major CJK families libxml2 reaches through iconv (Japanese, Korean, Simplified and Traditional Chinese).

View File

@ -99,7 +99,7 @@ flowchart TB
PureXML is a working, dependency-free XML library today: parse, emit, validate,
query, and stream documents on macOS, Linux, Windows, and WASM. The test suite
currently runs **785 tests in 120 suites** (`swift test`).
currently runs **786 tests in 120 suites** (`swift test`).
### Shipped (libxml2-aligned surface)

View File

@ -37,6 +37,7 @@ extension PureXML.Parsing {
case .gbk: GBK.decode(body)
case .gb18030: GB18030.decode(body)
case .big5: Big5.decode(body)
case .iso2022jp: ISO2022JP.decode(body)
default: nil
}
}
@ -164,6 +165,7 @@ extension PureXML.Parsing {
"gbk": .gbk, "gb2312": .gbk, "gb_2312-80": .gbk, "csgb2312": .gbk, "x-gbk": .gbk, "chinese": .gbk,
"gb18030": .gb18030, "gb-18030": .gb18030, "csgb18030": .gb18030,
"big5": .big5, "big5-hkscs": .big5, "cn-big5": .big5, "csbig5": .big5, "x-x-big5": .big5,
"iso-2022-jp": .iso2022jp, "csiso2022jp": .iso2022jp,
"iso-8859-5": .latinCyrillic, "iso8859-5": .latinCyrillic, "cyrillic": .latinCyrillic,
"iso-8859-9": .latin5, "iso8859-9": .latin5, "latin5": .latin5, "latin-5": .latin5, "l5": .latin5,
"iso-8859-15": .latin9, "iso8859-15": .latin9, "latin9": .latin9, "latin-9": .latin9, "l9": .latin9,

View File

@ -0,0 +1,106 @@
extension PureXML.Parsing.ByteDecoder {
/// The ISO-2022-JP decoder (the WHATWG `iso-2022-jp` algorithm). Unlike the
/// other CJK encodings this one is stateful: escape sequences switch between
/// ASCII, JIS X 0201 Roman, JIS X 0201 katakana, and the JIS X 0208 plane,
/// which is resolved through the shared `jis0208` table (no new data).
enum ISO2022JP {
static func decode(_ bytes: ArraySlice<UInt8>) -> String {
var scalars = String.UnicodeScalarView()
var mode: ISO2022JPMode = .ascii
var lead: UInt8?
let array = Array(bytes)
var index = 0
while index < array.count {
let byte = array[index]
index += 1
if byte == 0x1B {
mode = applyEscape(array, &index, into: &scalars) ?? mode
lead = nil
continue
}
decodeByte(byte, mode: mode, lead: &lead, into: &scalars)
}
if lead != nil { scalars.append("\u{FFFD}") }
return String(scalars)
}
/// Reads the bytes after an escape and returns the new mode, or nil (with a
/// replacement emitted) for an unrecognized sequence.
private static func applyEscape(_ array: [UInt8], _ index: inout Int, into scalars: inout String.UnicodeScalarView) -> ISO2022JPMode? {
guard index < array.count else { scalars.append("\u{FFFD}")
return nil
}
let first = array[index]
index += 1
guard index < array.count else { scalars.append("\u{FFFD}")
return nil
}
let second = array[index]
index += 1
switch (first, second) {
case (0x28, 0x42): return .ascii // ESC ( B
case (0x28, 0x4A): return .roman // ESC ( J
case (0x28, 0x49): return .katakana // ESC ( I
case (0x24, 0x40), (0x24, 0x42): return .jis0208 // ESC $ @ / ESC $ B
default:
scalars.append("\u{FFFD}")
return nil
}
}
private static func decodeByte(_ byte: UInt8, mode: ISO2022JPMode, lead: inout UInt8?, into scalars: inout String.UnicodeScalarView) {
switch mode {
case .ascii:
scalars.append(byte <= 0x7F ? Unicode.Scalar(byte) : "\u{FFFD}")
case .roman:
switch byte {
case 0x5C: scalars.append("\u{00A5}") // yen
case 0x7E: scalars.append("\u{203E}") // overline
case 0 ... 0x7F: scalars.append(Unicode.Scalar(byte))
default: scalars.append("\u{FFFD}")
}
case .katakana:
if (0x21 ... 0x5F).contains(byte) {
scalars.append(Unicode.Scalar(0xFF61 + UInt32(byte) - 0x21) ?? "\u{FFFD}")
} else {
scalars.append("\u{FFFD}")
}
case .jis0208:
decodeJIS0208(byte, lead: &lead, into: &scalars)
}
}
private static func decodeJIS0208(_ byte: UInt8, lead: inout UInt8?, into scalars: inout String.UnicodeScalarView) {
guard let first = lead else {
if (0x21 ... 0x7E).contains(byte) {
lead = byte
} else if byte == 0x0A || byte == 0x0D {
scalars.append(Unicode.Scalar(byte))
} else {
scalars.append("\u{FFFD}")
}
return
}
lead = nil
guard (0x21 ... 0x7E).contains(first), (0x21 ... 0x7E).contains(byte) else {
scalars.append("\u{FFFD}")
return
}
let pointer = (Int(first) - 0x21) * 94 + Int(byte) - 0x21
if pointer >= 0, pointer < jis0208.count, jis0208[pointer] != 0xFFFF {
scalars.append(Unicode.Scalar(UInt32(jis0208[pointer])) ?? "\u{FFFD}")
} else {
scalars.append("\u{FFFD}")
}
}
}
}
/// The active character set while decoding ISO-2022-JP, switched by escape
/// sequences.
private enum ISO2022JPMode {
case ascii
case roman
case katakana
case jis0208
}

View File

@ -37,6 +37,7 @@ public extension PureXML.Parsing {
case gbk
case gb18030
case big5
case iso2022jp
case latinCyrillic // ISO-8859-5
case latin5 // ISO-8859-9 (Turkish)
case latin9 // ISO-8859-15

View File

@ -192,6 +192,22 @@ struct EncodingTests {
try #expect(decoded("csbig5", [0x88, 0x62]) == "\u{00CA}\u{0304}")
}
@Test("Decodes ISO-2022-JP: ASCII, JIS X 0201 Roman and katakana, and JIS X 0208")
func test_iso2022jp() throws {
let esc: UInt8 = 0x1B
// JIS X 0201 Roman: 0x5C is the yen sign, 0x7E the overline.
try #expect(decoded("ISO-2022-JP", [esc, 0x28, 0x4A, 0x5C, 0x7E, esc, 0x28, 0x42]) == "\u{00A5}\u{203E}")
// JIS X 0201 katakana: 0x31 -> U+FF71 (ア).
try #expect(decoded("iso-2022-jp", [esc, 0x28, 0x49, 0x31, esc, 0x28, 0x42]) == "\u{FF71}")
// JIS X 0208: 0x46 0x7C shares pointer 3569 with EUC-JP 0xC6 0xFC, the kanji 日.
let kanji = try decoded("ISO-2022-JP", [esc, 0x24, 0x42, 0x46, 0x7C, esc, 0x28, 0x42])
let viaEUCJP = try decoded("EUC-JP", [0xC6, 0xFC])
#expect(kanji == viaEUCJP)
#expect(kanji == "\u{65E5}")
// ASCII passes through, and mode resets across an escape.
try #expect(decoded("ISO-2022-JP", [0x48, 0x69]) == "Hi")
}
@Test("Decodes ISO-8859-5: the Cyrillic block")
func test_iso8859_5() throws {
try #expect(decoded("ISO-8859-5", [0xB0]) == "\u{0410}") // А