Coverage Report

Created: 2026-08-28 06:28

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