Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions mrbgems/mruby-regexp/src/regexp.c
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,10 @@ set_match_globals(mrb_state *mrb, mrb_value obj, mrb_value str, int *captures, i
static mrb_value
create_matchdata(mrb_state *mrb, mrb_value regexp, mrb_value str, int *captures, int ncap)
{
/* Snapshot the subject: MatchData reports the string as it was at match
time, so later in-place changes to it must not be visible here. */
str = mrb_str_dup_frozen(mrb, str);

struct RClass *md_class = mrb_class_get(mrb, "MatchData");
mrb_match_data *md = (mrb_match_data*)mrb_malloc(mrb, sizeof(mrb_match_data));
md->source = str;
Expand Down
31 changes: 31 additions & 0 deletions mrbgems/mruby-regexp/test/regexp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,37 @@
assert_equal "abcde", md.string
end

assert("MatchData - subject is snapshotted at match time") do
# Regression: source used to alias the subject, so mutating it afterwards
# retroactively changed what an already-created MatchData reported.
s = "hello"
md = /l/.match(s)
s.upcase!
assert_equal "l", md[0]
assert_equal "hello", md.string
assert_equal "he", md.pre_match
assert_equal "lo", md.post_match
assert_true md.string.frozen?

s2 = "hello"
s2 =~ /l/
s2.upcase!
assert_equal "l", $~[0]
assert_equal "hello", $~.string
end

assert("MatchData - match globals survive subject mutation in a gsub block") do
# Regression: the mrblib gsub loop republishes $&, $` and $' from the
# MatchData after the block runs, so a block that mutates the subject used
# to make them describe the mutated string.
t = "hello"
n = 0
t.gsub(/l/) { n += 1; t.upcase! if n == 2; "X" }
assert_equal "l", $&
assert_equal "hel", $`
assert_equal "o", $'
end

assert("MatchData#regexp") do
re = Regexp.new("bc")
md = re.match("abcde")
Expand Down
Loading