Commit d40bc31b
d40bc31b97a3Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified
Description
Merge pull request #1423 from rubys/fix/blog-remaining-blockers
codegen: reconcile bare/value returns with the inferred return type
Details
- Commit
- d40bc31b97a3
- Parent
- 7a3a0611a278
- Merge parent
- fa8898f08625
src/codegen_stmt.cmodifiedView file
@@ -1735,6 +1735,18 @@
17351735
}17361736
buf_printf(b, " return _t%d; }\n", ta);17371737
}1738+
else if (n > 0 && g_ret_type == TY_VOID) {1739+
/* void function: a `return <expr>` (typically `return nil`) discards its1740+
value. Evaluate a non-literal expr for side effects, then a bare return,1741+
so the generated C doesn't `return <value>` from a void function. */1742+
const char *aty = nt_type(c->nt, a[0]);1743+
int trivial = aty && (!strcmp(aty, "NilNode") || !strcmp(aty, "IntegerNode") ||1744+
!strcmp(aty, "FloatNode") || !strcmp(aty, "StringNode") ||1745+
!strcmp(aty, "SymbolNode") || !strcmp(aty, "TrueNode") ||1746+
!strcmp(aty, "FalseNode"));1747+
if (!trivial) { buf_puts(b, "(void)("); emit_expr(c, a[0], b); buf_puts(b, "); "); }1748+
buf_puts(b, "return;\n");1749+
}17381750
else if (n > 0) {17391751
buf_puts(b, "return ");17401752
TyKind r0 = comp_ntype(c, a[0]);@@ -1747,7 +1759,14 @@
17471759
buf_puts(b, ";\n");17481760
}17491761
else if (g_ret_type == TY_POLY) buf_puts(b, "return sp_box_nil();\n");1750-
else buf_puts(b, "return;\n");1762+
else if (g_ret_type == TY_VOID || g_ret_type == TY_UNKNOWN) buf_puts(b, "return;\n");1763+
/* bare `return` is Ruby nil: emit the return type's nil representation, not a1764+
bare `return;` (illegal in a non-void C function -- e.g. `Db.close` returns1765+
a nullable DbPool*, where nil is NULL). */1766+
else if (g_ret_type == TY_INT) buf_puts(b, "return SP_INT_NIL;\n");1767+
else if (g_ret_type == TY_FLOAT) buf_puts(b, "return sp_float_nil();\n");1768+
else if (g_ret_type == TY_STRING) buf_puts(b, "return NULL;\n");1769+
else buf_printf(b, "return %s;\n", default_value(g_ret_type));17511770
}17521771
17531772
void emit_stmt_inner(Compiler *c, int id, Buf *b, int indent);test/return_void_and_nullable_object.rbaddedView file
Loading diff…
test/return_void_and_nullable_object.rb.expectedaddedView file
Loading diff…