Commit 4b4e396d

4b4e396dde15Merged

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

Description

Regex =~ raises TypeError for non-String argument

When /pat/ =~ arg and arg is not a String, emit a TypeError raise matching CRuby's behavior. For TY_POLY args a runtime tag check is emitted; for known non-string types the error is raised unconditionally.

Co-Authored-By: Claude Sonnet 4.6 [email protected]

Details

Commit
4b4e396dde15
Parent
14befe654c5d

src/codegen.cmodifiedView file

@@ -3436,7 +3436,26 @@
34363436 free(rp.p); return;
34373437 }
34383438 if (!strcmp(name, "=~") && argc == 1) {
3439- buf_printf(b, "sp_re_match_poly(%s, ", rp.p); emit_expr(c, argv[0], b); buf_puts(b, ")");
3439+ if (a0 == TY_STRING) {
3440+ buf_printf(b, "sp_re_match_poly(%s, ", rp.p); emit_expr(c, argv[0], b); buf_puts(b, ")");
3441+ }
3442+ else if (a0 == TY_POLY) {
3443+ /* runtime type check: raise TypeError if not a string */
3444+ int tv = ++g_tmp;
3445+ emit_indent(g_pre, g_indent);
3446+ buf_printf(g_pre, "sp_RbVal _t%d = ", tv); emit_expr(c, argv[0], g_pre); buf_puts(g_pre, ";\n");
3447+ emit_indent(g_pre, g_indent);
3448+ buf_printf(g_pre, "if (_t%d.tag != SP_TAG_STR) sp_raise_cls(\"TypeError\", \"no implicit conversion into String\");\n", tv);
3449+ buf_printf(b, "sp_re_match_poly(%s, _t%d.v.s)", rp.p, tv);
3450+ }
3451+ else {
3452+ /* statically known non-string: always raises TypeError */
3453+ const char *tn = (a0 == TY_INT) ? "Integer" : (a0 == TY_FLOAT) ? "Float"
3454+ : (a0 == TY_BOOL) ? "true/false" : (a0 == TY_NIL) ? "NilClass" : "Object";
3455+ buf_printf(b, "((void)(");
3456+ emit_expr(c, argv[0], b);
3457+ buf_printf(b, "), sp_raise_cls(\"TypeError\", \"no implicit conversion of %s into String\"), sp_box_nil())", tn);
3458+ }
34403459 free(rp.p); return;
34413460 }
34423461 if (!strcmp(name, "match") && (argc == 1 || argc == 2)) {