Commit e888148a

e888148a7374Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified

Description

codegen: BeginNode as rvalue expression

Adds emit_expr support for BeginNode (begin..rescue..end as an expression value, e.g. puts (begin; raise; rescue; "x"; end)).

The code hoists the begin block into g_pre (the prelude buffer) and references the result temp inline, matching how other multi-statement expression forms work. Falls back to a GCC statement expression when g_pre is unavailable (e.g. inside another expression's prelude).

Also adds a forward declaration for emit_begin so emit_expr can call it before emit_begin's definition.

Co-Authored-By: Claude Sonnet 4.6 [email protected]

Details

Commit
e888148a7374
Parent
d963af260d92

src/codegen.cmodifiedView file

@@ -356,6 +356,7 @@
356356 static void emit_stmt(Compiler *c, int id, Buf *b, int indent);
357357 static void emit_stmts(Compiler *c, int id, Buf *b, int indent);
358358 static void emit_stmts_tail(Compiler *c, int id, Buf *b, int indent);
359+static void emit_begin(Compiler *c, int id, Buf *b, int indent, const char *resultvar);
359360 static int emit_array_mutate_stmt(Compiler *c, int id, Buf *b, int indent);
360361 static int emit_output_call(Compiler *c, int id, Buf *b, int indent);
361362 static int emit_iteration_stmt(Compiler *c, int id, Buf *b, int indent);
@@ -5457,6 +5458,33 @@
54575458 return;
54585459 }
54595460
5461+ if (!strcmp(ty, "BeginNode")) {
5462+ /* begin/rescue as an rvalue: hoist the block into g_pre so the temp
5463+ is assigned before the surrounding expression reads it. */
5464+ TyKind rt = comp_ntype(c, id);
5465+ int t = ++g_tmp;
5466+ char rv[32]; snprintf(rv, sizeof rv, "_t%d", t);
5467+ int sp = g_result_poly; g_result_poly = (rt == TY_POLY);
5468+ if (g_pre) {
5469+ emit_indent(g_pre, g_indent); emit_ctype(c, rt, g_pre);
5470+ buf_printf(g_pre, " _t%d = %s;\n", t, default_value(rt));
5471+ emit_begin(c, id, g_pre, g_indent, rv);
5472+ }
5473+ else {
5474+ /* No prelude available (e.g. inside another expression's prelude):
5475+ fall back to a GCC statement expression. */
5476+ buf_puts(b, "({ ");
5477+ emit_ctype(c, rt, b); buf_printf(b, " _t%d = %s;\n", t, default_value(rt));
5478+ emit_begin(c, id, b, 0, rv);
5479+ buf_printf(b, "_t%d; })", t);
5480+ g_result_poly = sp;
5481+ return;
5482+ }
5483+ g_result_poly = sp;
5484+ buf_printf(b, "_t%d", t);
5485+ return;
5486+ }
5487+
54605488 unsupported(c, id, "expression");
54615489 }
54625490
@@ -6294,6 +6322,7 @@
62946322 else {
62956323 if (has_retval) buf_printf(b, "if (_retf%d) return _retv%d;\n", eid, eid);
62966324 else if (g_ret_type == TY_POLY) buf_printf(b, "if (_retf%d) return sp_box_nil();\n", eid);
6325+ else if (g_ret_type == TY_UNKNOWN) buf_printf(b, "if (_retf%d) return 0;\n", eid); /* main() */
62976326 else buf_printf(b, "if (_retf%d) return;\n", eid);
62986327 }
62996328 return;