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