Commit b598846f
b598846f7840Merged
Ryan Seys <[email protected]> · 6 months ago · 2 files · +1 added · ~1 modified
Description
feat(codegen): Hash#transform_keys block form for str_int_hash
Mirror image of the existing Hash#transform_values block form. Runs
the block once per key, uses the return value as the new key,
preserves the original value, and builds a fresh hash of the same
type. Common usage shape: h.transform_keys { |k| k.upcase }.
Dispatch arm in compile_call_expr's str_int_hash block:
sp_StrIntHash *t = sp_StrIntHash_new();
for (mrb_int _i = 0; _i < rc->len; _i++) {
const char *lv_<bp> = rc->order[_i];
sp_StrIntHash_set(t, <block-body>,
sp_StrIntHash_get(rc, rc->order[_i]));
}
infer_method_name_type gets a transform_keys arm that returns the
receiver type unchanged — symmetric with transform_values. The
result type assumes the block returns the same key C-type as the
input (string -> string for str_int_hash). Other key-type
combinations (e.g. block returns symbol, switching the result to
sym_int_hash) are out of scope and would need infer_block_return_type
plus matching code paths.
Test exercises:
- identity transform (lookup against original keys works)
- upcase transform (lookup against new keys works; old keys gone)
- key concatenation with a suffix
- empty hash transform yields empty
- length preserved across transform
Out of scope: int_str_hash#transform_keys (would need a separate arm at line ~17688), str_str_hash, sym_int_hash, sym_str_hash — all mechanical mirrors. Block returning a different key type (string -> symbol => sym_int_hash result) is also deferred.
Bootstrap: gen2.c == gen3.c. Tests: 215 pass.
Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]
Details
- Commit
- b598846f7840
- Parent
- 02005f26deba
spinel_codegen.rbmodifiedView file
end return "str_int_hash" end if mname == "transform_keys" if recv >= 0 return infer_type(recv) end return "str_int_hash" end if mname == "zip" if recv >= 0 rt = infer_type(recv) return tmp end end # transform_keys: apply the block to each key, keep the matching # value, build a new hash. Result type matches the input hash # type when the block returns the same key C-type — the common # case for `transform_keys { |k| k.upcase }` etc. if mname == "transform_keys" if @nd_block[nid] >= 0 blk = @nd_block[nid] bp = get_block_param(nid, 0) tmp = new_temp emit(" sp_StrIntHash *" + tmp + " = sp_StrIntHash_new();") emit(" for (mrb_int _i = 0; _i < " + rc + "->len; _i++) {") emit(" const char *lv_" + bp + " = " + rc + "->order[_i];") push_scope declare_var(bp, "string") bbody = @nd_body[blk] bexpr = "lv_" + bp if bbody >= 0 bs = get_stmts(bbody) if bs.length > 0 bexpr = compile_expr(bs.last) end end emit(" sp_StrIntHash_set(" + tmp + ", " + bexpr + ", sp_StrIntHash_get(" + rc + ", " + rc + "->order[_i]));") pop_scope emit(" }") return tmp end end end if recv_type == "int_str_hash" @needs_int_str_hash = 1test/hash_transform_keys.rbaddedView file
Loading diff…