You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

511 lines
16 KiB

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