Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ kept so existing scripts fail loudly (Refs #56)

==== Added

* WASM: `slice` on a String and `show` on Int or Bool now compile on the
core-WASM backend. The typechecker records the argument type and the wasm
elaboration picks `string_slice`, `int_to_string`, or an if over
"true"/"false". `show` on other types is a named error, since the
interpreter and Deno render Strings, Chars and Floats differently; a
user-defined `show` or `slice` is still called (Closes #560)
* json: `hpm_json_object_len` / `hpm_json_object_key` enumerate object
members, so `to_json` materialises objects instead of returning `None`.
Lowered on Bun-ESM; the matching hpm-json-rsr Zig exports are not merged
Expand Down
75 changes: 74 additions & 1 deletion lib/codegen.ml
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ let rec is_string_concat_operand (e : expr) : bool =
(* String-returning builtins (Int/Char-returning ones are excluded). *)
List.mem id.name
[ "int_to_string"; "float_to_string"; "to_lowercase"; "to_uppercase";
"trim"; "string_sub"; "string_from_char_code"; "show" ]
"trim"; "string_sub"; "string_slice"; "string_from_char_code"; "show" ]
| ExprBinary (a, OpConcat, b) ->
is_string_concat_operand a || is_string_concat_operand b
| _ -> false
Expand Down Expand Up @@ -1509,6 +1509,79 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result =
in
Ok (ctx_v, code)

| ExprVar id when id.name = "string_slice"
&& List.length args = 3 ->
(* #560: `slice(s, lo, hi)` on a String, after
Typecheck.elaborate_string_concat picked the String case of the
polymorphic builtin. Half-open [lo, hi); a negative index counts
from the end; both are clamped. This matches the interpreter
oracle (lib/interp.ml `slice`) and JS `.slice` on the Deno backend:
norm i = i < 0 ? max 0 (n + i) : min i n
len = max 0 (norm hi - norm lo)
followed by the same allocate-then-copy as `string_sub`. *)
let* (ctx1, s_code) = gen_expr ctx (List.nth args 0) in
let* (ctx2, lo_code) = gen_expr ctx1 (List.nth args 1) in
let* (ctx3, hi_code) = gen_expr ctx2 (List.nth args 2) in
let (ctx4, heap_idx) = ensure_heap_ptr ctx3 in
let (c5, src) = alloc_local ctx4 "__sslc_src" in
let (c6, n) = alloc_local c5 "__sslc_n" in
let (c7, lo) = alloc_local c6 "__sslc_lo" in
let (c8, hi) = alloc_local c7 "__sslc_hi" in
let (c9, dst) = alloc_local c8 "__sslc_dst" in
let (c10, k) = alloc_local c9 "__sslc_k" in
(* local := (local < 0) ? max(0, n + local) : min(local, n) *)
let norm v =
[ LocalGet v; I32Const 0l; I32LtS;
If (BtEmpty,
(* n + v, floored at 0 *)
[ LocalGet n; LocalGet v; I32Add; I32Const 0l;
LocalGet n; LocalGet v; I32Add; I32Const 0l; I32GtS;
Select; LocalSet v ],
(* min(v, n) *)
[ LocalGet v; LocalGet n; LocalGet v; LocalGet n; I32LtS;
Select; LocalSet v ]) ] in
let code =
s_code @ [LocalSet src] @
lo_code @ [LocalSet lo] @
hi_code @ [LocalSet hi] @
[ LocalGet src; I32Load (2, 0); LocalSet n ] @
norm lo @ norm hi @
(* hi := max(0, hi - lo), now the byte count *)
[ LocalGet hi; LocalGet lo; I32Sub; I32Const 0l;
LocalGet hi; LocalGet lo; I32Sub; I32Const 0l; I32GtS;
Select; LocalSet hi ] @
(* dst = heap; heap += 4 + count; dst[0] = count *)
[ GlobalGet heap_idx; LocalSet dst;
GlobalGet heap_idx; I32Const 4l; LocalGet hi; I32Add; I32Add;
GlobalSet heap_idx;
LocalGet dst; LocalGet hi; I32Store (2, 0) ] @
(* for k in 0..count: dst[4+k] = src[4 + lo + k] *)
[ I32Const 0l; LocalSet k;
Block (BtEmpty, [ Loop (BtEmpty, [
LocalGet k; LocalGet hi; I32GeS; BrIf 1;
LocalGet dst; LocalGet k; I32Add;
LocalGet src; LocalGet lo; I32Add; LocalGet k; I32Add;
I32Load8U (0, 4);
I32Store8 (0, 4);
LocalGet k; I32Const 1l; I32Add; LocalSet k;
Br 0 ]) ]) ] @
[ LocalGet dst ]
in
Ok (c10, code)

| ExprVar id when String.length id.name > 19
&& String.sub id.name 0 19 = "__show_unsupported:" ->
(* #560: `show` on a type whose rendering the backends do not agree
on (the interpreter quotes Strings and Chars and prints Float 3.0
as "3."; the Deno backend does not), so core WASM refuses it by
name rather than pick one. Int and Bool are lowered. *)
let tname = String.sub id.name 19 (String.length id.name - 19) in
Error (UnsupportedFeature (Printf.sprintf
"show on %s is not lowered on the core-WASM backend (its output \
differs between backends; only Int and Bool are lowered). Use \
the type's own to-string function, e.g. float_to_string. (#560)"
tname))

| ExprVar id when id.name = "string_sub"
&& List.length args = 3 ->
(* PHASE-F string-wall slice 3: the runtime-length copy op.
Expand Down
59 changes: 57 additions & 2 deletions lib/typecheck.ml
Original file line number Diff line number Diff line change
Expand Up @@ -843,6 +843,18 @@ let float_heap_sites : expr list ref = ref []
(** Discard any recorded Float-heap sites (e.g. before re-checking). *)
let reset_float_heap_sites () : unit = float_heap_sites := []

(** String-wall #560. Physical-identity map from each call of a polymorphic
builtin the core-WASM backend cannot lower untyped (`slice`, `show`) to
the instantiated function type at that call. After checking, the first
parameter of that type is the argument's type, so
{!elaborate_string_concat} can pick a monomorphic lowering:
`slice` on a String becomes `string_slice`; `show` on Int becomes
`int_to_string`, on Bool an if over two literals. Same physical-identity
discipline as {!string_concat_sites}. *)
let poly_builtin_sites : (expr * ty) list ref = ref []

let reset_poly_builtin_sites () : unit = poly_builtin_sites := []

(** Float heap wall — heterogeneous tuples. A tuple with at least one scalar
`Float` field is laid out with uniform 8-byte cells (see {!Ast.ExprCellTuple}).
These two physical-identity *maps* carry the per-cell kinds (a set is not
Expand Down Expand Up @@ -1042,8 +1054,14 @@ let rec synth (ctx : context) (expr : expr) : ty result =
Ok ty

(* Function application *)
| ExprApp (fn_expr, args) ->
| ExprApp (fn_expr, args) as app_node ->
let* fn_ty = synth ctx fn_expr in
(* #560: remember the instantiated type at `slice`/`show` calls; the
argument type is read off it after [apply_args] has unified it. *)
(match fn_expr, args with
| ExprVar { name = ("slice" | "show"); _ }, _ :: _ ->
poly_builtin_sites := (app_node, fn_ty) :: !poly_builtin_sites
| _ -> ());
begin match args with
| [] ->
(* A zero-argument call [f()]. Zero-parameter function
Expand Down Expand Up @@ -1739,6 +1757,27 @@ and synth_and_unify (ctx : context) (expr : expr) (expected : ty) : unit result
expression grammar — any constructor it failed to descend into would leave
a String `++` un-elaborated, where the slice-8a guard would (loudly) catch
the obvious cases and a var-var case could still miscompile. *)
let poly_builtin_shadowed : string list ref = ref []

(** #560: monomorphic lowering for a recorded `slice`/`show` call, from the
argument type (first parameter of the instantiated [fty]). Cases the
backends do not agree on are renamed to `__show_unsupported:<Type>`, so
core-WASM codegen reports them by name instead of "unbound `show`". *)
let elab_poly_builtin (id : ident) (fty : ty) (args : expr list) : expr =
let arg_ty = match repr fty with TArrow (a, _, _, _) -> Some (repr a) | _ -> None in
let call name = ExprApp (ExprVar { id with name }, args) in
match id.name, arg_ty, args with
| "slice", Some (TCon "String"), _ -> call "string_slice"
| "show", Some (TCon "Int"), _ -> call "int_to_string"
| "show", Some (TCon "Bool"), [b] ->
ExprIf { ei_cond = b;
ei_then = ExprLit (LitString ("true", id.span));
ei_else = Some (ExprLit (LitString ("false", id.span))) }
| "show", Some t, _ ->
let tname = match t with TCon c -> c | TApp (TCon c, _) -> c | _ -> "this type" in
call ("__show_unsupported:" ^ tname)
| _ -> ExprApp (ExprVar id, args)

let rec elab_expr (e : expr) : expr =
match e with
| ExprBinary (l, op, r) ->
Expand Down Expand Up @@ -1776,7 +1815,13 @@ let rec elab_expr (e : expr) : expr =
ExprMatch { em_scrutinee = elab_expr r.em_scrutinee;
em_arms = List.map elab_arm r.em_arms }
| ExprLambda r -> ExprLambda { r with elam_body = elab_expr r.elam_body }
| ExprApp (f, args) -> ExprApp (elab_expr f, List.map elab_expr args)
| ExprApp (f, args) ->
let args' = List.map elab_expr args in
(match List.assq_opt e !poly_builtin_sites, f with
| Some fty, ExprVar ({ name; _ } as id)
when not (List.mem name !poly_builtin_shadowed) ->
elab_poly_builtin id fty args'
| _ -> ExprApp (elab_expr f, args'))
| ExprTupleIndex (e1, i) ->
(* Float heap wall: rewrite a float-bearing tuple's `t.i` into the cell load. *)
(match List.assq_opt e !cell_tuple_index_sites with
Expand Down Expand Up @@ -1890,7 +1935,16 @@ let elaborate_string_concat (program : program) : program =
|| !float_binop_sites <> [] || !float_heap_sites <> []
|| !cell_tuple_sites <> [] || !cell_tuple_index_sites <> []
|| !cell_record_sites <> [] || !cell_field_sites <> []
|| !poly_builtin_sites <> []
in
(* #560: a program that defines its own `slice`/`show` keeps calling it. *)
poly_builtin_shadowed :=
List.filter_map (function
| TopFn fd when fd.fd_name.name = "slice" || fd.fd_name.name = "show" ->
Some fd.fd_name.name
| TopExternFn { ef_name; _ }
when ef_name.name = "slice" || ef_name.name = "show" -> Some ef_name.name
| _ -> None) program.prog_decls;
let result =
if any_sites
then { program with prog_decls = List.map elab_top program.prog_decls }
Expand All @@ -1905,6 +1959,7 @@ let elaborate_string_concat (program : program) : program =
reset_cell_tuple_index_sites ();
reset_cell_record_sites ();
reset_cell_field_sites ();
reset_poly_builtin_sites ();
result

(** {1 Declaration checking} *)
Expand Down
11 changes: 7 additions & 4 deletions proposals/MIGRATION-PLAN.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,12 @@ toc::[]
slice 3), *ASCII case-folding* (`to_lowercase` / `to_uppercase`, slice 4),
*whitespace trimming* (`trim`, slice 5), *substring search* (`string_find`,
slice 6), and *decimal rendering* (`int_to_string`, slice 7) now lower to
wasm (Phase F, see Ledger) — *the clean lane is closed*; only concat / `++`
and polymorphic `slice` remain, gated on a type-access design decision (see
Ledger F+). Gates every STRING-GATED kernel (e.g. `Kernel_IO`, `DeviceType`,
wasm (Phase F, see Ledger) — *the clean lane is closed*. String `++`
(slice 8b) and polymorphic `slice` on a String plus `show` on Int / Bool
(#560) are lowered by type-directed elaboration: the typechecker records
the argument type and `Typecheck.elaborate_string_concat` picks the
monomorphic op. `show` on other types is a named codegen error, because the
interpreter and Deno render Strings, Chars and Floats differently. Gates every STRING-GATED kernel (e.g. `Kernel_IO`, `DeviceType`,
i18n) whose work is building/transforming strings rather than scanning them.
Lives
in *this* repo's compiler, so it is
Expand Down Expand Up @@ -218,7 +221,7 @@ Heuristic:
| F (string slice 7) | DONE | String-wall slice 7 — *decimal rendering landed in the wasm backend* (2026-06-13, Opus). `int_to_string(n)` (already wired in resolve/typecheck/interp) gained a wasm lowering over the slice-3 allocation idiom: `neg = n<0`; `m = neg ? n : -n` (non-positive magnitude via `Select`); a do-while digit-count loop (so `n=0` yields one '0' with no special case); allocate `4 + dc + neg`; a do-while backward-write loop emitting `48 - (m%10)` per digit; leading `'-'` when negative. *INT_MIN-safe* — the un-representable positive magnitude is never formed; `div_s`/`rem_s` by 10 never trap. *Gates:* G1 builds; G2 parity over 0/single/multi-digit/negative/powers-of-ten/INT_MAX/INT_MIN (wasm string read back from memory vs `string_of_int`). Tests: `test/test_e2e.ml` new `eval_string_fn` + group "E2E String-wall slice 7 (int_to_string)" (5 full-string cases incl. INT_MIN, `dune runtest`) + `tests/codegen/string_int_to_string.{affine,…mjs}` (executable wasm parity; full `run_codegen_wasm_tests.sh` green, no regressions). Evidence: `proposals/EVIDENCE-stringwall-slice7.adoc`. *Clean lane CLOSED — every name-dispatched string builtin with a trap-free wasm analogue is lowered.* NEXT: the gated concat/`slice` decision, or the effect wall.
| F (string slice 8a) | DONE | String-wall slice 8a — *string-`++` footgun GUARD landed in the wasm backend* (2026-06-13, Opus). *Finding:* string `++` silently miscompiles to wasm — it typechecks (`++` is type-dispatched at `typecheck.ml:1062`), the interp is correct, but codegen lowers `++` only as *list*-concat (4-byte element stride), so a string's `[len][utf8]` is copied as i32 elements (`"ab" ++ "cd"` -> byte 2 = 2, the length word of "cd", instead of 'c'). A #555-class silent mis-lowering. *Decision (owner, "guard first, then full fix"):* the "add a `string_concat` builtin / ban `++`" route is ruled out — `++` is the canonical, stdlib-pervasive surface and `string_concat` was deliberately removed (#330). *This slice:* the wasm `OpConcat` handler now rejects the syntactically-obvious string `++` (string literal / String-returning builtin call / nested string `++`, via `is_string_concat_operand`) with a loud `UnsupportedFeature` error instead of emitting garbage — a *sound-rejection* heuristic (never misfires on list `++`; deliberately incomplete on pure var-var string `++`, which slice 8b closes). *Gates:* G1 builds; guard verified (string `++` -> loud error; list `++` + slices 1-7 fixtures still compile; full `run_codegen_wasm_tests.sh` green incl. `list_concat`). Tests: `test/test_e2e.ml` group "E2E String-wall slice 8 guard". Design: `proposals/DESIGN-string-concat.adoc` (merged #574). NEXT: slice 8b — type-directed string-`++` lowering (`ExprStringConcat` elaboration + byte-concat), making `++` correct + complete.
| F (string slice 8b) | DONE | String-wall slice 8b — *type-directed string-`++` lowering landed in the wasm backend* (2026-06-13, Opus). The full fix the 8a guard stood in for. *Channel:* `synth` records each `++` it types as String concat (physical identity, `string_concat_sites`); `Typecheck.elaborate_string_concat` rewrites exactly those nodes to a new `ExprStringConcat` (`ast.ml`); the wasm path (`bin/main.ml`) runs it after typecheck, before `Opt.fold` — the interp + non-wasm backends keep the original `ExprBinary _ OpConcat _`, so the oracle is unchanged. Physical-identity keying is sound because typecheck and codegen share one `prog` object (`parse_with_face`'s lowered prog). *Lowering* (`codegen.ml`): byte concat — alloc `4 + la + lb`, length word, copy a's then b's bytes (the list-concat handler with 1-byte elements + one length word). *Effect parity:* `effect_sites.ml` recurses `ExprStringConcat` like `ExprBinary`, NOT as an `ExprApp` call site, so effect-ordinals stay identical interp-vs-wasm (no #555-class desync). `opt.ml` folds sub-exprs; `interp.ml` handles it defensively. *Gates:* G1 builds; the canonical miscompile is fixed (`"ab" ++ "cd"` byte 2 = 99 'c', was 2); var-var + chained + empty all parity-green; list `++` + slices 1-7 + effect tests still green (full `run_codegen_wasm_tests.sh`). Tests: `tests/codegen/string_concat.{affine,mjs}` (executable parity) + `test/test_e2e.ml` "E2E String-wall slice 8 guard" (incl. lowers-after-elaboration). The 8a guard is retained as a backstop. Design: `proposals/DESIGN-string-concat.adoc`. *String wall: every name-dispatched op (slices 1-7) + concat (8) now lower to wasm.*
| F+ | TODO | *String-wall residuals (minor/deferred), then the effect wall.* String residuals: *`slice`*-on-string negative-index (mostly covered by the shipped `string_sub`); *`float_to_string`* stays host-side permanently (float-wall — floats are Int-native-re-decomposed per the C6/C7 milli-unit convention); *`string_get`/`int_to_char`* deferred (raise on out-of-range; no trap-free wasm analogue). These do not gate "CLEAR" materially. *The big remaining compiler half is the effect-codegen wall* (111 EFFECT-GATED corpus files per Phase B): module-state, `Date.now`, `Console.log` → wasm. Essentially unstarted. After both walls + the migratable corpus: *Phase Ω* cutover/extinction (retire shadows, flip FeaturePacks). *String slices 1-8 landed (clean lane + concat).*
| F+ | TODO | *String-wall residuals (minor/deferred), then the effect wall.* String residuals: *`slice`* on a String (incl. negative indices) DONE in #560 (`string_slice`, wasm parity in `tests/codegen/string_slice.{affine,…mjs}`); `slice` on an *array* still unlowered; `show` lowered for Int / Bool only (#560); *`float_to_string`* stays host-side permanently (float-wall — floats are Int-native-re-decomposed per the C6/C7 milli-unit convention); *`string_get`/`int_to_char`* deferred (raise on out-of-range; no trap-free wasm analogue). These do not gate "CLEAR" materially. *The big remaining compiler half is the effect-codegen wall* (111 EFFECT-GATED corpus files per Phase B): module-state, `Date.now`, `Console.log` → wasm. Essentially unstarted. After both walls + the migratable corpus: *Phase Ω* cutover/extinction (retire shadows, flip FeaturePacks). *String slices 1-8 landed (clean lane + concat).*
| Ω | TODO (access-gated) | Cutover + extinction.
|===

Expand Down
Loading
Loading