Commit c3ca6fc1

c3ca6fc1e64fMerged

Ryan Seys <[email protected]> · 6 months ago · 4 files · ~4 modified

Description

feat(parse,codegen,runtime): support InterpolatedRegularExpressionNode (/foo_#{x}/)

Pattern is only known at execution time, so it can't be pre-compiled to an sp_re_pat_ global. The compile_expr arm builds the pattern string via the existing compile_interpolated machinery (same as InterpolatedSymbolNode at 69fb8c7) and feeds the result to sp_re_runtime_compile (one-line wrapper around re_compile, added in this commit).

Adds a regex_pat_c_expr(nid) helper that returns the C expression for a regex pattern -- "sp_re_pat_" for static literals, the runtime- compile call for InterpolatedRegex. Each =~/match?/match/gsub/sub/scan/ split dispatch site now goes through the helper, so the same call shape handles both forms transparently. The receiver-side regex.match?(s) path also uses it for /foo_#{x}/.match?(s).

Test exercises (test/interp_regex.rb):

  • match? predicate with interpolated pattern
  • $1 capture from a /foo_#{x}_(\d+)/ match
  • gsub and sub with interpolated patterns
  • per-iteration interpolation proves no stale cache

Tests: 289 pass. Bootstrap: gen2.c == gen3.c.

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

Details

Commit
c3ca6fc1e64f
Parent
002de75cb713

spinel_codegen.rbmodifiedView file

@@ -281,6 +281,13 @@
281281 @needs_rand = 0
282282 @regexp_patterns = "".split(",")
283283 @regexp_flags = "".split(",")
284+ # Dynamic-regex (InterpolatedRegularExpressionNode) call-site cache.
285+ # Each AST node gets a unique idx so the emitter can produce one
286+ # `sp_re_dyn_<idx>` helper per source location with its own
287+ # function-scope cache (string key + compiled pattern). Collected
288+ # in scan_features so indexes are stable across compile_expr visits.
289+ @dyn_regex_node_ids = []
290+ @dyn_regex_flags = "".split(",")
284291 # `var = /lit/` resolution. Parallel arrays: `@local_regex_names`
285292 # holds the local-variable name and `@local_regex_idx` holds the
286293 # corresponding `@regexp_patterns` index, or -1 when the same name
@@ -1552,6 +1559,66 @@
15521559 -1
15531560 end
15541561
1562+ # Returns a C expression evaluating to a `mrb_regexp_pattern *`, or "" if
1563+ # the node isn't a regex source. Static literals resolve to their
1564+ # pre-compiled `sp_re_pat_<i>` global; InterpolatedRegularExpressionNode
1565+ # gets a runtime `sp_re_runtime_compile(...)` call. Centralizes the
1566+ # dispatch so each =~/match?/match/gsub/sub/scan/split call site doesn't
1567+ # have to repeat the InterpolatedRegex check.
1568+ def regex_pat_c_expr(nid)
1569+ ridx = find_regexp_index(nid)
1570+ if ridx >= 0
1571+ return "sp_re_pat_" + ridx.to_s
1572+ end
1573+ if @nd_type[nid] == "InterpolatedRegularExpressionNode"
1574+ @needs_regexp = 1
1575+ return compile_expr(nid)
1576+ end
1577+ ""
1578+ end
1579+
1580+ # Maps Prism's regex flag bits to the engine's `RE_FLAG_*` values and
1581+ # returns a C bitwise-OR string ("0", "1", "1|6", etc.). Single source
1582+ # of truth used by both the static-regex collector arm in scan_features
1583+ # and the per-call-site helper emitted by emit_dyn_regex_helpers.
1584+ # Prism: IGNORE_CASE=4, EXTENDED=8, MULTI_LINE=16.
1585+ # Engine: IGNORECASE=1, MULTILINE=2, DOTALL=4, EXTENDED=8.
1586+ # Ruby's /m (dot-matches-newline) maps to MULTILINE|DOTALL = 6.
1587+ def regex_engine_flags(nid)
1588+ if @nd_flags[nid] == 0
1589+ return "0"
1590+ end
1591+ f = @nd_flags[nid]
1592+ parts = "".split(",")
1593+ if f & 4 != 0
1594+ parts.push("1")
1595+ end
1596+ if f & 16 != 0
1597+ parts.push("6")
1598+ end
1599+ if f & 8 != 0
1600+ parts.push("8")
1601+ end
1602+ if parts.length == 0
1603+ return "0"
1604+ end
1605+ parts.join("|")
1606+ end
1607+
1608+ # Index of an InterpolatedRegularExpressionNode in @dyn_regex_node_ids,
1609+ # or -1 if scan_features hasn't registered it (defensive — should not
1610+ # happen for any reachable node).
1611+ def find_dyn_regex_index(nid)
1612+ i = 0
1613+ while i < @dyn_regex_node_ids.length
1614+ if @dyn_regex_node_ids[i] == nid
1615+ return i
1616+ end
1617+ i = i + 1
1618+ end
1619+ -1
1620+ end
1621+
15551622 def find_class_idx(name)
15561623 i = 0
15571624 while i < @cls_names.length
@@ -12088,31 +12155,35 @@
1208812155 @needs_setjmp = 1
1208912156 end
1209012157 end
12158+ if t == "InterpolatedRegularExpressionNode" || t == "InterpolatedMatchLastLineNode"
12159+ # Pre-flag so emit_regexp_runtime fires (defines sp_re_init) even
12160+ # when the program uses ONLY interpolated regexes -- without this,
12161+ # the linker fails on the unreferenced sp_re_init main() call.
12162+ @needs_regexp = 1
12163+ end
12164+ if t == "InterpolatedRegularExpressionNode"
12165+ # Register this AST site so emit_dyn_regex_helpers produces a
12166+ # dedicated `sp_re_dyn_<idx>` cache for it. Idempotent: a node
12167+ # visited twice (e.g. through type-inference + emit passes) keeps
12168+ # its first-assigned index.
12169+ already_dyn = 0
12170+ di = 0
12171+ while di < @dyn_regex_node_ids.length
12172+ if @dyn_regex_node_ids[di] == nid
12173+ already_dyn = 1
12174+ end
12175+ di = di + 1
12176+ end
12177+ if already_dyn == 0
12178+ @dyn_regex_node_ids.push(nid)
12179+ @dyn_regex_flags.push(regex_engine_flags(nid))
12180+ end
12181+ end
1209112182 if t == "RegularExpressionNode"
1209212183 @needs_regexp = 1
1209312184 # Collect pattern and flags
1209412185 pat = @nd_unescaped[nid]
12095- flags = "0"
12096- if @nd_flags[nid] != 0
12097- f = @nd_flags[nid]
12098- parts = "".split(",")
12099- # Prism flag bits → engine `RE_FLAG_*` values (see re_internal.h).
12100- # Prism: IGNORE_CASE=4, EXTENDED=8, MULTI_LINE=16.
12101- # Engine: IGNORECASE=1, MULTILINE=2, DOTALL=4, EXTENDED=8.
12102- # Ruby's /m (dot-matches-newline) maps to MULTILINE|DOTALL = 6.
12103- if f & 4 != 0
12104- parts.push("1")
12105- end
12106- if f & 16 != 0
12107- parts.push("6")
12108- end
12109- if f & 8 != 0
12110- parts.push("8")
12111- end
12112- if parts.length > 0
12113- flags = parts.join("|")
12114- end
12115- end
12186+ flags = regex_engine_flags(nid)
1211612187 # Idempotent: identical patterns share the same compiled global,
1211712188 # so a second visit (e.g. via the LocalVariableWriteNode pre-scan
1211812189 # below) is a no-op.
@@ -13490,6 +13561,7 @@
1349013561 # Emit program-specific regexp patterns
1349113562 if @needs_regexp == 1
1349213563 emit_regexp_runtime
13564+ emit_dyn_regex_helpers
1349313565 end
1349413566 emit_class_structs
1349513567 emit_raw("/*TUPLE_INSERT_POINT*/")
@@ -14209,6 +14281,34 @@
1420914281 emit_raw("")
1421014282 end
1421114283
14284+ # Per-call-site cached helper for InterpolatedRegularExpressionNode.
14285+ # Each AST source location gets a `sp_re_dyn_<idx>(const char *new_pat)`
14286+ # function with its own function-scope statics for the cached pattern
14287+ # string and compiled engine pattern. On a cache hit (strcmp match) we
14288+ # return the existing pattern; on a miss we re_free the old one and
14289+ # recompile with the call-site's baked flags. This bounds heap to one
14290+ # `mrb_regexp_pattern` per call site (count fixed at AOT compile time)
14291+ # and matches Ruby's per-source-location dynamic-regexp cache. The old
14292+ # `sp_re_runtime_compile` leaked a fresh pattern every evaluation.
14293+ def emit_dyn_regex_helpers
14294+ i = 0
14295+ while i < @dyn_regex_node_ids.length
14296+ flags = @dyn_regex_flags[i]
14297+ emit_raw("static mrb_regexp_pattern *sp_re_dyn_" + i.to_s + "(const char *new_pat) {")
14298+ emit_raw(" static char *cached_str = NULL;")
14299+ emit_raw(" static mrb_regexp_pattern *cached_pat = NULL;")
14300+ emit_raw(" if (cached_str != NULL && strcmp(cached_str, new_pat) == 0) return cached_pat;")
14301+ emit_raw(" re_free(cached_pat);")
14302+ emit_raw(" free(cached_str);")
14303+ emit_raw(" cached_str = strdup(new_pat);")
14304+ emit_raw(" cached_pat = re_compile(new_pat, (int64_t)strlen(new_pat), " + flags + ");")
14305+ emit_raw(" return cached_pat;")
14306+ emit_raw("}")
14307+ emit_raw("")
14308+ i = i + 1
14309+ end
14310+ end
14311+
1421214312 # ---- Struct emission ----
1421314313 def emit_global_constants
1421414314 # Emit file-scope constant declarations (initialized in main)
@@ -18354,6 +18454,20 @@
1835418454 $stderr.puts "Spinel: BackReferenceReadNode `" + n + "` not supported"
1835518455 exit(1)
1835618456 end
18457+ if t == "InterpolatedRegularExpressionNode"
18458+ # `/foo_#{x}/` -- pattern is only known at execution time, so we
18459+ # can't pre-compile to an sp_re_pat_<i> global. The pattern string
18460+ # is built via compile_interpolated and passed to a per-call-site
18461+ # cached helper `sp_re_dyn_<idx>` (emitted by emit_dyn_regex_helpers).
18462+ # The helper compares the new pattern bytes to its cached key and
18463+ # only re_free+recompile on miss, so heap is bounded to one engine
18464+ # pattern per source location regardless of how many times the
18465+ # site evaluates. Flags are baked into the helper at emission time.
18466+ @needs_regexp = 1
18467+ pat_c = compile_interpolated(nid)
18468+ idx = find_dyn_regex_index(nid)
18469+ return "sp_re_dyn_" + idx.to_s + "(" + pat_c + ")"
18470+ end
1835718471 if t == "NumberedReferenceReadNode"
1835818472 num = @nd_value[nid]
1835918473 if num >= 1 && num <= 9
@@ -19656,19 +19770,20 @@
1965619770 # regex.match? / regex.match / regex =~ str — receiver is the regex
1965719771 # (typically a constant referring to a /…/ literal). Dispatched here
1965819772 # rather than compile_string_method_expr, which wants a string
19659- # receiver.
19773+ # receiver. Receiver can also be InterpolatedRegularExpressionNode
19774+ # for `/foo_#{x}/.match?(s)` (rare but valid).
1966019775 if recv >= 0 && (mname == "match?" || mname == "=~" || mname == "match")
19661- ridx = find_regexp_index(recv)
19662- if ridx >= 0
19776+ rpat = regex_pat_c_expr(recv)
19777+ if rpat != ""
1966319778 args_id = @nd_arguments[nid]
1966419779 if args_id >= 0
1966519780 arg_ids = get_args(args_id)
1966619781 if arg_ids.length > 0
1966719782 sc = compile_expr(arg_ids[0])
1966819783 if mname == "match?"
19669- return "sp_re_match_p(sp_re_pat_" + ridx.to_s + ", " + sc + ")"
19784+ return "sp_re_match_p(" + rpat + ", " + sc + ")"
1967019785 end
19671- return "sp_re_match(sp_re_pat_" + ridx.to_s + ", " + sc + ")"
19786+ return "sp_re_match(" + rpat + ", " + sc + ")"
1967219787 end
1967319788 end
1967419789 end
@@ -20879,15 +20994,17 @@
2087920994 return "(" + compile_expr(recv) + " >= " + compile_arg0(nid) + ")"
2088020995 end
2088120996 if mname == "=~"
20882- # str =~ /pattern/ → sp_re_match(pat, str)
20997+ # str =~ /pattern/ → sp_re_match(pat, str). Pattern source can be
20998+ # a static literal, a regex-typed local/const (find_regexp_index),
20999+ # or InterpolatedRegularExpressionNode (runtime-compiled).
2088321000 rc = compile_expr_gc_rooted(recv)
2088421001 re_args_id = @nd_arguments[nid]
2088521002 if re_args_id >= 0
2088621003 argl = get_args(re_args_id)
2088721004 if argl.length > 0
20888- ridx = find_regexp_index(argl[0])
20889- if ridx >= 0
20890- return "sp_re_match(sp_re_pat_" + ridx.to_s + ", " + rc + ")"
21005+ rpat = regex_pat_c_expr(argl[0])
21006+ if rpat != ""
21007+ return "sp_re_match(" + rpat + ", " + rc + ")"
2089121008 end
2089221009 end
2089321010 end
@@ -21460,9 +21577,9 @@
2146021577 if args_id >= 0
2146121578 a = get_args(args_id)
2146221579 if a.length > 0
21463- ridx = find_regexp_index(a[0])
21464- if ridx >= 0
21465- return "sp_re_split(sp_re_pat_" + ridx.to_s + ", " + rc + ")"
21580+ rpat = regex_pat_c_expr(a[0])
21581+ if rpat != ""
21582+ return "sp_re_split(" + rpat + ", " + rc + ")"
2146621583 end
2146721584 # Peephole: literal "".split(literal) is the empty-StrArray idiom;
2146821585 # skip the strlen+sep scan and emit a direct allocator call.
@@ -21484,11 +21601,10 @@
2148421601 if args_id >= 0
2148521602 argl = get_args(args_id)
2148621603 if argl.length > 0
21487- ridx = find_regexp_index(argl[0])
21488- if ridx >= 0
21604+ rpat = regex_pat_c_expr(argl[0])
21605+ if rpat != ""
2148921606 @needs_str_array = 1
21490- @needs_regexp = 1
21491- return "sp_re_scan(sp_re_pat_" + ridx.to_s + ", " + rc + ")"
21607+ return "sp_re_scan(" + rpat + ", " + rc + ")"
2149221608 end
2149321609 end
2149421610 end
@@ -21499,9 +21615,9 @@
2149921615 if re_args_id >= 0
2150021616 argl = get_args(re_args_id)
2150121617 if argl.length > 0
21502- ridx = find_regexp_index(argl[0])
21503- if ridx >= 0
21504- return "sp_re_match_p(sp_re_pat_" + ridx.to_s + ", " + rc + ")"
21618+ rpat = regex_pat_c_expr(argl[0])
21619+ if rpat != ""
21620+ return "sp_re_match_p(" + rpat + ", " + rc + ")"
2150521621 end
2150621622 end
2150721623 end
@@ -21512,9 +21628,9 @@
2151221628 if args_id >= 0
2151321629 a = get_args(args_id)
2151421630 if a.length >= 2
21515- ridx = find_regexp_index(a[0])
21516- if ridx >= 0
21517- return "sp_re_gsub(sp_re_pat_" + ridx.to_s + ", " + rc + ", " + compile_expr(a[1]) + ")"
21631+ rpat = regex_pat_c_expr(a[0])
21632+ if rpat != ""
21633+ return "sp_re_gsub(" + rpat + ", " + rc + ", " + compile_expr(a[1]) + ")"
2151821634 end
2151921635 return "sp_str_gsub(" + rc + ", " + compile_expr(a[0]) + ", " + compile_expr(a[1]) + ")"
2152021636 end
@@ -21526,9 +21642,9 @@
2152621642 if args_id >= 0
2152721643 a = get_args(args_id)
2152821644 if a.length >= 2
21529- ridx = find_regexp_index(a[0])
21530- if ridx >= 0
21531- return "sp_re_sub(sp_re_pat_" + ridx.to_s + ", " + rc + ", " + compile_expr(a[1]) + ")"
21645+ rpat = regex_pat_c_expr(a[0])
21646+ if rpat != ""
21647+ return "sp_re_sub(" + rpat + ", " + rc + ", " + compile_expr(a[1]) + ")"
2153221648 end
2153321649 return "sp_str_sub(" + rc + ", " + compile_expr(a[0]) + ", " + compile_expr(a[1]) + ")"
2153421650 end