blob: f63d5f90c0f47deb2417410efe3f0c2891fab524 [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001#ifndef __REGEXP_PCRE_HPP
2#define __REGEXP_PCRE_HPP
3
4#include <pcre.h>
5#include <array>
6#include <stdexcept>
7#include <string>
8#include <vector>
9
10namespace rgx {
11/* partially implement the std::regex interface using PCRE for performance
12 * (=> pass "match" as non-const reference)
13 */
14
15namespace regex_constants {
16enum error_type {
17 _enum_error_collate,
18 _enum_error_ctype,
19 _enum_error_escape,
20 _enum_error_backref,
21 _enum_error_brack,
22 _enum_error_paren,
23 _enum_error_brace,
24 _enum_error_badbrace,
25 _enum_error_range,
26 _enum_error_space,
27 _enum_error_badrepeat,
28 _enum_error_complexity,
29 _enum_error_stack,
30 _enum_error_last
31};
32static const error_type error_collate(_enum_error_collate);
33static const error_type error_ctype(_enum_error_ctype);
34static const error_type error_escape(_enum_error_escape);
35static const error_type error_backref(_enum_error_backref);
36static const error_type error_brack(_enum_error_brack);
37static const error_type error_paren(_enum_error_paren);
38static const error_type error_brace(_enum_error_brace);
39static const error_type error_badbrace(_enum_error_badbrace);
40static const error_type error_range(_enum_error_range);
41static const error_type error_space(_enum_error_space);
42static const error_type error_badrepeat(_enum_error_badrepeat);
43static const error_type error_complexity(_enum_error_complexity);
44static const error_type error_stack(_enum_error_stack);
45} // namespace regex_constants
46
47class regex_error : public std::runtime_error {
48 private:
49 regex_constants::error_type errcode;
50
51 public:
52 explicit regex_error(regex_constants::error_type code, const char* what = "regex error")
53 : runtime_error(what), errcode(code)
54 {}
55
56 [[nodiscard]] auto virtual code() const -> regex_constants::error_type;
57};
58
59[[nodiscard]] auto regex_error::code() const -> regex_constants::error_type
60{
61 return errcode;
62}
63
64class regex {
65 private:
66 int errcode = 0;
67
68 const char* errptr = nullptr;
69
70 int erroffset = 0;
71
72 pcre* const re = nullptr;
73
74 static const std::array<regex_constants::error_type, 86> errcode_pcre2regex;
75
76 static const auto BASE = 10;
77
78 public:
79 inline regex() = default;
80
81 inline regex(const regex&) = delete;
82
83 inline regex(regex&&) = default;
84
85 inline auto operator=(const regex&) -> regex& = delete;
86
87 inline auto operator=(regex &&) -> regex& = delete;
88
89 explicit regex(const std::string& str) : regex(str.c_str()) {}
90
91 explicit regex(const char* const str)
92 : re{pcre_compile2(str, 0, &errcode, &errptr, &erroffset, nullptr)}
93 {
94 if (re == nullptr) {
95 std::string what = std::string("regex error: ") + errptr + '\n';
96 what += " '" + std::string{str} + "'\n";
97 what += " " + std::string(erroffset, ' ') + '^';
98
99 throw regex_error(errcode_pcre2regex.at(errcode), what.c_str());
100 }
101 }
102
103 ~regex()
104 {
105 if (re != nullptr) {
106 pcre_free(re);
107 }
108 }
109
110 inline auto operator()() const -> const pcre*
111 {
112 return re;
113 }
114};
115
116class smatch {
117 friend auto regex_search(std::string::const_iterator begin,
118 std::string::const_iterator end,
119 smatch& match, // NOLINT(google-runtime-references)
120 const regex& rgx); // match std::regex interface.
121
122 private:
123 std::string::const_iterator begin;
124
125 std::string::const_iterator end;
126
127 std::vector<int> vec{};
128
129 int n = 0;
130
131 public:
132 [[nodiscard]] inline auto position(int i = 0) const
133 {
134 return (i < 0 || i >= n) ? std::string::npos : vec[2 * i];
135 }
136
137 [[nodiscard]] inline auto length(int i = 0) const
138 {
139 return (i < 0 || i >= n) ? 0 : vec[2 * i + 1] - vec[2 * i];
140 }
141
142 [[nodiscard]] auto str(int i = 0) const -> std::string
143 { // should we throw?
144 if (i < 0 || i >= n) {
145 return "";
146 }
147 int x = vec[2 * i];
148 if (x < 0) {
149 return "";
150 }
151 int y = vec[2 * i + 1];
152 return std::string{begin + x, begin + y};
153 }
154
155 [[nodiscard]] auto format(const std::string& fmt) const;
156
157 [[nodiscard]] auto size() const -> int
158 {
159 return n;
160 }
161
162 [[nodiscard]] inline auto empty() const
163 {
164 return n < 0;
165 }
166
167 [[nodiscard]] inline auto ready() const
168 {
169 return !vec.empty();
170 }
171};
172
173inline auto regex_search(const std::string& subj, const regex& rgx);
174
175auto regex_replace(const std::string& subj, const regex& rgx, const std::string& insert);
176
177inline auto regex_search(const std::string& subj,
178 smatch& match, // NOLINT(google-runtime-references)
179 const regex& rgx); // match std::regex interface.
180
181auto regex_search(std::string::const_iterator begin,
182 std::string::const_iterator end,
183 smatch& match, // NOLINT(google-runtime-references)
184 const regex& rgx); // match std::regex interface.
185
186// ------------------------- implementation: ----------------------------------
187
188inline auto regex_search(const std::string& subj, const regex& rgx)
189{
190 if (rgx() == nullptr) {
191 throw std::runtime_error("regex_search error: no regex given");
192 }
193 int n =
194 pcre_exec(rgx(), nullptr, subj.c_str(), static_cast<int>(subj.length()), 0, 0, nullptr, 0);
195 return n >= 0;
196}
197
198auto regex_search(const std::string::const_iterator begin,
199 const std::string::const_iterator end,
200 smatch& match,
201 const regex& rgx)
202{
203 if (rgx() == nullptr) {
204 throw std::runtime_error("regex_search error: no regex given");
205 }
206
207 int sz = 0;
208 pcre_fullinfo(rgx(), nullptr, PCRE_INFO_CAPTURECOUNT, &sz);
209 sz = 3 * (sz + 1);
210
211 match.vec.reserve(sz);
212
213 const char* subj = &*begin;
214 int len = static_cast<int>(&*end - subj);
215
216 match.begin = begin;
217 match.end = end;
218
219 match.n = pcre_exec(rgx(), nullptr, subj, len, 0, 0, &match.vec[0], sz);
220
221 if (match.n < 0) {
222 return false;
223 }
224 if (match.n == 0) {
225 match.n = sz / 3;
226 }
227
228 return true;
229}
230
231inline auto regex_search(const std::string& subj, smatch& match, const regex& rgx)
232{
233 return regex_search(subj.begin(), subj.end(), match, rgx);
234}
235
236auto smatch::format(const std::string& fmt) const
237{
238 std::string ret{};
239 size_t index = 0;
240
241 size_t pos = 0;
242 while ((pos = fmt.find('$', index)) != std::string::npos) {
243 ret.append(fmt, index, pos - index);
244 index = pos + 1;
245
246 char chr = fmt[index++];
247 switch (chr) {
248 case '&': // match
249 ret += str(0);
250 break;
251
252 case '`': // prefix
253 ret.append(begin, begin + vec[0]);
254 break;
255
256 case '\'': // suffix
257 ret.append(begin + vec[1], end);
258 break;
259
260 default:
261 if (isdigit(chr) != 0) { // one or two digits => submatch:
262 int num = chr - '0';
263 chr = fmt[index];
264 if (isdigit(chr) != 0) { // second digit:
265 ++index;
266 static const auto base = 10;
267 num = num * base + chr - '0';
268 }
269 ret += str(num);
270 break;
271 } // else:
272
273 ret += '$';
274 [[fallthrough]];
275
276 case '$': // escaped
277 ret += chr;
278 }
279 }
280 ret.append(fmt, index);
281 return ret;
282}
283
284auto regex_replace(const std::string& subj, const regex& rgx, const std::string& insert)
285{
286 if (rgx() == nullptr) {
287 throw std::runtime_error("regex_replace error: no regex given");
288 }
289
290 std::string ret{};
291 auto pos = subj.begin();
292
293 for (smatch match; regex_search(pos, subj.end(), match, rgx);
294 pos += match.position(0) + match.length(0))
295 {
296 ret.append(pos, pos + match.position(0));
297 ret.append(match.format(insert));
298 }
299
300 ret.append(pos, subj.end());
301 return ret;
302}
303
304// ------------ There is only the translation table below : -------------------
305
306const std::array<regex_constants::error_type, 86> regex::errcode_pcre2regex = {
307 // 0 no error
308 regex_constants::error_type::_enum_error_last,
309 // 1 \ at end of pattern
310 regex_constants::error_escape,
311 // 2 \c at end of pattern
312 regex_constants::error_escape,
313 // 3 unrecognized character follows \ .
314 regex_constants::error_escape,
315 // 4 numbers out of order in {} quantifier
316 regex_constants::error_badbrace,
317 // 5 number too big in {} quantifier
318 regex_constants::error_badbrace,
319 // 6 missing terminating for character class
320 regex_constants::error_brack,
321 // 7 invalid escape sequence in character class
322 regex_constants::error_escape,
323 // 8 range out of order in character class
324 regex_constants::error_range,
325 // 9 nothing to repeat
326 regex_constants::error_badrepeat,
327 // 10 [this code is not in use
328 regex_constants::error_type::_enum_error_last,
329 // 11 internal error: unexpected repeat
330 regex_constants::error_badrepeat,
331 // 12 unrecognized character after (? or (?-
332 regex_constants::error_backref,
333 // 13 POSIX named classes are supported only within a class
334 regex_constants::error_range,
335 // 14 missing )
336 regex_constants::error_paren,
337 // 15 reference to non-existent subpattern
338 regex_constants::error_backref,
339 // 16 erroffset passed as NULL
340 regex_constants::error_type::_enum_error_last,
341 // 17 unknown option bit(s) set
342 regex_constants::error_type::_enum_error_last,
343 // 18 missing ) after comment
344 regex_constants::error_paren,
345 // 19 [this code is not in use
346 regex_constants::error_type::_enum_error_last,
347 // 20 regular expression is too large
348 regex_constants::error_space,
349 // 21 failed to get memory
350 regex_constants::error_stack,
351 // 22 unmatched parentheses
352 regex_constants::error_paren,
353 // 23 internal error: code overflow
354 regex_constants::error_stack,
355 // 24 unrecognized character after (?<
356 regex_constants::error_backref,
357 // 25 lookbehind assertion is not fixed length
358 regex_constants::error_backref,
359 // 26 malformed number or name after (?(
360 regex_constants::error_backref,
361 // 27 conditional group contains more than two branches
362 regex_constants::error_backref,
363 // 28 assertion expected after (?(
364 regex_constants::error_backref,
365 // 29 (?R or (?[+-digits must be followed by )
366 regex_constants::error_backref,
367 // 30 unknown POSIX class name
368 regex_constants::error_ctype,
369 // 31 POSIX collating elements are not supported
370 regex_constants::error_collate,
371 // 32 this version of PCRE is compiled without UTF support
372 regex_constants::error_collate,
373 // 33 [this code is not in use
374 regex_constants::error_type::_enum_error_last,
375 // 34 character value in \x{} or \o{} is too large
376 regex_constants::error_escape,
377 // 35 invalid condition (?(0)
378 regex_constants::error_backref,
379 // 36 \C not allowed in lookbehind assertion
380 regex_constants::error_escape,
381 // 37 PCRE does not support \L, \l, \N{name}, \U, or \u
382 regex_constants::error_escape,
383 // 38 number after (?C is > 255
384 regex_constants::error_backref,
385 // 39 closing ) for (?C expected
386 regex_constants::error_paren,
387 // 40 recursive call could loop indefinitely
388 regex_constants::error_complexity,
389 // 41 unrecognized character after (?P
390 regex_constants::error_backref,
391 // 42 syntax error in subpattern name (missing terminator)
392 regex_constants::error_paren,
393 // 43 two named subpatterns have the same name
394 regex_constants::error_backref,
395 // 44 invalid UTF-8 string (specifically UTF-8)
396 regex_constants::error_collate,
397 // 45 support for \P, \p, and \X has not been compiled
398 regex_constants::error_escape,
399 // 46 malformed \P or \p sequence
400 regex_constants::error_escape,
401 // 47 unknown property name after \P or \p
402 regex_constants::error_escape,
403 // 48 subpattern name is too long (maximum 32 characters)
404 regex_constants::error_backref,
405 // 49 too many named subpatterns (maximum 10000)
406 regex_constants::error_complexity,
407 // 50 [this code is not in use
408 regex_constants::error_type::_enum_error_last,
409 // 51 octal value is greater than \377 in 8-bit non-UTF-8 mode
410 regex_constants::error_escape,
411 // 52 internal error: overran compiling workspace
412 regex_constants::error_type::_enum_error_last,
413 // 53 internal error: previously-checked referenced subpattern not found
414 regex_constants::error_type::_enum_error_last,
415 // 54 DEFINE group contains more than one branch
416 regex_constants::error_backref,
417 // 55 repeating a DEFINE group is not allowed
418 regex_constants::error_backref,
419 // 56 inconsistent NEWLINE options
420 regex_constants::error_escape,
421 // 57 \g is not followed by a braced, angle-bracketed, or quoted name/number or by a plain
422 // number
423 regex_constants::error_backref,
424 // 58 a numbered reference must not be zero
425 regex_constants::error_backref,
426 // 59 an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)
427 regex_constants::error_complexity,
428 // 60 (*VERB) not recognized or malformed
429 regex_constants::error_complexity,
430 // 61 number is too big
431 regex_constants::error_complexity,
432 // 62 subpattern name expected
433 regex_constants::error_backref,
434 // 63 digit expected after (?+
435 regex_constants::error_backref,
436 // 64 is an invalid data character in JavaScript compatibility mode
437 regex_constants::error_escape,
438 // 65 different names for subpatterns of the same number are not allowed
439 regex_constants::error_backref,
440 // 66 (*MARK) must have an argument
441 regex_constants::error_complexity,
442 // 67 this version of PCRE is not compiled with Unicode property support
443 regex_constants::error_collate,
444 // 68 \c must be followed by an ASCII character
445 regex_constants::error_escape,
446 // 69 \k is not followed by a braced, angle-bracketed, or quoted name
447 regex_constants::error_backref,
448 // 70 internal error: unknown opcode in find_fixedlength()
449 regex_constants::error_type::_enum_error_last,
450 // 71 \N is not supported in a class
451 regex_constants::error_ctype,
452 // 72 too many forward references
453 regex_constants::error_backref,
454 // 73 disallowed Unicode code point (>= 0xd800 && <= 0xdfff)
455 regex_constants::error_escape,
456 // 74 invalid UTF-16 string (specifically UTF-16)
457 regex_constants::error_collate,
458 // 75 name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)
459 regex_constants::error_complexity,
460 // 76 character value in \u.... sequence is too large
461 regex_constants::error_escape,
462 // 77 invalid UTF-32 string (specifically UTF-32)
463 regex_constants::error_collate,
464 // 78 setting UTF is disabled by the application
465 regex_constants::error_collate,
466 // 79 non-hex character in \x{} (closing brace missing?)
467 regex_constants::error_escape,
468 // 80 non-octal character in \o{} (closing brace missing?)
469 regex_constants::error_escape,
470 // 81 missing opening brace after \o
471 regex_constants::error_brace,
472 // 82 parentheses are too deeply nested
473 regex_constants::error_complexity,
474 // 83 invalid range in character class
475 regex_constants::error_range,
476 // 84 group name must start with a non-digit
477 regex_constants::error_backref,
478 // 85 parentheses are too deeply nested (stack check)
479 regex_constants::error_stack};
480
481} // namespace rgx
482
483#endif