Skip to content

fix(runtime): a Char holds any u32 on every lane; U+FFFD only at text edges - #1411

Merged
nicolas-abril merged 3 commits into
bendlang:mainfrom
oxura:fix/1080-unicode-scalar-construction
Oct 13, 2026
Merged

nicolas-abril merged 3 commits into
bendlang:mainfrom
oxura:fix/1080-unicode-scalar-construction

Conversation

@oxura

@oxura oxura commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1080.

A Char holds any u32, on every lane. Char.to_u32(Char.from_u32(n)) gives back n for every n. Interp, JS and C now agree. Before this change, interp and JS stopped with bend: 55296 is not a Unicode scalar value, and C wrote invalid UTF-8 (ED A0 80) with exit 0. A non-scalar is replaced with U+FFFD only where text leaves Bend.

  • Values: Char.from_u32 and Char.to_u32 are unchanged. The interpreter already kept such Chars exact; it shows them as \u{d800}.
  • JS: a valid Char is still one code point in a JS string. A non-scalar Char is stored as four units in the DC00-DFFF range that carry the full u32, so it can't merge with a neighbour (a D800 next to a DC00 stays two Chars). char_new/char_code/char_len read and write this form. String.length counts it as one Char. Appending is still h + t.
  • Edges: print, file/socket writes (io_bytes), compiled-module returns, FFI/host values, Process.run argv/stdin and get_env names get U+FFFD. The C writer (io_utf8) does the same. A host string with a lone surrogate comes in as U+FFFD.
  • Tests: new show/char_any_code, io/print_non_scalar, io/process_run_non_scalar. io/marshal_char_scalar, io/marshal_string_scalar and show/string_escape were updated (no more exit 1).

Not covered: a host value that nests Strings (for example a List(String) returned from a compiled module) is passed through without conversion. Effects that build text call str_out/io_bytes themselves.

comp.ts: 63,391 -> 63,722 ttok (cap 64,000).

@nicolas-abril
nicolas-abril force-pushed the fix/1080-unicode-scalar-construction branch from babcca2 to 4e18eac Compare October 13, 2026 11:34
@nicolas-abril

Copy link
Copy Markdown
Collaborator

Rebased on main f60b6ee and pushed 4e18eac (your commit kept as db210d4, one small commit on top).

Rebase. #1506 removed js_marshal: a host Nat is now a plain number, and nat_in checks only top-level export params and foreign answers. So the deep ADT/Array/function walk in this PR had nothing to attach to. The Char/String checks now go in the same two places as nat_in: host_nat became host_in, which returns nat_in, char_in or str_in. Nested Chars and Strings inside ADTs or Arrays are not checked, the same as nested Nats. Export return values are not checked either, since compiled code can no longer build an invalid Char. The GUIDE.md sentence was dropped because GUIDE.md is at 7998/8000 ttok.

Simplify. str_in finds a lone surrogate with /\p{Cs}/u and reports it through char_new. char_in destructures to one code point. Messages are unchanged. The typeof check is gone, matching U32 and ADT params, which are not type-checked at the boundary either.

Review. No bugs found. The C char_new on non-constant Chr, the term_const change and ERR_CHRS are as in your commit.

Checks (macOS): gates repo 54/54, ping 55/55, test 1616/1616, perf 124/124; comp.ts 63,703 ttok (main 63,299). The issue's surrogate.bend now exits 1 with bend: 55296 is not a Unicode scalar value in interp, JS and native. A compiled .mjs rejects a\uD800, \uDC00\uD800, ab and "", and accepts astral strings, under both bun and node. Not run: Linux, CUDA, Metal.

Unsupervised AI review (Claude), on behalf of @nicolas-abril.

@oxura

oxura commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for rebasing and for the detailed boundary contract. I exercised the updated head 4e18eac on Linux x64: tests/reg/unicode_scalar.bend prints 55295, 57344, 1114111 in the interpreter, emitted JavaScript under Bun, and the native binary. tests/reg/unicode_surrogate_high.bend rejects 57343 with the same Unicode-scalar diagnostic and exit 1 in all three lanes. The repository gate passes 54/54. I did not run CUDA, Metal, the mini-cluster test/perf gates, or a fresh Node host-marshalling check. No additional patch pushed; nested host values remain outside the documented top-level boundary, as described in your rebase note.

…s Bend (bendlang#1080)

JS keeps a Char that is no Unicode scalar (a surrogate, past U+10FFFF) as
0xDC00 and three 11-bit pieces, so Char.to_u32 reads back the code put in
and D800, DC00 built apart stay two Chars. Text written, handed to a foreign
def or returned from a library export gets U+FFFD for such a Char (str_out);
a host's lone surrogate comes in as U+FFFD (str_in). C writes U+FFFD in
io_utf8 instead of the raw bytes. The interpreter already kept exact codes.
@nicolas-abril
nicolas-abril force-pushed the fix/1080-unicode-scalar-construction branch from 4e18eac to 88fb722 Compare October 13, 2026 15:23
@nicolas-abril nicolas-abril changed the title fix(runtime): enforce Unicode scalars at construction and JS boundaries fix(runtime): a Char holds any u32 on every lane; U+FFFD only at text edges Oct 13, 2026
@nicolas-abril

Copy link
Copy Markdown
Collaborator

Rewrote this PR (head 4957361, rebased on main f846cb5). The old version rejected non-scalar Chars when they were created. Now every lane keeps the exact u32, and U+FFFD appears only where text leaves Bend. The description is updated.

Gates at 4957361 (mini cluster, run from macOS): repo 54/54, ping 57/57, test 1617/1617, perf 124/124.
Checked by hand: interp, bun, node and C give the same output for the new and changed tests. Lexer bench (JS): same md5, bun 41.6-42.1 s vs main 40.5-41.7 s, node 20.0-20.1 s vs main 21.2-21.4 s.
Not run: safe.ts --verdict (no BendTT binary here; bend.ts is untouched), Linux, CUDA, Metal. Process.run fails under Node on main as well (Worker is not defined), so the new process test was only checked on bun and C.

Unsupervised AI review.

@oxura

oxura commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

Linux x64 verification on the rewritten head 4957361, not the superseded scalar-rejection version:

  • All six changed/new fixtures (char_any_code, string_escape, print_non_scalar, process_run_non_scalar, marshal_char_scalar, marshal_string_scalar) matched their #| output under the CLI interpreter and emitted JS on Bun 1.3.13.
  • The four non-foreign fixtures also matched under emitted native C (one thread). The marshaling fixtures import JS only and have no .c counterparts; attempting native emission correctly reported no .c import: echo, so I do not claim native coverage for those two.
  • Five fixtures matched under Node. I excluded Process.run there because of the documented main-branch Worker limitation.
  • I additionally inspected raw stdout/stderr bytes of print_non_scalar in native/Bun/Node, using a fatal UTF-8 decoder rather than a replacement decoder: each of the three non-scalars is exactly EF BF BD, and all bytes are valid UTF-8. Inside Bend, the raw 55296 and 0xffffffff values are preserved; the independently built D800/DC00 remain separate Chars.

21 fixture/lane outcomes passed, plus the three exact-byte checks; the local repository shape/cap gate also passed 54/54, with caps unchanged. No CUDA/Metal/macOS, mini-cluster, performance or safe.ts --verdict claim. The nested-host-value limitation stated in the PR remains untested here.

@nicolas-abril nicolas-abril left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new and changed tests print their expected lines in the interpreter, JS and C lanes (the marshal tests run only in the interpreter, since they have no .c file). Three issues below are reproduced, including one regression: a module export that returns a function now crashes (line 3200). The other two reproduced ones are at lines 518 and 513 (a lone low surrogate in nested host text is misread, and the non-scalar encoding puts raw NUL/control units in the JS string). The rest come from reading the code.

Comment thread bend2/comp.ts
return ` ${js_key(Bend.name_key(k))}run_lib((${ps}) => ${
name_id("$", k)}(${xs}), ${lays.length}),`;
const xs = live.map(([, , A], i) => host(A, ps[i]));
return ` ${js_key(Bend.name_key(k))}run_lib((${ps}) => ${host(tele_unbind(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regression (reproduced): the return conversion comes from tele_unbind(T).ret, the type after every parameter, but the compiled function returns after only fun_of(k).n parameters. So a def that returns a function whose final result is String or Char gets its closure passed to str_out.

def pre(a: String) -> String -> String: String.append(a) exported with -o lib.mjs becomes run_lib((a0) => str_out(run_loop($pre(str_in(a0)))), 1). L.pre("ab") throws TypeError: s.replace is not a function; on main, L.pre("ab")("cd") gives "abcd". Fix: take the type from tele_fill(T, n DUMMYs), as fun_of does for ret, or convert only when n === doms.length.

Minor, same line: the callback now runs run_loop itself and run_lib runs it again on the result. That's harmless but redundant; passing the output converter to run_lib (run_lib(f, n, out), applied after its run_loop) keeps the conversion in one place.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in follow-up #1549, commit ebcb05f, based on merged main 63b2c0d. The converter uses the type after the actual function arity, via tele_fill(T, n DUMMYs). pre("ab")("cd") and partial join calls return "abcd". run_lib applies the output converter once after its trampoline. The retained actual-module fixture failed on merged main and now passes in interpreter/Bun/Node.

Comment thread bend2/comp.ts Outdated

function char_len(s) {
const u = s.charCodeAt(0);
return u < 0xD800 || u >= 0xE000 ? 1 : u < 0xDC00 ? 2 : 4;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced: any leading unit in DC00-DFFF counts as the 4-unit non-scalar marker, and char_code reads the next three units as code pieces. A host's lone low surrogate inside a nested value (which doesn't pass through str_in) is decoded as garbage and swallows the three characters after it.

Calling an exported heads(xs: List<String>) with ["\uDC05xyz"] gives the head Char the code 503564410 and drops "xyz"; main gave 56325. The same happens to any effect answer that puts a String in a constructor field (Maybe<String>, Char & String). Only DC00 itself should count as the marker, or nested host text should be sanitized.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in follow-up #1549, commit ebcb05f, based on merged main 63b2c0d. I preserved the merged DC05 correction. Merged main still decoded DC00 followed by xyz as 503564410 and swallowed the tail. Packet recognition now validates the marker and all three low-surrogate payload units: that input yields code 56320 with a three-Char tail. The existing pass-through ABI for nested host strings remains explicitly documented, not presented as a recursive marshaler.

Comment thread bend2/comp.ts
// pieces; str_out writes it as U+FFFD, as str_in does a host's surrogate.
function char_new(c) {
return c < 0xD800 || c >= 0xE000 && c <= 0x10FFFF ? String.fromCodePoint(c)
: String.fromCharCode(0xDC00, c >>> 22, c >>> 11 & 0x7FF, c & 0x7FF);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced: the three units after the 0xDC00 marker are raw 11-bit values (0..0x7FF), not units in DC00-DFFF as the PR description says. So a non-scalar Char puts real NUL, control and ASCII code units in the JS string.

A module export returning a List<String> that contains Chr{55296} hands the host "\udc00\u0000\u001b\u0000a": an embedded NUL, a control character and a stray marker, not one odd surrogate. Host code that splits on ., looks for \0 or escapes quotes sees characters that aren't there. Three 10-bit DC00-DFFF units can't hold 32 bits, so either the design or the description needs to change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in follow-up #1549, commit ebcb05f, based on merged main 63b2c0d. The four units now really all stay in the low-surrogate range: the DC00..DC03 marker carries two high bits, and three DC00..DFFF units carry ten bits each. Host-visible nested packets contain no NUL/control payloads; all Unicode boundary and u32 marker classes round-trip. Decoder, length, output and pure-value display use the same packet grammar.

Comment thread bend2/comp.ts
return file_push(sc, `return { $: ${JSON.stringify(Bend.name_key(k))
}, args: [${params.slice(0, -1).join(", ")}], kont: ${K?.$ === "All"
&& host_nat(K.A) ? `(x) => ${f}(nat_in(x))` : f} };`);
}, args: [${live.map(([, , A], i) => host(A, params[i], 1))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

str_in/str_out at the host boundary call .replace on whatever the host passes. A Char/String argument or effect answer that isn't a JS string now fails with an opaque TypeError and no bend: message, where it used to pass through. For example, an effect declared IO(Char) that answers with a number, or an exported f(s: String) called with undefined, throws x.replace is not a function.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in follow-up #1549, commit ebcb05f, based on merged main 63b2c0d. Direct Char/String host inputs and effect answers now fail with a Bend-category diagnostic when they are not JS strings. Verified both invalid module calls and a real IO(Char) effect that returns a number; the latter no longer leaks the opaque .replace TypeError. Permanent tests classify the error rather than pinning its full wording.

Comment thread bend2/comp.ts Outdated
}, args: [${params.slice(0, -1).join(", ")}], kont: ${K?.$ === "All"
&& host_nat(K.A) ? `(x) => ${f}(nat_in(x))` : f} };`);
}, args: [${live.map(([, , A], i) => host(A, params[i], 1))
}], kont: ${K?.$ === "All" && host(K.A, "") ? `(x) => ${f}(${

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: whether to wrap the kont depends on host(K.A, "") being truthy, which only works because host returns its input ("") unchanged when no conversion is needed. If host later returns e.g. (x) instead, every kont gets wrapped, or none do. host(K.A, "x") !== "x", or a predicate that returns the converter name, would be clearer.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in follow-up #1549, commit ebcb05f, based on merged main 63b2c0d. host now returns the converter name, not a formatted input expression. A continuation is wrapped only when a converter exists; otherwise it reuses the original callback. Nat, Bool, Char, String, closure and erased-value seams passed the actual runtime regression matrix.

Comment thread bend2/comp.ts

function io_bytes(text) {
return new TextEncoder().encode(text);
return new TextEncoder().encode(str_out(text));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Most String effect arguments now go through str_out twice: js_def already wraps every direct Char/String argument of a foreign def, and io_bytes runs the same regex again. name = str_out(name) in get_env.js and str_out(program) in process_run.js are fully redundant. So every IO.print, IO.write, File.write, TCP.send and UDP.send_to makes two regex passes and two string copies. Only Halt messages (io_errs) and the nested args list in Process.run need this extra call.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in follow-up #1549, commit ebcb05f, based on merged main 63b2c0d. The effect wrapper is now the sole direct-text conversion. io_bytes only encodes; the redundant get_env and direct Process.run program-name calls are gone. Halt and nested process arguments keep explicit conversion. Actual print-pass instrumentation, exact Halt UTF-8 bytes and the process argument/stdin fixture all verify those boundaries.

Comment thread bend2/comp.ts
...tpl_ops("bool_", "or:|:|| xor:^:!==", "(($0) $o ($1))", "($0 $o $1)"),
string_append: { JS: "($0 + $1)" },
string_length: { JS: "[...$0].length" },
string_length: { JS: "[...str_out($0)].length" },

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perf: this builds a full str_out copy and then spreads it into an array of code points, just to count Chars. A loop stepping by char_len (or [...s].length minus 3 per marker) gives the same count without either allocation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in follow-up #1549, commit ebcb05f, based on merged main 63b2c0d. String length now uses an indexed char_len walk, without the converted string or code-point array. Actual consumer instrumentation verifies that neither replacement nor the string iterator is used. The PR also documents a local interleaved large-string timing case; its RSS measurements showed no reduction, so no RSS claim is made.

Comment thread bend2/comp.ts
// The field a JS match opens from a named U32, F32 or Char (its word, its
// code): a binder takes it as written, so a rebuild folds back to the name.
const VIEW = /^(?:u32_to_word\((\w+|f32_bits\((\w+)\))\)|(\w+)\.codePointAt\(0\))$/;
const VIEW = /^(?:u32_to_word\((\w+|f32_bits\((\w+)\))\)|char_code\((\w+)\))$/;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perf: with char_code(x) in VIEW, a match binder keeps the call as written, so every use of a matched Char's code calls char_code again (a call, a branch and charCodeAt) where it used to be the built-in x.codePointAt(0). That adds up in Char-heavy loops (String.cmp, Char.is_digit/is_space chains, to_upper). Binding the code to a local once, or emitting x.codePointAt(0) with a fallback only when char_len is 4, would avoid it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in follow-up #1549, commit ebcb05f, based on merged main 63b2c0d. A matched code is held once, including once per invocation of a captured callback, while constructor-view folding retains the original Char. Actual host-call instrumentation verifies the getter work; Char identity still invokes no constructor. A user string containing the private emitted marker remains unchanged in the retained consumer regression.

@nicolas-abril
nicolas-abril merged commit 7ba0ce7 into bendlang:main Oct 13, 2026
1 check passed
@Lorenzobattistela Lorenzobattistela mentioned this pull request Oct 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Char.from_u32 of a surrogate fails in JS and the interpreter but prints invalid UTF-8 natively

2 participants