regex.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. /**************************************************************************/
  2. /* regex.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "regex.h"
  31. #include "core/os/memory.h"
  32. extern "C" {
  33. #include <pcre2.h>
  34. }
  35. static void *_regex_malloc(PCRE2_SIZE size, void *user) {
  36. return memalloc(size);
  37. }
  38. static void _regex_free(void *ptr, void *user) {
  39. if (ptr) {
  40. memfree(ptr);
  41. }
  42. }
  43. int RegExMatch::_find(const Variant &p_name) const {
  44. if (p_name.is_num()) {
  45. int i = (int)p_name;
  46. if (i >= data.size()) {
  47. return -1;
  48. }
  49. return i;
  50. } else if (p_name.get_type() == Variant::STRING) {
  51. const Map<String, int>::Element *found = names.find((String)p_name);
  52. if (found) {
  53. return found->value();
  54. }
  55. }
  56. return -1;
  57. }
  58. String RegExMatch::get_subject() const {
  59. return subject;
  60. }
  61. int RegExMatch::get_group_count() const {
  62. if (data.size() == 0) {
  63. return 0;
  64. }
  65. return data.size() - 1;
  66. }
  67. Dictionary RegExMatch::get_names() const {
  68. Dictionary result;
  69. for (const Map<String, int>::Element *i = names.front(); i != nullptr; i = i->next()) {
  70. result[i->key()] = i->value();
  71. }
  72. return result;
  73. }
  74. Array RegExMatch::get_strings() const {
  75. Array result;
  76. int size = data.size();
  77. for (int i = 0; i < size; i++) {
  78. int start = data[i].start;
  79. if (start == -1) {
  80. result.append(String());
  81. continue;
  82. }
  83. int length = data[i].end - start;
  84. result.append(subject.substr(start, length));
  85. }
  86. return result;
  87. }
  88. String RegExMatch::get_string(const Variant &p_name) const {
  89. int id = _find(p_name);
  90. if (id < 0) {
  91. return String();
  92. }
  93. int start = data[id].start;
  94. if (start == -1) {
  95. return String();
  96. }
  97. int length = data[id].end - start;
  98. return subject.substr(start, length);
  99. }
  100. int RegExMatch::get_start(const Variant &p_name) const {
  101. int id = _find(p_name);
  102. if (id < 0) {
  103. return -1;
  104. }
  105. return data[id].start;
  106. }
  107. int RegExMatch::get_end(const Variant &p_name) const {
  108. int id = _find(p_name);
  109. if (id < 0) {
  110. return -1;
  111. }
  112. return data[id].end;
  113. }
  114. void RegExMatch::_bind_methods() {
  115. ClassDB::bind_method(D_METHOD("get_subject"), &RegExMatch::get_subject);
  116. ClassDB::bind_method(D_METHOD("get_group_count"), &RegExMatch::get_group_count);
  117. ClassDB::bind_method(D_METHOD("get_names"), &RegExMatch::get_names);
  118. ClassDB::bind_method(D_METHOD("get_strings"), &RegExMatch::get_strings);
  119. ClassDB::bind_method(D_METHOD("get_string", "name"), &RegExMatch::get_string, DEFVAL(0));
  120. ClassDB::bind_method(D_METHOD("get_start", "name"), &RegExMatch::get_start, DEFVAL(0));
  121. ClassDB::bind_method(D_METHOD("get_end", "name"), &RegExMatch::get_end, DEFVAL(0));
  122. ADD_PROPERTY(PropertyInfo(Variant::STRING, "subject"), "", "get_subject");
  123. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "names"), "", "get_names");
  124. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "strings"), "", "get_strings");
  125. }
  126. void RegEx::_pattern_info(uint32_t what, void *where) const {
  127. if (sizeof(CharType) == 2) {
  128. pcre2_pattern_info_16((pcre2_code_16 *)code, what, where);
  129. } else {
  130. pcre2_pattern_info_32((pcre2_code_32 *)code, what, where);
  131. }
  132. }
  133. void RegEx::clear() {
  134. if (sizeof(CharType) == 2) {
  135. if (code) {
  136. pcre2_code_free_16((pcre2_code_16 *)code);
  137. code = nullptr;
  138. }
  139. } else {
  140. if (code) {
  141. pcre2_code_free_32((pcre2_code_32 *)code);
  142. code = nullptr;
  143. }
  144. }
  145. }
  146. Error RegEx::compile(const String &p_pattern) {
  147. pattern = p_pattern;
  148. clear();
  149. int err;
  150. PCRE2_SIZE offset;
  151. uint32_t flags = PCRE2_DUPNAMES;
  152. if (sizeof(CharType) == 2) {
  153. pcre2_general_context_16 *gctx = (pcre2_general_context_16 *)general_ctx;
  154. pcre2_compile_context_16 *cctx = pcre2_compile_context_create_16(gctx);
  155. PCRE2_SPTR16 p = (PCRE2_SPTR16)pattern.c_str();
  156. code = pcre2_compile_16(p, pattern.length(), flags, &err, &offset, cctx);
  157. pcre2_compile_context_free_16(cctx);
  158. if (!code) {
  159. PCRE2_UCHAR16 buf[256];
  160. pcre2_get_error_message_16(err, buf, 256);
  161. String message = String::num(offset) + ": " + String((const CharType *)buf);
  162. ERR_PRINT(message.utf8());
  163. return FAILED;
  164. }
  165. } else {
  166. pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
  167. pcre2_compile_context_32 *cctx = pcre2_compile_context_create_32(gctx);
  168. PCRE2_SPTR32 p = (PCRE2_SPTR32)pattern.c_str();
  169. code = pcre2_compile_32(p, pattern.length(), flags, &err, &offset, cctx);
  170. pcre2_compile_context_free_32(cctx);
  171. if (!code) {
  172. PCRE2_UCHAR32 buf[256];
  173. pcre2_get_error_message_32(err, buf, 256);
  174. String message = String::num(offset) + ": " + String((const CharType *)buf);
  175. ERR_PRINT(message.utf8());
  176. return FAILED;
  177. }
  178. }
  179. return OK;
  180. }
  181. Ref<RegExMatch> RegEx::search(const String &p_subject, int p_offset, int p_end) const {
  182. ERR_FAIL_COND_V(!is_valid(), nullptr);
  183. Ref<RegExMatch> result = memnew(RegExMatch);
  184. int length = p_subject.length();
  185. if (p_end >= 0 && p_end < length) {
  186. length = p_end;
  187. }
  188. if (sizeof(CharType) == 2) {
  189. pcre2_code_16 *c = (pcre2_code_16 *)code;
  190. pcre2_general_context_16 *gctx = (pcre2_general_context_16 *)general_ctx;
  191. pcre2_match_context_16 *mctx = pcre2_match_context_create_16(gctx);
  192. PCRE2_SPTR16 s = (PCRE2_SPTR16)p_subject.c_str();
  193. pcre2_match_data_16 *match = pcre2_match_data_create_from_pattern_16(c, gctx);
  194. int res = pcre2_match_16(c, s, length, p_offset, 0, match, mctx);
  195. if (res < 0) {
  196. pcre2_match_data_free_16(match);
  197. pcre2_match_context_free_16(mctx);
  198. return nullptr;
  199. }
  200. uint32_t size = pcre2_get_ovector_count_16(match);
  201. PCRE2_SIZE *ovector = pcre2_get_ovector_pointer_16(match);
  202. result->data.resize(size);
  203. for (uint32_t i = 0; i < size; i++) {
  204. result->data.write[i].start = ovector[i * 2];
  205. result->data.write[i].end = ovector[i * 2 + 1];
  206. }
  207. pcre2_match_data_free_16(match);
  208. pcre2_match_context_free_16(mctx);
  209. } else {
  210. pcre2_code_32 *c = (pcre2_code_32 *)code;
  211. pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
  212. pcre2_match_context_32 *mctx = pcre2_match_context_create_32(gctx);
  213. PCRE2_SPTR32 s = (PCRE2_SPTR32)p_subject.c_str();
  214. pcre2_match_data_32 *match = pcre2_match_data_create_from_pattern_32(c, gctx);
  215. int res = pcre2_match_32(c, s, length, p_offset, 0, match, mctx);
  216. if (res < 0) {
  217. pcre2_match_data_free_32(match);
  218. pcre2_match_context_free_32(mctx);
  219. return nullptr;
  220. }
  221. uint32_t size = pcre2_get_ovector_count_32(match);
  222. PCRE2_SIZE *ovector = pcre2_get_ovector_pointer_32(match);
  223. result->data.resize(size);
  224. for (uint32_t i = 0; i < size; i++) {
  225. result->data.write[i].start = ovector[i * 2];
  226. result->data.write[i].end = ovector[i * 2 + 1];
  227. }
  228. pcre2_match_data_free_32(match);
  229. pcre2_match_context_free_32(mctx);
  230. }
  231. result->subject = p_subject;
  232. uint32_t count;
  233. const CharType *table;
  234. uint32_t entry_size;
  235. _pattern_info(PCRE2_INFO_NAMECOUNT, &count);
  236. _pattern_info(PCRE2_INFO_NAMETABLE, &table);
  237. _pattern_info(PCRE2_INFO_NAMEENTRYSIZE, &entry_size);
  238. for (uint32_t i = 0; i < count; i++) {
  239. CharType id = table[i * entry_size];
  240. if (result->data[id].start == -1) {
  241. continue;
  242. }
  243. String name = &table[i * entry_size + 1];
  244. if (result->names.has(name)) {
  245. continue;
  246. }
  247. result->names.insert(name, id);
  248. }
  249. return result;
  250. }
  251. Array RegEx::search_all(const String &p_subject, int p_offset, int p_end) const {
  252. int last_end = -1;
  253. Array result;
  254. Ref<RegExMatch> match = search(p_subject, p_offset, p_end);
  255. while (match.is_valid()) {
  256. if (last_end == match->get_end(0)) {
  257. break;
  258. }
  259. result.push_back(match);
  260. last_end = match->get_end(0);
  261. match = search(p_subject, match->get_end(0), p_end);
  262. }
  263. return result;
  264. }
  265. String RegEx::sub(const String &p_subject, const String &p_replacement, bool p_all, int p_offset, int p_end) const {
  266. ERR_FAIL_COND_V(!is_valid(), String());
  267. // safety_zone is the number of chars we allocate in addition to the number of chars expected in order to
  268. // guard against the PCRE API writing one additional \0 at the end. PCRE's API docs are unclear on whether
  269. // PCRE understands outlength in pcre2_substitute() as counting an implicit additional terminating char or
  270. // not. always allocating one char more than telling PCRE has us on the safe side.
  271. const int safety_zone = 1;
  272. PCRE2_SIZE olength = p_subject.length() + 1; // space for output string and one terminating \0 character
  273. Vector<CharType> output;
  274. output.resize(olength + safety_zone);
  275. uint32_t flags = PCRE2_SUBSTITUTE_OVERFLOW_LENGTH;
  276. if (p_all) {
  277. flags |= PCRE2_SUBSTITUTE_GLOBAL;
  278. }
  279. PCRE2_SIZE length = p_subject.length();
  280. if (p_end >= 0 && (uint32_t)p_end < length) {
  281. length = p_end;
  282. }
  283. if (sizeof(CharType) == 2) {
  284. pcre2_code_16 *c = (pcre2_code_16 *)code;
  285. pcre2_general_context_16 *gctx = (pcre2_general_context_16 *)general_ctx;
  286. pcre2_match_context_16 *mctx = pcre2_match_context_create_16(gctx);
  287. PCRE2_SPTR16 s = (PCRE2_SPTR16)p_subject.c_str();
  288. PCRE2_SPTR16 r = (PCRE2_SPTR16)p_replacement.c_str();
  289. PCRE2_UCHAR16 *o = (PCRE2_UCHAR16 *)output.ptrw();
  290. pcre2_match_data_16 *match = pcre2_match_data_create_from_pattern_16(c, gctx);
  291. int res = pcre2_substitute_16(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
  292. if (res == PCRE2_ERROR_NOMEMORY) {
  293. output.resize(olength + safety_zone);
  294. o = (PCRE2_UCHAR16 *)output.ptrw();
  295. res = pcre2_substitute_16(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
  296. }
  297. pcre2_match_data_free_16(match);
  298. pcre2_match_context_free_16(mctx);
  299. if (res < 0) {
  300. return String();
  301. }
  302. } else {
  303. pcre2_code_32 *c = (pcre2_code_32 *)code;
  304. pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
  305. pcre2_match_context_32 *mctx = pcre2_match_context_create_32(gctx);
  306. PCRE2_SPTR32 s = (PCRE2_SPTR32)p_subject.c_str();
  307. PCRE2_SPTR32 r = (PCRE2_SPTR32)p_replacement.c_str();
  308. PCRE2_UCHAR32 *o = (PCRE2_UCHAR32 *)output.ptrw();
  309. pcre2_match_data_32 *match = pcre2_match_data_create_from_pattern_32(c, gctx);
  310. int res = pcre2_substitute_32(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
  311. if (res == PCRE2_ERROR_NOMEMORY) {
  312. output.resize(olength + safety_zone);
  313. o = (PCRE2_UCHAR32 *)output.ptrw();
  314. res = pcre2_substitute_32(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
  315. }
  316. pcre2_match_data_free_32(match);
  317. pcre2_match_context_free_32(mctx);
  318. if (res < 0) {
  319. return String();
  320. }
  321. }
  322. return String(output.ptr(), olength);
  323. }
  324. bool RegEx::is_valid() const {
  325. return (code != nullptr);
  326. }
  327. String RegEx::get_pattern() const {
  328. return pattern;
  329. }
  330. int RegEx::get_group_count() const {
  331. ERR_FAIL_COND_V(!is_valid(), 0);
  332. uint32_t count;
  333. _pattern_info(PCRE2_INFO_CAPTURECOUNT, &count);
  334. return count;
  335. }
  336. Array RegEx::get_names() const {
  337. Array result;
  338. ERR_FAIL_COND_V(!is_valid(), result);
  339. uint32_t count;
  340. const CharType *table;
  341. uint32_t entry_size;
  342. _pattern_info(PCRE2_INFO_NAMECOUNT, &count);
  343. _pattern_info(PCRE2_INFO_NAMETABLE, &table);
  344. _pattern_info(PCRE2_INFO_NAMEENTRYSIZE, &entry_size);
  345. for (uint32_t i = 0; i < count; i++) {
  346. String name = &table[i * entry_size + 1];
  347. if (result.find(name) < 0) {
  348. result.append(name);
  349. }
  350. }
  351. return result;
  352. }
  353. RegEx::RegEx() {
  354. if (sizeof(CharType) == 2) {
  355. general_ctx = pcre2_general_context_create_16(&_regex_malloc, &_regex_free, nullptr);
  356. } else {
  357. general_ctx = pcre2_general_context_create_32(&_regex_malloc, &_regex_free, nullptr);
  358. }
  359. code = nullptr;
  360. }
  361. RegEx::RegEx(const String &p_pattern) {
  362. if (sizeof(CharType) == 2) {
  363. general_ctx = pcre2_general_context_create_16(&_regex_malloc, &_regex_free, nullptr);
  364. } else {
  365. general_ctx = pcre2_general_context_create_32(&_regex_malloc, &_regex_free, nullptr);
  366. }
  367. code = nullptr;
  368. compile(p_pattern);
  369. }
  370. RegEx::~RegEx() {
  371. if (sizeof(CharType) == 2) {
  372. if (code) {
  373. pcre2_code_free_16((pcre2_code_16 *)code);
  374. }
  375. pcre2_general_context_free_16((pcre2_general_context_16 *)general_ctx);
  376. } else {
  377. if (code) {
  378. pcre2_code_free_32((pcre2_code_32 *)code);
  379. }
  380. pcre2_general_context_free_32((pcre2_general_context_32 *)general_ctx);
  381. }
  382. }
  383. void RegEx::_bind_methods() {
  384. ClassDB::bind_method(D_METHOD("clear"), &RegEx::clear);
  385. ClassDB::bind_method(D_METHOD("compile", "pattern"), &RegEx::compile);
  386. ClassDB::bind_method(D_METHOD("search", "subject", "offset", "end"), &RegEx::search, DEFVAL(0), DEFVAL(-1));
  387. ClassDB::bind_method(D_METHOD("search_all", "subject", "offset", "end"), &RegEx::search_all, DEFVAL(0), DEFVAL(-1));
  388. ClassDB::bind_method(D_METHOD("sub", "subject", "replacement", "all", "offset", "end"), &RegEx::sub, DEFVAL(false), DEFVAL(0), DEFVAL(-1));
  389. ClassDB::bind_method(D_METHOD("is_valid"), &RegEx::is_valid);
  390. ClassDB::bind_method(D_METHOD("get_pattern"), &RegEx::get_pattern);
  391. ClassDB::bind_method(D_METHOD("get_group_count"), &RegEx::get_group_count);
  392. ClassDB::bind_method(D_METHOD("get_names"), &RegEx::get_names);
  393. }