Files
Library/docs/roadmap/subsystems/Unicode.md

157 lines
10 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# NEW Unicode subsystem
Status: NEW design; no Unicode source directory/target is claimed to exist. All tasks
are **PLANNED**. Baseline: `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected
2026-11-24. Selected initial data version: **Unicode 17.0.0**, intentionally pinned,
not a promise to track a moving latest release.
## Existing behavior and why a separate owner is needed
[Text Str](../../../include/Void/Text/Str.hpp) provides byte-oriented trimming/casing;
[Html](../../../include/Void/Text/Html.hpp) appends UTF-8 for entity values. General
[Json](../../../include/Void/Data/Json.hpp) and restricted
[StrictJson](../../../include/Void/Data/StrictJson.hpp) each handle string escapes.
These are local capabilities, not a current complete Unicode normalization, property,
segmentation or error-policy contract. [Text encoding tests](../../../tests/standalone/Text/Encoding.cpp)
and [StrictJson tests](../../../tests/standalone/Data/StrictJson.cpp) are compatibility
inputs. Graph coverage marked Json lines 243/1090 partial; the flagged ranges and relevant
string handling were read directly. No existing parser is replaced merely by introducing
this subsystem.
## Dependency and backend choice
Under [C-01/C-07](../ARCHITECTURE.md), choose **Unicode→Text**, with Text staying byte/ASCII
only. The optional integration header belongs to Unicode; Text never includes Unicode.
Unicode may use Core traits and standard PMR resources; no locale engine, ICU, Runtime,
network access, dynamic data download or hidden worker is required. Data may explicitly
use a Unicode validation adapter, but signed StrictJson acceptance remains frozen until
its owner separately approves any security change. Normalization is never an automatic
step in signature verification, URL decoding, filesystem authorization or key equality.
Use native UTF scanners and generated immutable lookup tables. Pin upstream input URLs,
version, license notices and SHA-256 hashes in a NEW reviewed data manifest; actual hashes
are obtained from downloaded files during implementation, not invented in this plan.
Check reviewed compact generated tables into source so ordinary builds need no Python
or download. A separately invoked deterministic generator reproduces them byte-for-byte.
The [17.0.0 UCD directory](https://www.unicode.org/Public/17.0.0/ucd/ReadMe.txt) identifies
the final versioned data. Unicode upgrades are explicit behavioral migrations.
NEW proposed paths: `include/Void/Unicode/Utf.hpp`, `Normalize.hpp`, `Segment.hpp`,
`Properties.hpp`, `TextAdapters.hpp`, `src/Unicode/module.cmake`,
`src/Unicode/generated/`, `tools/unicode/` and `tests/standalone/Unicode/`. Generator,
manifest and generated sources require exclusive ownership in their future task; this
document does not authorize parallel workers to regenerate shared files.
## NEW UTF API and exact error policy
Illustrative proposed declarations, not existing compiling examples:
```cpp
namespace Void::Unicode {
enum class UtfPolicy { reject, replace_one_unit };
enum class UtfErrorKind { invalid_lead, invalid_continuation, overlong,
surrogate, out_of_range, incomplete, limit,
cancelled, allocation_failed };
struct UtfError { UtfErrorKind kind; std::size_t offset; };
struct Scalar { char32_t value; std::size_t begin, end; };
struct UtfLimits {
std::size_t max_input_bytes = 16 * 1024 * 1024;
std::size_t max_output_bytes = 16 * 1024 * 1024;
std::size_t max_scalars = 4194304;
};
std::expected<std::vector<Scalar>, UtfError>
decode_utf8(std::string_view, UtfPolicy = UtfPolicy::reject, UtfLimits = {});
std::expected<std::u16string, UtfError>
to_utf16(std::string_view, UtfPolicy = UtfPolicy::reject, UtfLimits = {});
std::string_view data_version() noexcept; // "17.0.0"
}
```
Default reject fails at the first invalid unit, reports the byte offset for UTF-8 or
code-unit offset for UTF-16, and publishes no partial owning result. Reject overlong
encodings, isolated continuation bytes, encoded surrogate values, values above U+10FFFF
and truncated tails. UTF-16 accepts paired surrogates only. UTF-32 accepts scalar values
only. Noncharacters are valid scalar values unless a separate application policy rejects
them; U+0000 is valid data and never an implicit terminator.
`replace_one_unit` is deliberately named: on malformed UTF-8 consume one byte and emit
U+FFFD; on malformed UTF-16 consume one code unit. Retry the next unit independently.
Thus an invalid multi-byte sequence can emit multiple replacements. This is an explicit
repair profile, not an unstated maximal-subpart claim. In streaming mode incomplete tails
are retained until finalization, not repaired at each chunk boundary. A valid BOM is
decoded as U+FEFF; stripping it is a separate option at document boundaries. Endianness
for UTF-16 bytes is explicit in Binary's adapter, not inferred from host representation.
Provide an allocation-free scalar iterator/view with the same policy and error offset,
plus into-span transcoding returning consumed/produced counts. Views borrow input and
must not outlive it. Stateful decoders retain at most three UTF-8 bytes or one UTF-16 high
surrogate. Defaults cap input/output at 16 MiB and scalar output at 4,194,304; expansion
checks precede reserve. Callers may supply stricter caps. Optional stop checks occur at
least every 4 KiB; already delivered iterator/callback values remain observed on stop.
## Normalization, casing and segmentation
Implement NFD/NFC first, then NFKD/NFKC with the same tables. Decompose recursively via
an explicit bounded stack, reorder by canonical combining class stably, and compose with
the versioned composition exclusions and Hangul rules. These forms and their conformance
tests are specified by [UAX #15 revision 57](https://www.unicode.org/reports/tr15/tr15-57.html).
Do not assume concatenating two normalized chunks is already normalized. The streaming
normalizer retains the uncommitted combining sequence and only emits stable prefixes.
Initial combining-sequence cap is 1,024 scalars; overflow returns `limit`, never inserts
new characters or truncates silently. Input/output and scratch defaults are 16 MiB/16 MiB/
4 MiB, with cumulative charging across stages.
Properties expose general category, combining class, whitespace and simple casing as
table queries. Full default case folding and root-locale casing use explicit APIs; full
casing may expand output. Context-sensitive rules follow the pinned data; Turkish/Azeri
tailoring is an explicit locale option, never inferred from the process locale. Casefold
and normalization are distinct operations. Search-key helpers must name the exact pipeline
(for example NFKC then casefold then NFC) and carry a version/policy identifier for
persisted indexes. Unicode alone is not a spoofing or authentication defense.
Segmentation starts with extended grapheme boundaries, then default word/sentence
boundaries from [UAX #29 revision 47](https://www.unicode.org/reports/tr29/tr29-47.html).
Emit byte ranges into the original validated UTF-8; no copied strings by default. Grapheme
boundaries are not terminal column width. Segmentation state handles regional indicators,
combining marks and emoji ZWJ sequences across chunks. Defaults cap one retained cluster
at 1,024 scalars and boundary output at 1,048,576 entries; return `limit` on excess.
Locale word dictionaries, collation and IDNA are deferred behind separate named capability
gates, not silently approximated by the first subsystem.
## Ordered implementation tasks
| Task | Phase; dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| S-UNICODE-01 | P0; upstream versioned UCD and current Text/Data fixtures | Record exact data inputs, license, hashes and generated-file ownership; reproducible generation works offline from reviewed inputs. | astra_implementer |
| S-UNICODE-02 | P1; S-UNICODE-01 | Add strict/one-unit-repair UTF scanners and span transcoders; every malformed sequence and chunk split matches the documented policy and offsets. | sol_implementer |
| S-UNICODE-03 | P2; S-UNICODE-01–02 | Add immutable properties and default/full casing; pinned case-fold/special-casing vectors and expansion limits pass. | sol_implementer |
| S-UNICODE-04 | P2; S-UNICODE-03 | Implement normalization and streaming stable-prefix behavior; full pinned NormalizationTest corpus passes and long combining sequences fail boundedly. | astra_implementer |
| S-UNICODE-05 | P2; S-UNICODE-03–04 | Implement grapheme then word/sentence boundaries; pinned break-test corpora and cross-chunk emoji/RI cases pass. | sol_implementer |
| S-UNICODE-06 | P3; S-UNICODE-02–05; Text/Data adapter gates | Ship explicit adapters, versioned search-key example and installed consumers; Text-only linkage excludes tables and StrictJson fixtures remain unchanged. | sol_implementer |
## Validation, version changes and rollback
CURRENT evidence covers only existing Text/Data source/tests. No Unicode conformance,
generator, sanitizer or benchmark was run. PROPOSED suites include exhaustive scalar
encode/decode round trips, independent invalid UTF vectors, all split boundaries,
NormalizationTest, GraphemeBreakTest, WordBreakTest and SentenceBreakTest from the pinned
version. Round trips alone cannot prove rejection rules. Reproduction checks compare
generated bytes twice in clean temporary directories and verify the reviewed manifest.
Fuzz chunking, output exhaustion and stop paths; preserve the original input on owning
operation failure. An optional external engine can be a development oracle only after
dependency approval and matching its Unicode version; it is not the shipped backend.
Measure ASCII/mixed-script/combining-heavy throughput and latency, table text/rodata size,
allocations, peak RSS/CPU and build cost under [PERFORMANCE](../PERFORMANCE.md), including
p50/p95/p99. Bound rejection work separately from normal text and report table-version
changes; do not promise smaller/faster than external engines without measurement.
[Migration](../MIGRATION.md) adds Unicode opt-in without changing Text byte semantics.
An upgrade records changed properties/boundaries, re-runs all corpora and builds old/new
persisted search-key indexes side by side. Retain original text and the old policy ID
until cutover is verified. Rollback selects the old tables/index; merely downgrading the
binary cannot recover overwritten keys. No signed payload is normalized during migration.
See [VALIDATION](../VALIDATION.md), [DEPENDENCIES](../DEPENDENCIES.md),
[DELIVERY](../DELIVERY.md), [requirements](../REQUIREMENTS.md),
[Text](../modules/Text.md), [Data](../modules/Data.md) and [Binary](../modules/Binary.md).