Commit bc6459e5

bc6459e56546Merged

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

Description

Implement multi-value return: a, b = func()

Multi-write with non-literal RHS now unpacks from IntArray/FloatArray. Supports: function returning [a, b], swap (a, b = b, a), and array literal multi-assign.

RHS evaluated once into temp variable, then elements extracted. Call-site param inference updated to discover multi-write calls.

58/58 tests, 39/39 benchmarks pass.

Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]

Details

Commit
bc6459e56546
Parent
95b4353b2b06

src/stmt.cmodifiedView file

@@ -2119,14 +2119,26 @@
21192119 }
21202120 ctx->indent--; emit(ctx, "}\n");
21212121 } else {
2122- /* RHS is a variable or expression — unpack via sp_IntArray_get */
2123- char *rhs = codegen_expr(ctx, n->value);
2122+ /* RHS is a variable or expression — evaluate once, unpack via sp_IntArray_get */
2123+ vtype_t rhs_type = infer_type(ctx, n->value);
2124+ char *rhs_expr = codegen_expr(ctx, n->value);
2125+ int mv_id = ctx->temp_counter++;
2126+ const char *arr_type = "sp_IntArray";
2127+ const char *get_fn = "sp_IntArray_get";
2128+ const char *len_fn = "sp_IntArray_length";
2129+ if (rhs_type.kind == SPINEL_TYPE_FLOAT_ARRAY) {
2130+ arr_type = "sp_FloatArray";
2131+ get_fn = "sp_FloatArray_get";
2132+ len_fn = "sp_FloatArray_length";
2133+ }
2134+ emit(ctx, "{ %s *_mv_%d = %s;\n", arr_type, mv_id, rhs_expr);
2135+ ctx->indent++;
21242136 for (size_t i = 0; i < n->lefts.size; i++) {
21252137 if (PM_NODE_TYPE(n->lefts.nodes[i]) == PM_LOCAL_VARIABLE_TARGET_NODE) {
21262138 pm_local_variable_target_node_t *t = (pm_local_variable_target_node_t *)n->lefts.nodes[i];
21272139 char *vn = cstr(ctx, t->name);
21282140 char *cn = make_cname(vn, false);
2129- emit(ctx, "%s = sp_IntArray_get(%s, %d);\n", cn, rhs, (int)i);
2141+ emit(ctx, "%s = %s(_mv_%d, %d);\n", cn, get_fn, mv_id, (int)i);
21302142 free(vn); free(cn);
21312143 }
21322144 }
@@ -2138,15 +2150,17 @@
21382150 char *vn = cstr(ctx, t->name);
21392151 char *cn = make_cname(vn, false);
21402152 int tmp = ctx->temp_counter++;
2141- emit(ctx, "{ sp_IntArray *_rest_%d = sp_IntArray_new();\n", tmp);
2142- emit(ctx, " for (mrb_int _ri_%d = %d; _ri_%d < sp_IntArray_length(%s); _ri_%d++)\n",
2143- tmp, (int)n->lefts.size, tmp, rhs, tmp);
2144- emit(ctx, " sp_IntArray_push(_rest_%d, sp_IntArray_get(%s, _ri_%d));\n", tmp, rhs, tmp);
2153+ emit(ctx, "{ %s *_rest_%d = %s_new();\n", arr_type, tmp, arr_type);
2154+ emit(ctx, " for (mrb_int _ri_%d = %d; _ri_%d < %s(_mv_%d); _ri_%d++)\n",
2155+ tmp, (int)n->lefts.size, tmp, len_fn, mv_id, tmp);
2156+ emit(ctx, " %s_push(_rest_%d, %s(_mv_%d, _ri_%d));\n", arr_type, tmp, get_fn, mv_id, tmp);
21452157 emit(ctx, " %s = _rest_%d; }\n", cn, tmp);
21462158 free(vn); free(cn);
21472159 }
21482160 }
2149- free(rhs);
2161+ ctx->indent--;
2162+ emit(ctx, "}\n");
2163+ free(rhs_expr);
21502164 }
21512165 break;
21522166 }