Coverage Report

Created: 2026-03-23 06:45

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