Skip to content

Floats: correctly rounded literals and C-compatible general, fixed, and scientific formatting - #1649

Merged
ehartford merged 5 commits into
withlang-dev:public-return-foundationfrom
joshhickson:josh/float-round-trip
Sep 25, 2026
Merged

ehartford merged 5 commits into
withlang-dev:public-return-foundationfrom
joshhickson:josh/float-round-trip

Conversation

@joshhickson

@joshhickson joshhickson commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Float literals previously accumulated rounding error, and f32 literals could round twice. Parse decimal text directly into its destination type on LLVM; emit-C removes digit separators and supplies the f32 suffix. Josh Hickson's two original commits and authorship are preserved.

Under Eric's C-formatting ruling (D68), default float display now follows C %g: six significant digits, notation selected after rounding, and trailing fractional zeros removed. Explicit g, f, and e precision uses exact decimal digits and ties-to-even rounding. Large fixed values and precision beyond 18 digits work without converting the integer part to u64 or clamping precision.

Debugging the old fixed formatter also exposed an independent float-to-unsigned cast bug: codegen selected fptosi from the source's signedness. It now uses Sema's destination type to select fptoui. The regression gets values through strtod so constant folding cannot erase an invalid conversion.

Validation on Darwin arm64, combined code head 1012a32b:

  • Pinned-seed build, byte-identical stage2/stage3 fixpoint, and drop/move audits passed.
  • All 1,290 behavior files reran and passed with a fresh C-import cache epoch.
  • Direct comparisons with C snprintf: 592 values × eight general/fixed/scientific formats, including 1,100-digit precision; debug allocator reports zero leaks.
  • Literal regression passes through both LLVM and compiled emit-C output, including the f32 double-rounding case.
  • Runtime unsigned-cast regression passes with the rebuilt compiler.
  • Full integration suite, test-green, last-green and user-programs-safe passed.

The C comparisons use the default C locale and round-to-nearest environment. With's text remains locale independent. Exact debugger/IR evidence and regression details are in docs/float-c-format-audit.md.

This replaces the proposed shortest-round-trip default with the approved C default. The wasm 1/3 output expectation follows that ruling (0.333333).

Depends on #1683, with #1672/#1675 below it. GitHub refuses fork PRs in stacks, so this original contributor PR is based on public-return-foundation and merges separately after that foundation. The repository-owned PRs remain in stack #1685.

@ehartford

Copy link
Copy Markdown
Contributor

How does C do this? We should make sure we do it the same way C does

@joshhickson

Copy link
Copy Markdown
Contributor Author

Rebased onto main 334739d2 locally and reran the battery on Windows x86_64. Main can't be built from the
pinned Windows seed (v0.15.2.1), so the driver is a main compiler I built by hopping through your darwin seed
chain (v0.15.2.1 → e69f397 → fa33bda → 8d3cc36 → 334739d; each hop a green full build, and :fixpoint green on the final one). That means
seed-driver refuses it, as designed, so this is evidence, not a recorded green:

main 334739d2 main + this PR
build ok ok (698 s)
:fixpoint ok ok, stage2 == stage3
behavior-tests 1274 ran, 9 failed 1277 ran (the 3 new), 9 failed, the same 9
compile-error tests 6 failed the same 6

The 15 failures are identical with and without the PR, all C facade tests (zlib, bzip2, sqlite, libcurl
facades, c_facade parse/verify, owning_wrapper_strdup) plus build_rss_budget. They're main's, on this
driver and host, not this change's. I'll rerun with the pinned seed once there's a Windows seed that builds main.

Josh Hickson and others added 5 commits September 25, 2026 13:37
`with_parse_float_ref` (rt/rt_core.w) accumulates `result + digit * frac` with
`frac = frac * 0.1`. It is not correctly rounded: 55 of 88 sampled literals land
1-4 ulps from the nearest double, subnormals become 0.0, and `std.math.TAU` is
1 ulp low. The three LLVM constant sites handed its f64 to `LLVMConstReal`, so an
f32 literal was rounded a second time; emit-C assigned the literal to a `float`
with no `f` suffix, which rounds twice in C for the same reason. Digit separators,
which §29.1 says are ignored for value parsing, reached both backends: `1_000.5`
was 1.0 under LLVM, and emit-C wrote `1_000.5` into C, which clang rejects.

- LLVM: `wl_const_real_of_string` binds `LLVMConstRealOfString`, so APFloat converts
  the literal's own text straight into the target type -- the same conversion clang
  performs on the text emit-C writes. rustc does the same (`parse_float_into_scalar`
  over `rustc_apfloat`, a port of APFloat).
- emit-C: an f32 literal now carries C's `f` suffix.
- `float_literal_value_text` (Ast.w) drops separators for both backends. The parser
  keeps them in the stored text so `render` and the bundle interface still print a
  literal as written; integer literals already normalize their own digits.

`with_parse_float_ref` is unchanged. Its remaining caller is CImport's macro
constant evaluation.

Evidence, Windows x86_64: the 88-literal corpus goes from 55 mismatches to 0 against
Python's nearest-double reference; `1.0000001788139343261718749` as f32 is 3f800001
(was 3f800002) on both backends, matching clang on the same text with `f`; `1_000.5`
is 408f440000000000 (was 3ff0000000000000, i.e. 1.0), and the emitted C compiles.

test/behavior/behav_float_literal.w covers all three. Its expected values are built
from exact operations (3.0 / 10.0, repeated halving), so it trusts no other literal.
…e f64; :e digits are exact

The default display (and :g, :?) normalized a value by repeated * 10.0 or
/ 10.0 before taking 15 digits, one rounding per step: of 3,032 values swept
across the exponent range, 883 printed a wrong digit, and f"{1e-300:e}" printed
10.000000e-301. Below 1 it printed 14 fractional digits rather than 15
significant ones, so 1/3/1e5 printed 0.00000333333333.

Digits now come from Burger & Dybvig's algorithm (PLDI 1996) on exact integers
(RtBig, 41 limbs), never from scaling the float. The default display prints the
shortest digits that read back as the value, the closest when several are that
short; :e prints exactly N+1 significant digits, correctly rounded, ties to even.
Switch points, exponent spelling, inf/nan/-0 and the :f modes are unchanged.

The spec leaves the digit count open (§15.4.2 g: "shortest of
fixed/scientific"); shortest round-trip is what Rust, Go, Zig, Python and JS
print. Checked against Python before touching the runtime: 25,239 values
(including every power of two and 20,000 random doubles), 0 mismatches in
shortest digits and 0 of 429,063 fixed-count digits.

Tests: behav_fstring_float_shortest.w, and behav_fstring_float_sweep.w (a golden
table of 290 values). wasm_alloc.w pinned the old 14-digit 1/3; it now expects
0.3333333333333333.
Use six significant digits by default and select notation from the rounded exponent. Honor explicit g precision, including zero and precision beyond the exact terminating expansion. Keep correctly rounded literal parsing and scientific digit generation.

Replace the proposed shortest-display golden sweep with a direct snprintf oracle for default and 30-digit output across 586 values. Boundary, literal, and oracle tests pass with pinned-seed-built stage1; full battery remains required.
…st targets

LLDB observes the bad integer conversion at old rt_core.w:152 and half-up floating arithmetic at :162. Replace the bounded-integer formatter with exact decimal rounding and size output for requested precision. Differential tests cover 592 values across eight C formats, including 1100-digit output, with zero debug-allocator leaks.

The emitted @convert(double)->u64 block used fptosi: CodegenDispatch selected from source signedness. Select from Sema destination type instead; a runtime-input regression defeats poison-based constant folding and fails on the old binary. Final cast verification and full pinned-seed battery remain pending; see docs/float-c-format-audit.md.
@ehartford
ehartford force-pushed the josh/float-round-trip branch from 302def9 to 0ab7f0f Compare September 25, 2026 18:06
@ehartford
ehartford changed the base branch from main to public-return-foundation September 25, 2026 18:06
@ehartford ehartford changed the title Floats round-trip: literals round once into their type, and the default display prints the shortest text that reads back as the same f64 Floats: correctly rounded literals and C-compatible general, fixed, and scientific formatting Sep 25, 2026
@ehartford
ehartford marked this pull request as ready for review September 25, 2026 18:07
@ehartford
ehartford merged commit 95726a7 into withlang-dev:public-return-foundation Sep 25, 2026
ehartford added a commit that referenced this pull request Sep 25, 2026
…1683)

* parser: honor public return inference independently of modeled C

Extract the specification-conformance correction from 869b2c7 so its seed can land without the unfinished retained-callback implementation. Preserve inference, imported/generic/method regressions and the D43 negative case.

* Require review of new explicit Unit returns and test visibility equivalence

Add the uncached unit-return-review gate to :test. Compare lexer-normalized declarations with the review base, reject unreviewed additions and untracked source, and require an exact signature plus semantic rationale for necessary annotations. Unit remains legal.

Validation: scanner tests pass; a real tracked-file annotation mutation exits 1 and is restored; build.w and src/main.w check pass with the fixed stage1. Generated private/public runtime and D43 rejection matrix passes on fixed stage1 and fails on the pinned seed with the exact unsupported public-return diagnostic. Full pinned-seed battery is still pending for the complete stack.

* Floats: correctly rounded literals and C-compatible general, fixed, and scientific formatting (#1649)

* codegen: round a float literal once, into the type it has

`with_parse_float_ref` (rt/rt_core.w) accumulates `result + digit * frac` with
`frac = frac * 0.1`. It is not correctly rounded: 55 of 88 sampled literals land
1-4 ulps from the nearest double, subnormals become 0.0, and `std.math.TAU` is
1 ulp low. The three LLVM constant sites handed its f64 to `LLVMConstReal`, so an
f32 literal was rounded a second time; emit-C assigned the literal to a `float`
with no `f` suffix, which rounds twice in C for the same reason. Digit separators,
which §29.1 says are ignored for value parsing, reached both backends: `1_000.5`
was 1.0 under LLVM, and emit-C wrote `1_000.5` into C, which clang rejects.

- LLVM: `wl_const_real_of_string` binds `LLVMConstRealOfString`, so APFloat converts
  the literal's own text straight into the target type -- the same conversion clang
  performs on the text emit-C writes. rustc does the same (`parse_float_into_scalar`
  over `rustc_apfloat`, a port of APFloat).
- emit-C: an f32 literal now carries C's `f` suffix.
- `float_literal_value_text` (Ast.w) drops separators for both backends. The parser
  keeps them in the stored text so `render` and the bundle interface still print a
  literal as written; integer literals already normalize their own digits.

`with_parse_float_ref` is unchanged. Its remaining caller is CImport's macro
constant evaluation.

Evidence, Windows x86_64: the 88-literal corpus goes from 55 mismatches to 0 against
Python's nearest-double reference; `1.0000001788139343261718749` as f32 is 3f800001
(was 3f800002) on both backends, matching clang on the same text with `f`; `1_000.5`
is 408f440000000000 (was 3ff0000000000000, i.e. 1.0), and the emitted C compiles.

test/behavior/behav_float_literal.w covers all three. Its expected values are built
from exact operations (3.0 / 10.0, repeated halving), so it trusts no other literal.

* rt: float display prints the shortest text that reads back as the same f64; :e digits are exact

The default display (and :g, :?) normalized a value by repeated * 10.0 or
/ 10.0 before taking 15 digits, one rounding per step: of 3,032 values swept
across the exponent range, 883 printed a wrong digit, and f"{1e-300:e}" printed
10.000000e-301. Below 1 it printed 14 fractional digits rather than 15
significant ones, so 1/3/1e5 printed 0.00000333333333.

Digits now come from Burger & Dybvig's algorithm (PLDI 1996) on exact integers
(RtBig, 41 limbs), never from scaling the float. The default display prints the
shortest digits that read back as the value, the closest when several are that
short; :e prints exactly N+1 significant digits, correctly rounded, ties to even.
Switch points, exponent spelling, inf/nan/-0 and the :f modes are unchanged.

The spec leaves the digit count open (§15.4.2 g: "shortest of
fixed/scientific"); shortest round-trip is what Rust, Go, Zig, Python and JS
print. Checked against Python before touching the runtime: 25,239 values
(including every power of two and 20,000 random doubles), 0 mismatches in
shortest digits and 0 of 429,063 fixed-count digits.

Tests: behav_fstring_float_shortest.w, and behav_fstring_float_sweep.w (a golden
table of 290 values). wasm_alloc.w pinned the old 14-digit 1/3; it now expects
0.3333333333333333.

* Follow C general float formatting under D68

Use six significant digits by default and select notation from the rounded exponent. Honor explicit g precision, including zero and precision beyond the exact terminating expansion. Keep correctly rounded literal parsing and scientific digit generation.

Replace the proposed shortest-display golden sweep with a direct snprintf oracle for default and 30-digit output across 586 values. Boundary, literal, and oracle tests pass with pinned-seed-built stage1; full battery remains required.

* Make fixed and scientific float output exact and preserve unsigned cast targets

LLDB observes the bad integer conversion at old rt_core.w:152 and half-up floating arithmetic at :162. Replace the bounded-integer formatter with exact decimal rounding and size output for requested precision. Differential tests cover 592 values across eight C formats, including 1100-digit output, with zero debug-allocator leaks.

The emitted @convert(double)->u64 block used fptosi: CodegenDispatch selected from source signedness. Select from Sema destination type instead; a runtime-input regression defeats poison-based constant folding and fails on the old binary. Final cast verification and full pinned-seed battery remain pending; see docs/float-c-format-audit.md.

* Record verified C float formatting and conversion evidence

---------

Co-authored-by: Josh Hickson <[email protected]>
Co-authored-by: Eric Hartford <[email protected]>

---------

Co-authored-by: Eric Hartford <[email protected]>
Co-authored-by: Joshua Hickson <[email protected]>
Co-authored-by: Josh Hickson <[email protected]>
ehartford added a commit that referenced this pull request Sep 25, 2026
#1649 was merged into the public-return-foundation branch and reached main inside #1683's squash (a5c6f43), which kept its commit messages but not its authorship. Record the credit where the work is documented.

Co-authored-by: Josh Hickson <[email protected]>
@ehartford

Copy link
Copy Markdown
Contributor

Attribution note: this PR was merged into public-return-foundation and reached main inside #1683's squash (a5c6f43), which carried the commit messages but not the authorship. The credit is now recorded on main (docs/float-c-format-audit.md, D68) with a Co-authored-by trailer for Josh Hickson (#1687). Thanks, Josh.

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.

2 participants