Commit b8ba5795

b8ba5795b945Merged

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

Description

Keep $stdout/$stderr puts valid and nil-typed in value position

$stdout.puts(x) / $stderr.puts(x) emitted its parts joined with ; (fputs(...); fputc('\n', stderr)), which is a statement sequence -- fine as a statement, but illegal inside the return (...) wrapper when the call is an if/else arm in value position. An if/else whose other arm is typed (e.g. File.open{...} or line.length) then failed to compile.

Two fixes:

  • Join the puts/print expansion with the comma operator so it is always a single valid C expression (also fixes multi-argument $stdout.puts, which had no separator between args, and gives puts a newline after each arg).
  • Type $stdout/$stderr .puts/.print/.write as nil, so a value-position use unifies and boxes as nil instead of leaking the fputc/fputs int return (a mismatched-type if/else otherwise printed 10, the newline byte, instead of nil).

Adds test/if_else_void_branch_value.rb.

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

Details

Commit
b8ba5795b945
Parent
f4a1285edecb

src/analyze_infer.cmodifiedView file

@@ -2104,6 +2104,14 @@
21042104
21052105 if (is_void_call(name) && recv < 0) return TY_VOID;
21062106
2107+ /* $stdout/$stderr.puts/print/write return nil (so a value-position use --
2108+ an if/else arm or assignment -- unifies and boxes as nil). */
2109+ if (recv >= 0 && (!strcmp(name, "puts") || !strcmp(name, "print") || !strcmp(name, "write")) &&
2110+ nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "GlobalVariableReadNode")) {
2111+ const char *gv = nt_str(nt, recv, "name");
2112+ if (gv && (!strcmp(gv, "$stdout") || !strcmp(gv, "$stderr"))) return TY_NIL;
2113+ }
2114+
21072115 /* tap: run block, return self */
21082116 if (!strcmp(name, "tap") && recv >= 0) return rt;
21092117 /* then / yield_self: run block, return block result */