Skip to content

Commit cb33fcd

Browse files
Merge branch 'main' into fix/833-interp-recursion-mut
Signed-off-by: Jonathan D.A. Jewell <6759885+hyperpolymath@users.noreply.github.com>
2 parents d2613c0 + ff3f08d commit cb33fcd

32 files changed

Lines changed: 3224 additions & 48 deletions

‎.machine_readable/descriptiles/STATE.deed‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,3 +257,14 @@ landed = [
257257
"docs: bindings/stdlib/alib roadmap Tracking sections de-staled to live umbrellas #446/#412/#413"
258258
]
259259
umbrella-446 = "stays open — STEP 1-3 done, STEP 4/5 long-running"
260+
261+
[[session-delta]]
262+
# Appended 2026-12-01 — core-wasm heap/literal overlap fix (#830).
263+
# Mirror entry only; soundness status is docs/SOUNDNESS.adoc (row #830).
264+
date = "2026-12-01"
265+
issue = "#830"
266+
landed = [
267+
"codegen: heap base computed after codegen as align8(end of last data segment); memory sized to cover it; module refused if heap base < data end (docs/WASM-MEMORY-LAYOUT.adoc)",
268+
"tests: test/test_wasm_heap_layout.ml (layout check, static layout, #829 repro + 40 KiB allocation + exhaustion under Bun WASI)",
269+
"audit: docs/reports/AUDIT-2026-12-01-backend-divergences.adoc; follow-ups #831 (string index units, owner decision), #832 (js builtins), #833 (eval), #834 (estate rebuilds)"
270+
]

‎docs/NAVIGATION.adoc‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ This guide helps you navigate the AffineScript repository structure.
5353
**Key specification documents:**
5454

5555
* link:ULTRAPLAN.adoc[Ultraplan — Mass Recon & Strategic Plan] - **NEW 2026-09-25** — ecosystem topology systemet→anytype→affinescript→faces, mathematical foundations, rename assessment, phased execution (do-nothing plan only)
56+
* link:decisions/0028-polonius-v1-decision.adoc[ADR-028: Borrow checking for v1 — ADR-022 or a recorded cut] - **PROPOSED 2026-12-01** — measured over-rejection, 15 unsound acceptances, options and a recommendation; the owner decides (#553, #563)
5657
* link:decisions/0027-systemet-rename-to-system-et.adoc[ADR-027: systemet→system-et Rename Assessment] - **NEW 2026-09-25** — blast radius, options, recommendation (Option A: keep systemet repo, display as system-et)
5758
* link:specs/affinescript-spec.md[AffineScript Specification] - Complete language spec
5859
* link:specs/SPEC.adoc[Core Specification] - Core language features

‎docs/SOUNDNESS.adoc‎

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
// Freshness stamp — a real main-ancestor commit (survives squash-merge); advance
55
// it (and --reseal) in any change that touches a soundness path. See "Keeping
66
// this honest" and tools/check-soundness-ledger.sh (property 4).
7-
:ground-truth-sha: 70180a1
7+
:ground-truth-sha: 84eca60
88
:ground-truth-date: 2026-12-01
99
:stamp-verified-by: tools/check-soundness-ledger.sh
1010
:toc: macro
@@ -292,25 +292,25 @@ core wasm; every wasm case fails on `4248912`. Also: an `extern fn` in scope
292292
keeps the lowering; the lowerings still run; `show`/`slice` are not captured;
293293
a local and an imported definition win)
294294

295-
| #833
296-
| The tree-walking interpreter — the oracle the compiled backends are compared
297-
against — runs the programs the checker accepts and agrees with Bun-ESM on
298-
them. It used to refuse a function that calls itself, one that calls a later
299-
declaration, any `let mut` / `const mut` assignment, and any use of an
300-
imported `Some` / `None` / `Ok` / `Err` (all loud). One shape was *silent*: an
301-
early `return` evaluated its operand and carried on, so
302-
`if c { return 1; } 2` yielded `2`. (The assignment arm also ignored a
303-
compound operator — `a += 5` would have stored `5` — which a
304-
`let mut` program could not reach, because the assignment failed first.) `affinescript eval` also type-checked
305-
with its own fold of `Typecheck.check_decl`, without the signature
306-
pre-registration of `Typecheck.check_program`, so it rejected forward and
307-
mutual references that `check` and `compile` accept; it now calls
308-
`check_program`. Not changed: `eval` still does not run the borrow checker
309-
(`check` and `compile` do), so it accepts programs they reject.
295+
| #830
296+
| Core-wasm heap allocations can no longer overwrite string literals. The
297+
heap-pointer global used to start at a fixed 1024 while literals were laid
298+
out from a fixed 2048, so a program that allocated more than ~1 KiB
299+
silently corrupted its own literals (#829's 60-line repro printed 21 lines,
300+
then `label_number_22abe`, then trapped). The heap base is now computed
301+
after code generation as the 8-aligned end of the last data segment, the
302+
initial memory covers it, and `generate_module` refuses (compile-time
303+
error) any module whose heap base lies below the end of static data. There
304+
is no `memory.grow`; exhausting the heap is an out-of-bounds trap, not a
305+
write into the literal region. Layout invariant:
306+
`docs/WASM-MEMORY-LAYOUT.adoc`.
310307
| `fixed`
311-
| `test/test_interp_eval.ml` (18 cases: each program passes the full frontend,
312-
then its interpreter output is compared with the expected lines and with the
313-
Bun-ESM output of the same program; all 18 fail on `4248912`).
308+
| `test/test_wasm_heap_layout.ml` (`test_wasm_heap_base_below_data_end_refused`
309+
— the gate refuses the old layout; `test_wasm_heap_after_literals_static`;
310+
`test_wasm_heap_repro_runs` and
311+
`test_wasm_heap_literals_intact_after_alloc` — run under Bun's WASI;
312+
`test_wasm_heap_exhaustion_traps`); `lib/codegen.ml`
313+
`memory_layout_of_datas` / `check_memory_layout`
314314
|===
315315

316316
== Still open — read before claiming "sound"

‎docs/UNICODE-STRINGS.adoc‎

Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
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

Comments
 (0)