Repository navigation
fix(runtime): a Char holds any u32 on every lane; U+FFFD only at text edges - #1411
Conversation
babcca2 to
4e18eac
Compare
|
Rebased on main f60b6ee and pushed 4e18eac (your commit kept as db210d4, one small commit on top). Rebase. #1506 removed Simplify. Review. No bugs found. The C 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 Unsupervised AI review (Claude), on behalf of @nicolas-abril. |
|
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.
4e18eac to
88fb722
Compare
|
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. Unsupervised AI review. |
|
Linux x64 verification on the rewritten head 4957361, not the superseded scalar-rejection version:
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 |
nicolas-abril
left a comment
There was a problem hiding this comment.
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.
| 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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
|
||
| function char_len(s) { | ||
| const u = s.charCodeAt(0); | ||
| return u < 0xD800 || u >= 0xE000 ? 1 : u < 0xDC00 ? 2 : 4; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| // 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| }, 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}(${ |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
|
||
| function io_bytes(text) { | ||
| return new TextEncoder().encode(text); | ||
| return new TextEncoder().encode(str_out(text)); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| ...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" }, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| // 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+)\))$/; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Fixes #1080.
A
Charholds any u32, on every lane.Char.to_u32(Char.from_u32(n))gives backnfor everyn. Interp, JS and C now agree. Before this change, interp and JS stopped withbend: 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.Char.from_u32andChar.to_u32are unchanged. The interpreter already kept such Chars exact; it shows them as\u{d800}.char_new/char_code/char_lenread and write this form.String.lengthcounts it as one Char. Appending is stillh + t.io_bytes), compiled-module returns, FFI/host values,Process.runargv/stdin andget_envnames get U+FFFD. The C writer (io_utf8) does the same. A host string with a lone surrogate comes in as U+FFFD.show/char_any_code,io/print_non_scalar,io/process_run_non_scalar.io/marshal_char_scalar,io/marshal_string_scalarandshow/string_escapewere 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 callstr_out/io_bytesthemselves.comp.ts: 63,391 -> 63,722 ttok (cap 64,000).