Commit 24a6b1d1
24a6b1d112e3Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · ~2 modified
Description
Hash#map { |k, v| ... }
Type the (k, v) block params for the hash block methods (map/select/reject/ sort_by/... ) the same way hash#each does, infer hash#map/collect's result as an array of the block value, and emit hash#map as a loop over the hash entries collecting block values into a result array.
make test: 187 pass / 6 fail / 651 error (was 186 / 6 / 652); hash_map_block green, no regressions.
Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]
Details
- Commit
- 24a6b1d112e3
- Parent
- b8825f5e0883
src/analyze.cmodifiedView file
@@ -539,6 +539,15 @@
539539
!strcmp(name, "count")) return TY_INT;540540
if (!strcmp(name, "keys")) return ty_array_of(ty_hash_key(rt));541541
if (!strcmp(name, "values")) return ty_array_of(ty_hash_val(rt));542+
{543+
int block = nt_ref(nt, id, "block");544+
if (block >= 0 && (!strcmp(name, "map") || !strcmp(name, "collect"))) {545+
int body = nt_ref(nt, block, "body");546+
int bn = 0; const int *bb = body >= 0 ? nt_arr(nt, body, "body", &bn) : NULL;547+
return ty_array_of(bn > 0 ? infer_type(c, bb[bn - 1]) : TY_UNKNOWN);548+
}549+
if (block >= 0 && (!strcmp(name, "select") || !strcmp(name, "filter") || !strcmp(name, "reject"))) return rt;550+
}542551
if (!strcmp(name, "merge") || !strcmp(name, "dup") || !strcmp(name, "clone")) return rt;543552
if (!strcmp(name, "has_key?") || !strcmp(name, "key?") ||544553
!strcmp(name, "include?") || !strcmp(name, "member?") ||@@ -1736,7 +1745,13 @@
17361745
}17371746
17381747
/* hash.each / each_pair { |k, v| } binds two params */1739-
if ((!strcmp(name, "each") || !strcmp(name, "each_pair")) && ty_is_hash(rt)) {1748+
if ((!strcmp(name, "each") || !strcmp(name, "each_pair") || !strcmp(name, "map") ||1749+
!strcmp(name, "collect") || !strcmp(name, "flat_map") || !strcmp(name, "select") ||1750+
!strcmp(name, "filter") || !strcmp(name, "reject") || !strcmp(name, "find") ||1751+
!strcmp(name, "detect") || !strcmp(name, "sort_by") || !strcmp(name, "min_by") ||1752+
!strcmp(name, "max_by") || !strcmp(name, "count") || !strcmp(name, "sum") ||1753+
!strcmp(name, "any?") || !strcmp(name, "all?") || !strcmp(name, "none?") ||1754+
!strcmp(name, "each_with_index") || !strcmp(name, "each_with_object")) && ty_is_hash(rt)) {17401755
Scope *hs = comp_scope_of(c, block);17411756
LocalVar *kp = scope_local_intern(hs, p0); kp->is_block_param = 1;17421757
TyKind km = ty_unify(kp->type, ty_hash_key(rt));src/codegen.cmodifiedView file
Loading diff…