Commit be5c851f

be5c851ff948Merged

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

Description

Array#each_cons with block destructuring

each_cons(n) iterates the sliding window of n consecutive elements. A single block param binds the n-element sub-array; multiple params destructure the window into scalar elements.

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
be5c851ff948
Parent
d13db6984168

src/analyze.cmodifiedView file

@@ -1939,6 +1939,21 @@
19391939 ty_is_array(rt))
19401940 pt = ty_array_elem(rt);
19411941
1942+ /* array.each_cons(n) { |a, b, ...| } -- a single param binds the n-element
1943+ sub-array; multiple params destructure consecutive elements */
1944+ if (!strcmp(name, "each_cons") && ty_is_array(rt)) {
1945+ Scope *es = comp_scope_of(c, block);
1946+ int np = 0; while (block_param_name(c, block, np)) np++;
1947+ for (int pj = 0; pj < np; pj++) {
1948+ const char *pn = block_param_name(c, block, pj);
1949+ LocalVar *lp = scope_local_intern(es, pn); lp->is_block_param = 1;
1950+ TyKind want = (np == 1) ? rt : ty_array_elem(rt);
1951+ TyKind m = ty_unify(lp->type, want);
1952+ if (m != lp->type) { lp->type = m; changed = 1; }
1953+ }
1954+ continue;
1955+ }
1956+
19421957 /* array.each_with_index { |x, i| } binds element + int index */
19431958 if (!strcmp(name, "each_with_index") && ty_is_array(rt)) {
19441959 Scope *es = comp_scope_of(c, block);