libstdc++
regex_executor.tcc
Go to the documentation of this file.
00001 // class template regex -*- C++ -*-
00002 
00003 // Copyright (C) 2013-2014 Free Software Foundation, Inc.
00004 //
00005 // This file is part of the GNU ISO C++ Library.  This library is free
00006 // software; you can redistribute it and/or modify it under the
00007 // terms of the GNU General Public License as published by the
00008 // Free Software Foundation; either version 3, or (at your option)
00009 // any later version.
00010 
00011 // This library is distributed in the hope that it will be useful,
00012 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00013 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014 // GNU General Public License for more details.
00015 
00016 // Under Section 7 of GPL version 3, you are granted additional
00017 // permissions described in the GCC Runtime Library Exception, version
00018 // 3.1, as published by the Free Software Foundation.
00019 
00020 // You should have received a copy of the GNU General Public License and
00021 // a copy of the GCC Runtime Library Exception along with this program;
00022 // see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
00023 // <http://www.gnu.org/licenses/>.
00024 
00025 /**
00026  *  @file bits/regex_executor.tcc
00027  *  This is an internal header file, included by other library headers.
00028  *  Do not attempt to use it directly. @headername{regex}
00029  */
00030 
00031 namespace std _GLIBCXX_VISIBILITY(default)
00032 {
00033 namespace __detail
00034 {
00035 _GLIBCXX_BEGIN_NAMESPACE_VERSION
00036 
00037   template<typename _BiIter, typename _Alloc, typename _TraitsT,
00038     bool __dfs_mode>
00039     bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
00040     _M_search()
00041     {
00042       if (_M_flags & regex_constants::match_continuous)
00043     return _M_search_from_first();
00044       auto __cur = _M_begin;
00045       do
00046     {
00047       _M_current = __cur;
00048       if (_M_main<false>())
00049         return true;
00050     }
00051       // Continue when __cur == _M_end
00052       while (__cur++ != _M_end);
00053       return false;
00054     }
00055 
00056   // This function operates in different modes, DFS mode or BFS mode, indicated
00057   // by template parameter __dfs_mode. See _M_main for details.
00058   //
00059   // ------------------------------------------------------------
00060   //
00061   // DFS mode:
00062   //
00063   // It applies a Depth-First-Search (aka backtracking) on given NFA and input
00064   // string.
00065   // At the very beginning the executor stands in the start state, then it tries
00066   // every possible state transition in current state recursively. Some state
00067   // transitions consume input string, say, a single-char-matcher or a
00068   // back-reference matcher; some don't, like assertion or other anchor nodes.
00069   // When the input is exhausted and/or the current state is an accepting state,
00070   // the whole executor returns true.
00071   //
00072   // TODO: This approach is exponentially slow for certain input.
00073   //       Try to compile the NFA to a DFA.
00074   //
00075   // Time complexity: \Omega(match_length), O(2^(_M_nfa.size()))
00076   // Space complexity: \theta(match_results.size() + match_length)
00077   //
00078   // ------------------------------------------------------------
00079   //
00080   // BFS mode:
00081   //
00082   // Russ Cox's article (http://swtch.com/~rsc/regexp/regexp1.html)
00083   // explained this algorithm clearly.
00084   //
00085   // It first computes epsilon closure (states that can be achieved without
00086   // consuming characters) for every state that's still matching,
00087   // using the same DFS algorithm, but doesn't re-enter states (find a true in
00088   // _M_visited), nor follows _S_opcode_match.
00089   //
00090   // Then apply DFS using every _S_opcode_match (in _M_match_queue) as the start
00091   // state.
00092   //
00093   // It significantly reduces potential duplicate states, so has a better
00094   // upper bound; but it requires more overhead.
00095   //
00096   // Time complexity: \Omega(match_length * match_results.size())
00097   //                  O(match_length * _M_nfa.size() * match_results.size())
00098   // Space complexity: \Omega(_M_nfa.size() + match_results.size())
00099   //                   O(_M_nfa.size() * match_results.size())
00100   template<typename _BiIter, typename _Alloc, typename _TraitsT,
00101     bool __dfs_mode>
00102   template<bool __match_mode>
00103     bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
00104     _M_main()
00105     {
00106       if (__dfs_mode)
00107     {
00108       _M_has_sol = false;
00109       _M_cur_results = _M_results;
00110       _M_dfs<__match_mode>(_M_start_state);
00111       return _M_has_sol;
00112     }
00113       else
00114     {
00115       _M_match_queue->push_back(make_pair(_M_start_state, _M_results));
00116       bool __ret = false;
00117       while (1)
00118         {
00119           _M_has_sol = false;
00120           if (_M_match_queue->empty())
00121         break;
00122           _M_visited->assign(_M_visited->size(), false);
00123           auto __old_queue = std::move(*_M_match_queue);
00124           for (auto& __task : __old_queue)
00125         {
00126           _M_cur_results = std::move(__task.second);
00127           _M_dfs<__match_mode>(__task.first);
00128         }
00129           if (!__match_mode)
00130         __ret |= _M_has_sol;
00131           if (_M_current == _M_end)
00132         break;
00133           ++_M_current;
00134         }
00135       if (__match_mode)
00136         __ret = _M_has_sol;
00137       return __ret;
00138     }
00139     }
00140 
00141   // Return whether now match the given sub-NFA.
00142   template<typename _BiIter, typename _Alloc, typename _TraitsT,
00143     bool __dfs_mode>
00144     bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
00145     _M_lookahead(_State<_TraitsT> __state)
00146     {
00147       // Backreferences may refer to captured content.
00148       // We may want to make this faster by not copying,
00149       // but let's not be clever prematurely.
00150       _ResultsVec __what(_M_cur_results);
00151       auto __sub = std::unique_ptr<_Executor>(new _Executor(_M_current,
00152                                 _M_end,
00153                                 __what,
00154                                 _M_re,
00155                                 _M_flags));
00156       __sub->_M_start_state = __state._M_alt;
00157       if (__sub->_M_search_from_first())
00158     {
00159       for (size_t __i = 0; __i < __what.size(); __i++)
00160         if (__what[__i].matched)
00161           _M_cur_results[__i] = __what[__i];
00162       return true;
00163     }
00164       return false;
00165     }
00166 
00167   // TODO: Use a function vector to dispatch, instead of using switch-case.
00168   template<typename _BiIter, typename _Alloc, typename _TraitsT,
00169     bool __dfs_mode>
00170   template<bool __match_mode>
00171     void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
00172     _M_dfs(_StateIdT __i)
00173     {
00174       if (!__dfs_mode)
00175     {
00176       if ((*_M_visited)[__i])
00177         return;
00178       (*_M_visited)[__i] = true;
00179     }
00180 
00181       const auto& __state = _M_nfa[__i];
00182       // Every change on _M_cur_results and _M_current will be rolled back after
00183       // finishing the recursion step.
00184       switch (__state._M_opcode)
00185     {
00186     // _M_alt branch is "match once more", while _M_next is "get me out
00187     // of this quantifier". Executing _M_next first or _M_alt first don't
00188     // mean the same thing, and we need to choose the correct order under
00189     // given greedy mode.
00190     case _S_opcode_alternative:
00191       // Greedy.
00192       if (!__state._M_neg)
00193         {
00194           // "Once more" is preferred in greedy mode.
00195           _M_dfs<__match_mode>(__state._M_alt);
00196           // If it's DFS executor and already accepted, we're done.
00197           if (!__dfs_mode || !_M_has_sol)
00198         _M_dfs<__match_mode>(__state._M_next);
00199         }
00200       else // Non-greedy mode
00201         {
00202           if (__dfs_mode)
00203         {
00204           // vice-versa.
00205           _M_dfs<__match_mode>(__state._M_next);
00206           if (!_M_has_sol)
00207             _M_dfs<__match_mode>(__state._M_alt);
00208         }
00209           else
00210         {
00211           // DON'T attempt anything, because there's already another
00212           // state with higher priority accepted. This state cannot be
00213           // better by attempting its next node.
00214           if (!_M_has_sol)
00215             {
00216               _M_dfs<__match_mode>(__state._M_next);
00217               // DON'T attempt anything if it's already accepted. An
00218               // accepted state *must* be better than a solution that
00219               // matches a non-greedy quantifier one more time.
00220               if (!_M_has_sol)
00221             _M_dfs<__match_mode>(__state._M_alt);
00222             }
00223         }
00224         }
00225       break;
00226     case _S_opcode_subexpr_begin:
00227       // If there's nothing changed since last visit, do NOT continue.
00228       // This prevents the executor from get into infinite loop when using
00229       // "()*" to match "".
00230       if (!_M_cur_results[__state._M_subexpr].matched
00231           || _M_cur_results[__state._M_subexpr].first != _M_current)
00232         {
00233           auto& __res = _M_cur_results[__state._M_subexpr];
00234           auto __back = __res.first;
00235           __res.first = _M_current;
00236           _M_dfs<__match_mode>(__state._M_next);
00237           __res.first = __back;
00238         }
00239       break;
00240     case _S_opcode_subexpr_end:
00241       if (_M_cur_results[__state._M_subexpr].second != _M_current
00242           || _M_cur_results[__state._M_subexpr].matched != true)
00243         {
00244           auto& __res = _M_cur_results[__state._M_subexpr];
00245           auto __back = __res;
00246           __res.second = _M_current;
00247           __res.matched = true;
00248           _M_dfs<__match_mode>(__state._M_next);
00249           __res = __back;
00250         }
00251       else
00252         _M_dfs<__match_mode>(__state._M_next);
00253       break;
00254     case _S_opcode_line_begin_assertion:
00255       if (_M_at_begin())
00256         _M_dfs<__match_mode>(__state._M_next);
00257       break;
00258     case _S_opcode_line_end_assertion:
00259       if (_M_at_end())
00260         _M_dfs<__match_mode>(__state._M_next);
00261       break;
00262     case _S_opcode_word_boundary:
00263       if (_M_word_boundary(__state) == !__state._M_neg)
00264         _M_dfs<__match_mode>(__state._M_next);
00265       break;
00266     // Here __state._M_alt offers a single start node for a sub-NFA.
00267     // We recursively invoke our algorithm to match the sub-NFA.
00268     case _S_opcode_subexpr_lookahead:
00269       if (_M_lookahead(__state) == !__state._M_neg)
00270         _M_dfs<__match_mode>(__state._M_next);
00271       break;
00272     case _S_opcode_match:
00273       if (_M_current == _M_end)
00274         break;
00275       if (__dfs_mode)
00276         {
00277           if (__state._M_matches(*_M_current))
00278         {
00279           ++_M_current;
00280           _M_dfs<__match_mode>(__state._M_next);
00281           --_M_current;
00282         }
00283         }
00284       else
00285         if (__state._M_matches(*_M_current))
00286           _M_match_queue->push_back(make_pair(__state._M_next,
00287                           _M_cur_results));
00288       break;
00289     // First fetch the matched result from _M_cur_results as __submatch;
00290     // then compare it with
00291     // (_M_current, _M_current + (__submatch.second - __submatch.first)).
00292     // If matched, keep going; else just return and try another state.
00293     case _S_opcode_backref:
00294       {
00295         _GLIBCXX_DEBUG_ASSERT(__dfs_mode);
00296         auto& __submatch = _M_cur_results[__state._M_backref_index];
00297         if (!__submatch.matched)
00298           break;
00299         auto __last = _M_current;
00300         for (auto __tmp = __submatch.first;
00301          __last != _M_end && __tmp != __submatch.second;
00302          ++__tmp)
00303           ++__last;
00304         if (_M_re._M_traits.transform(__submatch.first,
00305                         __submatch.second)
00306         == _M_re._M_traits.transform(_M_current, __last))
00307           {
00308         if (__last != _M_current)
00309           {
00310             auto __backup = _M_current;
00311             _M_current = __last;
00312             _M_dfs<__match_mode>(__state._M_next);
00313             _M_current = __backup;
00314           }
00315         else
00316           _M_dfs<__match_mode>(__state._M_next);
00317           }
00318       }
00319       break;
00320     case _S_opcode_accept:
00321       if (__dfs_mode)
00322         {
00323           _GLIBCXX_DEBUG_ASSERT(!_M_has_sol);
00324           if (__match_mode)
00325         _M_has_sol = _M_current == _M_end;
00326           else
00327         _M_has_sol = true;
00328           if (_M_current == _M_begin
00329           && (_M_flags & regex_constants::match_not_null))
00330         _M_has_sol = false;
00331           if (_M_has_sol)
00332         _M_results = _M_cur_results;
00333         }
00334       else
00335         {
00336           if (_M_current == _M_begin
00337           && (_M_flags & regex_constants::match_not_null))
00338         break;
00339           if (!__match_mode || _M_current == _M_end)
00340         if (!_M_has_sol)
00341           {
00342             _M_has_sol = true;
00343             _M_results = _M_cur_results;
00344           }
00345         }
00346       break;
00347     default:
00348       _GLIBCXX_DEBUG_ASSERT(false);
00349     }
00350     }
00351 
00352   // Return whether now is at some word boundary.
00353   template<typename _BiIter, typename _Alloc, typename _TraitsT,
00354     bool __dfs_mode>
00355     bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
00356     _M_word_boundary(_State<_TraitsT> __state) const
00357     {
00358       bool __left_is_word = false;
00359       if (_M_current != _M_begin
00360       || (_M_flags & regex_constants::match_prev_avail))
00361     {
00362       auto __prev = _M_current;
00363       if (_M_is_word(*std::prev(__prev)))
00364         __left_is_word = true;
00365     }
00366       bool __right_is_word =
00367     _M_current != _M_end && _M_is_word(*_M_current);
00368 
00369       if (__left_is_word == __right_is_word)
00370     return false;
00371       if (__left_is_word && !(_M_flags & regex_constants::match_not_eow))
00372     return true;
00373       if (__right_is_word && !(_M_flags & regex_constants::match_not_bow))
00374     return true;
00375       return false;
00376     }
00377 
00378 _GLIBCXX_END_NAMESPACE_VERSION
00379 } // namespace __detail
00380 } // namespace