Debian Codegraph @

Modules/_sre/sre.c

raw
1 /*
2 * Secret Labs' Regular Expression Engine
3 *
4 * regular expression matching engine
5 *
6 * partial history:
7 * 1999-10-24 fl created (based on existing template matcher code)
8 * 2000-03-06 fl first alpha, sort of
9 * 2000-08-01 fl fixes for 1.6b1
10 * 2000-08-07 fl use PyOS_CheckStack() if available
11 * 2000-09-20 fl added expand method
12 * 2001-03-20 fl lots of fixes for 2.1b2
13 * 2001-04-15 fl export copyright as Python attribute, not global
14 * 2001-04-28 fl added __copy__ methods (work in progress)
15 * 2001-05-14 fl fixes for 1.5.2 compatibility
16 * 2001-07-01 fl added BIGCHARSET support (from Martin von Loewis)
17 * 2001-10-18 fl fixed group reset issue (from Matthew Mueller)
18 * 2001-10-20 fl added split primitive; re-enable unicode for 1.6/2.0/2.1
19 * 2001-10-21 fl added sub/subn primitive
20 * 2001-10-24 fl added finditer primitive (for 2.2 only)
21 * 2001-12-07 fl fixed memory leak in sub/subn (Guido van Rossum)
22 * 2002-11-09 fl fixed empty sub/subn return type
23 * 2003-04-18 mvl fully support 4-byte codes
24 * 2003-10-17 gn implemented non recursive scheme
25 * 2013-02-04 mrab added fullmatch primitive
26 *
27 * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved.
28 *
29 * This version of the SRE library can be redistributed under CNRI's
30 * Python 1.6 license. For any other use, please contact Secret Labs
31 * AB ([email protected]).
32 *
33 * Portions of this engine have been developed in cooperation with
34 * CNRI. Hewlett-Packard provided funding for 1.6 integration and
35 * other compatibility work.
36 */
37
38 static const char copyright[] =
39 " SRE 2.2.2 Copyright (c) 1997-2002 by Secret Labs AB ";
40
41 #include "Python.h"
42 #include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION
43 #include "pycore_dict.h" // _PyDict_Next()
44 #include "pycore_long.h" // _PyLong_GetZero()
45 #include "pycore_moduleobject.h" // _PyModule_GetState()
46 #include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
47
48 #include "sre.h" // SRE_CODE
49
50 #include <ctype.h> // tolower(), toupper(), isalnum()
51
52 #define SRE_CODE_BITS (8 * sizeof(SRE_CODE))
53
54 // On macOS, use the wide character ctype API using btowc()
55 #if defined(__APPLE__)
56 # define USE_CTYPE_WINT_T
57 #endif
58
59 static int sre_isalnum(unsigned int ch) {
60 #ifdef USE_CTYPE_WINT_T
61 return (unsigned int)iswalnum(btowc((int)ch));
62 #else
63 return (unsigned int)isalnum((int)ch);
64 #endif
65 }
66
67 static unsigned int sre_tolower(unsigned int ch) {
68 #ifdef USE_CTYPE_WINT_T
69 return (unsigned int)towlower(btowc((int)ch));
70 #else
71 return (unsigned int)tolower((int)ch);
72 #endif
73 }
74
75 static unsigned int sre_toupper(unsigned int ch) {
76 #ifdef USE_CTYPE_WINT_T
77 return (unsigned int)towupper(btowc((int)ch));
78 #else
79 return (unsigned int)toupper((int)ch);
80 #endif
81 }
82
83 /* Defining this one controls tracing:
84 * 0 -- disabled
85 * 1 -- only if the DEBUG flag set
86 * 2 -- always
87 */
88 #ifndef VERBOSE
89 # define VERBOSE 0
90 #endif
91
92 /* -------------------------------------------------------------------- */
93
94 #if defined(_MSC_VER)
95 #pragma optimize("agtw", on) /* doesn't seem to make much difference... */
96 #pragma warning(disable: 4710) /* who cares if functions are not inlined ;-) */
97 /* fastest possible local call under MSVC */
98 #define LOCAL(type) static __inline type __fastcall
99 #else
100 #define LOCAL(type) static inline type
101 #endif
102
103 /* error codes */
104 #define SRE_ERROR_ILLEGAL -1 /* illegal opcode */
105 #define SRE_ERROR_STATE -2 /* illegal state */
106 #define SRE_ERROR_RECURSION_LIMIT -3 /* runaway recursion */
107 #define SRE_ERROR_MEMORY -9 /* out of memory */
108 #define SRE_ERROR_INTERRUPTED -10 /* signal handler raised exception */
109
110 #if VERBOSE == 0
111 # define INIT_TRACE(state)
112 # define DO_TRACE 0
113 # define TRACE(v)
114 #elif VERBOSE == 1
115 # define INIT_TRACE(state) int _debug = (state)->debug
116 # define DO_TRACE (_debug)
117 # define TRACE(v) do { \
118 if (_debug) { \
119 printf v; \
120 } \
121 } while (0)
122 #elif VERBOSE == 2
123 # define INIT_TRACE(state)
124 # define DO_TRACE 1
125 # define TRACE(v) printf v
126 #else
127 # error VERBOSE must be 0, 1 or 2
128 #endif
129
130 /* -------------------------------------------------------------------- */
131 /* search engine state */
132
133 #define SRE_IS_DIGIT(ch)\
134 ((ch) <= '9' && Py_ISDIGIT(ch))
135 #define SRE_IS_SPACE(ch)\
136 ((ch) <= ' ' && Py_ISSPACE(ch))
137 #define SRE_IS_LINEBREAK(ch)\
138 ((ch) == '\n')
139 #define SRE_IS_WORD(ch)\
140 ((ch) <= 'z' && (Py_ISALNUM(ch) || (ch) == '_'))
141
142 static unsigned int sre_lower_ascii(unsigned int ch)
143 {
144 return ((ch) < 128 ? Py_TOLOWER(ch) : ch);
145 }
146
147 /* locale-specific character predicates */
148 /* !(c & ~N) == (c < N+1) for any unsigned c, this avoids
149 * warnings when c's type supports only numbers < N+1 */
150 #define SRE_LOC_IS_ALNUM(ch) (!((ch) & ~255) ? sre_isalnum((ch)) : 0)
151 #define SRE_LOC_IS_WORD(ch) (SRE_LOC_IS_ALNUM((ch)) || (ch) == '_')
152
153 static unsigned int sre_lower_locale(unsigned int ch)
154 {
155 return ((ch) < 256 ? (unsigned int)sre_tolower((ch)) : ch);
156 }
157
158 static unsigned int sre_upper_locale(unsigned int ch)
159 {
160 return ((ch) < 256 ? (unsigned int)sre_toupper((ch)) : ch);
161 }
162
163 /* unicode-specific character predicates */
164
165 #define SRE_UNI_IS_DIGIT(ch) Py_UNICODE_ISDECIMAL(ch)
166 #define SRE_UNI_IS_SPACE(ch) Py_UNICODE_ISSPACE(ch)
167 #define SRE_UNI_IS_LINEBREAK(ch) Py_UNICODE_ISLINEBREAK(ch)
168 #define SRE_UNI_IS_ALNUM(ch) Py_UNICODE_ISALNUM(ch)
169 #define SRE_UNI_IS_WORD(ch) (SRE_UNI_IS_ALNUM(ch) || (ch) == '_')
170
171 static unsigned int sre_lower_unicode(unsigned int ch)
172 {
173 return (unsigned int) Py_UNICODE_TOLOWER(ch);
174 }
175
176 static unsigned int sre_upper_unicode(unsigned int ch)
177 {
178 return (unsigned int) Py_UNICODE_TOUPPER(ch);
179 }
180
181 LOCAL(int)
182 sre_category(SRE_CODE category, unsigned int ch)
183 {
184 switch (category) {
185
186 case SRE_CATEGORY_DIGIT:
187 return SRE_IS_DIGIT(ch);
188 case SRE_CATEGORY_NOT_DIGIT:
189 return !SRE_IS_DIGIT(ch);
190 case SRE_CATEGORY_SPACE:
191 return SRE_IS_SPACE(ch);
192 case SRE_CATEGORY_NOT_SPACE:
193 return !SRE_IS_SPACE(ch);
194 case SRE_CATEGORY_WORD:
195 return SRE_IS_WORD(ch);
196 case SRE_CATEGORY_NOT_WORD:
197 return !SRE_IS_WORD(ch);
198 case SRE_CATEGORY_LINEBREAK:
199 return SRE_IS_LINEBREAK(ch);
200 case SRE_CATEGORY_NOT_LINEBREAK:
201 return !SRE_IS_LINEBREAK(ch);
202
203 case SRE_CATEGORY_LOC_WORD:
204 return SRE_LOC_IS_WORD(ch);
205 case SRE_CATEGORY_LOC_NOT_WORD:
206 return !SRE_LOC_IS_WORD(ch);
207
208 case SRE_CATEGORY_UNI_DIGIT:
209 return SRE_UNI_IS_DIGIT(ch);
210 case SRE_CATEGORY_UNI_NOT_DIGIT:
211 return !SRE_UNI_IS_DIGIT(ch);
212 case SRE_CATEGORY_UNI_SPACE:
213 return SRE_UNI_IS_SPACE(ch);
214 case SRE_CATEGORY_UNI_NOT_SPACE:
215 return !SRE_UNI_IS_SPACE(ch);
216 case SRE_CATEGORY_UNI_WORD:
217 return SRE_UNI_IS_WORD(ch);
218 case SRE_CATEGORY_UNI_NOT_WORD:
219 return !SRE_UNI_IS_WORD(ch);
220 case SRE_CATEGORY_UNI_LINEBREAK:
221 return SRE_UNI_IS_LINEBREAK(ch);
222 case SRE_CATEGORY_UNI_NOT_LINEBREAK:
223 return !SRE_UNI_IS_LINEBREAK(ch);
224 }
225 return 0;
226 }
227
228 LOCAL(int)
229 char_loc_ignore(SRE_CODE pattern, SRE_CODE ch)
230 {
231 return ch == pattern
232 || (SRE_CODE) sre_lower_locale(ch) == pattern
233 || (SRE_CODE) sre_upper_locale(ch) == pattern;
234 }
235
236
237 /* helpers */
238
239 static void
240 data_stack_dealloc(SRE_STATE* state)
241 {
242 if (state->data_stack) {
243 PyMem_Free(state->data_stack);
244 state->data_stack = NULL;
245 }
246 state->data_stack_size = state->data_stack_base = 0;
247 }
248
249 static int
250 data_stack_grow(SRE_STATE* state, Py_ssize_t size)
251 {
252 INIT_TRACE(state);
253 Py_ssize_t minsize, cursize;
254 minsize = state->data_stack_base+size;
255 cursize = state->data_stack_size;
256 if (cursize < minsize) {
257 void* stack;
258 cursize = minsize+minsize/4+1024;
259 TRACE(("allocate/grow stack %zd\n", cursize));
260 stack = PyMem_Realloc(state->data_stack, cursize);
261 if (!stack) {
262 data_stack_dealloc(state);
263 return SRE_ERROR_MEMORY;
264 }
265 state->data_stack = (char *)stack;
266 state->data_stack_size = cursize;
267 }
268 return 0;
269 }
270
271 /* memory pool functions for SRE_REPEAT, this can avoid memory
272 leak when SRE(match) function terminates abruptly.
273 state->repeat_pool_used is a doubly-linked list, so that we
274 can remove a SRE_REPEAT node from it.
275 state->repeat_pool_unused is a singly-linked list, we put/get
276 node at the head. */
277 static SRE_REPEAT *
278 repeat_pool_malloc(SRE_STATE *state)
279 {
280 SRE_REPEAT *repeat;
281
282 if (state->repeat_pool_unused) {
283 /* remove from unused pool (singly-linked list) */
284 repeat = state->repeat_pool_unused;
285 state->repeat_pool_unused = repeat->pool_next;
286 }
287 else {
288 repeat = PyMem_Malloc(sizeof(SRE_REPEAT));
289 if (!repeat) {
290 return NULL;
291 }
292 }
293
294 /* add to used pool (doubly-linked list) */
295 SRE_REPEAT *temp = state->repeat_pool_used;
296 if (temp) {
297 temp->pool_prev = repeat;
298 }
299 repeat->pool_prev = NULL;
300 repeat->pool_next = temp;
301 state->repeat_pool_used = repeat;
302
303 return repeat;
304 }
305
306 static void
307 repeat_pool_free(SRE_STATE *state, SRE_REPEAT *repeat)
308 {
309 SRE_REPEAT *prev = repeat->pool_prev;
310 SRE_REPEAT *next = repeat->pool_next;
311
312 /* remove from used pool (doubly-linked list) */
313 if (prev) {
314 prev->pool_next = next;
315 }
316 else {
317 state->repeat_pool_used = next;
318 }
319 if (next) {
320 next->pool_prev = prev;
321 }
322
323 /* add to unused pool (singly-linked list) */
324 repeat->pool_next = state->repeat_pool_unused;
325 state->repeat_pool_unused = repeat;
326 }
327
328 static void
329 repeat_pool_clear(SRE_STATE *state)
330 {
331 /* clear used pool */
332 SRE_REPEAT *next = state->repeat_pool_used;
333 state->repeat_pool_used = NULL;
334 while (next) {
335 SRE_REPEAT *temp = next;
336 next = temp->pool_next;
337 PyMem_Free(temp);
338 }
339
340 /* clear unused pool */
341 next = state->repeat_pool_unused;
342 state->repeat_pool_unused = NULL;
343 while (next) {
344 SRE_REPEAT *temp = next;
345 next = temp->pool_next;
346 PyMem_Free(temp);
347 }
348 }
349
350 /* generate 8-bit version */
351
352 #define SRE_CHAR Py_UCS1
353 #define SIZEOF_SRE_CHAR 1
354 #define SRE(F) sre_ucs1_##F
355 #include "sre_lib.h"
356
357 /* generate 16-bit unicode version */
358
359 #define SRE_CHAR Py_UCS2
360 #define SIZEOF_SRE_CHAR 2
361 #define SRE(F) sre_ucs2_##F
362 #include "sre_lib.h"
363
364 /* generate 32-bit unicode version */
365
366 #define SRE_CHAR Py_UCS4
367 #define SIZEOF_SRE_CHAR 4
368 #define SRE(F) sre_ucs4_##F
369 #include "sre_lib.h"
370
371 /* -------------------------------------------------------------------- */
372 /* factories and destructors */
373
374 /* module state */
375 typedef struct {
376 PyTypeObject *Pattern_Type;
377 PyTypeObject *Match_Type;
378 PyTypeObject *Scanner_Type;
379 PyTypeObject *Template_Type;
380 PyObject *compile_template; // reference to re._compile_template
381 } _sremodulestate;
382
383 static _sremodulestate *
384 get_sre_module_state(PyObject *m)
385 {
386 _sremodulestate *state = (_sremodulestate *)_PyModule_GetState(m);
387 assert(state);
388 return state;
389 }
390
391 static struct PyModuleDef sremodule;
392 #define get_sre_module_state_by_class(cls) \
393 (get_sre_module_state(PyType_GetModule(cls)))
394
395 /* see sre.h for object declarations */
396 static PyObject*pattern_new_match(_sremodulestate *, PatternObject*, SRE_STATE*, Py_ssize_t);
397 static PyObject *pattern_scanner(_sremodulestate *, PatternObject *, PyObject *, Py_ssize_t, Py_ssize_t);
398
399 /*[clinic input]
400 module _sre
401 class _sre.SRE_Pattern "PatternObject *" "get_sre_module_state_by_class(tp)->Pattern_Type"
402 class _sre.SRE_Match "MatchObject *" "get_sre_module_state_by_class(tp)->Match_Type"
403 class _sre.SRE_Scanner "ScannerObject *" "get_sre_module_state_by_class(tp)->Scanner_Type"
404 [clinic start generated code]*/
405 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=fe2966e32b66a231]*/
406
407 /*[clinic input]
408 _sre.getcodesize -> int
409 [clinic start generated code]*/
410
411 static int
412 _sre_getcodesize_impl(PyObject *module)
413 /*[clinic end generated code: output=e0db7ce34a6dd7b1 input=bd6f6ecf4916bb2b]*/
414 {
415 return sizeof(SRE_CODE);
416 }
417
418 /*[clinic input]
419 _sre.ascii_iscased -> bool
420
421 character: int
422 /
423
424 [clinic start generated code]*/
425
426 static int
427 _sre_ascii_iscased_impl(PyObject *module, int character)
428 /*[clinic end generated code: output=4f454b630fbd19a2 input=9f0bd952812c7ed3]*/
429 {
430 unsigned int ch = (unsigned int)character;
431 return ch < 128 && Py_ISALPHA(ch);
432 }
433
434 /*[clinic input]
435 _sre.unicode_iscased -> bool
436
437 character: int
438 /
439
440 [clinic start generated code]*/
441
442 static int
443 _sre_unicode_iscased_impl(PyObject *module, int character)
444 /*[clinic end generated code: output=9c5ddee0dc2bc258 input=51e42c3b8dddb78e]*/
445 {
446 unsigned int ch = (unsigned int)character;
447 return ch != sre_lower_unicode(ch) || ch != sre_upper_unicode(ch);
448 }
449
450 /*[clinic input]
451 _sre.ascii_tolower -> int
452
453 character: int
454 /
455
456 [clinic start generated code]*/
457
458 static int
459 _sre_ascii_tolower_impl(PyObject *module, int character)
460 /*[clinic end generated code: output=228294ed6ff2a612 input=272c609b5b61f136]*/
461 {
462 return sre_lower_ascii(character);
463 }
464
465 /*[clinic input]
466 _sre.unicode_tolower -> int
467
468 character: int
469 /
470
471 [clinic start generated code]*/
472
473 static int
474 _sre_unicode_tolower_impl(PyObject *module, int character)
475 /*[clinic end generated code: output=6422272d7d7fee65 input=91d708c5f3c2045a]*/
476 {
477 return sre_lower_unicode(character);
478 }
479
480 LOCAL(void)
481 state_reset(SRE_STATE* state)
482 {
483 /* state->mark will be set to 0 in SRE_OP_MARK dynamically. */
484 /*memset(state->mark, 0, sizeof(*state->mark) * SRE_MARK_SIZE);*/
485
486 state->lastmark = -1;
487 state->lastindex = -1;
488
489 state->repeat = NULL;
490
491 data_stack_dealloc(state);
492 }
493
494 static const void*
495 getstring(PyObject* string, Py_ssize_t* p_length,
496 int* p_isbytes, int* p_charsize,
497 Py_buffer *view)
498 {
499 /* given a python object, return a data pointer, a length (in
500 characters), and a character size. return NULL if the object
501 is not a string (or not compatible) */
502
503 /* Unicode objects do not support the buffer API. So, get the data
504 directly instead. */
505 if (PyUnicode_Check(string)) {
506 *p_length = PyUnicode_GET_LENGTH(string);
507 *p_charsize = PyUnicode_KIND(string);
508 *p_isbytes = 0;
509 return PyUnicode_DATA(string);
510 }
511
512 /* get pointer to byte string buffer */
513 if (PyObject_GetBuffer(string, view, PyBUF_SIMPLE) != 0) {
514 PyErr_Format(PyExc_TypeError, "expected string or bytes-like "
515 "object, got '%.200s'", Py_TYPE(string)->tp_name);
516 return NULL;
517 }
518
519 *p_length = view->len;
520 *p_charsize = 1;
521 *p_isbytes = 1;
522
523 if (view->buf == NULL) {
524 PyErr_SetString(PyExc_ValueError, "Buffer is NULL");
525 PyBuffer_Release(view);
526 view->buf = NULL;
527 return NULL;
528 }
529 return view->buf;
530 }
531
532 LOCAL(PyObject*)
533 state_init(SRE_STATE* state, PatternObject* pattern, PyObject* string,
534 Py_ssize_t start, Py_ssize_t end)
535 {
536 /* prepare state object */
537
538 Py_ssize_t length;
539 int isbytes, charsize;
540 const void* ptr;
541
542 memset(state, 0, sizeof(SRE_STATE));
543
544 state->mark = PyMem_New(const void *, pattern->groups * 2);
545 if (!state->mark) {
546 PyErr_NoMemory();
547 goto err;
548 }
549 state->lastmark = -1;
550 state->lastindex = -1;
551
552 state->buffer.buf = NULL;
553 ptr = getstring(string, &length, &isbytes, &charsize, &state->buffer);
554 if (!ptr)
555 goto err;
556
557 if (isbytes && pattern->isbytes == 0) {
558 PyErr_SetString(PyExc_TypeError,
559 "cannot use a string pattern on a bytes-like object");
560 goto err;
561 }
562 if (!isbytes && pattern->isbytes > 0) {
563 PyErr_SetString(PyExc_TypeError,
564 "cannot use a bytes pattern on a string-like object");
565 goto err;
566 }
567
568 /* adjust boundaries */
569 if (start < 0)
570 start = 0;
571 else if (start > length)
572 start = length;
573
574 if (end < 0)
575 end = 0;
576 else if (end > length)
577 end = length;
578
579 state->isbytes = isbytes;
580 state->charsize = charsize;
581 state->match_all = 0;
582 state->must_advance = 0;
583 state->debug = ((pattern->flags & SRE_FLAG_DEBUG) != 0);
584
585 state->beginning = ptr;
586
587 state->start = (void*) ((char*) ptr + start * state->charsize);
588 state->end = (void*) ((char*) ptr + end * state->charsize);
589
590 state->string = Py_NewRef(string);
591 state->pos = start;
592 state->endpos = end;
593
594 #ifdef Py_DEBUG
595 state->fail_after_count = pattern->fail_after_count;
596 state->fail_after_exc = pattern->fail_after_exc; // borrowed ref
597 #endif
598
599 return string;
600 err:
601 /* We add an explicit cast here because MSVC has a bug when
602 compiling C code where it believes that `const void**` cannot be
603 safely casted to `void*`, see bpo-39943 for details. */
604 PyMem_Free((void*) state->mark);
605 state->mark = NULL;
606 if (state->buffer.buf)
607 PyBuffer_Release(&state->buffer);
608 return NULL;
609 }
610
611 LOCAL(void)
612 state_fini(SRE_STATE* state)
613 {
614 if (state->buffer.buf)
615 PyBuffer_Release(&state->buffer);
616 Py_XDECREF(state->string);
617 data_stack_dealloc(state);
618 /* See above PyMem_Del for why we explicitly cast here. */
619 PyMem_Free((void*) state->mark);
620 state->mark = NULL;
621 /* SRE_REPEAT pool */
622 repeat_pool_clear(state);
623 }
624
625 /* calculate offset from start of string */
626 #define STATE_OFFSET(state, member)\
627 (((char*)(member) - (char*)(state)->beginning) / (state)->charsize)
628
629 LOCAL(PyObject*)
630 getslice(int isbytes, const void *ptr,
631 PyObject* string, Py_ssize_t start, Py_ssize_t end)
632 {
633 if (isbytes) {
634 if (PyBytes_CheckExact(string) &&
635 start == 0 && end == PyBytes_GET_SIZE(string)) {
636 return Py_NewRef(string);
637 }
638 return PyBytes_FromStringAndSize(
639 (const char *)ptr + start, end - start);
640 }
641 else {
642 return PyUnicode_Substring(string, start, end);
643 }
644 }
645
646 LOCAL(PyObject*)
647 state_getslice(SRE_STATE* state, Py_ssize_t index, PyObject* string, int empty)
648 {
649 Py_ssize_t i, j;
650
651 index = (index - 1) * 2;
652
653 if (string == Py_None || index >= state->lastmark || !state->mark[index] || !state->mark[index+1]) {
654 if (empty)
655 /* want empty string */
656 i = j = 0;
657 else {
658 Py_RETURN_NONE;
659 }
660 } else {
661 i = STATE_OFFSET(state, state->mark[index]);
662 j = STATE_OFFSET(state, state->mark[index+1]);
663
664 /* check wrong span */
665 if (i > j) {
666 PyErr_SetString(PyExc_SystemError,
667 "The span of capturing group is wrong,"
668 " please report a bug for the re module.");
669 return NULL;
670 }
671 }
672
673 return getslice(state->isbytes, state->beginning, string, i, j);
674 }
675
676 static void
677 pattern_error(Py_ssize_t status)
678 {
679 switch (status) {
680 case SRE_ERROR_RECURSION_LIMIT:
681 /* This error code seems to be unused. */
682 PyErr_SetString(
683 PyExc_RecursionError,
684 "maximum recursion limit exceeded"
685 );
686 break;
687 case SRE_ERROR_MEMORY:
688 PyErr_NoMemory();
689 break;
690 case SRE_ERROR_INTERRUPTED:
691 /* An exception has already been raised, so let it fly */
692 break;
693 default:
694 /* other error codes indicate compiler/engine bugs */
695 PyErr_SetString(
696 PyExc_RuntimeError,
697 "internal error in regular expression engine"
698 );
699 }
700 }
701
702 static int
703 pattern_traverse(PatternObject *self, visitproc visit, void *arg)
704 {
705 Py_VISIT(Py_TYPE(self));
706 Py_VISIT(self->groupindex);
707 Py_VISIT(self->indexgroup);
708 Py_VISIT(self->pattern);
709 #ifdef Py_DEBUG
710 Py_VISIT(self->fail_after_exc);
711 #endif
712 return 0;
713 }
714
715 static int
716 pattern_clear(PatternObject *self)
717 {
718 Py_CLEAR(self->groupindex);
719 Py_CLEAR(self->indexgroup);
720 Py_CLEAR(self->pattern);
721 #ifdef Py_DEBUG
722 Py_CLEAR(self->fail_after_exc);
723 #endif
724 return 0;
725 }
726
727 static void
728 pattern_dealloc(PatternObject* self)
729 {
730 PyTypeObject *tp = Py_TYPE(self);
731
732 PyObject_GC_UnTrack(self);
733 FT_CLEAR_WEAKREFS((PyObject *) self, self->weakreflist);
734 (void)pattern_clear(self);
735 tp->tp_free(self);
736 Py_DECREF(tp);
737 }
738
739 LOCAL(Py_ssize_t)
740 sre_match(SRE_STATE* state, SRE_CODE* pattern)
741 {
742 if (state->charsize == 1)
743 return sre_ucs1_match(state, pattern, 1);
744 if (state->charsize == 2)
745 return sre_ucs2_match(state, pattern, 1);
746 assert(state->charsize == 4);
747 return sre_ucs4_match(state, pattern, 1);
748 }
749
750 LOCAL(Py_ssize_t)
751 sre_search(SRE_STATE* state, SRE_CODE* pattern)
752 {
753 if (state->charsize == 1)
754 return sre_ucs1_search(state, pattern);
755 if (state->charsize == 2)
756 return sre_ucs2_search(state, pattern);
757 assert(state->charsize == 4);
758 return sre_ucs4_search(state, pattern);
759 }
760
761 /*[clinic input]
762 _sre.SRE_Pattern.match
763
764 cls: defining_class
765 /
766 string: object
767 pos: Py_ssize_t = 0
768 endpos: Py_ssize_t(c_default="PY_SSIZE_T_MAX") = sys.maxsize
769
770 Matches zero or more characters at the beginning of the string.
771 [clinic start generated code]*/
772
773 static PyObject *
774 _sre_SRE_Pattern_match_impl(PatternObject *self, PyTypeObject *cls,
775 PyObject *string, Py_ssize_t pos,
776 Py_ssize_t endpos)
777 /*[clinic end generated code: output=ec6208ea58a0cca0 input=4bdb9c3e564d13ac]*/
778 {
779 _sremodulestate *module_state = get_sre_module_state_by_class(cls);
780 SRE_STATE state;
781 Py_ssize_t status;
782 PyObject *match;
783
784 if (!state_init(&state, self, string, pos, endpos))
785 return NULL;
786
787 INIT_TRACE(&state);
788 state.ptr = state.start;
789
790 TRACE(("|%p|%p|MATCH\n", PatternObject_GetCode(self), state.ptr));
791
792 status = sre_match(&state, PatternObject_GetCode(self));
793
794 TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
795 if (PyErr_Occurred()) {
796 state_fini(&state);
797 return NULL;
798 }
799
800 match = pattern_new_match(module_state, self, &state, status);
801 state_fini(&state);
802 return match;
803 }
804
805 /*[clinic input]
806 _sre.SRE_Pattern.fullmatch
807
808 cls: defining_class
809 /
810 string: object
811 pos: Py_ssize_t = 0
812 endpos: Py_ssize_t(c_default="PY_SSIZE_T_MAX") = sys.maxsize
813
814 Matches against all of the string.
815 [clinic start generated code]*/
816
817 static PyObject *
818 _sre_SRE_Pattern_fullmatch_impl(PatternObject *self, PyTypeObject *cls,
819 PyObject *string, Py_ssize_t pos,
820 Py_ssize_t endpos)
821 /*[clinic end generated code: output=625b75b027ef94da input=50981172ab0fcfdd]*/
822 {
823 _sremodulestate *module_state = get_sre_module_state_by_class(cls);
824 SRE_STATE state;
825 Py_ssize_t status;
826 PyObject *match;
827
828 if (!state_init(&state, self, string, pos, endpos))
829 return NULL;
830
831 INIT_TRACE(&state);
832 state.ptr = state.start;
833
834 TRACE(("|%p|%p|FULLMATCH\n", PatternObject_GetCode(self), state.ptr));
835
836 state.match_all = 1;
837 status = sre_match(&state, PatternObject_GetCode(self));
838
839 TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
840 if (PyErr_Occurred()) {
841 state_fini(&state);
842 return NULL;
843 }
844
845 match = pattern_new_match(module_state, self, &state, status);
846 state_fini(&state);
847 return match;
848 }
849
850 /*[clinic input]
851 _sre.SRE_Pattern.search
852
853 cls: defining_class
854 /
855 string: object
856 pos: Py_ssize_t = 0
857 endpos: Py_ssize_t(c_default="PY_SSIZE_T_MAX") = sys.maxsize
858
859 Scan through string looking for a match, and return a corresponding match object instance.
860
861 Return None if no position in the string matches.
862 [clinic start generated code]*/
863
864 static PyObject *
865 _sre_SRE_Pattern_search_impl(PatternObject *self, PyTypeObject *cls,
866 PyObject *string, Py_ssize_t pos,
867 Py_ssize_t endpos)
868 /*[clinic end generated code: output=bd7f2d9d583e1463 input=afa9afb66a74a4b3]*/
869 {
870 _sremodulestate *module_state = get_sre_module_state_by_class(cls);
871 SRE_STATE state;
872 Py_ssize_t status;
873 PyObject *match;
874
875 if (!state_init(&state, self, string, pos, endpos))
876 return NULL;
877
878 INIT_TRACE(&state);
879 TRACE(("|%p|%p|SEARCH\n", PatternObject_GetCode(self), state.ptr));
880
881 status = sre_search(&state, PatternObject_GetCode(self));
882
883 TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
884
885 if (PyErr_Occurred()) {
886 state_fini(&state);
887 return NULL;
888 }
889
890 match = pattern_new_match(module_state, self, &state, status);
891 state_fini(&state);
892 return match;
893 }
894
895 /*[clinic input]
896 _sre.SRE_Pattern.findall
897
898 string: object
899 pos: Py_ssize_t = 0
900 endpos: Py_ssize_t(c_default="PY_SSIZE_T_MAX") = sys.maxsize
901
902 Return a list of all non-overlapping matches of pattern in string.
903 [clinic start generated code]*/
904
905 static PyObject *
906 _sre_SRE_Pattern_findall_impl(PatternObject *self, PyObject *string,
907 Py_ssize_t pos, Py_ssize_t endpos)
908 /*[clinic end generated code: output=f4966baceea60aca input=5b6a4ee799741563]*/
909 {
910 SRE_STATE state;
911 PyObject* list;
912 Py_ssize_t status;
913 Py_ssize_t i, b, e;
914
915 if (!state_init(&state, self, string, pos, endpos))
916 return NULL;
917
918 list = PyList_New(0);
919 if (!list) {
920 state_fini(&state);
921 return NULL;
922 }
923
924 while (state.start <= state.end) {
925
926 PyObject* item;
927
928 state_reset(&state);
929
930 state.ptr = state.start;
931
932 status = sre_search(&state, PatternObject_GetCode(self));
933 if (PyErr_Occurred())
934 goto error;
935
936 if (status <= 0) {
937 if (status == 0)
938 break;
939 pattern_error(status);
940 goto error;
941 }
942
943 /* don't bother to build a match object */
944 switch (self->groups) {
945 case 0:
946 b = STATE_OFFSET(&state, state.start);
947 e = STATE_OFFSET(&state, state.ptr);
948 item = getslice(state.isbytes, state.beginning,
949 string, b, e);
950 if (!item)
951 goto error;
952 break;
953 case 1:
954 item = state_getslice(&state, 1, string, 1);
955 if (!item)
956 goto error;
957 break;
958 default:
959 item = PyTuple_New(self->groups);
960 if (!item)
961 goto error;
962 for (i = 0; i < self->groups; i++) {
963 PyObject* o = state_getslice(&state, i+1, string, 1);
964 if (!o) {
965 Py_DECREF(item);
966 goto error;
967 }
968 PyTuple_SET_ITEM(item, i, o);
969 }
970 break;
971 }
972
973 status = PyList_Append(list, item);
974 Py_DECREF(item);
975 if (status < 0)
976 goto error;
977
978 state.must_advance = (state.ptr == state.start);
979 state.start = state.ptr;
980 }
981
982 state_fini(&state);
983 return list;
984
985 error:
986 Py_DECREF(list);
987 state_fini(&state);
988 return NULL;
989
990 }
991
992 /*[clinic input]
993 _sre.SRE_Pattern.finditer
994
995 cls: defining_class
996 /
997 string: object
998 pos: Py_ssize_t = 0
999 endpos: Py_ssize_t(c_default="PY_SSIZE_T_MAX") = sys.maxsize
1000
1001 Return an iterator over all non-overlapping matches for the RE pattern in string.
1002
1003 For each match, the iterator returns a match object.
1004 [clinic start generated code]*/
1005
1006 static PyObject *
1007 _sre_SRE_Pattern_finditer_impl(PatternObject *self, PyTypeObject *cls,
1008 PyObject *string, Py_ssize_t pos,
1009 Py_ssize_t endpos)
1010 /*[clinic end generated code: output=1791dbf3618ade56 input=812e332a4848cbaf]*/
1011 {
1012 _sremodulestate *module_state = get_sre_module_state_by_class(cls);
1013 PyObject* scanner;
1014 PyObject* search;
1015 PyObject* iterator;
1016
1017 scanner = pattern_scanner(module_state, self, string, pos, endpos);
1018 if (!scanner)
1019 return NULL;
1020
1021 search = PyObject_GetAttrString(scanner, "search");
1022 Py_DECREF(scanner);
1023 if (!search)
1024 return NULL;
1025
1026 iterator = PyCallIter_New(search, Py_None);
1027 Py_DECREF(search);
1028
1029 return iterator;
1030 }
1031
1032 /*[clinic input]
1033 _sre.SRE_Pattern.scanner
1034
1035 cls: defining_class
1036 /
1037 string: object
1038 pos: Py_ssize_t = 0
1039 endpos: Py_ssize_t(c_default="PY_SSIZE_T_MAX") = sys.maxsize
1040
1041 [clinic start generated code]*/
1042
1043 static PyObject *
1044 _sre_SRE_Pattern_scanner_impl(PatternObject *self, PyTypeObject *cls,
1045 PyObject *string, Py_ssize_t pos,
1046 Py_ssize_t endpos)
1047 /*[clinic end generated code: output=f70cd506112f1bd9 input=2e487e5151bcee4c]*/
1048 {
1049 _sremodulestate *module_state = get_sre_module_state_by_class(cls);
1050
1051 return pattern_scanner(module_state, self, string, pos, endpos);
1052 }
1053
1054 /*[clinic input]
1055 _sre.SRE_Pattern.split
1056
1057 string: object
1058 maxsplit: Py_ssize_t = 0
1059
1060 Split string by the occurrences of pattern.
1061 [clinic start generated code]*/
1062
1063 static PyObject *
1064 _sre_SRE_Pattern_split_impl(PatternObject *self, PyObject *string,
1065 Py_ssize_t maxsplit)
1066 /*[clinic end generated code: output=7ac66f381c45e0be input=1eeeb10dafc9947a]*/
1067 {
1068 SRE_STATE state;
1069 PyObject* list;
1070 PyObject* item;
1071 Py_ssize_t status;
1072 Py_ssize_t n;
1073 Py_ssize_t i;
1074 const void* last;
1075
1076 assert(self->codesize != 0);
1077
1078 if (!state_init(&state, self, string, 0, PY_SSIZE_T_MAX))
1079 return NULL;
1080
1081 list = PyList_New(0);
1082 if (!list) {
1083 state_fini(&state);
1084 return NULL;
1085 }
1086
1087 n = 0;
1088 last = state.start;
1089
1090 while (!maxsplit || n < maxsplit) {
1091
1092 state_reset(&state);
1093
1094 state.ptr = state.start;
1095
1096 status = sre_search(&state, PatternObject_GetCode(self));
1097 if (PyErr_Occurred())
1098 goto error;
1099
1100 if (status <= 0) {
1101 if (status == 0)
1102 break;
1103 pattern_error(status);
1104 goto error;
1105 }
1106
1107 /* get segment before this match */
1108 item = getslice(state.isbytes, state.beginning,
1109 string, STATE_OFFSET(&state, last),
1110 STATE_OFFSET(&state, state.start)
1111 );
1112 if (!item)
1113 goto error;
1114 status = PyList_Append(list, item);
1115 Py_DECREF(item);
1116 if (status < 0)
1117 goto error;
1118
1119 /* add groups (if any) */
1120 for (i = 0; i < self->groups; i++) {
1121 item = state_getslice(&state, i+1, string, 0);
1122 if (!item)
1123 goto error;
1124 status = PyList_Append(list, item);
1125 Py_DECREF(item);
1126 if (status < 0)
1127 goto error;
1128 }
1129
1130 n = n + 1;
1131 state.must_advance = (state.ptr == state.start);
1132 last = state.start = state.ptr;
1133
1134 }
1135
1136 /* get segment following last match (even if empty) */
1137 item = getslice(state.isbytes, state.beginning,
1138 string, STATE_OFFSET(&state, last), state.endpos
1139 );
1140 if (!item)
1141 goto error;
1142 status = PyList_Append(list, item);
1143 Py_DECREF(item);
1144 if (status < 0)
1145 goto error;
1146
1147 state_fini(&state);
1148 return list;
1149
1150 error:
1151 Py_DECREF(list);
1152 state_fini(&state);
1153 return NULL;
1154
1155 }
1156
1157 static PyObject *
1158 compile_template(_sremodulestate *module_state,
1159 PatternObject *pattern, PyObject *template)
1160 {
1161 /* delegate to Python code */
1162 PyObject *func = FT_ATOMIC_LOAD_PTR(module_state->compile_template);
1163 if (func == NULL) {
1164 func = _PyImport_GetModuleAttrString("re", "_compile_template");
1165 if (func == NULL) {
1166 return NULL;
1167 }
1168 #ifdef Py_GIL_DISABLED
1169 PyObject *other_func = NULL;
1170 if (!_Py_atomic_compare_exchange_ptr(&module_state->compile_template, &other_func, func)) {
1171 Py_DECREF(func);
1172 func = other_func;
1173 }
1174 #else
1175 Py_XSETREF(module_state->compile_template, func);
1176 #endif
1177 }
1178
1179 PyObject *args[] = {(PyObject *)pattern, template};
1180 PyObject *result = PyObject_Vectorcall(func, args, 2, NULL);
1181
1182 if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1183 /* If the replacement string is unhashable (e.g. bytearray),
1184 * convert it to the basic type (str or bytes) and repeat. */
1185 if (PyUnicode_Check(template) && !PyUnicode_CheckExact(template)) {
1186 PyErr_Clear();
1187 template = _PyUnicode_Copy(template);
1188 }
1189 else if (PyObject_CheckBuffer(template) && !PyBytes_CheckExact(template)) {
1190 PyErr_Clear();
1191 template = PyBytes_FromObject(template);
1192 }
1193 else {
1194 return NULL;
1195 }
1196 if (template == NULL) {
1197 return NULL;
1198 }
1199 args[1] = template;
1200 result = PyObject_Vectorcall(func, args, 2, NULL);
1201 Py_DECREF(template);
1202 }
1203
1204 if (result != NULL && Py_TYPE(result) != module_state->Template_Type) {
1205 PyErr_Format(PyExc_RuntimeError,
1206 "the result of compiling a replacement string is %.200s",
1207 Py_TYPE(result)->tp_name);
1208 Py_DECREF(result);
1209 return NULL;
1210 }
1211 return result;
1212 }
1213
1214 static PyObject *expand_template(TemplateObject *, MatchObject *); /* Forward */
1215
1216 static PyObject*
1217 pattern_subx(_sremodulestate* module_state,
1218 PatternObject* self,
1219 PyObject* ptemplate,
1220 PyObject* string,
1221 Py_ssize_t count,
1222 Py_ssize_t subn)
1223 {
1224 SRE_STATE state;
1225 PyObject* list;
1226 PyObject* joiner;
1227 PyObject* item;
1228 PyObject* filter;
1229 PyObject* match;
1230 const void* ptr;
1231 Py_ssize_t status;
1232 Py_ssize_t n;
1233 Py_ssize_t i, b, e;
1234 int isbytes, charsize;
1235 enum {LITERAL, TEMPLATE, CALLABLE} filter_type;
1236 Py_buffer view;
1237
1238 if (PyCallable_Check(ptemplate)) {
1239 /* sub/subn takes either a function or a template */
1240 filter = Py_NewRef(ptemplate);
1241 filter_type = CALLABLE;
1242 } else {
1243 /* if not callable, check if it's a literal string */
1244 int literal;
1245 view.buf = NULL;
1246 ptr = getstring(ptemplate, &n, &isbytes, &charsize, &view);
1247 if (ptr) {
1248 if (charsize == 1)
1249 literal = memchr(ptr, '\\', n) == NULL;
1250 else
1251 literal = PyUnicode_FindChar(ptemplate, '\\', 0, n, 1) == -1;
1252 } else {
1253 PyErr_Clear();
1254 literal = 0;
1255 }
1256 if (view.buf)
1257 PyBuffer_Release(&view);
1258 if (literal) {
1259 filter = Py_NewRef(ptemplate);
1260 filter_type = LITERAL;
1261 } else {
1262 /* not a literal; hand it over to the template compiler */
1263 filter = compile_template(module_state, self, ptemplate);
1264 if (!filter)
1265 return NULL;
1266
1267 assert(Py_TYPE(filter) == module_state->Template_Type);
1268 if (Py_SIZE(filter) == 0) {
1269 Py_SETREF(filter,
1270 Py_NewRef(((TemplateObject *)filter)->literal));
1271 filter_type = LITERAL;
1272 }
1273 else {
1274 filter_type = TEMPLATE;
1275 }
1276 }
1277 }
1278
1279 if (!state_init(&state, self, string, 0, PY_SSIZE_T_MAX)) {
1280 Py_DECREF(filter);
1281 return NULL;
1282 }
1283
1284 list = PyList_New(0);
1285 if (!list) {
1286 Py_DECREF(filter);
1287 state_fini(&state);
1288 return NULL;
1289 }
1290
1291 n = i = 0;
1292
1293 while (!count || n < count) {
1294
1295 state_reset(&state);
1296
1297 state.ptr = state.start;
1298
1299 status = sre_search(&state, PatternObject_GetCode(self));
1300 if (PyErr_Occurred())
1301 goto error;
1302
1303 if (status <= 0) {
1304 if (status == 0)
1305 break;
1306 pattern_error(status);
1307 goto error;
1308 }
1309
1310 b = STATE_OFFSET(&state, state.start);
1311 e = STATE_OFFSET(&state, state.ptr);
1312
1313 if (i < b) {
1314 /* get segment before this match */
1315 item = getslice(state.isbytes, state.beginning,
1316 string, i, b);
1317 if (!item)
1318 goto error;
1319 status = PyList_Append(list, item);
1320 Py_DECREF(item);
1321 if (status < 0)
1322 goto error;
1323
1324 }
1325
1326 if (filter_type != LITERAL) {
1327 /* pass match object through filter */
1328 match = pattern_new_match(module_state, self, &state, 1);
1329 if (!match)
1330 goto error;
1331 if (filter_type == TEMPLATE) {
1332 item = expand_template((TemplateObject *)filter,
1333 (MatchObject *)match);
1334 }
1335 else {
1336 assert(filter_type == CALLABLE);
1337 item = PyObject_CallOneArg(filter, match);
1338 }
1339 Py_DECREF(match);
1340 if (!item)
1341 goto error;
1342 } else {
1343 /* filter is literal string */
1344 item = Py_NewRef(filter);
1345 }
1346
1347 /* add to list */
1348 if (item != Py_None) {
1349 status = PyList_Append(list, item);
1350 Py_DECREF(item);
1351 if (status < 0)
1352 goto error;
1353 }
1354
1355 i = e;
1356 n = n + 1;
1357 state.must_advance = (state.ptr == state.start);
1358 state.start = state.ptr;
1359 }
1360
1361 /* get segment following last match */
1362 if (i < state.endpos) {
1363 item = getslice(state.isbytes, state.beginning,
1364 string, i, state.endpos);
1365 if (!item)
1366 goto error;
1367 status = PyList_Append(list, item);
1368 Py_DECREF(item);
1369 if (status < 0)
1370 goto error;
1371 }
1372
1373 state_fini(&state);
1374
1375 Py_DECREF(filter);
1376
1377 /* convert list to single string (also removes list) */
1378 joiner = getslice(state.isbytes, state.beginning, string, 0, 0);
1379 if (!joiner) {
1380 Py_DECREF(list);
1381 return NULL;
1382 }
1383 if (PyList_GET_SIZE(list) == 0) {
1384 Py_DECREF(list);
1385 item = joiner;
1386 }
1387 else {
1388 if (state.isbytes)
1389 item = _PyBytes_Join(joiner, list);
1390 else
1391 item = PyUnicode_Join(joiner, list);
1392 Py_DECREF(joiner);
1393 Py_DECREF(list);
1394 if (!item)
1395 return NULL;
1396 }
1397
1398 if (subn)
1399 return Py_BuildValue("Nn", item, n);
1400
1401 return item;
1402
1403 error:
1404 Py_DECREF(list);
1405 state_fini(&state);
1406 Py_DECREF(filter);
1407 return NULL;
1408
1409 }
1410
1411 /*[clinic input]
1412 _sre.SRE_Pattern.sub
1413
1414 cls: defining_class
1415 /
1416 repl: object
1417 string: object
1418 count: Py_ssize_t = 0
1419
1420 Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.
1421 [clinic start generated code]*/
1422
1423 static PyObject *
1424 _sre_SRE_Pattern_sub_impl(PatternObject *self, PyTypeObject *cls,
1425 PyObject *repl, PyObject *string, Py_ssize_t count)
1426 /*[clinic end generated code: output=4be141ab04bca60d input=d8d1d4ac2311a07c]*/
1427 {
1428 _sremodulestate *module_state = get_sre_module_state_by_class(cls);
1429
1430 return pattern_subx(module_state, self, repl, string, count, 0);
1431 }
1432
1433 /*[clinic input]
1434 _sre.SRE_Pattern.subn
1435
1436 cls: defining_class
1437 /
1438 repl: object
1439 string: object
1440 count: Py_ssize_t = 0
1441
1442 Return the tuple (new_string, number_of_subs_made) found by replacing the leftmost non-overlapping occurrences of pattern with the replacement repl.
1443 [clinic start generated code]*/
1444
1445 static PyObject *
1446 _sre_SRE_Pattern_subn_impl(PatternObject *self, PyTypeObject *cls,
1447 PyObject *repl, PyObject *string,
1448 Py_ssize_t count)
1449 /*[clinic end generated code: output=da02fd85258b1e1f input=8b78a65b8302e58d]*/
1450 {
1451 _sremodulestate *module_state = get_sre_module_state_by_class(cls);
1452
1453 return pattern_subx(module_state, self, repl, string, count, 1);
1454 }
1455
1456 /*[clinic input]
1457 _sre.SRE_Pattern.__copy__
1458
1459 [clinic start generated code]*/
1460
1461 static PyObject *
1462 _sre_SRE_Pattern___copy___impl(PatternObject *self)
1463 /*[clinic end generated code: output=85dedc2db1bd8694 input=a730a59d863bc9f5]*/
1464 {
1465 return Py_NewRef(self);
1466 }
1467
1468 /*[clinic input]
1469 _sre.SRE_Pattern.__deepcopy__
1470
1471 memo: object
1472 /
1473
1474 [clinic start generated code]*/
1475
1476 static PyObject *
1477 _sre_SRE_Pattern___deepcopy__(PatternObject *self, PyObject *memo)
1478 /*[clinic end generated code: output=2ad25679c1f1204a input=a465b1602f997bed]*/
1479 {
1480 return Py_NewRef(self);
1481 }
1482
1483 #ifdef Py_DEBUG
1484 /*[clinic input]
1485 _sre.SRE_Pattern._fail_after
1486
1487 count: int
1488 exception: object
1489 /
1490
1491 For debugging.
1492 [clinic start generated code]*/
1493
1494 static PyObject *
1495 _sre_SRE_Pattern__fail_after_impl(PatternObject *self, int count,
1496 PyObject *exception)
1497 /*[clinic end generated code: output=9a6bf12135ac50c2 input=ef80a45c66c5499d]*/
1498 {
1499 self->fail_after_count = count;
1500 Py_INCREF(exception);
1501 Py_XSETREF(self->fail_after_exc, exception);
1502 Py_RETURN_NONE;
1503 }
1504 #endif /* Py_DEBUG */
1505
1506 static PyObject *
1507 pattern_repr(PatternObject *obj)
1508 {
1509 static const struct {
1510 const char *name;
1511 int value;
1512 } flag_names[] = {
1513 {"re.IGNORECASE", SRE_FLAG_IGNORECASE},
1514 {"re.LOCALE", SRE_FLAG_LOCALE},
1515 {"re.MULTILINE", SRE_FLAG_MULTILINE},
1516 {"re.DOTALL", SRE_FLAG_DOTALL},
1517 {"re.UNICODE", SRE_FLAG_UNICODE},
1518 {"re.VERBOSE", SRE_FLAG_VERBOSE},
1519 {"re.DEBUG", SRE_FLAG_DEBUG},
1520 {"re.ASCII", SRE_FLAG_ASCII},
1521 };
1522 PyObject *result = NULL;
1523 PyObject *flag_items;
1524 size_t i;
1525 int flags = obj->flags;
1526
1527 /* Omit re.UNICODE for valid string patterns. */
1528 if (obj->isbytes == 0 &&
1529 (flags & (SRE_FLAG_LOCALE|SRE_FLAG_UNICODE|SRE_FLAG_ASCII)) ==
1530 SRE_FLAG_UNICODE)
1531 flags &= ~SRE_FLAG_UNICODE;
1532
1533 flag_items = PyList_New(0);
1534 if (!flag_items)
1535 return NULL;
1536
1537 for (i = 0; i < Py_ARRAY_LENGTH(flag_names); i++) {
1538 if (flags & flag_names[i].value) {
1539 PyObject *item = PyUnicode_FromString(flag_names[i].name);
1540 if (!item)
1541 goto done;
1542
1543 if (PyList_Append(flag_items, item) < 0) {
1544 Py_DECREF(item);
1545 goto done;
1546 }
1547 Py_DECREF(item);
1548 flags &= ~flag_names[i].value;
1549 }
1550 }
1551 if (flags) {
1552 PyObject *item = PyUnicode_FromFormat("0x%x", flags);
1553 if (!item)
1554 goto done;
1555
1556 if (PyList_Append(flag_items, item) < 0) {
1557 Py_DECREF(item);
1558 goto done;
1559 }
1560 Py_DECREF(item);
1561 }
1562
1563 if (PyList_Size(flag_items) > 0) {
1564 PyObject *flags_result;
1565 PyObject *sep = PyUnicode_FromString("|");
1566 if (!sep)
1567 goto done;
1568 flags_result = PyUnicode_Join(sep, flag_items);
1569 Py_DECREF(sep);
1570 if (!flags_result)
1571 goto done;
1572 result = PyUnicode_FromFormat("re.compile(%.200R, %S)",
1573 obj->pattern, flags_result);
1574 Py_DECREF(flags_result);
1575 }
1576 else {
1577 result = PyUnicode_FromFormat("re.compile(%.200R)", obj->pattern);
1578 }
1579
1580 done:
1581 Py_DECREF(flag_items);
1582 return result;
1583 }
1584
1585 PyDoc_STRVAR(pattern_doc, "Compiled regular expression object.");
1586
1587 /* PatternObject's 'groupindex' method. */
1588 static PyObject *
1589 pattern_groupindex(PatternObject *self, void *Py_UNUSED(ignored))
1590 {
1591 if (self->groupindex == NULL)
1592 return PyDict_New();
1593 return PyDictProxy_New(self->groupindex);
1594 }
1595
1596 static int _validate(PatternObject *self); /* Forward */
1597
1598 /*[clinic input]
1599 _sre.compile
1600
1601 pattern: object
1602 flags: int
1603 code: object(subclass_of='&PyList_Type')
1604 groups: Py_ssize_t
1605 groupindex: object(subclass_of='&PyDict_Type')
1606 indexgroup: object(subclass_of='&PyTuple_Type')
1607
1608 [clinic start generated code]*/
1609
1610 static PyObject *
1611 _sre_compile_impl(PyObject *module, PyObject *pattern, int flags,
1612 PyObject *code, Py_ssize_t groups, PyObject *groupindex,
1613 PyObject *indexgroup)
1614 /*[clinic end generated code: output=ef9c2b3693776404 input=0a68476dbbe5db30]*/
1615 {
1616 /* "compile" pattern descriptor to pattern object */
1617
1618 _sremodulestate *module_state = get_sre_module_state(module);
1619 PatternObject* self;
1620 Py_ssize_t i, n;
1621
1622 n = PyList_GET_SIZE(code);
1623 /* coverity[ampersand_in_size] */
1624 self = PyObject_GC_NewVar(PatternObject, module_state->Pattern_Type, n);
1625 if (!self)
1626 return NULL;
1627 self->weakreflist = NULL;
1628 self->pattern = NULL;
1629 self->groupindex = NULL;
1630 self->indexgroup = NULL;
1631 #ifdef Py_DEBUG
1632 self->fail_after_count = -1;
1633 self->fail_after_exc = NULL;
1634 #endif
1635
1636 self->codesize = n;
1637
1638 for (i = 0; i < n; i++) {
1639 PyObject *o = PyList_GET_ITEM(code, i);
1640 unsigned long value = PyLong_AsUnsignedLong(o);
1641 if (value == (unsigned long)-1 && PyErr_Occurred()) {
1642 break;
1643 }
1644 self->code[i] = (SRE_CODE) value;
1645 if ((unsigned long) self->code[i] != value) {
1646 PyErr_SetString(PyExc_OverflowError,
1647 "regular expression code size limit exceeded");
1648 break;
1649 }
1650 }
1651 PyObject_GC_Track(self);
1652
1653 if (PyErr_Occurred()) {
1654 Py_DECREF(self);
1655 return NULL;
1656 }
1657
1658 if (pattern == Py_None) {
1659 self->isbytes = -1;
1660 }
1661 else {
1662 Py_ssize_t p_length;
1663 int charsize;
1664 Py_buffer view;
1665 view.buf = NULL;
1666 if (!getstring(pattern, &p_length, &self->isbytes,
1667 &charsize, &view)) {
1668 Py_DECREF(self);
1669 return NULL;
1670 }
1671 if (view.buf)
1672 PyBuffer_Release(&view);
1673 }
1674
1675 self->pattern = Py_NewRef(pattern);
1676
1677 self->flags = flags;
1678
1679 self->groups = groups;
1680
1681 if (PyDict_GET_SIZE(groupindex) > 0) {
1682 self->groupindex = Py_NewRef(groupindex);
1683 if (PyTuple_GET_SIZE(indexgroup) > 0) {
1684 self->indexgroup = Py_NewRef(indexgroup);
1685 }
1686 }
1687
1688 if (!_validate(self)) {
1689 Py_DECREF(self);
1690 return NULL;
1691 }
1692
1693 return (PyObject*) self;
1694 }
1695
1696 /*[clinic input]
1697 _sre.template
1698
1699 pattern: object
1700 template: object(subclass_of="&PyList_Type")
1701 A list containing interleaved literal strings (str or bytes) and group
1702 indices (int), as returned by re._parser.parse_template():
1703 [literal1, group1, ..., literalN, groupN]
1704 /
1705
1706 [clinic start generated code]*/
1707
1708 static PyObject *
1709 _sre_template_impl(PyObject *module, PyObject *pattern, PyObject *template)
1710 /*[clinic end generated code: output=d51290e596ebca86 input=af55380b27f02942]*/
1711 {
1712 /* template is a list containing interleaved literal strings (str or bytes)
1713 * and group indices (int), as returned by _parser.parse_template:
1714 * [literal1, group1, literal2, ..., literalN].
1715 */
1716 _sremodulestate *module_state = get_sre_module_state(module);
1717 TemplateObject *self = NULL;
1718 Py_ssize_t n = PyList_GET_SIZE(template);
1719 if ((n & 1) == 0 || n < 1) {
1720 goto bad_template;
1721 }
1722 n /= 2;
1723 self = PyObject_GC_NewVar(TemplateObject, module_state->Template_Type, n);
1724 if (!self)
1725 return NULL;
1726 self->chunks = 1 + 2*n;
1727 self->literal = Py_NewRef(PyList_GET_ITEM(template, 0));
1728 for (Py_ssize_t i = 0; i < n; i++) {
1729 Py_ssize_t index = PyLong_AsSsize_t(PyList_GET_ITEM(template, 2*i+1));
1730 if (index == -1 && PyErr_Occurred()) {
1731 Py_SET_SIZE(self, i);
1732 Py_DECREF(self);
1733 return NULL;
1734 }
1735 if (index < 0) {
1736 Py_SET_SIZE(self, i);
1737 goto bad_template;
1738 }
1739 self->items[i].index = index;
1740
1741 PyObject *literal = PyList_GET_ITEM(template, 2*i+2);
1742 // Skip empty literals.
1743 if ((PyUnicode_Check(literal) && !PyUnicode_GET_LENGTH(literal)) ||
1744 (PyBytes_Check(literal) && !PyBytes_GET_SIZE(literal)))
1745 {
1746 literal = NULL;
1747 self->chunks--;
1748 }
1749 self->items[i].literal = Py_XNewRef(literal);
1750 }
1751 PyObject_GC_Track(self);
1752 return (PyObject*) self;
1753
1754 bad_template:
1755 PyErr_SetString(PyExc_TypeError, "invalid template");
1756 Py_XDECREF(self);
1757 return NULL;
1758 }
1759
1760 /* -------------------------------------------------------------------- */
1761 /* Code validation */
1762
1763 /* To learn more about this code, have a look at the _compile() function in
1764 Lib/sre_compile.py. The validation functions below checks the code array
1765 for conformance with the code patterns generated there.
1766
1767 The nice thing about the generated code is that it is position-independent:
1768 all jumps are relative jumps forward. Also, jumps don't cross each other:
1769 the target of a later jump is always earlier than the target of an earlier
1770 jump. IOW, this is okay:
1771
1772 J---------J-------T--------T
1773 \ \_____/ /
1774 \______________________/
1775
1776 but this is not:
1777
1778 J---------J-------T--------T
1779 \_________\_____/ /
1780 \____________/
1781
1782 It also helps that SRE_CODE is always an unsigned type.
1783 */
1784
1785 /* Defining this one enables tracing of the validator */
1786 #undef VVERBOSE
1787
1788 /* Trace macro for the validator */
1789 #if defined(VVERBOSE)
1790 #define VTRACE(v) printf v
1791 #else
1792 #define VTRACE(v) do {} while(0) /* do nothing */
1793 #endif
1794
1795 /* Report failure */
1796 #define FAIL do { VTRACE(("FAIL: %d\n", __LINE__)); return -1; } while (0)
1797
1798 /* Extract opcode, argument, or skip count from code array */
1799 #define GET_OP \
1800 do { \
1801 VTRACE(("%p: ", code)); \
1802 if (code >= end) FAIL; \
1803 op = *code++; \
1804 VTRACE(("%lu (op)\n", (unsigned long)op)); \
1805 } while (0)
1806 #define GET_ARG \
1807 do { \
1808 VTRACE(("%p= ", code)); \
1809 if (code >= end) FAIL; \
1810 arg = *code++; \
1811 VTRACE(("%lu (arg)\n", (unsigned long)arg)); \
1812 } while (0)
1813 #define GET_SKIP_ADJ(adj) \
1814 do { \
1815 VTRACE(("%p= ", code)); \
1816 if (code >= end) FAIL; \
1817 skip = *code; \
1818 VTRACE(("%lu (skip to %p)\n", \
1819 (unsigned long)skip, code+skip)); \
1820 if (skip-adj > (uintptr_t)(end - code)) \
1821 FAIL; \
1822 code++; \
1823 } while (0)
1824 #define GET_SKIP GET_SKIP_ADJ(0)
1825
1826 static int
1827 _validate_charset(SRE_CODE *code, SRE_CODE *end)
1828 {
1829 /* Some variables are manipulated by the macros above */
1830 SRE_CODE op;
1831 SRE_CODE arg;
1832 SRE_CODE offset;
1833 int i;
1834
1835 while (code < end) {
1836 GET_OP;
1837 switch (op) {
1838
1839 case SRE_OP_NEGATE:
1840 break;
1841
1842 case SRE_OP_LITERAL:
1843 GET_ARG;
1844 break;
1845
1846 case SRE_OP_RANGE:
1847 case SRE_OP_RANGE_UNI_IGNORE:
1848 GET_ARG;
1849 GET_ARG;
1850 break;
1851
1852 case SRE_OP_CHARSET:
1853 offset = 256/SRE_CODE_BITS; /* 256-bit bitmap */
1854 if (offset > (uintptr_t)(end - code))
1855 FAIL;
1856 code += offset;
1857 break;
1858
1859 case SRE_OP_BIGCHARSET:
1860 GET_ARG; /* Number of blocks */
1861 offset = 256/sizeof(SRE_CODE); /* 256-byte table */
1862 if (offset > (uintptr_t)(end - code))
1863 FAIL;
1864 /* Make sure that each byte points to a valid block */
1865 for (i = 0; i < 256; i++) {
1866 if (((unsigned char *)code)[i] >= arg)
1867 FAIL;
1868 }
1869 code += offset;
1870 offset = arg * (256/SRE_CODE_BITS); /* 256-bit bitmap times arg */
1871 if (offset > (uintptr_t)(end - code))
1872 FAIL;
1873 code += offset;
1874 break;
1875
1876 case SRE_OP_CATEGORY:
1877 GET_ARG;
1878 switch (arg) {
1879 case SRE_CATEGORY_DIGIT:
1880 case SRE_CATEGORY_NOT_DIGIT:
1881 case SRE_CATEGORY_SPACE:
1882 case SRE_CATEGORY_NOT_SPACE:
1883 case SRE_CATEGORY_WORD:
1884 case SRE_CATEGORY_NOT_WORD:
1885 case SRE_CATEGORY_LINEBREAK:
1886 case SRE_CATEGORY_NOT_LINEBREAK:
1887 case SRE_CATEGORY_LOC_WORD:
1888 case SRE_CATEGORY_LOC_NOT_WORD:
1889 case SRE_CATEGORY_UNI_DIGIT:
1890 case SRE_CATEGORY_UNI_NOT_DIGIT:
1891 case SRE_CATEGORY_UNI_SPACE:
1892 case SRE_CATEGORY_UNI_NOT_SPACE:
1893 case SRE_CATEGORY_UNI_WORD:
1894 case SRE_CATEGORY_UNI_NOT_WORD:
1895 case SRE_CATEGORY_UNI_LINEBREAK:
1896 case SRE_CATEGORY_UNI_NOT_LINEBREAK:
1897 break;
1898 default:
1899 FAIL;
1900 }
1901 break;
1902
1903 default:
1904 FAIL;
1905
1906 }
1907 }
1908
1909 return 0;
1910 }
1911
1912 /* Returns 0 on success, -1 on failure, and 1 if the last op is JUMP. */
1913 static int
1914 _validate_inner(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups)
1915 {
1916 /* Some variables are manipulated by the macros above */
1917 SRE_CODE op;
1918 SRE_CODE arg;
1919 SRE_CODE skip;
1920
1921 VTRACE(("code=%p, end=%p\n", code, end));
1922
1923 if (code > end)
1924 FAIL;
1925
1926 while (code < end) {
1927 GET_OP;
1928 switch (op) {
1929
1930 case SRE_OP_MARK:
1931 /* We don't check whether marks are properly nested; the
1932 sre_match() code is robust even if they don't, and the worst
1933 you can get is nonsensical match results. */
1934 GET_ARG;
1935 if (arg >= 2 * (size_t)groups) {
1936 VTRACE(("arg=%d, groups=%d\n", (int)arg, (int)groups));
1937 FAIL;
1938 }
1939 break;
1940
1941 case SRE_OP_LITERAL:
1942 case SRE_OP_NOT_LITERAL:
1943 case SRE_OP_LITERAL_IGNORE:
1944 case SRE_OP_NOT_LITERAL_IGNORE:
1945 case SRE_OP_LITERAL_UNI_IGNORE:
1946 case SRE_OP_NOT_LITERAL_UNI_IGNORE:
1947 case SRE_OP_LITERAL_LOC_IGNORE:
1948 case SRE_OP_NOT_LITERAL_LOC_IGNORE:
1949 GET_ARG;
1950 /* The arg is just a character, nothing to check */
1951 break;
1952
1953 case SRE_OP_SUCCESS:
1954 case SRE_OP_FAILURE:
1955 /* Nothing to check; these normally end the matching process */
1956 break;
1957
1958 case SRE_OP_AT:
1959 GET_ARG;
1960 switch (arg) {
1961 case SRE_AT_BEGINNING:
1962 case SRE_AT_BEGINNING_STRING:
1963 case SRE_AT_BEGINNING_LINE:
1964 case SRE_AT_END:
1965 case SRE_AT_END_LINE:
1966 case SRE_AT_END_STRING:
1967 case SRE_AT_BOUNDARY:
1968 case SRE_AT_NON_BOUNDARY:
1969 case SRE_AT_LOC_BOUNDARY:
1970 case SRE_AT_LOC_NON_BOUNDARY:
1971 case SRE_AT_UNI_BOUNDARY:
1972 case SRE_AT_UNI_NON_BOUNDARY:
1973 break;
1974 default:
1975 FAIL;
1976 }
1977 break;
1978
1979 case SRE_OP_ANY:
1980 case SRE_OP_ANY_ALL:
1981 /* These have no operands */
1982 break;
1983
1984 case SRE_OP_IN:
1985 case SRE_OP_IN_IGNORE:
1986 case SRE_OP_IN_UNI_IGNORE:
1987 case SRE_OP_IN_LOC_IGNORE:
1988 GET_SKIP;
1989 /* Stop 1 before the end; we check the FAILURE below */
1990 if (_validate_charset(code, code+skip-2))
1991 FAIL;
1992 if (code[skip-2] != SRE_OP_FAILURE)
1993 FAIL;
1994 code += skip-1;
1995 break;
1996
1997 case SRE_OP_INFO:
1998 {
1999 /* A minimal info field is
2000 <INFO> <1=skip> <2=flags> <3=min> <4=max>;
2001 If SRE_INFO_PREFIX or SRE_INFO_CHARSET is in the flags,
2002 more follows. */
2003 SRE_CODE flags, i;
2004 SRE_CODE *newcode;
2005 GET_SKIP;
2006 newcode = code+skip-1;
2007 GET_ARG; flags = arg;
2008 GET_ARG;
2009 GET_ARG;
2010 /* Check that only valid flags are present */
2011 if ((flags & ~(SRE_INFO_PREFIX |
2012 SRE_INFO_LITERAL |
2013 SRE_INFO_CHARSET)) != 0)
2014 FAIL;
2015 /* PREFIX and CHARSET are mutually exclusive */
2016 if ((flags & SRE_INFO_PREFIX) &&
2017 (flags & SRE_INFO_CHARSET))
2018 FAIL;
2019 /* LITERAL implies PREFIX */
2020 if ((flags & SRE_INFO_LITERAL) &&
2021 !(flags & SRE_INFO_PREFIX))
2022 FAIL;
2023 /* Validate the prefix */
2024 if (flags & SRE_INFO_PREFIX) {
2025 SRE_CODE prefix_len;
2026 GET_ARG; prefix_len = arg;
2027 GET_ARG;
2028 /* Here comes the prefix string */
2029 if (prefix_len > (uintptr_t)(newcode - code))
2030 FAIL;
2031 code += prefix_len;
2032 /* And here comes the overlap table */
2033 if (prefix_len > (uintptr_t)(newcode - code))
2034 FAIL;
2035 /* Each overlap value should be < prefix_len */
2036 for (i = 0; i < prefix_len; i++) {
2037 if (code[i] >= prefix_len)
2038 FAIL;
2039 }
2040 code += prefix_len;
2041 }
2042 /* Validate the charset */
2043 if (flags & SRE_INFO_CHARSET) {
2044 if (_validate_charset(code, newcode-1))
2045 FAIL;
2046 if (newcode[-1] != SRE_OP_FAILURE)
2047 FAIL;
2048 code = newcode;
2049 }
2050 else if (code != newcode) {
2051 VTRACE(("code=%p, newcode=%p\n", code, newcode));
2052 FAIL;
2053 }
2054 }
2055 break;
2056
2057 case SRE_OP_BRANCH:
2058 {
2059 SRE_CODE *target = NULL;
2060 for (;;) {
2061 GET_SKIP;
2062 if (skip == 0)
2063 break;
2064 /* Stop 2 before the end; we check the JUMP below */
2065 if (_validate_inner(code, code+skip-3, groups))
2066 FAIL;
2067 code += skip-3;
2068 /* Check that it ends with a JUMP, and that each JUMP
2069 has the same target */
2070 GET_OP;
2071 if (op != SRE_OP_JUMP)
2072 FAIL;
2073 GET_SKIP;
2074 if (target == NULL)
2075 target = code+skip-1;
2076 else if (code+skip-1 != target)
2077 FAIL;
2078 }
2079 if (code != target)
2080 FAIL;
2081 }
2082 break;
2083
2084 case SRE_OP_REPEAT_ONE:
2085 case SRE_OP_MIN_REPEAT_ONE:
2086 case SRE_OP_POSSESSIVE_REPEAT_ONE:
2087 {
2088 SRE_CODE min, max;
2089 GET_SKIP;
2090 GET_ARG; min = arg;
2091 GET_ARG; max = arg;
2092 if (min > max)
2093 FAIL;
2094 if (max > SRE_MAXREPEAT)
2095 FAIL;
2096 if (_validate_inner(code, code+skip-4, groups))
2097 FAIL;
2098 code += skip-4;
2099 GET_OP;
2100 if (op != SRE_OP_SUCCESS)
2101 FAIL;
2102 }
2103 break;
2104
2105 case SRE_OP_REPEAT:
2106 case SRE_OP_POSSESSIVE_REPEAT:
2107 {
2108 SRE_CODE op1 = op, min, max;
2109 GET_SKIP;
2110 GET_ARG; min = arg;
2111 GET_ARG; max = arg;
2112 if (min > max)
2113 FAIL;
2114 if (max > SRE_MAXREPEAT)
2115 FAIL;
2116 if (_validate_inner(code, code+skip-3, groups))
2117 FAIL;
2118 code += skip-3;
2119 GET_OP;
2120 if (op1 == SRE_OP_POSSESSIVE_REPEAT) {
2121 if (op != SRE_OP_SUCCESS)
2122 FAIL;
2123 }
2124 else {
2125 if (op != SRE_OP_MAX_UNTIL && op != SRE_OP_MIN_UNTIL)
2126 FAIL;
2127 }
2128 }
2129 break;
2130
2131 case SRE_OP_ATOMIC_GROUP:
2132 {
2133 GET_SKIP;
2134 if (_validate_inner(code, code+skip-2, groups))
2135 FAIL;
2136 code += skip-2;
2137 GET_OP;
2138 if (op != SRE_OP_SUCCESS)
2139 FAIL;
2140 }
2141 break;
2142
2143 case SRE_OP_GROUPREF:
2144 case SRE_OP_GROUPREF_IGNORE:
2145 case SRE_OP_GROUPREF_UNI_IGNORE:
2146 case SRE_OP_GROUPREF_LOC_IGNORE:
2147 GET_ARG;
2148 if (arg >= (size_t)groups)
2149 FAIL;
2150 break;
2151
2152 case SRE_OP_GROUPREF_EXISTS:
2153 /* The regex syntax for this is: '(?(group)then|else)', where
2154 'group' is either an integer group number or a group name,
2155 'then' and 'else' are sub-regexes, and 'else' is optional. */
2156 GET_ARG;
2157 if (arg >= (size_t)groups)
2158 FAIL;
2159 GET_SKIP_ADJ(1);
2160 code--; /* The skip is relative to the first arg! */
2161 /* There are two possibilities here: if there is both a 'then'
2162 part and an 'else' part, the generated code looks like:
2163
2164 GROUPREF_EXISTS
2165 <group>
2166 <skipyes>
2167 ...then part...
2168 JUMP
2169 <skipno>
2170 (<skipyes> jumps here)
2171 ...else part...
2172 (<skipno> jumps here)
2173
2174 If there is only a 'then' part, it looks like:
2175
2176 GROUPREF_EXISTS
2177 <group>
2178 <skip>
2179 ...then part...
2180 (<skip> jumps here)
2181
2182 There is no direct way to decide which it is, and we don't want
2183 to allow arbitrary jumps anywhere in the code; so we just look
2184 for a JUMP opcode preceding our skip target.
2185 */
2186 VTRACE(("then part:\n"));
2187 int rc = _validate_inner(code+1, code+skip-1, groups);
2188 if (rc == 1) {
2189 VTRACE(("else part:\n"));
2190 code += skip-2; /* Position after JUMP, at <skipno> */
2191 GET_SKIP;
2192 rc = _validate_inner(code, code+skip-1, groups);
2193 }
2194 if (rc)
2195 FAIL;
2196 code += skip-1;
2197 break;
2198
2199 case SRE_OP_ASSERT:
2200 case SRE_OP_ASSERT_NOT:
2201 GET_SKIP;
2202 GET_ARG; /* 0 for lookahead, width for lookbehind */
2203 code--; /* Back up over arg to simplify math below */
2204 /* Stop 1 before the end; we check the SUCCESS below */
2205 if (_validate_inner(code+1, code+skip-2, groups))
2206 FAIL;
2207 code += skip-2;
2208 GET_OP;
2209 if (op != SRE_OP_SUCCESS)
2210 FAIL;
2211 break;
2212
2213 case SRE_OP_JUMP:
2214 if (code + 1 != end)
2215 FAIL;
2216 VTRACE(("JUMP: %d\n", __LINE__));
2217 return 1;
2218
2219 default:
2220 FAIL;
2221
2222 }
2223 }
2224
2225 VTRACE(("okay\n"));
2226 return 0;
2227 }
2228
2229 static int
2230 _validate_outer(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups)
2231 {
2232 if (groups < 0 || (size_t)groups > SRE_MAXGROUPS ||
2233 code >= end || end[-1] != SRE_OP_SUCCESS)
2234 FAIL;
2235 return _validate_inner(code, end-1, groups);
2236 }
2237
2238 static int
2239 _validate(PatternObject *self)
2240 {
2241 if (_validate_outer(self->code, self->code+self->codesize, self->groups))
2242 {
2243 PyErr_SetString(PyExc_RuntimeError, "invalid SRE code");
2244 return 0;
2245 }
2246 else
2247 VTRACE(("Success!\n"));
2248 return 1;
2249 }
2250
2251 /* -------------------------------------------------------------------- */
2252 /* match methods */
2253
2254 static int
2255 match_traverse(MatchObject *self, visitproc visit, void *arg)
2256 {
2257 Py_VISIT(Py_TYPE(self));
2258 Py_VISIT(self->string);
2259 Py_VISIT(self->regs);
2260 Py_VISIT(self->pattern);
2261 return 0;
2262 }
2263
2264 static int
2265 match_clear(MatchObject *self)
2266 {
2267 Py_CLEAR(self->string);
2268 Py_CLEAR(self->regs);
2269 Py_CLEAR(self->pattern);
2270 return 0;
2271 }
2272
2273 static void
2274 match_dealloc(MatchObject* self)
2275 {
2276 PyTypeObject *tp = Py_TYPE(self);
2277
2278 PyObject_GC_UnTrack(self);
2279 (void)match_clear(self);
2280 tp->tp_free(self);
2281 Py_DECREF(tp);
2282 }
2283
2284 static PyObject*
2285 match_getslice_by_index(MatchObject* self, Py_ssize_t index, PyObject* def)
2286 {
2287 Py_ssize_t length;
2288 int isbytes, charsize;
2289 Py_buffer view;
2290 PyObject *result;
2291 const void* ptr;
2292 Py_ssize_t i, j;
2293
2294 assert(0 <= index && index < self->groups);
2295 index *= 2;
2296
2297 if (self->string == Py_None || self->mark[index] < 0) {
2298 /* return default value if the string or group is undefined */
2299 return Py_NewRef(def);
2300 }
2301
2302 ptr = getstring(self->string, &length, &isbytes, &charsize, &view);
2303 if (ptr == NULL)
2304 return NULL;
2305
2306 i = self->mark[index];
2307 j = self->mark[index+1];
2308 i = Py_MIN(i, length);
2309 j = Py_MIN(j, length);
2310 result = getslice(isbytes, ptr, self->string, i, j);
2311 if (isbytes && view.buf != NULL)
2312 PyBuffer_Release(&view);
2313 return result;
2314 }
2315
2316 static Py_ssize_t
2317 match_getindex(MatchObject* self, PyObject* index)
2318 {
2319 Py_ssize_t i;
2320
2321 if (index == NULL)
2322 /* Default value */
2323 return 0;
2324
2325 if (PyIndex_Check(index)) {
2326 i = PyNumber_AsSsize_t(index, NULL);
2327 }
2328 else {
2329 i = -1;
2330
2331 if (self->pattern->groupindex) {
2332 index = PyDict_GetItemWithError(self->pattern->groupindex, index);
2333 if (index && PyLong_Check(index)) {
2334 i = PyLong_AsSsize_t(index);
2335 }
2336 }
2337 }
2338 if (i < 0 || i >= self->groups) {
2339 /* raise IndexError if we were given a bad group number */
2340 if (!PyErr_Occurred()) {
2341 PyErr_SetString(PyExc_IndexError, "no such group");
2342 }
2343 return -1;
2344 }
2345
2346 // Check that i*2 cannot overflow to make static analyzers happy
2347 assert(i <= SRE_MAXGROUPS);
2348 return i;
2349 }
2350
2351 static PyObject*
2352 match_getslice(MatchObject* self, PyObject* index, PyObject* def)
2353 {
2354 Py_ssize_t i = match_getindex(self, index);
2355
2356 if (i < 0) {
2357 return NULL;
2358 }
2359
2360 return match_getslice_by_index(self, i, def);
2361 }
2362
2363 /*[clinic input]
2364 _sre.SRE_Match.expand
2365
2366 template: object
2367
2368 Return the string obtained by doing backslash substitution on the string template, as done by the sub() method.
2369 [clinic start generated code]*/
2370
2371 static PyObject *
2372 _sre_SRE_Match_expand_impl(MatchObject *self, PyObject *template)
2373 /*[clinic end generated code: output=931b58ccc323c3a1 input=4bfdb22c2f8b146a]*/
2374 {
2375 _sremodulestate *module_state = get_sre_module_state_by_class(Py_TYPE(self));
2376 PyObject *filter = compile_template(module_state, self->pattern, template);
2377 if (filter == NULL) {
2378 return NULL;
2379 }
2380 PyObject *result = expand_template((TemplateObject *)filter, self);
2381 Py_DECREF(filter);
2382 return result;
2383 }
2384
2385 static PyObject*
2386 match_group(MatchObject* self, PyObject* args)
2387 {
2388 PyObject* result;
2389 Py_ssize_t i, size;
2390
2391 size = PyTuple_GET_SIZE(args);
2392
2393 switch (size) {
2394 case 0:
2395 result = match_getslice(self, _PyLong_GetZero(), Py_None);
2396 break;
2397 case 1:
2398 result = match_getslice(self, PyTuple_GET_ITEM(args, 0), Py_None);
2399 break;
2400 default:
2401 /* fetch multiple items */
2402 result = PyTuple_New(size);
2403 if (!result)
2404 return NULL;
2405 for (i = 0; i < size; i++) {
2406 PyObject* item = match_getslice(
2407 self, PyTuple_GET_ITEM(args, i), Py_None
2408 );
2409 if (!item) {
2410 Py_DECREF(result);
2411 return NULL;
2412 }
2413 PyTuple_SET_ITEM(result, i, item);
2414 }
2415 break;
2416 }
2417 return result;
2418 }
2419
2420 static PyObject*
2421 match_getitem(MatchObject* self, PyObject* name)
2422 {
2423 return match_getslice(self, name, Py_None);
2424 }
2425
2426 /*[clinic input]
2427 _sre.SRE_Match.groups
2428
2429 default: object = None
2430 Is used for groups that did not participate in the match.
2431
2432 Return a tuple containing all the subgroups of the match, from 1.
2433 [clinic start generated code]*/
2434
2435 static PyObject *
2436 _sre_SRE_Match_groups_impl(MatchObject *self, PyObject *default_value)
2437 /*[clinic end generated code: output=daf8e2641537238a input=bb069ef55dabca91]*/
2438 {
2439 PyObject* result;
2440 Py_ssize_t index;
2441
2442 result = PyTuple_New(self->groups-1);
2443 if (!result)
2444 return NULL;
2445
2446 for (index = 1; index < self->groups; index++) {
2447 PyObject* item;
2448 item = match_getslice_by_index(self, index, default_value);
2449 if (!item) {
2450 Py_DECREF(result);
2451 return NULL;
2452 }
2453 PyTuple_SET_ITEM(result, index-1, item);
2454 }
2455
2456 return result;
2457 }
2458
2459 /*[clinic input]
2460 _sre.SRE_Match.groupdict
2461
2462 default: object = None
2463 Is used for groups that did not participate in the match.
2464
2465 Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name.
2466 [clinic start generated code]*/
2467
2468 static PyObject *
2469 _sre_SRE_Match_groupdict_impl(MatchObject *self, PyObject *default_value)
2470 /*[clinic end generated code: output=29917c9073e41757 input=0ded7960b23780aa]*/
2471 {
2472 PyObject *result;
2473 PyObject *key;
2474 PyObject *value;
2475 Py_ssize_t pos = 0;
2476 Py_hash_t hash;
2477
2478 result = PyDict_New();
2479 if (!result || !self->pattern->groupindex)
2480 return result;
2481
2482 Py_BEGIN_CRITICAL_SECTION(self->pattern->groupindex);
2483 while (_PyDict_Next(self->pattern->groupindex, &pos, &key, &value, &hash)) {
2484 int status;
2485 Py_INCREF(key);
2486 value = match_getslice(self, key, default_value);
2487 if (!value) {
2488 Py_DECREF(key);
2489 Py_CLEAR(result);
2490 goto exit;
2491 }
2492 status = _PyDict_SetItem_KnownHash(result, key, value, hash);
2493 Py_DECREF(value);
2494 Py_DECREF(key);
2495 if (status < 0) {
2496 Py_CLEAR(result);
2497 goto exit;
2498 }
2499 }
2500 exit:;
2501 Py_END_CRITICAL_SECTION();
2502
2503 return result;
2504 }
2505
2506 /*[clinic input]
2507 _sre.SRE_Match.start -> Py_ssize_t
2508
2509 group: object(c_default="NULL") = 0
2510 /
2511
2512 Return index of the start of the substring matched by group.
2513 [clinic start generated code]*/
2514
2515 static Py_ssize_t
2516 _sre_SRE_Match_start_impl(MatchObject *self, PyObject *group)
2517 /*[clinic end generated code: output=3f6e7f9df2fb5201 input=ced8e4ed4b33ee6c]*/
2518 {
2519 Py_ssize_t index = match_getindex(self, group);
2520
2521 if (index < 0) {
2522 return -1;
2523 }
2524
2525 /* mark is -1 if group is undefined */
2526 return self->mark[index*2];
2527 }
2528
2529 /*[clinic input]
2530 _sre.SRE_Match.end -> Py_ssize_t
2531
2532 group: object(c_default="NULL") = 0
2533 /
2534
2535 Return index of the end of the substring matched by group.
2536 [clinic start generated code]*/
2537
2538 static Py_ssize_t
2539 _sre_SRE_Match_end_impl(MatchObject *self, PyObject *group)
2540 /*[clinic end generated code: output=f4240b09911f7692 input=1b799560c7f3d7e6]*/
2541 {
2542 Py_ssize_t index = match_getindex(self, group);
2543
2544 if (index < 0) {
2545 return -1;
2546 }
2547
2548 /* mark is -1 if group is undefined */
2549 return self->mark[index*2+1];
2550 }
2551
2552 LOCAL(PyObject*)
2553 _pair(Py_ssize_t i1, Py_ssize_t i2)
2554 {
2555 PyObject* pair;
2556 PyObject* item;
2557
2558 pair = PyTuple_New(2);
2559 if (!pair)
2560 return NULL;
2561
2562 item = PyLong_FromSsize_t(i1);
2563 if (!item)
2564 goto error;
2565 PyTuple_SET_ITEM(pair, 0, item);
2566
2567 item = PyLong_FromSsize_t(i2);
2568 if (!item)
2569 goto error;
2570 PyTuple_SET_ITEM(pair, 1, item);
2571
2572 return pair;
2573
2574 error:
2575 Py_DECREF(pair);
2576 return NULL;
2577 }
2578
2579 /*[clinic input]
2580 _sre.SRE_Match.span
2581
2582 group: object(c_default="NULL") = 0
2583 /
2584
2585 For match object m, return the 2-tuple (m.start(group), m.end(group)).
2586 [clinic start generated code]*/
2587
2588 static PyObject *
2589 _sre_SRE_Match_span_impl(MatchObject *self, PyObject *group)
2590 /*[clinic end generated code: output=f02ae40594d14fe6 input=8fa6014e982d71d4]*/
2591 {
2592 Py_ssize_t index = match_getindex(self, group);
2593
2594 if (index < 0) {
2595 return NULL;
2596 }
2597
2598 /* marks are -1 if group is undefined */
2599 return _pair(self->mark[index*2], self->mark[index*2+1]);
2600 }
2601
2602 static PyObject*
2603 match_regs(MatchObject* self)
2604 {
2605 PyObject* regs;
2606 PyObject* item;
2607 Py_ssize_t index;
2608
2609 regs = PyTuple_New(self->groups);
2610 if (!regs)
2611 return NULL;
2612
2613 for (index = 0; index < self->groups; index++) {
2614 item = _pair(self->mark[index*2], self->mark[index*2+1]);
2615 if (!item) {
2616 Py_DECREF(regs);
2617 return NULL;
2618 }
2619 PyTuple_SET_ITEM(regs, index, item);
2620 }
2621
2622 self->regs = Py_NewRef(regs);
2623
2624 return regs;
2625 }
2626
2627 /*[clinic input]
2628 _sre.SRE_Match.__copy__
2629
2630 [clinic start generated code]*/
2631
2632 static PyObject *
2633 _sre_SRE_Match___copy___impl(MatchObject *self)
2634 /*[clinic end generated code: output=a779c5fc8b5b4eb4 input=3bb4d30b6baddb5b]*/
2635 {
2636 return Py_NewRef(self);
2637 }
2638
2639 /*[clinic input]
2640 _sre.SRE_Match.__deepcopy__
2641
2642 memo: object
2643 /
2644
2645 [clinic start generated code]*/
2646
2647 static PyObject *
2648 _sre_SRE_Match___deepcopy__(MatchObject *self, PyObject *memo)
2649 /*[clinic end generated code: output=ba7cb46d655e4ee2 input=779d12a31c2c325e]*/
2650 {
2651 return Py_NewRef(self);
2652 }
2653
2654 PyDoc_STRVAR(match_doc,
2655 "The result of re.match() and re.search().\n\
2656 Match objects always have a boolean value of True.");
2657
2658 PyDoc_STRVAR(match_group_doc,
2659 "group([group1, ...]) -> str or tuple.\n\
2660 Return subgroup(s) of the match by indices or names.\n\
2661 For 0 returns the entire match.");
2662
2663 static PyObject *
2664 match_lastindex_get(MatchObject *self, void *Py_UNUSED(ignored))
2665 {
2666 if (self->lastindex >= 0)
2667 return PyLong_FromSsize_t(self->lastindex);
2668 Py_RETURN_NONE;
2669 }
2670
2671 static PyObject *
2672 match_lastgroup_get(MatchObject *self, void *Py_UNUSED(ignored))
2673 {
2674 if (self->pattern->indexgroup &&
2675 self->lastindex >= 0 &&
2676 self->lastindex < PyTuple_GET_SIZE(self->pattern->indexgroup))
2677 {
2678 PyObject *result = PyTuple_GET_ITEM(self->pattern->indexgroup,
2679 self->lastindex);
2680 return Py_NewRef(result);
2681 }
2682 Py_RETURN_NONE;
2683 }
2684
2685 static PyObject *
2686 match_regs_get(MatchObject *self, void *Py_UNUSED(ignored))
2687 {
2688 if (self->regs) {
2689 return Py_NewRef(self->regs);
2690 } else
2691 return match_regs(self);
2692 }
2693
2694 static PyObject *
2695 match_repr(MatchObject *self)
2696 {
2697 PyObject *result;
2698 PyObject *group0 = match_getslice_by_index(self, 0, Py_None);
2699 if (group0 == NULL)
2700 return NULL;
2701 result = PyUnicode_FromFormat(
2702 "<%s object; span=(%zd, %zd), match=%.50R>",
2703 Py_TYPE(self)->tp_name,
2704 self->mark[0], self->mark[1], group0);
2705 Py_DECREF(group0);
2706 return result;
2707 }
2708
2709
2710 static PyObject*
2711 pattern_new_match(_sremodulestate* module_state,
2712 PatternObject* pattern,
2713 SRE_STATE* state,
2714 Py_ssize_t status)
2715 {
2716 /* create match object (from state object) */
2717
2718 MatchObject* match;
2719 Py_ssize_t i, j;
2720 char* base;
2721 int n;
2722
2723 if (status > 0) {
2724
2725 /* create match object (with room for extra group marks) */
2726 /* coverity[ampersand_in_size] */
2727 match = PyObject_GC_NewVar(MatchObject,
2728 module_state->Match_Type,
2729 2*(pattern->groups+1));
2730 if (!match)
2731 return NULL;
2732
2733 Py_INCREF(pattern);
2734 match->pattern = pattern;
2735
2736 match->string = Py_NewRef(state->string);
2737
2738 match->regs = NULL;
2739 match->groups = pattern->groups+1;
2740
2741 /* fill in group slices */
2742
2743 base = (char*) state->beginning;
2744 n = state->charsize;
2745
2746 match->mark[0] = ((char*) state->start - base) / n;
2747 match->mark[1] = ((char*) state->ptr - base) / n;
2748
2749 for (i = j = 0; i < pattern->groups; i++, j+=2)
2750 if (j+1 <= state->lastmark && state->mark[j] && state->mark[j+1]) {
2751 match->mark[j+2] = ((char*) state->mark[j] - base) / n;
2752 match->mark[j+3] = ((char*) state->mark[j+1] - base) / n;
2753
2754 /* check wrong span */
2755 if (match->mark[j+2] > match->mark[j+3]) {
2756 PyErr_SetString(PyExc_SystemError,
2757 "The span of capturing group is wrong,"
2758 " please report a bug for the re module.");
2759 Py_DECREF(match);
2760 return NULL;
2761 }
2762 } else
2763 match->mark[j+2] = match->mark[j+3] = -1; /* undefined */
2764
2765 match->pos = state->pos;
2766 match->endpos = state->endpos;
2767
2768 match->lastindex = state->lastindex;
2769
2770 PyObject_GC_Track(match);
2771 return (PyObject*) match;
2772
2773 } else if (status == 0) {
2774
2775 /* no match */
2776 Py_RETURN_NONE;
2777
2778 }
2779
2780 /* internal error */
2781 pattern_error(status);
2782 return NULL;
2783 }
2784
2785
2786 /* -------------------------------------------------------------------- */
2787 /* scanner methods (experimental) */
2788
2789 static int
2790 scanner_traverse(ScannerObject *self, visitproc visit, void *arg)
2791 {
2792 Py_VISIT(Py_TYPE(self));
2793 Py_VISIT(self->pattern);
2794 return 0;
2795 }
2796
2797 static int
2798 scanner_clear(ScannerObject *self)
2799 {
2800 Py_CLEAR(self->pattern);
2801 return 0;
2802 }
2803
2804 static void
2805 scanner_dealloc(ScannerObject* self)
2806 {
2807 PyTypeObject *tp = Py_TYPE(self);
2808
2809 PyObject_GC_UnTrack(self);
2810 state_fini(&self->state);
2811 (void)scanner_clear(self);
2812 tp->tp_free(self);
2813 Py_DECREF(tp);
2814 }
2815
2816 static int
2817 scanner_begin(ScannerObject* self)
2818 {
2819 if (self->executing) {
2820 PyErr_SetString(PyExc_ValueError,
2821 "regular expression scanner already executing");
2822 return 0;
2823 }
2824 self->executing = 1;
2825 return 1;
2826 }
2827
2828 static void
2829 scanner_end(ScannerObject* self)
2830 {
2831 assert(self->executing);
2832 self->executing = 0;
2833 }
2834
2835 /*[clinic input]
2836 _sre.SRE_Scanner.match
2837
2838 cls: defining_class
2839 /
2840
2841 [clinic start generated code]*/
2842
2843 static PyObject *
2844 _sre_SRE_Scanner_match_impl(ScannerObject *self, PyTypeObject *cls)
2845 /*[clinic end generated code: output=6e22c149dc0f0325 input=b5146e1f30278cb7]*/
2846 {
2847 _sremodulestate *module_state = get_sre_module_state_by_class(cls);
2848 SRE_STATE* state = &self->state;
2849 PyObject* match;
2850 Py_ssize_t status;
2851
2852 if (!scanner_begin(self)) {
2853 return NULL;
2854 }
2855 if (state->start == NULL) {
2856 scanner_end(self);
2857 Py_RETURN_NONE;
2858 }
2859
2860 state_reset(state);
2861
2862 state->ptr = state->start;
2863
2864 status = sre_match(state, PatternObject_GetCode(self->pattern));
2865 if (PyErr_Occurred()) {
2866 scanner_end(self);
2867 return NULL;
2868 }
2869
2870 match = pattern_new_match(module_state, self->pattern,
2871 state, status);
2872
2873 if (status == 0)
2874 state->start = NULL;
2875 else {
2876 state->must_advance = (state->ptr == state->start);
2877 state->start = state->ptr;
2878 }
2879
2880 scanner_end(self);
2881 return match;
2882 }
2883
2884
2885 /*[clinic input]
2886 _sre.SRE_Scanner.search
2887
2888 cls: defining_class
2889 /
2890
2891 [clinic start generated code]*/
2892
2893 static PyObject *
2894 _sre_SRE_Scanner_search_impl(ScannerObject *self, PyTypeObject *cls)
2895 /*[clinic end generated code: output=23e8fc78013f9161 input=056c2d37171d0bf2]*/
2896 {
2897 _sremodulestate *module_state = get_sre_module_state_by_class(cls);
2898 SRE_STATE* state = &self->state;
2899 PyObject* match;
2900 Py_ssize_t status;
2901
2902 if (!scanner_begin(self)) {
2903 return NULL;
2904 }
2905 if (state->start == NULL) {
2906 scanner_end(self);
2907 Py_RETURN_NONE;
2908 }
2909
2910 state_reset(state);
2911
2912 state->ptr = state->start;
2913
2914 status = sre_search(state, PatternObject_GetCode(self->pattern));
2915 if (PyErr_Occurred()) {
2916 scanner_end(self);
2917 return NULL;
2918 }
2919
2920 match = pattern_new_match(module_state, self->pattern,
2921 state, status);
2922
2923 if (status == 0)
2924 state->start = NULL;
2925 else {
2926 state->must_advance = (state->ptr == state->start);
2927 state->start = state->ptr;
2928 }
2929
2930 scanner_end(self);
2931 return match;
2932 }
2933
2934 static PyObject *
2935 pattern_scanner(_sremodulestate *module_state,
2936 PatternObject *self,
2937 PyObject *string,
2938 Py_ssize_t pos,
2939 Py_ssize_t endpos)
2940 {
2941 ScannerObject* scanner;
2942
2943 /* create scanner object */
2944 scanner = PyObject_GC_New(ScannerObject, module_state->Scanner_Type);
2945 if (!scanner)
2946 return NULL;
2947 scanner->pattern = NULL;
2948 scanner->executing = 0;
2949
2950 /* create search state object */
2951 if (!state_init(&scanner->state, self, string, pos, endpos)) {
2952 Py_DECREF(scanner);
2953 return NULL;
2954 }
2955
2956 Py_INCREF(self);
2957 scanner->pattern = self;
2958
2959 PyObject_GC_Track(scanner);
2960 return (PyObject*) scanner;
2961 }
2962
2963 /* -------------------------------------------------------------------- */
2964 /* template methods */
2965
2966 static int
2967 template_traverse(TemplateObject *self, visitproc visit, void *arg)
2968 {
2969 Py_VISIT(Py_TYPE(self));
2970 Py_VISIT(self->literal);
2971 for (Py_ssize_t i = 0, n = Py_SIZE(self); i < n; i++) {
2972 Py_VISIT(self->items[i].literal);
2973 }
2974 return 0;
2975 }
2976
2977 static int
2978 template_clear(TemplateObject *self)
2979 {
2980 Py_CLEAR(self->literal);
2981 for (Py_ssize_t i = 0, n = Py_SIZE(self); i < n; i++) {
2982 Py_CLEAR(self->items[i].literal);
2983 }
2984 return 0;
2985 }
2986
2987 static void
2988 template_dealloc(TemplateObject *self)
2989 {
2990 PyTypeObject *tp = Py_TYPE(self);
2991
2992 PyObject_GC_UnTrack(self);
2993 (void)template_clear(self);
2994 tp->tp_free(self);
2995 Py_DECREF(tp);
2996 }
2997
2998 static PyObject *
2999 expand_template(TemplateObject *self, MatchObject *match)
3000 {
3001 if (Py_SIZE(self) == 0) {
3002 return Py_NewRef(self->literal);
3003 }
3004
3005 PyObject *result = NULL;
3006 Py_ssize_t count = 0; // the number of non-empty chunks
3007 /* For small number of strings use a buffer allocated on the stack,
3008 * otherwise use a list object. */
3009 PyObject *buffer[10];
3010 PyObject **out = buffer;
3011 PyObject *list = NULL;
3012 if (self->chunks > (int)Py_ARRAY_LENGTH(buffer) ||
3013 !PyUnicode_Check(self->literal))
3014 {
3015 list = PyList_New(self->chunks);
3016 if (!list) {
3017 return NULL;
3018 }
3019 out = &PyList_GET_ITEM(list, 0);
3020 }
3021
3022 out[count++] = Py_NewRef(self->literal);
3023 for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
3024 Py_ssize_t index = self->items[i].index;
3025 if (index >= match->groups) {
3026 PyErr_SetString(PyExc_IndexError, "no such group");
3027 goto cleanup;
3028 }
3029 PyObject *item = match_getslice_by_index(match, index, Py_None);
3030 if (item == NULL) {
3031 goto cleanup;
3032 }
3033 if (item != Py_None) {
3034 out[count++] = Py_NewRef(item);
3035 }
3036 Py_DECREF(item);
3037
3038 PyObject *literal = self->items[i].literal;
3039 if (literal != NULL) {
3040 out[count++] = Py_NewRef(literal);
3041 }
3042 }
3043
3044 if (PyUnicode_Check(self->literal)) {
3045 result = _PyUnicode_JoinArray(&_Py_STR(empty), out, count);
3046 }
3047 else {
3048 Py_SET_SIZE(list, count);
3049 result = _PyBytes_Join((PyObject *)&_Py_SINGLETON(bytes_empty), list);
3050 }
3051
3052 cleanup:
3053 if (list) {
3054 Py_DECREF(list);
3055 }
3056 else {
3057 for (Py_ssize_t i = 0; i < count; i++) {
3058 Py_DECREF(out[i]);
3059 }
3060 }
3061 return result;
3062 }
3063
3064
3065 static Py_hash_t
3066 pattern_hash(PatternObject *self)
3067 {
3068 Py_hash_t hash, hash2;
3069
3070 hash = PyObject_Hash(self->pattern);
3071 if (hash == -1) {
3072 return -1;
3073 }
3074
3075 hash2 = _Py_HashBytes(self->code, sizeof(self->code[0]) * self->codesize);
3076 hash ^= hash2;
3077
3078 hash ^= self->flags;
3079 hash ^= self->isbytes;
3080 hash ^= self->codesize;
3081
3082 if (hash == -1) {
3083 hash = -2;
3084 }
3085 return hash;
3086 }
3087
3088 static PyObject*
3089 pattern_richcompare(PyObject *lefto, PyObject *righto, int op)
3090 {
3091 PyTypeObject *tp = Py_TYPE(lefto);
3092 _sremodulestate *module_state = get_sre_module_state_by_class(tp);
3093 PatternObject *left, *right;
3094 int cmp;
3095
3096 if (op != Py_EQ && op != Py_NE) {
3097 Py_RETURN_NOTIMPLEMENTED;
3098 }
3099
3100 if (!Py_IS_TYPE(righto, module_state->Pattern_Type))
3101 {
3102 Py_RETURN_NOTIMPLEMENTED;
3103 }
3104
3105 if (lefto == righto) {
3106 /* a pattern is equal to itself */
3107 return PyBool_FromLong(op == Py_EQ);
3108 }
3109
3110 left = (PatternObject *)lefto;
3111 right = (PatternObject *)righto;
3112
3113 cmp = (left->flags == right->flags
3114 && left->isbytes == right->isbytes
3115 && left->codesize == right->codesize);
3116 if (cmp) {
3117 /* Compare the code and the pattern because the same pattern can
3118 produce different codes depending on the locale used to compile the
3119 pattern when the re.LOCALE flag is used. Don't compare groups,
3120 indexgroup nor groupindex: they are derivated from the pattern. */
3121 cmp = (memcmp(left->code, right->code,
3122 sizeof(left->code[0]) * left->codesize) == 0);
3123 }
3124 if (cmp) {
3125 cmp = PyObject_RichCompareBool(left->pattern, right->pattern,
3126 Py_EQ);
3127 if (cmp < 0) {
3128 return NULL;
3129 }
3130 }
3131 if (op == Py_NE) {
3132 cmp = !cmp;
3133 }
3134 return PyBool_FromLong(cmp);
3135 }
3136
3137 #include "clinic/sre.c.h"
3138
3139 static PyMethodDef pattern_methods[] = {
3140 _SRE_SRE_PATTERN_MATCH_METHODDEF
3141 _SRE_SRE_PATTERN_FULLMATCH_METHODDEF
3142 _SRE_SRE_PATTERN_SEARCH_METHODDEF
3143 _SRE_SRE_PATTERN_SUB_METHODDEF
3144 _SRE_SRE_PATTERN_SUBN_METHODDEF
3145 _SRE_SRE_PATTERN_FINDALL_METHODDEF
3146 _SRE_SRE_PATTERN_SPLIT_METHODDEF
3147 _SRE_SRE_PATTERN_FINDITER_METHODDEF
3148 _SRE_SRE_PATTERN_SCANNER_METHODDEF
3149 _SRE_SRE_PATTERN___COPY___METHODDEF
3150 _SRE_SRE_PATTERN___DEEPCOPY___METHODDEF
3151 _SRE_SRE_PATTERN__FAIL_AFTER_METHODDEF
3152 {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
3153 PyDoc_STR("See PEP 585")},
3154 {NULL, NULL}
3155 };
3156
3157 static PyGetSetDef pattern_getset[] = {
3158 {"groupindex", (getter)pattern_groupindex, (setter)NULL,
3159 "A dictionary mapping group names to group numbers."},
3160 {NULL} /* Sentinel */
3161 };
3162
3163 #define PAT_OFF(x) offsetof(PatternObject, x)
3164 static PyMemberDef pattern_members[] = {
3165 {"pattern", _Py_T_OBJECT, PAT_OFF(pattern), Py_READONLY,
3166 "The pattern string from which the RE object was compiled."},
3167 {"flags", Py_T_INT, PAT_OFF(flags), Py_READONLY,
3168 "The regex matching flags."},
3169 {"groups", Py_T_PYSSIZET, PAT_OFF(groups), Py_READONLY,
3170 "The number of capturing groups in the pattern."},
3171 {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(PatternObject, weakreflist), Py_READONLY},
3172 {NULL} /* Sentinel */
3173 };
3174
3175 static PyType_Slot pattern_slots[] = {
3176 {Py_tp_dealloc, (destructor)pattern_dealloc},
3177 {Py_tp_repr, (reprfunc)pattern_repr},
3178 {Py_tp_hash, (hashfunc)pattern_hash},
3179 {Py_tp_doc, (void *)pattern_doc},
3180 {Py_tp_richcompare, pattern_richcompare},
3181 {Py_tp_methods, pattern_methods},
3182 {Py_tp_members, pattern_members},
3183 {Py_tp_getset, pattern_getset},
3184 {Py_tp_traverse, pattern_traverse},
3185 {Py_tp_clear, pattern_clear},
3186 {0, NULL},
3187 };
3188
3189 static PyType_Spec pattern_spec = {
3190 .name = "re.Pattern",
3191 .basicsize = sizeof(PatternObject),
3192 .itemsize = sizeof(SRE_CODE),
3193 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
3194 Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC),
3195 .slots = pattern_slots,
3196 };
3197
3198 static PyMethodDef match_methods[] = {
3199 {"group", (PyCFunction) match_group, METH_VARARGS, match_group_doc},
3200 _SRE_SRE_MATCH_START_METHODDEF
3201 _SRE_SRE_MATCH_END_METHODDEF
3202 _SRE_SRE_MATCH_SPAN_METHODDEF
3203 _SRE_SRE_MATCH_GROUPS_METHODDEF
3204 _SRE_SRE_MATCH_GROUPDICT_METHODDEF
3205 _SRE_SRE_MATCH_EXPAND_METHODDEF
3206 _SRE_SRE_MATCH___COPY___METHODDEF
3207 _SRE_SRE_MATCH___DEEPCOPY___METHODDEF
3208 {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
3209 PyDoc_STR("See PEP 585")},
3210 {NULL, NULL}
3211 };
3212
3213 static PyGetSetDef match_getset[] = {
3214 {"lastindex", (getter)match_lastindex_get, (setter)NULL,
3215 "The integer index of the last matched capturing group."},
3216 {"lastgroup", (getter)match_lastgroup_get, (setter)NULL,
3217 "The name of the last matched capturing group."},
3218 {"regs", (getter)match_regs_get, (setter)NULL},
3219 {NULL}
3220 };
3221
3222 #define MATCH_OFF(x) offsetof(MatchObject, x)
3223 static PyMemberDef match_members[] = {
3224 {"string", _Py_T_OBJECT, MATCH_OFF(string), Py_READONLY,
3225 "The string passed to match() or search()."},
3226 {"re", _Py_T_OBJECT, MATCH_OFF(pattern), Py_READONLY,
3227 "The regular expression object."},
3228 {"pos", Py_T_PYSSIZET, MATCH_OFF(pos), Py_READONLY,
3229 "The index into the string at which the RE engine started looking for a match."},
3230 {"endpos", Py_T_PYSSIZET, MATCH_OFF(endpos), Py_READONLY,
3231 "The index into the string beyond which the RE engine will not go."},
3232 {NULL}
3233 };
3234
3235 /* FIXME: implement setattr("string", None) as a special case (to
3236 detach the associated string, if any */
3237 static PyType_Slot match_slots[] = {
3238 {Py_tp_dealloc, match_dealloc},
3239 {Py_tp_repr, match_repr},
3240 {Py_tp_doc, (void *)match_doc},
3241 {Py_tp_methods, match_methods},
3242 {Py_tp_members, match_members},
3243 {Py_tp_getset, match_getset},
3244 {Py_tp_traverse, match_traverse},
3245 {Py_tp_clear, match_clear},
3246
3247 /* As mapping.
3248 *
3249 * Match objects do not support length or assignment, but do support
3250 * __getitem__.
3251 */
3252 {Py_mp_subscript, match_getitem},
3253
3254 {0, NULL},
3255 };
3256
3257 static PyType_Spec match_spec = {
3258 .name = "re.Match",
3259 .basicsize = sizeof(MatchObject),
3260 .itemsize = sizeof(Py_ssize_t),
3261 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
3262 Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC),
3263 .slots = match_slots,
3264 };
3265
3266 static PyMethodDef scanner_methods[] = {
3267 _SRE_SRE_SCANNER_MATCH_METHODDEF
3268 _SRE_SRE_SCANNER_SEARCH_METHODDEF
3269 {NULL, NULL}
3270 };
3271
3272 #define SCAN_OFF(x) offsetof(ScannerObject, x)
3273 static PyMemberDef scanner_members[] = {
3274 {"pattern", _Py_T_OBJECT, SCAN_OFF(pattern), Py_READONLY},
3275 {NULL} /* Sentinel */
3276 };
3277
3278 static PyType_Slot scanner_slots[] = {
3279 {Py_tp_dealloc, scanner_dealloc},
3280 {Py_tp_methods, scanner_methods},
3281 {Py_tp_members, scanner_members},
3282 {Py_tp_traverse, scanner_traverse},
3283 {Py_tp_clear, scanner_clear},
3284 {0, NULL},
3285 };
3286
3287 static PyType_Spec scanner_spec = {
3288 .name = "_sre.SRE_Scanner",
3289 .basicsize = sizeof(ScannerObject),
3290 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
3291 Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC),
3292 .slots = scanner_slots,
3293 };
3294
3295 static PyType_Slot template_slots[] = {
3296 {Py_tp_dealloc, template_dealloc},
3297 {Py_tp_traverse, template_traverse},
3298 {Py_tp_clear, template_clear},
3299 {0, NULL},
3300 };
3301
3302 static PyType_Spec template_spec = {
3303 .name = "_sre.SRE_Template",
3304 .basicsize = sizeof(TemplateObject),
3305 .itemsize = sizeof(((TemplateObject *)0)->items[0]),
3306 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
3307 Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC),
3308 .slots = template_slots,
3309 };
3310
3311 static PyMethodDef _functions[] = {
3312 _SRE_COMPILE_METHODDEF
3313 _SRE_TEMPLATE_METHODDEF
3314 _SRE_GETCODESIZE_METHODDEF
3315 _SRE_ASCII_ISCASED_METHODDEF
3316 _SRE_UNICODE_ISCASED_METHODDEF
3317 _SRE_ASCII_TOLOWER_METHODDEF
3318 _SRE_UNICODE_TOLOWER_METHODDEF
3319 {NULL, NULL}
3320 };
3321
3322 static int
3323 sre_traverse(PyObject *module, visitproc visit, void *arg)
3324 {
3325 _sremodulestate *state = get_sre_module_state(module);
3326
3327 Py_VISIT(state->Pattern_Type);
3328 Py_VISIT(state->Match_Type);
3329 Py_VISIT(state->Scanner_Type);
3330 Py_VISIT(state->Template_Type);
3331 Py_VISIT(state->compile_template);
3332
3333 return 0;
3334 }
3335
3336 static int
3337 sre_clear(PyObject *module)
3338 {
3339 _sremodulestate *state = get_sre_module_state(module);
3340
3341 Py_CLEAR(state->Pattern_Type);
3342 Py_CLEAR(state->Match_Type);
3343 Py_CLEAR(state->Scanner_Type);
3344 Py_CLEAR(state->Template_Type);
3345 Py_CLEAR(state->compile_template);
3346
3347 return 0;
3348 }
3349
3350 static void
3351 sre_free(void *module)
3352 {
3353 sre_clear((PyObject *)module);
3354 }
3355
3356 #define CREATE_TYPE(m, type, spec) \
3357 do { \
3358 type = (PyTypeObject *)PyType_FromModuleAndSpec(m, spec, NULL); \
3359 if (type == NULL) { \
3360 goto error; \
3361 } \
3362 } while (0)
3363
3364 #define ADD_ULONG_CONSTANT(module, name, value) \
3365 do { \
3366 if (PyModule_Add(module, name, PyLong_FromUnsignedLong(value)) < 0) { \
3367 goto error; \
3368 } \
3369 } while (0)
3370
3371 static int
3372 sre_exec(PyObject *m)
3373 {
3374 _sremodulestate *state;
3375
3376 /* Create heap types */
3377 state = get_sre_module_state(m);
3378 CREATE_TYPE(m, state->Pattern_Type, &pattern_spec);
3379 CREATE_TYPE(m, state->Match_Type, &match_spec);
3380 CREATE_TYPE(m, state->Scanner_Type, &scanner_spec);
3381 CREATE_TYPE(m, state->Template_Type, &template_spec);
3382
3383 if (PyModule_AddIntConstant(m, "MAGIC", SRE_MAGIC) < 0) {
3384 goto error;
3385 }
3386
3387 if (PyModule_AddIntConstant(m, "CODESIZE", sizeof(SRE_CODE)) < 0) {
3388 goto error;
3389 }
3390
3391 ADD_ULONG_CONSTANT(m, "MAXREPEAT", SRE_MAXREPEAT);
3392 ADD_ULONG_CONSTANT(m, "MAXGROUPS", SRE_MAXGROUPS);
3393
3394 if (PyModule_AddStringConstant(m, "copyright", copyright) < 0) {
3395 goto error;
3396 }
3397
3398 return 0;
3399
3400 error:
3401 return -1;
3402 }
3403
3404 static PyModuleDef_Slot sre_slots[] = {
3405 {Py_mod_exec, sre_exec},
3406 {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
3407 {Py_mod_gil, Py_MOD_GIL_NOT_USED},
3408 {0, NULL},
3409 };
3410
3411 static struct PyModuleDef sremodule = {
3412 .m_base = PyModuleDef_HEAD_INIT,
3413 .m_name = "_sre",
3414 .m_size = sizeof(_sremodulestate),
3415 .m_methods = _functions,
3416 .m_slots = sre_slots,
3417 .m_traverse = sre_traverse,
3418 .m_free = sre_free,
3419 .m_clear = sre_clear,
3420 };
3421
3422 PyMODINIT_FUNC
3423 PyInit__sre(void)
3424 {
3425 return PyModuleDef_Init(&sremodule);
3426 }
3427
3428 /* vim:ts=4:sw=4:et
3429 */