Commit 525a45c6

525a45c6fb15Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 1 file · ~1 modified

Description

feat: add Array#any?, #all?, #none? with block

Iterates the array with short-circuit evaluation:

  • any? returns true on first truthy block result
  • all? returns false on first falsy block result
  • none? returns false on first truthy block result Works for all array element types.

Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]

Details

Commit
525a45c6fb15
Parent
0bbc43e823c1

spinel_codegen.rbmodifiedView file

@@ -12156,6 +12156,9 @@
1215612156 pfx = array_c_prefix(recv_type)
1215712157 return "(sp_" + pfx + "_length(" + rc + ") == 0)"
1215812158 end
12159+ if (mname == "any?" || mname == "all?" || mname == "none?") && @nd_block[nid] >= 0
12160+ return compile_array_predicate_block(nid, rc, recv_type, mname)
12161+ end
1215912162 # Array methods
1216012163 if recv_type == "int_array"
1216112164 if mname == "length"
@@ -16634,6 +16637,56 @@
1663416637 @in_loop = old
1663516638 end
1663616639
16640+ def compile_array_predicate_block(nid, rc, recv_type, mname)
16641+ # Implements any?/all?/none? with block by short-circuit loop
16642+ bp1 = get_block_param(nid, 0)
16643+ if bp1 == ""
16644+ bp1 = "_x"
16645+ end
16646+ # Infer element type for block parameter
16647+ elem_type = "int"
16648+ if recv_type == "str_array"
16649+ elem_type = "string"
16650+ elsif recv_type == "float_array"
16651+ elem_type = "float"
16652+ end
16653+ declare_var(bp1, elem_type)
16654+ tmp_res = new_temp
16655+ tmp_i = new_temp
16656+ pfx = array_c_prefix(recv_type)
16657+ init_val = "FALSE"
16658+ if mname == "all?" || mname == "none?"
16659+ init_val = "TRUE"
16660+ end
16661+ emit(" mrb_bool " + tmp_res + " = " + init_val + ";")
16662+ emit(" for (mrb_int " + tmp_i + " = 0; " + tmp_i + " < sp_" + pfx + "_length(" + rc + "); " + tmp_i + "++) {")
16663+ emit(" lv_" + bp1 + " = sp_" + pfx + "_get(" + rc + ", " + tmp_i + ");")
16664+ blk = @nd_block[nid]
16665+ bbody = @nd_body[blk]
16666+ bexpr = "0"
16667+ if bbody >= 0
16668+ bs = get_stmts(bbody)
16669+ if bs.length > 0
16670+ k = 0
16671+ while k < bs.length - 1
16672+ compile_stmt(bs[k])
16673+ k = k + 1
16674+ end
16675+ bexpr = compile_expr(bs.last)
16676+ end
16677+ end
16678+ if mname == "any?"
16679+ emit(" if (" + bexpr + ") { " + tmp_res + " = TRUE; break; }")
16680+ elsif mname == "all?"
16681+ emit(" if (!(" + bexpr + ")) { " + tmp_res + " = FALSE; break; }")
16682+ else
16683+ # none?
16684+ emit(" if (" + bexpr + ") { " + tmp_res + " = FALSE; break; }")
16685+ end
16686+ emit(" }")
16687+ tmp_res
16688+ end
16689+
1663716690 def compile_hash_select_reject(nid, hash_type, rc, mname)
1663816691 # Build a new hash by filtering entries using the block
1663916692 bp1 = get_block_param(nid, 0)