regex.cpp 11 KB

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