Commit 37f49719
37f49719f32fMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · ~2 modified
Description
Spaceship operator and comparator-block sort/min/max/minmax
Add the <=> operator for numeric and string operands (returning -1/0/1 via the sign idiom), and the comparator-block forms of sort, min, max and minmax on arrays. The comparator block binds both parameters to the element type and yields the ordering; sort bubble-sorts a copy, while min/max/minmax scan once. Homogeneous receivers work; reusing the same block-parameter names across differently-typed receivers still hits the shared-local widening limit.
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- 37f49719f32f
- Parent
- 027bd45bce55
src/analyze.cmodifiedView file
@@ -825,6 +825,9 @@
825825
return (rt == TY_FLOAT || a0 == TY_FLOAT) ? TY_FLOAT : TY_INT;826826
return TY_UNKNOWN;827827
}828+
if (recv >= 0 && argc == 1 && !strcmp(name, "<=>") &&829+
((ty_is_numeric(rt) && ty_is_numeric(a0)) || (rt == TY_STRING && a0 == TY_STRING)))830+
return TY_INT;828831
if (recv >= 0 && argc == 1 && is_cmp_op(name)) {829832
if (!strcmp(name, "<=>")) return TY_INT;830833
return TY_BOOL;@@ -2071,6 +2074,21 @@
20712074
continue;20722075
}20732076
2077+
/* array.sort/min/max/minmax { |a, b| cmp } -- a comparator block binds2078+
both parameters to the element type */2079+
if ((!strcmp(name, "sort") || !strcmp(name, "min") || !strcmp(name, "max") ||2080+
!strcmp(name, "minmax")) && ty_is_array(rt)) {2081+
Scope *cs = comp_scope_of(c, block);2082+
for (int pj = 0; pj < 2; pj++) {2083+
const char *pn = block_param_name(c, block, pj);2084+
if (!pn) continue;2085+
LocalVar *lp = scope_local_intern(cs, pn); lp->is_block_param = 1;2086+
TyKind m = ty_unify(lp->type, ty_array_elem(rt));2087+
if (m != lp->type) { lp->type = m; changed = 1; }2088+
}2089+
continue;2090+
}2091+
20742092
/* array.each_with_index { |x, i| } binds element + int index */20752093
if (!strcmp(name, "each_with_index") && ty_is_array(rt)) {20762094
Scope *es = comp_scope_of(c, block);src/codegen.cmodifiedView file
Loading diff…