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       _ResultsVec __what(_M_cur_results.size());
00148       auto __sub = std::unique_ptr<_Executor>(new _Executor(_M_current,
00149                                 _M_end,
00150                                 __what,
00151                                 _M_re,
00152                                 _M_flags));
00153       __sub->_M_start_state = __state._M_alt;
00154       if (__sub->_M_search_from_first())
00155     {
00156       for (size_t __i = 0; __i < __what.size(); __i++)
00157         if (__what[__i].matched)
00158           _M_cur_results[__i] = __what[__i];
00159       return true;
00160     }
00161       return false;
00162     }
00163 
00164   // TODO: Use a function vector to dispatch, instead of using switch-case.
00165   template<typename _BiIter, typename _Alloc, typename _TraitsT,
00166     bool __dfs_mode>
00167   template<bool __match_mode>
00168     void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
00169     _M_dfs(_StateIdT __i)
00170     {
00171       if (!__dfs_mode)
00172     {
00173       if ((*_M_visited)[__i])
00174         return;
00175       (*_M_visited)[__i] = true;
00176     }
00177 
00178       const auto& __state = _M_nfa[__i];
00179       // Every change on _M_cur_results and _M_current will be rolled back after
00180       // finishing the recursion step.
00181       switch (__state._M_opcode)
00182     {
00183     // _M_alt branch is "match once more", while _M_next is "get me out
00184     // of this quantifier". Executing _M_next first or _M_alt first don't
00185     // mean the same thing, and we need to choose the correct order under
00186     // given greedy mode.
00187     case _S_opcode_alternative:
00188       // Greedy.
00189       if (!__state._M_neg)
00190         {
00191           // "Once more" is preferred in greedy mode.
00192           _M_dfs<__match_mode>(__state._M_alt);
00193           // If it's DFS executor and already accepted, we're done.
00194           if (!__dfs_mode || !_M_has_sol)
00195         _M_dfs<__match_mode>(__state._M_next);
00196         }
00197       else // Non-greedy mode
00198         {
00199           if (__dfs_mode)
00200         {
00201           // vice-versa.
00202           _M_dfs<__match_mode>(__state._M_next);
00203           if (!_M_has_sol)
00204             _M_dfs<__match_mode>(__state._M_alt);
00205         }
00206           else
00207         {
00208           // DON'T attempt anything, because there's already another
00209           // state with higher priority accepted. This state cannot be
00210           // better by attempting its next node.
00211           if (!_M_has_sol)
00212             {
00213               _M_dfs<__match_mode>(__state._M_next);
00214               // DON'T attempt anything if it's already accepted. An
00215               // accepted state *must* be better than a solution that
00216               // matches a non-greedy quantifier one more time.
00217               if (!_M_has_sol)
00218             _M_dfs<__match_mode>(__state._M_alt);
00219             }
00220         }
00221         }
00222       break;
00223     case _S_opcode_subexpr_begin:
00224       // If there's nothing changed since last visit, do NOT continue.
00225       // This prevents the executor from get into infinite loop when using
00226       // "()*" to match "".
00227       if (!_M_cur_results[__state._M_subexpr].matched
00228           || _M_cur_results[__state._M_subexpr].first != _M_current)
00229         {
00230           auto& __res = _M_cur_results[__state._M_subexpr];
00231           auto __back = __res.first;
00232           __res.first = _M_current;
00233           _M_dfs<__match_mode>(__state._M_next);
00234           __res.first = __back;
00235         }
00236       break;
00237     case _S_opcode_subexpr_end:
00238       if (_M_cur_results[__state._M_subexpr].second != _M_current
00239           || _M_cur_results[__state._M_subexpr].matched != true)
00240         {
00241           auto& __res = _M_cur_results[__state._M_subexpr];
00242           auto __back = __res;
00243           __res.second = _M_current;
00244           __res.matched = true;
00245           _M_dfs<__match_mode>(__state._M_next);
00246           __res = __back;
00247         }
00248       else
00249         _M_dfs<__match_mode>(__state._M_next);
00250       break;
00251     case _S_opcode_line_begin_assertion:
00252       if (_M_at_begin())
00253         _M_dfs<__match_mode>(__state._M_next);
00254       break;
00255     case _S_opcode_line_end_assertion:
00256       if (_M_at_end())
00257         _M_dfs<__match_mode>(__state._M_next);
00258       break;
00259     case _S_opcode_word_boundary:
00260       if (_M_word_boundary(__state) == !__state._M_neg)
00261         _M_dfs<__match_mode>(__state._M_next);
00262       break;
00263     // Here __state._M_alt offers a single start node for a sub-NFA.
00264     // We recursively invoke our algorithm to match the sub-NFA.
00265     case _S_opcode_subexpr_lookahead:
00266       if (_M_lookahead(__state) == !__state._M_neg)
00267         _M_dfs<__match_mode>(__state._M_next);
00268       break;
00269     case _S_opcode_match:
00270       if (__dfs_mode)
00271         {
00272           if (_M_current != _M_end && __state._M_matches(*_M_current))
00273         {
00274           ++_M_current;
00275           _M_dfs<__match_mode>(__state._M_next);
00276           --_M_current;
00277         }
00278         }
00279       else
00280         if (__state._M_matches(*_M_current))
00281           _M_match_queue->push_back(make_pair(__state._M_next,
00282                           _M_cur_results));
00283       break;
00284     // First fetch the matched result from _M_cur_results as __submatch;
00285     // then compare it with
00286     // (_M_current, _M_current + (__submatch.second - __submatch.first)).
00287     // If matched, keep going; else just return and try another state.
00288     case _S_opcode_backref:
00289       {
00290         _GLIBCXX_DEBUG_ASSERT(__dfs_mode);
00291         auto& __submatch = _M_cur_results[__state._M_backref_index];
00292         if (!__submatch.matched)
00293           break;
00294         auto __last = _M_current;
00295         for (auto __tmp = __submatch.first;
00296          __last != _M_end && __tmp != __submatch.second;
00297          ++__tmp)
00298           ++__last;
00299         if (_M_re._M_traits.transform(__submatch.first,
00300                         __submatch.second)
00301         == _M_re._M_traits.transform(_M_current, __last))
00302           {
00303         if (__last != _M_current)
00304           {
00305             auto __backup = _M_current;
00306             _M_current = __last;
00307             _M_dfs<__match_mode>(__state._M_next);
00308             _M_current = __backup;
00309           }
00310         else
00311           _M_dfs<__match_mode>(__state._M_next);
00312           }
00313       }
00314       break;
00315     case _S_opcode_accept:
00316       if (__dfs_mode)
00317         {
00318           _GLIBCXX_DEBUG_ASSERT(!_M_has_sol);
00319           if (__match_mode)
00320         _M_has_sol = _M_current == _M_end;
00321           else
00322         _M_has_sol = true;
00323           if (_M_current == _M_begin
00324           && (_M_flags & regex_constants::match_not_null))
00325         _M_has_sol = false;
00326           if (_M_has_sol)
00327         _M_results = _M_cur_results;
00328         }
00329       else
00330         {
00331           if (_M_current == _M_begin
00332           && (_M_flags & regex_constants::match_not_null))
00333         break;
00334           if (!__match_mode || _M_current == _M_end)
00335         if (!_M_has_sol)
00336           {
00337             _M_has_sol = true;
00338             _M_results = _M_cur_results;
00339           }
00340         }
00341       break;
00342     default:
00343       _GLIBCXX_DEBUG_ASSERT(false);
00344     }
00345     }
00346 
00347   // Return whether now is at some word boundary.
00348   template<typename _BiIter, typename _Alloc, typename _TraitsT,
00349     bool __dfs_mode>
00350     bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>::
00351     _M_word_boundary(_State<_TraitsT> __state) const
00352     {
00353       // By definition.
00354       bool __ans = false;
00355       auto __pre = _M_current;
00356       --__pre;
00357       if (!(_M_at_begin() && _M_at_end()))
00358     {
00359       if (_M_at_begin())
00360         __ans = _M_is_word(*_M_current)
00361           && !(_M_flags & regex_constants::match_not_bow);
00362       else if (_M_at_end())
00363         __ans = _M_is_word(*__pre)
00364           && !(_M_flags & regex_constants::match_not_eow);
00365       else
00366         __ans = _M_is_word(*_M_current)
00367           != _M_is_word(*__pre);
00368     }
00369       return __ans;
00370     }
00371 
00372 _GLIBCXX_END_NAMESPACE_VERSION
00373 } // namespace __detail
00374 } // namespace