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
int is_sym_op = a0ty && !strcmp(a0ty, "SymbolNode") && argc == 1; if (!is_sym_op) { TyKind it = infer_type(c, argv[0]); if (it != TY_UNKNOWN) return it; if (it != TY_UNKNOWN) { /* The accumulator is reassigned to the block body each iteration, so an int seed folded over floats accumulates float. */ int rblk = nt_ref(nt, id, "block"); int rbody = rblk >= 0 ? nt_ref(nt, rblk, "body") : -1; int rbn = 0; const int *rbb = rbody >= 0 ? nt_arr(nt, rbody, "body", &rbn) : NULL; if (rbn > 0) { TyKind bt = infer_type(c, rbb[rbn - 1]); if (ty_is_numeric(bt)) it = ty_promote_numeric(it, bt); } return it; } } } /* empty array literal `[]` with sym op: codegen treats as int_array → returns int */src/codegen_fold.cmodifiedView file
Loading diff…
src/types.cmodifiedView file
Loading diff…
src/types.hmodifiedView file
Loading diff…
test/reduce_numeric_promotion.rbaddedView file
Loading diff…