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
end18351835
return "int_array"18361836
end1837-
if mname == "first"1837+
if mname == "first" || mname == "last"18381838
if recv >= 018391839
rt = infer_type(recv)1840-
if rt == "str_array"1841-
return "string"1840+
# With arg → returns array of same type1841+
if @nd_arguments[nid] >= 01842+
aargs = get_args(@nd_arguments[nid])1843+
if aargs.length > 01844+
return rt1845+
end18421846
end1843-
end1844-
return "int"1845-
end1846-
if mname == "last"1847-
if recv >= 01848-
rt = infer_type(recv)18491847
if rt == "str_array"18501848
return "string"18511849
end1850+
if rt == "float_array"1851+
return "float"1852+
end18521853
end18531854
return "int"18541855
end@@ -12192,6 +12193,35 @@
1219212193
if recv_type == "str_int_hash" || recv_type == "str_str_hash"1219312194
return ""1219412195
end12196+
# first(n) / last(n) with argument: return new array12197+
if mname == "first" && @nd_arguments[nid] >= 012198+
aargs = get_args(@nd_arguments[nid])12199+
if aargs.length > 012200+
pfx = array_c_prefix(recv_type)12201+
n = compile_expr(aargs[0])12202+
tmp = new_temp12203+
itmp = new_temp12204+
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 tmp12208+
end12209+
end12210+
if mname == "last" && @nd_arguments[nid] >= 012211+
aargs = get_args(@nd_arguments[nid])12212+
if aargs.length > 012213+
pfx = array_c_prefix(recv_type)12214+
n = compile_expr(aargs[0])12215+
tmp = new_temp12216+
itmp = new_temp12217+
len_tmp = new_temp12218+
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 tmp12223+
end12224+
end1219512225
# Common array methods (all array types)1219612226
if mname == "take"1219712227
pfx = array_c_prefix(recv_type)