Skip to content

Truly independent web browser

LibRegex: Keep Unicode matches at code-point boundaries

sideshowbarkeraa125429b608
diff --git a/Libraries/LibJS/Rust/src/runtime/regexp_prototype.rs b/Libraries/LibJS/Rust/src/runtime/regexp_prototype.rs
index 952bff2bb6a..fa1af67e143 100644
--- a/Libraries/LibJS/Rust/src/runtime/regexp_prototype.rs
+++ b/Libraries/LibJS/Rust/src/runtime/regexp_prototype.rs
@@ -288,7 +288,7 @@ struct ExecWithLastIndexResult {
effective_last_index: usize,
}
-fn exec_with_unicode_last_index_retry(
+fn exec_with_unicode_last_index(
compiled_regex: &EcmaScriptRegex,
utf16_view: Utf16View<'_>,
last_index: usize,
@@ -314,31 +314,9 @@ fn exec_with_unicode_last_index_retry(
return exec_at(last_index);
}
- // NB: V8/SpiderMonkey first try the code point that starts at the
- // surrogate pair boundary, but zero-width patterns can still match at the
- // original low-surrogate index when that earlier retry fails. Consuming
- // retries must still be rejected so /u and /v regexes never split the
- // surrogate pair.
- let snapped_result = exec_at(last_index - 1);
- if snapped_result.result != MatchResult::NoMatch {
- return snapped_result;
- }
-
- let retried_result = exec_at(last_index);
- if retried_result.result != MatchResult::Match {
- return retried_result;
- }
-
- let match_start = compiled_regex.capture_slot(0);
- let match_end = compiled_regex.capture_slot(1);
- if match_start >= 0 && match_end >= 0 && match_start as usize == last_index && match_end as usize == last_index {
- return retried_result;
- }
-
- ExecWithLastIndexResult {
- result: MatchResult::NoMatch,
- effective_last_index: last_index,
- }
+ // https://tc39.es/ecma262/#sec-regexpbuiltinexec
+ // 13.b. Let inputIndex be the index into input of the character that was obtained from element lastIndex of string.
+ exec_at(last_index - 1)
}
fn legacy_capture_slots(compiled_regex: &EcmaScriptRegex, n_capture_groups: u32) -> LegacyCaptureSlots {
@@ -436,7 +414,7 @@ fn regexp_builtin_exec(
let unicode_mode = flag_bits.has(RegExpFlags::UNICODE) || flag_bits.has(RegExpFlags::UNICODE_SETS);
let utf16_view = string.utf16_string_view();
- let exec_result = exec_with_unicode_last_index_retry(&compiled_regex, utf16_view, last_index, unicode_mode, sticky);
+ let exec_result = exec_with_unicode_last_index(&compiled_regex, utf16_view, last_index, unicode_mode, sticky);
if exec_result.result == MatchResult::LimitExceeded {
return throw_backtrack_limit_exceeded(vm);
}
@@ -1359,7 +1337,7 @@ impl RegExpPrototype {
break;
}
- let exec_result = exec_with_unicode_last_index_retry(
+ let exec_result = exec_with_unicode_last_index(
&compiled_regex,
utf16_view,
last_index as usize,
@@ -1532,7 +1510,7 @@ impl RegExpPrototype {
let mut last_index = 0;
while last_index <= length {
let exec_result =
- exec_with_unicode_last_index_retry(&compiled_regex, string_view, last_index, full_unicode, false);
+ exec_with_unicode_last_index(&compiled_regex, string_view, last_index, full_unicode, false);
if exec_result.result == MatchResult::LimitExceeded {
return throw_backtrack_limit_exceeded(vm);
}
diff --git a/Libraries/LibRegex/Rust/src/regex.rs b/Libraries/LibRegex/Rust/src/regex.rs
index 59f82693c1f..586d5c3b7a8 100644
--- a/Libraries/LibRegex/Rust/src/regex.rs
+++ b/Libraries/LibRegex/Rust/src/regex.rs
@@ -55,7 +55,7 @@ impl Regex {
let mut program = compiler::compile(&parsed);
Self::resolve_properties(&mut program);
let required_literal_hint = extract_required_literal_hint(&parsed, flags);
- let hints = vm::analyze_pattern(&program, pattern_can_match_empty(&parsed), required_literal_hint);
+ let hints = vm::analyze_pattern(&program, required_literal_hint);
let literal_u16 = extract_literal_u16(&parsed, flags);
let word_boundary_literal_u16 = extract_word_boundary_literal_u16(&parsed, flags);
@@ -922,44 +922,6 @@ fn contains_literal_subslice(haystack: &[u16], needle: &[u16]) -> bool {
haystack.windows(needle.len()).any(|window| window == needle)
}
-fn pattern_can_match_empty(pattern: &Pattern) -> bool {
- disjunction_can_match_empty(&pattern.disjunction)
-}
-
-fn disjunction_can_match_empty(disjunction: &Disjunction) -> bool {
- disjunction.alternatives.iter().any(alternative_can_match_empty)
-}
-
-fn alternative_can_match_empty(alternative: &Alternative) -> bool {
- alternative.terms.iter().all(term_can_match_empty)
-}
-
-fn term_can_match_empty(term: &Term) -> bool {
- if let Some(quantifier) = &term.quantifier
- && quantifier.min == 0
- {
- return true;
- }
-
- atom_can_match_empty(&term.atom)
-}
-
-fn atom_can_match_empty(atom: &Atom) -> bool {
- match atom {
- Atom::Literal(_)
- | Atom::Dot
- | Atom::CharacterClass(_)
- | Atom::BuiltinCharacterClass(_)
- | Atom::UnicodeProperty(_) => false,
- Atom::Group(group) => disjunction_can_match_empty(&group.body),
- Atom::NonCapturingGroup(group) => disjunction_can_match_empty(&group.body),
- Atom::Lookaround(_) | Atom::Assertion(_) => true,
- // Backreferences can match empty if their capture is unset or empty.
- Atom::Backreference(_) => true,
- Atom::ModifierGroup(group) => disjunction_can_match_empty(&group.body),
- }
-}
-
fn extract_literal_u16(pattern: &Pattern, flags: Flags) -> Option<Vec<u16>> {
if flags.ignore_case && (flags.unicode || flags.unicode_sets) {
return None;
diff --git a/Libraries/LibRegex/Rust/src/vm.rs b/Libraries/LibRegex/Rust/src/vm.rs
index 9d12e297d9b..121807a91f7 100644
--- a/Libraries/LibRegex/Rust/src/vm.rs
+++ b/Libraries/LibRegex/Rust/src/vm.rs
@@ -442,7 +442,6 @@ fn first_filter_matches<I: Input>(program: &Program, input: I, pos: usize, filte
fn next_candidate_start<I: Input>(program: &Program, input: I, hints: &PatternHints, mut pos: usize) -> Option<usize> {
while pos <= input.len() {
if program.unicode
- && !hints.can_match_empty
&& pos > 0
&& pos < input.len()
&& is_low_surrogate(input.code_unit(pos))
@@ -994,8 +993,6 @@ pub struct PatternHints {
/// Simple pattern: just a single matcher (Save(0) + matcher + Save(1) + Match).
/// Can be executed with a fast scan without the full VM.
simple_scan: Option<SimpleScan>,
- /// Whether the full pattern can match without consuming input.
- can_match_empty: bool,
}
pub(crate) struct RequiredLiteralHint {
@@ -1150,11 +1147,7 @@ fn next_literal_start_from_hint<I: Input>(input: I, start: usize, hint: &StartPo
}
/// Analyze the program to extract optimization hints.
-pub(crate) fn analyze_pattern(
- program: &Program,
- can_match_empty: bool,
- ast_required_literal: Option<RequiredLiteralHint>,
-) -> PatternHints {
+pub(crate) fn analyze_pattern(program: &Program, ast_required_literal: Option<RequiredLiteralHint>) -> PatternHints {
// Pattern typically starts with Save(0), then the first real instruction.
let skip = if matches!(program.instructions.first(), Some(Instruction::Save(0))) {
1
@@ -1285,7 +1278,6 @@ pub(crate) fn analyze_pattern(
trailing_literal,
required_literal,
simple_scan,
- can_match_empty,
}
}
diff --git a/Tests/LibJS/Runtime/builtins/RegExp/RegExp.js b/Tests/LibJS/Runtime/builtins/RegExp/RegExp.js
index 1fb3fe8b90f..4c78ccec838 100644
--- a/Tests/LibJS/Runtime/builtins/RegExp/RegExp.js
+++ b/Tests/LibJS/Runtime/builtins/RegExp/RegExp.js
@@ -207,17 +207,14 @@ test("complex v-mode lookbehind with negated emoji class finds the V8 match", ()
expect(subject.match(new RegExp(regex.source, "gv"))).toEqual([expected]);
});
-test("unicode lastIndex retries the original low-surrogate position after a failed snap-back", () => {
+test("unicode lastIndex does not retry a failed lookbehind inside a surrogate pair", () => {
const regex = /\p{Script=Cyrillic}?(?<!\D)/vy;
regex.lastIndex = 2;
- const result = regex.exec("A😘");
- expect(result).not.toBeNull();
- expect(result.index).toBe(2);
- expect(result[0]).toBe("");
- expect(regex.lastIndex).toBe(2);
+ expect(regex.exec("A😘")).toBeNull();
+ expect(regex.lastIndex).toBe(0);
- expect("A😘".match(/\p{Script=Cyrillic}?(?<!\D)/gv)).toEqual(["", ""]);
+ expect("A😘".match(/\p{Script=Cyrillic}?(?<!\D)/gv)).toEqual([""]);
});
test("unicode lastIndex still snaps to the start of a surrogate pair when that matches", () => {
@@ -242,15 +239,15 @@ test("unicode lastIndex does not retry consuming matches at low surrogates", ()
expect("πŸ˜€".replace(regex, "x")).toBe("πŸ˜€");
});
-test("global unicode matches keep low-surrogate empty matches that V8 finds", () => {
+test("negative non-digit lookbehind matches only at the start or after digits", () => {
const subject =
"Ψ³Ω„Ψ§Ω… μΉ΄μ°¨κ°€β‰  -YAπŸ˜˜πŸ™‚πŸ€” Ψ°Ψ°Ψ°/8️⃣ бшгА884 ΠΆΠ• πŸŒŸπŸŽ€πŸŽ€πŸŽˆβœ¨πŸš€\nβœ¨Ρ‚Π΅ΡΡ‚( \n\t \t },{ `:ΰ€•ΰ€—ΰ€΅ΰ€šΰ€šΰ€œΰ€― mmmmm\t999\nβš‘πŸ’’πŸ’₯β€οΈπŸ’§;δΊΊΰ€¬ΰ€ˆΓ·{{πŸ˜ŠπŸ˜ŠπŸ”’πŸ”’πŸ”’_";
- expect(subject.match(/\p{Script=Cyrillic}?(?<!\D)/gv)).toEqual(new Array(24).fill(""));
+ expect(subject.match(/\p{Script=Cyrillic}?(?<!\D)/gv)).toEqual(new Array(8).fill(""));
});
-test("lookahead inside surrogate pair does not match paired low surrogate as a character", () => {
- expect("πŸ’¦πŸ’¦".match(/(?!\W)/gv)).toEqual(["", "", ""]);
- expect("πŸ’¦πŸ’¦".match(/\p{Emoji_Presentation}?(?!\W)/gv)).toEqual(["", "πŸ’¦", ""]);
+test("negative non-word lookahead does not match inside surrogate pairs", () => {
+ expect("πŸ’¦πŸ’¦".match(/(?!\W)/gv)).toEqual([""]);
+ expect("πŸ’¦πŸ’¦".match(/\p{Emoji_Presentation}?(?!\W)/gv)).toEqual(["πŸ’¦", ""]);
});
test("backward v-mode class-set operations inspect the consumed code point", () => {
diff --git a/Tests/LibJS/Runtime/regexp-unicode-zero-width-surrogate-positions.js b/Tests/LibJS/Runtime/regexp-unicode-zero-width-surrogate-positions.js
index 2e05f14de53..71ac04377ea 100644
--- a/Tests/LibJS/Runtime/regexp-unicode-zero-width-surrogate-positions.js
+++ b/Tests/LibJS/Runtime/regexp-unicode-zero-width-surrogate-positions.js
@@ -1,15 +1,91 @@
-test("unicode zero-width patterns can match at surrogate interior positions", () => {
- let global_matcher = /\B/gu;
- global_matcher.lastIndex = 2;
-
- let match = global_matcher.exec("AπŸ˜€");
- expect(match).not.toBeNull();
- expect(match[0]).toBe("");
- expect(match.index).toBe(2);
- expect(global_matcher.lastIndex).toBe(2);
-
- match = /(?!πŸ˜€)/u.exec("πŸ˜€");
- expect(match).not.toBeNull();
- expect(match[0]).toBe("");
- expect(match.index).toBe(1);
+for (const flag of ["u", "v"]) {
+ test(`/${flag} zero-width searches skip surrogate interiors`, () => {
+ const match = new RegExp("(?!πŸ˜€)", flag).exec("πŸ˜€");
+ expect(match[0]).toBe("");
+ expect(match.index).toBe(2);
+ expect(new RegExp("(?!\\W)$", flag).test("πŸ˜€")).toBeTrue();
+ expect(new RegExp("(?!\\W)(?=.)", flag).test("πŸ˜€")).toBeFalse();
+ });
+
+ for (const [source, indices, replacement] of [
+ ["(?<g1>.{0}\\k<g1>)", [0, 2, 4, 6], "#πŸ˜€#πŸ˜€#πŸ˜€#"],
+ ["(?<a>)\\k<a>(?<!.)", [0], "#πŸ˜€πŸ˜€πŸ˜€"],
+ ["(?!\\W)", [6], "πŸ˜€πŸ˜€πŸ˜€#"],
+ ["(?<!.)", [0], "#πŸ˜€πŸ˜€πŸ˜€"],
+ ["\\B", [0, 2, 4, 6], "#πŸ˜€#πŸ˜€#πŸ˜€#"],
+ ]) {
+ test(`/${source}/g${flag} matches only at code-point boundaries`, () => {
+ const matcher = new RegExp(source, "g" + flag);
+ expect(Array.from("πŸ˜€πŸ˜€πŸ˜€".matchAll(matcher), match => match.index)).toEqual(indices);
+ expect("πŸ˜€πŸ˜€πŸ˜€".match(matcher)).toEqual(indices.map(() => ""));
+ expect("πŸ˜€πŸ˜€πŸ˜€".replace(matcher, "#")).toBe(replacement);
+ expect("πŸ˜€πŸ˜€πŸ˜€".replace(matcher, () => "#")).toBe(replacement);
+ });
+ }
+
+ test(`/${flag} searches retain lone surrogates`, () => {
+ const matcher = new RegExp("(?!πŸ˜€)", "g" + flag);
+ const input = "\uD83Da\uDE00πŸ˜€";
+ expect(Array.from(input.matchAll(matcher), match => match.index)).toEqual([0, 1, 2, 5]);
+ });
+
+ for (const source of ["\\B", "(?!πŸ˜€)"]) {
+ test(`/${source}/g${flag} searches past a pair containing lastIndex`, () => {
+ const matcher = new RegExp(source, "dg" + flag);
+ matcher.lastIndex = 2;
+ const match = matcher.exec("AπŸ˜€");
+ expect(match[0]).toBe("");
+ expect(match.index).toBe(3);
+ expect(match.indices).toEqual([[3, 3]]);
+ expect(matcher.lastIndex).toBe(3);
+ });
+
+ for (const flags of ["y" + flag, "gy" + flag]) {
+ test(`/${source}/${flags} does not retry inside a surrogate pair`, () => {
+ const matcher = new RegExp(source, flags);
+ matcher.lastIndex = 2;
+ expect(matcher.exec("AπŸ˜€")).toBeNull();
+ expect(matcher.lastIndex).toBe(0);
+
+ matcher.lastIndex = 2;
+ expect(matcher.test("AπŸ˜€")).toBeFalse();
+ expect(matcher.lastIndex).toBe(0);
+ });
+ }
+
+ test(`/${source}/y${flag} replacement does not split a surrogate pair`, () => {
+ const matcher = new RegExp(source, "y" + flag);
+ matcher.lastIndex = 2;
+ expect("AπŸ˜€".replace(matcher, "#")).toBe("AπŸ˜€");
+ expect(matcher.lastIndex).toBe(0);
+
+ matcher.lastIndex = 2;
+ expect("AπŸ˜€".replace(matcher, () => "#")).toBe("AπŸ˜€");
+ expect(matcher.lastIndex).toBe(0);
+ });
+ }
+
+ for (const flags of ["g" + flag, "y" + flag]) {
+ for (const [source, matched, end] of [
+ ["(?:)", "", 1],
+ [".", "πŸ˜€", 3],
+ ]) {
+ test(`/${source}/${flags} starts at the code point containing lastIndex`, () => {
+ const matcher = new RegExp(source, flags);
+ matcher.lastIndex = 2;
+ const match = matcher.exec("AπŸ˜€");
+ expect(match[0]).toBe(matched);
+ expect(match.index).toBe(1);
+ expect(matcher.lastIndex).toBe(end);
+ });
+ }
+ }
+}
+
+test("non-Unicode zero-width patterns can match inside surrogate pairs", () => {
+ expect(Array.from("πŸ˜€".matchAll(/\B/g), match => match.index)).toEqual([0, 1, 2]);
+ const matcher = /\B/y;
+ matcher.lastIndex = 2;
+ expect(matcher.exec("AπŸ˜€").index).toBe(2);
+ expect(matcher.lastIndex).toBe(2);
});
diff --git a/Tests/LibRegex/TestRegex.cpp b/Tests/LibRegex/TestRegex.cpp
index 38228897758..7b348787587 100644
--- a/Tests/LibRegex/TestRegex.cpp
+++ b/Tests/LibRegex/TestRegex.cpp
@@ -241,6 +241,28 @@ TEST_CASE(find_all_returns_non_overlapping_matches)
EXPECT_EQ(regex.find_all_match(1).end, 7);
}
+TEST_CASE(unicode_find_all_skips_surrogate_interiors_after_empty_matches)
+{
+ for (auto flags : { regex::ECMAScriptCompileFlags { .unicode = true }, regex::ECMAScriptCompileFlags { .unicode_sets = true } }) {
+ auto empty = compile_regex("(?<a>)\\k<a>"sv, flags);
+ EXPECT_EQ(empty.find_all(u"πŸ˜€πŸ˜€"sv, 0), 3);
+ for (size_t i = 0; i < 3; ++i) {
+ EXPECT_EQ(empty.find_all_match(i).start, static_cast<i32>(i * 2));
+ EXPECT_EQ(empty.find_all_match(i).end, static_cast<i32>(i * 2));
+ }
+
+ auto lookbehind = compile_regex("(?<!.)"sv, flags);
+ EXPECT_EQ(lookbehind.find_all(u"πŸ˜€πŸ˜€"sv, 0), 1);
+ EXPECT_EQ(lookbehind.find_all_match(0).start, 0);
+ EXPECT_EQ(lookbehind.find_all_match(0).end, 0);
+
+ auto lookahead = compile_regex("(?!\\W)"sv, flags);
+ EXPECT_EQ(lookahead.find_all(u"πŸ˜€πŸ˜€"sv, 0), 1);
+ EXPECT_EQ(lookahead.find_all_match(0).start, 4);
+ EXPECT_EQ(lookahead.find_all_match(0).end, 4);
+ }
+}
+
TEST_CASE(unicode_property_matching_works)
{
auto regex = MUST(compile_regex_result("\\p{ASCII}+"sv, { .unicode = true }));