Commit 9e058673
9e058673b861Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified
Description
Hash#fetch: KeyError on miss, and the (key, default) form
fetch(key) with no default now raises KeyError on a missing key instead of returning the value type's default. fetch(key, default) returns the default when the key is absent (boxing it into a poly-valued hash).
Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]
Details
- Commit
- 9e058673b861
- Parent
- d3528342426e
src/codegen.cmodifiedView file
@@ -1978,8 +1978,26 @@
19781978
buf_printf(b, "; }); })");19791979
return;19801980
}1981-
buf_printf(b, "sp_%sHash_get(", hn);1982-
emit_expr(c, recv, b); buf_puts(b, ", "); emit_expr(c, argv[0], b); buf_puts(b, ")");1981+
/* fetch(key) with no default raises KeyError on a miss */1982+
TyKind vt = ty_hash_val(rt);1983+
int th = ++g_tmp, tk = ++g_tmp;1984+
buf_printf(b, "({ %s _t%d = ", c_type_name(rt), th); emit_expr(c, recv, b);1985+
buf_printf(b, "; %s _t%d = ", c_type_name(ty_hash_key(rt)), tk); emit_expr(c, argv[0], b);1986+
buf_printf(b, "; sp_%sHash_has_key(_t%d, _t%d) ? sp_%sHash_get(_t%d, _t%d)"1987+
" : (sp_raise_cls(\"KeyError\", \"key not found\"), %s); })",1988+
hn, th, tk, hn, th, tk, vt == TY_POLY ? "sp_box_nil()" : default_value(vt));1989+
return;1990+
}1991+
if (!strcmp(name, "fetch") && argc == 2) {1992+
/* fetch(key, default) -> has_key? ? value : default */1993+
TyKind vt = ty_hash_val(rt);1994+
int th = ++g_tmp, tk = ++g_tmp;1995+
buf_printf(b, "({ %s _t%d = ", c_type_name(rt), th); emit_expr(c, recv, b);1996+
buf_printf(b, "; %s _t%d = ", c_type_name(ty_hash_key(rt)), tk); emit_expr(c, argv[0], b);1997+
buf_printf(b, "; sp_%sHash_has_key(_t%d, _t%d) ? sp_%sHash_get(_t%d, _t%d) : ", hn, th, tk, hn, th, tk);1998+
if (vt == TY_POLY && comp_ntype(c, argv[1]) != TY_POLY) emit_boxed(c, argv[1], b);1999+
else emit_expr(c, argv[1], b);2000+
buf_puts(b, "; })");19832001
return;19842002
}19852003
if ((!strcmp(name, "length") || !strcmp(name, "size") || !strcmp(name, "count")) && argc == 0) {