Commit fab6afd9

fab6afd98f97Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 4 files · ~4 modified

Description

fix(analyze,codegen): Regexp.new with dynamic argument routes through dyn cache

Extends the literal-only Regexp.new fix so that Regexp.new("<#{x}>"), Regexp.new(arg) from a method param, and other non-static 1-arg forms compile correctly instead of falling through to the unresolved obj_Regexp / sp_Regexp * path. This unblocks the real-world idiom that motivated #586 (Regexp.new("<#{tag}[^>]*>...") in assert_select).

scan_features now registers the CallNode in @dyn_regex_node_ids when its single argument isn't a StringNode literal, so emit_dyn_regex_helpers produces a per-call-site sp_re_dyn_<idx>(const char *pat) cache exactly as it does for InterpolatedRegularExpressionNode. regex_pat_c_expr emits sp_re_dyn_<idx>(<arg_c_expr>) at each match site, so the cache's key compare absorbs identical re-evaluations (pat.match?(s) in a loop is one compile, not N).

For LV-bound forms (pat = Regexp.new(<dyn>); pat.match?(s)) the single-write LV tracking gets a parallel @local_regex_call_nids array storing the CallNode id. The read site looks up the LV in this table and re-emits the dyn-cache call. The arg's free variables (method params, ivars, surrounding LVs) are still in scope at the read site in C terms, so re-eval produces the same pattern string the write site would have -- provided the user hasn't mutated those free variables between write and read.

Re-eval semantics intentionally diverge from CRuby for the corner case of: tag = "div"; pat = Regexp.new(tag); tag = "span"; pat.match?(s) CRuby's pat matches /div/; spinel re-evaluates and matches /span/. The common idiom (write once, read shortly after, no intervening reassignment) gives identical results, which covers the assert_select case that motivated this issue.

Refs #586

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

Details

Commit
fab6afd98f97
Parent
01011f532228

spinel_analyze.rbmodifiedView file

@@ -434,12 +434,15 @@
434434 @dyn_regex_node_ids = []
435435 @dyn_regex_flags = "".split(",")
436436 # `var = /lit/` resolution. Parallel arrays: `@local_regex_names`
437- # holds the local-variable name and `@local_regex_idx` holds the
438- # corresponding `@regexp_patterns` index, or -1 when the same name
439- # has any other (non-regex or different-regex) write anywhere in
440- # the program — in which case the dispatcher must fall through.
437+ # holds the local-variable name; `@local_regex_idx` holds the
438+ # corresponding `@regexp_patterns` index (-1 when the LV is
439+ # ambiguous or is bound to a dyn-Regexp.new); `@local_regex_call_nids`
440+ # holds the AST node id of a single-write `Regexp.new(<dyn>)`
441+ # right-hand side (-1 otherwise), so the read-site dyn-cache emit
442+ # can locate the call. Multi-write resets both to -1 / -1.
441443 @local_regex_names = "".split(",")
442444 @local_regex_idx = []
445+ @local_regex_call_nids = []
443446
444447 # Cache for parse_id_list: AST list fields never change once loaded,
445448 # so the parsed IntArray can be shared across callers. The `[[0]]`
@@ -1540,55 +1543,82 @@
15401543 parts.join("|")
15411544 end
15421545
1543- # Returns the literal source string when `nid` is a `Regexp.new("...")`
1544- # (or `Regexp.compile("...")`) call with exactly one StringNode
1545- # argument, "" otherwise. Lets `pattern = Regexp.new("foo")` fold
1546- # into the same static pattern table as `pattern = /foo/`, so
1547- # `pattern.match?(s)` dispatches through `sp_re_pat_<i>` instead of
1548- # falling through to unresolved-call. Dynamic-arg forms return ""
1549- # and fall back.
1550- #
1551- # The arity check is strict (exactly 1 arg, no kwargs, no block) so
1552- # `Regexp.new("foo", Regexp::IGNORECASE)` falls through to the loud
1553- # `warn_unresolved_call` path instead of silently dropping the flag
1554- # -- silent CRuby divergence on a supported method belongs in the
1555- # bug bucket, not the quirk bucket.
1556- def regexp_new_literal_pattern(nid)
1546+ # Returns the AST node id of the single argument when `nid` is a
1547+ # `Regexp.new(<arg>)` / `Regexp.compile(<arg>)` call with exactly
1548+ # one argument (no block, no kwargs, recv is a `Regexp` constant
1549+ # ref). Returns -1 otherwise. Strict arity so `Regexp.new("foo",
1550+ # Regexp::IGNORECASE)` falls through to unresolved-call instead of
1551+ # silently dropping the flag -- silent CRuby divergence on a
1552+ # supported method belongs in the bug bucket, not the quirk bucket.
1553+ def regexp_new_call_arg_id(nid)
15571554 if @nd_type[nid] != "CallNode"
1558- return ""
1555+ return -1
15591556 end
15601557 mn = @nd_name[nid]
15611558 if mn != "new" && mn != "compile"
1562- return ""
1559+ return -1
15631560 end
15641561 if @nd_block[nid] >= 0
1565- return ""
1562+ return -1
15661563 end
15671564 recv = @nd_receiver[nid]
15681565 if recv < 0
1569- return ""
1566+ return -1
15701567 end
15711568 if @nd_type[recv] != "ConstantReadNode"
1572- return ""
1569+ return -1
15731570 end
15741571 if @nd_name[recv] != "Regexp"
1575- return ""
1572+ return -1
15761573 end
15771574 args_id = @nd_arguments[nid]
15781575 if args_id < 0
1579- return ""
1576+ return -1
15801577 end
15811578 arg_ids = get_args(args_id)
15821579 if arg_ids.length != 1
1580+ return -1
1581+ end
1582+ arg_ids[0]
1583+ end
1584+
1585+ # Returns the literal source string when the Regexp.new/compile
1586+ # call's single argument is a StringNode, "" otherwise. Lets
1587+ # `pattern = Regexp.new("foo")` fold into the same static pattern
1588+ # table as `pattern = /foo/`, so `pattern.match?(s)` dispatches
1589+ # through `sp_re_pat_<i>`. Non-literal 1-arg forms route through
1590+ # the dyn cache instead (see scan_features CallNode arm).
1591+ def regexp_new_literal_pattern(nid)
1592+ a0 = regexp_new_call_arg_id(nid)
1593+ if a0 < 0
15831594 return ""
15841595 end
1585- a0 = arg_ids[0]
15861596 if @nd_type[a0] != "StringNode"
15871597 return ""
15881598 end
15891599 @nd_content[a0]
15901600 end
15911601
1602+ # Returns 1 if `nid` is a 1-arg `Regexp.new`/`compile` call whose
1603+ # argument is NOT a StringNode literal. These route through the
1604+ # per-call-site `sp_re_dyn_<idx>` cache so the pattern string is
1605+ # re-evaluated each visit -- correct semantics for the common idiom
1606+ # `pat = Regexp.new("<#{tag}>")` where the arg's free variables
1607+ # don't mutate between write and read. A user who reassigns those
1608+ # free variables between the write and a later read of `pat` gets
1609+ # CRuby-divergent semantics; that case is rare and the runtime
1610+ # cache will at least give consistent results for any given input.
1611+ def regexp_new_dynamic?(nid)
1612+ a0 = regexp_new_call_arg_id(nid)
1613+ if a0 < 0
1614+ return 0
1615+ end
1616+ if @nd_type[a0] == "StringNode"
1617+ return 0
1618+ end
1619+ 1
1620+ end
1621+
15921622 # Index of an InterpolatedRegularExpressionNode in @dyn_regex_node_ids,
15931623 # or -1 if scan_features hasn't registered it (defensive — should not
15941624 # happen for any reachable node).
@@ -5338,16 +5368,17 @@
53385368 if rn == "Time"
53395369 return "time"
53405370 end
5341- # `Regexp.new(literal)` / `Regexp.compile(literal)` registers the
5342- # pattern with the static regex table (scan_features arm) and the
5343- # local-name → pattern map (LocalVariableWriteNode arm). The LV
5344- # itself carries no useful runtime payload — match?/=~/match all
5345- # dispatch through `regex_pat_c_expr` at the call site, which
5346- # resolves the LV via `@local_regex_names` and emits the global
5347- # `sp_re_pat_<i>`. Type the call as "int" so the LV lowers to
5348- # `mrb_int lv_x = 0;` (the same shape `pattern = /foo/` produces).
5371+ # `Regexp.new(<arg>)` / `Regexp.compile(<arg>)` -- both literal and
5372+ # dyn variants. Scan_features registered the pattern (static table
5373+ # or per-call-site dyn cache) and LocalVariableWriteNode recorded
5374+ # the LV-name → resolution map. The LV carries no useful runtime
5375+ # payload: match?/=~/match all dispatch through `regex_pat_c_expr`
5376+ # at the call site, which either emits `sp_re_pat_<i>` (static) or
5377+ # re-emits `sp_re_dyn_<idx>(<arg>)` (dyn). Type the call as "int"
5378+ # so the LV lowers to `mrb_int lv_x = 0;` (matching the shape
5379+ # `pattern = /foo/` produces).
53495380 if rn == "Regexp"
5350- if regexp_new_literal_pattern(nid) != ""
5381+ if regexp_new_literal_pattern(nid) != "" || regexp_new_dynamic?(nid) == 1
53515382 return "int"
53525383 end
53535384 end
@@ -17719,8 +17750,10 @@
1771917750 # `Regexp.new("literal")` / `Regexp.compile("literal")` folds into
1772017751 # the same static pattern table so `.match?`/`=~` dispatch through
1772117752 # `sp_re_pat_<i>` like a `/literal/` literal. Dynamic-arg forms
17722- # (`Regexp.new(s)` with a non-literal arg) return "" from the helper
17723- # and are left to the existing fallback (currently unresolved).
17753+ # (`Regexp.new("<#{x}>")`, `Regexp.new(s)`, etc.) register a
17754+ # per-call-site `sp_re_dyn_<idx>` cache instead -- regex_pat_c_expr
17755+ # re-evaluates the arg at each match site, the cache compares the
17756+ # produced string to its stored key and only recompiles on miss.
1772417757 if t == "CallNode"
1772517758 rxlit = regexp_new_literal_pattern(nid)
1772617759 if rxlit != ""
@@ -17737,6 +17770,20 @@
1773717770 @regexp_patterns.push(rxlit)
1773817771 @regexp_flags.push("0")
1773917772 end
17773+ elsif regexp_new_dynamic?(nid) == 1
17774+ @needs_regexp = 1
17775+ already_dn = 0
17776+ dni = 0
17777+ while dni < @dyn_regex_node_ids.length
17778+ if @dyn_regex_node_ids[dni] == nid
17779+ already_dn = 1
17780+ end
17781+ dni = dni + 1
17782+ end
17783+ if already_dn == 0
17784+ @dyn_regex_node_ids.push(nid)
17785+ @dyn_regex_flags.push("0")
17786+ end
1774017787 end
1774117788 end
1774217789 # Track `var = /lit/` so a regex held in a local can be dispatched
@@ -17776,21 +17823,34 @@
1777617823 end
1777717824 end
1777817825 end
17826+ # `var = Regexp.new(<dyn>)`: record the call's AST node id so the
17827+ # read-site can emit `sp_re_dyn_<idx>(<arg_c>)` with the cached
17828+ # compiled pattern. Pre-scan ensures @dyn_regex_node_ids has the
17829+ # entry before find_dyn_regex_index runs at emit time.
17830+ this_call_nid = -1
17831+ if this_idx == -1 && vid >= 0 && regexp_new_dynamic?(vid) == 1
17832+ scan_features(vid)
17833+ this_call_nid = vid
17834+ end
1777917835 i2 = 0
1778017836 found = 0
1778117837 while i2 < @local_regex_names.length
1778217838 if @local_regex_names[i2] == lname
1778317839 found = 1
17784- # Any second write (regex or not) marks ambiguous.
17840+ # Any second write (regex or not) marks ambiguous in both slots.
1778517841 if @local_regex_idx[i2] != this_idx
1778617842 @local_regex_idx[i2] = -1
1778717843 end
17844+ if @local_regex_call_nids[i2] != this_call_nid
17845+ @local_regex_call_nids[i2] = -1
17846+ end
1778817847 end
1778917848 i2 = i2 + 1
1779017849 end
1779117850 if found == 0
1779217851 @local_regex_names.push(lname)
1779317852 @local_regex_idx.push(this_idx)
17853+ @local_regex_call_nids.push(this_call_nid)
1779417854 end
1779517855 end
1779617856 if t == "ArrayNode"
@@ -24860,6 +24920,7 @@
2486024920 buf = ir_emit_sa(buf, "@dyn_regex_flags", @dyn_regex_flags)
2486124921 buf = ir_emit_sa(buf, "@local_regex_names", @local_regex_names)
2486224922 buf = ir_emit_ia(buf, "@local_regex_idx", @local_regex_idx)
24923+ buf = ir_emit_ia(buf, "@local_regex_call_nids", @local_regex_call_nids)
2486324924
2486424925 # Misc tables
2486524926 buf = ir_emit_sa(buf, "@open_class_names", @open_class_names)