Coverage Report

Created: 2026-10-17 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Modules/_sre/sre.c
Line
Count
Source
1
/*
2
 * Secret Labs' Regular Expression Engine
3
 *
4
 * regular expression matching engine
5
 *
6
 * partial history:
7
 * 1999-10-24 fl   created (based on existing template matcher code)
8
 * 2000-03-06 fl   first alpha, sort of
9
 * 2000-08-01 fl   fixes for 1.6b1
10
 * 2000-08-07 fl   use PyOS_CheckStack() if available
11
 * 2000-09-20 fl   added expand method
12
 * 2001-03-20 fl   lots of fixes for 2.1b2
13
 * 2001-04-15 fl   export copyright as Python attribute, not global
14
 * 2001-04-28 fl   added __copy__ methods (work in progress)
15
 * 2001-05-14 fl   fixes for 1.5.2 compatibility
16
 * 2001-07-01 fl   added BIGCHARSET support (from Martin von Loewis)
17
 * 2001-10-18 fl   fixed group reset issue (from Matthew Mueller)
18
 * 2001-10-20 fl   added split primitive; re-enable unicode for 1.6/2.0/2.1
19
 * 2001-10-21 fl   added sub/subn primitive
20
 * 2001-10-24 fl   added finditer primitive (for 2.2 only)
21
 * 2001-12-07 fl   fixed memory leak in sub/subn (Guido van Rossum)
22
 * 2002-11-09 fl   fixed empty sub/subn return type
23
 * 2003-04-18 mvl  fully support 4-byte codes
24
 * 2003-10-17 gn   implemented non recursive scheme
25
 * 2013-02-04 mrab added fullmatch primitive
26
 *
27
 * Copyright (c) 1997-2001 by Secret Labs AB.  All rights reserved.
28
 *
29
 * This version of the SRE library can be redistributed under CNRI's
30
 * Python 1.6 license.  For any other use, please contact Secret Labs
31
 * AB (info@pythonware.com).
32
 *
33
 * Portions of this engine have been developed in cooperation with
34
 * CNRI.  Hewlett-Packard provided funding for 1.6 integration and
35
 * other compatibility work.
36
 */
37
38
static const char copyright[] =
39
    " SRE 2.2.2 Copyright (c) 1997-2002 by Secret Labs AB ";
40
41
#include "Python.h"
42
#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION
43
#include "pycore_dict.h"             // _PyDict_Next()
44
#include "pycore_long.h"             // _PyLong_GetZero()
45
#include "pycore_list.h"             // _PyList_AppendTakeRef()
46
#include "pycore_moduleobject.h"     // _PyModule_GetState()
47
#include "pycore_tuple.h"            // _PyTuple_FromPairSteal
48
#include "pycore_unicodeobject.h"    // _PyUnicode_Copy
49
#include "pycore_unicodectype.h"     // _PyUnicode_IsXidStart()
50
#include "pycore_weakref.h"          // FT_CLEAR_WEAKREFS()
51
52
#include "sre.h"                     // SRE_CODE
53
54
#include <ctype.h>                   // tolower(), toupper(), isalnum()
55
56
325M
#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.69k
    ((ch) <= '9' && Py_ISDIGIT(ch))
139
#define SRE_IS_SPACE(ch)\
140
32
    ((ch) <= ' ' && Py_ISSPACE(ch))
141
#define SRE_IS_LINEBREAK(ch)\
142
31.2M
    ((ch) == '\n')
143
#define SRE_IS_WORD(ch)\
144
11.0M
    ((ch) <= 'z' && (Py_ISALNUM(ch) || (ch) == '_'))
145
146
static unsigned int sre_lower_ascii(unsigned int ch)
147
977k
{
148
977k
    return ((ch) < 128 ? Py_TOLOWER(ch) : ch);
149
977k
}
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
127M
#define SRE_UNI_IS_SPACE(ch) Py_UNICODE_ISSPACE(ch)
171
0
#define SRE_UNI_IS_LINEBREAK(ch) Py_UNICODE_ISLINEBREAK(ch)
172
1.43k
#define SRE_UNI_IS_ALNUM(ch) Py_UNICODE_ISALNUM(ch)
173
716
#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
92.4M
{
219
92.4M
    return (unsigned int) Py_UNICODE_TOLOWER(ch);
220
92.4M
}
221
222
static unsigned int sre_upper_unicode(unsigned int ch)
223
19.2M
{
224
19.2M
    return (unsigned int) Py_UNICODE_TOUPPER(ch);
225
19.2M
}
226
227
LOCAL(int)
228
sre_category(SRE_CODE category, unsigned int ch)
229
138M
{
230
138M
    switch (category) {
231
232
1.69k
    case SRE_CATEGORY_DIGIT:
233
1.69k
        return SRE_IS_DIGIT(ch);
234
0
    case SRE_CATEGORY_NOT_DIGIT:
235
0
        return !SRE_IS_DIGIT(ch);
236
32
    case SRE_CATEGORY_SPACE:
237
32
        return SRE_IS_SPACE(ch);
238
0
    case SRE_CATEGORY_NOT_SPACE:
239
0
        return !SRE_IS_SPACE(ch);
240
11.0M
    case SRE_CATEGORY_WORD:
241
11.0M
        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
15.5M
    case SRE_CATEGORY_UNI_SPACE:
259
15.5M
        return SRE_UNI_IS_SPACE(ch);
260
111M
    case SRE_CATEGORY_UNI_NOT_SPACE:
261
111M
        return !SRE_UNI_IS_SPACE(ch);
262
716
    case SRE_CATEGORY_UNI_WORD:
263
716
        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
138M
    }
372
0
    return 0;
373
138M
}
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
152M
{
389
152M
    if (state->data_stack) {
390
133M
        PyMem_Free(state->data_stack);
391
133M
        state->data_stack = NULL;
392
133M
    }
393
152M
    state->data_stack_size = state->data_stack_base = 0;
394
152M
}
395
396
static int
397
data_stack_grow(SRE_STATE* state, Py_ssize_t size)
398
136M
{
399
136M
    INIT_TRACE(state);
400
136M
    Py_ssize_t minsize, cursize;
401
136M
    minsize = state->data_stack_base+size;
402
136M
    cursize = state->data_stack_size;
403
136M
    if (cursize < minsize) {
404
136M
        void* stack;
405
136M
        cursize = minsize+minsize/4+1024;
406
136M
        TRACE(("allocate/grow stack %zd\n", cursize));
407
136M
        stack = PyMem_Realloc(state->data_stack, cursize);
408
136M
        if (!stack) {
409
0
            data_stack_dealloc(state);
410
0
            return SRE_ERROR_MEMORY;
411
0
        }
412
136M
        state->data_stack = (char *)stack;
413
136M
        state->data_stack_size = cursize;
414
136M
    }
415
136M
    return 0;
416
136M
}
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
29.3M
{
427
29.3M
    SRE_REPEAT *repeat;
428
429
29.3M
    if (state->repeat_pool_unused) {
430
        /* remove from unused pool (singly-linked list) */
431
5.18M
        repeat = state->repeat_pool_unused;
432
5.18M
        state->repeat_pool_unused = repeat->pool_next;
433
5.18M
    }
434
24.1M
    else {
435
24.1M
        repeat = PyMem_Malloc(sizeof(SRE_REPEAT));
436
24.1M
        if (!repeat) {
437
0
            return NULL;
438
0
        }
439
24.1M
    }
440
441
    /* add to used pool (doubly-linked list) */
442
29.3M
    SRE_REPEAT *temp = state->repeat_pool_used;
443
29.3M
    if (temp) {
444
20.4M
        temp->pool_prev = repeat;
445
20.4M
    }
446
29.3M
    repeat->pool_prev = NULL;
447
29.3M
    repeat->pool_next = temp;
448
29.3M
    state->repeat_pool_used = repeat;
449
450
29.3M
    return repeat;
451
29.3M
}
452
453
static void
454
repeat_pool_free(SRE_STATE *state, SRE_REPEAT *repeat)
455
29.3M
{
456
29.3M
    SRE_REPEAT *prev = repeat->pool_prev;
457
29.3M
    SRE_REPEAT *next = repeat->pool_next;
458
459
    /* remove from used pool (doubly-linked list) */
460
29.3M
    if (prev) {
461
0
        prev->pool_next = next;
462
0
    }
463
29.3M
    else {
464
29.3M
        state->repeat_pool_used = next;
465
29.3M
    }
466
29.3M
    if (next) {
467
20.4M
        next->pool_prev = prev;
468
20.4M
    }
469
470
    /* add to unused pool (singly-linked list) */
471
29.3M
    repeat->pool_next = state->repeat_pool_unused;
472
29.3M
    state->repeat_pool_unused = repeat;
473
29.3M
}
474
475
static void
476
repeat_pool_clear(SRE_STATE *state)
477
61.0M
{
478
    /* clear used pool */
479
61.0M
    SRE_REPEAT *next = state->repeat_pool_used;
480
61.0M
    state->repeat_pool_used = NULL;
481
61.0M
    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
61.0M
    next = state->repeat_pool_unused;
489
61.0M
    state->repeat_pool_unused = NULL;
490
85.2M
    while (next) {
491
24.1M
        SRE_REPEAT *temp = next;
492
24.1M
        next = temp->pool_next;
493
24.1M
        PyMem_Free(temp);
494
24.1M
    }
495
61.0M
}
496
497
/* generate 8-bit version */
498
499
191M
#define SRE_CHAR Py_UCS1
500
#define SIZEOF_SRE_CHAR 1
501
788M
#define SRE(F) sre_ucs1_##F
502
#include "sre_lib.h"
503
504
/* generate 16-bit unicode version */
505
506
238M
#define SRE_CHAR Py_UCS2
507
#define SIZEOF_SRE_CHAR 2
508
1.20G
#define SRE(F) sre_ucs2_##F
509
#include "sre_lib.h"
510
511
/* generate 32-bit unicode version */
512
513
51.9M
#define SRE_CHAR Py_UCS4
514
#define SIZEOF_SRE_CHAR 4
515
294M
#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
59.4M
{
533
59.4M
    _sremodulestate *state = (_sremodulestate *)_PyModule_GetState(m);
534
59.4M
    assert(state);
535
59.4M
    return state;
536
59.4M
}
537
538
static struct PyModuleDef sremodule;
539
#define get_sre_module_state_by_class(cls) \
540
59.4M
    (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
17.3k
#define _PatternObject_CAST(op)     ((PatternObject *)(op))
547
38.9M
#define _MatchObject_CAST(op)       ((MatchObject *)(op))
548
0
#define _TemplateObject_CAST(op)    ((TemplateObject *)(op))
549
657k
#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
195k
{
582
195k
    unsigned int ch = (unsigned int)character;
583
195k
    return ch < 128 && Py_ISALPHA(ch);
584
195k
}
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
22.0M
{
598
22.0M
    unsigned int ch = (unsigned int)character;
599
22.0M
    return ch != sre_lower_unicode(ch) || ch != sre_upper_unicode(ch);
600
22.0M
}
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
977k
{
614
977k
    return sre_lower_ascii(character);
615
977k
}
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
70.3M
{
629
70.3M
    return sre_lower_unicode(character);
630
70.3M
}
631
632
LOCAL(void)
633
state_reset(SRE_STATE* state)
634
91.8M
{
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
91.8M
    state->lastmark = -1;
639
91.8M
    state->lastindex = -1;
640
641
91.8M
    state->repeat = NULL;
642
643
91.8M
    data_stack_dealloc(state);
644
91.8M
}
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
93.0M
{
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
93.0M
    if (PyUnicode_Check(string)) {
658
92.4M
        *p_length = PyUnicode_GET_LENGTH(string);
659
92.4M
        *p_charsize = PyUnicode_KIND(string);
660
92.4M
        *p_isbytes = 0;
661
92.4M
        return PyUnicode_DATA(string);
662
92.4M
    }
663
664
    /* get pointer to byte string buffer */
665
641k
    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
641k
    *p_length = view->len;
672
641k
    *p_charsize = 1;
673
641k
    *p_isbytes = 1;
674
675
641k
    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
641k
    return view->buf;
682
641k
}
683
684
LOCAL(PyObject*)
685
state_init(SRE_STATE* state, PatternObject* pattern, PyObject* string,
686
           Py_ssize_t start, Py_ssize_t end)
687
61.0M
{
688
    /* prepare state object */
689
690
61.0M
    Py_ssize_t length;
691
61.0M
    int isbytes, charsize;
692
61.0M
    const void* ptr;
693
694
61.0M
    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
61.0M
    if (pattern->groups) {
701
31.0M
        state->mark = PyMem_New(const void *, pattern->groups * 2);
702
31.0M
        if (!state->mark) {
703
0
            PyErr_NoMemory();
704
0
            goto err;
705
0
        }
706
31.0M
    }
707
61.0M
    state->lastmark = -1;
708
61.0M
    state->lastindex = -1;
709
710
61.0M
    state->buffer.buf = NULL;
711
61.0M
    ptr = getstring(string, &length, &isbytes, &charsize, &state->buffer);
712
61.0M
    if (!ptr)
713
0
        goto err;
714
715
61.0M
    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
61.0M
    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
61.0M
    if (start < 0)
728
0
        start = 0;
729
61.0M
    else if (start > length)
730
0
        start = length;
731
732
61.0M
    if (end < 0)
733
0
        end = 0;
734
61.0M
    else if (end > length)
735
61.0M
        end = length;
736
737
61.0M
    state->isbytes = isbytes;
738
61.0M
    state->charsize = charsize;
739
61.0M
    state->match_all = 0;
740
61.0M
    state->must_advance = 0;
741
61.0M
    state->save_marks = 0;
742
61.0M
    state->debug = ((pattern->flags & SRE_FLAG_DEBUG) != 0);
743
744
61.0M
    state->beginning = ptr;
745
746
61.0M
    state->start = (void*) ((char*) ptr + start * state->charsize);
747
61.0M
    state->end = (void*) ((char*) ptr + end * state->charsize);
748
749
61.0M
    state->string = Py_NewRef(string);
750
61.0M
    state->pos = start;
751
61.0M
    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
61.0M
    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
61.0M
}
769
770
LOCAL(void)
771
state_fini(SRE_STATE* state)
772
61.0M
{
773
61.0M
    if (state->buffer.buf)
774
328k
        PyBuffer_Release(&state->buffer);
775
61.0M
    Py_XDECREF(state->string);
776
61.0M
    data_stack_dealloc(state);
777
    /* See above PyMem_Free() for why we explicitly cast here. */
778
61.0M
    PyMem_Free((void*) state->mark);
779
61.0M
    state->mark = NULL;
780
    /* SRE_REPEAT pool */
781
61.0M
    repeat_pool_clear(state);
782
61.0M
}
783
784
/* calculate offset from start of string */
785
#define STATE_OFFSET(state, member)\
786
156M
    (((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
116M
{
792
116M
    if (isbytes) {
793
377k
        if (PyBytes_CheckExact(string) &&
794
377k
            start == 0 && end == PyBytes_GET_SIZE(string)) {
795
2.16k
            return Py_NewRef(string);
796
2.16k
        }
797
375k
        return PyBytes_FromStringAndSize(
798
375k
                (const char *)ptr + start, end - start);
799
377k
    }
800
115M
    else {
801
115M
        return PyUnicode_Substring(string, start, end);
802
115M
    }
803
116M
}
804
805
LOCAL(PyObject*)
806
state_getslice(SRE_STATE* state, Py_ssize_t index, PyObject* string, int empty)
807
735k
{
808
735k
    Py_ssize_t i, j;
809
810
735k
    index = (index - 1) * 2;
811
812
735k
    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
735k
    } else {
820
735k
        i = STATE_OFFSET(state, state->mark[index]);
821
735k
        j = STATE_OFFSET(state, state->mark[index+1]);
822
823
        /* check wrong span */
824
735k
        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
735k
    }
831
832
735k
    return getslice(state->isbytes, state->beginning, string, i, j);
833
735k
}
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
14.4k
{
864
14.4k
    PatternObject *self = _PatternObject_CAST(op);
865
14.4k
    Py_VISIT(Py_TYPE(self));
866
14.4k
    Py_VISIT(self->groupindex);
867
14.4k
    Py_VISIT(self->indexgroup);
868
14.4k
    Py_VISIT(self->pattern);
869
#ifdef Py_DEBUG
870
    Py_VISIT(self->fail_after_exc);
871
#endif
872
14.4k
    return 0;
873
14.4k
}
874
875
static int
876
pattern_clear(PyObject *op)
877
2.95k
{
878
2.95k
    PatternObject *self = _PatternObject_CAST(op);
879
2.95k
    Py_CLEAR(self->groupindex);
880
2.95k
    Py_CLEAR(self->indexgroup);
881
2.95k
    Py_CLEAR(self->pattern);
882
#ifdef Py_DEBUG
883
    Py_CLEAR(self->fail_after_exc);
884
#endif
885
2.95k
    return 0;
886
2.95k
}
887
888
static void
889
pattern_dealloc(PyObject *self)
890
2.95k
{
891
2.95k
    PyTypeObject *tp = Py_TYPE(self);
892
2.95k
    PyObject_GC_UnTrack(self);
893
2.95k
    FT_CLEAR_WEAKREFS(self, _PatternObject_CAST(self)->weakreflist);
894
2.95k
    (void)pattern_clear(self);
895
2.95k
    tp->tp_free(self);
896
2.95k
    Py_DECREF(tp);
897
2.95k
}
898
899
LOCAL(Py_ssize_t)
900
sre_match(SRE_STATE* state, SRE_CODE* pattern)
901
43.0M
{
902
43.0M
    if (state->charsize == 1)
903
36.5M
        return sre_ucs1_match(state, pattern, 1);
904
6.44M
    if (state->charsize == 2)
905
6.06M
        return sre_ucs2_match(state, pattern, 1);
906
6.44M
    assert(state->charsize == 4);
907
383k
    return sre_ucs4_match(state, pattern, 1);
908
6.44M
}
909
910
LOCAL(Py_ssize_t)
911
sre_search(SRE_STATE* state, SRE_CODE* pattern)
912
97.1M
{
913
97.1M
    if (state->charsize == 1)
914
47.7M
        return sre_ucs1_search(state, pattern);
915
49.4M
    if (state->charsize == 2)
916
43.9M
        return sre_ucs2_search(state, pattern);
917
49.4M
    assert(state->charsize == 4);
918
5.45M
    return sre_ucs4_search(state, pattern);
919
49.4M
}
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
43.0M
{
939
43.0M
    _sremodulestate *module_state = get_sre_module_state_by_class(cls);
940
43.0M
    SRE_STATE state;
941
43.0M
    Py_ssize_t status;
942
43.0M
    PyObject *match;
943
944
43.0M
    if (!state_init(&state, self, string, pos, endpos))
945
0
        return NULL;
946
947
43.0M
    INIT_TRACE(&state);
948
43.0M
    state.ptr = state.start;
949
950
43.0M
    TRACE(("|%p|%p|MATCH\n", PatternObject_GetCode(self), state.ptr));
951
952
43.0M
    status = sre_match(&state, PatternObject_GetCode(self));
953
954
43.0M
    TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
955
43.0M
    if (PyErr_Occurred()) {
956
0
        state_fini(&state);
957
0
        return NULL;
958
0
    }
959
960
43.0M
    match = pattern_new_match(module_state, self, &state, status);
961
43.0M
    state_fini(&state);
962
43.0M
    return match;
963
43.0M
}
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
21
{
984
21
    _sremodulestate *module_state = get_sre_module_state_by_class(cls);
985
21
    SRE_STATE state;
986
21
    Py_ssize_t status;
987
21
    PyObject *match;
988
989
21
    if (!state_init(&state, self, string, pos, endpos))
990
0
        return NULL;
991
992
21
    INIT_TRACE(&state);
993
21
    state.ptr = state.start;
994
995
21
    TRACE(("|%p|%p|FULLMATCH\n", PatternObject_GetCode(self), state.ptr));
996
997
21
    state.match_all = 1;
998
21
    status = sre_match(&state, PatternObject_GetCode(self));
999
1000
21
    TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
1001
21
    if (PyErr_Occurred()) {
1002
0
        state_fini(&state);
1003
0
        return NULL;
1004
0
    }
1005
1006
21
    match = pattern_new_match(module_state, self, &state, status);
1007
21
    state_fini(&state);
1008
21
    return match;
1009
21
}
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
5.33M
{
1032
5.33M
    _sremodulestate *module_state = get_sre_module_state_by_class(cls);
1033
5.33M
    SRE_STATE state;
1034
5.33M
    Py_ssize_t status;
1035
5.33M
    PyObject *match;
1036
1037
5.33M
    if (!state_init(&state, self, string, pos, endpos))
1038
0
        return NULL;
1039
1040
5.33M
    INIT_TRACE(&state);
1041
5.33M
    TRACE(("|%p|%p|SEARCH\n", PatternObject_GetCode(self), state.ptr));
1042
1043
5.33M
    status = sre_search(&state, PatternObject_GetCode(self));
1044
1045
5.33M
    TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
1046
1047
5.33M
    if (PyErr_Occurred()) {
1048
0
        state_fini(&state);
1049
0
        return NULL;
1050
0
    }
1051
1052
5.33M
    match = pattern_new_match(module_state, self, &state, status);
1053
5.33M
    state_fini(&state);
1054
5.33M
    return match;
1055
5.33M
}
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
3.65M
{
1072
3.65M
    SRE_STATE state;
1073
3.65M
    PyObject* list;
1074
3.65M
    Py_ssize_t status;
1075
3.65M
    Py_ssize_t i, b, e;
1076
1077
3.65M
    if (!state_init(&state, self, string, pos, endpos))
1078
0
        return NULL;
1079
1080
3.65M
    list = PyList_New(0);
1081
3.65M
    if (!list) {
1082
0
        state_fini(&state);
1083
0
        return NULL;
1084
0
    }
1085
1086
79.8M
    while (state.start <= state.end) {
1087
1088
79.8M
        PyObject* item;
1089
1090
79.8M
        state_reset(&state);
1091
1092
79.8M
        state.ptr = state.start;
1093
1094
79.8M
        status = sre_search(&state, PatternObject_GetCode(self));
1095
79.8M
        if (PyErr_Occurred())
1096
0
            goto error;
1097
1098
79.8M
        if (status <= 0) {
1099
3.65M
            if (status == 0)
1100
3.65M
                break;
1101
0
            pattern_error(status);
1102
0
            goto error;
1103
3.65M
        }
1104
1105
        /* don't bother to build a match object */
1106
76.1M
        switch (self->groups) {
1107
76.1M
        case 0:
1108
76.1M
            b = STATE_OFFSET(&state, state.start);
1109
76.1M
            e = STATE_OFFSET(&state, state.ptr);
1110
76.1M
            item = getslice(state.isbytes, state.beginning,
1111
76.1M
                            string, b, e);
1112
76.1M
            if (!item)
1113
0
                goto error;
1114
76.1M
            break;
1115
76.1M
        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
76.1M
        }
1134
1135
76.1M
        status = _PyList_AppendTakeRef((PyListObject *)list, item);
1136
76.1M
        if (status < 0)
1137
0
            goto error;
1138
1139
76.1M
        state.must_advance = (state.ptr == state.start);
1140
76.1M
        state.start = state.ptr;
1141
76.1M
    }
1142
1143
3.65M
    state_fini(&state);
1144
3.65M
    return list;
1145
1146
0
error:
1147
0
    Py_DECREF(list);
1148
0
    state_fini(&state);
1149
0
    return NULL;
1150
1151
3.65M
}
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
328k
{
1174
328k
    _sremodulestate *module_state = get_sre_module_state_by_class(cls);
1175
328k
    PyObject* scanner;
1176
328k
    PyObject* search;
1177
328k
    PyObject* iterator;
1178
1179
328k
    scanner = pattern_scanner(module_state, self, string, pos, endpos);
1180
328k
    if (!scanner)
1181
0
        return NULL;
1182
1183
328k
    search = PyObject_GetAttrString(scanner, "search");
1184
328k
    Py_DECREF(scanner);
1185
328k
    if (!search)
1186
0
        return NULL;
1187
1188
328k
    iterator = PyCallIter_New(search, Py_None);
1189
328k
    Py_DECREF(search);
1190
1191
328k
    return iterator;
1192
328k
}
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
1.15M
{
1230
1.15M
    SRE_STATE state;
1231
1.15M
    PyObject* list;
1232
1.15M
    PyObject* item;
1233
1.15M
    Py_ssize_t status;
1234
1.15M
    Py_ssize_t n;
1235
1.15M
    Py_ssize_t i;
1236
1.15M
    const void* last;
1237
1238
1.15M
    assert(self->codesize != 0);
1239
1240
1.15M
    if (!state_init(&state, self, string, 0, PY_SSIZE_T_MAX))
1241
0
        return NULL;
1242
1243
1.15M
    list = PyList_New(0);
1244
1.15M
    if (!list) {
1245
0
        state_fini(&state);
1246
0
        return NULL;
1247
0
    }
1248
1249
1.15M
    n = 0;
1250
1.15M
    last = state.start;
1251
1252
1.96M
    while (!maxsplit || n < maxsplit) {
1253
1254
1.22M
        state_reset(&state);
1255
1256
1.22M
        state.ptr = state.start;
1257
1258
1.22M
        status = sre_search(&state, PatternObject_GetCode(self));
1259
1.22M
        if (PyErr_Occurred())
1260
0
            goto error;
1261
1262
1.22M
        if (status <= 0) {
1263
423k
            if (status == 0)
1264
423k
                break;
1265
0
            pattern_error(status);
1266
0
            goto error;
1267
423k
        }
1268
1269
        /* get segment before this match */
1270
806k
        item = getslice(state.isbytes, state.beginning,
1271
806k
            string, STATE_OFFSET(&state, last),
1272
806k
            STATE_OFFSET(&state, state.start)
1273
806k
            );
1274
806k
        if (!item)
1275
0
            goto error;
1276
806k
        status = _PyList_AppendTakeRef((PyListObject *)list, item);
1277
806k
        if (status < 0)
1278
0
            goto error;
1279
1280
        /* add groups (if any) */
1281
1.54M
        for (i = 0; i < self->groups; i++) {
1282
735k
            item = state_getslice(&state, i+1, string, 0);
1283
735k
            if (!item)
1284
0
                goto error;
1285
735k
            status = _PyList_AppendTakeRef((PyListObject *)list, item);
1286
735k
            if (status < 0)
1287
0
                goto error;
1288
735k
        }
1289
1290
806k
        n = n + 1;
1291
806k
        state.must_advance = (state.ptr == state.start);
1292
806k
        last = state.start = state.ptr;
1293
1294
806k
    }
1295
1296
    /* get segment following last match (even if empty) */
1297
1.15M
    item = getslice(state.isbytes, state.beginning,
1298
1.15M
        string, STATE_OFFSET(&state, last), state.endpos
1299
1.15M
        );
1300
1.15M
    if (!item)
1301
0
        goto error;
1302
1.15M
    status = _PyList_AppendTakeRef((PyListObject *)list, item);
1303
1.15M
    if (status < 0)
1304
0
        goto error;
1305
1306
1.15M
    state_fini(&state);
1307
1.15M
    return list;
1308
1309
0
error:
1310
0
    Py_DECREF(list);
1311
0
    state_fini(&state);
1312
0
    return NULL;
1313
1314
1.15M
}
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
7.56M
{
1383
7.56M
    SRE_STATE state;
1384
7.56M
    PyObject* list;
1385
7.56M
    PyObject* joiner;
1386
7.56M
    PyObject* item;
1387
7.56M
    PyObject* filter;
1388
7.56M
    PyObject* match;
1389
7.56M
    const void* ptr;
1390
7.56M
    Py_ssize_t status;
1391
7.56M
    Py_ssize_t n;
1392
7.56M
    Py_ssize_t i, b, e;
1393
7.56M
    int isbytes, charsize;
1394
7.56M
    enum {LITERAL, TEMPLATE, CALLABLE} filter_type;
1395
7.56M
    Py_buffer view;
1396
1397
7.56M
    if (PyCallable_Check(ptemplate)) {
1398
        /* sub/subn takes either a function or a template */
1399
43.1k
        filter = Py_NewRef(ptemplate);
1400
43.1k
        filter_type = CALLABLE;
1401
7.52M
    } else {
1402
        /* if not callable, check if it's a literal string */
1403
7.52M
        int literal;
1404
7.52M
        view.buf = NULL;
1405
7.52M
        ptr = getstring(ptemplate, &n, &isbytes, &charsize, &view);
1406
7.52M
        if (ptr) {
1407
7.52M
            if (charsize == 1)
1408
7.52M
                literal = memchr(ptr, '\\', n) == NULL;
1409
0
            else
1410
0
                literal = PyUnicode_FindChar(ptemplate, '\\', 0, n, 1) == -1;
1411
7.52M
        } else {
1412
0
            PyErr_Clear();
1413
0
            literal = 0;
1414
0
        }
1415
7.52M
        if (view.buf)
1416
0
            PyBuffer_Release(&view);
1417
7.52M
        if (literal) {
1418
7.52M
            filter = Py_NewRef(ptemplate);
1419
7.52M
            filter_type = LITERAL;
1420
7.52M
        } 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
7.52M
    }
1437
1438
7.56M
    if (!state_init(&state, self, string, 0, PY_SSIZE_T_MAX)) {
1439
0
        Py_DECREF(filter);
1440
0
        return NULL;
1441
0
    }
1442
1443
7.56M
    list = PyList_New(0);
1444
7.56M
    if (!list) {
1445
0
        Py_DECREF(filter);
1446
0
        state_fini(&state);
1447
0
        return NULL;
1448
0
    }
1449
1450
7.56M
    n = i = 0;
1451
1452
7.62M
    while (!count || n < count) {
1453
1454
7.62M
        state_reset(&state);
1455
1456
7.62M
        state.ptr = state.start;
1457
1458
7.62M
        status = sre_search(&state, PatternObject_GetCode(self));
1459
7.62M
        if (PyErr_Occurred())
1460
0
            goto error;
1461
1462
7.62M
        if (status <= 0) {
1463
7.56M
            if (status == 0)
1464
7.56M
                break;
1465
0
            pattern_error(status);
1466
0
            goto error;
1467
7.56M
        }
1468
1469
54.2k
        b = STATE_OFFSET(&state, state.start);
1470
54.2k
        e = STATE_OFFSET(&state, state.ptr);
1471
1472
54.2k
        if (i < b) {
1473
            /* get segment before this match */
1474
26.2k
            item = getslice(state.isbytes, state.beginning,
1475
26.2k
                string, i, b);
1476
26.2k
            if (!item)
1477
0
                goto error;
1478
26.2k
            status = _PyList_AppendTakeRef((PyListObject *)list, item);
1479
26.2k
            if (status < 0)
1480
0
                goto error;
1481
1482
26.2k
        }
1483
1484
54.2k
        if (filter_type != LITERAL) {
1485
            /* pass match object through filter */
1486
51.2k
            match = pattern_new_match(module_state, self, &state, 1);
1487
51.2k
            if (!match)
1488
0
                goto error;
1489
51.2k
            if (filter_type == TEMPLATE) {
1490
0
                item = expand_template((TemplateObject *)filter,
1491
0
                                       (MatchObject *)match);
1492
0
            }
1493
51.2k
            else {
1494
51.2k
                assert(filter_type == CALLABLE);
1495
51.2k
                item = PyObject_CallOneArg(filter, match);
1496
51.2k
            }
1497
51.2k
            Py_DECREF(match);
1498
51.2k
            if (!item)
1499
0
                goto error;
1500
51.2k
        } else {
1501
            /* filter is literal string */
1502
3.04k
            item = Py_NewRef(filter);
1503
3.04k
        }
1504
1505
        /* add to list */
1506
54.2k
        if (item != Py_None) {
1507
54.2k
            status = _PyList_AppendTakeRef((PyListObject *)list, item);
1508
54.2k
            if (status < 0)
1509
0
                goto error;
1510
54.2k
        }
1511
1512
54.2k
        i = e;
1513
54.2k
        n = n + 1;
1514
54.2k
        state.must_advance = (state.ptr == state.start);
1515
54.2k
        state.start = state.ptr;
1516
54.2k
    }
1517
1518
    /* get segment following last match */
1519
7.56M
    if (i < state.endpos) {
1520
5.36M
        item = getslice(state.isbytes, state.beginning,
1521
5.36M
                        string, i, state.endpos);
1522
5.36M
        if (!item)
1523
0
            goto error;
1524
5.36M
        status = _PyList_AppendTakeRef((PyListObject *)list, item);
1525
5.36M
        if (status < 0)
1526
0
            goto error;
1527
5.36M
    }
1528
1529
7.56M
    state_fini(&state);
1530
1531
7.56M
    Py_DECREF(filter);
1532
1533
    /* convert list to single string (also removes list) */
1534
7.56M
    joiner = getslice(state.isbytes, state.beginning, string, 0, 0);
1535
7.56M
    if (!joiner) {
1536
0
        Py_DECREF(list);
1537
0
        return NULL;
1538
0
    }
1539
7.56M
    if (PyList_GET_SIZE(list) == 0) {
1540
2.19M
        Py_DECREF(list);
1541
2.19M
        item = joiner;
1542
2.19M
    }
1543
5.37M
    else {
1544
5.37M
        if (state.isbytes)
1545
32.1k
            item = PyBytes_Join(joiner, list);
1546
5.34M
        else
1547
5.34M
            item = PyUnicode_Join(joiner, list);
1548
5.37M
        Py_DECREF(joiner);
1549
5.37M
        Py_DECREF(list);
1550
5.37M
        if (!item)
1551
0
            return NULL;
1552
5.37M
    }
1553
1554
7.56M
    if (subn)
1555
0
        return Py_BuildValue("Nn", item, n);
1556
1557
7.56M
    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
7.56M
}
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
7.56M
{
1585
7.56M
    _sremodulestate *module_state = get_sre_module_state_by_class(cls);
1586
1587
7.56M
    return pattern_subx(module_state, self, repl, string, count, 0);
1588
7.56M
}
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
3.30k
{
1777
    /* "compile" pattern descriptor to pattern object */
1778
1779
3.30k
    _sremodulestate *module_state = get_sre_module_state(module);
1780
3.30k
    PatternObject* self;
1781
3.30k
    Py_ssize_t i, n;
1782
1783
3.30k
    n = PyList_GET_SIZE(code);
1784
    /* coverity[ampersand_in_size] */
1785
3.30k
    self = PyObject_GC_NewVar(PatternObject, module_state->Pattern_Type, n);
1786
3.30k
    if (!self)
1787
0
        return NULL;
1788
3.30k
    self->weakreflist = NULL;
1789
3.30k
    self->pattern = NULL;
1790
3.30k
    self->groupindex = NULL;
1791
3.30k
    self->indexgroup = NULL;
1792
#ifdef Py_DEBUG
1793
    self->fail_after_count = -1;
1794
    self->fail_after_exc = NULL;
1795
#endif
1796
1797
3.30k
    self->codesize = n;
1798
1799
65.8M
    for (i = 0; i < n; i++) {
1800
65.8M
        PyObject *o = PyList_GET_ITEM(code, i);
1801
65.8M
        unsigned long value = PyLong_AsUnsignedLong(o);
1802
65.8M
        if (value == (unsigned long)-1 && PyErr_Occurred()) {
1803
0
            break;
1804
0
        }
1805
65.8M
        self->code[i] = (SRE_CODE) value;
1806
65.8M
        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
65.8M
    }
1812
3.30k
    PyObject_GC_Track(self);
1813
1814
3.30k
    if (PyErr_Occurred()) {
1815
0
        Py_DECREF(self);
1816
0
        return NULL;
1817
0
    }
1818
1819
3.30k
    if (pattern == Py_None) {
1820
0
        self->isbytes = -1;
1821
0
    }
1822
3.30k
    else {
1823
3.30k
        Py_ssize_t p_length;
1824
3.30k
        int charsize;
1825
3.30k
        Py_buffer view;
1826
3.30k
        view.buf = NULL;
1827
3.30k
        if (!getstring(pattern, &p_length, &self->isbytes,
1828
3.30k
                       &charsize, &view)) {
1829
0
            Py_DECREF(self);
1830
0
            return NULL;
1831
0
        }
1832
3.30k
        if (view.buf)
1833
48
            PyBuffer_Release(&view);
1834
3.30k
    }
1835
1836
3.30k
    self->pattern = Py_NewRef(pattern);
1837
1838
3.30k
    self->flags = flags;
1839
1840
3.30k
    self->groups = groups;
1841
1842
3.30k
    if (PyDict_GET_SIZE(groupindex) > 0) {
1843
59
        self->groupindex = Py_NewRef(groupindex);
1844
59
        if (PyTuple_GET_SIZE(indexgroup) > 0) {
1845
59
            self->indexgroup = Py_NewRef(indexgroup);
1846
59
        }
1847
59
    }
1848
1849
3.30k
    if (!_validate(self)) {
1850
0
        Py_DECREF(self);
1851
0
        return NULL;
1852
0
    }
1853
1854
3.30k
    return (PyObject*) self;
1855
3.30k
}
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
102M
#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
23.8M
    do {                                                \
1962
23.8M
        VTRACE(("%p: ", code));                         \
1963
23.8M
        if (code >= end) FAIL;                          \
1964
23.8M
        op = *code++;                                   \
1965
23.8M
        VTRACE(("%lu (op)\n", (unsigned long)op));      \
1966
23.8M
    } while (0)
1967
#define GET_ARG                                         \
1968
21.5M
    do {                                                \
1969
21.5M
        VTRACE(("%p= ", code));                         \
1970
21.5M
        if (code >= end) FAIL;                          \
1971
21.5M
        arg = *code++;                                  \
1972
21.5M
        VTRACE(("%lu (arg)\n", (unsigned long)arg));    \
1973
21.5M
    } while (0)
1974
#define GET_SKIP_ADJ(adj)                               \
1975
4.08M
    do {                                                \
1976
4.08M
        VTRACE(("%p= ", code));                         \
1977
4.08M
        if (code >= end) FAIL;                          \
1978
4.08M
        skip = *code;                                   \
1979
4.08M
        VTRACE(("%lu (skip to %p)\n",                   \
1980
4.08M
               (unsigned long)skip, code+skip));        \
1981
4.08M
        if (skip-adj > (uintptr_t)(end - code))         \
1982
4.08M
            FAIL;                                       \
1983
4.08M
        code++;                                         \
1984
4.08M
    } while (0)
1985
4.08M
#define GET_SKIP GET_SKIP_ADJ(0)
1986
1987
static int
1988
_validate_category(SRE_CODE arg)
1989
1.19k
{
1990
1.19k
    switch (arg) {
1991
34
    case SRE_CATEGORY_DIGIT:
1992
34
    case SRE_CATEGORY_NOT_DIGIT:
1993
66
    case SRE_CATEGORY_SPACE:
1994
68
    case SRE_CATEGORY_NOT_SPACE:
1995
94
    case SRE_CATEGORY_WORD:
1996
96
    case SRE_CATEGORY_NOT_WORD:
1997
96
    case SRE_CATEGORY_LINEBREAK:
1998
96
    case SRE_CATEGORY_NOT_LINEBREAK:
1999
96
    case SRE_CATEGORY_LOC_WORD:
2000
96
    case SRE_CATEGORY_LOC_NOT_WORD:
2001
266
    case SRE_CATEGORY_UNI_DIGIT:
2002
549
    case SRE_CATEGORY_UNI_NOT_DIGIT:
2003
1.06k
    case SRE_CATEGORY_UNI_SPACE:
2004
1.07k
    case SRE_CATEGORY_UNI_NOT_SPACE:
2005
1.14k
    case SRE_CATEGORY_UNI_WORD:
2006
1.15k
    case SRE_CATEGORY_UNI_NOT_WORD:
2007
1.15k
    case SRE_CATEGORY_UNI_LINEBREAK:
2008
1.15k
    case SRE_CATEGORY_UNI_NOT_LINEBREAK:
2009
1.16k
    case SRE_CATEGORY_ALPHA:
2010
1.17k
    case SRE_CATEGORY_NOT_ALPHA:
2011
1.17k
    case SRE_CATEGORY_LOWER:
2012
1.17k
    case SRE_CATEGORY_NOT_LOWER:
2013
1.17k
    case SRE_CATEGORY_UPPER:
2014
1.17k
    case SRE_CATEGORY_NOT_UPPER:
2015
1.17k
    case SRE_CATEGORY_NUMERIC:
2016
1.17k
    case SRE_CATEGORY_NOT_NUMERIC:
2017
1.17k
    case SRE_CATEGORY_PRINTABLE:
2018
1.17k
    case SRE_CATEGORY_NOT_PRINTABLE:
2019
1.17k
    case SRE_CATEGORY_ALNUM:
2020
1.17k
    case SRE_CATEGORY_NOT_ALNUM:
2021
1.17k
    case SRE_CATEGORY_XID_START:
2022
1.17k
    case SRE_CATEGORY_NOT_XID_START:
2023
1.17k
    case SRE_CATEGORY_XID_CONTINUE:
2024
1.17k
    case SRE_CATEGORY_NOT_XID_CONTINUE:
2025
1.17k
    case SRE_CATEGORY_TITLE:
2026
1.17k
    case SRE_CATEGORY_NOT_TITLE:
2027
1.17k
    case SRE_CATEGORY_CASED:
2028
1.17k
    case SRE_CATEGORY_NOT_CASED:
2029
1.17k
    case SRE_CATEGORY_CASE_IGNORABLE:
2030
1.17k
    case SRE_CATEGORY_NOT_CASE_IGNORABLE:
2031
1.17k
    case SRE_CATEGORY_LU:
2032
1.18k
    case SRE_CATEGORY_NOT_LU:
2033
1.18k
    case SRE_CATEGORY_N:
2034
1.18k
    case SRE_CATEGORY_NOT_N:
2035
1.18k
    case SRE_CATEGORY_LM:
2036
1.18k
    case SRE_CATEGORY_NOT_LM:
2037
1.18k
    case SRE_CATEGORY_NL:
2038
1.18k
    case SRE_CATEGORY_NOT_NL:
2039
1.18k
    case SRE_CATEGORY_NO:
2040
1.18k
    case SRE_CATEGORY_NOT_NO:
2041
1.18k
    case SRE_CATEGORY_CF:
2042
1.18k
    case SRE_CATEGORY_NOT_CF:
2043
1.18k
    case SRE_CATEGORY_Z:
2044
1.18k
    case SRE_CATEGORY_NOT_Z:
2045
1.18k
    case SRE_CATEGORY_ZS:
2046
1.19k
    case SRE_CATEGORY_NOT_ZS:
2047
1.19k
    case SRE_CATEGORY_C:
2048
1.19k
    case SRE_CATEGORY_NOT_C:
2049
1.19k
    case SRE_CATEGORY_CN:
2050
1.19k
    case SRE_CATEGORY_NOT_CN:
2051
1.19k
    case SRE_CATEGORY_ASSIGNED:
2052
1.19k
    case SRE_CATEGORY_NOT_ASSIGNED:
2053
1.19k
    case SRE_CATEGORY_BLANK:
2054
1.19k
    case SRE_CATEGORY_NOT_BLANK:
2055
1.19k
    case SRE_CATEGORY_GRAPH:
2056
1.19k
    case SRE_CATEGORY_NOT_GRAPH:
2057
1.19k
    case SRE_CATEGORY_PRINT:
2058
1.19k
    case SRE_CATEGORY_NOT_PRINT:
2059
1.19k
        return 1;
2060
0
    default:
2061
0
        return 0;
2062
1.19k
    }
2063
1.19k
}
2064
2065
static int
2066
_validate_charset(SRE_CODE *code, SRE_CODE *end)
2067
1.35M
{
2068
    /* Some variables are manipulated by the macros above */
2069
1.35M
    SRE_CODE op;
2070
1.35M
    SRE_CODE arg;
2071
1.35M
    SRE_CODE offset;
2072
1.35M
    int i;
2073
2074
3.97M
    while (code < end) {
2075
2.61M
        GET_OP;
2076
2.61M
        switch (op) {
2077
2078
1.12k
        case SRE_OP_NEGATE:
2079
1.12k
            break;
2080
2081
2.52M
        case SRE_OP_LITERAL:
2082
2.52M
            GET_ARG;
2083
2.52M
            break;
2084
2085
2.52M
        case SRE_OP_RANGE:
2086
3.77k
        case SRE_OP_RANGE_UNI_IGNORE:
2087
3.77k
            GET_ARG;
2088
3.77k
            GET_ARG;
2089
3.77k
            break;
2090
2091
3.77k
        case SRE_OP_CHARSET:
2092
702
            offset = 256/SRE_CODE_BITS; /* 256-bit bitmap */
2093
702
            if (offset > (uintptr_t)(end - code))
2094
0
                FAIL;
2095
702
            code += offset;
2096
702
            break;
2097
2098
90.1k
        case SRE_OP_BIGCHARSET:
2099
90.1k
            GET_ARG; /* Number of blocks */
2100
90.1k
            offset = 256/sizeof(SRE_CODE); /* 256-byte table */
2101
90.1k
            if (offset > (uintptr_t)(end - code))
2102
0
                FAIL;
2103
            /* Make sure that each byte points to a valid block */
2104
23.1M
            for (i = 0; i < 256; i++) {
2105
23.0M
                if (((unsigned char *)code)[i] >= arg)
2106
0
                    FAIL;
2107
23.0M
            }
2108
90.1k
            code += offset;
2109
90.1k
            offset = arg * (256/SRE_CODE_BITS); /* 256-bit bitmap times arg */
2110
90.1k
            if (offset > (uintptr_t)(end - code))
2111
0
                FAIL;
2112
90.1k
            code += offset;
2113
90.1k
            break;
2114
2115
535
        case SRE_OP_CATEGORY:
2116
535
            GET_ARG;
2117
535
            if (!_validate_category(arg)) {
2118
0
                FAIL;
2119
0
            }
2120
535
            break;
2121
2122
535
        default:
2123
0
            FAIL;
2124
2125
2.61M
        }
2126
2.61M
    }
2127
2128
1.35M
    return 0;
2129
1.35M
}
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
1.80M
{
2135
    /* Some variables are manipulated by the macros above */
2136
1.80M
    SRE_CODE op;
2137
1.80M
    SRE_CODE arg;
2138
1.80M
    SRE_CODE skip;
2139
2140
1.80M
    VTRACE(("code=%p, end=%p\n", code, end));
2141
2142
1.80M
    if (code > end)
2143
0
        FAIL;
2144
2145
21.2M
    while (code < end) {
2146
19.4M
        GET_OP;
2147
19.4M
        switch (op) {
2148
2149
174k
        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
174k
            GET_ARG;
2154
174k
            if (arg >= 2 * (size_t)groups) {
2155
0
                VTRACE(("arg=%d, groups=%d\n", (int)arg, (int)groups));
2156
0
                FAIL;
2157
0
            }
2158
174k
            break;
2159
2160
12.6M
        case SRE_OP_LITERAL:
2161
12.6M
        case SRE_OP_NOT_LITERAL:
2162
12.7M
        case SRE_OP_LITERAL_IGNORE:
2163
12.7M
        case SRE_OP_NOT_LITERAL_IGNORE:
2164
16.9M
        case SRE_OP_LITERAL_UNI_IGNORE:
2165
16.9M
        case SRE_OP_NOT_LITERAL_UNI_IGNORE:
2166
16.9M
        case SRE_OP_LITERAL_LOC_IGNORE:
2167
16.9M
        case SRE_OP_NOT_LITERAL_LOC_IGNORE:
2168
16.9M
            GET_ARG;
2169
            /* The arg is just a character, nothing to check */
2170
16.9M
            break;
2171
2172
16.9M
        case SRE_OP_SUCCESS:
2173
97
        case SRE_OP_FAILURE:
2174
            /* Nothing to check; these normally end the matching process */
2175
97
            break;
2176
2177
34.6k
        case SRE_OP_AT:
2178
34.6k
            GET_ARG;
2179
34.6k
            switch (arg) {
2180
41
            case SRE_AT_BEGINNING:
2181
50
            case SRE_AT_BEGINNING_STRING:
2182
14.6k
            case SRE_AT_BEGINNING_LINE:
2183
14.7k
            case SRE_AT_END:
2184
16.9k
            case SRE_AT_END_LINE:
2185
17.0k
            case SRE_AT_END_STRING:
2186
17.0k
            case SRE_AT_BOUNDARY:
2187
17.0k
            case SRE_AT_NON_BOUNDARY:
2188
17.0k
            case SRE_AT_LOC_BOUNDARY:
2189
17.0k
            case SRE_AT_LOC_NON_BOUNDARY:
2190
34.6k
            case SRE_AT_UNI_BOUNDARY:
2191
34.6k
            case SRE_AT_UNI_NON_BOUNDARY:
2192
34.6k
                break;
2193
0
            default:
2194
0
                FAIL;
2195
34.6k
            }
2196
34.6k
            break;
2197
2198
34.6k
        case SRE_OP_CATEGORY:
2199
657
            GET_ARG;
2200
657
            if (!_validate_category(arg)) {
2201
0
                FAIL;
2202
0
            }
2203
657
            break;
2204
2205
51.5k
        case SRE_OP_ANY:
2206
51.5k
        case SRE_OP_ANY_ALL:
2207
            /* These have no operands */
2208
51.5k
            break;
2209
2210
3.70k
        case SRE_OP_IN:
2211
4.30k
        case SRE_OP_IN_IGNORE:
2212
1.35M
        case SRE_OP_IN_UNI_IGNORE:
2213
1.35M
        case SRE_OP_IN_LOC_IGNORE:
2214
1.35M
            GET_SKIP;
2215
            /* Stop 1 before the end; we check the FAILURE below */
2216
1.35M
            if (_validate_charset(code, code+skip-2))
2217
0
                FAIL;
2218
1.35M
            if (code[skip-2] != SRE_OP_FAILURE)
2219
0
                FAIL;
2220
1.35M
            code += skip-1;
2221
1.35M
            break;
2222
2223
3.30k
        case SRE_OP_INFO:
2224
3.30k
            {
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
3.30k
                SRE_CODE flags, i;
2230
3.30k
                SRE_CODE *newcode;
2231
3.30k
                GET_SKIP;
2232
3.30k
                newcode = code+skip-1;
2233
3.30k
                GET_ARG; flags = arg;
2234
3.30k
                GET_ARG;
2235
3.30k
                GET_ARG;
2236
                /* Check that only valid flags are present */
2237
3.30k
                if ((flags & ~(SRE_INFO_PREFIX |
2238
3.30k
                               SRE_INFO_LITERAL |
2239
3.30k
                               SRE_INFO_CHARSET)) != 0)
2240
0
                    FAIL;
2241
                /* PREFIX and CHARSET are mutually exclusive */
2242
3.30k
                if ((flags & SRE_INFO_PREFIX) &&
2243
1.40k
                    (flags & SRE_INFO_CHARSET))
2244
0
                    FAIL;
2245
                /* LITERAL implies PREFIX */
2246
3.30k
                if ((flags & SRE_INFO_LITERAL) &&
2247
603
                    !(flags & SRE_INFO_PREFIX))
2248
0
                    FAIL;
2249
                /* Validate the prefix */
2250
3.30k
                if (flags & SRE_INFO_PREFIX) {
2251
1.40k
                    SRE_CODE prefix_len;
2252
1.40k
                    GET_ARG; prefix_len = arg;
2253
1.40k
                    GET_ARG;
2254
                    /* Here comes the prefix string */
2255
1.40k
                    if (prefix_len > (uintptr_t)(newcode - code))
2256
0
                        FAIL;
2257
1.40k
                    code += prefix_len;
2258
                    /* And here comes the overlap table */
2259
1.40k
                    if (prefix_len > (uintptr_t)(newcode - code))
2260
0
                        FAIL;
2261
                    /* Each overlap value should be < prefix_len */
2262
3.44M
                    for (i = 0; i < prefix_len; i++) {
2263
3.44M
                        if (code[i] >= prefix_len)
2264
0
                            FAIL;
2265
3.44M
                    }
2266
1.40k
                    code += prefix_len;
2267
1.40k
                }
2268
                /* Validate the charset */
2269
3.30k
                if (flags & SRE_INFO_CHARSET) {
2270
399
                    if (_validate_charset(code, newcode-1))
2271
0
                        FAIL;
2272
399
                    if (newcode[-1] != SRE_OP_FAILURE)
2273
0
                        FAIL;
2274
399
                    code = newcode;
2275
399
                }
2276
2.90k
                else if (code != newcode) {
2277
0
                  VTRACE(("code=%p, newcode=%p\n", code, newcode));
2278
0
                    FAIL;
2279
0
                }
2280
3.30k
            }
2281
3.30k
            break;
2282
2283
24.4k
        case SRE_OP_BRANCH:
2284
24.4k
            {
2285
24.4k
                SRE_CODE *target = NULL;
2286
927k
                for (;;) {
2287
927k
                    GET_SKIP;
2288
927k
                    if (skip == 0)
2289
24.4k
                        break;
2290
                    /* Stop 2 before the end; we check the JUMP below */
2291
903k
                    if (_validate_inner(code, code+skip-3, groups))
2292
0
                        FAIL;
2293
903k
                    code += skip-3;
2294
                    /* Check that it ends with a JUMP, and that each JUMP
2295
                       has the same target */
2296
903k
                    GET_OP;
2297
903k
                    if (op != SRE_OP_JUMP)
2298
0
                        FAIL;
2299
903k
                    GET_SKIP;
2300
903k
                    if (target == NULL)
2301
24.4k
                        target = code+skip-1;
2302
878k
                    else if (code+skip-1 != target)
2303
0
                        FAIL;
2304
903k
                }
2305
24.4k
                if (code != target)
2306
0
                    FAIL;
2307
24.4k
            }
2308
24.4k
            break;
2309
2310
858k
        case SRE_OP_REPEAT_ONE:
2311
859k
        case SRE_OP_MIN_REPEAT_ONE:
2312
859k
        case SRE_OP_POSSESSIVE_REPEAT_ONE:
2313
859k
            {
2314
859k
                SRE_CODE min, max;
2315
859k
                GET_SKIP;
2316
859k
                GET_ARG; min = arg;
2317
859k
                GET_ARG; max = arg;
2318
859k
                if (min > max)
2319
0
                    FAIL;
2320
859k
                if (max > SRE_MAXREPEAT)
2321
0
                    FAIL;
2322
859k
                if (_validate_inner(code, code+skip-4, groups))
2323
0
                    FAIL;
2324
859k
                code += skip-4;
2325
859k
                GET_OP;
2326
859k
                if (op != SRE_OP_SUCCESS)
2327
0
                    FAIL;
2328
859k
            }
2329
859k
            break;
2330
2331
859k
        case SRE_OP_REPEAT:
2332
31.1k
        case SRE_OP_POSSESSIVE_REPEAT:
2333
31.1k
            {
2334
31.1k
                SRE_CODE op1 = op, min, max;
2335
31.1k
                GET_SKIP;
2336
31.1k
                GET_ARG; min = arg;
2337
31.1k
                GET_ARG; max = arg;
2338
31.1k
                if (min > max)
2339
0
                    FAIL;
2340
31.1k
                if (max > SRE_MAXREPEAT)
2341
0
                    FAIL;
2342
31.1k
                if (_validate_inner(code, code+skip-3, groups))
2343
0
                    FAIL;
2344
31.1k
                code += skip-3;
2345
31.1k
                GET_OP;
2346
31.1k
                if (op1 == SRE_OP_POSSESSIVE_REPEAT) {
2347
40
                    if (op != SRE_OP_SUCCESS)
2348
0
                        FAIL;
2349
40
                }
2350
31.1k
                else {
2351
31.1k
                    if (op != SRE_OP_MAX_UNTIL && op != SRE_OP_MIN_UNTIL)
2352
0
                        FAIL;
2353
31.1k
                }
2354
31.1k
            }
2355
31.1k
            break;
2356
2357
31.1k
        case SRE_OP_ATOMIC_GROUP:
2358
339
            {
2359
339
                GET_SKIP;
2360
339
                if (_validate_inner(code, code+skip-2, groups))
2361
0
                    FAIL;
2362
339
                code += skip-2;
2363
339
                GET_OP;
2364
339
                if (op != SRE_OP_SUCCESS)
2365
0
                    FAIL;
2366
339
            }
2367
339
            break;
2368
2369
339
        case SRE_OP_GROUPREF:
2370
694
        case SRE_OP_GROUPREF_IGNORE:
2371
1.31k
        case SRE_OP_GROUPREF_UNI_IGNORE:
2372
1.31k
        case SRE_OP_GROUPREF_LOC_IGNORE:
2373
1.31k
            GET_ARG;
2374
1.31k
            if (arg >= (size_t)groups)
2375
0
                FAIL;
2376
1.31k
            break;
2377
2378
1.31k
        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
92
            GET_ARG;
2383
92
            if (arg >= (size_t)groups)
2384
0
                FAIL;
2385
92
            GET_SKIP_ADJ(1);
2386
92
            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
92
            VTRACE(("then part:\n"));
2413
92
            int rc = _validate_inner(code+1, code+skip-1, groups);
2414
92
            if (rc == 1) {
2415
74
                VTRACE(("else part:\n"));
2416
74
                code += skip-2; /* Position after JUMP, at <skipno> */
2417
74
                GET_SKIP;
2418
74
                rc = _validate_inner(code, code+skip-1, groups);
2419
74
            }
2420
92
            if (rc)
2421
0
                FAIL;
2422
92
            code += skip-1;
2423
92
            break;
2424
2425
7.15k
        case SRE_OP_ASSERT:
2426
8.17k
        case SRE_OP_ASSERT_NOT:
2427
8.17k
            GET_SKIP;
2428
8.17k
            GET_ARG; /* 0 for lookahead, width for lookbehind */
2429
8.17k
            code--; /* Back up over arg to simplify math below */
2430
            /* Stop 1 before the end; we check the SUCCESS below */
2431
8.17k
            if (_validate_inner(code+1, code+skip-2, groups))
2432
0
                FAIL;
2433
8.17k
            code += skip-2;
2434
8.17k
            GET_OP;
2435
8.17k
            if (op != SRE_OP_SUCCESS)
2436
0
                FAIL;
2437
8.17k
            break;
2438
2439
8.17k
        case SRE_OP_JUMP:
2440
74
            if (code + 1 != end)
2441
0
                FAIL;
2442
74
            VTRACE(("JUMP: %d\n", __LINE__));
2443
74
            return 1;
2444
2445
0
        default:
2446
0
            FAIL;
2447
2448
19.4M
        }
2449
19.4M
    }
2450
2451
1.80M
    VTRACE(("okay\n"));
2452
1.80M
    return 0;
2453
1.80M
}
2454
2455
static int
2456
_validate_outer(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups)
2457
3.30k
{
2458
3.30k
    if (groups < 0 || (size_t)groups > SRE_MAXGROUPS ||
2459
3.30k
        code >= end || end[-1] != SRE_OP_SUCCESS)
2460
0
        FAIL;
2461
3.30k
    return _validate_inner(code, end-1, groups);
2462
3.30k
}
2463
2464
static int
2465
_validate(PatternObject *self)
2466
3.30k
{
2467
3.30k
    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
3.30k
    else
2473
3.30k
        VTRACE(("Success!\n"));
2474
3.30k
    return 1;
2475
3.30k
}
2476
2477
/* -------------------------------------------------------------------- */
2478
/* match methods */
2479
2480
static int
2481
match_traverse(PyObject *op, visitproc visit, void *arg)
2482
48.3k
{
2483
48.3k
    MatchObject *self = _MatchObject_CAST(op);
2484
48.3k
    Py_VISIT(Py_TYPE(self));
2485
48.3k
    Py_VISIT(self->string);
2486
48.3k
    Py_VISIT(self->regs);
2487
48.3k
    Py_VISIT(self->pattern);
2488
48.3k
    return 0;
2489
48.3k
}
2490
2491
static int
2492
match_clear(PyObject *op)
2493
36.0M
{
2494
36.0M
    MatchObject *self = _MatchObject_CAST(op);
2495
36.0M
    Py_CLEAR(self->string);
2496
36.0M
    Py_CLEAR(self->regs);
2497
36.0M
    Py_CLEAR(self->pattern);
2498
36.0M
    return 0;
2499
36.0M
}
2500
2501
static void
2502
match_dealloc(PyObject *self)
2503
36.0M
{
2504
36.0M
    PyTypeObject *tp = Py_TYPE(self);
2505
36.0M
    PyObject_GC_UnTrack(self);
2506
36.0M
    (void)match_clear(self);
2507
36.0M
    tp->tp_free(self);
2508
36.0M
    Py_DECREF(tp);
2509
36.0M
}
2510
2511
static PyObject*
2512
match_getslice_by_index(MatchObject* self, Py_ssize_t index, PyObject* def)
2513
28.8M
{
2514
28.8M
    Py_ssize_t length;
2515
28.8M
    int isbytes, charsize;
2516
28.8M
    Py_buffer view;
2517
28.8M
    PyObject *result;
2518
28.8M
    const void* ptr;
2519
28.8M
    Py_ssize_t i, j;
2520
2521
28.8M
    assert(0 <= index && index < self->groups);
2522
28.8M
    index *= 2;
2523
2524
28.8M
    if (self->string == Py_None || self->mark[index] < 0) {
2525
        /* return default value if the string or group is undefined */
2526
4.39M
        return Py_NewRef(def);
2527
4.39M
    }
2528
2529
24.4M
    ptr = getstring(self->string, &length, &isbytes, &charsize, &view);
2530
24.4M
    if (ptr == NULL)
2531
0
        return NULL;
2532
2533
24.4M
    i = self->mark[index];
2534
24.4M
    j = self->mark[index+1];
2535
24.4M
    i = Py_MIN(i, length);
2536
24.4M
    j = Py_MIN(j, length);
2537
24.4M
    result = getslice(isbytes, ptr, self->string, i, j);
2538
24.4M
    if (isbytes && view.buf != NULL)
2539
312k
        PyBuffer_Release(&view);
2540
24.4M
    return result;
2541
24.4M
}
2542
2543
static Py_ssize_t
2544
match_getindex(MatchObject* self, PyObject* index)
2545
38.3M
{
2546
38.3M
    Py_ssize_t i;
2547
2548
38.3M
    if (index == NULL)
2549
        /* Default value */
2550
9.07M
        return 0;
2551
2552
29.2M
    if (PyIndex_Check(index)) {
2553
7.31M
        i = PyNumber_AsSsize_t(index, NULL);
2554
7.31M
    }
2555
21.9M
    else {
2556
21.9M
        i = -1;
2557
2558
21.9M
        if (self->pattern->groupindex) {
2559
21.9M
            index = PyDict_GetItemWithError(self->pattern->groupindex, index);
2560
21.9M
            if (index && PyLong_Check(index)) {
2561
21.9M
                i = PyLong_AsSsize_t(index);
2562
21.9M
            }
2563
21.9M
        }
2564
21.9M
    }
2565
29.2M
    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
29.2M
    assert((size_t)i <= SRE_MAXGROUPS);
2575
29.2M
    return i;
2576
29.2M
}
2577
2578
static PyObject*
2579
match_getslice(MatchObject* self, PyObject* index, PyObject* def)
2580
28.7M
{
2581
28.7M
    Py_ssize_t i = match_getindex(self, index);
2582
2583
28.7M
    if (i < 0) {
2584
0
        return NULL;
2585
0
    }
2586
2587
28.7M
    return match_getslice_by_index(self, i, def);
2588
28.7M
}
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
/*[clinic input]
2614
_sre.SRE_Match.group
2615
2616
    *args: array
2617
2618
Return subgroup(s) of the match by indices or names.
2619
2620
For 0 returns the entire match.
2621
[clinic start generated code]*/
2622
2623
static PyObject *
2624
_sre_SRE_Match_group_impl(MatchObject *self, PyObject * const *args,
2625
                          Py_ssize_t args_length)
2626
/*[clinic end generated code: output=240cddd2cf62ee2a input=f6d9bfa0d01f3cda]*/
2627
12.9M
{
2628
12.9M
    PyObject* result;
2629
12.9M
    Py_ssize_t i;
2630
2631
12.9M
    switch (args_length) {
2632
3.56M
    case 0:
2633
3.56M
        result = match_getslice(self, _PyLong_GetZero(), Py_None);
2634
3.56M
        break;
2635
1.47M
    case 1:
2636
1.47M
        result = match_getslice(self, args[0], Py_None);
2637
1.47M
        break;
2638
7.87M
    default:
2639
        /* fetch multiple items */
2640
7.87M
        result = PyTuple_New(args_length);
2641
7.87M
        if (!result)
2642
0
            return NULL;
2643
28.7M
        for (i = 0; i < args_length; i++) {
2644
20.8M
            PyObject* item = match_getslice(self, args[i], Py_None);
2645
20.8M
            if (!item) {
2646
0
                Py_DECREF(result);
2647
0
                return NULL;
2648
0
            }
2649
20.8M
            PyTuple_SET_ITEM(result, i, item);
2650
20.8M
        }
2651
7.87M
        break;
2652
12.9M
    }
2653
12.9M
    return result;
2654
12.9M
}
2655
2656
static PyObject*
2657
match_getitem(PyObject *op, PyObject* name)
2658
2.82M
{
2659
2.82M
    MatchObject *self = _MatchObject_CAST(op);
2660
2.82M
    return match_getslice(self, name, Py_None);
2661
2.82M
}
2662
2663
/*[clinic input]
2664
_sre.SRE_Match.groups
2665
2666
    default: object = None
2667
        Is used for groups that did not participate in the match.
2668
2669
Return a tuple containing all the subgroups of the match, from 1.
2670
[clinic start generated code]*/
2671
2672
static PyObject *
2673
_sre_SRE_Match_groups_impl(MatchObject *self, PyObject *default_value)
2674
/*[clinic end generated code: output=daf8e2641537238a input=bb069ef55dabca91]*/
2675
17.9k
{
2676
17.9k
    PyObject* result;
2677
17.9k
    Py_ssize_t index;
2678
2679
17.9k
    result = PyTuple_New(self->groups-1);
2680
17.9k
    if (!result)
2681
0
        return NULL;
2682
2683
150k
    for (index = 1; index < self->groups; index++) {
2684
132k
        PyObject* item;
2685
132k
        item = match_getslice_by_index(self, index, default_value);
2686
132k
        if (!item) {
2687
0
            Py_DECREF(result);
2688
0
            return NULL;
2689
0
        }
2690
132k
        PyTuple_SET_ITEM(result, index-1, item);
2691
132k
    }
2692
2693
17.9k
    return result;
2694
17.9k
}
2695
2696
/*[clinic input]
2697
@permit_long_summary
2698
_sre.SRE_Match.groupdict
2699
2700
    default: object = None
2701
        Is used for groups that did not participate in the match.
2702
2703
Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name.
2704
[clinic start generated code]*/
2705
2706
static PyObject *
2707
_sre_SRE_Match_groupdict_impl(MatchObject *self, PyObject *default_value)
2708
/*[clinic end generated code: output=29917c9073e41757 input=a8d3a1dc80336872]*/
2709
137
{
2710
137
    PyObject *result;
2711
137
    PyObject *key;
2712
137
    PyObject *value;
2713
137
    Py_ssize_t pos = 0;
2714
137
    Py_hash_t hash;
2715
2716
137
    result = PyDict_New();
2717
137
    if (!result || !self->pattern->groupindex)
2718
0
        return result;
2719
2720
137
    Py_BEGIN_CRITICAL_SECTION(self->pattern->groupindex);
2721
911
    while (_PyDict_Next(self->pattern->groupindex, &pos, &key, &value, &hash)) {
2722
774
        int status;
2723
774
        Py_INCREF(key);
2724
774
        value = match_getslice(self, key, default_value);
2725
774
        if (!value) {
2726
0
            Py_DECREF(key);
2727
0
            Py_CLEAR(result);
2728
0
            goto exit;
2729
0
        }
2730
774
        status = _PyDict_SetItem_KnownHash(result, key, value, hash);
2731
774
        Py_DECREF(value);
2732
774
        Py_DECREF(key);
2733
774
        if (status < 0) {
2734
0
            Py_CLEAR(result);
2735
0
            goto exit;
2736
0
        }
2737
774
    }
2738
137
exit:;
2739
137
    Py_END_CRITICAL_SECTION();
2740
2741
137
    return result;
2742
137
}
2743
2744
/*[clinic input]
2745
_sre.SRE_Match.start -> Py_ssize_t
2746
2747
    group: object(c_default="NULL") = 0
2748
    /
2749
2750
Return index of the start of the substring matched by group.
2751
[clinic start generated code]*/
2752
2753
static Py_ssize_t
2754
_sre_SRE_Match_start_impl(MatchObject *self, PyObject *group)
2755
/*[clinic end generated code: output=3f6e7f9df2fb5201 input=ced8e4ed4b33ee6c]*/
2756
5.61M
{
2757
5.61M
    Py_ssize_t index = match_getindex(self, group);
2758
2759
5.61M
    if (index < 0) {
2760
0
        return -1;
2761
0
    }
2762
2763
    /* mark is -1 if group is undefined */
2764
5.61M
    return self->mark[index*2];
2765
5.61M
}
2766
2767
/*[clinic input]
2768
_sre.SRE_Match.end -> Py_ssize_t
2769
2770
    group: object(c_default="NULL") = 0
2771
    /
2772
2773
Return index of the end of the substring matched by group.
2774
[clinic start generated code]*/
2775
2776
static Py_ssize_t
2777
_sre_SRE_Match_end_impl(MatchObject *self, PyObject *group)
2778
/*[clinic end generated code: output=f4240b09911f7692 input=1b799560c7f3d7e6]*/
2779
1.18M
{
2780
1.18M
    Py_ssize_t index = match_getindex(self, group);
2781
2782
1.18M
    if (index < 0) {
2783
0
        return -1;
2784
0
    }
2785
2786
    /* mark is -1 if group is undefined */
2787
1.18M
    return self->mark[index*2+1];
2788
1.18M
}
2789
2790
LOCAL(PyObject*)
2791
_pair(Py_ssize_t i1, Py_ssize_t i2)
2792
2.84M
{
2793
2.84M
    PyObject* item1 = PyLong_FromSsize_t(i1);
2794
2.84M
    if (!item1) {
2795
0
        return NULL;
2796
0
    }
2797
2.84M
    PyObject* item2 = PyLong_FromSsize_t(i2);
2798
2.84M
    if(!item2) {
2799
0
        Py_DECREF(item1);
2800
0
        return NULL;
2801
0
    }
2802
2803
2.84M
    return _PyTuple_FromPairSteal(item1, item2);
2804
2.84M
}
2805
2806
/*[clinic input]
2807
@permit_long_summary
2808
_sre.SRE_Match.span
2809
2810
    group: object(c_default="NULL") = 0
2811
    /
2812
2813
For match object m, return the 2-tuple (m.start(group), m.end(group)).
2814
[clinic start generated code]*/
2815
2816
static PyObject *
2817
_sre_SRE_Match_span_impl(MatchObject *self, PyObject *group)
2818
/*[clinic end generated code: output=f02ae40594d14fe6 input=834cfe444f0f55cf]*/
2819
2.84M
{
2820
2.84M
    Py_ssize_t index = match_getindex(self, group);
2821
2822
2.84M
    if (index < 0) {
2823
0
        return NULL;
2824
0
    }
2825
2826
    /* marks are -1 if group is undefined */
2827
2.84M
    return _pair(self->mark[index*2], self->mark[index*2+1]);
2828
2.84M
}
2829
2830
static PyObject*
2831
match_regs(MatchObject* self)
2832
0
{
2833
0
    PyObject* regs;
2834
0
    PyObject* item;
2835
0
    Py_ssize_t index;
2836
2837
0
    regs = PyTuple_New(self->groups);
2838
0
    if (!regs)
2839
0
        return NULL;
2840
2841
0
    for (index = 0; index < self->groups; index++) {
2842
0
        item = _pair(self->mark[index*2], self->mark[index*2+1]);
2843
0
        if (!item) {
2844
0
            Py_DECREF(regs);
2845
0
            return NULL;
2846
0
        }
2847
0
        PyTuple_SET_ITEM(regs, index, item);
2848
0
    }
2849
2850
0
    self->regs = Py_NewRef(regs);
2851
2852
0
    return regs;
2853
0
}
2854
2855
/*[clinic input]
2856
_sre.SRE_Match.__copy__
2857
2858
[clinic start generated code]*/
2859
2860
static PyObject *
2861
_sre_SRE_Match___copy___impl(MatchObject *self)
2862
/*[clinic end generated code: output=a779c5fc8b5b4eb4 input=3bb4d30b6baddb5b]*/
2863
0
{
2864
0
    return Py_NewRef(self);
2865
0
}
2866
2867
/*[clinic input]
2868
_sre.SRE_Match.__deepcopy__
2869
2870
    memo: object
2871
    /
2872
2873
[clinic start generated code]*/
2874
2875
static PyObject *
2876
_sre_SRE_Match___deepcopy___impl(MatchObject *self, PyObject *memo)
2877
/*[clinic end generated code: output=2b657578eb03f4a3 input=779d12a31c2c325e]*/
2878
0
{
2879
0
    return Py_NewRef(self);
2880
0
}
2881
2882
PyDoc_STRVAR(match_doc,
2883
"The result of re.search(), re.prefixmatch(), and re.fullmatch().\n\
2884
Match objects always have a boolean value of True.");
2885
2886
static PyObject *
2887
match_lastindex_get(PyObject *op, void *Py_UNUSED(ignored))
2888
0
{
2889
0
    MatchObject *self = _MatchObject_CAST(op);
2890
0
    if (self->lastindex >= 0)
2891
0
        return PyLong_FromSsize_t(self->lastindex);
2892
0
    Py_RETURN_NONE;
2893
0
}
2894
2895
static PyObject *
2896
match_lastgroup_get(PyObject *op, void *Py_UNUSED(ignored))
2897
0
{
2898
0
    MatchObject *self = _MatchObject_CAST(op);
2899
0
    if (self->pattern->indexgroup &&
2900
0
        self->lastindex >= 0 &&
2901
0
        self->lastindex < PyTuple_GET_SIZE(self->pattern->indexgroup))
2902
0
    {
2903
0
        PyObject *result = PyTuple_GET_ITEM(self->pattern->indexgroup,
2904
0
                                            self->lastindex);
2905
0
        return Py_NewRef(result);
2906
0
    }
2907
0
    Py_RETURN_NONE;
2908
0
}
2909
2910
static PyObject *
2911
match_regs_get(PyObject *op, void *Py_UNUSED(ignored))
2912
0
{
2913
0
    MatchObject *self = _MatchObject_CAST(op);
2914
0
    if (self->regs) {
2915
0
        return Py_NewRef(self->regs);
2916
0
    } else
2917
0
        return match_regs(self);
2918
0
}
2919
2920
static PyObject *
2921
match_repr(PyObject *op)
2922
0
{
2923
0
    MatchObject *self = _MatchObject_CAST(op);
2924
0
    PyObject *result;
2925
0
    PyObject *group0 = match_getslice_by_index(self, 0, Py_None);
2926
0
    if (group0 == NULL)
2927
0
        return NULL;
2928
0
    result = PyUnicode_FromFormat(
2929
0
            "<%s object; span=(%zd, %zd), match=%.50R>",
2930
0
            Py_TYPE(self)->tp_name,
2931
0
            self->mark[0], self->mark[1], group0);
2932
0
    Py_DECREF(group0);
2933
0
    return result;
2934
0
}
2935
2936
2937
static PyObject*
2938
pattern_new_match(_sremodulestate* module_state,
2939
                  PatternObject* pattern,
2940
                  SRE_STATE* state,
2941
                  Py_ssize_t status)
2942
51.5M
{
2943
    /* create match object (from state object) */
2944
2945
51.5M
    MatchObject* match;
2946
51.5M
    Py_ssize_t i, j;
2947
51.5M
    char* base;
2948
51.5M
    int n;
2949
2950
51.5M
    if (status > 0) {
2951
2952
        /* create match object (with room for extra group marks) */
2953
        /* coverity[ampersand_in_size] */
2954
36.0M
        match = PyObject_GC_NewVar(MatchObject,
2955
36.0M
                                   module_state->Match_Type,
2956
36.0M
                                   2*(pattern->groups+1));
2957
36.0M
        if (!match)
2958
0
            return NULL;
2959
2960
36.0M
        Py_INCREF(pattern);
2961
36.0M
        match->pattern = pattern;
2962
2963
36.0M
        match->string = Py_NewRef(state->string);
2964
2965
36.0M
        match->regs = NULL;
2966
36.0M
        match->groups = pattern->groups+1;
2967
2968
        /* fill in group slices */
2969
2970
36.0M
        base = (char*) state->beginning;
2971
36.0M
        n = state->charsize;
2972
2973
36.0M
        match->mark[0] = ((char*) state->start - base) / n;
2974
36.0M
        match->mark[1] = ((char*) state->ptr - base) / n;
2975
2976
65.5M
        for (i = j = 0; i < pattern->groups; i++, j+=2)
2977
29.5M
            if (j+1 <= state->lastmark && state->mark[j] && state->mark[j+1]) {
2978
24.6M
                match->mark[j+2] = ((char*) state->mark[j] - base) / n;
2979
24.6M
                match->mark[j+3] = ((char*) state->mark[j+1] - base) / n;
2980
2981
                /* check wrong span */
2982
24.6M
                if (match->mark[j+2] > match->mark[j+3]) {
2983
0
                    PyErr_SetString(PyExc_SystemError,
2984
0
                                    "The span of capturing group is wrong,"
2985
0
                                    " please report a bug for the re module.");
2986
0
                    Py_DECREF(match);
2987
0
                    return NULL;
2988
0
                }
2989
24.6M
            } else
2990
4.90M
                match->mark[j+2] = match->mark[j+3] = -1; /* undefined */
2991
2992
36.0M
        match->pos = state->pos;
2993
36.0M
        match->endpos = state->endpos;
2994
2995
36.0M
        match->lastindex = state->lastindex;
2996
2997
36.0M
        PyObject_GC_Track(match);
2998
36.0M
        return (PyObject*) match;
2999
3000
36.0M
    } else if (status == 0) {
3001
3002
        /* no match */
3003
15.5M
        Py_RETURN_NONE;
3004
3005
15.5M
    }
3006
3007
    /* internal error */
3008
0
    pattern_error(status);
3009
0
    return NULL;
3010
51.5M
}
3011
3012
3013
/* -------------------------------------------------------------------- */
3014
/* scanner methods (experimental) */
3015
3016
static int
3017
scanner_traverse(PyObject *op, visitproc visit, void *arg)
3018
1.03k
{
3019
1.03k
    ScannerObject *self = _ScannerObject_CAST(op);
3020
1.03k
    Py_VISIT(Py_TYPE(self));
3021
1.03k
    Py_VISIT(self->pattern);
3022
1.03k
    return 0;
3023
1.03k
}
3024
3025
static int
3026
scanner_clear(PyObject *op)
3027
328k
{
3028
328k
    ScannerObject *self = _ScannerObject_CAST(op);
3029
328k
    Py_CLEAR(self->pattern);
3030
328k
    return 0;
3031
328k
}
3032
3033
static void
3034
scanner_dealloc(PyObject *self)
3035
328k
{
3036
328k
    PyTypeObject *tp = Py_TYPE(self);
3037
328k
    PyObject_GC_UnTrack(self);
3038
328k
    ScannerObject *scanner = _ScannerObject_CAST(self);
3039
328k
    state_fini(&scanner->state);
3040
328k
    (void)scanner_clear(self);
3041
328k
    tp->tp_free(self);
3042
328k
    Py_DECREF(tp);
3043
328k
}
3044
3045
static int
3046
scanner_begin(ScannerObject* self)
3047
3.15M
{
3048
#ifdef Py_GIL_DISABLED
3049
    int was_executing = _Py_atomic_exchange_int(&self->executing, 1);
3050
#else
3051
3.15M
    int was_executing = self->executing;
3052
3.15M
    self->executing = 1;
3053
3.15M
#endif
3054
3.15M
    if (was_executing) {
3055
0
        PyErr_SetString(PyExc_ValueError,
3056
0
                        "regular expression scanner already executing");
3057
0
        return 0;
3058
0
    }
3059
3.15M
    return 1;
3060
3.15M
}
3061
3062
static void
3063
scanner_end(ScannerObject* self)
3064
3.15M
{
3065
3.15M
    assert(FT_ATOMIC_LOAD_INT_RELAXED(self->executing));
3066
3.15M
    FT_ATOMIC_STORE_INT(self->executing, 0);
3067
3.15M
}
3068
3069
/*[clinic input]
3070
_sre.SRE_Scanner.prefixmatch
3071
3072
    cls: defining_class
3073
    /
3074
3075
[clinic start generated code]*/
3076
3077
static PyObject *
3078
_sre_SRE_Scanner_prefixmatch_impl(ScannerObject *self, PyTypeObject *cls)
3079
/*[clinic end generated code: output=02b3b9d2954a2157 input=3049b20466c56a8e]*/
3080
0
{
3081
0
    _sremodulestate *module_state = get_sre_module_state_by_class(cls);
3082
0
    SRE_STATE* state = &self->state;
3083
0
    PyObject* match;
3084
0
    Py_ssize_t status;
3085
3086
0
    if (!scanner_begin(self)) {
3087
0
        return NULL;
3088
0
    }
3089
0
    if (state->start == NULL) {
3090
0
        scanner_end(self);
3091
0
        Py_RETURN_NONE;
3092
0
    }
3093
3094
0
    state_reset(state);
3095
3096
0
    state->ptr = state->start;
3097
3098
0
    status = sre_match(state, PatternObject_GetCode(self->pattern));
3099
0
    if (PyErr_Occurred()) {
3100
0
        scanner_end(self);
3101
0
        return NULL;
3102
0
    }
3103
3104
0
    match = pattern_new_match(module_state, self->pattern,
3105
0
                              state, status);
3106
3107
0
    if (status == 0)
3108
0
        state->start = NULL;
3109
0
    else {
3110
0
        state->must_advance = (state->ptr == state->start);
3111
0
        state->start = state->ptr;
3112
0
    }
3113
3114
0
    scanner_end(self);
3115
0
    return match;
3116
0
}
3117
3118
3119
/*[clinic input]
3120
_sre.SRE_Scanner.search
3121
3122
    cls: defining_class
3123
    /
3124
3125
[clinic start generated code]*/
3126
3127
static PyObject *
3128
_sre_SRE_Scanner_search_impl(ScannerObject *self, PyTypeObject *cls)
3129
/*[clinic end generated code: output=23e8fc78013f9161 input=056c2d37171d0bf2]*/
3130
3.15M
{
3131
3.15M
    _sremodulestate *module_state = get_sre_module_state_by_class(cls);
3132
3.15M
    SRE_STATE* state = &self->state;
3133
3.15M
    PyObject* match;
3134
3.15M
    Py_ssize_t status;
3135
3136
3.15M
    if (!scanner_begin(self)) {
3137
0
        return NULL;
3138
0
    }
3139
3.15M
    if (state->start == NULL) {
3140
0
        scanner_end(self);
3141
0
        Py_RETURN_NONE;
3142
0
    }
3143
3144
3.15M
    state_reset(state);
3145
3146
3.15M
    state->ptr = state->start;
3147
3148
3.15M
    status = sre_search(state, PatternObject_GetCode(self->pattern));
3149
3.15M
    if (PyErr_Occurred()) {
3150
0
        scanner_end(self);
3151
0
        return NULL;
3152
0
    }
3153
3154
3.15M
    match = pattern_new_match(module_state, self->pattern,
3155
3.15M
                              state, status);
3156
3157
3.15M
    if (status == 0)
3158
328k
        state->start = NULL;
3159
2.82M
    else {
3160
2.82M
        state->must_advance = (state->ptr == state->start);
3161
2.82M
        state->start = state->ptr;
3162
2.82M
    }
3163
3164
3.15M
    scanner_end(self);
3165
3.15M
    return match;
3166
3.15M
}
3167
3168
static PyObject *
3169
pattern_scanner(_sremodulestate *module_state,
3170
                PatternObject *self,
3171
                PyObject *string,
3172
                Py_ssize_t pos,
3173
                Py_ssize_t endpos)
3174
328k
{
3175
328k
    ScannerObject* scanner;
3176
3177
    /* create scanner object */
3178
328k
    scanner = PyObject_GC_New(ScannerObject, module_state->Scanner_Type);
3179
328k
    if (!scanner)
3180
0
        return NULL;
3181
328k
    scanner->pattern = NULL;
3182
328k
    scanner->executing = 0;
3183
3184
    /* create search state object */
3185
328k
    if (!state_init(&scanner->state, self, string, pos, endpos)) {
3186
0
        Py_DECREF(scanner);
3187
0
        return NULL;
3188
0
    }
3189
3190
328k
    Py_INCREF(self);
3191
328k
    scanner->pattern = self;
3192
3193
328k
    PyObject_GC_Track(scanner);
3194
328k
    return (PyObject*) scanner;
3195
328k
}
3196
3197
/* -------------------------------------------------------------------- */
3198
/* template methods */
3199
3200
static int
3201
template_traverse(PyObject *op, visitproc visit, void *arg)
3202
0
{
3203
0
    TemplateObject *self = _TemplateObject_CAST(op);
3204
0
    Py_VISIT(Py_TYPE(self));
3205
0
    Py_VISIT(self->literal);
3206
0
    for (Py_ssize_t i = 0, n = Py_SIZE(self); i < n; i++) {
3207
0
        Py_VISIT(self->items[i].literal);
3208
0
    }
3209
0
    return 0;
3210
0
}
3211
3212
static int
3213
template_clear(PyObject *op)
3214
0
{
3215
0
    TemplateObject *self = _TemplateObject_CAST(op);
3216
0
    Py_CLEAR(self->literal);
3217
0
    for (Py_ssize_t i = 0, n = Py_SIZE(self); i < n; i++) {
3218
0
        Py_CLEAR(self->items[i].literal);
3219
0
    }
3220
0
    return 0;
3221
0
}
3222
3223
static void
3224
template_dealloc(PyObject *self)
3225
0
{
3226
0
    PyTypeObject *tp = Py_TYPE(self);
3227
0
    PyObject_GC_UnTrack(self);
3228
0
    (void)template_clear(self);
3229
0
    tp->tp_free(self);
3230
0
    Py_DECREF(tp);
3231
0
}
3232
3233
static PyObject *
3234
expand_template(TemplateObject *self, MatchObject *match)
3235
0
{
3236
0
    if (Py_SIZE(self) == 0) {
3237
0
        return Py_NewRef(self->literal);
3238
0
    }
3239
3240
0
    PyObject *result = NULL;
3241
0
    Py_ssize_t count = 0;  // the number of non-empty chunks
3242
    /* For small number of strings use a buffer allocated on the stack,
3243
     * otherwise use a list object. */
3244
0
    PyObject *buffer[10];
3245
0
    PyObject **out = buffer;
3246
0
    PyObject *list = NULL;
3247
0
    if (self->chunks > (int)Py_ARRAY_LENGTH(buffer) ||
3248
0
        !PyUnicode_Check(self->literal))
3249
0
    {
3250
0
        list = PyList_New(self->chunks);
3251
0
        if (!list) {
3252
0
            return NULL;
3253
0
        }
3254
0
        out = &PyList_GET_ITEM(list, 0);
3255
0
    }
3256
3257
0
    out[count++] = Py_NewRef(self->literal);
3258
0
    for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
3259
0
        Py_ssize_t index = self->items[i].index;
3260
0
        if (index >= match->groups) {
3261
0
            PyErr_SetString(PyExc_IndexError, "no such group");
3262
0
            goto cleanup;
3263
0
        }
3264
0
        PyObject *item = match_getslice_by_index(match, index, Py_None);
3265
0
        if (item == NULL) {
3266
0
            goto cleanup;
3267
0
        }
3268
0
        if (item != Py_None) {
3269
0
            out[count++] = Py_NewRef(item);
3270
0
        }
3271
0
        Py_DECREF(item);
3272
3273
0
        PyObject *literal = self->items[i].literal;
3274
0
        if (literal != NULL) {
3275
0
            out[count++] = Py_NewRef(literal);
3276
0
        }
3277
0
    }
3278
3279
0
    if (PyUnicode_Check(self->literal)) {
3280
0
        result = _PyUnicode_JoinArray(&_Py_STR(empty), out, count);
3281
0
    }
3282
0
    else {
3283
0
        Py_SET_SIZE(list, count);
3284
0
        result = PyBytes_Join((PyObject *)&_Py_SINGLETON(bytes_empty), list);
3285
0
    }
3286
3287
0
cleanup:
3288
0
    if (list) {
3289
0
        Py_DECREF(list);
3290
0
    }
3291
0
    else {
3292
0
        for (Py_ssize_t i = 0; i < count; i++) {
3293
0
            Py_DECREF(out[i]);
3294
0
        }
3295
0
    }
3296
0
    return result;
3297
0
}
3298
3299
3300
static Py_hash_t
3301
pattern_hash(PyObject *op)
3302
0
{
3303
0
    PatternObject *self = _PatternObject_CAST(op);
3304
3305
0
    Py_hash_t hash, hash2;
3306
3307
0
    hash = PyObject_Hash(self->pattern);
3308
0
    if (hash == -1) {
3309
0
        return -1;
3310
0
    }
3311
3312
0
    hash2 = Py_HashBuffer(self->code, sizeof(self->code[0]) * self->codesize);
3313
0
    hash ^= hash2;
3314
3315
0
    hash ^= self->flags;
3316
0
    hash ^= self->isbytes;
3317
0
    hash ^= self->codesize;
3318
3319
0
    if (hash == -1) {
3320
0
        hash = -2;
3321
0
    }
3322
0
    return hash;
3323
0
}
3324
3325
static PyObject*
3326
pattern_richcompare(PyObject *lefto, PyObject *righto, int op)
3327
0
{
3328
0
    PyTypeObject *tp = Py_TYPE(lefto);
3329
0
    _sremodulestate *module_state = get_sre_module_state_by_class(tp);
3330
0
    PatternObject *left, *right;
3331
0
    int cmp;
3332
3333
0
    if (op != Py_EQ && op != Py_NE) {
3334
0
        Py_RETURN_NOTIMPLEMENTED;
3335
0
    }
3336
3337
0
    if (!Py_IS_TYPE(righto, module_state->Pattern_Type))
3338
0
    {
3339
0
        Py_RETURN_NOTIMPLEMENTED;
3340
0
    }
3341
3342
0
    if (lefto == righto) {
3343
        /* a pattern is equal to itself */
3344
0
        return PyBool_FromLong(op == Py_EQ);
3345
0
    }
3346
3347
0
    left = (PatternObject *)lefto;
3348
0
    right = (PatternObject *)righto;
3349
3350
0
    cmp = (left->flags == right->flags
3351
0
           && left->isbytes == right->isbytes
3352
0
           && left->codesize == right->codesize);
3353
0
    if (cmp) {
3354
        /* Compare the code and the pattern because the same pattern can
3355
           produce different codes depending on the locale used to compile the
3356
           pattern when the re.LOCALE flag is used. Don't compare groups,
3357
           indexgroup nor groupindex: they are derivated from the pattern. */
3358
0
        cmp = (memcmp(left->code, right->code,
3359
0
                      sizeof(left->code[0]) * left->codesize) == 0);
3360
0
    }
3361
0
    if (cmp) {
3362
0
        cmp = PyObject_RichCompareBool(left->pattern, right->pattern,
3363
0
                                       Py_EQ);
3364
0
        if (cmp < 0) {
3365
0
            return NULL;
3366
0
        }
3367
0
    }
3368
0
    if (op == Py_NE) {
3369
0
        cmp = !cmp;
3370
0
    }
3371
0
    return PyBool_FromLong(cmp);
3372
0
}
3373
3374
#include "clinic/sre.c.h"
3375
3376
static PyMethodDef pattern_methods[] = {
3377
    _SRE_SRE_PATTERN_PREFIXMATCH_METHODDEF
3378
    /* "match" reuses the prefixmatch Clinic-generated parser and impl
3379
     * to avoid duplicating the argument parsing boilerplate code. */
3380
    {"match", _PyCFunction_CAST(_sre_SRE_Pattern_prefixmatch),
3381
     METH_METHOD|METH_FASTCALL|METH_KEYWORDS,
3382
     _sre_SRE_Pattern_prefixmatch__doc__},
3383
    _SRE_SRE_PATTERN_FULLMATCH_METHODDEF
3384
    _SRE_SRE_PATTERN_SEARCH_METHODDEF
3385
    _SRE_SRE_PATTERN_SUB_METHODDEF
3386
    _SRE_SRE_PATTERN_SUBN_METHODDEF
3387
    _SRE_SRE_PATTERN_FINDALL_METHODDEF
3388
    _SRE_SRE_PATTERN_SPLIT_METHODDEF
3389
    _SRE_SRE_PATTERN_FINDITER_METHODDEF
3390
    _SRE_SRE_PATTERN_SCANNER_METHODDEF
3391
    _SRE_SRE_PATTERN___COPY___METHODDEF
3392
    _SRE_SRE_PATTERN___DEEPCOPY___METHODDEF
3393
    _SRE_SRE_PATTERN__FAIL_AFTER_METHODDEF
3394
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
3395
     PyDoc_STR("Patterns are generic over the type of string they handle (str or bytes)")},
3396
    {NULL, NULL}
3397
};
3398
3399
static PyGetSetDef pattern_getset[] = {
3400
    {"groupindex", pattern_groupindex, NULL,
3401
      "A dictionary mapping group names to group numbers."},
3402
    {NULL}  /* Sentinel */
3403
};
3404
3405
#define PAT_OFF(x) offsetof(PatternObject, x)
3406
static PyMemberDef pattern_members[] = {
3407
    {"pattern",    _Py_T_OBJECT,    PAT_OFF(pattern),       Py_READONLY,
3408
     "The pattern string from which the RE object was compiled."},
3409
    {"flags",      Py_T_INT,       PAT_OFF(flags),         Py_READONLY,
3410
     "The regex matching flags."},
3411
    {"groups",     Py_T_PYSSIZET,  PAT_OFF(groups),        Py_READONLY,
3412
     "The number of capturing groups in the pattern."},
3413
    {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(PatternObject, weakreflist), Py_READONLY},
3414
    {NULL}  /* Sentinel */
3415
};
3416
3417
static PyType_Slot pattern_slots[] = {
3418
    {Py_tp_dealloc, pattern_dealloc},
3419
    {Py_tp_repr, pattern_repr},
3420
    {Py_tp_hash, pattern_hash},
3421
    {Py_tp_doc, (void *)pattern_doc},
3422
    {Py_tp_richcompare, pattern_richcompare},
3423
    {Py_tp_methods, pattern_methods},
3424
    {Py_tp_members, pattern_members},
3425
    {Py_tp_getset, pattern_getset},
3426
    {Py_tp_traverse, pattern_traverse},
3427
    {Py_tp_clear, pattern_clear},
3428
    {0, NULL},
3429
};
3430
3431
static PyType_Spec pattern_spec = {
3432
    .name = "re.Pattern",
3433
    .basicsize = sizeof(PatternObject),
3434
    .itemsize = sizeof(SRE_CODE),
3435
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
3436
              Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC),
3437
    .slots = pattern_slots,
3438
};
3439
3440
static PyMethodDef match_methods[] = {
3441
    _SRE_SRE_MATCH_GROUP_METHODDEF
3442
    _SRE_SRE_MATCH_START_METHODDEF
3443
    _SRE_SRE_MATCH_END_METHODDEF
3444
    _SRE_SRE_MATCH_SPAN_METHODDEF
3445
    _SRE_SRE_MATCH_GROUPS_METHODDEF
3446
    _SRE_SRE_MATCH_GROUPDICT_METHODDEF
3447
    _SRE_SRE_MATCH_EXPAND_METHODDEF
3448
    _SRE_SRE_MATCH___COPY___METHODDEF
3449
    _SRE_SRE_MATCH___DEEPCOPY___METHODDEF
3450
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
3451
     PyDoc_STR("Matches are generic over the type of string which was matched (str or bytes)")},
3452
    {NULL, NULL}
3453
};
3454
3455
static PyGetSetDef match_getset[] = {
3456
    {"lastindex", match_lastindex_get, NULL,
3457
     "The integer index of the last matched capturing group."},
3458
    {"lastgroup", match_lastgroup_get, NULL,
3459
     "The name of the last matched capturing group."},
3460
    {"regs", match_regs_get, NULL, NULL},
3461
    {NULL}
3462
};
3463
3464
#define MATCH_OFF(x) offsetof(MatchObject, x)
3465
static PyMemberDef match_members[] = {
3466
    {"string",  _Py_T_OBJECT,   MATCH_OFF(string),  Py_READONLY,
3467
     "The string passed to match() or search()."},
3468
    {"re",      _Py_T_OBJECT,   MATCH_OFF(pattern), Py_READONLY,
3469
     "The regular expression object."},
3470
    {"pos",     Py_T_PYSSIZET, MATCH_OFF(pos),     Py_READONLY,
3471
     "The index into the string at which the RE engine started looking for a match."},
3472
    {"endpos",  Py_T_PYSSIZET, MATCH_OFF(endpos),  Py_READONLY,
3473
     "The index into the string beyond which the RE engine will not go."},
3474
    {NULL}
3475
};
3476
3477
/* FIXME: implement setattr("string", None) as a special case (to
3478
   detach the associated string, if any */
3479
static PyType_Slot match_slots[] = {
3480
    {Py_tp_dealloc, match_dealloc},
3481
    {Py_tp_repr, match_repr},
3482
    {Py_tp_doc, (void *)match_doc},
3483
    {Py_tp_methods, match_methods},
3484
    {Py_tp_members, match_members},
3485
    {Py_tp_getset, match_getset},
3486
    {Py_tp_traverse, match_traverse},
3487
    {Py_tp_clear, match_clear},
3488
3489
    /* As mapping.
3490
     *
3491
     * Match objects do not support length or assignment, but do support
3492
     * __getitem__.
3493
     */
3494
    {Py_mp_subscript, match_getitem},
3495
3496
    {0, NULL},
3497
};
3498
3499
static PyType_Spec match_spec = {
3500
    .name = "re.Match",
3501
    .basicsize = sizeof(MatchObject),
3502
    .itemsize = sizeof(Py_ssize_t),
3503
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
3504
              Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC),
3505
    .slots = match_slots,
3506
};
3507
3508
static PyMethodDef scanner_methods[] = {
3509
    _SRE_SRE_SCANNER_PREFIXMATCH_METHODDEF
3510
    /* "match" reuses the prefixmatch Clinic-generated parser and impl
3511
     * to avoid duplicating the argument parsing boilerplate code. */
3512
    {"match", _PyCFunction_CAST(_sre_SRE_Scanner_prefixmatch),
3513
     METH_METHOD|METH_FASTCALL|METH_KEYWORDS,
3514
     _sre_SRE_Scanner_prefixmatch__doc__},
3515
    _SRE_SRE_SCANNER_SEARCH_METHODDEF
3516
    {NULL, NULL}
3517
};
3518
3519
#define SCAN_OFF(x) offsetof(ScannerObject, x)
3520
static PyMemberDef scanner_members[] = {
3521
    {"pattern", _Py_T_OBJECT, SCAN_OFF(pattern), Py_READONLY},
3522
    {NULL}  /* Sentinel */
3523
};
3524
3525
static PyType_Slot scanner_slots[] = {
3526
    {Py_tp_dealloc, scanner_dealloc},
3527
    {Py_tp_methods, scanner_methods},
3528
    {Py_tp_members, scanner_members},
3529
    {Py_tp_traverse, scanner_traverse},
3530
    {Py_tp_clear, scanner_clear},
3531
    {0, NULL},
3532
};
3533
3534
static PyType_Spec scanner_spec = {
3535
    .name = "_sre.SRE_Scanner",
3536
    .basicsize = sizeof(ScannerObject),
3537
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
3538
              Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC),
3539
    .slots = scanner_slots,
3540
};
3541
3542
static PyType_Slot template_slots[] = {
3543
    {Py_tp_dealloc, template_dealloc},
3544
    {Py_tp_traverse, template_traverse},
3545
    {Py_tp_clear, template_clear},
3546
    {0, NULL},
3547
};
3548
3549
static PyType_Spec template_spec = {
3550
    .name = "_sre.SRE_Template",
3551
    .basicsize = sizeof(TemplateObject),
3552
    .itemsize = sizeof(((TemplateObject *)0)->items[0]),
3553
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
3554
              Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC),
3555
    .slots = template_slots,
3556
};
3557
3558
static PyMethodDef _functions[] = {
3559
    _SRE_COMPILE_METHODDEF
3560
    _SRE_TEMPLATE_METHODDEF
3561
    _SRE_GETCODESIZE_METHODDEF
3562
    _SRE_ASCII_ISCASED_METHODDEF
3563
    _SRE_UNICODE_ISCASED_METHODDEF
3564
    _SRE_ASCII_TOLOWER_METHODDEF
3565
    _SRE_UNICODE_TOLOWER_METHODDEF
3566
    {NULL, NULL}
3567
};
3568
3569
static int
3570
sre_traverse(PyObject *module, visitproc visit, void *arg)
3571
1.58k
{
3572
1.58k
    _sremodulestate *state = get_sre_module_state(module);
3573
3574
1.58k
    Py_VISIT(state->Pattern_Type);
3575
1.58k
    Py_VISIT(state->Match_Type);
3576
1.58k
    Py_VISIT(state->Scanner_Type);
3577
1.58k
    Py_VISIT(state->Template_Type);
3578
1.58k
    Py_VISIT(state->compile_template);
3579
3580
1.58k
    return 0;
3581
1.58k
}
3582
3583
static int
3584
sre_clear(PyObject *module)
3585
0
{
3586
0
    _sremodulestate *state = get_sre_module_state(module);
3587
3588
0
    Py_CLEAR(state->Pattern_Type);
3589
0
    Py_CLEAR(state->Match_Type);
3590
0
    Py_CLEAR(state->Scanner_Type);
3591
0
    Py_CLEAR(state->Template_Type);
3592
0
    Py_CLEAR(state->compile_template);
3593
3594
0
    return 0;
3595
0
}
3596
3597
static void
3598
sre_free(void *module)
3599
0
{
3600
0
    sre_clear((PyObject *)module);
3601
0
}
3602
3603
108
#define CREATE_TYPE(m, type, spec)                                  \
3604
108
do {                                                                \
3605
108
    type = (PyTypeObject *)PyType_FromModuleAndSpec(m, spec, NULL); \
3606
108
    if (type == NULL) {                                             \
3607
0
        goto error;                                                 \
3608
0
    }                                                               \
3609
108
} while (0)
3610
3611
#define ADD_ULONG_CONSTANT(module, name, value)           \
3612
54
    do {                                                  \
3613
54
        if (PyModule_Add(module, name, PyLong_FromUnsignedLong(value)) < 0) { \
3614
0
            goto error;                                   \
3615
0
        }                                                 \
3616
54
} while (0)
3617
3618
3619
#ifdef Py_DEBUG
3620
static void
3621
_assert_match_aliases_prefixmatch(PyMethodDef *methods)
3622
{
3623
    PyMethodDef *prefixmatch_md = &methods[0];
3624
    PyMethodDef *match_md = &methods[1];
3625
    assert(strcmp(prefixmatch_md->ml_name, "prefixmatch") == 0);
3626
    assert(strcmp(match_md->ml_name, "match") == 0);
3627
    assert(match_md->ml_meth == prefixmatch_md->ml_meth);
3628
    assert(match_md->ml_flags == prefixmatch_md->ml_flags);
3629
    assert(match_md->ml_doc == prefixmatch_md->ml_doc);
3630
}
3631
#endif
3632
3633
static int
3634
sre_exec(PyObject *m)
3635
27
{
3636
27
    _sremodulestate *state;
3637
3638
#ifdef Py_DEBUG
3639
    _assert_match_aliases_prefixmatch(pattern_methods);
3640
    _assert_match_aliases_prefixmatch(scanner_methods);
3641
#endif
3642
3643
    /* Create heap types */
3644
27
    state = get_sre_module_state(m);
3645
27
    CREATE_TYPE(m, state->Pattern_Type, &pattern_spec);
3646
27
    CREATE_TYPE(m, state->Match_Type, &match_spec);
3647
27
    CREATE_TYPE(m, state->Scanner_Type, &scanner_spec);
3648
27
    CREATE_TYPE(m, state->Template_Type, &template_spec);
3649
3650
27
    if (PyModule_AddIntConstant(m, "MAGIC", SRE_MAGIC) < 0) {
3651
0
        goto error;
3652
0
    }
3653
3654
27
    if (PyModule_AddIntConstant(m, "CODESIZE", sizeof(SRE_CODE)) < 0) {
3655
0
        goto error;
3656
0
    }
3657
3658
27
    ADD_ULONG_CONSTANT(m, "MAXREPEAT", SRE_MAXREPEAT);
3659
27
    ADD_ULONG_CONSTANT(m, "MAXGROUPS", SRE_MAXGROUPS);
3660
3661
27
    if (PyModule_AddStringConstant(m, "copyright", copyright) < 0) {
3662
0
        goto error;
3663
0
    }
3664
3665
27
    return 0;
3666
3667
0
error:
3668
0
    return -1;
3669
27
}
3670
3671
static PyModuleDef_Slot sre_slots[] = {
3672
    _Py_ABI_SLOT,
3673
    {Py_mod_exec, sre_exec},
3674
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
3675
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
3676
    {0, NULL},
3677
};
3678
3679
static struct PyModuleDef sremodule = {
3680
    .m_base = PyModuleDef_HEAD_INIT,
3681
    .m_name = "_sre",
3682
    .m_size = sizeof(_sremodulestate),
3683
    .m_methods = _functions,
3684
    .m_slots = sre_slots,
3685
    .m_traverse = sre_traverse,
3686
    .m_free = sre_free,
3687
    .m_clear = sre_clear,
3688
};
3689
3690
PyMODINIT_FUNC
3691
PyInit__sre(void)
3692
27
{
3693
27
    return PyModuleDef_Init(&sremodule);
3694
27
}
3695
3696
/* vim:ts=4:sw=4:et
3697
*/