Commit 193a8d85
193a8d856d21Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified
Description
codegen: Array#find_index with block returns first matching index
[1,2,3].find_index { |x| x > 2 } should return the index of the
first truthy block result. The block form fell through to the
unresolved-call fallback. The value-arg form already worked.
Mirror compile_array_find_block but capture the loop index (int? sentinel SP_INT_NIL for not-found).
Refs #864
Co-Authored-By: Claude Opus 4.7 [email protected]
Details
- Commit
- 193a8d856d21
- Parent
- 316a8220c758
spinel_codegen.rbmodifiedView file
@@ -20383,6 +20383,9 @@
2038320383
if (mname == "find" || mname == "detect") && @nd_block[nid] >= 02038420384
return compile_array_find_block(nid, rc, recv_type)2038520385
end20386+
if mname == "find_index" && @nd_block[nid] >= 020387+
return compile_array_find_index_block(nid, rc, recv_type)20388+
end2038620389
if mname == "filter_map" && @nd_block[nid] >= 02038720390
return compile_array_filter_map(nid, rc, recv_type)2038820391
end@@ -37382,6 +37385,42 @@
3738237385
tmp_res3738337386
end3738437387
37388+
# Array#find_index { block } -- returns the FIRST index where37389+
# the block is truthy, nil otherwise. Mirrors compile_array_find_block37390+
# but captures the index instead of the element. Result is int?37391+
# (SP_INT_NIL sentinel for nil). Issue #864.37392+
def compile_array_find_index_block(nid, rc, recv_type)37393+
bp1 = get_block_param(nid, 0)37394+
if bp1 == ""37395+
bp1 = "_x"37396+
end37397+
elem_type = iter_elem_type(recv_type)37398+
tmp_res = new_temp37399+
tmp_i = new_temp37400+
emit(" mrb_int " + tmp_res + " = SP_INT_NIL;")37401+
emit_iter_open(rc, recv_type, "lv_" + bp1, tmp_i)37402+
push_scope37403+
declare_var(bp1, elem_type)37404+
blk = @nd_block[nid]37405+
bbody = @nd_body[blk]37406+
bexpr = "0"37407+
if bbody >= 037408+
bs = get_stmts(bbody)37409+
if bs.length > 037410+
k = 037411+
while k < bs.length - 137412+
compile_stmt(bs[k])37413+
k = k + 137414+
end37415+
bexpr = compile_expr(bs.last)37416+
end37417+
end37418+
emit(" if (" + bexpr + ") { " + tmp_res + " = " + tmp_i + "; break; }")37419+
pop_scope37420+
emit(" }")37421+
tmp_res37422+
end37423+
3738537424
def compile_array_predicate_block(nid, rc, recv_type, mname)3738637425
# Implements any?/all?/none? with block by short-circuit loop3738737426
bp1 = get_block_param(nid, 0)test/array_find_index_block.rbaddedView file
Loading diff…
test/array_find_index_block.rb.expectedaddedView file
Loading diff…