From 882f5272f260618236614b988b60d1ed0faabad4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 14:12:39 +0000 Subject: [PATCH 1/8] feat(strings): backend-independent UTF-8 octet count and code-point view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `len`, `string_get` and `string_sub` index by UTF-8 octet on the interpreter and core wasm but by UTF-16 code unit on Bun-ESM (len("🦜") is 4 vs 2), and the plain-JS backend lowers none of them. Ground truth per backend is recorded in docs/UNICODE-STRINGS.adoc. Their meaning is unchanged here: existing code depends on it. Add three intrinsics with one meaning on every backend (interp, Bun-ESM, plain JS, core wasm): utf8_byte_length(s: String) -> Int octets of the UTF-8 encoding code_points(s: String) -> [Int] Unicode scalar values string_from_code_points(cps: [Int]) -> String inverse of code_points Each is defined only on well-formed input and fails loudly otherwise (run-time error / JS throw / wasm trap): a string cut mid-character by string_sub, a lone surrogate, an overlong or truncated UTF-8 sequence, or a non-scalar Int. The interpreter decodes with OCaml's strict String.get_utf_8_uchar; core wasm gets a matching strict decoder (gen_utf8_decode_loop) and encoder. stdlib/utf8.affine derives utf8_width, code_point_count, code_point_slice and code_points_within_octets in AffineScript. test/test_unicode_octets.ml runs fixtures through the real CLI on all four backends and checks each against RFC 3629 / Unicode values, plus loud failure on ill-formed input (28 cases; mutation-checked). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDfgDTxx9Bumfa2XXcQ --- docs/UNICODE-STRINGS.adoc | 252 ++++++++++++++++++++++ lib/codegen.ml | 176 +++++++++++++++ lib/codegen_deno.ml | 49 ++++- lib/int_div_classifier.ml | 2 +- lib/interp.ml | 68 ++++++ lib/js_codegen.ml | 35 ++- lib/resolve.ml | 2 + lib/typecheck.ml | 8 + stdlib/utf8.affine | 94 ++++++++ test/dune | 4 +- test/test_deno_builtins_consistency.ml | 2 + test/test_main.ml | 1 + test/test_unicode_octets.ml | 283 +++++++++++++++++++++++++ 13 files changed, 972 insertions(+), 4 deletions(-) create mode 100644 docs/UNICODE-STRINGS.adoc create mode 100644 stdlib/utf8.affine create mode 100644 test/test_unicode_octets.ml diff --git a/docs/UNICODE-STRINGS.adoc b/docs/UNICODE-STRINGS.adoc new file mode 100644 index 00000000..9a9cae99 --- /dev/null +++ b/docs/UNICODE-STRINGS.adoc @@ -0,0 +1,252 @@ +// 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. diff --git a/lib/codegen.ml b/lib/codegen.ml index 26a459fe..290a1507 100644 --- a/lib/codegen.ml +++ b/lib/codegen.ml @@ -612,6 +612,80 @@ let gen_box_zero_arg_variant (ctx : context) (tag : int) : (context * instr list LocalGet ptr; ]) +(** Strict UTF-8 decoding loop over the AS string at local [src] + ([len: i32][utf8 bytes...]), for the Unicode / UTF-8 octet primitives + (docs/UNICODE-STRINGS.adoc). For each scalar value it leaves it in local + [cp] and runs [on_cp] (straight-line code: it must not branch out of the + loop). An ill-formed sequence — a stray continuation or 0xC0/0xC1/0xF5+ + lead byte, a truncated sequence, a bad continuation byte, an overlong + form, a surrogate or a value above U+10FFFF — traps ([unreachable]), + exactly the inputs on which the interpreter's [String.get_utf_8_uchar] + and the JS lone-surrogate check fail. Returns the code and the context + with the loop's scratch locals allocated. *) +let gen_utf8_decode_loop (ctx : context) ~(src : int) ~(cp : int) + ~(on_cp : instr list) : context * instr list = + let (c1, slen) = alloc_local ctx "__u8_slen" in + let (c2, i) = alloc_local c1 "__u8_i" in + let (c3, b) = alloc_local c2 "__u8_b" in + let (c4, n) = alloc_local c3 "__u8_n" in + let (c5, k) = alloc_local c4 "__u8_k" in + let trap_if cond = cond @ [ If (BtEmpty, [ Unreachable ], []) ] in + let byte_at off = [ LocalGet src; LocalGet i; I32Add ] @ off @ [ I32Load8U (0, 4) ] in + (* lead byte -> (cp := payload bits; n := sequence length), else trap *) + let lead = + [ LocalGet b; I32Const 0x80l; I32LtU; + If (BtEmpty, + [ LocalGet b; LocalSet cp; I32Const 1l; LocalSet n ], + trap_if [ LocalGet b; I32Const 0xC2l; I32LtU ] @ + [ LocalGet b; I32Const 0xE0l; I32LtU; + If (BtEmpty, + [ LocalGet b; I32Const 0x1Fl; I32And; LocalSet cp; + I32Const 2l; LocalSet n ], + [ LocalGet b; I32Const 0xF0l; I32LtU; + If (BtEmpty, + [ LocalGet b; I32Const 0x0Fl; I32And; LocalSet cp; + I32Const 3l; LocalSet n ], + trap_if [ LocalGet b; I32Const 0xF5l; I32GeU ] @ + [ LocalGet b; I32Const 0x07l; I32And; LocalSet cp; + I32Const 4l; LocalSet n ]) ]) ]) ] + in + let continuation = + (* the whole sequence must lie inside the string *) + trap_if [ LocalGet i; LocalGet n; I32Add; LocalGet slen; I32GtU ] @ + [ I32Const 1l; LocalSet k; + Block (BtEmpty, [ Loop (BtEmpty, [ + LocalGet k; LocalGet n; I32GeU; BrIf 1; + LocalGet src; LocalGet i; I32Add; LocalGet k; I32Add; + I32Load8U (0, 4); LocalSet b; + LocalGet b; I32Const 0xC0l; I32And; I32Const 0x80l; I32Ne; + If (BtEmpty, [ Unreachable ], []); + LocalGet cp; I32Const 6l; I32Shl; + LocalGet b; I32Const 0x3Fl; I32And; I32Or; LocalSet cp; + LocalGet k; I32Const 1l; I32Add; LocalSet k; + Br 0 ]) ]) ] + in + let range_checks = + (* overlong 3-byte, surrogates *) + trap_if [ LocalGet n; I32Const 3l; I32Eq; + LocalGet cp; I32Const 0x800l; I32LtU; I32And ] @ + trap_if [ LocalGet cp; I32Const 0xD800l; I32GeU; + LocalGet cp; I32Const 0xDFFFl; I32LeU; I32And ] @ + (* overlong 4-byte, above U+10FFFF *) + trap_if [ LocalGet n; I32Const 4l; I32Eq; + LocalGet cp; I32Const 0x10000l; I32LtU; I32And ] @ + trap_if [ LocalGet cp; I32Const 0x10FFFFl; I32GtU ] + in + let code = + [ LocalGet src; I32Load (2, 0); LocalSet slen; + I32Const 0l; LocalSet i; + Block (BtEmpty, [ Loop (BtEmpty, + [ LocalGet i; LocalGet slen; I32GeU; BrIf 1 ] @ + byte_at [] @ [ LocalSet b ] @ + lead @ continuation @ range_checks @ on_cp @ + [ LocalGet i; LocalGet n; I32Add; LocalSet i; Br 0 ]) ]) ] + in + (c5, code) + (** Generate code for an expression, returning instructions and updated context *) let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = match expr with @@ -1471,6 +1545,108 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = let* (ctx_with_arg, arg_code) = gen_expr ctx (List.hd args) in Ok (ctx_with_arg, arg_code @ [I32Load (2, 0)]) + | ExprVar id when id.name = "utf8_byte_length" && List.length args = 1 -> + (* Unicode / UTF-8 octet primitives (docs/UNICODE-STRINGS.adoc). + A wasm String *is* its UTF-8 octets, so the count is the length + word — but only for a well-formed string, so validate first + (trapping like the interpreter errors) and then read it. *) + let* (c1, s_code) = gen_expr ctx (List.hd args) in + let (c2, src) = alloc_local c1 "__u8len_src" in + let (c3, cp) = alloc_local c2 "__u8len_cp" in + let (c4, scan) = gen_utf8_decode_loop c3 ~src ~cp ~on_cp:[] in + Ok (c4, s_code @ [ LocalSet src ] @ scan @ [ LocalGet src; I32Load (2, 0) ]) + + | ExprVar id when id.name = "code_points" && List.length args = 1 -> + (* Two strict decode passes: count the scalar values, allocate the + `[len: i32][i32 cells...]` array (the ExprArray layout), fill it. *) + let* (c1, s_code) = gen_expr ctx (List.hd args) in + let (c2, heap_idx) = ensure_heap_ptr c1 in + let (c3, src) = alloc_local c2 "__cps_src" in + let (c4, cp) = alloc_local c3 "__cps_cp" in + let (c5, cnt) = alloc_local c4 "__cps_cnt" in + let (c6, dst) = alloc_local c5 "__cps_dst" in + let (c7, j) = alloc_local c6 "__cps_j" in + let (c8, count_pass) = + gen_utf8_decode_loop c7 ~src ~cp + ~on_cp:[ LocalGet cnt; I32Const 1l; I32Add; LocalSet cnt ] in + let (c9, fill_pass) = + gen_utf8_decode_loop c8 ~src ~cp + ~on_cp:[ LocalGet dst; LocalGet j; I32Const 4l; I32Mul; I32Add; + LocalGet cp; I32Store (2, 4); + LocalGet j; I32Const 1l; I32Add; LocalSet j ] in + Ok (c9, + s_code @ [ LocalSet src; I32Const 0l; LocalSet cnt ] @ count_pass @ + [ GlobalGet heap_idx; LocalSet dst; + GlobalGet heap_idx; I32Const 4l; + LocalGet cnt; I32Const 4l; I32Mul; I32Add; I32Add; + GlobalSet heap_idx; + LocalGet dst; LocalGet cnt; I32Store (2, 0); + I32Const 0l; LocalSet j ] @ fill_pass @ [ LocalGet dst ]) + + | ExprVar id when id.name = "string_from_code_points" + && List.length args = 1 -> + (* Inverse of code_points: validate every cell is a Unicode scalar + value (trap otherwise, like the interpreter's error), sum the + UTF-8 widths, allocate `[len][bytes]`, encode. *) + let* (c1, a_code) = gen_expr ctx (List.hd args) in + let (c2, heap_idx) = ensure_heap_ptr c1 in + let (c3, arr) = alloc_local c2 "__sfc_arr" in + let (c4, cnt) = alloc_local c3 "__sfc_cnt" in + let (c5, j) = alloc_local c4 "__sfc_j" in + let (c6, v) = alloc_local c5 "__sfc_v" in + let (c7, w) = alloc_local c6 "__sfc_w" in + let (c8, dst) = alloc_local c7 "__sfc_dst" in + let (c9, pos) = alloc_local c8 "__sfc_pos" in + let over_cells body = + [ I32Const 0l; LocalSet j; + Block (BtEmpty, [ Loop (BtEmpty, + [ LocalGet j; LocalGet cnt; I32GeS; BrIf 1; + LocalGet arr; LocalGet j; I32Const 4l; I32Mul; I32Add; + I32Load (2, 4); LocalSet v ] @ body @ + [ LocalGet j; I32Const 1l; I32Add; LocalSet j; Br 0 ]) ]) ] in + let validate = + [ LocalGet v; I32Const 0l; I32LtS; + LocalGet v; I32Const 0x10FFFFl; I32GtS; I32Or; + LocalGet v; I32Const 0xD800l; I32GeS; + LocalGet v; I32Const 0xDFFFl; I32LeS; I32And; I32Or; + If (BtEmpty, [ Unreachable ], []) ] in + (* width = 1 + [v >= 0x80] + [v >= 0x800] + [v >= 0x10000] *) + let add_width = + [ LocalGet w; I32Const 1l; I32Add; + LocalGet v; I32Const 0x80l; I32GeS; I32Add; + LocalGet v; I32Const 0x800l; I32GeS; I32Add; + LocalGet v; I32Const 0x10000l; I32GeS; I32Add; LocalSet w ] in + let put off byte = + [ LocalGet dst; LocalGet pos; I32Add ] @ byte @ [ I32Store8 (0, 4 + off) ] in + let cont shift = + [ LocalGet v; I32Const (Int32.of_int shift); I32ShrU; + I32Const 0x3Fl; I32And; I32Const 0x80l; I32Or ] in + let lead mark shift = + [ LocalGet v; I32Const (Int32.of_int shift); I32ShrU; + I32Const mark; I32Or ] in + let advance k = [ LocalGet pos; I32Const k; I32Add; LocalSet pos ] in + let encode = + [ LocalGet v; I32Const 0x80l; I32LtU; + If (BtEmpty, put 0 [ LocalGet v ] @ advance 1l, + [ LocalGet v; I32Const 0x800l; I32LtU; + If (BtEmpty, put 0 (lead 0xC0l 6) @ put 1 (cont 0) @ advance 2l, + [ LocalGet v; I32Const 0x10000l; I32LtU; + If (BtEmpty, + put 0 (lead 0xE0l 12) @ put 1 (cont 6) @ put 2 (cont 0) + @ advance 3l, + put 0 (lead 0xF0l 18) @ put 1 (cont 12) @ put 2 (cont 6) + @ put 3 (cont 0) @ advance 4l) ]) ]) ] in + Ok (c9, + a_code @ [ LocalSet arr; LocalGet arr; I32Load (2, 0); LocalSet cnt; + I32Const 0l; LocalSet w ] @ + over_cells (validate @ add_width) @ + [ GlobalGet heap_idx; LocalSet dst; + GlobalGet heap_idx; I32Const 4l; LocalGet w; I32Add; I32Add; + GlobalSet heap_idx; + LocalGet dst; LocalGet w; I32Store (2, 0); + I32Const 0l; LocalSet pos ] @ + over_cells encode @ [ LocalGet dst ]) + | ExprVar id when id.name = "string_char_code_at" && List.length args = 2 -> (* PHASE-F string-wall slice 1 (proposals/MIGRATION-PLAN.adoc diff --git a/lib/codegen_deno.ml b/lib/codegen_deno.ml index 8d23be6c..6b7d90c0 100644 --- a/lib/codegen_deno.ml +++ b/lib/codegen_deno.ml @@ -612,6 +612,46 @@ const __as_concat = (a, b) => Array.isArray(a) ? a.concat(b) : (a + b); const __as_strSub = (s, start, n) => String(s).slice(start, start + n); const __as_strGet = (s, i) => String(s)[i]; const __as_strFind = (s, n) => String(s).indexOf(n); +// Unicode / UTF-8 octet primitives (docs/UNICODE-STRINGS.adoc). A JS string +// is UTF-16; these view it as its Unicode scalar values and count the octets +// of its UTF-8 encoding, so they agree with the interpreter and wasm (which +// store UTF-8). A lone surrogate is not a scalar value and has no UTF-8 +// encoding: every primitive throws on one rather than substitute U+FFFD. +const __as_codePoints = (s, who) => { + s = String(s); + const out = []; + for (let i = 0; i < s.length; i++) { + const c = s.charCodeAt(i); + if (c >= 0xD800 && c <= 0xDBFF && i + 1 < s.length) { + const d = s.charCodeAt(i + 1); + if (d >= 0xDC00 && d <= 0xDFFF) { + out.push(((c - 0xD800) << 10) + (d - 0xDC00) + 0x10000); i++; continue; + } + } + if (c >= 0xD800 && c <= 0xDFFF) { + throw new Error(`${who ?? "code_points"}: lone surrogate at UTF-16 index ${i} (the string is not a sequence of Unicode scalar values; was it cut mid-character by string_sub?)`); + } + out.push(c); + } + return out; +}; +const __as_utf8Width = (cp) => (cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4); +const __as_utf8ByteLength = (s) => { + let n = 0; + for (const cp of __as_codePoints(s, "utf8_byte_length")) n += __as_utf8Width(cp); + return n; +}; +const __as_stringFromCodePoints = (cps) => { + let s = ""; + for (let i = 0; i < cps.length; i++) { + const n = cps[i]; + if (!Number.isInteger(n) || n < 0 || n > 0x10FFFF || (n >= 0xD800 && n <= 0xDFFF)) { + throw new Error(`string_from_code_points: ${n} at index ${i} is not a Unicode scalar value (0..0x10FFFF excluding surrogates)`); + } + s += String.fromCodePoint(n); + } + return s; +}; const __as_charToInt = (c) => String(c).codePointAt(0); const __as_intToChar = (n) => String.fromCodePoint(n); const __as_strCharCodeAt = (s, i) => (i >= 0 && i < s.length ? s.charCodeAt(i) : -1); @@ -1244,6 +1284,13 @@ let () = b "string_get" (fun a -> Printf.sprintf "__as_strGet(%s, %s)" (arg 0 a) (arg 1 a)); b "string_sub" (fun a -> Printf.sprintf "__as_strSub(%s, %s, %s)" (arg 0 a) (arg 1 a) (arg 2 a)); b "string_find" (fun a -> Printf.sprintf "__as_strFind(%s, %s)" (arg 0 a) (arg 1 a)); + (* Unicode / UTF-8 octet primitives (docs/UNICODE-STRINGS.adoc): unlike + `len`/`string_get`/`string_sub` above (UTF-16 code units on this + backend), these mean the same on every backend. *) + b "utf8_byte_length" (fun a -> Printf.sprintf "__as_utf8ByteLength(%s)" (arg 0 a)); + b "code_points" (fun a -> Printf.sprintf "__as_codePoints(%s)" (arg 0 a)); + b "string_from_code_points" + (fun a -> Printf.sprintf "__as_stringFromCodePoints(%s)" (arg 0 a)); b "to_lowercase" (fun a -> Printf.sprintf "String(%s).toLowerCase()" (arg 0 a)); b "to_uppercase" (fun a -> Printf.sprintf "String(%s).toUpperCase()" (arg 0 a)); b "trim" (fun a -> Printf.sprintf "String(%s).trim()" (arg 0 a)); @@ -1574,7 +1621,7 @@ let builtins_for ctx = let int_returning_builtins = [ "len"; "string_find"; "string_char_code_at"; "char_to_int"; - "string_length" ] + "string_length"; "utf8_byte_length" ] (* Conservative "is this expression provably an [Int]?" Used only to decide whether a `/` should truncate; a [false] is always safe (keeps `/`). *) diff --git a/lib/int_div_classifier.ml b/lib/int_div_classifier.ml index 3e3fe7f1..d47c6450 100644 --- a/lib/int_div_classifier.ml +++ b/lib/int_div_classifier.ml @@ -50,7 +50,7 @@ let pat_var_name : pattern -> string option = function Option.) *) let int_returning_builtins = [ "len"; "string_find"; "string_char_code_at"; "char_to_int"; - "string_length" ] + "string_length"; "utf8_byte_length" ] (* ---------------------------------------------------------------------- * * Mutable per-pass state diff --git a/lib/interp.ml b/lib/interp.ml index b850b647..96169a83 100644 --- a/lib/interp.ml +++ b/lib/interp.ml @@ -583,6 +583,26 @@ and apply_function (func : value) (args : value list) : value result = | _ -> Error (TypeMismatch "Expected function") (** Create initial environment with builtins *) +(** Decode a UTF-8 byte string to its Unicode scalar values, strictly. + [Error] names the first ill-formed byte offset; see the [utf8_byte_length] + / [code_points] builtins below and docs/UNICODE-STRINGS.adoc. *) +let utf8_scalars ~who (s : string) : int list result = + let n = String.length s in + let rec go i acc = + if i >= n then Ok (List.rev acc) + else + let d = String.get_utf_8_uchar s i in + if Uchar.utf_decode_is_valid d then + go (i + Uchar.utf_decode_length d) + (Uchar.to_int (Uchar.utf_decode_uchar d) :: acc) + else + Error (RuntimeError (Printf.sprintf + "%s: ill-formed UTF-8 at byte %d (the string is not a sequence of \ + Unicode scalar values; was it cut mid-character by string_sub?)" + who i)) + in + go 0 [] + let create_initial_env () : env = let builtins = [ (* -- Console I/O -------------------------------------------------------- *) @@ -647,6 +667,54 @@ let create_initial_env () : env = Ok (VString (String.sub s start' length')) | _ -> Error (TypeMismatch "string_sub expects (String, Int, Int)") )); + (* -- Unicode / UTF-8 octet primitives (docs/UNICODE-STRINGS.adoc) ------- + The backend-independent Unicode surface. A String's meaning here is its + sequence of Unicode scalar values; these three primitives are the only + trusted ones (stdlib/utf8.affine derives the rest): + utf8_byte_length s = number of octets of the UTF-8 encoding of s + code_points s = the scalar values of s, in order + string_from_code_points = the inverse of code_points + The interpreter stores a String as its UTF-8 bytes, so the octet count is + String.length — *after* checking the bytes are well-formed UTF-8. An + ill-formed string (e.g. `string_sub("🦜", 0, 1)`) has no UTF-8 octet + count, so every primitive fails loudly rather than guess; the Bun-ESM, + JS and wasm lowerings fail on the same inputs. Decoding is + OCaml's strict String.get_utf_8_uchar (rejects overlong forms, + surrogates, > U+10FFFF and truncated sequences). *) + ("utf8_byte_length", VBuiltin ("utf8_byte_length", fun args -> + match args with + | [VString s] -> + (match utf8_scalars ~who:"utf8_byte_length" s with + | Ok _ -> Ok (VInt (String.length s)) + | Error e -> Error e) + | _ -> Error (TypeMismatch "utf8_byte_length expects String") + )); + ("code_points", VBuiltin ("code_points", fun args -> + match args with + | [VString s] -> + (match utf8_scalars ~who:"code_points" s with + | Ok cps -> Ok (VArray (Array.of_list (List.map (fun c -> VInt c) cps))) + | Error e -> Error e) + | _ -> Error (TypeMismatch "code_points expects String") + )); + ("string_from_code_points", VBuiltin ("string_from_code_points", fun args -> + match args with + | [VArray cps] -> + let buf = Buffer.create (Array.length cps) in + let rec go i = + if i >= Array.length cps then Ok (VString (Buffer.contents buf)) + else match cps.(i) with + | VInt n when Uchar.is_valid n -> + Buffer.add_utf_8_uchar buf (Uchar.of_int n); go (i + 1) + | VInt n -> + Error (RuntimeError (Printf.sprintf + "string_from_code_points: %d at index %d is not a Unicode \ + scalar value (0..0x10FFFF excluding surrogates)" n i)) + | _ -> Error (TypeMismatch "string_from_code_points expects [Int]") + in + go 0 + | _ -> Error (TypeMismatch "string_from_code_points expects [Int]") + )); ("string_find", VBuiltin ("string_find", fun args -> match args with | [VString haystack; VString needle] -> diff --git a/lib/js_codegen.ml b/lib/js_codegen.ml index ce20cbd7..6e7b8b68 100644 --- a/lib/js_codegen.ml +++ b/lib/js_codegen.ml @@ -78,6 +78,38 @@ const read_line = () => { __as_stdin_off = nl + 1; return r; }; +// Unicode / UTF-8 octet primitives (docs/UNICODE-STRINGS.adoc): the same +// contract as the interpreter, Bun-ESM and wasm. A lone surrogate is not a +// Unicode scalar value, so each primitive throws on one. +const code_points = (s) => { + s = String(s); + const out = []; + for (let i = 0; i < s.length; i++) { + const c = s.charCodeAt(i); + if (c >= 0xD800 && c <= 0xDBFF && i + 1 < s.length) { + const d = s.charCodeAt(i + 1); + if (d >= 0xDC00 && d <= 0xDFFF) { out.push(((c - 0xD800) << 10) + (d - 0xDC00) + 0x10000); i++; continue; } + } + if (c >= 0xD800 && c <= 0xDFFF) throw new Error("code_points: lone surrogate at UTF-16 index " + i); + out.push(c); + } + return out; +}; +const utf8_byte_length = (s) => { + let n = 0; + for (const cp of code_points(s)) n += cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4; + return n; +}; +const string_from_code_points = (cps) => { + let s = ""; + for (let i = 0; i < cps.length; i++) { + const n = cps[i]; + if (!Number.isInteger(n) || n < 0 || n > 0x10FFFF || (n >= 0xD800 && n <= 0xDFFF)) + throw new Error("string_from_code_points: " + n + " at index " + i + " is not a Unicode scalar value"); + s += String.fromCodePoint(n); + } + return s; +}; // ---- end runtime ---- |} @@ -649,7 +681,8 @@ let generate (program : program) (symbols : Symbol.t) : string = constructors named Some/None/Ok/Err are filtered before [claim]. *) List.iter (fun n -> Hashtbl.replace top_names n "") [ "Some"; "None"; "Ok"; "Err"; "Unit"; "print"; "println"; - "__as_stdin_buf"; "__as_stdin_off"; "read_line" ]; + "__as_stdin_buf"; "__as_stdin_off"; "read_line"; + "code_points"; "utf8_byte_length"; "string_from_code_points" ]; let claim name signature = match Hashtbl.find_opt top_names name with | None -> Hashtbl.replace top_names name signature; true diff --git a/lib/resolve.ml b/lib/resolve.ml index b45ddd52..009e96cd 100644 --- a/lib/resolve.ml +++ b/lib/resolve.ml @@ -73,6 +73,8 @@ let seed_builtins (symbols : Symbol.t) : unit = def "string_char_code_at"; def "string_from_char_code"; def "to_lowercase"; def "to_uppercase"; def "trim"; def "int_to_string"; def "float_to_string"; def "string_length"; + (* Unicode / UTF-8 octet primitives (docs/UNICODE-STRINGS.adoc) *) + def "utf8_byte_length"; def "code_points"; def "string_from_code_points"; (* STDLIB-04e (Refs #332): `string_to_int` typed-alias for `parse_int` *) def "string_to_int"; def "parse_int"; def "parse_float"; diff --git a/lib/typecheck.ml b/lib/typecheck.ml index 96af4cfa..8bd29716 100644 --- a/lib/typecheck.ml +++ b/lib/typecheck.ml @@ -2042,6 +2042,14 @@ let register_builtins (ctx : context) : unit = bind_var ctx "float" (TArrow (ty_int, QOmega, ty_float, EPure)); bind_var ctx "float_to_string" (TArrow (ty_float, QOmega, ty_string, EPure)); bind_var ctx "string_length" (TArrow (ty_string, QOmega, ty_int, EPure)); + (* Unicode / UTF-8 octet primitives — backend-independent by contract + (docs/UNICODE-STRINGS.adoc). Code points are [Int] (Unicode scalar + values), not [Char]: Char is one octet on the interpreter and wasm. *) + bind_var ctx "utf8_byte_length" (TArrow (ty_string, QOmega, ty_int, EPure)); + bind_var ctx "code_points" + (TArrow (ty_string, QOmega, TApp (TCon "Array", [ty_int]), EPure)); + bind_var ctx "string_from_code_points" + (TArrow (TApp (TCon "Array", [ty_int]), QOmega, ty_string, EPure)); bind_var ctx "sqrt" (TArrow (ty_float, QOmega, ty_float, EPure)); bind_var ctx "abs" int_binop; bind_var ctx "max" int_binop; diff --git a/stdlib/utf8.affine b/stdlib/utf8.affine new file mode 100644 index 00000000..3691e4ac --- /dev/null +++ b/stdlib/utf8.affine @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 hyperpolymath +// +// AffineScript Standard Library - Unicode strings as scalar values and +// UTF-8 octets, with the same meaning on every backend. +// +// Contract and per-backend ground truth: docs/UNICODE-STRINGS.adoc. +// +// Why this module exists: `len`, `string_get` and `string_sub` do NOT mean +// the same thing on every backend. They count UTF-8 octets on the +// interpreter and wasm, but UTF-16 code units on Bun-ESM, so +// `len("🦜")` is 4 on one backend and 2 on another. Code that must count +// octets (a DEED line is at most 998 octets) or must never split a character +// should use only this module and the three primitives it rests on: +// +// 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 inverse of code_points +// +// Code points are Int, not Char: a Char is one octet on the interpreter and +// wasm, so it cannot hold U+1F99C. +// +// Each primitive is defined only on well-formed input (a String that is a +// sequence of scalar values; an [Int] of values in 0..0x10FFFF excluding the +// surrogates D800..DFFF). On anything else it fails loudly (runtime error, +// JS exception or wasm trap) on every backend instead of guessing. A String +// produced by `string_sub` that cuts a character in half is NOT well-formed. +// +// Backends: the three primitives are lowered on the interpreter, Bun-ESM, +// plain JS and core wasm. The functions below are AffineScript, so they run +// wherever a backend can link a stdlib module and supports `len`/`slice` on +// arrays (interpreter and Bun-ESM today). + +// ============================================================================ +// Per-code-point octet width +// ============================================================================ + +/// Number of octets in the UTF-8 encoding of one scalar value `cp` +/// (1 for U+0000..U+007F, 2 up to U+07FF, 3 up to U+FFFF, 4 beyond). +/// Total over all Int; only meaningful for a scalar value. +pub fn utf8_width(cp: Int) -> Int { + if cp < 128 { + 1 + } else { + if cp < 2048 { + 2 + } else { + if cp < 65536 { 3 } else { 4 } + } + } +} + +// ============================================================================ +// Code-point view +// ============================================================================ + +/// Number of Unicode scalar values in `s` (not octets, not UTF-16 units). +pub fn code_point_count(s: String) -> Int { + len(code_points(s)) +} + +/// The substring of `s` holding the scalar values with index in +/// [start, end), counted in code points. Never splits a character. Indices +/// are clamped to 0..code_point_count(s); an empty range gives "". +pub fn code_point_slice(s: String, start: Int, end: Int) -> String { + let cps = code_points(s); + let n = len(cps); + let lo = if start < 0 { 0 } else { if start > n { n } else { start } }; + let hi = if end < lo { lo } else { if end > n { n } else { end } }; + string_from_code_points(slice(cps, lo, hi)) +} + +// The largest k >= i such that cps[i..k) fits in `room` octets. Structural +// recursion on n - i. (Defined before its caller: AffineScript resolves +// top-level names in declaration order.) +fn code_points_fit_from(cps: [Int], n: Int, i: Int, room: Int) -> Int { + if i >= n { + i + } else { + let w = utf8_width(cps[i]); + if w > room { i } else { code_points_fit_from(cps, n, i + 1, room - w) } + } +} + +/// The number of leading code points of `s` whose UTF-8 encoding fits in +/// `max_octets` octets. `code_point_slice(s, 0, k)` with that `k` is the +/// longest prefix of `s` that fits without splitting a character. +pub fn code_points_within_octets(s: String, max_octets: Int) -> Int { + let cps = code_points(s); + code_points_fit_from(cps, len(cps), 0, max_octets) +} diff --git a/test/dune b/test/dune index 4c5bb097..3621b398 100644 --- a/test/dune +++ b/test/dune @@ -6,4 +6,6 @@ (source_tree e2e) (source_tree ../examples) (source_tree ../stdlib) - (file ../lib/codegen_deno.ml))) + (file ../lib/codegen_deno.ml) + ; test_unicode_octets drives the real CLI on every backend + ../bin/main.exe)) diff --git a/test/test_deno_builtins_consistency.ml b/test/test_deno_builtins_consistency.ml index 788bdd53..fbbb205f 100644 --- a/test/test_deno_builtins_consistency.ml +++ b/test/test_deno_builtins_consistency.ml @@ -88,6 +88,8 @@ let codegen_only_names = "float"; "atan2"; "pow_float"; "string_length"; "string_sub"; "string_get"; "string_find"; "string_char_code_at"; "string_from_char_code"; + (* Unicode / UTF-8 octet primitives (docs/UNICODE-STRINGS.adoc) *) + "utf8_byte_length"; "code_points"; "string_from_code_points"; "to_lowercase"; "to_uppercase"; "trim"; "http_request"; "hpm_json_array_get"; "hpm_json_array_len"; "hpm_json_bool"; diff --git a/test/test_main.ml b/test/test_main.ml index b87c8e62..9282f679 100644 --- a/test/test_main.ml +++ b/test/test_main.ml @@ -35,6 +35,7 @@ let () = ("Int-div on JS-text backend (#478)", Test_int_div_js.tests); ("Deno builtins ↔ stdlib decls consistency", Test_deno_builtins_consistency.tests); ("Bun integer block scope", Test_int_scope_bun.tests); + ("Unicode strings / UTF-8 octets, cross-backend", Test_unicode_octets.tests); ("Same cube: faces compile alike (#601)", Test_same_cube.tests); ("float_to_string format (#643)", Test_float_format.tests); ("ESM runtime pruning", Test_runtime_prune.tests); diff --git a/test/test_unicode_octets.ml b/test/test_unicode_octets.ml new file mode 100644 index 00000000..a5d4b414 --- /dev/null +++ b/test/test_unicode_octets.ml @@ -0,0 +1,283 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(* SPDX-FileCopyrightText: 2026 hyperpolymath *) + +(** Cross-backend semantics of the Unicode / UTF-8 octet primitives + (docs/UNICODE-STRINGS.adoc): [utf8_byte_length], [code_points], + [string_from_code_points] and the stdlib/utf8.affine functions on top. + + Every backend is checked against the *specification* (RFC 3629 octet + widths, Unicode scalar values), not against another backend, so two + backends that agreed on a wrong answer would still fail. Each AffineScript + program prints "