Commit 2af8b178
2af8b1781a6bMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified
Description
codegen: evaluate a nullable int once in its to_s / inspect
<nullable int>.to_s and .inspect lower to a test-then-convert
(x == SP_INT_NIL ? "" : sp_int_to_s(x)), but the receiver text x was
inlined into both arms, so a side-effecting receiver ran twice -- e.g.
puts ARGF.read.length read stdin twice (the second hit EOF and printed
0), and a counter-bumping step.to_s double-counted.
Bind the receiver to a temp in a statement-expression so it is evaluated exactly once. Idempotent receivers are unaffected.
Refs #1157
Details
- Commit
- 2af8b1781a6b
- Parent
- ab5c2555097b
src/codegen_call.cmodifiedView file
@@ -8025,8 +8025,17 @@
80258025
else handled = 0;80268026
}80278027
else if (rt == TY_INT) {8028-
if (!strcmp(name, "to_s") && argc == 0) buf_printf(b, "((%s) == SP_INT_NIL ? SPL(\"\") : sp_int_to_s(%s))", r, r);8029-
else if (!strcmp(name, "inspect")) buf_printf(b, "((%s) == SP_INT_NIL ? SPL(\"nil\") : sp_int_to_s(%s))", r, r);8028+
/* a nullable int's to_s/inspect tests the value and converts it -- bind8029+
the receiver to a temp first so a side-effecting `r` (e.g. ARGF.read,8030+
a method call) is evaluated exactly once, not twice. */8031+
if (!strcmp(name, "to_s") && argc == 0) {8032+
int _tn = ++g_tmp;8033+
buf_printf(b, "({ mrb_int _t%d = (%s); _t%d == SP_INT_NIL ? SPL(\"\") : sp_int_to_s(_t%d); })", _tn, r, _tn, _tn);8034+
}8035+
else if (!strcmp(name, "inspect")) {8036+
int _tn = ++g_tmp;8037+
buf_printf(b, "({ mrb_int _t%d = (%s); _t%d == SP_INT_NIL ? SPL(\"nil\") : sp_int_to_s(_t%d); })", _tn, r, _tn, _tn);8038+
}80308039
else if (!strcmp(name, "to_f")) buf_printf(b, "((mrb_float)(%s))", r);80318040
else if ((!strcmp(name, "to_i") || !strcmp(name, "to_int") || !strcmp(name, "floor") ||80328041
!strcmp(name, "ceil") || !strcmp(name, "round") || !strcmp(name, "truncate")) &&test/nullable_int_to_s_evaluates_once.rbaddedView file
Loading diff…
test/nullable_int_to_s_evaluates_once.rb.expectedaddedView file
Loading diff…