Commit ed3efe4f
ed3efe4f6befMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified
Description
Add if/unless as an expression (ternary)
x = if c then a else b end (and the ?: ternary, which Prism also
represents as IfNode) lower to (cond ? a : b) when both branches are
single value-expressions. analyze already unifies the branch types.
make test: 39.
Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]
Details
- Commit
- ed3efe4f6bef
- Parent
- bd123579b145
src/codegen.cmodifiedView file
@@ -171,6 +171,7 @@
171171
static int emit_iteration_stmt(Compiler *c, int id, Buf *b, int indent);172172
static int emit_inline_call(Compiler *c, int id, Buf *b, int indent);173173
static int emit_inline_expr(Compiler *c, int id, Buf *b);174+
static void emit_cond(Compiler *c, int id, Buf *b);174175
static int needs_root(TyKind t);175176
static void emit_index_op_write(Compiler *c, int id, Buf *b, int indent);176177
static void emit_super(Compiler *c, int id, Buf *b);@@ -1500,6 +1501,34 @@
15001501
buf_printf(b, "_t%d", t);15011502
return;15021503
}1504+
if (!strcmp(ty, "IfNode") || !strcmp(ty, "UnlessNode")) {1505+
/* if/unless as a value: a ternary when both branches are single1506+
value-expressions */1507+
int pred = nt_ref(nt, id, "predicate");1508+
int then_b = nt_ref(nt, id, "statements");1509+
int sub = nt_ref(nt, id, "subsequent");1510+
int is_unless = !strcmp(ty, "UnlessNode");1511+
int tn = 0;1512+
const int *tb = then_b >= 0 ? nt_arr(nt, then_b, "body", &tn) : NULL;1513+
int else_stmts = -1;1514+
if (sub >= 0 && nt_type(nt, sub) && !strcmp(nt_type(nt, sub), "ElseNode"))1515+
else_stmts = nt_ref(nt, sub, "statements");1516+
int en = 0;1517+
const int *eb = else_stmts >= 0 ? nt_arr(nt, else_stmts, "body", &en) : NULL;1518+
if (tn == 1 && en == 1) {1519+
buf_puts(b, "(");1520+
if (is_unless) buf_puts(b, "!(");1521+
emit_cond(c, pred, b);1522+
if (is_unless) buf_puts(b, ")");1523+
buf_puts(b, " ? ");1524+
emit_expr(c, tb[0], b);1525+
buf_puts(b, " : ");1526+
emit_expr(c, eb[0], b);1527+
buf_puts(b, ")");1528+
return;1529+
}1530+
unsupported(c, id, "if/unless expression");1531+
}15031532
if (!strcmp(ty, "CallNode")) { emit_call(c, id, b); return; }15041533
if (!strcmp(ty, "SuperNode") || !strcmp(ty, "ForwardingSuperNode")) { emit_super(c, id, b); return; }15051534
if (!strcmp(ty, "AndNode") || !strcmp(ty, "OrNode")) {