In [\w.+-]+@, backtracking over the run cannot uncover an @: every
character given back was accepted by the loop body, which rejects @.
Yet DFS retries each shorter exit, at each candidate start position.

After a non-empty run, look past capture boundaries and dummy states.
If the next matcher and the body are disjoint, omit the backtracking
frames.  When either matcher is an untranslated literal, testing that
literal against the other matcher proves whether they overlap.

Two other exits need no backtracking: $ if it cannot succeed inside the
run, and the accept state.  At accept, a shorter exit is before the end
of the input in exact mode; in prefix mode the longest exit already
succeeds.  Otherwise keep the usual greedy order.  Cache the decision
in the repeat count that the single-character loop doesn't use.

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.

 * Selected individual patterns (best of 5-7 runs, two rounds; per-line
   timings use the same input file):

                                            before    after
      search 0*[1-9], 100K runs of 8 zeros   ~31 ms    ~13 ms
      same, wchar_t                         ~108 ms    ~37 ms
      search \s+$ per line                   ~81 ms    ~68 ms
      match [\w ]+ per line                  ~17 ms    ~11 ms

   On 20000 consecutive x characters, searching for x+y fell from
   about 1085 ms to 46 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  |  73 +++++-
 .../regex_search/ecma/greedy_loop_literal.cc  | 217 ++++++++++++++++++
 3 files changed, 287 insertions(+), 6 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 bbe68c4798c..aa17d2ca337 100644
--- a/libstdc++-v3/include/bits/regex_executor.h
+++ b/libstdc++-v3/include/bits/regex_executor.h
@@ -137,6 +137,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 a179fddbf53..f68a48ced3d 100644
--- a/libstdc++-v3/include/bits/regex_executor.tcc
+++ b/libstdc++-v3/include/bits/regex_executor.tcc
@@ -492,8 +492,8 @@ namespace __detail
     };
 
   // For a greedy repeat -> match -> repeat, try the longest run first.
-  // Two frames record all remaining exits: the lower frame holds the start
-  // of the run and the upper frame walks back one character at a time.
+  // If shorter exits might be needed, two frames record them: the lower
+  // frame holds the start of the run and the upper walks back towards it.
   //
   // The body cannot return to __i without consuming a character.  Any
   // cycle that re-enters __i without consuming input must take the exit
@@ -509,15 +509,76 @@ 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));
+         // Reuse the spare count: 0 = unknown, 1 = skip, -1 = keep.
+         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;
     }
 
+  // The run is non-empty.  At each shorter exit the next character is one
+  // the body accepted.  Return true if none of those exits can improve
+  // on the longest, skipping capture boundaries and dummy states.
+  template<typename _BiIter, typename _Alloc, typename _TraitsT>
+    bool _Executor<_BiIter, _Alloc, _TraitsT>::
+    _M_skip_shorter_exits(const _State<_CharT>& __rep) const
+    {
+      // With neither icase nor collate, a literal 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 either matcher is a literal, one test tells us whether
+               // they overlap, e.g. the 0 and [1-9] in 0*[1-9].
+               if (const auto* __lit
+                     = __state._M_get_matcher().template 
_M_fast_target<_CharM>())
+                 return !__body._M_matches(__lit->_M_ch);
+               if (const auto* __lit
+                     = __body._M_get_matcher().template 
_M_fast_target<_CharM>())
+                 return !__state._M_matches(__lit->_M_ch);
+               return false;
+             }
+           case _S_opcode_line_end_assertion:
+             // No shorter exit is at _M_end.  In multiline mode also
+             // rule out an exit just before a line terminator.
+             if (!_M_match_multiline())
+               return true;
+             if (const auto* __lit
+                   = __body._M_get_matcher().template _M_fast_target<_CharM>())
+               return !_M_is_line_terminator(__lit->_M_ch);
+             return false;
+           case _S_opcode_accept:
+             // Exact matches require _M_end.  Prefix matches already
+             // succeed at the longest exit, even with match_not_null.
+             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..e64b0775ef4
--- /dev/null
+++ 
b/libstdc++-v3/testsuite/28_regex/algorithms/regex_search/ecma/greedy_loop_literal.cc
@@ -0,0 +1,217 @@
+// { dg-do run { target c++11 } }
+
+// Check greedy single-character loops followed by a matcher, $, or the
+// end of the pattern, including cases where backtracking is required.
+
+#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)));
+  // Here the body consumes a newline, so $ needs a shorter exit.
+  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


Reply via email to