Skip to content

Commit

Permalink
Merge pull request #2227 from herwinw/regexp_too_short_escape_sequence
Browse files Browse the repository at this point in the history
Throw exception in Regexp.new/compile for trailing single backslash
  • Loading branch information
herwinw committed Sep 20, 2024
2 parents 8059785 + 87e4c9d commit fadd824
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
4 changes: 1 addition & 3 deletions spec/core/regexp/shared/new.rb
Original file line number Diff line number Diff line change
Expand Up @@ -261,9 +261,7 @@ def obj.to_int() ScratchPad.record(:called) end

describe "with escaped characters" do
it "raises a Regexp error if there is a trailing backslash" do
NATFIXME "raises a Regexp error if there is a trailing backslash", exception: SpecFailedException do
-> { Regexp.send(@method, "\\") }.should raise_error(RegexpError, Regexp.new(Regexp.escape("too short escape sequence: /\\/")))
end
-> { Regexp.send(@method, "\\") }.should raise_error(RegexpError, Regexp.new(Regexp.escape("too short escape sequence: /\\/")))
end

it "does not raise a Regexp error if there is an escaped trailing backslash" do
Expand Down
8 changes: 6 additions & 2 deletions src/regexp_object.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ Value RegexpObject::initialize(Env *env, Value pattern, Value opts) {
return this;
}

static String prepare_pattern_for_onigmo(const StringObject *pattern, bool *fixed_encoding) {
static String prepare_pattern_for_onigmo(Env *env, const StringObject *pattern, bool *fixed_encoding) {
String new_pattern;
auto length = pattern->bytesize();
size_t index = 0;
Expand Down Expand Up @@ -344,6 +344,10 @@ static String prepare_pattern_for_onigmo(const StringObject *pattern, bool *fixe
break;
}

case '\0':
env->raise("RegexpError", "too short escape sequence: /{}/", pattern->string());
break;

default:
new_pattern.append_char('\\');
new_pattern.append_char(c);
Expand All @@ -368,7 +372,7 @@ void RegexpObject::initialize_internal(Env *env, const StringObject *pattern, in

bool no_encoding = options & RegexOpts::NoEncoding;
bool fixed_encoding = options & RegexOpts::FixedEncoding;
auto tweaked_pattern = prepare_pattern_for_onigmo(pattern, &fixed_encoding);
auto tweaked_pattern = prepare_pattern_for_onigmo(env, pattern, &fixed_encoding);

if (fixed_encoding)
options |= RegexOpts::FixedEncoding;
Expand Down

0 comments on commit fadd824

Please sign in to comment.