libstdc++
regex_executor.tcc
Go to the documentation of this file.
1 // class template regex -*- C++ -*-
2 
3 // Copyright (C) 2013-2025 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
9 // any later version.
10 
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15 
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
19 
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
24 
25 /**
26  * @file bits/regex_executor.tcc
27  * This is an internal header file, included by other library headers.
28  * Do not attempt to use it directly. @headername{regex}
29  */
30 
31 namespace std _GLIBCXX_VISIBILITY(default)
32 {
33 _GLIBCXX_BEGIN_NAMESPACE_VERSION
34 
35 #pragma GCC diagnostic push
36 #pragma GCC diagnostic ignored "-Wc++17-extensions" // if constexpr
37 namespace __detail
38 {
39  template<typename _BiIter, typename _Alloc, typename _TraitsT,
40  bool __dfs_mode>
41  bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
42  _M_search()
43  {
44  if (_M_search_from_first())
45  return true;
46  if (_M_flags & regex_constants::match_continuous)
47  return false;
49  while (_M_begin != _M_end)
50  {
51  ++_M_begin;
52  if (_M_search_from_first())
53  return true;
54  }
55  return false;
56  }
57 
58  // The _M_main function operates in different modes, DFS mode or BFS mode,
59  // indicated by template parameter __dfs_mode, and dispatches to one of the
60  // _M_main_dispatch overloads.
61  //
62  // ------------------------------------------------------------
63  //
64  // DFS mode:
65  //
66  // It applies a Depth-First-Search (aka backtracking) on given NFA and input
67  // string.
68  // At the very beginning the executor stands in the start state, then it
69  // tries every possible state transition in current state recursively. Some
70  // state transitions consume input string, say, a single-char-matcher or a
71  // back-reference matcher; some don't, like assertion or other anchor nodes.
72  // When the input is exhausted and/or the current state is an accepting
73  // state, the whole executor returns true.
74  //
75  // TODO: This approach is exponentially slow for certain input.
76  // Try to compile the NFA to a DFA.
77  //
78  // Time complexity: \Omega(match_length), O(2^(_M_nfa.size()))
79  // Space complexity: \theta(match_results.size() + match_length)
80  //
81  template<typename _BiIter, typename _Alloc, typename _TraitsT,
82  bool __dfs_mode>
83  bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
84  _M_main_dispatch(_Match_mode __match_mode, __dfs)
85  {
86  _M_has_sol = false;
87  *_M_states._M_get_sol_pos() = _BiIter();
88  _M_cur_results = _M_results;
89  _M_dfs(__match_mode, _M_states._M_start);
90  return _M_has_sol;
91  }
92 
93  // ------------------------------------------------------------
94  //
95  // BFS mode:
96  //
97  // Russ Cox's article (http://swtch.com/~rsc/regexp/regexp1.html)
98  // explained this algorithm clearly.
99  //
100  // It first computes epsilon closure (states that can be achieved without
101  // consuming characters) for every state that's still matching,
102  // using the same DFS algorithm, but doesn't re-enter states (using
103  // _M_states._M_visited to check), nor follow _S_opcode_match.
104  //
105  // Then apply DFS using every _S_opcode_match (in _M_states._M_match_queue)
106  // as the start state.
107  //
108  // It significantly reduces potential duplicate states, so has a better
109  // upper bound; but it requires more overhead.
110  //
111  // Time complexity: \Omega(match_length * match_results.size())
112  // O(match_length * _M_nfa.size() * match_results.size())
113  // Space complexity: \Omega(_M_nfa.size() + match_results.size())
114  // O(_M_nfa.size() * match_results.size())
115  template<typename _BiIter, typename _Alloc, typename _TraitsT,
116  bool __dfs_mode>
117  bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
118  _M_main_dispatch(_Match_mode __match_mode, __bfs)
119  {
120  _M_states._M_queue(_M_states._M_start, _M_results);
121  bool __ret = false;
122  while (1)
123  {
124  _M_has_sol = false;
125  if (_M_states._M_match_queue.empty())
126  break;
127  std::fill_n(_M_states._M_visited_states, _M_nfa.size(), false);
128  auto __old_queue = std::move(_M_states._M_match_queue);
129  auto __alloc = _M_cur_results.get_allocator();
130  for (auto& __task : __old_queue)
131  {
132  _M_cur_results = _ResultsVec(std::move(__task.second), __alloc);
133  _M_dfs(__match_mode, __task.first);
134  }
135  if (__match_mode == _Match_mode::_Prefix)
136  __ret |= _M_has_sol;
137  if (_M_current == _M_end)
138  break;
139  ++_M_current;
140  }
141  if (__match_mode == _Match_mode::_Exact)
142  __ret = _M_has_sol;
143  _M_states._M_match_queue.clear();
144  return __ret;
145  }
146 
147  // Return whether now match the given sub-NFA.
148  template<typename _BiIter, typename _Alloc, typename _TraitsT,
149  bool __dfs_mode>
150  bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
151  _M_lookahead(_StateIdT __next)
152  {
153  // Backreferences may refer to captured content.
154  // We may want to make this faster by not copying,
155  // but let's not be clever prematurely.
156  _ResultsVec __what(_M_cur_results);
157  _Executor __sub(_M_current, _M_end, __what, _M_re, _M_flags);
158  __sub._M_states._M_start = __next;
159  if (__sub._M_search_from_first())
160  {
161  for (size_t __i = 0; __i < __what.size(); __i++)
162  if (__what[__i].matched)
163  _M_cur_results[__i] = __what[__i];
164  return true;
165  }
166  return false;
167  }
168 
169  // __rep_count records how many times (__rep_count.second)
170  // this node is visited under certain input iterator
171  // (__rep_count.first). This prevent the executor from entering
172  // infinite loop by refusing to continue when it's already been
173  // visited more than twice. It's `twice` instead of `once` because
174  // we need to spare one more time for potential group capture.
175  template<typename _BiIter, typename _Alloc, typename _TraitsT,
176  bool __dfs_mode>
177  void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
178  _M_rep_once_more(_Match_mode __match_mode, _StateIdT __i)
179  {
180  const auto& __state = _M_nfa[__i];
181  auto& __rep_count = _M_rep_count[__i];
182  if (__rep_count.second == 0 || __rep_count.first != _M_current)
183  {
184  auto __back = __rep_count;
185  __rep_count.first = _M_current;
186  __rep_count.second = 1;
187  _M_dfs(__match_mode, __state._M_alt);
188  __rep_count = __back;
189  }
190  else
191  {
192  if (__rep_count.second < 2)
193  {
194  __rep_count.second++;
195  _M_dfs(__match_mode, __state._M_alt);
196  __rep_count.second--;
197  }
198  }
199  }
200 
201  // _M_alt branch is "match once more", while _M_next is "get me out
202  // of this quantifier". Executing _M_next first or _M_alt first don't
203  // mean the same thing, and we need to choose the correct order under
204  // given greedy mode.
205  template<typename _BiIter, typename _Alloc, typename _TraitsT,
206  bool __dfs_mode>
207  void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
208  _M_handle_repeat(_Match_mode __match_mode, _StateIdT __i)
209  {
210  const auto& __state = _M_nfa[__i];
211 
212  // Greedy.
213  if (!__state._M_neg)
214  {
215  _M_rep_once_more(__match_mode, __i);
216  // If it's DFS executor and already accepted, we're done.
217  if (!__dfs_mode || !_M_has_sol)
218  _M_dfs(__match_mode, __state._M_next);
219  }
220  else // Non-greedy mode
221  {
222  if constexpr (__dfs_mode)
223  {
224  // vice-versa.
225  _M_dfs(__match_mode, __state._M_next);
226  if (!_M_has_sol)
227  _M_rep_once_more(__match_mode, __i);
228  }
229  else
230  {
231  // DON'T attempt anything, because there's already another
232  // state with higher priority accepted. This state cannot
233  // be better by attempting its next node.
234  if (!_M_has_sol)
235  {
236  _M_dfs(__match_mode, __state._M_next);
237  // DON'T attempt anything if it's already accepted. An
238  // accepted state *must* be better than a solution that
239  // matches a non-greedy quantifier one more time.
240  if (!_M_has_sol)
241  _M_rep_once_more(__match_mode, __i);
242  }
243  }
244  }
245  }
246 
247  template<typename _BiIter, typename _Alloc, typename _TraitsT,
248  bool __dfs_mode>
249  void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
250  _M_handle_subexpr_begin(_Match_mode __match_mode, _StateIdT __i)
251  {
252  const auto& __state = _M_nfa[__i];
253 
254  auto& __res = _M_cur_results[__state._M_subexpr];
255  auto __back = __res.first;
256  __res.first = _M_current;
257  _M_dfs(__match_mode, __state._M_next);
258  __res.first = __back;
259  }
260 
261  template<typename _BiIter, typename _Alloc, typename _TraitsT,
262  bool __dfs_mode>
263  void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
264  _M_handle_subexpr_end(_Match_mode __match_mode, _StateIdT __i)
265  {
266  const auto& __state = _M_nfa[__i];
267 
268  auto& __res = _M_cur_results[__state._M_subexpr];
269  auto __back = __res;
270  __res.second = _M_current;
271  __res.matched = true;
272  _M_dfs(__match_mode, __state._M_next);
273  __res = __back;
274  }
275 
276  template<typename _BiIter, typename _Alloc, typename _TraitsT,
277  bool __dfs_mode>
278  inline void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
279  _M_handle_line_begin_assertion(_Match_mode __match_mode, _StateIdT __i)
280  {
281  const auto& __state = _M_nfa[__i];
282  if (_M_at_begin())
283  _M_dfs(__match_mode, __state._M_next);
284  }
285 
286  template<typename _BiIter, typename _Alloc, typename _TraitsT,
287  bool __dfs_mode>
288  inline void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
289  _M_handle_line_end_assertion(_Match_mode __match_mode, _StateIdT __i)
290  {
291  const auto& __state = _M_nfa[__i];
292  if (_M_at_end())
293  _M_dfs(__match_mode, __state._M_next);
294  }
295 
296  template<typename _BiIter, typename _Alloc, typename _TraitsT,
297  bool __dfs_mode>
298  inline void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
299  _M_handle_word_boundary(_Match_mode __match_mode, _StateIdT __i)
300  {
301  const auto& __state = _M_nfa[__i];
302  if (_M_word_boundary() == !__state._M_neg)
303  _M_dfs(__match_mode, __state._M_next);
304  }
305 
306  // Here __state._M_alt offers a single start node for a sub-NFA.
307  // We recursively invoke our algorithm to match the sub-NFA.
308  template<typename _BiIter, typename _Alloc, typename _TraitsT,
309  bool __dfs_mode>
310  void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
311  _M_handle_subexpr_lookahead(_Match_mode __match_mode, _StateIdT __i)
312  {
313  const auto& __state = _M_nfa[__i];
314  if (_M_lookahead(__state._M_alt) == !__state._M_neg)
315  _M_dfs(__match_mode, __state._M_next);
316  }
317 
318  template<typename _BiIter, typename _Alloc, typename _TraitsT,
319  bool __dfs_mode>
320  void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
321  _M_handle_match(_Match_mode __match_mode, _StateIdT __i)
322  {
323  const auto& __state = _M_nfa[__i];
324 
325  if (_M_current == _M_end)
326  return;
327  if constexpr (__dfs_mode)
328  {
329  if (__state._M_matches(*_M_current))
330  {
331  ++_M_current;
332  _M_dfs(__match_mode, __state._M_next);
333  --_M_current;
334  }
335  }
336  else
337  if (__state._M_matches(*_M_current))
338  _M_states._M_queue(__state._M_next, _M_cur_results);
339  }
340 
341  template<typename _BiIter, typename _TraitsT>
342  struct _Backref_matcher
343  {
344  _Backref_matcher(bool /* __icase */, const _TraitsT& __traits)
345  : _M_traits(__traits) { }
346 
347  bool
348  _M_apply(_BiIter __expected_begin,
349  _BiIter __expected_end, _BiIter __actual_begin,
350  _BiIter __actual_end)
351  {
352  return _M_traits.transform(__expected_begin, __expected_end)
353  == _M_traits.transform(__actual_begin, __actual_end);
354  }
355 
356  const _TraitsT& _M_traits;
357  };
358 
359  template<typename _BiIter, typename _CharT>
360  struct _Backref_matcher<_BiIter, std::regex_traits<_CharT>>
361  {
362  using _TraitsT = std::regex_traits<_CharT>;
363  _Backref_matcher(bool __icase, const _TraitsT& __traits)
364  : _M_icase(__icase), _M_traits(__traits) { }
365 
366  bool
367  _M_apply(_BiIter __expected_begin,
368  _BiIter __expected_end, _BiIter __actual_begin,
369  _BiIter __actual_end)
370  {
371  if (!_M_icase)
372  return _GLIBCXX_STD_A::__equal4(__expected_begin, __expected_end,
373  __actual_begin, __actual_end);
374  typedef std::ctype<_CharT> __ctype_type;
375  const auto& __fctyp = use_facet<__ctype_type>(_M_traits.getloc());
376  return _GLIBCXX_STD_A::__equal4(__expected_begin, __expected_end,
377  __actual_begin, __actual_end,
378  [this, &__fctyp](_CharT __lhs, _CharT __rhs)
379  {
380  return __fctyp.tolower(__lhs)
381  == __fctyp.tolower(__rhs);
382  });
383  }
384 
385  bool _M_icase;
386  const _TraitsT& _M_traits;
387  };
388 
389  // First fetch the matched result from _M_cur_results as __submatch;
390  // then compare it with
391  // (_M_current, _M_current + (__submatch.second - __submatch.first)).
392  // If matched, keep going; else just return and try another state.
393  template<typename _BiIter, typename _Alloc, typename _TraitsT,
394  bool __dfs_mode>
395  void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
396  _M_handle_backref(_Match_mode __match_mode, _StateIdT __i)
397  {
398  static_assert(__dfs_mode, "this should never be instantiated");
399 
400  const auto& __state = _M_nfa[__i];
401  auto& __submatch = _M_cur_results[__state._M_backref_index];
402  if (!__submatch.matched)
403  return;
404  auto __last = _M_current;
405  for (auto __tmp = __submatch.first;
406  __last != _M_end && __tmp != __submatch.second;
407  ++__tmp)
408  ++__last;
409  if (_Backref_matcher<_BiIter, _TraitsT>(
410  _M_re.flags() & regex_constants::icase,
411  _M_re._M_automaton->_M_traits)._M_apply(
412  __submatch.first, __submatch.second, _M_current, __last))
413  {
414  if (__last != _M_current)
415  {
416  auto __backup = _M_current;
417  _M_current = __last;
418  _M_dfs(__match_mode, __state._M_next);
419  _M_current = __backup;
420  }
421  else
422  _M_dfs(__match_mode, __state._M_next);
423  }
424  }
425 
426  template<typename _BiIter, typename _Alloc, typename _TraitsT,
427  bool __dfs_mode>
428  void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
429  _M_handle_accept(_Match_mode __match_mode, _StateIdT)
430  {
431  if constexpr (__dfs_mode)
432  {
433  __glibcxx_assert(!_M_has_sol);
434  if (__match_mode == _Match_mode::_Exact)
435  _M_has_sol = _M_current == _M_end;
436  else
437  _M_has_sol = true;
438  if (_M_current == _M_begin
439  && (_M_flags & regex_constants::match_not_null))
440  _M_has_sol = false;
441  if (_M_has_sol)
442  {
443  if (_M_nfa._M_flags & regex_constants::ECMAScript)
444  _M_results = _M_cur_results;
445  else // POSIX
446  {
447  __glibcxx_assert(_M_states._M_get_sol_pos());
448  // Here's POSIX's logic: match the longest one. However
449  // we never know which one (lhs or rhs of "|") is longer
450  // unless we try both of them and compare the results.
451  // The member variable _M_sol_pos records the end
452  // position of the last successful match. It's better
453  // to be larger, because POSIX regex is always greedy.
454  // TODO: This could be slow.
455  if (*_M_states._M_get_sol_pos() == _BiIter()
456  || std::distance(_M_begin,
457  *_M_states._M_get_sol_pos())
458  < std::distance(_M_begin, _M_current))
459  {
460  *_M_states._M_get_sol_pos() = _M_current;
461  _M_results = _M_cur_results;
462  }
463  }
464  }
465  }
466  else
467  {
468  if (_M_current == _M_begin
469  && (_M_flags & regex_constants::match_not_null))
470  return;
471  if (__match_mode == _Match_mode::_Prefix || _M_current == _M_end)
472  if (!_M_has_sol)
473  {
474  _M_has_sol = true;
475  _M_results = _M_cur_results;
476  }
477  }
478  }
479 
480  template<typename _BiIter, typename _Alloc, typename _TraitsT,
481  bool __dfs_mode>
482  void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
483  _M_handle_alternative(_Match_mode __match_mode, _StateIdT __i)
484  {
485  const auto& __state = _M_nfa[__i];
486 
487  if (_M_nfa._M_flags & regex_constants::ECMAScript)
488  {
489  // TODO: Fix BFS support. It is wrong.
490  _M_dfs(__match_mode, __state._M_alt);
491  // Pick lhs if it matches. Only try rhs if it doesn't.
492  if (!_M_has_sol)
493  _M_dfs(__match_mode, __state._M_next);
494  }
495  else
496  {
497  // Try both and compare the result.
498  // See "case _S_opcode_accept:" handling above.
499  _M_dfs(__match_mode, __state._M_alt);
500  auto __has_sol = _M_has_sol;
501  _M_has_sol = false;
502  _M_dfs(__match_mode, __state._M_next);
503  _M_has_sol |= __has_sol;
504  }
505  }
506 
507  template<typename _BiIter, typename _Alloc, typename _TraitsT,
508  bool __dfs_mode>
509  void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
510  _M_dfs(_Match_mode __match_mode, _StateIdT __i)
511  {
512  if (_M_states._M_visited(__i))
513  return;
514 
515  switch (_M_nfa[__i]._M_opcode())
516  {
517  case _S_opcode_repeat:
518  _M_handle_repeat(__match_mode, __i); break;
519  case _S_opcode_subexpr_begin:
520  _M_handle_subexpr_begin(__match_mode, __i); break;
521  case _S_opcode_subexpr_end:
522  _M_handle_subexpr_end(__match_mode, __i); break;
523  case _S_opcode_line_begin_assertion:
524  _M_handle_line_begin_assertion(__match_mode, __i); break;
525  case _S_opcode_line_end_assertion:
526  _M_handle_line_end_assertion(__match_mode, __i); break;
527  case _S_opcode_word_boundary:
528  _M_handle_word_boundary(__match_mode, __i); break;
529  case _S_opcode_subexpr_lookahead:
530  _M_handle_subexpr_lookahead(__match_mode, __i); break;
531  case _S_opcode_match:
532  _M_handle_match(__match_mode, __i); break;
533  case _S_opcode_backref:
534  if constexpr (__dfs_mode)
535  _M_handle_backref(__match_mode, __i);
536  else
537  __builtin_unreachable();
538  break;
539  case _S_opcode_accept:
540  _M_handle_accept(__match_mode, __i); break;
541  case _S_opcode_alternative:
542  _M_handle_alternative(__match_mode, __i); break;
543  default:
544  __glibcxx_assert(false);
545  }
546  }
547 
548  // Return whether now is at some word boundary.
549  template<typename _BiIter, typename _Alloc, typename _TraitsT,
550  bool __dfs_mode>
551  bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
552  _M_word_boundary() const
553  {
554  if (_M_current == _M_begin && (_M_flags & regex_constants::match_not_bow))
555  return false;
556  if (_M_current == _M_end && (_M_flags & regex_constants::match_not_eow))
557  return false;
558 
559  bool __left_is_word = false;
560  if (_M_current != _M_begin
561  || (_M_flags & regex_constants::match_prev_avail))
562  {
563  auto __prev = _M_current;
564  if (_M_is_word(*std::prev(__prev)))
565  __left_is_word = true;
566  }
567  bool __right_is_word =
568  _M_current != _M_end && _M_is_word(*_M_current);
569 
570  return __left_is_word != __right_is_word;
571  }
572 } // namespace __detail
573 #pragma GCC diagnostic pop
574 
575 _GLIBCXX_END_NAMESPACE_VERSION
576 } // namespace
constexpr match_flag_type match_continuous
constexpr match_flag_type match_prev_avail
Definition: simd.h:306
Describes aspects of a regular expression.
Definition: regex.h:99
constexpr match_flag_type match_not_bow
Primary class template ctype facet.This template class defines classification and conversion function...
constexpr _OI fill_n(_OI __first, _Size __n, const _Tp &__value)
Fills the range [first,first+n) with copies of value.
constexpr syntax_option_type ECMAScript
constexpr match_flag_type match_not_eow
constexpr syntax_option_type icase
ISO C++ entities toplevel namespace is std.
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition: move.h:138
constexpr match_flag_type match_not_null
constexpr iterator_traits< _InputIterator >::difference_type distance(_InputIterator __first, _InputIterator __last)
A generalization of pointer arithmetic.