Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/SOUNDNESS.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// Freshness stamp — a real main-ancestor commit (survives squash-merge); advance
// it (and --reseal) in any change that touches a soundness path. See "Keeping
// this honest" and tools/check-soundness-ledger.sh (property 4).
:ground-truth-sha: 0cf73b2
:ground-truth-sha: 84eca60
:ground-truth-date: 2026-12-01
:stamp-verified-by: tools/check-soundness-ledger.sh
:toc: macro
Expand Down
261 changes: 261 additions & 0 deletions docs/UNICODE-STRINGS.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
// SPDX-License-Identifier: CC-BY-SA-4.0
// SPDX-FileCopyrightText: 2026 hyperpolymath
= Unicode Strings and UTF-8 Octets Across Backends
:toc: macro
:toclevels: 2
:icons: font

What `String` operations mean on each backend, and the additive API that has
one meaning on every backend. Written for the estate DEED printer, which must
count line length in UTF-8 octets (a DEED line is at most 998 octets,
`deed.abnf` v1.3.0) and must never split a character.

toc::[]

== Ground truth before this change

Measured on `main` at `ee211d3` (2026-12-01) by compiling and running probe
programs through the real CLI: `affinescript eval` (interp),
`compile --bun-esm` then `bun` (Bun ESM), `compile x.js` then `node` (plain
JS), and `compile x.wasm` then `bun run` (core wasm, via Bun's WASI). The
inputs mix 1-octet (`a`), 2-octet (`é` U+00E9), 3-octet (`漢` U+6F22) and
4-octet (`🦜` U+1F99C) characters.

[cols="2,2,2,2,2",options="header"]
|===
| Operation | interp | Bun ESM | plain JS | core wasm

| `len` on `a` / `é` / `漢` / `🦜`
| 1 / 2 / 3 / 4 (UTF-8 octets)
| 1 / 1 / 1 / 2 (UTF-16 code units)
| not lowered: `ReferenceError: len is not defined` at run time
| 1 / 2 / 3 / 4 (octets)

| `len("aé漢🦜")`
| 10 | 5 | `ReferenceError` | 10

| `string_length("🦜")`
| 4 | 2 | `ReferenceError` | 4

| `string_get("🦜", 0)` then `char_to_int`
| 240 (first octet, `0xF0`)
| 55358 (lone high surrogate `0xD83E`)
| `ReferenceError`
| rejected at compile time (`string_get` not lowered)

| `string_char_code_at("🦜", 0)` / `(…, 1)`
| 240 / 159 (octets) | 55358 / 56732 (UTF-16 units) | `ReferenceError` | 240 / 159

| `string_sub("🦜x", 0, 1)`
| one octet `0xF0`: ill-formed UTF-8
| one lone surrogate: ill-formed UTF-16
| `ReferenceError`
| one octet `0xF0`: ill-formed UTF-8

| stdlib `string::length("🦜")`
| 4 | 2 | `ReferenceError` (uses `len`) | stdlib modules do not link on wasm (unresolved import `string:substring`)

| stdlib `string::char_at("🦜", 1)`
| run-time error `Unbound variable: Some` (see Findings) | 56732 | `ReferenceError` | does not link

| Char literal `'é'`
4+| rejected by the lexer on every backend (`Invalid character literal`): a
`Char` is one octet in the AST (`LitChar of char`)
|===

Deno ESM was retired: `--deno-esm` and a `.deno.js` output are refused
("Deno-ESM was removed"), and `lib/codegen_deno.ml` now emits Bun ESM only.
The Bun-ESM column covers it.

Summary: *index and length units differ by backend*. The interpreter and core
wasm store a `String` as its UTF-8 octets and index by octet. Bun ESM stores a
JS (UTF-16) string and indexes by UTF-16 code unit. The plain-JS backend does
not lower the string builtins at all. `string_sub` can cut a character on
every backend and yields a string that is not a sequence of Unicode scalar
values.

== The additive API

Nothing above was changed: `len`, `string_get`, `string_sub`, `char_at` and
`substring` keep their current per-backend meaning, because existing code
depends on it. Three new primitives have *one* meaning on every backend:

[cols="3,5",options="header"]
|===
| Primitive | Meaning

| `utf8_byte_length(s: String) -> Int`
| The number of octets of the UTF-8 encoding of `s`.

| `code_points(s: String) -> [Int]`
| The Unicode scalar values of `s`, in order.

| `string_from_code_points(cps: [Int]) -> String`
| The string whose scalar values are `cps`: the inverse of `code_points`.
|===

Code points are `Int`, not `Char`, because a `Char` is one octet on the
interpreter and wasm and cannot hold U+1F99C. These primitives are intrinsics,
registered in `lib/resolve.ml` and `lib/typecheck.ml` like `string_sub`, and
lowered in `lib/interp.ml`, `lib/codegen_deno.ml` (Bun ESM), `lib/js_codegen.ml`
(plain JS) and `lib/codegen.ml` (core wasm).

`stdlib/utf8.affine` adds functions written in AffineScript on top of them:

[cols="3,5",options="header"]
|===
| Function | Meaning

| `utf8_width(cp: Int) -> Int`
| Octets in the UTF-8 encoding of one scalar value: 1, 2, 3 or 4.

| `code_point_count(s: String) -> Int`
| Number of scalar values in `s`.

| `code_point_slice(s: String, start: Int, end: Int) -> String`
| The scalar values with index in `[start, end)`, clamped. Never splits a
character.

| `code_points_within_octets(s: String, max_octets: Int) -> Int`
| How many leading code points fit in `max_octets` octets. With that `k`,
`code_point_slice(s, 0, k)` is the longest prefix that fits.
|===

Which backend runs which part:

[cols="3,1,1,1,1",options="header"]
|===
| | interp | Bun ESM | plain JS | core wasm

| the three primitives | yes | yes | yes | yes
| `utf8_width`, `code_point_count`, `code_point_slice` | yes | yes | no (the backend has no `len`) | no (stdlib modules do not link)
| `code_points_within_octets` | no (self-recursion, see Findings) | yes | no | no
|===

=== Ill-formed input fails loudly

Each primitive is defined only on well-formed input:

* a `String` that is a sequence of Unicode scalar values;
* an `[Int]` of values in `0..0x10FFFF` that excludes the surrogates
`0xD800..0xDFFF`.

On anything else it fails instead of guessing or substituting U+FFFD. The
interpreter raises a run-time error, Bun ESM and plain JS throw, and core wasm
traps (`unreachable`). That covers:

* overlong forms, surrogates encoded in UTF-8, values above U+10FFFF and
truncated sequences, on the octet backends;
* lone surrogates, on the JS backends;
* a string that `string_sub` cut in half, on every backend.

The interpreter decodes with OCaml's strict `String.get_utf_8_uchar`. The wasm
decoder (`gen_utf8_decode_loop` in `lib/codegen.ml`) rejects the same set of
inputs.

== Assumptions the octet count rests on

A later formal proof of the DEED printer's round trip will rely on these. Each
is *tested, not proved*.

. *Abstract value.* A well-formed `String` denotes a finite sequence of Unicode
scalar values. The three primitives are defined only on well-formed input and
fail loudly otherwise; they never return a value for ill-formed input.
. *Isomorphism.* `string_from_code_points(code_points(s)) == s` for every
well-formed `s`, and `code_points(string_from_code_points(cps)) == cps` for
every `cps` made only of scalar values.
. *Octet law.* `utf8_byte_length(s)` equals the sum of `utf8_width(cp)` over
`code_points(s)`. `utf8_width` follows RFC 3629 shortest form: 1 octet below
`0x80`, 2 below `0x800`, 3 below `0x10000`, 4 otherwise. On the interpreter and
wasm, the count is the stored byte length after validation. On the JS backends,
it is computed from the decoded scalar values.
. *Output equals count.* On Bun, writing a well-formed string as UTF-8 (`fs`
with `"utf8"`, or `TextEncoder`) emits exactly `utf8_byte_length(s)` octets.
On the interpreter and wasm, the stored bytes are the bytes written. A lone
surrogate would be written as the 3-octet U+FFFD; that is why the primitives
refuse one instead of counting it.
. *No normalisation.* Counts are over the scalar values as given. NFC and NFD
forms of the same text have different counts, and nothing here normalises.
. *Integer range.* Lengths are exact: wasm `i32` (strings under 2^31 octets)
and JS `Number` (exact below 2^53).
. *Trusted base.*
** The interpreter: OCaml's `String.get_utf_8_uchar`, `Uchar.is_valid` and
`Buffer.add_utf_8_uchar`.
** JS: `String.prototype.charCodeAt` and `String.fromCodePoint`.
** Wasm: the hand-written decode and encode loops in `lib/codegen.ml`.
** Everything else (`stdlib/utf8.affine`) is AffineScript over these.

== Tests

`test/test_unicode_octets.ml` (in `dune runtest`) compiles and runs fixture
programs through the real CLI on the interp, Bun ESM, plain JS and core wasm.
It checks each backend against values from RFC 3629 and Unicode, not against
another backend, so two backends agreeing on a wrong answer still fail.

Covered:

* octet counts for 0- to 4-octet characters, plus a maximal 998-octet DEED line;
* `code_points` values and round trips;
* encoding at every width boundary (`0`, `0x7F`, `0x80`, `0x7FF`, `0x800`,
`0xFFFF`, `0x10000`, `0x10FFFF`);
* loud failure on surrogates, values above U+10FFFF, negative values, and
strings cut by `string_sub` (both a cut lead and a cut tail);
* the `stdlib/utf8.affine` functions where a backend runs them.

A backend whose host runtime is not on `PATH` is skipped with a printed SKIP
line. The CI `build` job provides Bun and Node, so all four backends run there.

The suite was mutation-checked:

* a wrong 2-octet width in the Bun helper fails the Bun-ESM checks;
* a missing surrogate check in the wasm encoder fails the wasm loud-failure
check.

== Findings (reported, not fixed here)

These came up while establishing ground truth. Each reproduces on `main` at
`ee211d3` without this change, and each is left for a separate change.

. *`len` / `string_get` / `string_sub` / `string_char_code_at` disagree
between backends* (table above). This is a cross-backend *semantic*
divergence, not a type-soundness hole: every result is a well-typed `Int` or
`String`. It is the same class as #560, where `show` disagreed between
backends and was fenced. Proposed fix, separately:
** make string indices octet offsets on every backend (the Rust model);
** make `string_sub` and `string_get` fail loudly off a character boundary;
** point code that needs characters at the API above.
. *Core-wasm heap overwrites string literals.* The heap pointer starts at a
fixed `1024` (`ensure_heap_ptr`), while string literals are laid out from
`2048` upward (`next_string_offset`). A program that allocates more than about
1 KiB overwrites its own literals. Repro: 60 statements of
`println("label_number_N" ++ " ok")` compiled to core wasm print 21 lines,
then a corrupted label (`label_number_22abe`), then trap with `Out of bounds
memory access`; the interpreter prints all 60. This is silent memory
corruption before the trap. Proposed fix: start the heap after the last data
segment (`align(next_string_offset, 8)`). `test/test_unicode_octets.ml` keeps
its success path allocation-free so that it tests the primitives, not this.
. *`affinescript eval` cannot run a self-recursive top-level function.* In
`lib/interp.ml`, `TopFn` builds the closure with `cl_env = env` *before*
binding the function's own name, so
`fn g(x: Int) -> Int { if x <= 0 { 0 } else { g(x - 1) + 2 } }` fails with
`Unbound variable: g`. Bun ESM gives `6` for `g(3)`.
. *`affinescript eval` rejects mutable locals.* `let mut k = 0; while k < 3 {
k = k + 1; }` fails with `Type mismatch: Expected mutable reference`, in
`main` or in any function.
. *`string::char_at` fails under `affinescript eval`* with `Unbound variable:
Some`, even with `use prelude::{Option, Some, None}` in the caller. The root
cause is not established.
. *The plain-JS backend lowers no string builtins* (`len`, `int_to_string`,
`string_sub`, …): each is a `ReferenceError` at run time, not a compile-time
refusal. It now lowers the three primitives above.
. *The interpreter's `println` shows a `String` as an escaped OCaml literal*
(`"\195\169"`, with quotes), while the other backends print the text.
. *Core wasm ignored a user function that shadows an intrinsic. Fixed by #841
(#836).* With `fn string_sub(s: String, a: Int, b: Int) -> Int { 7 }`, a call
`string_sub("x", 0, 1)` printed `7` on the interpreter and Bun ESM, but a heap
pointer (`1024`) on wasm. Every name-matched arm in `lib/codegen.ml` now
dispatches on `intrinsic_callee`, which skips the intrinsic when the program
defines the name (a `fn` with a body, or a `const`), while the deliberate WASI
lowerings of stdlib `extern fn`s still apply. The three Unicode primitives here
go through the same dispatch and are covered by `test/test_intrinsic_shadow.ml`
and `test/test_unicode_octets.ml` on every backend.
Loading
Loading