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] >= 0
2038420384 return compile_array_find_block(nid, rc, recv_type)
2038520385 end
20386+ if mname == "find_index" && @nd_block[nid] >= 0
20387+ return compile_array_find_index_block(nid, rc, recv_type)
20388+ end
2038620389 if mname == "filter_map" && @nd_block[nid] >= 0
2038720390 return compile_array_filter_map(nid, rc, recv_type)
2038820391 end
@@ -37382,6 +37385,42 @@
3738237385 tmp_res
3738337386 end
3738437387
37388+ # Array#find_index { block } -- returns the FIRST index where
37389+ # the block is truthy, nil otherwise. Mirrors compile_array_find_block
37390+ # 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+ end
37397+ elem_type = iter_elem_type(recv_type)
37398+ tmp_res = new_temp
37399+ tmp_i = new_temp
37400+ emit(" mrb_int " + tmp_res + " = SP_INT_NIL;")
37401+ emit_iter_open(rc, recv_type, "lv_" + bp1, tmp_i)
37402+ push_scope
37403+ declare_var(bp1, elem_type)
37404+ blk = @nd_block[nid]
37405+ bbody = @nd_body[blk]
37406+ bexpr = "0"
37407+ if bbody >= 0
37408+ bs = get_stmts(bbody)
37409+ if bs.length > 0
37410+ k = 0
37411+ while k < bs.length - 1
37412+ compile_stmt(bs[k])
37413+ k = k + 1
37414+ end
37415+ bexpr = compile_expr(bs.last)
37416+ end
37417+ end
37418+ emit(" if (" + bexpr + ") { " + tmp_res + " = " + tmp_i + "; break; }")
37419+ pop_scope
37420+ emit(" }")
37421+ tmp_res
37422+ end
37423+
3738537424 def compile_array_predicate_block(nid, rc, recv_type, mname)
3738637425 # Implements any?/all?/none? with block by short-circuit loop
3738737426 bp1 = get_block_param(nid, 0)