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
5 changes: 5 additions & 0 deletions CHANGELOG.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,11 @@ pure-extern semantics (Closes #332) (#338)
compiles to the same code as the statement form (`println("Hi");`).
Faces keep whichever form the author wrote, so greet in all six faces
now gives byte-identical wasm instead of two classes (Closes #601)
* float_to_string: core WASM lowers it (it failed with UnboundVariable),
with an inline shortest round-trip printer, and the interpreter now prints
the same text as Bun's `String(x)`: `3.0` gives "3" (was "3."), and 17
significant digits are kept where needed (was 12). All three backends agree
(Closes #643)
* Bun-ESM: every module carried the whole runtime (~300 host helpers),
including a `document.body.innerHTML` setter that add-on linters flag. Only
the helpers a module reaches are emitted now, in their original order
Expand Down
34 changes: 34 additions & 0 deletions lib/codegen.ml
Original file line number Diff line number Diff line change
Expand Up @@ -1839,6 +1839,16 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result =
in
Ok (c10, code)

| ExprVar id when id.name = "float_to_string"
&& List.length args = 1 ->
(* #643: shortest round-trip rendering, the same text as Bun's
`String(x)` and the interpreter. The printer is emitted once per
module by [Wasm_dtoa]; this call is patched to its index when the
module is assembled. It allocates from the bump heap. *)
let* (ctx1, x_code) = gen_expr ctx (List.hd args) in
let (ctx2, _heap_idx) = ensure_heap_ptr ctx1 in
Ok (ctx2, x_code @ [Call Wasm_dtoa.call_sentinel])

| ExprVar id when (id.name = "env_at" || id.name = "arg_at")
&& List.length args = 1 ->
(* ADR-015 S5 (#180): env_at(i) / arg_at(i) — fetch the i-th
Expand Down Expand Up @@ -4010,6 +4020,30 @@ let generate_module ?loader (prog : program) : wasm_module result =
| _ -> (ctx'.types, all_funcs, exports_with_mem)
in

(* #643: a module that calls float_to_string gets the shortest-digits
printer appended after every other function (so no existing index
moves), and its call sites are patched to the printer's index. *)
let final_types, final_funcs =
let uses_dtoa =
List.exists (fun f -> Wasm_dtoa.body_calls_sentinel f.f_body) final_funcs
in
match uses_dtoa, ctx'.heap_ptr with
| true, Some heap ->
let base = import_offset + List.length final_funcs in
let types = ref final_types in
let intern ft =
let (idx, ts) = intern_func_type !types ft in
types := ts; idx
in
let helpers = Wasm_dtoa.funcs ~base ~heap ~intern in
let patched =
List.map (fun f -> { f with f_body = Wasm_dtoa.patch_calls base f.f_body })
final_funcs
in
(!types, patched @ helpers)
| _ -> (final_types, final_funcs)
in

(* Stage 2: Build [typedwasm.ownership] custom section from collected annotations *)
let ownership_payload = build_ownership_section (List.rev ctx'.ownership_annots) in (* cons-accumulated; restore entry order *)
let custom_sections = if Bytes.length ownership_payload > 0 then
Expand Down
2 changes: 2 additions & 0 deletions lib/dune
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@
wasm_gc
wasm_gc_encode
wasi_runtime
wasm_dtoa
float_format
wgsl_codegen)
(libraries str unix sedlex fmt menhirLib yojson borrow_polonius)
; Warnings 8 (partial-match) and 9 (missing-record-fields) are demoted from
Expand Down
50 changes: 50 additions & 0 deletions lib/float_format.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
(* SPDX-License-Identifier: MPL-2.0 *)
(* SPDX-FileCopyrightText: 2026 hyperpolymath *)

(** [float_to_string] text, shared by every backend (#643).

The format is ECMAScript [Number.prototype.toString], which is what
Bun's [String(x)] gives: the fewest significant digits that read back
to the same double (the closest such digits, an exact tie going to
the even digit), laid out as "1e+21", "100", "0.000001", "1e-7",
"NaN", "-Infinity". Both zeros print as "0". The core-WASM printer
({!Wasm_dtoa}) produces the same text. *)

(* Shortest digits: the first precision whose correctly rounded %e form
reads back to [x]. If any p-digit decimal round-trips, the correctly
rounded one does, since it is the closest. *)
let shortest_digits (x : float) : string * int =
let rec go p =
let s = Printf.sprintf "%.*e" (p - 1) x in
if p >= 17 || float_of_string s = x then s else go (p + 1)
in
let s = go 1 in
let e_at = String.index s 'e' in
let mant = String.sub s 0 e_at in
let exp10 = int_of_string (String.sub s (e_at + 1) (String.length s - e_at - 1)) in
let digits = String.concat "" (String.split_on_char '.' mant) in
(* drop trailing zeros (%.16e of 0.5 gives no extras, but be safe) *)
let n = ref (String.length digits) in
while !n > 1 && digits.[!n - 1] = '0' do decr n done;
(String.sub digits 0 !n, exp10 + 1)

let to_string (x : float) : string =
if Float.is_nan x then "NaN"
else if x = Float.infinity then "Infinity"
else if x = Float.neg_infinity then "-Infinity"
else if x = 0.0 then "0"
else
let sign = if x < 0.0 then "-" else "" in
let (ds, n) = shortest_digits (Float.abs x) in
let k = String.length ds in
let body =
if k <= n && n <= 21 then ds ^ String.make (n - k) '0'
else if 0 < n && n <= 21 then
String.sub ds 0 n ^ "." ^ String.sub ds n (k - n)
else if -6 < n && n <= 0 then "0." ^ String.make (-n) '0' ^ ds
else
let e = n - 1 in
let m = if k = 1 then ds else String.sub ds 0 1 ^ "." ^ String.sub ds 1 (k - 1) in
m ^ "e" ^ (if e < 0 then "-" else "+") ^ string_of_int (abs e)
in
sign ^ body
2 changes: 1 addition & 1 deletion lib/interp.ml
Original file line number Diff line number Diff line change
Expand Up @@ -728,7 +728,7 @@ let create_initial_env () : env =
));
("float_to_string", VBuiltin ("float_to_string", fun args ->
match args with
| [VFloat f] -> Ok (VString (string_of_float f))
| [VFloat f] -> Ok (VString (Float_format.to_string f))
| _ -> Error (TypeMismatch "float_to_string expects Float")
));
(* STDLIB-04e (Refs #332): `string_length : String -> Int / Pure` is
Expand Down
Loading
Loading