Commit 378e47f1
378e47f1f9d0Merged
Ryan Seys <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified
Description
feat(iter): flat_map { |x| x } identity one-level flatten
flat_map with an identity block over an array of arrays is exactly
flatten(1): each sub-array is concatenated and scalars pass through. The block
returns the bare element -- a poly element, not statically an array -- so the
array-returning flat_map path declined it. Recognize the identity block over a
poly-array receiver and emit the existing one-level runtime flatten directly,
reusing the depth-bounded walker rather than the per-element map/concat loop.
Details
- Commit
- 378e47f1f9d0
- Parent
- 1ed7a764a8bb
src/codegen_fold.cmodifiedView file
@@ -517,6 +517,23 @@
517517
int body = nt_ref(nt, block, "body");518518
int bn = 0; const int *bb = body >= 0 ? nt_arr(nt, body, "body", &bn) : NULL;519519
if (bn < 1) return 0;520+
/* Identity block `{ |x| x }` over an array of arrays is a one-level flatten,521+
equivalent to `flatten(1)`: each sub-array element is unboxed inline and522+
scalars pass through. The block returns the bare element (a poly element,523+
not statically an array), so the array-returning path below cannot handle524+
it; emit the runtime flatten directly. */525+
if (bn == 1 && rt == TY_POLY_ARRAY) {526+
const char *p0 = block_param_name(c, block, 0);527+
const char *sty = nt_type(nt, bb[0]);528+
if (p0 && !block_param_name(c, block, 1) && sty &&529+
!strcmp(sty, "LocalVariableReadNode") && nt_str(nt, bb[0], "name") &&530+
!strcmp(nt_str(nt, bb[0], "name"), p0)) {531+
buf_puts(b, "sp_PolyArray_flatten_n(");532+
emit_expr(c, recv, b);533+
buf_puts(b, ", 1)");534+
return 1;535+
}536+
}520537
TyKind bret = comp_ntype(c, bb[bn - 1]);521538
if (!ty_is_array(bret)) return 0; /* only array-returning blocks */522539
const char *bk = (bret == TY_POLY_ARRAY) ? "Poly" : array_kind(bret);test/flat_map_identity.rbaddedView file
Loading diff…
test/flat_map_identity.rb.expectedaddedView file
Loading diff…