Debian Codegraph @

modules/regex/regex.cpp

raw symbols SCIP
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
31 #include "regex.h"
32 #include "regex.compat.inc"
33
34 #include "core/os/memory.h"
35
36 extern "C" {
37 #include <pcre2.h>
38 }
39
40 static void *_regex_malloc(PCRE2_SIZE size, void *user) {
41 return memalloc(size);
42 }
43
44 static void _regex_free(void *ptr, void *user) {
45 if (ptr) {
46 memfree(ptr);
47 }
48 }
49
50 int RegExMatch::_find(const Variant &p_name) const {
51 if (p_name.is_num()) {
52 int i = (int)p_name;
53 if (i >= data.size()) {
54 return -1;
55 }
56 return i;
57 } else if (p_name.is_string()) {
58 HashMap<String, int>::ConstIterator found = names.find(p_name);
59 if (found) {
60 return found->value;
61 }
62 }
63
64 return -1;
65 }
66
67 String RegExMatch::get_subject() const {
68 return subject;
69 }
70
71 int RegExMatch::get_group_count() const {
72 if (data.is_empty()) {
73 return 0;
74 }
75 return data.size() - 1;
76 }
77
78 Dictionary RegExMatch::get_names() const {
79 Dictionary result;
80
81 for (const KeyValue<String, int> &E : names) {
82 result[E.key] = E.value;
83 }
84
85 return result;
86 }
87
88 PackedStringArray RegExMatch::get_strings() const {
89 PackedStringArray result;
90
91 int size = data.size();
92
93 for (int i = 0; i < size; i++) {
94 int start = data[i].start;
95
96 if (start == -1) {
97 result.append(String());
98 continue;
99 }
100
101 int length = data[i].end - start;
102
103 result.append(subject.substr(start, length));
104 }
105
106 return result;
107 }
108
109 String RegExMatch::get_string(const Variant &p_name) const {
110 int id = _find(p_name);
111
112 if (id < 0) {
113 return String();
114 }
115
116 int start = data[id].start;
117
118 if (start == -1) {
119 return String();
120 }
121
122 int length = data[id].end - start;
123
124 return subject.substr(start, length);
125 }
126
127 int RegExMatch::get_start(const Variant &p_name) const {
128 int id = _find(p_name);
129
130 if (id < 0) {
131 return -1;
132 }
133
134 return data[id].start;
135 }
136
137 int RegExMatch::get_end(const Variant &p_name) const {
138 int id = _find(p_name);
139
140 if (id < 0) {
141 return -1;
142 }
143
144 return data[id].end;
145 }
146
147 void RegExMatch::_bind_methods() {
148 ClassDB::bind_method(D_METHOD("get_subject"), &RegExMatch::get_subject);
149 ClassDB::bind_method(D_METHOD("get_group_count"), &RegExMatch::get_group_count);
150 ClassDB::bind_method(D_METHOD("get_names"), &RegExMatch::get_names);
151 ClassDB::bind_method(D_METHOD("get_strings"), &RegExMatch::get_strings);
152 ClassDB::bind_method(D_METHOD("get_string", "name"), &RegExMatch::get_string, DEFVAL(0));
153 ClassDB::bind_method(D_METHOD("get_start", "name"), &RegExMatch::get_start, DEFVAL(0));
154 ClassDB::bind_method(D_METHOD("get_end", "name"), &RegExMatch::get_end, DEFVAL(0));
155
156 ADD_PROPERTY(PropertyInfo(Variant::STRING, "subject"), "", "get_subject");
157 ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "names"), "", "get_names");
158 ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "strings"), "", "get_strings");
159 }
160
161 void RegEx::_pattern_info(uint32_t what, void *where) const {
162 pcre2_pattern_info_32((pcre2_code_32 *)code, what, where);
163 }
164
165 Ref<RegEx> RegEx::create_from_string(const String &p_pattern, bool p_show_error) {
166 Ref<RegEx> ret;
167 ret.instantiate();
168 ret->compile(p_pattern, p_show_error);
169 return ret;
170 }
171
172 void RegEx::clear() {
173 if (code) {
174 pcre2_code_free_32((pcre2_code_32 *)code);
175 code = nullptr;
176 }
177 }
178
179 Error RegEx::compile(const String &p_pattern, bool p_show_error) {
180 pattern = p_pattern;
181 clear();
182
183 int err;
184 PCRE2_SIZE offset;
185 uint32_t flags = PCRE2_DUPNAMES;
186
187 pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
188 pcre2_compile_context_32 *cctx = pcre2_compile_context_create_32(gctx);
189 PCRE2_SPTR32 p = (PCRE2_SPTR32)pattern.get_data();
190
191 code = pcre2_compile_32(p, pattern.length(), flags, &err, &offset, cctx);
192
193 pcre2_compile_context_free_32(cctx);
194
195 if (!code) {
196 if (p_show_error) {
197 PCRE2_UCHAR32 buf[256];
198 pcre2_get_error_message_32(err, buf, 256);
199 String message = String::num_int64(offset) + ": " + String((const char32_t *)buf);
200 ERR_PRINT(message);
201 }
202 return FAILED;
203 }
204 return OK;
205 }
206
207 Ref<RegExMatch> RegEx::search(const String &p_subject, int p_offset, int p_end) const {
208 ERR_FAIL_COND_V(!is_valid(), nullptr);
209 ERR_FAIL_COND_V_MSG(p_offset < 0, nullptr, "RegEx search offset must be >= 0");
210
211 Ref<RegExMatch> result = memnew(RegExMatch);
212
213 int length = p_subject.length();
214 if (p_end >= 0 && p_end < length) {
215 length = p_end;
216 }
217
218 pcre2_code_32 *c = (pcre2_code_32 *)code;
219 pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
220 pcre2_match_context_32 *mctx = pcre2_match_context_create_32(gctx);
221 PCRE2_SPTR32 s = (PCRE2_SPTR32)p_subject.get_data();
222
223 pcre2_match_data_32 *match = pcre2_match_data_create_from_pattern_32(c, gctx);
224
225 int res = pcre2_match_32(c, s, length, p_offset, 0, match, mctx);
226
227 if (res < 0) {
228 pcre2_match_data_free_32(match);
229 pcre2_match_context_free_32(mctx);
230
231 return nullptr;
232 }
233
234 uint32_t size = pcre2_get_ovector_count_32(match);
235 PCRE2_SIZE *ovector = pcre2_get_ovector_pointer_32(match);
236
237 result->data.resize(size);
238
239 for (uint32_t i = 0; i < size; i++) {
240 result->data.write[i].start = ovector[i * 2];
241 result->data.write[i].end = ovector[i * 2 + 1];
242 }
243
244 pcre2_match_data_free_32(match);
245 pcre2_match_context_free_32(mctx);
246
247 result->subject = p_subject;
248
249 uint32_t count;
250 const char32_t *table;
251 uint32_t entry_size;
252
253 _pattern_info(PCRE2_INFO_NAMECOUNT, &count);
254 _pattern_info(PCRE2_INFO_NAMETABLE, &table);
255 _pattern_info(PCRE2_INFO_NAMEENTRYSIZE, &entry_size);
256
257 for (uint32_t i = 0; i < count; i++) {
258 char32_t id = table[i * entry_size];
259 if (result->data[id].start == -1) {
260 continue;
261 }
262 String name = &table[i * entry_size + 1];
263 if (result->names.has(name)) {
264 continue;
265 }
266
267 result->names.insert(name, id);
268 }
269
270 return result;
271 }
272
273 TypedArray<RegExMatch> RegEx::search_all(const String &p_subject, int p_offset, int p_end) const {
274 ERR_FAIL_COND_V_MSG(p_offset < 0, TypedArray<RegExMatch>(), "RegEx search offset must be >= 0");
275
276 int last_end = 0;
277 TypedArray<RegExMatch> result;
278 Ref<RegExMatch> match = search(p_subject, p_offset, p_end);
279
280 while (match.is_valid()) {
281 last_end = match->get_end(0);
282 if (match->get_start(0) == last_end) {
283 last_end++;
284 }
285
286 result.push_back(match);
287 match = search(p_subject, last_end, p_end);
288 }
289 return result;
290 }
291
292 int RegEx::_sub(const String &p_subject, const String &p_replacement, int p_offset, int p_end, uint32_t p_flags, String &r_output) const {
293 // `safety_zone` is the number of chars we allocate in addition to the number of chars expected in order to
294 // guard against the PCRE API writing one additional `\0` at the end. PCRE's API docs are unclear on whether
295 // PCRE understands outlength in `pcre2_substitute(`) as counting an implicit additional terminating char or
296 // not. Always allocating one char more than telling PCRE has us on the safe side.
297 const int safety_zone = 1;
298
299 PCRE2_SIZE olength = p_subject.length() + 1; // Space for output string and one terminating `\0` character.
300 Vector<char32_t> output;
301 output.resize(olength + safety_zone);
302
303 PCRE2_SIZE length = p_subject.length();
304 if (p_end >= 0 && (uint32_t)p_end < length) {
305 length = p_end;
306 }
307
308 pcre2_code_32 *c = (pcre2_code_32 *)code;
309 pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
310 pcre2_match_context_32 *mctx = pcre2_match_context_create_32(gctx);
311 PCRE2_SPTR32 s = (PCRE2_SPTR32)p_subject.get_data();
312 PCRE2_SPTR32 r = (PCRE2_SPTR32)p_replacement.get_data();
313 PCRE2_UCHAR32 *o = (PCRE2_UCHAR32 *)output.ptrw();
314
315 pcre2_match_data_32 *match = pcre2_match_data_create_from_pattern_32(c, gctx);
316
317 int res = pcre2_substitute_32(c, s, length, p_offset, p_flags, match, mctx, r, p_replacement.length(), o, &olength);
318
319 if (res == PCRE2_ERROR_NOMEMORY) {
320 output.resize(olength + safety_zone);
321 o = (PCRE2_UCHAR32 *)output.ptrw();
322 res = pcre2_substitute_32(c, s, length, p_offset, p_flags, match, mctx, r, p_replacement.length(), o, &olength);
323 }
324
325 pcre2_match_data_free_32(match);
326 pcre2_match_context_free_32(mctx);
327
328 if (res >= 0) {
329 r_output = String::utf32(Span(output.ptr(), olength)) + p_subject.substr(length);
330 }
331
332 return res;
333 }
334
335 String RegEx::sub(const String &p_subject, const String &p_replacement, bool p_all, int p_offset, int p_end) const {
336 ERR_FAIL_COND_V(!is_valid(), String());
337 ERR_FAIL_COND_V_MSG(p_offset < 0, String(), "RegEx sub offset must be >= 0");
338
339 uint32_t flags = PCRE2_SUBSTITUTE_OVERFLOW_LENGTH | PCRE2_SUBSTITUTE_UNSET_EMPTY;
340 if (p_all) {
341 flags |= PCRE2_SUBSTITUTE_GLOBAL;
342 }
343
344 String output;
345 const int res = _sub(p_subject, p_replacement, p_offset, p_end, flags, output);
346
347 if (res < 0) {
348 PCRE2_UCHAR32 buf[256];
349 pcre2_get_error_message_32(res, buf, 256);
350 String message = "PCRE2 Error: " + String((const char32_t *)buf);
351 ERR_PRINT(message);
352
353 if (res == PCRE2_ERROR_NOSUBSTRING) {
354 flags |= PCRE2_SUBSTITUTE_UNKNOWN_UNSET;
355 _sub(p_subject, p_replacement, p_offset, p_end, flags, output);
356 }
357 }
358
359 return output;
360 }
361
362 bool RegEx::is_valid() const {
363 return (code != nullptr);
364 }
365
366 String RegEx::get_pattern() const {
367 return pattern;
368 }
369
370 int RegEx::get_group_count() const {
371 ERR_FAIL_COND_V(!is_valid(), 0);
372
373 uint32_t count;
374
375 _pattern_info(PCRE2_INFO_CAPTURECOUNT, &count);
376
377 return count;
378 }
379
380 PackedStringArray RegEx::get_names() const {
381 PackedStringArray result;
382
383 ERR_FAIL_COND_V(!is_valid(), result);
384
385 uint32_t count;
386 const char32_t *table;
387 uint32_t entry_size;
388
389 _pattern_info(PCRE2_INFO_NAMECOUNT, &count);
390 _pattern_info(PCRE2_INFO_NAMETABLE, &table);
391 _pattern_info(PCRE2_INFO_NAMEENTRYSIZE, &entry_size);
392
393 for (uint32_t i = 0; i < count; i++) {
394 String name = &table[i * entry_size + 1];
395 if (!result.has(name)) {
396 result.append(name);
397 }
398 }
399
400 return result;
401 }
402
403 RegEx::RegEx() {
404 general_ctx = pcre2_general_context_create_32(&_regex_malloc, &_regex_free, nullptr);
405 }
406
407 RegEx::RegEx(const String &p_pattern) {
408 general_ctx = pcre2_general_context_create_32(&_regex_malloc, &_regex_free, nullptr);
409 compile(p_pattern);
410 }
411
412 RegEx::~RegEx() {
413 if (code) {
414 pcre2_code_free_32((pcre2_code_32 *)code);
415 }
416 pcre2_general_context_free_32((pcre2_general_context_32 *)general_ctx);
417 }
418
419 void RegEx::_bind_methods() {
420 ClassDB::bind_static_method("RegEx", D_METHOD("create_from_string", "pattern", "show_error"), &RegEx::create_from_string, DEFVAL(true));
421
422 ClassDB::bind_method(D_METHOD("clear"), &RegEx::clear);
423 ClassDB::bind_method(D_METHOD("compile", "pattern", "show_error"), &RegEx::compile, DEFVAL(true));
424 ClassDB::bind_method(D_METHOD("search", "subject", "offset", "end"), &RegEx::search, DEFVAL(0), DEFVAL(-1));
425 ClassDB::bind_method(D_METHOD("search_all", "subject", "offset", "end"), &RegEx::search_all, DEFVAL(0), DEFVAL(-1));
426 ClassDB::bind_method(D_METHOD("sub", "subject", "replacement", "all", "offset", "end"), &RegEx::sub, DEFVAL(false), DEFVAL(0), DEFVAL(-1));
427 ClassDB::bind_method(D_METHOD("is_valid"), &RegEx::is_valid);
428 ClassDB::bind_method(D_METHOD("get_pattern"), &RegEx::get_pattern);
429 ClassDB::bind_method(D_METHOD("get_group_count"), &RegEx::get_group_count);
430 ClassDB::bind_method(D_METHOD("get_names"), &RegEx::get_names);
431 }