Commit f2f8031e
f2f8031ea03aMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · ~2 modified
Description
Array#first/#last: empty -> nil, and the first(n)/last(n) forms
first/last of an empty array literal now read as nil, carried as the SP_INT_NIL sentinel so .inspect renders "nil" and .nil? is true. The arity-1 forms first(n)/last(n) return a subarray of the same kind via sp_*Array_slice (last(n) uses slice's negative-start-from-end).
Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]
Details
- Commit
- f2f8031ea03a
- Parent
- 24f08f66e281
src/analyze.cmodifiedView file
@@ -216,7 +216,11 @@
216216
const char *rty = nt_type(nt, recv);217217
if (rty && !strcmp(rty, "ArrayNode")) {218218
int en = 0; nt_arr(nt, recv, "elements", &en);219-
if (en == 0) rt = TY_POLY_ARRAY;219+
if (en == 0) {220+
/* first/last of an empty array is nil; carry it as a nullable int */221+
if ((!strcmp(name, "first") || !strcmp(name, "last")) && argc == 0) return TY_INT;222+
rt = TY_POLY_ARRAY;223+
}220224
}221225
}222226
@@ -465,6 +469,7 @@
465469
if (!strcmp(name, "length") || !strcmp(name, "size") ||466470
!strcmp(name, "count") || !strcmp(name, "index")) return TY_INT;467471
if (!strcmp(name, "sum")) return ty_array_elem(rt);472+
if ((!strcmp(name, "first") || !strcmp(name, "last")) && argc == 1) return rt; /* first(n)/last(n) -> subarray */468473
if (!strcmp(name, "first") || !strcmp(name, "last") ||469474
!strcmp(name, "min") || !strcmp(name, "max") ||470475
!strcmp(name, "pop")) return ty_array_elem(rt);src/codegen.cmodifiedView file
Loading diff…