|
| 1 | +// SPDX-License-Identifier: CC-BY-SA-4.0 |
| 2 | +// SPDX-FileCopyrightText: 2026 hyperpolymath |
| 3 | += Unicode Strings and UTF-8 Octets Across Backends |
| 4 | +:toc: macro |
| 5 | +:toclevels: 2 |
| 6 | +:icons: font |
| 7 | + |
| 8 | +What `String` operations mean on each backend, and the additive API that has |
| 9 | +one meaning on every backend. Written for the estate DEED printer, which must |
| 10 | +count line length in UTF-8 octets (a DEED line is at most 998 octets, |
| 11 | +`deed.abnf` v1.3.0) and must never split a character. |
| 12 | + |
| 13 | +toc::[] |
| 14 | + |
| 15 | +== Ground truth before this change |
| 16 | + |
| 17 | +Measured on `main` at `ee211d3` (2026-12-01) by compiling and running probe |
| 18 | +programs through the real CLI: `affinescript eval` (interp), |
| 19 | +`compile --bun-esm` then `bun` (Bun ESM), `compile x.js` then `node` (plain |
| 20 | +JS), and `compile x.wasm` then `bun run` (core wasm, via Bun's WASI). The |
| 21 | +inputs mix 1-octet (`a`), 2-octet (`é` U+00E9), 3-octet (`漢` U+6F22) and |
| 22 | +4-octet (`🦜` U+1F99C) characters. |
| 23 | + |
| 24 | +[cols="2,2,2,2,2",options="header"] |
| 25 | +|=== |
| 26 | +| Operation | interp | Bun ESM | plain JS | core wasm |
| 27 | + |
| 28 | +| `len` on `a` / `é` / `漢` / `🦜` |
| 29 | +| 1 / 2 / 3 / 4 (UTF-8 octets) |
| 30 | +| 1 / 1 / 1 / 2 (UTF-16 code units) |
| 31 | +| not lowered: `ReferenceError: len is not defined` at run time |
| 32 | +| 1 / 2 / 3 / 4 (octets) |
| 33 | + |
| 34 | +| `len("aé漢🦜")` |
| 35 | +| 10 | 5 | `ReferenceError` | 10 |
| 36 | + |
| 37 | +| `string_length("🦜")` |
| 38 | +| 4 | 2 | `ReferenceError` | 4 |
| 39 | + |
| 40 | +| `string_get("🦜", 0)` then `char_to_int` |
| 41 | +| 240 (first octet, `0xF0`) |
| 42 | +| 55358 (lone high surrogate `0xD83E`) |
| 43 | +| `ReferenceError` |
| 44 | +| rejected at compile time (`string_get` not lowered) |
| 45 | + |
| 46 | +| `string_char_code_at("🦜", 0)` / `(…, 1)` |
| 47 | +| 240 / 159 (octets) | 55358 / 56732 (UTF-16 units) | `ReferenceError` | 240 / 159 |
| 48 | + |
| 49 | +| `string_sub("🦜x", 0, 1)` |
| 50 | +| one octet `0xF0`: ill-formed UTF-8 |
| 51 | +| one lone surrogate: ill-formed UTF-16 |
| 52 | +| `ReferenceError` |
| 53 | +| one octet `0xF0`: ill-formed UTF-8 |
| 54 | + |
| 55 | +| stdlib `string::length("🦜")` |
| 56 | +| 4 | 2 | `ReferenceError` (uses `len`) | stdlib modules do not link on wasm (unresolved import `string:substring`) |
| 57 | + |
| 58 | +| stdlib `string::char_at("🦜", 1)` |
| 59 | +| run-time error `Unbound variable: Some` (see Findings) | 56732 | `ReferenceError` | does not link |
| 60 | + |
| 61 | +| Char literal `'é'` |
| 62 | +4+| rejected by the lexer on every backend (`Invalid character literal`): a |
| 63 | +`Char` is one octet in the AST (`LitChar of char`) |
| 64 | +|=== |
| 65 | + |
| 66 | +Deno ESM was retired: `--deno-esm` and a `.deno.js` output are refused |
| 67 | +("Deno-ESM was removed"), and `lib/codegen_deno.ml` now emits Bun ESM only. |
| 68 | +The Bun-ESM column covers it. |
| 69 | + |
| 70 | +Summary: *index and length units differ by backend*. The interpreter and core |
| 71 | +wasm store a `String` as its UTF-8 octets and index by octet. Bun ESM stores a |
| 72 | +JS (UTF-16) string and indexes by UTF-16 code unit. The plain-JS backend does |
| 73 | +not lower the string builtins at all. `string_sub` can cut a character on |
| 74 | +every backend and yields a string that is not a sequence of Unicode scalar |
| 75 | +values. |
| 76 | + |
| 77 | +== The additive API |
| 78 | + |
| 79 | +Nothing above was changed: `len`, `string_get`, `string_sub`, `char_at` and |
| 80 | +`substring` keep their current per-backend meaning, because existing code |
| 81 | +depends on it. Three new primitives have *one* meaning on every backend: |
| 82 | + |
| 83 | +[cols="3,5",options="header"] |
| 84 | +|=== |
| 85 | +| Primitive | Meaning |
| 86 | + |
| 87 | +| `utf8_byte_length(s: String) -> Int` |
| 88 | +| The number of octets of the UTF-8 encoding of `s`. |
| 89 | + |
| 90 | +| `code_points(s: String) -> [Int]` |
| 91 | +| The Unicode scalar values of `s`, in order. |
| 92 | + |
| 93 | +| `string_from_code_points(cps: [Int]) -> String` |
| 94 | +| The string whose scalar values are `cps`: the inverse of `code_points`. |
| 95 | +|=== |
| 96 | + |
| 97 | +Code points are `Int`, not `Char`, because a `Char` is one octet on the |
| 98 | +interpreter and wasm and cannot hold U+1F99C. These primitives are intrinsics, |
| 99 | +registered in `lib/resolve.ml` and `lib/typecheck.ml` like `string_sub`, and |
| 100 | +lowered in `lib/interp.ml`, `lib/codegen_deno.ml` (Bun ESM), `lib/js_codegen.ml` |
| 101 | +(plain JS) and `lib/codegen.ml` (core wasm). |
| 102 | + |
| 103 | +`stdlib/utf8.affine` adds functions written in AffineScript on top of them: |
| 104 | + |
| 105 | +[cols="3,5",options="header"] |
| 106 | +|=== |
| 107 | +| Function | Meaning |
| 108 | + |
| 109 | +| `utf8_width(cp: Int) -> Int` |
| 110 | +| Octets in the UTF-8 encoding of one scalar value: 1, 2, 3 or 4. |
| 111 | + |
| 112 | +| `code_point_count(s: String) -> Int` |
| 113 | +| Number of scalar values in `s`. |
| 114 | + |
| 115 | +| `code_point_slice(s: String, start: Int, end: Int) -> String` |
| 116 | +| The scalar values with index in `[start, end)`, clamped. Never splits a |
| 117 | +character. |
| 118 | + |
| 119 | +| `code_points_within_octets(s: String, max_octets: Int) -> Int` |
| 120 | +| How many leading code points fit in `max_octets` octets. With that `k`, |
| 121 | +`code_point_slice(s, 0, k)` is the longest prefix that fits. |
| 122 | +|=== |
| 123 | + |
| 124 | +Which backend runs which part: |
| 125 | + |
| 126 | +[cols="3,1,1,1,1",options="header"] |
| 127 | +|=== |
| 128 | +| | interp | Bun ESM | plain JS | core wasm |
| 129 | + |
| 130 | +| the three primitives | yes | yes | yes | yes |
| 131 | +| `utf8_width`, `code_point_count`, `code_point_slice` | yes | yes | no (the backend has no `len`) | no (stdlib modules do not link) |
| 132 | +| `code_points_within_octets` | no (self-recursion, see Findings) | yes | no | no |
| 133 | +|=== |
| 134 | + |
| 135 | +=== Ill-formed input fails loudly |
| 136 | + |
| 137 | +Each primitive is defined only on well-formed input: |
| 138 | + |
| 139 | +* a `String` that is a sequence of Unicode scalar values; |
| 140 | +* an `[Int]` of values in `0..0x10FFFF` that excludes the surrogates |
| 141 | +`0xD800..0xDFFF`. |
| 142 | + |
| 143 | +On anything else it fails instead of guessing or substituting U+FFFD. The |
| 144 | +interpreter raises a run-time error, Bun ESM and plain JS throw, and core wasm |
| 145 | +traps (`unreachable`). That covers: |
| 146 | + |
| 147 | +* overlong forms, surrogates encoded in UTF-8, values above U+10FFFF and |
| 148 | +truncated sequences, on the octet backends; |
| 149 | +* lone surrogates, on the JS backends; |
| 150 | +* a string that `string_sub` cut in half, on every backend. |
| 151 | + |
| 152 | +The interpreter decodes with OCaml's strict `String.get_utf_8_uchar`. The wasm |
| 153 | +decoder (`gen_utf8_decode_loop` in `lib/codegen.ml`) rejects the same set of |
| 154 | +inputs. |
| 155 | + |
| 156 | +== Assumptions the octet count rests on |
| 157 | + |
| 158 | +A later formal proof of the DEED printer's round trip will rely on these. Each |
| 159 | +is *tested, not proved*. |
| 160 | + |
| 161 | +. *Abstract value.* A well-formed `String` denotes a finite sequence of Unicode |
| 162 | +scalar values. The three primitives are defined only on well-formed input and |
| 163 | +fail loudly otherwise; they never return a value for ill-formed input. |
| 164 | +. *Isomorphism.* `string_from_code_points(code_points(s)) == s` for every |
| 165 | +well-formed `s`, and `code_points(string_from_code_points(cps)) == cps` for |
| 166 | +every `cps` made only of scalar values. |
| 167 | +. *Octet law.* `utf8_byte_length(s)` equals the sum of `utf8_width(cp)` over |
| 168 | +`code_points(s)`. `utf8_width` follows RFC 3629 shortest form: 1 octet below |
| 169 | +`0x80`, 2 below `0x800`, 3 below `0x10000`, 4 otherwise. On the interpreter and |
| 170 | +wasm, the count is the stored byte length after validation. On the JS backends, |
| 171 | +it is computed from the decoded scalar values. |
| 172 | +. *Output equals count.* On Bun, writing a well-formed string as UTF-8 (`fs` |
| 173 | +with `"utf8"`, or `TextEncoder`) emits exactly `utf8_byte_length(s)` octets. |
| 174 | +On the interpreter and wasm, the stored bytes are the bytes written. A lone |
| 175 | +surrogate would be written as the 3-octet U+FFFD; that is why the primitives |
| 176 | +refuse one instead of counting it. |
| 177 | +. *No normalisation.* Counts are over the scalar values as given. NFC and NFD |
| 178 | +forms of the same text have different counts, and nothing here normalises. |
| 179 | +. *Integer range.* Lengths are exact: wasm `i32` (strings under 2^31 octets) |
| 180 | +and JS `Number` (exact below 2^53). |
| 181 | +. *Trusted base.* |
| 182 | +** The interpreter: OCaml's `String.get_utf_8_uchar`, `Uchar.is_valid` and |
| 183 | +`Buffer.add_utf_8_uchar`. |
| 184 | +** JS: `String.prototype.charCodeAt` and `String.fromCodePoint`. |
| 185 | +** Wasm: the hand-written decode and encode loops in `lib/codegen.ml`. |
| 186 | +** Everything else (`stdlib/utf8.affine`) is AffineScript over these. |
| 187 | + |
| 188 | +== Tests |
| 189 | + |
| 190 | +`test/test_unicode_octets.ml` (in `dune runtest`) compiles and runs fixture |
| 191 | +programs through the real CLI on the interp, Bun ESM, plain JS and core wasm. |
| 192 | +It checks each backend against values from RFC 3629 and Unicode, not against |
| 193 | +another backend, so two backends agreeing on a wrong answer still fail. |
| 194 | + |
| 195 | +Covered: |
| 196 | + |
| 197 | +* octet counts for 0- to 4-octet characters, plus a maximal 998-octet DEED line; |
| 198 | +* `code_points` values and round trips; |
| 199 | +* encoding at every width boundary (`0`, `0x7F`, `0x80`, `0x7FF`, `0x800`, |
| 200 | +`0xFFFF`, `0x10000`, `0x10FFFF`); |
| 201 | +* loud failure on surrogates, values above U+10FFFF, negative values, and |
| 202 | +strings cut by `string_sub` (both a cut lead and a cut tail); |
| 203 | +* the `stdlib/utf8.affine` functions where a backend runs them. |
| 204 | + |
| 205 | +A backend whose host runtime is not on `PATH` is skipped with a printed SKIP |
| 206 | +line. The CI `build` job provides Bun and Node, so all four backends run there. |
| 207 | + |
| 208 | +The suite was mutation-checked: |
| 209 | + |
| 210 | +* a wrong 2-octet width in the Bun helper fails the Bun-ESM checks; |
| 211 | +* a missing surrogate check in the wasm encoder fails the wasm loud-failure |
| 212 | +check. |
| 213 | + |
| 214 | +== Findings (reported, not fixed here) |
| 215 | + |
| 216 | +These came up while establishing ground truth. Each reproduces on `main` at |
| 217 | +`ee211d3` without this change, and each is left for a separate change. |
| 218 | + |
| 219 | +. *`len` / `string_get` / `string_sub` / `string_char_code_at` disagree |
| 220 | +between backends* (table above). This is a cross-backend *semantic* |
| 221 | +divergence, not a type-soundness hole: every result is a well-typed `Int` or |
| 222 | +`String`. It is the same class as #560, where `show` disagreed between |
| 223 | +backends and was fenced. Proposed fix, separately: |
| 224 | +** make string indices octet offsets on every backend (the Rust model); |
| 225 | +** make `string_sub` and `string_get` fail loudly off a character boundary; |
| 226 | +** point code that needs characters at the API above. |
| 227 | +. *Core-wasm heap overwrites string literals.* The heap pointer starts at a |
| 228 | +fixed `1024` (`ensure_heap_ptr`), while string literals are laid out from |
| 229 | +`2048` upward (`next_string_offset`). A program that allocates more than about |
| 230 | +1 KiB overwrites its own literals. Repro: 60 statements of |
| 231 | +`println("label_number_N" ++ " ok")` compiled to core wasm print 21 lines, |
| 232 | +then a corrupted label (`label_number_22abe`), then trap with `Out of bounds |
| 233 | +memory access`; the interpreter prints all 60. This is silent memory |
| 234 | +corruption before the trap. Proposed fix: start the heap after the last data |
| 235 | +segment (`align(next_string_offset, 8)`). `test/test_unicode_octets.ml` keeps |
| 236 | +its success path allocation-free so that it tests the primitives, not this. |
| 237 | +. *`affinescript eval` cannot run a self-recursive top-level function.* In |
| 238 | +`lib/interp.ml`, `TopFn` builds the closure with `cl_env = env` *before* |
| 239 | +binding the function's own name, so |
| 240 | +`fn g(x: Int) -> Int { if x <= 0 { 0 } else { g(x - 1) + 2 } }` fails with |
| 241 | +`Unbound variable: g`. Bun ESM gives `6` for `g(3)`. |
| 242 | +. *`affinescript eval` rejects mutable locals.* `let mut k = 0; while k < 3 { |
| 243 | +k = k + 1; }` fails with `Type mismatch: Expected mutable reference`, in |
| 244 | +`main` or in any function. |
| 245 | +. *`string::char_at` fails under `affinescript eval`* with `Unbound variable: |
| 246 | +Some`, even with `use prelude::{Option, Some, None}` in the caller. The root |
| 247 | +cause is not established. |
| 248 | +. *The plain-JS backend lowers no string builtins* (`len`, `int_to_string`, |
| 249 | +`string_sub`, …): each is a `ReferenceError` at run time, not a compile-time |
| 250 | +refusal. It now lowers the three primitives above. |
| 251 | +. *The interpreter's `println` shows a `String` as an escaped OCaml literal* |
| 252 | +(`"\195\169"`, with quotes), while the other backends print the text. |
| 253 | +. *Core wasm ignored a user function that shadows an intrinsic. Fixed by #841 |
| 254 | +(#836).* With `fn string_sub(s: String, a: Int, b: Int) -> Int { 7 }`, a call |
| 255 | +`string_sub("x", 0, 1)` printed `7` on the interpreter and Bun ESM, but a heap |
| 256 | +pointer (`1024`) on wasm. Every name-matched arm in `lib/codegen.ml` now |
| 257 | +dispatches on `intrinsic_callee`, which skips the intrinsic when the program |
| 258 | +defines the name (a `fn` with a body, or a `const`), while the deliberate WASI |
| 259 | +lowerings of stdlib `extern fn`s still apply. The three Unicode primitives here |
| 260 | +go through the same dispatch and are covered by `test/test_intrinsic_shadow.ml` |
| 261 | +and `test/test_unicode_octets.ml` on every backend. |
0 commit comments