Coverage Report

Created: 2026-12-01 06:09

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