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