Commit 7b4d8127

7b4d8127849dMerged

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

Description

feat: add Array#first(n) and Array#last(n) with argument

With an integer argument, returns a new array of the first or last n elements respectively. Without an argument, still returns a single element as before. Works for all array element types.

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

Details

Commit
7b4d8127849d
Parent
652badece270

spinel_codegen.rbmodifiedView file

@@ -1834,21 +1834,22 @@
18341834 end
18351835 return "int_array"
18361836 end
1837- if mname == "first"
1837+ if mname == "first" || mname == "last"
18381838 if recv >= 0
18391839 rt = infer_type(recv)
1840- if rt == "str_array"
1841- return "string"
1840+ # With arg → returns array of same type
1841+ if @nd_arguments[nid] >= 0
1842+ aargs = get_args(@nd_arguments[nid])
1843+ if aargs.length > 0
1844+ return rt
1845+ end
18421846 end
1843- end
1844- return "int"
1845- end
1846- if mname == "last"
1847- if recv >= 0
1848- rt = infer_type(recv)
18491847 if rt == "str_array"
18501848 return "string"
18511849 end
1850+ if rt == "float_array"
1851+ return "float"
1852+ end
18521853 end
18531854 return "int"
18541855 end
@@ -12192,6 +12193,35 @@
1219212193 if recv_type == "str_int_hash" || recv_type == "str_str_hash"
1219312194 return ""
1219412195 end
12196+ # first(n) / last(n) with argument: return new array
12197+ if mname == "first" && @nd_arguments[nid] >= 0
12198+ aargs = get_args(@nd_arguments[nid])
12199+ if aargs.length > 0
12200+ pfx = array_c_prefix(recv_type)
12201+ n = compile_expr(aargs[0])
12202+ tmp = new_temp
12203+ itmp = new_temp
12204+ emit(" " + c_type(recv_type) + " " + tmp + " = sp_" + pfx + "_new();")
12205+ emit(" for (mrb_int " + itmp + " = 0; " + itmp + " < " + n + " && " + itmp + " < sp_" + pfx + "_length(" + rc + "); " + itmp + "++)")
12206+ emit(" sp_" + pfx + "_push(" + tmp + ", sp_" + pfx + "_get(" + rc + ", " + itmp + "));")
12207+ return tmp
12208+ end
12209+ end
12210+ if mname == "last" && @nd_arguments[nid] >= 0
12211+ aargs = get_args(@nd_arguments[nid])
12212+ if aargs.length > 0
12213+ pfx = array_c_prefix(recv_type)
12214+ n = compile_expr(aargs[0])
12215+ tmp = new_temp
12216+ itmp = new_temp
12217+ len_tmp = new_temp
12218+ emit(" mrb_int " + len_tmp + " = sp_" + pfx + "_length(" + rc + ");")
12219+ emit(" " + c_type(recv_type) + " " + tmp + " = sp_" + pfx + "_new();")
12220+ emit(" for (mrb_int " + itmp + " = (" + len_tmp + " - " + n + " < 0 ? 0 : " + len_tmp + " - " + n + "); " + itmp + " < " + len_tmp + "; " + itmp + "++)")
12221+ emit(" sp_" + pfx + "_push(" + tmp + ", sp_" + pfx + "_get(" + rc + ", " + itmp + "));")
12222+ return tmp
12223+ end
12224+ end
1219512225 # Common array methods (all array types)
1219612226 if mname == "take"
1219712227 pfx = array_c_prefix(recv_type)