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