Commit 7e3308dc

7e3308dccc78Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 2 files · +1 added · ~1 modified

Description

fix(codegen): dispatch regex held in a constant through the engine

Stage 3 of issue #61. RX = /pat/; RX.match?(s) and s =~ RX fell through every dispatcher and compiled to 0 / (-1):

  • find_regexp_index only resolved direct RegularExpressionNodes, not ConstantReadNodes pointing at one. Extend it to walk the constant's @const_expr_ids[ci] and recurse when the initializer is itself a regex literal.
  • match? / match / =~ with a regex receiver were unhandled in compile_call_expr (the only match? site lived in compile_string_method_expr, which is keyed on a string receiver). Add a regex-receiver dispatch above the no-receiver fork so RX.match?(s) and RX =~ s reach sp_re_match_p / sp_re_match.

Combined with stages 1 (byte-length fix) and 2 (engine UTF-8 char class support), the issue's reproducer puts RX.match?("₁₂") now prints true.

test/regex_via_constant.rb covers the four call shapes (RX.match?, s =~ RX, RX =~ s, RX.match).

Closes #61

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
7e3308dccc78
Parent
65250c0ad119

spinel_codegen.rbmodifiedView file

@@ -910,7 +910,24 @@
910910 end
911911 i = i + 1
912912 end
913+ return -1
913914 end
915+ # A constant initialized to a regex literal forwards to the
916+ # underlying pattern, so `RX = /pat/; RX.match?(s)` and
917+ # `s =~ RX` dispatch to the engine instead of falling through
918+ # to the literal-`(-1)` / `sp_str_include` fallbacks.
919+ if @nd_type[nid] == "ConstantReadNode"
920+ cname = resolve_const_ref_name(nid)
921+ if cname != ""
922+ ci = find_const_idx(cname)
923+ if ci >= 0 && ci < @const_expr_ids.length
924+ eid = @const_expr_ids[ci]
925+ if eid >= 0 && @nd_type[eid] == "RegularExpressionNode"
926+ return find_regexp_index(eid)
927+ end
928+ end
929+ end
930+ end
914931 -1
915932 end
916933
@@ -13271,6 +13288,27 @@
1327113288 end
1327213289 end
1327313290
13291+ # regex.match? / regex.match / regex =~ str — receiver is the regex
13292+ # (typically a constant referring to a /…/ literal). Dispatched here
13293+ # rather than compile_string_method_expr, which wants a string
13294+ # receiver.
13295+ if recv >= 0 && (mname == "match?" || mname == "=~" || mname == "match")
13296+ ridx = find_regexp_index(recv)
13297+ if ridx >= 0
13298+ args_id = @nd_arguments[nid]
13299+ if args_id >= 0
13300+ arg_ids = get_args(args_id)
13301+ if arg_ids.length > 0
13302+ sc = compile_expr(arg_ids[0])
13303+ if mname == "match?"
13304+ return "sp_re_match_p(sp_re_pat_" + ridx.to_s + ", " + sc + ")"
13305+ end
13306+ return "sp_re_match(sp_re_pat_" + ridx.to_s + ", " + sc + ")"
13307+ end
13308+ end
13309+ end
13310+ end
13311+
1327413312 # No receiver
1327513313 if recv < 0
1327613314 return compile_no_recv_call_expr(nid, mname)