Repository navigation
Floats: correctly rounded literals and C-compatible general, fixed, and scientific formatting - #1649
Conversation
|
How does C do this? We should make sure we do it the same way C does |
|
Rebased onto main
The 15 failures are identical with and without the PR, all C facade tests (zlib, bzip2, sqlite, libcurl |
`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.
302def9 to
0ab7f0f
Compare
…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]>
#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]>
|
Attribution note: this PR was merged into |
Float literals previously accumulated rounding error, and
f32literals could round twice. Parse decimal text directly into its destination type on LLVM; emit-C removes digit separators and supplies thef32suffix. 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. Explicitg,f, andeprecision uses exact decimal digits and ties-to-even rounding. Large fixed values and precision beyond 18 digits work without converting the integer part tou64or clamping precision.Debugging the old fixed formatter also exposed an independent float-to-unsigned cast bug: codegen selected
fptosifrom the source's signedness. It now uses Sema's destination type to selectfptoui. The regression gets values throughstrtodso constant folding cannot erase an invalid conversion.Validation on Darwin arm64, combined code head
1012a32b:snprintf: 592 values × eight general/fixed/scientific formats, including 1,100-digit precision; debug allocator reports zero leaks.f32double-rounding case.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/3output 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-foundationand merges separately after that foundation. The repository-owned PRs remain in stack #1685.