Commit f4a1285e

f4a1285edecbMerged

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

Description

Promote a reduce accumulator from int seed to float fold

[1.5, 2.5].reduce(0) { |a, x| a + x } returned 3, not 4.0: the accumulator's type was taken from the seed alone (0 -> int), both for the reduce return type (infer_type) and the C accumulator variable (codegen). Each iteration then truncated the float fold back to int.

In Ruby the accumulator is reassigned to the block body every iteration, so an int seed folded over floats accumulates float. Add ty_promote_numeric (int/float/bigint mixed -> the widest; non-numeric falls back to ty_unify) and apply it to the seed using the fold body's result type, at both the reduce return type and the C accumulator type so they agree.

Guard the promotion to a numeric body: a transient-poly body (e.g. the inner block param of a 3-stage map.map.reduce chain that has not yet re-narrowed) must keep the seed type, otherwise the accumulator widens to poly and the seed 0 no longer initializes it. A genuinely poly fold is unaffected -- codegen re-types the params and re-infers the body under its shadow scope.

Adds test/reduce_numeric_promotion.rb (float promotion, int-stays-int, string-element int body, explicit to_f, and the chained-map fold).

Refs #1392 Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

Details

Commit
f4a1285edecb
Parent
6dcb31bf5ceb

src/analyze_infer.cmodifiedView file

@@ -1454,7 +1454,15 @@
14541454 int is_sym_op = a0ty && !strcmp(a0ty, "SymbolNode") && argc == 1;
14551455 if (!is_sym_op) {
14561456 TyKind it = infer_type(c, argv[0]);
1457- if (it != TY_UNKNOWN) return it;
1457+ if (it != TY_UNKNOWN) {
1458+ /* The accumulator is reassigned to the block body each iteration,
1459+ so an int seed folded over floats accumulates float. */
1460+ int rblk = nt_ref(nt, id, "block");
1461+ int rbody = rblk >= 0 ? nt_ref(nt, rblk, "body") : -1;
1462+ int rbn = 0; const int *rbb = rbody >= 0 ? nt_arr(nt, rbody, "body", &rbn) : NULL;
1463+ if (rbn > 0) { TyKind bt = infer_type(c, rbb[rbn - 1]); if (ty_is_numeric(bt)) it = ty_promote_numeric(it, bt); }
1464+ return it;
1465+ }
14581466 }
14591467 }
14601468 /* empty array literal `[]` with sym op: codegen treats as int_array → returns int */