Commit 89af54f4

89af54f49b71Merged

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

Description

Add array.each_slice(n).map { |x, y| } chain support

Infer each_slice.map return type as array of block result, infer block params as source array element type, and emit a direct slice loop in codegen that destructures multi-params from indexed array elements.

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

Details

Commit
89af54f49b71
Parent
101c0077d3e1

src/analyze.cmodifiedView file

@@ -701,6 +701,19 @@
701701 }
702702 }
703703
704+ /* each_slice(n).map/collect { |...| } chain: return array of block result type */
705+ if (recv >= 0 && rt == TY_UNKNOWN && (!strcmp(name, "map") || !strcmp(name, "collect")) &&
706+ nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "CallNode") &&
707+ nt_str(nt, recv, "name") && !strcmp(nt_str(nt, recv, "name"), "each_slice") &&
708+ nt_ref(nt, recv, "block") < 0) {
709+ int blk_es = nt_ref(nt, id, "block");
710+ if (blk_es >= 0) {
711+ int body_es = nt_ref(nt, blk_es, "body");
712+ int bn_es = 0; const int *bb_es = body_es >= 0 ? nt_arr(nt, body_es, "body", &bn_es) : NULL;
713+ return ty_array_of(bn_es > 0 ? infer_type(c, bb_es[bn_es - 1]) : TY_UNKNOWN);
714+ }
715+ }
716+
704717 /* array receiver methods */
705718 if (recv >= 0 && ty_is_array(rt)) {
706719 int block = nt_ref(nt, id, "block");
@@ -3613,6 +3626,31 @@
36133626 continue;
36143627 }
36153628
3629+ /* array.each_slice(n).map/collect { |x, y, ...| } chain: each block param
3630+ gets the element type of the original array (slice elements) */
3631+ if ((!strcmp(name, "map") || !strcmp(name, "collect")) && rt == TY_UNKNOWN &&
3632+ nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "CallNode") &&
3633+ nt_str(nt, recv, "name") && !strcmp(nt_str(nt, recv, "name"), "each_slice") &&
3634+ nt_ref(nt, recv, "block") < 0) {
3635+ int es_recv2 = nt_ref(nt, recv, "receiver");
3636+ TyKind arr_t2 = es_recv2 >= 0 ? infer_type(c, es_recv2) : TY_UNKNOWN;
3637+ if (ty_is_array(arr_t2)) {
3638+ TyKind elem_t2 = ty_array_elem(arr_t2);
3639+ if (elem_t2 != TY_UNKNOWN) {
3640+ Scope *es2 = comp_scope_of(c, block);
3641+ int np2 = 0; while (block_param_name(c, block, np2)) np2++;
3642+ for (int pj2 = 0; pj2 < np2; pj2++) {
3643+ const char *pn2 = block_param_name(c, block, pj2);
3644+ if (!pn2) break;
3645+ LocalVar *lp2 = scope_local_intern(es2, pn2); lp2->is_block_param = 1;
3646+ TyKind m2 = ty_unify(lp2->type, elem_t2);
3647+ if (m2 != lp2->type) { lp2->type = m2; changed = 1; }
3648+ }
3649+ continue;
3650+ }
3651+ }
3652+ }
3653+
36163654 /* array.combination(k) { |c| } binds the k-element sub-array (same kind) */
36173655 if (!strcmp(name, "combination") && ty_is_array(rt)) {
36183656 LocalVar *lp = scope_local_intern(comp_scope_of(c, block), p0); lp->is_block_param = 1;