regex.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. /*************************************************************************/
  2. /* regex.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  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. memfree(ptr);
  40. }
  41. int RegExMatch::_find(const Variant &p_name) const {
  42. if (p_name.is_num()) {
  43. int i = (int)p_name;
  44. if (i >= data.size())
  45. return -1;
  46. return i;
  47. } else if (p_name.get_type() == Variant::STRING) {
  48. const Map<String, int>::Element *found = names.find((String)p_name);
  49. if (found)
  50. return found->value();
  51. }
  52. return -1;
  53. }
  54. String RegExMatch::get_subject() const {
  55. return subject;
  56. }
  57. int RegExMatch::get_group_count() const {
  58. if (data.size() == 0)
  59. return 0;
  60. return data.size() - 1;
  61. }
  62. Dictionary RegExMatch::get_names() const {
  63. Dictionary result;
  64. for (const Map<String, int>::Element *i = names.front(); i != NULL; i = i->next()) {
  65. result[i->key()] = i->value();
  66. }
  67. return result;
  68. }
  69. Array RegExMatch::get_strings() const {
  70. Array result;
  71. int size = data.size();
  72. for (int i = 0; i < size; i++) {
  73. int start = data[i].start;
  74. if (start == -1) {
  75. result.append(String());
  76. continue;
  77. }
  78. int length = data[i].end - start;
  79. result.append(subject.substr(start, length));
  80. }
  81. return result;
  82. }
  83. String RegExMatch::get_string(const Variant &p_name) const {
  84. int id = _find(p_name);
  85. if (id < 0)
  86. return String();
  87. int start = data[id].start;
  88. if (start == -1)
  89. return String();
  90. int length = data[id].end - start;
  91. return subject.substr(start, length);
  92. }
  93. int RegExMatch::get_start(const Variant &p_name) const {
  94. int id = _find(p_name);
  95. if (id < 0)
  96. return -1;
  97. return data[id].start;
  98. }
  99. int RegExMatch::get_end(const Variant &p_name) const {
  100. int id = _find(p_name);
  101. if (id < 0)
  102. return -1;
  103. return data[id].end;
  104. }
  105. void RegExMatch::_bind_methods() {
  106. ClassDB::bind_method(D_METHOD("get_subject"), &RegExMatch::get_subject);
  107. ClassDB::bind_method(D_METHOD("get_group_count"), &RegExMatch::get_group_count);
  108. ClassDB::bind_method(D_METHOD("get_names"), &RegExMatch::get_names);
  109. ClassDB::bind_method(D_METHOD("get_strings"), &RegExMatch::get_strings);
  110. ClassDB::bind_method(D_METHOD("get_string", "name"), &RegExMatch::get_string, DEFVAL(0));
  111. ClassDB::bind_method(D_METHOD("get_start", "name"), &RegExMatch::get_start, DEFVAL(0));
  112. ClassDB::bind_method(D_METHOD("get_end", "name"), &RegExMatch::get_end, DEFVAL(0));
  113. ADD_PROPERTY(PropertyInfo(Variant::STRING, "subject"), "", "get_subject");
  114. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "names"), "", "get_names");
  115. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "strings"), "", "get_strings");
  116. }
  117. void RegEx::_pattern_info(uint32_t what, void *where) const {
  118. if (sizeof(CharType) == 2) {
  119. pcre2_pattern_info_16((pcre2_code_16 *)code, what, where);
  120. } else {
  121. pcre2_pattern_info_32((pcre2_code_32 *)code, what, where);
  122. }
  123. }
  124. void RegEx::clear() {
  125. if (sizeof(CharType) == 2) {
  126. if (code) {
  127. pcre2_code_free_16((pcre2_code_16 *)code);
  128. code = NULL;
  129. }
  130. } else {
  131. if (code) {
  132. pcre2_code_free_32((pcre2_code_32 *)code);
  133. code = NULL;
  134. }
  135. }
  136. }
  137. Error RegEx::compile(const String &p_pattern) {
  138. pattern = p_pattern;
  139. clear();
  140. int err;
  141. PCRE2_SIZE offset;
  142. uint32_t flags = PCRE2_DUPNAMES;
  143. if (sizeof(CharType) == 2) {
  144. pcre2_general_context_16 *gctx = (pcre2_general_context_16 *)general_ctx;
  145. pcre2_compile_context_16 *cctx = pcre2_compile_context_create_16(gctx);
  146. PCRE2_SPTR16 p = (PCRE2_SPTR16)pattern.c_str();
  147. code = pcre2_compile_16(p, pattern.length(), flags, &err, &offset, cctx);
  148. pcre2_compile_context_free_16(cctx);
  149. if (!code) {
  150. PCRE2_UCHAR16 buf[256];
  151. pcre2_get_error_message_16(err, buf, 256);
  152. String message = String::num(offset) + ": " + String((const CharType *)buf);
  153. ERR_PRINT(message.utf8());
  154. return FAILED;
  155. }
  156. } else {
  157. pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
  158. pcre2_compile_context_32 *cctx = pcre2_compile_context_create_32(gctx);
  159. PCRE2_SPTR32 p = (PCRE2_SPTR32)pattern.c_str();
  160. code = pcre2_compile_32(p, pattern.length(), flags, &err, &offset, cctx);
  161. pcre2_compile_context_free_32(cctx);
  162. if (!code) {
  163. PCRE2_UCHAR32 buf[256];
  164. pcre2_get_error_message_32(err, buf, 256);
  165. String message = String::num(offset) + ": " + String((const CharType *)buf);
  166. ERR_PRINT(message.utf8());
  167. return FAILED;
  168. }
  169. }
  170. return OK;
  171. }
  172. Ref<RegExMatch> RegEx::search(const String &p_subject, int p_offset, int p_end) const {
  173. ERR_FAIL_COND_V(!is_valid(), NULL);
  174. Ref<RegExMatch> result = memnew(RegExMatch);
  175. int length = p_subject.length();
  176. if (p_end >= 0 && p_end < length)
  177. length = p_end;
  178. if (sizeof(CharType) == 2) {
  179. pcre2_code_16 *c = (pcre2_code_16 *)code;
  180. pcre2_general_context_16 *gctx = (pcre2_general_context_16 *)general_ctx;
  181. pcre2_match_context_16 *mctx = pcre2_match_context_create_16(gctx);
  182. PCRE2_SPTR16 s = (PCRE2_SPTR16)p_subject.c_str();
  183. pcre2_match_data_16 *match = pcre2_match_data_create_from_pattern_16(c, gctx);
  184. int res = pcre2_match_16(c, s, length, p_offset, 0, match, mctx);
  185. if (res < 0) {
  186. pcre2_match_data_free_16(match);
  187. return NULL;
  188. }
  189. uint32_t size = pcre2_get_ovector_count_16(match);
  190. PCRE2_SIZE *ovector = pcre2_get_ovector_pointer_16(match);
  191. result->data.resize(size);
  192. for (uint32_t i = 0; i < size; i++) {
  193. result->data.write[i].start = ovector[i * 2];
  194. result->data.write[i].end = ovector[i * 2 + 1];
  195. }
  196. pcre2_match_data_free_16(match);
  197. pcre2_match_context_free_16(mctx);
  198. } else {
  199. pcre2_code_32 *c = (pcre2_code_32 *)code;
  200. pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
  201. pcre2_match_context_32 *mctx = pcre2_match_context_create_32(gctx);
  202. PCRE2_SPTR32 s = (PCRE2_SPTR32)p_subject.c_str();
  203. pcre2_match_data_32 *match = pcre2_match_data_create_from_pattern_32(c, gctx);
  204. int res = pcre2_match_32(c, s, length, p_offset, 0, match, mctx);
  205. if (res < 0) {
  206. pcre2_match_data_free_32(match);
  207. pcre2_match_context_free_32(mctx);
  208. return NULL;
  209. }
  210. uint32_t size = pcre2_get_ovector_count_32(match);
  211. PCRE2_SIZE *ovector = pcre2_get_ovector_pointer_32(match);
  212. result->data.resize(size);
  213. for (uint32_t i = 0; i < size; i++) {
  214. result->data.write[i].start = ovector[i * 2];
  215. result->data.write[i].end = ovector[i * 2 + 1];
  216. }
  217. pcre2_match_data_free_32(match);
  218. pcre2_match_context_free_32(mctx);
  219. }
  220. result->subject = p_subject;
  221. uint32_t count;
  222. const CharType *table;
  223. uint32_t entry_size;
  224. _pattern_info(PCRE2_INFO_NAMECOUNT, &count);
  225. _pattern_info(PCRE2_INFO_NAMETABLE, &table);
  226. _pattern_info(PCRE2_INFO_NAMEENTRYSIZE, &entry_size);
  227. for (uint32_t i = 0; i < count; i++) {
  228. CharType id = table[i * entry_size];
  229. if (result->data[id].start == -1)
  230. continue;
  231. String name = &table[i * entry_size + 1];
  232. if (result->names.has(name))
  233. continue;
  234. result->names.insert(name, id);
  235. }
  236. return result;
  237. }
  238. Array RegEx::search_all(const String &p_subject, int p_offset, int p_end) const {
  239. int last_end = -1;
  240. Array result;
  241. Ref<RegExMatch> match = search(p_subject, p_offset, p_end);
  242. while (match.is_valid()) {
  243. if (last_end == match->get_end(0))
  244. break;
  245. result.push_back(match);
  246. last_end = match->get_end(0);
  247. match = search(p_subject, match->get_end(0), p_end);
  248. }
  249. return result;
  250. }
  251. String RegEx::sub(const String &p_subject, const String &p_replacement, bool p_all, int p_offset, int p_end) const {
  252. ERR_FAIL_COND_V(!is_valid(), String());
  253. // safety_zone is the number of chars we allocate in addition to the number of chars expected in order to
  254. // guard against the PCRE API writing one additional \0 at the end. PCRE's API docs are unclear on whether
  255. // PCRE understands outlength in pcre2_substitute() as counting an implicit additional terminating char or
  256. // not. always allocating one char more than telling PCRE has us on the safe side.
  257. const int safety_zone = 1;
  258. PCRE2_SIZE olength = p_subject.length() + 1; // space for output string and one terminating \0 character
  259. Vector<CharType> output;
  260. output.resize(olength + safety_zone);
  261. uint32_t flags = PCRE2_SUBSTITUTE_OVERFLOW_LENGTH;
  262. if (p_all)
  263. flags |= PCRE2_SUBSTITUTE_GLOBAL;
  264. PCRE2_SIZE length = p_subject.length();
  265. if (p_end >= 0 && (uint32_t)p_end < length)
  266. length = p_end;
  267. if (sizeof(CharType) == 2) {
  268. pcre2_code_16 *c = (pcre2_code_16 *)code;
  269. pcre2_general_context_16 *gctx = (pcre2_general_context_16 *)general_ctx;
  270. pcre2_match_context_16 *mctx = pcre2_match_context_create_16(gctx);
  271. PCRE2_SPTR16 s = (PCRE2_SPTR16)p_subject.c_str();
  272. PCRE2_SPTR16 r = (PCRE2_SPTR16)p_replacement.c_str();
  273. PCRE2_UCHAR16 *o = (PCRE2_UCHAR16 *)output.ptrw();
  274. pcre2_match_data_16 *match = pcre2_match_data_create_from_pattern_16(c, gctx);
  275. int res = pcre2_substitute_16(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
  276. if (res == PCRE2_ERROR_NOMEMORY) {
  277. output.resize(olength + safety_zone);
  278. o = (PCRE2_UCHAR16 *)output.ptrw();
  279. res = pcre2_substitute_16(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
  280. }
  281. pcre2_match_data_free_16(match);
  282. pcre2_match_context_free_16(mctx);
  283. if (res < 0)
  284. return String();
  285. } else {
  286. pcre2_code_32 *c = (pcre2_code_32 *)code;
  287. pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
  288. pcre2_match_context_32 *mctx = pcre2_match_context_create_32(gctx);
  289. PCRE2_SPTR32 s = (PCRE2_SPTR32)p_subject.c_str();
  290. PCRE2_SPTR32 r = (PCRE2_SPTR32)p_replacement.c_str();
  291. PCRE2_UCHAR32 *o = (PCRE2_UCHAR32 *)output.ptrw();
  292. pcre2_match_data_32 *match = pcre2_match_data_create_from_pattern_32(c, gctx);
  293. int res = pcre2_substitute_32(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
  294. if (res == PCRE2_ERROR_NOMEMORY) {
  295. output.resize(olength + safety_zone);
  296. o = (PCRE2_UCHAR32 *)output.ptrw();
  297. res = pcre2_substitute_32(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
  298. }
  299. pcre2_match_data_free_32(match);
  300. pcre2_match_context_free_32(mctx);
  301. if (res < 0)
  302. return String();
  303. }
  304. return String(output.ptr(), olength);
  305. }
  306. bool RegEx::is_valid() const {
  307. return (code != NULL);
  308. }
  309. String RegEx::get_pattern() const {
  310. return pattern;
  311. }
  312. int RegEx::get_group_count() const {
  313. ERR_FAIL_COND_V(!is_valid(), 0);
  314. uint32_t count;
  315. _pattern_info(PCRE2_INFO_CAPTURECOUNT, &count);
  316. return count;
  317. }
  318. Array RegEx::get_names() const {
  319. Array result;
  320. ERR_FAIL_COND_V(!is_valid(), result);
  321. uint32_t count;
  322. const CharType *table;
  323. uint32_t entry_size;
  324. _pattern_info(PCRE2_INFO_NAMECOUNT, &count);
  325. _pattern_info(PCRE2_INFO_NAMETABLE, &table);
  326. _pattern_info(PCRE2_INFO_NAMEENTRYSIZE, &entry_size);
  327. for (uint32_t i = 0; i < count; i++) {
  328. String name = &table[i * entry_size + 1];
  329. if (result.find(name) < 0) {
  330. result.append(name);
  331. }
  332. }
  333. return result;
  334. }
  335. RegEx::RegEx() {
  336. if (sizeof(CharType) == 2) {
  337. general_ctx = pcre2_general_context_create_16(&_regex_malloc, &_regex_free, NULL);
  338. } else {
  339. general_ctx = pcre2_general_context_create_32(&_regex_malloc, &_regex_free, NULL);
  340. }
  341. code = NULL;
  342. }
  343. RegEx::RegEx(const String &p_pattern) {
  344. if (sizeof(CharType) == 2) {
  345. general_ctx = pcre2_general_context_create_16(&_regex_malloc, &_regex_free, NULL);
  346. } else {
  347. general_ctx = pcre2_general_context_create_32(&_regex_malloc, &_regex_free, NULL);
  348. }
  349. code = NULL;
  350. compile(p_pattern);
  351. }
  352. RegEx::~RegEx() {
  353. if (sizeof(CharType) == 2) {
  354. if (code)
  355. pcre2_code_free_16((pcre2_code_16 *)code);
  356. pcre2_general_context_free_16((pcre2_general_context_16 *)general_ctx);
  357. } else {
  358. if (code)
  359. pcre2_code_free_32((pcre2_code_32 *)code);
  360. pcre2_general_context_free_32((pcre2_general_context_32 *)general_ctx);
  361. }
  362. }
  363. void RegEx::_bind_methods() {
  364. ClassDB::bind_method(D_METHOD("clear"), &RegEx::clear);
  365. ClassDB::bind_method(D_METHOD("compile", "pattern"), &RegEx::compile);
  366. ClassDB::bind_method(D_METHOD("search", "subject", "offset", "end"), &RegEx::search, DEFVAL(0), DEFVAL(-1));
  367. ClassDB::bind_method(D_METHOD("search_all", "subject", "offset", "end"), &RegEx::search_all, DEFVAL(0), DEFVAL(-1));
  368. ClassDB::bind_method(D_METHOD("sub", "subject", "replacement", "all", "offset", "end"), &RegEx::sub, DEFVAL(false), DEFVAL(0), DEFVAL(-1));
  369. ClassDB::bind_method(D_METHOD("is_valid"), &RegEx::is_valid);
  370. ClassDB::bind_method(D_METHOD("get_pattern"), &RegEx::get_pattern);
  371. ClassDB::bind_method(D_METHOD("get_group_count"), &RegEx::get_group_count);
  372. ClassDB::bind_method(D_METHOD("get_names"), &RegEx::get_names);
  373. }