libstdc++
regex_compiler.h
Go to the documentation of this file.
1 // class template regex -*- C++ -*-
2 
3 // Copyright (C) 2010-2017 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_compiler.h
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 _GLIBCXX_BEGIN_NAMESPACE_CXX11
35 
36  template<typename>
37  class regex_traits;
38 
39 _GLIBCXX_END_NAMESPACE_CXX11
40 _GLIBCXX_END_NAMESPACE_VERSION
41 
42 namespace __detail
43 {
44 _GLIBCXX_BEGIN_NAMESPACE_VERSION
45 
46  /**
47  * @addtogroup regex-detail
48  * @{
49  */
50 
51  template<typename, bool, bool>
53 
54  /**
55  * @brief Builds an NFA from an input iterator range.
56  *
57  * The %_TraitsT type should fulfill requirements [28.3].
58  */
59  template<typename _TraitsT>
60  class _Compiler
61  {
62  public:
63  typedef typename _TraitsT::char_type _CharT;
64  typedef const _CharT* _IterT;
65  typedef _NFA<_TraitsT> _RegexT;
67 
68  _Compiler(_IterT __b, _IterT __e,
69  const typename _TraitsT::locale_type& __traits, _FlagT __flags);
70 
72  _M_get_nfa()
73  { return std::move(_M_nfa); }
74 
75  private:
76  typedef _Scanner<_CharT> _ScannerT;
77  typedef typename _TraitsT::string_type _StringT;
78  typedef typename _ScannerT::_TokenT _TokenT;
82 
83  // accepts a specific token or returns false.
84  bool
85  _M_match_token(_TokenT __token);
86 
87  void
88  _M_disjunction();
89 
90  void
91  _M_alternative();
92 
93  bool
94  _M_term();
95 
96  bool
97  _M_assertion();
98 
99  bool
100  _M_quantifier();
101 
102  bool
103  _M_atom();
104 
105  bool
106  _M_bracket_expression();
107 
108  template<bool __icase, bool __collate>
109  void
110  _M_insert_any_matcher_ecma();
111 
112  template<bool __icase, bool __collate>
113  void
114  _M_insert_any_matcher_posix();
115 
116  template<bool __icase, bool __collate>
117  void
118  _M_insert_char_matcher();
119 
120  template<bool __icase, bool __collate>
121  void
122  _M_insert_character_class_matcher();
123 
124  template<bool __icase, bool __collate>
125  void
126  _M_insert_bracket_matcher(bool __neg);
127 
128  // Returns true if successfully matched one term and should continue.
129  // Returns false if the compiler should move on.
130  template<bool __icase, bool __collate>
131  bool
132  _M_expression_term(pair<bool, _CharT>& __last_char,
134  __matcher);
135 
136  int
137  _M_cur_int_value(int __radix);
138 
139  bool
140  _M_try_char();
141 
142  _StateSeqT
143  _M_pop()
144  {
145  auto ret = _M_stack.top();
146  _M_stack.pop();
147  return ret;
148  }
149 
150  _FlagT _M_flags;
151  _ScannerT _M_scanner;
152  shared_ptr<_RegexT> _M_nfa;
153  _StringT _M_value;
154  _StackT _M_stack;
155  const _TraitsT& _M_traits;
156  const _CtypeT& _M_ctype;
157  };
158 
159  template<typename _Tp>
160  struct __has_contiguous_iter : std::false_type { };
161 
162  template<typename _Ch, typename _Tr, typename _Alloc>
163  struct __has_contiguous_iter<std::basic_string<_Ch, _Tr, _Alloc>>
165  { };
166 
167  template<typename _Tp, typename _Alloc>
168  struct __has_contiguous_iter<std::vector<_Tp, _Alloc>>
170  { };
171 
172  template<typename _Tp>
173  struct __is_contiguous_normal_iter : std::false_type { };
174 
175  template<typename _CharT>
176  struct __is_contiguous_normal_iter<_CharT*> : std::true_type { };
177 
178  template<typename _Tp, typename _Cont>
179  struct
180  __is_contiguous_normal_iter<__gnu_cxx::__normal_iterator<_Tp, _Cont>>
182  { };
183 
184  template<typename _Iter, typename _TraitsT>
185  using __enable_if_contiguous_normal_iter
186  = typename enable_if< __is_contiguous_normal_iter<_Iter>::value,
188 
189  template<typename _Iter, typename _TraitsT>
190  using __disable_if_contiguous_normal_iter
191  = typename enable_if< !__is_contiguous_normal_iter<_Iter>::value,
193 
194  template<typename _FwdIter, typename _TraitsT>
195  inline __enable_if_contiguous_normal_iter<_FwdIter, _TraitsT>
196  __compile_nfa(_FwdIter __first, _FwdIter __last,
197  const typename _TraitsT::locale_type& __loc,
199  {
200  size_t __len = __last - __first;
201  const auto* __cfirst = __len ? std::__addressof(*__first) : nullptr;
202  using _Cmplr = _Compiler<_TraitsT>;
203  return _Cmplr(__cfirst, __cfirst + __len, __loc, __flags)._M_get_nfa();
204  }
205 
206  template<typename _FwdIter, typename _TraitsT>
207  inline __disable_if_contiguous_normal_iter<_FwdIter, _TraitsT>
208  __compile_nfa(_FwdIter __first, _FwdIter __last,
209  const typename _TraitsT::locale_type& __loc,
211  {
212  basic_string<typename _TraitsT::char_type> __str(__first, __last);
213  return __compile_nfa(__str.data(), __str.data() + __str.size(), __loc,
214  __flags);
215  }
216 
217  // [28.13.14]
218  template<typename _TraitsT, bool __icase, bool __collate>
219  class _RegexTranslatorBase
220  {
221  public:
222  typedef typename _TraitsT::char_type _CharT;
223  typedef typename _TraitsT::string_type _StringT;
224  typedef _StringT _StrTransT;
225 
226  explicit
227  _RegexTranslatorBase(const _TraitsT& __traits)
228  : _M_traits(__traits)
229  { }
230 
231  _CharT
232  _M_translate(_CharT __ch) const
233  {
234  if (__icase)
235  return _M_traits.translate_nocase(__ch);
236  else if (__collate)
237  return _M_traits.translate(__ch);
238  else
239  return __ch;
240  }
241 
242  _StrTransT
243  _M_transform(_CharT __ch) const
244  {
245  _StrTransT __str(1, __ch);
246  return _M_traits.transform(__str.begin(), __str.end());
247  }
248 
249  // See LWG 523. It's not efficiently implementable when _TraitsT is not
250  // std::regex_traits<>, and __collate is true. See specializations for
251  // implementations of other cases.
252  bool
253  _M_match_range(const _StrTransT& __first, const _StrTransT& __last,
254  const _StrTransT& __s) const
255  { return __first <= __s && __s <= __last; }
256 
257  protected:
258  bool _M_in_range_icase(_CharT __first, _CharT __last, _CharT __ch) const
259  {
260  typedef std::ctype<_CharT> __ctype_type;
261  const auto& __fctyp = use_facet<__ctype_type>(this->_M_traits.getloc());
262  auto __lower = __fctyp.tolower(__ch);
263  auto __upper = __fctyp.toupper(__ch);
264  return (__first <= __lower && __lower <= __last)
265  || (__first <= __upper && __upper <= __last);
266  }
267 
268  const _TraitsT& _M_traits;
269  };
270 
271  template<typename _TraitsT, bool __icase, bool __collate>
272  class _RegexTranslator
273  : public _RegexTranslatorBase<_TraitsT, __icase, __collate>
274  {
275  public:
276  typedef _RegexTranslatorBase<_TraitsT, __icase, __collate> _Base;
277  using _Base::_Base;
278  };
279 
280  template<typename _TraitsT, bool __icase>
281  class _RegexTranslator<_TraitsT, __icase, false>
282  : public _RegexTranslatorBase<_TraitsT, __icase, false>
283  {
284  public:
285  typedef _RegexTranslatorBase<_TraitsT, __icase, false> _Base;
286  typedef typename _Base::_CharT _CharT;
287  typedef _CharT _StrTransT;
288 
289  using _Base::_Base;
290 
291  _StrTransT
292  _M_transform(_CharT __ch) const
293  { return __ch; }
294 
295  bool
296  _M_match_range(_CharT __first, _CharT __last, _CharT __ch) const
297  {
298  if (!__icase)
299  return __first <= __ch && __ch <= __last;
300  return this->_M_in_range_icase(__first, __last, __ch);
301  }
302  };
303 
304  template<typename _CharType>
305  class _RegexTranslator<std::regex_traits<_CharType>, true, true>
306  : public _RegexTranslatorBase<std::regex_traits<_CharType>, true, true>
307  {
308  public:
309  typedef _RegexTranslatorBase<std::regex_traits<_CharType>, true, true>
310  _Base;
311  typedef typename _Base::_CharT _CharT;
312  typedef typename _Base::_StrTransT _StrTransT;
313 
314  using _Base::_Base;
315 
316  bool
317  _M_match_range(const _StrTransT& __first, const _StrTransT& __last,
318  const _StrTransT& __str) const
319  {
320  __glibcxx_assert(__first.size() == 1);
321  __glibcxx_assert(__last.size() == 1);
322  __glibcxx_assert(__str.size() == 1);
323  return this->_M_in_range_icase(__first[0], __last[0], __str[0]);
324  }
325  };
326 
327  template<typename _TraitsT>
328  class _RegexTranslator<_TraitsT, false, false>
329  {
330  public:
331  typedef typename _TraitsT::char_type _CharT;
332  typedef _CharT _StrTransT;
333 
334  explicit
335  _RegexTranslator(const _TraitsT&)
336  { }
337 
338  _CharT
339  _M_translate(_CharT __ch) const
340  { return __ch; }
341 
342  _StrTransT
343  _M_transform(_CharT __ch) const
344  { return __ch; }
345 
346  bool
347  _M_match_range(_CharT __first, _CharT __last, _CharT __ch) const
348  { return __first <= __ch && __ch <= __last; }
349  };
350 
351  template<typename _TraitsT, bool __is_ecma, bool __icase, bool __collate>
352  struct _AnyMatcher;
353 
354  template<typename _TraitsT, bool __icase, bool __collate>
355  struct _AnyMatcher<_TraitsT, false, __icase, __collate>
356  {
357  typedef _RegexTranslator<_TraitsT, __icase, __collate> _TransT;
358  typedef typename _TransT::_CharT _CharT;
359 
360  explicit
361  _AnyMatcher(const _TraitsT& __traits)
362  : _M_translator(__traits)
363  { }
364 
365  bool
366  operator()(_CharT __ch) const
367  {
368  static auto __nul = _M_translator._M_translate('\0');
369  return _M_translator._M_translate(__ch) != __nul;
370  }
371 
372  _TransT _M_translator;
373  };
374 
375  template<typename _TraitsT, bool __icase, bool __collate>
376  struct _AnyMatcher<_TraitsT, true, __icase, __collate>
377  {
378  typedef _RegexTranslator<_TraitsT, __icase, __collate> _TransT;
379  typedef typename _TransT::_CharT _CharT;
380 
381  explicit
382  _AnyMatcher(const _TraitsT& __traits)
383  : _M_translator(__traits)
384  { }
385 
386  bool
387  operator()(_CharT __ch) const
388  { return _M_apply(__ch, typename is_same<_CharT, char>::type()); }
389 
390  bool
391  _M_apply(_CharT __ch, true_type) const
392  {
393  auto __c = _M_translator._M_translate(__ch);
394  auto __n = _M_translator._M_translate('\n');
395  auto __r = _M_translator._M_translate('\r');
396  return __c != __n && __c != __r;
397  }
398 
399  bool
400  _M_apply(_CharT __ch, false_type) const
401  {
402  auto __c = _M_translator._M_translate(__ch);
403  auto __n = _M_translator._M_translate('\n');
404  auto __r = _M_translator._M_translate('\r');
405  auto __u2028 = _M_translator._M_translate(u'\u2028');
406  auto __u2029 = _M_translator._M_translate(u'\u2029');
407  return __c != __n && __c != __r && __c != __u2028 && __c != __u2029;
408  }
409 
410  _TransT _M_translator;
411  };
412 
413  template<typename _TraitsT, bool __icase, bool __collate>
414  struct _CharMatcher
415  {
416  typedef _RegexTranslator<_TraitsT, __icase, __collate> _TransT;
417  typedef typename _TransT::_CharT _CharT;
418 
419  _CharMatcher(_CharT __ch, const _TraitsT& __traits)
420  : _M_translator(__traits), _M_ch(_M_translator._M_translate(__ch))
421  { }
422 
423  bool
424  operator()(_CharT __ch) const
425  { return _M_ch == _M_translator._M_translate(__ch); }
426 
427  _TransT _M_translator;
428  _CharT _M_ch;
429  };
430 
431  /// Matches a character range (bracket expression)
432  template<typename _TraitsT, bool __icase, bool __collate>
433  struct _BracketMatcher
434  {
435  public:
436  typedef _RegexTranslator<_TraitsT, __icase, __collate> _TransT;
437  typedef typename _TransT::_CharT _CharT;
438  typedef typename _TransT::_StrTransT _StrTransT;
439  typedef typename _TraitsT::string_type _StringT;
440  typedef typename _TraitsT::char_class_type _CharClassT;
441 
442  public:
443  _BracketMatcher(bool __is_non_matching,
444  const _TraitsT& __traits)
445  : _M_class_set(0), _M_translator(__traits), _M_traits(__traits),
446  _M_is_non_matching(__is_non_matching)
447  { }
448 
449  bool
450  operator()(_CharT __ch) const
451  {
452  _GLIBCXX_DEBUG_ASSERT(_M_is_ready);
453  return _M_apply(__ch, _UseCache());
454  }
455 
456  void
457  _M_add_char(_CharT __c)
458  {
459  _M_char_set.push_back(_M_translator._M_translate(__c));
460  _GLIBCXX_DEBUG_ONLY(_M_is_ready = false);
461  }
462 
463  _StringT
464  _M_add_collate_element(const _StringT& __s)
465  {
466  auto __st = _M_traits.lookup_collatename(__s.data(),
467  __s.data() + __s.size());
468  if (__st.empty())
469  __throw_regex_error(regex_constants::error_collate,
470  "Invalid collate element.");
471  _M_char_set.push_back(_M_translator._M_translate(__st[0]));
472  _GLIBCXX_DEBUG_ONLY(_M_is_ready = false);
473  return __st;
474  }
475 
476  void
477  _M_add_equivalence_class(const _StringT& __s)
478  {
479  auto __st = _M_traits.lookup_collatename(__s.data(),
480  __s.data() + __s.size());
481  if (__st.empty())
482  __throw_regex_error(regex_constants::error_collate,
483  "Invalid equivalence class.");
484  __st = _M_traits.transform_primary(__st.data(),
485  __st.data() + __st.size());
486  _M_equiv_set.push_back(__st);
487  _GLIBCXX_DEBUG_ONLY(_M_is_ready = false);
488  }
489 
490  // __neg should be true for \D, \S and \W only.
491  void
492  _M_add_character_class(const _StringT& __s, bool __neg)
493  {
494  auto __mask = _M_traits.lookup_classname(__s.data(),
495  __s.data() + __s.size(),
496  __icase);
497  if (__mask == 0)
498  __throw_regex_error(regex_constants::error_collate,
499  "Invalid character class.");
500  if (!__neg)
501  _M_class_set |= __mask;
502  else
503  _M_neg_class_set.push_back(__mask);
504  _GLIBCXX_DEBUG_ONLY(_M_is_ready = false);
505  }
506 
507  void
508  _M_make_range(_CharT __l, _CharT __r)
509  {
510  if (__l > __r)
511  __throw_regex_error(regex_constants::error_range,
512  "Invalid range in bracket expression.");
513  _M_range_set.push_back(make_pair(_M_translator._M_transform(__l),
514  _M_translator._M_transform(__r)));
515  _GLIBCXX_DEBUG_ONLY(_M_is_ready = false);
516  }
517 
518  void
519  _M_ready()
520  {
521  std::sort(_M_char_set.begin(), _M_char_set.end());
522  auto __end = std::unique(_M_char_set.begin(), _M_char_set.end());
523  _M_char_set.erase(__end, _M_char_set.end());
524  _M_make_cache(_UseCache());
525  _GLIBCXX_DEBUG_ONLY(_M_is_ready = true);
526  }
527 
528  private:
529  // Currently we only use the cache for char
530  typedef typename std::is_same<_CharT, char>::type _UseCache;
531 
532  static constexpr size_t
533  _S_cache_size()
534  {
535  return 1ul << (sizeof(_CharT) * __CHAR_BIT__ * int(_UseCache::value));
536  }
537 
538  struct _Dummy { };
539  typedef typename std::conditional<_UseCache::value,
541  _Dummy>::type _CacheT;
542  typedef typename std::make_unsigned<_CharT>::type _UnsignedCharT;
543 
544  bool
545  _M_apply(_CharT __ch, false_type) const;
546 
547  bool
548  _M_apply(_CharT __ch, true_type) const
549  { return _M_cache[static_cast<_UnsignedCharT>(__ch)]; }
550 
551  void
552  _M_make_cache(true_type)
553  {
554  for (unsigned __i = 0; __i < _M_cache.size(); __i++)
555  _M_cache[__i] = _M_apply(static_cast<_CharT>(__i), false_type());
556  }
557 
558  void
559  _M_make_cache(false_type)
560  { }
561 
562  private:
563  std::vector<_CharT> _M_char_set;
564  std::vector<_StringT> _M_equiv_set;
566  std::vector<_CharClassT> _M_neg_class_set;
567  _CharClassT _M_class_set;
568  _TransT _M_translator;
569  const _TraitsT& _M_traits;
570  bool _M_is_non_matching;
571  _CacheT _M_cache;
572 #ifdef _GLIBCXX_DEBUG
573  bool _M_is_ready = false;
574 #endif
575  };
576 
577  //@} regex-detail
578 _GLIBCXX_END_NAMESPACE_VERSION
579 } // namespace __detail
580 } // namespace std
581 
582 #include <bits/regex_compiler.tcc>
void pop()
Removes first element.
Definition: stl_stack.h:258
Describes a sequence of one or more _State, its current start and end(s). This structure contains fra...
Matches a character range (bracket expression)
integral_constant< bool, false > false_type
The type used as a compile-time boolean with false value.
Definition: type_traits:90
Primary class template ctype facet.This template class defines classification and conversion function...
const _CharT * data() const noexcept
Return const pointer to contents.
Managing sequences of characters and character-like objects.
size_type size() const noexcept
Returns the number of characters in the string, not including any null-termination.
A standard container which offers fixed time access to individual elements in any order...
Definition: stl_vector.h:216
integral_constant
Definition: type_traits:69
Scans an input range for regex tokens.
_ForwardIterator unique(_ForwardIterator __first, _ForwardIterator __last, _BinaryPredicate __binary_pred)
Remove consecutive values from a sequence using a predicate.
Definition: stl_algo.h:1025
ISO C++ entities toplevel namespace is std.
constexpr pair< typename __decay_and_strip< _T1 >::__type, typename __decay_and_strip< _T2 >::__type > make_pair(_T1 &&__x, _T2 &&__y)
A convenience wrapper for creating a pair from two objects.
Definition: stl_pair.h:519
void sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
Sort the elements of a sequence using a predicate for comparison.
Definition: stl_algo.h:4842
A smart pointer with reference-counted copy semantics.
constexpr error_type error_collate(_S_error_collate)
constexpr _Tp * __addressof(_Tp &__r) noexcept
Same as C++11 std::addressof.
Definition: move.h:47
Describes aspects of a regular expression.
Definition: regex.h:87
syntax_option_type
This is a bitmask type indicating how to interpret the regex.
reference top()
Definition: stl_stack.h:198
Struct holding two objects of arbitrary type.
Definition: stl_pair.h:198
constexpr error_type error_range(_S_error_range)
The bitset class represents a fixed-size sequence of bits.(Note that bitset does not meet the formal ...
Definition: bitset:747
char_type tolower(char_type __c) const
Convert to lowercase.
Builds an NFA from an input iterator range.