Commit a624878b

a624878b9aabMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 5 files · +2 added · ~3 modified

Description

codegen: compute Float#round/ceil/floor/truncate exactly for a non-literal ndigits

With a literal-integer ndigits these methods already match CRuby's value- based return class (Integer for ndigits <= 0, Float for ndigits > 0). With a NON-literal ndigits the C backend dropped the argument entirely and emitted (mrb_int)round(x), which both forced Integer and discarded the precision: 1.234.round(n) with n==2 returned 1 instead of 1.23, and 1234.5.round(n) with n==-1 returned 1235 instead of 1230. Those are wrong values, not just a #class difference.

Restore the documented behavior: a non-literal ndigits is typed Float and lowered to the runtime form round(x * 10**n) / 10**n, which is exact for any n. The result is numerically equal to CRuby's; only #class (and the default string form) still differs when n turns out <= 0, the residual divergence already described in docs/FLOAT-ROUNDING.md. Code needing an Integer converts with .to_i.

Also refresh that doc's stale implementation pointers (the legacy spinel_analyze.rb / spinel_codegen.rb are now analyze_infer.c / codegen_call.c).

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
a624878b9aab
Parent
fa7999fed514

docs/FLOAT-ROUNDING.mdmodifiedView file

@@ -38,10 +38,12 @@
3838
3939 So `x.round(n)` where `n` is a variable holding a non-positive value
4040 returns a Float (`10.0`) where CRuby returns an Integer (`10`). The
41-values are numerically equal; only `#class` and the default string form
42-(`"10.0"` vs `"10"`) differ. Code that needs an Integer can convert
41+**value is still computed exactly** (`1.234.round(n)` with `n == 2` is
42+`1.23`, `1234.5.round(n)` with `n == -1` is `1230.0`); the values are
43+numerically equal to CRuby's and only `#class` and the default string
44+form (`"10.0"` vs `"10"`) differ. Code that needs an Integer can convert
4345 explicitly: `x.round(n).to_i`.
4446
45-The implementation lives in `infer_method_name_type` (spinel_analyze.rb)
46-and `compile_float_round_expr` (spinel_codegen.rb); both classify a
47-literal-integer `ndigits` by sign and fall back to Float otherwise.
47+The implementation lives in `infer_call` (`src/analyze_infer.c`) and
48+`emit_scalar_call` (`src/codegen_call.c`); both classify a literal-integer
49+`ndigits` by sign and fall back to an exact Float computation otherwise.