Skip to content

Commit 60b184e

Browse files
committed
Shorten a word boundary next to a word character
A "\b" becomes a condition with three word classes, because PCRE has other word characters than ICU. Next to a literal ASCII letter, digit, or "_" that is not repeated, one side of the boundary is known, so one class is enough: "\bword\b" is now "(?<![…])word(?![…])". The same holds for "\B". Measured on PHP 8.5 with PCRE 10.49, on 5.9 MB of text that does not match: - "\bneedle\b|\bhaystack\b|\bthread\b" takes 7.9 ms, and 54.7 ms before. Without JIT, it takes 40.7 ms, and 685 ms before. - "\bneedle\b" takes 1.7 ms, and 3.1 ms before. - A list of "\bword\b" alternatives compiles with up to 426 words, and with up to 148 before. A boundary next to a group, a set, or a repeated character is unchanged.
1 parent 05a962f commit 60b184e

2 files changed

Lines changed: 50 additions & 28 deletions

File tree

‎packages/mysql-on-sqlite/src/icu/class-wp-icu-regex-translator.php‎

Lines changed: 32 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -114,9 +114,11 @@ class WP_ICU_Regex_Translator {
114114
);
115115

116116
/*
117-
* The tokens of a pattern. An item may have a quantifier, and a position may not.
118-
* TOKEN captures the quantifier (1), the flags that an inline flag group turns on (2)
119-
* and off (3) with its end (4), and text that is no supported token (5).
117+
* TOKEN capture groups used by translate_token()
118+
* 1 Optional quantifier
119+
* 2–4 Flags to enable, flags to disable, and the delimiter (":" or ")")
120+
* 5 Unsupported syntax
121+
* 6 Following ASCII word character, if unquantified
120122
*/
121123
private const QUOTE = '\\\\Q(?!\\\\E)(?:[^\\\\]++|\\\\(?!E))*+';
122124
private const ESCAPE = '\\\\(?:[pP]\{[^}]*\}|x\{[0-9A-Fa-f]{1,6}\}|x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}|0[0-3][0-7]{2}|0[0-7]{1,2}|c[\x00-\x7F]|k<[A-Za-z][A-Za-z0-9]*>|[1-9](?!\d)|[^Q0-9])';
@@ -128,45 +130,37 @@ class WP_ICU_Regex_Translator {
128130
private const GROUP = '\((?:(?!\?)|\?(?:[:=!>]|<[A-Za-z][A-Za-z0-9]*>|#[^)\\\\]*\)|(?=[imsdu-])([imsdu]*)-?([imsdu]*)([:)])))';
129131
private const BRACE = '\}|(?!' . self::INTERVAL . ')\{';
130132

131-
/*
132-
* A look-behind is one token. It can hold single characters, sets, and "|" only, as
133-
* every PCRE version supports that, where older ones reject other look-behinds.
134-
*/
133+
// Match the whole lookbehind here so each alternative has a fixed length on older PCRE versions.
135134
private const LOOK_BEHIND = '\(\?<[=!](?:' . self::SET . '|(?!\\\\[AbBGkRXzZ1-9])' . self::ESCAPE . '|[^\\\\\[(){}^$.*+?]++|\.)*+\)';
136135

137-
// Text that is no supported token: the start of an escape or a group, or a character.
136+
// Catch unrecognized syntax so the error can name the offending token.
138137
private const OTHER = '\\\\(?:Q\\\\E|\d+)?|\(\?(?:<[=!]|\w+|[^)])?|[\s\S]';
139-
private const TOKEN = '/(?:[^\\\\\[(){}|^$.*+?\/\x00]++|' . self::QUOTE . '(?:\\\\E|\z)|' . self::ESCAPE . '|' . self::POSIX . '|' . self::SET . '|[.)\/\x00])' . self::QUANTIFIER . '|' . self::LOOK_BEHIND . '|' . self::GROUP . '|' . self::BRACE . '|\[\[:[<>]:\]\]|[|^$]|(' . self::OTHER . ')/';
138+
private const TOKEN = '/(?:(?:[^\\\\\[(){}|^$.*+?\/\x00]++|' . self::QUOTE . '(?:\\\\E|\z)|' . self::ESCAPE . '|' . self::POSIX . '|' . self::SET . '|[.)\/\x00])' . self::QUANTIFIER . '|' . self::LOOK_BEHIND . '|' . self::GROUP . '|' . self::BRACE . '|\[\[:[<>]:\]\]|[|^$]|(' . self::OTHER . '))(?=([A-Za-z0-9_](?![*+?{]))?)/';
140139

141-
// The longest pattern to translate. A translation can be many times as long as its
142-
// pattern, and PCRE can compile only few longer patterns, like a long set.
140+
// Cap the input size before expanding tokens such as word boundaries into longer PCRE patterns.
143141
private const MAX_LENGTH = 65535;
144142

145-
// The MySQL error for a regular expression feature that isn't implemented.
143+
// MySQL ER_REGEXP_UNIMPLEMENTED.
146144
private const UNSUPPORTED = 3690;
147145

148-
// The flags in effect, as ICU's flag letters.
149146
private $flags;
150147

151-
// For each open group: the flags to restore at its end, whether it can be repeated,
152-
// and the number of start checks before it.
148+
// Each open group saves its flags, whether it can be quantified, and the current count of start checks.
153149
private $groups = array();
154150

155-
// Where a match can start, for each ".*" that starts a leading group. The translation
156-
// has a NUL byte in the place of each one. A repeated group has an empty one.
151+
// Deferred start checks, in the order of their NUL placeholders in the translated pattern.
157152
private $starts = array();
158153

159-
// Whether the pattern has a backreference.
160154
private $has_backreference = false;
161155

162-
// Whether the next token starts the pattern, an alternative outside of groups, or a
163-
// group that does.
156+
// True at the start of the pattern, a top-level alternative, or a group that starts there.
164157
private $is_leading = true;
165158

166-
// Whether "\G" never matches.
159+
// The previous token ended with an unquantified ASCII word character.
160+
private $is_after_word = false;
161+
167162
private $without_g;
168163

169-
// Whether the pattern matches bytes instead of UTF-8 characters.
170164
private $bytes;
171165

172166
/**
@@ -210,16 +204,24 @@ private function translate_token( $parts ) {
210204
$token = $parts[0];
211205
$quantifier = $parts[1] ?? '';
212206
$item = substr( $token, 0, strlen( $token ) - strlen( $quantifier ) );
213-
if ( isset( $parts[5] ) ) {
207+
if ( '' !== ( $parts[5] ?? '' ) ) {
214208
throw new WP_ICU_Regex_Exception( "Unsupported regular expression syntax: $token", self::UNSUPPORTED );
215209
}
216-
$is_leading = $this->is_leading;
217-
$this->is_leading = '|' === $token && ! $this->groups;
210+
$is_leading = $this->is_leading;
211+
$this->is_leading = '|' === $token && ! $this->groups;
212+
$is_after_word = $this->is_after_word;
213+
$this->is_after_word = false;
218214

219215
switch ( $item[0] ) {
220216
case '\\':
221217
// A position, like "\b", can't be repeated.
222218
if ( '' === $quantifier || false === strpos( 'AbBGzZ', $item[1] ) ) {
219+
// In "\bword\b", each boundary needs to test only the side facing away from the word.
220+
// Omitting the other tests keeps word lists smaller when PCRE compiles them.
221+
$is_before_word = isset( $parts[6] );
222+
if ( 'b' === strtolower( $item[1] ) && ! $this->bytes && ( $is_before_word || $is_after_word ) ) {
223+
return '(?' . ( $is_before_word ? '<' : '' ) . ( 'b' === $item[1] ? '!' : '=' ) . '[' . self::WORD . '])';
224+
}
223225
return $this->translate_escape( substr( $item, 1 ), false ) . $quantifier;
224226
}
225227
break;
@@ -247,9 +249,10 @@ private function translate_token( $parts ) {
247249
if ( '#' === $item[2] ) {
248250
return '(?#)';
249251
}
250-
// A look-behind has no groups, so its tokens are translated in place.
251-
$inside = self::replace( self::TOKEN, array( $this, 'translate_token' ), substr( $item, 4, -1 ) );
252-
$this->is_leading = false;
252+
// LOOK_BEHIND excludes nested groups. Translate its contents with the current flags.
253+
$inside = self::replace( self::TOKEN, array( $this, 'translate_token' ), substr( $item, 4, -1 ) );
254+
$this->is_leading = false;
255+
$this->is_after_word = false;
253256
return substr( $item, 0, 4 ) . $inside . ')';
254257
}
255258
// A lookahead consumes no text. An atomic group keeps its first match.
@@ -303,6 +306,7 @@ private function translate_token( $parts ) {
303306
case '|':
304307
return '|';
305308
default:
309+
$this->is_after_word = '' === $quantifier && 1 === preg_match( '/[A-Za-z0-9_]$/D', $token );
306310
return $token;
307311
}
308312
throw new WP_ICU_Regex_Exception( "Unsupported regular expression syntax: $token", self::UNSUPPORTED );

‎packages/mysql-on-sqlite/tests/icu/WP_ICU_Regex_Translator_Tests.php‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1046,6 +1046,24 @@ public function test_a_leading_dot_star_matches_like_any_other(): void {
10461046
$this->assertSame( '/(?:\G|(?<=[\n\x0B\f\r]))[^\n\x0B\f\r]*a/X', WP_ICU_Regex_Translator::translate( '.*a', '', false, true ) );
10471047
}
10481048

1049+
public function test_a_word_boundary_next_to_a_word_character_checks_one_side(): void {
1050+
$word = '[\p{L}\p{M}\p{Nd}\p{Nl}\p{Pc}\x{200C}\x{200D}\x{24B6}-\x{24E9}\x{1F130}-\x{1F149}\x{1F150}-\x{1F169}\x{1F170}-\x{1F189}]';
1051+
$this->assertSame( "/(?<!$word)word(?!$word)/uX", WP_ICU_Regex_Translator::translate( '\bword\b' ) );
1052+
$this->assertSame( "/(?<=$word)_1(?=$word)/uX", WP_ICU_Regex_Translator::translate( '\B_1\B' ) );
1053+
$this->assertSame( "/a(?<!$word)b|c(?!$word)/uXi", WP_ICU_Regex_Translator::translate( 'a\bb|c\b', 'i' ) );
1054+
$this->assertSame( '/\bword\b/X', WP_ICU_Regex_Translator::translate( '\bword\b', '', false, true ) );
1055+
1056+
// Keep the full boundary check unless the translator recognizes an adjacent, unquantified ASCII word character.
1057+
foreach ( array( '\b', '\b-', '\bé', '\ba*', '\ba?', '\ba{2}', '\b(a)', '\b[a]', '\b\w', '-\b', 'é\b', 'a*\b', 'a+\b', '(a)\b', '[a]\b', '\x61\b', '(?<=a)\b' ) as $pattern ) {
1058+
$this->assertStringContainsString( "(?(?<=$word)(?!$word)|(?=$word))", WP_ICU_Regex_Translator::translate( $pattern ), $pattern );
1059+
}
1060+
1061+
$this->assertSame( '<cat> concat cat_ écat <cat>', $this->replace_matches( WP_ICU_Regex_Translator::translate( '\bcat\b' ), 'cat concat cat_ écat cat' ) );
1062+
$this->assertSame( 'cat con<cat> é<cat>', $this->replace_matches( WP_ICU_Regex_Translator::translate( '\Bcat' ), 'cat concat écat' ) );
1063+
$this->assertSame( "<k> <\u{212A}> ak", $this->replace_matches( WP_ICU_Regex_Translator::translate( '\bk\b', 'i' ), "k \u{212A} ak" ) );
1064+
$this->assertSame( 'ab', $this->replace_matches( WP_ICU_Regex_Translator::translate( 'a\bb' ), 'ab' ) );
1065+
}
1066+
10491067
public function test_unknown_flags_are_rejected(): void {
10501068
$this->expectException( WP_ICU_Regex_Exception::class );
10511069
WP_ICU_Regex_Translator::translate( 'a', 'x' );

0 commit comments

Comments
 (0)