When _M_greedy_char_loop has consumed a run of characters, it records
the shorter exits, one character shorter each time, so that the DFS can
backtrack into them if the longest one fails. But often none of them
can succeed: in [\w.+-]+@ the loop body rejects '@', and every character
of the run was accepted by the body, so '@' can't match after any
shorter exit. Backtracking into them anyway costs a frame pop and push,
a dispatch and a std::function call per exit, for each start position
in the run, which is much more expensive than scanning the run itself.
This patch adds _M_skip_shorter_exits, which follows the loop's exit
through states that neither consume input nor branch (captures and
dummies) to the first state that does, and skips recording the shorter
exits if that state is:
* A match state that can't accept any character the loop body
accepted. We check this when either side is a literal character (a
non-icase, non-collate _CharMatcher): the following literal is
rejected by the body, e.g. "[^"]*", [^\n]*\n, .*\n, [\w.+-]+@ in the
Email pattern and [\w]+: in the URI pattern, or the literal body is
rejected by the following match state, e.g. 0*[1-9], ' *[^ ]' and
a*\d. But not e.g. [\w.-]+\., \w+\w, a*[a-c] or (a*)\w, where the
following match state accepts some character the body accepts.
* A line end assertion. Every shorter exit is before the longest one
and so before the end of the input, so a non-multiline $ must fail
there, e.g. \s+$. A multiline $ also succeeds before a line
terminator, which can only follow a shorter exit if the loop body
accepts one, so the shorter exits must also fail if the body is a
literal other than a line terminator, e.g. ' +$'.
* The accept state. In _Match_mode::_Exact it only succeeds at the end
of the input, so the shorter exits must fail, e.g. regex_match with
\w+. In _Match_mode::_Prefix it always succeeds after the longest
exit, which is non-empty, and the shorter exits are then discarded
without being tried. So they needn't be recorded in either mode,
which keeps _M_skip_shorter_exits independent of the match mode.
Anything else on the way (alternatives, repeats, other assertions,
lookaheads, backrefs) leaves the loop as before. Only paths that must
fail or would never be tried are skipped, so results are unchanged. The
answer depends only on the NFA, so it's computed the first time the loop
is entered and cached in the loop's _M_rep_count entry, which is
otherwise unused for such loops.
Benchmark (x86_64, -O2, pinned to one core):
* regex-benchmark's cpp/benchmark.cpp, i.e. sregex_token_iterator over
its 6.8 MB input-text.txt (median of 5 interleaved runs):
before after
Email ~154 ms ~93 ms
URI ~135 ms ~86 ms
IP ~10 ms ~10 ms
* Calling regex_search separately on each of the file's 206K lines
(median of 5 interleaved runs):
before after
Email ~195 ms ~131 ms
URI ~165 ms ~120 ms
IP ~86 ms ~86 ms
The IP pattern has no * or + loops, so it is unaffected. Match counts
are identical before and after.
* Other patterns (best of 5-7 runs, two rounds; "per line" means
calling regex_search or regex_match separately on each line of the
same file):
before after
regex_search 0*[1-9] over 100K runs
of 8 zeros ~31 ms ~13 ms
same, wchar_t ~108 ms ~37 ms
regex_search ' *[^ \w]' over 50K
indented words ~23 ms ~15 ms
regex_search a*\d over 100K runs of 8 a's ~31 ms ~13 ms
regex_search \s+$ per line ~81 ms ~68 ms
regex_search [ \t]+$ per line ~79 ms ~68 ms
regex_search \w+$ per line ~159 ms ~112 ms
regex_match [\w ]+ per line ~17 ms ~11 ms
regex_match [^\t]* per line ~26 ms ~23 ms
The [^\t]* case matches every line, but no longer pushes the frames
for the shorter exits only to discard them, and neither does
regex_search with a pattern ending in such a loop.
* Extreme cases:
before after
regex_search x+y on 20000 x's ~1085 ms ~46 ms
regex_search ' *[^ \w]' on 20000
spaces then x ~1160 ms ~48 ms
regex_search \s+$ on 20000 spaces
then x ~1125 ms ~139 ms
regex_match \w+ on 20000 a's then !,
1000 times ~120 ms ~14 ms
libstdc++-v3/ChangeLog:
* include/bits/regex_executor.h
(_Executor::_M_skip_shorter_exits): Declare.
* include/bits/regex_executor.tcc
(_Executor::_M_greedy_char_loop): Don't record the shorter exits
if _M_skip_shorter_exits, caching its result in _M_rep_count.
(_Executor::_M_skip_shorter_exits): Define.
*
testsuite/28_regex/algorithms/regex_search/ecma/greedy_loop_literal.cc:
New test.
Assisted-by: Claude Opus 5.5
---
libstdc++-v3/include/bits/regex_executor.h | 3 +
libstdc++-v3/include/bits/regex_executor.tcc | 91 +++++++-
.../regex_search/ecma/greedy_loop_literal.cc | 218 ++++++++++++++++++
3 files changed, 307 insertions(+), 5 deletions(-)
create mode 100644
libstdc++-v3/testsuite/28_regex/algorithms/regex_search/ecma/greedy_loop_literal.cc
diff --git a/libstdc++-v3/include/bits/regex_executor.h
b/libstdc++-v3/include/bits/regex_executor.h
index ca5d77bfa1e..69979c4f6fb 100644
--- a/libstdc++-v3/include/bits/regex_executor.h
+++ b/libstdc++-v3/include/bits/regex_executor.h
@@ -138,6 +138,9 @@ _GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V3)
_StateIdT
_M_greedy_char_loop(_StateIdT);
+ bool
+ _M_skip_shorter_exits(const _State<_CharT>&) const;
+
template<_Search_mode __search_mode>
_StateIdT
_M_handle_repeat(_Match_mode, _StateIdT);
diff --git a/libstdc++-v3/include/bits/regex_executor.tcc
b/libstdc++-v3/include/bits/regex_executor.tcc
index a9f1eaab22a..d6ba91a79f9 100644
--- a/libstdc++-v3/include/bits/regex_executor.tcc
+++ b/libstdc++-v3/include/bits/regex_executor.tcc
@@ -517,12 +517,17 @@ namespace __detail
// are recorded by a single _S_fopcode_greedy_char_loop frame (on top of a
// _S_fopcode_greedy_char_loop_bound frame holding the start position)
// which is unwound in _M_dfs. This explores the same paths in the same
- // order as the generic code.
+ // order as the generic code, except that the shorter exits aren't
+ // recorded at all if none of them could make a difference (see
+ // _M_skip_shorter_exits).
//
// _M_rep_count[__i] is not needed: entering the body immediately consumes a
// character or fails, so in the generic code __i can never be re-entered at
// the same position while its repeat-count frame is active, and any epsilon
// cycle through __i must pass through another repeat that tracks its count.
+ // Since __i never reaches _M_rep_once_more, _M_rep_count[__i].second is
+ // instead used to cache the result of _M_skip_shorter_exits: 0 means not
+ // yet computed, 1 means true and -1 means false.
template<typename _BiIter, typename _Alloc, typename _TraitsT>
_StateIdT _Executor<_BiIter, _Alloc, _TraitsT>::
_M_greedy_char_loop(_StateIdT __i)
@@ -533,15 +538,91 @@ namespace __detail
= _M_visit_matcher(__body, _Greedy_scan{_M_current, _M_end});
if (__cur != _M_current)
{
- _M_frames.emplace_back(_S_fopcode_greedy_char_loop_bound, __i,
- _M_current);
- _M_frames.emplace_back(_S_fopcode_greedy_char_loop, __state._M_next,
- std::prev(__cur));
+ int& __cache = _M_rep_count[__i].second;
+ if (__cache == 0)
+ __cache = _M_skip_shorter_exits(__state) ? 1 : -1;
+ if (__cache < 0)
+ {
+ _M_frames.emplace_back(_S_fopcode_greedy_char_loop_bound, __i,
+ _M_current);
+ _M_frames.emplace_back(_S_fopcode_greedy_char_loop,
+ __state._M_next, std::prev(__cur));
+ }
_M_current = __cur;
}
return __state._M_next;
}
+ // Return whether the exits of the greedy single-char loop at the repeat
+ // state __rep other than the longest one needn't be recorded. This is
+ // only asked once the loop has consumed at least one character, so each
+ // shorter exit is before the longest one and is followed by a character
+ // the loop body accepted. We look at the state that the loop's exit
+ // leads to through states that neither consume input nor branch:
+ //
+ // - A match state: the shorter exits must fail if it can't accept any
+ // character the loop body accepted. We check this when either side is
+ // a literal character: the following literal is rejected by the body,
+ // e.g. "[^"]*" or [\w.+-]+@, or the literal body is rejected by the
+ // following match state, e.g. 0*[1-9] or ' *[^ ]'. But not e.g.
+ // [\w.-]+\., \w+\w or a*[a-c].
+ //
+ // - A line end assertion: a non-multiline $ only succeeds at _M_end, which
+ // no shorter exit is at, e.g. \s+$. A multiline $ also succeeds before
+ // a line terminator, so the shorter exits must fail only if the body is
+ // a literal other than a line terminator, e.g. ' +$'.
+ //
+ // - The accept state: in _Match_mode::_Exact it only succeeds at _M_end,
+ // so the shorter exits must fail. In _Match_mode::_Prefix it always
+ // succeeds after the longest exit (which is non-empty, so even
+ // match_not_null can't reject it), and the shorter exits would then be
+ // discarded unexplored. Either way, e.g. \w+ in regex_match or
+ // regex_search.
+ template<typename _BiIter, typename _Alloc, typename _TraitsT>
+ bool _Executor<_BiIter, _Alloc, _TraitsT>::
+ _M_skip_shorter_exits(const _State<_CharT>& __rep) const
+ {
+ // A non-icase, non-collate _CharMatcher matches exactly _M_ch.
+ using _CharM = _CharMatcher<_TraitsT, false, false>;
+ const auto& __body = _M_nfa[__rep._M_alt];
+ // Every NFA cycle passes through a repeat state, so this terminates.
+ _StateIdT __i = __rep._M_next;
+ while (__i != _S_invalid_state_id)
+ {
+ const auto& __state = _M_nfa[__i];
+ switch (__state._M_opcode())
+ {
+ case _S_opcode_subexpr_begin:
+ case _S_opcode_subexpr_end:
+ case _S_opcode_dummy:
+ __i = __state._M_next;
+ break;
+ case _S_opcode_match:
+ {
+ if (const auto* __lit
+ = __state._M_get_matcher().template
_M_target_if<_CharM>())
+ return !__body._M_matches(__lit->_M_ch);
+ if (const auto* __lit
+ = __body._M_get_matcher().template _M_target_if<_CharM>())
+ return !__state._M_matches(__lit->_M_ch);
+ return false;
+ }
+ case _S_opcode_line_end_assertion:
+ if (!_M_match_multiline())
+ return true;
+ if (const auto* __lit
+ = __body._M_get_matcher().template _M_target_if<_CharM>())
+ return !_M_is_line_terminator(__lit->_M_ch);
+ return false;
+ case _S_opcode_accept:
+ return true;
+ default:
+ return false;
+ }
+ }
+ return false;
+ }
+
// _M_alt branch is "match once more", while _M_next is "get me out
// of this quantifier". Executing _M_next first or _M_alt first don't
// mean the same thing, and we need to choose the correct order under
diff --git
a/libstdc++-v3/testsuite/28_regex/algorithms/regex_search/ecma/greedy_loop_literal.cc
b/libstdc++-v3/testsuite/28_regex/algorithms/regex_search/ecma/greedy_loop_literal.cc
new file mode 100644
index 00000000000..f179dce87f7
--- /dev/null
+++
b/libstdc++-v3/testsuite/28_regex/algorithms/regex_search/ecma/greedy_loop_literal.cc
@@ -0,0 +1,218 @@
+// { dg-do run { target c++11 } }
+
+// Greedy single-character loops followed by a literal, where all exits
+// of the loop other than the longest can be skipped when the loop body
+// rejects the literal. Also check cases where they can't be skipped.
+
+#include <regex>
+#include <string>
+#include <testsuite_hooks.h>
+#include <testsuite_regex.h>
+
+using namespace __gnu_test;
+using namespace std;
+
+#define TEST(i, s) VERIFY(m[i].matched && string(m[i].first, m[i].second) == s)
+
+void
+test01()
+{
+ cmatch m;
+
+ // The body rejects the literal.
+ VERIFY(regex_search_debug("x \"abc\" y", m, regex("\"[^\"]*\"")));
+ TEST(0, "\"abc\"");
+ VERIFY(regex_search_debug("mail [email protected] now", m,
+ regex("[\\w.+-]+@[\\w.-]+\\.[\\w.-]+")));
+ TEST(0, "[email protected]");
+ VERIFY(regex_search_debug("aaac aab", m, regex("a*b")));
+ TEST(0, "aab");
+ VERIFY(regex_search_debug("ab\ncd", m, regex("[^\\n]*\\n")));
+ TEST(0, "ab\n");
+ VERIFY(regex_search_debug("ab\ncd\n", m, regex(".*\\n")));
+ TEST(0, "ab\n");
+ VERIFY(!regex_search_debug("xxxz", m, regex("x*y")));
+ VERIFY(regex_search_debug("ab\rcd\n", m, regex(".*\\n")));
+ TEST(0, "cd\n");
+
+ // The literal body is rejected by what follows.
+ VERIFY(regex_search_debug("000x 0042", m, regex("0*[1-9]")));
+ TEST(0, "004");
+ VERIFY(regex_search_debug(" ab =", m, regex(" *[^ \\w]")));
+ TEST(0, " =");
+ VERIFY(!regex_search_debug("aaa.", m, regex("a*\\d")));
+ VERIFY(regex_search_debug("baa1", m, regex("(a*)(\\d)")));
+ TEST(0, "aa1");
+ TEST(1, "aa");
+ VERIFY(regex_search_debug("aaab", m, regex("a*[^a]")));
+ TEST(0, "aaab");
+
+ // Runs of zero or one characters.
+ VERIFY(regex_search_debug("b", m, regex("a*b")));
+ TEST(0, "b");
+ VERIFY(regex_search_debug("ab", m, regex("a*b")));
+ TEST(0, "ab");
+ VERIFY(!regex_search_debug("ac", m, regex("a*b")));
+ VERIFY(regex_search_debug("ab", m, regex("a+b")));
+ TEST(0, "ab");
+
+ // A quantified literal after the loop.
+ VERIFY(regex_search_debug("aaabbc", m, regex("a*b+")));
+ TEST(0, "aaabb");
+ VERIFY(regex_search_debug("aaabbbbc", m, regex("a*b{2,3}")));
+ TEST(0, "aaabbb");
+
+ // Captures between the loop and the literal.
+ VERIFY(regex_search_debug("caaab", m, regex("(a*)(b)")));
+ TEST(0, "aaab");
+ TEST(1, "aaa");
+ TEST(2, "b");
+ VERIFY(regex_search_debug("caaab", m, regex("((a*))(?:b)")));
+ TEST(0, "aaab");
+ TEST(1, "aaa");
+ TEST(2, "aaa");
+ // Captures made on the way to the literal are undone when it fails.
+ VERIFY(regex_search_debug("aaac", m, regex("(?:(a*)b|a*c)")));
+ TEST(0, "aaac");
+ VERIFY(!m[1].matched);
+
+ // The loop inside a repeated group.
+ VERIFY(regex_search_debug("abaabc", m, regex("(?:a*b)*c")));
+ TEST(0, "abaabc");
+ VERIFY(regex_search_debug("aabab!", m, regex("(a*b)+!")));
+ TEST(0, "aabab!");
+ TEST(1, "ab");
+
+ // The body accepts the literal, so shorter exits must be tried.
+ VERIFY(regex_search_debug("aaa", m, regex("(a*)a")));
+ TEST(0, "aaa");
+ TEST(1, "aa");
+ VERIFY(regex_search_debug("foo.bar.baz", m, regex("[\\w.]+\\.")));
+ TEST(0, "foo.bar.");
+ VERIFY(regex_search_debug("abc", m, regex("(\\w+)c")));
+ TEST(1, "ab");
+ VERIFY(regex_search_debug("aAb", m, regex("a*Ab", regex::icase)));
+ TEST(0, "aAb");
+ VERIFY(regex_search_debug("aaa", m, regex("a*.")));
+ TEST(0, "aaa");
+ VERIFY(regex_search_debug("aaa", m, regex("(a*)\\w")));
+ TEST(1, "aa");
+ VERIFY(regex_search_debug("aaa", m, regex("a*[a-c]")));
+ TEST(0, "aaa");
+ VERIFY(regex_search_debug("aaa", m, regex("a*[^A]")));
+ TEST(0, "aaa");
+ VERIFY(regex_search_debug("aaA!", m, regex("a*[A]!", regex::icase)));
+ TEST(0, "aaA!");
+ VERIFY(regex_search_debug("aaa", m, regex("a*a", regex::collate)));
+ TEST(0, "aaa");
+ VERIFY(regex_search_debug("aab", m, regex("a*b", regex::collate)));
+ TEST(0, "aab");
+
+ // The loop isn't followed directly by a literal.
+ VERIFY(regex_search_debug("aaab", m, regex("a*(?:b|a)")));
+ TEST(0, "aaab");
+ VERIFY(regex_search_debug("aaa", m, regex("a*$")));
+ TEST(0, "aaa");
+ VERIFY(regex_search_debug("aaa", m, regex("a*b?a")));
+ TEST(0, "aaa");
+ VERIFY(regex_search_debug("aaa", m, regex("a*b*a")));
+ TEST(0, "aaa");
+ VERIFY(regex_search_debug("aaa", m, regex("a*(?=a)a")));
+ TEST(0, "aaa");
+ VERIFY(regex_search_debug("aaa", m, regex("(a)a*\\1")));
+ TEST(0, "aaa");
+ VERIFY(regex_search_debug("abba", m, regex("(a)b*\\1")));
+ TEST(0, "abba");
+}
+
+void
+test02()
+{
+ // regex_match, POSIX, and wchar_t.
+ cmatch m;
+ VERIFY(regex_match_debug("aaab", m, regex("a*b")));
+ VERIFY(!regex_match_debug("aaabb", m, regex("a*b")));
+ VERIFY(regex_match_debug("aaab", m, regex("([^b]*)b", regex::extended)));
+ TEST(1, "aaa");
+ // In POSIX, . matches \n, so the shorter exits must be tried.
+ VERIFY(regex_search_debug("a\nb\nc", m, regex("(.*)\n", regex::extended)));
+ TEST(0, "a\nb\n");
+ TEST(1, "a\nb");
+
+ VERIFY(regex_search_debug("000x0012", m, regex("0*[1-9]", regex::extended)));
+ TEST(0, "001");
+
+ wcmatch wm;
+ VERIFY(regex_search_debug(L"x\"ab\"", wm, wregex(L"\"[^\"]*\"")));
+ VERIFY(wm[0].matched && wstring(wm[0].first, wm[0].second) == L"\"ab\"");
+ VERIFY(regex_search_debug(L"00x007", wm, wregex(L"0*[1-9]")));
+ VERIFY(wm[0].matched && wstring(wm[0].first, wm[0].second) == L"007");
+}
+
+void
+test03()
+{
+ // The loop's exit leads to a state that only succeeds at the end.
+ cmatch m;
+ VERIFY(regex_match_debug("abc", m, regex("(\\w+)")));
+ TEST(1, "abc");
+ VERIFY(!regex_match_debug("abc!", m, regex("\\w+")));
+ VERIFY(!regex_match_debug("abc1", m, regex("[a-z]*")));
+ VERIFY(regex_match_debug("aaa", m, regex("(a*)", regex::extended)));
+ TEST(1, "aaa");
+ VERIFY(!regex_match_debug("aab", m, regex("a*", regex::extended)));
+ VERIFY(regex_match_debug("aab", m, regex("(?=a*)a*b")));
+
+ // In regex_search, the accept state succeeds after the longest exit.
+ VERIFY(regex_search_debug("aab", m, regex("(a*)")));
+ TEST(1, "aa");
+ VERIFY(regex_search_debug("aab", m, regex("a*"),
+ regex_constants::match_not_null));
+ TEST(0, "aa");
+ VERIFY(regex_search_debug("aab", m, regex("(?=(a*))")));
+ TEST(1, "aa");
+ VERIFY(regex_search_debug("aab", m, regex("(a*|aab)", regex::extended)));
+ TEST(1, "aab");
+
+ VERIFY(regex_search_debug("a b ", m, regex("\\s+$")));
+ TEST(0, " ");
+ VERIFY(!regex_search_debug("a b", m, regex("\\s+$")));
+ VERIFY(regex_search_debug("x aa", m, regex("(a*)$")));
+ TEST(1, "aa");
+ VERIFY(regex_search_debug("aa", m, regex("a*$", regex::extended)));
+ TEST(0, "aa");
+ VERIFY(!regex_search_debug("aa", m, regex("a+$"),
+ regex_constants::match_not_eol));
+
+ // A multiline $ also succeeds before a line terminator.
+ VERIFY(regex_search_debug("a\nab", m,
+ regex("[^b]+$", regex::ECMAScript
+ | regex_constants::__multiline)));
+ TEST(0, "a");
+ VERIFY(regex_search_debug("ab\nc", m,
+ regex("[ab]+$", regex::ECMAScript
+ | regex_constants::__multiline)));
+ TEST(0, "ab");
+ VERIFY(regex_search_debug("a b \nc", m,
+ regex(" +$", regex::ECMAScript
+ | regex_constants::__multiline)));
+ TEST(0, " ");
+ VERIFY(m.position(0) == 4);
+ VERIFY(!regex_search_debug("a b", m,
+ regex(" +$", regex::ECMAScript
+ | regex_constants::__multiline)));
+ // But not if the literal body is a line terminator.
+ VERIFY(regex_search_debug("x\n\ny", m,
+ regex("\n+$", regex::ECMAScript
+ | regex_constants::__multiline)));
+ TEST(0, "\n");
+ VERIFY(m.position(0) == 1);
+}
+
+int
+main()
+{
+ test01();
+ test02();
+ test03();
+}
--
2.56.1