diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index 02984227..0ae67c50 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -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 diff --git a/lib/codegen.ml b/lib/codegen.ml index 53921072..6cd9bc3a 100644 --- a/lib/codegen.ml +++ b/lib/codegen.ml @@ -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 @@ -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 diff --git a/lib/dune b/lib/dune index df737673..818f6fcf 100644 --- a/lib/dune +++ b/lib/dune @@ -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 diff --git a/lib/float_format.ml b/lib/float_format.ml new file mode 100644 index 00000000..ef0f64a8 --- /dev/null +++ b/lib/float_format.ml @@ -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 diff --git a/lib/interp.ml b/lib/interp.ml index 459628d0..b850b647 100644 --- a/lib/interp.ml +++ b/lib/interp.ml @@ -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 diff --git a/lib/wasm_dtoa.ml b/lib/wasm_dtoa.ml new file mode 100644 index 00000000..68d82f6f --- /dev/null +++ b/lib/wasm_dtoa.ml @@ -0,0 +1,334 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(* SPDX-FileCopyrightText: 2026 hyperpolymath *) + +(** Shortest round-trip [float_to_string] for core WASM (#643). + + The output matches ECMAScript [Number.prototype.toString] (Bun's + [String(x)]) and the interpreter ({!Float_format}): the fewest + significant digits that read back to the same double, the closest + such digits when several qualify, then the JS layout ("1e+21", + "0.000001", "1e-7", "NaN", "-Infinity", "0" for both zeros). + + Digits come from Burger & Dybvig's free-format algorithm ("Printing + Floating-Point Numbers Quickly and Accurately", PLDI 1996) run on + fixed 40-limb (1280-bit) bignums in linear memory, which holds every + intermediate for the full double range. No tables and no host import. + + The printer is a handful of helper functions appended once to a + module that uses it. A call site emits [Call call_sentinel]; the + module assembler patches that to the real index ({!patch_calls}). + + Memory: the result string is written at the heap pointer B + ([len:i32][bytes], at most 25 bytes). Scratch digits sit at B+48 and + the bignums R, S, M+, M-, T at B+80 .. B+880. Only the string is + kept: the heap pointer ends just past it, so a call leaks nothing. *) + +open Wasm + +(** Placeholder index a call site uses for the printer's entry point. *) +let call_sentinel = -643 + +let limbs = 40 +let limb_bytes = limbs * 4 + +(* Helper order: the entry point first, so [base] is its index. *) +let i_f2s = 0 +let i_mul10 = 1 +let i_add = 2 +let i_sub = 3 +let i_cmp = 4 +let i_set = 5 + +(* addr = p + i*4, for limb [i] of bignum [p] *) +let limb_addr p i = [LocalGet p; LocalGet i; I32Const 2l; I32Shl; I32Add] + +(* p *= 10. params p; locals i, carry:i64, t:i64 *) +let mul10_body = + let p, i, carry, t = 0, 1, 2, 3 in + [ I64Const 0L; LocalSet carry; I32Const 0l; LocalSet i; + Loop (BtEmpty, + limb_addr p i + @ limb_addr p i + @ [ I64Load32U (2, 0); I64Const 10L; I64Mul; LocalGet carry; I64Add; + LocalTee t; I64Store32 (2, 0); + LocalGet t; I64Const 32L; I64ShrU; LocalSet carry; + LocalGet i; I32Const 1l; I32Add; LocalTee i; + I32Const (Int32.of_int limbs); I32LtU; BrIf 0 ]) ] + +(* dst = a + b (dst may alias a or b). params dst, a, b; locals i, carry, t *) +let add_body = + let dst, a, b, i, carry, t = 0, 1, 2, 3, 4, 5 in + [ I64Const 0L; LocalSet carry; I32Const 0l; LocalSet i; + Loop (BtEmpty, + limb_addr dst i + @ limb_addr a i @ [I64Load32U (2, 0)] + @ limb_addr b i @ [I64Load32U (2, 0)] + @ [ I64Add; LocalGet carry; I64Add; LocalTee t; I64Store32 (2, 0); + LocalGet t; I64Const 32L; I64ShrU; LocalSet carry; + LocalGet i; I32Const 1l; I32Add; LocalTee i; + I32Const (Int32.of_int limbs); I32LtU; BrIf 0 ]) ] + +(* a -= b, requires a >= b. params a, b; locals i, borrow, t *) +let sub_body = + let a, b, i, borrow, t = 0, 1, 2, 3, 4 in + [ I64Const 0L; LocalSet borrow; I32Const 0l; LocalSet i; + Loop (BtEmpty, + limb_addr a i + @ limb_addr a i @ [I64Load32U (2, 0)] + @ limb_addr b i @ [I64Load32U (2, 0)] + @ [ I64Sub; LocalGet borrow; I64Sub; LocalTee t; I64Store32 (2, 0); + (* t is negative exactly when this limb borrowed *) + LocalGet t; I64Const 63L; I64ShrU; LocalSet borrow; + LocalGet i; I32Const 1l; I32Add; LocalTee i; + I32Const (Int32.of_int limbs); I32LtU; BrIf 0 ]) ] + +(* sign(a - b) as -1 / 0 / 1. params a, b; locals i, x, y *) +let cmp_body = + let a, b, i, x, y = 0, 1, 2, 3, 4 in + [ I32Const (Int32.of_int (limbs - 1)); LocalSet i; + Loop (BtEmpty, + limb_addr a i @ [I32Load (2, 0); LocalSet x] + @ limb_addr b i @ [I32Load (2, 0); LocalSet y] + @ [ LocalGet x; LocalGet y; I32Ne; + If (BtEmpty, + [ I32Const 1l; I32Const (-1l); + LocalGet x; LocalGet y; I32GtU; Select; Return ], + [Nop]); + LocalGet i; I32Const 1l; I32Sub; LocalTee i; + I32Const 0l; I32GeS; BrIf 0 ]); + I32Const 0l ] + +(* p = f * 2^n, f < 2^54. params p, f:i64, n; locals i, addr, bit *) +let set_body = + let p, f, n, i, addr, bit = 0, 1, 2, 3, 4, 5 in + [ I32Const 0l; LocalSet i; + Loop (BtEmpty, + limb_addr p i + @ [ I32Const 0l; I32Store (2, 0); + LocalGet i; I32Const 1l; I32Add; LocalTee i; + I32Const (Int32.of_int limbs); I32LtU; BrIf 0 ]); + LocalGet p; LocalGet n; I32Const 5l; I32ShrU; I32Const 2l; I32Shl; + I32Add; LocalSet addr; + LocalGet n; I32Const 31l; I32And; LocalSet bit; + LocalGet addr; LocalGet f; LocalGet bit; I64ExtendI32U; I64Shl; + I64Store (3, 0); + LocalGet bit; + If (BtEmpty, + [ LocalGet addr; + LocalGet f; I64Const 64L; LocalGet bit; I64ExtendI32U; I64Sub; + I64ShrU; I32WrapI64; I32Store (2, 8) ], + [Nop]) ] + +let f2s_body ~base ~heap = + let call i = Call (base + i) in + (* locals: 0 = x (param) *) + let bits, f = 1, 2 in (* i64 *) + let neg, bexp, e, sh, even, k = 3, 4, 5, 6, 7, 8 in + let bb, b, r, s, mp, mm, t = 9, 10, 11, 12, 13, 14, 15 in + let d, nd, w, i, tc1, tc2, ex, dig, hi = 16, 17, 18, 19, 20, 21, 22, 23, 24 in + let aa = 25 in + let put_code code = (* store the i32 on top, w++ *) + [LocalGet w] @ code @ [I32Store8 (0, 0); + LocalGet w; I32Const 1l; I32Add; LocalSet w] in + let put c = put_code [I32Const (Int32.of_int (Char.code c))] in + let put_str str = List.concat_map put (List.of_seq (String.to_seq str)) in + let mul10_all = [LocalGet r; call i_mul10; LocalGet mp; call i_mul10; + LocalGet mm; call i_mul10] in + (* while (cnt > 0) { body; cnt-- } with cnt in local [i] *) + let repeat body = + [ Block (BtEmpty, [ Loop (BtEmpty, + [ LocalGet i; I32Const 0l; I32LeS; BrIf 1 ] @ body + @ [ LocalGet i; I32Const 1l; I32Sub; LocalSet i; Br 0 ]) ]) ] in + (* emit digits dig[i .. hi) as ASCII, i and hi already set *) + let copy_digits = + [ Block (BtEmpty, [ Loop (BtEmpty, + [ LocalGet i; LocalGet hi; I32GeS; BrIf 1 ] + @ put_code [LocalGet dig; LocalGet i; I32Add; I32Load8U (0, 0); + I32Const 48l; I32Add] + @ [ LocalGet i; I32Const 1l; I32Add; LocalSet i; Br 0 ]) ]) ] in + let digits_range lo hi_code = + lo @ [LocalSet i] @ hi_code @ [LocalSet hi] @ copy_digits in + let zeros cnt_code = cnt_code @ [LocalSet i] @ repeat (put '0') in + (* "is c > 0, or c = 0 when the mantissa is even" for c on the stack *) + let gt_or_even_eq c = + [ LocalTee c; I32Const 0l; I32GtS; + LocalGet c; I32Eqz; LocalGet even; I32And; I32Or ] in + let general = + [ LocalGet neg; If (BtEmpty, put '-', [Nop]); + (* sh: the gap below v is half the gap above (f = 2^52, bexp > 1) *) + LocalGet f; I64Eqz; LocalGet bexp; I32Const 1l; I32GtU; I32And; + LocalSet sh; + LocalGet bexp; I32Eqz; + If (BtEmpty, + [ I32Const (-1074l); LocalSet e ], + [ LocalGet f; I64Const 0x10000000000000L; I64Or; LocalSet f; + LocalGet bexp; I32Const 1075l; I32Sub; LocalSet e ]); + LocalGet f; I32WrapI64; I32Const 1l; I32And; I32Eqz; LocalSet even; + (* aa = max(e, 0), bb = max(-e, 0) *) + LocalGet e; I32Const 0l; LocalGet e; I32Const 0l; I32GtS; Select; + LocalSet aa; + I32Const 0l; LocalGet e; I32Sub; I32Const 0l; + LocalGet e; I32Const 0l; I32LtS; Select; LocalSet bb; + (* r = f 2^(aa+1+sh), s = 2^(bb+1+sh), m+ = 2^(aa+sh), m- = 2^aa *) + LocalGet r; LocalGet f; + LocalGet aa; I32Const 1l; I32Add; LocalGet sh; I32Add; call i_set; + LocalGet s; I64Const 1L; + LocalGet bb; I32Const 1l; I32Add; LocalGet sh; I32Add; call i_set; + LocalGet mp; I64Const 1L; LocalGet aa; LocalGet sh; I32Add; call i_set; + LocalGet mm; I64Const 1L; LocalGet aa; call i_set; + (* k = ceil(floor(log2 v) log10 2 - 1e-10): exact or one too small *) + LocalGet e; I32Const 63l; I32Add; LocalGet f; I64Clz; I32WrapI64; + I32Sub; F64ConvertI32S; F64Const 0.30102999566398114; F64Mul; + F64Const 1e-10; F64Sub; F64Ceil; I32TruncF64S; LocalSet k; + LocalGet k; I32Const 0l; I32GeS; + If (BtEmpty, + [LocalGet k; LocalSet i] @ repeat [LocalGet s; call i_mul10], + [I32Const 0l; LocalGet k; I32Sub; LocalSet i] @ repeat mul10_all); + (* fixup: if v's upper bound reaches 10^k the estimate was low *) + LocalGet t; LocalGet r; LocalGet mp; call i_add; + LocalGet t; LocalGet s; call i_cmp ] @ gt_or_even_eq tc2 @ + [ If (BtEmpty, + [ LocalGet k; I32Const 1l; I32Add; LocalSet k ], + mul10_all); + (* digit generation *) + I32Const 0l; LocalSet nd; + Loop (BtEmpty, + [ I32Const 0l; LocalSet d; + Block (BtEmpty, [ Loop (BtEmpty, + [ LocalGet r; LocalGet s; call i_cmp; I32Const 0l; I32LtS; BrIf 1; + LocalGet r; LocalGet s; call i_sub; + LocalGet d; I32Const 1l; I32Add; LocalSet d; Br 0 ]) ]); + (* tc1: r < m- (<= when even); tc2: r + m+ > s (>= when even) *) + LocalGet mm; LocalGet r; call i_cmp ] + @ gt_or_even_eq tc1 @ [ LocalSet tc1; + LocalGet t; LocalGet r; LocalGet mp; call i_add; + LocalGet t; LocalGet s; call i_cmp ] + @ gt_or_even_eq tc2 @ [ LocalSet tc2; + LocalGet tc1; LocalGet tc2; I32Or; I32Eqz; + If (BtEmpty, + [ LocalGet dig; LocalGet nd; I32Add; LocalGet d; I32Store8 (0, 0); + LocalGet nd; I32Const 1l; I32Add; LocalSet nd ] + @ mul10_all @ [ Br 1 ], + [Nop]); + (* last digit: round up when only the upper bound is near, or + when both are and r is over half of s (an exact half goes to + the even digit, as Bun does) *) + LocalGet tc1; LocalGet tc2; I32And; + If (BtEmpty, + [ LocalGet t; LocalGet r; LocalGet r; call i_add; + LocalGet d; LocalGet t; LocalGet s; call i_cmp; LocalTee hi; + I32Const 0l; I32GtS; LocalGet hi; I32Eqz; + LocalGet d; I32Const 1l; I32And; I32And; I32Or; + I32Add; LocalSet d ], + [ LocalGet d; LocalGet tc2; I32Add; LocalSet d ]); + LocalGet dig; LocalGet nd; I32Add; LocalGet d; I32Store8 (0, 0); + LocalGet nd; I32Const 1l; I32Add; LocalSet nd ]); + (* layout, per Number::toString with n = k, digit count nd *) + Block (BtEmpty, + [ (* nd <= k <= 21: digits then zeros *) + LocalGet nd; LocalGet k; I32LeS; LocalGet k; I32Const 21l; I32LeS; + I32And; + If (BtEmpty, + digits_range [I32Const 0l] [LocalGet nd] + @ zeros [LocalGet k; LocalGet nd; I32Sub] @ [Br 1], + [Nop]); + (* 0 < k <= 21: digits with a point inside *) + LocalGet k; I32Const 0l; I32GtS; LocalGet k; I32Const 21l; I32LeS; + I32And; + If (BtEmpty, + digits_range [I32Const 0l] [LocalGet k] @ put '.' + @ digits_range [LocalGet k] [LocalGet nd] @ [Br 1], + [Nop]); + (* -6 < k <= 0: 0.000ddd *) + LocalGet k; I32Const (-6l); I32GtS; LocalGet k; I32Const 0l; I32LeS; + I32And; + If (BtEmpty, + put_str "0." @ zeros [I32Const 0l; LocalGet k; I32Sub] + @ digits_range [I32Const 0l] [LocalGet nd] @ [Br 1], + [Nop]) ] + (* exponent form: d[.ddd]e±x *) + @ digits_range [I32Const 0l] [I32Const 1l] + @ [ LocalGet nd; I32Const 1l; I32GtS; + If (BtEmpty, + put '.' @ digits_range [I32Const 1l] [LocalGet nd], [Nop]) ] + @ put 'e' + @ [ LocalGet k; I32Const 1l; I32Sub; LocalTee ex; I32Const 0l; I32LtS; + If (BtEmpty, + put '-' @ [I32Const 0l; LocalGet ex; I32Sub; LocalSet ex], + put '+'); + LocalGet ex; I32Const 100l; I32GeS; + If (BtEmpty, + put_code [LocalGet ex; I32Const 100l; I32DivU; I32Const 48l; + I32Add], [Nop]); + LocalGet ex; I32Const 10l; I32GeS; + If (BtEmpty, + put_code [LocalGet ex; I32Const 10l; I32DivU; I32Const 10l; + I32RemU; I32Const 48l; I32Add], [Nop]) ] + @ put_code [LocalGet ex; I32Const 10l; I32RemU; I32Const 48l; I32Add]) ] + in + [ GlobalGet heap; LocalSet b; + LocalGet b; I32Const 4l; I32Add; LocalSet w; + LocalGet b; I32Const 48l; I32Add; LocalSet dig; + LocalGet b; I32Const 80l; I32Add; LocalSet r; + LocalGet r; I32Const (Int32.of_int limb_bytes); I32Add; LocalSet s; + LocalGet s; I32Const (Int32.of_int limb_bytes); I32Add; LocalSet mp; + LocalGet mp; I32Const (Int32.of_int limb_bytes); I32Add; LocalSet mm; + LocalGet mm; I32Const (Int32.of_int limb_bytes); I32Add; LocalSet t; + LocalGet 0; I64ReinterpretF64; LocalSet bits; + LocalGet bits; I64Const 63L; I64ShrU; I32WrapI64; LocalSet neg; + LocalGet bits; I64Const 52L; I64ShrU; I32WrapI64; I32Const 0x7ffl; I32And; + LocalSet bexp; + LocalGet bits; I64Const 0xFFFFFFFFFFFFFL; I64And; LocalSet f; + Block (BtEmpty, + [ LocalGet bexp; I32Const 0x7ffl; I32Eq; + If (BtEmpty, + [ LocalGet f; I64Eqz; + If (BtEmpty, + [ LocalGet neg; If (BtEmpty, put '-', [Nop]) ] + @ put_str "Infinity", + put_str "NaN"); + Br 1 ], + [Nop]); + (* both zeros print as "0" *) + LocalGet bits; I64Const 0x7FFFFFFFFFFFFFFFL; I64And; I64Eqz; + If (BtEmpty, put '0' @ [Br 1], [Nop]) ] + @ general); + LocalGet b; LocalGet w; LocalGet b; I32Sub; I32Const 4l; I32Sub; + I32Store (2, 0); + LocalGet w; GlobalSet heap; + LocalGet b ] + +(** The printer's functions, to append at function index [base], with + [heap] the bump-allocator global. [intern] gives a type index. *) +let funcs ~base ~heap ~(intern : func_type -> int) : func list = + let fn params results n_i32 n_i64 body = + { f_type = intern { ft_params = params; ft_results = results }; + f_locals = + List.filter (fun l -> l.l_count > 0) + [ { l_count = n_i32; l_type = I32 }; { l_count = n_i64; l_type = I64 } ]; + f_body = body } in + [ (* f2s: 2 i64 locals first (bits, f), then the i32s *) + { f_type = intern { ft_params = [F64]; ft_results = [I32] }; + f_locals = [ { l_count = 2; l_type = I64 }; { l_count = 23; l_type = I32 } ]; + f_body = f2s_body ~base ~heap }; + fn [I32] [] 1 2 mul10_body; + fn [I32; I32; I32] [] 1 2 add_body; + fn [I32; I32] [] 1 2 sub_body; + fn [I32; I32] [I32] 3 0 cmp_body; + fn [I32; I64; I32] [] 3 0 set_body ] + +(** Replace [Call call_sentinel] with [Call target] throughout [body]. *) +let rec patch_calls target (body : instr list) : instr list = + List.map (function + | Call n when n = call_sentinel -> Call target + | Block (bt, b) -> Block (bt, patch_calls target b) + | Loop (bt, b) -> Loop (bt, patch_calls target b) + | If (bt, a, b) -> If (bt, patch_calls target a, patch_calls target b) + | i -> i) body + +let rec body_calls_sentinel (body : instr list) : bool = + List.exists (function + | Call n -> n = call_sentinel + | Block (_, b) | Loop (_, b) -> body_calls_sentinel b + | If (_, a, b) -> body_calls_sentinel a || body_calls_sentinel b + | _ -> false) body diff --git a/stdlib/string.affine b/stdlib/string.affine index e0914468..ed42e9fb 100644 --- a/stdlib/string.affine +++ b/stdlib/string.affine @@ -210,7 +210,8 @@ pub fn pad_right(s: String, target_len: Int, pad_char: String) -> String { // ============================================================================ // int_to_string(n: Int) -> String — builtin -// float_to_string(f: Float) -> String — builtin +// float_to_string(f: Float) -> String — builtin; shortest round-trip +// digits in JS layout on every backend: 3.0 -> "3", 1e21 -> "1e+21" (#643) // parse_int(s: String) -> Option — builtin // parse_float(s: String) -> Option — builtin diff --git a/test/test_float_format.ml b/test/test_float_format.ml new file mode 100644 index 00000000..9869dfea --- /dev/null +++ b/test/test_float_format.ml @@ -0,0 +1,85 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(* SPDX-FileCopyrightText: 2026 hyperpolymath *) + +(** #643: float_to_string prints the same text on every backend: the + shortest round-trip digits in ECMAScript layout (Bun's String(x)). + The full WASM-vs-Bun sweep is tests/codegen/test_float_to_string.mjs; + these pin the shared table, the interpreter and the module assembly. *) + +open Affinescript + +(* (value, what String(x) prints in Bun) *) +let table = [ + (0.0, "0"); (-0.0, "0"); (Float.nan, "NaN"); + (Float.infinity, "Infinity"); (Float.neg_infinity, "-Infinity"); + (3.0, "3"); (-1.5, "-1.5"); (0.1, "0.1"); (0.1 +. 0.2, "0.30000000000000004"); + (1.0 /. 3.0, "0.3333333333333333"); (100.0, "100"); + (1e20, "100000000000000000000"); (1e21, "1e+21"); (1.5e21, "1.5e+21"); + (1e-6, "0.000001"); (1.5e-6, "0.0000015"); (1e-7, "1e-7"); (1.5e-7, "1.5e-7"); + (5e-324, "5e-324"); (2.2250738585072014e-308, "2.2250738585072014e-308"); + (1.7976931348623157e308, "1.7976931348623157e+308"); + (9007199254740992.0, "9007199254740992"); + (267522186230338.625, "267522186230338.62"); (* exact tie: even digit *) + (12345.678, "12345.678"); (123e-20, "1.23e-18"); +] + +let test_table () = + List.iter (fun (x, want) -> + Alcotest.(check string) want want (Float_format.to_string x)) table + +let interp_string src name = + let prog = Parse_driver.parse_string ~file:"" src in + match Interp.eval_program prog with + | Error e -> Alcotest.failf "interp: %s" (Value.show_eval_error e) + | Ok env -> + match Value.lookup_env name env with + | Ok (Value.VString s) -> s + | Ok _ -> Alcotest.failf "%s is not a string" name + | Error e -> Alcotest.failf "lookup: %s" (Value.show_eval_error e) + +(* The interpreter used OCaml's string_of_float ("3.", 12 digits). *) +let test_interp () = + Alcotest.(check string) "whole float" "3" + (interp_string "const s: String = float_to_string(3.0);" "s"); + Alcotest.(check string) "17 digits" "0.30000000000000004" + (interp_string "const s: String = float_to_string(0.1 + 0.2);" "s"); + Alcotest.(check string) "exponent" "1e+21" + (interp_string "const s: String = float_to_string(1.0e21);" "s") + +let wasm src = + let prog = Parse_driver.parse_string ~file:"" src in + match Codegen.generate_module (Opt.fold_constants_program prog) with + | Ok m -> m + | Error e -> Alcotest.failf "codegen: %s" (Codegen.show_codegen_error e) + +let calls_index n body = + let rec go = function + | Wasm.Call i -> i = n + | Wasm.Block (_, b) | Wasm.Loop (_, b) -> List.exists go b + | Wasm.If (_, a, b) -> List.exists go a || List.exists go b + | _ -> false in + List.exists go body + +(* Used to fail with UnboundVariable. The printer is appended after the + user's functions, and the call site points at it. *) +let test_wasm_assembly () = + let plain = wasm "pub fn f(x: Float) -> Float { return x; }" in + let m = wasm "pub fn f(x: Float) -> String { return float_to_string(x); }" in + Alcotest.(check int) "printer functions appended" + (List.length plain.funcs + List.length (Wasm_dtoa.funcs ~base:0 ~heap:0 + ~intern:(fun _ -> 0))) + (List.length m.funcs); + let imports = List.length (List.filter (fun (i : Wasm.import) -> + match i.i_desc with Wasm.ImportFunc _ -> true | _ -> false) m.imports) in + let user_f = List.hd m.funcs in + Alcotest.(check bool) "call site patched to the printer" true + (calls_index (imports + List.length plain.funcs) user_f.f_body); + List.iter (fun (f : Wasm.func) -> + Alcotest.(check bool) "no sentinel left" false + (Wasm_dtoa.body_calls_sentinel f.f_body)) m.funcs + +let tests = [ + Alcotest.test_case "shared table matches String(x)" `Quick test_table; + Alcotest.test_case "interpreter uses the shared format" `Quick test_interp; + Alcotest.test_case "core WASM lowers float_to_string" `Quick test_wasm_assembly; +] diff --git a/test/test_main.ml b/test/test_main.ml index fc123f75..b87c8e62 100644 --- a/test/test_main.ml +++ b/test/test_main.ml @@ -36,6 +36,7 @@ let () = ("Deno builtins ↔ stdlib decls consistency", Test_deno_builtins_consistency.tests); ("Bun integer block scope", Test_int_scope_bun.tests); ("Same cube: faces compile alike (#601)", Test_same_cube.tests); + ("float_to_string format (#643)", Test_float_format.tests); ("ESM runtime pruning", Test_runtime_prune.tests); ("Stdlib algebraic laws (batch 1)", Test_stdlib_laws.tests); ("Solo CESK (VM M1, ADR-0025)", Test_solo_cesk.tests); diff --git a/tests/codegen/float_to_string.affine b/tests/codegen/float_to_string.affine new file mode 100644 index 00000000..a75cee56 --- /dev/null +++ b/tests/codegen/float_to_string.affine @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 hyperpolymath +// +// #643: float_to_string on core WASM. The companion harness +// test_float_to_string.mjs calls `show` on edge cases and random doubles +// and requires the same text as Bun's String(x). + +pub fn show(x: Float) -> String { + return float_to_string(x); +} + +fn main() -> Int { + string_length(float_to_string(0.1)) // "0.1" = 3 +} diff --git a/tests/codegen/test_float_to_string.mjs b/tests/codegen/test_float_to_string.mjs new file mode 100644 index 00000000..6a3f85fd --- /dev/null +++ b/tests/codegen/test_float_to_string.mjs @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: MPL-2.0 +// +// #643: float_to_string on core WASM must print exactly what Bun's +// String(x) prints (shortest round-trip digits, ECMAScript layout). +// Checks the boundaries (powers of 2 and 10 and their neighbours, +// subnormals, extremes, ties) and a seeded batch of random doubles. +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; + +const buf = await readFile('./tests/codegen/float_to_string.wasm'); +const imports = { wasi_snapshot_preview1: { fd_write: () => 0 } }; +const { exports: ex } = (await WebAssembly.instantiate(buf, imports)).instance; + +// The bump heap never frees, and each call keeps its result string. +ex.memory.grow(2000); +const dec = new TextDecoder(); +const show = (x) => { + const p = ex.show(x); + const len = new DataView(ex.memory.buffer).getInt32(p, true); + return dec.decode(new Uint8Array(ex.memory.buffer, p + 4, len)); +}; + +const dv = new DataView(new ArrayBuffer(8)); +const step = (x, d) => { + dv.setFloat64(0, x); + dv.setBigUint64(0, dv.getBigUint64(0) + BigInt(d)); + return dv.getFloat64(0); +}; + +const cases = [0, -0, Number.NaN, Infinity, -Infinity, 0.1, 0.2, 0.1 + 0.2, 1 / 3, + 100, 1e21, 1e20, 1e-6, 1e-7, 1.5e-7, 5e-324, -5e-324, 2.2250738585072014e-308, + 1.7976931348623157e308, 2 ** 53, 2 ** 53 + 2, 267522186230338.625 /* exact tie */, 4.35, 12345.678]; +for (let i = -1074; i <= 1023; i += 7) cases.push(2 ** i); +for (let i = -323; i <= 308; i += 3) cases.push(Number('1e' + i)); +const seeds = cases.filter(Number.isFinite).filter((x) => x !== 0); +for (const s of seeds) for (const d of [-1, 1]) cases.push(step(s, d), -step(s, d)); + +// xorshift32, fixed seed: random bit patterns, so every exponent is hit +let st = 0x9e3779b9; +const rnd = () => { st ^= st << 13; st ^= st >>> 17; st ^= st << 5; return st >>> 0; }; +for (let i = 0; i < 20000; i++) { + dv.setUint32(0, rnd()); dv.setUint32(4, rnd()); + cases.push(dv.getFloat64(0)); +} + +let bad = 0; +for (const x of cases) { + const got = show(x), want = String(x); + if (got !== want && bad++ < 10) console.error(`float_to_string(${want}) = ${got}`); +} +assert.equal(bad, 0, `${bad} of ${cases.length} doubles differ from String(x)`); +assert.equal(ex.main(), 3); +console.log(`test_float_to_string.mjs OK (${cases.length} doubles)`);