Commit 9ec2e6bf

9ec2e6bfb6daMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · ~2 modified

Description

Hash#transform_keys / transform_values with a block

Rebuild a hash applying the block to each key (or value), keeping the other half. The result variant is derived from the block's return type (e.g. a sym->string key block turns a sym_poly_hash into a str_poly_hash); values are boxed when the destination variant is poly. analyze types the block parameter and the result hash variant.

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
9ec2e6bfb6da
Parent
f0185545fa6f

src/analyze.cmodifiedView file

@@ -682,6 +682,20 @@
682682 return ty_array_of(bn > 0 ? infer_type(c, bb[bn - 1]) : TY_UNKNOWN);
683683 }
684684 if (block >= 0 && (!strcmp(name, "select") || !strcmp(name, "filter") || !strcmp(name, "reject"))) return rt;
685+ if (block >= 0 && !strcmp(name, "transform_keys")) {
686+ int body = nt_ref(nt, block, "body");
687+ int bn = 0; const int *bb = body >= 0 ? nt_arr(nt, body, "body", &bn) : NULL;
688+ TyKind nkt = bn > 0 ? infer_type(c, bb[bn - 1]) : TY_UNKNOWN;
689+ TyKind r = ty_hash_of(nkt, ty_hash_val(rt));
690+ return r != TY_UNKNOWN ? r : rt;
691+ }
692+ if (block >= 0 && !strcmp(name, "transform_values")) {
693+ int body = nt_ref(nt, block, "body");
694+ int bn = 0; const int *bb = body >= 0 ? nt_arr(nt, body, "body", &bn) : NULL;
695+ TyKind nvt = bn > 0 ? infer_type(c, bb[bn - 1]) : TY_UNKNOWN;
696+ TyKind r = ty_hash_of(ty_hash_key(rt), nvt);
697+ return r != TY_UNKNOWN ? r : rt;
698+ }
685699 }
686700 if (!strcmp(name, "merge") || !strcmp(name, "dup") || !strcmp(name, "clone") ||
687701 !strcmp(name, "replace")) return rt;
@@ -2078,6 +2092,16 @@
20782092 continue;
20792093 }
20802094
2095+ /* hash.transform_keys { |k| } binds key; transform_values { |v| } value */
2096+ if ((!strcmp(name, "transform_keys") || !strcmp(name, "transform_values")) && ty_is_hash(rt)) {
2097+ Scope *hs = comp_scope_of(c, block);
2098+ LocalVar *vp = scope_local_intern(hs, p0); vp->is_block_param = 1;
2099+ TyKind want = !strcmp(name, "transform_keys") ? ty_hash_key(rt) : ty_hash_val(rt);
2100+ TyKind vm = ty_unify(vp->type, want);
2101+ if (vm != vp->type) { vp->type = vm; changed = 1; }
2102+ continue;
2103+ }
2104+
20812105 /* hash.each_value { |v| } binds value; each_key { |k| } binds key */
20822106 if ((!strcmp(name, "each_value") || !strcmp(name, "each_key")) && ty_is_hash(rt)) {
20832107 Scope *hs = comp_scope_of(c, block);