Debian Codegraph @

regex_3/_regex.c

raw symbols SCIP
1 /* Secret Labs' Regular Expression Engine
2 *
3 * regular expression matching engine
4 *
5 * partial history:
6 * 1999-10-24 fl created (based on existing template matcher code)
7 * 2000-03-06 fl first alpha, sort of
8 * 2000-08-01 fl fixes for 1.6b1
9 * 2000-08-07 fl use PyOS_CheckStack() if available
10 * 2000-09-20 fl added expand method
11 * 2001-03-20 fl lots of fixes for 2.1b2
12 * 2001-04-15 fl export copyright as Python attribute, not global
13 * 2001-04-28 fl added __copy__ methods (work in progress)
14 * 2001-05-14 fl fixes for 1.5.2 compatibility
15 * 2001-07-01 fl added BIGCHARSET support (from Martin von Loewis)
16 * 2001-10-18 fl fixed group reset issue (from Matthew Mueller)
17 * 2001-10-20 fl added split primitive; reenable unicode for 1.6/2.0/2.1
18 * 2001-10-21 fl added sub/subn primitive
19 * 2001-10-24 fl added finditer primitive (for 2.2 only)
20 * 2001-12-07 fl fixed memory leak in sub/subn (Guido van Rossum)
21 * 2002-11-09 fl fixed empty sub/subn return type
22 * 2003-04-18 mvl fully support 4-byte codes
23 * 2003-10-17 gn implemented non recursive scheme
24 * 2009-07-26 mrab completely re-designed matcher code
25 * 2011-11-18 mrab added support for PEP 393 strings
26 *
27 * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved.
28 *
29 * This version of the SRE library can be redistributed under CNRI's
30 * Python 1.6 license. For any other use, please contact Secret Labs
31 * AB ([email protected]).
32 *
33 * Portions of this engine have been developed in cooperation with
34 * CNRI. Hewlett-Packard provided funding for 1.6 integration and
35 * other compatibility work.
36 */
37
38 /* #define VERBOSE */
39
40 #define RE_MEMORY_LIMIT 0x40000000
41
42 #if defined(VERBOSE)
43 #define TRACE(X) printf X;
44 #else
45 #define TRACE(X)
46 #endif
47
48 #define PY_SSIZE_T_CLEAN
49
50 #include "Python.h"
51 #include "structmember.h" /* offsetof */
52 #include <ctype.h>
53 #include <time.h>
54 #include "_regex.h"
55 #include "pyport.h"
56 #include "pythread.h"
57
58 typedef RE_UINT32 RE_CODE;
59 typedef unsigned char BYTE;
60
61 /* An unassigned codepoint. */
62 #define UNASSIGNED_CODEPOINT 0x10FFFF
63
64 /* Properties in the General Category. */
65 #define RE_PROP_GC_CN ((RE_PROP_GC << 16) | RE_PROP_CN)
66 #define RE_PROP_GC_LU ((RE_PROP_GC << 16) | RE_PROP_LU)
67 #define RE_PROP_GC_LL ((RE_PROP_GC << 16) | RE_PROP_LL)
68 #define RE_PROP_GC_LT ((RE_PROP_GC << 16) | RE_PROP_LT)
69 #define RE_PROP_GC_P ((RE_PROP_GC << 16) | RE_PROP_P)
70
71 /* Unlimited repeat count. */
72 #define RE_UNLIMITED (~(RE_CODE)0)
73
74 /* The status of a . */
75 typedef RE_UINT32 RE_STATUS_T;
76
77 /* Whether to match concurrently, i.e. release the GIL while matching. */
78 #define RE_CONC_NO 0
79 #define RE_CONC_YES 1
80 #define RE_CONC_DEFAULT 2
81
82 /* The result of decoding the timeout. Values are in clock ticks. Non-negative
83 * values are valid.
84 */
85 #define RE_NO_TIMEOUT -1
86 #define RE_BAD_TIMEOUT -2
87
88 /* The side that could truncate in a partial match.
89 *
90 * The values RE_PARTIAL_LEFT and RE_PARTIAL_RIGHT are also used as array
91 * indexes, so they need to be 0 and 1.
92 */
93 #define RE_PARTIAL_NONE -1
94 #define RE_PARTIAL_LEFT 0
95 #define RE_PARTIAL_RIGHT 1
96
97 /* Flags for the kind of 'sub' call: 'sub', 'subn', 'subf', 'subfn'. */
98 #define RE_SUB 0x0
99 #define RE_SUBN 0x1
100 #define RE_SUBF 0x2
101
102 /* Error codes. */
103 #define RE_ERROR_INITIALISING 2 /* Initialising object. */
104 #define RE_ERROR_SUCCESS 1 /* Successful match. */
105 #define RE_ERROR_FAILURE 0 /* Unsuccessful match. */
106 #define RE_ERROR_ILLEGAL -1 /* Illegal code. */
107 #define RE_ERROR_INTERNAL -2 /* Internal error. */
108 #define RE_ERROR_CONCURRENT -3 /* "concurrent" invalid. */
109 #define RE_ERROR_MEMORY -4 /* Out of memory. */
110 #define RE_ERROR_CANCELLED -5 /* Matching cancelled. */
111 #define RE_ERROR_REPLACEMENT -6 /* Invalid replacement string. */
112 #define RE_ERROR_INVALID_GROUP_REF -7 /* Invalid group reference. */
113 #define RE_ERROR_GROUP_INDEX_TYPE -8 /* Group index type error. */
114 #define RE_ERROR_NO_SUCH_GROUP -9 /* No such group. */
115 #define RE_ERROR_INDEX -10 /* String index. */
116 #define RE_ERROR_NOT_STRING -11 /* Not a string. */
117 #define RE_ERROR_NOT_UNICODE -12 /* Not a Unicode string. */
118 #define RE_ERROR_PARTIAL -13 /* Partial match. */
119 #define RE_ERROR_NOT_BYTES -14 /* Not a bytestring. */
120 #define RE_ERROR_BAD_TIMEOUT -15 /* "timeout" invalid. */
121 #define RE_ERROR_TIMED_OUT -16 /* Matching has timed out. */
122
123 /* Node bitflags. */
124 #define RE_POSITIVE_OP 0x1
125 #define RE_ZEROWIDTH_OP 0x2
126 #define RE_FUZZY_OP 0x4
127 #define RE_REVERSE_OP 0x8
128 #define RE_REQUIRED_OP 0x10
129
130 /* Guards against further matching can occur at the start of the body and the
131 * tail of a repeat containing a repeat.
132 */
133 #define RE_STATUS_BODY 0x1
134 #define RE_STATUS_TAIL 0x2
135
136 /* Whether a guard is added depends on whether there's a repeat in the body of
137 * the repeat or a group reference in the body or tail of the repeat.
138 */
139 #define RE_STATUS_NEITHER 0x0
140 #define RE_STATUS_REPEAT 0x4
141 #define RE_STATUS_LIMITED 0x8
142 #define RE_STATUS_REF 0x10
143 #define RE_STATUS_VISITED_AG 0x20
144 #define RE_STATUS_VISITED_REP 0x40
145
146 /* Whether a string node has been initialised for fast searching. */
147 #define RE_STATUS_FAST_INIT 0x80
148
149 /* Whether a node us being used. (Additional nodes may be created while the
150 * pattern is being built.
151 */
152 #define RE_STATUS_USED 0x100
153
154 /* Whether a node is a string node. */
155 #define RE_STATUS_STRING 0x200
156
157 /* Whether a repeat node is within another repeat. */
158 #define RE_STATUS_INNER 0x400
159
160 /* Various flags stored in a node status member. */
161 #define RE_STATUS_SHIFT 11
162
163 #define RE_ENCODING_SHIFT 16
164 #define ASCII_ENCODING 1
165 #define UNICODE_ENCODING 2
166 #define ENCODING_KIND(NODE) (((NODE)->status >> RE_ENCODING_SHIFT) & 0x3)
167
168 #define RE_STATUS_FUZZY (RE_FUZZY_OP << RE_STATUS_SHIFT)
169 #define RE_STATUS_REVERSE (RE_REVERSE_OP << RE_STATUS_SHIFT)
170 #define RE_STATUS_REQUIRED (RE_REQUIRED_OP << RE_STATUS_SHIFT)
171 #define RE_STATUS_HAS_GROUPS 0x10000
172 #define RE_STATUS_HAS_REPEATS 0x20000
173 #define RE_STATUS_ALL_ATOMIC 0x40000
174
175 /* The different error types for fuzzy matching. */
176 #define RE_FUZZY_SUB 0
177 #define RE_FUZZY_INS 1
178 #define RE_FUZZY_DEL 2
179 #define RE_FUZZY_ERR 3
180 #define RE_FUZZY_COUNT 3
181
182 /* The various values in a FUZZY node. */
183 #define RE_FUZZY_VAL_MIN_BASE 1
184 #define RE_FUZZY_VAL_MIN_SUB (RE_FUZZY_VAL_MIN_BASE + RE_FUZZY_SUB)
185 #define RE_FUZZY_VAL_MIN_INS (RE_FUZZY_VAL_MIN_BASE + RE_FUZZY_INS)
186 #define RE_FUZZY_VAL_MIN_DEL (RE_FUZZY_VAL_MIN_BASE + RE_FUZZY_DEL)
187 #define RE_FUZZY_VAL_MIN_ERR (RE_FUZZY_VAL_MIN_BASE + RE_FUZZY_ERR)
188
189 #define RE_FUZZY_VAL_MAX_BASE 5
190 #define RE_FUZZY_VAL_MAX_SUB (RE_FUZZY_VAL_MAX_BASE + RE_FUZZY_SUB)
191 #define RE_FUZZY_VAL_MAX_INS (RE_FUZZY_VAL_MAX_BASE + RE_FUZZY_INS)
192 #define RE_FUZZY_VAL_MAX_DEL (RE_FUZZY_VAL_MAX_BASE + RE_FUZZY_DEL)
193 #define RE_FUZZY_VAL_MAX_ERR (RE_FUZZY_VAL_MAX_BASE + RE_FUZZY_ERR)
194
195 #define RE_FUZZY_VAL_COST_BASE 9
196 #define RE_FUZZY_VAL_SUB_COST (RE_FUZZY_VAL_COST_BASE + RE_FUZZY_SUB)
197 #define RE_FUZZY_VAL_INS_COST (RE_FUZZY_VAL_COST_BASE + RE_FUZZY_INS)
198 #define RE_FUZZY_VAL_DEL_COST (RE_FUZZY_VAL_COST_BASE + RE_FUZZY_DEL)
199 #define RE_FUZZY_VAL_MAX_COST (RE_FUZZY_VAL_COST_BASE + RE_FUZZY_ERR)
200
201 /* The maximum number of errors when trying to improve a fuzzy match. */
202 #define RE_MAX_ERRORS 10
203
204 /* The flags which will be set for full Unicode case folding. */
205 #define RE_FULL_CASE_FOLDING (RE_FLAG_UNICODE | RE_FLAG_FULLCASE | RE_FLAG_IGNORECASE)
206
207 /* The shortest string prefix for which we'll use a fast string search. */
208 #define RE_MIN_FAST_LENGTH 5
209
210 static char copyright[] =
211 " RE 2.3.0 Copyright (c) 1997-2002 by Secret Labs AB ";
212
213 /* The exception to raise on error. */
214 static PyObject* error_exception;
215
216 /* The dictionary of Unicode properties. */
217 static PyObject* property_dict;
218
219 typedef struct RE_State* RE_StatePtr;
220
221 /* Bit-flags for the common character properties supported by locale-sensitive
222 * matching.
223 */
224 #define RE_LOCALE_ALNUM 0x001
225 #define RE_LOCALE_ALPHA 0x002
226 #define RE_LOCALE_CNTRL 0x004
227 #define RE_LOCALE_DIGIT 0x008
228 #define RE_LOCALE_GRAPH 0x010
229 #define RE_LOCALE_LOWER 0x020
230 #define RE_LOCALE_PRINT 0x040
231 #define RE_LOCALE_PUNCT 0x080
232 #define RE_LOCALE_SPACE 0x100
233 #define RE_LOCALE_UPPER 0x200
234
235 /* Info about the current locale.
236 *
237 * Used by patterns that are locale-sensitive.
238 */
239 typedef struct RE_LocaleInfo {
240 unsigned short properties[0x100];
241 unsigned char uppercase[0x100];
242 unsigned char lowercase[0x100];
243 } RE_LocaleInfo;
244
245 /* Handlers for ASCII, locale and Unicode. */
246 typedef struct RE_EncodingTable {
247 BOOL (*has_property)(RE_LocaleInfo* locale_info, RE_CODE property, Py_UCS4
248 ch);
249 BOOL (*at_boundary)(RE_StatePtr state, Py_ssize_t text_pos);
250 BOOL (*at_word_start)(RE_StatePtr state, Py_ssize_t text_pos);
251 BOOL (*at_word_end)(RE_StatePtr state, Py_ssize_t text_pos);
252 BOOL (*at_default_boundary)(RE_StatePtr state, Py_ssize_t text_pos);
253 BOOL (*at_default_word_start)(RE_StatePtr state, Py_ssize_t text_pos);
254 BOOL (*at_default_word_end)(RE_StatePtr state, Py_ssize_t text_pos);
255 BOOL (*at_grapheme_boundary)(RE_StatePtr state, Py_ssize_t text_pos);
256 BOOL (*is_line_sep)(Py_UCS4 ch);
257 BOOL (*at_line_start)(RE_StatePtr state, Py_ssize_t text_pos);
258 BOOL (*at_line_end)(RE_StatePtr state, Py_ssize_t text_pos);
259 BOOL (*possible_turkic)(RE_LocaleInfo* locale_info, Py_UCS4 ch);
260 int (*all_cases)(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
261 codepoints);
262 Py_UCS4 (*simple_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch);
263 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
264 folded);
265 int (*all_turkic_i)(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
266 cases);
267 } RE_EncodingTable;
268
269 /* Position within the regex and text. */
270 typedef struct RE_Position {
271 struct RE_Node* node;
272 Py_ssize_t text_pos;
273 } RE_Position;
274
275 /* Info about a group's span. */
276 typedef struct RE_GroupSpan {
277 Py_ssize_t start;
278 Py_ssize_t end;
279 } RE_GroupSpan;
280
281 /* Storage for the next node. */
282 typedef struct RE_NextNode {
283 struct RE_Node* node;
284 struct RE_Node* test;
285 struct RE_Node* match_next;
286 Py_ssize_t match_step;
287 } RE_NextNode;
288
289 /* A pattern node. */
290 typedef struct RE_Node {
291 RE_NextNode next_1;
292 union {
293 struct {
294 RE_NextNode next_2;
295 struct RE_Node* true_node; /* Used by a CONDITIONAL node. */
296 } nonstring;
297 struct {
298 /* Used only if (node->status & RE_STATUS_STRING) is true. */
299 Py_ssize_t* bad_character_offset;
300 Py_ssize_t* good_suffix_offset;
301 } string;
302 };
303 Py_ssize_t step;
304 size_t value_count;
305 RE_CODE* values;
306 RE_STATUS_T status;
307 RE_UINT8 op;
308 BOOL match;
309 } RE_Node;
310
311 /* Span of a guard (inclusive range). */
312 typedef struct RE_GuardSpan {
313 Py_ssize_t low;
314 Py_ssize_t high;
315 BOOL protect;
316 } RE_GuardSpan;
317
318 /* Spans guarded against further matching. */
319 typedef struct RE_GuardList {
320 size_t capacity;
321 size_t count;
322 RE_GuardSpan* spans;
323 Py_ssize_t last_text_pos;
324 size_t last_low;
325 } RE_GuardList;
326
327 /* Info about a group. */
328 typedef struct RE_GroupData {
329 size_t capacity;
330 size_t count;
331 Py_ssize_t current;
332 RE_GroupSpan* captures;
333 } RE_GroupData;
334
335 /* Info about a repeat. */
336 typedef struct RE_RepeatData {
337 RE_GuardList body_guard_list;
338 RE_GuardList tail_guard_list;
339 size_t count;
340 Py_ssize_t start;
341 size_t capture_change;
342 } RE_RepeatData;
343
344 /* Guards for fuzzy sections. */
345 typedef struct RE_FuzzyGuards {
346 RE_GuardList body_guard_list;
347 RE_GuardList tail_guard_list;
348 } RE_FuzzyGuards;
349
350 /* Info about a capture group. */
351 typedef struct RE_GroupInfo {
352 Py_ssize_t end_index;
353 RE_Node* node;
354 BOOL referenced;
355 BOOL has_name;
356 } RE_GroupInfo;
357
358 /* Info about a call_ref. */
359 typedef struct RE_CallRefInfo {
360 RE_Node* node;
361 BOOL defined;
362 BOOL used;
363 } RE_CallRefInfo;
364
365 /* Info about a repeat. */
366 typedef struct RE_RepeatInfo {
367 RE_STATUS_T status;
368 } RE_RepeatInfo;
369
370 /* Info about a string argument. */
371 typedef struct RE_StringInfo {
372 Py_buffer view; /* View of the string if it's a buffer object. */
373 void* characters; /* Pointer to the characters of the string. */
374 Py_ssize_t length; /* Length of the string. */
375 Py_ssize_t charsize; /* Size of the characters in the string. */
376 BOOL is_unicode; /* Whether the string is Unicode. */
377 BOOL should_release; /* Whether the buffer should be released. */
378 } RE_StringInfo;
379
380 /* Info about where the next match was found, starting from a certain search
381 * position. This is used when a pattern starts with a BRANCH.
382 */
383 #define MAX_SEARCH_POSITIONS 7
384
385 /* Info about a search position. */
386 typedef struct {
387 Py_ssize_t start_pos;
388 Py_ssize_t match_pos;
389 } RE_SearchPosition;
390
391 typedef struct RE_FuzzyChange {
392 RE_UINT8 type;
393 Py_ssize_t pos;
394 } RE_FuzzyChange;
395
396 typedef struct RE_FuzzyChangesList {
397 size_t capacity;
398 size_t count;
399 RE_FuzzyChange* items;
400 } RE_FuzzyChangesList;
401
402 typedef struct RE_BestChangesList {
403 size_t capacity;
404 size_t count;
405 RE_FuzzyChangesList* lists;
406 } RE_BestChangesList;
407
408 typedef struct RE_LookaroundStateData {
409 void* node;
410 Py_ssize_t slice_start;
411 Py_ssize_t slice_end;
412 Py_ssize_t text_pos;
413 } RE_LookaroundStateData;
414
415 typedef struct RE_GroupStateData {
416 Py_ssize_t text_pos;
417 Py_ssize_t current;
418 size_t capture_change;
419 RE_CODE private_index;
420 RE_CODE public_index;
421 } RE_GroupStateData;
422
423 typedef struct RE_MatchBodyTailStateData {
424 RE_Position position;
425 size_t count;
426 Py_ssize_t start;
427 size_t capture_change;
428 RE_CODE index;
429 Py_ssize_t text_pos;
430 } RE_MatchBodyTailStateData;
431
432 typedef struct RE_BodyEndStateData {
433 size_t count;
434 Py_ssize_t start;
435 size_t capture_change;
436 RE_CODE index;
437 } RE_BodyEndStateData;
438
439 typedef struct RE_RepeatStateData {
440 size_t count;
441 Py_ssize_t start;
442 size_t capture_change;
443 RE_CODE index;
444 Py_ssize_t text_pos;
445 } RE_RepeatStateData;
446
447 typedef struct RE_RepeatOneStateData {
448 size_t count;
449 Py_ssize_t start;
450 void* node;
451 RE_CODE index;
452 } RE_RepeatOneStateData;
453
454 /* A stack of bytes. */
455 typedef struct ByteStack {
456 size_t capacity;
457 size_t count;
458 BYTE* storage;
459 } ByteStack;
460
461 /* The state object used during matching. */
462 typedef struct RE_State {
463 struct PatternObject* pattern; /* Parent PatternObject. */
464 /* Info about the string being matched. */
465 PyObject* string;
466 Py_buffer view; /* View of the string if it's a buffer object. */
467 Py_ssize_t charsize;
468 void* text;
469 Py_ssize_t text_length;
470 /* The slice of the string being searched. */
471 Py_ssize_t slice_start;
472 Py_ssize_t slice_end;
473 /* The hard limits of the string being searched. */
474 Py_ssize_t text_start;
475 Py_ssize_t text_end;
476 /* Info about the capture groups. */
477 RE_GroupData* groups;
478 Py_ssize_t lastindex;
479 Py_ssize_t lastgroup;
480 /* Info about the repeats. */
481 RE_RepeatData* repeats;
482 Py_ssize_t search_anchor; /* Where the last match finished. */
483 Py_ssize_t match_pos; /* The start position of the match. */
484 Py_ssize_t text_pos; /* The current position of the match. */
485 Py_ssize_t final_newline; /* The index of newline at end of string, or -1. */
486 Py_ssize_t final_line_sep; /* The index of line separator at end of string, or -1. */
487 /* Storage for backtrack info. */
488 ByteStack sstack; /* The structure stack. */
489 ByteStack bstack; /* The backtracking stack. */
490 ByteStack pstack; /* The pruning stack. */
491 /* Info about the best POSIX match (leftmost longest). */
492 Py_ssize_t best_match_pos;
493 Py_ssize_t best_text_pos;
494 RE_GroupData* best_match_groups;
495 /* Miscellaneous. */
496 Py_ssize_t min_width; /* The minimum width of the string to match (assuming it's not a fuzzy pattern). */
497 RE_EncodingTable* encoding; /* The 'encoding' of the string being searched. */
498 RE_LocaleInfo* locale_info; /* Info about the locale, if needed. */
499 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
500 void (*set_char_at)(void* text, Py_ssize_t pos, Py_UCS4 ch);
501 void* (*point_to)(void* text, Py_ssize_t pos);
502 PyThreadState* thread_state; /* The thread state after releasing the GIL. */
503 PyThread_type_lock lock; /* A lock for accessing the state across threads. */
504 size_t fuzzy_counts[RE_FUZZY_COUNT]; /* The counts for the current fuzzy matching. */
505 RE_Node* fuzzy_node; /* The node of the current fuzzy matching. */
506 size_t best_fuzzy_counts[RE_FUZZY_COUNT]; /* Best totals for fuzzy matching. */
507 RE_FuzzyGuards* fuzzy_guards; /* The guards for a fuzzy match. */
508 size_t total_errors; /* The total number of errors of a fuzzy match. */
509 size_t max_errors; /* The maximum permitted number of errors. */
510 size_t fewest_errors; /* The fewest errors so far of an enhanced fuzzy match. */
511 /* The group call guards. */
512 RE_GuardList* group_call_guard_list;
513 RE_FuzzyChangesList fuzzy_changes;
514 RE_SearchPosition search_positions[MAX_SEARCH_POSITIONS]; /* Where the search matches next. */
515 size_t capture_change; /* Incremented every time a captive group changes. */
516 Py_ssize_t req_pos; /* The position where the required string matched. */
517 Py_ssize_t req_end; /* The end position where the required string matched. */
518 Py_ssize_t timeout; /* The timeout in clock ticks. */
519 clock_t start_time; /* The clock time when matching started. */
520 int partial_side; /* The side that could truncate in a partial match. */
521 /* Various flags. */
522 RE_UINT16 iterations; /* The number of iterations the matching engine has performed since checking for KeyboardInterrupt. */
523 BOOL is_unicode; /* Whether the string to be matched is Unicode. */
524 BOOL should_release; /* Whether the buffer should be released. */
525 BOOL overlapped; /* Whether the matches can be overlapped. */
526 BOOL reverse; /* Whether it's a reverse pattern. */
527 BOOL visible_captures; /* Whether the 'captures' method will be visible. */
528 BOOL version_0; /* Whether to perform version_0 behaviour (same as re module). */
529 BOOL must_advance; /* Whether the end of the match must advance past its start. */
530 BOOL is_multithreaded; /* Whether to release the GIL while matching. */
531 BOOL too_few_errors; /* Whether there were too few fuzzy errors. */
532 BOOL match_all; /* Whether to match all of the string ('fullmatch'). */
533 BOOL found_match; /* Whether a POSIX match has been found. */
534 BOOL is_fuzzy; /* Whether the pattern is fuzzy. */
535 } RE_State;
536
537 /* The PatternObject created from a regular expression. */
538 typedef struct PatternObject {
539 PyObject_HEAD
540 PyObject* pattern; /* Pattern source (or None). */
541 Py_ssize_t flags; /* Flags used when compiling pattern source. */
542 PyObject* packed_code_list;
543 PyObject* weakreflist; /* List of weak references */
544 /* Nodes into which the regular expression is compiled. */
545 RE_Node* start_node;
546 RE_Node* start_test;
547 size_t true_group_count; /* The true number of capture groups. */
548 size_t public_group_count; /* The number of public capture groups. */
549 size_t visible_capture_count; /* The number of capture groups that are visible (not hidden in (?(DEFINE)...). */
550 size_t repeat_count; /* The number of repeats. */
551 Py_ssize_t group_end_index; /* The number of group closures. */
552 PyObject* groupindex;
553 PyObject* indexgroup;
554 PyObject* named_lists;
555 size_t named_lists_count;
556 PyObject** partial_named_lists[2];
557 PyObject* named_list_indexes;
558 /* Storage for the pattern nodes. */
559 size_t node_capacity;
560 size_t node_count;
561 RE_Node** node_list;
562 /* Info about the capture groups. */
563 size_t group_info_capacity;
564 RE_GroupInfo* group_info;
565 /* Info about the call_refs. */
566 size_t call_ref_info_capacity;
567 size_t call_ref_info_count;
568 RE_CallRefInfo* call_ref_info;
569 Py_ssize_t pattern_call_ref;
570 /* Info about the repeats. */
571 size_t repeat_info_capacity;
572 RE_RepeatInfo* repeat_info;
573 Py_ssize_t min_width; /* The minimum width of the string to match (assuming it isn't a fuzzy pattern). */
574 RE_EncodingTable* encoding; /* Encoding handlers. */
575 RE_LocaleInfo* locale_info; /* Info about the locale, if needed. */
576 RE_GroupData* groups_storage; /* Cached storage for group data. */
577 RE_RepeatData* repeats_storage; /* Cached storage for repeats. */
578 BYTE* stack_storage; /* Cached storage for the bstack. */
579 size_t stack_capacity; /* The size of the cached storage for bstack. */
580 size_t fuzzy_count; /* The number of fuzzy sections. */
581 /* Additional info. */
582 Py_ssize_t req_offset; /* The offset to the required string. */
583 PyObject* required_chars;
584 Py_ssize_t req_flags;
585 RE_Node* req_string; /* The required string. */
586 BOOL is_fuzzy; /* Whether it's a fuzzy pattern. */
587 BOOL do_search_start; /* Whether to do an initial search. */
588 } PatternObject;
589
590 /* The MatchObject created when a match is found. */
591 typedef struct MatchObject {
592 PyObject_HEAD
593 PyObject* string; /* Link to the target string or NULL if detached. */
594 PyObject* substring; /* Link to (a substring of) the target string. */
595 Py_ssize_t substring_offset; /* Offset into the target string. */
596 PatternObject* pattern; /* Link to the regex (pattern) object. */
597 Py_ssize_t pos; /* Start of current slice. */
598 Py_ssize_t endpos; /* End of current slice. */
599 Py_ssize_t match_start; /* Start of matched slice. */
600 Py_ssize_t match_end; /* End of matched slice. */
601 Py_ssize_t lastindex; /* Last group seen by the engine (-1 if none). */
602 Py_ssize_t lastgroup; /* Last named group seen by the engine (-1 if none). */
603 size_t group_count; /* The number of groups. */
604 RE_GroupData* groups; /* The capture groups. */
605 PyObject* regs;
606 size_t fuzzy_counts[RE_FUZZY_COUNT];
607 RE_FuzzyChange* fuzzy_changes;
608 BOOL partial; /* Whether it's a partial match. */
609 } MatchObject;
610
611 /* The ScannerObject. */
612 typedef struct ScannerObject {
613 PyObject_HEAD
614 PatternObject* pattern;
615 RE_State state;
616 int status;
617 } ScannerObject;
618
619 /* The SplitterObject. */
620 typedef struct SplitterObject {
621 PyObject_HEAD
622 PatternObject* pattern;
623 RE_State state;
624 Py_ssize_t maxsplit;
625 Py_ssize_t last_pos;
626 Py_ssize_t split_count;
627 Py_ssize_t index;
628 int status;
629 } SplitterObject;
630
631 /* The CaptureObject. */
632 typedef struct CaptureObject {
633 PyObject_HEAD
634 Py_ssize_t group_index;
635 MatchObject** match_indirect;
636 } CaptureObject;
637
638 /* Info used when compiling a pattern to nodes. */
639 typedef struct RE_CompileArgs {
640 RE_CODE* code; /* The start of the compiled pattern. */
641 RE_CODE* end_code; /* The end of the compiled pattern. */
642 PatternObject* pattern; /* The pattern object. */
643 Py_ssize_t min_width; /* The minimum width of the string to match (assuming it isn't a fuzzy pattern). */
644 RE_Node* start; /* The start node. */
645 RE_Node* end; /* The end node. */
646 size_t repeat_depth; /* The nesting depth of the repeat. */
647 size_t visible_capture_count; /* The number of capture groups that are visible (not hidden in (?(DEFINE)...). */
648 BOOL forward; /* Whether it's a forward (not reverse) pattern. */
649 BOOL visible_captures; /* Whether all of the captures will be visible. */
650 BOOL has_captures; /* Whether the pattern has capture groups. */
651 BOOL is_fuzzy; /* Whether the pattern (or some part of it) is fuzzy. */
652 BOOL within_fuzzy; /* Whether the subpattern is within a fuzzy section. */
653 BOOL has_groups; /* Whether the subpattern contains captures. */
654 BOOL has_repeats; /* Whether the subpattern contains repeats. */
655 BOOL in_define; /* Whether we're in (?(DEFINE)...). */
656 BOOL all_atomic; /* The sequence consists only of atomic items. */
657 } RE_CompileArgs;
658
659 /* The string slices which will be concatenated to make the result string of
660 * the 'sub' method.
661 *
662 * This allows us to avoid creating a list of slices if there of fewer than 2
663 * of them. Empty strings aren't recorded, so if 'list' and 'item' are both
664 * NULL then the result is an empty string.
665 */
666 typedef struct RE_JoinInfo {
667 PyObject* list; /* The list of slices if there are more than 2 of them. */
668 PyObject* item; /* The slice if there is only 1 of them. */
669 BOOL reversed; /* Whether the slices have been found in reverse order. */
670 BOOL is_unicode; /* Whether the string is Unicode. */
671 } RE_JoinInfo;
672
673 /* Info about fuzzy matching. */
674 typedef struct {
675 RE_Node* new_node;
676 Py_ssize_t new_text_pos;
677 Py_ssize_t limit;
678 Py_ssize_t new_string_pos;
679 int new_folded_pos;
680 int folded_len;
681 int new_gfolded_pos;
682 int new_group_pos;
683 RE_UINT8 fuzzy_type;
684 RE_INT8 step;
685 BOOL permit_insertion;
686 } RE_FuzzyData;
687
688 typedef struct RE_BestEntry {
689 Py_ssize_t match_pos;
690 Py_ssize_t text_pos;
691 } RE_BestEntry;
692
693 typedef struct RE_BestList {
694 size_t capacity;
695 size_t count;
696 RE_BestEntry* entries;
697 } RE_BestList;
698
699 /* A stack of guard checks. */
700 typedef struct RE_Check {
701 RE_Node* node;
702 RE_STATUS_T result;
703 } RE_Check;
704
705 typedef struct RE_CheckStack {
706 size_t capacity;
707 size_t count;
708 RE_Check* items;
709 } RE_CheckStack;
710
711 /* A stack of nodes. */
712 typedef struct RE_NodeStack {
713 size_t capacity;
714 size_t count;
715 RE_Node** items;
716 } RE_NodeStack;
717
718 /* Function types for getting info from a MatchObject. */
719 typedef PyObject* (*RE_GetByIndexFunc)(MatchObject* self, Py_ssize_t index);
720
721 /* Returns the magnitude of a 'Py_ssize_t' value. */
722 Py_LOCAL_INLINE(Py_ssize_t) abs_ssize_t(Py_ssize_t x) {
723 return x >= 0 ? x : -x;
724 }
725
726 /* Returns the minimum of 2 'Py_ssize_t' values. */
727 Py_LOCAL_INLINE(Py_ssize_t) min_ssize_t(Py_ssize_t x, Py_ssize_t y) {
728 return x <= y ? x : y;
729 }
730
731 /* Returns the maximum of 2 'Py_ssize_t' values. */
732 Py_LOCAL_INLINE(Py_ssize_t) max_ssize_t(Py_ssize_t x, Py_ssize_t y) {
733 return x >= y ? x : y;
734 }
735
736 /* Returns the minimum of 2 'size_t' values. */
737 Py_LOCAL_INLINE(size_t) min_size_t(size_t x, size_t y) {
738 return x <= y ? x : y;
739 }
740
741 /* Returns the 'maximum' of 2 RE_STATUS_T values. */
742 Py_LOCAL_INLINE(RE_STATUS_T) max_status_2(RE_STATUS_T x, RE_STATUS_T y) {
743 return x >= y ? x : y;
744 }
745
746 /* Returns the 'maximum' of 3 RE_STATUS_T values. */
747 Py_LOCAL_INLINE(RE_STATUS_T) max_status_3(RE_STATUS_T x, RE_STATUS_T y,
748 RE_STATUS_T z) {
749 return max_status_2(x, max_status_2(y, z));
750 }
751
752 /* Returns the 'maximum' of 4 RE_STATUS_T values. */
753 Py_LOCAL_INLINE(RE_STATUS_T) max_status_4(RE_STATUS_T w, RE_STATUS_T x,
754 RE_STATUS_T y, RE_STATUS_T z) {
755 return max_status_2(max_status_2(w, x), max_status_2(y, z));
756 }
757
758 /* Gets a character at a position assuming 1 byte per character. */
759 static Py_UCS4 bytes1_char_at(void* text, Py_ssize_t pos) {
760 return *((Py_UCS1*)text + pos);
761 }
762
763 /* Sets a character at a position assuming 1 byte per character. */
764 static void bytes1_set_char_at(void* text, Py_ssize_t pos, Py_UCS4 ch) {
765 *((Py_UCS1*)text + pos) = (Py_UCS1)ch;
766 }
767
768 /* Gets a pointer to a position assuming 1 byte per character. */
769 static void* bytes1_point_to(void* text, Py_ssize_t pos) {
770 return (Py_UCS1*)text + pos;
771 }
772
773 /* Gets a character at a position assuming 2 bytes per character. */
774 static Py_UCS4 bytes2_char_at(void* text, Py_ssize_t pos) {
775 return *((Py_UCS2*)text + pos);
776 }
777
778 /* Sets a character at a position assuming 2 bytes per character. */
779 static void bytes2_set_char_at(void* text, Py_ssize_t pos, Py_UCS4 ch) {
780 *((Py_UCS2*)text + pos) = (Py_UCS2)ch;
781 }
782
783 /* Gets a pointer to a position assuming 2 bytes per character. */
784 static void* bytes2_point_to(void* text, Py_ssize_t pos) {
785 return (Py_UCS2*)text + pos;
786 }
787
788 /* Gets a character at a position assuming 4 bytes per character. */
789 static Py_UCS4 bytes4_char_at(void* text, Py_ssize_t pos) {
790 return *((Py_UCS4*)text + pos);
791 }
792
793 /* Sets a character at a position assuming 4 bytes per character. */
794 static void bytes4_set_char_at(void* text, Py_ssize_t pos, Py_UCS4 ch) {
795 *((Py_UCS4*)text + pos) = (Py_UCS4)ch;
796 }
797
798 /* Gets a pointer to a position assuming 4 bytes per character. */
799 static void* bytes4_point_to(void* text, Py_ssize_t pos) {
800 return (Py_UCS4*)text + pos;
801 }
802
803 /* Default for whether a position is on a word boundary. */
804 static BOOL at_boundary_always(RE_State* state, Py_ssize_t text_pos) {
805 return TRUE;
806 }
807
808 /* Converts a BOOL to success/failure. */
809 Py_LOCAL_INLINE(int) bool_as_status(BOOL value) {
810 return value ? RE_ERROR_SUCCESS : RE_ERROR_FAILURE;
811 }
812
813 /* ASCII-specific. */
814
815 Py_LOCAL_INLINE(BOOL) unicode_has_property(RE_CODE property, Py_UCS4 ch);
816
817 /* Checks whether a character has a property. */
818 Py_LOCAL_INLINE(BOOL) ascii_has_property(RE_CODE property, Py_UCS4 ch) {
819 if (ch > RE_ASCII_MAX) {
820 /* Treat it as an unassigned codepoint. */
821 ch = UNASSIGNED_CODEPOINT;
822 }
823
824 return unicode_has_property(property, ch);
825 }
826
827 /* Checks whether a character has a property, ignoring case. */
828 Py_LOCAL_INLINE(BOOL) ascii_has_property_ign(RE_CODE property, Py_UCS4 ch) {
829 RE_UINT32 prop;
830
831 if (ch > RE_ASCII_MAX) {
832 /* Treat it as an unassigned codepoint. */
833 ch = UNASSIGNED_CODEPOINT;
834 }
835
836 prop = property >> 16;
837
838 /* The property is case-insensitive. */
839 return ascii_has_property(property, ch);
840 }
841
842 /* Wrapper for calling 'ascii_has_property' via a pointer. */
843 static BOOL ascii_has_property_wrapper(RE_LocaleInfo* locale_info, RE_CODE
844 property, Py_UCS4 ch) {
845 return ascii_has_property(property, ch);
846 }
847
848 /* Checks whether there's a word character to the left. */
849 Py_LOCAL_INLINE(BOOL) ascii_word_left(RE_State* state, Py_ssize_t text_pos) {
850 return text_pos > state->text_start && ascii_has_property(RE_PROP_WORD,
851 state->char_at(state->text, text_pos - 1));
852 }
853
854 /* Checks whether there's a word character to the right. */
855 Py_LOCAL_INLINE(BOOL) ascii_word_right(RE_State* state, Py_ssize_t text_pos) {
856 return text_pos < state->text_end && ascii_has_property(RE_PROP_WORD,
857 state->char_at(state->text, text_pos));
858 }
859
860 /* Checks whether a position is on a word boundary. */
861 static BOOL ascii_at_boundary(RE_State* state, Py_ssize_t text_pos) {
862 BOOL left;
863 BOOL right;
864
865 left = ascii_word_left(state, text_pos);
866 right = ascii_word_right(state, text_pos);
867
868 return left != right;
869 }
870
871 /* Checks whether a position is at the start of a word. */
872 static BOOL ascii_at_word_start(RE_State* state, Py_ssize_t text_pos) {
873 BOOL left;
874 BOOL right;
875
876 left = ascii_word_left(state, text_pos);
877 right = ascii_word_right(state, text_pos);
878
879 return !left && right;
880 }
881
882 /* Checks whether a position is at the end of a word. */
883 static BOOL ascii_at_word_end(RE_State* state, Py_ssize_t text_pos) {
884 BOOL left;
885 BOOL right;
886
887 left = ascii_word_left(state, text_pos);
888 right = ascii_word_right(state, text_pos);
889
890 return left && !right;
891 }
892
893 /* Checks whether a character is a line separator. */
894 static BOOL ascii_is_line_sep(Py_UCS4 ch) {
895 return 0x0A <= ch && ch <= 0x0D;
896 }
897
898 /* Checks whether a position is at the start of a line. */
899 static BOOL ascii_at_line_start(RE_State* state, Py_ssize_t text_pos) {
900 Py_UCS4 ch;
901
902 if (text_pos <= state->text_start)
903 return TRUE;
904
905 ch = state->char_at(state->text, text_pos - 1);
906
907 if (ch == 0x0D) {
908 if (text_pos >= state->text_end)
909 return TRUE;
910
911 /* No line break inside CRLF. */
912 return state->char_at(state->text, text_pos) != 0x0A;
913 }
914
915 return 0x0A <= ch && ch <= 0x0D;
916 }
917
918 /* Checks whether a position is at the end of a line. */
919 static BOOL ascii_at_line_end(RE_State* state, Py_ssize_t text_pos) {
920 Py_UCS4 ch;
921
922 if (text_pos >= state->text_end)
923 return TRUE;
924
925 ch = state->char_at(state->text, text_pos);
926
927 if (ch == 0x0A) {
928 if (text_pos <= state->text_start)
929 return TRUE;
930
931 /* No line break inside CRLF. */
932 return state->char_at(state->text, text_pos - 1) != 0x0D;
933 }
934
935 return 0x0A <= ch && ch <= 0x0D;
936 }
937
938 /* Checks whether a character could be Turkic (variants of I/i). For ASCII, it
939 * won't be.
940 */
941 static BOOL ascii_possible_turkic(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
942 return FALSE;
943 }
944
945 /* Gets all the cases of a character. */
946 static int ascii_all_cases(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
947 codepoints) {
948 int count;
949
950 count = 0;
951
952 codepoints[count++] = ch;
953
954 if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z'))
955 /* It's a letter, so add the other case. */
956 codepoints[count++] = ch ^ 0x20;
957
958 return count;
959 }
960
961 /* Returns a character with its case folded. */
962 static Py_UCS4 ascii_simple_case_fold(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
963 if ('A' <= ch && ch <= 'Z')
964 /* Uppercase folds to lowercase. */
965 return ch ^ 0x20;
966
967 return ch;
968 }
969
970 /* Returns a character with its case folded. */
971 static int ascii_full_case_fold(RE_LocaleInfo* locale_info, Py_UCS4 ch,
972 Py_UCS4* folded) {
973 if ('A' <= ch && ch <= 'Z')
974 /* Uppercase folds to lowercase. */
975 folded[0] = ch ^ 0x20;
976 else
977 folded[0] = ch;
978
979 return 1;
980 }
981
982 /* Gets all the case variants of Turkic 'I'. The given character will be listed
983 * first.
984 */
985 static int ascii_all_turkic_i(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
986 cases) {
987 int count;
988
989 count = 0;
990
991 cases[count++] = ch;
992
993 if (ch != 'I')
994 cases[count++] = 'I';
995
996 if (ch != 'i')
997 cases[count++] = 'i';
998
999 return count;
1000 }
1001
1002 /* The handlers for ASCII characters. */
1003 static RE_EncodingTable ascii_encoding = {
1004 ascii_has_property_wrapper,
1005 ascii_at_boundary,
1006 ascii_at_word_start,
1007 ascii_at_word_end,
1008 ascii_at_boundary, /* No special "default word boundary" for ASCII. */
1009 ascii_at_word_start, /* No special "default start of word" for ASCII. */
1010 ascii_at_word_end, /* No special "default end of a word" for ASCII. */
1011 at_boundary_always, /* No special "grapheme boundary" for ASCII. */
1012 ascii_is_line_sep,
1013 ascii_at_line_start,
1014 ascii_at_line_end,
1015 ascii_possible_turkic,
1016 ascii_all_cases,
1017 ascii_simple_case_fold,
1018 ascii_full_case_fold,
1019 ascii_all_turkic_i,
1020 };
1021
1022 /* Locale-specific. */
1023
1024 /* Checks whether a character has the 'alnum' property in the given locale. */
1025 Py_LOCAL_INLINE(BOOL) locale_isalnum(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
1026 return ch <= RE_LOCALE_MAX && (locale_info->properties[ch] &
1027 RE_LOCALE_ALNUM) != 0;
1028 }
1029
1030 /* Checks whether a character has the 'alpha' property in the given locale. */
1031 Py_LOCAL_INLINE(BOOL) locale_isalpha(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
1032 return ch <= RE_LOCALE_MAX && (locale_info->properties[ch] &
1033 RE_LOCALE_ALPHA) != 0;
1034 }
1035
1036 /* Checks whether a character has the 'cntrl' property in the given locale. */
1037 Py_LOCAL_INLINE(BOOL) locale_iscntrl(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
1038 return ch <= RE_LOCALE_MAX && (locale_info->properties[ch] &
1039 RE_LOCALE_CNTRL) != 0;
1040 }
1041
1042 /* Checks whether a character has the 'digit' property in the given locale. */
1043 Py_LOCAL_INLINE(BOOL) locale_isdigit(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
1044 return ch <= RE_LOCALE_MAX && (locale_info->properties[ch] &
1045 RE_LOCALE_DIGIT) != 0;
1046 }
1047
1048 /* Checks whether a character has the 'graph' property in the given locale. */
1049 Py_LOCAL_INLINE(BOOL) locale_isgraph(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
1050 return ch <= RE_LOCALE_MAX && (locale_info->properties[ch] &
1051 RE_LOCALE_GRAPH) != 0;
1052 }
1053
1054 /* Checks whether a character has the 'lower' property in the given locale. */
1055 Py_LOCAL_INLINE(BOOL) locale_islower(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
1056 return ch <= RE_LOCALE_MAX && (locale_info->properties[ch] &
1057 RE_LOCALE_LOWER) != 0;
1058 }
1059
1060 /* Checks whether a character has the 'print' property in the given locale. */
1061 Py_LOCAL_INLINE(BOOL) locale_isprint(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
1062 return ch <= RE_LOCALE_MAX && (locale_info->properties[ch] &
1063 RE_LOCALE_PRINT) != 0;
1064 }
1065
1066 /* Checks whether a character has the 'punct' property in the given locale. */
1067 Py_LOCAL_INLINE(BOOL) locale_ispunct(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
1068 return ch <= RE_LOCALE_MAX && (locale_info->properties[ch] &
1069 RE_LOCALE_PUNCT) != 0;
1070 }
1071
1072 /* Checks whether a character has the 'space' property in the given locale. */
1073 Py_LOCAL_INLINE(BOOL) locale_isspace(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
1074 return ch <= RE_LOCALE_MAX && (locale_info->properties[ch] &
1075 RE_LOCALE_SPACE) != 0;
1076 }
1077
1078 /* Checks whether a character has the 'upper' property in the given locale. */
1079 Py_LOCAL_INLINE(BOOL) locale_isupper(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
1080 return ch <= RE_LOCALE_MAX && (locale_info->properties[ch] &
1081 RE_LOCALE_UPPER) != 0;
1082 }
1083
1084 /* Converts a character to lowercase in the given locale. */
1085 Py_LOCAL_INLINE(Py_UCS4) locale_tolower(RE_LocaleInfo* locale_info, Py_UCS4 ch)
1086 {
1087 return ch <= RE_LOCALE_MAX ? locale_info->lowercase[ch] : ch;
1088 }
1089
1090 /* Converts a character to uppercase in the given locale. */
1091 Py_LOCAL_INLINE(Py_UCS4) locale_toupper(RE_LocaleInfo* locale_info, Py_UCS4 ch)
1092 {
1093 return ch <= RE_LOCALE_MAX ? locale_info->uppercase[ch] : ch;
1094 }
1095
1096 /* Checks whether a character has a property. */
1097 Py_LOCAL_INLINE(BOOL) locale_has_property(RE_LocaleInfo* locale_info, RE_CODE
1098 property, Py_UCS4 ch) {
1099 RE_UINT32 value;
1100 RE_UINT32 v;
1101
1102 value = property & 0xFFFF;
1103
1104 if (ch > RE_LOCALE_MAX)
1105 /* Outside the locale range. */
1106 return value == 0;
1107
1108 switch (property >> 16) {
1109 case RE_PROP_ALNUM >> 16:
1110 v = locale_isalnum(locale_info, ch) != 0;
1111 break;
1112 case RE_PROP_ALPHA >> 16:
1113 v = locale_isalpha(locale_info, ch) != 0;
1114 break;
1115 case RE_PROP_ANY >> 16:
1116 v = 1;
1117 break;
1118 case RE_PROP_ASCII >> 16:
1119 v = ch <= RE_ASCII_MAX;
1120 break;
1121 case RE_PROP_BLANK >> 16:
1122 v = ch == '\t' || ch == ' ';
1123 break;
1124 case RE_PROP_GC:
1125 switch (property) {
1126 case RE_PROP_ASSIGNED:
1127 v = ch <= RE_LOCALE_MAX;
1128 break;
1129 case RE_PROP_CASEDLETTER:
1130 v = locale_isalpha(locale_info, ch) ? value : 0xFFFF;
1131 break;
1132 case RE_PROP_CNTRL:
1133 v = locale_iscntrl(locale_info, ch) ? value : 0xFFFF;
1134 break;
1135 case RE_PROP_DIGIT:
1136 v = locale_isdigit(locale_info, ch) ? value : 0xFFFF;
1137 break;
1138 case RE_PROP_GC_CN:
1139 v = ch > RE_LOCALE_MAX;
1140 break;
1141 case RE_PROP_GC_LL:
1142 v = locale_islower(locale_info, ch) ? value : 0xFFFF;
1143 break;
1144 case RE_PROP_GC_LU:
1145 v = locale_isupper(locale_info, ch) ? value : 0xFFFF;
1146 break;
1147 case RE_PROP_GC_P:
1148 v = locale_ispunct(locale_info, ch) ? value : 0xFFFF;
1149 break;
1150 default:
1151 v = 0xFFFF;
1152 break;
1153 }
1154 break;
1155 case RE_PROP_GRAPH >> 16:
1156 v = locale_isgraph(locale_info, ch) != 0;
1157 break;
1158 case RE_PROP_LOWER >> 16:
1159 v = locale_islower(locale_info, ch) != 0;
1160 break;
1161 case RE_PROP_POSIX_ALNUM >> 16:
1162 v = re_get_posix_alnum(ch) != 0;
1163 break;
1164 case RE_PROP_POSIX_DIGIT >> 16:
1165 v = re_get_posix_digit(ch) != 0;
1166 break;
1167 case RE_PROP_POSIX_PUNCT >> 16:
1168 v = re_get_posix_punct(ch) != 0;
1169 break;
1170 case RE_PROP_POSIX_XDIGIT >> 16:
1171 v = re_get_posix_xdigit(ch) != 0;
1172 break;
1173 case RE_PROP_PRINT >> 16:
1174 v = locale_isprint(locale_info, ch) != 0;
1175 break;
1176 case RE_PROP_SPACE >> 16:
1177 v = locale_isspace(locale_info, ch) != 0;
1178 break;
1179 case RE_PROP_UPPER >> 16:
1180 v = locale_isupper(locale_info, ch) != 0;
1181 break;
1182 case RE_PROP_WORD >> 16:
1183 v = ch == '_' || locale_isalnum(locale_info, ch) != 0;
1184 break;
1185 case RE_PROP_XDIGIT >> 16:
1186 v = re_get_hex_digit(ch) != 0;
1187 break;
1188 default:
1189 v = 0;
1190 break;
1191 }
1192
1193 return v == value;
1194 }
1195
1196 /* Checks whether a character has a property, ignoring case. */
1197 Py_LOCAL_INLINE(BOOL) locale_has_property_ign(RE_LocaleInfo* locale_info,
1198 RE_CODE property, Py_UCS4 ch) {
1199 RE_UINT32 prop;
1200
1201 prop = property >> 16;
1202
1203 if (property == RE_PROP_GC_LU || property == RE_PROP_GC_LL || property ==
1204 RE_PROP_GC_LT)
1205 return locale_isupper(locale_info, ch) || locale_islower(locale_info,
1206 ch);
1207 else if (prop == RE_PROP_UPPERCASE || prop == RE_PROP_LOWERCASE)
1208 return locale_isupper(locale_info, ch) || locale_islower(locale_info,
1209 ch);
1210
1211 /* The property is case-insensitive. */
1212 return locale_has_property(locale_info, property, ch);
1213 }
1214
1215 /* Wrapper for calling 'locale_has_property' via a pointer. */
1216 static BOOL locale_has_property_wrapper(RE_LocaleInfo* locale_info, RE_CODE
1217 property, Py_UCS4 ch) {
1218 return locale_has_property(locale_info, property, ch);
1219 }
1220
1221 /* Checks whether there's a word character to the left. */
1222 Py_LOCAL_INLINE(BOOL) locale_word_left(RE_State* state, Py_ssize_t text_pos) {
1223 return text_pos > state->text_start && locale_has_property(state->locale_info,
1224 RE_PROP_WORD, state->char_at(state->text, text_pos - 1));
1225 }
1226
1227 /* Checks whether there's a word character to the right. */
1228 Py_LOCAL_INLINE(BOOL) locale_word_right(RE_State* state, Py_ssize_t text_pos) {
1229 return text_pos < state->text_end &&
1230 locale_has_property(state->locale_info, RE_PROP_WORD,
1231 state->char_at(state->text, text_pos));
1232 }
1233
1234 /* Checks whether a position is on a word boundary. */
1235 static BOOL locale_at_boundary(RE_State* state, Py_ssize_t text_pos) {
1236 BOOL left;
1237 BOOL right;
1238
1239 left = locale_word_left(state, text_pos);
1240 right = locale_word_right(state, text_pos);
1241
1242 return left != right;
1243 }
1244
1245 /* Checks whether a position is at the start of a word. */
1246 static BOOL locale_at_word_start(RE_State* state, Py_ssize_t text_pos) {
1247 BOOL left;
1248 BOOL right;
1249
1250 left = locale_word_left(state, text_pos);
1251 right = locale_word_right(state, text_pos);
1252
1253 return !left && right;
1254 }
1255
1256 /* Checks whether a position is at the end of a word. */
1257 static BOOL locale_at_word_end(RE_State* state, Py_ssize_t text_pos) {
1258 BOOL left;
1259 BOOL right;
1260
1261 left = locale_word_left(state, text_pos);
1262 right = locale_word_right(state, text_pos);
1263
1264 return left && !right;
1265 }
1266
1267 /* Checks whether a character could be Turkic (variants of I/i). */
1268 static BOOL locale_possible_turkic(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
1269 return locale_toupper(locale_info, ch) == 'I' ||
1270 locale_tolower(locale_info, ch) == 'i';
1271 }
1272
1273 /* Gets all the cases of a character. */
1274 static int locale_all_cases(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
1275 codepoints) {
1276 int count;
1277 Py_UCS4 other;
1278
1279 count = 0;
1280
1281 codepoints[count++] = ch;
1282
1283 other = locale_toupper(locale_info, ch);
1284 if (other != ch)
1285 codepoints[count++] = other;
1286
1287 other = locale_tolower(locale_info, ch);
1288 if (other != ch)
1289 codepoints[count++] = other;
1290
1291 return count;
1292 }
1293
1294 /* Returns a character with its case folded. */
1295 static Py_UCS4 locale_simple_case_fold(RE_LocaleInfo* locale_info, Py_UCS4 ch)
1296 {
1297 return locale_tolower(locale_info, ch);
1298 }
1299
1300 /* Returns a character with its case folded. */
1301 static int locale_full_case_fold(RE_LocaleInfo* locale_info, Py_UCS4 ch,
1302 Py_UCS4* folded) {
1303 folded[0] = locale_tolower(locale_info, ch);
1304
1305 return 1;
1306 }
1307
1308 /* Gets all the case variants of Turkic 'I'. The given character will be listed
1309 * first.
1310 */
1311 static int locale_all_turkic_i(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
1312 cases) {
1313 int count;
1314 Py_UCS4 other;
1315
1316 count = 0;
1317
1318 cases[count++] = ch;
1319
1320 if (ch != 'I')
1321 cases[count++] = 'I';
1322
1323 if (ch != 'i')
1324 cases[count++] = 'i';
1325
1326 /* Uppercase 'i' will be either dotted (Turkic) or dotless (non-Turkic). */
1327 other = locale_toupper(locale_info, 'i');
1328 if (other != ch && other != 'I')
1329 cases[count++] = other;
1330
1331 /* Lowercase 'I' will be either dotless (Turkic) or dotted (non-Turkic). */
1332 other = locale_tolower(locale_info, 'I');
1333 if (other != ch && other != 'i')
1334 cases[count++] = other;
1335
1336 return count;
1337 }
1338
1339 /* The handlers for locale characters. */
1340 static RE_EncodingTable locale_encoding = {
1341 locale_has_property_wrapper,
1342 locale_at_boundary,
1343 locale_at_word_start,
1344 locale_at_word_end,
1345 locale_at_boundary, /* No special "default word boundary" for locale. */
1346 locale_at_word_start, /* No special "default start of a word" for locale. */
1347 locale_at_word_end, /* No special "default end of a word" for locale. */
1348 at_boundary_always, /* No special "grapheme boundary" for locale. */
1349 ascii_is_line_sep, /* Assume locale line separators are same as ASCII. */
1350 ascii_at_line_start, /* Assume locale line separators are same as ASCII. */
1351 ascii_at_line_end, /* Assume locale line separators are same as ASCII. */
1352 locale_possible_turkic,
1353 locale_all_cases,
1354 locale_simple_case_fold,
1355 locale_full_case_fold,
1356 locale_all_turkic_i,
1357 };
1358
1359 /* Unicode-specific. */
1360
1361 /* Checks whether a Unicode character has a property. */
1362 Py_LOCAL_INLINE(BOOL) unicode_has_property(RE_CODE property, Py_UCS4 ch) {
1363 RE_UINT32 prop;
1364 RE_UINT32 value;
1365 RE_UINT32 v;
1366
1367 prop = property >> 16;
1368 if (prop >= sizeof(re_get_property) / sizeof(re_get_property[0]))
1369 return FALSE;
1370
1371 value = property & 0xFFFF;
1372
1373 if (prop == RE_PROP_SCX) {
1374 int count;
1375 RE_UINT8 scripts[RE_MAX_SCX];
1376 int i;
1377
1378 count = re_get_script_extensions(ch, scripts);
1379
1380 for (i = 0; i < count; i++) {
1381 if (scripts[i] == value)
1382 return TRUE;
1383 }
1384
1385 return FALSE;
1386 }
1387
1388 v = re_get_property[prop](ch);
1389
1390 if (v == value)
1391 return TRUE;
1392
1393 if (prop == RE_PROP_GC) {
1394 switch (value) {
1395 case RE_PROP_ASSIGNED:
1396 return v != RE_PROP_CN;
1397 case RE_PROP_C:
1398 return (RE_PROP_C_MASK & (1 << v)) != 0;
1399 case RE_PROP_CASEDLETTER:
1400 return v == RE_PROP_LU || v == RE_PROP_LL || v == RE_PROP_LT;
1401 case RE_PROP_L:
1402 return (RE_PROP_L_MASK & (1 << v)) != 0;
1403 case RE_PROP_M:
1404 return (RE_PROP_M_MASK & (1 << v)) != 0;
1405 case RE_PROP_N:
1406 return (RE_PROP_N_MASK & (1 << v)) != 0;
1407 case RE_PROP_P:
1408 return (RE_PROP_P_MASK & (1 << v)) != 0;
1409 case RE_PROP_S:
1410 return (RE_PROP_S_MASK & (1 << v)) != 0;
1411 case RE_PROP_Z:
1412 return (RE_PROP_Z_MASK & (1 << v)) != 0;
1413 }
1414 }
1415
1416 return FALSE;
1417 }
1418
1419 /* Checks whether a character has a property, ignoring case. */
1420 Py_LOCAL_INLINE(BOOL) unicode_has_property_ign(RE_CODE property, Py_UCS4 ch) {
1421 RE_UINT32 prop;
1422
1423 prop = property >> 16;
1424
1425 if (property == RE_PROP_GC_LU || property == RE_PROP_GC_LL || property ==
1426 RE_PROP_GC_LT) {
1427 RE_UINT32 value;
1428
1429 value = re_get_general_category(ch);
1430
1431 return value == RE_PROP_LU || value == RE_PROP_LL || value ==
1432 RE_PROP_LT;
1433 } else if (prop == RE_PROP_UPPERCASE || prop == RE_PROP_LOWERCASE)
1434 return (BOOL)re_get_cased(ch);
1435
1436 /* The property is case-insensitive. */
1437 return unicode_has_property(property, ch);
1438 }
1439
1440 /* Wrapper for calling 'unicode_has_property' via a pointer. */
1441 static BOOL unicode_has_property_wrapper(RE_LocaleInfo* locale_info, RE_CODE
1442 property, Py_UCS4 ch) {
1443 return unicode_has_property(property, ch);
1444 }
1445
1446 /* Checks whether there's a word character to the left. */
1447 Py_LOCAL_INLINE(BOOL) unicode_word_left(RE_State* state, Py_ssize_t text_pos) {
1448 return text_pos > state->text_start && unicode_has_property(RE_PROP_WORD,
1449 state->char_at(state->text, text_pos - 1));
1450 }
1451
1452 /* Checks whether there's a word character to the right. */
1453 Py_LOCAL_INLINE(BOOL) unicode_word_right(RE_State* state, Py_ssize_t text_pos)
1454 {
1455 return text_pos < state->text_end && unicode_has_property(RE_PROP_WORD,
1456 state->char_at(state->text, text_pos));
1457 }
1458
1459 /* Checks whether a position is on a word boundary. */
1460 static BOOL unicode_at_boundary(RE_State* state, Py_ssize_t text_pos) {
1461 BOOL left;
1462 BOOL right;
1463
1464 left = unicode_word_left(state, text_pos);
1465 right = unicode_word_right(state, text_pos);
1466
1467 return left != right;
1468 }
1469
1470 /* Checks whether a position is at the start of a word. */
1471 static BOOL unicode_at_word_start(RE_State* state, Py_ssize_t text_pos) {
1472 BOOL left;
1473 BOOL right;
1474
1475 left = unicode_word_left(state, text_pos);
1476 right = unicode_word_right(state, text_pos);
1477
1478 return !left && right;
1479 }
1480
1481 /* Checks whether a position is at the end of a word. */
1482 static BOOL unicode_at_word_end(RE_State* state, Py_ssize_t text_pos) {
1483 BOOL left;
1484 BOOL right;
1485
1486 left = unicode_word_left(state, text_pos);
1487 right = unicode_word_right(state, text_pos);
1488
1489 return left && !right;
1490 }
1491
1492 /* Checks whether a character is a Unicode vowel.
1493 *
1494 * Only a limited number are treated as vowels.
1495 */
1496 Py_LOCAL_INLINE(BOOL) is_unicode_vowel(Py_UCS4 ch) {
1497 switch (Py_UNICODE_TOLOWER(ch)) {
1498 case 'a': case 0xE0: case 0xE1: case 0xE2:
1499 case 'e': case 0xE8: case 0xE9: case 0xEA:
1500 case 'i': case 0xEC: case 0xED: case 0xEE:
1501 case 'o': case 0xF2: case 0xF3: case 0xF4:
1502 case 'u': case 0xF9: case 0xFA: case 0xFB:
1503 return TRUE;
1504 default:
1505 return FALSE;
1506 }
1507 }
1508
1509 /* Checks whether a character is a Unicode apostrophe.
1510 *
1511 * This could be U+0027 (APOSTROPHE) or U+2019 (RIGHT SINGLE QUOTATION MARK /
1512 * curly apostrophe).
1513 */
1514 static BOOL is_unicode_apostrophe(Py_UCS4 ch) {
1515 return ch == 0x27 || ch == 0x2019;
1516 }
1517
1518 Py_LOCAL_INLINE(BOOL) IS_AHLETTER(RE_UINT32 v) {
1519 return v == RE_WBREAK_ALETTER || v == RE_WBREAK_HEBREWLETTER;
1520 }
1521
1522 Py_LOCAL_INLINE(BOOL) IS_MIDNUMLETQ(RE_UINT32 v) {
1523 return v == RE_WBREAK_MIDNUMLET || v == RE_WBREAK_SINGLEQUOTE;
1524 }
1525
1526 /* Checks whether a position is on a default word boundary.
1527 *
1528 * The rules are defined here:
1529 * https://www.unicode.org/reports/tr29/#Default_Word_Boundaries
1530 */
1531 static BOOL unicode_at_default_boundary(RE_State* state, Py_ssize_t text_pos) {
1532 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
1533 Py_ssize_t left_pos;
1534 Py_ssize_t right_pos;
1535 Py_UCS4 left_char;
1536 Py_UCS4 right_char;
1537 RE_UINT32 left_prop;
1538 RE_UINT32 right_prop;
1539 Py_ssize_t pos;
1540
1541 /* Break at the start and end of text, unless the text is empty. */
1542 /* WB1 and WB2 */
1543 if (text_pos <= state->text_start || text_pos >= state->text_end)
1544 return state->text_end > state->text_start;
1545
1546 /* In this function, left_pos is inclusive, i.e. it's the index of the
1547 * character.
1548 */
1549 char_at = state->char_at;
1550
1551 left_pos = text_pos - 1;
1552 right_pos = text_pos;
1553 left_char = char_at(state->text, left_pos);
1554 right_char = char_at(state->text, right_pos);
1555
1556 /* Do not break within CRLF. */
1557 /* WB3 */
1558 left_prop = re_get_word_break(left_char);
1559 right_prop = re_get_word_break(right_char);
1560
1561 if (left_prop == RE_WBREAK_CR && right_prop == RE_WBREAK_LF)
1562 return FALSE;
1563
1564 /* Otherwise break before and after Newlines (including CR and LF) */
1565 /* WB3a */
1566 if (left_prop == RE_WBREAK_NEWLINE || left_prop == RE_WBREAK_CR ||
1567 left_prop == RE_WBREAK_LF)
1568 return TRUE;
1569
1570 /* WB3b */
1571 if (right_prop == RE_WBREAK_NEWLINE || right_prop == RE_WBREAK_CR ||
1572 right_prop == RE_WBREAK_LF)
1573 return TRUE;
1574
1575 /* Do not break within emoji zwj sequences. */
1576 /* WB3c */
1577 if (left_prop == RE_WBREAK_ZWJ && re_get_extended_pictographic(right_char)
1578 != 0)
1579 return FALSE;
1580
1581 /* Keep horizontal whitespace together. */
1582 /* WB3d */
1583 if (left_prop == RE_WBREAK_WSEGSPACE && right_prop == RE_WBREAK_WSEGSPACE)
1584 return FALSE;
1585
1586 /* Ignore Format and Extend characters, except after sot, CR, LF, and
1587 * Newline. This also has the effect of: Any x (Format || Extend || ZWJ)
1588 */
1589 /* WB4 */
1590 if (right_prop == RE_WBREAK_EXTEND || right_prop == RE_WBREAK_FORMAT ||
1591 right_prop == RE_WBREAK_ZWJ)
1592 return FALSE;
1593
1594 while (left_prop == RE_WBREAK_EXTEND || left_prop == RE_WBREAK_FORMAT ||
1595 left_prop == RE_WBREAK_ZWJ) {
1596 if (left_pos <= state->text_start)
1597 return FALSE;
1598 --left_pos;
1599 left_char = char_at(state->text, left_pos);
1600 left_prop = re_get_word_break(left_char);
1601 }
1602
1603 /* Do not break between most letters. */
1604 /* WB5 */
1605 if (IS_AHLETTER(left_prop) && IS_AHLETTER(right_prop))
1606 return FALSE;
1607
1608 /* Break between apostrophe and vowels (French, Italian). */
1609 /* WB5a */
1610 if (is_unicode_apostrophe(left_char) && is_unicode_vowel(right_char))
1611 return FALSE;
1612
1613 /* Do not break letters across certain punctuation. */
1614 /* WB6 */
1615 if (right_pos + 1 < state->text_end) {
1616 Py_UCS4 right_right_char;
1617 RE_UINT32 right_right_prop;
1618
1619 right_right_char = char_at(state->text, right_pos + 1);
1620 right_right_prop = re_get_word_break(right_right_char);
1621
1622 if (IS_AHLETTER(left_prop) && (right_prop == RE_WBREAK_MIDLETTER ||
1623 IS_MIDNUMLETQ(right_prop)) && IS_AHLETTER(right_right_prop))
1624 return FALSE;
1625 }
1626
1627 /* WB7 */
1628 if (left_pos - 1 >= state->text_start) {
1629 Py_UCS4 left_left_char;
1630 RE_UINT32 left_left_prop;
1631
1632 left_left_char = char_at(state->text, left_pos - 1);
1633 left_left_prop = re_get_word_break(left_left_char);
1634
1635 if (IS_AHLETTER(left_left_prop) && (left_prop == RE_WBREAK_MIDLETTER ||
1636 IS_MIDNUMLETQ(left_prop)) && IS_AHLETTER(right_prop))
1637 return FALSE;
1638 }
1639
1640 /* WB7a */
1641 if (left_prop == RE_WBREAK_HEBREWLETTER && right_prop ==
1642 RE_WBREAK_SINGLEQUOTE)
1643 return FALSE;
1644
1645 /* WB7b */
1646 if (right_pos + 1 < state->text_end) {
1647 Py_UCS4 right_right_char;
1648 RE_UINT32 right_right_prop;
1649
1650 right_right_char = char_at(state->text, right_pos + 1);
1651 right_right_prop = re_get_word_break(right_right_char);
1652
1653 if (left_prop == RE_WBREAK_HEBREWLETTER && right_prop ==
1654 RE_WBREAK_DOUBLEQUOTE && right_right_prop == RE_WBREAK_HEBREWLETTER)
1655 return FALSE;
1656 }
1657
1658 /* WB7c */
1659 if (left_pos - 1 >= state->text_start) {
1660 Py_UCS4 left_left_char;
1661 RE_UINT32 left_left_prop;
1662
1663 left_left_char = char_at(state->text, left_pos - 1);
1664 left_left_prop = re_get_word_break(left_left_char);
1665
1666 if (left_left_prop == RE_WBREAK_HEBREWLETTER && left_prop ==
1667 RE_WBREAK_DOUBLEQUOTE && right_prop == RE_WBREAK_HEBREWLETTER)
1668 return FALSE;
1669 }
1670
1671 /* Do not break within sequences of digits, or digits adjacent to letters
1672 * ("3a", or "A3").
1673 */
1674 /* WB8 */
1675 if (left_prop == RE_WBREAK_NUMERIC && right_prop == RE_WBREAK_NUMERIC)
1676 return FALSE;
1677
1678 /* WB9 */
1679 if (IS_AHLETTER(left_prop) && right_prop == RE_WBREAK_NUMERIC)
1680 return FALSE;
1681
1682 /* WB10 */
1683 if (left_prop == RE_WBREAK_NUMERIC && IS_AHLETTER(right_prop))
1684 return FALSE;
1685
1686 /* Do not break within sequences, such as "3.2" or "3,456.789". */
1687 /* WB11 */
1688 if (left_pos - 1 >= state->text_start) {
1689 Py_UCS4 left_left_char;
1690 RE_UINT32 left_left_prop;
1691
1692 left_left_char = char_at(state->text, left_pos - 1);
1693 left_left_prop = re_get_word_break(left_left_char);
1694
1695 if (left_left_prop == RE_WBREAK_NUMERIC && (left_prop ==
1696 RE_WBREAK_MIDNUM || IS_MIDNUMLETQ(left_prop)) && right_prop ==
1697 RE_WBREAK_NUMERIC)
1698 return FALSE;
1699 }
1700
1701 /* WB12 */
1702 if (right_pos + 1 < state->text_end) {
1703 Py_UCS4 right_right_char;
1704 RE_UINT32 right_right_prop;
1705
1706 right_right_char = char_at(state->text, right_pos + 1);
1707 right_right_prop = re_get_word_break(right_right_char);
1708
1709 if (left_prop == RE_WBREAK_NUMERIC && (right_prop == RE_WBREAK_MIDNUM
1710 || IS_MIDNUMLETQ(right_prop)) && right_right_prop ==
1711 RE_WBREAK_NUMERIC)
1712 return FALSE;
1713 }
1714
1715 /* Do not break between Katakana. */
1716 /* WB13 */
1717 if (left_prop == RE_WBREAK_KATAKANA && right_prop == RE_WBREAK_KATAKANA)
1718 return FALSE;
1719
1720 /* Do not break from extenders. */
1721 /* WB13a */
1722 if ((IS_AHLETTER(left_prop) || left_prop == RE_WBREAK_NUMERIC || left_prop
1723 == RE_WBREAK_KATAKANA || left_prop == RE_WBREAK_EXTENDNUMLET) &&
1724 right_prop == RE_WBREAK_EXTENDNUMLET)
1725 return FALSE;
1726
1727 /* WB13b */
1728 if (left_prop == RE_WBREAK_EXTENDNUMLET && (IS_AHLETTER(right_prop) ||
1729 right_prop == RE_WBREAK_NUMERIC || right_prop == RE_WBREAK_KATAKANA))
1730 return FALSE;
1731
1732 /* Do not break within emoji flag sequences. That is, do not break between
1733 * regional indicator (RI) symbols if there is an odd number of RI
1734 * characters before the break point.
1735 */
1736 /* WB15 and WB16 */
1737 pos = left_pos;
1738
1739 while (pos >= state->text_start && re_get_word_break(char_at(state->text, pos)) ==
1740 RE_WBREAK_REGIONALINDICATOR)
1741 --pos;
1742
1743 if ((left_pos - pos) % 2 == 1)
1744 return FALSE;
1745
1746 /* Otherwise, break everywhere (including around ideographs). */
1747 /* WB999 */
1748 return TRUE;
1749 }
1750
1751 /* Checks whether a position is at the start/end of a word. */
1752 Py_LOCAL_INLINE(BOOL) unicode_at_default_word_start_or_end(RE_State* state,
1753 Py_ssize_t text_pos, BOOL at_start) {
1754 BOOL before;
1755 BOOL after;
1756
1757 /* Is it at a boundary? */
1758 if (!unicode_at_default_boundary(state, text_pos))
1759 return FALSE;
1760
1761 /* Look at the 2 characters either side of the boundary. Are they part of a
1762 * word?
1763 */
1764 before = unicode_word_left(state, text_pos);
1765 after = unicode_word_right(state, text_pos);
1766
1767 return before != at_start && after == at_start;
1768 }
1769
1770 /* Checks whether a position is at the start of a word. */
1771 static BOOL unicode_at_default_word_start(RE_State* state, Py_ssize_t text_pos)
1772 {
1773 return unicode_at_default_word_start_or_end(state, text_pos, TRUE);
1774 }
1775
1776 /* Checks whether a position is at the end of a word. */
1777 static BOOL unicode_at_default_word_end(RE_State* state, Py_ssize_t text_pos) {
1778 return unicode_at_default_word_start_or_end(state, text_pos, FALSE);
1779 }
1780
1781 /* Checks whether a position is on a grapheme boundary.
1782 *
1783 * The rules are defined here:
1784 * https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
1785 */
1786 static BOOL unicode_at_grapheme_boundary(RE_State* state, Py_ssize_t text_pos)
1787 {
1788 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
1789 Py_ssize_t left_pos;
1790 Py_ssize_t right_pos;
1791 Py_UCS4 left_char;
1792 Py_UCS4 right_char;
1793 RE_UINT32 left_prop;
1794 RE_UINT32 right_prop;
1795 RE_UINT32 prop;
1796 Py_ssize_t pos;
1797
1798 /* Break at the start and end of text, unless the text is empty. */
1799 /* GB1 and GB2 */
1800 if (text_pos <= state->text_start || text_pos >= state->text_end)
1801 return state->text_end > state->text_start;
1802
1803 /* In this function, left_pos is inclusive, i.e. it's the index of the
1804 * character.
1805 */
1806 char_at = state->char_at;
1807
1808 left_pos = text_pos - 1;
1809 right_pos = text_pos;
1810 left_char = char_at(state->text, left_pos);
1811 right_char = char_at(state->text, right_pos);
1812
1813 /* Do not break between a CR and LF. Otherwise, break before and after
1814 * controls.
1815 */
1816 /* GB3 */
1817 left_prop = re_get_grapheme_cluster_break(left_char);
1818 right_prop = re_get_grapheme_cluster_break(right_char);
1819
1820 if (left_prop == RE_GBREAK_CR && right_prop == RE_GBREAK_LF)
1821 return FALSE;
1822
1823 /* GB4 */
1824 if (left_prop == RE_GBREAK_CONTROL || left_prop == RE_GBREAK_CR ||
1825 left_prop == RE_GBREAK_LF)
1826 return TRUE;
1827
1828 /* GB5 */
1829 if (right_prop == RE_GBREAK_CONTROL || right_prop == RE_GBREAK_CR ||
1830 right_prop == RE_GBREAK_LF)
1831 return TRUE;
1832
1833 /* Do not break Hangul syllable sequences. */
1834 /* GB6 */
1835 if (left_prop == RE_GBREAK_L && (right_prop == RE_GBREAK_L || right_prop ==
1836 RE_GBREAK_V || right_prop == RE_GBREAK_LV || right_prop ==
1837 RE_GBREAK_LVT))
1838 return FALSE;
1839
1840 /* GB7 */
1841 if ((left_prop == RE_GBREAK_LV || left_prop == RE_GBREAK_V) && (right_prop
1842 == RE_GBREAK_V || right_prop == RE_GBREAK_T))
1843 return FALSE;
1844
1845 /* GB8 */
1846 if ((left_prop == RE_GBREAK_LVT || left_prop == RE_GBREAK_T) && right_prop
1847 == RE_GBREAK_T)
1848 return FALSE;
1849
1850 /* Do not break before extending characters or ZWJ. */
1851 /* GB9 */
1852 if (right_prop == RE_GBREAK_EXTEND || right_prop == RE_GBREAK_ZWJ)
1853 return FALSE;
1854
1855 /* The GB9a and GB9b rules only apply to extended grapheme clusters: Do not
1856 * break before SpacingMarks, or after Prepend characters.
1857 */
1858 /* GB9a */
1859 if (right_prop == RE_GBREAK_SPACINGMARK)
1860 return FALSE;
1861
1862 /* GB9b */
1863 if (left_prop == RE_GBREAK_PREPEND)
1864 return FALSE;
1865
1866 /* The GB9c rule only applies to extended grapheme clusters: Do not break
1867 * within certain combinations with Indic_Conjunct_Break (InCB)=Linker.
1868 */
1869 /* GB9c */
1870 if (re_get_indic_conjunct_break(right_char) == RE_INCB_CONSONANT) {
1871 BOOL has_linker;
1872
1873 has_linker = FALSE;
1874 pos = left_pos;
1875
1876 do {
1877 prop = re_get_indic_conjunct_break(char_at(state->text, pos));
1878
1879 switch (prop) {
1880 case RE_INCB_LINKER:
1881 has_linker = TRUE;
1882 break;
1883 case RE_INCB_EXTEND:
1884 break;
1885 case RE_INCB_CONSONANT:
1886 if (has_linker)
1887 return FALSE;
1888 goto end_GB9c;
1889 default:
1890 goto end_GB9c;
1891 }
1892
1893 --pos;
1894 } while (pos >= state->text_start);
1895 }
1896
1897 end_GB9c:
1898 /* Do not break within emoji modifier sequences or emoji zwj sequences. */
1899 /* GB11 */
1900 if (left_prop == RE_GBREAK_ZWJ && re_get_extended_pictographic(right_char))
1901 {
1902 pos = left_pos - 1;
1903
1904 while (pos >= state->text_start && re_get_grapheme_cluster_break(char_at(state->text,
1905 pos)) == RE_GBREAK_EXTEND)
1906 --pos;
1907
1908 if (pos >= state->text_start && re_get_extended_pictographic(char_at(state->text,
1909 pos)))
1910 return FALSE;
1911 }
1912
1913 /* The \p{Extended_Pictographic} values are provided as a part of the Emoji
1914 * data in [UTS51]. Do not break within emoji flag sequences. That is, do
1915 * not break between regional indicator (RI) symbols if there is an odd
1916 * number of RI characters before the break point.
1917 */
1918 /* GB12 and GB13 */
1919 if (right_prop == RE_GBREAK_REGIONALINDICATOR) {
1920 pos = left_pos;
1921
1922 while (pos >= state->text_start && re_get_grapheme_cluster_break(char_at(state->text,
1923 pos)) == RE_GBREAK_REGIONALINDICATOR)
1924 --pos;
1925
1926 if ((left_pos - pos) % 2 == 1)
1927 return FALSE;
1928 }
1929
1930 /* Otherwise, break everywhere. */
1931 /* GB999 */
1932 return TRUE;
1933 }
1934
1935 /* Checks whether a character is a line separator. */
1936 static BOOL unicode_is_line_sep(Py_UCS4 ch) {
1937 return (0x0A <= ch && ch <= 0x0D) || ch == 0x85 || ch == 0x2028 || ch ==
1938 0x2029;
1939 }
1940
1941 /* Checks whether a position is at the start of a line. */
1942 static BOOL unicode_at_line_start(RE_State* state, Py_ssize_t text_pos) {
1943 Py_UCS4 ch;
1944
1945 if (text_pos <= state->text_start)
1946 return TRUE;
1947
1948 ch = state->char_at(state->text, text_pos - 1);
1949
1950 if (ch == 0x0D) {
1951 if (text_pos >= state->text_end)
1952 return TRUE;
1953
1954 /* No line break inside CRLF. */
1955 return state->char_at(state->text, text_pos) != 0x0A;
1956 }
1957
1958 return (0x0A <= ch && ch <= 0x0D) || ch == 0x85 || ch == 0x2028 || ch ==
1959 0x2029;
1960 }
1961
1962 /* Checks whether a position is at the end of a line. */
1963 static BOOL unicode_at_line_end(RE_State* state, Py_ssize_t text_pos) {
1964 Py_UCS4 ch;
1965
1966 if (text_pos >= state->text_end)
1967 return TRUE;
1968
1969 ch = state->char_at(state->text, text_pos);
1970
1971 if (ch == 0x0A) {
1972 if (text_pos <= state->text_start)
1973 return TRUE;
1974
1975 /* No line break inside CRLF. */
1976 return state->char_at(state->text, text_pos - 1) != 0x0D;
1977 }
1978
1979 return (0x0A <= ch && ch <= 0x0D) || ch == 0x85 || ch == 0x2028 || ch ==
1980 0x2029;
1981 }
1982
1983 /* Checks whether a character could be Turkic (variants of I/i). */
1984 static BOOL unicode_possible_turkic(RE_LocaleInfo* locale_info, Py_UCS4 ch) {
1985 return ch == 'I' || ch == 'i' || ch == 0x0130 || ch == 0x0131;
1986 }
1987
1988 /* Gets all the cases of a character. */
1989 static int unicode_all_cases(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
1990 codepoints) {
1991 return re_get_all_cases(ch, codepoints);
1992 }
1993
1994 /* Returns a character with its case folded, unless it could be Turkic
1995 * (variants of I/i).
1996 */
1997 static Py_UCS4 unicode_simple_case_fold(RE_LocaleInfo* locale_info, Py_UCS4 ch)
1998 {
1999 /* Is it a possible Turkic character? If so, pass it through unchanged. */
2000 if (ch == 'I' || ch == 'i' || ch == 0x0130 || ch == 0x0131)
2001 return ch;
2002
2003 return (Py_UCS4)re_get_simple_case_folding(ch);
2004 }
2005
2006 /* Returns a character with its case folded, unless it could be Turkic
2007 * (variants of I/i).
2008 */
2009 static int unicode_full_case_fold(RE_LocaleInfo* locale_info, Py_UCS4 ch,
2010 Py_UCS4* folded) {
2011 /* Is it a possible Turkic character? If so, pass it through unchanged. */
2012 if (ch == 'I' || ch == 'i' || ch == 0x0130 || ch == 0x0131) {
2013 folded[0] = ch;
2014 return 1;
2015 }
2016
2017 return re_get_full_case_folding(ch, folded);
2018 }
2019
2020 /* Gets all the case variants of Turkic 'I'. */
2021 static int unicode_all_turkic_i(RE_LocaleInfo* locale_info, Py_UCS4 ch,
2022 Py_UCS4* cases) {
2023 int count;
2024
2025 count = 0;
2026
2027 cases[count++] = ch;
2028
2029 if (ch != 'I')
2030 cases[count++] = 'I';
2031
2032 if (ch != 'i')
2033 cases[count++] = 'i';
2034
2035 if (ch != 0x130)
2036 cases[count++] = 0x130;
2037
2038 if (ch != 0x131)
2039 cases[count++] = 0x131;
2040
2041 return count;
2042
2043 }
2044
2045 /* The handlers for Unicode characters. */
2046 static RE_EncodingTable unicode_encoding = {
2047 unicode_has_property_wrapper,
2048 unicode_at_boundary,
2049 unicode_at_word_start,
2050 unicode_at_word_end,
2051 unicode_at_default_boundary,
2052 unicode_at_default_word_start,
2053 unicode_at_default_word_end,
2054 unicode_at_grapheme_boundary,
2055 unicode_is_line_sep,
2056 unicode_at_line_start,
2057 unicode_at_line_end,
2058 unicode_possible_turkic,
2059 unicode_all_cases,
2060 unicode_simple_case_fold,
2061 unicode_full_case_fold,
2062 unicode_all_turkic_i,
2063 };
2064
2065 Py_LOCAL_INLINE(PyObject*) get_object(char* module_name, char* object_name);
2066
2067 /* Sets the error message. */
2068 Py_LOCAL_INLINE(void) set_error(int status, PyObject* object) {
2069 TRACE(("<<set_error>>\n"))
2070
2071 PyErr_Clear();
2072
2073 switch (status) {
2074 case RE_ERROR_BAD_TIMEOUT:
2075 PyErr_SetString(PyExc_ValueError, "timeout not float or None");
2076 break;
2077 case RE_ERROR_CANCELLED:
2078 /* An exception has already been raised, so let it fly. */
2079 break;
2080 case RE_ERROR_CONCURRENT:
2081 PyErr_SetString(PyExc_ValueError, "concurrent not int or None");
2082 break;
2083 case RE_ERROR_GROUP_INDEX_TYPE:
2084 if (object)
2085 PyErr_Format(PyExc_TypeError,
2086 "group indices must be integers or strings, not %.200s",
2087 object->ob_type->tp_name);
2088 else
2089 PyErr_Format(PyExc_TypeError,
2090 "group indices must be integers or strings");
2091 break;
2092 case RE_ERROR_ILLEGAL:
2093 PyErr_SetString(PyExc_RuntimeError, "invalid RE code");
2094 break;
2095 case RE_ERROR_INDEX:
2096 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
2097 break;
2098 case RE_ERROR_INVALID_GROUP_REF:
2099 if (!error_exception)
2100 error_exception = get_object("regex._regex_core", "error");
2101
2102 PyErr_SetString(error_exception, "invalid group reference");
2103 break;
2104 case RE_ERROR_MEMORY:
2105 PyErr_NoMemory();
2106 break;
2107 case RE_ERROR_NOT_BYTES:
2108 PyErr_Format(PyExc_TypeError,
2109 "expected a bytes-like object, %.200s found",
2110 object->ob_type->tp_name);
2111 break;
2112 case RE_ERROR_NOT_STRING:
2113 PyErr_Format(PyExc_TypeError, "expected string instance, %.200s found",
2114 object->ob_type->tp_name);
2115 break;
2116 case RE_ERROR_NOT_UNICODE:
2117 PyErr_Format(PyExc_TypeError, "expected str instance, %.200s found",
2118 object->ob_type->tp_name);
2119 break;
2120 case RE_ERROR_NO_SUCH_GROUP:
2121 PyErr_SetString(PyExc_IndexError, "no such group");
2122 break;
2123 case RE_ERROR_REPLACEMENT:
2124 if (!error_exception)
2125 error_exception = get_object("regex._regex_core", "error");
2126
2127 PyErr_SetString(error_exception, "invalid replacement");
2128 break;
2129 case RE_ERROR_TIMED_OUT:
2130 PyErr_SetString(PyExc_TimeoutError, "regex timed out");
2131 break;
2132 default:
2133 /* Other error codes indicate compiler/engine bugs. */
2134 PyErr_SetString(PyExc_RuntimeError,
2135 "internal error in regular expression engine");
2136 break;
2137 }
2138 }
2139
2140 /* Allocates memory.
2141 *
2142 * Sets the Python error handler and returns NULL if the allocation fails.
2143 */
2144 Py_LOCAL_INLINE(void*) re_alloc(size_t size) {
2145 void* new_ptr;
2146
2147 new_ptr = PyMem_Malloc(size);
2148 if (!new_ptr)
2149 set_error(RE_ERROR_MEMORY, NULL);
2150
2151 return new_ptr;
2152 }
2153
2154 /* Reallocates memory.
2155 *
2156 * Sets the Python error handler and returns NULL if the reallocation fails.
2157 */
2158 Py_LOCAL_INLINE(void*) re_realloc(void* ptr, size_t size) {
2159 void* new_ptr;
2160
2161 new_ptr = PyMem_Realloc(ptr, size);
2162 if (!new_ptr)
2163 set_error(RE_ERROR_MEMORY, NULL);
2164
2165 return new_ptr;
2166 }
2167
2168 /* Deallocates memory. */
2169 Py_LOCAL_INLINE(void) re_dealloc(void* ptr) {
2170 PyMem_Free(ptr);
2171 }
2172
2173 /* Releases the GIL if multithreading is enabled. */
2174 Py_LOCAL_INLINE(void) release_GIL(RE_State* state) {
2175 if (state->is_multithreaded && !state->thread_state)
2176 state->thread_state = PyEval_SaveThread();
2177 }
2178
2179 /* Acquires the GIL if multithreading is enabled. */
2180 Py_LOCAL_INLINE(void) acquire_GIL(RE_State* state) {
2181 if (state->is_multithreaded && state->thread_state) {
2182 PyEval_RestoreThread(state->thread_state);
2183 state->thread_state = NULL;
2184 }
2185 }
2186
2187 /* Allocates memory, holding the GIL during the allocation.
2188 *
2189 * Sets the Python error handler and returns NULL if the allocation fails.
2190 */
2191 Py_LOCAL_INLINE(void*) safe_alloc(RE_State* state, size_t size) {
2192 void* new_ptr;
2193
2194 acquire_GIL(state);
2195
2196 new_ptr = re_alloc(size);
2197
2198 release_GIL(state);
2199
2200 return new_ptr;
2201 }
2202
2203 /* Reallocates memory, holding the GIL during the reallocation.
2204 *
2205 * Sets the Python error handler and returns NULL if the reallocation fails.
2206 */
2207 Py_LOCAL_INLINE(void*) safe_realloc(RE_State* state, void* ptr, size_t size) {
2208 void* new_ptr;
2209
2210 acquire_GIL(state);
2211
2212 new_ptr = re_realloc(ptr, size);
2213
2214 release_GIL(state);
2215
2216 return new_ptr;
2217 }
2218
2219 /* Deallocates memory, holding the GIL during the deallocation. */
2220 Py_LOCAL_INLINE(void) safe_dealloc(RE_State* state, void* ptr) {
2221 acquire_GIL(state);
2222
2223 re_dealloc(ptr);
2224
2225 release_GIL(state);
2226 }
2227
2228 /* Checks whether matching has timed out. */
2229 Py_LOCAL_INLINE(BOOL) check_timed_out(RE_State* state) {
2230 if (state->timeout == RE_NO_TIMEOUT)
2231 /* No timeout. */
2232 return FALSE;
2233
2234 if ((Py_ssize_t)(clock() - state->start_time) < state->timeout)
2235 /* Hasn't timed out yet. */
2236 return FALSE;
2237
2238 set_error(RE_ERROR_TIMED_OUT, NULL);
2239
2240 return TRUE;
2241 }
2242
2243 /* Checks whether to cancel due to a KeyboardInterrupt or a timeout. */
2244 Py_LOCAL_INLINE(BOOL) safe_check_cancel(RE_State* state) {
2245 BOOL result;
2246
2247 acquire_GIL(state);
2248
2249 result = (BOOL)PyErr_CheckSignals();
2250
2251 if (!result)
2252 /* Has it timed out? */
2253 result = check_timed_out(state);
2254
2255 release_GIL(state);
2256
2257 return result;
2258 }
2259
2260 /* Initialises a stack of bytes. */
2261 Py_LOCAL_INLINE(BOOL) ByteStack_init(RE_State* state, ByteStack* stack) {
2262 stack->capacity = 0;
2263 stack->count = 0;
2264 stack->storage = NULL;
2265
2266 return TRUE;
2267 }
2268
2269 /* Finalises a stack of bytes. */
2270 Py_LOCAL_INLINE(void) ByteStack_fini(RE_State* state, ByteStack* stack) {
2271 re_dealloc(stack->storage);
2272 stack->storage = NULL;
2273 stack->capacity = 0;
2274 stack->count = 0;
2275 }
2276
2277 /* Resets a stack of bytes. */
2278 Py_LOCAL_INLINE(void) ByteStack_reset(RE_State* state, ByteStack* stack) {
2279 stack->count = 0;
2280 }
2281
2282 /* Pushes a byte onto a stack of bytes. */
2283 Py_LOCAL_INLINE(BOOL) ByteStack_push(RE_State* state, ByteStack* stack, BYTE
2284 item) {
2285 if (stack->count >= stack->capacity) {
2286 size_t new_capacity;
2287 void* new_storage;
2288
2289 new_capacity = stack->capacity * 2;
2290
2291 if (new_capacity == 0)
2292 new_capacity = 64;
2293
2294 if (new_capacity >= RE_MEMORY_LIMIT) {
2295 acquire_GIL(state);
2296 set_error(RE_ERROR_MEMORY, NULL);
2297 release_GIL(state);
2298 return FALSE;
2299 }
2300
2301 new_storage = safe_realloc(state, stack->storage, new_capacity);
2302 if (!new_storage)
2303 return FALSE;
2304
2305 stack->capacity = new_capacity;
2306 stack->storage = new_storage;
2307 }
2308
2309 stack->storage[stack->count++] = item;
2310
2311 return TRUE;
2312 }
2313
2314 /* Pushes a block onto a stack of bytes. */
2315 Py_LOCAL_INLINE(BOOL) ByteStack_push_block(RE_State* state, ByteStack* stack,
2316 void* block, size_t count) {
2317 size_t new_count;
2318
2319 new_count = stack->count + count;
2320
2321 if (new_count > stack->capacity) {
2322 size_t new_capacity;
2323 void* new_storage;
2324
2325 new_capacity = stack->capacity;
2326
2327 if (new_capacity == 0)
2328 new_capacity = 256;
2329
2330 while (new_count > new_capacity)
2331 new_capacity *= 2;
2332
2333 if (new_capacity >= RE_MEMORY_LIMIT) {
2334 acquire_GIL(state);
2335 set_error(RE_ERROR_MEMORY, NULL);
2336 release_GIL(state);
2337 return FALSE;
2338 }
2339
2340 new_storage = safe_realloc(state, stack->storage, new_capacity);
2341 if (!new_storage)
2342 return FALSE;
2343
2344 stack->capacity = new_capacity;
2345 stack->storage = new_storage;
2346 }
2347
2348 Py_MEMCPY(stack->storage + stack->count, block, count);
2349 stack->count = new_count;
2350
2351 return TRUE;
2352 }
2353
2354 /* Pops a byte off a stack of bytes. */
2355 Py_LOCAL_INLINE(BOOL) ByteStack_pop(RE_State* state, ByteStack* stack, BYTE*
2356 item) {
2357 if (stack->count < 1)
2358 return FALSE;
2359
2360 *item = stack->storage[--stack->count];
2361
2362 return TRUE;
2363 }
2364
2365 /* Pops a block off a stack of bytes. */
2366 Py_LOCAL_INLINE(BOOL) ByteStack_pop_block(RE_State* state, ByteStack* stack,
2367 void* block, size_t count) {
2368 if (count > stack->count)
2369 return FALSE;
2370
2371 stack->count -= count;
2372 Py_MEMCPY(block, stack->storage + stack->count, count);
2373
2374 return TRUE;
2375 }
2376
2377 /* Drops a byte off a stack of bytes. */
2378 Py_LOCAL_INLINE(BOOL) ByteStack_drop(RE_State* state, ByteStack* stack) {
2379 if (stack->count < 1)
2380 return FALSE;
2381
2382 --stack->count;
2383
2384 return TRUE;
2385 }
2386
2387 /* Drops a block off a stack of bytes. */
2388 Py_LOCAL_INLINE(BOOL) ByteStack_drop_block(RE_State* state, ByteStack* stack,
2389 size_t count) {
2390 if (count > stack->count)
2391 return FALSE;
2392
2393 stack->count -= count;
2394
2395 return TRUE;
2396 }
2397
2398 /* Gets the top block off a stack of bytes. */
2399 Py_LOCAL_INLINE(BOOL) ByteStack_top_block(RE_State* state, ByteStack* stack,
2400 void* block, size_t count) {
2401 if (count > stack->count)
2402 return FALSE;
2403
2404 Py_MEMCPY(block, stack->storage + stack->count - count, count);
2405
2406 return TRUE;
2407 }
2408
2409 /* Pushes a int8 onto a stack of bytes. */
2410 Py_LOCAL_INLINE(BOOL) push_int8(RE_State* state, ByteStack* stack, RE_INT8
2411 item) {
2412 return ByteStack_push(state, stack, (BYTE)item);
2413 }
2414
2415 /* Pushes a uint8 onto a stack of bytes. */
2416 Py_LOCAL_INLINE(BOOL) push_uint8(RE_State* state, ByteStack* stack, RE_UINT8
2417 item) {
2418 return ByteStack_push(state, stack, (BYTE)item);
2419 }
2420
2421 /* Pushes a bool onto a stack of bytes. */
2422 Py_LOCAL_INLINE(BOOL) push_bool(RE_State* state, ByteStack* stack, BOOL item) {
2423 return ByteStack_push(state, stack, (BYTE)item);
2424 }
2425
2426 /* Pushes a Py_ssize_t onto a stack of bytes. */
2427 Py_LOCAL_INLINE(BOOL) push_ssize(RE_State* state, ByteStack* stack, Py_ssize_t
2428 item) {
2429 return ByteStack_push_block(state, stack, (void*)&item, sizeof(item));
2430 }
2431
2432 /* Pushes a size_t onto a stack of bytes. */
2433 Py_LOCAL_INLINE(BOOL) push_size(RE_State* state, ByteStack* stack, size_t item)
2434 {
2435 return ByteStack_push_block(state, stack, (void*)&item, sizeof(item));
2436 }
2437
2438 /* Pushes a code onto a stack of bytes. */
2439 Py_LOCAL_INLINE(BOOL) push_code(RE_State* state, ByteStack* stack, RE_CODE
2440 item) {
2441 return ByteStack_push_block(state, stack, (void*)&item, sizeof(item));
2442 }
2443
2444 /* Pushes an int onto a stack of bytes. */
2445 Py_LOCAL_INLINE(BOOL) push_int(RE_State* state, ByteStack* stack, int item) {
2446 return ByteStack_push_block(state, stack, (void*)&item, sizeof(item));
2447 }
2448
2449 /* Pushes a pointer onto a stack of bytes. */
2450 Py_LOCAL_INLINE(BOOL) push_pointer(RE_State* state, ByteStack* stack, void*
2451 item) {
2452 return ByteStack_push_block(state, stack, (void*)&item, sizeof(item));
2453 }
2454
2455 /* Pushes fuzzy counts onto a stack of bytes. */
2456 Py_LOCAL_INLINE(BOOL) push_fuzzy_counts(RE_State* state, ByteStack* stack,
2457 size_t* fuzzy_counts) {
2458 if (!state->is_fuzzy)
2459 return TRUE;
2460
2461 return ByteStack_push_block(state, stack, (void*)fuzzy_counts,
2462 RE_FUZZY_COUNT * sizeof(size_t));
2463 }
2464
2465 /* Pushes group spans onto a stack of bytes. */
2466 Py_LOCAL_INLINE(BOOL) push_groups(RE_State* state, ByteStack* stack) {
2467 Py_ssize_t group_count;
2468 Py_ssize_t g;
2469
2470 group_count = (Py_ssize_t)state->pattern->true_group_count;
2471 if (group_count == 0)
2472 return TRUE;
2473
2474 for (g = 0; g < group_count; g++) {
2475 RE_GroupData* group;
2476
2477 group = &state->groups[g];
2478
2479 if (!push_ssize(state, stack, group->current))
2480 return FALSE;
2481 }
2482
2483 /* stack: current#0 current#1 ... */
2484
2485 return TRUE;
2486 }
2487
2488 /* Pushes group captures and spans onto a stack of bytes. */
2489 Py_LOCAL_INLINE(BOOL) push_captures(RE_State* state, ByteStack* stack) {
2490 Py_ssize_t group_count;
2491 Py_ssize_t g;
2492
2493 group_count = (Py_ssize_t)state->pattern->true_group_count;
2494 if (group_count == 0)
2495 return TRUE;
2496
2497 for (g = 0; g < group_count; g++) {
2498 RE_GroupData* group;
2499
2500 group = &state->groups[g];
2501
2502 if (!push_size(state, stack, group->count))
2503 return FALSE;
2504 if (!push_ssize(state, stack, group->current))
2505 return FALSE;
2506 }
2507
2508 /* stack: group[0] group[1] ...
2509 *
2510 * group: capture[0] capture[1] ... count current
2511 */
2512
2513 return TRUE;
2514 }
2515
2516 /* Pushes the repeat guard data onto the stack. */
2517 Py_LOCAL_INLINE(BOOL) push_guard_data(RE_State* state, ByteStack* stack,
2518 RE_GuardList* guard_list) {
2519 if (!ByteStack_push_block(state, stack, (void*)guard_list->spans,
2520 guard_list->count * sizeof(RE_GuardSpan)))
2521 return FALSE;
2522 if (!push_size(state, stack, guard_list->count))
2523 return FALSE;
2524
2525 return TRUE;
2526 }
2527
2528 /* Pushes the repeat data onto the stack. */
2529 Py_LOCAL_INLINE(BOOL) push_repeat_data(RE_State* state, ByteStack* stack,
2530 RE_RepeatData* repeat_data) {
2531 if (!push_guard_data(state, stack, &repeat_data->body_guard_list))
2532 return FALSE;
2533 if (!push_guard_data(state, stack, &repeat_data->tail_guard_list))
2534 return FALSE;
2535 if (!push_size(state, stack, repeat_data->count))
2536 return FALSE;
2537 if (!push_ssize(state, stack, repeat_data->start))
2538 return FALSE;
2539 if (!push_size(state, stack, repeat_data->capture_change))
2540 return FALSE;
2541
2542 return TRUE;
2543 }
2544
2545 /* Pushes the repeats onto the stack. */
2546 Py_LOCAL_INLINE(BOOL) push_repeats(RE_State* state, ByteStack* stack) {
2547 PatternObject* pattern;
2548 Py_ssize_t repeat_count;
2549 Py_ssize_t r;
2550
2551 pattern = state->pattern;
2552
2553 repeat_count = (Py_ssize_t)pattern->repeat_count;
2554 if (repeat_count == 0)
2555 return TRUE;
2556
2557 for (r = 0; r < repeat_count; r++) {
2558 if (!push_repeat_data(state, stack, &state->repeats[r]))
2559 return FALSE;
2560 }
2561
2562 return TRUE;
2563 }
2564
2565 /* Pushes the bstack count onto the pstack. */
2566 Py_LOCAL_INLINE(BOOL) push_bstack(RE_State* state) {
2567 if (!push_size(state, &state->pstack, state->bstack.count))
2568 return FALSE;
2569
2570 return TRUE;
2571 }
2572
2573 /* Pushes the sstack count onto the bstack. */
2574 Py_LOCAL_INLINE(BOOL) push_sstack(RE_State* state) {
2575 if (!push_size(state, &state->bstack, state->sstack.count))
2576 return FALSE;
2577
2578 return TRUE;
2579 }
2580
2581 /* Pops a int8 off a stack of bytes. */
2582 Py_LOCAL_INLINE(BOOL) pop_int8(RE_State* state, ByteStack* stack, RE_INT8*
2583 item) {
2584 return ByteStack_pop(state, stack, (BYTE*)item);
2585 }
2586
2587 /* Pops a uint8 off a stack of bytes. */
2588 Py_LOCAL_INLINE(BOOL) pop_uint8(RE_State* state, ByteStack* stack, RE_UINT8*
2589 item) {
2590 return ByteStack_pop(state, stack, (BYTE*)item);
2591 }
2592
2593 /* Pops a bool off a stack of bytes. */
2594 Py_LOCAL_INLINE(BOOL) pop_bool(RE_State* state, ByteStack* stack, BOOL* item) {
2595 return ByteStack_pop(state, stack, (BYTE*)item);
2596 }
2597
2598 /* Pops a Py_ssize_t off a stack of bytes. */
2599 Py_LOCAL_INLINE(BOOL) pop_ssize(RE_State* state, ByteStack* stack, Py_ssize_t*
2600 item) {
2601 return ByteStack_pop_block(state, stack, (void*)item, sizeof(*item));
2602 }
2603
2604 /* Pops a size_t off a stack of bytes. */
2605 Py_LOCAL_INLINE(BOOL) pop_size(RE_State* state, ByteStack* stack, size_t* item)
2606 {
2607 return ByteStack_pop_block(state, stack, (void*)item, sizeof(*item));
2608 }
2609
2610 /* Pops a RE_CODE off a stack of bytes. */
2611 Py_LOCAL_INLINE(BOOL) pop_code(RE_State* state, ByteStack* stack, RE_CODE*
2612 item) {
2613 return ByteStack_pop_block(state, stack, (void*)item, sizeof(*item));
2614 }
2615
2616 /* Pops an int off a stack of bytes. */
2617 Py_LOCAL_INLINE(BOOL) pop_int(RE_State* state, ByteStack* stack, int* item) {
2618 return ByteStack_pop_block(state, stack, (void*)item, sizeof(*item));
2619 }
2620
2621 /* Pops a pointer off a stack of bytes. */
2622 Py_LOCAL_INLINE(BOOL) pop_pointer(RE_State* state, ByteStack* stack, void**
2623 item) {
2624 return ByteStack_pop_block(state, stack, (void*)item, sizeof(*item));
2625 }
2626
2627 /* Pops fuzzy counts off a stack of bytes. */
2628 Py_LOCAL_INLINE(BOOL) pop_fuzzy_counts(RE_State* state, ByteStack* stack,
2629 size_t* fuzzy_counts) {
2630 if (!state->is_fuzzy)
2631 return TRUE;
2632
2633 return ByteStack_pop_block(state, stack, (void*)fuzzy_counts,
2634 RE_FUZZY_COUNT * sizeof(size_t));
2635 }
2636
2637 /* Pushes group spans off a stack of bytes. */
2638 Py_LOCAL_INLINE(BOOL) pop_groups(RE_State* state, ByteStack* stack) {
2639 Py_ssize_t group_count;
2640 Py_ssize_t g;
2641
2642 /* stack: current#0 current#1 ... */
2643
2644 group_count = (Py_ssize_t)state->pattern->true_group_count;
2645 if (group_count == 0)
2646 return TRUE;
2647
2648 for (g = group_count - 1; g >= 0; g--) {
2649 RE_GroupData* group;
2650
2651 group = &state->groups[g];
2652
2653 if (!pop_ssize(state, stack, &group->current))
2654 return FALSE;
2655 }
2656
2657 return TRUE;
2658 }
2659
2660 /* Pops group captures and spans off a stack of bytes. */
2661 Py_LOCAL_INLINE(BOOL) pop_captures(RE_State* state, ByteStack* stack) {
2662 Py_ssize_t group_count;
2663 Py_ssize_t g;
2664
2665 /* stack: group[0] group[1] ...
2666 *
2667 * group: capture[0] capture[1] ... count current
2668 */
2669
2670 group_count = (Py_ssize_t)state->pattern->true_group_count;
2671 if (group_count == 0)
2672 return TRUE;
2673
2674 for (g = group_count - 1; g >= 0; g--) {
2675 RE_GroupData* group;
2676
2677 group = &state->groups[g];
2678
2679 if (!pop_ssize(state, stack, &group->current))
2680 return FALSE;
2681 if (!pop_size(state, stack, &group->count))
2682 return FALSE;
2683 }
2684
2685 return TRUE;
2686 }
2687
2688 /* Pops the repeat guard data off the stack. */
2689 Py_LOCAL_INLINE(BOOL) pop_guard_data(RE_State* state, ByteStack* stack,
2690 RE_GuardList* guard_list) {
2691 if (!pop_size(state, stack, &guard_list->count))
2692 return FALSE;
2693 if (!ByteStack_pop_block(state, stack, (void*)guard_list->spans,
2694 guard_list->count * sizeof(RE_GuardSpan)))
2695 return FALSE;
2696
2697 guard_list->last_text_pos = -1;
2698
2699 return TRUE;
2700 }
2701
2702 /* Pops the repeat data off the stack. */
2703 Py_LOCAL_INLINE(BOOL) pop_repeat_data(RE_State* state, ByteStack* stack,
2704 RE_RepeatData* repeat_data) {
2705 if (!pop_size(state, stack, &repeat_data->capture_change))
2706 return FALSE;
2707 if (!pop_ssize(state, stack, &repeat_data->start))
2708 return FALSE;
2709 if (!pop_size(state, stack, &repeat_data->count))
2710 return FALSE;
2711 if (!pop_guard_data(state, stack, &repeat_data->tail_guard_list))
2712 return FALSE;
2713 if (!pop_guard_data(state, stack, &repeat_data->body_guard_list))
2714 return FALSE;
2715
2716 return TRUE;
2717 }
2718
2719 /* Pops the repeats off the stack. */
2720 Py_LOCAL_INLINE(BOOL) pop_repeats(RE_State* state, ByteStack* stack) {
2721 PatternObject* pattern;
2722 Py_ssize_t repeat_count;
2723 Py_ssize_t r;
2724
2725 pattern = state->pattern;
2726
2727 repeat_count = (Py_ssize_t)pattern->repeat_count;
2728 if (repeat_count == 0)
2729 return TRUE;
2730
2731 for (r = repeat_count - 1; r >= 0; r--) {
2732 if (!pop_repeat_data(state, stack, &state->repeats[r]))
2733 return FALSE;
2734 }
2735
2736 return TRUE;
2737 }
2738
2739 /* Pops the bstack count off the pstack. */
2740 Py_LOCAL_INLINE(BOOL) pop_bstack(RE_State* state) {
2741 if (!pop_size(state, &state->pstack, &state->bstack.count))
2742 return FALSE;
2743
2744 return TRUE;
2745 }
2746
2747 /* Pops the sstack count off the bstack. */
2748 Py_LOCAL_INLINE(BOOL) pop_sstack(RE_State* state) {
2749 if (!pop_size(state, &state->bstack, &state->sstack.count))
2750 return FALSE;
2751
2752 return TRUE;
2753 }
2754
2755 /* Drops a uint8 off a stack of bytes. */
2756 Py_LOCAL_INLINE(BOOL) drop_uint8(RE_State* state, ByteStack* stack) {
2757 return ByteStack_drop(state, stack);
2758 }
2759
2760 /* Drops a Py_ssize_t off a stack of bytes. */
2761 Py_LOCAL_INLINE(BOOL) drop_ssize(RE_State* state, ByteStack* stack) {
2762 return ByteStack_drop_block(state, stack, sizeof(Py_ssize_t));
2763 }
2764
2765 /* Drops a size_t off a stack of bytes. */
2766 Py_LOCAL_INLINE(BOOL) drop_size(RE_State* state, ByteStack* stack) {
2767 return ByteStack_drop_block(state, stack, sizeof(size_t));
2768 }
2769
2770 /* Drops a pointer off a stack of bytes. */
2771 Py_LOCAL_INLINE(BOOL) drop_pointer(RE_State* state, ByteStack* stack) {
2772 return ByteStack_drop_block(state, stack, sizeof(void*));
2773 }
2774
2775 /* Drops the bstack count off the pstack. */
2776 Py_LOCAL_INLINE(BOOL) drop_bstack(RE_State* state) {
2777 return drop_size(state, &state->pstack);
2778 }
2779
2780 /* Gets the top size_t off a stack of bytes. */
2781 Py_LOCAL_INLINE(BOOL) top_size(RE_State* state, ByteStack* stack, size_t* item)
2782 {
2783 return ByteStack_top_block(state, stack, (void*)item, sizeof(*item));
2784 }
2785
2786 /* Returns the top bstack count off the pstack. */
2787 Py_LOCAL_INLINE(BOOL) top_bstack(RE_State* state) {
2788 return top_size(state, &state->pstack, &state->bstack.count);
2789 }
2790
2791 /* Checks whether a character is in a range. */
2792 Py_LOCAL_INLINE(BOOL) in_range(Py_UCS4 lower, Py_UCS4 upper, Py_UCS4 ch) {
2793 return lower <= ch && ch <= upper;
2794 }
2795
2796 /* Checks whether a character is in a range, ignoring case. */
2797 Py_LOCAL_INLINE(BOOL) in_range_ign(RE_EncodingTable* encoding, RE_LocaleInfo*
2798 locale_info, Py_UCS4 lower, Py_UCS4 upper, Py_UCS4 ch) {
2799 int count;
2800 Py_UCS4 cases[RE_MAX_CASES];
2801 int i;
2802
2803 count = encoding->all_cases(locale_info, ch, cases);
2804
2805 for (i = 0; i < count; i++) {
2806 if (in_range(lower, upper, cases[i]))
2807 return TRUE;
2808 }
2809
2810 return FALSE;
2811 }
2812
2813 /* Checks whether 2 characters are the same. */
2814 Py_LOCAL_INLINE(BOOL) same_char(Py_UCS4 ch1, Py_UCS4 ch2) {
2815 return ch1 == ch2;
2816 }
2817
2818 /* Wrapper for calling 'same_char' via a pointer. */
2819 static BOOL same_char_wrapper(RE_EncodingTable* encoding, RE_LocaleInfo*
2820 locale_info, Py_UCS4 ch1, Py_UCS4 ch2) {
2821 return same_char(ch1, ch2);
2822 }
2823
2824 /* Checks whether 2 characters are the same, ignoring case. */
2825 Py_LOCAL_INLINE(BOOL) same_char_ign(RE_EncodingTable* encoding, RE_LocaleInfo*
2826 locale_info, Py_UCS4 ch1, Py_UCS4 ch2) {
2827 int count;
2828 Py_UCS4 cases[RE_MAX_CASES];
2829 int i;
2830
2831 if (ch1 == ch2)
2832 return TRUE;
2833
2834 count = encoding->all_cases(locale_info, ch1, cases);
2835
2836 for (i = 1; i < count; i++) {
2837 if (cases[i] == ch2)
2838 return TRUE;
2839 }
2840
2841 return FALSE;
2842 }
2843
2844 /* Checks whether 2 characters are the same, ignoring case. The first character
2845 * is already case-folded or is a possible Turkic 'I'.
2846 */
2847 Py_LOCAL_INLINE(BOOL) same_char_ign_turkic(RE_EncodingTable* encoding,
2848 RE_LocaleInfo* locale_info, Py_UCS4 ch1, Py_UCS4 ch2) {
2849 int count;
2850 Py_UCS4 cases[RE_MAX_CASES];
2851 int i;
2852
2853 if (ch1 == ch2)
2854 return TRUE;
2855
2856 if (!encoding->possible_turkic(locale_info, ch1))
2857 return FALSE;
2858
2859 count = encoding->all_turkic_i(locale_info, ch1, cases);
2860
2861 for (i = 1; i < count; i++) {
2862 if (cases[i] == ch2)
2863 return TRUE;
2864 }
2865
2866 return FALSE;
2867 }
2868
2869 /* Wrapper for calling 'same_char' via a pointer. */
2870 static BOOL same_char_ign_wrapper(RE_EncodingTable* encoding, RE_LocaleInfo*
2871 locale_info, Py_UCS4 ch1, Py_UCS4 ch2) {
2872 return same_char_ign(encoding, locale_info, ch1, ch2);
2873 }
2874
2875 /* Checks whether a character is anything except a newline. */
2876 Py_LOCAL_INLINE(BOOL) matches_ANY(RE_EncodingTable* encoding, RE_Node* node,
2877 Py_UCS4 ch) {
2878 return ch != '\n';
2879 }
2880
2881 /* Checks whether a character is anything except a line separator. */
2882 Py_LOCAL_INLINE(BOOL) matches_ANY_U(RE_EncodingTable* encoding, RE_Node* node,
2883 Py_UCS4 ch) {
2884 return !encoding->is_line_sep(ch);
2885 }
2886
2887 /* Checks whether 2 characters are the same. */
2888 Py_LOCAL_INLINE(BOOL) matches_CHARACTER(RE_EncodingTable* encoding,
2889 RE_LocaleInfo* locale_info, RE_Node* node, Py_UCS4 ch) {
2890 return same_char(node->values[0], ch);
2891 }
2892
2893 /* Checks whether 2 characters are the same, ignoring case. */
2894 Py_LOCAL_INLINE(BOOL) matches_CHARACTER_IGN(RE_EncodingTable* encoding,
2895 RE_LocaleInfo* locale_info, RE_Node* node, Py_UCS4 ch) {
2896 return same_char_ign(encoding, locale_info, node->values[0], ch);
2897 }
2898
2899 /* Checks whether a character has a property. */
2900 Py_LOCAL_INLINE(BOOL) matches_PROPERTY(RE_EncodingTable* encoding,
2901 RE_LocaleInfo* locale_info, RE_Node* node, Py_UCS4 ch) {
2902 switch (ENCODING_KIND(node)) {
2903 case ASCII_ENCODING:
2904 return ascii_encoding.has_property(locale_info, node->values[0], ch);
2905 case UNICODE_ENCODING:
2906 return unicode_encoding.has_property(locale_info, node->values[0], ch);
2907 default:
2908 return encoding->has_property(locale_info, node->values[0], ch);
2909 }
2910 }
2911
2912 /* Checks whether a character has a property, ignoring case. */
2913 Py_LOCAL_INLINE(BOOL) matches_PROPERTY_IGN(RE_EncodingTable* encoding,
2914 RE_LocaleInfo* locale_info, RE_Node* node, Py_UCS4 ch) {
2915 RE_UINT32 property;
2916 RE_UINT32 prop;
2917
2918 property = node->values[0];
2919 prop = property >> 16;
2920
2921 switch (ENCODING_KIND(node)) {
2922 case ASCII_ENCODING:
2923 encoding = &ascii_encoding;
2924 break;
2925 case UNICODE_ENCODING:
2926 encoding = &unicode_encoding;
2927 break;
2928 }
2929
2930 /* We need to do special handling of case-sensitive properties according to
2931 * the 'encoding'.
2932 */
2933 if (encoding == &unicode_encoding) {
2934 /* We are working with Unicode. */
2935 if (property == RE_PROP_GC_LU || property == RE_PROP_GC_LL || property
2936 == RE_PROP_GC_LT) {
2937 RE_UINT32 value;
2938
2939 value = re_get_general_category(ch);
2940
2941 return value == RE_PROP_LU || value == RE_PROP_LL || value ==
2942 RE_PROP_LT;
2943 } else if (prop == RE_PROP_UPPERCASE || prop == RE_PROP_LOWERCASE)
2944 return (BOOL)re_get_cased(ch);
2945
2946 /* The property is case-insensitive. */
2947 return unicode_has_property(property, ch);
2948 } else if (encoding == &ascii_encoding) {
2949 /* We are working with ASCII. */
2950 if (property == RE_PROP_GC_LU || property == RE_PROP_GC_LL || property
2951 == RE_PROP_GC_LT) {
2952 RE_UINT32 value;
2953
2954 value = re_get_general_category(ch);
2955
2956 return value == RE_PROP_LU || value == RE_PROP_LL || value ==
2957 RE_PROP_LT;
2958 } else if (prop == RE_PROP_UPPERCASE || prop == RE_PROP_LOWERCASE)
2959 return (BOOL)re_get_cased(ch);
2960
2961 /* The property is case-insensitive. */
2962 return ascii_has_property(property, ch);
2963 } else {
2964 /* We are working with Locale. */
2965 if (property == RE_PROP_GC_LU || property == RE_PROP_GC_LL || property
2966 == RE_PROP_GC_LT)
2967 return locale_isupper(locale_info, ch) ||
2968 locale_islower(locale_info, ch);
2969 else if (prop == RE_PROP_UPPERCASE || prop == RE_PROP_LOWERCASE)
2970 return locale_isupper(locale_info, ch) ||
2971 locale_islower(locale_info, ch);
2972
2973 /* The property is case-insensitive. */
2974 return locale_has_property(locale_info, property, ch);
2975 }
2976 }
2977
2978 /* Checks whether a character is in a range. */
2979 Py_LOCAL_INLINE(BOOL) matches_RANGE(RE_EncodingTable* encoding, RE_LocaleInfo*
2980 locale_info, RE_Node* node, Py_UCS4 ch) {
2981 return in_range(node->values[0], node->values[1], ch);
2982 }
2983
2984 /* Checks whether a character is in a range, ignoring case. */
2985 Py_LOCAL_INLINE(BOOL) matches_RANGE_IGN(RE_EncodingTable* encoding,
2986 RE_LocaleInfo* locale_info, RE_Node* node, Py_UCS4 ch) {
2987 return in_range_ign(encoding, locale_info, node->values[0],
2988 node->values[1], ch);
2989 }
2990
2991 Py_LOCAL_INLINE(BOOL) in_set_diff(RE_EncodingTable* encoding, RE_LocaleInfo*
2992 locale_info, RE_Node* node, Py_UCS4 ch);
2993 Py_LOCAL_INLINE(BOOL) in_set_inter(RE_EncodingTable* encoding, RE_LocaleInfo*
2994 locale_info, RE_Node* node, Py_UCS4 ch);
2995 Py_LOCAL_INLINE(BOOL) in_set_sym_diff(RE_EncodingTable* encoding,
2996 RE_LocaleInfo* locale_info, RE_Node* node, Py_UCS4 ch);
2997 Py_LOCAL_INLINE(BOOL) in_set_union(RE_EncodingTable* encoding, RE_LocaleInfo*
2998 locale_info, RE_Node* node, Py_UCS4 ch);
2999
3000 /* Checks whether a character matches a set member. */
3001 Py_LOCAL_INLINE(BOOL) matches_member(RE_EncodingTable* encoding, RE_LocaleInfo*
3002 locale_info, RE_Node* member, Py_UCS4 ch) {
3003 switch (member->op) {
3004 case RE_OP_ANY_ALL:
3005 TRACE(("%s\n", re_op_text[member->op]))
3006 return TRUE;
3007 case RE_OP_CHARACTER:
3008 /* values are: char_code */
3009 TRACE(("%s %d %d\n", re_op_text[member->op], member->match,
3010 member->values[0]))
3011 return ch == member->values[0];
3012 case RE_OP_PROPERTY:
3013 /* values are: property */
3014 TRACE(("%s %d %d\n", re_op_text[member->op], member->match,
3015 member->values[0]))
3016
3017 switch (ENCODING_KIND(member)) {
3018 case ASCII_ENCODING:
3019 return ascii_encoding.has_property(locale_info, member->values[0], ch);
3020 case UNICODE_ENCODING:
3021 return unicode_encoding.has_property(locale_info, member->values[0], ch);
3022 default:
3023 return encoding->has_property(locale_info, member->values[0], ch);
3024 }
3025 case RE_OP_RANGE:
3026 /* values are: lower, upper */
3027 TRACE(("%s %d %d %d\n", re_op_text[member->op], member->match,
3028 member->values[0], member->values[1]))
3029 return in_range(member->values[0], member->values[1], ch);
3030 case RE_OP_SET_DIFF:
3031 TRACE(("%s\n", re_op_text[member->op]))
3032 return in_set_diff(encoding, locale_info, member, ch);
3033 case RE_OP_SET_INTER:
3034 TRACE(("%s\n", re_op_text[member->op]))
3035 return in_set_inter(encoding, locale_info, member, ch);
3036 case RE_OP_SET_SYM_DIFF:
3037 TRACE(("%s\n", re_op_text[member->op]))
3038 return in_set_sym_diff(encoding, locale_info, member, ch);
3039 case RE_OP_SET_UNION:
3040 TRACE(("%s\n", re_op_text[member->op]))
3041 return in_set_union(encoding, locale_info, member, ch);
3042 case RE_OP_STRING:
3043 {
3044 /* values are: char_code, char_code, ... */
3045 size_t i;
3046 TRACE(("%s %d %" PY_FORMAT_SIZE_T "d\n", re_op_text[member->op],
3047 member->match, member->value_count))
3048
3049 for (i = 0; i < member->value_count; i++) {
3050 if (ch == member->values[i])
3051 return TRUE;
3052 }
3053 return FALSE;
3054 }
3055 default:
3056 return FALSE;
3057 }
3058 }
3059
3060 /* Checks whether a character matches a set member, ignoring case. */
3061 Py_LOCAL_INLINE(BOOL) matches_member_ign(RE_EncodingTable* encoding,
3062 RE_LocaleInfo* locale_info, RE_Node* member, int case_count, Py_UCS4* cases)
3063 {
3064 int i;
3065
3066 for (i = 0; i < case_count; i++) {
3067 switch (member->op) {
3068 case RE_OP_CHARACTER:
3069 /* values are: char_code */
3070 TRACE(("%s %d %d\n", re_op_text[member->op], member->match,
3071 member->values[0]))
3072 if (cases[i] == member->values[0])
3073 return TRUE;
3074 break;
3075 case RE_OP_PROPERTY:
3076 /* values are: property */
3077 TRACE(("%s %d %d\n", re_op_text[member->op], member->match,
3078 member->values[0]))
3079 if (encoding->has_property(locale_info, member->values[0],
3080 cases[i]))
3081 return TRUE;
3082 break;
3083 case RE_OP_RANGE:
3084 /* values are: lower, upper */
3085 TRACE(("%s %d %d %d\n", re_op_text[member->op], member->match,
3086 member->values[0], member->values[1]))
3087 if (in_range(member->values[0], member->values[1], cases[i]))
3088 return TRUE;
3089 break;
3090 case RE_OP_SET_DIFF:
3091 TRACE(("%s\n", re_op_text[member->op]))
3092 if (in_set_diff(encoding, locale_info, member, cases[i]))
3093 return TRUE;
3094 break;
3095 case RE_OP_SET_INTER:
3096 TRACE(("%s\n", re_op_text[member->op]))
3097 if (in_set_inter(encoding, locale_info, member, cases[i]))
3098 return TRUE;
3099 break;
3100 case RE_OP_SET_SYM_DIFF:
3101 TRACE(("%s\n", re_op_text[member->op]))
3102 if (in_set_sym_diff(encoding, locale_info, member, cases[i]))
3103 return TRUE;
3104 break;
3105 case RE_OP_SET_UNION:
3106 TRACE(("%s\n", re_op_text[member->op]))
3107 if (in_set_union(encoding, locale_info, member, cases[i]))
3108 return TRUE;
3109 break;
3110 case RE_OP_STRING:
3111 {
3112 size_t j;
3113 TRACE(("%s %d %zd\n", re_op_text[member->op], member->match,
3114 member->value_count))
3115
3116 for (j = 0; j < member->value_count; j++) {
3117 if (cases[i] == member->values[j])
3118 return TRUE;
3119 }
3120 break;
3121 }
3122 default:
3123 return TRUE;
3124 }
3125 }
3126
3127 return FALSE;
3128 }
3129
3130 /* Checks whether a character is in a set difference. */
3131 Py_LOCAL_INLINE(BOOL) in_set_diff(RE_EncodingTable* encoding, RE_LocaleInfo*
3132 locale_info, RE_Node* node, Py_UCS4 ch) {
3133 RE_Node* member;
3134
3135 member = node->nonstring.next_2.node;
3136
3137 if (matches_member(encoding, locale_info, member, ch) != member->match)
3138 return FALSE;
3139
3140 member = member->next_1.node;
3141
3142 while (member) {
3143 if (matches_member(encoding, locale_info, member, ch) == member->match)
3144 return FALSE;
3145
3146 member = member->next_1.node;
3147 }
3148
3149 return TRUE;
3150 }
3151
3152 /* Checks whether a character is in a set difference, ignoring case. */
3153 Py_LOCAL_INLINE(BOOL) in_set_diff_ign(RE_EncodingTable* encoding,
3154 RE_LocaleInfo* locale_info, RE_Node* node, int case_count, Py_UCS4* cases) {
3155 RE_Node* member;
3156
3157 member = node->nonstring.next_2.node;
3158
3159 if (matches_member_ign(encoding, locale_info, member, case_count, cases) !=
3160 member->match)
3161 return FALSE;
3162
3163 member = member->next_1.node;
3164
3165 while (member) {
3166 if (matches_member_ign(encoding, locale_info, member, case_count,
3167 cases) == member->match)
3168 return FALSE;
3169
3170 member = member->next_1.node;
3171 }
3172
3173 return TRUE;
3174 }
3175
3176 /* Checks whether a character is in a set intersection. */
3177 Py_LOCAL_INLINE(BOOL) in_set_inter(RE_EncodingTable* encoding, RE_LocaleInfo*
3178 locale_info, RE_Node* node, Py_UCS4 ch) {
3179 RE_Node* member;
3180
3181 member = node->nonstring.next_2.node;
3182
3183 while (member) {
3184 if (matches_member(encoding, locale_info, member, ch) != member->match)
3185 return FALSE;
3186
3187 member = member->next_1.node;
3188 }
3189
3190 return TRUE;
3191 }
3192
3193 /* Checks whether a character is in a set intersection, ignoring case. */
3194 Py_LOCAL_INLINE(BOOL) in_set_inter_ign(RE_EncodingTable* encoding,
3195 RE_LocaleInfo* locale_info, RE_Node* node, int case_count, Py_UCS4* cases) {
3196 RE_Node* member;
3197
3198 member = node->nonstring.next_2.node;
3199
3200 while (member) {
3201 if (matches_member_ign(encoding, locale_info, member, case_count,
3202 cases) != member->match)
3203 return FALSE;
3204
3205 member = member->next_1.node;
3206 }
3207
3208 return TRUE;
3209 }
3210
3211 /* Checks whether a character is in a set symmetric difference. */
3212 Py_LOCAL_INLINE(BOOL) in_set_sym_diff(RE_EncodingTable* encoding,
3213 RE_LocaleInfo* locale_info, RE_Node* node, Py_UCS4 ch) {
3214 RE_Node* member;
3215 BOOL result;
3216
3217 member = node->nonstring.next_2.node;
3218
3219 result = FALSE;
3220
3221 while (member) {
3222 if (matches_member(encoding, locale_info, member, ch) == member->match)
3223 result = !result;
3224
3225 member = member->next_1.node;
3226 }
3227
3228 return result;
3229 }
3230
3231 /* Checks whether a character is in a set symmetric difference, ignoring case.
3232 */
3233 Py_LOCAL_INLINE(BOOL) in_set_sym_diff_ign(RE_EncodingTable* encoding,
3234 RE_LocaleInfo* locale_info, RE_Node* node, int case_count, Py_UCS4* cases) {
3235 RE_Node* member;
3236 BOOL result;
3237
3238 member = node->nonstring.next_2.node;
3239
3240 result = FALSE;
3241
3242 while (member) {
3243 if (matches_member_ign(encoding, locale_info, member, case_count,
3244 cases) == member->match)
3245 result = !result;
3246
3247 member = member->next_1.node;
3248 }
3249
3250 return result;
3251 }
3252
3253 /* Checks whether a character is in a set union. */
3254 Py_LOCAL_INLINE(BOOL) in_set_union(RE_EncodingTable* encoding, RE_LocaleInfo*
3255 locale_info, RE_Node* node, Py_UCS4 ch) {
3256 RE_Node* member;
3257
3258 member = node->nonstring.next_2.node;
3259
3260 while (member) {
3261 if (matches_member(encoding, locale_info, member, ch) == member->match)
3262 return TRUE;
3263
3264 member = member->next_1.node;
3265 }
3266
3267 return FALSE;
3268 }
3269
3270 /* Checks whether a character is in a set union, ignoring case. */
3271 Py_LOCAL_INLINE(BOOL) in_set_union_ign(RE_EncodingTable* encoding,
3272 RE_LocaleInfo* locale_info, RE_Node* node, int case_count, Py_UCS4* cases) {
3273 RE_Node* member;
3274
3275 member = node->nonstring.next_2.node;
3276
3277 while (member) {
3278 if (matches_member_ign(encoding, locale_info, member, case_count,
3279 cases) == member->match)
3280 return TRUE;
3281
3282 member = member->next_1.node;
3283 }
3284
3285 return FALSE;
3286 }
3287
3288 /* Checks whether a character is in a set. */
3289 Py_LOCAL_INLINE(BOOL) matches_SET(RE_EncodingTable* encoding,
3290 RE_LocaleInfo* locale_info, RE_Node* node, Py_UCS4 ch) {
3291 switch (node->op) {
3292 case RE_OP_SET_DIFF:
3293 case RE_OP_SET_DIFF_REV:
3294 return in_set_diff(encoding, locale_info, node, ch);
3295 case RE_OP_SET_INTER:
3296 case RE_OP_SET_INTER_REV:
3297 return in_set_inter(encoding, locale_info, node, ch);
3298 case RE_OP_SET_SYM_DIFF:
3299 case RE_OP_SET_SYM_DIFF_REV:
3300 return in_set_sym_diff(encoding, locale_info, node, ch);
3301 case RE_OP_SET_UNION:
3302 case RE_OP_SET_UNION_REV:
3303 return in_set_union(encoding, locale_info, node, ch);
3304 }
3305
3306 return FALSE;
3307 }
3308
3309 /* Checks whether a character is in a set, ignoring case. */
3310 Py_LOCAL_INLINE(BOOL) matches_SET_IGN(RE_EncodingTable* encoding,
3311 RE_LocaleInfo* locale_info, RE_Node* node, Py_UCS4 ch) {
3312 Py_UCS4 cases[RE_MAX_CASES];
3313 int case_count;
3314
3315 case_count = encoding->all_cases(locale_info, ch, cases);
3316
3317 switch (node->op) {
3318 case RE_OP_SET_DIFF_IGN:
3319 case RE_OP_SET_DIFF_IGN_REV:
3320 return in_set_diff_ign(encoding, locale_info, node, case_count, cases);
3321 case RE_OP_SET_INTER_IGN:
3322 case RE_OP_SET_INTER_IGN_REV:
3323 return in_set_inter_ign(encoding, locale_info, node, case_count,
3324 cases);
3325 case RE_OP_SET_SYM_DIFF_IGN:
3326 case RE_OP_SET_SYM_DIFF_IGN_REV:
3327 return in_set_sym_diff_ign(encoding, locale_info, node, case_count,
3328 cases);
3329 case RE_OP_SET_UNION_IGN:
3330 case RE_OP_SET_UNION_IGN_REV:
3331 return in_set_union_ign(encoding, locale_info, node, case_count,
3332 cases);
3333 }
3334
3335 return FALSE;
3336 }
3337
3338 /* Resets a guard list. */
3339 Py_LOCAL_INLINE(void) reset_guard_list(RE_GuardList* guard_list) {
3340 guard_list->count = 0;
3341 guard_list->last_text_pos = -1;
3342 }
3343
3344 /* Clears the groups. */
3345 Py_LOCAL_INLINE(void) clear_groups(RE_State* state) {
3346 size_t i;
3347
3348 for (i = 0; i < state->pattern->true_group_count; i++) {
3349 RE_GroupData* group;
3350
3351 group = &state->groups[i];
3352 group->count = 0;
3353
3354 group->current = -1;
3355 }
3356 }
3357
3358 /* Resets the various guards. */
3359 Py_LOCAL_INLINE(void) reset_guards(RE_State* state) {
3360 size_t i;
3361
3362 /* Reset the guards for the repeats. */
3363 for (i = 0; i < state->pattern->repeat_count; i++) {
3364 reset_guard_list(&state->repeats[i].body_guard_list);
3365 reset_guard_list(&state->repeats[i].tail_guard_list);
3366 }
3367
3368 /* Reset the guards for the fuzzy sections. */
3369 for (i = 0; i < state->pattern->fuzzy_count; i++) {
3370 reset_guard_list(&state->fuzzy_guards[i].body_guard_list);
3371 reset_guard_list(&state->fuzzy_guards[i].tail_guard_list);
3372 }
3373
3374 /* Reset the guards for the group calls. */
3375 for (i = 0; i < state->pattern->call_ref_info_count; i++)
3376 reset_guard_list(&state->group_call_guard_list[i]);
3377 }
3378
3379 /* Initialises the state for a match. */
3380 Py_LOCAL_INLINE(void) init_match(RE_State* state) {
3381 /* Reset the stacks. */
3382 ByteStack_reset(state, &state->sstack);
3383 ByteStack_reset(state, &state->bstack);
3384 ByteStack_reset(state, &state->pstack);
3385
3386 state->search_anchor = state->text_pos;
3387 state->match_pos = state->text_pos;
3388
3389 /* Clear the groups. */
3390 clear_groups(state);
3391
3392 /* Reset the guards. */
3393 reset_guards(state);
3394
3395 /* Clear the counts and cost for matching. */
3396 if (state->is_fuzzy) {
3397 memset(state->fuzzy_counts, 0, sizeof(state->fuzzy_counts));
3398 state->fuzzy_node = NULL;
3399 state->fuzzy_changes.count = 0;
3400 }
3401
3402 state->total_errors = 0;
3403 state->found_match = FALSE;
3404 state->capture_change = 0;
3405 state->iterations = 0;
3406 }
3407
3408 /* Checks whether a node matches only 1 character. */
3409 Py_LOCAL_INLINE(BOOL) node_matches_one_character(RE_Node* node) {
3410 switch (node->op) {
3411 case RE_OP_ANY:
3412 case RE_OP_ANY_ALL:
3413 case RE_OP_ANY_ALL_REV:
3414 case RE_OP_ANY_REV:
3415 case RE_OP_ANY_U:
3416 case RE_OP_ANY_U_REV:
3417 case RE_OP_CHARACTER:
3418 case RE_OP_CHARACTER_IGN:
3419 case RE_OP_CHARACTER_IGN_REV:
3420 case RE_OP_CHARACTER_REV:
3421 case RE_OP_PROPERTY:
3422 case RE_OP_PROPERTY_IGN:
3423 case RE_OP_PROPERTY_IGN_REV:
3424 case RE_OP_PROPERTY_REV:
3425 case RE_OP_RANGE:
3426 case RE_OP_RANGE_IGN:
3427 case RE_OP_RANGE_IGN_REV:
3428 case RE_OP_RANGE_REV:
3429 case RE_OP_SET_DIFF:
3430 case RE_OP_SET_DIFF_IGN:
3431 case RE_OP_SET_DIFF_IGN_REV:
3432 case RE_OP_SET_DIFF_REV:
3433 case RE_OP_SET_INTER:
3434 case RE_OP_SET_INTER_IGN:
3435 case RE_OP_SET_INTER_IGN_REV:
3436 case RE_OP_SET_INTER_REV:
3437 case RE_OP_SET_SYM_DIFF:
3438 case RE_OP_SET_SYM_DIFF_IGN:
3439 case RE_OP_SET_SYM_DIFF_IGN_REV:
3440 case RE_OP_SET_SYM_DIFF_REV:
3441 case RE_OP_SET_UNION:
3442 case RE_OP_SET_UNION_IGN:
3443 case RE_OP_SET_UNION_IGN_REV:
3444 case RE_OP_SET_UNION_REV:
3445 return TRUE;
3446 default:
3447 return FALSE;
3448 }
3449 }
3450
3451 /* Locates the start node for testing ahead. */
3452 Py_LOCAL_INLINE(RE_Node*) locate_test_start(RE_Node* node) {
3453 for (;;) {
3454 switch (node->op) {
3455 case RE_OP_BOUNDARY:
3456 switch (node->next_1.node->op) {
3457 case RE_OP_STRING:
3458 case RE_OP_STRING_FLD:
3459 case RE_OP_STRING_FLD_REV:
3460 case RE_OP_STRING_IGN:
3461 case RE_OP_STRING_IGN_REV:
3462 case RE_OP_STRING_REV:
3463 return node->next_1.node;
3464 default:
3465 return node;
3466 }
3467 case RE_OP_CALL_REF:
3468 case RE_OP_END_GROUP:
3469 case RE_OP_START_GROUP:
3470 node = node->next_1.node;
3471 break;
3472 case RE_OP_GREEDY_REPEAT:
3473 case RE_OP_LAZY_REPEAT:
3474 if (node->values[1] == 0)
3475 return node;
3476 node = node->next_1.node;
3477 break;
3478 case RE_OP_GREEDY_REPEAT_ONE:
3479 case RE_OP_LAZY_REPEAT_ONE:
3480 if (node->values[1] == 0)
3481 return node;
3482 return node->nonstring.next_2.node;
3483 case RE_OP_LOOKAROUND:
3484 node = node->nonstring.next_2.node;
3485 break;
3486 default:
3487 if (node->step == 0 && node_matches_one_character(node)) {
3488 switch (node->next_1.node->op) {
3489 case RE_OP_END_OF_STRING:
3490 case RE_OP_START_OF_STRING:
3491 return node->next_1.node;
3492 }
3493 }
3494
3495 return node;
3496 }
3497 }
3498 }
3499
3500 /* Checks whether a character matches any of a set of case characters. */
3501 Py_LOCAL_INLINE(BOOL) any_case(Py_UCS4 ch, int case_count, Py_UCS4* cases) {
3502 int i;
3503
3504 for (i = 0; i < case_count; i++) {
3505 if (ch == cases[i])
3506 return TRUE;
3507 }
3508
3509 return FALSE;
3510 }
3511
3512 /* Matches many ANYs, up to a limit. */
3513 Py_LOCAL_INLINE(Py_ssize_t) match_many_ANY(RE_State* state, RE_Node* node,
3514 Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
3515 void* text;
3516
3517 text = state->text;
3518
3519 switch (state->charsize) {
3520 case 1:
3521 {
3522 Py_UCS1* text_ptr;
3523 Py_UCS1* limit_ptr;
3524
3525 text_ptr = (Py_UCS1*)text + text_pos;
3526 limit_ptr = (Py_UCS1*)text + limit;
3527
3528 while (text_ptr < limit_ptr && (text_ptr[0] != '\n') == match)
3529 ++text_ptr;
3530
3531 text_pos = text_ptr - (Py_UCS1*)text;
3532 break;
3533 }
3534 case 2:
3535 {
3536 Py_UCS2* text_ptr;
3537 Py_UCS2* limit_ptr;
3538
3539 text_ptr = (Py_UCS2*)text + text_pos;
3540 limit_ptr = (Py_UCS2*)text + limit;
3541
3542 while (text_ptr < limit_ptr && (text_ptr[0] != '\n') == match)
3543 ++text_ptr;
3544
3545 text_pos = text_ptr - (Py_UCS2*)text;
3546 break;
3547 }
3548 case 4:
3549 {
3550 Py_UCS4* text_ptr;
3551 Py_UCS4* limit_ptr;
3552
3553 text_ptr = (Py_UCS4*)text + text_pos;
3554 limit_ptr = (Py_UCS4*)text + limit;
3555
3556 while (text_ptr < limit_ptr && (text_ptr[0] != '\n') == match)
3557 ++text_ptr;
3558
3559 text_pos = text_ptr - (Py_UCS4*)text;
3560 break;
3561 }
3562 }
3563
3564 return text_pos;
3565 }
3566
3567 /* Matches many ANYs, up to a limit, backwards. */
3568 Py_LOCAL_INLINE(Py_ssize_t) match_many_ANY_REV(RE_State* state, RE_Node* node,
3569 Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
3570 void* text;
3571
3572 text = state->text;
3573
3574 switch (state->charsize) {
3575 case 1:
3576 {
3577 Py_UCS1* text_ptr;
3578 Py_UCS1* limit_ptr;
3579
3580 text_ptr = (Py_UCS1*)text + text_pos;
3581 limit_ptr = (Py_UCS1*)text + limit;
3582
3583 while (text_ptr > limit_ptr && (text_ptr[-1] != '\n') == match)
3584 --text_ptr;
3585
3586 text_pos = text_ptr - (Py_UCS1*)text;
3587 break;
3588 }
3589 case 2:
3590 {
3591 Py_UCS2* text_ptr;
3592 Py_UCS2* limit_ptr;
3593
3594 text_ptr = (Py_UCS2*)text + text_pos;
3595 limit_ptr = (Py_UCS2*)text + limit;
3596
3597 while (text_ptr > limit_ptr && (text_ptr[-1] != '\n') == match)
3598 --text_ptr;
3599
3600 text_pos = text_ptr - (Py_UCS2*)text;
3601 break;
3602 }
3603 case 4:
3604 {
3605 Py_UCS4* text_ptr;
3606 Py_UCS4* limit_ptr;
3607
3608 text_ptr = (Py_UCS4*)text + text_pos;
3609 limit_ptr = (Py_UCS4*)text + limit;
3610
3611 while (text_ptr > limit_ptr && (text_ptr[-1] != '\n') == match)
3612 --text_ptr;
3613
3614 text_pos = text_ptr - (Py_UCS4*)text;
3615 break;
3616 }
3617 }
3618
3619 return text_pos;
3620 }
3621
3622 /* Matches many ANY_Us, up to a limit. */
3623 Py_LOCAL_INLINE(Py_ssize_t) match_many_ANY_U(RE_State* state, RE_Node* node,
3624 Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
3625 void* text;
3626 RE_EncodingTable* encoding;
3627
3628 text = state->text;
3629 encoding = state->encoding;
3630
3631 switch (state->charsize) {
3632 case 1:
3633 {
3634 Py_UCS1* text_ptr;
3635 Py_UCS1* limit_ptr;
3636
3637 text_ptr = (Py_UCS1*)text + text_pos;
3638 limit_ptr = (Py_UCS1*)text + limit;
3639
3640 if (encoding == &unicode_encoding) {
3641 while (text_ptr < limit_ptr && unicode_is_line_sep(text_ptr[0]) !=
3642 match)
3643 ++text_ptr;
3644 } else {
3645 while (text_ptr < limit_ptr && ascii_is_line_sep(text_ptr[0]) !=
3646 match)
3647 ++text_ptr;
3648 }
3649
3650 text_pos = text_ptr - (Py_UCS1*)text;
3651 break;
3652 }
3653 case 2:
3654 {
3655 Py_UCS2* text_ptr;
3656 Py_UCS2* limit_ptr;
3657
3658 text_ptr = (Py_UCS2*)text + text_pos;
3659 limit_ptr = (Py_UCS2*)text + limit;
3660
3661 if (encoding == &unicode_encoding) {
3662 while (text_ptr < limit_ptr && unicode_is_line_sep(text_ptr[0]) !=
3663 match)
3664 ++text_ptr;
3665 } else {
3666 while (text_ptr < limit_ptr && ascii_is_line_sep(text_ptr[0]) !=
3667 match)
3668 ++text_ptr;
3669 }
3670
3671 text_pos = text_ptr - (Py_UCS2*)text;
3672 break;
3673 }
3674 case 4:
3675 {
3676 Py_UCS4* text_ptr;
3677 Py_UCS4* limit_ptr;
3678
3679 text_ptr = (Py_UCS4*)text + text_pos;
3680 limit_ptr = (Py_UCS4*)text + limit;
3681
3682 if (encoding == &unicode_encoding) {
3683 while (text_ptr < limit_ptr && unicode_is_line_sep(text_ptr[0]) !=
3684 match)
3685 ++text_ptr;
3686 } else {
3687 while (text_ptr < limit_ptr && ascii_is_line_sep(text_ptr[0]) !=
3688 match)
3689 ++text_ptr;
3690 }
3691
3692 text_pos = text_ptr - (Py_UCS4*)text;
3693 break;
3694 }
3695 }
3696
3697 return text_pos;
3698 }
3699
3700 /* Matches many ANY_Us, up to a limit, backwards. */
3701 Py_LOCAL_INLINE(Py_ssize_t) match_many_ANY_U_REV(RE_State* state, RE_Node*
3702 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
3703 void* text;
3704 RE_EncodingTable* encoding;
3705
3706 text = state->text;
3707 encoding = state->encoding;
3708
3709 switch (state->charsize) {
3710 case 1:
3711 {
3712 Py_UCS1* text_ptr;
3713 Py_UCS1* limit_ptr;
3714
3715 text_ptr = (Py_UCS1*)text + text_pos;
3716 limit_ptr = (Py_UCS1*)text + limit;
3717
3718 if (encoding == &unicode_encoding) {
3719 while (text_ptr > limit_ptr && unicode_is_line_sep(text_ptr[-1]) !=
3720 match)
3721 --text_ptr;
3722 } else {
3723 while (text_ptr > limit_ptr && ascii_is_line_sep(text_ptr[-1]) !=
3724 match)
3725 --text_ptr;
3726 }
3727
3728 text_pos = text_ptr - (Py_UCS1*)text;
3729 break;
3730 }
3731 case 2:
3732 {
3733 Py_UCS2* text_ptr;
3734 Py_UCS2* limit_ptr;
3735
3736 text_ptr = (Py_UCS2*)text + text_pos;
3737 limit_ptr = (Py_UCS2*)text + limit;
3738
3739 if (encoding == &unicode_encoding) {
3740 while (text_ptr > limit_ptr && unicode_is_line_sep(text_ptr[-1]) !=
3741 match)
3742 --text_ptr;
3743 } else {
3744 while (text_ptr > limit_ptr && ascii_is_line_sep(text_ptr[-1]) !=
3745 match)
3746 --text_ptr;
3747 }
3748
3749 text_pos = text_ptr - (Py_UCS2*)text;
3750 break;
3751 }
3752 case 4:
3753 {
3754 Py_UCS4* text_ptr;
3755 Py_UCS4* limit_ptr;
3756
3757 text_ptr = (Py_UCS4*)text + text_pos;
3758 limit_ptr = (Py_UCS4*)text + limit;
3759
3760 if (encoding == &unicode_encoding) {
3761 while (text_ptr > limit_ptr && unicode_is_line_sep(text_ptr[-1]) !=
3762 match)
3763 --text_ptr;
3764 } else {
3765 while (text_ptr > limit_ptr && ascii_is_line_sep(text_ptr[-1]) !=
3766 match)
3767 --text_ptr;
3768 }
3769
3770 text_pos = text_ptr - (Py_UCS4*)text;
3771 break;
3772 }
3773 }
3774
3775 return text_pos;
3776 }
3777
3778 /* Matches many CHARACTERs, up to a limit. */
3779 Py_LOCAL_INLINE(Py_ssize_t) match_many_CHARACTER(RE_State* state, RE_Node*
3780 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
3781 void* text;
3782 Py_UCS4 ch;
3783
3784 text = state->text;
3785 match = node->match == match;
3786 ch = node->values[0];
3787
3788 switch (state->charsize) {
3789 case 1:
3790 {
3791 Py_UCS1* text_ptr;
3792 Py_UCS1* limit_ptr;
3793
3794 text_ptr = (Py_UCS1*)text + text_pos;
3795 limit_ptr = (Py_UCS1*)text + limit;
3796
3797 while (text_ptr < limit_ptr && (text_ptr[0] == ch) == match)
3798 ++text_ptr;
3799
3800 text_pos = text_ptr - (Py_UCS1*)text;
3801 break;
3802 }
3803 case 2:
3804 {
3805 Py_UCS2* text_ptr;
3806 Py_UCS2* limit_ptr;
3807
3808 text_ptr = (Py_UCS2*)text + text_pos;
3809 limit_ptr = (Py_UCS2*)text + limit;
3810
3811 while (text_ptr < limit_ptr && (text_ptr[0] == ch) == match)
3812 ++text_ptr;
3813
3814 text_pos = text_ptr - (Py_UCS2*)text;
3815 break;
3816 }
3817 case 4:
3818 {
3819 Py_UCS4* text_ptr;
3820 Py_UCS4* limit_ptr;
3821
3822 text_ptr = (Py_UCS4*)text + text_pos;
3823 limit_ptr = (Py_UCS4*)text + limit;
3824
3825 while (text_ptr < limit_ptr && (text_ptr[0] == ch) == match)
3826 ++text_ptr;
3827
3828 text_pos = text_ptr - (Py_UCS4*)text;
3829 break;
3830 }
3831 }
3832
3833 return text_pos;
3834 }
3835
3836 /* Matches many CHARACTERs, up to a limit, ignoring case. */
3837 Py_LOCAL_INLINE(Py_ssize_t) match_many_CHARACTER_IGN(RE_State* state, RE_Node*
3838 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
3839 void* text;
3840 Py_UCS4 cases[RE_MAX_CASES];
3841 int case_count;
3842
3843 text = state->text;
3844 match = node->match == match;
3845 case_count = state->encoding->all_cases(state->locale_info,
3846 node->values[0], cases);
3847
3848 switch (state->charsize) {
3849 case 1:
3850 {
3851 Py_UCS1* text_ptr;
3852 Py_UCS1* limit_ptr;
3853
3854 text_ptr = (Py_UCS1*)text + text_pos;
3855 limit_ptr = (Py_UCS1*)text + limit;
3856
3857 while (text_ptr < limit_ptr && any_case(text_ptr[0], case_count, cases)
3858 == match)
3859 ++text_ptr;
3860
3861 text_pos = text_ptr - (Py_UCS1*)text;
3862 break;
3863 }
3864 case 2:
3865 {
3866 Py_UCS2* text_ptr;
3867 Py_UCS2* limit_ptr;
3868
3869 text_ptr = (Py_UCS2*)text + text_pos;
3870 limit_ptr = (Py_UCS2*)text + limit;
3871
3872 while (text_ptr < limit_ptr && any_case(text_ptr[0], case_count, cases)
3873 == match)
3874 ++text_ptr;
3875
3876 text_pos = text_ptr - (Py_UCS2*)text;
3877 break;
3878 }
3879 case 4:
3880 {
3881 Py_UCS4* text_ptr;
3882 Py_UCS4* limit_ptr;
3883
3884 text_ptr = (Py_UCS4*)text + text_pos;
3885 limit_ptr = (Py_UCS4*)text + limit;
3886
3887 while (text_ptr < limit_ptr && any_case(text_ptr[0], case_count, cases)
3888 == match)
3889 ++text_ptr;
3890
3891 text_pos = text_ptr - (Py_UCS4*)text;
3892 break;
3893 }
3894 }
3895
3896 return text_pos;
3897 }
3898
3899 /* Matches many CHARACTERs, up to a limit, backwards, ignoring case. */
3900 Py_LOCAL_INLINE(Py_ssize_t) match_many_CHARACTER_IGN_REV(RE_State* state,
3901 RE_Node* node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
3902 void* text;
3903 Py_UCS4 cases[RE_MAX_CASES];
3904 int case_count;
3905
3906 text = state->text;
3907 match = node->match == match;
3908 case_count = state->encoding->all_cases(state->locale_info,
3909 node->values[0], cases);
3910
3911 switch (state->charsize) {
3912 case 1:
3913 {
3914 Py_UCS1* text_ptr;
3915 Py_UCS1* limit_ptr;
3916
3917 text_ptr = (Py_UCS1*)text + text_pos;
3918 limit_ptr = (Py_UCS1*)text + limit;
3919
3920 while (text_ptr > limit_ptr && any_case(text_ptr[-1], case_count,
3921 cases) == match)
3922 --text_ptr;
3923
3924 text_pos = text_ptr - (Py_UCS1*)text;
3925 break;
3926 }
3927 case 2:
3928 {
3929 Py_UCS2* text_ptr;
3930 Py_UCS2* limit_ptr;
3931
3932 text_ptr = (Py_UCS2*)text + text_pos;
3933 limit_ptr = (Py_UCS2*)text + limit;
3934
3935 while (text_ptr > limit_ptr && any_case(text_ptr[-1], case_count,
3936 cases) == match)
3937 --text_ptr;
3938
3939 text_pos = text_ptr - (Py_UCS2*)text;
3940 break;
3941 }
3942 case 4:
3943 {
3944 Py_UCS4* text_ptr;
3945 Py_UCS4* limit_ptr;
3946
3947 text_ptr = (Py_UCS4*)text + text_pos;
3948 limit_ptr = (Py_UCS4*)text + limit;
3949
3950 while (text_ptr > limit_ptr && any_case(text_ptr[-1], case_count,
3951 cases) == match)
3952 --text_ptr;
3953
3954 text_pos = text_ptr - (Py_UCS4*)text;
3955 break;
3956 }
3957 }
3958
3959 return text_pos;
3960 }
3961
3962 /* Matches many CHARACTERs, up to a limit, backwards. */
3963 Py_LOCAL_INLINE(Py_ssize_t) match_many_CHARACTER_REV(RE_State* state, RE_Node*
3964 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
3965 void* text;
3966 Py_UCS4 ch;
3967
3968 text = state->text;
3969 match = node->match == match;
3970 ch = node->values[0];
3971
3972 switch (state->charsize) {
3973 case 1:
3974 {
3975 Py_UCS1* text_ptr;
3976 Py_UCS1* limit_ptr;
3977
3978 text_ptr = (Py_UCS1*)text + text_pos;
3979 limit_ptr = (Py_UCS1*)text + limit;
3980
3981 while (text_ptr > limit_ptr && (text_ptr[-1] == ch) == match)
3982 --text_ptr;
3983
3984 text_pos = text_ptr - (Py_UCS1*)text;
3985 break;
3986 }
3987 case 2:
3988 {
3989 Py_UCS2* text_ptr;
3990 Py_UCS2* limit_ptr;
3991
3992 text_ptr = (Py_UCS2*)text + text_pos;
3993 limit_ptr = (Py_UCS2*)text + limit;
3994
3995 while (text_ptr > limit_ptr && (text_ptr[-1] == ch) == match)
3996 --text_ptr;
3997
3998 text_pos = text_ptr - (Py_UCS2*)text;
3999 break;
4000 }
4001 case 4:
4002 {
4003 Py_UCS4* text_ptr;
4004 Py_UCS4* limit_ptr;
4005
4006 text_ptr = (Py_UCS4*)text + text_pos;
4007 limit_ptr = (Py_UCS4*)text + limit;
4008
4009 while (text_ptr > limit_ptr && (text_ptr[-1] == ch) == match)
4010 --text_ptr;
4011
4012 text_pos = text_ptr - (Py_UCS4*)text;
4013 break;
4014 }
4015 }
4016
4017 return text_pos;
4018 }
4019
4020 /* Matches many PROPERTYs, up to a limit. */
4021 Py_LOCAL_INLINE(Py_ssize_t) match_many_PROPERTY(RE_State* state, RE_Node* node,
4022 Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
4023 void* text;
4024 RE_EncodingTable* encoding;
4025 RE_LocaleInfo* locale_info;
4026 RE_CODE property;
4027
4028 text = state->text;
4029 match = node->match == match;
4030
4031 switch (ENCODING_KIND(node)) {
4032 case ASCII_ENCODING:
4033 encoding = &ascii_encoding;
4034 break;
4035 case UNICODE_ENCODING:
4036 encoding = &unicode_encoding;
4037 break;
4038 default:
4039 encoding = state->encoding;
4040 break;
4041 }
4042
4043 locale_info = state->locale_info;
4044 property = node->values[0];
4045
4046 switch (state->charsize) {
4047 case 1:
4048 {
4049 Py_UCS1* text_ptr;
4050 Py_UCS1* limit_ptr;
4051
4052 text_ptr = (Py_UCS1*)text + text_pos;
4053 limit_ptr = (Py_UCS1*)text + limit;
4054
4055 if (encoding == &unicode_encoding) {
4056 while (text_ptr < limit_ptr && unicode_has_property(property,
4057 text_ptr[0]) == match)
4058 ++text_ptr;
4059 } else if (encoding == &ascii_encoding) {
4060 while (text_ptr < limit_ptr && ascii_has_property(property,
4061 text_ptr[0]) == match)
4062 ++text_ptr;
4063 } else {
4064 while (text_ptr < limit_ptr && locale_has_property(locale_info,
4065 property,
4066 text_ptr[0]) == match)
4067 ++text_ptr;
4068 }
4069
4070 text_pos = text_ptr - (Py_UCS1*)text;
4071 break;
4072 }
4073 case 2:
4074 {
4075 Py_UCS2* text_ptr;
4076 Py_UCS2* limit_ptr;
4077
4078 text_ptr = (Py_UCS2*)text + text_pos;
4079 limit_ptr = (Py_UCS2*)text + limit;
4080
4081 if (encoding == &unicode_encoding) {
4082 while (text_ptr < limit_ptr && unicode_has_property(property,
4083 text_ptr[0]) == match)
4084 ++text_ptr;
4085 } else if (encoding == &ascii_encoding) {
4086 while (text_ptr < limit_ptr && ascii_has_property(property,
4087 text_ptr[0]) == match)
4088 ++text_ptr;
4089 } else {
4090 while (text_ptr < limit_ptr && locale_has_property(locale_info,
4091 property,
4092 text_ptr[0]) == match)
4093 ++text_ptr;
4094 }
4095
4096 text_pos = text_ptr - (Py_UCS2*)text;
4097 break;
4098 }
4099 case 4:
4100 {
4101 Py_UCS4* text_ptr;
4102 Py_UCS4* limit_ptr;
4103
4104 text_ptr = (Py_UCS4*)text + text_pos;
4105 limit_ptr = (Py_UCS4*)text + limit;
4106
4107 if (encoding == &unicode_encoding) {
4108 while (text_ptr < limit_ptr && unicode_has_property(property,
4109 text_ptr[0]) == match)
4110 ++text_ptr;
4111 } else if (encoding == &ascii_encoding) {
4112 while (text_ptr < limit_ptr && ascii_has_property(property,
4113 text_ptr[0]) == match)
4114 ++text_ptr;
4115 } else {
4116 while (text_ptr < limit_ptr && locale_has_property(locale_info,
4117 property,
4118 text_ptr[0]) == match)
4119 ++text_ptr;
4120 }
4121
4122 text_pos = text_ptr - (Py_UCS4*)text;
4123 break;
4124 }
4125 }
4126
4127 return text_pos;
4128 }
4129
4130 /* Matches many PROPERTYs, up to a limit, ignoring case. */
4131 Py_LOCAL_INLINE(Py_ssize_t) match_many_PROPERTY_IGN(RE_State* state, RE_Node*
4132 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
4133 void* text;
4134 RE_EncodingTable* encoding;
4135 RE_LocaleInfo* locale_info;
4136 RE_CODE property;
4137
4138 text = state->text;
4139 match = node->match == match;
4140
4141 switch (ENCODING_KIND(node)) {
4142 case ASCII_ENCODING:
4143 encoding = &ascii_encoding;
4144 break;
4145 case UNICODE_ENCODING:
4146 encoding = &unicode_encoding;
4147 break;
4148 default:
4149 encoding = state->encoding;
4150 break;
4151 }
4152
4153 locale_info = state->locale_info;
4154 property = node->values[0];
4155
4156 switch (state->charsize) {
4157 case 1:
4158 {
4159 Py_UCS1* text_ptr;
4160 Py_UCS1* limit_ptr;
4161
4162 text_ptr = (Py_UCS1*)text + text_pos;
4163 limit_ptr = (Py_UCS1*)text + limit;
4164
4165 if (encoding == &unicode_encoding) {
4166 while (text_ptr < limit_ptr && unicode_has_property_ign(property,
4167 text_ptr[0]) == match)
4168 ++text_ptr;
4169 } else if (encoding == &ascii_encoding) {
4170 while (text_ptr < limit_ptr && ascii_has_property_ign(property,
4171 text_ptr[0]) == match)
4172 ++text_ptr;
4173 } else {
4174 while (text_ptr < limit_ptr && locale_has_property_ign(locale_info,
4175 property,
4176 text_ptr[0]) == match)
4177 ++text_ptr;
4178 }
4179
4180 text_pos = text_ptr - (Py_UCS1*)text;
4181 break;
4182 }
4183 case 2:
4184 {
4185 Py_UCS2* text_ptr;
4186 Py_UCS2* limit_ptr;
4187
4188 text_ptr = (Py_UCS2*)text + text_pos;
4189 limit_ptr = (Py_UCS2*)text + limit;
4190
4191 if (encoding == &unicode_encoding) {
4192 while (text_ptr < limit_ptr && unicode_has_property_ign(property,
4193 text_ptr[0]) == match)
4194 ++text_ptr;
4195 } else if (encoding == &ascii_encoding) {
4196 while (text_ptr < limit_ptr && ascii_has_property_ign(property,
4197 text_ptr[0]) == match)
4198 ++text_ptr;
4199 } else {
4200 while (text_ptr < limit_ptr && locale_has_property_ign(locale_info,
4201 property,
4202 text_ptr[0]) == match)
4203 ++text_ptr;
4204 }
4205
4206 text_pos = text_ptr - (Py_UCS2*)text;
4207 break;
4208 }
4209 case 4:
4210 {
4211 Py_UCS4* text_ptr;
4212 Py_UCS4* limit_ptr;
4213
4214 text_ptr = (Py_UCS4*)text + text_pos;
4215 limit_ptr = (Py_UCS4*)text + limit;
4216
4217 if (encoding == &unicode_encoding) {
4218 while (text_ptr < limit_ptr && unicode_has_property_ign(property,
4219 text_ptr[0]) == match)
4220 ++text_ptr;
4221 } else if (encoding == &ascii_encoding) {
4222 while (text_ptr < limit_ptr && ascii_has_property_ign(property,
4223 text_ptr[0]) == match)
4224 ++text_ptr;
4225 } else {
4226 while (text_ptr < limit_ptr && locale_has_property_ign(locale_info,
4227 property,
4228 text_ptr[0]) == match)
4229 ++text_ptr;
4230 }
4231
4232 text_pos = text_ptr - (Py_UCS4*)text;
4233 break;
4234 }
4235 }
4236
4237 return text_pos;
4238 }
4239
4240 /* Matches many PROPERTYs, up to a limit, backwards, ignoring case. */
4241 Py_LOCAL_INLINE(Py_ssize_t) match_many_PROPERTY_IGN_REV(RE_State* state,
4242 RE_Node* node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
4243 void* text;
4244 RE_EncodingTable* encoding;
4245 RE_LocaleInfo* locale_info;
4246 RE_CODE property;
4247
4248 text = state->text;
4249 match = node->match == match;
4250
4251 switch (ENCODING_KIND(node)) {
4252 case ASCII_ENCODING:
4253 encoding = &ascii_encoding;
4254 break;
4255 case UNICODE_ENCODING:
4256 encoding = &unicode_encoding;
4257 break;
4258 default:
4259 encoding = state->encoding;
4260 break;
4261 }
4262
4263 locale_info = state->locale_info;
4264 property = node->values[0];
4265
4266 switch (state->charsize) {
4267 case 1:
4268 {
4269 Py_UCS1* text_ptr;
4270 Py_UCS1* limit_ptr;
4271
4272 text_ptr = (Py_UCS1*)text + text_pos;
4273 limit_ptr = (Py_UCS1*)text + limit;
4274
4275 if (encoding == &unicode_encoding) {
4276 while (text_ptr > limit_ptr && unicode_has_property_ign(property,
4277 text_ptr[-1]) == match)
4278 --text_ptr;
4279 } else if (encoding == &ascii_encoding) {
4280 while (text_ptr > limit_ptr && ascii_has_property_ign(property,
4281 text_ptr[-1]) == match)
4282 --text_ptr;
4283 } else {
4284 while (text_ptr > limit_ptr && locale_has_property_ign(locale_info,
4285 property,
4286 text_ptr[-1]) == match)
4287 --text_ptr;
4288 }
4289
4290 text_pos = text_ptr - (Py_UCS1*)text;
4291 break;
4292 }
4293 case 2:
4294 {
4295 Py_UCS2* text_ptr;
4296 Py_UCS2* limit_ptr;
4297
4298 text_ptr = (Py_UCS2*)text + text_pos;
4299 limit_ptr = (Py_UCS2*)text + limit;
4300
4301 if (encoding == &unicode_encoding) {
4302 while (text_ptr > limit_ptr && unicode_has_property_ign(property,
4303 text_ptr[-1]) == match)
4304 --text_ptr;
4305 } else if (encoding == &ascii_encoding) {
4306 while (text_ptr > limit_ptr && ascii_has_property_ign(property,
4307 text_ptr[-1]) == match)
4308 --text_ptr;
4309 } else {
4310 while (text_ptr > limit_ptr && locale_has_property_ign(locale_info,
4311 property,
4312 text_ptr[-1]) == match)
4313 --text_ptr;
4314 }
4315
4316 text_pos = text_ptr - (Py_UCS2*)text;
4317 break;
4318 }
4319 case 4:
4320 {
4321 Py_UCS4* text_ptr;
4322 Py_UCS4* limit_ptr;
4323
4324 text_ptr = (Py_UCS4*)text + text_pos;
4325 limit_ptr = (Py_UCS4*)text + limit;
4326
4327 if (encoding == &unicode_encoding) {
4328 while (text_ptr > limit_ptr && unicode_has_property_ign(property,
4329 text_ptr[-1]) == match)
4330 --text_ptr;
4331 } else if (encoding == &ascii_encoding) {
4332 while (text_ptr > limit_ptr && ascii_has_property_ign(property,
4333 text_ptr[-1]) == match)
4334 --text_ptr;
4335 } else {
4336 while (text_ptr > limit_ptr && locale_has_property_ign(locale_info,
4337 property,
4338 text_ptr[-1]) == match)
4339 --text_ptr;
4340 }
4341
4342 text_pos = text_ptr - (Py_UCS4*)text;
4343 break;
4344 }
4345 }
4346
4347 return text_pos;
4348 }
4349
4350 /* Matches many PROPERTYs, up to a limit, backwards. */
4351 Py_LOCAL_INLINE(Py_ssize_t) match_many_PROPERTY_REV(RE_State* state, RE_Node*
4352 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
4353 void* text;
4354 RE_EncodingTable* encoding;
4355 RE_LocaleInfo* locale_info;
4356 RE_CODE property;
4357
4358 text = state->text;
4359 match = node->match == match;
4360
4361 switch (ENCODING_KIND(node)) {
4362 case ASCII_ENCODING:
4363 encoding = &ascii_encoding;
4364 break;
4365 case UNICODE_ENCODING:
4366 encoding = &unicode_encoding;
4367 break;
4368 default:
4369 encoding = state->encoding;
4370 break;
4371 }
4372
4373 locale_info = state->locale_info;
4374 property = node->values[0];
4375
4376 switch (state->charsize) {
4377 case 1:
4378 {
4379 Py_UCS1* text_ptr;
4380 Py_UCS1* limit_ptr;
4381
4382 text_ptr = (Py_UCS1*)text + text_pos;
4383 limit_ptr = (Py_UCS1*)text + limit;
4384
4385 if (encoding == &unicode_encoding) {
4386 while (text_ptr > limit_ptr && unicode_has_property(property,
4387 text_ptr[-1]) == match)
4388 --text_ptr;
4389 } else if (encoding == &ascii_encoding) {
4390 while (text_ptr > limit_ptr && ascii_has_property(property,
4391 text_ptr[-1]) == match)
4392 --text_ptr;
4393 } else {
4394 while (text_ptr > limit_ptr && locale_has_property(locale_info,
4395 property,
4396 text_ptr[-1]) == match)
4397 --text_ptr;
4398 }
4399
4400 text_pos = text_ptr - (Py_UCS1*)text;
4401 break;
4402 }
4403 case 2:
4404 {
4405 Py_UCS2* text_ptr;
4406 Py_UCS2* limit_ptr;
4407
4408 text_ptr = (Py_UCS2*)text + text_pos;
4409 limit_ptr = (Py_UCS2*)text + limit;
4410
4411 if (encoding == &unicode_encoding) {
4412 while (text_ptr > limit_ptr && unicode_has_property(property,
4413 text_ptr[-1]) == match)
4414 --text_ptr;
4415 } else if (encoding == &ascii_encoding) {
4416 while (text_ptr > limit_ptr && ascii_has_property(property,
4417 text_ptr[-1]) == match)
4418 --text_ptr;
4419 } else {
4420 while (text_ptr > limit_ptr && locale_has_property(locale_info,
4421 property,
4422 text_ptr[-1]) == match)
4423 --text_ptr;
4424 }
4425
4426 text_pos = text_ptr - (Py_UCS2*)text;
4427 break;
4428 }
4429 case 4:
4430 {
4431 Py_UCS4* text_ptr;
4432 Py_UCS4* limit_ptr;
4433
4434 text_ptr = (Py_UCS4*)text + text_pos;
4435 limit_ptr = (Py_UCS4*)text + limit;
4436
4437 if (encoding == &unicode_encoding) {
4438 while (text_ptr > limit_ptr && unicode_has_property(property,
4439 text_ptr[-1]) == match)
4440 --text_ptr;
4441 } else if (encoding == &ascii_encoding) {
4442 while (text_ptr > limit_ptr && ascii_has_property(property,
4443 text_ptr[-1]) == match)
4444 --text_ptr;
4445 } else {
4446 while (text_ptr > limit_ptr && locale_has_property(locale_info,
4447 property,
4448 text_ptr[-1]) == match)
4449 --text_ptr;
4450 }
4451
4452 text_pos = text_ptr - (Py_UCS4*)text;
4453 break;
4454 }
4455 }
4456
4457 return text_pos;
4458 }
4459
4460 /* Matches many RANGEs, up to a limit. */
4461 Py_LOCAL_INLINE(Py_ssize_t) match_many_RANGE(RE_State* state, RE_Node* node,
4462 Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
4463 void* text;
4464 RE_EncodingTable* encoding;
4465 RE_LocaleInfo* locale_info;
4466
4467 text = state->text;
4468 match = node->match == match;
4469 encoding = state->encoding;
4470 locale_info = state->locale_info;
4471
4472 switch (state->charsize) {
4473 case 1:
4474 {
4475 Py_UCS1* text_ptr;
4476 Py_UCS1* limit_ptr;
4477
4478 text_ptr = (Py_UCS1*)text + text_pos;
4479 limit_ptr = (Py_UCS1*)text + limit;
4480
4481 while (text_ptr < limit_ptr && matches_RANGE(encoding, locale_info,
4482 node, text_ptr[0]) == match)
4483 ++text_ptr;
4484
4485 text_pos = text_ptr - (Py_UCS1*)text;
4486 break;
4487 }
4488 case 2:
4489 {
4490 Py_UCS2* text_ptr;
4491 Py_UCS2* limit_ptr;
4492
4493 text_ptr = (Py_UCS2*)text + text_pos;
4494 limit_ptr = (Py_UCS2*)text + limit;
4495
4496 while (text_ptr < limit_ptr && matches_RANGE(encoding, locale_info,
4497 node, text_ptr[0]) == match)
4498 ++text_ptr;
4499
4500 text_pos = text_ptr - (Py_UCS2*)text;
4501 break;
4502 }
4503 case 4:
4504 {
4505 Py_UCS4* text_ptr;
4506 Py_UCS4* limit_ptr;
4507
4508 text_ptr = (Py_UCS4*)text + text_pos;
4509 limit_ptr = (Py_UCS4*)text + limit;
4510
4511 while (text_ptr < limit_ptr && matches_RANGE(encoding, locale_info,
4512 node, text_ptr[0]) == match)
4513 ++text_ptr;
4514
4515 text_pos = text_ptr - (Py_UCS4*)text;
4516 break;
4517 }
4518 }
4519
4520 return text_pos;
4521 }
4522
4523 /* Matches many RANGEs, up to a limit, ignoring case. */
4524 Py_LOCAL_INLINE(Py_ssize_t) match_many_RANGE_IGN(RE_State* state, RE_Node*
4525 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
4526 void* text;
4527 RE_EncodingTable* encoding;
4528 RE_LocaleInfo* locale_info;
4529
4530 text = state->text;
4531 match = node->match == match;
4532 encoding = state->encoding;
4533 locale_info = state->locale_info;
4534
4535 switch (state->charsize) {
4536 case 1:
4537 {
4538 Py_UCS1* text_ptr;
4539 Py_UCS1* limit_ptr;
4540
4541 text_ptr = (Py_UCS1*)text + text_pos;
4542 limit_ptr = (Py_UCS1*)text + limit;
4543
4544 while (text_ptr < limit_ptr && matches_RANGE_IGN(encoding, locale_info,
4545 node, text_ptr[0]) == match)
4546 ++text_ptr;
4547
4548 text_pos = text_ptr - (Py_UCS1*)text;
4549 break;
4550 }
4551 case 2:
4552 {
4553 Py_UCS2* text_ptr;
4554 Py_UCS2* limit_ptr;
4555
4556 text_ptr = (Py_UCS2*)text + text_pos;
4557 limit_ptr = (Py_UCS2*)text + limit;
4558
4559 while (text_ptr < limit_ptr && matches_RANGE_IGN(encoding, locale_info,
4560 node, text_ptr[0]) == match)
4561 ++text_ptr;
4562
4563 text_pos = text_ptr - (Py_UCS2*)text;
4564 break;
4565 }
4566 case 4:
4567 {
4568 Py_UCS4* text_ptr;
4569 Py_UCS4* limit_ptr;
4570
4571 text_ptr = (Py_UCS4*)text + text_pos;
4572 limit_ptr = (Py_UCS4*)text + limit;
4573
4574 while (text_ptr < limit_ptr && matches_RANGE_IGN(encoding, locale_info,
4575 node, text_ptr[0]) == match)
4576 ++text_ptr;
4577
4578 text_pos = text_ptr - (Py_UCS4*)text;
4579 break;
4580 }
4581 }
4582
4583 return text_pos;
4584 }
4585
4586 /* Matches many RANGEs, up to a limit, backwards, ignoring case. */
4587 Py_LOCAL_INLINE(Py_ssize_t) match_many_RANGE_IGN_REV(RE_State* state, RE_Node*
4588 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
4589 void* text;
4590 RE_EncodingTable* encoding;
4591 RE_LocaleInfo* locale_info;
4592
4593 text = state->text;
4594 match = node->match == match;
4595 encoding = state->encoding;
4596 locale_info = state->locale_info;
4597
4598 switch (state->charsize) {
4599 case 1:
4600 {
4601 Py_UCS1* text_ptr;
4602 Py_UCS1* limit_ptr;
4603
4604 text_ptr = (Py_UCS1*)text + text_pos;
4605 limit_ptr = (Py_UCS1*)text + limit;
4606
4607 while (text_ptr > limit_ptr && matches_RANGE_IGN(encoding, locale_info,
4608 node, text_ptr[-1]) == match)
4609 --text_ptr;
4610
4611 text_pos = text_ptr - (Py_UCS1*)text;
4612 break;
4613 }
4614 case 2:
4615 {
4616 Py_UCS2* text_ptr;
4617 Py_UCS2* limit_ptr;
4618
4619 text_ptr = (Py_UCS2*)text + text_pos;
4620 limit_ptr = (Py_UCS2*)text + limit;
4621
4622 while (text_ptr > limit_ptr && matches_RANGE_IGN(encoding, locale_info,
4623 node, text_ptr[-1]) == match)
4624 --text_ptr;
4625
4626 text_pos = text_ptr - (Py_UCS2*)text;
4627 break;
4628 }
4629 case 4:
4630 {
4631 Py_UCS4* text_ptr;
4632 Py_UCS4* limit_ptr;
4633
4634 text_ptr = (Py_UCS4*)text + text_pos;
4635 limit_ptr = (Py_UCS4*)text + limit;
4636
4637 while (text_ptr > limit_ptr && matches_RANGE_IGN(encoding, locale_info,
4638 node, text_ptr[-1]) == match)
4639 --text_ptr;
4640
4641 text_pos = text_ptr - (Py_UCS4*)text;
4642 break;
4643 }
4644 }
4645
4646 return text_pos;
4647 }
4648
4649 /* Matches many RANGEs, up to a limit, backwards. */
4650 Py_LOCAL_INLINE(Py_ssize_t) match_many_RANGE_REV(RE_State* state, RE_Node*
4651 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
4652 void* text;
4653 RE_EncodingTable* encoding;
4654 RE_LocaleInfo* locale_info;
4655
4656 text = state->text;
4657 match = node->match == match;
4658 encoding = state->encoding;
4659 locale_info = state->locale_info;
4660
4661 switch (state->charsize) {
4662 case 1:
4663 {
4664 Py_UCS1* text_ptr;
4665 Py_UCS1* limit_ptr;
4666
4667 text_ptr = (Py_UCS1*)text + text_pos;
4668 limit_ptr = (Py_UCS1*)text + limit;
4669
4670 while (text_ptr > limit_ptr && matches_RANGE(encoding, locale_info,
4671 node, text_ptr[-1]) == match)
4672 --text_ptr;
4673
4674 text_pos = text_ptr - (Py_UCS1*)text;
4675 break;
4676 }
4677 case 2:
4678 {
4679 Py_UCS2* text_ptr;
4680 Py_UCS2* limit_ptr;
4681
4682 text_ptr = (Py_UCS2*)text + text_pos;
4683 limit_ptr = (Py_UCS2*)text + limit;
4684
4685 while (text_ptr > limit_ptr && matches_RANGE(encoding, locale_info,
4686 node, text_ptr[-1]) == match)
4687 --text_ptr;
4688
4689 text_pos = text_ptr - (Py_UCS2*)text;
4690 break;
4691 }
4692 case 4:
4693 {
4694 Py_UCS4* text_ptr;
4695 Py_UCS4* limit_ptr;
4696
4697 text_ptr = (Py_UCS4*)text + text_pos;
4698 limit_ptr = (Py_UCS4*)text + limit;
4699
4700 while (text_ptr > limit_ptr && matches_RANGE(encoding, locale_info,
4701 node, text_ptr[-1]) == match)
4702 --text_ptr;
4703
4704 text_pos = text_ptr - (Py_UCS4*)text;
4705 break;
4706 }
4707 }
4708
4709 return text_pos;
4710 }
4711
4712 /* Matches many SETs, up to a limit. */
4713 Py_LOCAL_INLINE(Py_ssize_t) match_many_SET(RE_State* state, RE_Node* node,
4714 Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
4715 void* text;
4716 RE_EncodingTable* encoding;
4717 RE_LocaleInfo* locale_info;
4718
4719 text = state->text;
4720 match = node->match == match;
4721 encoding = state->encoding;
4722 locale_info = state->locale_info;
4723
4724 switch (state->charsize) {
4725 case 1:
4726 {
4727 Py_UCS1* text_ptr;
4728 Py_UCS1* limit_ptr;
4729
4730 text_ptr = (Py_UCS1*)text + text_pos;
4731 limit_ptr = (Py_UCS1*)text + limit;
4732
4733 while (text_ptr < limit_ptr && matches_SET(encoding, locale_info, node,
4734 text_ptr[0]) == match)
4735 ++text_ptr;
4736
4737 text_pos = text_ptr - (Py_UCS1*)text;
4738 break;
4739 }
4740 case 2:
4741 {
4742 Py_UCS2* text_ptr;
4743 Py_UCS2* limit_ptr;
4744
4745 text_ptr = (Py_UCS2*)text + text_pos;
4746 limit_ptr = (Py_UCS2*)text + limit;
4747
4748 while (text_ptr < limit_ptr && matches_SET(encoding, locale_info, node,
4749 text_ptr[0]) == match)
4750 ++text_ptr;
4751
4752 text_pos = text_ptr - (Py_UCS2*)text;
4753 break;
4754 }
4755 case 4:
4756 {
4757 Py_UCS4* text_ptr;
4758 Py_UCS4* limit_ptr;
4759
4760 text_ptr = (Py_UCS4*)text + text_pos;
4761 limit_ptr = (Py_UCS4*)text + limit;
4762
4763 while (text_ptr < limit_ptr && matches_SET(encoding, locale_info, node,
4764 text_ptr[0]) == match)
4765 ++text_ptr;
4766
4767 text_pos = text_ptr - (Py_UCS4*)text;
4768 break;
4769 }
4770 }
4771
4772 return text_pos;
4773 }
4774
4775 /* Matches many SETs, up to a limit, ignoring case. */
4776 Py_LOCAL_INLINE(Py_ssize_t) match_many_SET_IGN(RE_State* state, RE_Node* node,
4777 Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
4778 void* text;
4779 RE_EncodingTable* encoding;
4780 RE_LocaleInfo* locale_info;
4781
4782 text = state->text;
4783 match = node->match == match;
4784 encoding = state->encoding;
4785 locale_info = state->locale_info;
4786
4787 switch (state->charsize) {
4788 case 1:
4789 {
4790 Py_UCS1* text_ptr;
4791 Py_UCS1* limit_ptr;
4792
4793 text_ptr = (Py_UCS1*)text + text_pos;
4794 limit_ptr = (Py_UCS1*)text + limit;
4795
4796 while (text_ptr < limit_ptr && matches_SET_IGN(encoding, locale_info,
4797 node, text_ptr[0]) == match)
4798 ++text_ptr;
4799
4800 text_pos = text_ptr - (Py_UCS1*)text;
4801 break;
4802 }
4803 case 2:
4804 {
4805 Py_UCS2* text_ptr;
4806 Py_UCS2* limit_ptr;
4807
4808 text_ptr = (Py_UCS2*)text + text_pos;
4809 limit_ptr = (Py_UCS2*)text + limit;
4810
4811 while (text_ptr < limit_ptr && matches_SET_IGN(encoding, locale_info,
4812 node, text_ptr[0]) == match)
4813 ++text_ptr;
4814
4815 text_pos = text_ptr - (Py_UCS2*)text;
4816 break;
4817 }
4818 case 4:
4819 {
4820 Py_UCS4* text_ptr;
4821 Py_UCS4* limit_ptr;
4822
4823 text_ptr = (Py_UCS4*)text + text_pos;
4824 limit_ptr = (Py_UCS4*)text + limit;
4825
4826 while (text_ptr < limit_ptr && matches_SET_IGN(encoding, locale_info,
4827 node, text_ptr[0]) == match)
4828 ++text_ptr;
4829
4830 text_pos = text_ptr - (Py_UCS4*)text;
4831 break;
4832 }
4833 }
4834
4835 return text_pos;
4836 }
4837
4838 /* Matches many SETs, up to a limit, backwards, ignoring case. */
4839 Py_LOCAL_INLINE(Py_ssize_t) match_many_SET_IGN_REV(RE_State* state, RE_Node*
4840 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
4841 void* text;
4842 RE_EncodingTable* encoding;
4843 RE_LocaleInfo* locale_info;
4844
4845 text = state->text;
4846 match = node->match == match;
4847 encoding = state->encoding;
4848 locale_info = state->locale_info;
4849
4850 switch (state->charsize) {
4851 case 1:
4852 {
4853 Py_UCS1* text_ptr;
4854 Py_UCS1* limit_ptr;
4855
4856 text_ptr = (Py_UCS1*)text + text_pos;
4857 limit_ptr = (Py_UCS1*)text + limit;
4858
4859 while (text_ptr > limit_ptr && matches_SET_IGN(encoding, locale_info,
4860 node, text_ptr[-1]) == match)
4861 --text_ptr;
4862
4863 text_pos = text_ptr - (Py_UCS1*)text;
4864 break;
4865 }
4866 case 2:
4867 {
4868 Py_UCS2* text_ptr;
4869 Py_UCS2* limit_ptr;
4870
4871 text_ptr = (Py_UCS2*)text + text_pos;
4872 limit_ptr = (Py_UCS2*)text + limit;
4873
4874 while (text_ptr > limit_ptr && matches_SET_IGN(encoding, locale_info,
4875 node, text_ptr[-1]) == match)
4876 --text_ptr;
4877
4878 text_pos = text_ptr - (Py_UCS2*)text;
4879 break;
4880 }
4881 case 4:
4882 {
4883 Py_UCS4* text_ptr;
4884 Py_UCS4* limit_ptr;
4885
4886 text_ptr = (Py_UCS4*)text + text_pos;
4887 limit_ptr = (Py_UCS4*)text + limit;
4888
4889 while (text_ptr > limit_ptr && matches_SET_IGN(encoding, locale_info,
4890 node, text_ptr[-1]) == match)
4891 --text_ptr;
4892
4893 text_pos = text_ptr - (Py_UCS4*)text;
4894 break;
4895 }
4896 }
4897
4898 return text_pos;
4899 }
4900
4901 /* Matches many SETs, up to a limit, backwards. */
4902 Py_LOCAL_INLINE(Py_ssize_t) match_many_SET_REV(RE_State* state, RE_Node* node,
4903 Py_ssize_t text_pos, Py_ssize_t limit, BOOL match) {
4904 void* text;
4905 RE_EncodingTable* encoding;
4906 RE_LocaleInfo* locale_info;
4907
4908 text = state->text;
4909 match = node->match == match;
4910 encoding = state->encoding;
4911 locale_info = state->locale_info;
4912
4913 switch (state->charsize) {
4914 case 1:
4915 {
4916 Py_UCS1* text_ptr;
4917 Py_UCS1* limit_ptr;
4918
4919 text_ptr = (Py_UCS1*)text + text_pos;
4920 limit_ptr = (Py_UCS1*)text + limit;
4921
4922 while (text_ptr > limit_ptr && matches_SET(encoding, locale_info, node,
4923 text_ptr[-1]) == match)
4924 --text_ptr;
4925
4926 text_pos = text_ptr - (Py_UCS1*)text;
4927 break;
4928 }
4929 case 2:
4930 {
4931 Py_UCS2* text_ptr;
4932 Py_UCS2* limit_ptr;
4933
4934 text_ptr = (Py_UCS2*)text + text_pos;
4935 limit_ptr = (Py_UCS2*)text + limit;
4936
4937 while (text_ptr > limit_ptr && matches_SET(encoding, locale_info, node,
4938 text_ptr[-1]) == match)
4939 --text_ptr;
4940
4941 text_pos = text_ptr - (Py_UCS2*)text;
4942 break;
4943 }
4944 case 4:
4945 {
4946 Py_UCS4* text_ptr;
4947 Py_UCS4* limit_ptr;
4948
4949 text_ptr = (Py_UCS4*)text + text_pos;
4950 limit_ptr = (Py_UCS4*)text + limit;
4951
4952 while (text_ptr > limit_ptr && matches_SET(encoding, locale_info, node,
4953 text_ptr[-1]) == match)
4954 --text_ptr;
4955
4956 text_pos = text_ptr - (Py_UCS4*)text;
4957 break;
4958 }
4959 }
4960
4961 return text_pos;
4962 }
4963
4964 /* Counts a repeated character pattern. */
4965 Py_LOCAL_INLINE(size_t) count_one(RE_State* state, RE_Node* node, Py_ssize_t
4966 text_pos, size_t max_count, BOOL* is_partial) {
4967 size_t count;
4968
4969 *is_partial = FALSE;
4970
4971 if (max_count < 1)
4972 return 0;
4973
4974 switch (node->op) {
4975 case RE_OP_ANY:
4976 count = min_size_t((size_t)(state->slice_end - text_pos), max_count);
4977
4978 count = (size_t)(match_many_ANY(state, node, text_pos, text_pos +
4979 (Py_ssize_t)count, TRUE) - text_pos);
4980
4981 *is_partial = count == (size_t)(state->text_end - text_pos) && count
4982 < max_count && state->partial_side == RE_PARTIAL_RIGHT;
4983
4984 return count;
4985 case RE_OP_ANY_ALL:
4986 count = min_size_t((size_t)(state->slice_end - text_pos), max_count);
4987
4988 *is_partial = count == (size_t)(state->text_end - text_pos) && count
4989 < max_count && state->partial_side == RE_PARTIAL_RIGHT;
4990
4991 return count;
4992 case RE_OP_ANY_ALL_REV:
4993 count = min_size_t((size_t)(text_pos - state->slice_start), max_count);
4994
4995 *is_partial = count == (size_t)(text_pos) && count < max_count &&
4996 state->partial_side == RE_PARTIAL_LEFT;
4997
4998 return count;
4999 case RE_OP_ANY_REV:
5000 count = min_size_t((size_t)(text_pos - state->slice_start), max_count);
5001
5002 count = (size_t)(text_pos - match_many_ANY_REV(state, node, text_pos,
5003 text_pos - (Py_ssize_t)count, TRUE));
5004
5005 *is_partial = count == (size_t)(text_pos) && count < max_count &&
5006 state->partial_side == RE_PARTIAL_LEFT;
5007
5008 return count;
5009 case RE_OP_ANY_U:
5010 count = min_size_t((size_t)(state->slice_end - text_pos), max_count);
5011
5012 count = (size_t)(match_many_ANY_U(state, node, text_pos, text_pos +
5013 (Py_ssize_t)count, TRUE) - text_pos);
5014
5015 *is_partial = count == (size_t)(state->text_end - text_pos) && count
5016 < max_count && state->partial_side == RE_PARTIAL_RIGHT;
5017
5018 return count;
5019 case RE_OP_ANY_U_REV:
5020 count = min_size_t((size_t)(text_pos - state->slice_start), max_count);
5021
5022 count = (size_t)(text_pos - match_many_ANY_U_REV(state, node, text_pos,
5023 text_pos - (Py_ssize_t)count, TRUE));
5024
5025 *is_partial = count == (size_t)(text_pos) && count < max_count &&
5026 state->partial_side == RE_PARTIAL_LEFT;
5027
5028 return count;
5029 case RE_OP_CHARACTER:
5030 count = min_size_t((size_t)(state->slice_end - text_pos), max_count);
5031
5032 count = (size_t)(match_many_CHARACTER(state, node, text_pos, text_pos +
5033 (Py_ssize_t)count, TRUE) - text_pos);
5034
5035 *is_partial = count == (size_t)(state->text_end - text_pos) && count
5036 < max_count && state->partial_side == RE_PARTIAL_RIGHT;
5037
5038 return count;
5039 case RE_OP_CHARACTER_IGN:
5040 count = min_size_t((size_t)(state->slice_end - text_pos), max_count);
5041
5042 count = (size_t)(match_many_CHARACTER_IGN(state, node, text_pos,
5043 text_pos + (Py_ssize_t)count, TRUE) - text_pos);
5044
5045 *is_partial = count == (size_t)(state->text_end - text_pos) && count
5046 < max_count && state->partial_side == RE_PARTIAL_RIGHT;
5047
5048 return count;
5049 case RE_OP_CHARACTER_IGN_REV:
5050 count = min_size_t((size_t)(text_pos - state->slice_start), max_count);
5051
5052 count = (size_t)(text_pos - match_many_CHARACTER_IGN_REV(state, node,
5053 text_pos, text_pos - (Py_ssize_t)count, TRUE));
5054
5055 *is_partial = count == (size_t)(text_pos) && count < max_count &&
5056 state->partial_side == RE_PARTIAL_LEFT;
5057
5058 return count;
5059 case RE_OP_CHARACTER_REV:
5060 count = min_size_t((size_t)(text_pos - state->slice_start), max_count);
5061
5062 count = (size_t)(text_pos - match_many_CHARACTER_REV(state, node,
5063 text_pos, text_pos - (Py_ssize_t)count, TRUE));
5064
5065 *is_partial = count == (size_t)(text_pos) && count < max_count &&
5066 state->partial_side == RE_PARTIAL_LEFT;
5067
5068 return count;
5069 case RE_OP_PROPERTY:
5070 count = min_size_t((size_t)(state->slice_end - text_pos), max_count);
5071
5072 count = (size_t)(match_many_PROPERTY(state, node, text_pos, text_pos +
5073 (Py_ssize_t)count, TRUE) - text_pos);
5074
5075 *is_partial = count == (size_t)(state->text_end - text_pos) && count
5076 < max_count && state->partial_side == RE_PARTIAL_RIGHT;
5077
5078 return count;
5079 case RE_OP_PROPERTY_IGN:
5080 count = min_size_t((size_t)(state->slice_end - text_pos), max_count);
5081
5082 count = (size_t)(match_many_PROPERTY_IGN(state, node, text_pos,
5083 text_pos + (Py_ssize_t)count, TRUE) - text_pos);
5084
5085 *is_partial = count == (size_t)(state->text_end - text_pos) && count
5086 < max_count && state->partial_side == RE_PARTIAL_RIGHT;
5087
5088 return count;
5089 case RE_OP_PROPERTY_IGN_REV:
5090 count = min_size_t((size_t)(text_pos - state->slice_start), max_count);
5091
5092 count = (size_t)(text_pos - match_many_PROPERTY_IGN_REV(state, node,
5093 text_pos, text_pos - (Py_ssize_t)count, TRUE));
5094
5095 *is_partial = count == (size_t)(text_pos) && count < max_count &&
5096 state->partial_side == RE_PARTIAL_LEFT;
5097
5098 return count;
5099 case RE_OP_PROPERTY_REV:
5100 count = min_size_t((size_t)(text_pos - state->slice_start), max_count);
5101
5102 count = (size_t)(text_pos - match_many_PROPERTY_REV(state, node,
5103 text_pos, text_pos - (Py_ssize_t)count, TRUE));
5104
5105 *is_partial = count == (size_t)(text_pos) && count < max_count &&
5106 state->partial_side == RE_PARTIAL_LEFT;
5107
5108 return count;
5109 case RE_OP_RANGE:
5110 count = min_size_t((size_t)(state->slice_end - text_pos), max_count);
5111
5112 count = (size_t)(match_many_RANGE(state, node, text_pos, text_pos +
5113 (Py_ssize_t)count, TRUE) - text_pos);
5114
5115 *is_partial = count == (size_t)(state->text_end - text_pos) && count
5116 < max_count && state->partial_side == RE_PARTIAL_RIGHT;
5117
5118 return count;
5119 case RE_OP_RANGE_IGN:
5120 count = min_size_t((size_t)(state->slice_end - text_pos), max_count);
5121
5122 count = (size_t)(match_many_RANGE_IGN(state, node, text_pos, text_pos +
5123 (Py_ssize_t)count, TRUE) - text_pos);
5124
5125 *is_partial = count == (size_t)(state->text_end - text_pos) && count
5126 < max_count && state->partial_side == RE_PARTIAL_RIGHT;
5127
5128 return count;
5129 case RE_OP_RANGE_IGN_REV:
5130 count = min_size_t((size_t)(text_pos - state->slice_start), max_count);
5131
5132 count = (size_t)(text_pos - match_many_RANGE_IGN_REV(state, node,
5133 text_pos, text_pos - (Py_ssize_t)count, TRUE));
5134
5135 *is_partial = count == (size_t)(text_pos) && count < max_count &&
5136 state->partial_side == RE_PARTIAL_LEFT;
5137
5138 return count;
5139 case RE_OP_RANGE_REV:
5140 count = min_size_t((size_t)(text_pos - state->slice_start), max_count);
5141
5142 count = (size_t)(text_pos - match_many_RANGE_REV(state, node, text_pos,
5143 text_pos - (Py_ssize_t)count, TRUE));
5144
5145 *is_partial = count == (size_t)(text_pos) && count < max_count &&
5146 state->partial_side == RE_PARTIAL_LEFT;
5147
5148 return count;
5149 case RE_OP_SET_DIFF:
5150 case RE_OP_SET_INTER:
5151 case RE_OP_SET_SYM_DIFF:
5152 case RE_OP_SET_UNION:
5153 count = min_size_t((size_t)(state->slice_end - text_pos), max_count);
5154
5155 count = (size_t)(match_many_SET(state, node, text_pos, text_pos +
5156 (Py_ssize_t)count, TRUE) - text_pos);
5157
5158 *is_partial = count == (size_t)(state->text_end - text_pos) && count
5159 < max_count && state->partial_side == RE_PARTIAL_RIGHT;
5160
5161 return count;
5162 case RE_OP_SET_DIFF_IGN:
5163 case RE_OP_SET_INTER_IGN:
5164 case RE_OP_SET_SYM_DIFF_IGN:
5165 case RE_OP_SET_UNION_IGN:
5166 count = min_size_t((size_t)(state->slice_end - text_pos), max_count);
5167
5168 count = (size_t)(match_many_SET_IGN(state, node, text_pos, text_pos +
5169 (Py_ssize_t)count, TRUE) - text_pos);
5170
5171 *is_partial = count == (size_t)(state->text_end - text_pos) && count
5172 < max_count && state->partial_side == RE_PARTIAL_RIGHT;
5173
5174 return count;
5175 case RE_OP_SET_DIFF_IGN_REV:
5176 case RE_OP_SET_INTER_IGN_REV:
5177 case RE_OP_SET_SYM_DIFF_IGN_REV:
5178 case RE_OP_SET_UNION_IGN_REV:
5179 count = min_size_t((size_t)(text_pos - state->slice_start), max_count);
5180
5181 count = (size_t)(text_pos - match_many_SET_IGN_REV(state, node,
5182 text_pos, text_pos - (Py_ssize_t)count, TRUE));
5183
5184 *is_partial = count == (size_t)(text_pos) && count < max_count &&
5185 state->partial_side == RE_PARTIAL_LEFT;
5186
5187 return count;
5188 case RE_OP_SET_DIFF_REV:
5189 case RE_OP_SET_INTER_REV:
5190 case RE_OP_SET_SYM_DIFF_REV:
5191 case RE_OP_SET_UNION_REV:
5192 count = min_size_t((size_t)(text_pos - state->slice_start), max_count);
5193
5194 count = (size_t)(text_pos - match_many_SET_REV(state, node, text_pos,
5195 text_pos - (Py_ssize_t)count, TRUE));
5196
5197 *is_partial = count == (size_t)(text_pos) && count < max_count &&
5198 state->partial_side == RE_PARTIAL_LEFT;
5199
5200 return count;
5201 }
5202
5203 return 0;
5204 }
5205
5206 /* Performs a simple string search. */
5207 Py_LOCAL_INLINE(Py_ssize_t) simple_string_search(RE_State* state, RE_Node*
5208 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL* is_partial) {
5209 Py_ssize_t length;
5210 RE_CODE* values;
5211 Py_UCS4 check_char;
5212
5213 length = (Py_ssize_t)node->value_count;
5214 values = node->values;
5215 check_char = values[0];
5216
5217 *is_partial = FALSE;
5218
5219 switch (state->charsize) {
5220 case 1:
5221 {
5222 Py_UCS1* text = (Py_UCS1*)state->text;
5223 Py_UCS1* text_ptr = text + text_pos;
5224 Py_UCS1* limit_ptr = text + limit;
5225
5226 while (text_ptr < limit_ptr) {
5227 if (text_ptr[0] == check_char) {
5228 Py_ssize_t s_pos;
5229
5230 s_pos = 1;
5231
5232 for (;;) {
5233 if (s_pos >= length)
5234 /* End of search string. */
5235 return text_ptr - text;
5236
5237 if (text_ptr + s_pos >= limit_ptr) {
5238 /* Off the end of the text. */
5239 if (state->partial_side == RE_PARTIAL_RIGHT) {
5240 /* Partial match. */
5241 *is_partial = TRUE;
5242 return text_ptr - text;
5243 }
5244
5245 return -1;
5246
5247 }
5248
5249 if (!same_char(text_ptr[s_pos], values[s_pos]))
5250 break;
5251
5252 ++s_pos;
5253 }
5254 }
5255
5256 ++text_ptr;
5257 }
5258 text_pos = text_ptr - text;
5259 break;
5260 }
5261 case 2:
5262 {
5263 Py_UCS2* text = (Py_UCS2*)state->text;
5264 Py_UCS2* text_ptr = text + text_pos;
5265 Py_UCS2* limit_ptr = text + limit;
5266
5267 while (text_ptr < limit_ptr) {
5268 if (text_ptr[0] == check_char) {
5269 Py_ssize_t s_pos;
5270
5271 s_pos = 1;
5272
5273 for (;;) {
5274 if (s_pos >= length)
5275 /* End of search string. */
5276 return text_ptr - text;
5277
5278 if (text_ptr + s_pos >= limit_ptr) {
5279 /* Off the end of the text. */
5280 if (state->partial_side == RE_PARTIAL_RIGHT) {
5281 /* Partial match. */
5282 *is_partial = TRUE;
5283 return text_ptr - text;
5284 }
5285
5286 return -1;
5287
5288 }
5289
5290 if (!same_char(text_ptr[s_pos], values[s_pos]))
5291 break;
5292
5293 ++s_pos;
5294 }
5295 }
5296
5297 ++text_ptr;
5298 }
5299 text_pos = text_ptr - text;
5300 break;
5301 }
5302 case 4:
5303 {
5304 Py_UCS4* text = (Py_UCS4*)state->text;
5305 Py_UCS4* text_ptr = text + text_pos;
5306 Py_UCS4* limit_ptr = text + limit;
5307
5308 while (text_ptr < limit_ptr) {
5309 if (text_ptr[0] == check_char) {
5310 Py_ssize_t s_pos;
5311
5312 s_pos = 1;
5313
5314 for (;;) {
5315 if (s_pos >= length)
5316 /* End of search string. */
5317 return text_ptr - text;
5318
5319 if (text_ptr + s_pos >= limit_ptr) {
5320 /* Off the end of the text. */
5321 if (state->partial_side == RE_PARTIAL_RIGHT) {
5322 /* Partial match. */
5323 *is_partial = TRUE;
5324 return text_ptr - text;
5325 }
5326
5327 return -1;
5328
5329 }
5330
5331 if (!same_char(text_ptr[s_pos], values[s_pos]))
5332 break;
5333
5334 ++s_pos;
5335 }
5336 }
5337
5338 ++text_ptr;
5339 }
5340 text_pos = text_ptr - text;
5341 break;
5342 }
5343 }
5344
5345 /* Off the end of the text. */
5346 if (state->partial_side == RE_PARTIAL_RIGHT) {
5347 /* Partial match. */
5348 *is_partial = TRUE;
5349 return text_pos;
5350 }
5351
5352 return -1;
5353 }
5354
5355 /* Performs a simple string search, ignoring case. */
5356 Py_LOCAL_INLINE(Py_ssize_t) simple_string_search_ign(RE_State* state, RE_Node*
5357 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL* is_partial) {
5358 Py_ssize_t length;
5359 RE_CODE* values;
5360 RE_EncodingTable* encoding;
5361 RE_LocaleInfo* locale_info;
5362 Py_UCS4 cases[RE_MAX_CASES];
5363 int case_count;
5364
5365 length = (Py_ssize_t)node->value_count;
5366 values = node->values;
5367 encoding = state->encoding;
5368 locale_info = state->locale_info;
5369 case_count = encoding->all_cases(locale_info, values[0], cases);
5370
5371 *is_partial = FALSE;
5372
5373 switch (state->charsize) {
5374 case 1:
5375 {
5376 Py_UCS1* text = (Py_UCS1*)state->text;
5377 Py_UCS1* text_ptr = text + text_pos;
5378 Py_UCS1* limit_ptr = text + limit;
5379
5380 while (text_ptr < limit_ptr) {
5381 if (any_case(text_ptr[0], case_count, cases)) {
5382 Py_ssize_t s_pos;
5383
5384 s_pos = 1;
5385
5386 for (;;) {
5387 if (s_pos >= length)
5388 /* End of search string. */
5389 return text_ptr - text;
5390
5391 if (text_ptr + s_pos >= limit_ptr) {
5392 /* Off the end of the text. */
5393 if (state->partial_side == RE_PARTIAL_RIGHT) {
5394 /* Partial match. */
5395 *is_partial = TRUE;
5396 return text_ptr - text;
5397 }
5398
5399 return -1;
5400
5401 }
5402
5403 if (!same_char_ign(encoding, locale_info, text_ptr[s_pos],
5404 values[s_pos]))
5405 break;
5406
5407 ++s_pos;
5408 }
5409 }
5410
5411 ++text_ptr;
5412 }
5413 text_pos = text_ptr - text;
5414 break;
5415 }
5416 case 2:
5417 {
5418 Py_UCS2* text = (Py_UCS2*)state->text;
5419 Py_UCS2* text_ptr = text + text_pos;
5420 Py_UCS2* limit_ptr = text + limit;
5421
5422 while (text_ptr < limit_ptr) {
5423 if (any_case(text_ptr[0], case_count, cases)) {
5424 Py_ssize_t s_pos;
5425
5426 s_pos = 1;
5427
5428 for (;;) {
5429 if (s_pos >= length)
5430 /* End of search string. */
5431 return text_ptr - text;
5432
5433 if (text_ptr + s_pos >= limit_ptr) {
5434 /* Off the end of the text. */
5435 if (state->partial_side == RE_PARTIAL_RIGHT) {
5436 /* Partial match. */
5437 *is_partial = TRUE;
5438 return text_ptr - text;
5439 }
5440
5441 return -1;
5442
5443 }
5444
5445 if (!same_char_ign(encoding, locale_info, text_ptr[s_pos],
5446 values[s_pos]))
5447 break;
5448
5449 ++s_pos;
5450 }
5451 }
5452
5453 ++text_ptr;
5454 }
5455 text_pos = text_ptr - text;
5456 break;
5457 }
5458 case 4:
5459 {
5460 Py_UCS4* text = (Py_UCS4*)state->text;
5461 Py_UCS4* text_ptr = text + text_pos;
5462 Py_UCS4* limit_ptr = text + limit;
5463
5464 while (text_ptr < limit_ptr) {
5465 if (any_case(text_ptr[0], case_count, cases)) {
5466 Py_ssize_t s_pos;
5467
5468 s_pos = 1;
5469
5470 for (;;) {
5471 if (s_pos >= length)
5472 /* End of search string. */
5473 return text_ptr - text;
5474
5475 if (text_ptr + s_pos >= limit_ptr) {
5476 /* Off the end of the text. */
5477 if (state->partial_side == RE_PARTIAL_RIGHT) {
5478 /* Partial match. */
5479 *is_partial = TRUE;
5480 return text_ptr - text;
5481 }
5482
5483 return -1;
5484
5485 }
5486
5487 if (!same_char_ign(encoding, locale_info, text_ptr[s_pos],
5488 values[s_pos]))
5489 break;
5490
5491 ++s_pos;
5492 }
5493 }
5494
5495 ++text_ptr;
5496 }
5497 text_pos = text_ptr - text;
5498 break;
5499 }
5500 }
5501
5502 /* Off the end of the text. */
5503 if (state->partial_side == RE_PARTIAL_RIGHT) {
5504 /* Partial match. */
5505 *is_partial = TRUE;
5506 return text_pos;
5507 }
5508
5509 return -1;
5510 }
5511
5512 /* Performs a simple string search, backwards, ignoring case. */
5513 Py_LOCAL_INLINE(Py_ssize_t) simple_string_search_ign_rev(RE_State* state,
5514 RE_Node* node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL* is_partial) {
5515 Py_ssize_t length;
5516 RE_CODE* values;
5517 RE_EncodingTable* encoding;
5518 RE_LocaleInfo* locale_info;
5519 Py_UCS4 cases[RE_MAX_CASES];
5520 int case_count;
5521
5522 length = (Py_ssize_t)node->value_count;
5523 values = node->values;
5524 encoding = state->encoding;
5525 locale_info = state->locale_info;
5526 case_count = encoding->all_cases(locale_info, values[length - 1], cases);
5527
5528 *is_partial = FALSE;
5529
5530 switch (state->charsize) {
5531 case 1:
5532 {
5533 Py_UCS1* text = (Py_UCS1*)state->text;
5534 Py_UCS1* text_ptr = text + text_pos;
5535 Py_UCS1* limit_ptr = text + limit;
5536
5537 while (text_ptr > limit_ptr) {
5538 if (any_case(text_ptr[-1], case_count, cases)) {
5539 Py_ssize_t s_pos;
5540
5541 s_pos = 1;
5542
5543 for (;;) {
5544 if (s_pos >= length)
5545 /* End of search string. */
5546 return text_ptr - text;
5547
5548 if (text_ptr - s_pos <= limit_ptr) {
5549 /* Off the end of the text. */
5550 if (state->partial_side == RE_PARTIAL_LEFT) {
5551 /* Partial match. */
5552 *is_partial = TRUE;
5553 return text_ptr - text;
5554 }
5555
5556 return -1;
5557
5558 }
5559
5560 if (!same_char_ign(encoding, locale_info, text_ptr[- s_pos
5561 - 1], values[length - s_pos - 1]))
5562 break;
5563
5564 ++s_pos;
5565 }
5566 }
5567
5568 --text_ptr;
5569 }
5570 text_pos = text_ptr - text;
5571 break;
5572 }
5573 case 2:
5574 {
5575 Py_UCS2* text = (Py_UCS2*)state->text;
5576 Py_UCS2* text_ptr = text + text_pos;
5577 Py_UCS2* limit_ptr = text + limit;
5578
5579 while (text_ptr > limit_ptr) {
5580 if (any_case(text_ptr[-1], case_count, cases)) {
5581 Py_ssize_t s_pos;
5582
5583 s_pos = 1;
5584
5585 for (;;) {
5586 if (s_pos >= length)
5587 /* End of search string. */
5588 return text_ptr - text;
5589
5590 if (text_ptr - s_pos <= limit_ptr) {
5591 /* Off the end of the text. */
5592 if (state->partial_side == RE_PARTIAL_LEFT) {
5593 /* Partial match. */
5594 *is_partial = TRUE;
5595 return text_ptr - text;
5596 }
5597
5598 return -1;
5599
5600 }
5601
5602 if (!same_char_ign(encoding, locale_info, text_ptr[- s_pos
5603 - 1], values[length - s_pos - 1]))
5604 break;
5605
5606 ++s_pos;
5607 }
5608 }
5609
5610 --text_ptr;
5611 }
5612 text_pos = text_ptr - text;
5613 break;
5614 }
5615 case 4:
5616 {
5617 Py_UCS4* text = (Py_UCS4*)state->text;
5618 Py_UCS4* text_ptr = text + text_pos;
5619 Py_UCS4* limit_ptr = text + limit;
5620
5621 while (text_ptr > limit_ptr) {
5622 if (any_case(text_ptr[-1], case_count, cases)) {
5623 Py_ssize_t s_pos;
5624
5625 s_pos = 1;
5626
5627 for (;;) {
5628 if (s_pos >= length)
5629 /* End of search string. */
5630 return text_ptr - text;
5631
5632 if (text_ptr - s_pos <= limit_ptr) {
5633 /* Off the end of the text. */
5634 if (state->partial_side == RE_PARTIAL_LEFT) {
5635 /* Partial match. */
5636 *is_partial = TRUE;
5637 return text_ptr - text;
5638 }
5639
5640 return -1;
5641
5642 }
5643
5644 if (!same_char_ign(encoding, locale_info, text_ptr[- s_pos
5645 - 1], values[length - s_pos - 1]))
5646 break;
5647
5648 ++s_pos;
5649 }
5650 }
5651
5652 --text_ptr;
5653 }
5654 text_pos = text_ptr - text;
5655 break;
5656 }
5657 }
5658
5659 /* Off the end of the text. */
5660 if (state->partial_side == RE_PARTIAL_LEFT) {
5661 /* Partial match. */
5662 *is_partial = TRUE;
5663 return text_pos;
5664 }
5665
5666 return -1;
5667 }
5668
5669 /* Performs a simple string search, backwards. */
5670 Py_LOCAL_INLINE(Py_ssize_t) simple_string_search_rev(RE_State* state, RE_Node*
5671 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL* is_partial) {
5672 Py_ssize_t length;
5673 RE_CODE* values;
5674 Py_UCS4 check_char;
5675
5676 length = (Py_ssize_t)node->value_count;
5677 values = node->values;
5678 check_char = values[length - 1];
5679
5680 *is_partial = FALSE;
5681
5682 switch (state->charsize) {
5683 case 1:
5684 {
5685 Py_UCS1* text = (Py_UCS1*)state->text;
5686 Py_UCS1* text_ptr = text + text_pos;
5687 Py_UCS1* limit_ptr = text + limit;
5688
5689 while (text_ptr > limit_ptr) {
5690 if (text_ptr[-1] == check_char) {
5691 Py_ssize_t s_pos;
5692
5693 s_pos = 1;
5694
5695 for (;;) {
5696 if (s_pos >= length)
5697 /* End of search string. */
5698 return text_ptr - text;
5699
5700 if (text_ptr - s_pos <= limit_ptr) {
5701 /* Off the end of the text. */
5702 if (state->partial_side == RE_PARTIAL_LEFT) {
5703 /* Partial match. */
5704 *is_partial = TRUE;
5705 return text_ptr - text;
5706 }
5707
5708 return -1;
5709
5710 }
5711
5712 if (!same_char(text_ptr[- s_pos - 1], values[length - s_pos
5713 - 1]))
5714 break;
5715
5716 ++s_pos;
5717 }
5718 }
5719
5720 --text_ptr;
5721 }
5722 text_pos = text_ptr - text;
5723 break;
5724 }
5725 case 2:
5726 {
5727 Py_UCS2* text = (Py_UCS2*)state->text;
5728 Py_UCS2* text_ptr = text + text_pos;
5729 Py_UCS2* limit_ptr = text + limit;
5730
5731 while (text_ptr > limit_ptr) {
5732 if (text_ptr[-1] == check_char) {
5733 Py_ssize_t s_pos;
5734
5735 s_pos = 1;
5736
5737 for (;;) {
5738 if (s_pos >= length)
5739 /* End of search string. */
5740 return text_ptr - text;
5741
5742 if (text_ptr - s_pos <= limit_ptr) {
5743 /* Off the end of the text. */
5744 if (state->partial_side == RE_PARTIAL_LEFT) {
5745 /* Partial match. */
5746 *is_partial = TRUE;
5747 return text_ptr - text;
5748 }
5749
5750 return -1;
5751
5752 }
5753
5754 if (!same_char(text_ptr[- s_pos - 1], values[length - s_pos
5755 - 1]))
5756 break;
5757
5758 ++s_pos;
5759 }
5760 }
5761
5762 --text_ptr;
5763 }
5764 text_pos = text_ptr - text;
5765 break;
5766 }
5767 case 4:
5768 {
5769 Py_UCS4* text = (Py_UCS4*)state->text;
5770 Py_UCS4* text_ptr = text + text_pos;
5771 Py_UCS4* limit_ptr = text + limit;
5772
5773 while (text_ptr > limit_ptr) {
5774 if (text_ptr[-1] == check_char) {
5775 Py_ssize_t s_pos;
5776
5777 s_pos = 1;
5778
5779 for (;;) {
5780 if (s_pos >= length)
5781 /* End of search string. */
5782 return text_ptr - text;
5783
5784 if (text_ptr - s_pos <= limit_ptr) {
5785 /* Off the end of the text. */
5786 if (state->partial_side == RE_PARTIAL_LEFT) {
5787 /* Partial match. */
5788 *is_partial = TRUE;
5789 return text_ptr - text;
5790 }
5791
5792 return -1;
5793
5794 }
5795
5796 if (!same_char(text_ptr[- s_pos - 1], values[length - s_pos
5797 - 1]))
5798 break;
5799
5800 ++s_pos;
5801 }
5802 }
5803
5804 --text_ptr;
5805 }
5806 text_pos = text_ptr - text;
5807 break;
5808 }
5809 }
5810
5811 /* Off the end of the text. */
5812 if (state->partial_side == RE_PARTIAL_LEFT) {
5813 /* Partial match. */
5814 *is_partial = TRUE;
5815 return text_pos;
5816 }
5817
5818 return -1;
5819 }
5820
5821 /* Performs a Boyer-Moore fast string search. */
5822 Py_LOCAL_INLINE(Py_ssize_t) fast_string_search(RE_State* state, RE_Node* node,
5823 Py_ssize_t text_pos, Py_ssize_t limit) {
5824 void* text;
5825 Py_ssize_t length;
5826 RE_CODE* values;
5827 Py_ssize_t* bad_character_offset;
5828 Py_ssize_t* good_suffix_offset;
5829 Py_ssize_t last_pos;
5830 Py_UCS4 check_char;
5831
5832 text = state->text;
5833 length = (Py_ssize_t)node->value_count;
5834 values = node->values;
5835 good_suffix_offset = node->string.good_suffix_offset;
5836 bad_character_offset = node->string.bad_character_offset;
5837 last_pos = length - 1;
5838 check_char = values[last_pos];
5839 limit -= length;
5840
5841 switch (state->charsize) {
5842 case 1:
5843 {
5844 Py_UCS1* text_ptr;
5845 Py_UCS1* limit_ptr;
5846
5847 text_ptr = (Py_UCS1*)text + text_pos;
5848 limit_ptr = (Py_UCS1*)text + limit;
5849
5850 while (text_ptr <= limit_ptr) {
5851 Py_UCS4 ch;
5852
5853 ch = text_ptr[last_pos];
5854 if (ch == check_char) {
5855 Py_ssize_t pos;
5856
5857 pos = last_pos - 1;
5858 while (pos >= 0 && same_char(text_ptr[pos], values[pos]))
5859 --pos;
5860
5861 if (pos < 0)
5862 return text_ptr - (Py_UCS1*)text;
5863
5864 text_ptr += good_suffix_offset[pos];
5865 } else
5866 text_ptr += bad_character_offset[ch & 0xFF];
5867 }
5868 break;
5869 }
5870 case 2:
5871 {
5872 Py_UCS2* text_ptr;
5873 Py_UCS2* limit_ptr;
5874
5875 text_ptr = (Py_UCS2*)text + text_pos;
5876 limit_ptr = (Py_UCS2*)text + limit;
5877
5878 while (text_ptr <= limit_ptr) {
5879 Py_UCS4 ch;
5880
5881 ch = text_ptr[last_pos];
5882 if (ch == check_char) {
5883 Py_ssize_t pos;
5884
5885 pos = last_pos - 1;
5886 while (pos >= 0 && same_char(text_ptr[pos], values[pos]))
5887 --pos;
5888
5889 if (pos < 0)
5890 return text_ptr - (Py_UCS2*)text;
5891
5892 text_ptr += good_suffix_offset[pos];
5893 } else
5894 text_ptr += bad_character_offset[ch & 0xFF];
5895 }
5896 break;
5897 }
5898 case 4:
5899 {
5900 Py_UCS4* text_ptr;
5901 Py_UCS4* limit_ptr;
5902
5903 text_ptr = (Py_UCS4*)text + text_pos;
5904 limit_ptr = (Py_UCS4*)text + limit;
5905
5906 while (text_ptr <= limit_ptr) {
5907 Py_UCS4 ch;
5908
5909 ch = text_ptr[last_pos];
5910 if (ch == check_char) {
5911 Py_ssize_t pos;
5912
5913 pos = last_pos - 1;
5914 while (pos >= 0 && same_char(text_ptr[pos], values[pos]))
5915 --pos;
5916
5917 if (pos < 0)
5918 return text_ptr - (Py_UCS4*)text;
5919
5920 text_ptr += good_suffix_offset[pos];
5921 } else
5922 text_ptr += bad_character_offset[ch & 0xFF];
5923 }
5924 break;
5925 }
5926 }
5927
5928 return -1;
5929 }
5930
5931 /* Performs a Boyer-Moore fast string search, ignoring case. */
5932 Py_LOCAL_INLINE(Py_ssize_t) fast_string_search_ign(RE_State* state, RE_Node*
5933 node, Py_ssize_t text_pos, Py_ssize_t limit) {
5934 RE_EncodingTable* encoding;
5935 RE_LocaleInfo* locale_info;
5936 void* text;
5937 Py_ssize_t length;
5938 RE_CODE* values;
5939 Py_ssize_t* bad_character_offset;
5940 Py_ssize_t* good_suffix_offset;
5941 Py_ssize_t last_pos;
5942 Py_UCS4 cases[RE_MAX_CASES];
5943 int case_count;
5944
5945 encoding = state->encoding;
5946 locale_info = state->locale_info;
5947 text = state->text;
5948 length = (Py_ssize_t)node->value_count;
5949 values = node->values;
5950 good_suffix_offset = node->string.good_suffix_offset;
5951 bad_character_offset = node->string.bad_character_offset;
5952 last_pos = length - 1;
5953 case_count = encoding->all_cases(locale_info, values[last_pos], cases);
5954 limit -= length;
5955
5956 switch (state->charsize) {
5957 case 1:
5958 {
5959 Py_UCS1* text_ptr;
5960 Py_UCS1* limit_ptr;
5961
5962 text_ptr = (Py_UCS1*)text + text_pos;
5963 limit_ptr = (Py_UCS1*)text + limit;
5964
5965 while (text_ptr <= limit_ptr) {
5966 Py_UCS4 ch;
5967
5968 ch = text_ptr[last_pos];
5969 if (any_case(ch, case_count, cases)) {
5970 Py_ssize_t pos;
5971
5972 pos = last_pos - 1;
5973 while (pos >= 0 && same_char_ign(encoding, locale_info,
5974 text_ptr[pos], values[pos]))
5975 --pos;
5976
5977 if (pos < 0)
5978 return text_ptr - (Py_UCS1*)text;
5979
5980 text_ptr += good_suffix_offset[pos];
5981 } else
5982 text_ptr += bad_character_offset[ch & 0xFF];
5983 }
5984 break;
5985 }
5986 case 2:
5987 {
5988 Py_UCS2* text_ptr;
5989 Py_UCS2* limit_ptr;
5990
5991 text_ptr = (Py_UCS2*)text + text_pos;
5992 limit_ptr = (Py_UCS2*)text + limit;
5993
5994 while (text_ptr <= limit_ptr) {
5995 Py_UCS4 ch;
5996
5997 ch = text_ptr[last_pos];
5998 if (any_case(ch, case_count, cases)) {
5999 Py_ssize_t pos;
6000
6001 pos = last_pos - 1;
6002 while (pos >= 0 && same_char_ign(encoding, locale_info,
6003 text_ptr[pos], values[pos]))
6004 --pos;
6005
6006 if (pos < 0)
6007 return text_ptr - (Py_UCS2*)text;
6008
6009 text_ptr += good_suffix_offset[pos];
6010 } else
6011 text_ptr += bad_character_offset[ch & 0xFF];
6012 }
6013 break;
6014 }
6015 case 4:
6016 {
6017 Py_UCS4* text_ptr;
6018 Py_UCS4* limit_ptr;
6019
6020 text_ptr = (Py_UCS4*)text + text_pos;
6021 limit_ptr = (Py_UCS4*)text + limit;
6022
6023 while (text_ptr <= limit_ptr) {
6024 Py_UCS4 ch;
6025
6026 ch = text_ptr[last_pos];
6027 if (any_case(ch, case_count, cases)) {
6028 Py_ssize_t pos;
6029
6030 pos = last_pos - 1;
6031 while (pos >= 0 && same_char_ign(encoding, locale_info,
6032 text_ptr[pos], values[pos]))
6033 --pos;
6034
6035 if (pos < 0)
6036 return text_ptr - (Py_UCS4*)text;
6037
6038 text_ptr += good_suffix_offset[pos];
6039 } else
6040 text_ptr += bad_character_offset[ch & 0xFF];
6041 }
6042 break;
6043 }
6044 }
6045
6046 return -1;
6047 }
6048
6049 /* Performs a Boyer-Moore fast string search, backwards, ignoring case. */
6050 Py_LOCAL_INLINE(Py_ssize_t) fast_string_search_ign_rev(RE_State* state,
6051 RE_Node* node, Py_ssize_t text_pos, Py_ssize_t limit) {
6052 RE_EncodingTable* encoding;
6053 RE_LocaleInfo* locale_info;
6054 void* text;
6055 Py_ssize_t length;
6056 RE_CODE* values;
6057 Py_ssize_t* bad_character_offset;
6058 Py_ssize_t* good_suffix_offset;
6059 Py_UCS4 cases[RE_MAX_CASES];
6060 int case_count;
6061
6062 encoding = state->encoding;
6063 locale_info = state->locale_info;
6064 text = state->text;
6065 length = (Py_ssize_t)node->value_count;
6066 values = node->values;
6067 good_suffix_offset = node->string.good_suffix_offset;
6068 bad_character_offset = node->string.bad_character_offset;
6069 case_count = encoding->all_cases(locale_info, values[0], cases);
6070 text_pos -= length;
6071
6072 switch (state->charsize) {
6073 case 1:
6074 {
6075 Py_UCS1* text_ptr;
6076 Py_UCS1* limit_ptr;
6077
6078 text_ptr = (Py_UCS1*)text + text_pos;
6079 limit_ptr = (Py_UCS1*)text + limit;
6080
6081 while (text_ptr >= limit_ptr) {
6082 Py_UCS4 ch;
6083
6084 ch = text_ptr[0];
6085 if (any_case(ch, case_count, cases)) {
6086 Py_ssize_t pos;
6087
6088 pos = 1;
6089 while (pos < length && same_char_ign(encoding, locale_info,
6090 text_ptr[pos], values[pos]))
6091 ++pos;
6092
6093 if (pos >= length)
6094 return text_ptr - (Py_UCS1*)text + length;
6095
6096 text_ptr += good_suffix_offset[pos];
6097 } else
6098 text_ptr += bad_character_offset[ch & 0xFF];
6099 }
6100 break;
6101 }
6102 case 2:
6103 {
6104 Py_UCS2* text_ptr;
6105 Py_UCS2* limit_ptr;
6106
6107 text_ptr = (Py_UCS2*)text + text_pos;
6108 limit_ptr = (Py_UCS2*)text + limit;
6109
6110 while (text_ptr >= limit_ptr) {
6111 Py_UCS4 ch;
6112
6113 ch = text_ptr[0];
6114 if (any_case(ch, case_count, cases)) {
6115 Py_ssize_t pos;
6116
6117 pos = 1;
6118 while (pos < length && same_char_ign(encoding, locale_info,
6119 text_ptr[pos], values[pos]))
6120 ++pos;
6121
6122 if (pos >= length)
6123 return text_ptr - (Py_UCS2*)text + length;
6124
6125 text_ptr += good_suffix_offset[pos];
6126 } else
6127 text_ptr += bad_character_offset[ch & 0xFF];
6128 }
6129 break;
6130 }
6131 case 4:
6132 {
6133 Py_UCS4* text_ptr;
6134 Py_UCS4* limit_ptr;
6135
6136 text_ptr = (Py_UCS4*)text + text_pos;
6137 limit_ptr = (Py_UCS4*)text + limit;
6138
6139 while (text_ptr >= limit_ptr) {
6140 Py_UCS4 ch;
6141
6142 ch = text_ptr[0];
6143 if (any_case(ch, case_count, cases)) {
6144 Py_ssize_t pos;
6145
6146 pos = 1;
6147 while (pos < length && same_char_ign(encoding, locale_info,
6148 text_ptr[pos], values[pos]))
6149 ++pos;
6150
6151 if (pos >= length)
6152 return text_ptr - (Py_UCS4*)text + length;
6153
6154 text_ptr += good_suffix_offset[pos];
6155 } else
6156 text_ptr += bad_character_offset[ch & 0xFF];
6157 }
6158 break;
6159 }
6160 }
6161
6162 return -1;
6163 }
6164
6165 /* Performs a Boyer-Moore fast string search, backwards. */
6166 Py_LOCAL_INLINE(Py_ssize_t) fast_string_search_rev(RE_State* state, RE_Node*
6167 node, Py_ssize_t text_pos, Py_ssize_t limit) {
6168 void* text;
6169 Py_ssize_t length;
6170 RE_CODE* values;
6171 Py_ssize_t* bad_character_offset;
6172 Py_ssize_t* good_suffix_offset;
6173 Py_UCS4 check_char;
6174
6175 text = state->text;
6176 length = (Py_ssize_t)node->value_count;
6177 values = node->values;
6178 good_suffix_offset = node->string.good_suffix_offset;
6179 bad_character_offset = node->string.bad_character_offset;
6180 check_char = values[0];
6181 text_pos -= length;
6182
6183 switch (state->charsize) {
6184 case 1:
6185 {
6186 Py_UCS1* text_ptr;
6187 Py_UCS1* limit_ptr;
6188
6189 text_ptr = (Py_UCS1*)text + text_pos;
6190 limit_ptr = (Py_UCS1*)text + limit;
6191
6192 while (text_ptr >= limit_ptr) {
6193 Py_UCS4 ch;
6194
6195 ch = text_ptr[0];
6196 if (ch == check_char) {
6197 Py_ssize_t pos;
6198
6199 pos = 1;
6200 while (pos < length && same_char(text_ptr[pos], values[pos]))
6201 ++pos;
6202
6203 if (pos >= length)
6204 return text_ptr - (Py_UCS1*)text + length;
6205
6206 text_ptr += good_suffix_offset[pos];
6207 } else
6208 text_ptr += bad_character_offset[ch & 0xFF];
6209 }
6210 break;
6211 }
6212 case 2:
6213 {
6214 Py_UCS2* text_ptr;
6215 Py_UCS2* limit_ptr;
6216
6217 text_ptr = (Py_UCS2*)text + text_pos;
6218 limit_ptr = (Py_UCS2*)text + limit;
6219
6220 while (text_ptr >= limit_ptr) {
6221 Py_UCS4 ch;
6222
6223 ch = text_ptr[0];
6224 if (ch == check_char) {
6225 Py_ssize_t pos;
6226
6227 pos = 1;
6228 while (pos < length && same_char(text_ptr[pos], values[pos]))
6229 ++pos;
6230
6231 if (pos >= length)
6232 return text_ptr - (Py_UCS2*)text + length;
6233
6234 text_ptr += good_suffix_offset[pos];
6235 } else
6236 text_ptr += bad_character_offset[ch & 0xFF];
6237 }
6238 break;
6239 }
6240 case 4:
6241 {
6242 Py_UCS4* text_ptr;
6243 Py_UCS4* limit_ptr;
6244
6245 text_ptr = (Py_UCS4*)text + text_pos;
6246 limit_ptr = (Py_UCS4*)text + limit;
6247
6248 while (text_ptr >= limit_ptr) {
6249 Py_UCS4 ch;
6250
6251 ch = text_ptr[0];
6252 if (ch == check_char) {
6253 Py_ssize_t pos;
6254
6255 pos = 1;
6256 while (pos < length && same_char(text_ptr[pos], values[pos]))
6257 ++pos;
6258
6259 if (pos >= length)
6260 return text_ptr - (Py_UCS4*)text + length;
6261
6262 text_ptr += good_suffix_offset[pos];
6263 } else
6264 text_ptr += bad_character_offset[ch & 0xFF];
6265 }
6266 break;
6267 }
6268 }
6269
6270 return -1;
6271 }
6272
6273 /* Builds the tables for a Boyer-Moore fast string search. */
6274 Py_LOCAL_INLINE(BOOL) build_fast_tables(RE_State* state, RE_Node* node, BOOL
6275 ignore) {
6276 Py_ssize_t length;
6277 RE_CODE* values;
6278 Py_ssize_t* bad;
6279 Py_ssize_t* good;
6280 Py_UCS4 ch;
6281 Py_ssize_t last_pos;
6282 Py_ssize_t pos;
6283 BOOL (*is_same_char)(RE_EncodingTable* encoding, RE_LocaleInfo*
6284 locale_info, Py_UCS4 ch1, Py_UCS4 ch2);
6285 Py_ssize_t suffix_len;
6286 BOOL saved_start;
6287 Py_ssize_t s;
6288 Py_ssize_t i;
6289 Py_ssize_t s_start;
6290 Py_UCS4 codepoints[RE_MAX_CASES];
6291
6292 length = (Py_ssize_t)node->value_count;
6293
6294 if (length < RE_MIN_FAST_LENGTH)
6295 return TRUE;
6296
6297 values = node->values;
6298 bad = (Py_ssize_t*)re_alloc(256 * sizeof(bad[0]));
6299 good = (Py_ssize_t*)re_alloc((size_t)length * sizeof(good[0]));
6300
6301 if (!bad || !good) {
6302 re_dealloc(bad);
6303 re_dealloc(good);
6304
6305 return FALSE;
6306 }
6307
6308 for (ch = 0; ch < 0x100; ch++)
6309 bad[ch] = length;
6310
6311 last_pos = length - 1;
6312
6313 for (pos = 0; pos < last_pos; pos++) {
6314 Py_ssize_t offset;
6315
6316 offset = last_pos - pos;
6317 ch = values[pos];
6318 if (ignore) {
6319 int count;
6320 int c;
6321
6322 count = state->encoding->all_cases(state->locale_info, ch,
6323 codepoints);
6324
6325 for (c = 0; c < count; c++)
6326 bad[codepoints[c] & 0xFF] = offset;
6327 } else
6328 bad[ch & 0xFF] = offset;
6329 }
6330
6331 is_same_char = ignore ? same_char_ign_wrapper : same_char_wrapper;
6332
6333 suffix_len = 2;
6334 pos = length - suffix_len;
6335 saved_start = FALSE;
6336 s = pos - 1;
6337 i = suffix_len - 1;
6338 s_start = s;
6339
6340 while (pos >= 0) {
6341 /* Look for another occurrence of the suffix. */
6342 while (i > 0) {
6343 /* Have we dropped off the end of the string? */
6344 if (s + i < 0)
6345 break;
6346
6347 if (is_same_char(state->encoding, state->locale_info, values[s +
6348 i], values[pos + i]))
6349 /* It still matches. */
6350 --i;
6351 else {
6352 /* Start again further along. */
6353 --s;
6354 i = suffix_len - 1;
6355 }
6356 }
6357
6358 if (s >= 0 && is_same_char(state->encoding, state->locale_info,
6359 values[s], values[pos])) {
6360 /* We haven't dropped off the end of the string, and the suffix has
6361 * matched this far, so this is a good starting point for the next
6362 * iteration.
6363 */
6364 --s;
6365 if (!saved_start) {
6366 s_start = s;
6367 saved_start = TRUE;
6368 }
6369 } else {
6370 /* Calculate the suffix offset. */
6371 good[pos] = pos - s;
6372
6373 /* Extend the suffix and start searching for _this_ one. */
6374 --pos;
6375 ++suffix_len;
6376
6377 /* Where's a good place to start searching? */
6378 if (saved_start) {
6379 s = s_start;
6380 saved_start = FALSE;
6381 } else
6382 --s;
6383
6384 /* Can we short-circuit the searching? */
6385 if (s < 0)
6386 break;
6387 }
6388
6389 i = suffix_len - 1;
6390 }
6391
6392 /* Fill-in any remaining entries. */
6393 while (pos >= 0) {
6394 good[pos] = pos - s;
6395 --pos;
6396 --s;
6397 }
6398
6399 node->string.bad_character_offset = bad;
6400 node->string.good_suffix_offset = good;
6401
6402 return TRUE;
6403 }
6404
6405 /* Builds the tables for a Boyer-Moore fast string search, backwards. */
6406 Py_LOCAL_INLINE(BOOL) build_fast_tables_rev(RE_State* state, RE_Node* node,
6407 BOOL ignore) {
6408 Py_ssize_t length;
6409 RE_CODE* values;
6410 Py_ssize_t* bad;
6411 Py_ssize_t* good;
6412 Py_UCS4 ch;
6413 Py_ssize_t last_pos;
6414 Py_ssize_t pos;
6415 BOOL (*is_same_char)(RE_EncodingTable* encoding, RE_LocaleInfo*
6416 locale_info, Py_UCS4 ch1, Py_UCS4 ch2);
6417 Py_ssize_t suffix_len;
6418 BOOL saved_start;
6419 Py_ssize_t s;
6420 Py_ssize_t i;
6421 Py_ssize_t s_start;
6422 Py_UCS4 codepoints[RE_MAX_CASES];
6423
6424 length = (Py_ssize_t)node->value_count;
6425
6426 if (length < RE_MIN_FAST_LENGTH)
6427 return TRUE;
6428
6429 values = node->values;
6430 bad = (Py_ssize_t*)re_alloc(256 * sizeof(bad[0]));
6431 good = (Py_ssize_t*)re_alloc((size_t)length * sizeof(good[0]));
6432
6433 if (!bad || !good) {
6434 re_dealloc(bad);
6435 re_dealloc(good);
6436
6437 return FALSE;
6438 }
6439
6440 for (ch = 0; ch < 0x100; ch++)
6441 bad[ch] = -length;
6442
6443 last_pos = length - 1;
6444
6445 for (pos = last_pos; pos > 0; pos--) {
6446 Py_ssize_t offset;
6447
6448 offset = -pos;
6449 ch = values[pos];
6450 if (ignore) {
6451 int count;
6452 int c;
6453
6454 count = state->encoding->all_cases(state->locale_info, ch,
6455 codepoints);
6456
6457 for (c = 0; c < count; c++)
6458 bad[codepoints[c] & 0xFF] = offset;
6459 } else
6460 bad[ch & 0xFF] = offset;
6461 }
6462
6463 is_same_char = ignore ? same_char_ign_wrapper : same_char_wrapper;
6464
6465 suffix_len = 2;
6466 pos = suffix_len - 1;
6467 saved_start = FALSE;
6468 s = pos + 1;
6469 i = suffix_len - 1;
6470 s_start = s;
6471
6472 while (pos < length) {
6473 /* Look for another occurrence of the suffix. */
6474 while (i > 0) {
6475 /* Have we dropped off the end of the string? */
6476 if (s - i >= length)
6477 break;
6478
6479 if (is_same_char(state->encoding, state->locale_info, values[s -
6480 i], values[pos - i]))
6481 /* It still matches. */
6482 --i;
6483 else {
6484 /* Start again further along. */
6485 ++s;
6486 i = suffix_len - 1;
6487 }
6488 }
6489
6490 if (s < length && is_same_char(state->encoding, state->locale_info,
6491 values[s], values[pos])) {
6492 /* We haven't dropped off the end of the string, and the suffix has
6493 * matched this far, so this is a good starting point for the next
6494 * iteration.
6495 */
6496 ++s;
6497 if (!saved_start) {
6498 s_start = s;
6499 saved_start = TRUE;
6500 }
6501 } else {
6502 /* Calculate the suffix offset. */
6503 good[pos] = pos - s;
6504
6505 /* Extend the suffix and start searching for _this_ one. */
6506 ++pos;
6507 ++suffix_len;
6508
6509 /* Where's a good place to start searching? */
6510 if (saved_start) {
6511 s = s_start;
6512 saved_start = FALSE;
6513 } else
6514 ++s;
6515
6516 /* Can we short-circuit the searching? */
6517 if (s >= length)
6518 break;
6519 }
6520
6521 i = suffix_len - 1;
6522 }
6523
6524 /* Fill-in any remaining entries. */
6525 while (pos < length) {
6526 good[pos] = pos - s;
6527 ++pos;
6528 ++s;
6529 }
6530
6531 node->string.bad_character_offset = bad;
6532 node->string.good_suffix_offset = good;
6533
6534 return TRUE;
6535 }
6536
6537 /* Performs a string search. */
6538 Py_LOCAL_INLINE(Py_ssize_t) string_search(RE_State* state, RE_Node* node,
6539 Py_ssize_t text_pos, Py_ssize_t limit, BOOL try_fast, BOOL* is_partial) {
6540 Py_ssize_t found_pos;
6541
6542 *is_partial = FALSE;
6543
6544 /* Has the node been initialised for fast searching, if necessary? */
6545 if (try_fast && !(node->status & RE_STATUS_FAST_INIT)) {
6546 /* Ideally the pattern should immutable and shareable across threads.
6547 * Internally, however, it isn't. For safety we need to hold the GIL.
6548 */
6549 acquire_GIL(state);
6550
6551 /* Double-check because of multithreading. */
6552 if (!(node->status & RE_STATUS_FAST_INIT)) {
6553 build_fast_tables(state, node, FALSE);
6554 node->status |= RE_STATUS_FAST_INIT;
6555 }
6556
6557 release_GIL(state);
6558 }
6559
6560 if (try_fast && node->string.bad_character_offset) {
6561 /* Start with a fast search. This will find the string if it's complete
6562 * (i.e. not truncated).
6563 */
6564 found_pos = fast_string_search(state, node, text_pos, limit);
6565 if (found_pos < 0 && state->partial_side == RE_PARTIAL_RIGHT)
6566 /* We didn't find the string, but it could've been truncated, so
6567 * try again, starting close to the end.
6568 */
6569 found_pos = simple_string_search(state, node, limit -
6570 (Py_ssize_t)(node->value_count - 1), limit, is_partial);
6571 } else
6572 found_pos = simple_string_search(state, node, text_pos, limit,
6573 is_partial);
6574
6575 return found_pos;
6576 }
6577
6578 /* Performs a string search, ignoring case. */
6579 Py_LOCAL_INLINE(Py_ssize_t) string_search_fld(RE_State* state, RE_Node* node,
6580 Py_ssize_t text_pos, Py_ssize_t limit, Py_ssize_t* new_pos, BOOL* is_partial)
6581 {
6582 RE_EncodingTable* encoding;
6583 RE_LocaleInfo* locale_info;
6584 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
6585 folded);
6586 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
6587 void* text;
6588 RE_CODE* values;
6589 Py_ssize_t start_pos;
6590 int f_pos;
6591 int folded_len;
6592 Py_ssize_t length;
6593 Py_ssize_t s_pos;
6594 Py_UCS4 folded[RE_MAX_FOLDED];
6595
6596 encoding = state->encoding;
6597 locale_info = state->locale_info;
6598 full_case_fold = encoding->full_case_fold;
6599 char_at = state->char_at;
6600 text = state->text;
6601
6602 values = node->values;
6603 start_pos = text_pos;
6604 f_pos = 0;
6605 folded_len = 0;
6606 length = (Py_ssize_t)node->value_count;
6607 s_pos = 0;
6608
6609 *is_partial = FALSE;
6610
6611 while (s_pos < length || f_pos < folded_len) {
6612 if (f_pos >= folded_len) {
6613 /* Fetch and casefold another character. */
6614 if (text_pos >= limit) {
6615 if (text_pos >= state->text_end && state->partial_side ==
6616 RE_PARTIAL_RIGHT) {
6617 *is_partial = TRUE;
6618 return start_pos;
6619 }
6620
6621 return -1;
6622 }
6623
6624 folded_len = full_case_fold(locale_info, char_at(text, text_pos),
6625 folded);
6626 f_pos = 0;
6627 }
6628
6629 if (s_pos < length && same_char_ign_turkic(encoding, locale_info,
6630 values[s_pos], folded[f_pos])) {
6631 ++s_pos;
6632 ++f_pos;
6633
6634 if (f_pos >= folded_len)
6635 ++text_pos;
6636 } else {
6637 ++start_pos;
6638 text_pos = start_pos;
6639 f_pos = 0;
6640 folded_len = 0;
6641 s_pos = 0;
6642 }
6643 }
6644
6645 /* We found the string. */
6646 if (new_pos)
6647 *new_pos = text_pos;
6648
6649 return start_pos;
6650 }
6651
6652 /* Performs a string search, backwards, ignoring case. */
6653 Py_LOCAL_INLINE(Py_ssize_t) string_search_fld_rev(RE_State* state, RE_Node*
6654 node, Py_ssize_t text_pos, Py_ssize_t limit, Py_ssize_t* new_pos, BOOL*
6655 is_partial) {
6656 RE_EncodingTable* encoding;
6657 RE_LocaleInfo* locale_info;
6658 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
6659 folded);
6660 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
6661 void* text;
6662 RE_CODE* values;
6663 Py_ssize_t start_pos;
6664 int f_pos;
6665 int folded_len;
6666 Py_ssize_t length;
6667 Py_ssize_t s_pos;
6668 Py_UCS4 folded[RE_MAX_FOLDED];
6669
6670 encoding = state->encoding;
6671 locale_info = state->locale_info;
6672 full_case_fold = encoding->full_case_fold;
6673 char_at = state->char_at;
6674 text = state->text;
6675
6676 values = node->values;
6677 start_pos = text_pos;
6678 f_pos = 0;
6679 folded_len = 0;
6680 length = (Py_ssize_t)node->value_count;
6681 s_pos = 0;
6682
6683 *is_partial = FALSE;
6684
6685 while (s_pos < length || f_pos < folded_len) {
6686 if (f_pos >= folded_len) {
6687 /* Fetch and casefold another character. */
6688 if (text_pos <= limit) {
6689 if (text_pos <= state->text_start && state->partial_side == RE_PARTIAL_LEFT) {
6690 *is_partial = TRUE;
6691 return start_pos;
6692 }
6693
6694 return -1;
6695 }
6696
6697 folded_len = full_case_fold(locale_info, char_at(text, text_pos -
6698 1), folded);
6699 f_pos = 0;
6700 }
6701
6702 if (s_pos < length && same_char_ign_turkic(encoding, locale_info,
6703 values[length - s_pos - 1], folded[folded_len - f_pos - 1])) {
6704 ++s_pos;
6705 ++f_pos;
6706
6707 if (f_pos >= folded_len)
6708 --text_pos;
6709 } else {
6710 --start_pos;
6711 text_pos = start_pos;
6712 f_pos = 0;
6713 folded_len = 0;
6714 s_pos = 0;
6715 }
6716 }
6717
6718 /* We found the string. */
6719 if (new_pos)
6720 *new_pos = text_pos;
6721
6722 return start_pos;
6723 }
6724
6725 /* Performs a string search, ignoring case. */
6726 Py_LOCAL_INLINE(Py_ssize_t) string_search_ign(RE_State* state, RE_Node* node,
6727 Py_ssize_t text_pos, Py_ssize_t limit, BOOL try_fast, BOOL* is_partial) {
6728 Py_ssize_t found_pos;
6729
6730 *is_partial = FALSE;
6731
6732 /* Has the node been initialised for fast searching, if necessary? */
6733 if (try_fast && !(node->status & RE_STATUS_FAST_INIT)) {
6734 /* Ideally the pattern should immutable and shareable across threads.
6735 * Internally, however, it isn't. For safety we need to hold the GIL.
6736 */
6737 acquire_GIL(state);
6738
6739 /* Double-check because of multithreading. */
6740 if (!(node->status & RE_STATUS_FAST_INIT)) {
6741 build_fast_tables(state, node, TRUE);
6742 node->status |= RE_STATUS_FAST_INIT;
6743 }
6744
6745 release_GIL(state);
6746 }
6747
6748 if (try_fast && node->string.bad_character_offset) {
6749 /* Start with a fast search. This will find the string if it's complete
6750 * (i.e. not truncated).
6751 */
6752 found_pos = fast_string_search_ign(state, node, text_pos, limit);
6753 if (found_pos < 0 && state->partial_side == RE_PARTIAL_RIGHT)
6754 /* We didn't find the string, but it could've been truncated, so
6755 * try again, starting close to the end.
6756 */
6757 found_pos = simple_string_search_ign(state, node, limit -
6758 (Py_ssize_t)(node->value_count - 1), limit, is_partial);
6759 } else
6760 found_pos = simple_string_search_ign(state, node, text_pos, limit,
6761 is_partial);
6762
6763 return found_pos;
6764 }
6765
6766 /* Performs a string search, backwards, ignoring case. */
6767 Py_LOCAL_INLINE(Py_ssize_t) string_search_ign_rev(RE_State* state, RE_Node*
6768 node, Py_ssize_t text_pos, Py_ssize_t limit, BOOL try_fast, BOOL* is_partial)
6769 {
6770 Py_ssize_t found_pos;
6771
6772 *is_partial = FALSE;
6773
6774 /* Has the node been initialised for fast searching, if necessary? */
6775 if (try_fast && !(node->status & RE_STATUS_FAST_INIT)) {
6776 /* Ideally the pattern should immutable and shareable across threads.
6777 * Internally, however, it isn't. For safety we need to hold the GIL.
6778 */
6779 acquire_GIL(state);
6780
6781 /* Double-check because of multithreading. */
6782 if (!(node->status & RE_STATUS_FAST_INIT)) {
6783 build_fast_tables_rev(state, node, TRUE);
6784 node->status |= RE_STATUS_FAST_INIT;
6785 }
6786
6787 release_GIL(state);
6788 }
6789
6790 if (try_fast && node->string.bad_character_offset) {
6791 /* Start with a fast search. This will find the string if it's complete
6792 * (i.e. not truncated).
6793 */
6794 found_pos = fast_string_search_ign_rev(state, node, text_pos, limit);
6795 if (found_pos < 0 && state->partial_side == RE_PARTIAL_LEFT)
6796 /* We didn't find the string, but it could've been truncated, so
6797 * try again, starting close to the end.
6798 */
6799 found_pos = simple_string_search_ign_rev(state, node, limit +
6800 (Py_ssize_t)(node->value_count - 1), limit, is_partial);
6801 } else
6802 found_pos = simple_string_search_ign_rev(state, node, text_pos, limit,
6803 is_partial);
6804
6805 return found_pos;
6806 }
6807
6808 /* Performs a string search, backwards. */
6809 Py_LOCAL_INLINE(Py_ssize_t) string_search_rev(RE_State* state, RE_Node* node,
6810 Py_ssize_t text_pos, Py_ssize_t limit, BOOL try_fast, BOOL* is_partial) {
6811 Py_ssize_t found_pos;
6812
6813 *is_partial = FALSE;
6814
6815 /* Has the node been initialised for fast searching, if necessary? */
6816 if (try_fast && !(node->status & RE_STATUS_FAST_INIT)) {
6817 /* Ideally the pattern should immutable and shareable across threads.
6818 * Internally, however, it isn't. For safety we need to hold the GIL.
6819 */
6820 acquire_GIL(state);
6821
6822 /* Double-check because of multithreading. */
6823 if (!(node->status & RE_STATUS_FAST_INIT)) {
6824 build_fast_tables_rev(state, node, FALSE);
6825 node->status |= RE_STATUS_FAST_INIT;
6826 }
6827
6828 release_GIL(state);
6829 }
6830
6831 if (try_fast && node->string.bad_character_offset) {
6832 /* Start with a fast search. This will find the string if it's complete
6833 * (i.e. not truncated).
6834 */
6835 found_pos = fast_string_search_rev(state, node, text_pos, limit);
6836 if (found_pos < 0 && state->partial_side == RE_PARTIAL_LEFT)
6837 /* We didn't find the string, but it could've been truncated, so
6838 * try again, starting close to the end.
6839 */
6840 found_pos = simple_string_search_rev(state, node, limit +
6841 (Py_ssize_t)(node->value_count - 1), limit, is_partial);
6842 } else
6843 found_pos = simple_string_search_rev(state, node, text_pos, limit,
6844 is_partial);
6845
6846 return found_pos;
6847 }
6848
6849 /* Returns how many characters there could be before full case-folding. */
6850 Py_LOCAL_INLINE(Py_ssize_t) possible_unfolded_length(Py_ssize_t length) {
6851 if (length == 0)
6852 return 0;
6853
6854 if (length < RE_MAX_FOLDED)
6855 return 1;
6856
6857 return length / RE_MAX_FOLDED;
6858 }
6859
6860 /* Checks whether there's any character except a newline at a position. */
6861 Py_LOCAL_INLINE(int) try_match_ANY(RE_State* state, RE_Node* node, Py_ssize_t
6862 text_pos) {
6863 if (text_pos >= state->text_end) {
6864 if (state->partial_side == RE_PARTIAL_RIGHT)
6865 return RE_ERROR_PARTIAL;
6866
6867 return RE_ERROR_FAILURE;
6868 }
6869
6870 return bool_as_status(text_pos < state->slice_end &&
6871 matches_ANY(state->encoding, node, state->char_at(state->text,
6872 text_pos)));
6873 }
6874
6875 /* Checks whether there's any character at all at a position. */
6876 Py_LOCAL_INLINE(int) try_match_ANY_ALL(RE_State* state, RE_Node* node,
6877 Py_ssize_t text_pos) {
6878 if (text_pos >= state->text_end) {
6879 if (state->partial_side == RE_PARTIAL_RIGHT)
6880 return RE_ERROR_PARTIAL;
6881
6882 return RE_ERROR_FAILURE;
6883 }
6884
6885 return bool_as_status(text_pos < state->slice_end);
6886 }
6887
6888 /* Checks whether there's any character at all at a position, backwards. */
6889 Py_LOCAL_INLINE(int) try_match_ANY_ALL_REV(RE_State* state, RE_Node* node,
6890 Py_ssize_t text_pos) {
6891 if (text_pos <= state->text_start) {
6892 if (state->partial_side == RE_PARTIAL_LEFT)
6893 return RE_ERROR_PARTIAL;
6894
6895 return RE_ERROR_FAILURE;
6896 }
6897
6898 return bool_as_status(text_pos > state->slice_start);
6899 }
6900
6901 /* Checks whether there's any character except a newline at a position,
6902 * backwards.
6903 */
6904 Py_LOCAL_INLINE(int) try_match_ANY_REV(RE_State* state, RE_Node* node,
6905 Py_ssize_t text_pos) {
6906 if (text_pos <= state->text_start) {
6907 if (state->partial_side == RE_PARTIAL_LEFT)
6908 return RE_ERROR_PARTIAL;
6909
6910 return RE_ERROR_FAILURE;
6911 }
6912
6913 return bool_as_status(text_pos > state->slice_start &&
6914 matches_ANY(state->encoding, node, state->char_at(state->text, text_pos -
6915 1)));
6916 }
6917
6918 /* Checks whether there's any character except a line separator at a position.
6919 */
6920 Py_LOCAL_INLINE(int) try_match_ANY_U(RE_State* state, RE_Node* node, Py_ssize_t
6921 text_pos) {
6922 if (text_pos >= state->text_end) {
6923 if (state->partial_side == RE_PARTIAL_RIGHT)
6924 return RE_ERROR_PARTIAL;
6925
6926 return RE_ERROR_FAILURE;
6927 }
6928
6929 return bool_as_status(text_pos < state->slice_end &&
6930 matches_ANY_U(state->encoding, node, state->char_at(state->text,
6931 text_pos)));
6932 }
6933
6934 /* Checks whether there's any character except a line separator at a position,
6935 * backwards.
6936 */
6937 Py_LOCAL_INLINE(int) try_match_ANY_U_REV(RE_State* state, RE_Node* node,
6938 Py_ssize_t text_pos) {
6939 if (text_pos <= state->text_start) {
6940 if (state->partial_side == RE_PARTIAL_LEFT)
6941 return RE_ERROR_PARTIAL;
6942
6943 return RE_ERROR_FAILURE;
6944 }
6945
6946 return bool_as_status(text_pos > state->slice_start &&
6947 matches_ANY_U(state->encoding, node, state->char_at(state->text, text_pos
6948 - 1)));
6949 }
6950
6951 /* Checks whether a position is on a word boundary. */
6952 Py_LOCAL_INLINE(int) try_match_BOUNDARY(RE_State* state, RE_Node* node,
6953 Py_ssize_t text_pos) {
6954 switch (ENCODING_KIND(node)) {
6955 case ASCII_ENCODING:
6956 return bool_as_status(ascii_encoding.at_boundary(state, text_pos) ==
6957 node->match);
6958 case UNICODE_ENCODING:
6959 return bool_as_status(unicode_encoding.at_boundary(state, text_pos) ==
6960 node->match);
6961 default:
6962 return bool_as_status(state->encoding->at_boundary(state, text_pos) ==
6963 node->match);
6964 }
6965 }
6966
6967 /* Checks whether there's a character at a position. */
6968 Py_LOCAL_INLINE(int) try_match_CHARACTER(RE_State* state, RE_Node* node,
6969 Py_ssize_t text_pos) {
6970 if (text_pos >= state->text_end) {
6971 if (state->partial_side == RE_PARTIAL_RIGHT)
6972 return RE_ERROR_PARTIAL;
6973
6974 return RE_ERROR_FAILURE;
6975 }
6976
6977 return bool_as_status(text_pos < state->slice_end &&
6978 matches_CHARACTER(state->encoding, state->locale_info, node,
6979 state->char_at(state->text, text_pos)) == node->match);
6980 }
6981
6982 /* Checks whether there's a character at a position, ignoring case. */
6983 Py_LOCAL_INLINE(int) try_match_CHARACTER_IGN(RE_State* state, RE_Node* node,
6984 Py_ssize_t text_pos) {
6985 if (text_pos >= state->text_end) {
6986 if (state->partial_side == RE_PARTIAL_RIGHT)
6987 return RE_ERROR_PARTIAL;
6988
6989 return RE_ERROR_FAILURE;
6990 }
6991
6992 return bool_as_status(text_pos < state->slice_end &&
6993 matches_CHARACTER_IGN(state->encoding, state->locale_info, node,
6994 state->char_at(state->text, text_pos)) == node->match);
6995 }
6996
6997 /* Checks whether there's a character at a position, ignoring case, backwards.
6998 */
6999 Py_LOCAL_INLINE(int) try_match_CHARACTER_IGN_REV(RE_State* state, RE_Node*
7000 node, Py_ssize_t text_pos) {
7001 if (text_pos <= state->text_start) {
7002 if (state->partial_side == RE_PARTIAL_LEFT)
7003 return RE_ERROR_PARTIAL;
7004
7005 return RE_ERROR_FAILURE;
7006 }
7007
7008 return bool_as_status(text_pos > state->slice_start &&
7009 matches_CHARACTER_IGN(state->encoding, state->locale_info, node,
7010 state->char_at(state->text, text_pos - 1)) == node->match);
7011 }
7012
7013 /* Checks whether there's a character at a position, backwards. */
7014 Py_LOCAL_INLINE(int) try_match_CHARACTER_REV(RE_State* state, RE_Node* node,
7015 Py_ssize_t text_pos) {
7016 if (text_pos <= state->text_start) {
7017 if (state->partial_side == RE_PARTIAL_LEFT)
7018 return RE_ERROR_PARTIAL;
7019
7020 return RE_ERROR_FAILURE;
7021 }
7022
7023 return bool_as_status(text_pos > state->slice_start &&
7024 matches_CHARACTER(state->encoding, state->locale_info, node,
7025 state->char_at(state->text, text_pos - 1)) == node->match);
7026 }
7027
7028 /* Checks whether a position is on a default word boundary. */
7029 Py_LOCAL_INLINE(int) try_match_DEFAULT_BOUNDARY(RE_State* state, RE_Node* node,
7030 Py_ssize_t text_pos) {
7031 return bool_as_status(state->encoding->at_default_boundary(state, text_pos)
7032 == node->match);
7033 }
7034
7035 /* Checks whether a position is at the default end of a word. */
7036 Py_LOCAL_INLINE(int) try_match_DEFAULT_END_OF_WORD(RE_State* state, RE_Node*
7037 node, Py_ssize_t text_pos) {
7038 return bool_as_status(state->encoding->at_default_word_end(state,
7039 text_pos));
7040 }
7041
7042 /* Checks whether a position is at the default start of a word. */
7043 Py_LOCAL_INLINE(int) try_match_DEFAULT_START_OF_WORD(RE_State* state, RE_Node*
7044 node, Py_ssize_t text_pos) {
7045 return bool_as_status(state->encoding->at_default_word_start(state,
7046 text_pos));
7047 }
7048
7049 /* Checks whether a position is at the end of a line. */
7050 Py_LOCAL_INLINE(int) try_match_END_OF_LINE(RE_State* state, RE_Node* node,
7051 Py_ssize_t text_pos) {
7052 return bool_as_status(text_pos >= state->slice_end ||
7053 state->char_at(state->text, text_pos) == '\n');
7054 }
7055
7056 /* Checks whether a position is at the end of a line. */
7057 Py_LOCAL_INLINE(int) try_match_END_OF_LINE_U(RE_State* state, RE_Node* node,
7058 Py_ssize_t text_pos) {
7059 return bool_as_status(state->encoding->at_line_end(state, text_pos));
7060 }
7061
7062 /* Checks whether a position is at the end of the string. */
7063 Py_LOCAL_INLINE(int) try_match_END_OF_STRING(RE_State* state, RE_Node* node,
7064 Py_ssize_t text_pos) {
7065 return bool_as_status(text_pos >= state->text_end);
7066 }
7067
7068 /* Checks whether a position is at the end of a line or the string. */
7069 Py_LOCAL_INLINE(int) try_match_END_OF_STRING_LINE(RE_State* state, RE_Node*
7070 node, Py_ssize_t text_pos) {
7071 return bool_as_status(text_pos >= state->text_end || text_pos ==
7072 state->final_newline);
7073 }
7074
7075 /* Checks whether a position is at the end of the string. */
7076 Py_LOCAL_INLINE(int) try_match_END_OF_STRING_LINE_U(RE_State* state, RE_Node*
7077 node, Py_ssize_t text_pos) {
7078 return bool_as_status(text_pos >= state->text_end || text_pos ==
7079 state->final_line_sep);
7080 }
7081
7082 /* Checks whether a position is at the end of a word. */
7083 Py_LOCAL_INLINE(int) try_match_END_OF_WORD(RE_State* state, RE_Node* node,
7084 Py_ssize_t text_pos) {
7085 return bool_as_status(state->encoding->at_word_end(state, text_pos));
7086 }
7087
7088 /* Checks whether a position is on a grapheme boundary. */
7089 Py_LOCAL_INLINE(int) try_match_GRAPHEME_BOUNDARY(RE_State* state, RE_Node*
7090 node, Py_ssize_t text_pos) {
7091 return bool_as_status(state->encoding->at_grapheme_boundary(state,
7092 text_pos));
7093 }
7094
7095 /* Checks whether there's a character with a certain property at a position. */
7096 Py_LOCAL_INLINE(int) try_match_PROPERTY(RE_State* state, RE_Node* node,
7097 Py_ssize_t text_pos) {
7098 if (text_pos >= state->text_end) {
7099 if (state->partial_side == RE_PARTIAL_RIGHT)
7100 return RE_ERROR_PARTIAL;
7101
7102 return RE_ERROR_FAILURE;
7103 }
7104
7105 return bool_as_status(text_pos < state->slice_end &&
7106 matches_PROPERTY(state->encoding, state->locale_info, node,
7107 state->char_at(state->text, text_pos)) == node->match);
7108 }
7109
7110 /* Checks whether there's a character with a certain property at a position,
7111 * ignoring case.
7112 */
7113 Py_LOCAL_INLINE(int) try_match_PROPERTY_IGN(RE_State* state, RE_Node* node,
7114 Py_ssize_t text_pos) {
7115 if (text_pos >= state->text_end) {
7116 if (state->partial_side == RE_PARTIAL_RIGHT)
7117 return RE_ERROR_PARTIAL;
7118
7119 return RE_ERROR_FAILURE;
7120 }
7121
7122 return bool_as_status(text_pos < state->slice_end &&
7123 matches_PROPERTY_IGN(state->encoding, state->locale_info, node,
7124 state->char_at(state->text, text_pos)) == node->match);
7125 }
7126
7127 /* Checks whether there's a character with a certain property at a position,
7128 * ignoring case, backwards.
7129 */
7130 Py_LOCAL_INLINE(int) try_match_PROPERTY_IGN_REV(RE_State* state, RE_Node* node,
7131 Py_ssize_t text_pos) {
7132 if (text_pos <= state->text_start) {
7133 if (state->partial_side == RE_PARTIAL_LEFT)
7134 return RE_ERROR_PARTIAL;
7135
7136 return RE_ERROR_FAILURE;
7137 }
7138
7139 return bool_as_status(text_pos > state->slice_start &&
7140 matches_PROPERTY_IGN(state->encoding, state->locale_info, node,
7141 state->char_at(state->text, text_pos - 1)) == node->match);
7142 }
7143
7144 /* Checks whether there's a character with a certain property at a position,
7145 * backwards.
7146 */
7147 Py_LOCAL_INLINE(int) try_match_PROPERTY_REV(RE_State* state, RE_Node* node,
7148 Py_ssize_t text_pos) {
7149 if (text_pos <= state->text_start) {
7150 if (state->partial_side == RE_PARTIAL_LEFT)
7151 return RE_ERROR_PARTIAL;
7152
7153 return RE_ERROR_FAILURE;
7154 }
7155
7156 return bool_as_status(text_pos > state->slice_start &&
7157 matches_PROPERTY(state->encoding, state->locale_info, node,
7158 state->char_at(state->text, text_pos - 1)) == node->match);
7159 }
7160
7161 /* Checks whether there's a character in a certain range at a position. */
7162 Py_LOCAL_INLINE(int) try_match_RANGE(RE_State* state, RE_Node* node, Py_ssize_t
7163 text_pos) {
7164 if (text_pos >= state->text_end) {
7165 if (state->partial_side == RE_PARTIAL_RIGHT)
7166 return RE_ERROR_PARTIAL;
7167
7168 return RE_ERROR_FAILURE;
7169 }
7170
7171 return bool_as_status(text_pos < state->slice_end &&
7172 matches_RANGE(state->encoding, state->locale_info, node,
7173 state->char_at(state->text, text_pos)) == node->match);
7174 }
7175
7176 /* Checks whether there's a character in a certain range at a position,
7177 * ignoring case.
7178 */
7179 Py_LOCAL_INLINE(int) try_match_RANGE_IGN(RE_State* state, RE_Node* node,
7180 Py_ssize_t text_pos) {
7181 if (text_pos >= state->text_end) {
7182 if (state->partial_side == RE_PARTIAL_RIGHT)
7183 return RE_ERROR_PARTIAL;
7184
7185 return RE_ERROR_FAILURE;
7186 }
7187
7188 return bool_as_status(text_pos < state->slice_end &&
7189 matches_RANGE_IGN(state->encoding, state->locale_info, node,
7190 state->char_at(state->text, text_pos)) == node->match);
7191 }
7192
7193 /* Checks whether there's a character in a certain range at a position,
7194 * ignoring case, backwards.
7195 */
7196 Py_LOCAL_INLINE(int) try_match_RANGE_IGN_REV(RE_State* state, RE_Node* node,
7197 Py_ssize_t text_pos) {
7198 if (text_pos <= state->text_start) {
7199 if (state->partial_side == RE_PARTIAL_LEFT)
7200 return RE_ERROR_PARTIAL;
7201
7202 return RE_ERROR_FAILURE;
7203 }
7204
7205 return bool_as_status(text_pos > state->slice_start &&
7206 matches_RANGE_IGN(state->encoding, state->locale_info, node,
7207 state->char_at(state->text, text_pos - 1)) == node->match);
7208 }
7209
7210 /* Checks whether there's a character in a certain range at a position,
7211 * backwards.
7212 */
7213 Py_LOCAL_INLINE(int) try_match_RANGE_REV(RE_State* state, RE_Node* node,
7214 Py_ssize_t text_pos) {
7215 if (text_pos <= state->text_start) {
7216 if (state->partial_side == RE_PARTIAL_LEFT)
7217 return RE_ERROR_PARTIAL;
7218
7219 return RE_ERROR_FAILURE;
7220 }
7221
7222 return bool_as_status(text_pos > state->slice_start &&
7223 matches_RANGE(state->encoding, state->locale_info, node,
7224 state->char_at(state->text, text_pos - 1)) == node->match);
7225 }
7226
7227 /* Checks whether a position is at the search anchor. */
7228 Py_LOCAL_INLINE(int) try_match_SEARCH_ANCHOR(RE_State* state, RE_Node* node,
7229 Py_ssize_t text_pos) {
7230 return bool_as_status(text_pos == state->search_anchor);
7231 }
7232
7233 /* Checks whether there's a character in a certain set at a position. */
7234 Py_LOCAL_INLINE(int) try_match_SET(RE_State* state, RE_Node* node, Py_ssize_t
7235 text_pos) {
7236 if (text_pos >= state->text_end) {
7237 if (state->partial_side == RE_PARTIAL_RIGHT)
7238 return RE_ERROR_PARTIAL;
7239
7240 return RE_ERROR_FAILURE;
7241 }
7242
7243 return bool_as_status(text_pos < state->slice_end &&
7244 matches_SET(state->encoding, state->locale_info, node,
7245 state->char_at(state->text, text_pos)) == node->match);
7246 }
7247
7248 /* Checks whether there's a character in a certain set at a position, ignoring
7249 * case.
7250 */
7251 Py_LOCAL_INLINE(int) try_match_SET_IGN(RE_State* state, RE_Node* node,
7252 Py_ssize_t text_pos) {
7253 if (text_pos >= state->text_end) {
7254 if (state->partial_side == RE_PARTIAL_RIGHT)
7255 return RE_ERROR_PARTIAL;
7256
7257 return RE_ERROR_FAILURE;
7258 }
7259
7260 return bool_as_status(text_pos < state->slice_end &&
7261 matches_SET_IGN(state->encoding, state->locale_info, node,
7262 state->char_at(state->text, text_pos)) == node->match);
7263 }
7264
7265 /* Checks whether there's a character in a certain set at a position, ignoring
7266 * case, backwards.
7267 */
7268 Py_LOCAL_INLINE(int) try_match_SET_IGN_REV(RE_State* state, RE_Node* node,
7269 Py_ssize_t text_pos) {
7270 if (text_pos <= state->text_start) {
7271 if (state->partial_side == RE_PARTIAL_LEFT)
7272 return RE_ERROR_PARTIAL;
7273
7274 return RE_ERROR_FAILURE;
7275 }
7276
7277 return bool_as_status(text_pos > state->slice_start &&
7278 matches_SET_IGN(state->encoding, state->locale_info, node,
7279 state->char_at(state->text, text_pos - 1)) == node->match);
7280 }
7281
7282 /* Checks whether there's a character in a certain set at a position,
7283 * backwards.
7284 */
7285 Py_LOCAL_INLINE(int) try_match_SET_REV(RE_State* state, RE_Node* node,
7286 Py_ssize_t text_pos) {
7287 if (text_pos <= state->text_start) {
7288 if (state->partial_side == RE_PARTIAL_LEFT)
7289 return RE_ERROR_PARTIAL;
7290
7291 return RE_ERROR_FAILURE;
7292 }
7293
7294 return bool_as_status(text_pos > state->slice_start &&
7295 matches_SET(state->encoding, state->locale_info, node,
7296 state->char_at(state->text, text_pos - 1)) == node->match);
7297 }
7298
7299 /* Checks whether a position is at the start of a line. */
7300 Py_LOCAL_INLINE(int) try_match_START_OF_LINE(RE_State* state, RE_Node* node,
7301 Py_ssize_t text_pos) {
7302 return bool_as_status(text_pos <= state->text_start || state->char_at(state->text, text_pos
7303 - 1) == '\n');
7304 }
7305
7306 /* Checks whether a position is at the start of a line. */
7307 Py_LOCAL_INLINE(int) try_match_START_OF_LINE_U(RE_State* state, RE_Node* node,
7308 Py_ssize_t text_pos) {
7309 return bool_as_status(state->encoding->at_line_start(state, text_pos));
7310 }
7311
7312 /* Checks whether a position is at the start of the string. */
7313 Py_LOCAL_INLINE(int) try_match_START_OF_STRING(RE_State* state, RE_Node* node,
7314 Py_ssize_t text_pos) {
7315 return bool_as_status(text_pos <= state->text_start);
7316 }
7317
7318 /* Checks whether a position is at the start of a word. */
7319 Py_LOCAL_INLINE(int) try_match_START_OF_WORD(RE_State* state, RE_Node* node,
7320 Py_ssize_t text_pos) {
7321 return bool_as_status(state->encoding->at_word_start(state, text_pos));
7322 }
7323
7324 /* Checks whether there's a certain string at a position. */
7325 Py_LOCAL_INLINE(int) try_match_STRING(RE_State* state, RE_NextNode* next,
7326 RE_Node* node, Py_ssize_t text_pos, RE_Position* next_position) {
7327 Py_ssize_t length;
7328 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
7329 RE_CODE* values;
7330 Py_ssize_t s_pos;
7331
7332 length = (Py_ssize_t)node->value_count;
7333 char_at = state->char_at;
7334 values = node->values;
7335
7336 for (s_pos = 0; s_pos < length; s_pos++) {
7337 if (text_pos + s_pos >= state->slice_end) {
7338 if (state->partial_side == RE_PARTIAL_RIGHT) {
7339 next_position->text_pos = text_pos;
7340 return RE_ERROR_PARTIAL;
7341 }
7342
7343 return RE_ERROR_FAILURE;
7344 }
7345
7346 if (!same_char(char_at(state->text, text_pos + s_pos), values[s_pos]))
7347 return RE_ERROR_FAILURE;
7348 }
7349
7350 next_position->node = next->match_next;
7351 next_position->text_pos = text_pos + next->match_step;
7352
7353 return RE_ERROR_SUCCESS;
7354 }
7355
7356 /* Checks whether there's a certain string at a position, ignoring case. */
7357 Py_LOCAL_INLINE(int) try_match_STRING_FLD(RE_State* state, RE_NextNode* next,
7358 RE_Node* node, Py_ssize_t text_pos, RE_Position* next_position) {
7359 Py_ssize_t length;
7360 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
7361 RE_EncodingTable* encoding;
7362 RE_LocaleInfo* locale_info;
7363 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
7364 folded);
7365 Py_ssize_t s_pos;
7366 RE_CODE* values;
7367 int folded_len;
7368 int f_pos;
7369 Py_ssize_t start_pos;
7370 Py_UCS4 folded[RE_MAX_FOLDED];
7371
7372 length = (Py_ssize_t)node->value_count;
7373 char_at = state->char_at;
7374 encoding = state->encoding;
7375 locale_info = state->locale_info;
7376 full_case_fold = encoding->full_case_fold;
7377
7378 s_pos = 0;
7379 values = node->values;
7380 folded_len = 0;
7381 f_pos = 0;
7382 start_pos = text_pos;
7383
7384 while (s_pos < length) {
7385 if (f_pos >= folded_len) {
7386 /* Fetch and casefold another character. */
7387 if (text_pos >= state->slice_end) {
7388 if (state->partial_side == RE_PARTIAL_RIGHT) {
7389 if (next->match_step == 0)
7390 next_position->text_pos = start_pos;
7391 else
7392 next_position->text_pos = text_pos;
7393 return RE_ERROR_PARTIAL;
7394 }
7395
7396 return RE_ERROR_FAILURE;
7397 }
7398
7399 folded_len = full_case_fold(locale_info, char_at(state->text,
7400 text_pos), folded);
7401 f_pos = 0;
7402 }
7403
7404 if (!same_char_ign(encoding, locale_info, values[s_pos],
7405 folded[f_pos]))
7406 return RE_ERROR_FAILURE;
7407
7408 ++s_pos;
7409 ++f_pos;
7410
7411 if (f_pos >= folded_len)
7412 ++text_pos;
7413 }
7414
7415 if (f_pos < folded_len)
7416 return RE_ERROR_FAILURE;
7417
7418 next_position->node = next->match_next;
7419 if (next->match_step == 0)
7420 next_position->text_pos = start_pos;
7421 else
7422 next_position->text_pos = text_pos;
7423
7424 return RE_ERROR_SUCCESS;
7425 }
7426
7427 /* Checks whether there's a certain string at a position, ignoring case,
7428 * backwards.
7429 */
7430 Py_LOCAL_INLINE(int) try_match_STRING_FLD_REV(RE_State* state, RE_NextNode*
7431 next, RE_Node* node, Py_ssize_t text_pos, RE_Position* next_position) {
7432 Py_ssize_t length;
7433 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
7434 RE_EncodingTable* encoding;
7435 RE_LocaleInfo* locale_info;
7436 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
7437 folded);
7438 Py_ssize_t s_pos;
7439 RE_CODE* values;
7440 int folded_len;
7441 int f_pos;
7442 Py_ssize_t start_pos;
7443 Py_UCS4 folded[RE_MAX_FOLDED];
7444
7445 length = (Py_ssize_t)node->value_count;
7446 char_at = state->char_at;
7447 encoding = state->encoding;
7448 locale_info = state->locale_info;
7449 full_case_fold = encoding->full_case_fold;
7450
7451 s_pos = 0;
7452 values = node->values;
7453 folded_len = 0;
7454 f_pos = 0;
7455 start_pos = text_pos;
7456
7457 while (s_pos < length) {
7458 if (f_pos >= folded_len) {
7459 /* Fetch and casefold another character. */
7460 if (text_pos <= state->slice_start) {
7461 if (state->partial_side == RE_PARTIAL_LEFT) {
7462 if (next->match_step == 0)
7463 next_position->text_pos = start_pos;
7464 else
7465 next_position->text_pos = text_pos;
7466 return RE_ERROR_PARTIAL;
7467 }
7468
7469 return RE_ERROR_FAILURE;
7470 }
7471
7472 folded_len = full_case_fold(locale_info, char_at(state->text,
7473 text_pos - 1), folded);
7474 f_pos = 0;
7475 }
7476
7477 if (!same_char_ign(encoding, locale_info, values[length - s_pos - 1],
7478 folded[folded_len - f_pos - 1]))
7479 return RE_ERROR_FAILURE;
7480
7481 ++s_pos;
7482 ++f_pos;
7483
7484 if (f_pos >= folded_len)
7485 --text_pos;
7486 }
7487
7488 if (f_pos < folded_len)
7489 return RE_ERROR_FAILURE;
7490
7491 next_position->node = next->match_next;
7492 if (next->match_step == 0)
7493 next_position->text_pos = start_pos;
7494 else
7495 next_position->text_pos = text_pos;
7496
7497 return RE_ERROR_SUCCESS;
7498 }
7499
7500 /* Checks whether there's a certain string at a position, ignoring case. */
7501 Py_LOCAL_INLINE(int) try_match_STRING_IGN(RE_State* state, RE_NextNode* next,
7502 RE_Node* node, Py_ssize_t text_pos, RE_Position* next_position) {
7503 Py_ssize_t length;
7504 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
7505 RE_EncodingTable* encoding;
7506 RE_LocaleInfo* locale_info;
7507 RE_CODE* values;
7508 Py_ssize_t s_pos;
7509
7510 length = (Py_ssize_t)node->value_count;
7511 char_at = state->char_at;
7512 encoding = state->encoding;
7513 locale_info = state->locale_info;
7514 values = node->values;
7515
7516 for (s_pos = 0; s_pos < length; s_pos++) {
7517 if (text_pos + s_pos >= state->slice_end) {
7518 if (state->partial_side == RE_PARTIAL_RIGHT) {
7519 next_position->text_pos = text_pos;
7520 return RE_ERROR_PARTIAL;
7521 }
7522
7523 return RE_ERROR_FAILURE;
7524 }
7525
7526 if (!same_char_ign(encoding, locale_info, char_at(state->text, text_pos
7527 + s_pos), values[s_pos]))
7528 return RE_ERROR_FAILURE;
7529 }
7530
7531 next_position->node = next->match_next;
7532 next_position->text_pos = text_pos + next->match_step;
7533
7534 return RE_ERROR_SUCCESS;
7535 }
7536
7537 /* Checks whether there's a certain string at a position, ignoring case,
7538 * backwards.
7539 */
7540 Py_LOCAL_INLINE(int) try_match_STRING_IGN_REV(RE_State* state, RE_NextNode*
7541 next, RE_Node* node, Py_ssize_t text_pos, RE_Position* next_position) {
7542 Py_ssize_t length;
7543 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
7544 RE_EncodingTable* encoding;
7545 RE_LocaleInfo* locale_info;
7546 RE_CODE* values;
7547 Py_ssize_t s_pos;
7548
7549 length = (Py_ssize_t)node->value_count;
7550 char_at = state->char_at;
7551 encoding = state->encoding;
7552 locale_info = state->locale_info;
7553 values = node->values;
7554
7555 for (s_pos = 0; s_pos < length; s_pos++) {
7556 if (text_pos - s_pos <= state->slice_start) {
7557 if (state->partial_side == RE_PARTIAL_LEFT) {
7558 next_position->text_pos = text_pos;
7559 return RE_ERROR_PARTIAL;
7560 }
7561
7562 return RE_ERROR_FAILURE;
7563 }
7564
7565 if (!same_char_ign(encoding, locale_info, char_at(state->text, text_pos
7566 - s_pos - 1), values[length - s_pos - 1]))
7567 return RE_ERROR_FAILURE;
7568 }
7569
7570 next_position->node = next->match_next;
7571 next_position->text_pos = text_pos + next->match_step;
7572
7573 return RE_ERROR_SUCCESS;
7574 }
7575
7576 /* Checks whether there's a certain string at a position, backwards. */
7577 Py_LOCAL_INLINE(int) try_match_STRING_REV(RE_State* state, RE_NextNode* next,
7578 RE_Node* node, Py_ssize_t text_pos, RE_Position* next_position) {
7579 Py_ssize_t length;
7580 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
7581 RE_CODE* values;
7582 Py_ssize_t s_pos;
7583
7584 length = (Py_ssize_t)node->value_count;
7585 char_at = state->char_at;
7586 values = node->values;
7587
7588 for (s_pos = 0; s_pos < length; s_pos++) {
7589 if (text_pos - s_pos <= state->slice_start) {
7590 if (state->partial_side == RE_PARTIAL_LEFT) {
7591 next_position->text_pos = text_pos;
7592 return RE_ERROR_PARTIAL;
7593 }
7594
7595 return RE_ERROR_FAILURE;
7596 }
7597
7598 if (!same_char(char_at(state->text, text_pos - s_pos - 1),
7599 values[length - s_pos - 1]))
7600 return RE_ERROR_FAILURE;
7601 }
7602
7603 next_position->node = next->match_next;
7604 next_position->text_pos = text_pos + next->match_step;
7605
7606 return RE_ERROR_SUCCESS;
7607 }
7608
7609 /* Tries a match at the current text position.
7610 *
7611 * Returns the next node and text position if the match succeeds.
7612 */
7613 Py_LOCAL_INLINE(int) try_match(RE_State* state, RE_NextNode* next, Py_ssize_t
7614 text_pos, RE_Position* next_position) {
7615 RE_Node* test;
7616 int status;
7617
7618 test = next->test;
7619
7620 if (test->status & RE_STATUS_FUZZY) {
7621 next_position->node = next->node;
7622 next_position->text_pos = text_pos;
7623 return RE_ERROR_SUCCESS;
7624 }
7625
7626 switch (test->op) {
7627 case RE_OP_ANY:
7628 status = try_match_ANY(state, test, text_pos);
7629 break;
7630 case RE_OP_ANY_ALL:
7631 status = try_match_ANY_ALL(state, test, text_pos);
7632 break;
7633 case RE_OP_ANY_ALL_REV:
7634 status = try_match_ANY_ALL_REV(state, test, text_pos);
7635 break;
7636 case RE_OP_ANY_REV:
7637 status = try_match_ANY_REV(state, test, text_pos);
7638 break;
7639 case RE_OP_ANY_U:
7640 status = try_match_ANY_U(state, test, text_pos);
7641 break;
7642 case RE_OP_ANY_U_REV:
7643 status = try_match_ANY_U_REV(state, test, text_pos);
7644 break;
7645 case RE_OP_BOUNDARY:
7646 status = try_match_BOUNDARY(state, test, text_pos);
7647 break;
7648 case RE_OP_CHARACTER:
7649 status = try_match_CHARACTER(state, test, text_pos);
7650 break;
7651 case RE_OP_CHARACTER_IGN:
7652 status = try_match_CHARACTER_IGN(state, test, text_pos);
7653 break;
7654 case RE_OP_CHARACTER_IGN_REV:
7655 status = try_match_CHARACTER_IGN_REV(state, test, text_pos);
7656 break;
7657 case RE_OP_CHARACTER_REV:
7658 status = try_match_CHARACTER_REV(state, test, text_pos);
7659 break;
7660 case RE_OP_DEFAULT_BOUNDARY:
7661 status = try_match_DEFAULT_BOUNDARY(state, test, text_pos);
7662 break;
7663 case RE_OP_DEFAULT_END_OF_WORD:
7664 status = try_match_DEFAULT_END_OF_WORD(state, test, text_pos);
7665 break;
7666 case RE_OP_DEFAULT_START_OF_WORD:
7667 status = try_match_DEFAULT_START_OF_WORD(state, test, text_pos);
7668 break;
7669 case RE_OP_END_OF_LINE:
7670 status = try_match_END_OF_LINE(state, test, text_pos);
7671 break;
7672 case RE_OP_END_OF_LINE_U:
7673 status = try_match_END_OF_LINE_U(state, test, text_pos);
7674 break;
7675 case RE_OP_END_OF_STRING:
7676 status = try_match_END_OF_STRING(state, test, text_pos);
7677 break;
7678 case RE_OP_END_OF_STRING_LINE:
7679 status = try_match_END_OF_STRING_LINE(state, test, text_pos);
7680 break;
7681 case RE_OP_END_OF_STRING_LINE_U:
7682 status = try_match_END_OF_STRING_LINE_U(state, test, text_pos);
7683 break;
7684 case RE_OP_END_OF_WORD:
7685 status = try_match_END_OF_WORD(state, test, text_pos);
7686 break;
7687 case RE_OP_GRAPHEME_BOUNDARY:
7688 status = try_match_GRAPHEME_BOUNDARY(state, test, text_pos);
7689 break;
7690 case RE_OP_PROPERTY:
7691 status = try_match_PROPERTY(state, test, text_pos);
7692 break;
7693 case RE_OP_PROPERTY_IGN:
7694 status = try_match_PROPERTY_IGN(state, test, text_pos);
7695 break;
7696 case RE_OP_PROPERTY_IGN_REV:
7697 status = try_match_PROPERTY_IGN_REV(state, test, text_pos);
7698 break;
7699 case RE_OP_PROPERTY_REV:
7700 status = try_match_PROPERTY_REV(state, test, text_pos);
7701 break;
7702 case RE_OP_RANGE:
7703 status = try_match_RANGE(state, test, text_pos);
7704 break;
7705 case RE_OP_RANGE_IGN:
7706 status = try_match_RANGE_IGN(state, test, text_pos);
7707 break;
7708 case RE_OP_RANGE_IGN_REV:
7709 status = try_match_RANGE_IGN_REV(state, test, text_pos);
7710 break;
7711 case RE_OP_RANGE_REV:
7712 status = try_match_RANGE_REV(state, test, text_pos);
7713 break;
7714 case RE_OP_SEARCH_ANCHOR:
7715 status = try_match_SEARCH_ANCHOR(state, test, text_pos);
7716 break;
7717 case RE_OP_SET_DIFF:
7718 case RE_OP_SET_INTER:
7719 case RE_OP_SET_SYM_DIFF:
7720 case RE_OP_SET_UNION:
7721 status = try_match_SET(state, test, text_pos);
7722 break;
7723 case RE_OP_SET_DIFF_IGN:
7724 case RE_OP_SET_INTER_IGN:
7725 case RE_OP_SET_SYM_DIFF_IGN:
7726 case RE_OP_SET_UNION_IGN:
7727 status = try_match_SET_IGN(state, test, text_pos);
7728 break;
7729 case RE_OP_SET_DIFF_IGN_REV:
7730 case RE_OP_SET_INTER_IGN_REV:
7731 case RE_OP_SET_SYM_DIFF_IGN_REV:
7732 case RE_OP_SET_UNION_IGN_REV:
7733 status = try_match_SET_IGN_REV(state, test, text_pos);
7734 break;
7735 case RE_OP_SET_DIFF_REV:
7736 case RE_OP_SET_INTER_REV:
7737 case RE_OP_SET_SYM_DIFF_REV:
7738 case RE_OP_SET_UNION_REV:
7739 status = try_match_SET_REV(state, test, text_pos);
7740 break;
7741 case RE_OP_START_OF_LINE:
7742 status = try_match_START_OF_LINE(state, test, text_pos);
7743 break;
7744 case RE_OP_START_OF_LINE_U:
7745 status = try_match_START_OF_LINE_U(state, test, text_pos);
7746 break;
7747 case RE_OP_START_OF_STRING:
7748 status = try_match_START_OF_STRING(state, test, text_pos);
7749 break;
7750 case RE_OP_START_OF_WORD:
7751 status = try_match_START_OF_WORD(state, test, text_pos);
7752 break;
7753 case RE_OP_STRING:
7754 return try_match_STRING(state, next, test, text_pos, next_position);
7755 case RE_OP_STRING_FLD:
7756 return try_match_STRING_FLD(state, next, test, text_pos,
7757 next_position);
7758 case RE_OP_STRING_FLD_REV:
7759 return try_match_STRING_FLD_REV(state, next, test, text_pos,
7760 next_position);
7761 case RE_OP_STRING_IGN:
7762 return try_match_STRING_IGN(state, next, test, text_pos,
7763 next_position);
7764 case RE_OP_STRING_IGN_REV:
7765 return try_match_STRING_IGN_REV(state, next, test, text_pos,
7766 next_position);
7767 case RE_OP_STRING_REV:
7768 return try_match_STRING_REV(state, next, test, text_pos,
7769 next_position);
7770 case RE_OP_SUCCESS:
7771 if (state->match_all) {
7772 /* We want to match all of the slice. */
7773 if (state->reverse) {
7774 if (text_pos > state->text_start)
7775 return RE_ERROR_FAILURE;
7776 } else {
7777 if (text_pos < state->text_end)
7778 return RE_ERROR_FAILURE;
7779 }
7780 }
7781
7782 next_position->node = next->node;
7783 next_position->text_pos = text_pos;
7784 return RE_ERROR_SUCCESS;
7785 default:
7786 next_position->node = next->node;
7787 next_position->text_pos = text_pos;
7788 return RE_ERROR_SUCCESS;
7789 }
7790
7791 if (status != RE_ERROR_SUCCESS)
7792 return status;
7793
7794 next_position->node = next->match_next;
7795 next_position->text_pos = text_pos + next->match_step;
7796
7797 return RE_ERROR_SUCCESS;
7798 }
7799
7800 /* Searches for a word boundary. */
7801 Py_LOCAL_INLINE(Py_ssize_t) search_start_BOUNDARY(RE_State* state, RE_Node*
7802 node, Py_ssize_t text_pos, BOOL* is_partial) {
7803 BOOL (*at_boundary)(RE_State* state, Py_ssize_t text_pos);
7804
7805 switch (ENCODING_KIND(node)) {
7806 case ASCII_ENCODING:
7807 at_boundary = ascii_encoding.at_boundary;
7808 break;
7809 case UNICODE_ENCODING:
7810 at_boundary = unicode_encoding.at_boundary;
7811 break;
7812 default:
7813 at_boundary = state->encoding->at_boundary;
7814 break;
7815 }
7816
7817 *is_partial = FALSE;
7818
7819 for (;;) {
7820 if (at_boundary(state, text_pos) == node->match)
7821 return text_pos;
7822
7823 if (text_pos >= state->slice_end)
7824 return -1;
7825
7826 ++text_pos;
7827 }
7828 }
7829
7830 /* Searches for a word boundary, backwards. */
7831 Py_LOCAL_INLINE(Py_ssize_t) search_start_BOUNDARY_rev(RE_State* state, RE_Node*
7832 node, Py_ssize_t text_pos, BOOL* is_partial) {
7833 BOOL (*at_boundary)(RE_State* state, Py_ssize_t text_pos);
7834
7835 switch (ENCODING_KIND(node)) {
7836 case ASCII_ENCODING:
7837 at_boundary = ascii_encoding.at_boundary;
7838 break;
7839 case UNICODE_ENCODING:
7840 at_boundary = unicode_encoding.at_boundary;
7841 break;
7842 default:
7843 at_boundary = state->encoding->at_boundary;
7844 break;
7845 }
7846
7847 *is_partial = FALSE;
7848
7849 for (;;) {
7850 if (at_boundary(state, text_pos) == node->match)
7851 return text_pos;
7852
7853 if (text_pos <= state->slice_start)
7854 return -1;
7855
7856 --text_pos;
7857 }
7858 }
7859
7860 /* Searches for a default word boundary. */
7861 Py_LOCAL_INLINE(Py_ssize_t) search_start_DEFAULT_BOUNDARY(RE_State* state,
7862 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
7863 BOOL (*at_default_boundary)(RE_State* state, Py_ssize_t text_pos);
7864
7865 at_default_boundary = state->encoding->at_default_boundary;
7866
7867 *is_partial = FALSE;
7868
7869 for (;;) {
7870 if (at_default_boundary(state, text_pos) == node->match)
7871 return text_pos;
7872
7873 if (text_pos >= state->slice_end)
7874 return -1;
7875
7876 ++text_pos;
7877 }
7878 }
7879
7880 /* Searches for a default word boundary, backwards. */
7881 Py_LOCAL_INLINE(Py_ssize_t) search_start_DEFAULT_BOUNDARY_rev(RE_State* state,
7882 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
7883 BOOL (*at_default_boundary)(RE_State* state, Py_ssize_t text_pos);
7884
7885 at_default_boundary = state->encoding->at_default_boundary;
7886
7887 *is_partial = FALSE;
7888
7889 for (;;) {
7890 if (at_default_boundary(state, text_pos) == node->match)
7891 return text_pos;
7892
7893 if (text_pos <= state->slice_start)
7894 return -1;
7895
7896 --text_pos;
7897 }
7898 }
7899
7900 /* Searches for the default end of a word. */
7901 Py_LOCAL_INLINE(Py_ssize_t) search_start_DEFAULT_END_OF_WORD(RE_State* state,
7902 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
7903 BOOL (*at_default_word_end)(RE_State* state, Py_ssize_t text_pos);
7904
7905 at_default_word_end = state->encoding->at_default_word_end;
7906
7907 *is_partial = FALSE;
7908
7909 for (;;) {
7910 if (at_default_word_end(state, text_pos) == node->match)
7911 return text_pos;
7912
7913 if (text_pos >= state->slice_end)
7914 return -1;
7915
7916 ++text_pos;
7917 }
7918 }
7919
7920 /* Searches for the default end of a word, backwards. */
7921 Py_LOCAL_INLINE(Py_ssize_t) search_start_DEFAULT_END_OF_WORD_rev(RE_State*
7922 state, RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
7923 BOOL (*at_default_word_end)(RE_State* state, Py_ssize_t text_pos);
7924
7925 at_default_word_end = state->encoding->at_default_word_end;
7926
7927 *is_partial = FALSE;
7928
7929 for (;;) {
7930 if (at_default_word_end(state, text_pos) == node->match)
7931 return text_pos;
7932
7933 if (text_pos <= state->slice_start)
7934 return -1;
7935
7936 --text_pos;
7937 }
7938 }
7939
7940 /* Searches for the default start of a word. */
7941 Py_LOCAL_INLINE(Py_ssize_t) search_start_DEFAULT_START_OF_WORD(RE_State* state,
7942 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
7943 BOOL (*at_default_word_start)(RE_State* state, Py_ssize_t text_pos);
7944
7945 at_default_word_start = state->encoding->at_default_word_start;
7946
7947 *is_partial = FALSE;
7948
7949 for (;;) {
7950 if (at_default_word_start(state, text_pos) == node->match)
7951 return text_pos;
7952
7953 if (text_pos >= state->slice_end)
7954 return -1;
7955
7956 ++text_pos;
7957 }
7958 }
7959
7960 /* Searches for the default start of a word, backwards. */
7961 Py_LOCAL_INLINE(Py_ssize_t) search_start_DEFAULT_START_OF_WORD_rev(RE_State*
7962 state, RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
7963 BOOL (*at_default_word_start)(RE_State* state, Py_ssize_t text_pos);
7964
7965 at_default_word_start = state->encoding->at_default_word_start;
7966
7967 *is_partial = FALSE;
7968
7969 for (;;) {
7970 if (at_default_word_start(state, text_pos) == node->match)
7971 return text_pos;
7972
7973 if (text_pos <= state->slice_start)
7974 return -1;
7975
7976 --text_pos;
7977 }
7978 }
7979
7980 /* Searches for the end of line. */
7981 Py_LOCAL_INLINE(Py_ssize_t) search_start_END_OF_LINE(RE_State* state, RE_Node*
7982 node, Py_ssize_t text_pos, BOOL* is_partial) {
7983 *is_partial = FALSE;
7984
7985 for (;;) {
7986 if (text_pos >= state->text_end || state->char_at(state->text,
7987 text_pos) == '\n')
7988 return text_pos;
7989
7990 if (text_pos >= state->slice_end)
7991 return -1;
7992
7993 ++text_pos;
7994 }
7995 }
7996
7997 /* Searches for the end of line, backwards. */
7998 Py_LOCAL_INLINE(Py_ssize_t) search_start_END_OF_LINE_rev(RE_State* state,
7999 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8000 *is_partial = FALSE;
8001
8002 for (;;) {
8003 if (text_pos >= state->text_end || state->char_at(state->text,
8004 text_pos) == '\n')
8005 return text_pos;
8006
8007 if (text_pos <= state->slice_start)
8008 return -1;
8009
8010 --text_pos;
8011 }
8012 }
8013
8014 /* Searches for the end of the string. */
8015 Py_LOCAL_INLINE(Py_ssize_t) search_start_END_OF_STRING(RE_State* state,
8016 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8017 *is_partial = FALSE;
8018
8019 if (state->slice_end >= state->text_end)
8020 return state->text_end;
8021
8022 return -1;
8023 }
8024
8025 /* Searches for the end of the string, backwards. */
8026 Py_LOCAL_INLINE(Py_ssize_t) search_start_END_OF_STRING_rev(RE_State* state,
8027 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8028 *is_partial = FALSE;
8029
8030 if (text_pos >= state->text_end)
8031 return text_pos;
8032
8033 return -1;
8034 }
8035
8036 /* Searches for the end of the string or line. */
8037 Py_LOCAL_INLINE(Py_ssize_t) search_start_END_OF_STRING_LINE(RE_State* state,
8038 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8039 *is_partial = FALSE;
8040
8041 if (text_pos <= state->final_newline)
8042 text_pos = state->final_newline;
8043 else if (text_pos <= state->text_end)
8044 text_pos = state->text_end;
8045
8046 if (text_pos > state->slice_end)
8047 return -1;
8048
8049 if (text_pos >= state->text_end)
8050 return text_pos;
8051
8052 return text_pos;
8053 }
8054
8055 /* Searches for the end of the string or line, backwards. */
8056 Py_LOCAL_INLINE(Py_ssize_t) search_start_END_OF_STRING_LINE_rev(RE_State*
8057 state, RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8058 *is_partial = FALSE;
8059
8060 if (text_pos >= state->text_end)
8061 text_pos = state->text_end;
8062 else if (text_pos >= state->final_newline)
8063 text_pos = state->final_newline;
8064 else
8065 return -1;
8066
8067 if (text_pos < state->slice_start)
8068 return -1;
8069
8070 if (text_pos <= state->text_start)
8071 return text_pos;
8072
8073 return text_pos;
8074 }
8075
8076 /* Searches for the end of a word. */
8077 Py_LOCAL_INLINE(Py_ssize_t) search_start_END_OF_WORD(RE_State* state, RE_Node*
8078 node, Py_ssize_t text_pos, BOOL* is_partial) {
8079 BOOL (*at_word_end)(RE_State* state, Py_ssize_t text_pos);
8080
8081 at_word_end = state->encoding->at_word_end;
8082
8083 *is_partial = FALSE;
8084
8085 for (;;) {
8086 if (at_word_end(state, text_pos) == node->match)
8087 return text_pos;
8088
8089 if (text_pos >= state->slice_end)
8090 return -1;
8091
8092 ++text_pos;
8093 }
8094 }
8095
8096 /* Searches for the end of a word, backwards. */
8097 Py_LOCAL_INLINE(Py_ssize_t) search_start_END_OF_WORD_rev(RE_State* state,
8098 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8099 BOOL (*at_word_end)(RE_State* state, Py_ssize_t text_pos);
8100
8101 at_word_end = state->encoding->at_word_end;
8102
8103 *is_partial = FALSE;
8104
8105 for (;;) {
8106 if (at_word_end(state, text_pos) == node->match)
8107 return text_pos;
8108
8109 if (text_pos <= state->slice_start)
8110 return -1;
8111
8112 --text_pos;
8113 }
8114 }
8115
8116 /* Searches for a grapheme boundary. */
8117 Py_LOCAL_INLINE(Py_ssize_t) search_start_GRAPHEME_BOUNDARY(RE_State* state,
8118 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8119 BOOL (*at_grapheme_boundary)(RE_State* state, Py_ssize_t text_pos);
8120
8121 at_grapheme_boundary = state->encoding->at_grapheme_boundary;
8122
8123 *is_partial = FALSE;
8124
8125 for (;;) {
8126 if (at_grapheme_boundary(state, text_pos) == node->match)
8127 return text_pos;
8128
8129 if (text_pos >= state->slice_end)
8130 return -1;
8131
8132 ++text_pos;
8133 }
8134 }
8135
8136 /* Searches for a grapheme boundary, backwards. */
8137 Py_LOCAL_INLINE(Py_ssize_t) search_start_GRAPHEME_BOUNDARY_rev(RE_State* state,
8138 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8139 BOOL (*at_grapheme_boundary)(RE_State* state, Py_ssize_t text_pos);
8140
8141 at_grapheme_boundary = state->encoding->at_grapheme_boundary;
8142
8143 *is_partial = FALSE;
8144
8145 for (;;) {
8146 if (at_grapheme_boundary(state, text_pos) == node->match)
8147 return text_pos;
8148
8149 if (text_pos <= state->slice_start)
8150 return -1;
8151
8152 --text_pos;
8153 }
8154 }
8155
8156 /* Searches for the start of line. */
8157 Py_LOCAL_INLINE(Py_ssize_t) search_start_START_OF_LINE(RE_State* state,
8158 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8159 *is_partial = FALSE;
8160
8161 for (;;) {
8162 if (text_pos <= state->text_start || state->char_at(state->text, text_pos - 1) == '\n')
8163 return text_pos;
8164
8165 if (text_pos >= state->slice_end)
8166 return -1;
8167
8168 ++text_pos;
8169 }
8170 }
8171
8172 /* Searches for the start of line, backwards. */
8173 Py_LOCAL_INLINE(Py_ssize_t) search_start_START_OF_LINE_rev(RE_State* state,
8174 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8175 *is_partial = FALSE;
8176
8177 for (;;) {
8178 if (text_pos <= state->text_start || state->char_at(state->text, text_pos - 1) == '\n')
8179 return text_pos;
8180
8181 if (text_pos <= state->slice_start)
8182 return -1;
8183
8184 --text_pos;
8185 }
8186 }
8187
8188 /* Searches for the start of the string. */
8189 Py_LOCAL_INLINE(Py_ssize_t) search_start_START_OF_STRING(RE_State* state,
8190 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8191 *is_partial = FALSE;
8192
8193 if (text_pos <= state->text_start)
8194 return text_pos;
8195
8196 return -1;
8197 }
8198
8199 /* Searches for the start of the string, backwards. */
8200 Py_LOCAL_INLINE(Py_ssize_t) search_start_START_OF_STRING_rev(RE_State* state,
8201 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8202 *is_partial = FALSE;
8203
8204 if (state->slice_start <= state->text_start)
8205 return state->text_start;
8206
8207 return -1;
8208 }
8209
8210 /* Searches for the start of a word. */
8211 Py_LOCAL_INLINE(Py_ssize_t) search_start_START_OF_WORD(RE_State* state,
8212 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8213 BOOL (*at_word_start)(RE_State* state, Py_ssize_t text_pos);
8214
8215 at_word_start = state->encoding->at_word_start;
8216
8217 *is_partial = FALSE;
8218
8219 for (;;) {
8220 if (at_word_start(state, text_pos) == node->match)
8221 return text_pos;
8222
8223 if (text_pos >= state->slice_end)
8224 return -1;
8225
8226 ++text_pos;
8227 }
8228 }
8229
8230 /* Searches for the start of a word, backwards. */
8231 Py_LOCAL_INLINE(Py_ssize_t) search_start_START_OF_WORD_rev(RE_State* state,
8232 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8233 BOOL (*at_word_start)(RE_State* state, Py_ssize_t text_pos);
8234
8235 at_word_start = state->encoding->at_word_start;
8236
8237 *is_partial = FALSE;
8238
8239 for (;;) {
8240 if (at_word_start(state, text_pos) == node->match)
8241 return text_pos;
8242
8243 if (text_pos <= state->slice_start)
8244 return -1;
8245
8246 --text_pos;
8247 }
8248 }
8249
8250 /* Searches for a string. */
8251 Py_LOCAL_INLINE(Py_ssize_t) search_start_STRING(RE_State* state, RE_Node* node,
8252 Py_ssize_t text_pos, BOOL* is_partial) {
8253 *is_partial = FALSE;
8254
8255 if ((node->status & RE_STATUS_REQUIRED) && text_pos == state->req_pos)
8256 return text_pos;
8257
8258 return string_search(state, node, text_pos, state->slice_end, TRUE,
8259 is_partial);
8260 }
8261
8262 /* Searches for a string, ignoring case. */
8263 Py_LOCAL_INLINE(Py_ssize_t) search_start_STRING_FLD(RE_State* state, RE_Node*
8264 node, Py_ssize_t text_pos, Py_ssize_t* new_pos, BOOL* is_partial) {
8265 *is_partial = FALSE;
8266
8267 if ((node->status & RE_STATUS_REQUIRED) && text_pos == state->req_pos) {
8268 *new_pos = state->req_end;
8269 return text_pos;
8270 }
8271
8272 return string_search_fld(state, node, text_pos, state->slice_end, new_pos,
8273 is_partial);
8274 }
8275
8276 /* Searches for a string, ignoring case, backwards. */
8277 Py_LOCAL_INLINE(Py_ssize_t) search_start_STRING_FLD_REV(RE_State* state,
8278 RE_Node* node, Py_ssize_t text_pos, Py_ssize_t* new_pos, BOOL* is_partial) {
8279 *is_partial = FALSE;
8280
8281 if ((node->status & RE_STATUS_REQUIRED) && text_pos == state->req_pos) {
8282 *new_pos = state->req_end;
8283 return text_pos;
8284 }
8285
8286 return string_search_fld_rev(state, node, text_pos, state->slice_start,
8287 new_pos, is_partial);
8288 }
8289
8290 /* Searches for a string, ignoring case. */
8291 Py_LOCAL_INLINE(Py_ssize_t) search_start_STRING_IGN(RE_State* state, RE_Node*
8292 node, Py_ssize_t text_pos, BOOL* is_partial) {
8293 *is_partial = FALSE;
8294
8295 if ((node->status & RE_STATUS_REQUIRED) && text_pos == state->req_pos)
8296 return text_pos;
8297
8298 return string_search_ign(state, node, text_pos, state->slice_end, TRUE,
8299 is_partial);
8300 }
8301
8302 /* Searches for a string, ignoring case, backwards. */
8303 Py_LOCAL_INLINE(Py_ssize_t) search_start_STRING_IGN_REV(RE_State* state,
8304 RE_Node* node, Py_ssize_t text_pos, BOOL* is_partial) {
8305 *is_partial = FALSE;
8306
8307 if ((node->status & RE_STATUS_REQUIRED) && text_pos == state->req_pos)
8308 return text_pos;
8309
8310 return string_search_ign_rev(state, node, text_pos, state->slice_start,
8311 TRUE, is_partial);
8312 }
8313
8314 /* Searches for a string, backwards. */
8315 Py_LOCAL_INLINE(Py_ssize_t) search_start_STRING_REV(RE_State* state, RE_Node*
8316 node, Py_ssize_t text_pos, BOOL* is_partial) {
8317 *is_partial = FALSE;
8318
8319 if ((node->status & RE_STATUS_REQUIRED) && text_pos == state->req_pos)
8320 return text_pos;
8321
8322 return string_search_rev(state, node, text_pos, state->slice_start, TRUE,
8323 is_partial);
8324 }
8325
8326 /* Searches for the start of a match. */
8327 Py_LOCAL_INLINE(int) search_start(RE_State* state, RE_NextNode* next,
8328 RE_Position* new_position, int search_index) {
8329 Py_ssize_t start_pos;
8330 RE_Node* test;
8331 RE_Node* node;
8332 RE_SearchPosition* info;
8333 Py_ssize_t text_pos;
8334
8335 start_pos = state->text_pos;
8336 TRACE(("<<search_start>> at %" PY_FORMAT_SIZE_T "d\n", start_pos))
8337
8338 test = next->test;
8339 node = next->node;
8340
8341 if (state->reverse) {
8342 if (start_pos < state->slice_start) {
8343 if (state->partial_side == RE_PARTIAL_LEFT) {
8344 new_position->text_pos = state->slice_start;
8345 return RE_ERROR_PARTIAL;
8346 }
8347
8348 return RE_ERROR_FAILURE;
8349 }
8350 } else {
8351 if (start_pos > state->slice_end) {
8352 if (state->partial_side == RE_PARTIAL_RIGHT) {
8353 new_position->text_pos = state->slice_end;
8354 return RE_ERROR_PARTIAL;
8355 }
8356 }
8357 }
8358
8359 if (test->status & RE_STATUS_FUZZY) {
8360 /* Don't call 'search_start' again. */
8361 state->pattern->do_search_start = FALSE;
8362
8363 state->match_pos = start_pos;
8364 new_position->node = node;
8365 new_position->text_pos = start_pos;
8366
8367 return RE_ERROR_SUCCESS;
8368 }
8369
8370 again:
8371 if (!state->is_fuzzy && state->partial_side == RE_PARTIAL_NONE) {
8372 if (state->reverse) {
8373 if (start_pos - state->min_width < state->slice_start)
8374 return RE_ERROR_FAILURE;
8375 } else {
8376 if (start_pos + state->min_width > state->slice_end)
8377 return RE_ERROR_FAILURE;
8378 }
8379 }
8380
8381 if (search_index < MAX_SEARCH_POSITIONS) {
8382 info = &state->search_positions[search_index];
8383 if (state->reverse) {
8384 if (info->start_pos >= 0 && info->start_pos >= start_pos &&
8385 start_pos >= info->match_pos) {
8386 state->match_pos = info->match_pos;
8387
8388 new_position->text_pos = state->match_pos;
8389 new_position->node = node;
8390
8391 return RE_ERROR_SUCCESS;
8392 }
8393 } else {
8394 if (info->start_pos >= 0 && info->start_pos <= start_pos &&
8395 start_pos <= info->match_pos) {
8396 state->match_pos = info->match_pos;
8397
8398 new_position->text_pos = state->match_pos;
8399 new_position->node = node;
8400
8401 return RE_ERROR_SUCCESS;
8402 }
8403 }
8404 } else
8405 info = NULL;
8406
8407 switch (test->op) {
8408 case RE_OP_ANY:
8409 start_pos = match_many_ANY(state, test, start_pos, state->slice_end,
8410 FALSE);
8411
8412 if (start_pos >= state->text_end) {
8413 if (state->partial_side == RE_PARTIAL_RIGHT) {
8414 new_position->text_pos = start_pos;
8415 return RE_ERROR_PARTIAL;
8416 }
8417 }
8418
8419 if (start_pos >= state->slice_end)
8420 return RE_ERROR_FAILURE;
8421 break;
8422 case RE_OP_ANY_ALL:
8423 case RE_OP_ANY_ALL_REV:
8424 break;
8425 case RE_OP_ANY_REV:
8426 start_pos = match_many_ANY_REV(state, test, start_pos,
8427 state->slice_start, FALSE);
8428
8429 if (start_pos <= state->text_start) {
8430 if (state->partial_side == RE_PARTIAL_LEFT) {
8431 new_position->text_pos = start_pos;
8432 return RE_ERROR_PARTIAL;
8433 }
8434 }
8435
8436 if (start_pos <= state->slice_start)
8437 return RE_ERROR_FAILURE;
8438 break;
8439 case RE_OP_ANY_U:
8440 start_pos = match_many_ANY_U(state, test, start_pos, state->slice_end,
8441 FALSE);
8442
8443 if (start_pos >= state->text_end) {
8444 if (state->partial_side == RE_PARTIAL_RIGHT) {
8445 new_position->text_pos = start_pos;
8446 return RE_ERROR_PARTIAL;
8447 }
8448 }
8449
8450 if (start_pos >= state->slice_end)
8451 return RE_ERROR_FAILURE;
8452 break;
8453 case RE_OP_ANY_U_REV:
8454 start_pos = match_many_ANY_U_REV(state, test, start_pos,
8455 state->slice_start, FALSE);
8456
8457 if (start_pos <= state->text_start) {
8458 if (state->partial_side == RE_PARTIAL_LEFT) {
8459 new_position->text_pos = start_pos;
8460 return RE_ERROR_PARTIAL;
8461 }
8462 }
8463
8464 if (start_pos <= state->slice_start)
8465 return RE_ERROR_FAILURE;
8466 break;
8467 case RE_OP_BOUNDARY:
8468 {
8469 BOOL is_partial;
8470
8471 if (state->reverse)
8472 start_pos = search_start_BOUNDARY_rev(state, test, start_pos,
8473 &is_partial);
8474 else
8475 start_pos = search_start_BOUNDARY(state, test, start_pos,
8476 &is_partial);
8477
8478 if (start_pos < 0)
8479 return RE_ERROR_FAILURE;
8480
8481 if (is_partial) {
8482 new_position->text_pos = start_pos;
8483 return RE_ERROR_PARTIAL;
8484 }
8485 break;
8486 }
8487 case RE_OP_CHARACTER:
8488 start_pos = match_many_CHARACTER(state, test, start_pos,
8489 state->slice_end, FALSE);
8490
8491 if (start_pos >= state->text_end) {
8492 if (state->partial_side == RE_PARTIAL_RIGHT) {
8493 new_position->text_pos = start_pos;
8494 return RE_ERROR_PARTIAL;
8495 }
8496 }
8497
8498 if (start_pos >= state->slice_end)
8499 return RE_ERROR_FAILURE;
8500 break;
8501 case RE_OP_CHARACTER_IGN:
8502 start_pos = match_many_CHARACTER_IGN(state, test, start_pos,
8503 state->slice_end, FALSE);
8504
8505 if (start_pos >= state->text_end) {
8506 if (state->partial_side == RE_PARTIAL_RIGHT) {
8507 new_position->text_pos = start_pos;
8508 return RE_ERROR_PARTIAL;
8509 }
8510 }
8511
8512 if (start_pos >= state->slice_end)
8513 return RE_ERROR_FAILURE;
8514 break;
8515 case RE_OP_CHARACTER_IGN_REV:
8516 start_pos = match_many_CHARACTER_IGN_REV(state, test, start_pos,
8517 state->slice_start, FALSE);
8518
8519 if (start_pos <= state->text_start) {
8520 if (state->partial_side == RE_PARTIAL_LEFT) {
8521 new_position->text_pos = start_pos;
8522 return RE_ERROR_PARTIAL;
8523 }
8524 }
8525
8526 if (start_pos <= state->slice_start)
8527 return RE_ERROR_FAILURE;
8528 break;
8529 case RE_OP_CHARACTER_REV:
8530 start_pos = match_many_CHARACTER_REV(state, test, start_pos,
8531 state->slice_start, FALSE);
8532
8533 if (start_pos <= state->text_start) {
8534 if (state->partial_side == RE_PARTIAL_LEFT) {
8535 new_position->text_pos = start_pos;
8536 return RE_ERROR_PARTIAL;
8537 }
8538 }
8539
8540 if (start_pos <= state->slice_start)
8541 return RE_ERROR_FAILURE;
8542 break;
8543 case RE_OP_DEFAULT_BOUNDARY:
8544 {
8545 BOOL is_partial;
8546
8547 if (state->reverse)
8548 start_pos = search_start_DEFAULT_BOUNDARY_rev(state, test,
8549 start_pos, &is_partial);
8550 else
8551 start_pos = search_start_DEFAULT_BOUNDARY(state, test, start_pos,
8552 &is_partial);
8553
8554 if (start_pos < 0)
8555 return RE_ERROR_FAILURE;
8556
8557 if (is_partial) {
8558 new_position->text_pos = start_pos;
8559 return RE_ERROR_PARTIAL;
8560 }
8561 break;
8562 }
8563 case RE_OP_DEFAULT_END_OF_WORD:
8564 {
8565 BOOL is_partial;
8566
8567 if (state->reverse)
8568 start_pos = search_start_DEFAULT_END_OF_WORD_rev(state, test,
8569 start_pos, &is_partial);
8570 else
8571 start_pos = search_start_DEFAULT_END_OF_WORD(state, test,
8572 start_pos, &is_partial);
8573
8574 if (start_pos < 0)
8575 return RE_ERROR_FAILURE;
8576
8577 if (is_partial) {
8578 new_position->text_pos = start_pos;
8579 return RE_ERROR_PARTIAL;
8580 }
8581 break;
8582 }
8583 case RE_OP_DEFAULT_START_OF_WORD:
8584 {
8585 BOOL is_partial;
8586
8587 if (state->reverse)
8588 start_pos = search_start_DEFAULT_START_OF_WORD_rev(state, test,
8589 start_pos, &is_partial);
8590 else
8591 start_pos = search_start_DEFAULT_START_OF_WORD(state, test,
8592 start_pos, &is_partial);
8593
8594 if (start_pos < 0)
8595 return RE_ERROR_FAILURE;
8596
8597 if (is_partial) {
8598 new_position->text_pos = start_pos;
8599 return RE_ERROR_PARTIAL;
8600 }
8601 break;
8602 }
8603 case RE_OP_END_OF_LINE:
8604 {
8605 BOOL is_partial;
8606
8607 if (state->reverse)
8608 start_pos = search_start_END_OF_LINE_rev(state, test, start_pos,
8609 &is_partial);
8610 else
8611 start_pos = search_start_END_OF_LINE(state, test, start_pos,
8612 &is_partial);
8613
8614 if (start_pos < 0)
8615 return RE_ERROR_FAILURE;
8616
8617 if (is_partial) {
8618 new_position->text_pos = start_pos;
8619 return RE_ERROR_PARTIAL;
8620 }
8621 break;
8622 }
8623 case RE_OP_END_OF_STRING:
8624 {
8625 BOOL is_partial;
8626
8627 if (state->reverse)
8628 start_pos = search_start_END_OF_STRING_rev(state, test, start_pos,
8629 &is_partial);
8630 else
8631 start_pos = search_start_END_OF_STRING(state, test, start_pos,
8632 &is_partial);
8633
8634 if (start_pos < 0)
8635 return RE_ERROR_FAILURE;
8636
8637 if (is_partial) {
8638 new_position->text_pos = start_pos;
8639 return RE_ERROR_PARTIAL;
8640 }
8641 break;
8642 }
8643 case RE_OP_END_OF_STRING_LINE:
8644 {
8645 BOOL is_partial;
8646
8647 if (state->reverse)
8648 start_pos = search_start_END_OF_STRING_LINE_rev(state, test,
8649 start_pos, &is_partial);
8650 else
8651 start_pos = search_start_END_OF_STRING_LINE(state, test, start_pos,
8652 &is_partial);
8653
8654 if (start_pos < 0)
8655 return RE_ERROR_FAILURE;
8656
8657 if (is_partial) {
8658 new_position->text_pos = start_pos;
8659 return RE_ERROR_PARTIAL;
8660 }
8661 break;
8662 }
8663 case RE_OP_END_OF_WORD:
8664 {
8665 BOOL is_partial;
8666
8667 if (state->reverse)
8668 start_pos = search_start_END_OF_WORD_rev(state, test, start_pos,
8669 &is_partial);
8670 else
8671 start_pos = search_start_END_OF_WORD(state, test, start_pos,
8672 &is_partial);
8673
8674 if (start_pos < 0)
8675 return RE_ERROR_FAILURE;
8676
8677 if (is_partial) {
8678 new_position->text_pos = start_pos;
8679 return RE_ERROR_PARTIAL;
8680 }
8681 break;
8682 }
8683 case RE_OP_GRAPHEME_BOUNDARY:
8684 {
8685 BOOL is_partial;
8686
8687 if (state->reverse)
8688 start_pos = search_start_GRAPHEME_BOUNDARY_rev(state, test,
8689 start_pos, &is_partial);
8690 else
8691 start_pos = search_start_GRAPHEME_BOUNDARY(state, test, start_pos,
8692 &is_partial);
8693
8694 if (start_pos < 0)
8695 return RE_ERROR_FAILURE;
8696
8697 if (is_partial) {
8698 new_position->text_pos = start_pos;
8699 return RE_ERROR_PARTIAL;
8700 }
8701 break;
8702 }
8703 case RE_OP_PROPERTY:
8704 start_pos = match_many_PROPERTY(state, test, start_pos,
8705 state->slice_end, FALSE);
8706
8707 if (start_pos >= state->text_end) {
8708 if (state->partial_side == RE_PARTIAL_RIGHT) {
8709 new_position->text_pos = start_pos;
8710 return RE_ERROR_PARTIAL;
8711 }
8712 }
8713
8714 if (start_pos >= state->slice_end)
8715 return RE_ERROR_FAILURE;
8716 break;
8717 case RE_OP_PROPERTY_IGN:
8718 start_pos = match_many_PROPERTY_IGN(state, test, start_pos,
8719 state->slice_end, FALSE);
8720
8721 if (start_pos >= state->text_end) {
8722 if (state->partial_side == RE_PARTIAL_RIGHT) {
8723 new_position->text_pos = start_pos;
8724 return RE_ERROR_PARTIAL;
8725 }
8726 }
8727
8728 if (start_pos >= state->slice_end)
8729 return RE_ERROR_FAILURE;
8730 break;
8731 case RE_OP_PROPERTY_IGN_REV:
8732 start_pos = match_many_PROPERTY_IGN_REV(state, test, start_pos,
8733 state->slice_start, FALSE);
8734
8735 if (start_pos <= state->text_start) {
8736 if (state->partial_side == RE_PARTIAL_LEFT) {
8737 new_position->text_pos = start_pos;
8738 return RE_ERROR_PARTIAL;
8739 }
8740 }
8741
8742 if (start_pos <= state->slice_start)
8743 return RE_ERROR_FAILURE;
8744 break;
8745 case RE_OP_PROPERTY_REV:
8746 start_pos = match_many_PROPERTY_REV(state, test, start_pos,
8747 state->slice_start, FALSE);
8748
8749 if (start_pos <= state->text_start) {
8750 if (state->partial_side == RE_PARTIAL_LEFT) {
8751 new_position->text_pos = start_pos;
8752 return RE_ERROR_PARTIAL;
8753 }
8754 }
8755
8756 if (start_pos <= state->slice_start)
8757 return RE_ERROR_FAILURE;
8758 break;
8759 case RE_OP_RANGE:
8760 start_pos = match_many_RANGE(state, test, start_pos, state->slice_end,
8761 FALSE);
8762
8763 if (start_pos >= state->text_end) {
8764 if (state->partial_side == RE_PARTIAL_RIGHT) {
8765 new_position->text_pos = start_pos;
8766 return RE_ERROR_PARTIAL;
8767 }
8768 }
8769
8770 if (start_pos >= state->slice_end)
8771 return RE_ERROR_FAILURE;
8772 break;
8773 case RE_OP_RANGE_IGN:
8774 start_pos = match_many_RANGE_IGN(state, test, start_pos,
8775 state->slice_end, FALSE);
8776
8777 if (start_pos >= state->text_end) {
8778 if (state->partial_side == RE_PARTIAL_RIGHT) {
8779 new_position->text_pos = start_pos;
8780 return RE_ERROR_PARTIAL;
8781 }
8782 }
8783
8784 if (start_pos >= state->slice_end)
8785 return RE_ERROR_FAILURE;
8786 break;
8787 case RE_OP_RANGE_IGN_REV:
8788 start_pos = match_many_RANGE_IGN_REV(state, test, start_pos,
8789 state->slice_start, FALSE);
8790
8791 if (start_pos <= state->text_start) {
8792 if (state->partial_side == RE_PARTIAL_LEFT) {
8793 new_position->text_pos = start_pos;
8794 return RE_ERROR_PARTIAL;
8795 }
8796 }
8797
8798 if (start_pos <= state->slice_start)
8799 return RE_ERROR_FAILURE;
8800 break;
8801 case RE_OP_RANGE_REV:
8802 start_pos = match_many_RANGE_REV(state, test, start_pos,
8803 state->slice_start, FALSE);
8804
8805 if (start_pos <= state->text_start) {
8806 if (state->partial_side == RE_PARTIAL_LEFT) {
8807 new_position->text_pos = start_pos;
8808 return RE_ERROR_PARTIAL;
8809 }
8810 }
8811
8812 if (start_pos <= state->slice_start)
8813 return RE_ERROR_FAILURE;
8814 break;
8815 case RE_OP_SEARCH_ANCHOR:
8816 if (state->reverse) {
8817 if (start_pos < state->search_anchor)
8818 return RE_ERROR_FAILURE;
8819 } else {
8820 if (start_pos > state->search_anchor)
8821 return RE_ERROR_FAILURE;
8822 }
8823
8824 start_pos = state->search_anchor;
8825 break;
8826 case RE_OP_SET_DIFF:
8827 case RE_OP_SET_INTER:
8828 case RE_OP_SET_SYM_DIFF:
8829 case RE_OP_SET_UNION:
8830 start_pos = match_many_SET(state, test, start_pos, state->slice_end,
8831 FALSE);
8832
8833 if (start_pos >= state->text_end) {
8834 if (state->partial_side == RE_PARTIAL_RIGHT) {
8835 new_position->text_pos = start_pos;
8836 return RE_ERROR_PARTIAL;
8837 }
8838 }
8839
8840 if (start_pos >= state->slice_end)
8841 return FALSE;
8842 break;
8843 case RE_OP_SET_DIFF_IGN:
8844 case RE_OP_SET_INTER_IGN:
8845 case RE_OP_SET_SYM_DIFF_IGN:
8846 case RE_OP_SET_UNION_IGN:
8847 start_pos = match_many_SET_IGN(state, test, start_pos,
8848 state->slice_end, FALSE);
8849
8850 if (start_pos >= state->text_end) {
8851 if (state->partial_side == RE_PARTIAL_RIGHT) {
8852 new_position->text_pos = start_pos;
8853 return RE_ERROR_PARTIAL;
8854 }
8855 }
8856
8857 if (start_pos >= state->slice_end)
8858 return FALSE;
8859 break;
8860 case RE_OP_SET_DIFF_IGN_REV:
8861 case RE_OP_SET_INTER_IGN_REV:
8862 case RE_OP_SET_SYM_DIFF_IGN_REV:
8863 case RE_OP_SET_UNION_IGN_REV:
8864 start_pos = match_many_SET_IGN_REV(state, test, start_pos,
8865 state->slice_start, FALSE);
8866
8867 if (start_pos <= state->text_start) {
8868 if (state->partial_side == RE_PARTIAL_LEFT) {
8869 new_position->text_pos = start_pos;
8870 return RE_ERROR_PARTIAL;
8871 }
8872 }
8873
8874 if (start_pos <= state->slice_start)
8875 return FALSE;
8876 break;
8877 case RE_OP_SET_DIFF_REV:
8878 case RE_OP_SET_INTER_REV:
8879 case RE_OP_SET_SYM_DIFF_REV:
8880 case RE_OP_SET_UNION_REV:
8881 start_pos = match_many_SET_REV(state, test, start_pos,
8882 state->slice_start, FALSE);
8883
8884 if (start_pos <= state->text_start) {
8885 if (state->partial_side == RE_PARTIAL_LEFT) {
8886 new_position->text_pos = start_pos;
8887 return RE_ERROR_PARTIAL;
8888 }
8889 }
8890
8891 if (start_pos <= state->slice_start)
8892 return FALSE;
8893 break;
8894 case RE_OP_START_OF_LINE:
8895 {
8896 BOOL is_partial;
8897
8898 if (state->reverse)
8899 start_pos = search_start_START_OF_LINE_rev(state, test, start_pos,
8900 &is_partial);
8901 else
8902 start_pos = search_start_START_OF_LINE(state, test, start_pos,
8903 &is_partial);
8904
8905 if (start_pos < 0)
8906 return RE_ERROR_FAILURE;
8907
8908 if (is_partial) {
8909 new_position->text_pos = start_pos;
8910 return RE_ERROR_PARTIAL;
8911 }
8912 break;
8913 }
8914 case RE_OP_START_OF_STRING:
8915 {
8916 BOOL is_partial;
8917
8918 if (state->reverse)
8919 start_pos = search_start_START_OF_STRING_rev(state, test,
8920 start_pos, &is_partial);
8921 else
8922 start_pos = search_start_START_OF_STRING(state, test, start_pos,
8923 &is_partial);
8924
8925 if (start_pos < 0)
8926 return RE_ERROR_FAILURE;
8927
8928 if (is_partial) {
8929 new_position->text_pos = start_pos;
8930 return RE_ERROR_PARTIAL;
8931 }
8932 break;
8933 }
8934 case RE_OP_START_OF_WORD:
8935 {
8936 BOOL is_partial;
8937
8938 if (state->reverse)
8939 start_pos = search_start_START_OF_WORD_rev(state, test, start_pos,
8940 &is_partial);
8941 else
8942 start_pos = search_start_START_OF_WORD(state, test, start_pos,
8943 &is_partial);
8944
8945 if (start_pos < 0)
8946 return RE_ERROR_FAILURE;
8947
8948 if (is_partial) {
8949 new_position->text_pos = start_pos;
8950 return RE_ERROR_PARTIAL;
8951 }
8952 break;
8953 }
8954 case RE_OP_STRING:
8955 {
8956 BOOL is_partial;
8957
8958 start_pos = search_start_STRING(state, test, start_pos, &is_partial);
8959 if (start_pos < 0)
8960 return RE_ERROR_FAILURE;
8961
8962 if (is_partial) {
8963 new_position->text_pos = start_pos;
8964 return RE_ERROR_PARTIAL;
8965 }
8966 break;
8967 }
8968 case RE_OP_STRING_FLD:
8969 {
8970 Py_ssize_t new_pos;
8971 BOOL is_partial;
8972
8973 start_pos = search_start_STRING_FLD(state, test, start_pos, &new_pos,
8974 &is_partial);
8975 if (start_pos < 0)
8976 return RE_ERROR_FAILURE;
8977
8978 if (is_partial) {
8979 new_position->text_pos = start_pos;
8980 return RE_ERROR_PARTIAL;
8981 }
8982
8983 /* Can we look further ahead? */
8984 if (test == node) {
8985 if (test->next_1.node) {
8986 int status;
8987
8988 status = try_match(state, &test->next_1, new_pos,
8989 new_position);
8990 if (status < 0)
8991 return status;
8992
8993 if (status == RE_ERROR_FAILURE) {
8994 ++start_pos;
8995
8996 if (start_pos >= state->slice_end) {
8997 if (state->partial_side == RE_PARTIAL_RIGHT) {
8998 new_position->text_pos = state->slice_start;
8999 return RE_ERROR_PARTIAL;
9000 }
9001
9002 return RE_ERROR_FAILURE;
9003 }
9004
9005 goto again;
9006 }
9007 }
9008
9009 /* It's a possible match. */
9010 state->match_pos = start_pos;
9011
9012 if (info) {
9013 info->start_pos = state->text_pos;
9014 info->match_pos = state->match_pos;
9015 }
9016
9017 return RE_ERROR_SUCCESS;
9018 }
9019 break;
9020 }
9021 case RE_OP_STRING_FLD_REV:
9022 {
9023 Py_ssize_t new_pos;
9024 BOOL is_partial;
9025
9026 start_pos = search_start_STRING_FLD_REV(state, test, start_pos,
9027 &new_pos, &is_partial);
9028 if (start_pos < 0)
9029 return RE_ERROR_FAILURE;
9030
9031 if (is_partial) {
9032 new_position->text_pos = start_pos;
9033 return RE_ERROR_PARTIAL;
9034 }
9035
9036 /* Can we look further ahead? */
9037 if (test == node) {
9038 if (test->next_1.node) {
9039 int status;
9040
9041 status = try_match(state, &test->next_1, new_pos,
9042 new_position);
9043 if (status < 0)
9044 return status;
9045
9046 if (status == RE_ERROR_FAILURE) {
9047 --start_pos;
9048
9049 if (start_pos <= state->slice_start) {
9050 if (state->partial_side == RE_PARTIAL_LEFT) {
9051 new_position->text_pos = state->slice_start;
9052 return RE_ERROR_PARTIAL;
9053 }
9054
9055 return RE_ERROR_FAILURE;
9056 }
9057
9058 goto again;
9059 }
9060 }
9061
9062 /* It's a possible match. */
9063 state->match_pos = start_pos;
9064
9065 if (info) {
9066 info->start_pos = state->text_pos;
9067 info->match_pos = state->match_pos;
9068 }
9069
9070 return RE_ERROR_SUCCESS;
9071 }
9072 break;
9073 }
9074 case RE_OP_STRING_IGN:
9075 {
9076 BOOL is_partial;
9077
9078 start_pos = search_start_STRING_IGN(state, test, start_pos,
9079 &is_partial);
9080 if (start_pos < 0)
9081 return RE_ERROR_FAILURE;
9082
9083 if (is_partial) {
9084 new_position->text_pos = start_pos;
9085 return RE_ERROR_PARTIAL;
9086 }
9087 break;
9088 }
9089 case RE_OP_STRING_IGN_REV:
9090 {
9091 BOOL is_partial;
9092
9093 start_pos = search_start_STRING_IGN_REV(state, test, start_pos,
9094 &is_partial);
9095 if (start_pos < 0)
9096 return RE_ERROR_FAILURE;
9097
9098 if (is_partial) {
9099 new_position->text_pos = start_pos;
9100 return RE_ERROR_PARTIAL;
9101 }
9102 break;
9103 }
9104 case RE_OP_STRING_REV:
9105 {
9106 BOOL is_partial;
9107
9108 start_pos = search_start_STRING_REV(state, test, start_pos,
9109 &is_partial);
9110 if (start_pos < 0)
9111 return RE_ERROR_FAILURE;
9112
9113 if (is_partial) {
9114 new_position->text_pos = start_pos;
9115 return RE_ERROR_PARTIAL;
9116 }
9117 break;
9118 }
9119 default:
9120 /* Don't call 'search_start' again. */
9121 state->pattern->do_search_start = FALSE;
9122
9123 state->match_pos = start_pos;
9124 new_position->node = node;
9125 new_position->text_pos = start_pos;
9126 return RE_ERROR_SUCCESS;
9127 }
9128
9129 /* Can we look further ahead? */
9130 if (test == node) {
9131 text_pos = start_pos + test->step;
9132
9133 if (test->next_1.node) {
9134 int status;
9135
9136 status = try_match(state, &test->next_1, text_pos, new_position);
9137 if (status == RE_ERROR_PARTIAL) {
9138 new_position->node = node;
9139 new_position->text_pos = start_pos;
9140 return status;
9141 }
9142 if (status < 0)
9143 return status;
9144
9145 if (status == RE_ERROR_FAILURE) {
9146 if (state->reverse) {
9147 --start_pos;
9148
9149 if (start_pos < state->slice_start) {
9150 if (state->partial_side == RE_PARTIAL_LEFT) {
9151 new_position->text_pos = state->slice_start;
9152 return RE_ERROR_PARTIAL;
9153 }
9154
9155 return RE_ERROR_FAILURE;
9156 }
9157 } else {
9158 ++start_pos;
9159
9160 if (start_pos > state->slice_end) {
9161 if (state->partial_side == RE_PARTIAL_RIGHT) {
9162 new_position->text_pos = state->slice_end;
9163 return RE_ERROR_PARTIAL;
9164 }
9165
9166 return RE_ERROR_FAILURE;
9167 }
9168 }
9169
9170 goto again;
9171 }
9172 }
9173 } else {
9174 new_position->node = node;
9175 new_position->text_pos = start_pos;
9176 }
9177
9178 /* It's a possible match. */
9179 state->match_pos = start_pos;
9180
9181 if (info) {
9182 info->start_pos = state->text_pos;
9183 info->match_pos = state->match_pos;
9184 }
9185
9186 return RE_ERROR_SUCCESS;
9187 }
9188
9189 /* Saves a capture group. */
9190 Py_LOCAL_INLINE(BOOL) save_capture(RE_State* state, size_t private_index,
9191 size_t public_index, RE_GroupSpan span) {
9192 RE_GroupData* group;
9193
9194 /* Capture group indexes are 1-based (excluding group 0, which is the
9195 * entire matched string).
9196 */
9197 group = &state->groups[public_index - 1];
9198
9199 if (group->count >= group->capacity) {
9200 size_t new_capacity;
9201 RE_GroupSpan* new_captures;
9202
9203 new_capacity = group->capacity * 2;
9204
9205 if (new_capacity == 0)
9206 new_capacity = 16;
9207
9208 new_captures = (RE_GroupSpan*)safe_realloc(state, group->captures,
9209 new_capacity * sizeof(RE_GroupSpan));
9210 if (!new_captures)
9211 return FALSE;
9212
9213 group->captures = new_captures;
9214 group->capacity = new_capacity;
9215 }
9216
9217 group->captures[group->count++] = span;
9218
9219 return TRUE;
9220 }
9221
9222 /* Unsaves a capture group. */
9223 Py_LOCAL_INLINE(void) unsave_capture(RE_State* state, size_t private_index,
9224 size_t public_index) {
9225 RE_GroupData* group;
9226
9227 /* Capture group indexes are 1-based (excluding group 0, which is the
9228 * entire matched string).
9229 */
9230 group = &state->groups[public_index - 1];
9231
9232 if (group->count > 0)
9233 --group->count;
9234 }
9235
9236 /* Inserts a new span in a guard list. */
9237 Py_LOCAL_INLINE(BOOL) insert_guard_span(RE_State* state, RE_GuardList*
9238 guard_list, size_t index) {
9239 size_t n;
9240
9241 if (guard_list->count >= guard_list->capacity) {
9242 size_t new_capacity;
9243 RE_GuardSpan* new_spans;
9244
9245 new_capacity = guard_list->capacity * 2;
9246
9247 if (new_capacity == 0)
9248 new_capacity = 16;
9249
9250 new_spans = (RE_GuardSpan*)safe_realloc(state, guard_list->spans,
9251 new_capacity * sizeof(RE_GuardSpan));
9252 if (!new_spans)
9253 return FALSE;
9254
9255 guard_list->capacity = new_capacity;
9256 guard_list->spans = new_spans;
9257 }
9258
9259 n = guard_list->count - index;
9260 if (n > 0)
9261 memmove(guard_list->spans + index + 1, guard_list->spans + index, n *
9262 sizeof(RE_GuardSpan));
9263 ++guard_list->count;
9264
9265 return TRUE;
9266 }
9267
9268 /* Deletes a span in a guard list. */
9269 Py_LOCAL_INLINE(void) delete_guard_span(RE_GuardList* guard_list, size_t index)
9270 {
9271 size_t n;
9272
9273 n = guard_list->count - index - 1;
9274 if (n > 0)
9275 memmove(guard_list->spans + index, guard_list->spans + index + 1, n *
9276 sizeof(RE_GuardSpan));
9277 --guard_list->count;
9278 }
9279
9280 /* Checks whether a position is guarded against further matching. */
9281 Py_LOCAL_INLINE(BOOL) is_guarded(RE_GuardList* guard_list, Py_ssize_t text_pos)
9282 {
9283 Py_ssize_t below;
9284 Py_ssize_t above;
9285 RE_GuardSpan* spans;
9286 Py_ssize_t count;
9287
9288 guard_list->last_text_pos = -1;
9289
9290 spans = guard_list->spans;
9291 count = (Py_ssize_t)guard_list->count;
9292
9293 if (count == 0 || text_pos < spans[0].low || text_pos > spans[count -
9294 1].high)
9295 return FALSE;
9296
9297 below = -1;
9298 above = count;
9299
9300 while (above - below > 1) {
9301 Py_ssize_t mid;
9302 RE_GuardSpan* span;
9303
9304 mid = (below + above) / 2;
9305 span = &spans[mid];
9306
9307 if (text_pos < span->low)
9308 above = mid;
9309 else if (text_pos > span->high)
9310 below = mid;
9311 else
9312 return span->protect;
9313 }
9314
9315 return FALSE;
9316 }
9317
9318 /* Guards a position against further matching. */
9319 Py_LOCAL_INLINE(BOOL) guard(RE_State* state, RE_GuardList* guard_list,
9320 Py_ssize_t text_pos, BOOL protect) {
9321 Py_ssize_t below;
9322 Py_ssize_t above;
9323 RE_GuardSpan* spans;
9324 Py_ssize_t count;
9325
9326 guard_list->last_text_pos = -1;
9327
9328 spans = guard_list->spans;
9329 count = (Py_ssize_t)guard_list->count;
9330
9331 if (count > 0 && text_pos > spans[count - 1].high) {
9332 below = count - 1;
9333 above = count;
9334 } else if (count > 0 && text_pos < spans[0].low) {
9335 below = -1;
9336 above = 0;
9337 } else {
9338 below = -1;
9339 above = count;
9340
9341 while (above - below > 1) {
9342 Py_ssize_t mid;
9343 RE_GuardSpan* span;
9344
9345 mid = (below + above) / 2;
9346 span = &spans[mid];
9347
9348 if (text_pos < span->low)
9349 above = mid;
9350 else if (text_pos > span->high)
9351 below = mid;
9352 else
9353 return TRUE;
9354 }
9355 }
9356
9357 /* Add the position to the guard list. */
9358 if (below >= 0 && text_pos - spans[below].high == 1 && spans[below].protect
9359 == protect) {
9360 if (above < count && spans[above].low - text_pos == 1 &&
9361 spans[above].protect == protect) {
9362 /* The new position joins 2 spans */
9363 spans[below].high = spans[above].high;
9364 delete_guard_span(guard_list, (size_t)above);
9365 } else {
9366 /* The new position is just above the 'below' span. */
9367 spans[below].high = text_pos;
9368 }
9369 } else if (above < count && spans[above].low - text_pos == 1 &&
9370 spans[above].protect == protect) {
9371 /* The new position is just below the 'above' span. */
9372 spans[above].low = text_pos;
9373 } else {
9374 /* Insert a new span. */
9375 if (!insert_guard_span(state, guard_list, (size_t)above))
9376 return FALSE;
9377 spans = guard_list->spans;
9378 spans[above].low = text_pos;
9379 spans[above].high = text_pos;
9380 spans[above].protect = protect;
9381 }
9382
9383 return TRUE;
9384 }
9385
9386 /* Guards a position against further matching for a repeat. */
9387 Py_LOCAL_INLINE(BOOL) guard_repeat(RE_State* state, size_t index, Py_ssize_t
9388 text_pos, RE_STATUS_T guard_type, BOOL protect) {
9389 RE_GuardList* guard_list;
9390
9391 /* Is a guard active here? */
9392 if (!(state->pattern->repeat_info[index].status & guard_type))
9393 return TRUE;
9394
9395 /* Which guard list? */
9396 if (guard_type & RE_STATUS_BODY)
9397 guard_list = &state->repeats[index].body_guard_list;
9398 else
9399 guard_list = &state->repeats[index].tail_guard_list;
9400
9401 return guard(state, guard_list, text_pos, protect);
9402 }
9403
9404 /* Guards a range of positions against further matching. */
9405 Py_LOCAL_INLINE(Py_ssize_t) guard_range(RE_State* state, RE_GuardList*
9406 guard_list, Py_ssize_t lo_pos, Py_ssize_t hi_pos, BOOL protect) {
9407 Py_ssize_t below;
9408 Py_ssize_t above;
9409 RE_GuardSpan* spans;
9410 Py_ssize_t count;
9411
9412 guard_list->last_text_pos = -1;
9413
9414 spans = guard_list->spans;
9415 count = (Py_ssize_t)guard_list->count;
9416
9417 below = -1;
9418 above = count;
9419
9420 while (above - below > 1) {
9421 Py_ssize_t mid;
9422 RE_GuardSpan* span;
9423
9424 mid = (below + above) / 2;
9425 span = &spans[mid];
9426
9427 if (lo_pos < span->low)
9428 above = mid;
9429 else if (lo_pos > span->high)
9430 below = mid;
9431 else
9432 return span->high + 1;
9433 }
9434
9435 /* Add the range to the guard list. */
9436 if (below >= 0 && lo_pos - spans[below].high == 1 && spans[below].protect
9437 == protect) {
9438 if (above < count && spans[above].low - hi_pos <= 1 &&
9439 spans[above].protect == protect) {
9440 /* The new range joins the spans */
9441 spans[below].high = spans[above].high;
9442 delete_guard_span(guard_list, (size_t)above);
9443 spans = guard_list->spans;
9444 } else {
9445 if (above < count)
9446 hi_pos = min_ssize_t(hi_pos, spans[above].low - 1);
9447
9448 spans[below].high = hi_pos;
9449 }
9450
9451 lo_pos = spans[below].high + 1;
9452 } else if (above < count && spans[above].low - hi_pos <= 1 &&
9453 spans[above].protect == protect) {
9454 spans[above].low = lo_pos;
9455 lo_pos = spans[above].high + 1;
9456 } else {
9457 /* Insert a new span. */
9458 if (!insert_guard_span(state, guard_list, (size_t)above))
9459 return -1;
9460 spans = guard_list->spans;
9461
9462 if (above < count)
9463 hi_pos = min_ssize_t(hi_pos, spans[above].low - 1);
9464
9465 spans[above].low = lo_pos;
9466 spans[above].high = hi_pos;
9467 spans[above].protect = protect;
9468 lo_pos = spans[above].high + 1;
9469 }
9470
9471 return lo_pos;
9472 }
9473
9474 /* Guards a range of positions against further matching for a repeat. */
9475 Py_LOCAL_INLINE(BOOL) guard_repeat_range(RE_State* state, size_t index,
9476 Py_ssize_t lo_pos, Py_ssize_t hi_pos, RE_STATUS_T guard_type, BOOL protect) {
9477 RE_GuardList* guard_list;
9478
9479 /* Is a guard active here? */
9480 if (!(state->pattern->repeat_info[index].status & guard_type))
9481 return TRUE;
9482
9483 /* Which guard list? */
9484 if (guard_type & RE_STATUS_BODY)
9485 guard_list = &state->repeats[index].body_guard_list;
9486 else
9487 guard_list = &state->repeats[index].tail_guard_list;
9488
9489 while (lo_pos <= hi_pos) {
9490 lo_pos = guard_range(state, guard_list, lo_pos, hi_pos, protect);
9491 if (lo_pos < 0)
9492 return FALSE;
9493 }
9494
9495 return TRUE;
9496 }
9497
9498 /* Checks whether a position is guarded against further matching for a repeat.
9499 */
9500 Py_LOCAL_INLINE(BOOL) is_repeat_guarded(RE_State* state, size_t index,
9501 Py_ssize_t text_pos, RE_STATUS_T guard_type) {
9502 RE_GuardList* guard_list;
9503
9504 /* Is a guard active here? */
9505 if (!(state->pattern->repeat_info[index].status & guard_type) ||
9506 state->is_fuzzy)
9507 return FALSE;
9508
9509 /* Which guard list? */
9510 if (guard_type == RE_STATUS_BODY)
9511 guard_list = &state->repeats[index].body_guard_list;
9512 else
9513 guard_list = &state->repeats[index].tail_guard_list;
9514
9515 return is_guarded(guard_list, text_pos);
9516 }
9517
9518 /* Builds a Unicode string. */
9519 Py_LOCAL_INLINE(PyObject*) build_unicode_value(void* buffer, Py_ssize_t start,
9520 Py_ssize_t end, Py_ssize_t buffer_charsize) {
9521 Py_ssize_t len;
9522 int kind;
9523
9524 buffer = (void*)((RE_UINT8*)buffer + start * buffer_charsize);
9525 len = end - start;
9526
9527 switch (buffer_charsize) {
9528 case 1:
9529 kind = PyUnicode_1BYTE_KIND;
9530 break;
9531 case 2:
9532 kind = PyUnicode_2BYTE_KIND;
9533 break;
9534 case 4:
9535 kind = PyUnicode_4BYTE_KIND;
9536 break;
9537 default:
9538 kind = PyUnicode_1BYTE_KIND;
9539 break;
9540 }
9541
9542 return PyUnicode_FromKindAndData(kind, buffer, len);
9543 }
9544
9545 /* Builds a bytestring. Returns NULL if any member is too wide. */
9546 Py_LOCAL_INLINE(PyObject*) build_bytes_value(void* buffer, Py_ssize_t start,
9547 Py_ssize_t end, Py_ssize_t buffer_charsize) {
9548 Py_ssize_t len;
9549 Py_UCS1* byte_buffer;
9550 Py_ssize_t i;
9551 PyObject* result;
9552
9553 buffer = (void*)((RE_UINT8*)buffer + start * buffer_charsize);
9554 len = end - start;
9555
9556 if (buffer_charsize == 1)
9557 return Py_BuildValue("y#", buffer, len);
9558
9559 byte_buffer = re_alloc((size_t)len);
9560 if (!byte_buffer)
9561 return NULL;
9562
9563 for (i = 0; i < len; i++) {
9564 Py_UCS2 c = ((Py_UCS2*)buffer)[i];
9565 if (c > 0xFF)
9566 goto too_wide;
9567
9568 byte_buffer[i] = (Py_UCS1)c;
9569 }
9570
9571 result = Py_BuildValue("y#", byte_buffer, len);
9572
9573 re_dealloc(byte_buffer);
9574
9575 return result;
9576
9577 too_wide:
9578 re_dealloc(byte_buffer);
9579
9580 return NULL;
9581 }
9582
9583 /* Calculates the total number of errors. */
9584 Py_LOCAL_INLINE(size_t) total_errors(size_t* fuzzy_counts) {
9585 return fuzzy_counts[RE_FUZZY_DEL] + fuzzy_counts[RE_FUZZY_INS] +
9586 fuzzy_counts[RE_FUZZY_SUB];
9587 }
9588
9589 /* Calculates the total cost of the errors. */
9590 Py_LOCAL_INLINE(size_t) total_cost(size_t* fuzzy_counts, RE_Node* fuzzy_node) {
9591 RE_CODE* values;
9592
9593 values = fuzzy_node->values;
9594
9595 return fuzzy_counts[RE_FUZZY_DEL] * values[RE_FUZZY_VAL_DEL_COST] +
9596 fuzzy_counts[RE_FUZZY_INS] * values[RE_FUZZY_VAL_INS_COST] +
9597 fuzzy_counts[RE_FUZZY_SUB] * values[RE_FUZZY_VAL_SUB_COST];
9598 }
9599
9600 /* Checks whether any additional fuzzy error is permitted. */
9601 Py_LOCAL_INLINE(BOOL) any_error_permitted(RE_State* state) {
9602 size_t* fuzzy_counts;
9603 RE_CODE* values;
9604 size_t error_count;
9605 size_t cost;
9606
9607 fuzzy_counts = state->fuzzy_counts;
9608 values = state->fuzzy_node->values;
9609 error_count = total_errors(fuzzy_counts);
9610 cost = total_cost(fuzzy_counts, state->fuzzy_node);
9611
9612 return cost <= values[RE_FUZZY_VAL_MAX_COST] && error_count <
9613 state->max_errors;
9614 }
9615
9616 /* Checks whether this additional fuzzy error is permitted. */
9617 Py_LOCAL_INLINE(BOOL) this_error_permitted(RE_State* state, RE_UINT8
9618 fuzzy_type) {
9619 size_t* fuzzy_counts;
9620 RE_CODE* values;
9621 size_t error_count;
9622 size_t cost;
9623
9624 fuzzy_counts = state->fuzzy_counts;
9625 values = state->fuzzy_node->values;
9626 error_count = total_errors(fuzzy_counts);
9627 cost = total_cost(fuzzy_counts, state->fuzzy_node);
9628
9629 return fuzzy_counts[fuzzy_type] < values[RE_FUZZY_VAL_MAX_BASE +
9630 fuzzy_type] && error_count < values[RE_FUZZY_VAL_MAX_ERR] && error_count
9631 < state->max_errors && cost + values[RE_FUZZY_VAL_COST_BASE + fuzzy_type]
9632 <= values[RE_FUZZY_VAL_MAX_COST];
9633 }
9634
9635 /* Checks whether an insertion is permitted. */
9636 Py_LOCAL_INLINE(BOOL) insertion_permitted(RE_State* state, RE_Node* fuzzy_node,
9637 size_t* fuzzy_counts) {
9638 RE_CODE* values;
9639 size_t error_count;
9640 size_t cost;
9641
9642 values = fuzzy_node->values;
9643 error_count = total_errors(fuzzy_counts);
9644 cost = total_cost(fuzzy_counts, fuzzy_node);
9645
9646 return fuzzy_counts[RE_FUZZY_INS] < values[RE_FUZZY_VAL_MAX_INS] &&
9647 error_count < values[RE_FUZZY_VAL_MAX_ERR] && cost +
9648 values[RE_FUZZY_VAL_INS_COST] <= values[RE_FUZZY_VAL_MAX_COST] &&
9649 error_count < state->max_errors;
9650 }
9651
9652 /* Checks whether the errors are within the fuzzy constraints. */
9653 Py_LOCAL_INLINE(BOOL) fuzzy_within_constraints(size_t* fuzzy_counts, RE_Node*
9654 fuzzy_node, size_t max_errors) {
9655 RE_CODE* values;
9656 size_t del_count;
9657 size_t ins_count;
9658 size_t sub_count;
9659 size_t err_count;
9660
9661 values = fuzzy_node->values;
9662 del_count = fuzzy_counts[RE_FUZZY_DEL];
9663 ins_count = fuzzy_counts[RE_FUZZY_INS];
9664 sub_count = fuzzy_counts[RE_FUZZY_SUB];
9665
9666 if (del_count < values[RE_FUZZY_VAL_MIN_DEL] || del_count >
9667 values[RE_FUZZY_VAL_MAX_DEL])
9668 return FALSE;
9669 if (ins_count < values[RE_FUZZY_VAL_MIN_INS] || ins_count >
9670 values[RE_FUZZY_VAL_MAX_INS])
9671 return FALSE;
9672 if (sub_count < values[RE_FUZZY_VAL_MIN_SUB] || sub_count >
9673 values[RE_FUZZY_VAL_MAX_SUB])
9674 return FALSE;
9675
9676 err_count = del_count + ins_count + sub_count;
9677
9678 if (err_count < values[RE_FUZZY_VAL_MIN_ERR] || err_count >
9679 values[RE_FUZZY_VAL_MAX_ERR])
9680 return FALSE;
9681
9682 if (err_count > max_errors)
9683 return FALSE;
9684
9685 return total_cost(fuzzy_counts, fuzzy_node) <=
9686 values[RE_FUZZY_VAL_MAX_COST];
9687 }
9688
9689 /* Checks whether we've reached the end of the text during a fuzzy partial
9690 * match.
9691 */
9692 Py_LOCAL_INLINE(int) check_fuzzy_partial(RE_State* state, Py_ssize_t text_pos)
9693 {
9694 switch (state->partial_side) {
9695 case RE_PARTIAL_LEFT:
9696 if (text_pos < state->text_start)
9697 return RE_ERROR_PARTIAL;
9698 break;
9699 case RE_PARTIAL_RIGHT:
9700 if (text_pos > state->text_end)
9701 return RE_ERROR_PARTIAL;
9702 break;
9703 }
9704
9705 return RE_ERROR_FAILURE;
9706 }
9707
9708 /* Records a fuzzy change. */
9709 Py_LOCAL_INLINE(BOOL) record_fuzzy(RE_State* state, RE_UINT8 fuzzy_type,
9710 Py_ssize_t text_pos) {
9711 RE_FuzzyChangesList* change_list;
9712 RE_FuzzyChange* change;
9713
9714 change_list = &state->fuzzy_changes;
9715
9716 if (change_list->count >= change_list->capacity) {
9717 size_t new_capacity;
9718 RE_FuzzyChange* new_items;
9719
9720 new_capacity = change_list->capacity * 2;
9721
9722 if (new_capacity == 0)
9723 new_capacity = 64;
9724
9725 new_items = (RE_FuzzyChange*)safe_realloc(state, change_list->items,
9726 new_capacity * sizeof(RE_FuzzyChange));
9727 if (!new_items)
9728 return FALSE;
9729
9730 change_list->items = new_items;
9731 change_list->capacity = new_capacity;
9732 }
9733
9734 change = &change_list->items[change_list->count++];
9735 change->type = fuzzy_type;
9736 change->pos = text_pos;
9737
9738 return TRUE;
9739 }
9740
9741 /* "Unrecords" a change in a fuzzy change. */
9742 Py_LOCAL_INLINE(void) unrecord_fuzzy(RE_State* state) {
9743 --state->fuzzy_changes.count;
9744 }
9745
9746 /* Initialises a list of fuzzy changes. */
9747 Py_LOCAL_INLINE(void) init_fuzzy_changes_list(RE_FuzzyChangesList*
9748 changes_list) {
9749 changes_list->capacity = 0;
9750 changes_list->count = 0;
9751 changes_list->items = NULL;
9752 }
9753
9754 /* Finalises a list of fuzzy changes. */
9755 Py_LOCAL_INLINE(void) fini_fuzzy_changes_list(RE_State* state,
9756 RE_FuzzyChangesList* changes_list) {
9757 safe_dealloc(state, changes_list->items);
9758 changes_list->capacity = 0;
9759 changes_list->count = 0;
9760 changes_list->items = NULL;
9761 }
9762
9763 /* Initialises a list of lists of fuzzy changes. */
9764 Py_LOCAL_INLINE(void) init_best_changes_list(RE_BestChangesList*
9765 best_changes_list) {
9766 best_changes_list->capacity = 0;
9767 best_changes_list->count = 0;
9768 best_changes_list->lists = NULL;
9769 }
9770
9771 /* Clears a list of lists of fuzzy changes. */
9772 Py_LOCAL_INLINE(void) clear_best_fuzzy_changes(RE_State* state,
9773 RE_BestChangesList* best_changes_list) {
9774 size_t i;
9775
9776 for (i = 0; i < best_changes_list->count; i++) {
9777 RE_FuzzyChangesList* list;
9778
9779 list = &best_changes_list->lists[i];
9780 list->capacity = 0;
9781 list->count = 0;
9782 safe_dealloc(state, list->items);
9783 list->items = NULL;
9784 }
9785
9786 best_changes_list->count = 0;
9787 }
9788
9789 /* Finalises a list of lists of fuzzy changes. */
9790 Py_LOCAL_INLINE(void) fini_best_changes_list(RE_State* state,
9791 RE_BestChangesList* best_changes_list) {
9792 clear_best_fuzzy_changes(state, best_changes_list);
9793 safe_dealloc(state, best_changes_list->lists);
9794 best_changes_list->capacity = 0;
9795 best_changes_list->count = 0;
9796 best_changes_list->lists = NULL;
9797 }
9798
9799 /* Adds a list of fuzzy changes to a list of best fuzzy changes. */
9800 Py_LOCAL_INLINE(BOOL) add_best_fuzzy_changes(RE_State* state,
9801 RE_BestChangesList* best_changes_list) {
9802 size_t size;
9803 RE_FuzzyChange* items;
9804 RE_FuzzyChangesList* changes;
9805
9806 if (best_changes_list->count >= best_changes_list->capacity) {
9807 size_t new_capacity;
9808 RE_FuzzyChangesList* new_lists;
9809
9810 new_capacity = best_changes_list->capacity * 2;
9811
9812 if (new_capacity == 0)
9813 new_capacity = 64;
9814
9815 new_lists = (RE_FuzzyChangesList*)safe_realloc(state,
9816 best_changes_list->lists, new_capacity *
9817 sizeof(RE_FuzzyChangesList));
9818 if (!new_lists)
9819 return FALSE;
9820
9821 best_changes_list->lists = new_lists;
9822 best_changes_list->capacity = new_capacity;
9823 }
9824
9825 size = (size_t)state->fuzzy_changes.count * sizeof(RE_FuzzyChange);
9826 items = (RE_FuzzyChange*)safe_alloc(state, size);
9827 if (!items)
9828 return FALSE;
9829 Py_MEMCPY(items, state->fuzzy_changes.items, size);
9830
9831 changes = &best_changes_list->lists[best_changes_list->count++];
9832 changes->capacity = state->fuzzy_changes.count;
9833 changes->count = state->fuzzy_changes.count;
9834 changes->items = items;
9835
9836 return TRUE;
9837 }
9838
9839 /* Saves a list of fuzzy changes. */
9840 Py_LOCAL_INLINE(BOOL) save_fuzzy_changes(RE_State* state, RE_FuzzyChangesList*
9841 best_changes_list) {
9842 if (state->fuzzy_changes.count > best_changes_list->capacity) {
9843 size_t new_capacity;
9844 RE_FuzzyChange* new_items;
9845
9846 new_capacity = best_changes_list->capacity;
9847
9848 if (new_capacity == 0)
9849 new_capacity = 64;
9850
9851 while (state->fuzzy_changes.count > new_capacity)
9852 new_capacity *= 2;
9853
9854 new_items = (RE_FuzzyChange*)safe_realloc(state,
9855 best_changes_list->items, new_capacity * sizeof(RE_FuzzyChange));
9856 if (!new_items)
9857 return FALSE;
9858
9859 best_changes_list->items = new_items;
9860 best_changes_list->capacity = new_capacity;
9861 }
9862
9863 Py_MEMCPY(best_changes_list->items, state->fuzzy_changes.items,
9864 (size_t)state->fuzzy_changes.count * sizeof(RE_FuzzyChange));
9865 best_changes_list->count = state->fuzzy_changes.count;
9866
9867 return TRUE;
9868 }
9869
9870 /* Restores a list of fuzzy changes. */
9871 Py_LOCAL_INLINE(void) restore_fuzzy_changes(RE_State* state,
9872 RE_FuzzyChangesList* best_changes_list) {
9873 Py_MEMCPY(state->fuzzy_changes.items, best_changes_list->items,
9874 (size_t)best_changes_list->count * sizeof(RE_FuzzyChange));
9875 state->fuzzy_changes.count = best_changes_list->count;
9876 }
9877
9878 /* Does the test of a FUZZY_EXT. */
9879 Py_LOCAL_INLINE(BOOL) fuzzy_ext_match(RE_State* state, RE_Node* fuzzy_node,
9880 Py_ssize_t pos) {
9881 RE_Node* test_node;
9882
9883 if (!fuzzy_node)
9884 return TRUE;
9885
9886 test_node = fuzzy_node->nonstring.next_2.node;
9887 if (!test_node)
9888 return TRUE;
9889
9890 switch (test_node->op) {
9891 case RE_OP_CHARACTER:
9892 return pos < state->slice_end && matches_CHARACTER(state->encoding,
9893 state->locale_info, test_node, state->char_at(state->text, pos)) ==
9894 test_node->match;
9895 case RE_OP_CHARACTER_IGN:
9896 return pos < state->slice_end && matches_CHARACTER_IGN(state->encoding,
9897 state->locale_info, test_node, state->char_at(state->text, pos)) ==
9898 test_node->match;
9899 case RE_OP_CHARACTER_IGN_REV:
9900 return pos > state->slice_start &&
9901 matches_CHARACTER_IGN(state->encoding, state->locale_info, test_node,
9902 state->char_at(state->text, pos - 1)) == test_node->match;
9903 case RE_OP_CHARACTER_REV:
9904 return pos > state->slice_start && matches_CHARACTER(state->encoding,
9905 state->locale_info, test_node, state->char_at(state->text, pos - 1))
9906 == test_node->match;
9907 case RE_OP_PROPERTY:
9908 return pos < state->slice_end && matches_PROPERTY(state->encoding,
9909 state->locale_info, test_node, state->char_at(state->text, pos)) ==
9910 test_node->match;
9911 case RE_OP_PROPERTY_IGN:
9912 return pos < state->slice_end && matches_PROPERTY_IGN(state->encoding,
9913 state->locale_info, test_node, state->char_at(state->text, pos)) ==
9914 test_node->match;
9915 case RE_OP_PROPERTY_IGN_REV:
9916 return pos > state->slice_start &&
9917 matches_PROPERTY_IGN(state->encoding, state->locale_info, test_node,
9918 state->char_at(state->text, pos - 1)) == test_node->match;
9919 case RE_OP_PROPERTY_REV:
9920 return pos > state->slice_start && matches_PROPERTY(state->encoding,
9921 state->locale_info, test_node, state->char_at(state->text, pos - 1))
9922 == test_node->match;
9923 case RE_OP_RANGE:
9924 return pos < state->slice_end && matches_RANGE(state->encoding,
9925 state->locale_info, test_node, state->char_at(state->text, pos)) ==
9926 test_node->match;
9927 case RE_OP_RANGE_IGN:
9928 return pos < state->slice_end && matches_RANGE_IGN(state->encoding,
9929 state->locale_info, test_node, state->char_at(state->text, pos)) ==
9930 test_node->match;
9931 case RE_OP_RANGE_IGN_REV:
9932 return pos > state->slice_start && matches_RANGE_IGN(state->encoding,
9933 state->locale_info, test_node, state->char_at(state->text, pos - 1))
9934 == test_node->match;
9935 case RE_OP_RANGE_REV:
9936 return pos > state->slice_start && matches_RANGE(state->encoding,
9937 state->locale_info, test_node, state->char_at(state->text, pos - 1))
9938 == test_node->match;
9939 case RE_OP_SET_DIFF:
9940 case RE_OP_SET_INTER:
9941 case RE_OP_SET_SYM_DIFF:
9942 case RE_OP_SET_UNION:
9943 return pos < state->slice_end && matches_SET(state->encoding,
9944 state->locale_info, test_node, state->char_at(state->text, pos)) ==
9945 test_node->match;
9946 case RE_OP_SET_DIFF_IGN:
9947 case RE_OP_SET_INTER_IGN:
9948 case RE_OP_SET_SYM_DIFF_IGN:
9949 case RE_OP_SET_UNION_IGN:
9950 return pos < state->slice_end && matches_SET_IGN(state->encoding,
9951 state->locale_info, test_node, state->char_at(state->text, pos)) ==
9952 test_node->match;
9953 }
9954
9955 return TRUE;
9956 }
9957
9958 /* Gets the folded character at a certain position. */
9959 Py_LOCAL_INLINE(Py_UCS4) folded_char_at(RE_State* state, Py_ssize_t pos, int
9960 folded_pos) {
9961 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
9962 folded);
9963 Py_UCS4 folded[RE_MAX_FOLDED];
9964
9965 full_case_fold = state->encoding->full_case_fold;
9966
9967 full_case_fold(state->locale_info, state->char_at(state->text, pos),
9968 folded);
9969
9970 return folded[folded_pos];
9971 }
9972
9973 /* Does the test of a FUZZY_EXT for a folded group. */
9974 Py_LOCAL_INLINE(BOOL) fuzzy_ext_match_group_fld(RE_State* state, RE_Node*
9975 fuzzy_node, int folded_pos) {
9976 RE_Node* test_node;
9977
9978 test_node = fuzzy_node->nonstring.next_2.node;
9979 if (!test_node)
9980 return TRUE;
9981
9982 switch (test_node->op) {
9983 case RE_OP_CHARACTER:
9984 return state->text_pos < state->slice_end &&
9985 matches_CHARACTER(state->encoding, state->locale_info, test_node,
9986 folded_char_at(state, state->text_pos, folded_pos)) ==
9987 test_node->match;
9988 case RE_OP_CHARACTER_IGN:
9989 return state->text_pos < state->slice_end &&
9990 matches_CHARACTER_IGN(state->encoding, state->locale_info, test_node,
9991 folded_char_at(state, state->text_pos, folded_pos)) ==
9992 test_node->match;
9993 case RE_OP_CHARACTER_IGN_REV:
9994 return state->text_pos > state->slice_start &&
9995 matches_CHARACTER_IGN(state->encoding, state->locale_info, test_node,
9996 folded_char_at(state, state->text_pos - 1, folded_pos - 1)) ==
9997 test_node->match;
9998 case RE_OP_CHARACTER_REV:
9999 return state->text_pos > state->slice_start &&
10000 matches_CHARACTER(state->encoding, state->locale_info, test_node,
10001 folded_char_at(state, state->text_pos - 1, folded_pos - 1)) ==
10002 test_node->match;
10003 case RE_OP_PROPERTY:
10004 return state->text_pos < state->slice_end &&
10005 matches_PROPERTY(state->encoding, state->locale_info, test_node,
10006 folded_char_at(state, state->text_pos, folded_pos)) ==
10007 test_node->match;
10008 case RE_OP_PROPERTY_IGN:
10009 return state->text_pos < state->slice_end &&
10010 matches_PROPERTY_IGN(state->encoding, state->locale_info, test_node,
10011 folded_char_at(state, state->text_pos, folded_pos)) ==
10012 test_node->match;
10013 case RE_OP_PROPERTY_IGN_REV:
10014 return state->text_pos > state->slice_start &&
10015 matches_PROPERTY_IGN(state->encoding, state->locale_info, test_node,
10016 folded_char_at(state, state->text_pos - 1, folded_pos - 1)) ==
10017 test_node->match;
10018 case RE_OP_PROPERTY_REV:
10019 return state->text_pos > state->slice_start &&
10020 matches_PROPERTY(state->encoding, state->locale_info, test_node,
10021 folded_char_at(state, state->text_pos - 1, folded_pos - 1)) ==
10022 test_node->match;
10023 case RE_OP_RANGE:
10024 return state->text_pos < state->slice_end &&
10025 matches_RANGE(state->encoding, state->locale_info, test_node,
10026 folded_char_at(state, state->text_pos, folded_pos)) ==
10027 test_node->match;
10028 case RE_OP_RANGE_IGN:
10029 return state->text_pos < state->slice_end &&
10030 matches_RANGE_IGN(state->encoding, state->locale_info, test_node,
10031 folded_char_at(state, state->text_pos, folded_pos)) ==
10032 test_node->match;
10033 case RE_OP_RANGE_IGN_REV:
10034 return state->text_pos > state->slice_start &&
10035 matches_RANGE_IGN(state->encoding, state->locale_info, test_node,
10036 folded_char_at(state, state->text_pos - 1, folded_pos - 1)) ==
10037 test_node->match;
10038 case RE_OP_RANGE_REV:
10039 return state->text_pos > state->slice_start &&
10040 matches_RANGE(state->encoding, state->locale_info, test_node,
10041 folded_char_at(state, state->text_pos - 1, folded_pos - 1)) ==
10042 test_node->match;
10043 case RE_OP_SET_DIFF:
10044 case RE_OP_SET_INTER:
10045 case RE_OP_SET_SYM_DIFF:
10046 case RE_OP_SET_UNION:
10047 return state->text_pos < state->slice_end &&
10048 matches_SET(state->encoding, state->locale_info, test_node,
10049 folded_char_at(state, state->text_pos, folded_pos)) ==
10050 test_node->match;
10051 }
10052
10053 return TRUE;
10054 }
10055
10056 /* Checks a fuzzy match of an item. */
10057 Py_LOCAL_INLINE(int) next_fuzzy_match_item(RE_State* state, RE_FuzzyData* data,
10058 BOOL is_string, RE_INT8 step) {
10059 Py_ssize_t new_pos;
10060
10061 if (!this_error_permitted(state, data->fuzzy_type))
10062 return RE_ERROR_FAILURE;
10063
10064 data->new_text_pos = state->text_pos;
10065
10066 switch (data->fuzzy_type) {
10067 case RE_FUZZY_DEL:
10068 /* Could a character at text_pos have been deleted? */
10069 if (step == 0)
10070 return RE_ERROR_FAILURE;
10071
10072 if (is_string)
10073 data->new_string_pos += step;
10074 else
10075 data->new_node = data->new_node->next_1.node;
10076
10077 return RE_ERROR_SUCCESS;
10078 case RE_FUZZY_INS:
10079 /* Could the character at text_pos have been inserted? */
10080 if (!data->permit_insertion)
10081 return RE_ERROR_FAILURE;
10082
10083 if (step == 0)
10084 new_pos = data->new_text_pos + data->step;
10085 else
10086 new_pos = data->new_text_pos + step;
10087
10088 if (state->slice_start <= new_pos && new_pos <= state->slice_end) {
10089 if (!fuzzy_ext_match(state, state->fuzzy_node, data->new_text_pos))
10090 return RE_ERROR_FAILURE;
10091
10092 data->new_text_pos = new_pos;
10093
10094 return RE_ERROR_SUCCESS;
10095 }
10096
10097 return check_fuzzy_partial(state, data->new_text_pos);
10098 case RE_FUZZY_SUB:
10099 /* Could the character at text_pos have been substituted? */
10100 if (step == 0)
10101 return RE_ERROR_FAILURE;
10102
10103 new_pos = data->new_text_pos + step;
10104
10105 if (state->slice_start <= new_pos && new_pos <= state->slice_end) {
10106 if (!fuzzy_ext_match(state, state->fuzzy_node, data->new_text_pos))
10107 return RE_ERROR_FAILURE;
10108
10109 data->new_text_pos = new_pos;
10110
10111 if (is_string)
10112 data->new_string_pos += step;
10113 else
10114 data->new_node = data->new_node->next_1.node;
10115
10116 return RE_ERROR_SUCCESS;
10117 }
10118
10119 return check_fuzzy_partial(state, new_pos);
10120 }
10121
10122 return RE_ERROR_FAILURE;
10123 }
10124
10125 /* Tries a fuzzy match of an item of width 0 or 1. */
10126 Py_LOCAL_INLINE(int) fuzzy_match_item(RE_State* state, BOOL search, RE_Node**
10127 node, RE_INT8 step) {
10128 size_t* fuzzy_counts;
10129 RE_FuzzyData data;
10130 TRACE(("<<fuzzy_match_item>>\n"))
10131
10132 fuzzy_counts = state->fuzzy_counts;
10133
10134 if (!any_error_permitted(state)) {
10135 TRACE((" return RE_ERROR_FAILURE\n"))
10136 return RE_ERROR_FAILURE;
10137 }
10138
10139 data.new_node = *node;
10140
10141 if (step == 0) {
10142 if (data.new_node->status & RE_STATUS_REVERSE) {
10143 data.step = -1;
10144 data.limit = state->slice_start;
10145 } else {
10146 data.step = 1;
10147 data.limit = state->slice_end;
10148 }
10149 } else
10150 data.step = step;
10151
10152 /* Permit insertion except initially when searching (it's better just to
10153 * start searching one character later).
10154 */
10155 data.permit_insertion = !search || state->text_pos != state->search_anchor;
10156
10157 for (data.fuzzy_type = 0; data.fuzzy_type < RE_FUZZY_COUNT;
10158 data.fuzzy_type++) {
10159 int status;
10160
10161 status = next_fuzzy_match_item(state, &data, FALSE, step);
10162 if (status < 0)
10163 return status;
10164
10165 if (status == RE_ERROR_SUCCESS)
10166 goto found;
10167 }
10168
10169 TRACE((" return RE_ERROR_FAILURE\n"))
10170 return RE_ERROR_FAILURE;
10171
10172 found:
10173 if (!push_pointer(state, &state->bstack, *node))
10174 return RE_ERROR_MEMORY;
10175 if (!push_int8(state, &state->bstack, step))
10176 return RE_ERROR_MEMORY;
10177 if (!push_ssize(state, &state->bstack, state->text_pos))
10178 return RE_ERROR_MEMORY;
10179 if (!push_uint8(state, &state->bstack, data.fuzzy_type))
10180 return RE_ERROR_MEMORY;
10181 if (!push_uint8(state, &state->bstack, (*node)->op))
10182 return RE_ERROR_MEMORY;
10183
10184 /* bstack: node step text_pos fuzzy_type op */
10185
10186 if (!record_fuzzy(state, data.fuzzy_type, data.fuzzy_type == RE_FUZZY_DEL ?
10187 data.new_text_pos : data.new_text_pos - data.step))
10188 return RE_ERROR_MEMORY;
10189
10190 ++fuzzy_counts[data.fuzzy_type];
10191 ++state->capture_change;
10192
10193 state->text_pos = data.new_text_pos;
10194 *node = data.new_node;
10195
10196 TRACE((" fuzzy_counts is (%zd, %zd, %zd)\n", fuzzy_counts[0],
10197 fuzzy_counts[1], fuzzy_counts[2]))
10198 TRACE((" return RE_ERROR_SUCCESS\n"))
10199 return RE_ERROR_SUCCESS;
10200 }
10201
10202 /* Retries a fuzzy match of a item of width 0 or 1. */
10203 Py_LOCAL_INLINE(int) retry_fuzzy_match_item(RE_State* state, RE_UINT8 op, BOOL
10204 search, RE_Node** node, BOOL advance) {
10205 size_t* fuzzy_counts;
10206 RE_FuzzyData data;
10207 RE_INT8 step;
10208 RE_Node* curr_node;
10209 TRACE(("<<retry_fuzzy_match_item>>\n"))
10210
10211 fuzzy_counts = state->fuzzy_counts;
10212
10213 unrecord_fuzzy(state);
10214
10215 /* bstack: node step text_pos fuzzy_type */
10216
10217 if (!pop_uint8(state, &state->bstack, &data.fuzzy_type))
10218 return RE_ERROR_MEMORY;
10219 if (!pop_ssize(state, &state->bstack, &state->text_pos))
10220 return RE_ERROR_MEMORY;
10221 if (!pop_int8(state, &state->bstack, &step))
10222 return RE_ERROR_MEMORY;
10223 if (!pop_pointer(state, &state->bstack, (void*)&curr_node))
10224 return RE_ERROR_MEMORY;
10225
10226 data.new_node = curr_node;
10227 data.step = step;
10228
10229 /* bstack: - */
10230
10231 if (data.fuzzy_type >= 0)
10232 --fuzzy_counts[data.fuzzy_type];
10233
10234 /* Permit insertion except initially when searching (it's better just to
10235 * start searching one character later).
10236 */
10237 data.permit_insertion = !search || state->text_pos != state->search_anchor;
10238
10239 step = advance ? data.step : 0;
10240
10241 for (++data.fuzzy_type; data.fuzzy_type < RE_FUZZY_COUNT;
10242 data.fuzzy_type++) {
10243 int status;
10244
10245 status = next_fuzzy_match_item(state, &data, FALSE, step);
10246 if (status < 0)
10247 return status;
10248
10249 if (status == RE_ERROR_SUCCESS)
10250 goto found;
10251 }
10252
10253 TRACE((" return RE_ERROR_FAILURE\n"))
10254 return RE_ERROR_FAILURE;
10255
10256 found:
10257 if (!push_pointer(state, &state->bstack, curr_node))
10258 return RE_ERROR_MEMORY;
10259 if (!push_int8(state, &state->bstack, step))
10260 return RE_ERROR_MEMORY;
10261 if (!push_ssize(state, &state->bstack, state->text_pos))
10262 return RE_ERROR_MEMORY;
10263 if (!push_uint8(state, &state->bstack, data.fuzzy_type))
10264 return RE_ERROR_MEMORY;
10265 if (!push_uint8(state, &state->bstack, op))
10266 return RE_ERROR_MEMORY;
10267
10268 /* bstack: node step text_pos fuzzy_type op */
10269
10270 if (!record_fuzzy(state, data.fuzzy_type, data.fuzzy_type == RE_FUZZY_DEL ?
10271 data.new_text_pos : data.new_text_pos - data.step))
10272 return RE_ERROR_MEMORY;
10273
10274 ++fuzzy_counts[data.fuzzy_type];
10275 ++state->capture_change;
10276
10277 state->text_pos = data.new_text_pos;
10278 *node = data.new_node;
10279
10280 TRACE((" fuzzy_counts is (%zd, %zd, %zd)\n", fuzzy_counts[0],
10281 fuzzy_counts[1], fuzzy_counts[2]))
10282 TRACE((" return RE_ERROR_SUCCESS\n"))
10283 return RE_ERROR_SUCCESS;
10284 }
10285
10286 /* Tries a fuzzy insertion of characters, initially 0, after a string. */
10287 Py_LOCAL_INLINE(int) fuzzy_insert(RE_State* state, int step, RE_Node* node) {
10288 Py_ssize_t limit;
10289
10290 limit = step > 0 ? state->slice_end : state->slice_start;
10291
10292 if (state->text_pos == limit || !insertion_permitted(state,
10293 state->fuzzy_node, state->fuzzy_counts))
10294 return RE_ERROR_SUCCESS;
10295
10296 if (!push_int8(state, &state->bstack, (RE_INT8)step))
10297 return RE_ERROR_MEMORY;
10298 if (!push_ssize(state, &state->bstack, state->text_pos))
10299 return RE_ERROR_MEMORY;
10300 if (!push_ssize(state, &state->bstack, 0))
10301 return RE_ERROR_MEMORY;
10302 if (!push_pointer(state, &state->bstack, node))
10303 return RE_ERROR_MEMORY;
10304 if (!push_uint8(state, &state->bstack, RE_OP_FUZZY_INSERT))
10305 return RE_ERROR_MEMORY;
10306
10307 /* bstack: step text_pos count node FUZZY_INSERT */
10308
10309 return RE_ERROR_SUCCESS;
10310 }
10311
10312 /* Retries a fuzzy insertion of characters after a string. */
10313 Py_LOCAL_INLINE(int) retry_fuzzy_insert(RE_State* state, RE_Node** node) {
10314 RE_Node* curr_node;
10315 Py_ssize_t count;
10316 RE_INT8 step;
10317 Py_ssize_t limit;
10318
10319 /* bstack: step text_pos count node */
10320
10321 if (!pop_pointer(state, &state->bstack, (void*)&curr_node))
10322 return RE_ERROR_MEMORY;
10323 if (!pop_ssize(state, &state->bstack, &count))
10324 return RE_ERROR_MEMORY;
10325 if (!pop_ssize(state, &state->bstack, &state->text_pos))
10326 return RE_ERROR_MEMORY;
10327 if (!pop_int8(state, &state->bstack, &step))
10328 return RE_ERROR_MEMORY;
10329
10330 limit = step > 0 ? state->slice_end : state->slice_start;
10331
10332 if (state->text_pos == limit || !insertion_permitted(state,
10333 state->fuzzy_node, state->fuzzy_counts) || !fuzzy_ext_match(state,
10334 state->fuzzy_node, state->text_pos)) {
10335 while (count > 0) {
10336 unrecord_fuzzy(state);
10337 --state->fuzzy_counts[RE_FUZZY_INS];
10338 --count;
10339 }
10340
10341 return RE_ERROR_FAILURE;
10342 }
10343
10344 state->text_pos += step;
10345 ++count;
10346
10347 if (!push_int8(state, &state->bstack, step))
10348 return RE_ERROR_MEMORY;
10349 if (!push_ssize(state, &state->bstack, state->text_pos))
10350 return RE_ERROR_MEMORY;
10351 if (!push_ssize(state, &state->bstack, count))
10352 return RE_ERROR_MEMORY;
10353 if (!push_pointer(state, &state->bstack, curr_node))
10354 return RE_ERROR_MEMORY;
10355 if (!push_uint8(state, &state->bstack, RE_OP_FUZZY_INSERT))
10356 return RE_ERROR_MEMORY;
10357
10358 /* bstack: step text_pos count node FUZZY_INSERT */
10359
10360 if (!record_fuzzy(state, RE_FUZZY_INS, state->text_pos - step))
10361 return RE_ERROR_MEMORY;
10362
10363 ++state->fuzzy_counts[RE_FUZZY_INS];
10364 ++state->capture_change;
10365
10366 *node = curr_node;
10367
10368 return RE_ERROR_SUCCESS;
10369 }
10370
10371 /* Tries a fuzzy match of a string. */
10372 Py_LOCAL_INLINE(int) fuzzy_match_string(RE_State* state, BOOL search, RE_Node*
10373 node, Py_ssize_t* string_pos, RE_INT8 step) {
10374 size_t* fuzzy_counts;
10375 RE_FuzzyData data;
10376 TRACE(("<<fuzzy_match_string>>\n"))
10377
10378 fuzzy_counts = state->fuzzy_counts;
10379
10380 if (!any_error_permitted(state)) {
10381 TRACE((" return RE_ERROR_FAILURE\n"))
10382 return RE_ERROR_FAILURE;
10383 }
10384
10385 data.new_string_pos = *string_pos;
10386 data.step = step;
10387
10388 /* Permit insertion except initially when searching (it's better just to
10389 * start searching one character later).
10390 */
10391 data.permit_insertion = !search || state->text_pos != state->search_anchor;
10392
10393 for (data.fuzzy_type = 0; data.fuzzy_type < RE_FUZZY_COUNT;
10394 data.fuzzy_type++) {
10395 int status;
10396
10397 status = next_fuzzy_match_item(state, &data, TRUE, data.step);
10398 if (status < 0)
10399 return status;
10400
10401 if (status == RE_ERROR_SUCCESS)
10402 goto found;
10403 }
10404
10405 TRACE((" return RE_ERROR_FAILURE\n"))
10406 return RE_ERROR_FAILURE;
10407
10408 found:
10409 if (!push_pointer(state, &state->bstack, node))
10410 return RE_ERROR_MEMORY;
10411 if (!push_int8(state, &state->bstack, step))
10412 return RE_ERROR_MEMORY;
10413 if (!push_ssize(state, &state->bstack, *string_pos))
10414 return RE_ERROR_MEMORY;
10415 if (!push_ssize(state, &state->bstack, state->text_pos))
10416 return RE_ERROR_MEMORY;
10417 if (!push_uint8(state, &state->bstack, data.fuzzy_type))
10418 return RE_ERROR_MEMORY;
10419 if (!push_uint8(state, &state->bstack, node->op))
10420 return RE_ERROR_MEMORY;
10421
10422 /* bstack: node step string_pos text_pos fuzzy_type op */
10423
10424 if (!record_fuzzy(state, data.fuzzy_type, state->text_pos))
10425 return RE_ERROR_MEMORY;
10426
10427 ++fuzzy_counts[data.fuzzy_type];
10428 ++state->capture_change;
10429
10430 state->text_pos = data.new_text_pos;
10431 *string_pos = data.new_string_pos;
10432
10433 TRACE((" fuzzy_counts is (%zd, %zd, %zd)\n", fuzzy_counts[0],
10434 fuzzy_counts[1], fuzzy_counts[2]))
10435 TRACE((" return RE_ERROR_SUCCESS\n"))
10436 return RE_ERROR_SUCCESS;
10437 }
10438
10439 /* Retries a fuzzy match of a string. */
10440 Py_LOCAL_INLINE(int) retry_fuzzy_match_string(RE_State* state, RE_UINT8 op,
10441 BOOL search, RE_Node** node, Py_ssize_t* string_pos) {
10442 size_t* fuzzy_counts;
10443 RE_FuzzyData data;
10444 RE_Node* new_node;
10445 TRACE(("<<retry_fuzzy_match_string>>\n"))
10446
10447 fuzzy_counts = state->fuzzy_counts;
10448
10449 unrecord_fuzzy(state);
10450
10451 /* bstack: node step string_pos text_pos fuzzy_type */
10452
10453 if (!pop_uint8(state, &state->bstack, &data.fuzzy_type))
10454 return RE_ERROR_MEMORY;
10455 if (!pop_ssize(state, &state->bstack, &state->text_pos))
10456 return RE_ERROR_MEMORY;
10457 if (!pop_ssize(state, &state->bstack, string_pos))
10458 return RE_ERROR_MEMORY;
10459 if (!pop_int8(state, &state->bstack, &data.step))
10460 return RE_ERROR_MEMORY;
10461 if (!pop_pointer(state, &state->bstack, (void*)&new_node))
10462 return RE_ERROR_MEMORY;
10463
10464 data.new_string_pos = *string_pos;
10465
10466 --fuzzy_counts[data.fuzzy_type];
10467
10468 /* Permit insertion except initially when searching (it's better just to
10469 * start searching one character later).
10470 */
10471 data.permit_insertion = !search || state->text_pos != state->search_anchor;
10472
10473 for (++data.fuzzy_type; data.fuzzy_type < RE_FUZZY_COUNT;
10474 data.fuzzy_type++) {
10475 int status;
10476
10477 status = next_fuzzy_match_item(state, &data, TRUE, data.step);
10478 if (status < 0)
10479 return status;
10480
10481 if (status == RE_ERROR_SUCCESS)
10482 goto found;
10483 }
10484
10485 TRACE((" return RE_ERROR_FAILURE\n"))
10486 return RE_ERROR_FAILURE;
10487
10488 found:
10489 if (!push_pointer(state, &state->bstack, new_node))
10490 return RE_ERROR_MEMORY;
10491 if (!push_int8(state, &state->bstack, data.step))
10492 return RE_ERROR_MEMORY;
10493 if (!push_ssize(state, &state->bstack, *string_pos))
10494 return RE_ERROR_MEMORY;
10495 if (!push_ssize(state, &state->bstack, state->text_pos))
10496 return RE_ERROR_MEMORY;
10497 if (!push_uint8(state, &state->bstack, data.fuzzy_type))
10498 return RE_ERROR_MEMORY;
10499 if (!push_uint8(state, &state->bstack, op))
10500 return RE_ERROR_MEMORY;
10501
10502 if (!record_fuzzy(state, data.fuzzy_type, state->text_pos))
10503 return RE_ERROR_MEMORY;
10504
10505 /* bstack: node step string_pos text_pos fuzzy_type op */
10506
10507 ++fuzzy_counts[data.fuzzy_type];
10508 ++state->capture_change;
10509
10510 state->text_pos = data.new_text_pos;
10511 *node = new_node;
10512 *string_pos = data.new_string_pos;
10513
10514 TRACE((" fuzzy_counts is (%zd, %zd, %zd)\n", fuzzy_counts[0],
10515 fuzzy_counts[1], fuzzy_counts[2]))
10516 TRACE((" return RE_ERROR_SUCCESS\n"))
10517 return RE_ERROR_SUCCESS;
10518 }
10519
10520 /* Checks a fuzzy match of a atring. */
10521 Py_LOCAL_INLINE(int) next_fuzzy_match_string_fld(RE_State* state, RE_FuzzyData*
10522 data) {
10523 int new_pos;
10524
10525 if (!this_error_permitted(state, data->fuzzy_type))
10526 return RE_ERROR_FAILURE;
10527
10528 data->new_text_pos = state->text_pos;
10529
10530 switch (data->fuzzy_type) {
10531 case RE_FUZZY_DEL:
10532 /* Could a character at text_pos have been deleted? */
10533 data->new_string_pos += data->step;
10534
10535 return RE_ERROR_SUCCESS;
10536 case RE_FUZZY_INS:
10537 /* Could the character at text_pos have been inserted? */
10538 if (!data->permit_insertion)
10539 return RE_ERROR_FAILURE;
10540
10541 new_pos = data->new_folded_pos + data->step;
10542
10543 if (0 <= new_pos && new_pos <= data->folded_len) {
10544 if (!fuzzy_ext_match(state, state->fuzzy_node,
10545 data->new_string_pos))
10546 return RE_ERROR_FAILURE;
10547
10548 data->new_folded_pos = new_pos;
10549
10550 return RE_ERROR_SUCCESS;
10551 }
10552
10553 return check_fuzzy_partial(state, new_pos);
10554 case RE_FUZZY_SUB:
10555 /* Could the character at text_pos have been substituted? */
10556 new_pos = data->new_folded_pos + data->step;
10557
10558 if (0 <= new_pos && new_pos <= data->folded_len) {
10559 if (!fuzzy_ext_match(state, state->fuzzy_node,
10560 data->new_string_pos))
10561 return RE_ERROR_FAILURE;
10562
10563 data->new_folded_pos = new_pos;
10564 data->new_string_pos += data->step;
10565
10566 return RE_ERROR_SUCCESS;
10567 }
10568
10569 return check_fuzzy_partial(state, new_pos);
10570 }
10571
10572 return RE_ERROR_FAILURE;
10573 }
10574
10575 /* Tries a fuzzy match of a string, ignoring case. */
10576 Py_LOCAL_INLINE(int) fuzzy_match_string_fld(RE_State* state, BOOL search,
10577 RE_Node* node, Py_ssize_t* string_pos, int* folded_pos, int folded_len,
10578 RE_INT8 step) {
10579 size_t* fuzzy_counts;
10580 RE_FuzzyData data;
10581 TRACE(("<<fuzzy_match_string_fld>>\n"))
10582
10583 fuzzy_counts = state->fuzzy_counts;
10584
10585 if (!any_error_permitted(state)) {
10586 TRACE((" return RE_ERROR_FAILURE\n"))
10587 return RE_ERROR_FAILURE;
10588 }
10589
10590 data.new_string_pos = *string_pos;
10591 data.new_folded_pos = *folded_pos;
10592 data.folded_len = folded_len;
10593 data.step = step;
10594
10595 /* Permit insertion except initially when searching (it's better just to
10596 * start searching one character later).
10597 */
10598 data.permit_insertion = !search || state->text_pos != state->search_anchor;
10599
10600 if (step > 0) {
10601 if (data.new_folded_pos != 0)
10602 data.permit_insertion = RE_ERROR_SUCCESS;
10603 } else {
10604 if (data.new_folded_pos != folded_len)
10605 data.permit_insertion = RE_ERROR_SUCCESS;
10606 }
10607
10608 for (data.fuzzy_type = 0; data.fuzzy_type < RE_FUZZY_COUNT;
10609 data.fuzzy_type++) {
10610 int status;
10611
10612 status = next_fuzzy_match_string_fld(state, &data);
10613 if (status < 0)
10614 return status;
10615
10616 if (status == RE_ERROR_SUCCESS)
10617 goto found;
10618 }
10619
10620 TRACE((" return RE_ERROR_FAILURE\n"))
10621 return RE_ERROR_FAILURE;
10622
10623 found:
10624 if (!push_pointer(state, &state->bstack, node))
10625 return RE_ERROR_MEMORY;
10626 if (!push_int8(state, &state->bstack, step))
10627 return RE_ERROR_MEMORY;
10628 if (!push_ssize(state, &state->bstack, *string_pos))
10629 return RE_ERROR_MEMORY;
10630 if (!push_int(state, &state->bstack, *folded_pos))
10631 return RE_ERROR_MEMORY;
10632 if (!push_int(state, &state->bstack, folded_len))
10633 return RE_ERROR_MEMORY;
10634 if (!push_ssize(state, &state->bstack, state->text_pos))
10635 return RE_ERROR_MEMORY;
10636 if (!push_uint8(state, &state->bstack, data.fuzzy_type))
10637 return RE_ERROR_MEMORY;
10638 if (!push_uint8(state, &state->bstack, node->op))
10639 return RE_ERROR_MEMORY;
10640
10641 /* bstack: node step string_pos folded_pos folded_len text_pos fuzzy_type
10642 * op
10643 */
10644
10645 if (!record_fuzzy(state, data.fuzzy_type, state->text_pos))
10646 return RE_ERROR_MEMORY;
10647
10648 ++fuzzy_counts[data.fuzzy_type];
10649 ++state->capture_change;
10650
10651 state->text_pos = data.new_text_pos;
10652 *string_pos = data.new_string_pos;
10653 *folded_pos = data.new_folded_pos;
10654
10655 TRACE((" fuzzy_counts is (%zd, %zd, %zd)\n", fuzzy_counts[0],
10656 fuzzy_counts[1], fuzzy_counts[2]))
10657 TRACE((" return RE_ERROR_SUCCESS\n"))
10658 return RE_ERROR_SUCCESS;
10659 }
10660
10661 /* Retries a fuzzy match of a string, ignoring case. */
10662 Py_LOCAL_INLINE(int) retry_fuzzy_match_string_fld(RE_State* state, RE_UINT8 op,
10663 BOOL search, RE_Node** node, Py_ssize_t* string_pos, int* folded_pos) {
10664 size_t* fuzzy_counts;
10665 RE_FuzzyData data;
10666 int curr_folded_pos;
10667 RE_Node* new_node;
10668 TRACE(("<<retry_fuzzy_match_string_fld>>\n"))
10669
10670 fuzzy_counts = state->fuzzy_counts;
10671
10672 unrecord_fuzzy(state);
10673
10674 /* bstack: node step string_pos folded_pos folded_len text_pos fuzzy_type
10675 */
10676
10677 if (!pop_uint8(state, &state->bstack, &data.fuzzy_type))
10678 return RE_ERROR_MEMORY;
10679 if (!pop_ssize(state, &state->bstack, &state->text_pos))
10680 return RE_ERROR_MEMORY;
10681 if (!pop_int(state, &state->bstack, &data.folded_len))
10682 return RE_ERROR_MEMORY;
10683 if (!pop_int(state, &state->bstack, &curr_folded_pos))
10684 return RE_ERROR_MEMORY;
10685 if (!pop_ssize(state, &state->bstack, string_pos))
10686 return RE_ERROR_MEMORY;
10687 if (!pop_int8(state, &state->bstack, &data.step))
10688 return RE_ERROR_MEMORY;
10689 if (!pop_pointer(state, &state->bstack, (void*)&new_node))
10690 return RE_ERROR_MEMORY;
10691
10692 data.new_string_pos = *string_pos;
10693 data.new_folded_pos = curr_folded_pos;
10694
10695 --fuzzy_counts[data.fuzzy_type];
10696
10697 /* Permit insertion except initially when searching (it's better just to
10698 * start searching one character later).
10699 */
10700 data.permit_insertion = !search || state->text_pos != state->search_anchor;
10701
10702 if (data.step > 0) {
10703 if (data.new_folded_pos != 0)
10704 data.permit_insertion = RE_ERROR_SUCCESS;
10705 } else {
10706 if (data.new_folded_pos != data.folded_len)
10707 data.permit_insertion = RE_ERROR_SUCCESS;
10708 }
10709
10710 for (++data.fuzzy_type; data.fuzzy_type < RE_FUZZY_COUNT;
10711 data.fuzzy_type++) {
10712 int status;
10713
10714 status = next_fuzzy_match_string_fld(state, &data);
10715 if (status < 0)
10716 return status;
10717
10718 if (status == RE_ERROR_SUCCESS)
10719 goto found;
10720 }
10721
10722 TRACE((" return RE_ERROR_FAILURE\n"))
10723 return RE_ERROR_FAILURE;
10724
10725 found:
10726 if (!push_pointer(state, &state->bstack, new_node))
10727 return RE_ERROR_MEMORY;
10728 if (!push_int8(state, &state->bstack, data.step))
10729 return RE_ERROR_MEMORY;
10730 if (!push_ssize(state, &state->bstack, *string_pos))
10731 return RE_ERROR_MEMORY;
10732 if (!push_int(state, &state->bstack, curr_folded_pos))
10733 return RE_ERROR_MEMORY;
10734 if (!push_int(state, &state->bstack, data.folded_len))
10735 return RE_ERROR_MEMORY;
10736 if (!push_ssize(state, &state->bstack, state->text_pos))
10737 return RE_ERROR_MEMORY;
10738 if (!push_uint8(state, &state->bstack, data.fuzzy_type))
10739 return RE_ERROR_MEMORY;
10740 if (!push_uint8(state, &state->bstack, op))
10741 return RE_ERROR_MEMORY;
10742
10743 if (!record_fuzzy(state, data.fuzzy_type, state->text_pos))
10744 return RE_ERROR_MEMORY;
10745
10746 /* bstack: node step string_pos folded_pos folded_len text_pos fuzzy_type
10747 * op
10748 */
10749
10750 ++fuzzy_counts[data.fuzzy_type];
10751 ++state->capture_change;
10752
10753 state->text_pos = data.new_text_pos;
10754 *node = new_node;
10755 *string_pos = data.new_string_pos;
10756 *folded_pos = data.new_folded_pos;
10757
10758 TRACE((" fuzzy_counts is (%zd, %zd, %zd)\n", fuzzy_counts[0],
10759 fuzzy_counts[1], fuzzy_counts[2]))
10760 TRACE((" return RE_ERROR_SUCCESS\n"))
10761 return RE_ERROR_SUCCESS;
10762 }
10763
10764 /* Checks a fuzzy match of a atring. */
10765 Py_LOCAL_INLINE(int) next_fuzzy_match_group_fld(RE_State* state, RE_FuzzyData*
10766 data) {
10767 int new_pos;
10768
10769 if (!this_error_permitted(state, data->fuzzy_type))
10770 return RE_ERROR_FAILURE;
10771
10772 data->new_text_pos = state->text_pos;
10773
10774 switch (data->fuzzy_type) {
10775 case RE_FUZZY_DEL:
10776 /* Could a character at text_pos have been deleted? */
10777 data->new_gfolded_pos += data->step;
10778
10779 return RE_ERROR_SUCCESS;
10780 case RE_FUZZY_INS:
10781 /* Could the character at text_pos have been inserted? */
10782 if (!data->permit_insertion)
10783 return RE_ERROR_FAILURE;
10784
10785 new_pos = data->new_folded_pos + data->step;
10786
10787 if (0 <= new_pos && new_pos <= data->folded_len) {
10788 if (!fuzzy_ext_match_group_fld(state, state->fuzzy_node,
10789 data->new_folded_pos))
10790 return RE_ERROR_FAILURE;
10791
10792 data->new_folded_pos = new_pos;
10793
10794 return RE_ERROR_SUCCESS;
10795 }
10796
10797 return check_fuzzy_partial(state, new_pos);
10798 case RE_FUZZY_SUB:
10799 /* Could the character at text_pos have been substituted? */
10800 new_pos = data->new_folded_pos + data->step;
10801
10802 if (0 <= new_pos && new_pos <= data->folded_len) {
10803 if (!fuzzy_ext_match_group_fld(state, state->fuzzy_node,
10804 data->new_folded_pos))
10805 return RE_ERROR_FAILURE;
10806
10807 data->new_folded_pos = new_pos;
10808 data->new_gfolded_pos += data->step;
10809
10810 return RE_ERROR_SUCCESS;
10811 }
10812
10813 return check_fuzzy_partial(state, new_pos);
10814 }
10815
10816 return RE_ERROR_FAILURE;
10817 }
10818
10819 /* Tries a fuzzy match of a group reference, ignoring case. */
10820 Py_LOCAL_INLINE(int) fuzzy_match_group_fld(RE_State* state, BOOL search,
10821 RE_Node* node, int* folded_pos, int folded_len, Py_ssize_t* group_pos, int*
10822 gfolded_pos, int gfolded_len, RE_INT8 step) {
10823 size_t* fuzzy_counts;
10824 RE_FuzzyData data;
10825 Py_ssize_t new_group_pos;
10826 TRACE(("<<fuzzy_match_group_fld>>\n"))
10827
10828 fuzzy_counts = state->fuzzy_counts;
10829
10830 if (!any_error_permitted(state)) {
10831 TRACE((" return RE_ERROR_FAILURE\n"))
10832 return RE_ERROR_FAILURE;
10833 }
10834
10835 data.new_folded_pos = *folded_pos;
10836 data.folded_len = folded_len;
10837 new_group_pos = *group_pos;
10838 data.new_gfolded_pos = *gfolded_pos;
10839 data.step = step;
10840
10841 /* Permit insertion except initially when searching (it's better just to
10842 * start searching one character later).
10843 */
10844 data.permit_insertion = !search || state->text_pos != state->search_anchor;
10845
10846 if (data.step > 0) {
10847 if (data.new_folded_pos != 0)
10848 data.permit_insertion = RE_ERROR_SUCCESS;
10849 } else {
10850 if (data.new_folded_pos != folded_len)
10851 data.permit_insertion = RE_ERROR_SUCCESS;
10852 }
10853
10854 for (data.fuzzy_type = 0; data.fuzzy_type < RE_FUZZY_COUNT;
10855 data.fuzzy_type++) {
10856 int status;
10857
10858 status = next_fuzzy_match_group_fld(state, &data);
10859 if (status < 0)
10860 return status;
10861
10862 if (status == RE_ERROR_SUCCESS)
10863 goto found;
10864 }
10865
10866 TRACE((" return RE_ERROR_FAILURE\n"))
10867 return RE_ERROR_FAILURE;
10868
10869 found:
10870 if (!push_pointer(state, &state->bstack, node))
10871 return RE_ERROR_MEMORY;
10872 if (!push_int8(state, &state->bstack, step))
10873 return RE_ERROR_MEMORY;
10874 if (!push_int(state, &state->bstack, *gfolded_pos))
10875 return RE_ERROR_MEMORY;
10876 if (!push_int(state, &state->bstack, gfolded_len))
10877 return RE_ERROR_MEMORY;
10878 if (!push_ssize(state, &state->bstack, *group_pos))
10879 return RE_ERROR_MEMORY;
10880 if (!push_int(state, &state->bstack, *folded_pos))
10881 return RE_ERROR_MEMORY;
10882 if (!push_int(state, &state->bstack, folded_len))
10883 return RE_ERROR_MEMORY;
10884 if (!push_ssize(state, &state->bstack, state->text_pos))
10885 return RE_ERROR_MEMORY;
10886 if (!push_uint8(state, &state->bstack, data.fuzzy_type))
10887 return RE_ERROR_MEMORY;
10888 if (!push_uint8(state, &state->bstack, node->op))
10889 return RE_ERROR_MEMORY;
10890
10891 /* bstack: node step gfolded_pos gfolded_len group_pos folded_pos
10892 * folded_len text_pos fuzzy_type op
10893 */
10894
10895 if (!record_fuzzy(state, data.fuzzy_type, state->text_pos))
10896 return RE_ERROR_MEMORY;
10897
10898 ++fuzzy_counts[data.fuzzy_type];
10899 ++state->capture_change;
10900
10901 state->text_pos = data.new_text_pos;
10902 *group_pos = new_group_pos;
10903 *folded_pos = data.new_folded_pos;
10904 *gfolded_pos = data.new_gfolded_pos;
10905
10906 TRACE((" fuzzy_counts is (%zd, %zd, %zd)\n", fuzzy_counts[0],
10907 fuzzy_counts[1], fuzzy_counts[2]))
10908 TRACE((" return RE_ERROR_SUCCESS\n"))
10909 return RE_ERROR_SUCCESS;
10910 }
10911
10912 /* Retries a fuzzy match of a group reference, ignoring case. */
10913 Py_LOCAL_INLINE(int) retry_fuzzy_match_group_fld(RE_State* state, RE_UINT8 op,
10914 BOOL search, RE_Node** node, int* folded_pos, Py_ssize_t* group_pos, int*
10915 gfolded_pos) {
10916 size_t* fuzzy_counts;
10917 RE_FuzzyData data;
10918 int new_folded_pos;
10919 Py_ssize_t new_group_pos;
10920 int gfolded_len;
10921 int new_gfolded_pos;
10922 RE_Node* new_node;
10923 TRACE(("<<retry_fuzzy_match_group_fld>>\n"))
10924
10925 fuzzy_counts = state->fuzzy_counts;
10926
10927 unrecord_fuzzy(state);
10928
10929 /* bstack: node step gfolded_pos gfolded_len group_pos folded_pos
10930 * folded_len text_pos fuzzy_type
10931 */
10932
10933 if (!pop_uint8(state, &state->bstack, &data.fuzzy_type))
10934 return RE_ERROR_MEMORY;
10935 if (!pop_ssize(state, &state->bstack, &state->text_pos))
10936 return RE_ERROR_MEMORY;
10937 if (!pop_int(state, &state->bstack, &data.folded_len))
10938 return RE_ERROR_MEMORY;
10939 if (!pop_int(state, &state->bstack, &new_folded_pos))
10940 return RE_ERROR_MEMORY;
10941 if (!pop_ssize(state, &state->bstack, &new_group_pos))
10942 return RE_ERROR_MEMORY;
10943 if (!pop_int(state, &state->bstack, &gfolded_len))
10944 return RE_ERROR_MEMORY;
10945 if (!pop_int(state, &state->bstack, &new_gfolded_pos))
10946 return RE_ERROR_MEMORY;
10947 if (!pop_int8(state, &state->bstack, &data.step))
10948 return RE_ERROR_MEMORY;
10949 if (!pop_pointer(state, &state->bstack, (void*)&new_node))
10950 return RE_ERROR_MEMORY;
10951
10952 data.new_folded_pos = new_folded_pos;
10953 data.new_gfolded_pos = new_gfolded_pos;
10954
10955 --fuzzy_counts[data.fuzzy_type];
10956
10957 /* Permit insertion except initially when searching (it's better just to
10958 * start searching one character later).
10959 */
10960 data.permit_insertion = !search || state->text_pos != state->search_anchor
10961 || data.new_folded_pos != data.folded_len;
10962
10963 for (++data.fuzzy_type; data.fuzzy_type < RE_FUZZY_COUNT;
10964 data.fuzzy_type++) {
10965 int status;
10966
10967 status = next_fuzzy_match_group_fld(state, &data);
10968 if (status < 0)
10969 return status;
10970
10971 if (status == RE_ERROR_SUCCESS)
10972 goto found;
10973 }
10974
10975 TRACE((" return RE_ERROR_FAILURE\n"))
10976 return RE_ERROR_FAILURE;
10977
10978 found:
10979 if (!push_pointer(state, &state->bstack, new_node))
10980 return RE_ERROR_MEMORY;
10981 if (!push_int8(state, &state->bstack, data.step))
10982 return RE_ERROR_MEMORY;
10983 if (!push_int(state, &state->bstack, new_gfolded_pos))
10984 return RE_ERROR_MEMORY;
10985 if (!push_int(state, &state->bstack, gfolded_len))
10986 return RE_ERROR_MEMORY;
10987 if (!push_ssize(state, &state->bstack, new_group_pos))
10988 return RE_ERROR_MEMORY;
10989 if (!push_int(state, &state->bstack, new_folded_pos))
10990 return RE_ERROR_MEMORY;
10991 if (!push_int(state, &state->bstack, data.folded_len))
10992 return RE_ERROR_MEMORY;
10993 if (!push_ssize(state, &state->bstack, state->text_pos))
10994 return RE_ERROR_MEMORY;
10995 if (!push_uint8(state, &state->bstack, data.fuzzy_type))
10996 return RE_ERROR_MEMORY;
10997 if (!push_uint8(state, &state->bstack, op))
10998 return RE_ERROR_MEMORY;
10999
11000 if (!record_fuzzy(state, data.fuzzy_type, state->text_pos))
11001 return RE_ERROR_MEMORY;
11002
11003 /* bstack: node step gfolded_pos gfolded_len group_pos folded_pos
11004 * folded_len text_pos fuzzy_type op
11005 */
11006
11007 ++fuzzy_counts[data.fuzzy_type];
11008 ++state->capture_change;
11009
11010 state->text_pos = data.new_text_pos;
11011 *node = new_node;
11012 *group_pos = new_group_pos;
11013 *folded_pos = data.new_folded_pos;
11014 *gfolded_pos = data.new_gfolded_pos;
11015
11016 TRACE((" fuzzy_counts is (%zd, %zd, %zd)\n", fuzzy_counts[0],
11017 fuzzy_counts[1], fuzzy_counts[2]))
11018 TRACE((" return RE_ERROR_SUCCESS\n"))
11019 return RE_ERROR_SUCCESS;
11020 }
11021
11022 /* Locates the required string, if there's one. */
11023 Py_LOCAL_INLINE(Py_ssize_t) locate_required_string(RE_State* state, BOOL
11024 search) {
11025 PatternObject* pattern;
11026 Py_ssize_t found_pos;
11027 Py_ssize_t end_pos;
11028
11029 pattern = state->pattern;
11030
11031 if (!pattern->req_string)
11032 /* There isn't a required string, so start matching from the current
11033 * position.
11034 */
11035 return state->text_pos;
11036
11037 /* Search for the required string and calculate where to start matching. */
11038 switch (pattern->req_string->op) {
11039 case RE_OP_STRING:
11040 {
11041 BOOL is_partial;
11042 Py_ssize_t limit;
11043
11044 if (search || pattern->req_offset < 0)
11045 limit = state->slice_end;
11046 else {
11047 limit = state->slice_start + pattern->req_offset +
11048 (Py_ssize_t)pattern->req_string->value_count;
11049 if (limit > state->slice_end)
11050 limit = state->slice_end;
11051 }
11052
11053 if (state->req_pos < 0 || state->text_pos > state->req_pos)
11054 /* First time or already passed it. */
11055 found_pos = string_search(state, pattern->req_string,
11056 state->text_pos, limit, TRUE, &is_partial);
11057 else {
11058 found_pos = state->req_pos;
11059 end_pos = state->req_end;
11060 is_partial = FALSE;
11061 }
11062
11063 if (found_pos < 0)
11064 /* The required string wasn't found. */
11065 return -1;
11066
11067 if (!is_partial) {
11068 /* Record where the required string matched. */
11069 state->req_pos = found_pos;
11070 state->req_end = found_pos +
11071 (Py_ssize_t)pattern->req_string->value_count;
11072 }
11073
11074 if (pattern->req_offset >= 0) {
11075 /* Step back from the required string to where we should start
11076 * matching.
11077 */
11078 found_pos -= pattern->req_offset;
11079 if (found_pos >= state->text_pos)
11080 return found_pos;
11081 }
11082 break;
11083 }
11084 case RE_OP_STRING_FLD:
11085 {
11086 BOOL is_partial;
11087 Py_ssize_t limit;
11088
11089 if (search || pattern->req_offset < 0)
11090 limit = state->slice_end;
11091 else {
11092 limit = state->slice_start + pattern->req_offset +
11093 (Py_ssize_t)pattern->req_string->value_count;
11094 if (limit > state->slice_end)
11095 limit = state->slice_end;
11096 }
11097
11098 if (state->req_pos < 0 || state->text_pos > state->req_pos)
11099 /* First time or already passed it. */
11100 found_pos = string_search_fld(state, pattern->req_string,
11101 state->text_pos, limit, &end_pos, &is_partial);
11102 else {
11103 found_pos = state->req_pos;
11104 end_pos = state->req_end;
11105 is_partial = FALSE;
11106 }
11107
11108 if (found_pos < 0)
11109 /* The required string wasn't found. */
11110 return -1;
11111
11112 if (!is_partial) {
11113 /* Record where the required string matched. */
11114 state->req_pos = found_pos;
11115 state->req_end = end_pos;
11116 }
11117
11118 if (pattern->req_offset >= 0) {
11119 /* Step back from the required string to where we should start
11120 * matching.
11121 */
11122 found_pos -= pattern->req_offset;
11123 if (found_pos >= state->text_pos)
11124 return found_pos;
11125 }
11126 break;
11127 }
11128 case RE_OP_STRING_FLD_REV:
11129 {
11130 BOOL is_partial;
11131 Py_ssize_t limit;
11132
11133 if (search || pattern->req_offset < 0)
11134 limit = state->slice_start;
11135 else {
11136 limit = state->slice_end - pattern->req_offset -
11137 (Py_ssize_t)pattern->req_string->value_count;
11138 if (limit < state->slice_start)
11139 limit = state->slice_start;
11140 }
11141
11142 if (state->req_pos < 0 || state->text_pos < state->req_pos)
11143 /* First time or already passed it. */
11144 found_pos = string_search_fld_rev(state, pattern->req_string,
11145 state->text_pos, limit, &end_pos, &is_partial);
11146 else {
11147 found_pos = state->req_pos;
11148 end_pos = state->req_end;
11149 is_partial = FALSE;
11150 }
11151
11152 if (found_pos < 0)
11153 /* The required string wasn't found. */
11154 return -1;
11155
11156 if (!is_partial) {
11157 /* Record where the required string matched. */
11158 state->req_pos = found_pos;
11159 state->req_end = end_pos;
11160 }
11161
11162 if (pattern->req_offset >= 0) {
11163 /* Step back from the required string to where we should start
11164 * matching.
11165 */
11166 found_pos += pattern->req_offset;
11167 if (found_pos <= state->text_pos)
11168 return found_pos;
11169 }
11170 break;
11171 }
11172 case RE_OP_STRING_IGN:
11173 {
11174 BOOL is_partial;
11175 Py_ssize_t limit;
11176
11177 if (search || pattern->req_offset < 0)
11178 limit = state->slice_end;
11179 else {
11180 limit = state->slice_start + pattern->req_offset +
11181 (Py_ssize_t)pattern->req_string->value_count;
11182 if (limit > state->slice_end)
11183 limit = state->slice_end;
11184 }
11185
11186 if (state->req_pos < 0 || state->text_pos > state->req_pos)
11187 /* First time or already passed it. */
11188 found_pos = string_search_ign(state, pattern->req_string,
11189 state->text_pos, limit, TRUE, &is_partial);
11190 else {
11191 found_pos = state->req_pos;
11192 end_pos = state->req_end;
11193 is_partial = FALSE;
11194 }
11195
11196 if (found_pos < 0)
11197 /* The required string wasn't found. */
11198 return -1;
11199
11200 if (!is_partial) {
11201 /* Record where the required string matched. */
11202 state->req_pos = found_pos;
11203 state->req_end = found_pos +
11204 (Py_ssize_t)pattern->req_string->value_count;
11205 }
11206
11207 if (pattern->req_offset >= 0) {
11208 /* Step back from the required string to where we should start
11209 * matching.
11210 */
11211 found_pos -= pattern->req_offset;
11212 if (found_pos >= state->text_pos)
11213 return found_pos;
11214 }
11215 break;
11216 }
11217 case RE_OP_STRING_IGN_REV:
11218 {
11219 BOOL is_partial;
11220 Py_ssize_t limit;
11221
11222 if (search || pattern->req_offset < 0)
11223 limit = state->slice_start;
11224 else {
11225 limit = state->slice_end - pattern->req_offset -
11226 (Py_ssize_t)pattern->req_string->value_count;
11227 if (limit < state->slice_start)
11228 limit = state->slice_start;
11229 }
11230
11231 if (state->req_pos < 0 || state->text_pos < state->req_pos)
11232 /* First time or already passed it. */
11233 found_pos = string_search_ign_rev(state, pattern->req_string,
11234 state->text_pos, limit, TRUE, &is_partial);
11235 else {
11236 found_pos = state->req_pos;
11237 end_pos = state->req_end;
11238 is_partial = FALSE;
11239 }
11240
11241 if (found_pos < 0)
11242 /* The required string wasn't found. */
11243 return -1;
11244
11245 if (!is_partial) {
11246 /* Record where the required string matched. */
11247 state->req_pos = found_pos;
11248 state->req_end = found_pos -
11249 (Py_ssize_t)pattern->req_string->value_count;
11250 }
11251
11252 if (pattern->req_offset >= 0) {
11253 /* Step back from the required string to where we should start
11254 * matching.
11255 */
11256 found_pos += pattern->req_offset;
11257 if (found_pos <= state->text_pos)
11258 return found_pos;
11259 }
11260 break;
11261 }
11262 case RE_OP_STRING_REV:
11263 {
11264 BOOL is_partial;
11265 Py_ssize_t limit;
11266
11267 if (search || pattern->req_offset < 0)
11268 limit = state->slice_start;
11269 else {
11270 limit = state->slice_end - pattern->req_offset -
11271 (Py_ssize_t)pattern->req_string->value_count;
11272 if (limit < state->slice_start)
11273 limit = state->slice_start;
11274 }
11275
11276 if (state->req_pos < 0 || state->text_pos < state->req_pos)
11277 /* First time or already passed it. */
11278 found_pos = string_search_rev(state, pattern->req_string,
11279 state->text_pos, limit, TRUE, &is_partial);
11280 else {
11281 found_pos = state->req_pos;
11282 end_pos = state->req_end;
11283 is_partial = FALSE;
11284 }
11285
11286 if (found_pos < 0)
11287 /* The required string wasn't found. */
11288 return -1;
11289
11290 if (!is_partial) {
11291 /* Record where the required string matched. */
11292 state->req_pos = found_pos;
11293 state->req_end = found_pos -
11294 (Py_ssize_t)pattern->req_string->value_count;
11295 }
11296
11297 if (pattern->req_offset >= 0) {
11298 /* Step back from the required string to where we should start
11299 * matching.
11300 */
11301 found_pos += pattern->req_offset;
11302 if (found_pos <= state->text_pos)
11303 return found_pos;
11304 }
11305 break;
11306 }
11307 }
11308
11309 /* Start matching from the current position. */
11310 return state->text_pos;
11311 }
11312
11313 /* Tries to match a character pattern. */
11314 Py_LOCAL_INLINE(int) match_one(RE_State* state, RE_Node* node, Py_ssize_t
11315 text_pos) {
11316 switch (node->op) {
11317 case RE_OP_ANY:
11318 return try_match_ANY(state, node, text_pos);
11319 case RE_OP_ANY_ALL:
11320 return try_match_ANY_ALL(state, node, text_pos);
11321 case RE_OP_ANY_ALL_REV:
11322 return try_match_ANY_ALL_REV(state, node, text_pos);
11323 case RE_OP_ANY_REV:
11324 return try_match_ANY_REV(state, node, text_pos);
11325 case RE_OP_ANY_U:
11326 return try_match_ANY_U(state, node, text_pos);
11327 case RE_OP_ANY_U_REV:
11328 return try_match_ANY_U_REV(state, node, text_pos);
11329 case RE_OP_CHARACTER:
11330 return try_match_CHARACTER(state, node, text_pos);
11331 case RE_OP_CHARACTER_IGN:
11332 return try_match_CHARACTER_IGN(state, node, text_pos);
11333 case RE_OP_CHARACTER_IGN_REV:
11334 return try_match_CHARACTER_IGN_REV(state, node, text_pos);
11335 case RE_OP_CHARACTER_REV:
11336 return try_match_CHARACTER_REV(state, node, text_pos);
11337 case RE_OP_PROPERTY:
11338 return try_match_PROPERTY(state, node, text_pos);
11339 case RE_OP_PROPERTY_IGN:
11340 return try_match_PROPERTY_IGN(state, node, text_pos);
11341 case RE_OP_PROPERTY_IGN_REV:
11342 return try_match_PROPERTY_IGN_REV(state, node, text_pos);
11343 case RE_OP_PROPERTY_REV:
11344 return try_match_PROPERTY_REV(state, node, text_pos);
11345 case RE_OP_RANGE:
11346 return try_match_RANGE(state, node, text_pos);
11347 case RE_OP_RANGE_IGN:
11348 return try_match_RANGE_IGN(state, node, text_pos);
11349 case RE_OP_RANGE_IGN_REV:
11350 return try_match_RANGE_IGN_REV(state, node, text_pos);
11351 case RE_OP_RANGE_REV:
11352 return try_match_RANGE_REV(state, node, text_pos);
11353 case RE_OP_SET_DIFF:
11354 case RE_OP_SET_INTER:
11355 case RE_OP_SET_SYM_DIFF:
11356 case RE_OP_SET_UNION:
11357 return try_match_SET(state, node, text_pos);
11358 case RE_OP_SET_DIFF_IGN:
11359 case RE_OP_SET_INTER_IGN:
11360 case RE_OP_SET_SYM_DIFF_IGN:
11361 case RE_OP_SET_UNION_IGN:
11362 return try_match_SET_IGN(state, node, text_pos);
11363 case RE_OP_SET_DIFF_IGN_REV:
11364 case RE_OP_SET_INTER_IGN_REV:
11365 case RE_OP_SET_SYM_DIFF_IGN_REV:
11366 case RE_OP_SET_UNION_IGN_REV:
11367 return try_match_SET_IGN_REV(state, node, text_pos);
11368 case RE_OP_SET_DIFF_REV:
11369 case RE_OP_SET_INTER_REV:
11370 case RE_OP_SET_SYM_DIFF_REV:
11371 case RE_OP_SET_UNION_REV:
11372 return try_match_SET_REV(state, node, text_pos);
11373 }
11374
11375 return FALSE;
11376 }
11377
11378 /* Tests whether 2 nodes contains the same values. */
11379 Py_LOCAL_INLINE(BOOL) same_values(RE_Node* node_1, RE_Node* node_2) {
11380 size_t i;
11381
11382 if (node_1->value_count != node_2->value_count)
11383 return FALSE;
11384
11385 for (i = 0; i < node_1->value_count; i++) {
11386 if (node_1->values[i] != node_2->values[i])
11387 return FALSE;
11388 }
11389
11390 return TRUE;
11391 }
11392
11393 /* Tests whether 2 nodes are equivalent (both string-like in the same way). */
11394 Py_LOCAL_INLINE(BOOL) equivalent_nodes(RE_Node* node_1, RE_Node* node_2) {
11395 switch (node_1->op) {
11396 case RE_OP_CHARACTER:
11397 case RE_OP_STRING:
11398 switch (node_2->op) {
11399 case RE_OP_CHARACTER:
11400 case RE_OP_STRING:
11401 return same_values(node_1, node_2);
11402 }
11403 break;
11404 case RE_OP_CHARACTER_IGN:
11405 case RE_OP_STRING_IGN:
11406 switch (node_2->op) {
11407 case RE_OP_CHARACTER_IGN:
11408 case RE_OP_STRING_IGN:
11409 return same_values(node_1, node_2);
11410 }
11411 break;
11412 case RE_OP_CHARACTER_IGN_REV:
11413 case RE_OP_STRING_IGN_REV:
11414 switch (node_2->op) {
11415 case RE_OP_CHARACTER_IGN_REV:
11416 case RE_OP_STRING_IGN_REV:
11417 return same_values(node_1, node_2);
11418 }
11419 break;
11420 case RE_OP_CHARACTER_REV:
11421 case RE_OP_STRING_REV:
11422 switch (node_2->op) {
11423 case RE_OP_CHARACTER_REV:
11424 case RE_OP_STRING_REV:
11425 return same_values(node_1, node_2);
11426 }
11427 break;
11428 }
11429
11430 return FALSE;
11431 }
11432
11433 /* Saves the match as the best POSIX match (leftmost longest) found so far. */
11434 Py_LOCAL_INLINE(BOOL) save_best_match(RE_State* state) {
11435 size_t group_count;
11436 size_t g;
11437
11438 state->best_match_pos = state->match_pos;
11439 state->best_text_pos = state->text_pos;
11440 state->found_match = TRUE;
11441
11442 Py_MEMCPY(state->best_fuzzy_counts, state->fuzzy_counts,
11443 sizeof(state->fuzzy_counts));
11444
11445 group_count = state->pattern->true_group_count;
11446 if (group_count == 0)
11447 return TRUE;
11448
11449 if (!state->best_match_groups) {
11450 /* Allocate storage for the groups of the best match. */
11451 state->best_match_groups = (RE_GroupData*)safe_alloc(state, group_count
11452 * sizeof(RE_GroupData));
11453 if (!state->best_match_groups)
11454 return FALSE;
11455
11456 memset(state->best_match_groups, 0, group_count *
11457 sizeof(RE_GroupData));
11458
11459 for (g = 0; g < group_count; g++) {
11460 RE_GroupData* best;
11461 RE_GroupData* group;
11462
11463 best = &state->best_match_groups[g];
11464 group = &state->groups[g];
11465
11466 best->capacity = group->capacity;
11467 best->captures = (RE_GroupSpan*)safe_alloc(state, best->capacity *
11468 sizeof(RE_GroupSpan));
11469 if (!best->captures)
11470 return FALSE;
11471 }
11472 }
11473
11474 /* Copy the group spans and captures. */
11475 for (g = 0; g < group_count; g++) {
11476 RE_GroupData* best;
11477 RE_GroupData* group;
11478
11479 best = &state->best_match_groups[g];
11480 group = &state->groups[g];
11481
11482 best->count = group->count;
11483 best->current = group->current;
11484
11485 if (best->count > best->capacity) {
11486 RE_GroupSpan* new_captures;
11487
11488 /* We need more space for the captures. */
11489 best->capacity = best->count;
11490 new_captures = (RE_GroupSpan*)safe_realloc(state, best->captures,
11491 best->capacity * sizeof(RE_GroupSpan));
11492 if (!new_captures)
11493 return FALSE;
11494 best->captures = new_captures;
11495 }
11496
11497 /* Copy the captures for this group. */
11498 Py_MEMCPY(best->captures, group->captures, group->count *
11499 sizeof(RE_GroupSpan));
11500 }
11501
11502 return TRUE;
11503 }
11504
11505 /* Restores the best match for a POSIX match (leftmost longest). */
11506 Py_LOCAL_INLINE(void) restore_best_match(RE_State* state) {
11507 size_t group_count;
11508 size_t g;
11509
11510 if (!state->found_match)
11511 return;
11512
11513 state->match_pos = state->best_match_pos;
11514 state->text_pos = state->best_text_pos;
11515
11516 Py_MEMCPY(state->fuzzy_counts, state->best_fuzzy_counts,
11517 sizeof(state->fuzzy_counts));
11518
11519 group_count = state->pattern->true_group_count;
11520 if (group_count == 0)
11521 return;
11522
11523 /* Copy the group spans and captures. */
11524 for (g = 0; g < group_count; g++) {
11525 RE_GroupData* group;
11526 RE_GroupData* best;
11527
11528 group = &state->groups[g];
11529 best = &state->best_match_groups[g];
11530
11531 group->count = best->count;
11532 group->current = best->current;
11533
11534 /* Copy the captures for this group. */
11535 Py_MEMCPY(group->captures, best->captures, best->count *
11536 sizeof(RE_GroupSpan));
11537 }
11538 }
11539
11540 /* Checks whether the new match is better than the current match for a POSIX
11541 * match (leftmost longest) and saves it if it is.
11542 */
11543 Py_LOCAL_INLINE(BOOL) check_posix_match(RE_State* state) {
11544 Py_ssize_t best_length;
11545 Py_ssize_t new_length;
11546
11547 if (!state->found_match)
11548 return save_best_match(state);
11549
11550 /* Check the overall match. */
11551 if (state->reverse) {
11552 /* We're searching backwards. */
11553 best_length = state->match_pos - state->best_text_pos;
11554 new_length = state->match_pos - state->text_pos;
11555 } else {
11556 /* We're searching forwards. */
11557 best_length = state->best_text_pos - state->match_pos;
11558 new_length = state->text_pos - state->match_pos;
11559 }
11560
11561 if (new_length > best_length)
11562 /* It's a longer match. */
11563 return save_best_match(state);
11564
11565 return TRUE;
11566 }
11567
11568 /* Checks whether the current position is at the end of the text. */
11569 Py_LOCAL_INLINE(int) at_end(RE_State* state) {
11570 return state->reverse ? state->text_pos == state->slice_start :
11571 state->text_pos == state->slice_end;
11572 }
11573
11574 /* Checks whether 2 spans match. */
11575 Py_LOCAL_INLINE(BOOL) same_span(RE_GroupSpan span_1, RE_GroupSpan span_2) {
11576 return span_1.start == span_2.start && span_1.end == span_2.end;
11577 }
11578
11579 /* Checks whether a span matches that of a group. */
11580 Py_LOCAL_INLINE(BOOL) same_span_as_group(RE_GroupData* group, RE_GroupSpan
11581 span) {
11582 return group->current >= 0 && same_span(group->captures[group->current],
11583 span);
11584 }
11585
11586 /* Checks whether 2 groups have the same spam. */
11587 Py_LOCAL_INLINE(BOOL) same_span_of_group(RE_GroupData* group_1, RE_GroupData*
11588 group_2) {
11589 return (group_1->current >= 0 && group_2->current >= 0 &&
11590 same_span(group_1->captures[group_1->current],
11591 group_2->captures[group_2->current])) || (group_1->current < 0 &&
11592 group_2->current < 0);
11593 }
11594
11595 /* Checks whether a string matches or at least partially if it's at the end. */
11596 Py_LOCAL_INLINE(BOOL) partial_string_match(RE_State* state, RE_Node* node,
11597 Py_ssize_t text_pos) {
11598 Py_ssize_t length;
11599 RE_CODE* values;
11600 Py_ssize_t ofs;
11601 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
11602
11603 length = (Py_ssize_t)node->value_count;
11604 values = node->values;
11605 ofs = 0;
11606 char_at = state->char_at;
11607
11608 while (ofs < length) {
11609 if (text_pos + ofs >= state->slice_end)
11610 return TRUE;
11611
11612 if (char_at(state->text, text_pos + ofs) != values[ofs])
11613 return FALSE;
11614
11615 ++ofs;
11616 }
11617
11618 return TRUE;
11619 }
11620
11621 /* Checks whether a string matches or at least partially if it's at the end,
11622 * ignoring case.
11623 */
11624 Py_LOCAL_INLINE(BOOL) partial_string_match_ign(RE_State* state, RE_Node* node,
11625 Py_ssize_t text_pos) {
11626 Py_ssize_t length;
11627 RE_CODE* values;
11628 Py_ssize_t ofs;
11629 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
11630 RE_EncodingTable* encoding;
11631 RE_LocaleInfo* locale_info;
11632
11633 length = (Py_ssize_t)node->value_count;
11634 values = node->values;
11635 ofs = 0;
11636 char_at = state->char_at;
11637 encoding = state->encoding;
11638 locale_info = state->locale_info;
11639
11640 while (ofs < length) {
11641 if (text_pos + ofs >= state->slice_end)
11642 return TRUE;
11643
11644 if (!same_char_ign(encoding, locale_info, char_at(state->text, text_pos
11645 + ofs), values[ofs]))
11646 return FALSE;
11647
11648 ++ofs;
11649 }
11650
11651 return TRUE;
11652 }
11653
11654 /* Performs a depth-first match or search from the context. */
11655 Py_LOCAL_INLINE(int) basic_match(RE_State* state, BOOL search) {
11656 RE_EncodingTable* encoding;
11657 RE_LocaleInfo* locale_info;
11658 PatternObject* pattern;
11659 RE_Node* start_node;
11660 RE_NextNode start_pair;
11661 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
11662 Py_ssize_t pattern_step; /* The overall step of the pattern (forwards or backwards). */
11663 Py_ssize_t string_pos;
11664 BOOL do_search_start;
11665 Py_ssize_t found_pos;
11666 int status;
11667 RE_Node* node;
11668 int folded_pos;
11669 int gfolded_pos;
11670 TRACE(("<<basic_match>>\n"))
11671
11672 encoding = state->encoding;
11673 locale_info = state->locale_info;
11674 pattern = state->pattern;
11675 start_node = pattern->start_node;
11676
11677 /* Look beyond any initial group node. */
11678 start_pair.node = start_node;
11679 start_pair.test = pattern->start_test;
11680
11681 /* Is the pattern anchored to the start or end of the string? */
11682 switch (start_pair.test->op) {
11683 case RE_OP_END_OF_STRING:
11684 if (state->reverse) {
11685 /* Searching backwards. */
11686 if (state->text_pos != state->text_end)
11687 return RE_ERROR_FAILURE;
11688
11689 /* Don't bother to search further because it's anchored. */
11690 search = FALSE;
11691 }
11692 break;
11693 case RE_OP_START_OF_STRING:
11694 if (!state->reverse) {
11695 /* Searching forwards. */
11696 if (state->text_pos != state->text_start)
11697 return RE_ERROR_FAILURE;
11698
11699 /* Don't bother to search further because it's anchored. */
11700 search = FALSE;
11701 }
11702 break;
11703 }
11704
11705 char_at = state->char_at;
11706 pattern_step = state->reverse ? -1 : 1;
11707 string_pos = -1;
11708 do_search_start = pattern->do_search_start;
11709 state->fewest_errors = state->max_errors;
11710
11711 if (do_search_start && pattern->req_string &&
11712 equivalent_nodes(start_pair.test, pattern->req_string))
11713 do_search_start = FALSE;
11714
11715 start_match:
11716 if (state->iterations == 0 && safe_check_cancel(state))
11717 return RE_ERROR_CANCELLED;
11718
11719 if (!push_uint8(state, &state->bstack, RE_OP_FAILURE))
11720 return RE_ERROR_MEMORY;
11721 if (!push_bstack(state))
11722 return RE_ERROR_MEMORY;
11723
11724 /* sstack: -
11725 *
11726 * bstack: FAILURE
11727 *
11728 * pstack: bstack
11729 */
11730
11731 /* Clear the fuzzy counts. */
11732 if (state->is_fuzzy)
11733 memset(state->fuzzy_counts, 0, sizeof(state->fuzzy_counts));
11734
11735 /* If we're searching, advance along the string until there could be a
11736 * match.
11737 */
11738 if (pattern->pattern_call_ref >= 0) {
11739 RE_GuardList* guard_list;
11740
11741 guard_list = &state->group_call_guard_list[pattern->pattern_call_ref];
11742 guard_list->count = 0;
11743 guard_list->last_text_pos = -1;
11744 }
11745
11746 /* Locate the required string, if there's one, unless this is a recursive
11747 * call of 'basic_match'.
11748 */
11749 if (!pattern->req_string || state->text_pos < state->req_pos)
11750 found_pos = state->text_pos;
11751 else {
11752 found_pos = locate_required_string(state, search);
11753 if (found_pos < 0)
11754 return RE_ERROR_FAILURE;
11755 }
11756
11757 if (search) {
11758 state->text_pos = found_pos;
11759
11760 if (do_search_start) {
11761 RE_Position new_position;
11762
11763 next_match_1:
11764 /* 'search_start' will clear 'do_search_start' if it can't perform
11765 * a fast search for the next possible match. This enables us to
11766 * avoid the overhead of the call subsequently.
11767 */
11768 status = search_start(state, &start_pair, &new_position, 0);
11769 if (status == RE_ERROR_PARTIAL) {
11770 state->match_pos = new_position.text_pos;
11771 return status;
11772 } else if (status != RE_ERROR_SUCCESS)
11773 return status;
11774
11775 node = new_position.node;
11776 state->text_pos = new_position.text_pos;
11777
11778 if (node->op == RE_OP_SUCCESS) {
11779 /* Must the match advance past its start? */
11780 if (state->text_pos != state->search_anchor ||
11781 !state->must_advance)
11782 return RE_ERROR_SUCCESS;
11783
11784 state->text_pos = state->match_pos + pattern_step;
11785 goto next_match_1;
11786 }
11787
11788 /* 'do_search_start' may have been cleared. */
11789 do_search_start = pattern->do_search_start;
11790 } else {
11791 /* Avoiding 'search_start', which we've found can't perform a fast
11792 * search for the next possible match.
11793 */
11794 node = start_node;
11795
11796 next_match_2:
11797 if (state->reverse) {
11798 if (state->text_pos < state->slice_start) {
11799 if (state->partial_side == RE_PARTIAL_LEFT)
11800 return RE_ERROR_PARTIAL;
11801
11802 return RE_ERROR_FAILURE;
11803 }
11804 } else {
11805 if (state->text_pos > state->slice_end) {
11806 if (state-> partial_side == RE_PARTIAL_RIGHT)
11807 return RE_ERROR_PARTIAL;
11808
11809 return RE_ERROR_FAILURE;
11810 }
11811 }
11812
11813 state->match_pos = state->text_pos;
11814
11815 if (node->op == RE_OP_SUCCESS) {
11816 /* Must the match advance past its start? */
11817 if (state->text_pos != state->search_anchor ||
11818 !state->must_advance) {
11819 BOOL success;
11820
11821 if (state->match_all) {
11822 /* We want to match all of the slice. */
11823 if (state->reverse)
11824 success = state->text_pos == state->slice_start;
11825 else
11826 success = state->text_pos == state->slice_end;
11827 } else
11828 success = TRUE;
11829
11830 if (success)
11831 return RE_ERROR_SUCCESS;
11832 }
11833
11834 state->text_pos = state->match_pos + pattern_step;
11835 goto next_match_2;
11836 }
11837 }
11838 } else {
11839 /* The start position is anchored to the current position. */
11840 if (found_pos != state->text_pos)
11841 return RE_ERROR_FAILURE;
11842
11843 node = start_node;
11844 }
11845
11846 advance:
11847 /* The main matching loop. */
11848 for (;;) {
11849 TRACE(("%" PY_FORMAT_SIZE_T "d|", state->text_pos))
11850
11851 /* Should we abort the matching? */
11852 state->iterations += 0x100U;
11853
11854 if (state->iterations == 0 && safe_check_cancel(state))
11855 return RE_ERROR_CANCELLED;
11856
11857 switch (node->op) {
11858 case RE_OP_ANY: /* Any character except a newline. */
11859 TRACE(("%s\n", re_op_text[node->op]))
11860
11861 status = try_match_ANY(state, node, state->text_pos);
11862 if (status < 0)
11863 return status;
11864
11865 if (status == RE_ERROR_SUCCESS) {
11866 ++state->text_pos;
11867 node = node->next_1.node;
11868 } else if (node->status & RE_STATUS_FUZZY) {
11869 status = fuzzy_match_item(state, search, &node, 1);
11870 if (status < 0)
11871 return status;
11872
11873 if (status == RE_ERROR_FAILURE)
11874 goto backtrack;
11875 } else
11876 goto backtrack;
11877 break;
11878 case RE_OP_ANY_ALL: /* Any character at all. */
11879 TRACE(("%s\n", re_op_text[node->op]))
11880
11881 status = try_match_ANY_ALL(state, node, state->text_pos);
11882 if (status < 0)
11883 return status;
11884
11885 if (status == RE_ERROR_SUCCESS) {
11886 ++state->text_pos;
11887 node = node->next_1.node;
11888 } else if (node->status & RE_STATUS_FUZZY) {
11889 status = fuzzy_match_item(state, search, &node, 1);
11890 if (status < 0)
11891 return status;
11892
11893 if (status == RE_ERROR_FAILURE)
11894 goto backtrack;
11895 } else
11896 goto backtrack;
11897 break;
11898 case RE_OP_ANY_ALL_REV: /* Any character at all, backwards. */
11899 TRACE(("%s\n", re_op_text[node->op]))
11900
11901 status = try_match_ANY_ALL_REV(state, node, state->text_pos);
11902 if (status < 0)
11903 return status;
11904
11905 if (status == RE_ERROR_SUCCESS) {
11906 --state->text_pos;
11907 node = node->next_1.node;
11908 } else if (node->status & RE_STATUS_FUZZY) {
11909 status = fuzzy_match_item(state, search, &node, -1);
11910 if (status < 0)
11911 return status;
11912
11913 if (status == RE_ERROR_FAILURE)
11914 goto backtrack;
11915 } else
11916 goto backtrack;
11917 break;
11918 case RE_OP_ANY_REV: /* Any character except a newline, backwards. */
11919 TRACE(("%s\n", re_op_text[node->op]))
11920
11921 status = try_match_ANY_REV(state, node, state->text_pos);
11922 if (status < 0)
11923 return status;
11924
11925 if (status == RE_ERROR_SUCCESS) {
11926 --state->text_pos;
11927 node = node->next_1.node;
11928 } else if (node->status & RE_STATUS_FUZZY) {
11929 status = fuzzy_match_item(state, search, &node, -1);
11930 if (status < 0)
11931 return status;
11932
11933 if (status == RE_ERROR_FAILURE)
11934 goto backtrack;
11935 } else
11936 goto backtrack;
11937 break;
11938 case RE_OP_ANY_U: /* Any character except a line separator. */
11939 TRACE(("%s\n", re_op_text[node->op]))
11940
11941 status = try_match_ANY_U(state, node, state->text_pos);
11942 if (status < 0)
11943 return status;
11944
11945 if (status == RE_ERROR_SUCCESS) {
11946 ++state->text_pos;
11947 node = node->next_1.node;
11948 } else if (node->status & RE_STATUS_FUZZY) {
11949 status = fuzzy_match_item(state, search, &node, 1);
11950 if (status < 0)
11951 return status;
11952
11953 if (status == RE_ERROR_FAILURE)
11954 goto backtrack;
11955 } else
11956 goto backtrack;
11957 break;
11958 case RE_OP_ANY_U_REV: /* Any character except a line separator, backwards. */
11959 TRACE(("%s\n", re_op_text[node->op]))
11960
11961 status = try_match_ANY_U_REV(state, node, state->text_pos);
11962 if (status < 0)
11963 return status;
11964
11965 if (status == RE_ERROR_SUCCESS) {
11966 --state->text_pos;
11967 node = node->next_1.node;
11968 } else if (node->status & RE_STATUS_FUZZY) {
11969 status = fuzzy_match_item(state, search, &node, -1);
11970 if (status < 0)
11971 return status;
11972
11973 if (status == RE_ERROR_FAILURE)
11974 goto backtrack;
11975 } else
11976 goto backtrack;
11977 break;
11978 case RE_OP_ATOMIC: /* Start of an atomic group. */
11979 TRACE(("%s\n", re_op_text[node->op]))
11980
11981 if (!push_captures(state, &state->bstack))
11982 return RE_ERROR_MEMORY;
11983 if (!push_fuzzy_counts(state, &state->bstack, state->fuzzy_counts))
11984 return RE_ERROR_MEMORY;
11985 if (!push_size(state, &state->bstack, state->capture_change))
11986 return RE_ERROR_MEMORY;
11987 if (!push_sstack(state))
11988 return RE_ERROR_MEMORY;
11989 if (!push_uint8(state, &state->bstack, RE_OP_ATOMIC))
11990 return RE_ERROR_MEMORY;
11991 if (!push_bstack(state))
11992 return RE_ERROR_MEMORY;
11993
11994 /* bstack: captures fuzzy_counts capture_change sstack ATOMIC
11995 *
11996 * pstack: bstack
11997 */
11998
11999 node = node->next_1.node;
12000 break;
12001 case RE_OP_BOUNDARY: /* At a word boundary. */
12002 TRACE(("%s %d\n", re_op_text[node->op], node->match))
12003
12004 status = try_match_BOUNDARY(state, node, state->text_pos);
12005 if (status < 0)
12006 return status;
12007
12008 if (status == RE_ERROR_SUCCESS)
12009 node = node->next_1.node;
12010 else if (node->status & RE_STATUS_FUZZY) {
12011 status = fuzzy_match_item(state, search, &node, 0);
12012 if (status < 0)
12013 return status;
12014
12015 if (status == RE_ERROR_FAILURE)
12016 goto backtrack;
12017 } else
12018 goto backtrack;
12019 break;
12020 case RE_OP_BRANCH: /* 2-way branch. */
12021 {
12022 RE_Position next_position;
12023 TRACE(("%s\n", re_op_text[node->op]))
12024
12025 status = try_match(state, &node->next_1, state->text_pos,
12026 &next_position);
12027 if (status < 0)
12028 return status;
12029
12030 if (status == RE_ERROR_SUCCESS) {
12031 if (!push_ssize(state, &state->bstack, state->text_pos))
12032 return RE_ERROR_MEMORY;
12033 if (!push_pointer(state, &state->bstack,
12034 node->nonstring.next_2.node))
12035 return RE_ERROR_MEMORY;
12036 if (!push_uint8(state, &state->bstack, RE_OP_BRANCH))
12037 return RE_ERROR_MEMORY;
12038
12039 /* bstack: text_pos node BRANCH */
12040
12041 node = next_position.node;
12042 state->text_pos = next_position.text_pos;
12043 } else
12044 node = node->nonstring.next_2.node;
12045 break;
12046 }
12047 case RE_OP_CALL_REF: /* A group call reference. */
12048 {
12049 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
12050
12051 if (!push_pointer(state, &state->sstack, NULL))
12052 return RE_ERROR_MEMORY;
12053 if (!push_uint8(state, &state->bstack, RE_OP_CALL_REF))
12054 return RE_ERROR_MEMORY;
12055
12056 /* sstack: NULL
12057 *
12058 * bstack: CALL_REF
12059 */
12060
12061 node = node->next_1.node;
12062 break;
12063 }
12064 case RE_OP_CHARACTER: /* A character. */
12065 TRACE(("%s %d %d\n", re_op_text[node->op], node->match,
12066 node->values[0]))
12067
12068 if (state->text_pos >= state->text_end && state->partial_side ==
12069 RE_PARTIAL_RIGHT)
12070 return RE_ERROR_PARTIAL;
12071
12072 if (state->text_pos < state->slice_end &&
12073 matches_CHARACTER(encoding, locale_info, node,
12074 char_at(state->text, state->text_pos)) == node->match) {
12075 state->text_pos += node->step;
12076 node = node->next_1.node;
12077 } else if (node->status & RE_STATUS_FUZZY) {
12078 status = fuzzy_match_item(state, search, &node, 1);
12079 if (status < 0)
12080 return status;
12081
12082 if (status == RE_ERROR_FAILURE)
12083 goto backtrack;
12084 } else
12085 goto backtrack;
12086 break;
12087 case RE_OP_CHARACTER_IGN: /* A character, ignoring case. */
12088 TRACE(("%s %d %d\n", re_op_text[node->op], node->match,
12089 node->values[0]))
12090
12091 if (state->text_pos >= state->text_end && state->partial_side ==
12092 RE_PARTIAL_RIGHT)
12093 return RE_ERROR_PARTIAL;
12094
12095 if (state->text_pos < state->slice_end &&
12096 matches_CHARACTER_IGN(encoding, locale_info, node,
12097 char_at(state->text, state->text_pos)) == node->match) {
12098 state->text_pos += node->step;
12099 node = node->next_1.node;
12100 } else if (node->status & RE_STATUS_FUZZY) {
12101 status = fuzzy_match_item(state, search, &node, 1);
12102 if (status < 0)
12103 return status;
12104
12105 if (status == RE_ERROR_FAILURE)
12106 goto backtrack;
12107 } else
12108 goto backtrack;
12109 break;
12110 case RE_OP_CHARACTER_IGN_REV: /* A character, backwards, ignoring case. */
12111 TRACE(("%s %d %d\n", re_op_text[node->op], node->match,
12112 node->values[0]))
12113
12114 if (state->text_pos <= state->text_start && state->partial_side == RE_PARTIAL_LEFT)
12115 return RE_ERROR_PARTIAL;
12116
12117 if (state->text_pos > state->slice_start &&
12118 matches_CHARACTER_IGN(encoding, locale_info, node,
12119 char_at(state->text, state->text_pos - 1)) == node->match) {
12120 state->text_pos += node->step;
12121 node = node->next_1.node;
12122 } else if (node->status & RE_STATUS_FUZZY) {
12123 status = fuzzy_match_item(state, search, &node, -1);
12124 if (status < 0)
12125 return status;
12126
12127 if (status == RE_ERROR_FAILURE)
12128 goto backtrack;
12129 } else
12130 goto backtrack;
12131 break;
12132 case RE_OP_CHARACTER_REV: /* A character, backwards. */
12133 TRACE(("%s %d %d\n", re_op_text[node->op], node->match,
12134 node->values[0]))
12135
12136 if (state->text_pos <= state->text_start && state->partial_side == RE_PARTIAL_LEFT)
12137 return RE_ERROR_PARTIAL;
12138
12139 if (state->text_pos > state->slice_start &&
12140 matches_CHARACTER(encoding, locale_info, node,
12141 char_at(state->text, state->text_pos - 1)) == node->match) {
12142 state->text_pos += node->step;
12143 node = node->next_1.node;
12144 } else if (node->status & RE_STATUS_FUZZY) {
12145 status = fuzzy_match_item(state, search, &node, -1);
12146 if (status < 0)
12147 return status;
12148
12149 if (status == RE_ERROR_FAILURE)
12150 goto backtrack;
12151 } else
12152 goto backtrack;
12153 break;
12154 case RE_OP_CONDITIONAL: /* Start of a conditional subpattern. */
12155 {
12156 RE_LookaroundStateData data_l;
12157 TRACE(("%s %d\n", re_op_text[node->op], node->match))
12158
12159 data_l.node = node;
12160 data_l.slice_start = state->slice_start;
12161 data_l.slice_end = state->slice_end;
12162 data_l.text_pos = state->text_pos;
12163
12164 if (!ByteStack_push_block(state, &state->sstack, (void*)&data_l,
12165 sizeof(data_l)))
12166 return RE_ERROR_MEMORY;
12167 if (!push_captures(state, &state->bstack))
12168 return RE_ERROR_MEMORY;
12169 if (!push_repeats(state, &state->bstack))
12170 return RE_ERROR_MEMORY;
12171 if (!push_fuzzy_counts(state, &state->bstack, state->fuzzy_counts))
12172 return RE_ERROR_MEMORY;
12173 if (!push_size(state, &state->bstack, state->capture_change))
12174 return RE_ERROR_MEMORY;
12175 if (!push_sstack(state))
12176 return RE_ERROR_MEMORY;
12177 if (!push_uint8(state, &state->bstack, RE_OP_CONDITIONAL))
12178 return RE_ERROR_MEMORY;
12179 if (!push_bstack(state))
12180 return RE_ERROR_MEMORY;
12181
12182 /* sstack: node slice_start slice_end text_pos
12183 *
12184 * bstack: captures repeats fuzzy_counts capture_change sstack
12185 * CONDITIONAL
12186 *
12187 * pstack: bstack
12188 */
12189
12190 state->slice_start = state->text_start;
12191 state->slice_end = state->text_end;
12192
12193 node = node->next_1.node;
12194 break;
12195 }
12196 case RE_OP_DEFAULT_BOUNDARY: /* At a default word boundary. */
12197 TRACE(("%s %d\n", re_op_text[node->op], node->match))
12198
12199 status = try_match_DEFAULT_BOUNDARY(state, node, state->text_pos);
12200 if (status < 0)
12201 return status;
12202
12203 if (status == RE_ERROR_SUCCESS)
12204 node = node->next_1.node;
12205 else if (node->status & RE_STATUS_FUZZY) {
12206 status = fuzzy_match_item(state, search, &node, 0);
12207 if (status < 0)
12208 return status;
12209
12210 if (status == RE_ERROR_FAILURE)
12211 goto backtrack;
12212 } else
12213 goto backtrack;
12214 break;
12215 case RE_OP_DEFAULT_END_OF_WORD: /* At the default end of a word. */
12216 TRACE(("%s\n", re_op_text[node->op]))
12217
12218 status = try_match_DEFAULT_END_OF_WORD(state, node,
12219 state->text_pos);
12220 if (status < 0)
12221 return status;
12222
12223 if (status == RE_ERROR_SUCCESS)
12224 node = node->next_1.node;
12225 else if (node->status & RE_STATUS_FUZZY) {
12226 status = fuzzy_match_item(state, search, &node, 0);
12227 if (status < 0)
12228 return status;
12229
12230 if (status == RE_ERROR_FAILURE)
12231 goto backtrack;
12232 } else
12233 goto backtrack;
12234 break;
12235 case RE_OP_DEFAULT_START_OF_WORD: /* At the default start of a word. */
12236 TRACE(("%s\n", re_op_text[node->op]))
12237
12238 status = try_match_DEFAULT_START_OF_WORD(state, node,
12239 state->text_pos);
12240 if (status < 0)
12241 return status;
12242
12243 if (status == RE_ERROR_SUCCESS)
12244 node = node->next_1.node;
12245 else if (node->status & RE_STATUS_FUZZY) {
12246 status = fuzzy_match_item(state, search, &node, 0);
12247 if (status < 0)
12248 return status;
12249
12250 if (status == RE_ERROR_FAILURE)
12251 goto backtrack;
12252 } else
12253 goto backtrack;
12254 break;
12255 case RE_OP_END_ATOMIC: /* End of an atomic group. */
12256 TRACE(("%s\n", re_op_text[node->op]))
12257
12258 /* sstack: ...
12259 *
12260 * bstack: captures fuzzy_counts capture_change sstack ATOMIC ...
12261 *
12262 * pstack: bstack
12263 */
12264
12265 if (!pop_bstack(state))
12266 return RE_ERROR_MEMORY;
12267
12268 /* sstack: ...
12269 *
12270 * bstack: captures fuzzy_counts capture_change sstack ATOMIC
12271 *
12272 * pstack: -
12273 */
12274
12275 if (!drop_uint8(state, &state->bstack))
12276 return RE_ERROR_MEMORY;
12277 if (!pop_sstack(state))
12278 return RE_ERROR_MEMORY;
12279
12280 /* sstack: -
12281 *
12282 * bstack: captures fuzzy_counts capture_change
12283 *
12284 * pstack: -
12285 */
12286
12287 if (!push_uint8(state, &state->bstack, RE_OP_END_ATOMIC))
12288 return RE_ERROR_MEMORY;
12289
12290 /* bstack: captures fuzzy_counts capture_change END_ATOMIC
12291 *
12292 * pstack: -
12293 */
12294
12295 node = node->next_1.node;
12296 break;
12297 case RE_OP_END_CONDITIONAL: /* End of a conditional subpattern. */
12298 {
12299 RE_Node* conditional;
12300 RE_LookaroundStateData data_l;
12301 TRACE(("%s\n", re_op_text[node->op]))
12302
12303 /* sstack: node slice_start slice_end text_pos ...
12304 *
12305 * bstack: captures repeats fuzzy_counts capture_change sstack
12306 * CONDITIONAL ...
12307 *
12308 * pstack: bstack
12309 */
12310
12311 if (!pop_bstack(state))
12312 return RE_ERROR_MEMORY;
12313
12314 /* sstack: node slice_start slice_end text_pos ...
12315 *
12316 * bstack: captures repeats fuzzy_counts capture_change sstack
12317 * CONDITIONAL
12318 *
12319 * pstack: -
12320 */
12321
12322 if (!drop_uint8(state, &state->bstack))
12323 return RE_ERROR_MEMORY;
12324 if (!pop_sstack(state))
12325 return RE_ERROR_MEMORY;
12326
12327 /* sstack: node slice_start slice_end text_pos
12328 *
12329 * bstack: captures repeats fuzzy_counts capture_change
12330 *
12331 * pstack: -
12332 */
12333
12334 if (!ByteStack_pop_block(state, &state->sstack, (void*)&data_l,
12335 sizeof(data_l)))
12336 return RE_ERROR_MEMORY;
12337
12338 state->text_pos = data_l.text_pos;
12339 state->slice_end = data_l.slice_end;
12340 state->slice_start = data_l.slice_start;
12341 conditional = data_l.node;
12342
12343 /* sstack: -
12344 *
12345 * bstack: captures repeats fuzzy_counts capture_change
12346 *
12347 * pstack: -
12348 */
12349
12350 if (conditional->match) {
12351 /* It's a positive lookaround that's succeeded. */
12352 if (!push_uint8(state, &state->bstack, RE_OP_END_CONDITIONAL))
12353 return RE_ERROR_MEMORY;
12354
12355 /* sstack: -
12356 *
12357 * bstack: captures repeats fuzzy_counts capture_change
12358 * END_CONDITIONAL
12359 *
12360 * pstack: -
12361 */
12362
12363 /* Go to the 'true' branch. */
12364 node = node->next_1.node;
12365 } else {
12366 /* It's a negative lookaround that's succeeded. */
12367 if (!pop_size(state, &state->bstack, &state->capture_change))
12368 return RE_ERROR_MEMORY;
12369 if (!pop_fuzzy_counts(state, &state->bstack,
12370 state->fuzzy_counts))
12371 return RE_ERROR_MEMORY;
12372 if (!pop_repeats(state, &state->bstack))
12373 return RE_ERROR_MEMORY;
12374 if (!pop_captures(state, &state->bstack))
12375 return RE_ERROR_MEMORY;
12376
12377 /* sstack: -
12378 *
12379 * bstack: -
12380 *
12381 * pstack: -
12382 */
12383
12384 /* Go to the 'false' branch. */
12385 node = conditional->nonstring.next_2.node;
12386 }
12387 break;
12388 }
12389 case RE_OP_END_FUZZY: /* End of fuzzy matching. */
12390 {
12391 RE_Node* outer_node;
12392 size_t outer_counts[RE_FUZZY_COUNT];
12393 size_t total_counts[RE_FUZZY_COUNT];
12394 TRACE(("%s\n", re_op_text[node->op]))
12395
12396 /* sstack: outer_counts outer_node
12397 *
12398 * bstack: -
12399 */
12400
12401 /* Are the inner constraints OK? */
12402 if (!fuzzy_within_constraints(state->fuzzy_counts,
12403 state->fuzzy_node, state->max_errors))
12404 goto backtrack;
12405
12406 if (!pop_pointer(state, &state->sstack, (void*)&outer_node))
12407 return RE_ERROR_MEMORY;
12408 if (!pop_fuzzy_counts(state, &state->sstack, outer_counts))
12409 return RE_ERROR_MEMORY;
12410
12411 /* sstack: -
12412 *
12413 * bstack: -
12414 */
12415
12416 /* Add the inner counts to the outer counts. */
12417 total_counts[RE_FUZZY_SUB] = outer_counts[RE_FUZZY_SUB] +
12418 state->fuzzy_counts[RE_FUZZY_SUB];
12419 total_counts[RE_FUZZY_INS] = outer_counts[RE_FUZZY_INS] +
12420 state->fuzzy_counts[RE_FUZZY_INS];
12421 total_counts[RE_FUZZY_DEL] = outer_counts[RE_FUZZY_DEL] +
12422 state->fuzzy_counts[RE_FUZZY_DEL];
12423
12424 /* Is the total number of errors OK? */
12425 state->total_errors = total_errors(total_counts);
12426
12427 if (state->total_errors > state->max_errors) {
12428 if (!push_fuzzy_counts(state, &state->sstack, outer_counts))
12429 return RE_ERROR_MEMORY;
12430 if (!push_pointer(state, &state->sstack, outer_node))
12431 return RE_ERROR_MEMORY;
12432
12433 /* sstack: outer_counts outer_node
12434 *
12435 * bstack: -
12436 */
12437 goto backtrack;
12438 }
12439
12440 /* Save the inner fuzzy info. */
12441 if (!push_fuzzy_counts(state, &state->bstack, state->fuzzy_counts))
12442 return RE_ERROR_MEMORY;
12443 if (!push_ssize(state, &state->bstack, 0))
12444 return RE_ERROR_MEMORY;
12445 if (!push_pointer(state, &state->bstack, state->fuzzy_node))
12446 return RE_ERROR_MEMORY;
12447 if (!push_ssize(state, &state->bstack, state->text_pos))
12448 return RE_ERROR_MEMORY;
12449 if (!push_pointer(state, &state->bstack, node))
12450 return RE_ERROR_MEMORY;
12451 if (!push_uint8(state, &state->bstack, RE_OP_END_FUZZY))
12452 return RE_ERROR_MEMORY;
12453
12454 Py_MEMCPY(state->fuzzy_counts, total_counts, sizeof(total_counts));
12455 state->fuzzy_node = outer_node;
12456
12457 /* sstack: -
12458 *
12459 * bstack: inner_counts inner_node text_pos end_fuzzy_node
12460 * END_FUZZY
12461 */
12462
12463 node = node->next_1.node;
12464 break;
12465 }
12466 case RE_OP_END_GREEDY_REPEAT: /* End of a greedy repeat. */
12467 {
12468 RE_CODE index;
12469 RE_RepeatData* rp_data;
12470 BOOL changed;
12471 BOOL try_body;
12472 int body_status;
12473 RE_Position next_body_position;
12474 BOOL try_tail;
12475 int tail_status;
12476 RE_Position next_tail_position;
12477 RE_BodyEndStateData data_be;
12478 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
12479
12480 /* Repeat indexes are 0-based. */
12481 index = node->values[0];
12482 rp_data = &state->repeats[index];
12483
12484 /* The body has matched successfully at this position. */
12485 if (!guard_repeat(state, index, rp_data->start, RE_STATUS_BODY,
12486 FALSE))
12487 return RE_ERROR_MEMORY;
12488
12489 ++rp_data->count;
12490
12491 /* Have we advanced through the text or has a capture group change?
12492 */
12493 changed = rp_data->capture_change != state->capture_change ||
12494 state->text_pos != rp_data->start;
12495
12496 /* Additional checks are needed if there's fuzzy matching. */
12497 if (changed && state->is_fuzzy && rp_data->count >=
12498 node->values[1])
12499 changed = !(node->step == 1 ? state->text_pos >=
12500 state->slice_end : state->text_pos <= state->slice_start);
12501
12502 /* The counts are of type size_t, so the format needs to specify
12503 * that.
12504 */
12505 TRACE((" min is %u, max is %u, count is %" PY_FORMAT_SIZE_T "u\n",
12506 node->values[1], node->values[2], rp_data->count))
12507
12508 /* Could the body or tail match? */
12509 try_body = changed && (rp_data->count < node->values[2] ||
12510 ~node->values[2] == 0) && !is_repeat_guarded(state, index,
12511 state->text_pos, RE_STATUS_BODY);
12512 if (try_body) {
12513 body_status = try_match(state, &node->next_1, state->text_pos,
12514 &next_body_position);
12515 if (body_status < 0) {
12516 if (body_status == RE_ERROR_PARTIAL && rp_data->count >=
12517 node->values[1] && at_end(state))
12518 body_status = RE_ERROR_FAILURE;
12519 else
12520 return body_status;
12521 }
12522
12523 if (body_status == RE_ERROR_FAILURE)
12524 try_body = FALSE;
12525 } else
12526 body_status = RE_ERROR_FAILURE;
12527
12528 try_tail = (!changed || rp_data->count >= node->values[1]) &&
12529 !is_repeat_guarded(state, index, state->text_pos,
12530 RE_STATUS_TAIL);
12531 if (try_tail) {
12532 tail_status = try_match(state, &node->nonstring.next_2,
12533 state->text_pos, &next_tail_position);
12534 if (tail_status < 0)
12535 return tail_status;
12536
12537 if (tail_status == RE_ERROR_FAILURE)
12538 try_tail = FALSE;
12539 } else
12540 tail_status = RE_ERROR_FAILURE;
12541
12542 if (!try_body && !try_tail) {
12543 /* Neither the body nor the tail could match. */
12544 --rp_data->count;
12545 goto backtrack;
12546 }
12547
12548 if (body_status < 0 || (body_status == 0 && tail_status < 0))
12549 return RE_ERROR_PARTIAL;
12550
12551 /* Record info in case we backtrack into the body. */
12552 data_be.count = rp_data->count - 1;
12553 data_be.start = rp_data->start;
12554 data_be.capture_change = rp_data->capture_change;
12555 data_be.index = index;
12556
12557 if (!ByteStack_push_block(state, &state->bstack, (void*)&data_be,
12558 sizeof(data_be)))
12559 return RE_ERROR_MEMORY;
12560 if (!push_uint8(state, &state->bstack, RE_OP_BODY_END))
12561 return RE_ERROR_MEMORY;
12562
12563 /* bstack: count start capture_change index BODY_END */
12564
12565 if (try_body) {
12566 if (try_tail) {
12567 /* Both the body and the tail could match, but the body
12568 * takes precedence. If the body fails to match then we
12569 * want to try the tail before backtracking further.
12570 */
12571 RE_MatchBodyTailStateData data_mbt;
12572
12573 /* Record backtracking info for matching the tail. */
12574 data_mbt.position = next_tail_position;
12575 data_mbt.count = rp_data->count;
12576 data_mbt.start = state->text_pos;
12577 data_mbt.capture_change = state->capture_change;
12578 data_mbt.index = index;
12579 data_mbt.text_pos = state->text_pos;
12580
12581 if (!ByteStack_push_block(state, &state->bstack,
12582 (void*)&data_mbt, sizeof(data_mbt)))
12583 return RE_ERROR_MEMORY;
12584 if (!push_uint8(state, &state->bstack, RE_OP_MATCH_TAIL))
12585 return RE_ERROR_MEMORY;
12586
12587 /* bstack: position count start capture_change index
12588 * text_pos MATCH_TAIL
12589 */
12590 }
12591
12592 /* Record backtracking info in case the body fails to match. */
12593 if (!push_code(state, &state->bstack, index))
12594 return RE_ERROR_MEMORY;
12595 if (!push_ssize(state, &state->bstack, state->text_pos))
12596 return RE_ERROR_MEMORY;
12597 if (!push_uint8(state, &state->bstack, RE_OP_BODY_START))
12598 return RE_ERROR_MEMORY;
12599
12600 /* bstack: index text_pos BODY_START */
12601
12602 rp_data->capture_change = state->capture_change;
12603 rp_data->start = state->text_pos;
12604
12605 /* Advance into the body. */
12606 node = next_body_position.node;
12607 state->text_pos = next_body_position.text_pos;
12608 } else {
12609 /* Only the tail could match. */
12610
12611 /* Record backtracking info in case the tail fails to match. */
12612 if (!push_code(state, &state->bstack, index))
12613 return RE_ERROR_MEMORY;
12614 if (!push_ssize(state, &state->bstack, state->text_pos))
12615 return RE_ERROR_MEMORY;
12616 if (!push_uint8(state, &state->bstack, RE_OP_TAIL_START))
12617 return RE_ERROR_MEMORY;
12618
12619 /* bstack: index text_pos TAIL_START */
12620
12621 /* Advance into the tail. */
12622 node = next_tail_position.node;
12623 state->text_pos = next_tail_position.text_pos;
12624 }
12625 break;
12626 }
12627 case RE_OP_END_GROUP: /* End of a capture group. */
12628 {
12629 RE_CODE private_index;
12630 RE_CODE public_index;
12631 RE_GroupData* group;
12632 BOOL capture;
12633 TRACE(("%s %d\n", re_op_text[node->op], node->values[1]))
12634
12635 /* Capture group indexes are 1-based (excluding group 0, which is
12636 * the entire matched string).
12637 */
12638 private_index = node->values[0];
12639 public_index = node->values[1];
12640 group = &state->groups[private_index - 1];
12641 capture = (BOOL)node->values[2];
12642
12643 if (capture) {
12644 RE_GroupSpan span;
12645 RE_GroupStateData data_g;
12646
12647 /* sstack: start
12648 *
12649 * bstack: -
12650 */
12651
12652 if (!pop_ssize(state, &state->sstack, &span.start))
12653 return RE_ERROR_MEMORY;
12654
12655 span.end = state->text_pos;
12656
12657 data_g.text_pos = span.start;
12658 data_g.current = group->current;
12659 data_g.capture_change = state->capture_change;
12660 data_g.private_index = private_index;
12661 data_g.public_index = public_index;
12662
12663 if (!ByteStack_push_block(state, &state->bstack,
12664 (void*)&data_g, sizeof(data_g)))
12665 return RE_ERROR_MEMORY;
12666
12667 if (pattern->group_info[private_index - 1].referenced &&
12668 !same_span_as_group(group, span))
12669 ++state->capture_change;
12670
12671 if (!save_capture(state, private_index, public_index, span))
12672 return RE_ERROR_MEMORY;
12673 group->current = (Py_ssize_t)group->count - 1;
12674 } else {
12675 if (!push_ssize(state, &state->sstack, state->text_pos))
12676 return RE_ERROR_MEMORY;
12677 }
12678
12679 if (!push_bool(state, &state->bstack, capture))
12680 return RE_ERROR_MEMORY;
12681 if (!push_uint8(state, &state->bstack, RE_OP_END_GROUP))
12682 return RE_ERROR_MEMORY;
12683
12684 /* If capturing:
12685 *
12686 * sstack: -
12687 *
12688 * bstack: start current capture_change private_index public_index
12689 * TRUE END_GROUP
12690 *
12691 * else:
12692 *
12693 * sstack: end
12694 *
12695 * bstack: FALSE END_GROUP
12696 */
12697
12698 node = node->next_1.node;
12699 break;
12700 }
12701 case RE_OP_END_LAZY_REPEAT: /* End of a lazy repeat. */
12702 {
12703 RE_CODE index;
12704 RE_RepeatData* rp_data;
12705 BOOL changed;
12706 BOOL try_body;
12707 int body_status;
12708 RE_Position next_body_position;
12709 BOOL try_tail;
12710 int tail_status;
12711 RE_Position next_tail_position;
12712 RE_BodyEndStateData data_be;
12713 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
12714
12715 /* Repeat indexes are 0-based. */
12716 index = node->values[0];
12717 rp_data = &state->repeats[index];
12718
12719 /* The body has matched successfully at this position. */
12720 if (!guard_repeat(state, index, rp_data->start, RE_STATUS_BODY,
12721 FALSE))
12722 return RE_ERROR_MEMORY;
12723
12724 ++rp_data->count;
12725
12726 /* Have we advanced through the text or has a capture group change?
12727 */
12728 changed = rp_data->capture_change != state->capture_change ||
12729 state->text_pos != rp_data->start;
12730
12731 /* Additional checks are needed if there's fuzzy matching. */
12732 if (changed && state->is_fuzzy && rp_data->count >=
12733 node->values[1])
12734 changed = !(node->step == 1 ? state->text_pos >=
12735 state->slice_end : state->text_pos <= state->slice_start);
12736
12737 /* The counts are of type size_t, so the format needs to specify
12738 * that.
12739 */
12740 TRACE((" min is %u, max is %u, count is %" PY_FORMAT_SIZE_T "u\n",
12741 node->values[1], node->values[2], rp_data->count))
12742
12743 /* Could the body or tail match? */
12744 try_body = changed && (rp_data->count < node->values[2] ||
12745 ~node->values[2] == 0) && !is_repeat_guarded(state, index,
12746 state->text_pos, RE_STATUS_BODY);
12747 if (try_body) {
12748 body_status = try_match(state, &node->next_1, state->text_pos,
12749 &next_body_position);
12750 if (body_status < 0)
12751 return body_status;
12752
12753 if (body_status == RE_ERROR_FAILURE)
12754 try_body = FALSE;
12755 } else
12756 body_status = RE_ERROR_FAILURE;
12757
12758 try_tail = (!changed || rp_data->count >= node->values[1]) &&
12759 !is_repeat_guarded(state, index, state->text_pos,
12760 RE_STATUS_TAIL);
12761 if (try_tail) {
12762 tail_status = try_match(state, &node->nonstring.next_2,
12763 state->text_pos, &next_tail_position);
12764 if (tail_status < 0)
12765 return tail_status;
12766
12767 if (tail_status == RE_ERROR_FAILURE)
12768 try_tail = FALSE;
12769 } else
12770 tail_status = RE_ERROR_FAILURE;
12771
12772 if (!try_body && !try_tail) {
12773 /* Neither the body nor the tail could match. */
12774 --rp_data->count;
12775 goto backtrack;
12776 }
12777
12778 if (body_status < 0 || (body_status == 0 && tail_status < 0))
12779 return RE_ERROR_PARTIAL;
12780
12781 /* Record info in case we backtrack into the body. */
12782 data_be.count = rp_data->count - 1;
12783 data_be.start = rp_data->start;
12784 data_be.capture_change = rp_data->capture_change;
12785 data_be.index = index;
12786
12787 if (!ByteStack_push_block(state, &state->bstack, (void*)&data_be,
12788 sizeof(data_be)))
12789 return RE_ERROR_MEMORY;
12790 if (!push_uint8(state, &state->bstack, RE_OP_BODY_END))
12791 return RE_ERROR_MEMORY;
12792
12793 /* bstack: count start capture_change index BODY_END */
12794
12795 if (try_tail) {
12796 if (try_body) {
12797 /* Both the body and the tail could match, but The tail
12798 * takes precedence. If the tail fails to match then we
12799 * want to try the body before backtracking further.
12800 */
12801 RE_MatchBodyTailStateData data_mbt;
12802
12803 /* Record backtracking info for matching the body. */
12804 data_mbt.position = next_body_position;
12805 data_mbt.count = rp_data->count;
12806 data_mbt.start = state->text_pos;
12807 data_mbt.capture_change = state->capture_change;
12808 data_mbt.index = index;
12809 data_mbt.text_pos = state->text_pos;
12810
12811 if (!ByteStack_push_block(state, &state->bstack,
12812 (void*)&data_mbt, sizeof(data_mbt)))
12813 return RE_ERROR_MEMORY;
12814 if (!push_uint8(state, &state->bstack, RE_OP_MATCH_BODY))
12815 return RE_ERROR_MEMORY;
12816
12817 /* bstack: position count start capture_change index
12818 * text_pos MATCH_BODY
12819 */
12820 }
12821
12822 /* Record backtracking info in case the tail fails to match. */
12823 if (!push_code(state, &state->bstack, index))
12824 return RE_ERROR_MEMORY;
12825 if (!push_ssize(state, &state->bstack, state->text_pos))
12826 return RE_ERROR_MEMORY;
12827 if (!push_uint8(state, &state->bstack, RE_OP_TAIL_START))
12828 return RE_ERROR_MEMORY;
12829
12830 /* bstack: index text_pos TAIL_START */
12831
12832 /* Advance into the tail. */
12833 node = next_tail_position.node;
12834 state->text_pos = next_tail_position.text_pos;
12835 } else {
12836 /* Only the body could match. */
12837
12838 /* Record backtracking info in case the body fails to
12839 * match.
12840 */
12841 if (!push_code(state, &state->bstack, index))
12842 return RE_ERROR_MEMORY;
12843 if (!push_ssize(state, &state->bstack, state->text_pos))
12844 return RE_ERROR_MEMORY;
12845 if (!push_uint8(state, &state->bstack, RE_OP_BODY_START))
12846 return RE_ERROR_MEMORY;
12847
12848 /* bstack: index text_pos BODY_START */
12849
12850 rp_data->capture_change = state->capture_change;
12851 rp_data->start = state->text_pos;
12852
12853 /* Advance into the body. */
12854 node = next_body_position.node;
12855 state->text_pos = next_body_position.text_pos;
12856 }
12857 break;
12858 }
12859 case RE_OP_END_LOOKAROUND: /* End of a lookaround subpattern. */
12860 {
12861 RE_LookaroundStateData data_l;
12862 RE_Node* lookaround;
12863 TRACE(("%s\n", re_op_text[node->op]))
12864
12865 /* sstack: node slice_start slice_end text_pos ...
12866 *
12867 * bstack: [captures TRUE | FALSE] fuzzy_counts capture_change
12868 * sstack LOOKAROUND ...
12869 *
12870 * pstack: bstack
12871 */
12872
12873 if (!pop_bstack(state))
12874 return RE_ERROR_MEMORY;
12875
12876 /* sstack: node slice_start slice_end text_pos ...
12877 *
12878 * bstack: [captures TRUE | FALSE] fuzzy_counts capture_change
12879 * sstack LOOKAROUND
12880 *
12881 * pstack: -
12882 */
12883
12884 if (!drop_uint8(state, &state->bstack))
12885 return RE_ERROR_MEMORY;
12886 if (!pop_sstack(state))
12887 return RE_ERROR_MEMORY;
12888
12889 /* sstack: node slice_start slice_end text_pos
12890 *
12891 * bstack: [captures TRUE | FALSE] fuzzy_counts capture_change
12892 *
12893 * pstack: -
12894 */
12895
12896 if (!ByteStack_pop_block(state, &state->sstack, (void*)&data_l,
12897 sizeof(data_l)))
12898 return RE_ERROR_MEMORY;
12899
12900 state->text_pos = data_l.text_pos;
12901 state->slice_end = data_l.slice_end;
12902 state->slice_start = data_l.slice_start;
12903 lookaround = data_l.node;
12904
12905 /* sstack: -
12906 *
12907 * bstack: [captures TRUE | FALSE] fuzzy_counts capture_change
12908 *
12909 * pstack: -
12910 */
12911
12912 if (lookaround->match) {
12913 /* It's a positive lookaround that's succeeded. */
12914 if (!push_uint8(state, &state->bstack, RE_OP_END_LOOKAROUND))
12915 return RE_ERROR_MEMORY;
12916
12917 /* sstack: -
12918 *
12919 * bstack: [captures TRUE | FALSE] fuzzy_counts capture_change
12920 * END_LOOKAROUND
12921 *
12922 * pstack: -
12923 */
12924
12925 /* Go to the 'true' branch. */
12926 node = node->next_1.node;
12927 } else {
12928 BOOL has_groups;
12929
12930 /* It's a negative lookaround that's succeeded. */
12931 if (!pop_size(state, &state->bstack, &state->capture_change))
12932 return RE_ERROR_MEMORY;
12933 if (!pop_fuzzy_counts(state, &state->bstack,
12934 state->fuzzy_counts))
12935 return RE_ERROR_MEMORY;
12936 if (!pop_bool(state, &state->bstack, &has_groups))
12937 return RE_ERROR_MEMORY;
12938 if (has_groups) {
12939 if (!pop_captures(state, &state->bstack))
12940 return RE_ERROR_MEMORY;
12941 }
12942
12943 /* sstack: -
12944 *
12945 * bstack: -
12946 *
12947 * pstack: -
12948 */
12949
12950 /* Go to the 'false' branch. */
12951 goto backtrack;
12952 }
12953 break;
12954 }
12955 case RE_OP_END_OF_LINE: /* At the end of a line. */
12956 TRACE(("%s\n", re_op_text[node->op]))
12957
12958 status = try_match_END_OF_LINE(state, node, state->text_pos);
12959 if (status < 0)
12960 return status;
12961
12962 if (status == RE_ERROR_SUCCESS)
12963 node = node->next_1.node;
12964 else if (node->status & RE_STATUS_FUZZY) {
12965 status = fuzzy_match_item(state, search, &node, 0);
12966 if (status < 0)
12967 return status;
12968
12969 if (status == RE_ERROR_FAILURE)
12970 goto backtrack;
12971 } else
12972 goto backtrack;
12973 break;
12974 case RE_OP_END_OF_LINE_U: /* At the end of a line. */
12975 TRACE(("%s\n", re_op_text[node->op]))
12976
12977 status = try_match_END_OF_LINE_U(state, node, state->text_pos);
12978 if (status < 0)
12979 return status;
12980
12981 if (status == RE_ERROR_SUCCESS)
12982 node = node->next_1.node;
12983 else if (node->status & RE_STATUS_FUZZY) {
12984 status = fuzzy_match_item(state, search, &node, 0);
12985 if (status < 0)
12986 return status;
12987
12988 if (status == RE_ERROR_FAILURE)
12989 goto backtrack;
12990 } else
12991 goto backtrack;
12992 break;
12993 case RE_OP_END_OF_STRING: /* At the end of the string. */
12994 TRACE(("%s\n", re_op_text[node->op]))
12995
12996 status = try_match_END_OF_STRING(state, node, state->text_pos);
12997 if (status < 0)
12998 return status;
12999
13000 if (status == RE_ERROR_SUCCESS)
13001 node = node->next_1.node;
13002 else if (node->status & RE_STATUS_FUZZY) {
13003 status = fuzzy_match_item(state, search, &node, 0);
13004 if (status < 0)
13005 return status;
13006
13007 if (status == RE_ERROR_FAILURE)
13008 goto backtrack;
13009 } else
13010 goto backtrack;
13011 break;
13012 case RE_OP_END_OF_STRING_LINE: /* At the end of string or final newline. */
13013 TRACE(("%s\n", re_op_text[node->op]))
13014
13015 status = try_match_END_OF_STRING_LINE(state, node,
13016 state->text_pos);
13017 if (status < 0)
13018 return status;
13019
13020 if (status == RE_ERROR_SUCCESS)
13021 node = node->next_1.node;
13022 else if (node->status & RE_STATUS_FUZZY) {
13023 status = fuzzy_match_item(state, search, &node, 0);
13024 if (status < 0)
13025 return status;
13026
13027 if (status == RE_ERROR_FAILURE)
13028 goto backtrack;
13029 } else
13030 goto backtrack;
13031 break;
13032 case RE_OP_END_OF_STRING_LINE_U: /* At the end of string or final newline. */
13033 TRACE(("%s\n", re_op_text[node->op]))
13034
13035 status = try_match_END_OF_STRING_LINE_U(state, node,
13036 state->text_pos);
13037 if (status < 0)
13038 return status;
13039
13040 if (status == RE_ERROR_SUCCESS)
13041 node = node->next_1.node;
13042 else if (node->status & RE_STATUS_FUZZY) {
13043 status = fuzzy_match_item(state, search, &node, 0);
13044 if (status < 0)
13045 return status;
13046
13047 if (status == RE_ERROR_FAILURE)
13048 goto backtrack;
13049 } else
13050 goto backtrack;
13051 break;
13052 case RE_OP_END_OF_WORD: /* At the end of a word. */
13053 TRACE(("%s\n", re_op_text[node->op]))
13054
13055 status = try_match_END_OF_WORD(state, node, state->text_pos);
13056 if (status < 0)
13057 return status;
13058
13059 if (status == RE_ERROR_SUCCESS)
13060 node = node->next_1.node;
13061 else if (node->status & RE_STATUS_FUZZY) {
13062 status = fuzzy_match_item(state, search, &node, 0);
13063 if (status < 0)
13064 return status;
13065
13066 if (status == RE_ERROR_FAILURE)
13067 goto backtrack;
13068 } else
13069 goto backtrack;
13070 break;
13071 case RE_OP_FAILURE: /* Failure. */
13072 goto backtrack;
13073 case RE_OP_FUZZY: /* Fuzzy matching. */
13074 {
13075 TRACE(("%s\n", re_op_text[node->op]))
13076
13077 /* Save the outer fuzzy info. */
13078 if (!push_fuzzy_counts(state, &state->sstack, state->fuzzy_counts))
13079 return RE_ERROR_MEMORY;
13080 if (!push_pointer(state, &state->sstack, state->fuzzy_node))
13081 return RE_ERROR_MEMORY;
13082
13083 /* Initialise the inner fuzzy info. */
13084 memset(state->fuzzy_counts, 0, sizeof(state->fuzzy_counts));
13085 state->fuzzy_node = node;
13086
13087 if (!push_uint8(state, &state->bstack, RE_OP_FUZZY))
13088 return RE_ERROR_MEMORY;
13089
13090 /* sstack: outer_counts outer_node
13091 *
13092 * bstack: FUZZY
13093 */
13094
13095 node = node->next_1.node;
13096 break;
13097 }
13098 case RE_OP_GRAPHEME_BOUNDARY: /* At a grapheme boundary. */
13099 TRACE(("%s\n", re_op_text[node->op]))
13100
13101 status = try_match_GRAPHEME_BOUNDARY(state, node, state->text_pos);
13102 if (status < 0)
13103 return status;
13104
13105 if (status == RE_ERROR_SUCCESS)
13106 node = node->next_1.node;
13107 else if (node->status & RE_STATUS_FUZZY) {
13108 status = fuzzy_match_item(state, search, &node, 0);
13109 if (status < 0)
13110 return status;
13111
13112 if (status == RE_ERROR_FAILURE)
13113 goto backtrack;
13114 } else
13115 goto backtrack;
13116 break;
13117 case RE_OP_GREEDY_REPEAT: /* Greedy repeat. */
13118 {
13119 RE_CODE index;
13120 RE_RepeatData* rp_data;
13121 BOOL try_body;
13122 int body_status;
13123 RE_Position next_body_position;
13124 BOOL try_tail;
13125 int tail_status;
13126 RE_Position next_tail_position;
13127 RE_RepeatStateData data_r;
13128 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
13129
13130 /* Repeat indexes are 0-based. */
13131 index = node->values[0];
13132 rp_data = &state->repeats[index];
13133
13134 /* We might need to backtrack into the head, so save the current
13135 * repeat.
13136 */
13137 data_r.count = rp_data->count;
13138 data_r.start = rp_data->start;
13139 data_r.capture_change = rp_data->capture_change;
13140 data_r.index = index;
13141 data_r.text_pos = state->text_pos;
13142
13143 if (!ByteStack_push_block(state, &state->bstack, (void*)&data_r,
13144 sizeof(data_r)))
13145 return RE_ERROR_MEMORY;
13146 if (!push_uint8(state, &state->bstack, RE_OP_GREEDY_REPEAT))
13147 return RE_ERROR_MEMORY;
13148
13149 /* bstack: count start capture_change index text_pos GREEDY_REPEAT
13150 */
13151
13152 /* Initialise the new repeat. */
13153 rp_data->count = 0;
13154 rp_data->start = state->text_pos;
13155 rp_data->capture_change = state->capture_change;
13156
13157 /* Could the body or tail match? */
13158 #if defined(VERBOSE)
13159 printf(" is_repeat_guarded(..., RE_STATUS_BODY) returns %d\n",
13160 is_repeat_guarded(state, index, state->text_pos,
13161 RE_STATUS_BODY));
13162 #endif
13163 try_body = node->values[2] > 0 && !is_repeat_guarded(state, index,
13164 state->text_pos, RE_STATUS_BODY);
13165 if (try_body) {
13166 body_status = try_match(state, &node->next_1, state->text_pos,
13167 &next_body_position);
13168 if (body_status < 0)
13169 return body_status;
13170
13171 if (body_status == RE_ERROR_FAILURE)
13172 try_body = FALSE;
13173 } else
13174 body_status = RE_ERROR_FAILURE;
13175
13176 try_tail = node->values[1] == 0;
13177 if (try_tail) {
13178 tail_status = try_match(state, &node->nonstring.next_2,
13179 state->text_pos, &next_tail_position);
13180 if (tail_status < 0)
13181 return tail_status;
13182
13183 if (tail_status == RE_ERROR_FAILURE)
13184 try_tail = FALSE;
13185 } else
13186 tail_status = RE_ERROR_FAILURE;
13187
13188 if (!try_body && !try_tail)
13189 /* Neither the body nor the tail could match. */
13190 goto backtrack;
13191
13192 if (body_status < 0 || (body_status == 0 && tail_status < 0))
13193 return RE_ERROR_PARTIAL;
13194
13195 if (try_body) {
13196 if (try_tail) {
13197 /* Both the body and the tail could match, but the body
13198 * takes precedence. If the body fails to match then we
13199 * want to try the tail before backtracking further.
13200 */
13201 RE_MatchBodyTailStateData data_mbt;
13202
13203 /* Record backtracking info for matching the tail. */
13204 data_mbt.position = next_tail_position;
13205 data_mbt.count = rp_data->count;
13206 data_mbt.start = rp_data->start;
13207 data_mbt.capture_change = rp_data->capture_change;
13208 data_mbt.index = index;
13209 data_mbt.text_pos = state->text_pos;
13210
13211 if (!ByteStack_push_block(state, &state->bstack,
13212 (void*)&data_mbt, sizeof(data_mbt)))
13213 return RE_ERROR_MEMORY;
13214 if (!push_uint8(state, &state->bstack, RE_OP_MATCH_TAIL))
13215 return RE_ERROR_MEMORY;
13216
13217 /* bstack: position count start capture_change index
13218 * text_pos MATCH_TAIL
13219 */
13220 }
13221
13222 /* Record backtracking info in case the body fails to match. */
13223 if (!push_code(state, &state->bstack, index))
13224 return RE_ERROR_MEMORY;
13225 if (!push_ssize(state, &state->bstack, state->text_pos))
13226 return RE_ERROR_MEMORY;
13227 if (!push_uint8(state, &state->bstack, RE_OP_BODY_START))
13228 return RE_ERROR_MEMORY;
13229
13230 /* bstack: index text_pos BODY_START */
13231
13232 /* Advance into the body. */
13233 node = next_body_position.node;
13234 state->text_pos = next_body_position.text_pos;
13235 } else {
13236 /* Only the tail could match. */
13237
13238 /* Record backtracking info in case the tail fails to match. */
13239 if (!push_code(state, &state->bstack, index))
13240 return RE_ERROR_MEMORY;
13241 if (!push_ssize(state, &state->bstack, state->text_pos))
13242 return RE_ERROR_MEMORY;
13243 if (!push_uint8(state, &state->bstack, RE_OP_TAIL_START))
13244 return RE_ERROR_MEMORY;
13245
13246 /* bstack: index text_pos TAIL_START */
13247
13248 /* Advance into the tail. */
13249 node = next_tail_position.node;
13250 state->text_pos = next_tail_position.text_pos;
13251 }
13252 break;
13253 }
13254 case RE_OP_GREEDY_REPEAT_ONE: /* Greedy repeat for one character. */
13255 {
13256 RE_CODE index;
13257 RE_RepeatData* rp_data;
13258 size_t count;
13259 BOOL is_partial;
13260 BOOL match;
13261 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
13262
13263 /* Repeat indexes are 0-based. */
13264 index = node->values[0];
13265 rp_data = &state->repeats[index];
13266
13267 if (is_repeat_guarded(state, index, state->text_pos,
13268 RE_STATUS_BODY))
13269 goto backtrack;
13270
13271 /* Count how many times the character repeats, up to the maximum.
13272 */
13273 count = count_one(state, node->nonstring.next_2.node,
13274 state->text_pos, node->values[2], &is_partial);
13275 if (is_partial) {
13276 state->text_pos += (Py_ssize_t)count * node->step;
13277 return RE_ERROR_PARTIAL;
13278 }
13279
13280 /* Unmatch until it's not guarded. */
13281 match = FALSE;
13282 for (;;) {
13283 if (count < node->values[1])
13284 /* The number of repeats is below the minimum. */
13285 break;
13286
13287 if (!is_repeat_guarded(state, index, state->text_pos +
13288 (Py_ssize_t)count * node->step, RE_STATUS_TAIL)) {
13289 /* It's not guarded at this position. */
13290 match = TRUE;
13291 break;
13292 }
13293
13294 if (count == 0)
13295 break;
13296
13297 --count;
13298 }
13299
13300 if (!match) {
13301 /* The repeat has failed to match at this position. */
13302 if (!guard_repeat(state, index, state->text_pos,
13303 RE_STATUS_BODY, TRUE))
13304 return RE_ERROR_MEMORY;
13305 goto backtrack;
13306 }
13307
13308 if (count > node->values[1]) {
13309 /* Record the backtracking info. */
13310 RE_RepeatOneStateData data_ro;
13311
13312 data_ro.count = rp_data->count;
13313 data_ro.start = rp_data->start;
13314 data_ro.node = node;
13315 data_ro.index = index;
13316
13317 if (!ByteStack_push_block(state, &state->bstack,
13318 (void*)&data_ro, sizeof(data_ro)))
13319 return RE_ERROR_MEMORY;
13320 if (!push_uint8(state, &state->bstack,
13321 RE_OP_GREEDY_REPEAT_ONE))
13322 return RE_ERROR_MEMORY;
13323
13324 /* bstack: count start node index GREEDY_REPEAT_ONE */
13325
13326 rp_data->start = state->text_pos;
13327 rp_data->count = count;
13328 }
13329
13330 /* Advance into the tail. */
13331 state->text_pos += (Py_ssize_t)count * node->step;
13332 node = node->next_1.node;
13333 break;
13334 }
13335 case RE_OP_GROUP_CALL: /* Group call. */
13336 {
13337 size_t index;
13338 RE_Node* next_node;
13339 size_t r;
13340 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
13341
13342 index = node->values[0];
13343 next_node = node->next_1.node;
13344
13345 /* For the caller. */
13346 if (!push_groups(state, &state->sstack))
13347 return RE_ERROR_MEMORY;
13348 if (!push_repeats(state, &state->sstack))
13349 return RE_ERROR_MEMORY;
13350 if (!push_size(state, &state->sstack, state->capture_change))
13351 return RE_ERROR_MEMORY;
13352 if (!push_pointer(state, &state->sstack, next_node))
13353 return RE_ERROR_MEMORY;
13354 if (!push_uint8(state, &state->bstack, RE_OP_GROUP_CALL))
13355 return RE_ERROR_MEMORY;
13356
13357 /* sstack: caller_groups caller_repeats capture_change return_node
13358 *
13359 * bstack: GROUP_CALL
13360 */
13361
13362 /* Clear the repeat guards for the group call. They'll be restored
13363 * on return.
13364 */
13365 for (r = 0; r < state->pattern->repeat_count; r++) {
13366 RE_RepeatData* repeat;
13367
13368 repeat = &state->repeats[r];
13369 repeat->body_guard_list.count = 0;
13370 repeat->body_guard_list.last_text_pos = -1;
13371 repeat->tail_guard_list.count = 0;
13372 repeat->tail_guard_list.last_text_pos = -1;
13373 }
13374
13375 /* Call a group, skipping its CALL_REF node. */
13376 node = pattern->call_ref_info[index].node->next_1.node;
13377 break;
13378 }
13379 case RE_OP_GROUP_EXISTS: /* Capture group exists. */
13380 {
13381 RE_CODE index;
13382 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
13383
13384 /* Capture group indexes are 1-based (excluding group 0, which is
13385 * the entire matched string).
13386 *
13387 * Check whether the captured text, if any, exists at this position
13388 * in the string.
13389 *
13390 * A group index of 0, however, means that it's a DEFINE, which we
13391 * should skip.
13392 */
13393 index = node->values[0];
13394
13395 if (index == 0)
13396 /* Skip past the body. */
13397 node = node->nonstring.next_2.node;
13398 else {
13399 RE_GroupData* group;
13400
13401 group = &state->groups[index - 1];
13402 if (group->current >= 0)
13403 /* The 'true' branch. */
13404 node = node->next_1.node;
13405 else
13406 /* The 'false' branch. */
13407 node = node->nonstring.next_2.node;
13408 }
13409 break;
13410 }
13411 case RE_OP_GROUP_RETURN: /* Group return. */
13412 {
13413 RE_Node* return_node;
13414 TRACE(("%s\n", re_op_text[node->op]))
13415
13416 /* If called:
13417 *
13418 * sstack: caller_groups caller_repeats capture_change return_node
13419 *
13420 * bstack: -
13421 *
13422 * else:
13423 *
13424 * sstack: NULL
13425 *
13426 * bstack: -
13427 */
13428
13429 if (!pop_pointer(state, &state->sstack, (void*)&return_node))
13430 return RE_ERROR_MEMORY;
13431
13432 if (return_node) {
13433 /* The group was called. */
13434 node = return_node;
13435
13436 /* For the callee. */
13437 if (!push_groups(state, &state->bstack))
13438 return RE_ERROR_MEMORY;
13439 if (!push_repeats(state, &state->bstack))
13440 return RE_ERROR_MEMORY;
13441 if (!push_size(state, &state->bstack, state->capture_change))
13442 return RE_ERROR_MEMORY;
13443 if (!push_pointer(state, &state->bstack, return_node))
13444 return RE_ERROR_MEMORY;
13445 if (!push_uint8(state, &state->bstack, RE_OP_GROUP_RETURN))
13446 return RE_ERROR_MEMORY;
13447
13448 /* For the caller. */
13449 if (!pop_size(state, &state->sstack, &state->capture_change))
13450 return RE_ERROR_MEMORY;
13451 if (!pop_repeats(state, &state->sstack))
13452 return RE_ERROR_MEMORY;
13453 if (!pop_groups(state, &state->sstack))
13454 return RE_ERROR_MEMORY;
13455 } else {
13456 /* The group was not called. */
13457 if (!push_pointer(state, &state->bstack, NULL))
13458 return RE_ERROR_MEMORY;
13459 if (!push_uint8(state, &state->bstack, RE_OP_GROUP_RETURN))
13460 return RE_ERROR_MEMORY;
13461
13462 node = node->next_1.node;
13463 }
13464
13465 /* If called:
13466 *
13467 * sstack: -
13468 *
13469 * bstack: callee_groups callee_repeats capture_change return_node
13470 * GROUP_RETURN
13471 *
13472 * else:
13473 *
13474 * sstack: -
13475 *
13476 * bstack: NULL GROUP_RETURN
13477 */
13478 break;
13479 }
13480 case RE_OP_KEEP: /* Keep. */
13481 TRACE(("%s\n", re_op_text[node->op]))
13482
13483 if (!push_ssize(state, &state->bstack, state->match_pos))
13484 return RE_ERROR_MEMORY;
13485 if (!push_uint8(state, &state->bstack, RE_OP_KEEP))
13486 return RE_ERROR_MEMORY;
13487
13488 /* bstack: match_pos KEEP */
13489
13490 state->match_pos = state->text_pos;
13491
13492 node = node->next_1.node;
13493 break;
13494 case RE_OP_LAZY_REPEAT: /* Lazy repeat. */
13495 {
13496 RE_CODE index;
13497 RE_RepeatData* rp_data;
13498 BOOL try_body;
13499 int body_status;
13500 RE_Position next_body_position;
13501 BOOL try_tail;
13502 int tail_status;
13503 RE_Position next_tail_position;
13504 RE_RepeatStateData data_r;
13505 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
13506
13507 /* Repeat indexes are 0-based. */
13508 index = node->values[0];
13509 rp_data = &state->repeats[index];
13510
13511 /* We might need to backtrack into the head, so save the current
13512 * repeat.
13513 */
13514 data_r.count = rp_data->count;
13515 data_r.start = rp_data->start;
13516 data_r.capture_change = rp_data->capture_change;
13517 data_r.index = index;
13518 data_r.text_pos = state->text_pos;
13519
13520 if (!ByteStack_push_block(state, &state->bstack, (void*)&data_r,
13521 sizeof(data_r)))
13522 return RE_ERROR_MEMORY;
13523 if (!push_uint8(state, &state->bstack, RE_OP_LAZY_REPEAT))
13524 return RE_ERROR_MEMORY;
13525
13526 /* bstack: count start capture_change index text_pos LAZY_REPEAT */
13527
13528 /* Initialise the new repeat. */
13529 rp_data->count = 0;
13530 rp_data->start = state->text_pos;
13531 rp_data->capture_change = state->capture_change;
13532
13533 /* Could the body or tail match? */
13534 #if defined(VERBOSE)
13535 printf(" is_repeat_guarded(..., RE_STATUS_BODY) returns %d\n",
13536 is_repeat_guarded(state, index, state->text_pos,
13537 RE_STATUS_BODY));
13538 #endif
13539 try_body = node->values[2] > 0 && !is_repeat_guarded(state, index,
13540 state->text_pos, RE_STATUS_BODY);
13541 if (try_body) {
13542 body_status = try_match(state, &node->next_1, state->text_pos,
13543 &next_body_position);
13544 if (body_status < 0)
13545 return body_status;
13546
13547 if (body_status == RE_ERROR_FAILURE)
13548 try_body = FALSE;
13549 } else
13550 body_status = RE_ERROR_FAILURE;
13551
13552 try_tail = node->values[1] == 0;
13553 if (try_tail) {
13554 tail_status = try_match(state, &node->nonstring.next_2,
13555 state->text_pos, &next_tail_position);
13556 if (tail_status < 0)
13557 return tail_status;
13558
13559 if (tail_status == RE_ERROR_FAILURE)
13560 try_tail = FALSE;
13561 } else
13562 tail_status = RE_ERROR_FAILURE;
13563
13564 if (!try_body && !try_tail)
13565 /* Neither the body nor the tail could match. */
13566 goto backtrack;
13567
13568 if (body_status < 0 || (body_status == 0 && tail_status < 0))
13569 return RE_ERROR_PARTIAL;
13570
13571 if (try_tail) {
13572 if (try_body) {
13573 /* Both the body and the tail could match, but the tail
13574 * takes precedence. If the tail fails to match then we
13575 * want to try the body before backtracking further.
13576 */
13577 RE_MatchBodyTailStateData data_mbt;
13578
13579 /* Record backtracking info for matching the body. */
13580 data_mbt.position = next_body_position;
13581 data_mbt.count = rp_data->count;
13582 data_mbt.start = rp_data->start;
13583 data_mbt.capture_change = rp_data->capture_change;
13584 data_mbt.index = index;
13585 data_mbt.text_pos = state->text_pos;
13586
13587 if (!ByteStack_push_block(state, &state->bstack,
13588 (void*)&data_mbt, sizeof(data_mbt)))
13589 return RE_ERROR_MEMORY;
13590 if (!push_uint8(state, &state->bstack, RE_OP_MATCH_BODY))
13591 return RE_ERROR_MEMORY;
13592
13593 /* bstack: position count start capture_change index
13594 * text_pos MATCH_BODY
13595 */
13596 }
13597
13598 /* Record backtracking info in case the tail fails to match. */
13599 if (!push_code(state, &state->bstack, index))
13600 return RE_ERROR_MEMORY;
13601 if (!push_ssize(state, &state->bstack, state->text_pos))
13602 return RE_ERROR_MEMORY;
13603 if (!push_uint8(state, &state->bstack, RE_OP_TAIL_START))
13604 return RE_ERROR_MEMORY;
13605
13606 /* bstack: index text_pos TAIL_START */
13607
13608 /* Advance into the tail. */
13609 node = next_tail_position.node;
13610 state->text_pos = next_tail_position.text_pos;
13611 } else {
13612 /* Only the body could match. */
13613
13614 /* Record backtracking info in case the body fails to match. */
13615 if (!push_code(state, &state->bstack, index))
13616 return RE_ERROR_MEMORY;
13617 if (!push_ssize(state, &state->bstack, state->text_pos))
13618 return RE_ERROR_MEMORY;
13619 if (!push_uint8(state, &state->bstack, RE_OP_BODY_START))
13620 return RE_ERROR_MEMORY;
13621
13622 /* bstack: index text_pos BODY_START */
13623
13624 /* Advance into the body. */
13625 node = next_body_position.node;
13626 state->text_pos = next_body_position.text_pos;
13627 }
13628 break;
13629 }
13630 case RE_OP_LAZY_REPEAT_ONE: /* Lazy repeat for one character. */
13631 {
13632 RE_CODE index;
13633 RE_RepeatData* rp_data;
13634 size_t count;
13635 BOOL is_partial;
13636 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
13637
13638 /* Repeat indexes are 0-based. */
13639 index = node->values[0];
13640 rp_data = &state->repeats[index];
13641
13642 if (is_repeat_guarded(state, index, state->text_pos,
13643 RE_STATUS_BODY))
13644 goto backtrack;
13645
13646 /* Count how many times the character repeats, up to the minimum.
13647 */
13648 count = count_one(state, node->nonstring.next_2.node,
13649 state->text_pos, node->values[1], &is_partial);
13650 if (is_partial) {
13651 state->text_pos += (Py_ssize_t)count * node->step;
13652 return RE_ERROR_PARTIAL;
13653 }
13654
13655 /* Have we matched at least the minimum? */
13656 if (count < node->values[1]) {
13657 /* The repeat has failed to match at this position. */
13658 if (!guard_repeat(state, index, state->text_pos,
13659 RE_STATUS_BODY, TRUE))
13660 return RE_ERROR_MEMORY;
13661 goto backtrack;
13662 }
13663
13664 if (count < node->values[2]) {
13665 /* The match is shorter than the maximum, so we might need to
13666 * backtrack the repeat to consume more.
13667 */
13668 RE_RepeatOneStateData data_ro;
13669
13670 data_ro.count = rp_data->count;
13671 data_ro.start = rp_data->start;
13672 data_ro.node = node;
13673 data_ro.index = index;
13674
13675 if (!ByteStack_push_block(state, &state->bstack,
13676 (void*)&data_ro, sizeof(data_ro)))
13677 return RE_ERROR_MEMORY;
13678 if (!push_uint8(state, &state->bstack, RE_OP_LAZY_REPEAT_ONE))
13679 return RE_ERROR_MEMORY;
13680
13681 /* bstack: count start node index LAZY_REPEAT_ONE */
13682
13683 /* Get the offset to the repeat values in the context. */
13684 rp_data = &state->repeats[index];
13685
13686 rp_data->start = state->text_pos;
13687 rp_data->count = count;
13688 }
13689
13690 /* Advance into the tail. */
13691 state->text_pos += (Py_ssize_t)count * node->step;
13692 node = node->next_1.node;
13693 break;
13694 }
13695 case RE_OP_LOOKAROUND: /* Start of a lookaround subpattern. */
13696 {
13697 RE_LookaroundStateData data_l;
13698 BOOL has_groups;
13699 TRACE(("%s %d\n", re_op_text[node->op], node->match))
13700
13701 data_l.node = node;
13702 data_l.slice_start = state->slice_start;
13703 data_l.slice_end = state->slice_end;
13704 data_l.text_pos = state->text_pos;
13705
13706 if (!ByteStack_push_block(state, &state->sstack, (void*)&data_l,
13707 sizeof(data_l)))
13708 return RE_ERROR_MEMORY;
13709 has_groups = (node->status & RE_STATUS_HAS_GROUPS) != 0;
13710 if (has_groups) {
13711 if (!push_captures(state, &state->bstack))
13712 return RE_ERROR_MEMORY;
13713 }
13714 if (!push_bool(state, &state->bstack, has_groups))
13715 return RE_ERROR_MEMORY;
13716 if (!push_fuzzy_counts(state, &state->bstack, state->fuzzy_counts))
13717 return RE_ERROR_MEMORY;
13718 if (!push_size(state, &state->bstack, state->capture_change))
13719 return RE_ERROR_MEMORY;
13720 if (!push_sstack(state))
13721 return RE_ERROR_MEMORY;
13722 if (!push_uint8(state, &state->bstack, RE_OP_LOOKAROUND))
13723 return RE_ERROR_MEMORY;
13724 if (!push_bstack(state))
13725 return RE_ERROR_MEMORY;
13726
13727 /* sstack: node slice_start slice_end text_pos
13728 *
13729 * bstack: [captures TRUE | FALSE] fuzzy_counts capture_change
13730 * sstack LOOKAROUND
13731 *
13732 * pstack: bstack
13733 */
13734
13735 state->slice_start = state->text_start;
13736 state->slice_end = state->text_end;
13737
13738 node = node->next_1.node;
13739 break;
13740 }
13741 case RE_OP_PROPERTY: /* A property. */
13742 TRACE(("%s %d %d\n", re_op_text[node->op], node->match,
13743 node->values[0]))
13744
13745 if (state->text_pos >= state->text_end && state->partial_side ==
13746 RE_PARTIAL_RIGHT)
13747 return RE_ERROR_PARTIAL;
13748
13749 if (state->text_pos < state->slice_end &&
13750 matches_PROPERTY(encoding, locale_info, node,
13751 char_at(state->text, state->text_pos)) == node->match) {
13752 state->text_pos += node->step;
13753 node = node->next_1.node;
13754 } else if (node->status & RE_STATUS_FUZZY) {
13755 status = fuzzy_match_item(state, search, &node, 1);
13756 if (status < 0)
13757 return status;
13758
13759 if (status == RE_ERROR_FAILURE)
13760 goto backtrack;
13761 } else
13762 goto backtrack;
13763 break;
13764 case RE_OP_PROPERTY_IGN: /* A property, ignoring case. */
13765 TRACE(("%s %d %d\n", re_op_text[node->op], node->match,
13766 node->values[0]))
13767
13768 if (state->text_pos >= state->text_end && state->partial_side ==
13769 RE_PARTIAL_RIGHT)
13770 return RE_ERROR_PARTIAL;
13771
13772 if (state->text_pos < state->slice_end &&
13773 matches_PROPERTY_IGN(encoding, locale_info, node,
13774 char_at(state->text, state->text_pos)) == node->match) {
13775 state->text_pos += node->step;
13776 node = node->next_1.node;
13777 } else if (node->status & RE_STATUS_FUZZY) {
13778 status = fuzzy_match_item(state, search, &node, 1);
13779 if (status < 0)
13780 return status;
13781
13782 if (status == RE_ERROR_FAILURE)
13783 goto backtrack;
13784 } else
13785 goto backtrack;
13786 break;
13787 case RE_OP_PROPERTY_IGN_REV: /* A property, backwards, ignoring case. */
13788 TRACE(("%s %d %d\n", re_op_text[node->op], node->match,
13789 node->values[0]))
13790
13791 if (state->text_pos <= state->text_start && state->partial_side == RE_PARTIAL_LEFT)
13792 return RE_ERROR_PARTIAL;
13793
13794 if (state->text_pos > state->slice_start &&
13795 matches_PROPERTY_IGN(encoding, locale_info, node,
13796 char_at(state->text, state->text_pos - 1)) == node->match) {
13797 state->text_pos += node->step;
13798 node = node->next_1.node;
13799 } else if (node->status & RE_STATUS_FUZZY) {
13800 status = fuzzy_match_item(state, search, &node, -1);
13801 if (status < 0)
13802 return status;
13803
13804 if (status == RE_ERROR_FAILURE)
13805 goto backtrack;
13806 } else
13807 goto backtrack;
13808 break;
13809 case RE_OP_PROPERTY_REV: /* A property, backwards. */
13810 TRACE(("%s %d %d\n", re_op_text[node->op], node->match,
13811 node->values[0]))
13812
13813 if (state->text_pos <= state->text_start && state->partial_side == RE_PARTIAL_LEFT)
13814 return RE_ERROR_PARTIAL;
13815
13816 if (state->text_pos > state->slice_start &&
13817 matches_PROPERTY(encoding, locale_info, node,
13818 char_at(state->text, state->text_pos - 1)) == node->match) {
13819 state->text_pos += node->step;
13820 node = node->next_1.node;
13821 } else if (node->status & RE_STATUS_FUZZY) {
13822 status = fuzzy_match_item(state, search, &node, -1);
13823 if (status < 0)
13824 return status;
13825
13826 if (status == RE_ERROR_FAILURE)
13827 goto backtrack;
13828 } else
13829 goto backtrack;
13830 break;
13831 case RE_OP_PRUNE: /* Prune the backtracking. */
13832 TRACE(("%s\n", re_op_text[node->op]))
13833
13834 /* bstack: ... | ...
13835 *
13836 * pstack: bstack
13837 */
13838
13839 /* Prune the backtracking back to an appropriate backtracking
13840 * point.
13841 */
13842 top_bstack(state);
13843
13844 /* bstack: ...
13845 *
13846 * pstack: bstack
13847 */
13848
13849 node = node->next_1.node;
13850 break;
13851 case RE_OP_RANGE: /* A range. */
13852 TRACE(("%s %d %d %d\n", re_op_text[node->op], node->match,
13853 node->values[0], node->values[1]))
13854
13855 if (state->text_pos >= state->text_end && state->partial_side ==
13856 RE_PARTIAL_RIGHT)
13857 return RE_ERROR_PARTIAL;
13858
13859 if (state->text_pos < state->slice_end && matches_RANGE(encoding,
13860 locale_info, node, char_at(state->text, state->text_pos)) ==
13861 node->match) {
13862 state->text_pos += node->step;
13863 node = node->next_1.node;
13864 } else if (node->status & RE_STATUS_FUZZY) {
13865 status = fuzzy_match_item(state, search, &node, 1);
13866 if (status < 0)
13867 return status;
13868
13869 if (status == RE_ERROR_FAILURE)
13870 goto backtrack;
13871 } else
13872 goto backtrack;
13873 break;
13874 case RE_OP_RANGE_IGN: /* A range, ignoring case. */
13875 TRACE(("%s %d %d %d\n", re_op_text[node->op], node->match,
13876 node->values[0], node->values[1]))
13877
13878 if (state->text_pos >= state->text_end && state->partial_side ==
13879 RE_PARTIAL_RIGHT)
13880 return RE_ERROR_PARTIAL;
13881
13882 if (state->text_pos < state->slice_end &&
13883 matches_RANGE_IGN(encoding, locale_info, node,
13884 char_at(state->text, state->text_pos)) == node->match) {
13885 state->text_pos += node->step;
13886 node = node->next_1.node;
13887 } else if (node->status & RE_STATUS_FUZZY) {
13888 status = fuzzy_match_item(state, search, &node, 1);
13889 if (status < 0)
13890 return status;
13891
13892 if (status == RE_ERROR_FAILURE)
13893 goto backtrack;
13894 } else
13895 goto backtrack;
13896 break;
13897 case RE_OP_RANGE_IGN_REV: /* A range, backwards, ignoring case. */
13898 TRACE(("%s %d %d %d\n", re_op_text[node->op], node->match,
13899 node->values[0], node->values[1]))
13900
13901 if (state->text_pos <= state->text_start && state->partial_side == RE_PARTIAL_LEFT)
13902 return RE_ERROR_PARTIAL;
13903
13904 if (state->text_pos > state->slice_start &&
13905 matches_RANGE_IGN(encoding, locale_info, node,
13906 char_at(state->text, state->text_pos - 1)) == node->match) {
13907 state->text_pos += node->step;
13908 node = node->next_1.node;
13909 } else if (node->status & RE_STATUS_FUZZY) {
13910 status = fuzzy_match_item(state, search, &node, -1);
13911 if (status < 0)
13912 return status;
13913
13914 if (status == RE_ERROR_FAILURE)
13915 goto backtrack;
13916 } else
13917 goto backtrack;
13918 break;
13919 case RE_OP_RANGE_REV: /* A range, backwards. */
13920 TRACE(("%s %d %d %d\n", re_op_text[node->op], node->match,
13921 node->values[0], node->values[1]))
13922
13923 if (state->text_pos <= state->text_start && state->partial_side == RE_PARTIAL_LEFT)
13924 return RE_ERROR_PARTIAL;
13925
13926 if (state->text_pos > state->slice_start && matches_RANGE(encoding,
13927 locale_info, node, char_at(state->text, state->text_pos - 1)) ==
13928 node->match) {
13929 state->text_pos += node->step;
13930 node = node->next_1.node;
13931 } else if (node->status & RE_STATUS_FUZZY) {
13932 status = fuzzy_match_item(state, search, &node, -1);
13933 if (status < 0)
13934 return status;
13935
13936 if (status == RE_ERROR_FAILURE)
13937 goto backtrack;
13938 } else
13939 goto backtrack;
13940 break;
13941 case RE_OP_REF_GROUP: /* Reference to a capture group. */
13942 {
13943 RE_GroupData* group;
13944 RE_GroupSpan* span;
13945 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
13946
13947 /* Capture group indexes are 1-based (excluding group 0, which is
13948 * the entire matched string).
13949 *
13950 * Check whether the captured text, if any, exists at this position
13951 * in the string.
13952 */
13953
13954 /* Did the group capture anything? */
13955 group = &state->groups[node->values[0] - 1];
13956 if (group->current < 0)
13957 goto backtrack;
13958
13959 span = &group->captures[group->current];
13960
13961 if (string_pos < 0)
13962 string_pos = span->start;
13963
13964 /* Try comparing. */
13965 while (string_pos < span->end) {
13966 if (state->text_pos >= state->text_end &&
13967 state->partial_side == RE_PARTIAL_RIGHT)
13968 return RE_ERROR_PARTIAL;
13969
13970 if (state->text_pos < state->slice_end &&
13971 same_char(char_at(state->text, state->text_pos),
13972 char_at(state->text, string_pos))) {
13973 ++string_pos;
13974 ++state->text_pos;
13975 } else if (node->status & RE_STATUS_FUZZY) {
13976 status = fuzzy_match_string(state, search, node,
13977 &string_pos, 1);
13978 if (status < 0)
13979 return status;
13980
13981 if (status == RE_ERROR_FAILURE) {
13982 string_pos = -1;
13983 goto backtrack;
13984 }
13985 } else {
13986 string_pos = -1;
13987 goto backtrack;
13988 }
13989 }
13990
13991 string_pos = -1;
13992
13993 /* Successful match. */
13994 node = node->next_1.node;
13995 break;
13996 }
13997 case RE_OP_REF_GROUP_FLD: /* Reference to a capture group, ignoring case. */
13998 {
13999 RE_GroupData* group;
14000 RE_GroupSpan* span;
14001 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch,
14002 Py_UCS4* folded);
14003 int folded_len;
14004 int gfolded_len;
14005 Py_UCS4 folded[RE_MAX_FOLDED];
14006 Py_UCS4 gfolded[RE_MAX_FOLDED];
14007 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
14008
14009 /* Capture group indexes are 1-based (excluding group 0, which is
14010 * the entire matched string).
14011 *
14012 * Check whether the captured text, if any, exists at this position
14013 * in the string.
14014 */
14015
14016 /* Did the group capture anything? */
14017 group = &state->groups[node->values[0] - 1];
14018 if (group->current < 0)
14019 goto backtrack;
14020
14021 span = &group->captures[group->current];
14022
14023 full_case_fold = encoding->full_case_fold;
14024
14025 if (string_pos < 0) {
14026 string_pos = span->start;
14027 folded_pos = 0;
14028 folded_len = 0;
14029 gfolded_pos = 0;
14030 gfolded_len = 0;
14031 } else {
14032 folded_len = full_case_fold(locale_info, char_at(state->text,
14033 state->text_pos), folded);
14034 gfolded_len = full_case_fold(locale_info, char_at(state->text,
14035 string_pos), gfolded);
14036 }
14037
14038 /* Try comparing. */
14039 while (string_pos < span->end) {
14040 /* Case-fold at current position in text. */
14041 if (folded_pos >= folded_len) {
14042 if (state->text_pos >= state->text_end &&
14043 state->partial_side == RE_PARTIAL_RIGHT)
14044 return RE_ERROR_PARTIAL;
14045
14046 if (state->text_pos < state->slice_end)
14047 folded_len = full_case_fold(locale_info,
14048 char_at(state->text, state->text_pos), folded);
14049 else
14050 folded_len = 0;
14051
14052 folded_pos = 0;
14053 }
14054
14055 /* Case-fold at current position in group. */
14056 if (gfolded_pos >= gfolded_len) {
14057 gfolded_len = full_case_fold(locale_info,
14058 char_at(state->text, string_pos), gfolded);
14059 gfolded_pos = 0;
14060 }
14061
14062 if (folded_pos < folded_len && same_char_ign(encoding,
14063 locale_info, gfolded[gfolded_pos], folded[folded_pos])) {
14064 ++folded_pos;
14065 ++gfolded_pos;
14066 } else if (node->status & RE_STATUS_FUZZY) {
14067 status = fuzzy_match_group_fld(state, search, node,
14068 &folded_pos, folded_len, &string_pos, &gfolded_pos,
14069 gfolded_len, 1);
14070 if (status < 0)
14071 return status;
14072
14073 if (status == RE_ERROR_FAILURE) {
14074 string_pos = -1;
14075 goto backtrack;
14076 }
14077 } else {
14078 string_pos = -1;
14079 goto backtrack;
14080 }
14081
14082 if (folded_pos >= folded_len && folded_len > 0)
14083 ++state->text_pos;
14084
14085 if (gfolded_pos >= gfolded_len)
14086 ++string_pos;
14087 }
14088
14089 string_pos = -1;
14090
14091 if (folded_pos < folded_len || gfolded_pos < gfolded_len)
14092 goto backtrack;
14093
14094 /* Successful match. */
14095 node = node->next_1.node;
14096 break;
14097 }
14098 case RE_OP_REF_GROUP_FLD_REV: /* Reference to a capture group, ignoring case. */
14099 {
14100 RE_GroupData* group;
14101 RE_GroupSpan* span;
14102 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch,
14103 Py_UCS4* folded);
14104 int folded_len;
14105 int gfolded_len;
14106 Py_UCS4 folded[RE_MAX_FOLDED];
14107 Py_UCS4 gfolded[RE_MAX_FOLDED];
14108 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
14109
14110 /* Capture group indexes are 1-based (excluding group 0, which is
14111 * the entire matched string).
14112 *
14113 * Check whether the captured text, if any, exists at this position
14114 * in the string.
14115 */
14116
14117 /* Did the group capture anything? */
14118 group = &state->groups[node->values[0] - 1];
14119 if (group->current < 0)
14120 goto backtrack;
14121
14122 span = &group->captures[group->current];
14123
14124 full_case_fold = encoding->full_case_fold;
14125
14126 if (string_pos < 0) {
14127 string_pos = span->end;
14128 folded_pos = 0;
14129 folded_len = 0;
14130 gfolded_pos = 0;
14131 gfolded_len = 0;
14132 } else {
14133 folded_len = full_case_fold(locale_info, char_at(state->text,
14134 state->text_pos - 1), folded);
14135 gfolded_len = full_case_fold(locale_info, char_at(state->text,
14136 string_pos - 1), gfolded);
14137 }
14138
14139 /* Try comparing. */
14140 while (string_pos > span->start) {
14141 /* Case-fold at current position in text. */
14142 if (folded_pos <= 0) {
14143 if (state->text_pos <= state->text_start && state->partial_side ==
14144 RE_PARTIAL_LEFT)
14145 return RE_ERROR_PARTIAL;
14146
14147 if (state->text_pos > state->slice_start)
14148 folded_len = full_case_fold(locale_info,
14149 char_at(state->text, state->text_pos - 1), folded);
14150 else
14151 folded_len = 0;
14152
14153 folded_pos = folded_len;
14154 }
14155
14156 /* Case-fold at current position in group. */
14157 if (gfolded_pos <= 0) {
14158 gfolded_len = full_case_fold(locale_info,
14159 char_at(state->text, string_pos - 1), gfolded);
14160 gfolded_pos = gfolded_len;
14161 }
14162
14163 if (folded_pos > 0 && same_char_ign(encoding, locale_info,
14164 gfolded[gfolded_pos - 1], folded[folded_pos - 1])) {
14165 --folded_pos;
14166 --gfolded_pos;
14167 } else if (node->status & RE_STATUS_FUZZY) {
14168 status = fuzzy_match_group_fld(state, search, node,
14169 &folded_pos, folded_len, &string_pos, &gfolded_pos,
14170 gfolded_len, -1);
14171 if (status < 0)
14172 return status;
14173
14174 if (status == RE_ERROR_FAILURE) {
14175 string_pos = -1;
14176 goto backtrack;
14177 }
14178 } else {
14179 string_pos = -1;
14180 goto backtrack;
14181 }
14182
14183 if (folded_pos <= 0 && folded_len > 0)
14184 --state->text_pos;
14185
14186 if (gfolded_pos <= 0)
14187 --string_pos;
14188 }
14189
14190 string_pos = -1;
14191
14192 if (folded_pos > 0 || gfolded_pos > 0)
14193 goto backtrack;
14194
14195 /* Successful match. */
14196 node = node->next_1.node;
14197 break;
14198 }
14199 case RE_OP_REF_GROUP_IGN: /* Reference to a capture group, ignoring case. */
14200 {
14201 RE_GroupData* group;
14202 RE_GroupSpan* span;
14203 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
14204
14205 /* Capture group indexes are 1-based (excluding group 0, which is
14206 * the entire matched string).
14207 *
14208 * Check whether the captured text, if any, exists at this position
14209 * in the string.
14210 */
14211
14212 /* Did the group capture anything? */
14213 group = &state->groups[node->values[0] - 1];
14214 if (group->current < 0)
14215 goto backtrack;
14216
14217 span = &group->captures[group->current];
14218
14219 if (string_pos < 0)
14220 string_pos = span->start;
14221
14222 /* Try comparing. */
14223 while (string_pos < span->end) {
14224 if (state->text_pos >= state->text_end &&
14225 state->partial_side == RE_PARTIAL_RIGHT)
14226 return RE_ERROR_PARTIAL;
14227
14228 if (state->text_pos < state->slice_end &&
14229 same_char_ign(encoding, locale_info, char_at(state->text,
14230 state->text_pos), char_at(state->text, string_pos))) {
14231 ++string_pos;
14232 ++state->text_pos;
14233 } else if (node->status & RE_STATUS_FUZZY) {
14234 status = fuzzy_match_string(state, search, node,
14235 &string_pos, 1);
14236 if (status < 0)
14237 return status;
14238
14239 if (status == RE_ERROR_FAILURE) {
14240 string_pos = -1;
14241 goto backtrack;
14242 }
14243 } else {
14244 string_pos = -1;
14245 goto backtrack;
14246 }
14247 }
14248
14249 string_pos = -1;
14250
14251 /* Successful match. */
14252 node = node->next_1.node;
14253 break;
14254 }
14255 case RE_OP_REF_GROUP_IGN_REV: /* Reference to a capture group, ignoring case. */
14256 {
14257 RE_GroupData* group;
14258 RE_GroupSpan* span;
14259 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
14260
14261 /* Capture group indexes are 1-based (excluding group 0, which is
14262 * the entire matched string).
14263 *
14264 * Check whether the captured text, if any, exists at this position
14265 * in the string.
14266 */
14267
14268 /* Did the group capture anything? */
14269 group = &state->groups[node->values[0] - 1];
14270 if (group->current < 0)
14271 goto backtrack;
14272
14273 span = &group->captures[group->current];
14274
14275 if (string_pos < 0)
14276 string_pos = span->end;
14277
14278 /* Try comparing. */
14279 while (string_pos > span->start) {
14280 if (state->text_pos <= state->text_start && state->partial_side ==
14281 RE_PARTIAL_LEFT)
14282 return RE_ERROR_PARTIAL;
14283
14284 if (state->text_pos > state->slice_start &&
14285 same_char_ign(encoding, locale_info, char_at(state->text,
14286 state->text_pos - 1), char_at(state->text, string_pos - 1)))
14287 {
14288 --string_pos;
14289 --state->text_pos;
14290 } else if (node->status & RE_STATUS_FUZZY) {
14291 status = fuzzy_match_string(state, search, node,
14292 &string_pos, -1);
14293 if (status < 0)
14294 return status;
14295
14296 if (status == RE_ERROR_FAILURE) {
14297 string_pos = -1;
14298 goto backtrack;
14299 }
14300 } else {
14301 string_pos = -1;
14302 goto backtrack;
14303 }
14304 }
14305
14306 string_pos = -1;
14307
14308 /* Successful match. */
14309 node = node->next_1.node;
14310 break;
14311 }
14312 case RE_OP_REF_GROUP_REV: /* Reference to a capture group. */
14313 {
14314 RE_GroupData* group;
14315 RE_GroupSpan* span;
14316 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
14317
14318 /* Capture group indexes are 1-based (excluding group 0, which is
14319 * the entire matched string).
14320 *
14321 * Check whether the captured text, if any, exists at this position
14322 * in the string.
14323 */
14324
14325 /* Did the group capture anything? */
14326 group = &state->groups[node->values[0] - 1];
14327 if (group->current < 0)
14328 goto backtrack;
14329
14330 span = &group->captures[group->current];
14331
14332 if (string_pos < 0)
14333 string_pos = span->end;
14334
14335 /* Try comparing. */
14336 while (string_pos > span->start) {
14337 if (state->text_pos <= state->text_start && state->partial_side ==
14338 RE_PARTIAL_LEFT)
14339 return RE_ERROR_PARTIAL;
14340
14341 if (state->text_pos > state->slice_start &&
14342 same_char(char_at(state->text, state->text_pos - 1),
14343 char_at(state->text, string_pos - 1))) {
14344 --string_pos;
14345 --state->text_pos;
14346 } else if (node->status & RE_STATUS_FUZZY) {
14347 status = fuzzy_match_string(state, search, node,
14348 &string_pos, -1);
14349 if (status < 0)
14350 return status;
14351
14352 if (status == RE_ERROR_FAILURE) {
14353 string_pos = -1;
14354 goto backtrack;
14355 }
14356 } else {
14357 string_pos = -1;
14358 goto backtrack;
14359 }
14360 }
14361
14362 string_pos = -1;
14363
14364 /* Successful match. */
14365 node = node->next_1.node;
14366 break;
14367 }
14368 case RE_OP_SEARCH_ANCHOR: /* At the start of the search. */
14369 TRACE(("%s %d\n", re_op_text[node->op], node->values[0]))
14370
14371 if (state->text_pos == state->search_anchor)
14372 node = node->next_1.node;
14373 else if (node->status & RE_STATUS_FUZZY) {
14374 status = fuzzy_match_item(state, search, &node, 0);
14375 if (status < 0)
14376 return status;
14377
14378 if (status == RE_ERROR_FAILURE)
14379 goto backtrack;
14380 } else
14381 goto backtrack;
14382 break;
14383 case RE_OP_SET_DIFF: /* Set difference. */
14384 case RE_OP_SET_INTER: /* Set intersection. */
14385 case RE_OP_SET_SYM_DIFF: /* Set symmetric difference. */
14386 case RE_OP_SET_UNION: /* Set union. */
14387 TRACE(("%s %d\n", re_op_text[node->op], node->match))
14388
14389 if (state->text_pos >= state->text_end && state->partial_side ==
14390 RE_PARTIAL_RIGHT)
14391 return RE_ERROR_PARTIAL;
14392
14393 if (state->text_pos < state->slice_end && matches_SET(encoding,
14394 locale_info, node, char_at(state->text, state->text_pos)) ==
14395 node->match) {
14396 state->text_pos += node->step;
14397 node = node->next_1.node;
14398 } else if (node->status & RE_STATUS_FUZZY) {
14399 status = fuzzy_match_item(state, search, &node, 1);
14400 if (status < 0)
14401 return status;
14402
14403 if (status == RE_ERROR_FAILURE)
14404 goto backtrack;
14405 } else
14406 goto backtrack;
14407 break;
14408 case RE_OP_SET_DIFF_IGN: /* Set difference, ignoring case. */
14409 case RE_OP_SET_INTER_IGN: /* Set intersection, ignoring case. */
14410 case RE_OP_SET_SYM_DIFF_IGN: /* Set symmetric difference, ignoring case. */
14411 case RE_OP_SET_UNION_IGN: /* Set union, ignoring case. */
14412 TRACE(("%s %d\n", re_op_text[node->op], node->match))
14413
14414 if (state->text_pos >= state->text_end && state->partial_side ==
14415 RE_PARTIAL_RIGHT)
14416 return RE_ERROR_PARTIAL;
14417
14418 if (state->text_pos < state->slice_end && matches_SET_IGN(encoding,
14419 locale_info, node, char_at(state->text, state->text_pos)) ==
14420 node->match) {
14421 state->text_pos += node->step;
14422 node = node->next_1.node;
14423 } else if (node->status & RE_STATUS_FUZZY) {
14424 status = fuzzy_match_item(state, search, &node, 1);
14425 if (status < 0)
14426 return status;
14427
14428 if (status == RE_ERROR_FAILURE)
14429 goto backtrack;
14430 } else
14431 goto backtrack;
14432 break;
14433 case RE_OP_SET_DIFF_IGN_REV: /* Set difference, ignoring case. */
14434 case RE_OP_SET_INTER_IGN_REV: /* Set intersection, ignoring case. */
14435 case RE_OP_SET_SYM_DIFF_IGN_REV: /* Set symmetric difference, ignoring case. */
14436 case RE_OP_SET_UNION_IGN_REV: /* Set union, ignoring case. */
14437 TRACE(("%s %d\n", re_op_text[node->op], node->match))
14438
14439 if (state->text_pos <= state->text_start && state->partial_side == RE_PARTIAL_LEFT)
14440 return RE_ERROR_PARTIAL;
14441
14442 if (state->text_pos > state->slice_start &&
14443 matches_SET_IGN(encoding, locale_info, node, char_at(state->text,
14444 state->text_pos - 1)) == node->match) {
14445 state->text_pos += node->step;
14446 node = node->next_1.node;
14447 } else if (node->status & RE_STATUS_FUZZY) {
14448 status = fuzzy_match_item(state, search, &node, -1);
14449 if (status < 0)
14450 return status;
14451
14452 if (status == RE_ERROR_FAILURE)
14453 goto backtrack;
14454 } else
14455 goto backtrack;
14456 break;
14457 case RE_OP_SET_DIFF_REV: /* Set difference. */
14458 case RE_OP_SET_INTER_REV: /* Set intersection. */
14459 case RE_OP_SET_SYM_DIFF_REV: /* Set symmetric difference. */
14460 case RE_OP_SET_UNION_REV: /* Set union. */
14461 TRACE(("%s %d\n", re_op_text[node->op], node->match))
14462
14463 if (state->text_pos <= state->text_start && state->partial_side == RE_PARTIAL_LEFT)
14464 return RE_ERROR_PARTIAL;
14465
14466 if (state->text_pos > state->slice_start && matches_SET(encoding,
14467 locale_info, node, char_at(state->text, state->text_pos - 1)) ==
14468 node->match) {
14469 state->text_pos += node->step;
14470 node = node->next_1.node;
14471 } else if (node->status & RE_STATUS_FUZZY) {
14472 status = fuzzy_match_item(state, search, &node, -1);
14473 if (status < 0)
14474 return status;
14475
14476 if (status == RE_ERROR_FAILURE)
14477 goto backtrack;
14478 } else
14479 goto backtrack;
14480 break;
14481 case RE_OP_SKIP: /* Skip the part of the text already matched. */
14482 TRACE(("%s\n", re_op_text[node->op]))
14483
14484 /* bstack: ... | ...
14485 *
14486 * pstack: bstack
14487 */
14488
14489 if (node->status & RE_STATUS_REVERSE)
14490 state->slice_end = state->text_pos;
14491 else
14492 state->slice_start = state->text_pos;
14493
14494 /* Prune the backtracking back to an appropriate backtracking
14495 * point.
14496 */
14497 top_bstack(state);
14498
14499 /* bstack: ...
14500 *
14501 * pstack: bstack
14502 */
14503
14504 node = node->next_1.node;
14505 break;
14506 case RE_OP_START_GROUP: /* Start of a capture group. */
14507 {
14508 RE_CODE private_index;
14509 RE_CODE public_index;
14510 RE_GroupData* group;
14511 BOOL capture;
14512 TRACE(("%s %d\n", re_op_text[node->op], node->values[1]))
14513
14514 /* Capture group indexes are 1-based (excluding group 0, which is
14515 * the entire matched string).
14516 */
14517 private_index = node->values[0];
14518 public_index = node->values[1];
14519 group = &state->groups[private_index - 1];
14520 capture = (BOOL)node->values[2];
14521
14522 if (capture) {
14523 RE_GroupSpan span;
14524 RE_GroupStateData data_g;
14525
14526 /* sstack: end
14527 *
14528 * bstack: -
14529 */
14530
14531 if (!pop_ssize(state, &state->sstack, &span.end))
14532 return RE_ERROR_MEMORY;
14533
14534 span.start = state->text_pos;
14535
14536 data_g.text_pos = span.end;
14537 data_g.current = group->current;
14538 data_g.capture_change = state->capture_change;
14539 data_g.private_index = private_index;
14540 data_g.public_index = public_index;
14541
14542 if (!ByteStack_push_block(state, &state->bstack,
14543 (void*)&data_g, sizeof(data_g)))
14544 return RE_ERROR_MEMORY;
14545
14546 if (pattern->group_info[private_index - 1].referenced &&
14547 !same_span_as_group(group, span))
14548 ++state->capture_change;
14549
14550 if (!save_capture(state, private_index, public_index, span))
14551 return RE_ERROR_MEMORY;
14552 group->current = (Py_ssize_t)group->count - 1;
14553 } else {
14554 if (!push_ssize(state, &state->sstack, state->text_pos))
14555 return RE_ERROR_MEMORY;
14556 }
14557
14558 if (!push_bool(state, &state->bstack, capture))
14559 return RE_ERROR_MEMORY;
14560 if (!push_uint8(state, &state->bstack, RE_OP_START_GROUP))
14561 return RE_ERROR_MEMORY;
14562
14563 /* If capturing:
14564 *
14565 * sstack: -
14566 *
14567 * bstack: end current capture_change private_index public_index
14568 * TRUE START_GROUP
14569 *
14570 * else:
14571 *
14572 * sstack: start
14573 *
14574 * bstack: FALSE START_GROUP
14575 */
14576
14577 node = node->next_1.node;
14578 break;
14579 }
14580 case RE_OP_START_OF_LINE: /* At the start of a line. */
14581 TRACE(("%s\n", re_op_text[node->op]))
14582
14583 status = try_match_START_OF_LINE(state, node, state->text_pos);
14584 if (status < 0)
14585 return status;
14586
14587 if (status == RE_ERROR_SUCCESS)
14588 node = node->next_1.node;
14589 else if (node->status & RE_STATUS_FUZZY) {
14590 status = fuzzy_match_item(state, search, &node, 0);
14591 if (status < 0)
14592 return status;
14593
14594 if (status == RE_ERROR_FAILURE)
14595 goto backtrack;
14596 } else
14597 goto backtrack;
14598 break;
14599 case RE_OP_START_OF_LINE_U: /* At the start of a line. */
14600 TRACE(("%s\n", re_op_text[node->op]))
14601
14602 status = try_match_START_OF_LINE_U(state, node, state->text_pos);
14603 if (status < 0)
14604 return status;
14605
14606 if (status == RE_ERROR_SUCCESS)
14607 node = node->next_1.node;
14608 else if (node->status & RE_STATUS_FUZZY) {
14609 status = fuzzy_match_item(state, search, &node, 0);
14610 if (status < 0)
14611 return status;
14612
14613 if (status == RE_ERROR_FAILURE)
14614 goto backtrack;
14615 } else
14616 goto backtrack;
14617 break;
14618 case RE_OP_START_OF_STRING: /* At the start of the string. */
14619 TRACE(("%s\n", re_op_text[node->op]))
14620
14621 status = try_match_START_OF_STRING(state, node, state->text_pos);
14622 if (status < 0)
14623 return status;
14624
14625 if (status == RE_ERROR_SUCCESS)
14626 node = node->next_1.node;
14627 else if (node->status & RE_STATUS_FUZZY) {
14628 status = fuzzy_match_item(state, search, &node, 0);
14629 if (status < 0)
14630 return status;
14631
14632 if (status == RE_ERROR_FAILURE)
14633 goto backtrack;
14634 } else
14635 goto backtrack;
14636 break;
14637 case RE_OP_START_OF_WORD: /* At the start of a word. */
14638 TRACE(("%s\n", re_op_text[node->op]))
14639
14640 status = try_match_START_OF_WORD(state, node, state->text_pos);
14641 if (status < 0)
14642 return status;
14643
14644 if (status == RE_ERROR_SUCCESS)
14645 node = node->next_1.node;
14646 else if (node->status & RE_STATUS_FUZZY) {
14647 status = fuzzy_match_item(state, search, &node, 0);
14648 if (status < 0)
14649 return status;
14650
14651 if (status == RE_ERROR_FAILURE)
14652 goto backtrack;
14653 } else
14654 goto backtrack;
14655 break;
14656 case RE_OP_STRING: /* A string. */
14657 {
14658 Py_ssize_t length;
14659 RE_CODE* values;
14660 TRACE(("%s %zd\n", re_op_text[node->op], node->value_count))
14661
14662 if ((node->status & RE_STATUS_REQUIRED) && state->text_pos ==
14663 state->req_pos && string_pos < 0)
14664 state->text_pos = state->req_end;
14665 else {
14666 length = (Py_ssize_t)node->value_count;
14667
14668 if (string_pos < 0)
14669 string_pos = 0;
14670
14671 values = node->values;
14672
14673 /* Try comparing. */
14674 while (string_pos < length) {
14675 if (state->text_pos >= state->text_end &&
14676 state->partial_side == RE_PARTIAL_RIGHT)
14677 return RE_ERROR_PARTIAL;
14678
14679 if (state->text_pos < state->slice_end &&
14680 same_char(char_at(state->text, state->text_pos),
14681 values[string_pos])) {
14682 ++string_pos;
14683 ++state->text_pos;
14684 } else if (node->status & RE_STATUS_FUZZY) {
14685 status = fuzzy_match_string(state, search, node,
14686 &string_pos, 1);
14687 if (status < 0)
14688 return status;
14689
14690 if (status == RE_ERROR_FAILURE) {
14691 string_pos = -1;
14692 goto backtrack;
14693 }
14694 } else {
14695 string_pos = -1;
14696 goto backtrack;
14697 }
14698 }
14699 }
14700
14701 if (node->status & RE_STATUS_FUZZY) {
14702 status = fuzzy_insert(state, 1, node->next_1.node);
14703 if (status < 0)
14704 return status;
14705 }
14706
14707 string_pos = -1;
14708
14709 /* Successful match. */
14710 node = node->next_1.node;
14711 break;
14712 }
14713 case RE_OP_STRING_FLD: /* A string, ignoring case. */
14714 {
14715 Py_ssize_t length;
14716 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch,
14717 Py_UCS4* folded);
14718 RE_CODE* values;
14719 int folded_len;
14720 Py_UCS4 folded[RE_MAX_FOLDED];
14721 TRACE(("%s %zd\n", re_op_text[node->op], node->value_count))
14722
14723 if ((node->status & RE_STATUS_REQUIRED) && state->text_pos ==
14724 state->req_pos && string_pos < 0)
14725 state->text_pos = state->req_end;
14726 else {
14727 length = (Py_ssize_t)node->value_count;
14728
14729 full_case_fold = encoding->full_case_fold;
14730
14731 if (string_pos < 0) {
14732 string_pos = 0;
14733 folded_pos = 0;
14734 folded_len = 0;
14735 } else {
14736 folded_len = full_case_fold(locale_info,
14737 char_at(state->text, state->text_pos), folded);
14738 if (folded_pos >= folded_len) {
14739 if (state->text_pos >= state->slice_end)
14740 goto backtrack;
14741
14742 ++state->text_pos;
14743 folded_pos = 0;
14744 folded_len = 0;
14745 }
14746 }
14747
14748 values = node->values;
14749
14750 /* Try comparing. */
14751 while (string_pos < length) {
14752 if (folded_pos >= folded_len) {
14753 if (state->text_pos >= state->text_end &&
14754 state->partial_side == RE_PARTIAL_RIGHT)
14755 return RE_ERROR_PARTIAL;
14756
14757 if (state->text_pos < state->slice_end)
14758 folded_len = full_case_fold(locale_info,
14759 char_at(state->text, state->text_pos), folded);
14760 else
14761 folded_len = 0;
14762
14763 folded_pos = 0;
14764 }
14765
14766 if (folded_pos < folded_len && same_char_ign(encoding,
14767 locale_info, values[string_pos], folded[folded_pos])) {
14768 ++string_pos;
14769 ++folded_pos;
14770
14771 if (folded_pos >= folded_len)
14772 ++state->text_pos;
14773 } else if (node->status & RE_STATUS_FUZZY) {
14774 status = fuzzy_match_string_fld(state, search, node,
14775 &string_pos, &folded_pos, folded_len, 1);
14776 if (status < 0)
14777 return status;
14778
14779 if (status == RE_ERROR_FAILURE) {
14780 string_pos = -1;
14781 goto backtrack;
14782 }
14783
14784 if (folded_pos >= folded_len && folded_len > 0)
14785 ++state->text_pos;
14786 } else {
14787 string_pos = -1;
14788 goto backtrack;
14789 }
14790 }
14791
14792 if (node->status & RE_STATUS_FUZZY) {
14793 while (folded_pos < folded_len) {
14794 status = fuzzy_match_string_fld(state, search, node,
14795 &string_pos, &folded_pos, folded_len, 1);
14796 if (status < 0)
14797 return status;
14798
14799 if (status == RE_ERROR_FAILURE) {
14800 string_pos = -1;
14801 goto backtrack;
14802 }
14803
14804 if (folded_pos >= folded_len && folded_len > 0)
14805 ++state->text_pos;
14806 }
14807 }
14808
14809 string_pos = -1;
14810
14811 if (folded_pos < folded_len)
14812 goto backtrack;
14813 }
14814
14815 /* Successful match. */
14816 node = node->next_1.node;
14817 break;
14818 }
14819 case RE_OP_STRING_FLD_REV: /* A string, ignoring case. */
14820 {
14821 Py_ssize_t length;
14822 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch,
14823 Py_UCS4* folded);
14824 RE_CODE* values;
14825 int folded_len;
14826 Py_UCS4 folded[RE_MAX_FOLDED];
14827 TRACE(("%s %zd\n", re_op_text[node->op], node->value_count))
14828
14829 if ((node->status & RE_STATUS_REQUIRED) && state->text_pos ==
14830 state->req_pos && string_pos < 0)
14831 state->text_pos = state->req_end;
14832 else {
14833 length = (Py_ssize_t)node->value_count;
14834
14835 full_case_fold = encoding->full_case_fold;
14836
14837 if (string_pos < 0) {
14838 string_pos = length;
14839 folded_pos = 0;
14840 folded_len = 0;
14841 } else {
14842 folded_len = full_case_fold(locale_info,
14843 char_at(state->text, state->text_pos - 1), folded);
14844 if (folded_pos <= 0) {
14845 if (state->text_pos <= state->slice_start)
14846 goto backtrack;
14847
14848 --state->text_pos;
14849 folded_pos = 0;
14850 folded_len = 0;
14851 }
14852 }
14853
14854 values = node->values;
14855
14856 /* Try comparing. */
14857 while (string_pos > 0) {
14858 if (folded_pos <= 0) {
14859 if (state->text_pos <= state->text_start && state->partial_side ==
14860 RE_PARTIAL_LEFT)
14861 return RE_ERROR_PARTIAL;
14862
14863 if (state->text_pos > state->slice_start)
14864 folded_len = full_case_fold(locale_info,
14865 char_at(state->text, state->text_pos - 1),
14866 folded);
14867 else
14868 folded_len = 0;
14869
14870 folded_pos = folded_len;
14871 }
14872
14873 if (folded_pos > 0 && same_char_ign(encoding, locale_info,
14874 values[string_pos - 1], folded[folded_pos - 1])) {
14875 --string_pos;
14876 --folded_pos;
14877
14878 if (folded_pos <= 0)
14879 --state->text_pos;
14880 } else if (node->status & RE_STATUS_FUZZY) {
14881 status = fuzzy_match_string_fld(state, search, node,
14882 &string_pos, &folded_pos, folded_len, -1);
14883 if (status < 0)
14884 return status;
14885
14886 if (status == RE_ERROR_FAILURE) {
14887 string_pos = -1;
14888 goto backtrack;
14889 }
14890
14891 if (folded_pos <= 0 && folded_len > 0)
14892 --state->text_pos;
14893 } else {
14894 string_pos = -1;
14895 goto backtrack;
14896 }
14897 }
14898
14899 if (node->status & RE_STATUS_FUZZY) {
14900 while (folded_pos > 0) {
14901 status = fuzzy_match_string_fld(state, search, node,
14902 &string_pos, &folded_pos, folded_len, -1);
14903 if (status < 0)
14904 return status;
14905
14906 if (status == RE_ERROR_FAILURE) {
14907 string_pos = -1;
14908 goto backtrack;
14909 }
14910
14911 if (folded_pos <= 0 && folded_len > 0)
14912 --state->text_pos;
14913 }
14914 }
14915
14916 string_pos = -1;
14917
14918 if (folded_pos > 0)
14919 goto backtrack;
14920 }
14921
14922 /* Successful match. */
14923 node = node->next_1.node;
14924 break;
14925 }
14926 case RE_OP_STRING_IGN: /* A string, ignoring case. */
14927 {
14928 Py_ssize_t length;
14929 RE_CODE* values;
14930 TRACE(("%s %zd\n", re_op_text[node->op], node->value_count))
14931
14932 if ((node->status & RE_STATUS_REQUIRED) && state->text_pos ==
14933 state->req_pos && string_pos < 0)
14934 state->text_pos = state->req_end;
14935 else {
14936 length = (Py_ssize_t)node->value_count;
14937
14938 if (string_pos < 0)
14939 string_pos = 0;
14940
14941 values = node->values;
14942
14943 /* Try comparing. */
14944 while (string_pos < length) {
14945 if (state->text_pos >= state->text_end &&
14946 state->partial_side == RE_PARTIAL_RIGHT)
14947 return RE_ERROR_PARTIAL;
14948
14949 if (state->text_pos < state->slice_end &&
14950 same_char_ign(encoding, locale_info, char_at(state->text,
14951 state->text_pos), values[string_pos])) {
14952 ++string_pos;
14953 ++state->text_pos;
14954 } else if (node->status & RE_STATUS_FUZZY) {
14955 status = fuzzy_match_string(state, search, node,
14956 &string_pos, 1);
14957 if (status < 0)
14958 return status;
14959
14960 if (status == RE_ERROR_FAILURE) {
14961 string_pos = -1;
14962 goto backtrack;
14963 }
14964 } else {
14965 string_pos = -1;
14966 goto backtrack;
14967 }
14968 }
14969 }
14970
14971 if (node->status & RE_STATUS_FUZZY) {
14972 status = fuzzy_insert(state, 1, node->next_1.node);
14973 if (status < 0)
14974 return status;
14975 }
14976
14977 string_pos = -1;
14978
14979 /* Successful match. */
14980 node = node->next_1.node;
14981 break;
14982 }
14983 case RE_OP_STRING_IGN_REV: /* A string, ignoring case. */
14984 {
14985 Py_ssize_t length;
14986 RE_CODE* values;
14987 TRACE(("%s %zd\n", re_op_text[node->op], node->value_count))
14988
14989 if ((node->status & RE_STATUS_REQUIRED) && state->text_pos ==
14990 state->req_pos && string_pos < 0)
14991 state->text_pos = state->req_end;
14992 else {
14993 length = (Py_ssize_t)node->value_count;
14994
14995 if (string_pos < 0)
14996 string_pos = length;
14997
14998 values = node->values;
14999
15000 /* Try comparing. */
15001 while (string_pos > 0) {
15002 if (state->text_pos <= state->text_start && state->partial_side ==
15003 RE_PARTIAL_LEFT)
15004 return RE_ERROR_PARTIAL;
15005
15006 if (state->text_pos > state->slice_start &&
15007 same_char_ign(encoding, locale_info, char_at(state->text,
15008 state->text_pos - 1), values[string_pos - 1])) {
15009 --string_pos;
15010 --state->text_pos;
15011 } else if (node->status & RE_STATUS_FUZZY) {
15012 status = fuzzy_match_string(state, search, node,
15013 &string_pos, -1);
15014 if (status < 0)
15015 return status;
15016
15017 if (status == RE_ERROR_FAILURE) {
15018 string_pos = -1;
15019 goto backtrack;
15020 }
15021 } else {
15022 string_pos = -1;
15023 goto backtrack;
15024 }
15025 }
15026 }
15027
15028 if (node->status & RE_STATUS_FUZZY) {
15029 status = fuzzy_insert(state, -1, node->next_1.node);
15030 if (status < 0)
15031 return status;
15032 }
15033
15034 string_pos = -1;
15035
15036 /* Successful match. */
15037 node = node->next_1.node;
15038 break;
15039 }
15040 case RE_OP_STRING_REV: /* A string. */
15041 {
15042 Py_ssize_t length;
15043 RE_CODE* values;
15044 TRACE(("%s %zd\n", re_op_text[node->op], node->value_count))
15045
15046 if ((node->status & RE_STATUS_REQUIRED) && state->text_pos ==
15047 state->req_pos && string_pos < 0)
15048 state->text_pos = state->req_end;
15049 else {
15050 length = (Py_ssize_t)node->value_count;
15051
15052 if (string_pos < 0)
15053 string_pos = length;
15054
15055 values = node->values;
15056
15057 /* Try comparing. */
15058 while (string_pos > 0) {
15059 if (state->text_pos <= state->text_start && state->partial_side ==
15060 RE_PARTIAL_LEFT)
15061 return RE_ERROR_PARTIAL;
15062
15063 if (state->text_pos > state->slice_start &&
15064 same_char(char_at(state->text, state->text_pos - 1),
15065 values[string_pos - 1])) {
15066 --string_pos;
15067 --state->text_pos;
15068 } else if (node->status & RE_STATUS_FUZZY) {
15069 status = fuzzy_match_string(state, search, node,
15070 &string_pos, -1);
15071 if (status < 0)
15072 return status;
15073
15074 if (status == RE_ERROR_FAILURE) {
15075 string_pos = -1;
15076 goto backtrack;
15077 }
15078 } else {
15079 string_pos = -1;
15080 goto backtrack;
15081 }
15082 }
15083 }
15084
15085 if (node->status & RE_STATUS_FUZZY) {
15086 status = fuzzy_insert(state, -1, node->next_1.node);
15087 if (status < 0)
15088 return status;
15089 }
15090
15091 string_pos = -1;
15092
15093 /* Successful match. */
15094 node = node->next_1.node;
15095 break;
15096 }
15097 case RE_OP_SUCCESS: /* Success. */
15098 /* Must the match advance past its start? */
15099 TRACE(("%s\n", re_op_text[node->op]))
15100
15101 if (state->text_pos == state->search_anchor && state->must_advance)
15102 goto backtrack;
15103
15104 if (state->match_all) {
15105 /* We want to match all of the slice. */
15106 if (state->reverse) {
15107 if (state->text_pos != state->slice_start)
15108 goto backtrack;
15109 } else {
15110 if (state->text_pos != state->slice_end)
15111 goto backtrack;
15112 }
15113 }
15114
15115 if (state->pattern->flags & RE_FLAG_POSIX) {
15116 /* If we're looking for a POSIX match, check whether this one
15117 * is better and then keep looking.
15118 */
15119 if (!check_posix_match(state))
15120 return RE_ERROR_MEMORY;
15121
15122 goto backtrack;
15123 }
15124
15125 return RE_ERROR_SUCCESS;
15126 default: /* Illegal opcode! */
15127 TRACE(("UNKNOWN OP %d\n", node->op))
15128 return RE_ERROR_ILLEGAL;
15129 }
15130 }
15131
15132 backtrack:
15133 for (;;) {
15134 RE_UINT8 op;
15135 TRACE(("BACKTRACK "))
15136
15137 /* Should we abort the matching? */
15138 state->iterations += 0x100U;
15139
15140 if (state->iterations == 0 && safe_check_cancel(state))
15141 return RE_ERROR_CANCELLED;
15142
15143 if (!pop_uint8(state, &state->bstack, &op))
15144 return RE_ERROR_MEMORY;
15145
15146 switch (op) {
15147 case RE_OP_ANY: /* Any character except a newline. */
15148 case RE_OP_ANY_ALL: /* Any character at all. */
15149 case RE_OP_ANY_ALL_REV: /* Any character at all, backwards. */
15150 case RE_OP_ANY_REV: /* Any character except a newline, backwards. */
15151 case RE_OP_ANY_U: /* Any character except a line separator. */
15152 case RE_OP_ANY_U_REV: /* Any character except a line separator, backwards. */
15153 case RE_OP_CHARACTER: /* A character. */
15154 case RE_OP_CHARACTER_IGN: /* A character, ignoring case. */
15155 case RE_OP_CHARACTER_IGN_REV: /* A character, ignoring case, backwards. */
15156 case RE_OP_CHARACTER_REV: /* A character, backwards. */
15157 case RE_OP_PROPERTY: /* A property. */
15158 case RE_OP_PROPERTY_IGN: /* A property, ignoring case. */
15159 case RE_OP_PROPERTY_IGN_REV: /* A property, ignoring case, backwards. */
15160 case RE_OP_PROPERTY_REV: /* A property, backwards. */
15161 case RE_OP_RANGE: /* A range. */
15162 case RE_OP_RANGE_IGN: /* A range, ignoring case. */
15163 case RE_OP_RANGE_IGN_REV: /* A range, ignoring case, backwards. */
15164 case RE_OP_RANGE_REV: /* A range, backwards. */
15165 case RE_OP_SET_DIFF: /* Set difference. */
15166 case RE_OP_SET_DIFF_IGN: /* Set difference, ignoring case. */
15167 case RE_OP_SET_DIFF_IGN_REV: /* Set difference, ignoring case, backwards. */
15168 case RE_OP_SET_DIFF_REV: /* Set difference, backwards. */
15169 case RE_OP_SET_INTER: /* Set intersection. */
15170 case RE_OP_SET_INTER_IGN: /* Set intersection, ignoring case. */
15171 case RE_OP_SET_INTER_IGN_REV: /* Set intersection, ignoring case, backwards. */
15172 case RE_OP_SET_INTER_REV: /* Set intersection, backwards. */
15173 case RE_OP_SET_SYM_DIFF: /* Set symmetric difference. */
15174 case RE_OP_SET_SYM_DIFF_IGN: /* Set symmetric difference, ignoring case. */
15175 case RE_OP_SET_SYM_DIFF_IGN_REV: /* Set symmetric difference, ignoring case, backwards. */
15176 case RE_OP_SET_SYM_DIFF_REV: /* Set symmetric difference, backwards. */
15177 case RE_OP_SET_UNION: /* Set union. */
15178 case RE_OP_SET_UNION_IGN: /* Set union, ignoring case. */
15179 case RE_OP_SET_UNION_IGN_REV: /* Set union, ignoring case, backwards. */
15180 case RE_OP_SET_UNION_REV: /* Set union, backwards. */
15181 TRACE(("%s\n", re_op_text[op]))
15182
15183 status = retry_fuzzy_match_item(state, op, search, &node, TRUE);
15184 if (status < 0)
15185 return status;
15186
15187 if (status == RE_ERROR_SUCCESS)
15188 goto advance;
15189 break;
15190 case RE_OP_ATOMIC: /* Start of an atomic group. */
15191 TRACE(("%s\n", re_op_text[op]))
15192
15193 /* sstack: ...
15194 *
15195 * bstack: captures fuzzy_counts capture_change sstack
15196 *
15197 * pstack: bstack
15198 */
15199
15200 if (!drop_bstack(state))
15201 return RE_ERROR_MEMORY;
15202 if (!pop_sstack(state))
15203 return RE_ERROR_MEMORY;
15204
15205 /* sstack: -
15206 *
15207 * bstack: captures fuzzy_counts capture_change
15208 *
15209 * pstack: -
15210 */
15211
15212 if (!pop_size(state, &state->bstack, &state->capture_change))
15213 return RE_ERROR_MEMORY;
15214 if (!pop_fuzzy_counts(state, &state->bstack, state->fuzzy_counts))
15215 return RE_ERROR_MEMORY;
15216 if (!pop_captures(state, &state->bstack))
15217 return RE_ERROR_MEMORY;
15218 break;
15219 case RE_OP_BODY_END:
15220 {
15221 RE_BodyEndStateData data_be;
15222 size_t capture_change;
15223 RE_CODE index;
15224 Py_ssize_t start;
15225 size_t count;
15226 RE_RepeatData* rp_data;
15227
15228 /* bstack: count start capture_change index */
15229
15230 if (!ByteStack_pop_block(state, &state->bstack, (void*)&data_be,
15231 sizeof(data_be)))
15232 return RE_ERROR_MEMORY;
15233
15234 index = data_be.index;
15235 capture_change = data_be.capture_change;
15236 start = data_be.start;
15237 count = data_be.count;
15238 TRACE(("%s %u\n", re_op_text[op], (unsigned int)index))
15239
15240 /* We're backtracking into the body. */
15241 rp_data = &state->repeats[index];
15242
15243 /* Restore the repeat info. */
15244 rp_data->count = count;
15245 rp_data->start = start;
15246 rp_data->capture_change = capture_change;
15247 break;
15248 }
15249 case RE_OP_BODY_START:
15250 {
15251 Py_ssize_t text_pos;
15252 RE_CODE index;
15253
15254 /* bstack: index text_pos */
15255
15256 if (!pop_ssize(state, &state->bstack, &text_pos))
15257 return RE_ERROR_MEMORY;
15258 if (!pop_code(state, &state->bstack, &index))
15259 return RE_ERROR_MEMORY;
15260 TRACE(("%s %u\n", re_op_text[op], (unsigned int)index))
15261
15262 /* The body may have failed to match at this position. */
15263 if (!guard_repeat(state, index, text_pos, RE_STATUS_BODY, TRUE))
15264 return RE_ERROR_MEMORY;
15265 break;
15266 }
15267 case RE_OP_BOUNDARY: /* At a word boundary. */
15268 case RE_OP_DEFAULT_BOUNDARY: /* At a default word boundary. */
15269 case RE_OP_DEFAULT_END_OF_WORD: /* At the default end of a word. */
15270 case RE_OP_DEFAULT_START_OF_WORD: /* At the default start of a word. */
15271 case RE_OP_END_OF_LINE: /* At the end of a line. */
15272 case RE_OP_END_OF_LINE_U: /* At the end of a line. */
15273 case RE_OP_END_OF_STRING: /* At the end of the string. */
15274 case RE_OP_END_OF_STRING_LINE: /* At the end of string or final newline. */
15275 case RE_OP_END_OF_STRING_LINE_U: /* At the end of string or final newline. */
15276 case RE_OP_END_OF_WORD: /* At the end of a word. */
15277 case RE_OP_GRAPHEME_BOUNDARY: /* On a grapheme boundary. */
15278 case RE_OP_START_OF_LINE: /* At the start of a line. */
15279 case RE_OP_START_OF_LINE_U: /* At the start of a line. */
15280 case RE_OP_START_OF_STRING: /* At the start of the string. */
15281 case RE_OP_START_OF_WORD: /* At the start of a word. */
15282 TRACE(("%s\n", re_op_text[op]))
15283
15284 status = retry_fuzzy_match_item(state, op, search, &node, FALSE);
15285 if (status < 0)
15286 return status;
15287
15288 if (status == RE_ERROR_SUCCESS)
15289 goto advance;
15290 break;
15291 case RE_OP_BRANCH: /* 2-way branch. */
15292 TRACE(("%s\n", re_op_text[op]))
15293
15294 /* sstack: -
15295 *
15296 * bstack: text_pos node
15297 */
15298
15299 if (!pop_pointer(state, &state->bstack, (void*)&node))
15300 return RE_ERROR_MEMORY;
15301 if (!pop_ssize(state, &state->bstack, &state->text_pos))
15302 return RE_ERROR_MEMORY;
15303 goto advance;
15304 case RE_OP_CALL_REF: /* A group call ref. */
15305 TRACE(("%s\n", re_op_text[op]))
15306
15307 /* sstack: NULL
15308 *
15309 * bstack: -
15310 */
15311
15312 if (!drop_pointer(state, &state->sstack))
15313 return RE_ERROR_MEMORY;
15314 break;
15315 case RE_OP_CONDITIONAL: /* Conditional subpattern. */
15316 {
15317 RE_Node* conditional;
15318 RE_LookaroundStateData data_l;
15319 TRACE(("%s\n", re_op_text[op]))
15320
15321 /* sstack: node slice_start slice_end text_pos ...
15322 *
15323 * bstack: captures repeats fuzzy_counts capture_change sstack
15324 *
15325 * pstack: bstack
15326 */
15327
15328 if (!drop_bstack(state))
15329 return RE_ERROR_MEMORY;
15330 if (!pop_sstack(state))
15331 return RE_ERROR_MEMORY;
15332
15333 /* sstack: node slice_start slice_end text_pos
15334 *
15335 * bstack: captures repeats fuzzy_counts capture_change
15336 *
15337 * pstack: -
15338 */
15339
15340 if (!ByteStack_pop_block(state, &state->sstack, (void*)&data_l,
15341 sizeof(data_l)))
15342 return RE_ERROR_MEMORY;
15343
15344 state->text_pos = data_l.text_pos;
15345 state->slice_end = data_l.slice_end;
15346 state->slice_start = data_l.slice_start;
15347 conditional = data_l.node;
15348
15349 /* sstack: -
15350 *
15351 * bstack: captures repeats fuzzy_counts capture_change
15352 *
15353 * pstack: -
15354 */
15355
15356 if (!pop_size(state, &state->bstack, &state->capture_change))
15357 return RE_ERROR_MEMORY;
15358 if (!pop_fuzzy_counts(state, &state->bstack, state->fuzzy_counts))
15359 return RE_ERROR_MEMORY;
15360 if (!pop_repeats(state, &state->bstack))
15361 return RE_ERROR_MEMORY;
15362 if (!pop_captures(state, &state->bstack))
15363 return RE_ERROR_MEMORY;
15364
15365 /* sstack: -
15366 *
15367 * bstack: -
15368 *
15369 * pstack: -
15370 */
15371
15372 if (conditional->match)
15373 /* It's a positive conditional that's failed. Go to the 'false'
15374 * 'false' branch.
15375 */
15376 node = conditional->nonstring.next_2.node;
15377 else
15378 /* It's a negative lookaround that's failed. Go to the 'true'
15379 * branch.
15380 */
15381 node = conditional->nonstring.true_node;
15382
15383 goto advance;
15384 }
15385 case RE_OP_END_ATOMIC: /* End of an atomic group. */
15386 TRACE(("%s\n", re_op_text[op]))
15387
15388 /* bstack: captures fuzzy_counts capture_change */
15389
15390 if (!pop_size(state, &state->bstack, &state->capture_change))
15391 return RE_ERROR_MEMORY;
15392 if (!pop_fuzzy_counts(state, &state->bstack, state->fuzzy_counts))
15393 return RE_ERROR_MEMORY;
15394 if (!pop_captures(state, &state->bstack))
15395 return RE_ERROR_MEMORY;
15396 break;
15397 case RE_OP_END_CONDITIONAL: /* End of a conditional subpattern. */
15398 {
15399 TRACE(("%s\n", re_op_text[op]))
15400
15401 /* sstack: -
15402 *
15403 * bstack: captures repeats fuzzy_counts capture_change
15404 *
15405 * pstack: -
15406 */
15407
15408 if (!pop_size(state, &state->bstack, &state->capture_change))
15409 return RE_ERROR_MEMORY;
15410 if (!pop_fuzzy_counts(state, &state->bstack, state->fuzzy_counts))
15411 return RE_ERROR_MEMORY;
15412 if (!pop_repeats(state, &state->bstack))
15413 return RE_ERROR_MEMORY;
15414 if (!pop_captures(state, &state->bstack))
15415 return RE_ERROR_MEMORY;
15416
15417 /* sstack: -
15418 *
15419 * bstack: -
15420 *
15421 * pstack: -
15422 */
15423 break;
15424 }
15425 case RE_OP_END_FUZZY: /* End of fuzzy matching. */
15426 {
15427 RE_Node* inner_node;
15428 size_t inner_counts[RE_FUZZY_COUNT];
15429 size_t insertions;
15430 TRACE(("%s\n", re_op_text[op]))
15431
15432 /* sstack: -
15433 *
15434 * bstack: inner_counts inner_node text_pos end_fuzzy_node
15435 */
15436
15437 if (!pop_pointer(state, &state->bstack, (void*)&node))
15438 return RE_ERROR_MEMORY;
15439 if (!pop_ssize(state, &state->bstack, &state->text_pos))
15440 return RE_ERROR_MEMORY;
15441 if (!pop_pointer(state, &state->bstack, (void*)&inner_node))
15442 return RE_ERROR_MEMORY;
15443 if (!pop_size(state, &state->bstack, &insertions))
15444 return RE_ERROR_MEMORY;
15445 if (!pop_fuzzy_counts(state, &state->bstack, inner_counts))
15446 return RE_ERROR_MEMORY;
15447
15448 /* sstack: -
15449 *
15450 * bstack: -
15451 */
15452
15453 if (insertion_permitted(state, inner_node, inner_counts) &&
15454 total_errors(state->fuzzy_counts) + total_errors(inner_counts) <
15455 state->max_errors && fuzzy_ext_match(state, inner_node,
15456 state->text_pos)) {
15457 RE_INT8 step;
15458 Py_ssize_t limit;
15459
15460 /* Try another insertion. */
15461 if (inner_node->status & RE_STATUS_REVERSE) {
15462 step = -1;
15463 limit = state->slice_start;
15464 } else {
15465 step = 1;
15466 limit = state->slice_end;
15467 }
15468
15469 if (state->text_pos != limit) {
15470 if (!record_fuzzy(state, RE_FUZZY_INS, state->text_pos))
15471 return RE_ERROR_MEMORY;
15472 ++inner_counts[RE_FUZZY_INS];
15473
15474 state->text_pos += step;
15475
15476 /* Save the inner fuzzy info. */
15477 if (!push_fuzzy_counts(state, &state->bstack,
15478 inner_counts))
15479 return RE_ERROR_MEMORY;
15480 if (!push_size(state, &state->bstack, insertions + 1))
15481 return RE_ERROR_MEMORY;
15482 if (!push_pointer(state, &state->bstack, inner_node))
15483 return RE_ERROR_MEMORY;
15484 if (!push_ssize(state, &state->bstack, state->text_pos))
15485 return RE_ERROR_MEMORY;
15486 if (!push_pointer(state, &state->bstack, node))
15487 return RE_ERROR_MEMORY;
15488 if (!push_uint8(state, &state->bstack, RE_OP_END_FUZZY))
15489 return RE_ERROR_MEMORY;
15490
15491 /* sstack: -
15492 *
15493 * bstack: inner_counts inner_node text_pos end_fuzzy_node
15494 * END_FUZZY
15495 */
15496
15497 ++state->fuzzy_counts[RE_FUZZY_INS];
15498 state->total_errors = total_errors(state->fuzzy_counts);
15499
15500 node = node->next_1.node;
15501 goto advance;
15502 }
15503 }
15504
15505 /* Subtract the inner counts from the outer counts. */
15506 state->fuzzy_counts[RE_FUZZY_SUB] -= inner_counts[RE_FUZZY_SUB];
15507 state->fuzzy_counts[RE_FUZZY_INS] -= inner_counts[RE_FUZZY_INS];
15508 state->fuzzy_counts[RE_FUZZY_DEL] -= inner_counts[RE_FUZZY_DEL];
15509
15510 /* Save the outer fuzzy info. */
15511 if (!push_fuzzy_counts(state, &state->sstack, state->fuzzy_counts))
15512 return RE_ERROR_MEMORY;
15513 if (!push_pointer(state, &state->sstack, state->fuzzy_node))
15514 return RE_ERROR_MEMORY;
15515
15516 /* sstack: outer_counts outer_node
15517 *
15518 * bstack: -
15519 */
15520
15521 inner_counts[RE_FUZZY_INS] -= insertions;
15522 while (insertions > 0) {
15523 unrecord_fuzzy(state);
15524 --insertions;
15525 }
15526
15527 /* Restore the inner fuzzy info. */
15528 Py_MEMCPY(state->fuzzy_counts, inner_counts,
15529 sizeof(state->fuzzy_counts));
15530 state->fuzzy_node = inner_node;
15531 break;
15532 }
15533 case RE_OP_END_GROUP: /* End of a capture group. */
15534 {
15535 BOOL capture;
15536 TRACE(("%s\n", re_op_text[op]))
15537
15538 /* If capturing:
15539 *
15540 * sstack: -
15541 *
15542 * bstack: start current capture_change private_index public_index
15543 * TRUE
15544 *
15545 * else:
15546 *
15547 * sstack: end
15548 *
15549 * bstack: FALSE
15550 */
15551
15552 if (!pop_bool(state, &state->bstack, &capture))
15553 return RE_ERROR_MEMORY;
15554
15555 if (capture) {
15556 RE_GroupStateData data_g;
15557 RE_CODE public_index;
15558 RE_CODE private_index;
15559 Py_ssize_t start;
15560 RE_GroupData* group;
15561
15562 if (!ByteStack_pop_block(state, &state->bstack, (void*)&data_g,
15563 sizeof(data_g)))
15564 return RE_ERROR_MEMORY;
15565
15566 public_index = data_g.public_index;
15567 private_index = data_g.private_index;
15568 state->capture_change = data_g.capture_change;
15569 group = &state->groups[private_index - 1];
15570 group->current = data_g.current;
15571 start = data_g.text_pos;
15572 if (!push_ssize(state, &state->sstack, start))
15573 return RE_ERROR_MEMORY;
15574
15575 unsave_capture(state, private_index, public_index);
15576
15577 /* sstack: start
15578 *
15579 * bstack: -
15580 */
15581 } else {
15582 if (!drop_ssize(state, &state->sstack))
15583 return RE_ERROR_MEMORY;
15584 }
15585 break;
15586 }
15587 case RE_OP_END_LOOKAROUND: /* End of a lookaround subpattern. */
15588 {
15589 BOOL has_groups;
15590 TRACE(("%s\n", re_op_text[op]))
15591
15592 /* sstack: -
15593 *
15594 * bstack: [captures TRUE | FALSE] fuzzy_counts capture_change
15595 *
15596 * pstack: -
15597 */
15598
15599 if (!pop_size(state, &state->bstack, &state->capture_change))
15600 return RE_ERROR_MEMORY;
15601 if (!pop_fuzzy_counts(state, &state->bstack, state->fuzzy_counts))
15602 return RE_ERROR_MEMORY;
15603 if (!pop_bool(state, &state->bstack, &has_groups))
15604 return RE_ERROR_MEMORY;
15605 if (has_groups) {
15606 if (!pop_captures(state, &state->bstack))
15607 return RE_ERROR_MEMORY;
15608 }
15609
15610 /* sstack: -
15611 *
15612 * bstack: -
15613 *
15614 * pstack: -
15615 */
15616 break;
15617 }
15618 case RE_OP_FAILURE: /* Failure. */
15619 TRACE(("%s\n", re_op_text[op]))
15620
15621 /* Have we been looking for a POSIX match? */
15622 if (state->found_match) {
15623 restore_best_match(state);
15624 return RE_OP_SUCCESS;
15625 }
15626
15627 /* Do we have to advance? */
15628 if (!search)
15629 return RE_ERROR_FAILURE;
15630
15631 /* Can we advance? */
15632 state->text_pos = state->match_pos;
15633
15634 if (state->reverse) {
15635 if (state->text_pos <= state->slice_start)
15636 return RE_ERROR_FAILURE;
15637 } else {
15638 if (state->text_pos >= state->slice_end)
15639 return RE_ERROR_FAILURE;
15640 }
15641
15642 /* Skip over any repeated leading characters. */
15643 switch (start_node->op) {
15644 case RE_OP_GREEDY_REPEAT_ONE:
15645 case RE_OP_LAZY_REPEAT_ONE:
15646 {
15647 size_t count;
15648 BOOL is_partial;
15649
15650 /* How many characters did the repeat actually match? */
15651 count = count_one(state, start_node->nonstring.next_2.node,
15652 state->text_pos, start_node->values[2], &is_partial);
15653
15654 /* If it's fewer than the maximum then skip over those
15655 * characters.
15656 */
15657 if (count < start_node->values[2])
15658 state->text_pos += (Py_ssize_t)count * pattern_step;
15659 break;
15660 }
15661 }
15662
15663 /* Advance and try to match again. We also need to check whether we
15664 * need to skip.
15665 */
15666 if (state->reverse) {
15667 if (state->text_pos > state->slice_end)
15668 state->text_pos = state->slice_end;
15669 else
15670 --state->text_pos;
15671 } else {
15672 if (state->text_pos < state->slice_start)
15673 state->text_pos = state->slice_start;
15674 else
15675 ++state->text_pos;
15676 }
15677
15678 /* Clear the groups. */
15679 clear_groups(state);
15680
15681 /* Reset the guards. */
15682 reset_guards(state);
15683
15684 /* Reset the stacks. */
15685 ByteStack_reset(state, &state->sstack);
15686 ByteStack_reset(state, &state->bstack);
15687 ByteStack_reset(state, &state->pstack);
15688 goto start_match;
15689 case RE_OP_FUZZY: /* Fuzzy matching. */
15690 TRACE(("%s\n", re_op_text[op]))
15691
15692 /* sstack: outer_counts outer_node
15693 *
15694 * bstack: -
15695 */
15696
15697 /* Restore the outer fuzzy info. */
15698 if (!pop_pointer(state, &state->sstack, (void*)&state->fuzzy_node))
15699 return RE_ERROR_MEMORY;
15700 if (!pop_fuzzy_counts(state, &state->sstack, state->fuzzy_counts))
15701 return RE_ERROR_MEMORY;
15702 break;
15703 case RE_OP_FUZZY_INSERT:
15704 TRACE(("%s\n", re_op_text[op]))
15705
15706 status = retry_fuzzy_insert(state, &node);
15707 if (status < 0)
15708 return status;
15709
15710 if (status == RE_ERROR_SUCCESS)
15711 goto advance;
15712
15713 string_pos = -1;
15714 break;
15715 case RE_OP_GREEDY_REPEAT: /* Greedy repeat. */
15716 case RE_OP_LAZY_REPEAT: /* Lazy repeat. */
15717 {
15718 RE_RepeatStateData data_r;
15719 Py_ssize_t text_pos;
15720 RE_CODE index;
15721 size_t capture_change;
15722 Py_ssize_t start;
15723 size_t count;
15724 RE_RepeatData* rp_data;
15725 TRACE(("%s\n", re_op_text[op]))
15726
15727 /* bstack: count start capture_change index text_pos */
15728
15729 if (!ByteStack_pop_block(state, &state->bstack, (void*)&data_r,
15730 sizeof(data_r)))
15731 return RE_ERROR_MEMORY;
15732
15733 text_pos = data_r.text_pos;
15734 index = data_r.index;
15735 capture_change = data_r.capture_change;
15736 start = data_r.start;
15737 count = data_r.count;
15738
15739 /* The repeat failed to match. */
15740 rp_data = &state->repeats[index];
15741
15742 /* The body may have failed to match at this position. */
15743 if (!guard_repeat(state, index, text_pos, RE_STATUS_BODY, TRUE))
15744 return RE_ERROR_MEMORY;
15745
15746 /* Restore the previous repeat. */
15747 rp_data->count = count;
15748 rp_data->start = start;
15749 rp_data->capture_change = capture_change;
15750 break;
15751 }
15752 case RE_OP_GREEDY_REPEAT_ONE: /* Greedy repeat for one character. */
15753 {
15754 RE_RepeatOneStateData data_ro;
15755 RE_CODE index;
15756 Py_ssize_t start;
15757 size_t saved_count;
15758 RE_RepeatData* rp_data;
15759 size_t count;
15760 Py_ssize_t step;
15761 Py_ssize_t pos;
15762 Py_ssize_t limit;
15763 RE_Node* test;
15764 BOOL match;
15765 BOOL m;
15766 TRACE(("%s\n", re_op_text[op]))
15767
15768 /* bstack: count start node index */
15769
15770 if (!ByteStack_pop_block(state, &state->bstack,
15771 (void*)&data_ro,sizeof(data_ro)))
15772 return RE_ERROR_MEMORY;
15773
15774 index = data_ro.index;
15775 node = data_ro.node;
15776 start = data_ro.start;
15777 saved_count = data_ro.count;
15778
15779 rp_data = &state->repeats[index];
15780
15781 /* Unmatch one character at a time until the tail could match or we
15782 * have reached the minimum.
15783 */
15784 state->text_pos = rp_data->start;
15785
15786 count = rp_data->count;
15787 step = node->nonstring.next_2.test->step;
15788 pos = state->text_pos + (Py_ssize_t)count * step;
15789 limit = state->text_pos + (Py_ssize_t)node->values[1] * step;
15790
15791 /* The tail failed to match at this position. */
15792 if (!guard_repeat(state, index, pos, RE_STATUS_TAIL, TRUE))
15793 return RE_ERROR_MEMORY;
15794
15795 /* A (*SKIP) might have changed the size of the slice. */
15796 if (step > 0) {
15797 if (limit < state->slice_start)
15798 limit = state->slice_start;
15799 } else {
15800 if (limit > state->slice_end)
15801 limit = state->slice_end;
15802 }
15803
15804 if (pos == limit) {
15805 /* We've backtracked the repeat as far as we can. */
15806 rp_data->start = start;
15807 rp_data->count = saved_count;
15808 break;
15809 }
15810
15811 test = node->next_1.test;
15812
15813 m = test->match;
15814 index = node->values[0];
15815
15816 match = FALSE;
15817
15818 if (test->status & RE_STATUS_FUZZY) {
15819 for (;;) {
15820 RE_Position next_position;
15821
15822 pos -= step;
15823
15824 status = try_match(state, &node->next_1, pos,
15825 &next_position);
15826 if (status < 0)
15827 return status;
15828
15829 if (status != RE_ERROR_FAILURE && !is_repeat_guarded(state,
15830 index, pos, RE_STATUS_TAIL)) {
15831 match = TRUE;
15832 break;
15833 }
15834
15835 if (pos == limit)
15836 break;
15837 }
15838 } else {
15839 /* A repeated single-character match is often followed by a
15840 * literal, so checking specially for it can be a good
15841 * optimisation when working with long strings.
15842 */
15843 switch (test->op) {
15844 case RE_OP_CHARACTER:
15845 {
15846 Py_UCS4 ch;
15847
15848 ch = test->values[0];
15849
15850 for (;;) {
15851 --pos;
15852
15853 if (same_char(char_at(state->text, pos), ch) == m &&
15854 !is_repeat_guarded(state, index, pos,
15855 RE_STATUS_TAIL)) {
15856 match = TRUE;
15857 break;
15858 }
15859
15860 if (pos == limit)
15861 break;
15862 }
15863 break;
15864 }
15865 case RE_OP_CHARACTER_IGN:
15866 {
15867 Py_UCS4 ch;
15868
15869 ch = test->values[0];
15870
15871 for (;;) {
15872 --pos;
15873
15874 if (same_char_ign(encoding, locale_info,
15875 char_at(state->text, pos), ch) == m &&
15876 !is_repeat_guarded(state, index, pos,
15877 RE_STATUS_TAIL)) {
15878 match = TRUE;
15879 break;
15880 }
15881
15882 if (pos == limit)
15883 break;
15884 }
15885 break;
15886 }
15887 case RE_OP_CHARACTER_IGN_REV:
15888 {
15889 Py_UCS4 ch;
15890
15891 ch = test->values[0];
15892
15893 for (;;) {
15894 ++pos;
15895
15896 if (same_char_ign(encoding, locale_info,
15897 char_at(state->text, pos - 1), ch) == m &&
15898 !is_repeat_guarded(state, index, pos,
15899 RE_STATUS_TAIL)) {
15900 match = TRUE;
15901 break;
15902 }
15903
15904 if (pos == limit)
15905 break;
15906 }
15907 break;
15908 }
15909 case RE_OP_CHARACTER_REV:
15910 {
15911 Py_UCS4 ch;
15912
15913 ch = test->values[0];
15914
15915 for (;;) {
15916 ++pos;
15917
15918 if (same_char(char_at(state->text, pos - 1), ch) == m
15919 && !is_repeat_guarded(state, index, pos,
15920 RE_STATUS_TAIL)) {
15921 match = TRUE;
15922 break;
15923 }
15924
15925 if (pos == limit)
15926 break;
15927 }
15928 break;
15929 }
15930 case RE_OP_STRING:
15931 {
15932 Py_ssize_t length;
15933
15934 length = (Py_ssize_t)test->value_count;
15935
15936 --pos;
15937
15938 /* Is it a partial match? */
15939 if (pos >= limit && pos > state->slice_end - length &&
15940 state->partial_side == RE_PARTIAL_RIGHT) {
15941 do {
15942 if (partial_string_match(state, test, pos))
15943 return RE_ERROR_PARTIAL;
15944
15945 --pos;
15946 } while (pos >= limit && pos > state->slice_end -
15947 length && state->partial_side == RE_PARTIAL_RIGHT);
15948 }
15949
15950 /* The tail is a string. We don't want to go off the end of
15951 * the slice.
15952 */
15953 pos = min_ssize_t(pos, state->slice_end - length);
15954
15955 for (;;) {
15956 Py_ssize_t found;
15957 BOOL is_partial;
15958
15959 if (pos < limit)
15960 break;
15961
15962 found = string_search_rev(state, test, pos + length,
15963 limit, FALSE, &is_partial);
15964 if (is_partial)
15965 return RE_ERROR_PARTIAL;
15966
15967 if (found < 0)
15968 break;
15969
15970 pos = found - length;
15971
15972 if (!is_repeat_guarded(state, index, pos,
15973 RE_STATUS_TAIL)) {
15974 match = TRUE;
15975 break;
15976 }
15977
15978 --pos;
15979 }
15980 break;
15981 }
15982 case RE_OP_STRING_FLD:
15983 {
15984 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4
15985 ch, Py_UCS4* folded);
15986 Py_ssize_t folded_length;
15987 size_t i;
15988 Py_UCS4 folded[RE_MAX_FOLDED];
15989
15990 full_case_fold = encoding->full_case_fold;
15991
15992 folded_length = 0;
15993 for (i = 0; i < test->value_count; i++)
15994 folded_length += full_case_fold(locale_info,
15995 test->values[i], folded);
15996
15997 /* The tail is a string. We don't want to go off the end of
15998 * the slice.
15999 */
16000 pos = min_ssize_t(pos - 1, state->slice_end -
16001 folded_length);
16002
16003 for (;;) {
16004 Py_ssize_t found;
16005 Py_ssize_t new_pos;
16006 BOOL is_partial;
16007
16008 if (pos < limit)
16009 break;
16010
16011 found = string_search_fld_rev(state, test, pos +
16012 folded_length, limit, &new_pos, &is_partial);
16013 if (is_partial)
16014 return RE_ERROR_PARTIAL;
16015
16016 if (found < 0)
16017 break;
16018
16019 pos = found - folded_length;
16020
16021 if (!is_repeat_guarded(state, index, pos,
16022 RE_STATUS_TAIL)) {
16023 match = TRUE;
16024 break;
16025 }
16026
16027 --pos;
16028 }
16029 break;
16030 }
16031 case RE_OP_STRING_FLD_REV:
16032 {
16033 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4
16034 ch, Py_UCS4* folded);
16035 Py_ssize_t folded_length;
16036 size_t i;
16037 Py_UCS4 folded[RE_MAX_FOLDED];
16038
16039 full_case_fold = encoding->full_case_fold;
16040
16041 folded_length = 0;
16042 for (i = 0; i < test->value_count; i++)
16043 folded_length += full_case_fold(locale_info,
16044 test->values[i], folded);
16045
16046 /* The tail is a string. We don't want to go off the end of
16047 * the slice.
16048 */
16049 pos = max_ssize_t(pos + 1, state->slice_start +
16050 folded_length);
16051
16052 for (;;) {
16053 Py_ssize_t found;
16054 Py_ssize_t new_pos;
16055 BOOL is_partial;
16056
16057 if (pos > limit)
16058 break;
16059
16060 found = string_search_fld(state, test, pos -
16061 folded_length, limit, &new_pos, &is_partial);
16062 if (is_partial)
16063 return RE_ERROR_PARTIAL;
16064
16065 if (found < 0)
16066 break;
16067
16068 pos = found + folded_length;
16069
16070 if (!is_repeat_guarded(state, index, pos,
16071 RE_STATUS_TAIL)) {
16072 match = TRUE;
16073 break;
16074 }
16075
16076 ++pos;
16077 }
16078 break;
16079 }
16080 case RE_OP_STRING_IGN:
16081 {
16082 Py_ssize_t length;
16083
16084 length = (Py_ssize_t)test->value_count;
16085
16086 --pos;
16087
16088 /* Is it a partial match? */
16089 if (pos >= limit && pos > state->slice_end - length &&
16090 state->partial_side == RE_PARTIAL_RIGHT) {
16091 do {
16092 if (partial_string_match_ign(state, test, pos))
16093 return RE_ERROR_PARTIAL;
16094
16095 --pos;
16096 } while (pos >= limit && pos > state->slice_end -
16097 length && state->partial_side == RE_PARTIAL_RIGHT);
16098 }
16099
16100 /* The tail is a string. We don't want to go off the end of
16101 * the slice.
16102 */
16103 pos = min_ssize_t(pos, state->slice_end - length);
16104
16105 for (;;) {
16106 Py_ssize_t found;
16107 BOOL is_partial;
16108
16109 if (pos < limit)
16110 break;
16111
16112 found = string_search_ign_rev(state, test, pos +
16113 length, limit, FALSE, &is_partial);
16114 if (is_partial)
16115 return RE_ERROR_PARTIAL;
16116
16117 if (found < 0)
16118 break;
16119
16120 pos = found - length;
16121
16122 if (!is_repeat_guarded(state, index, pos,
16123 RE_STATUS_TAIL)) {
16124 match = TRUE;
16125 break;
16126 }
16127
16128 --pos;
16129 }
16130 break;
16131 }
16132 case RE_OP_STRING_IGN_REV:
16133 {
16134 Py_ssize_t length;
16135
16136 length = (Py_ssize_t)test->value_count;
16137
16138 /* The tail is a string. We don't want to go off the end of
16139 * the slice.
16140 */
16141 pos = max_ssize_t(pos + 1, state->slice_start + length);
16142
16143 for (;;) {
16144 Py_ssize_t found;
16145 BOOL is_partial;
16146
16147 if (pos > limit)
16148 break;
16149
16150 found = string_search_ign(state, test, pos - length,
16151 limit, FALSE, &is_partial);
16152 if (is_partial)
16153 return RE_ERROR_PARTIAL;
16154
16155 if (found < 0)
16156 break;
16157
16158 pos = found + length;
16159
16160 if (!is_repeat_guarded(state, index, pos,
16161 RE_STATUS_TAIL)) {
16162 match = TRUE;
16163 break;
16164 }
16165
16166 ++pos;
16167 }
16168 break;
16169 }
16170 case RE_OP_STRING_REV:
16171 {
16172 Py_ssize_t length;
16173
16174 length = (Py_ssize_t)test->value_count;
16175
16176 /* The tail is a string. We don't want to go off the end of
16177 * the slice.
16178 */
16179 pos = max_ssize_t(pos + 1, state->slice_start + length);
16180
16181 for (;;) {
16182 Py_ssize_t found;
16183 BOOL is_partial;
16184
16185 if (pos > limit)
16186 break;
16187
16188 found = string_search(state, test, pos - length, limit,
16189 FALSE, &is_partial);
16190 if (is_partial)
16191 return RE_ERROR_PARTIAL;
16192
16193 if (found < 0)
16194 break;
16195
16196 pos = found + length;
16197
16198 if (!is_repeat_guarded(state, index, pos,
16199 RE_STATUS_TAIL)) {
16200 match = TRUE;
16201 break;
16202 }
16203
16204 ++pos;
16205 }
16206 break;
16207 }
16208 default:
16209 for (;;) {
16210 RE_Position next_position;
16211
16212 pos -= step;
16213
16214 status = try_match(state, &node->next_1, pos,
16215 &next_position);
16216 if (status < 0)
16217 return status;
16218
16219 if (status == RE_ERROR_SUCCESS &&
16220 !is_repeat_guarded(state, index, pos,
16221 RE_STATUS_TAIL)) {
16222 match = TRUE;
16223 break;
16224 }
16225
16226 if (pos == limit)
16227 break;
16228 }
16229 break;
16230 }
16231 }
16232
16233 if (match) {
16234 count = (size_t)abs_ssize_t(pos - state->text_pos);
16235
16236 /* The tail could match. */
16237 if (count > node->values[1]) {
16238 /* The match is longer than the minimum, so we might need
16239 * to backtrack the repeat again to consume less.
16240 */
16241 RE_RepeatOneStateData data_ro;
16242
16243 rp_data->count = count;
16244
16245 data_ro.count = saved_count;
16246 data_ro.start = start;
16247 data_ro.node = node;
16248 data_ro.index = index;
16249
16250 if (!ByteStack_push_block(state, &state->bstack,
16251 (void*)&data_ro, sizeof(data_ro)))
16252 return RE_ERROR_MEMORY;
16253 if (!push_uint8(state, &state->bstack,
16254 RE_OP_GREEDY_REPEAT_ONE))
16255 return RE_ERROR_MEMORY;
16256
16257 /* bstack: count start node index GREEDY_REPEAT_ONE */
16258 } else {
16259 /* We've reached or passed the minimum, so we won't need to
16260 * backtrack the repeat again.
16261 */
16262 rp_data->start = start;
16263 rp_data->count = saved_count;
16264
16265 /* Have we passed the minimum? */
16266 if (count < node->values[1])
16267 goto backtrack;
16268 }
16269
16270 node = node->next_1.node;
16271 state->text_pos = pos;
16272 goto advance;
16273 } else {
16274 /* Don't try this repeated match again. */
16275 if (step > 0) {
16276 if (!guard_repeat_range(state, index, limit, pos,
16277 RE_STATUS_BODY, TRUE))
16278 return RE_ERROR_MEMORY;
16279 } else if (step < 0) {
16280 if (!guard_repeat_range(state, index, pos, limit,
16281 RE_STATUS_BODY, TRUE))
16282 return RE_ERROR_MEMORY;
16283 }
16284
16285 /* We've backtracked the repeat as far as we can. */
16286 rp_data->start = start;
16287 rp_data->count = saved_count;
16288 }
16289 break;
16290 }
16291 case RE_OP_GROUP_CALL: /* Group call. */
16292 {
16293 TRACE(("%s\n", re_op_text[op]))
16294
16295 /* sstack: caller_groups caller_repeats capture_change return_node
16296 *
16297 * bstack: -
16298 */
16299
16300 if (!drop_pointer(state, &state->sstack))
16301 return RE_ERROR_MEMORY;
16302
16303 /* For the caller. */
16304 if (!pop_size(state, &state->sstack, &state->capture_change))
16305 return RE_ERROR_MEMORY;
16306 if (!pop_repeats(state, &state->sstack))
16307 return RE_ERROR_MEMORY;
16308 if (!pop_groups(state, &state->sstack))
16309 return RE_ERROR_MEMORY;
16310 break;
16311 }
16312 case RE_OP_GROUP_RETURN: /* Group return. */
16313 {
16314 RE_Node* return_node;
16315 TRACE(("%s\n", re_op_text[op]))
16316
16317 /* If called:
16318 *
16319 * sstack: -
16320 *
16321 * bstack: callee_groups callee_repeats capture_change return_node
16322 *
16323 * else:
16324 *
16325 * sstack: -
16326 *
16327 * bstack: NULL
16328 */
16329
16330 if (!pop_pointer(state, &state->bstack, (void*)&return_node))
16331 return RE_ERROR_MEMORY;
16332
16333 if (return_node) {
16334 /* For the caller. */
16335 if (!push_groups(state, &state->sstack))
16336 return RE_ERROR_MEMORY;
16337 if (!push_repeats(state, &state->sstack))
16338 return RE_ERROR_MEMORY;
16339 if (!push_size(state, &state->sstack, state->capture_change))
16340 return RE_ERROR_MEMORY;
16341 if (!push_pointer(state, &state->sstack, return_node))
16342 return RE_ERROR_MEMORY;
16343
16344 /* sstack: caller_groups caller_repeats capture_change
16345 * return_node
16346 *
16347 * bstack: callee_groups callee_repeats capture_change
16348 */
16349
16350 /* For the callee. */
16351 if (!pop_size(state, &state->bstack, &state->capture_change))
16352 return RE_ERROR_MEMORY;
16353 if (!pop_repeats(state, &state->bstack))
16354 return RE_ERROR_MEMORY;
16355 if (!pop_groups(state, &state->bstack))
16356 return RE_ERROR_MEMORY;
16357 } else {
16358 if (!push_pointer(state, &state->sstack, NULL))
16359 return RE_ERROR_MEMORY;
16360 }
16361
16362 /* If called:
16363 *
16364 * sstack: caller_groups caller_repeats capture_change return_node
16365 *
16366 * bstack: -
16367 *
16368 * else:
16369 *
16370 * sstack: NULL
16371 *
16372 * bstack: -
16373 */
16374 break;
16375 }
16376 case RE_OP_KEEP: /* Keep. */
16377 /* bstack: match_pos */
16378
16379 if (!pop_ssize(state, &state->bstack, &state->match_pos))
16380 return RE_ERROR_MEMORY;
16381 break;
16382 case RE_OP_LAZY_REPEAT_ONE: /* Lazy repeat for one character. */
16383 {
16384 RE_RepeatOneStateData data;
16385 RE_CODE index;
16386 Py_ssize_t start;
16387 size_t saved_count;
16388 RE_RepeatData* rp_data;
16389 size_t count;
16390 Py_ssize_t step;
16391 Py_ssize_t pos;
16392 Py_ssize_t available;
16393 size_t max_count;
16394 Py_ssize_t limit;
16395 RE_Node* repeated;
16396 RE_Node* test;
16397 BOOL match;
16398 Py_ssize_t skip_pos;
16399 BOOL m;
16400 TRACE(("%s\n", re_op_text[op]))
16401
16402 /* bstack: count start node index */
16403
16404 if (!ByteStack_pop_block(state, &state->bstack, (void*)&data,
16405 sizeof(data)))
16406 return RE_ERROR_MEMORY;
16407
16408 index = data.index;
16409 node = data.node;
16410 start = data.start;
16411 saved_count = data.count;
16412
16413 rp_data = &state->repeats[index];
16414
16415 /* Match one character at a time until the tail could match or we
16416 * have reached the maximum.
16417 */
16418 state->text_pos = rp_data->start;
16419 count = rp_data->count;
16420
16421 step = node->nonstring.next_2.test->step;
16422 pos = state->text_pos + (Py_ssize_t)count * step;
16423 available = step > 0 ? state->slice_end - state->text_pos :
16424 state->text_pos - state->slice_start;
16425 max_count = min_size_t((size_t)available, node->values[2]);
16426 limit = state->text_pos + (Py_ssize_t)max_count * step;
16427
16428 repeated = node->nonstring.next_2.node;
16429
16430 test = node->next_1.test;
16431
16432 m = test->match;
16433 index = node->values[0];
16434
16435 match = FALSE;
16436 skip_pos = -1;
16437 if (test->status & RE_STATUS_FUZZY) {
16438 for (;;) {
16439 RE_Position next_position;
16440
16441 status = match_one(state, repeated, pos);
16442 if (status < 0)
16443 return status;
16444
16445 if (status == RE_ERROR_FAILURE)
16446 break;
16447
16448 pos += step;
16449
16450 status = try_match(state, &node->next_1, pos,
16451 &next_position);
16452 if (status < 0)
16453 return status;
16454
16455 if (status == RE_ERROR_SUCCESS && !is_repeat_guarded(state,
16456 index, pos, RE_STATUS_TAIL)) {
16457 match = TRUE;
16458 break;
16459 }
16460
16461 if (pos == limit)
16462 break;
16463 }
16464 } else {
16465 /* A repeated single-character match is often followed by a
16466 * literal, so checking specially for it can be a good
16467 * optimisation when working with long strings.
16468 */
16469 switch (test->op) {
16470 case RE_OP_CHARACTER:
16471 {
16472 Py_UCS4 ch;
16473
16474 ch = test->values[0];
16475
16476 /* The tail is a character. We don't want to go off the end
16477 * of the slice.
16478 */
16479 limit = min_ssize_t(limit, state->slice_end - 1);
16480
16481 for (;;) {
16482 if (pos + 1 >= state->text_end &&
16483 state->partial_side == RE_PARTIAL_RIGHT)
16484 return RE_ERROR_PARTIAL;
16485
16486 if (pos >= limit)
16487 break;
16488
16489 status = match_one(state, repeated, pos);
16490 if (status < 0)
16491 return status;
16492
16493 if (status == RE_ERROR_FAILURE)
16494 break;
16495
16496 ++pos;
16497
16498 if (same_char(char_at(state->text, pos), ch) == m &&
16499 !is_repeat_guarded(state, index, pos,
16500 RE_STATUS_TAIL)) {
16501 match = TRUE;
16502 break;
16503 }
16504 }
16505 break;
16506 }
16507 case RE_OP_CHARACTER_IGN:
16508 {
16509 Py_UCS4 ch;
16510
16511 ch = test->values[0];
16512
16513 /* The tail is a character. We don't want to go off the end
16514 * of the slice.
16515 */
16516 limit = min_ssize_t(limit, state->slice_end - 1);
16517
16518 for (;;) {
16519 if (pos + 1 >= state->text_end &&
16520 state->partial_side == RE_PARTIAL_RIGHT)
16521 return RE_ERROR_PARTIAL;
16522
16523 if (pos >= limit)
16524 break;
16525
16526 status = match_one(state, repeated, pos);
16527 if (status < 0)
16528 return status;
16529
16530 if (status == RE_ERROR_FAILURE)
16531 break;
16532
16533 ++pos;
16534
16535 if (same_char_ign(encoding, locale_info,
16536 char_at(state->text, pos), ch) == m &&
16537 !is_repeat_guarded(state, index, pos,
16538 RE_STATUS_TAIL)) {
16539 match = TRUE;
16540 break;
16541 }
16542 }
16543 break;
16544 }
16545 case RE_OP_CHARACTER_IGN_REV:
16546 {
16547 Py_UCS4 ch;
16548
16549 ch = test->values[0];
16550
16551 /* The tail is a character. We don't want to go off the end
16552 * of the slice.
16553 */
16554 limit = max_ssize_t(limit, state->slice_start + 1);
16555
16556 for (;;) {
16557 if (pos - 1 <= state->text_start && state->partial_side ==
16558 RE_PARTIAL_LEFT)
16559 return RE_ERROR_PARTIAL;
16560
16561 if (pos <= limit)
16562 break;
16563
16564 status = match_one(state, repeated, pos);
16565 if (status < 0)
16566 return status;
16567
16568 if (status == RE_ERROR_FAILURE)
16569 break;
16570
16571 --pos;
16572
16573 if (same_char_ign(encoding, locale_info,
16574 char_at(state->text, pos - 1), ch) == m &&
16575 !is_repeat_guarded(state, index, pos,
16576 RE_STATUS_TAIL)) {
16577 match = TRUE;
16578 break;
16579 }
16580 }
16581 break;
16582 }
16583 case RE_OP_CHARACTER_REV:
16584 {
16585 Py_UCS4 ch;
16586
16587 ch = test->values[0];
16588
16589 /* The tail is a character. We don't want to go off the end
16590 * of the slice.
16591 */
16592 limit = max_ssize_t(limit, state->slice_start + 1);
16593
16594 for (;;) {
16595 if (pos - 1 <= state->text_start && state->partial_side ==
16596 RE_PARTIAL_LEFT)
16597 return RE_ERROR_PARTIAL;
16598
16599 if (pos <= limit)
16600 break;
16601
16602 status = match_one(state, repeated, pos);
16603 if (status < 0)
16604 return status;
16605
16606 if (status == RE_ERROR_FAILURE)
16607 break;
16608
16609 --pos;
16610
16611 if (same_char(char_at(state->text, pos - 1), ch) == m
16612 && !is_repeat_guarded(state, index, pos,
16613 RE_STATUS_TAIL)) {
16614 match = TRUE;
16615 break;
16616 }
16617 }
16618 break;
16619 }
16620 case RE_OP_STRING:
16621 {
16622 Py_ssize_t length;
16623
16624 length = (Py_ssize_t)test->value_count;
16625
16626 /* The tail is a string. We don't want to go off the end of
16627 * the slice.
16628 */
16629 limit = min_ssize_t(limit, state->slice_end - length);
16630
16631 for (;;) {
16632 Py_ssize_t found;
16633 BOOL is_partial;
16634
16635 if (pos >= state->text_end && state->partial_side ==
16636 RE_PARTIAL_RIGHT)
16637 return RE_ERROR_PARTIAL;
16638
16639 /* Look for the tail string. */
16640 found = string_search(state, test, pos + 1, limit +
16641 length, TRUE, &is_partial);
16642 if (is_partial)
16643 return RE_ERROR_PARTIAL;
16644
16645 if (found < 0)
16646 break;
16647
16648 if (repeated->op == RE_OP_ANY_ALL)
16649 /* Anything can precede the tail. */
16650 pos = found;
16651 else {
16652 /* Check that what precedes the tail will match. */
16653 while (pos != found) {
16654 status = match_one(state, repeated, pos);
16655 if (status < 0)
16656 return status;
16657
16658 if (status == RE_ERROR_FAILURE)
16659 break;
16660
16661 ++pos;
16662 }
16663
16664 if (pos != found)
16665 /* Something preceding the tail didn't match.
16666 */
16667 break;
16668 }
16669
16670 if (!is_repeat_guarded(state, index, pos,
16671 RE_STATUS_TAIL)) {
16672 match = TRUE;
16673 break;
16674 }
16675 }
16676 break;
16677 }
16678 case RE_OP_STRING_FLD:
16679 {
16680 /* The tail is a string. We don't want to go off the end of
16681 * the slice.
16682 */
16683 limit = min_ssize_t(limit, state->slice_end);
16684
16685 for (;;) {
16686 Py_ssize_t found;
16687 Py_ssize_t new_pos;
16688 BOOL is_partial;
16689
16690 if (pos >= state->text_end && state->partial_side ==
16691 RE_PARTIAL_RIGHT)
16692 return RE_ERROR_PARTIAL;
16693
16694 /* Look for the tail string. */
16695 found = string_search_fld(state, test, pos + 1, limit,
16696 &new_pos, &is_partial);
16697 if (is_partial)
16698 return RE_ERROR_PARTIAL;
16699
16700 if (found < 0)
16701 break;
16702
16703 if (repeated->op == RE_OP_ANY_ALL)
16704 /* Anything can precede the tail. */
16705 pos = found;
16706 else {
16707 /* Check that what precedes the tail will match. */
16708 while (pos != found) {
16709 status = match_one(state, repeated, pos);
16710 if (status < 0)
16711 return status;
16712
16713 if (status == RE_ERROR_FAILURE)
16714 break;
16715
16716 ++pos;
16717 }
16718
16719 if (pos != found)
16720 /* Something preceding the tail didn't match.
16721 */
16722 break;
16723 }
16724
16725 if (!is_repeat_guarded(state, index, pos,
16726 RE_STATUS_TAIL)) {
16727 match = TRUE;
16728 skip_pos = new_pos;
16729 break;
16730 }
16731 }
16732 break;
16733 }
16734 case RE_OP_STRING_FLD_REV:
16735 {
16736 /* The tail is a string. We don't want to go off the end of
16737 * the slice.
16738 */
16739 limit = max_ssize_t(limit, state->slice_start);
16740
16741 for (;;) {
16742 Py_ssize_t found;
16743 Py_ssize_t new_pos;
16744 BOOL is_partial;
16745
16746 if (pos <= state->text_start && state->partial_side == RE_PARTIAL_LEFT)
16747 return RE_ERROR_PARTIAL;
16748
16749 /* Look for the tail string. */
16750 found = string_search_fld_rev(state, test, pos - 1,
16751 limit, &new_pos, &is_partial);
16752 if (is_partial)
16753 return RE_ERROR_PARTIAL;
16754
16755 if (found < 0)
16756 break;
16757
16758 if (repeated->op == RE_OP_ANY_ALL)
16759 /* Anything can precede the tail. */
16760 pos = found;
16761 else {
16762 /* Check that what precedes the tail will match. */
16763 while (pos != found) {
16764 status = match_one(state, repeated, pos);
16765 if (status < 0)
16766 return status;
16767
16768 if (status == RE_ERROR_FAILURE)
16769 break;
16770
16771 --pos;
16772 }
16773
16774 if (pos != found)
16775 /* Something preceding the tail didn't match.
16776 */
16777 break;
16778 }
16779
16780 if (!is_repeat_guarded(state, index, pos,
16781 RE_STATUS_TAIL)) {
16782 match = TRUE;
16783 skip_pos = new_pos;
16784 break;
16785 }
16786 }
16787 break;
16788 }
16789 case RE_OP_STRING_IGN:
16790 {
16791 Py_ssize_t length;
16792
16793 length = (Py_ssize_t)test->value_count;
16794
16795 /* The tail is a string. We don't want to go off the end of
16796 * the slice.
16797 */
16798 limit = min_ssize_t(limit, state->slice_end - length);
16799
16800 for (;;) {
16801 Py_ssize_t found;
16802 BOOL is_partial;
16803
16804 if (pos >= state->text_end && state->partial_side ==
16805 RE_PARTIAL_RIGHT)
16806 return RE_ERROR_PARTIAL;
16807
16808 /* Look for the tail string. */
16809 found = string_search_ign(state, test, pos + 1, limit +
16810 length, TRUE, &is_partial);
16811 if (is_partial)
16812 return RE_ERROR_PARTIAL;
16813
16814 if (found < 0)
16815 break;
16816
16817 if (repeated->op == RE_OP_ANY_ALL)
16818 /* Anything can precede the tail. */
16819 pos = found;
16820 else {
16821 /* Check that what precedes the tail will match. */
16822 while (pos != found) {
16823 status = match_one(state, repeated, pos);
16824 if (status < 0)
16825 return status;
16826
16827 if (status == RE_ERROR_FAILURE)
16828 break;
16829
16830 ++pos;
16831 }
16832
16833 if (pos != found)
16834 /* Something preceding the tail didn't match.
16835 */
16836 break;
16837 }
16838
16839 if (!is_repeat_guarded(state, index, pos,
16840 RE_STATUS_TAIL)) {
16841 match = TRUE;
16842 break;
16843 }
16844 }
16845 break;
16846 }
16847 case RE_OP_STRING_IGN_REV:
16848 {
16849 Py_ssize_t length;
16850
16851 length = (Py_ssize_t)test->value_count;
16852
16853 /* The tail is a string. We don't want to go off the end of
16854 * the slice.
16855 */
16856 limit = max_ssize_t(limit, state->slice_start + length);
16857
16858 for (;;) {
16859 Py_ssize_t found;
16860 BOOL is_partial;
16861
16862 if (pos <= state->text_start && state->partial_side == RE_PARTIAL_LEFT)
16863 return RE_ERROR_PARTIAL;
16864
16865 /* Look for the tail string. */
16866 found = string_search_ign_rev(state, test, pos - 1,
16867 limit - length, TRUE, &is_partial);
16868 if (is_partial)
16869 return RE_ERROR_PARTIAL;
16870
16871 if (found < 0)
16872 break;
16873
16874 if (repeated->op == RE_OP_ANY_ALL)
16875 /* Anything can precede the tail. */
16876 pos = found;
16877 else {
16878 /* Check that what precedes the tail will match. */
16879 while (pos != found) {
16880 status = match_one(state, repeated, pos);
16881 if (status < 0)
16882 return status;
16883
16884 if (status == RE_ERROR_FAILURE)
16885 break;
16886
16887 --pos;
16888 }
16889
16890 if (pos != found)
16891 /* Something preceding the tail didn't match.
16892 */
16893 break;
16894 }
16895
16896 if (!is_repeat_guarded(state, index, pos,
16897 RE_STATUS_TAIL)) {
16898 match = TRUE;
16899 break;
16900 }
16901 }
16902 break;
16903 }
16904 case RE_OP_STRING_REV:
16905 {
16906 Py_ssize_t length;
16907
16908 length = (Py_ssize_t)test->value_count;
16909
16910 /* The tail is a string. We don't want to go off the end of
16911 * the slice.
16912 */
16913 limit = max_ssize_t(limit, state->slice_start + length);
16914
16915 for (;;) {
16916 Py_ssize_t found;
16917 BOOL is_partial;
16918
16919 if (pos <= state->text_start && state->partial_side == RE_PARTIAL_LEFT)
16920 return RE_ERROR_PARTIAL;
16921
16922 /* Look for the tail string. */
16923 found = string_search_rev(state, test, pos - 1, limit -
16924 length, TRUE, &is_partial);
16925 if (is_partial)
16926 return RE_ERROR_PARTIAL;
16927
16928 if (found < 0)
16929 break;
16930
16931 if (repeated->op == RE_OP_ANY_ALL)
16932 /* Anything can precede the tail. */
16933 pos = found;
16934 else {
16935 /* Check that what precedes the tail will match. */
16936 while (pos != found) {
16937 status = match_one(state, repeated, pos);
16938 if (status < 0)
16939 return status;
16940
16941 if (status == RE_ERROR_FAILURE)
16942 break;
16943
16944 --pos;
16945 }
16946
16947 if (pos != found)
16948 /* Something preceding the tail didn't match.
16949 */
16950 break;
16951 }
16952
16953 if (!is_repeat_guarded(state, index, pos,
16954 RE_STATUS_TAIL)) {
16955 match = TRUE;
16956 break;
16957 }
16958 }
16959 break;
16960 }
16961 default:
16962 for (;;) {
16963 RE_Position next_position;
16964
16965 status = match_one(state, repeated, pos);
16966 if (status < 0)
16967 return status;
16968
16969 if (status == RE_ERROR_FAILURE)
16970 break;
16971
16972 pos += step;
16973
16974 status = try_match(state, &node->next_1, pos,
16975 &next_position);
16976 if (status < 0)
16977 return RE_ERROR_PARTIAL;
16978
16979 if (status == RE_ERROR_SUCCESS &&
16980 !is_repeat_guarded(state, index, pos,
16981 RE_STATUS_TAIL)) {
16982 match = TRUE;
16983 break;
16984 }
16985
16986 if (pos == limit)
16987 break;
16988 }
16989 break;
16990 }
16991 }
16992
16993 if (match) {
16994 /* The tail could match. */
16995 count = (size_t)abs_ssize_t(pos - state->text_pos);
16996 state->text_pos = pos;
16997
16998 if (count < max_count) {
16999 /* The match is shorter than the maximum, so we might need
17000 * to backtrack the repeat again to consume more.
17001 */
17002 RE_RepeatOneStateData data_ro;
17003
17004 rp_data->count = count;
17005
17006 data_ro.count = saved_count;
17007 data_ro.start = start;
17008 data_ro.node = node;
17009 data_ro.index = index;
17010
17011 if (!ByteStack_push_block(state, &state->bstack,
17012 (void*)&data_ro, sizeof(data_ro)))
17013 return RE_ERROR_MEMORY;
17014 if (!push_uint8(state, &state->bstack,
17015 RE_OP_LAZY_REPEAT_ONE))
17016 return RE_ERROR_MEMORY;
17017
17018 /* bstack: count start node index LAZY_REPEAT_ONE */
17019 } else {
17020 /* We've reached or passed the maximum, so we won't need to
17021 * backtrack the repeat again.
17022 */
17023 rp_data->start = start;
17024 rp_data->count = saved_count;
17025
17026 /* Have we passed the maximum? */
17027 if (count > max_count)
17028 goto backtrack;
17029 }
17030
17031 node = node->next_1.node;
17032
17033 if (skip_pos >= 0) {
17034 state->text_pos = skip_pos;
17035 node = node->next_1.node;
17036 }
17037
17038 goto advance;
17039 } else {
17040 /* The tail couldn't match. */
17041 rp_data->start = start;
17042 rp_data->count = saved_count;
17043 }
17044 break;
17045 }
17046 case RE_OP_LOOKAROUND: /* Lookaround subpattern. */
17047 {
17048 RE_Node* lookaround;
17049 RE_LookaroundStateData data_l;
17050 BOOL has_groups;
17051 TRACE(("%s\n", re_op_text[op]))
17052
17053 /* sstack: node slice_start slice_end text_pos ...
17054 *
17055 * bstack: [captures TRUE | FALSE] fuzzy_counts capture_change
17056 * sstack
17057 *
17058 * pstack: bstack
17059 */
17060
17061 if (!drop_bstack(state))
17062 return RE_ERROR_MEMORY;
17063 if (!pop_sstack(state))
17064 return RE_ERROR_MEMORY;
17065
17066 /* sstack: node slice_start slice_end text_pos
17067 *
17068 * bstack: [captures TRUE | FALSE] fuzzy_counts capture_change
17069 *
17070 * pstack: -
17071 */
17072
17073 if (!ByteStack_pop_block(state, &state->sstack, (void*)&data_l,
17074 sizeof(data_l)))
17075 return RE_ERROR_MEMORY;
17076
17077 state->text_pos = data_l.text_pos;
17078 state->slice_end = data_l.slice_end;
17079 state->slice_start = data_l.slice_start;
17080 lookaround = data_l.node;
17081
17082 /* sstack: -
17083 *
17084 * bstack: [captures TRUE | FALSE] fuzzy_counts capture_change
17085 *
17086 * pstack: -
17087 */
17088
17089 if (!pop_size(state, &state->bstack, &state->capture_change))
17090 return RE_ERROR_MEMORY;
17091 if (!pop_fuzzy_counts(state, &state->bstack, state->fuzzy_counts))
17092 return RE_ERROR_MEMORY;
17093 if (!pop_bool(state, &state->bstack, &has_groups))
17094 return RE_ERROR_MEMORY;
17095 if (has_groups) {
17096 if (!pop_captures(state, &state->bstack))
17097 return RE_ERROR_MEMORY;
17098 }
17099
17100 /* sstack: -
17101 *
17102 * bstack: -
17103 *
17104 * pstack: -
17105 */
17106
17107 if (!lookaround->match) {
17108 /* It's a negative lookaround that's failed. */
17109 node = lookaround->nonstring.next_2.node;
17110 goto advance;
17111 }
17112 break;
17113 }
17114 case RE_OP_MATCH_BODY:
17115 {
17116 RE_MatchBodyTailStateData data_mbt;
17117 RE_CODE index;
17118 size_t capture_change;
17119 Py_ssize_t start;
17120 size_t count;
17121 RE_Position position;
17122 RE_RepeatData* rp_data;
17123
17124 /* bstack: position count start capture_change index text_pos */
17125
17126 if (!ByteStack_pop_block(state, &state->bstack, (void*)&data_mbt,
17127 sizeof(data_mbt)))
17128 return RE_ERROR_MEMORY;
17129
17130 index = data_mbt.index;
17131 capture_change = data_mbt.capture_change;
17132 start = data_mbt.start;
17133 count = data_mbt.count;
17134 position = data_mbt.position;
17135 TRACE(("%s %u\n", re_op_text[op], (unsigned int)index))
17136
17137 /* We want to match the body. */
17138 rp_data = &state->repeats[index];
17139
17140 /* Restore the repeat info. */
17141 rp_data->count = count;
17142 rp_data->start = start;
17143 rp_data->capture_change = capture_change;
17144
17145 /* Record backtracking info in case the body fails to match. */
17146 if (!push_code(state, &state->bstack, index))
17147 return RE_ERROR_MEMORY;
17148 if (!push_ssize(state, &state->bstack, data_mbt.text_pos))
17149 return RE_ERROR_MEMORY;
17150 if (!push_uint8(state, &state->bstack, RE_OP_BODY_START))
17151 return RE_ERROR_MEMORY;
17152
17153 /* bstack: index text_pos BODY_START */
17154
17155 /* Advance into the body. */
17156 node = position.node;
17157 state->text_pos = position.text_pos;
17158 goto advance;
17159 }
17160 case RE_OP_MATCH_TAIL:
17161 {
17162 RE_MatchBodyTailStateData data_mbt;
17163 RE_CODE index;
17164 size_t capture_change;
17165 Py_ssize_t start;
17166 size_t count;
17167 RE_Position position;
17168 RE_RepeatData* rp_data;
17169
17170 /* bstack: position count start capture_change index text_pos */
17171
17172 if (!ByteStack_pop_block(state, &state->bstack, (void*)&data_mbt,
17173 sizeof(data_mbt)))
17174 return RE_ERROR_MEMORY;
17175
17176 index = data_mbt.index;
17177 capture_change = data_mbt.capture_change;
17178 start = data_mbt.start;
17179 count = data_mbt.count;
17180 position = data_mbt.position;
17181 TRACE(("%s %u\n", re_op_text[op], (unsigned int)index))
17182
17183 /* We want to match the tail. */
17184 rp_data = &state->repeats[index];
17185
17186 /* Restore the repeat info. */
17187 rp_data->count = count;
17188 rp_data->start = start;
17189 rp_data->capture_change = capture_change;
17190
17191 /* Record backtracking info in case the tail fails to match. */
17192 if (!push_code(state, &state->bstack, index))
17193 return RE_ERROR_MEMORY;
17194 if (!push_ssize(state, &state->bstack, data_mbt.text_pos))
17195 return RE_ERROR_MEMORY;
17196 if (!push_uint8(state, &state->bstack, RE_OP_TAIL_START))
17197 return RE_ERROR_MEMORY;
17198
17199 /* bstack: index text_pos TAIL_START */
17200
17201 /* Advance into the tail. */
17202 node = position.node;
17203 state->text_pos = position.text_pos;
17204 goto advance;
17205 }
17206 case RE_OP_REF_GROUP: /* Reference to a capture group. */
17207 case RE_OP_REF_GROUP_IGN: /* Reference to a capture group, ignoring case. */
17208 case RE_OP_REF_GROUP_IGN_REV: /* Reference to a capture group, backwards, ignoring case. */
17209 case RE_OP_REF_GROUP_REV: /* Reference to a capture group, backwards. */
17210 case RE_OP_STRING: /* A string. */
17211 case RE_OP_STRING_IGN: /* A string, ignoring case. */
17212 case RE_OP_STRING_IGN_REV: /* A string, backwards, ignoring case. */
17213 case RE_OP_STRING_REV: /* A string, backwards. */
17214 {
17215 TRACE(("%s\n", re_op_text[op]))
17216
17217 status = retry_fuzzy_match_string(state, op, search, &node,
17218 &string_pos);
17219 if (status < 0)
17220 return status;
17221
17222 if (status == RE_ERROR_SUCCESS)
17223 goto advance;
17224
17225 string_pos = -1;
17226 break;
17227 }
17228 case RE_OP_REF_GROUP_FLD: /* Reference to a capture group, ignoring case. */
17229 case RE_OP_REF_GROUP_FLD_REV: /* Reference to a capture group, backwards, ignoring case. */
17230 {
17231 TRACE(("%s\n", re_op_text[op]))
17232
17233 status = retry_fuzzy_match_group_fld(state, op, search, &node,
17234 &folded_pos, &string_pos, &gfolded_pos);
17235 if (status < 0)
17236 return status;
17237
17238 if (status == RE_ERROR_SUCCESS)
17239 goto advance;
17240
17241 string_pos = -1;
17242 break;
17243 }
17244 case RE_OP_START_GROUP: /* Start of a capture group. */
17245 {
17246 BOOL capture;
17247 TRACE(("%s\n", re_op_text[op]))
17248
17249 /* If capturing:
17250 *
17251 * sstack: -
17252 *
17253 * bstack: end current capture_change private_index public_index
17254 * TRUE
17255 *
17256 * else:
17257 *
17258 * sstack: start
17259 *
17260 * bstack: FALSE
17261 */
17262
17263 if (!pop_bool(state, &state->bstack, &capture))
17264 return RE_ERROR_MEMORY;
17265
17266 if (capture) {
17267 RE_GroupStateData data_g;
17268 RE_CODE public_index;
17269 RE_CODE private_index;
17270 Py_ssize_t end;
17271 RE_GroupData* group;
17272
17273 if (!ByteStack_pop_block(state, &state->bstack, (void*)&data_g,
17274 sizeof(data_g)))
17275 return RE_ERROR_MEMORY;
17276
17277 public_index = data_g.public_index;
17278 private_index = data_g.private_index;
17279 state->capture_change = data_g.capture_change;
17280 group = &state->groups[private_index - 1];
17281 group->current = data_g.current;
17282 end = data_g.text_pos;
17283 if (!push_ssize(state, &state->sstack, end))
17284 return RE_ERROR_MEMORY;
17285
17286 unsave_capture(state, private_index, public_index);
17287
17288 /* sstack: end
17289 *
17290 * bstack: -
17291 */
17292 } else {
17293 if (!drop_ssize(state, &state->sstack))
17294 return RE_ERROR_MEMORY;
17295 }
17296 break;
17297 }
17298 case RE_OP_STRING_FLD: /* A string, ignoring case. */
17299 case RE_OP_STRING_FLD_REV: /* A string, backwards, ignoring case. */
17300 {
17301 TRACE(("%s\n", re_op_text[op]))
17302
17303 status = retry_fuzzy_match_string_fld(state, op, search, &node,
17304 &string_pos, &folded_pos);
17305 if (status < 0)
17306 return status;
17307
17308 if (status == RE_ERROR_SUCCESS)
17309 goto advance;
17310
17311 string_pos = -1;
17312 break;
17313 }
17314 case RE_OP_TAIL_START:
17315 {
17316 Py_ssize_t text_pos;
17317 RE_CODE index;
17318
17319 /* bstack: index text_pos */
17320
17321 if (!pop_ssize(state, &state->bstack, &text_pos))
17322 return RE_ERROR_MEMORY;
17323 if (!pop_code(state, &state->bstack, &index))
17324 return RE_ERROR_MEMORY;
17325 TRACE(("%s %u\n", re_op_text[op], (unsigned int)index))
17326
17327 /* The tail may have failed to match at this position. */
17328 if (!guard_repeat(state, index, text_pos, RE_STATUS_TAIL, TRUE))
17329 return RE_ERROR_MEMORY;
17330 break;
17331 }
17332 default:
17333 TRACE(("UNKNOWN OP %d\n", op))
17334 return RE_ERROR_ILLEGAL;
17335 }
17336 }
17337 }
17338
17339 /* Saves group data for fuzzy matching. */
17340 Py_LOCAL_INLINE(RE_GroupData*) save_captures(RE_State* state, RE_GroupData*
17341 saved_groups) {
17342 PatternObject* pattern;
17343 size_t g;
17344
17345 /* Re-acquire the GIL. */
17346 acquire_GIL(state);
17347
17348 pattern = state->pattern;
17349
17350 if (!saved_groups) {
17351 saved_groups = (RE_GroupData*)re_alloc(pattern->true_group_count *
17352 sizeof(RE_GroupData));
17353 if (!saved_groups)
17354 goto error;
17355
17356 memset(saved_groups, 0, pattern->true_group_count *
17357 sizeof(RE_GroupData));
17358 }
17359
17360 for (g = 0; g < pattern->true_group_count; g++) {
17361 RE_GroupData* orig;
17362 RE_GroupData* copy;
17363
17364 orig = &state->groups[g];
17365 copy = &saved_groups[g];
17366
17367 if (orig->count > copy->capacity) {
17368 RE_GroupSpan* cap_copy;
17369
17370 cap_copy = (RE_GroupSpan*)re_realloc(copy->captures, orig->count *
17371 sizeof(RE_GroupSpan));
17372 if (!cap_copy)
17373 goto error;
17374
17375 copy->capacity = orig->count;
17376 copy->captures = cap_copy;
17377 }
17378
17379 copy->count = orig->count;
17380 Py_MEMCPY(copy->captures, orig->captures, orig->count *
17381 sizeof(RE_GroupSpan));
17382 copy->current = orig->current;
17383 }
17384
17385 /* Release the GIL. */
17386 release_GIL(state);
17387
17388 return saved_groups;
17389
17390 error:
17391 if (saved_groups) {
17392 for (g = 0; g < pattern->true_group_count; g++)
17393 re_dealloc(saved_groups[g].captures);
17394
17395 re_dealloc(saved_groups);
17396 }
17397
17398 /* Release the GIL. */
17399 release_GIL(state);
17400
17401 return NULL;
17402 }
17403
17404 /* Restores group data for fuzzy matching. */
17405 Py_LOCAL_INLINE(void) restore_groups(RE_State* state, RE_GroupData*
17406 saved_groups) {
17407 PatternObject* pattern;
17408 size_t g;
17409
17410 /* Re-acquire the GIL. */
17411 acquire_GIL(state);
17412
17413 pattern = state->pattern;
17414
17415 for (g = 0; g < pattern->true_group_count; g++) {
17416 RE_GroupData* group;
17417 RE_GroupData* saved;
17418
17419 group = &state->groups[g];
17420 saved = &saved_groups[g];
17421
17422 group->count = saved->count;
17423 Py_MEMCPY(group->captures, saved->captures, saved->count *
17424 sizeof(RE_GroupSpan));
17425 group->current = saved->current;
17426
17427 re_dealloc(saved->captures);
17428 }
17429
17430 re_dealloc(saved_groups);
17431
17432 /* Release the GIL. */
17433 release_GIL(state);
17434 }
17435
17436 /* Discards group data for fuzzy matching. */
17437 Py_LOCAL_INLINE(void) discard_groups(RE_State* state, RE_GroupData*
17438 saved_groups) {
17439 PatternObject* pattern;
17440 size_t g;
17441
17442 /* Re-acquire the GIL. */
17443 acquire_GIL(state);
17444
17445 pattern = state->pattern;
17446
17447 for (g = 0; g < pattern->true_group_count; g++)
17448 re_dealloc(saved_groups[g].captures);
17449
17450 re_dealloc(saved_groups);
17451
17452 /* Release the GIL. */
17453 release_GIL(state);
17454 }
17455
17456 /* Saves the fuzzy counts. */
17457 Py_LOCAL_INLINE(void) save_fuzzy_counts(RE_State* state, size_t* fuzzy_counts)
17458 {
17459 Py_MEMCPY(fuzzy_counts, state->fuzzy_counts, sizeof(state->fuzzy_counts));
17460 }
17461
17462 /* Restores the fuzzy counts. */
17463 Py_LOCAL_INLINE(void) restore_fuzzy_counts(RE_State* state, size_t*
17464 fuzzy_counts) {
17465 Py_MEMCPY(state->fuzzy_counts, fuzzy_counts, sizeof(state->fuzzy_counts));
17466 }
17467
17468 /* Initialises the list of best matches found so far. */
17469 Py_LOCAL_INLINE(void) init_best_list(RE_BestList* best_list) {
17470 best_list->capacity = 0;
17471 best_list->count = 0;
17472 best_list->entries = NULL;
17473 }
17474
17475 /* Finalises the list of best matches found so far. */
17476 Py_LOCAL_INLINE(void) fini_best_list(RE_State* state, RE_BestList* best_list) {
17477 safe_dealloc(state, best_list->entries);
17478 best_list->capacity = 0;
17479 best_list->count = 0;
17480 best_list->entries = NULL;
17481 }
17482
17483 /* Clears the list of best matches found so far. */
17484 Py_LOCAL_INLINE(void) clear_best_list(RE_BestList* best_list) {
17485 best_list->count = 0;
17486 }
17487
17488 /* Adds a new entry to the list of best matches found so far. */
17489 Py_LOCAL_INLINE(BOOL) add_to_best_list(RE_State* state, RE_BestList* best_list,
17490 Py_ssize_t match_pos, Py_ssize_t text_pos) {
17491 RE_BestEntry* entry;
17492
17493 if (best_list->count >= best_list->capacity) {
17494 size_t new_capacity;
17495 RE_BestEntry* new_entries;
17496
17497 new_capacity = best_list->capacity * 2;
17498
17499 if (new_capacity == 0)
17500 new_capacity = 16;
17501
17502 new_entries = safe_realloc(state, best_list->entries, new_capacity *
17503 sizeof(RE_BestEntry));
17504 if (!new_entries)
17505 return FALSE;
17506
17507 best_list->entries = new_entries;
17508 best_list->capacity = new_capacity;
17509 }
17510
17511 entry = &best_list->entries[best_list->count++];
17512 entry->match_pos = match_pos;
17513 entry->text_pos = text_pos;
17514
17515 return TRUE;
17516 }
17517
17518 /* Performs a match or search from the current text position for a best fuzzy
17519 * match.
17520 */
17521 Py_LOCAL_INLINE(int) do_best_fuzzy_match(RE_State* state, BOOL search) {
17522 Py_ssize_t available;
17523 int step;
17524 size_t fewest_errors;
17525 BOOL must_advance;
17526 BOOL found_match;
17527 RE_BestList best_list;
17528 RE_BestChangesList best_changes_list;
17529 Py_ssize_t start_pos;
17530 int status = RE_ERROR_FAILURE;
17531 TRACE(("<<do_best_fuzzy_match>>\n"))
17532
17533 if (state->reverse) {
17534 available = state->text_pos - state->slice_start;
17535 step = -1;
17536 } else {
17537 available = state->slice_end - state->text_pos;
17538 step = 1;
17539 }
17540
17541 /* The maximum permitted cost. */
17542 state->max_errors = PY_SSIZE_T_MAX;
17543 fewest_errors = PY_SSIZE_T_MAX;
17544
17545 state->best_text_pos = state->reverse ? state->slice_start :
17546 state->slice_end;
17547
17548 must_advance = state->must_advance;
17549 found_match = FALSE;
17550
17551 init_best_list(&best_list);
17552 init_best_changes_list(&best_changes_list);
17553
17554 /* Search the text for the best match. */
17555 start_pos = state->text_pos;
17556 while (state->slice_start <= start_pos && start_pos <= state->slice_end) {
17557 state->text_pos = start_pos;
17558 state->must_advance = must_advance;
17559
17560 /* Initialise the state. */
17561 init_match(state);
17562
17563 status = RE_ERROR_SUCCESS;
17564 if (state->max_errors == 0 && state->partial_side == RE_PARTIAL_NONE) {
17565 /* An exact match, and partial matches not permitted. */
17566 if (available < state->min_width || (available == 0 &&
17567 state->must_advance))
17568 status = RE_ERROR_FAILURE;
17569 }
17570
17571 if (status == RE_ERROR_SUCCESS)
17572 status = basic_match(state, search);
17573
17574 /* Has an error occurred, or is it a partial match? */
17575 if (status < 0)
17576 goto error;
17577
17578 if (status == RE_ERROR_FAILURE)
17579 break;
17580
17581 /* It was a successful match. */
17582 found_match = TRUE;
17583
17584 if (state->total_errors < fewest_errors) {
17585 /* This match was better than any of the previous ones. */
17586 fewest_errors = state->total_errors;
17587
17588 if (state->total_errors == 0)
17589 /* It was a perfect match. */
17590 break;
17591
17592 /* Forget all the previous worse matches and remember this one. */
17593 clear_best_list(&best_list);
17594 if (!add_to_best_list(state, &best_list, state->match_pos,
17595 state->text_pos))
17596 goto mem_error;
17597
17598 clear_best_fuzzy_changes(state, &best_changes_list);
17599 if (!add_best_fuzzy_changes(state, &best_changes_list))
17600 goto mem_error;
17601 } else if (state->total_errors == fewest_errors) {
17602 /* This match was as good as the previous matches. Remember this
17603 * one.
17604 */
17605 add_to_best_list(state, &best_list, state->match_pos,
17606 state->text_pos);
17607 if (!add_best_fuzzy_changes(state, &best_changes_list))
17608 goto mem_error;
17609 }
17610
17611 start_pos = state->match_pos;
17612 state->max_errors = fewest_errors - 1;
17613 }
17614
17615 if (found_match) {
17616 RE_FuzzyChangesList* list;
17617
17618 /* We found a match. */
17619 if (fewest_errors > 0) {
17620 /* It doesn't look like a perfect match. */
17621 size_t i;
17622 Py_ssize_t slice_start;
17623 Py_ssize_t slice_end;
17624 size_t error_limit;
17625 size_t best_fuzzy_counts[RE_FUZZY_COUNT];
17626 RE_FuzzyChangesList best_fuzzy_changes;
17627 RE_GroupData* best_groups;
17628 Py_ssize_t best_match_pos = 0;
17629 Py_ssize_t best_text_pos;
17630
17631 slice_start = state->slice_start;
17632 slice_end = state->slice_end;
17633
17634 error_limit = fewest_errors;
17635
17636 if (error_limit > RE_MAX_ERRORS)
17637 error_limit = RE_MAX_ERRORS;
17638
17639 best_groups = NULL;
17640 init_fuzzy_changes_list(&best_fuzzy_changes);
17641
17642 /* Look again at the best of the matches that we've seen. */
17643 for (i = 0; i < best_list.count; i++) {
17644 RE_BestEntry* entry;
17645 Py_ssize_t max_offset;
17646 Py_ssize_t offset;
17647
17648 /* Look for the best fit at this position. */
17649 entry = &best_list.entries[i];
17650
17651 if (search) {
17652 max_offset = state->reverse ? entry->match_pos -
17653 state->slice_start : state->slice_end - entry->match_pos;
17654
17655 if (max_offset > (Py_ssize_t)fewest_errors)
17656 max_offset = (Py_ssize_t)fewest_errors;
17657
17658 if (max_offset > (Py_ssize_t)error_limit)
17659 max_offset = (Py_ssize_t)error_limit;
17660 } else
17661 max_offset = 0;
17662
17663 start_pos = entry->match_pos;
17664 offset = 0;
17665
17666 while (offset <= max_offset) {
17667 state->max_errors = 1;
17668
17669 while (state->max_errors <= error_limit) {
17670 state->text_pos = start_pos;
17671 init_match(state);
17672 status = basic_match(state, FALSE);
17673
17674 if (status < 0)
17675 goto error;
17676
17677 if (status == RE_ERROR_SUCCESS) {
17678 BOOL better = FALSE;
17679
17680 if (state->total_errors < error_limit || (i == 0 &&
17681 offset == 0))
17682 better = TRUE;
17683 else if (state->total_errors == error_limit)
17684 /* The cost is as low as the current best, but
17685 * is it earlier?
17686 */
17687 better = state->reverse ? state->match_pos >
17688 best_match_pos : state->match_pos <
17689 best_match_pos;
17690
17691 if (better) {
17692 save_fuzzy_counts(state, best_fuzzy_counts);
17693 if (!save_fuzzy_changes(state,
17694 &best_fuzzy_changes))
17695 goto mem_error;
17696
17697 best_groups = save_captures(state,
17698 best_groups);
17699 if (!best_groups)
17700 goto mem_error;
17701
17702 best_match_pos = state->match_pos;
17703 best_text_pos = state->text_pos;
17704 error_limit = state->total_errors;
17705 }
17706
17707 break;
17708 }
17709
17710 ++state->max_errors;
17711 }
17712
17713 start_pos += step;
17714 ++offset;
17715 }
17716
17717 if (status == RE_ERROR_SUCCESS && state->total_errors == 0)
17718 break;
17719 }
17720
17721 if (best_groups) {
17722 status = RE_ERROR_SUCCESS;
17723 state->match_pos = best_match_pos;
17724 state->text_pos = best_text_pos;
17725
17726 restore_groups(state, best_groups);
17727 restore_fuzzy_counts(state, best_fuzzy_counts);
17728 restore_fuzzy_changes(state, &best_fuzzy_changes);
17729 } else {
17730 /* None of the "best" matches could be improved on, so pick the
17731 * first.
17732 */
17733 RE_BestEntry* entry;
17734
17735 /* Look at only the part of the string around the match. */
17736 entry = &best_list.entries[0];
17737
17738 if (state->reverse) {
17739 state->slice_start = entry->text_pos;
17740 state->slice_end = entry->match_pos;
17741 } else {
17742 state->slice_start = entry->match_pos;
17743 state->slice_end = entry->text_pos;
17744 }
17745
17746 /* We'll expand the part that we're looking at to take to
17747 * compensate for any matching errors that have occurred.
17748 */
17749 if (state->slice_start - slice_start >=
17750 (Py_ssize_t)fewest_errors)
17751 state->slice_start -= (Py_ssize_t)fewest_errors;
17752 else
17753 state->slice_start = slice_start;
17754
17755 if (slice_end - state->slice_end >= (Py_ssize_t)fewest_errors)
17756 state->slice_end += (Py_ssize_t)fewest_errors;
17757 else
17758 state->slice_end = slice_end;
17759
17760 state->max_errors = fewest_errors;
17761 state->text_pos = entry->match_pos;
17762 init_match(state);
17763 status = basic_match(state, search);
17764
17765 if (status < 0)
17766 goto error;
17767
17768 list = &best_changes_list.lists[0];
17769 state->fuzzy_changes.count = list->count;
17770 Py_MEMCPY(state->fuzzy_changes.items, list->items,
17771 (size_t)list->count * sizeof(RE_FuzzyChange));
17772 }
17773
17774 fini_fuzzy_changes_list(state, &best_fuzzy_changes);
17775
17776 state->slice_start = slice_start;
17777 state->slice_end = slice_end;
17778 } else
17779 state->fuzzy_changes.count = 0;
17780 }
17781
17782 fini_best_list(state, &best_list);
17783 fini_best_changes_list(state, &best_changes_list);
17784
17785 return status;
17786
17787 mem_error:
17788 status = RE_ERROR_MEMORY;
17789
17790 error:
17791 fini_best_list(state, &best_list);
17792 fini_best_changes_list(state, &best_changes_list);
17793 return status;
17794 }
17795
17796 /* Performs a match or search from the current text position for an enhanced
17797 * fuzzy match.
17798 */
17799 Py_LOCAL_INLINE(int) do_enhanced_fuzzy_match(RE_State* state, BOOL search) {
17800 PatternObject* pattern;
17801 Py_ssize_t available;
17802 size_t fewest_errors;
17803 RE_GroupData* best_groups;
17804 Py_ssize_t best_match_pos;
17805 BOOL must_advance;
17806 Py_ssize_t slice_start;
17807 Py_ssize_t slice_end;
17808 int status;
17809 size_t best_fuzzy_counts[RE_FUZZY_COUNT];
17810 RE_FuzzyChangesList best_fuzzy_changes;
17811 Py_ssize_t best_text_pos = 0; /* Initialise to stop compiler warning. */
17812 TRACE(("<<do_enhanced_fuzzy_match>>\n"))
17813
17814 pattern = state->pattern;
17815
17816 init_fuzzy_changes_list(&best_fuzzy_changes);
17817
17818 if (state->reverse)
17819 available = state->text_pos - state->slice_start;
17820 else
17821 available = state->slice_end - state->text_pos;
17822
17823 /* The maximum permitted cost. */
17824 state->max_errors = PY_SSIZE_T_MAX;
17825 fewest_errors = PY_SSIZE_T_MAX;
17826
17827 best_groups = NULL;
17828
17829 state->best_match_pos = state->text_pos;
17830 state->best_text_pos = state->reverse ? state->slice_start :
17831 state->slice_end;
17832
17833 best_match_pos = state->text_pos;
17834 must_advance = state->must_advance;
17835
17836 slice_start = state->slice_start;
17837 slice_end = state->slice_end;
17838
17839 for (;;) {
17840 /* If there's a better match, it won't start earlier in the string than
17841 * the current best match, so there's no need to start earlier than
17842 * that match.
17843 */
17844 state->must_advance = must_advance;
17845
17846 /* Initialise the state. */
17847 init_match(state);
17848
17849 status = RE_ERROR_SUCCESS;
17850 if (state->max_errors == 0 && state->partial_side == RE_PARTIAL_NONE) {
17851 /* An exact match, and partial matches not permitted. */
17852 if (available < state->min_width || (available == 0 &&
17853 state->must_advance))
17854 status = RE_ERROR_FAILURE;
17855 }
17856
17857 if (status == RE_ERROR_SUCCESS)
17858 status = basic_match(state, search);
17859
17860 /* Has an error occurred, or is it a partial match? */
17861 if (status < 0)
17862 break;
17863
17864 if (status == RE_ERROR_SUCCESS) {
17865 BOOL better;
17866
17867 better = state->total_errors < fewest_errors;
17868
17869 if (better) {
17870 BOOL same_match;
17871
17872 fewest_errors = state->total_errors;
17873 state->max_errors = fewest_errors;
17874
17875 save_fuzzy_counts(state, best_fuzzy_counts);
17876 if (!save_fuzzy_changes(state, &best_fuzzy_changes))
17877 goto error;
17878
17879 same_match = state->match_pos == best_match_pos &&
17880 state->text_pos == best_text_pos;
17881 same_match = FALSE;
17882
17883 if (best_groups) {
17884 size_t g;
17885
17886 /* Did we get the same match as the best so far? */
17887 for (g = 0; same_match && g < pattern->public_group_count;
17888 g++)
17889 same_match = same_span_of_group(&state->groups[g],
17890 &best_groups[g]);
17891 }
17892
17893 /* Save the best result so far. */
17894 best_groups = save_captures(state, best_groups);
17895 if (!best_groups) {
17896 status = RE_ERROR_MEMORY;
17897 break;
17898 }
17899
17900 best_match_pos = state->match_pos;
17901 best_text_pos = state->text_pos;
17902
17903 if (same_match || state->total_errors == 0)
17904 break;
17905
17906 state->max_errors = state->total_errors;
17907 if (state->max_errors < RE_MAX_ERRORS)
17908 --state->max_errors;
17909 } else
17910 break;
17911
17912 if (state->reverse) {
17913 state->slice_start = state->text_pos;
17914 state->slice_end = state->match_pos;
17915 } else {
17916 state->slice_start = state->match_pos;
17917 state->slice_end = state->text_pos;
17918 }
17919
17920 state->text_pos = state->match_pos;
17921
17922 if (state->max_errors == PY_SSIZE_T_MAX)
17923 state->max_errors = 0;
17924 } else
17925 break;
17926 }
17927
17928 if (status < 0 && status != RE_ERROR_PARTIAL)
17929 goto error;
17930
17931 state->slice_start = slice_start;
17932 state->slice_end = slice_end;
17933
17934 if (best_groups) {
17935 if (status == RE_ERROR_SUCCESS && state->total_errors == 0)
17936 /* We have a perfect match, so the previous best match. */
17937 discard_groups(state, best_groups);
17938 else {
17939 /* Restore the previous best match. */
17940 status = RE_ERROR_SUCCESS;
17941
17942 state->match_pos = best_match_pos;
17943 state->text_pos = best_text_pos;
17944
17945 restore_groups(state, best_groups);
17946 restore_fuzzy_counts(state, best_fuzzy_counts);
17947 }
17948
17949 restore_fuzzy_changes(state, &best_fuzzy_changes);
17950 }
17951
17952 fini_fuzzy_changes_list(state, &best_fuzzy_changes);
17953
17954 return status;
17955
17956 error:
17957 fini_fuzzy_changes_list(state, &best_fuzzy_changes);
17958 return status;
17959 }
17960
17961 /* Performs a match or search from the current text position for a simple fuzzy
17962 * match.
17963 */
17964 Py_LOCAL_INLINE(int) do_simple_fuzzy_match(RE_State* state, BOOL search) {
17965 Py_ssize_t available;
17966 int status;
17967 TRACE(("<<do_simple_fuzzy_match>>\n"))
17968
17969 if (state->reverse)
17970 available = state->text_pos - state->slice_start;
17971 else
17972 available = state->slice_end - state->text_pos;
17973
17974 /* The maximum permitted cost. */
17975 state->max_errors = PY_SSIZE_T_MAX;
17976
17977 state->best_match_pos = state->text_pos;
17978 state->best_text_pos = state->reverse ? state->slice_start :
17979 state->slice_end;
17980
17981 /* Initialise the state. */
17982 init_match(state);
17983
17984 status = RE_ERROR_SUCCESS;
17985 if (state->max_errors == 0 && state->partial_side == RE_PARTIAL_NONE) {
17986 /* An exact match, and partial matches not permitted. */
17987 if (available < state->min_width || (available == 0 &&
17988 state->must_advance))
17989 status = RE_ERROR_FAILURE;
17990 }
17991
17992 if (status == RE_ERROR_SUCCESS)
17993 status = basic_match(state, search);
17994
17995 return status;
17996 }
17997
17998 /* Performs a match or search from the current text position for an exact
17999 * match.
18000 */
18001 Py_LOCAL_INLINE(int) do_exact_match(RE_State* state, BOOL search) {
18002 Py_ssize_t available;
18003 int status;
18004 TRACE(("<<do_exact_match>>\n"))
18005
18006 if (state->reverse)
18007 available = state->text_pos - state->slice_start;
18008 else
18009 available = state->slice_end - state->text_pos;
18010
18011 /* The maximum permitted cost. */
18012 state->max_errors = 0;
18013
18014 state->best_match_pos = state->text_pos;
18015 state->best_text_pos = state->reverse ? state->slice_start :
18016 state->slice_end;
18017
18018 /* Initialise the state. */
18019 init_match(state);
18020
18021 status = RE_ERROR_SUCCESS;
18022 if (state->max_errors == 0 && state->partial_side == RE_PARTIAL_NONE) {
18023 /* An exact match, and partial matches not permitted. */
18024 if (available < state->min_width || (available == 0 &&
18025 state->must_advance))
18026 status = RE_ERROR_FAILURE;
18027 }
18028
18029 if (status == RE_ERROR_SUCCESS)
18030 status = basic_match(state, search);
18031
18032 return status;
18033 }
18034
18035 /* Performs the requested kind (i.e. fuzziness) of match. */
18036 Py_LOCAL_INLINE(int) do_match_2(RE_State* state, BOOL search) {
18037 PatternObject* pattern;
18038
18039 pattern = state->pattern;
18040
18041 if (!pattern->is_fuzzy)
18042 return do_exact_match(state, search);
18043
18044 if (pattern->flags & RE_FLAG_BESTMATCH)
18045 return do_best_fuzzy_match(state, search);
18046
18047 if (pattern->flags & RE_FLAG_ENHANCEMATCH)
18048 return do_enhanced_fuzzy_match(state, search);
18049
18050 return do_simple_fuzzy_match(state, search);
18051 }
18052
18053 /* Performs a match or search from the current text position.
18054 *
18055 * The state can sometimes be shared across threads. In such instances there's
18056 * a lock (mutex) on it. The lock is held for the duration of matching.
18057 */
18058 Py_LOCAL_INLINE(int) do_match(RE_State* state, BOOL search) {
18059 PatternObject* pattern;
18060 int status;
18061 TRACE(("<<do_match>>\n"))
18062
18063 pattern = state->pattern;
18064
18065 /* Is there enough to search? */
18066 if (state->reverse) {
18067 if (state->text_pos < state->slice_start)
18068 return FALSE;
18069 } else {
18070 if (state->text_pos > state->slice_end)
18071 return FALSE;
18072 }
18073
18074 /* Release the GIL. */
18075 release_GIL(state);
18076
18077 /* Perform a normal match, but fall back to a partial match if requested.
18078 */
18079 if (state->partial_side == RE_PARTIAL_NONE)
18080 /* Normal match. */
18081 status = do_match_2(state, search);
18082 else {
18083 int partial_side;
18084 Py_ssize_t text_pos;
18085
18086 partial_side = state->partial_side;
18087 text_pos = state->text_pos;
18088
18089 /* Try a normal match first. */
18090 state->partial_side = RE_PARTIAL_NONE;
18091
18092 status = do_match_2(state, search);
18093
18094 state->partial_side = partial_side;
18095
18096 if (status == RE_ERROR_FAILURE) {
18097 /* Fall back to the partial match as originally requested. */
18098 state->text_pos = text_pos;
18099 status = do_match_2(state, search);
18100 }
18101 }
18102
18103 if (status == RE_ERROR_SUCCESS || status == RE_ERROR_PARTIAL) {
18104 Py_ssize_t max_end_index;
18105 RE_GroupInfo* group_info;
18106 size_t g;
18107
18108 /* Store the results. */
18109 state->lastindex = -1;
18110 state->lastgroup = -1;
18111 max_end_index = -1;
18112
18113 if (status == RE_ERROR_PARTIAL) {
18114 /* We've matched up to the limit of the slice. */
18115 if (state->reverse)
18116 state->text_pos = state->slice_start;
18117 else
18118 state->text_pos = state->slice_end;
18119 }
18120
18121 /* Store the capture groups. */
18122 group_info = pattern->group_info;
18123
18124 for (g = 0; g < pattern->public_group_count; g++) {
18125 RE_GroupData* group;
18126
18127 group = &state->groups[g];
18128
18129 if (group->current >= 0 && group_info[g].end_index > max_end_index)
18130 {
18131 max_end_index = group_info[g].end_index;
18132 state->lastindex = (Py_ssize_t)g + 1;
18133 if (group_info[g].has_name)
18134 state->lastgroup = (Py_ssize_t)g + 1;
18135 }
18136 }
18137 }
18138
18139 /* Re-acquire the GIL. */
18140 acquire_GIL(state);
18141
18142 if (status < 0 && status != RE_ERROR_PARTIAL && !PyErr_Occurred())
18143 set_error(status, NULL);
18144
18145 return status;
18146 }
18147
18148 /* Gets a string from a Python object.
18149 *
18150 * If the function returns true and str_info->should_release is true then it's
18151 * the responsibility of the caller to release the buffer when it's no longer
18152 * needed.
18153 */
18154 Py_LOCAL_INLINE(BOOL) get_string(PyObject* string, RE_StringInfo* str_info) {
18155 /* Given a Python object, return a data pointer, a length (in characters),
18156 * and a character size. Return FALSE if the object is not a string (or not
18157 * compatible).
18158 */
18159 /* Unicode objects do not support the buffer API. So, get the data directly
18160 * instead.
18161 */
18162 if (PyUnicode_Check(string)) {
18163 /* Unicode strings don't always support the buffer interface. */
18164 if (PyUnicode_READY(string) == -1)
18165 return FALSE;
18166
18167 str_info->characters = (void*)PyUnicode_DATA(string);
18168 str_info->length = PyUnicode_GET_LENGTH(string);
18169 str_info->charsize = PyUnicode_KIND(string);
18170 str_info->is_unicode = TRUE;
18171 str_info->should_release = FALSE;
18172 return TRUE;
18173 }
18174
18175 /* Get pointer to string buffer. */
18176 if (PyObject_GetBuffer(string, &str_info->view, PyBUF_SIMPLE) != 0) {
18177 PyErr_SetString(PyExc_TypeError, "expected string or buffer");
18178 return FALSE;
18179 }
18180
18181 if (!str_info->view.buf) {
18182 PyBuffer_Release(&str_info->view);
18183 PyErr_SetString(PyExc_ValueError, "buffer is NULL");
18184 return FALSE;
18185 }
18186
18187 str_info->should_release = TRUE;
18188
18189 str_info->characters = str_info->view.buf;
18190 str_info->length = str_info->view.len;
18191 str_info->charsize = 1;
18192 str_info->is_unicode = FALSE;
18193
18194 return TRUE;
18195 }
18196
18197 /* Deallocates the groups storage. */
18198 Py_LOCAL_INLINE(void) dealloc_groups(RE_GroupData* groups, size_t group_count)
18199 {
18200 size_t g;
18201
18202 if (!groups)
18203 return;
18204
18205 for (g = 0; g < group_count; g++)
18206 re_dealloc(groups[g].captures);
18207
18208 re_dealloc(groups);
18209 }
18210
18211 /* Initialises a state object. */
18212 Py_LOCAL_INLINE(BOOL) state_init_2(RE_State* state, PatternObject* pattern,
18213 PyObject* string, RE_StringInfo* str_info, Py_ssize_t start, Py_ssize_t end,
18214 BOOL overlapped, int concurrent, BOOL partial, BOOL use_lock, BOOL
18215 visible_captures, BOOL match_all, Py_ssize_t timeout) {
18216 Py_ssize_t final_pos;
18217 int p;
18218
18219 state->thread_state = NULL;
18220
18221 ByteStack_init(state, &state->sstack);
18222 ByteStack_init(state, &state->bstack);
18223 ByteStack_init(state, &state->pstack);
18224
18225 /* We might already have some cached storage we can use for bstack. */
18226 if (pattern->stack_storage) {
18227 state->bstack.storage = pattern->stack_storage;
18228 state->bstack.capacity = pattern->stack_capacity;
18229 pattern->stack_storage = NULL;
18230 pattern->stack_capacity = 0;
18231 }
18232
18233 state->groups = NULL;
18234 state->best_match_groups = NULL;
18235 state->repeats = NULL;
18236 state->visible_captures = visible_captures;
18237 state->match_all = match_all;
18238 state->lock = NULL;
18239 state->fuzzy_guards = NULL;
18240 state->group_call_guard_list = NULL;
18241 state->req_pos = -1;
18242 state->is_fuzzy = pattern->is_fuzzy;
18243
18244 /* The call guards used by recursive patterns. */
18245 if (pattern->call_ref_info_count > 0) {
18246 state->group_call_guard_list =
18247 (RE_GuardList*)re_alloc(pattern->call_ref_info_count *
18248 sizeof(RE_GuardList));
18249 if (!state->group_call_guard_list)
18250 goto error;
18251 memset(state->group_call_guard_list, 0, pattern->call_ref_info_count *
18252 sizeof(RE_GuardList));
18253 }
18254
18255 /* The capture groups. */
18256 if (pattern->true_group_count) {
18257 size_t g;
18258
18259 if (pattern->groups_storage) {
18260 state->groups = pattern->groups_storage;
18261 pattern->groups_storage = NULL;
18262 } else {
18263 state->groups = (RE_GroupData*)re_alloc(pattern->true_group_count *
18264 sizeof(RE_GroupData));
18265 if (!state->groups)
18266 goto error;
18267 memset(state->groups, 0, pattern->true_group_count *
18268 sizeof(RE_GroupData));
18269
18270 for (g = 0; g < pattern->true_group_count; g++) {
18271 RE_GroupSpan* captures;
18272
18273 captures = (RE_GroupSpan*)re_alloc(sizeof(RE_GroupSpan));
18274 if (!captures) {
18275 size_t i;
18276
18277 for (i = 0; i < g; i++)
18278 re_dealloc(state->groups[i].captures);
18279
18280 goto error;
18281 }
18282
18283 state->groups[g].captures = captures;
18284 state->groups[g].capacity = 1;
18285 }
18286 }
18287 }
18288
18289 /* Adjust boundaries. */
18290 if (start < 0)
18291 start += str_info->length;
18292 if (start < 0)
18293 start = 0;
18294 else if (start > str_info->length)
18295 start = str_info->length;
18296
18297 if (end < 0)
18298 end += str_info->length;
18299 if (end < 0)
18300 end = 0;
18301 else if (end > str_info->length)
18302 end = str_info->length;
18303
18304 state->overlapped = overlapped;
18305 state->min_width = pattern->min_width;
18306
18307 /* Initialise the getters and setters for the character size. */
18308 state->charsize = str_info->charsize;
18309 state->is_unicode = str_info->is_unicode;
18310
18311 /* Are we using a buffer object? If so, we need to copy the info. */
18312 state->should_release = str_info->should_release;
18313 if (state->should_release)
18314 state->view = str_info->view;
18315
18316 switch (state->charsize) {
18317 case 1:
18318 state->char_at = bytes1_char_at;
18319 state->set_char_at = bytes1_set_char_at;
18320 state->point_to = bytes1_point_to;
18321 break;
18322 case 2:
18323 state->char_at = bytes2_char_at;
18324 state->set_char_at = bytes2_set_char_at;
18325 state->point_to = bytes2_point_to;
18326 break;
18327 case 4:
18328 state->char_at = bytes4_char_at;
18329 state->set_char_at = bytes4_set_char_at;
18330 state->point_to = bytes4_point_to;
18331 break;
18332 default:
18333 goto error;
18334 }
18335
18336 state->encoding = pattern->encoding;
18337 state->locale_info = pattern->locale_info;
18338
18339 /* The state object contains a reference to the string and also a pointer
18340 * to its contents.
18341 *
18342 * The documentation says that the end of the slice behaves like the end of
18343 * the string.
18344 */
18345 state->text = str_info->characters;
18346 state->text_length = str_info->length;
18347
18348 /* Open start and closed end bounds, like in re module. */
18349 state->text_start = 0;
18350 state->text_end = end;
18351
18352 state->slice_start = start;
18353 state->slice_end = end;
18354
18355 state->reverse = (pattern->flags & RE_FLAG_REVERSE) != 0;
18356 if (partial)
18357 state->partial_side = state->reverse ? RE_PARTIAL_LEFT :
18358 RE_PARTIAL_RIGHT;
18359 else
18360 state->partial_side = RE_PARTIAL_NONE;
18361
18362 state->text_pos = state->reverse ? state->slice_end : state->slice_start;
18363
18364 /* Point to the final newline and line separator if it's at the end of the
18365 * string, otherwise just -1.
18366 */
18367 state->final_newline = -1;
18368 state->final_line_sep = -1;
18369 final_pos = state->text_end - 1;
18370 if (final_pos >= 0) {
18371 Py_UCS4 ch;
18372
18373 ch = state->char_at(state->text, final_pos);
18374 if (ch == 0x0A) {
18375 /* The string ends with LF. */
18376 state->final_newline = final_pos;
18377 state->final_line_sep = final_pos;
18378
18379 /* Does the string end with CR/LF? */
18380 --final_pos;
18381 if (final_pos >= 0 && state->char_at(state->text, final_pos) ==
18382 0x0D)
18383 state->final_line_sep = final_pos;
18384 } else {
18385 /* The string doesn't end with LF, but it could be another kind of
18386 * line separator.
18387 */
18388 if (state->encoding->is_line_sep(ch))
18389 state->final_line_sep = final_pos;
18390 }
18391 }
18392
18393 /* If the 'new' behaviour is enabled then split correctly on zero-width
18394 * matches.
18395 */
18396 state->version_0 = (pattern->flags & RE_FLAG_VERSION1) == 0;
18397 state->must_advance = FALSE;
18398
18399 state->pattern = pattern;
18400 state->string = string;
18401
18402 if (pattern->repeat_count) {
18403 if (pattern->repeats_storage) {
18404 state->repeats = pattern->repeats_storage;
18405 pattern->repeats_storage = NULL;
18406 } else {
18407 state->repeats = (RE_RepeatData*)re_alloc(pattern->repeat_count *
18408 sizeof(RE_RepeatData));
18409 if (!state->repeats)
18410 goto error;
18411 memset(state->repeats, 0, pattern->repeat_count *
18412 sizeof(RE_RepeatData));
18413 }
18414 }
18415
18416 if (pattern->fuzzy_count) {
18417 state->fuzzy_guards = (RE_FuzzyGuards*)re_alloc(pattern->fuzzy_count *
18418 sizeof(RE_FuzzyGuards));
18419 if (!state->fuzzy_guards)
18420 goto error;
18421 memset(state->fuzzy_guards, 0, pattern->fuzzy_count *
18422 sizeof(RE_FuzzyGuards));
18423 }
18424
18425 state->fuzzy_changes.capacity = 0;
18426 state->fuzzy_changes.count = 0;
18427 state->fuzzy_changes.items = NULL;
18428
18429 Py_INCREF(state->pattern);
18430 Py_INCREF(state->string);
18431
18432 /* Multithreading is allowed during matching when explicitly enabled or on
18433 * immutable strings.
18434 */
18435 switch (concurrent) {
18436 case RE_CONC_NO:
18437 state->is_multithreaded = FALSE;
18438 break;
18439 case RE_CONC_YES:
18440 state->is_multithreaded = TRUE;
18441 break;
18442 default:
18443 state->is_multithreaded = PyUnicode_Check(string) ||
18444 PyBytes_Check(string);
18445 break;
18446 }
18447
18448 state->timeout = timeout;
18449 state->start_time = timeout == RE_NO_TIMEOUT ? 0 : clock();
18450
18451 /* A state struct can sometimes be shared across threads. In such
18452 * instances, if multithreading is enabled we need to protect the state
18453 * with a lock (mutex) during matching.
18454 */
18455 if (state->is_multithreaded && use_lock)
18456 state->lock = PyThread_allocate_lock();
18457
18458 for (p = 0; p < MAX_SEARCH_POSITIONS; p++)
18459 state->search_positions[p].start_pos = -1;
18460
18461 return TRUE;
18462
18463 error:
18464 re_dealloc(state->group_call_guard_list);
18465 re_dealloc(state->repeats);
18466 dealloc_groups(state->groups, pattern->true_group_count);
18467 re_dealloc(state->fuzzy_guards);
18468 state->repeats = NULL;
18469 state->groups = NULL;
18470 state->fuzzy_guards = NULL;
18471 return FALSE;
18472 }
18473
18474 /* Checks that the string has the same charsize as the pattern. */
18475 Py_LOCAL_INLINE(BOOL) check_compatible(PatternObject* pattern, BOOL unicode) {
18476 if (PyBytes_Check(pattern->pattern)) {
18477 if (unicode) {
18478 PyErr_SetString(PyExc_TypeError,
18479 "cannot use a bytes pattern on a string-like object");
18480 return FALSE;
18481 }
18482 } else {
18483 if (!unicode) {
18484 PyErr_SetString(PyExc_TypeError,
18485 "cannot use a string pattern on a bytes-like object");
18486 return FALSE;
18487 }
18488 }
18489
18490 return TRUE;
18491 }
18492
18493 /* Releases the string's buffer, if necessary. */
18494 Py_LOCAL_INLINE(void) release_buffer(RE_StringInfo* str_info) {
18495 if (str_info->should_release)
18496 PyBuffer_Release(&str_info->view);
18497 }
18498
18499 /* Initialises a state object. */
18500 Py_LOCAL_INLINE(BOOL) state_init(RE_State* state, PatternObject* pattern,
18501 PyObject* string, Py_ssize_t start, Py_ssize_t end, BOOL overlapped, int
18502 concurrent, BOOL partial, BOOL use_lock, BOOL visible_captures, BOOL
18503 match_all, Py_ssize_t timeout) {
18504 RE_StringInfo str_info;
18505
18506 /* Get the string to search or match. */
18507 if (!get_string(string, &str_info))
18508 return FALSE;
18509
18510 /* If we fail to initialise the state then we need to release the buffer if
18511 * the string is a buffer object.
18512 */
18513 if (!check_compatible(pattern, str_info.is_unicode)) {
18514 release_buffer(&str_info);
18515 return FALSE;
18516 }
18517
18518 if (!state_init_2(state, pattern, string, &str_info, start, end,
18519 overlapped, concurrent, partial, use_lock, visible_captures, match_all,
18520 timeout)) {
18521 release_buffer(&str_info);
18522 return FALSE;
18523 }
18524
18525 /* The state has been initialised successfully, so now the state has the
18526 * responsibility of releasing the buffer if the string is a buffer object.
18527 */
18528 return TRUE;
18529 }
18530
18531 /* Deallocates repeat data. */
18532 Py_LOCAL_INLINE(void) dealloc_repeats(RE_RepeatData* repeats, size_t
18533 repeat_count) {
18534 size_t i;
18535
18536 if (!repeats)
18537 return;
18538
18539 for (i = 0; i < repeat_count; i++) {
18540 re_dealloc(repeats[i].body_guard_list.spans);
18541 re_dealloc(repeats[i].tail_guard_list.spans);
18542 }
18543
18544 re_dealloc(repeats);
18545 }
18546
18547 /* Deallocates fuzzy guards. */
18548 Py_LOCAL_INLINE(void) dealloc_fuzzy_guards(RE_FuzzyGuards* guards, size_t
18549 fuzzy_count) {
18550 size_t i;
18551
18552 if (!guards)
18553 return;
18554
18555 for (i = 0; i < fuzzy_count; i++) {
18556 re_dealloc(guards[i].body_guard_list.spans);
18557 re_dealloc(guards[i].tail_guard_list.spans);
18558 }
18559
18560 re_dealloc(guards);
18561 }
18562
18563 /* Finalises a state object, discarding its contents. */
18564 Py_LOCAL_INLINE(void) state_fini(RE_State* state) {
18565 PatternObject* pattern;
18566 size_t i;
18567
18568 /* Discard the lock (mutex) if there's one. */
18569 if (state->lock)
18570 PyThread_free_lock(state->lock);
18571
18572 pattern = state->pattern;
18573
18574 /* If possible cache the storage of bstack. */
18575 if (!pattern->stack_storage) {
18576 pattern->stack_storage = state->bstack.storage;
18577 pattern->stack_capacity = state->bstack.capacity;
18578 state->bstack.storage = NULL;
18579 state->bstack.capacity = 0;
18580 state->bstack.count = 0;
18581
18582 /* Limit the size of the cached storage to <= 64KB. */
18583 if (pattern->stack_capacity > 0x10000) {
18584 BYTE* new_storage;
18585
18586 new_storage = re_realloc(pattern->stack_storage, 0x10000);
18587 if (new_storage) {
18588 pattern->stack_storage = new_storage;
18589 pattern->stack_capacity = 0x10000;
18590 }
18591 }
18592 }
18593
18594 /* Clear the stacks. */
18595 ByteStack_fini(state, &state->sstack);
18596 ByteStack_fini(state, &state->bstack);
18597 ByteStack_fini(state, &state->pstack);
18598
18599 if (state->best_match_groups)
18600 dealloc_groups(state->best_match_groups, pattern->true_group_count);
18601
18602 if (pattern->groups_storage)
18603 dealloc_groups(state->groups, pattern->true_group_count);
18604 else
18605 pattern->groups_storage = state->groups;
18606
18607 if (pattern->repeats_storage)
18608 dealloc_repeats(state->repeats, pattern->repeat_count);
18609 else
18610 pattern->repeats_storage = state->repeats;
18611
18612 for (i = 0; i < pattern->call_ref_info_count; i++)
18613 re_dealloc(state->group_call_guard_list[i].spans);
18614
18615 if (state->group_call_guard_list)
18616 re_dealloc(state->group_call_guard_list);
18617
18618 if (state->fuzzy_guards)
18619 dealloc_fuzzy_guards(state->fuzzy_guards, pattern->fuzzy_count);
18620
18621 re_dealloc(state->fuzzy_changes.items);
18622
18623 Py_DECREF(state->pattern);
18624 Py_DECREF(state->string);
18625
18626 if (state->should_release)
18627 PyBuffer_Release(&state->view);
18628 }
18629
18630 /* Converts a string index to an integer.
18631 *
18632 * If the index is None then the default will be returned.
18633 */
18634 Py_LOCAL_INLINE(Py_ssize_t) as_string_index(PyObject* obj, Py_ssize_t def) {
18635 Py_ssize_t value;
18636
18637 if (obj == Py_None)
18638 return def;
18639
18640 value = PyLong_AsLong(obj);
18641 if (!(value == -1 && PyErr_Occurred()))
18642 return value;
18643
18644 set_error(RE_ERROR_INDEX, NULL);
18645 return -1;
18646 }
18647
18648 /* Deallocates a MatchObject. */
18649 static void match_dealloc(PyObject* self_) {
18650 MatchObject* self;
18651
18652 self = (MatchObject*)self_;
18653
18654 Py_XDECREF(self->string);
18655 Py_XDECREF(self->substring);
18656 Py_DECREF(self->pattern);
18657 if (self->groups)
18658 re_dealloc(self->groups);
18659 if (self->fuzzy_changes)
18660 re_dealloc(self->fuzzy_changes);
18661 Py_XDECREF(self->regs);
18662 PyObject_DEL(self);
18663 }
18664
18665 /* Ensures that the string is the immutable Unicode string or bytestring.
18666 * DECREFs the original string if a copy is returned.
18667 */
18668 Py_LOCAL_INLINE(PyObject*) ensure_immutable(PyObject* string) {
18669 PyObject* new_string;
18670
18671 if (PyUnicode_CheckExact(string) || PyBytes_CheckExact(string))
18672 return string;
18673
18674 if (PyUnicode_Check(string))
18675 new_string = PyUnicode_FromObject(string);
18676 else
18677 new_string = PyBytes_FromObject(string);
18678
18679 Py_DECREF(string);
18680
18681 return new_string;
18682 }
18683
18684 /* Restricts a value to a range. */
18685 Py_LOCAL_INLINE(Py_ssize_t) limited_range(Py_ssize_t value, Py_ssize_t lower,
18686 Py_ssize_t upper) {
18687 if (value < lower)
18688 return lower;
18689
18690 if (value > upper)
18691 return upper;
18692
18693 return value;
18694 }
18695
18696 /* Gets a slice from a Unicode string. */
18697 Py_LOCAL_INLINE(PyObject*) unicode_slice(PyObject* string, Py_ssize_t start,
18698 Py_ssize_t end) {
18699 Py_ssize_t length;
18700
18701 length = PyUnicode_GET_LENGTH(string);
18702 start = limited_range(start, 0, length);
18703 end = limited_range(end, 0, length);
18704
18705 return PyUnicode_Substring(string, start, end);
18706 }
18707
18708 /* Gets a slice from a bytestring. */
18709 Py_LOCAL_INLINE(PyObject*) bytes_slice(PyObject* string, Py_ssize_t start,
18710 Py_ssize_t end) {
18711 Py_ssize_t length;
18712 char* buffer;
18713
18714 length = PyBytes_GET_SIZE(string);
18715 start = limited_range(start, 0, length);
18716 end = limited_range(end, 0, length);
18717
18718 buffer = PyBytes_AsString(string);
18719
18720 return PyBytes_FromStringAndSize(buffer + start, end - start);
18721 }
18722
18723 /* Gets a slice from a string, returning either a Unicode string or a
18724 * bytestring.
18725 */
18726 Py_LOCAL_INLINE(PyObject*) get_slice(PyObject* string, Py_ssize_t start,
18727 Py_ssize_t end) {
18728 if (PyUnicode_Check(string))
18729 return unicode_slice(string, start, end);
18730
18731 if (PyBytes_Check(string))
18732 return bytes_slice(string, start, end);
18733
18734 return ensure_immutable(PySequence_GetSlice(string, start, end));
18735 }
18736
18737 /* Gets a MatchObject's group by integer index. */
18738 static PyObject* match_get_group_by_index(MatchObject* self, Py_ssize_t index,
18739 PyObject* def) {
18740 RE_GroupData* group;
18741 RE_GroupSpan* span;
18742
18743 if (index < 0 || (size_t)index > self->group_count) {
18744 /* Raise error if we were given a bad group number. */
18745 set_error(RE_ERROR_NO_SUCH_GROUP, NULL);
18746 return NULL;
18747 }
18748
18749 if (index == 0)
18750 return get_slice(self->substring, self->match_start -
18751 self->substring_offset, self->match_end - self->substring_offset);
18752
18753 /* Capture group indexes are 1-based (excluding group 0, which is the
18754 * entire matched string).
18755 */
18756 group = &self->groups[index - 1];
18757
18758 if (group->current < 0) {
18759 /* Return default value if the string or group is undefined. */
18760 Py_INCREF(def);
18761 return def;
18762 }
18763
18764 span = &group->captures[group->current];
18765
18766 return get_slice(self->substring, span->start - self->substring_offset,
18767 span->end - self->substring_offset);
18768 }
18769
18770 /* Gets a MatchObject's start by integer index. */
18771 static PyObject* match_get_start_by_index(MatchObject* self, Py_ssize_t index)
18772 {
18773 RE_GroupData* group;
18774 RE_GroupSpan* span;
18775
18776 if (index < 0 || (size_t)index > self->group_count) {
18777 /* Raise error if we were given a bad group number. */
18778 set_error(RE_ERROR_NO_SUCH_GROUP, NULL);
18779 return NULL;
18780 }
18781
18782 if (index == 0)
18783 return Py_BuildValue("n", self->match_start);
18784
18785 /* Capture group indexes are 1-based (excluding group 0, which is the
18786 * entire matched string).
18787 */
18788 group = &self->groups[index - 1];
18789
18790 if (group->current < 0)
18791 return Py_BuildValue("n", (Py_ssize_t)-1);
18792
18793 span = &group->captures[group->current];
18794
18795 return Py_BuildValue("n", span->start);
18796 }
18797
18798 /* Gets a MatchObject's starts by integer index. */
18799 static PyObject* match_get_starts_by_index(MatchObject* self, Py_ssize_t index)
18800 {
18801 RE_GroupData* group;
18802 PyObject* result;
18803 PyObject* item;
18804 size_t i;
18805
18806 if (index < 0 || (size_t)index > self->group_count) {
18807 /* Raise error if we were given a bad group number. */
18808 set_error(RE_ERROR_NO_SUCH_GROUP, NULL);
18809 return NULL;
18810 }
18811
18812 if (index == 0) {
18813 result = PyList_New(1);
18814 if (!result)
18815 return NULL;
18816
18817 item = Py_BuildValue("n", self->match_start);
18818 if (!item)
18819 goto error;
18820
18821 /* PyList_SetItem borrows the reference. */
18822 PyList_SetItem(result, 0, item);
18823
18824 return result;
18825 }
18826
18827 /* Capture group indexes are 1-based (excluding group 0, which is the
18828 * entire matched string).
18829 */
18830 group = &self->groups[index - 1];
18831
18832 result = PyList_New((Py_ssize_t)group->count);
18833 if (!result)
18834 return NULL;
18835
18836 for (i = 0; i < group->count; i++) {
18837 item = Py_BuildValue("n", group->captures[i].start);
18838 if (!item)
18839 goto error;
18840
18841 /* PyList_SetItem borrows the reference. */
18842 PyList_SetItem(result, i, item);
18843 }
18844
18845 return result;
18846
18847 error:
18848 Py_DECREF(result);
18849 return NULL;
18850 }
18851
18852 /* Gets a MatchObject's end by integer index. */
18853 static PyObject* match_get_end_by_index(MatchObject* self, Py_ssize_t index) {
18854 RE_GroupData* group;
18855 RE_GroupSpan* span;
18856
18857 if (index < 0 || (size_t)index > self->group_count) {
18858 /* Raise error if we were given a bad group number. */
18859 set_error(RE_ERROR_NO_SUCH_GROUP, NULL);
18860 return NULL;
18861 }
18862
18863 if (index == 0)
18864 return Py_BuildValue("n", self->match_end);
18865
18866 /* Capture group indexes are 1-based (excluding group 0, which is the
18867 * entire matched string).
18868 */
18869 group = &self->groups[index - 1];
18870
18871 if (group->current < 0)
18872 return Py_BuildValue("n", (Py_ssize_t)-1);
18873
18874 span = &group->captures[group->current];
18875
18876 return Py_BuildValue("n", span->end);
18877 }
18878
18879 /* Gets a MatchObject's ends by integer index. */
18880 static PyObject* match_get_ends_by_index(MatchObject* self, Py_ssize_t index) {
18881 RE_GroupData* group;
18882 PyObject* result;
18883 PyObject* item;
18884 size_t i;
18885
18886 if (index < 0 || (size_t)index > self->group_count) {
18887 /* Raise error if we were given a bad group number. */
18888 set_error(RE_ERROR_NO_SUCH_GROUP, NULL);
18889 return NULL;
18890 }
18891
18892 if (index == 0) {
18893 result = PyList_New(1);
18894 if (!result)
18895 return NULL;
18896
18897 item = Py_BuildValue("n", self->match_end);
18898 if (!item)
18899 goto error;
18900
18901 /* PyList_SetItem borrows the reference. */
18902 PyList_SetItem(result, 0, item);
18903
18904 return result;
18905 }
18906
18907 /* Capture group indexes are 1-based (excluding group 0, which is the
18908 * entire matched string).
18909 */
18910 group = &self->groups[index - 1];
18911
18912 result = PyList_New((Py_ssize_t)group->count);
18913 if (!result)
18914 return NULL;
18915
18916 for (i = 0; i < group->count; i++) {
18917 item = Py_BuildValue("n", group->captures[i].end);
18918 if (!item)
18919 goto error;
18920
18921 /* PyList_SetItem borrows the reference. */
18922 PyList_SetItem(result, i, item);
18923 }
18924
18925 return result;
18926
18927 error:
18928 Py_DECREF(result);
18929 return NULL;
18930 }
18931
18932 /* Gets a MatchObject's span by integer index. */
18933 static PyObject* match_get_span_by_index(MatchObject* self, Py_ssize_t index) {
18934 RE_GroupData* group;
18935 RE_GroupSpan* span;
18936
18937 if (index < 0 || (size_t)index > self->group_count) {
18938 /* Raise error if we were given a bad group number. */
18939 set_error(RE_ERROR_NO_SUCH_GROUP, NULL);
18940 return NULL;
18941 }
18942
18943 if (index == 0)
18944 return Py_BuildValue("nn", self->match_start, self->match_end);
18945
18946 /* Capture group indexes are 1-based (excluding group 0, which is the
18947 * entire matched string).
18948 */
18949 group = &self->groups[index - 1];
18950
18951 if (group->current < 0)
18952 return Py_BuildValue("nn", (Py_ssize_t)-1, (Py_ssize_t)-1);
18953
18954 span = &group->captures[group->current];
18955
18956 return Py_BuildValue("nn", span->start, span->end);
18957 }
18958
18959 /* Gets a MatchObject's spans by integer index. */
18960 static PyObject* match_get_spans_by_index(MatchObject* self, Py_ssize_t index)
18961 {
18962 PyObject* result;
18963 PyObject* item;
18964 RE_GroupData* group;
18965 size_t i;
18966
18967 if (index < 0 || (size_t)index > self->group_count) {
18968 /* Raise error if we were given a bad group number. */
18969 set_error(RE_ERROR_NO_SUCH_GROUP, NULL);
18970 return NULL;
18971 }
18972
18973 if (index == 0) {
18974 result = PyList_New(1);
18975 if (!result)
18976 return NULL;
18977
18978 item = Py_BuildValue("nn", self->match_start, self->match_end);
18979 if (!item)
18980 goto error;
18981
18982 /* PyList_SetItem borrows the reference. */
18983 PyList_SetItem(result, 0, item);
18984
18985 return result;
18986 }
18987
18988 /* Capture group indexes are 1-based (excluding group 0, which is the
18989 * entire matched string).
18990 */
18991 group = &self->groups[index - 1];
18992
18993 result = PyList_New((Py_ssize_t)group->count);
18994 if (!result)
18995 return NULL;
18996
18997 for (i = 0; i < group->count; i++) {
18998 item = Py_BuildValue("nn", group->captures[i].start,
18999 group->captures[i].end);
19000 if (!item)
19001 goto error;
19002
19003 /* PyList_SetItem borrows the reference. */
19004 PyList_SetItem(result, i, item);
19005 }
19006
19007 return result;
19008
19009 error:
19010 Py_DECREF(result);
19011 return NULL;
19012 }
19013
19014 /* Gets a MatchObject's captures by integer index. */
19015 static PyObject* match_get_captures_by_index(MatchObject* self, Py_ssize_t
19016 index) {
19017 PyObject* result;
19018 PyObject* slice;
19019 RE_GroupData* group;
19020 size_t i;
19021
19022 if (index < 0 || (size_t)index > self->group_count) {
19023 /* Raise error if we were given a bad group number. */
19024 set_error(RE_ERROR_NO_SUCH_GROUP, NULL);
19025 return NULL;
19026 }
19027
19028 if (index == 0) {
19029 result = PyList_New(1);
19030 if (!result)
19031 return NULL;
19032
19033 slice = get_slice(self->substring, self->match_start -
19034 self->substring_offset, self->match_end - self->substring_offset);
19035 if (!slice)
19036 goto error;
19037
19038 /* PyList_SetItem borrows the reference. */
19039 PyList_SetItem(result, 0, slice);
19040
19041 return result;
19042 }
19043
19044 /* Capture group indexes are 1-based (excluding group 0, which is the
19045 * entire matched string).
19046 */
19047 group = &self->groups[index - 1];
19048
19049 result = PyList_New((Py_ssize_t)group->count);
19050 if (!result)
19051 return NULL;
19052
19053 for (i = 0; i < group->count; i++) {
19054 slice = get_slice(self->substring, group->captures[i].start -
19055 self->substring_offset, group->captures[i].end -
19056 self->substring_offset);
19057 if (!slice)
19058 goto error;
19059
19060 /* PyList_SetItem borrows the reference. */
19061 PyList_SetItem(result, i, slice);
19062 }
19063
19064 return result;
19065
19066 error:
19067 Py_DECREF(result);
19068 return NULL;
19069 }
19070
19071 /* Converts a group index to an integer. */
19072 Py_LOCAL_INLINE(Py_ssize_t) as_group_index(PyObject* obj) {
19073 Py_ssize_t value;
19074
19075 value = PyLong_AsLong(obj);
19076 if (!(value == -1 && PyErr_Occurred()))
19077 return value;
19078
19079 set_error(RE_ERROR_INDEX, NULL);
19080 return -1;
19081 }
19082
19083 /* Gets a MatchObject's group index.
19084 *
19085 * The supplied index can be an integer or a string (group name) object.
19086 */
19087 Py_LOCAL_INLINE(Py_ssize_t) match_get_group_index(MatchObject* self, PyObject*
19088 index, BOOL allow_neg) {
19089 Py_ssize_t group;
19090
19091 /* Is the index an integer? */
19092 group = as_group_index(index);
19093 if (!(group == -1 && PyErr_Occurred())) {
19094 Py_ssize_t min_group = 0;
19095
19096 /* Adjust negative indices where valid and allowed. */
19097 if (group < 0 && allow_neg) {
19098 group += (Py_ssize_t)self->group_count + 1;
19099 min_group = 1;
19100 }
19101
19102 if (min_group <= group && (size_t)group <= self->group_count)
19103 return group;
19104
19105 return -1;
19106 }
19107
19108 PyErr_Clear();
19109
19110 /* The index might be a group name. */
19111 if (self->pattern->groupindex) {
19112 /* Look up the name. */
19113 index = PyObject_GetItem(self->pattern->groupindex, index);
19114 if (index) {
19115 /* Check that we have an integer. */
19116 group = as_group_index(index);
19117 Py_DECREF(index);
19118 if (!(group == -1 && PyErr_Occurred()))
19119 return group;
19120 }
19121 }
19122
19123 PyErr_Clear();
19124 return -1;
19125 }
19126
19127 /* Gets a MatchObject's group by object index. */
19128 Py_LOCAL_INLINE(PyObject*) match_get_group(MatchObject* self, PyObject* index,
19129 PyObject* def, BOOL allow_neg) {
19130 /* Check that the index is an integer or a string. */
19131 if (PyLong_Check(index) || PyUnicode_Check(index) || PyBytes_Check(index))
19132 return match_get_group_by_index(self, match_get_group_index(self,
19133 index, allow_neg), def);
19134
19135 set_error(RE_ERROR_GROUP_INDEX_TYPE, index);
19136 return NULL;
19137 }
19138
19139 /* Gets info from a MatchObject by object index. */
19140 Py_LOCAL_INLINE(PyObject*) get_by_arg(MatchObject* self, PyObject* index,
19141 RE_GetByIndexFunc get_by_index) {
19142 /* Check that the index is an integer or a string. */
19143 if (PyLong_Check(index) || PyUnicode_Check(index) || PyBytes_Check(index))
19144 return get_by_index(self, match_get_group_index(self, index, FALSE));
19145
19146 set_error(RE_ERROR_GROUP_INDEX_TYPE, index);
19147 return NULL;
19148 }
19149
19150 /* MatchObject's 'group' method. */
19151 static PyObject* match_group(MatchObject* self, PyObject* args) {
19152 Py_ssize_t size;
19153 PyObject* result;
19154 Py_ssize_t i;
19155
19156 size = PyTuple_GET_SIZE(args);
19157
19158 switch (size) {
19159 case 0:
19160 /* group() */
19161 result = match_get_group_by_index(self, 0, Py_None);
19162 break;
19163 case 1:
19164 /* group(x). PyTuple_GET_ITEM borrows the reference. */
19165 result = match_get_group(self, PyTuple_GET_ITEM(args, 0), Py_None,
19166 FALSE);
19167 break;
19168 default:
19169 /* group(x, y, z, ...) */
19170 /* Fetch multiple items. */
19171 result = PyTuple_New(size);
19172 if (!result)
19173 return NULL;
19174
19175 for (i = 0; i < size; i++) {
19176 PyObject* item;
19177
19178 /* PyTuple_GET_ITEM borrows the reference. */
19179 item = match_get_group(self, PyTuple_GET_ITEM(args, i), Py_None,
19180 FALSE);
19181 if (!item) {
19182 Py_DECREF(result);
19183 return NULL;
19184 }
19185
19186 /* PyTuple_SET_ITEM borrows the reference. */
19187 PyTuple_SET_ITEM(result, i, item);
19188 }
19189 break;
19190 }
19191
19192 return result;
19193 }
19194
19195 /* Generic method for getting info from a MatchObject. */
19196 Py_LOCAL_INLINE(PyObject*) get_from_match(MatchObject* self, PyObject* args,
19197 RE_GetByIndexFunc get_by_index) {
19198 Py_ssize_t size;
19199 PyObject* result;
19200 Py_ssize_t i;
19201
19202 size = PyTuple_GET_SIZE(args);
19203
19204 switch (size) {
19205 case 0:
19206 /* get() */
19207 result = get_by_index(self, 0);
19208 break;
19209 case 1:
19210 /* get(x). PyTuple_GET_ITEM borrows the reference. */
19211 result = get_by_arg(self, PyTuple_GET_ITEM(args, 0), get_by_index);
19212 break;
19213 default:
19214 /* get(x, y, z, ...) */
19215 /* Fetch multiple items. */
19216 result = PyTuple_New(size);
19217 if (!result)
19218 return NULL;
19219
19220 for (i = 0; i < size; i++) {
19221 PyObject* item;
19222
19223 /* PyTuple_GET_ITEM borrows the reference. */
19224 item = get_by_arg(self, PyTuple_GET_ITEM(args, i), get_by_index);
19225 if (!item) {
19226 Py_DECREF(result);
19227 return NULL;
19228 }
19229
19230 /* PyTuple_SET_ITEM borrows the reference. */
19231 PyTuple_SET_ITEM(result, i, item);
19232 }
19233 break;
19234 }
19235
19236 return result;
19237 }
19238
19239 /* MatchObject's 'start' method. */
19240 static PyObject* match_start(MatchObject* self, PyObject* args) {
19241 return get_from_match(self, args, match_get_start_by_index);
19242 }
19243
19244 /* MatchObject's 'starts' method. */
19245 static PyObject* match_starts(MatchObject* self, PyObject* args) {
19246 return get_from_match(self, args, match_get_starts_by_index);
19247 }
19248
19249 /* MatchObject's 'end' method. */
19250 static PyObject* match_end(MatchObject* self, PyObject* args) {
19251 return get_from_match(self, args, match_get_end_by_index);
19252 }
19253
19254 /* MatchObject's 'ends' method. */
19255 static PyObject* match_ends(MatchObject* self, PyObject* args) {
19256 return get_from_match(self, args, match_get_ends_by_index);
19257 }
19258
19259 /* MatchObject's 'span' method. */
19260 static PyObject* match_span(MatchObject* self, PyObject* args) {
19261 return get_from_match(self, args, match_get_span_by_index);
19262 }
19263
19264 /* MatchObject's 'spans' method. */
19265 static PyObject* match_spans(MatchObject* self, PyObject* args) {
19266 return get_from_match(self, args, match_get_spans_by_index);
19267 }
19268
19269 /* MatchObject's 'allspans' method. */
19270 static PyObject* match_allspans(MatchObject* self) {
19271 PyObject* list;
19272 size_t i;
19273 PyObject* result;
19274
19275 list = PyList_New(0);
19276 if (!list)
19277 return NULL;
19278
19279 /* Include all the groups, including group 0 (the whole match). */
19280 for (i = 0; i <= self->group_count; i++) {
19281 PyObject* span;
19282 int status;
19283
19284 span = match_get_spans_by_index(self, i);
19285 if (!span)
19286 goto error;
19287
19288 status = PyList_Append(list, span);
19289 Py_DECREF(span);
19290 if (status < 0)
19291 goto error;
19292 }
19293
19294 result = PyList_AsTuple(list);
19295 Py_DECREF(list);
19296 return result;
19297
19298 error:
19299 Py_DECREF(list);
19300 return NULL;
19301 }
19302
19303 /* MatchObject's 'captures' method. */
19304 static PyObject* match_captures(MatchObject* self, PyObject* args) {
19305 return get_from_match(self, args, match_get_captures_by_index);
19306 }
19307
19308 /* MatchObject's 'allcaptures' method. */
19309 static PyObject* match_allcaptures(MatchObject* self) {
19310 PyObject* list;
19311 size_t i;
19312 PyObject* result;
19313
19314 list = PyList_New(0);
19315 if (!list)
19316 return NULL;
19317
19318 /* Include all the groups, including group 0 (the whole match). */
19319 for (i = 0; i <= self->group_count; i++) {
19320 PyObject* span;
19321 int status;
19322
19323 span = match_get_captures_by_index(self, i);
19324 if (!span)
19325 goto error;
19326
19327 status = PyList_Append(list, span);
19328 Py_DECREF(span);
19329 if (status < 0)
19330 goto error;
19331 }
19332
19333 result = PyList_AsTuple(list);
19334 Py_DECREF(list);
19335 return result;
19336
19337 error:
19338 Py_DECREF(list);
19339 return NULL;
19340 }
19341
19342 /* MatchObject's 'groups' method. */
19343 static PyObject* match_groups(MatchObject* self, PyObject* args, PyObject*
19344 kwargs) {
19345 PyObject* result;
19346 size_t g;
19347
19348 PyObject* def = Py_None;
19349 static char* kwlist[] = { "default", NULL };
19350 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O:groups", kwlist, &def))
19351 return NULL;
19352
19353 result = PyTuple_New((Py_ssize_t)self->group_count);
19354 if (!result)
19355 return NULL;
19356
19357 /* Group 0 is the entire matched portion of the string. */
19358 for (g = 0; g < self->group_count; g++) {
19359 PyObject* item;
19360
19361 item = match_get_group_by_index(self, (Py_ssize_t)g + 1, def);
19362 if (!item)
19363 goto error;
19364
19365 /* PyTuple_SET_ITEM borrows the reference. */
19366 PyTuple_SET_ITEM(result, g, item);
19367 }
19368
19369 return result;
19370
19371 error:
19372 Py_DECREF(result);
19373 return NULL;
19374 }
19375
19376 /* MatchObject's 'groupdict' method. */
19377 static PyObject* match_groupdict(MatchObject* self, PyObject* args, PyObject*
19378 kwargs) {
19379 PyObject* result;
19380 PyObject* keys;
19381 Py_ssize_t g;
19382
19383 PyObject* def = Py_None;
19384 static char* kwlist[] = { "default", NULL };
19385 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O:groupdict", kwlist,
19386 &def))
19387 return NULL;
19388
19389 result = PyDict_New();
19390 if (!result || !self->pattern->groupindex)
19391 return result;
19392
19393 keys = PyMapping_Keys(self->pattern->groupindex);
19394 if (!keys)
19395 goto failed;
19396
19397 for (g = 0; g < PyList_Size(keys); g++) {
19398 PyObject* key;
19399 PyObject* value;
19400 int status;
19401
19402 /* PyList_GetItem borrows a reference. */
19403 key = PyList_GetItem(keys, g);
19404 if (!key)
19405 goto failed;
19406
19407 value = match_get_group(self, key, def, FALSE);
19408 if (!value)
19409 goto failed;
19410
19411 status = PyDict_SetItem(result, key, value);
19412 Py_DECREF(value);
19413 if (status < 0)
19414 goto failed;
19415 }
19416
19417 Py_DECREF(keys);
19418
19419 return result;
19420
19421 failed:
19422 Py_XDECREF(keys);
19423 Py_DECREF(result);
19424 return NULL;
19425 }
19426
19427 /* MatchObject's 'capturesdict' method. */
19428 static PyObject* match_capturesdict(MatchObject* self) {
19429 PyObject* result;
19430 PyObject* keys;
19431 Py_ssize_t g;
19432
19433 result = PyDict_New();
19434 if (!result || !self->pattern->groupindex)
19435 return result;
19436
19437 keys = PyMapping_Keys(self->pattern->groupindex);
19438 if (!keys)
19439 goto failed;
19440
19441 for (g = 0; g < PyList_Size(keys); g++) {
19442 PyObject* key;
19443 Py_ssize_t group;
19444 PyObject* captures;
19445 int status;
19446
19447 /* PyList_GetItem borrows a reference. */
19448 key = PyList_GetItem(keys, g);
19449 if (!key)
19450 goto failed;
19451
19452 group = match_get_group_index(self, key, FALSE);
19453 if (group < 0)
19454 goto failed;
19455
19456 captures = match_get_captures_by_index(self, group);
19457 if (!captures)
19458 goto failed;
19459
19460 status = PyDict_SetItem(result, key, captures);
19461 Py_DECREF(captures);
19462 if (status < 0)
19463 goto failed;
19464 }
19465
19466 Py_DECREF(keys);
19467
19468 return result;
19469
19470 failed:
19471 Py_XDECREF(keys);
19472 Py_DECREF(result);
19473 return NULL;
19474 }
19475
19476 /* Gets a Python object by name from a named module. */
19477 Py_LOCAL_INLINE(PyObject*) get_object(char* module_name, char* object_name) {
19478 PyObject* module;
19479 PyObject* object;
19480
19481 module = PyImport_ImportModule(module_name);
19482 if (!module)
19483 return NULL;
19484
19485 object = PyObject_GetAttrString(module, object_name);
19486 Py_DECREF(module);
19487
19488 return object;
19489 }
19490
19491 /* Calls a function in a module. */
19492 Py_LOCAL_INLINE(PyObject*) call(char* module_name, char* function_name,
19493 PyObject* args) {
19494 PyObject* function;
19495 PyObject* result;
19496
19497 if (!args)
19498 return NULL;
19499
19500 function = get_object(module_name, function_name);
19501 if (!function)
19502 return NULL;
19503
19504 result = PyObject_CallObject(function, args);
19505 Py_DECREF(function);
19506 Py_DECREF(args);
19507
19508 return result;
19509 }
19510
19511 /* Gets a replacement item from the replacement list.
19512 *
19513 * The replacement item could be a string literal or a group.
19514 */
19515 Py_LOCAL_INLINE(PyObject*) get_match_replacement(MatchObject* self, PyObject*
19516 item, size_t group_count) {
19517 Py_ssize_t index;
19518
19519 if (PyUnicode_Check(item) || PyBytes_Check(item)) {
19520 /* It's a literal, which can be added directly to the list. */
19521
19522 /* ensure_immutable will DECREF the original item if it has to make an
19523 * immutable copy, but that original item might have a borrowed
19524 * reference, so we must INCREF it first in order to ensure it won't be
19525 * destroyed.
19526 */
19527 Py_INCREF(item);
19528 item = ensure_immutable(item);
19529 return item;
19530 }
19531
19532 /* Is it a group reference? */
19533 index = as_group_index(item);
19534 if (index == -1 && PyErr_Occurred()) {
19535 /* Not a group either! */
19536 set_error(RE_ERROR_REPLACEMENT, NULL);
19537 return NULL;
19538 }
19539
19540 if (index == 0) {
19541 /* The entire matched portion of the string. */
19542 return get_slice(self->substring, self->match_start -
19543 self->substring_offset, self->match_end - self->substring_offset);
19544 } else if (index >= 1 && (size_t)index <= group_count) {
19545 /* A group. If it didn't match then return None instead. */
19546 RE_GroupData* group;
19547
19548 group = &self->groups[index - 1];
19549
19550 if (group->current >= 0) {
19551 RE_GroupSpan* span;
19552
19553 span = &group->captures[group->current];
19554
19555 return get_slice(self->substring, span->start -
19556 self->substring_offset, span->end - self->substring_offset);
19557 } else
19558 Py_RETURN_NONE;
19559 } else {
19560 /* No such group. */
19561 set_error(RE_ERROR_NO_SUCH_GROUP, NULL);
19562 return NULL;
19563 }
19564 }
19565
19566 /* Initialises the join list. */
19567 Py_LOCAL_INLINE(void) init_join_list(RE_JoinInfo* join_info, BOOL reversed,
19568 BOOL is_unicode) {
19569 join_info->list = NULL;
19570 join_info->item = NULL;
19571 join_info->reversed = reversed;
19572 join_info->is_unicode = is_unicode;
19573 }
19574
19575 /* Adds an item to the join list. */
19576 Py_LOCAL_INLINE(int) add_to_join_list(RE_JoinInfo* join_info, PyObject* item) {
19577 PyObject* new_item;
19578 int status;
19579
19580 if (join_info->is_unicode) {
19581 if (PyUnicode_CheckExact(item)) {
19582 new_item = item;
19583 Py_INCREF(new_item);
19584 } else {
19585 new_item = PyUnicode_FromObject(item);
19586 if (!new_item) {
19587 set_error(RE_ERROR_NOT_UNICODE, item);
19588 return RE_ERROR_NOT_UNICODE;
19589 }
19590 }
19591 } else {
19592 if (PyBytes_CheckExact(item)) {
19593 new_item = item;
19594 Py_INCREF(new_item);
19595 } else {
19596 new_item = PyBytes_FromObject(item);
19597 if (!new_item) {
19598 set_error(RE_ERROR_NOT_BYTES, item);
19599 return RE_ERROR_NOT_BYTES;
19600 }
19601 }
19602 }
19603
19604 /* If the list already exists then just add the item to it. */
19605 if (join_info->list) {
19606 status = PyList_Append(join_info->list, new_item);
19607 if (status < 0)
19608 goto error;
19609
19610 Py_DECREF(new_item);
19611 return status;
19612 }
19613
19614 /* If we already have an item then we now have 2(!) and we need to put them
19615 * into a list.
19616 */
19617 if (join_info->item) {
19618 join_info->list = PyList_New(2);
19619 if (!join_info->list) {
19620 status = RE_ERROR_MEMORY;
19621 goto error;
19622 }
19623
19624 /* PyList_SetItem borrows the reference. */
19625 PyList_SetItem(join_info->list, 0, join_info->item);
19626 join_info->item = NULL;
19627
19628 /* PyList_SetItem borrows the reference. */
19629 PyList_SetItem(join_info->list, 1, new_item);
19630 return 0;
19631 }
19632
19633 /* This is the first item. */
19634 join_info->item = new_item;
19635
19636 return 0;
19637
19638 error:
19639 Py_DECREF(new_item);
19640 set_error(status, NULL);
19641 return status;
19642 }
19643
19644 /* Clears the join list. */
19645 Py_LOCAL_INLINE(void) clear_join_list(RE_JoinInfo* join_info) {
19646 Py_XDECREF(join_info->list);
19647 Py_XDECREF(join_info->item);
19648 }
19649
19650 /* Joins a list of bytestrings. */
19651 Py_LOCAL_INLINE(PyObject*) join_bytestrings(PyObject* list) {
19652 Py_ssize_t count;
19653 Py_ssize_t length;
19654 Py_ssize_t i;
19655 PyObject *result;
19656 char* to_bytes;
19657
19658 count = PyList_Size(list);
19659
19660 /* How long will the result be? */
19661 length = 0;
19662
19663 for (i = 0; i < count; i++)
19664 length += PyBytes_Size(PyList_GetItem(list, i));
19665
19666 /* Create the resulting bytestring, but uninitialised. */
19667 result = PyBytes_FromStringAndSize(NULL, length);
19668 if (!result)
19669 return NULL;
19670
19671 /* Fill the resulting bytestring. */
19672 to_bytes = PyBytes_AsString(result);
19673 length = 0;
19674
19675 for (i = 0; i < count; i++) {
19676 PyObject* bytestring;
19677 char* from_bytes;
19678 Py_ssize_t from_length;
19679
19680 bytestring = PyList_GetItem(list, i);
19681 from_bytes = PyBytes_AsString(bytestring);
19682 from_length = PyBytes_Size(bytestring);
19683 memmove(to_bytes + length, from_bytes, from_length);
19684 length += from_length;
19685 }
19686
19687 return result;
19688 }
19689
19690 /* Joins a list of strings. */
19691 Py_LOCAL_INLINE(PyObject*) join_strings(PyObject* list) {
19692 PyObject* joiner;
19693 PyObject* result;
19694
19695 joiner = PyUnicode_FromString("");
19696 if (!joiner)
19697 return NULL;
19698
19699 result = PyUnicode_Join(joiner, list);
19700 Py_DECREF(joiner);
19701
19702 return result;
19703 }
19704
19705 /* Joins together a list of strings for pattern_subx. */
19706 Py_LOCAL_INLINE(PyObject*) join_list_info(RE_JoinInfo* join_info) {
19707 /* If the list already exists then just do the join. */
19708 if (join_info->list) {
19709 PyObject* result;
19710
19711 if (join_info->reversed)
19712 /* The list needs to be reversed before being joined. */
19713 PyList_Reverse(join_info->list);
19714
19715 if (join_info->is_unicode)
19716 /* Concatenate the Unicode strings. */
19717 result = join_strings(join_info->list);
19718 else
19719 /* Concatenate the bytestrings. */
19720 result = join_bytestrings(join_info->list);
19721
19722 clear_join_list(join_info);
19723
19724 return result;
19725 }
19726
19727 /* If we have only 1 item, so we'll just return it. */
19728 if (join_info->item)
19729 return join_info->item;
19730
19731 /* There are no items, so return an empty string. */
19732 if (join_info->is_unicode)
19733 return PyUnicode_New(0, 0);
19734 else
19735 return PyBytes_FromString("");
19736 }
19737
19738 /* Checks whether a string replacement is a literal.
19739 *
19740 * To keep it simple we'll say that a literal is a string which can be used
19741 * as-is.
19742 *
19743 * Returns its length if it is a literal, otherwise -1.
19744 */
19745 Py_LOCAL_INLINE(Py_ssize_t) check_replacement_string(PyObject* str_replacement,
19746 unsigned char special_char) {
19747 RE_StringInfo str_info;
19748 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
19749 Py_ssize_t pos;
19750
19751 if (!get_string(str_replacement, &str_info))
19752 return -1;
19753
19754 switch (str_info.charsize) {
19755 case 1:
19756 char_at = bytes1_char_at;
19757 break;
19758 case 2:
19759 char_at = bytes2_char_at;
19760 break;
19761 case 4:
19762 char_at = bytes4_char_at;
19763 break;
19764 default:
19765 release_buffer(&str_info);
19766 return -1;
19767 }
19768
19769 for (pos = 0; pos < str_info.length; pos++) {
19770 if (char_at(str_info.characters, pos) == special_char) {
19771 release_buffer(&str_info);
19772 return -1;
19773 }
19774 }
19775
19776 release_buffer(&str_info);
19777
19778 return str_info.length;
19779 }
19780
19781 /* MatchObject's 'expand' method. */
19782 static PyObject* match_expand(MatchObject* self, PyObject* str_template) {
19783 Py_ssize_t literal_length;
19784 PyObject* replacement;
19785 RE_JoinInfo join_info;
19786 Py_ssize_t size;
19787 Py_ssize_t i;
19788
19789 /* Is the template just a literal? */
19790 literal_length = check_replacement_string(str_template, '\\');
19791 if (literal_length >= 0) {
19792 /* It's a literal. */
19793 Py_INCREF(str_template);
19794 return str_template;
19795 }
19796
19797 /* Hand the template to the template compiler. */
19798 replacement = call("regex.regex", "_compile_replacement_helper",
19799 PyTuple_Pack(2, self->pattern, str_template));
19800 if (!replacement)
19801 return NULL;
19802
19803 init_join_list(&join_info, FALSE, PyUnicode_Check(self->string));
19804
19805 /* Add each part of the template to the list. */
19806 size = PyList_Size(replacement);
19807 for (i = 0; i < size; i++) {
19808 PyObject* item;
19809 PyObject* str_item;
19810
19811 /* PyList_GetItem borrows a reference. */
19812 item = PyList_GetItem(replacement, i);
19813 str_item = get_match_replacement(self, item, self->group_count);
19814 if (!str_item)
19815 goto error;
19816
19817 /* Add to the list. */
19818 if (str_item == Py_None)
19819 Py_DECREF(str_item);
19820 else {
19821 int status;
19822
19823 status = add_to_join_list(&join_info, str_item);
19824 Py_DECREF(str_item);
19825 if (status < 0)
19826 goto error;
19827 }
19828 }
19829
19830 Py_DECREF(replacement);
19831
19832 /* Convert the list to a single string (also cleans up join_info). */
19833 return join_list_info(&join_info);
19834
19835 error:
19836 clear_join_list(&join_info);
19837 Py_DECREF(replacement);
19838 return NULL;
19839 }
19840
19841 static PyTypeObject Capture_Type = {
19842 PyVarObject_HEAD_INIT(NULL,0)
19843 "_regex.Capture",
19844 sizeof(MatchObject)
19845 };
19846
19847 /* Creates a new CaptureObject. */
19848 Py_LOCAL_INLINE(PyObject*) make_capture_object(MatchObject** match_indirect,
19849 Py_ssize_t index) {
19850 CaptureObject* capture;
19851
19852 capture = PyObject_NEW(CaptureObject, &Capture_Type);
19853 if (!capture)
19854 return NULL;
19855
19856 capture->group_index = index;
19857 capture->match_indirect = match_indirect;
19858
19859 return (PyObject*)capture;
19860 }
19861
19862 /* Makes a MatchObject's capture dictionary. */
19863 Py_LOCAL_INLINE(PyObject*) make_capture_dict(MatchObject* match, MatchObject**
19864 match_indirect) {
19865 PyObject* result;
19866 PyObject* keys;
19867 PyObject* values = NULL;
19868 Py_ssize_t g;
19869
19870 result = PyDict_New();
19871 if (!result)
19872 return result;
19873
19874 keys = PyMapping_Keys(match->pattern->groupindex);
19875 if (!keys)
19876 goto failed;
19877
19878 values = PyMapping_Values(match->pattern->groupindex);
19879 if (!values)
19880 goto failed;
19881
19882 for (g = 0; g < PyList_Size(keys); g++) {
19883 PyObject* key;
19884 PyObject* value;
19885 Py_ssize_t v;
19886 int status;
19887
19888 /* PyList_GetItem borrows a reference. */
19889 key = PyList_GetItem(keys, g);
19890 if (!key)
19891 goto failed;
19892
19893 /* PyList_GetItem borrows a reference. */
19894 value = PyList_GetItem(values, g);
19895 if (!value)
19896 goto failed;
19897
19898 v = PyLong_AsLong(value);
19899 if (v == -1 && PyErr_Occurred())
19900 goto failed;
19901
19902 value = make_capture_object(match_indirect, v);
19903 if (!value)
19904 goto failed;
19905
19906 status = PyDict_SetItem(result, key, value);
19907 Py_DECREF(value);
19908 if (status < 0)
19909 goto failed;
19910 }
19911
19912 Py_DECREF(values);
19913 Py_DECREF(keys);
19914
19915 return result;
19916
19917 failed:
19918 Py_XDECREF(values);
19919 Py_XDECREF(keys);
19920 Py_DECREF(result);
19921 return NULL;
19922 }
19923
19924 /* MatchObject's 'expandf' method. */
19925 static PyObject* match_expandf(MatchObject* self, PyObject* str_template) {
19926 PyObject* format_func;
19927 PyObject* args = NULL;
19928 size_t g;
19929 PyObject* kwargs = NULL;
19930 PyObject* result;
19931
19932 format_func = PyObject_GetAttrString(str_template, "format");
19933 if (!format_func)
19934 return NULL;
19935
19936 args = PyTuple_New((Py_ssize_t)self->group_count + 1);
19937 if (!args)
19938 goto error;
19939
19940 for (g = 0; g < self->group_count + 1; g++)
19941 /* PyTuple_SetItem borrows the reference. */
19942 PyTuple_SetItem(args, (Py_ssize_t)g, make_capture_object(&self,
19943 (Py_ssize_t)g));
19944
19945 kwargs = make_capture_dict(self, &self);
19946 if (!kwargs)
19947 goto error;
19948
19949 result = PyObject_Call(format_func, args, kwargs);
19950
19951 Py_DECREF(kwargs);
19952 Py_DECREF(args);
19953 Py_DECREF(format_func);
19954
19955 return result;
19956
19957 error:
19958 Py_XDECREF(args);
19959 Py_DECREF(format_func);
19960 return NULL;
19961 }
19962
19963 Py_LOCAL_INLINE(PyObject*) make_match_copy(MatchObject* self);
19964
19965 /* MatchObject's '__copy__' method. */
19966 static PyObject* match_copy(MatchObject* self, PyObject* unused) {
19967 return make_match_copy(self);
19968 }
19969
19970 /* MatchObject's '__deepcopy__' method. */
19971 static PyObject* match_deepcopy(MatchObject* self, PyObject* memo) {
19972 return make_match_copy(self);
19973 }
19974
19975 /* MatchObject's 'regs' attribute. */
19976 static PyObject* match_regs(MatchObject* self, void* unused) {
19977 PyObject* regs;
19978 PyObject* item;
19979 size_t g;
19980
19981 if (self->regs) {
19982 Py_INCREF(self->regs);
19983
19984 return self->regs;
19985 }
19986
19987 regs = PyTuple_New((Py_ssize_t)self->group_count + 1);
19988 if (!regs)
19989 return NULL;
19990
19991 item = Py_BuildValue("nn", self->match_start, self->match_end);
19992 if (!item)
19993 goto error;
19994
19995 /* PyTuple_SET_ITEM borrows the reference. */
19996 PyTuple_SET_ITEM(regs, 0, item);
19997
19998 for (g = 0; g < self->group_count; g++) {
19999 RE_GroupData* group;
20000
20001 group = &self->groups[g];
20002
20003 if (group->current < 0)
20004 item = Py_BuildValue("nn", (Py_ssize_t)-1, (Py_ssize_t)-1);
20005 else {
20006 RE_GroupSpan* span;
20007
20008 span = &group->captures[group->current];
20009 item = Py_BuildValue("nn", span->start, span->end);
20010 }
20011 if (!item)
20012 goto error;
20013
20014 /* PyTuple_SET_ITEM borrows the reference. */
20015 PyTuple_SET_ITEM(regs, g + 1, item);
20016 }
20017
20018 self->regs = regs;
20019
20020 Py_INCREF(self->regs);
20021
20022 return self->regs;
20023
20024 error:
20025 Py_DECREF(regs);
20026 return NULL;
20027 }
20028
20029 /* MatchObject's slice method. */
20030 Py_LOCAL_INLINE(PyObject*) match_get_group_slice(MatchObject* self, PyObject*
20031 slice) {
20032 Py_ssize_t start;
20033 Py_ssize_t end;
20034 Py_ssize_t step;
20035 Py_ssize_t slice_length;
20036
20037 if (PySlice_GetIndicesEx(slice, (Py_ssize_t)self->group_count + 1, &start,
20038 &end, &step, &slice_length) < 0)
20039 return NULL;
20040
20041 if (slice_length <= 0)
20042 return PyTuple_New(0);
20043 else {
20044 PyObject* result;
20045 Py_ssize_t cur;
20046 Py_ssize_t i;
20047
20048 result = PyTuple_New(slice_length);
20049 if (!result)
20050 return NULL;
20051
20052 cur = start;
20053 for (i = 0; i < slice_length; i++) {
20054 /* PyTuple_SetItem borrows the reference. */
20055 PyTuple_SetItem(result, i, match_get_group_by_index(self, cur,
20056 Py_None));
20057 cur += step;
20058 }
20059
20060 return result;
20061 }
20062 }
20063
20064 /* MatchObject's length method. */
20065 Py_LOCAL_INLINE(Py_ssize_t) match_length(MatchObject* self) {
20066 return (Py_ssize_t)self->group_count + 1;
20067 }
20068
20069 /* MatchObject's '__getitem__' method. */
20070 static PyObject* match_getitem(MatchObject* self, PyObject* item) {
20071 if (PySlice_Check(item))
20072 return match_get_group_slice(self, item);
20073
20074 return match_get_group(self, item, Py_None, TRUE);
20075 }
20076
20077 /* Determines the portion of the target string which is covered by the group
20078 * captures.
20079 */
20080 Py_LOCAL_INLINE(void) determine_target_substring(MatchObject* match,
20081 Py_ssize_t* slice_start, Py_ssize_t* slice_end) {
20082 Py_ssize_t start;
20083 Py_ssize_t end;
20084 size_t g;
20085
20086 start = match->pos;
20087 end = match->endpos;
20088
20089 for (g = 0; g < match->group_count; g++) {
20090 RE_GroupData* group;
20091 size_t c;
20092
20093 group = &match->groups[g];
20094
20095 for (c = 0; c < match->groups[g].count; c++) {
20096 RE_GroupSpan* span;
20097
20098 span = &group->captures[c];
20099 if (span->start < start)
20100 start = span->start;
20101 if (span->end > end)
20102 end = span->end;
20103 }
20104 }
20105
20106 *slice_start = start;
20107 *slice_end = end;
20108 }
20109
20110 /* MatchObject's 'detach_string' method. */
20111 static PyObject* match_detach_string(MatchObject* self, PyObject* unused) {
20112 if (self->string) {
20113 Py_ssize_t start;
20114 Py_ssize_t end;
20115 PyObject* substring;
20116
20117 determine_target_substring(self, &start, &end);
20118
20119 substring = get_slice(self->string, start, end);
20120 if (substring) {
20121 Py_XDECREF(self->substring);
20122 self->substring = substring;
20123 self->substring_offset = start;
20124
20125 Py_DECREF(self->string);
20126 self->string = NULL;
20127 }
20128 }
20129
20130 Py_RETURN_NONE;
20131 }
20132
20133 /* The documentation of a MatchObject. */
20134 PyDoc_STRVAR(match_group_doc,
20135 "group([group1, ...]) --> string or tuple of strings.\n\
20136 Return one or more subgroups of the match. If there is a single argument,\n\
20137 the result is a single string, or None if the group did not contribute to\n\
20138 the match; if there are multiple arguments, the result is a tuple with one\n\
20139 item per argument; if there are no arguments, the whole match is returned.\n\
20140 Group 0 is the whole match.");
20141
20142 PyDoc_STRVAR(match_start_doc,
20143 "start([group1, ...]) --> int or tuple of ints.\n\
20144 Return the index of the start of one or more subgroups of the match. If\n\
20145 there is a single argument, the result is an index, or -1 if the group did\n\
20146 not contribute to the match; if there are multiple arguments, the result is\n\
20147 a tuple with one item per argument; if there are no arguments, the index of\n\
20148 the start of the whole match is returned. Group 0 is the whole match.");
20149
20150 PyDoc_STRVAR(match_end_doc,
20151 "end([group1, ...]) --> int or tuple of ints.\n\
20152 Return the index of the end of one or more subgroups of the match. If there\n\
20153 is a single argument, the result is an index, or -1 if the group did not\n\
20154 contribute to the match; if there are multiple arguments, the result is a\n\
20155 tuple with one item per argument; if there are no arguments, the index of\n\
20156 the end of the whole match is returned. Group 0 is the whole match.");
20157
20158 PyDoc_STRVAR(match_span_doc,
20159 "span([group1, ...]) --> 2-tuple of int or tuple of 2-tuple of ints.\n\
20160 Return the span (a 2-tuple of the indices of the start and end) of one or\n\
20161 more subgroups of the match. If there is a single argument, the result is a\n\
20162 span, or (-1, -1) if the group did not contribute to the match; if there are\n\
20163 multiple arguments, the result is a tuple with one item per argument; if\n\
20164 there are no arguments, the span of the whole match is returned. Group 0 is\n\
20165 the whole match.");
20166
20167 PyDoc_STRVAR(match_groups_doc,
20168 "groups(default=None) --> tuple of strings.\n\
20169 Return a tuple containing all the subgroups of the match. The argument is\n\
20170 the default for groups that did not participate in the match.");
20171
20172 PyDoc_STRVAR(match_groupdict_doc,
20173 "groupdict(default=None) --> dict.\n\
20174 Return a dictionary containing all the named subgroups of the match, keyed\n\
20175 by the subgroup name. The argument is the value to be given for groups that\n\
20176 did not participate in the match.");
20177
20178 PyDoc_STRVAR(match_capturesdict_doc,
20179 "capturesdict() --> dict.\n\
20180 Return a dictionary containing the captures of all the named subgroups of the\n\
20181 match, keyed by the subgroup name.");
20182
20183 PyDoc_STRVAR(match_expand_doc,
20184 "expand(template) --> string.\n\
20185 Return the string obtained by doing backslash substitution on the template,\n\
20186 as done by the sub() method.");
20187
20188 PyDoc_STRVAR(match_expandf_doc,
20189 "expandf(format) --> string.\n\
20190 Return the string obtained by using the format, as done by the subf()\n\
20191 method.");
20192
20193 PyDoc_STRVAR(match_captures_doc,
20194 "captures([group1, ...]) --> list of strings or tuple of list of strings.\n\
20195 Return the captures of one or more subgroups of the match. If there is a\n\
20196 single argument, the result is a list of strings; if there are multiple\n\
20197 arguments, the result is a tuple of lists with one item per argument; if\n\
20198 there are no arguments, the captures of the whole match is returned. Group\n\
20199 0 is the whole match.");
20200
20201 PyDoc_STRVAR(match_allcaptures_doc,
20202 "allcaptures() --> list of strings or tuple of list of strings.\n\
20203 Return the captures of all the groups of the match and the whole match.");
20204
20205 PyDoc_STRVAR(match_starts_doc,
20206 "starts([group1, ...]) --> list of ints or tuple of list of ints.\n\
20207 Return the indices of the starts of the captures of one or more subgroups of\n\
20208 the match. If there is a single argument, the result is a list of indices;\n\
20209 if there are multiple arguments, the result is a tuple of lists with one\n\
20210 item per argument; if there are no arguments, the indices of the starts of\n\
20211 the captures of the whole match is returned. Group 0 is the whole match.");
20212
20213 PyDoc_STRVAR(match_ends_doc,
20214 "ends([group1, ...]) --> list of ints or tuple of list of ints.\n\
20215 Return the indices of the ends of the captures of one or more subgroups of\n\
20216 the match. If there is a single argument, the result is a list of indices;\n\
20217 if there are multiple arguments, the result is a tuple of lists with one\n\
20218 item per argument; if there are no arguments, the indices of the ends of the\n\
20219 captures of the whole match is returned. Group 0 is the whole match.");
20220
20221 PyDoc_STRVAR(match_spans_doc,
20222 "spans([group1, ...]) --> list of 2-tuple of ints or tuple of list of 2-tuple of ints.\n\
20223 Return the spans (a 2-tuple of the indices of the start and end) of the\n\
20224 captures of one or more subgroups of the match. If there is a single\n\
20225 argument, the result is a list of spans; if there are multiple arguments,\n\
20226 the result is a tuple of lists with one item per argument; if there are no\n\
20227 arguments, the spans of the captures of the whole match is returned. Group\n\
20228 0 is the whole match.");
20229
20230 PyDoc_STRVAR(match_allspans_doc,
20231 "allspans() --> list of 2-tuple of ints or tuple of list of 2-tuple of ints.\n\
20232 Return the spans (a 2-tuple of the indices of the start and end) of all the\n\
20233 captures of all the groups of the match and the whole match.");
20234
20235 PyDoc_STRVAR(match_detach_string_doc,
20236 "detach_string()\n\
20237 Detaches the target string from the match object. The 'string' attribute\n\
20238 will become None.");
20239
20240 /* MatchObject's methods. */
20241 static PyMethodDef match_methods[] = {
20242 {"group", (PyCFunction)match_group, METH_VARARGS, match_group_doc},
20243 {"start", (PyCFunction)match_start, METH_VARARGS, match_start_doc},
20244 {"end", (PyCFunction)match_end, METH_VARARGS, match_end_doc},
20245 {"span", (PyCFunction)match_span, METH_VARARGS, match_span_doc},
20246 {"groups", (PyCFunction)match_groups, METH_VARARGS|METH_KEYWORDS,
20247 match_groups_doc},
20248 {"groupdict", (PyCFunction)match_groupdict, METH_VARARGS|METH_KEYWORDS,
20249 match_groupdict_doc},
20250 {"capturesdict", (PyCFunction)match_capturesdict, METH_NOARGS,
20251 match_capturesdict_doc},
20252 {"expand", (PyCFunction)match_expand, METH_O, match_expand_doc},
20253 {"expandf", (PyCFunction)match_expandf, METH_O, match_expandf_doc},
20254 {"captures", (PyCFunction)match_captures, METH_VARARGS,
20255 match_captures_doc},
20256 {"allcaptures", (PyCFunction)match_allcaptures, METH_NOARGS,
20257 match_allcaptures_doc},
20258 {"starts", (PyCFunction)match_starts, METH_VARARGS, match_starts_doc},
20259 {"ends", (PyCFunction)match_ends, METH_VARARGS, match_ends_doc},
20260 {"spans", (PyCFunction)match_spans, METH_VARARGS, match_spans_doc},
20261 {"allspans", (PyCFunction)match_allspans, METH_NOARGS, match_allspans_doc},
20262 {"detach_string", (PyCFunction)match_detach_string, METH_NOARGS,
20263 match_detach_string_doc},
20264 {"__copy__", (PyCFunction)match_copy, METH_NOARGS},
20265 {"__deepcopy__", (PyCFunction)match_deepcopy, METH_O},
20266 {"__getitem__", (PyCFunction)match_getitem, METH_O|METH_COEXIST},
20267 #if PY_VERSION_HEX >= 0x03090000
20268 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS,
20269 PyDoc_STR("See PEP 585")},
20270 #endif
20271 {NULL, NULL}
20272 };
20273
20274 PyDoc_STRVAR(match_doc, "Match object");
20275
20276 /* MatchObject's 'lastindex' attribute. */
20277 static PyObject* match_lastindex(PyObject* self_, void* unused) {
20278 MatchObject* self;
20279
20280 self = (MatchObject*)self_;
20281
20282 if (self->lastindex >= 0)
20283 return Py_BuildValue("n", self->lastindex);
20284
20285 Py_RETURN_NONE;
20286 }
20287
20288 /* MatchObject's 'lastgroup' attribute. */
20289 static PyObject* match_lastgroup(PyObject* self_, void* unused) {
20290 MatchObject* self;
20291
20292 self = (MatchObject*)self_;
20293
20294 if (self->pattern->indexgroup && self->lastgroup >= 0) {
20295 PyObject* index;
20296 PyObject* result;
20297
20298 index = Py_BuildValue("n", self->lastgroup);
20299 if (!index)
20300 return NULL;
20301
20302 /* PyDict_GetItem returns borrows a reference. */
20303 result = PyDict_GetItem(self->pattern->indexgroup, index);
20304 Py_DECREF(index);
20305 if (result) {
20306 Py_INCREF(result);
20307 return result;
20308 }
20309 PyErr_Clear();
20310 }
20311
20312 Py_RETURN_NONE;
20313 }
20314
20315 /* MatchObject's 'string' attribute. */
20316 static PyObject* match_string(PyObject* self_, void* unused) {
20317 MatchObject* self;
20318
20319 self = (MatchObject*)self_;
20320
20321 if (self->string) {
20322 Py_INCREF(self->string);
20323 return self->string;
20324 } else
20325 Py_RETURN_NONE;
20326 }
20327
20328 /* MatchObject's 'fuzzy_counts' attribute. */
20329 static PyObject* match_fuzzy_counts(PyObject* self_, void* unused) {
20330 MatchObject* self;
20331
20332 self = (MatchObject*)self_;
20333
20334 return Py_BuildValue("nnn", self->fuzzy_counts[RE_FUZZY_SUB],
20335 self->fuzzy_counts[RE_FUZZY_INS], self->fuzzy_counts[RE_FUZZY_DEL]);
20336 }
20337
20338 /* MatchObject's 'fuzzy_changes' attribute. */
20339 static PyObject* match_fuzzy_changes(PyObject* self_, void* unused) {
20340 MatchObject* self;
20341 PyObject* sub_changes;
20342 PyObject* ins_changes;
20343 PyObject* del_changes;
20344 size_t count;
20345 Py_ssize_t offset;
20346 size_t i;
20347 PyObject* result;
20348
20349 self = (MatchObject*)self_;
20350
20351 sub_changes = PyList_New(0);
20352 ins_changes = PyList_New(0);
20353 del_changes = PyList_New(0);
20354 if (!sub_changes || !ins_changes || !del_changes)
20355 goto error;
20356
20357 count = self->fuzzy_counts[RE_FUZZY_SUB] + self->fuzzy_counts[RE_FUZZY_INS]
20358 + self->fuzzy_counts[RE_FUZZY_DEL];
20359 offset = 0;
20360
20361 for (i = 0; i < count; i++) {
20362 RE_FuzzyChange* change;
20363 Py_ssize_t pos;
20364 PyObject* position;
20365 int status;
20366
20367 change = &self->fuzzy_changes[i];
20368
20369 pos = change->pos;
20370 if (change->type == RE_FUZZY_DEL) {
20371 pos += offset;
20372 ++offset;
20373 }
20374
20375 position = Py_BuildValue("n", pos);
20376 if (!position)
20377 goto error;
20378
20379 switch (change->type) {
20380 case RE_FUZZY_DEL:
20381 status = PyList_Append(del_changes, position);
20382 break;
20383 case RE_FUZZY_INS:
20384 status = PyList_Append(ins_changes, position);
20385 break;
20386 case RE_FUZZY_SUB:
20387 status = PyList_Append(sub_changes, position);
20388 break;
20389 default:
20390 status = 0;
20391 break;
20392 }
20393
20394 Py_DECREF(position);
20395
20396 if (status == -1)
20397 goto error;
20398 }
20399
20400 result = PyTuple_Pack(3, sub_changes, ins_changes, del_changes);
20401
20402 Py_DECREF(sub_changes);
20403 Py_DECREF(ins_changes);
20404 Py_DECREF(del_changes);
20405
20406 return result;
20407
20408 error:
20409 Py_XDECREF(sub_changes);
20410 Py_XDECREF(ins_changes);
20411 Py_XDECREF(del_changes);
20412 return NULL;
20413 }
20414
20415 static PyGetSetDef match_getset[] = {
20416 {"lastindex", (getter)match_lastindex, (setter)NULL,
20417 "The group number of the last matched capturing group, or None."},
20418 {"lastgroup", (getter)match_lastgroup, (setter)NULL,
20419 "The name of the last matched capturing group, or None."},
20420 {"regs", (getter)match_regs, (setter)NULL,
20421 "A tuple of the spans of the capturing groups."},
20422 {"string", (getter)match_string, (setter)NULL,
20423 "The string that was searched, or None if it has been detached."},
20424 {"fuzzy_counts", (getter)match_fuzzy_counts, (setter)NULL,
20425 "A tuple of the number of substitutions, insertions and deletions."},
20426 {"fuzzy_changes", (getter)match_fuzzy_changes, (setter)NULL,
20427 "A tuple of the positions of the substitutions, insertions and deletions."},
20428 {NULL} /* Sentinel */
20429 };
20430
20431 static PyMemberDef match_members[] = {
20432 {"re", T_OBJECT, offsetof(MatchObject, pattern), READONLY,
20433 "The regex object that produced this match object."},
20434 {"pos", T_PYSSIZET, offsetof(MatchObject, pos), READONLY,
20435 "The position at which the regex engine starting searching."},
20436 {"endpos", T_PYSSIZET, offsetof(MatchObject, endpos), READONLY,
20437 "The final position beyond which the regex engine won't search."},
20438 {"partial", T_BOOL, offsetof(MatchObject, partial), READONLY,
20439 "Whether it's a partial match."},
20440 {NULL} /* Sentinel */
20441 };
20442
20443 static PyMappingMethods match_as_mapping = {
20444 (lenfunc)match_length, /* mp_length */
20445 (binaryfunc)match_getitem, /* mp_subscript */
20446 0, /* mp_ass_subscript */
20447 };
20448
20449 static PyTypeObject Match_Type = {
20450 PyVarObject_HEAD_INIT(NULL,0)
20451 "_regex.Match",
20452 sizeof(MatchObject)
20453 };
20454
20455 /* Copies the groups. */
20456 Py_LOCAL_INLINE(RE_GroupData*) copy_groups(RE_GroupData* groups, size_t
20457 group_count) {
20458 size_t span_count;
20459 size_t g;
20460 RE_GroupData* groups_copy;
20461 RE_GroupSpan* spans_copy;
20462 size_t offset;
20463
20464 /* Calculate the total size of the group info. */
20465 span_count = 0;
20466 for (g = 0; g < group_count; g++)
20467 span_count += groups[g].count;
20468
20469 /* Allocate the storage for the group info in a single block. */
20470 groups_copy = (RE_GroupData*)re_alloc(group_count * sizeof(RE_GroupData) +
20471 span_count * sizeof(RE_GroupSpan));
20472 if (!groups_copy)
20473 return NULL;
20474
20475 /* The storage for the spans comes after the other group info. */
20476 spans_copy = (RE_GroupSpan*)&groups_copy[group_count];
20477
20478 /* There's no need to initialise the spans info. */
20479 memset(groups_copy, 0, group_count * sizeof(RE_GroupData));
20480
20481 offset = 0;
20482 for (g = 0; g < group_count; g++) {
20483 RE_GroupData* orig;
20484 RE_GroupData* copy;
20485
20486 orig = &groups[g];
20487 copy = &groups_copy[g];
20488
20489 copy->captures = &spans_copy[offset];
20490 offset += orig->count;
20491
20492 if (orig->count > 0) {
20493 Py_MEMCPY(copy->captures, orig->captures, orig->count *
20494 sizeof(RE_GroupSpan));
20495 copy->capacity = orig->count;
20496 copy->count = orig->count;
20497 }
20498
20499 copy->current = orig->current;
20500 }
20501
20502 return groups_copy;
20503 }
20504
20505 /* Makes a copy of a MatchObject. */
20506 Py_LOCAL_INLINE(PyObject*) make_match_copy(MatchObject* self) {
20507 MatchObject* match;
20508
20509 if (!self->string) {
20510 /* The target string has been detached, so the MatchObject is now
20511 * immutable.
20512 */
20513 Py_INCREF(self);
20514 return (PyObject*)self;
20515 }
20516
20517 /* Create a MatchObject. */
20518 match = PyObject_NEW(MatchObject, &Match_Type);
20519 if (!match)
20520 return NULL;
20521
20522 match->string = self->string;
20523 match->substring = self->substring;
20524 match->substring_offset = self->substring_offset;
20525 match->pattern = self->pattern;
20526 match->pos = self->pos;
20527 match->endpos = self->endpos;
20528 match->match_start = self->match_start;
20529 match->match_end = self->match_end;
20530 match->lastindex = self->lastindex;
20531 match->lastgroup = self->lastgroup;
20532 match->group_count = self->group_count;
20533 match->groups = NULL; /* Copy them later. */
20534 match->regs = self->regs;
20535 Py_MEMCPY(match->fuzzy_counts, self->fuzzy_counts,
20536 sizeof(self->fuzzy_counts));
20537 match->fuzzy_changes = NULL; /* Copy them later. */
20538 match->partial = self->partial;
20539 Py_INCREF(match->string);
20540 Py_INCREF(match->substring);
20541 Py_INCREF(match->pattern);
20542 Py_XINCREF(match->regs);
20543
20544 /* Copy the groups to the MatchObject. */
20545 if (self->group_count > 0) {
20546 match->groups = copy_groups(self->groups, self->group_count);
20547 if (!match->groups) {
20548 Py_DECREF(match);
20549 return NULL;
20550 }
20551 }
20552
20553 /* Copy the fuzzy changes to the MatchObject. */
20554 if (self->fuzzy_changes) {
20555 size_t total_changes;
20556 size_t size;
20557
20558 total_changes = self->fuzzy_counts[RE_FUZZY_SUB] +
20559 self->fuzzy_counts[RE_FUZZY_INS] + self->fuzzy_counts[RE_FUZZY_DEL];
20560 size = (size_t)total_changes * sizeof(RE_FuzzyChange);
20561 match->fuzzy_changes = (RE_FuzzyChange*)re_alloc(size);
20562 if (!match->fuzzy_changes) {
20563 Py_DECREF(match);
20564 return NULL;
20565 }
20566 Py_MEMCPY(match->fuzzy_changes, self->fuzzy_changes, size);
20567 }
20568
20569 return (PyObject*)match;
20570 }
20571
20572 /* Creates a new MatchObject. */
20573 Py_LOCAL_INLINE(PyObject*) pattern_new_match(PatternObject* pattern, RE_State*
20574 state, int status) {
20575 /* Create MatchObject (from state object). */
20576 if (status > 0 || status == RE_ERROR_PARTIAL) {
20577 MatchObject* match;
20578
20579 /* Create a MatchObject. */
20580 match = PyObject_NEW(MatchObject, &Match_Type);
20581 if (!match)
20582 return NULL;
20583
20584 match->string = state->string;
20585 match->substring = state->string;
20586 match->substring_offset = 0;
20587 match->pattern = pattern;
20588 match->regs = NULL;
20589
20590 if (pattern->is_fuzzy)
20591 Py_MEMCPY(match->fuzzy_counts, state->fuzzy_counts,
20592 sizeof(state->fuzzy_counts));
20593 else
20594 memset(match->fuzzy_counts, 0, sizeof(match->fuzzy_counts));
20595
20596 if (state->fuzzy_changes.count > 0) {
20597 size_t size;
20598
20599 size = state->fuzzy_changes.count * sizeof(RE_FuzzyChange);
20600 match->fuzzy_changes = (RE_FuzzyChange*)re_alloc(size);
20601 if (!match->fuzzy_changes) {
20602 Py_DECREF(match);
20603 return NULL;
20604 }
20605 Py_MEMCPY(match->fuzzy_changes, state->fuzzy_changes.items, size);
20606 } else
20607 match->fuzzy_changes = NULL;
20608
20609 match->partial = status == RE_ERROR_PARTIAL;
20610 Py_INCREF(match->string);
20611 Py_INCREF(match->substring);
20612 Py_INCREF(match->pattern);
20613
20614 /* Copy the groups to the MatchObject. */
20615 if (pattern->public_group_count > 0) {
20616 match->groups = copy_groups(state->groups,
20617 pattern->public_group_count);
20618 if (!match->groups) {
20619 Py_DECREF(match);
20620 return NULL;
20621 }
20622 } else
20623 match->groups = NULL;
20624
20625 match->group_count = pattern->public_group_count;
20626
20627 match->pos = state->slice_start;
20628 match->endpos = state->slice_end;
20629
20630 if (state->reverse) {
20631 match->match_start = state->text_pos;
20632 match->match_end = state->match_pos;
20633 } else {
20634 match->match_start = state->match_pos;
20635 match->match_end = state->text_pos;
20636 }
20637
20638 match->lastindex = state->lastindex;
20639 match->lastgroup = state->lastgroup;
20640
20641 return (PyObject*)match;
20642 } else if (status == 0) {
20643 /* No match. */
20644 Py_RETURN_NONE;
20645 } else {
20646 /* Internal error. */
20647 set_error(status, NULL);
20648 return NULL;
20649 }
20650 }
20651
20652 /* Gets the text of a capture group from a state. */
20653 Py_LOCAL_INLINE(PyObject*) state_get_group(RE_State* state, Py_ssize_t index,
20654 PyObject* string, BOOL empty) {
20655 RE_GroupData* group;
20656 Py_ssize_t start;
20657 Py_ssize_t end;
20658
20659 group = &state->groups[index - 1];
20660
20661 if (string != Py_None && index >= 1 && (size_t)index <=
20662 state->pattern->public_group_count && group->current >= 0) {
20663 RE_GroupSpan* span;
20664
20665 span = &group->captures[group->current];
20666 start = span->start;
20667 end = span->end;
20668 } else if (empty)
20669 /* Want an empty string. */
20670 start = end = 0;
20671 else
20672 Py_RETURN_NONE;
20673
20674 return get_slice(string, start, end);
20675 }
20676
20677 /* Acquires the lock (mutex) on the state if there's one.
20678 *
20679 * It also increments the owner's refcount just to ensure that it won't be
20680 * destroyed by another thread.
20681 */
20682 Py_LOCAL_INLINE(void) acquire_state_lock(PyObject* owner, RE_State* state) {
20683 if (state->lock) {
20684 /* In order to avoid deadlock we need to release the GIL while trying
20685 * to acquire the lock.
20686 */
20687 Py_INCREF(owner);
20688 if (!PyThread_acquire_lock(state->lock, 0)) {
20689 release_GIL(state);
20690 PyThread_acquire_lock(state->lock, 1);
20691 acquire_GIL(state);
20692 }
20693 }
20694 }
20695
20696 /* Releases the lock (mutex) on the state if there's one.
20697 *
20698 * It also decrements the owner's refcount, which was incremented when the lock
20699 * was acquired.
20700 */
20701 Py_LOCAL_INLINE(void) release_state_lock(PyObject* owner, RE_State* state) {
20702 if (state->lock) {
20703 PyThread_release_lock(state->lock);
20704 Py_DECREF(owner);
20705 }
20706 }
20707
20708 /* Implements the functionality of ScanObject's search and match methods. */
20709 Py_LOCAL_INLINE(PyObject*) scanner_search_or_match(ScannerObject* self, BOOL
20710 search) {
20711 RE_State* state;
20712 PyObject* match;
20713
20714 state = &self->state;
20715
20716 /* Acquire the state lock in case we're sharing the scanner object across
20717 * threads.
20718 */
20719 acquire_state_lock((PyObject*)self, state);
20720
20721 if (self->status == RE_ERROR_FAILURE || self->status == RE_ERROR_PARTIAL) {
20722 /* No or partial match. */
20723 release_state_lock((PyObject*)self, state);
20724 Py_RETURN_NONE;
20725 } else if (self->status < 0) {
20726 /* Internal error. */
20727 release_state_lock((PyObject*)self, state);
20728 set_error(self->status, NULL);
20729 return NULL;
20730 }
20731
20732 /* Look for another match. */
20733 self->status = do_match(state, search);
20734 if (self->status >= 0 || self->status == RE_ERROR_PARTIAL) {
20735 /* Create the match object. */
20736 match = pattern_new_match(self->pattern, state, self->status);
20737
20738 if (search && state->overlapped) {
20739 /* Advance one character. */
20740 Py_ssize_t step;
20741
20742 step = state->reverse ? -1 : 1;
20743 state->text_pos = state->match_pos + step;
20744 state->must_advance = FALSE;
20745 } else
20746 /* Don't allow 2 contiguous zero-width matches. */
20747 state->must_advance = state->text_pos == state->match_pos;
20748 } else
20749 /* Internal error. */
20750 match = NULL;
20751
20752 /* Release the state lock. */
20753 release_state_lock((PyObject*)self, state);
20754
20755 return match;
20756 }
20757
20758 /* ScannerObject's 'match' method. */
20759 static PyObject* scanner_match(ScannerObject* self, PyObject* unused) {
20760 return scanner_search_or_match(self, FALSE);
20761 }
20762
20763 /* ScannerObject's 'search' method. */
20764 static PyObject* scanner_search(ScannerObject* self, PyObject* unused) {
20765 return scanner_search_or_match(self, TRUE);
20766 }
20767
20768 /* Returns an iterator for a ScannerObject.
20769 *
20770 * The iterator is actually the ScannerObject itself.
20771 */
20772 static PyObject* scanner_iter(PyObject* self) {
20773 Py_INCREF(self);
20774 return self;
20775 }
20776
20777 /* Gets the next result from a scanner iterator. */
20778 static PyObject* scanner_iternext(PyObject* self) {
20779 PyObject* match;
20780
20781 match = scanner_search((ScannerObject*)self, NULL);
20782
20783 if (match == Py_None) {
20784 /* No match. */
20785 Py_DECREF(match);
20786 return NULL;
20787 }
20788
20789 return match;
20790 }
20791
20792 /* Makes a copy of a ScannerObject.
20793 *
20794 * It actually doesn't make a copy, just returns the original object.
20795 */
20796 Py_LOCAL_INLINE(PyObject*) make_scanner_copy(ScannerObject* self) {
20797 Py_INCREF(self);
20798 return (PyObject*)self;
20799 }
20800
20801 /* ScannerObject's '__copy__' method. */
20802 static PyObject* scanner_copy(ScannerObject* self, PyObject* unused) {
20803 return make_scanner_copy(self);
20804 }
20805
20806 /* ScannerObject's '__deepcopy__' method. */
20807 static PyObject* scanner_deepcopy(ScannerObject* self, PyObject* memo) {
20808 return make_scanner_copy(self);
20809 }
20810
20811 /* The documentation of a ScannerObject. */
20812 PyDoc_STRVAR(scanner_match_doc,
20813 "match() --> MatchObject or None.\n\
20814 Match at the current position in the string.");
20815
20816 PyDoc_STRVAR(scanner_search_doc,
20817 "search() --> MatchObject or None.\n\
20818 Search from the current position in the string.");
20819
20820 /* ScannerObject's methods. */
20821 static PyMethodDef scanner_methods[] = {
20822 {"match", (PyCFunction)scanner_match, METH_NOARGS, scanner_match_doc},
20823 {"search", (PyCFunction)scanner_search, METH_NOARGS, scanner_search_doc},
20824 {"__copy__", (PyCFunction)scanner_copy, METH_NOARGS},
20825 {"__deepcopy__", (PyCFunction)scanner_deepcopy, METH_O},
20826 {NULL, NULL}
20827 };
20828
20829 PyDoc_STRVAR(scanner_doc, "Scanner object");
20830
20831 /* Deallocates a ScannerObject. */
20832 static void scanner_dealloc(PyObject* self_) {
20833 ScannerObject* self;
20834
20835 self = (ScannerObject*)self_;
20836
20837 if (self->status != RE_ERROR_INITIALISING)
20838 state_fini(&self->state);
20839 Py_DECREF(self->pattern);
20840 PyObject_DEL(self);
20841 }
20842
20843 static PyMemberDef scanner_members[] = {
20844 {"pattern", T_OBJECT, offsetof(ScannerObject, pattern), READONLY,
20845 "The regex object that produced this scanner object."},
20846 {NULL} /* Sentinel */
20847 };
20848
20849 static PyTypeObject Scanner_Type = {
20850 PyVarObject_HEAD_INIT(NULL, 0)
20851 "_regex.Scanner",
20852 sizeof(ScannerObject)
20853 };
20854
20855 /* Decodes a 'concurrent' argument. */
20856 Py_LOCAL_INLINE(int) decode_concurrent(PyObject* concurrent) {
20857 Py_ssize_t value;
20858
20859 if (concurrent == Py_None)
20860 return RE_CONC_DEFAULT;
20861
20862 value = PyLong_AsLong(concurrent);
20863 if (value == -1 && PyErr_Occurred()) {
20864 set_error(RE_ERROR_CONCURRENT, NULL);
20865 return -1;
20866 }
20867
20868 return value ? RE_CONC_YES : RE_CONC_NO;
20869 }
20870
20871 /* Decodes a 'partial' argument. */
20872 Py_LOCAL_INLINE(BOOL) decode_partial(PyObject* partial) {
20873 Py_ssize_t value;
20874
20875 if (partial == Py_False)
20876 return FALSE;
20877
20878 if (partial == Py_True)
20879 return TRUE;
20880
20881 value = PyLong_AsLong(partial);
20882 if (value == -1 && PyErr_Occurred()) {
20883 PyErr_Clear();
20884 return TRUE;
20885 }
20886
20887 return value != 0;
20888 }
20889
20890 /* Decodes a 'timeout' argument. */
20891 Py_LOCAL_INLINE(Py_ssize_t) decode_timeout(PyObject* timeout) {
20892 double value;
20893
20894 if (timeout == Py_None)
20895 return RE_NO_TIMEOUT;
20896
20897 value = PyFloat_AsDouble(timeout);
20898 if (value == -1.0 && PyErr_Occurred()) {
20899 set_error(RE_ERROR_BAD_TIMEOUT, NULL);
20900 return RE_BAD_TIMEOUT;
20901 }
20902
20903 return value >= 0.0 ? (Py_ssize_t)(value * CLOCKS_PER_SEC) : RE_NO_TIMEOUT;
20904 }
20905
20906 /* Creates a new ScannerObject. */
20907 static PyObject* pattern_scanner(PatternObject* pattern, PyObject* args,
20908 PyObject* kwargs) {
20909 /* Create search state object. */
20910 ScannerObject* self;
20911 Py_ssize_t start;
20912 Py_ssize_t end;
20913 int conc;
20914 Py_ssize_t tim;
20915 BOOL part;
20916
20917 PyObject* string;
20918 PyObject* pos = Py_None;
20919 PyObject* endpos = Py_None;
20920 Py_ssize_t overlapped = FALSE;
20921 PyObject* concurrent = Py_None;
20922 PyObject* timeout = Py_None;
20923 PyObject* partial = Py_False;
20924 static char* kwlist[] = { "string", "pos", "endpos", "overlapped",
20925 "concurrent", "partial", "timeout", NULL };
20926 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OOnOOO:scanner", kwlist,
20927 &string, &pos, &endpos, &overlapped, &concurrent, &partial, &timeout))
20928 return NULL;
20929
20930 start = as_string_index(pos, 0);
20931 if (start == -1 && PyErr_Occurred())
20932 return NULL;
20933
20934 end = as_string_index(endpos, PY_SSIZE_T_MAX);
20935 if (end == -1 && PyErr_Occurred())
20936 return NULL;
20937
20938 conc = decode_concurrent(concurrent);
20939 if (conc < 0)
20940 return NULL;
20941
20942 tim = decode_timeout(timeout);
20943 if (tim == RE_BAD_TIMEOUT)
20944 return NULL;
20945
20946 part = decode_partial(partial);
20947
20948 /* Create a scanner object. */
20949 self = PyObject_NEW(ScannerObject, &Scanner_Type);
20950 if (!self)
20951 return NULL;
20952
20953 self->pattern = pattern;
20954 Py_INCREF(self->pattern);
20955 self->status = RE_ERROR_INITIALISING;
20956
20957 /* The MatchObject, and therefore repeated captures, will be visible. */
20958 if (!state_init(&self->state, pattern, string, start, end, overlapped != 0,
20959 conc, part, TRUE, TRUE, FALSE, tim)) {
20960 Py_DECREF(self);
20961 return NULL;
20962 }
20963
20964 self->status = RE_ERROR_SUCCESS;
20965
20966 return (PyObject*) self;
20967 }
20968
20969 /* Performs the split for the SplitterObject. */
20970 Py_LOCAL_INLINE(PyObject*) next_split_part(SplitterObject* self) {
20971 RE_State* state;
20972 PyObject* result = NULL; /* Initialise to stop compiler warning. */
20973
20974 state = &self->state;
20975
20976 /* Acquire the state lock in case we're sharing the splitter object across
20977 * threads.
20978 */
20979 acquire_state_lock((PyObject*)self, state);
20980
20981 if (self->status == RE_ERROR_FAILURE || self->status == RE_ERROR_PARTIAL) {
20982 /* Finished. */
20983 release_state_lock((PyObject*)self, state);
20984 result = Py_False;
20985 Py_INCREF(result);
20986 return result;
20987 } else if (self->status < 0) {
20988 /* Internal error. */
20989 release_state_lock((PyObject*)self, state);
20990 set_error(self->status, NULL);
20991 return NULL;
20992 }
20993
20994 if (self->index == 0) {
20995 if (self->split_count < self->maxsplit) {
20996 self->status = do_match(state, TRUE);
20997 if (self->status < 0)
20998 goto error;
20999
21000 if (self->status == RE_ERROR_SUCCESS) {
21001 ++self->split_count;
21002
21003 /* Get segment before this match. */
21004 if (state->reverse)
21005 result = get_slice(state->string, state->match_pos,
21006 self->last_pos);
21007 else
21008 result = get_slice(state->string, self->last_pos,
21009 state->match_pos);
21010 if (!result)
21011 goto error;
21012
21013 self->last_pos = state->text_pos;
21014
21015 /* Don't allow 2 contiguous zero-width matches. */
21016 state->must_advance = state->text_pos == state->match_pos;
21017 }
21018 } else
21019 goto no_match;
21020
21021 if (self->status == RE_ERROR_FAILURE || self->status ==
21022 RE_ERROR_PARTIAL) {
21023 no_match:
21024 /* Get segment following last match (even if empty). */
21025 if (state->reverse)
21026 result = get_slice(state->string, 0, self->last_pos);
21027 else
21028 result = get_slice(state->string, self->last_pos,
21029 state->text_length);
21030 if (!result)
21031 goto error;
21032 }
21033 } else {
21034 /* Add group. */
21035 result = state_get_group(state, self->index, state->string, FALSE);
21036 if (!result)
21037 goto error;
21038 }
21039
21040 ++self->index;
21041 if ((size_t)self->index > state->pattern->public_group_count)
21042 self->index = 0;
21043
21044 /* Release the state lock. */
21045 release_state_lock((PyObject*)self, state);
21046
21047 return result;
21048
21049 error:
21050 /* Release the state lock. */
21051 release_state_lock((PyObject*)self, state);
21052
21053 return NULL;
21054 }
21055
21056 /* SplitterObject's 'split' method. */
21057 static PyObject* splitter_split(SplitterObject* self, PyObject* unused) {
21058 PyObject* result;
21059
21060 result = next_split_part(self);
21061
21062 if (result == Py_False) {
21063 /* The sentinel. */
21064 Py_DECREF(Py_False);
21065 Py_RETURN_NONE;
21066 }
21067
21068 return result;
21069 }
21070
21071 /* Returns an iterator for a SplitterObject.
21072 *
21073 * The iterator is actually the SplitterObject itself.
21074 */
21075 static PyObject* splitter_iter(PyObject* self) {
21076 Py_INCREF(self);
21077 return self;
21078 }
21079
21080 /* Gets the next result from a splitter iterator. */
21081 static PyObject* splitter_iternext(PyObject* self) {
21082 PyObject* result;
21083
21084 result = next_split_part((SplitterObject*)self);
21085
21086 if (result == Py_False) {
21087 /* No match. */
21088 Py_DECREF(result);
21089 return NULL;
21090 }
21091
21092 return result;
21093 }
21094
21095 /* Makes a copy of a SplitterObject.
21096 *
21097 * It actually doesn't make a copy, just returns the original object.
21098 */
21099 Py_LOCAL_INLINE(PyObject*) make_splitter_copy(SplitterObject* self) {
21100 Py_INCREF(self);
21101 return (PyObject*)self;
21102 }
21103
21104 /* SplitterObject's '__copy__' method. */
21105 static PyObject* splitter_copy(SplitterObject* self, PyObject* unused) {
21106 return make_splitter_copy(self);
21107 }
21108
21109 /* SplitterObject's '__deepcopy__' method. */
21110 static PyObject* splitter_deepcopy(SplitterObject* self, PyObject* memo) {
21111 return make_splitter_copy(self);
21112 }
21113
21114 /* The documentation of a SplitterObject. */
21115 PyDoc_STRVAR(splitter_split_doc,
21116 "split() --> string or None.\n\
21117 Return the next part of the split string.");
21118
21119 /* SplitterObject's methods. */
21120 static PyMethodDef splitter_methods[] = {
21121 {"split", (PyCFunction)splitter_split, METH_NOARGS, splitter_split_doc},
21122 {"__copy__", (PyCFunction)splitter_copy, METH_NOARGS},
21123 {"__deepcopy__", (PyCFunction)splitter_deepcopy, METH_O},
21124 {NULL, NULL}
21125 };
21126
21127 PyDoc_STRVAR(splitter_doc, "Splitter object");
21128
21129 /* Deallocates a SplitterObject. */
21130 static void splitter_dealloc(PyObject* self_) {
21131 SplitterObject* self;
21132
21133 self = (SplitterObject*)self_;
21134
21135 if (self->status != RE_ERROR_INITIALISING)
21136 state_fini(&self->state);
21137 Py_DECREF(self->pattern);
21138 PyObject_DEL(self);
21139 }
21140
21141 /* Converts a captures index to an integer.
21142 *
21143 * A negative capture index in 'expandf' and 'subf' is passed as a string
21144 * because negative indexes are not supported by 'str.format'.
21145 */
21146 Py_LOCAL_INLINE(Py_ssize_t) index_to_integer(PyObject* item) {
21147 Py_ssize_t value;
21148
21149 value = PyLong_AsLong(item);
21150 if (!(value == -1 && PyErr_Occurred()))
21151 return value;
21152
21153 PyErr_Clear();
21154
21155 /* Is the index a string representation of an integer? */
21156 if (PyUnicode_Check(item)) {
21157 PyObject* int_obj;
21158
21159 int_obj = PyLong_FromUnicodeObject(item, 0);
21160 if (!int_obj)
21161 goto error;
21162
21163 value = PyLong_AsLong(int_obj);
21164 Py_DECREF(int_obj);
21165 if (!PyErr_Occurred())
21166 return value;
21167 } else if (PyBytes_Check(item)) {
21168 char* characters;
21169 PyObject* int_obj;
21170
21171 characters = PyBytes_AsString(item);
21172 int_obj = PyLong_FromString(characters, NULL, 0);
21173 if (!int_obj)
21174 goto error;
21175
21176 value = PyLong_AsLong(int_obj);
21177 Py_DECREF(int_obj);
21178 if (!PyErr_Occurred())
21179 return value;
21180 }
21181
21182 error:
21183 PyErr_Clear();
21184 PyErr_Format(PyExc_TypeError, "list indices must be integers, not %.200s",
21185 item->ob_type->tp_name);
21186
21187 return -1;
21188 }
21189
21190 /* CaptureObject's length method. */
21191 Py_LOCAL_INLINE(Py_ssize_t) capture_length(CaptureObject* self) {
21192 MatchObject* match;
21193 RE_GroupData* group;
21194
21195 if (self->group_index == 0)
21196 return 1;
21197
21198 match = *self->match_indirect;
21199 group = &match->groups[self->group_index - 1];
21200
21201 return (Py_ssize_t)group->count;
21202 }
21203
21204 /* CaptureObject's '__getitem__' method. */
21205 static PyObject* capture_getitem(CaptureObject* self, PyObject* item) {
21206 Py_ssize_t index;
21207 MatchObject* match;
21208 Py_ssize_t start;
21209 Py_ssize_t end;
21210
21211 index = index_to_integer(item);
21212 if (index == -1 && PyErr_Occurred())
21213 return NULL;
21214
21215 match = *self->match_indirect;
21216
21217 if (self->group_index == 0) {
21218 if (index < 0)
21219 index += 1;
21220
21221 if (index != 0) {
21222 PyErr_SetString(PyExc_IndexError, "list index out of range");
21223 return NULL;
21224 }
21225
21226 start = match->match_start;
21227 end = match->match_end;
21228 } else {
21229 RE_GroupData* group;
21230 RE_GroupSpan* span;
21231
21232 group = &match->groups[self->group_index - 1];
21233
21234 if (index < 0)
21235 index += (Py_ssize_t)group->count;
21236
21237 if (index < 0 || index >= (Py_ssize_t)group->count) {
21238 PyErr_SetString(PyExc_IndexError, "list index out of range");
21239 return NULL;
21240 }
21241
21242 span = &group->captures[index];
21243
21244 start = span->start;
21245 end = span->end;
21246 }
21247
21248 return get_slice(match->substring, start - match->substring_offset, end -
21249 match->substring_offset);
21250 }
21251
21252 static PyMappingMethods capture_as_mapping = {
21253 (lenfunc)capture_length, /* mp_length */
21254 (binaryfunc)capture_getitem, /* mp_subscript */
21255 0, /* mp_ass_subscript */
21256 };
21257
21258 /* CaptureObject's methods. */
21259 static PyMethodDef capture_methods[] = {
21260 {"__getitem__", (PyCFunction)capture_getitem, METH_O|METH_COEXIST},
21261 {NULL, NULL}
21262 };
21263
21264 /* Deallocates a CaptureObject. */
21265 static void capture_dealloc(PyObject* self_) {
21266 CaptureObject* self;
21267
21268 self = (CaptureObject*)self_;
21269 PyObject_DEL(self);
21270 }
21271
21272 /* CaptureObject's 'str' method. */
21273 static PyObject* capture_str(PyObject* self_) {
21274 CaptureObject* self;
21275 MatchObject* match;
21276 PyObject* default_value;
21277 PyObject* result;
21278
21279 self = (CaptureObject*)self_;
21280 match = *self->match_indirect;
21281
21282 default_value = PySequence_GetSlice(match->string, 0, 0);
21283 result = match_get_group_by_index(match, self->group_index, default_value);
21284 Py_DECREF(default_value);
21285
21286 return result;
21287 }
21288
21289 static PyMemberDef splitter_members[] = {
21290 {"pattern", T_OBJECT, offsetof(SplitterObject, pattern), READONLY,
21291 "The regex object that produced this splitter object."},
21292 {NULL} /* Sentinel */
21293 };
21294
21295 static PyTypeObject Splitter_Type = {
21296 PyVarObject_HEAD_INIT(NULL, 0)
21297 "_regex.Splitter",
21298 sizeof(SplitterObject)
21299 };
21300
21301 /* Creates a new SplitterObject. */
21302 Py_LOCAL_INLINE(PyObject*) pattern_splitter(PatternObject* pattern, PyObject*
21303 args, PyObject* kwargs) {
21304 /* Create split state object. */
21305 int conc;
21306 Py_ssize_t tim;
21307 SplitterObject* self;
21308
21309 PyObject* string;
21310 Py_ssize_t maxsplit = 0;
21311 PyObject* concurrent = Py_None;
21312 PyObject* timeout = Py_None;
21313 static char* kwlist[] = { "string", "maxsplit", "concurrent", "timeout",
21314 NULL };
21315 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|nOO:splitter", kwlist,
21316 &string, &maxsplit, &concurrent, &timeout))
21317 return NULL;
21318
21319 conc = decode_concurrent(concurrent);
21320 if (conc < 0)
21321 return NULL;
21322
21323 tim = decode_timeout(timeout);
21324 if (tim == RE_BAD_TIMEOUT)
21325 return NULL;
21326
21327 /* Create a splitter object. */
21328 self = PyObject_NEW(SplitterObject, &Splitter_Type);
21329 if (!self)
21330 return NULL;
21331
21332 self->pattern = pattern;
21333 Py_INCREF(self->pattern);
21334 self->status = RE_ERROR_INITIALISING;
21335
21336 if (maxsplit == 0)
21337 maxsplit = PY_SSIZE_T_MAX;
21338
21339 /* The MatchObject, and therefore repeated captures, will not be visible.
21340 */
21341 if (!state_init(&self->state, pattern, string, 0, PY_SSIZE_T_MAX, FALSE,
21342 conc, FALSE, TRUE, FALSE, FALSE, tim)) {
21343 Py_DECREF(self);
21344 return NULL;
21345 }
21346
21347 self->maxsplit = maxsplit;
21348 self->last_pos = self->state.reverse ? self->state.text_length : 0;
21349 self->split_count = 0;
21350 self->index = 0;
21351 self->status = RE_ERROR_SUCCESS;
21352
21353 return (PyObject*) self;
21354 }
21355
21356 /* Implements the functionality of PatternObject's search and match methods. */
21357 Py_LOCAL_INLINE(PyObject*) pattern_search_or_match(PatternObject* self,
21358 PyObject* args, PyObject* kwargs, char* args_desc, BOOL search, BOOL
21359 match_all) {
21360 Py_ssize_t start;
21361 Py_ssize_t end;
21362 int conc;
21363 Py_ssize_t tim;
21364 BOOL part;
21365 RE_State state;
21366 int status;
21367 PyObject* match;
21368
21369 PyObject* string;
21370 PyObject* pos = Py_None;
21371 PyObject* endpos = Py_None;
21372 PyObject* concurrent = Py_None;
21373 PyObject* timeout = Py_None;
21374 PyObject* partial = Py_False;
21375 static char* kwlist[] = { "string", "pos", "endpos", "concurrent",
21376 "partial", "timeout", NULL };
21377 /* When working with a short string, such as a line from a file, the
21378 * relative cost of PyArg_ParseTupleAndKeywords can be significant, and
21379 * it's worth not using it when there are only positional arguments.
21380 */
21381 Py_ssize_t arg_count;
21382 if (args && !kwargs && PyTuple_CheckExact(args))
21383 arg_count = PyTuple_GET_SIZE(args);
21384 else
21385 arg_count = -1;
21386
21387 if (1 <= arg_count && arg_count <= 5) {
21388 /* PyTuple_GET_ITEM borrows the reference. */
21389 string = PyTuple_GET_ITEM(args, 0);
21390 if (arg_count >= 2)
21391 pos = PyTuple_GET_ITEM(args, 1);
21392 if (arg_count >= 3)
21393 endpos = PyTuple_GET_ITEM(args, 2);
21394 if (arg_count >= 4)
21395 concurrent = PyTuple_GET_ITEM(args, 3);
21396 if (arg_count >= 5)
21397 partial = PyTuple_GET_ITEM(args, 4);
21398 if (arg_count >= 6)
21399 timeout = PyTuple_GET_ITEM(args, 5);
21400 } else if (!PyArg_ParseTupleAndKeywords(args, kwargs, args_desc, kwlist,
21401 &string, &pos, &endpos, &concurrent, &partial, &timeout))
21402 return NULL;
21403
21404 start = as_string_index(pos, 0);
21405 if (start == -1 && PyErr_Occurred())
21406 return NULL;
21407
21408 end = as_string_index(endpos, PY_SSIZE_T_MAX);
21409 if (end == -1 && PyErr_Occurred())
21410 return NULL;
21411
21412 conc = decode_concurrent(concurrent);
21413 if (conc < 0)
21414 return NULL;
21415
21416 tim = decode_timeout(timeout);
21417 if (tim == RE_BAD_TIMEOUT)
21418 return NULL;
21419
21420 part = decode_partial(partial);
21421
21422 /* The MatchObject, and therefore repeated captures, will be visible. */
21423 if (!state_init(&state, self, string, start, end, FALSE, conc, part, FALSE,
21424 TRUE, match_all, tim))
21425 return NULL;
21426
21427 status = do_match(&state, search);
21428
21429 if (status >= 0 || status == RE_ERROR_PARTIAL)
21430 /* Create the match object. */
21431 match = pattern_new_match(self, &state, status);
21432 else
21433 match = NULL;
21434
21435 state_fini(&state);
21436
21437 return match;
21438 }
21439
21440 /* PatternObject's 'match' method. */
21441 static PyObject* pattern_match(PatternObject* self, PyObject* args, PyObject*
21442 kwargs) {
21443 return pattern_search_or_match(self, args, kwargs, "O|OOOOO:match", FALSE,
21444 FALSE);
21445 }
21446
21447 /* PatternObject's 'fullmatch' method. */
21448 static PyObject* pattern_fullmatch(PatternObject* self, PyObject* args,
21449 PyObject* kwargs) {
21450 return pattern_search_or_match(self, args, kwargs, "O|OOOOO:fullmatch",
21451 FALSE, TRUE);
21452 }
21453
21454 /* PatternObject's 'search' method. */
21455 static PyObject* pattern_search(PatternObject* self, PyObject* args, PyObject*
21456 kwargs) {
21457 return pattern_search_or_match(self, args, kwargs, "O|OOOOO:search", TRUE,
21458 FALSE);
21459 }
21460
21461 /* Gets the limits of the matching. */
21462 Py_LOCAL_INLINE(BOOL) get_limits(PyObject* pos, PyObject* endpos, Py_ssize_t
21463 length, Py_ssize_t* start, Py_ssize_t* end) {
21464 Py_ssize_t s;
21465 Py_ssize_t e;
21466
21467 s = as_string_index(pos, 0);
21468 if (s == -1 && PyErr_Occurred())
21469 return FALSE;
21470
21471 e = as_string_index(endpos, PY_SSIZE_T_MAX);
21472 if (e == -1 && PyErr_Occurred())
21473 return FALSE;
21474
21475 /* Adjust boundaries. */
21476 if (s < 0)
21477 s += length;
21478 if (s < 0)
21479 s = 0;
21480 else if (s > length)
21481 s = length;
21482
21483 if (e < 0)
21484 e += length;
21485 if (e < 0)
21486 e = 0;
21487 else if (e > length)
21488 e = length;
21489
21490 *start = s;
21491 *end = e;
21492
21493 return TRUE;
21494 }
21495
21496 /* Gets a replacement item from the replacement list.
21497 *
21498 * The replacement item could be a string literal or a group.
21499 *
21500 * It can return None to represent an empty string.
21501 */
21502 Py_LOCAL_INLINE(PyObject*) get_sub_replacement(PyObject* item, PyObject*
21503 string, RE_State* state, size_t group_count) {
21504 Py_ssize_t index;
21505
21506 if (PyUnicode_CheckExact(item) || PyBytes_CheckExact(item)) {
21507 /* It's a literal, which can be added directly to the list. */
21508
21509 /* ensure_immutable will DECREF the original item if it has to make an
21510 * immutable copy, but that original item might have a borrowed
21511 * reference, so we must INCREF it first in order to ensure it won't be
21512 * destroyed.
21513 */
21514 Py_INCREF(item);
21515 item = ensure_immutable(item);
21516 return item;
21517 }
21518
21519 /* Is it a group reference? */
21520 index = as_group_index(item);
21521 if (index == -1 && PyErr_Occurred()) {
21522 /* Not a group either! */
21523 set_error(RE_ERROR_REPLACEMENT, NULL);
21524 return NULL;
21525 }
21526
21527 if (index == 0) {
21528 /* The entire matched portion of the string. */
21529 if (state->match_pos == state->text_pos) {
21530 /* Return None for "". */
21531 Py_RETURN_NONE;
21532 }
21533
21534 if (state->reverse)
21535 return get_slice(string, state->text_pos, state->match_pos);
21536 else
21537 return get_slice(string, state->match_pos, state->text_pos);
21538 } else if (1 <= index && (size_t)index <= group_count) {
21539 /* A group. */
21540 RE_GroupData* group;
21541 RE_GroupSpan* span;
21542
21543 group = &state->groups[index - 1];
21544
21545 if (group->current < 0) {
21546 /* The group didn't match or is "", so return None for "". */
21547 Py_RETURN_NONE;
21548 }
21549
21550 span = &group->captures[group->current];
21551
21552 return get_slice(string, span->start, span->end);
21553 } else {
21554 /* No such group. */
21555 set_error(RE_ERROR_INVALID_GROUP_REF, NULL);
21556 return NULL;
21557 }
21558 }
21559
21560 /* PatternObject's 'subx' method. */
21561 Py_LOCAL_INLINE(PyObject*) pattern_subx(PatternObject* self, PyObject*
21562 str_template, PyObject* string, Py_ssize_t maxsub, int sub_type, PyObject*
21563 pos, PyObject* endpos, int concurrent, Py_ssize_t timeout) {
21564 RE_StringInfo str_info;
21565 Py_ssize_t start;
21566 Py_ssize_t end;
21567 BOOL is_callable = FALSE;
21568 PyObject* replacement = NULL;
21569 BOOL is_literal = FALSE;
21570 BOOL is_format = FALSE;
21571 BOOL is_template = FALSE;
21572 RE_State state;
21573 RE_JoinInfo join_info;
21574 Py_ssize_t sub_count;
21575 Py_ssize_t last_pos;
21576 PyObject* item;
21577 MatchObject* match;
21578 BOOL built_capture = FALSE;
21579 PyObject* args = NULL;
21580 PyObject* kwargs = NULL;
21581 Py_ssize_t end_pos;
21582
21583 /* Get the string. */
21584 if (!get_string(string, &str_info))
21585 return NULL;
21586
21587 if (!check_compatible(self, str_info.is_unicode)) {
21588 release_buffer(&str_info);
21589 return NULL;
21590 }
21591
21592 /* Get the limits of the search. */
21593 if (!get_limits(pos, endpos, str_info.length, &start, &end)) {
21594 release_buffer(&str_info);
21595 return NULL;
21596 }
21597
21598 /* If the pattern is too long for the string, then take a shortcut, unless
21599 * it's a fuzzy pattern.
21600 */
21601 if (!self->is_fuzzy && self->min_width > end - start) {
21602 PyObject* result;
21603
21604 Py_INCREF(string);
21605
21606 if (sub_type & RE_SUBN)
21607 result = Py_BuildValue("Nn", string, 0);
21608 else
21609 result = string;
21610
21611 release_buffer(&str_info);
21612
21613 return result;
21614 }
21615
21616 if (maxsub == 0)
21617 maxsub = PY_SSIZE_T_MAX;
21618
21619 /* sub/subn takes either a function or a string template. */
21620 if (PyCallable_Check(str_template)) {
21621 /* It's callable. */
21622 is_callable = TRUE;
21623
21624 replacement = str_template;
21625 Py_INCREF(replacement);
21626 } else if (sub_type & RE_SUBF) {
21627 /* Is it a literal format?
21628 *
21629 * To keep it simple we'll say that a literal is a string which can be
21630 * used as-is, so no placeholders.
21631 */
21632 Py_ssize_t literal_length;
21633
21634 literal_length = check_replacement_string(str_template, '{');
21635 if (literal_length > 0) {
21636 /* It's a literal. */
21637 is_literal = TRUE;
21638
21639 replacement = str_template;
21640 Py_INCREF(replacement);
21641 } else if (literal_length < 0) {
21642 /* It isn't a literal, so get the 'format' method. */
21643 is_format = TRUE;
21644
21645 replacement = PyObject_GetAttrString(str_template, "format");
21646 if (!replacement) {
21647 release_buffer(&str_info);
21648 return NULL;
21649 }
21650 }
21651 } else {
21652 /* Is it a literal template?
21653 *
21654 * To keep it simple we'll say that a literal is a string which can be
21655 * used as-is, so no backslashes.
21656 */
21657 Py_ssize_t literal_length;
21658
21659 literal_length = check_replacement_string(str_template, '\\');
21660 if (literal_length > 0) {
21661 /* It's a literal. */
21662 is_literal = TRUE;
21663
21664 replacement = str_template;
21665 Py_INCREF(replacement);
21666 } else if (literal_length < 0 ) {
21667 /* It isn't a literal, so hand it over to the template compiler. */
21668 is_template = TRUE;
21669
21670 replacement = call("regex.regex", "_compile_replacement_helper",
21671 PyTuple_Pack(2, self, str_template));
21672 if (!replacement) {
21673 release_buffer(&str_info);
21674 return NULL;
21675 }
21676 }
21677 }
21678
21679 /* The MatchObject, and therefore repeated captures, will be visible only
21680 * if the replacement is callable or subf is used.
21681 */
21682 if (!state_init_2(&state, self, string, &str_info, start, end, FALSE,
21683 concurrent, FALSE, FALSE, is_callable || (sub_type & RE_SUBF) != 0,
21684 FALSE, timeout)) {
21685 release_buffer(&str_info);
21686 Py_XDECREF(replacement);
21687 return NULL;
21688 }
21689
21690 init_join_list(&join_info, state.reverse, PyUnicode_Check(string));
21691
21692 sub_count = 0;
21693 last_pos = state.reverse ? state.text_length : 0;
21694 while (sub_count < maxsub) {
21695 int status;
21696
21697 status = do_match(&state, TRUE);
21698 if (status < 0)
21699 goto error;
21700
21701 if (status == 0)
21702 break;
21703
21704 /* Append the segment before this match. */
21705 if (state.match_pos != last_pos) {
21706 if (state.reverse)
21707 item = get_slice(string, state.match_pos, last_pos);
21708 else
21709 item = get_slice(string, last_pos, state.match_pos);
21710 if (!item)
21711 goto error;
21712
21713 /* Add to the list. */
21714 status = add_to_join_list(&join_info, item);
21715 Py_DECREF(item);
21716 if (status < 0)
21717 goto error;
21718 }
21719
21720 /* Add this match. */
21721 if (is_literal) {
21722 /* The replacement is a literal string. */
21723 status = add_to_join_list(&join_info, replacement);
21724 if (status < 0)
21725 goto error;
21726 } else if (is_format) {
21727 /* The replacement is a format string. */
21728 size_t g;
21729
21730 /* We need to create the arguments for the 'format' method. We'll
21731 * start by creating a MatchObject.
21732 */
21733 match = (MatchObject*)pattern_new_match(self, &state, 1);
21734 if (!match)
21735 goto error;
21736
21737 /* We'll build the args and kwargs the first time. They'll be using
21738 * capture objects which refer to the match object indirectly; this
21739 * means that args and kwargs can be reused with different match
21740 * objects.
21741 */
21742 if (!built_capture) {
21743 /* The args are a tuple of the capture group matches. */
21744 args = PyTuple_New((Py_ssize_t)match->group_count + 1);
21745 if (!args) {
21746 Py_DECREF(match);
21747 goto error;
21748 }
21749
21750 for (g = 0; g < match->group_count + 1; g++)
21751 /* PyTuple_SetItem borrows the reference. */
21752 PyTuple_SetItem(args, (Py_ssize_t)g,
21753 make_capture_object(&match, (Py_ssize_t)g));
21754
21755 /* The kwargs are a dict of the named capture group matches. */
21756 kwargs = make_capture_dict(match, &match);
21757 if (!kwargs) {
21758 Py_DECREF(args);
21759 Py_DECREF(match);
21760 goto error;
21761 }
21762
21763 built_capture = TRUE;
21764 }
21765
21766 /* Call the 'format' method. */
21767 item = PyObject_Call(replacement, args, kwargs);
21768
21769 Py_DECREF(match);
21770 if (!item)
21771 goto error;
21772
21773 /* Add the result to the list. */
21774 status = add_to_join_list(&join_info, item);
21775 Py_DECREF(item);
21776 if (status < 0)
21777 goto error;
21778 } else if (is_template) {
21779 /* The replacement is a list template. */
21780 Py_ssize_t count;
21781 Py_ssize_t index;
21782 Py_ssize_t step;
21783
21784 /* Add each part of the template to the list. */
21785 count = PyList_Size(replacement);
21786 if (join_info.reversed) {
21787 /* We're searching backwards, so we'll be reversing the list
21788 * when it's complete. Therefore, we need to add the items of
21789 * the template in reverse order for them to be in the correct
21790 * order after the reversal.
21791 */
21792 index = count - 1;
21793 step = -1;
21794 } else {
21795 /* We're searching forwards. */
21796 index = 0;
21797 step = 1;
21798 }
21799
21800 while (count > 0) {
21801 PyObject* item;
21802 PyObject* str_item;
21803
21804 /* PyList_GetItem borrows a reference. */
21805 item = PyList_GetItem(replacement, index);
21806 str_item = get_sub_replacement(item, string, &state,
21807 self->public_group_count);
21808 if (!str_item)
21809 goto error;
21810
21811 /* Add the result to the list. */
21812 if (str_item == Py_None)
21813 /* None for "". */
21814 Py_DECREF(str_item);
21815 else {
21816 status = add_to_join_list(&join_info, str_item);
21817 Py_DECREF(str_item);
21818 if (status < 0)
21819 goto error;
21820 }
21821
21822 --count;
21823 index += step;
21824 }
21825 } else if (is_callable) {
21826 /* Pass a MatchObject to the replacement function. */
21827 PyObject* match;
21828 PyObject* args;
21829
21830 /* We need to create a MatchObject to pass to the replacement
21831 * function.
21832 */
21833 match = pattern_new_match(self, &state, 1);
21834 if (!match)
21835 goto error;
21836
21837 /* The args for the replacement function. */
21838 args = PyTuple_Pack(1, match);
21839 if (!args) {
21840 Py_DECREF(match);
21841 goto error;
21842 }
21843
21844 /* Call the replacement function. */
21845 item = PyObject_CallObject(replacement, args);
21846 Py_DECREF(args);
21847 Py_DECREF(match);
21848 if (!item)
21849 goto error;
21850
21851 /* Add the result to the list. */
21852 if (item != Py_None)
21853 status = add_to_join_list(&join_info, item);
21854
21855 Py_DECREF(item);
21856 if (status < 0)
21857 goto error;
21858 }
21859
21860 ++sub_count;
21861
21862 last_pos = state.text_pos;
21863
21864 /* Don't allow 2 contiguous zero-width matches. */
21865 state.must_advance = state.match_pos == state.text_pos;
21866 }
21867
21868 /* Get the segment following the last match. We use 'length' instead of
21869 * 'text_length' because the latter is truncated to 'slice_end', a
21870 * documented idiosyncracy of the 're' module.
21871 */
21872 end_pos = state.reverse ? 0 : str_info.length;
21873 if (last_pos != end_pos) {
21874 int status;
21875
21876 /* The segment is part of the original string. */
21877 if (state.reverse)
21878 item = get_slice(string, 0, last_pos);
21879 else
21880 item = get_slice(string, last_pos, str_info.length);
21881 if (!item)
21882 goto error;
21883
21884 status = add_to_join_list(&join_info, item);
21885 Py_DECREF(item);
21886 if (status < 0)
21887 goto error;
21888 }
21889
21890 Py_XDECREF(replacement);
21891
21892 /* Convert the list to a single string (also cleans up join_info). */
21893 item = join_list_info(&join_info);
21894
21895 state_fini(&state);
21896
21897 if (built_capture) {
21898 Py_DECREF(kwargs);
21899 Py_DECREF(args);
21900 }
21901
21902 if (!item)
21903 return NULL;
21904
21905 if (sub_type & RE_SUBN)
21906 return Py_BuildValue("Nn", item, sub_count);
21907
21908 return item;
21909
21910 error:
21911 if (built_capture) {
21912 Py_DECREF(kwargs);
21913 Py_DECREF(args);
21914 }
21915
21916 clear_join_list(&join_info);
21917 state_fini(&state);
21918 Py_XDECREF(replacement);
21919 return NULL;
21920 }
21921
21922 /* PatternObject's 'sub' method. */
21923 static PyObject* pattern_sub(PatternObject* self, PyObject* args, PyObject*
21924 kwargs) {
21925 int conc;
21926 Py_ssize_t tim;
21927
21928 PyObject* replacement;
21929 PyObject* string;
21930 Py_ssize_t count = 0;
21931 PyObject* pos = Py_None;
21932 PyObject* endpos = Py_None;
21933 PyObject* concurrent = Py_None;
21934 PyObject* timeout = Py_None;
21935 static char* kwlist[] = { "repl", "string", "count", "pos", "endpos",
21936 "concurrent", "timeout", NULL };
21937 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|nOOOO:sub", kwlist,
21938 &replacement, &string, &count, &pos, &endpos, &concurrent, &timeout))
21939 return NULL;
21940
21941 conc = decode_concurrent(concurrent);
21942 if (conc < 0)
21943 return NULL;
21944
21945 tim = decode_timeout(timeout);
21946 if (tim == RE_BAD_TIMEOUT)
21947 return NULL;
21948
21949 return pattern_subx(self, replacement, string, count, RE_SUB, pos, endpos,
21950 conc, tim);
21951 }
21952
21953 /* PatternObject's 'subf' method. */
21954 static PyObject* pattern_subf(PatternObject* self, PyObject* args, PyObject*
21955 kwargs) {
21956 int conc;
21957 Py_ssize_t tim;
21958
21959 PyObject* format;
21960 PyObject* string;
21961 Py_ssize_t count = 0;
21962 PyObject* pos = Py_None;
21963 PyObject* endpos = Py_None;
21964 PyObject* concurrent = Py_None;
21965 PyObject* timeout = Py_None;
21966 static char* kwlist[] = { "format", "string", "count", "pos", "endpos",
21967 "concurrent", "timeout", NULL };
21968 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|nOOOO:sub", kwlist,
21969 &format, &string, &count, &pos, &endpos, &concurrent, &timeout))
21970 return NULL;
21971
21972 conc = decode_concurrent(concurrent);
21973 if (conc < 0)
21974 return NULL;
21975
21976 tim = decode_timeout(timeout);
21977 if (tim == RE_BAD_TIMEOUT)
21978 return NULL;
21979
21980 return pattern_subx(self, format, string, count, RE_SUBF, pos, endpos,
21981 conc, tim);
21982 }
21983
21984 /* PatternObject's 'subn' method. */
21985 static PyObject* pattern_subn(PatternObject* self, PyObject* args, PyObject*
21986 kwargs) {
21987 int conc;
21988 Py_ssize_t tim;
21989
21990 PyObject* replacement;
21991 PyObject* string;
21992 Py_ssize_t count = 0;
21993 PyObject* pos = Py_None;
21994 PyObject* endpos = Py_None;
21995 PyObject* concurrent = Py_None;
21996 PyObject* timeout = Py_None;
21997 static char* kwlist[] = { "repl", "string", "count", "pos", "endpos",
21998 "concurrent", "timeout", NULL };
21999 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|nOOOO:subn", kwlist,
22000 &replacement, &string, &count, &pos, &endpos, &concurrent, &timeout))
22001 return NULL;
22002
22003 conc = decode_concurrent(concurrent);
22004 if (conc < 0)
22005 return NULL;
22006
22007 tim = decode_timeout(timeout);
22008 if (tim == RE_BAD_TIMEOUT)
22009 return NULL;
22010
22011 return pattern_subx(self, replacement, string, count, RE_SUBN, pos, endpos,
22012 conc, tim);
22013 }
22014
22015 /* PatternObject's 'subfn' method. */
22016 static PyObject* pattern_subfn(PatternObject* self, PyObject* args, PyObject*
22017 kwargs) {
22018 int conc;
22019 Py_ssize_t tim;
22020
22021 PyObject* format;
22022 PyObject* string;
22023 Py_ssize_t count = 0;
22024 PyObject* pos = Py_None;
22025 PyObject* endpos = Py_None;
22026 PyObject* concurrent = Py_None;
22027 PyObject* timeout = Py_None;
22028 static char* kwlist[] = { "format", "string", "count", "pos", "endpos",
22029 "concurrent", "timeout", NULL };
22030 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|nOOOO:subn", kwlist,
22031 &format, &string, &count, &pos, &endpos, &concurrent, &timeout))
22032 return NULL;
22033
22034 conc = decode_concurrent(concurrent);
22035 if (conc < 0)
22036 return NULL;
22037
22038 tim = decode_timeout(timeout);
22039 if (tim == RE_BAD_TIMEOUT)
22040 return NULL;
22041
22042 return pattern_subx(self, format, string, count, RE_SUBF | RE_SUBN, pos,
22043 endpos, conc, tim);
22044 }
22045
22046 /* PatternObject's 'split' method. */
22047 static PyObject* pattern_split(PatternObject* self, PyObject* args, PyObject*
22048 kwargs) {
22049 int conc;
22050 Py_ssize_t tim;
22051 RE_State state;
22052 PyObject* list;
22053 PyObject* item;
22054 int status;
22055 Py_ssize_t split_count;
22056 size_t g;
22057 Py_ssize_t start_pos;
22058 Py_ssize_t last_pos;
22059
22060 PyObject* string;
22061 Py_ssize_t maxsplit = 0;
22062 PyObject* concurrent = Py_None;
22063 PyObject* timeout = Py_None;
22064 static char* kwlist[] = { "string", "maxsplit", "concurrent", "timeout",
22065 NULL };
22066 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|nOO:split", kwlist,
22067 &string, &maxsplit, &concurrent, &timeout))
22068 return NULL;
22069
22070 if (maxsplit == 0)
22071 maxsplit = PY_SSIZE_T_MAX;
22072
22073 conc = decode_concurrent(concurrent);
22074 if (conc < 0)
22075 return NULL;
22076
22077 tim = decode_timeout(timeout);
22078 if (tim == RE_BAD_TIMEOUT)
22079 return NULL;
22080
22081 /* The MatchObject, and therefore repeated captures, will not be visible.
22082 */
22083 if (!state_init(&state, self, string, 0, PY_SSIZE_T_MAX, FALSE, conc,
22084 FALSE, FALSE, FALSE, FALSE, tim))
22085 return NULL;
22086
22087 list = PyList_New(0);
22088 if (!list) {
22089 state_fini(&state);
22090 return NULL;
22091 }
22092
22093 split_count = 0;
22094 if (state.reverse) {
22095 start_pos = state.text_length;
22096 } else {
22097 start_pos = 0;
22098 }
22099
22100 last_pos = start_pos;
22101 while (split_count < maxsplit) {
22102 status = do_match(&state, TRUE);
22103 if (status < 0)
22104 goto error;
22105
22106 if (status == 0)
22107 /* No more matches. */
22108 break;
22109
22110 /* Get segment before this match. */
22111 if (state.reverse)
22112 item = get_slice(string, state.match_pos, last_pos);
22113 else
22114 item = get_slice(string, last_pos, state.match_pos);
22115 if (!item)
22116 goto error;
22117
22118 status = PyList_Append(list, item);
22119 Py_DECREF(item);
22120 if (status < 0)
22121 goto error;
22122
22123 /* Add groups (if any). */
22124 for (g = 1; g <= self->public_group_count; g++) {
22125 item = state_get_group(&state, (Py_ssize_t)g, string, FALSE);
22126 if (!item)
22127 goto error;
22128
22129 status = PyList_Append(list, item);
22130 Py_DECREF(item);
22131 if (status < 0)
22132 goto error;
22133 }
22134
22135 ++split_count;
22136 last_pos = state.text_pos;
22137
22138 /* Don't allow 2 contiguous zero-width matches. */
22139 state.must_advance = state.text_pos == state.match_pos;
22140 }
22141
22142 /* Get segment following last match (even if empty). */
22143 if (state.reverse)
22144 item = get_slice(string, 0, last_pos);
22145 else
22146 item = get_slice(string, last_pos, state.text_length);
22147 if (!item)
22148 goto error;
22149
22150 status = PyList_Append(list, item);
22151 Py_DECREF(item);
22152 if (status < 0)
22153 goto error;
22154
22155 state_fini(&state);
22156
22157 return list;
22158
22159 error:
22160 Py_DECREF(list);
22161 state_fini(&state);
22162 return NULL;
22163 }
22164
22165 /* PatternObject's 'splititer' method. */
22166 static PyObject* pattern_splititer(PatternObject* pattern, PyObject* args,
22167 PyObject* kwargs) {
22168 return pattern_splitter(pattern, args, kwargs);
22169 }
22170
22171 /* PatternObject's 'findall' method. */
22172 static PyObject* pattern_findall(PatternObject* self, PyObject* args, PyObject*
22173 kwargs) {
22174 Py_ssize_t start;
22175 Py_ssize_t end;
22176 int conc;
22177 Py_ssize_t tim;
22178 RE_State state;
22179 PyObject* list;
22180 Py_ssize_t step;
22181 int status;
22182 Py_ssize_t b;
22183 Py_ssize_t e;
22184 size_t g;
22185
22186 PyObject* string;
22187 PyObject* pos = Py_None;
22188 PyObject* endpos = Py_None;
22189 Py_ssize_t overlapped = FALSE;
22190 PyObject* concurrent = Py_None;
22191 PyObject* timeout = Py_None;
22192 static char* kwlist[] = { "string", "pos", "endpos", "overlapped",
22193 "concurrent", "timeout", NULL };
22194 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OOnOO:findall", kwlist,
22195 &string, &pos, &endpos, &overlapped, &concurrent, &timeout))
22196 return NULL;
22197
22198 start = as_string_index(pos, 0);
22199 if (start == -1 && PyErr_Occurred())
22200 return NULL;
22201
22202 end = as_string_index(endpos, PY_SSIZE_T_MAX);
22203 if (end == -1 && PyErr_Occurred())
22204 return NULL;
22205
22206 conc = decode_concurrent(concurrent);
22207 if (conc < 0)
22208 return NULL;
22209
22210 tim = decode_timeout(timeout);
22211 if (tim == RE_BAD_TIMEOUT)
22212 return NULL;
22213
22214 /* The MatchObject, and therefore repeated captures, will not be visible.
22215 */
22216 if (!state_init(&state, self, string, start, end, overlapped != 0, conc,
22217 FALSE, FALSE, FALSE, FALSE, tim))
22218 return NULL;
22219
22220 list = PyList_New(0);
22221 if (!list) {
22222 state_fini(&state);
22223 return NULL;
22224 }
22225
22226 step = state.reverse ? -1 : 1;
22227 while (state.slice_start <= state.text_pos && state.text_pos <=
22228 state.slice_end) {
22229 PyObject* item;
22230
22231 status = do_match(&state, TRUE);
22232 if (status < 0)
22233 goto error;
22234
22235 if (status == 0)
22236 break;
22237
22238 /* Don't bother to build a MatchObject. */
22239 switch (self->visible_capture_count) {
22240 case 0:
22241 if (state.reverse) {
22242 b = state.text_pos;
22243 e = state.match_pos;
22244 } else {
22245 b = state.match_pos;
22246 e = state.text_pos;
22247 }
22248 item = get_slice(string, b, e);
22249 if (!item)
22250 goto error;
22251 break;
22252 case 1:
22253 item = state_get_group(&state, 1, string, TRUE);
22254 if (!item)
22255 goto error;
22256 break;
22257 default:
22258 item = PyTuple_New((Py_ssize_t)self->public_group_count);
22259 if (!item)
22260 goto error;
22261
22262 for (g = 0; g < self->public_group_count; g++) {
22263 PyObject* o;
22264
22265 o = state_get_group(&state, (Py_ssize_t)g + 1, string, TRUE);
22266 if (!o) {
22267 Py_DECREF(item);
22268 goto error;
22269 }
22270
22271 /* PyTuple_SET_ITEM borrows the reference. */
22272 PyTuple_SET_ITEM(item, g, o);
22273 }
22274 break;
22275 }
22276
22277 status = PyList_Append(list, item);
22278 Py_DECREF(item);
22279 if (status < 0)
22280 goto error;
22281
22282 if (state.overlapped) {
22283 /* Advance one character. */
22284 state.text_pos = state.match_pos + step;
22285 state.must_advance = FALSE;
22286 } else
22287 /* Don't allow 2 contiguous zero-width matches. */
22288 state.must_advance = state.text_pos == state.match_pos;
22289 }
22290
22291 state_fini(&state);
22292
22293 return list;
22294
22295 error:
22296 Py_DECREF(list);
22297 state_fini(&state);
22298 return NULL;
22299 }
22300
22301 /* PatternObject's 'finditer' method. */
22302 static PyObject* pattern_finditer(PatternObject* pattern, PyObject* args,
22303 PyObject* kwargs) {
22304 return pattern_scanner(pattern, args, kwargs);
22305 }
22306
22307 /* Makes a copy of a PatternObject.
22308 *
22309 * It actually doesn't make a copy, just returns the original object.
22310 */
22311 Py_LOCAL_INLINE(PyObject*) make_pattern_copy(PatternObject* self) {
22312 Py_INCREF(self);
22313 return (PyObject*)self;
22314 }
22315
22316 /* PatternObject's '__copy__' method. */
22317 static PyObject* pattern_copy(PatternObject* self, PyObject* unused) {
22318 return make_pattern_copy(self);
22319 }
22320
22321 /* PatternObject's '__deepcopy__' method. */
22322 static PyObject* pattern_deepcopy(PatternObject* self, PyObject* memo) {
22323 return make_pattern_copy(self);
22324 }
22325
22326 /* PatternObject's '__sizeof__' method. */
22327 static PyObject* pattern_sizeof(PatternObject* self, PyObject* args) {
22328 Py_ssize_t size;
22329 size_t i;
22330 PyObject* result;
22331
22332 size = sizeof(PatternObject);
22333 size += self->node_count * sizeof(RE_Node);
22334
22335 for (i = 0; i < self->node_count; i++) {
22336 RE_Node* node;
22337
22338 node = self->node_list[i];
22339 size += node->value_count * sizeof(RE_CODE);
22340 }
22341
22342 size += self->true_group_count * sizeof(RE_GroupInfo);
22343 size += self->repeat_count * sizeof(RE_RepeatInfo);
22344
22345 result = PyObject_CallMethod(self->packed_code_list, "__sizeof__", NULL);
22346 if (!result)
22347 return NULL;
22348
22349 size += PyLong_AsSize_t(result);
22350 Py_DECREF(result);
22351
22352 size += self->call_ref_info_count * sizeof(RE_CallRefInfo);
22353
22354 if (self->locale_info)
22355 size += sizeof(RE_LocaleInfo);
22356
22357 return PyLong_FromSsize_t(size);
22358 }
22359
22360 /* The documentation of a PatternObject. */
22361 PyDoc_STRVAR(pattern_match_doc,
22362 "match(string, pos=None, endpos=None, concurrent=None, timeout=None) --> MatchObject or None.\n\
22363 Match zero or more characters at the beginning of the string.");
22364
22365 PyDoc_STRVAR(pattern_fullmatch_doc,
22366 "fullmatch(string, pos=None, endpos=None, concurrent=None, timeout=None) --> MatchObject or None.\n\
22367 Match zero or more characters against all of the string.");
22368
22369 PyDoc_STRVAR(pattern_search_doc,
22370 "search(string, pos=None, endpos=None, concurrent=None, timeout=None) --> MatchObject or None.\n\
22371 Search through string looking for a match, and return a corresponding\n\
22372 match object instance. Return None if no match is found.");
22373
22374 PyDoc_STRVAR(pattern_sub_doc,
22375 "sub(repl, string, count=0, flags=0, pos=None, endpos=None, concurrent=None, timeout=None) --> newstring\n\
22376 Return the string obtained by replacing the leftmost (or rightmost with a\n\
22377 reverse pattern) non-overlapping occurrences of pattern in string by the\n\
22378 replacement repl.");
22379
22380 PyDoc_STRVAR(pattern_subf_doc,
22381 "subf(format, string, count=0, flags=0, pos=None, endpos=None, concurrent=None, timeout=None) --> newstring\n\
22382 Return the string obtained by replacing the leftmost (or rightmost with a\n\
22383 reverse pattern) non-overlapping occurrences of pattern in string by the\n\
22384 replacement format.");
22385
22386 PyDoc_STRVAR(pattern_subn_doc,
22387 "subn(repl, string, count=0, flags=0, pos=None, endpos=None, concurrent=None, timeout=None) --> (newstring, number of subs)\n\
22388 Return the tuple (new_string, number_of_subs_made) found by replacing the\n\
22389 leftmost (or rightmost with a reverse pattern) non-overlapping occurrences\n\
22390 of pattern with the replacement repl.");
22391
22392 PyDoc_STRVAR(pattern_subfn_doc,
22393 "subfn(format, string, count=0, flags=0, pos=None, endpos=None, concurrent=None, timeout=None) --> (newstring, number of subs)\n\
22394 Return the tuple (new_string, number_of_subs_made) found by replacing the\n\
22395 leftmost (or rightmost with a reverse pattern) non-overlapping occurrences\n\
22396 of pattern with the replacement format.");
22397
22398 PyDoc_STRVAR(pattern_split_doc,
22399 "split(string, maxsplit=0, concurrent=None, timeout=None) --> list.\n\
22400 Split string by the occurrences of pattern.");
22401
22402 PyDoc_STRVAR(pattern_splititer_doc,
22403 "splititer(string, maxsplit=0, concurrent=None, timeout=None) --> iterator.\n\
22404 Return an iterator yielding the parts of a split string.");
22405
22406 PyDoc_STRVAR(pattern_findall_doc,
22407 "findall(string, pos=None, endpos=None, overlapped=False, concurrent=None, timeout=None) --> list.\n\
22408 Return a list of all matches of pattern in string. The matches may be\n\
22409 overlapped if overlapped is True.");
22410
22411 PyDoc_STRVAR(pattern_finditer_doc,
22412 "finditer(string, pos=None, endpos=None, overlapped=False, concurrent=None, timeout=None) --> iterator.\n\
22413 Return an iterator over all matches for the RE pattern in string. The\n\
22414 matches may be overlapped if overlapped is True. For each match, the\n\
22415 iterator returns a MatchObject.");
22416
22417 PyDoc_STRVAR(pattern_scanner_doc,
22418 "scanner(string, pos=None, endpos=None, overlapped=False, concurrent=None, timeout=None) --> scanner.\n\
22419 Return an scanner for the RE pattern in string. The matches may be overlapped\n\
22420 if overlapped is True.");
22421
22422 /* The methods of a PatternObject. */
22423 static PyMethodDef pattern_methods[] = {
22424 {"match", (PyCFunction)pattern_match, METH_VARARGS|METH_KEYWORDS,
22425 pattern_match_doc},
22426 {"fullmatch", (PyCFunction)pattern_fullmatch, METH_VARARGS|METH_KEYWORDS,
22427 pattern_fullmatch_doc},
22428 {"search", (PyCFunction)pattern_search, METH_VARARGS|METH_KEYWORDS,
22429 pattern_search_doc},
22430 {"sub", (PyCFunction)pattern_sub, METH_VARARGS|METH_KEYWORDS,
22431 pattern_sub_doc},
22432 {"subf", (PyCFunction)pattern_subf, METH_VARARGS|METH_KEYWORDS,
22433 pattern_subf_doc},
22434 {"subn", (PyCFunction)pattern_subn, METH_VARARGS|METH_KEYWORDS,
22435 pattern_subn_doc},
22436 {"subfn", (PyCFunction)pattern_subfn, METH_VARARGS|METH_KEYWORDS,
22437 pattern_subfn_doc},
22438 {"split", (PyCFunction)pattern_split, METH_VARARGS|METH_KEYWORDS,
22439 pattern_split_doc},
22440 {"splititer", (PyCFunction)pattern_splititer, METH_VARARGS|METH_KEYWORDS,
22441 pattern_splititer_doc},
22442 {"findall", (PyCFunction)pattern_findall, METH_VARARGS|METH_KEYWORDS,
22443 pattern_findall_doc},
22444 {"finditer", (PyCFunction)pattern_finditer, METH_VARARGS|METH_KEYWORDS,
22445 pattern_finditer_doc},
22446 {"scanner", (PyCFunction)pattern_scanner, METH_VARARGS|METH_KEYWORDS,
22447 pattern_scanner_doc},
22448 {"__copy__", (PyCFunction)pattern_copy, METH_NOARGS},
22449 {"__deepcopy__", (PyCFunction)pattern_deepcopy, METH_O},
22450 {"__sizeof__", (PyCFunction)pattern_sizeof, METH_NOARGS|METH_COEXIST},
22451 #if PY_VERSION_HEX >= 0x03090000
22452 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS,
22453 PyDoc_STR("See PEP 585")},
22454 #endif
22455 {NULL, NULL}
22456 };
22457
22458 PyDoc_STRVAR(pattern_doc, "Compiled regex object");
22459
22460 /* Deallocates a PatternObject. */
22461 static void pattern_dealloc(PyObject* self_) {
22462 PatternObject* self;
22463 size_t i;
22464 int partial_side;
22465
22466 self = (PatternObject*)self_;
22467
22468 /* Discard the nodes. */
22469 for (i = 0; i < self->node_count; i++) {
22470 RE_Node* node;
22471
22472 node = self->node_list[i];
22473 re_dealloc(node->values);
22474 if (node->status & RE_STATUS_STRING) {
22475 re_dealloc(node->string.bad_character_offset);
22476 re_dealloc(node->string.good_suffix_offset);
22477 }
22478 re_dealloc(node);
22479 }
22480 re_dealloc(self->node_list);
22481
22482 /* Discard the group info. */
22483 re_dealloc(self->group_info);
22484
22485 /* Discard the call_ref info. */
22486 re_dealloc(self->call_ref_info);
22487
22488 /* Discard the repeat info. */
22489 re_dealloc(self->repeat_info);
22490
22491 dealloc_groups(self->groups_storage, self->true_group_count);
22492
22493 dealloc_repeats(self->repeats_storage, self->repeat_count);
22494
22495 re_dealloc(self->stack_storage);
22496
22497 if (self->weakreflist)
22498 PyObject_ClearWeakRefs((PyObject*)self);
22499 Py_XDECREF(self->pattern);
22500 Py_XDECREF(self->groupindex);
22501 Py_XDECREF(self->indexgroup);
22502
22503 for (partial_side = 0; partial_side < 2; partial_side++) {
22504 if (self->partial_named_lists[partial_side]) {
22505 for (i = 0; i < self->named_lists_count; i++)
22506 Py_XDECREF(self->partial_named_lists[partial_side][i]);
22507
22508 re_dealloc(self->partial_named_lists[partial_side]);
22509 }
22510 }
22511
22512 Py_DECREF(self->named_lists);
22513 Py_DECREF(self->named_list_indexes);
22514 Py_DECREF(self->required_chars);
22515 re_dealloc(self->locale_info);
22516 Py_DECREF(self->packed_code_list);
22517 PyObject_DEL(self);
22518 }
22519
22520 /* Info about the various flags that can be passed in. */
22521 typedef struct RE_FlagName {
22522 char* name;
22523 int value;
22524 } RE_FlagName;
22525
22526 /* We won't bother about the U flag in Python 3. */
22527 static RE_FlagName flag_names[] = {
22528 {"A", RE_FLAG_ASCII},
22529 {"B", RE_FLAG_BESTMATCH},
22530 {"D", RE_FLAG_DEBUG},
22531 {"S", RE_FLAG_DOTALL},
22532 {"F", RE_FLAG_FULLCASE},
22533 {"I", RE_FLAG_IGNORECASE},
22534 {"L", RE_FLAG_LOCALE},
22535 {"M", RE_FLAG_MULTILINE},
22536 {"P", RE_FLAG_POSIX},
22537 {"R", RE_FLAG_REVERSE},
22538 {"T", RE_FLAG_TEMPLATE},
22539 {"X", RE_FLAG_VERBOSE},
22540 {"V0", RE_FLAG_VERSION0},
22541 {"V1", RE_FLAG_VERSION1},
22542 {"W", RE_FLAG_WORD},
22543 };
22544
22545 /* Appends a string to a list. */
22546 Py_LOCAL_INLINE(BOOL) append_string(PyObject* list, char* string) {
22547 PyObject* item;
22548 int status;
22549
22550 item = Py_BuildValue("U", string);
22551 if (!item)
22552 return FALSE;
22553
22554 status = PyList_Append(list, item);
22555 Py_DECREF(item);
22556 if (status < 0)
22557 return FALSE;
22558
22559 return TRUE;
22560 }
22561
22562 /* Appends a (decimal) integer to a list. */
22563 Py_LOCAL_INLINE(BOOL) append_integer(PyObject* list, Py_ssize_t value) {
22564 PyObject* int_obj;
22565 PyObject* repr_obj;
22566 int status;
22567
22568 int_obj = Py_BuildValue("n", value);
22569 if (!int_obj)
22570 return FALSE;
22571
22572 repr_obj = PyObject_Repr(int_obj);
22573 Py_DECREF(int_obj);
22574 if (!repr_obj)
22575 return FALSE;
22576
22577 status = PyList_Append(list, repr_obj);
22578 Py_DECREF(repr_obj);
22579 if (status < 0)
22580 return FALSE;
22581
22582 return TRUE;
22583 }
22584
22585 /* Packs the code list that's needed for pickling. */
22586 Py_LOCAL_INLINE(PyObject*) pack_code_list(RE_CODE* code, Py_ssize_t code_len) {
22587 Py_ssize_t max_size;
22588 RE_UINT8* packed;
22589 Py_ssize_t count;
22590 RE_UINT32 value;
22591 Py_ssize_t i;
22592 PyObject* packed_code_list;
22593
22594 /* What is the maximum number of bytes needed to store it?
22595 *
22596 * A 32-bit RE_CODE might need 5 bytes ((32 + 6) / 7).
22597 */
22598 max_size = code_len * 5 + (Py_ssize_t)((sizeof(Py_ssize_t) * 8) + 6) / 7;
22599
22600 packed = (RE_UINT8*)re_alloc((size_t)max_size);
22601 count = 0;
22602
22603 /* Store the length of the code list. */
22604 value = (RE_UINT32)code_len;
22605
22606 while (value >= 0x80) {
22607 packed[count++] = 0x80 | (RE_UINT8)(value & 0x7F);
22608 value >>= 7;
22609 }
22610
22611 packed[count++] = (RE_UINT8)value;
22612
22613 /* Store each of the elements of the code list. */
22614 for (i = 0; i < code_len; i++) {
22615 value = (RE_UINT32)code[i];
22616
22617 while (value >= 0x80) {
22618 packed[count++] = 0x80 | (RE_UINT8)(value & 0x7F);
22619 value >>= 7;
22620 }
22621
22622 packed[count++] = (RE_UINT8)value;
22623 }
22624
22625 packed_code_list = PyBytes_FromStringAndSize((const char *)packed, count);
22626 re_dealloc(packed);
22627
22628 return packed_code_list;
22629 }
22630
22631 /* Unpacks the code list that's needed for pickling. */
22632 Py_LOCAL_INLINE(PyObject*) unpack_code_list(PyObject* packed) {
22633 PyObject* code_list;
22634 RE_UINT8* packed_data;
22635 Py_ssize_t index;
22636 RE_UINT32 value;
22637 int shift;
22638 size_t count;
22639
22640 code_list = PyList_New(0);
22641 if (!code_list)
22642 return NULL;
22643
22644 packed_data = (RE_UINT8*)PyBytes_AsString(packed);
22645 index = 0;
22646
22647 /* Unpack the length of the code list. */
22648 value = 0;
22649 shift = 0;
22650
22651 while (packed_data[index] >= 0x80) {
22652 value |= (RE_UINT32)(packed_data[index++] & 0x7F) << shift;
22653 shift += 7;
22654 }
22655
22656 value |= (RE_UINT32)packed_data[index++] << shift;
22657 count = (size_t)value;
22658
22659 /* Unpack each of the elements of the code list. */
22660 while (count > 0) {
22661 PyObject* obj;
22662 int status;
22663
22664 value = 0;
22665 shift = 0;
22666
22667 while (packed_data[index] >= 0x80) {
22668 value |= (RE_UINT32)(packed_data[index++] & 0x7F) << shift;
22669 shift += 7;
22670 }
22671
22672 value |= (RE_UINT32)packed_data[index++] << shift;
22673 obj = PyLong_FromSize_t((size_t)value);
22674 if (!obj)
22675 goto error;
22676
22677 status = PyList_Append(code_list, obj);
22678 Py_DECREF(obj);
22679 if (status == -1)
22680 goto error;
22681
22682 --count;
22683 }
22684
22685 return code_list;
22686
22687 error:
22688 Py_DECREF(code_list);
22689 return NULL;
22690 }
22691
22692 /* MatchObject's '__repr__' method. */
22693 static PyObject* match_repr(PyObject* self_) {
22694 MatchObject* self;
22695 PyObject* list;
22696 PyObject* matched_substring;
22697 PyObject* matched_repr;
22698 int status;
22699 PyObject* separator;
22700 PyObject* result;
22701
22702 self = (MatchObject*)self_;
22703
22704 list = PyList_New(0);
22705 if (!list)
22706 return NULL;
22707
22708 if (!append_string(list, "<regex.Match object; span=("))
22709 goto error;
22710
22711 if (!append_integer(list, self->match_start))
22712 goto error;
22713
22714 if (!append_string(list, ", "))
22715 goto error;
22716
22717 if (!append_integer(list, self->match_end))
22718 goto error;
22719
22720 if (!append_string(list, "), match="))
22721 goto error;
22722
22723 matched_substring = get_slice(self->substring, self->match_start -
22724 self->substring_offset, self->match_end - self->substring_offset);
22725 if (!matched_substring)
22726 goto error;
22727
22728 matched_repr = PyObject_Repr(matched_substring);
22729 Py_DECREF(matched_substring);
22730 if (!matched_repr)
22731 goto error;
22732
22733 status = PyList_Append(list, matched_repr);
22734 Py_DECREF(matched_repr);
22735 if (status < 0)
22736 goto error;
22737
22738 if (self->fuzzy_counts[RE_FUZZY_SUB] != 0 ||
22739 self->fuzzy_counts[RE_FUZZY_INS] != 0 || self->fuzzy_counts[RE_FUZZY_DEL]
22740 != 0) {
22741 if (!append_string(list, ", fuzzy_counts=("))
22742 goto error;
22743
22744 if (!append_integer(list,
22745 (Py_ssize_t)self->fuzzy_counts[RE_FUZZY_SUB]))
22746 goto error;
22747
22748 if (!append_string(list, ", "))
22749 goto error;
22750
22751 if (!append_integer(list,
22752 (Py_ssize_t)self->fuzzy_counts[RE_FUZZY_INS]))
22753 goto error;
22754
22755 if (!append_string(list, ", "))
22756 goto error;
22757 if (!append_integer(list,
22758 (Py_ssize_t)self->fuzzy_counts[RE_FUZZY_DEL]))
22759 goto error;
22760
22761 if (!append_string(list, ")"))
22762 goto error;
22763 }
22764
22765 if (self->partial) {
22766 if (!append_string(list, ", partial=True"))
22767 goto error;
22768 }
22769
22770 if (!append_string(list, ">"))
22771 goto error;
22772
22773 separator = Py_BuildValue("U", "");
22774 if (!separator)
22775 goto error;
22776
22777 result = PyUnicode_Join(separator, list);
22778 Py_DECREF(separator);
22779 Py_DECREF(list);
22780
22781 return result;
22782
22783 error:
22784 Py_DECREF(list);
22785 return NULL;
22786 }
22787
22788 /* PatternObject's '__repr__' method. */
22789 static PyObject* pattern_repr(PyObject* self_) {
22790 PatternObject* self;
22791 PyObject* list;
22792 PyObject* item;
22793 int status;
22794 int flag_count;
22795 unsigned int i;
22796 Py_ssize_t pos;
22797 PyObject* key;
22798 PyObject* value;
22799 PyObject* separator;
22800 PyObject* result;
22801
22802 self = (PatternObject*)self_;
22803
22804 list = PyList_New(0);
22805 if (!list)
22806 return NULL;
22807
22808 if (!append_string(list, "regex.Regex("))
22809 goto error;
22810
22811 item = PyObject_Repr(self->pattern);
22812 if (!item)
22813 goto error;
22814
22815 status = PyList_Append(list, item);
22816 Py_DECREF(item);
22817 if (status < 0)
22818 goto error;
22819
22820 flag_count = 0;
22821 for (i = 0; i < sizeof(flag_names) / sizeof(flag_names[0]); i++) {
22822 if (self->flags & flag_names[i].value) {
22823 if (flag_count == 0) {
22824 if (!append_string(list, ", flags="))
22825 goto error;
22826 } else {
22827 if (!append_string(list, " | "))
22828 goto error;
22829 }
22830
22831 if (!append_string(list, "regex."))
22832 goto error;
22833
22834 if (!append_string(list, flag_names[i].name))
22835 goto error;
22836
22837 ++flag_count;
22838 }
22839 }
22840
22841 pos = 0;
22842 /* PyDict_Next borrows references. */
22843 while (PyDict_Next(self->named_lists, &pos, &key, &value)) {
22844 if (!append_string(list, ", "))
22845 goto error;
22846
22847 status = PyList_Append(list, key);
22848 if (status < 0)
22849 goto error;
22850
22851 if (!append_string(list, "="))
22852 goto error;
22853
22854 item = PyObject_Repr(value);
22855 if (!item)
22856 goto error;
22857
22858 status = PyList_Append(list, item);
22859 Py_DECREF(item);
22860 if (status < 0)
22861 goto error;
22862 }
22863
22864 if (!append_string(list, ")"))
22865 goto error;
22866
22867 separator = Py_BuildValue("U", "");
22868 if (!separator)
22869 goto error;
22870
22871 result = PyUnicode_Join(separator, list);
22872 Py_DECREF(separator);
22873 Py_DECREF(list);
22874
22875 return result;
22876
22877 error:
22878 Py_DECREF(list);
22879 return NULL;
22880 }
22881
22882 /* PatternObject's 'groupindex' method. */
22883 static PyObject* pattern_groupindex(PyObject* self_) {
22884 PatternObject* self;
22885
22886 self = (PatternObject*)self_;
22887
22888 return PyDict_Copy(self->groupindex);
22889 }
22890
22891 /* PatternObject's '_pickled_data' method. */
22892 static PyObject* pattern_pickled_data(PyObject* self_) {
22893 PatternObject* self;
22894 PyObject* pickled_data;
22895
22896 self = (PatternObject*)self_;
22897
22898 /* Build the data needed for picking. */
22899 pickled_data = Py_BuildValue("OnOOOOOnOnn", self->pattern, self->flags,
22900 self->packed_code_list, self->groupindex, self->indexgroup,
22901 self->named_lists, self->named_list_indexes, self->req_offset,
22902 self->required_chars, self->req_flags, self->public_group_count);
22903
22904 return pickled_data;
22905 }
22906
22907 static PyGetSetDef pattern_getset[] = {
22908 {"groupindex", (getter)pattern_groupindex, (setter)NULL,
22909 "A dictionary mapping group names to group numbers."},
22910 {"_pickled_data", (getter)pattern_pickled_data, (setter)NULL,
22911 "Data used for pickling."},
22912 {NULL} /* Sentinel */
22913 };
22914
22915 static PyMemberDef pattern_members[] = {
22916 {"pattern", T_OBJECT, offsetof(PatternObject, pattern), READONLY,
22917 "The pattern string from which the regex object was compiled."},
22918 {"flags", T_PYSSIZET, offsetof(PatternObject, flags), READONLY,
22919 "The regex matching flags."},
22920 {"groups", T_PYSSIZET, offsetof(PatternObject, public_group_count),
22921 READONLY, "The number of capturing groups in the pattern."},
22922 {"named_lists", T_OBJECT, offsetof(PatternObject, named_lists), READONLY,
22923 "The named lists used by the regex."},
22924 {NULL} /* Sentinel */
22925 };
22926
22927 static PyTypeObject Pattern_Type = {
22928 PyVarObject_HEAD_INIT(NULL, 0)
22929 "_regex.Pattern",
22930 sizeof(PatternObject)
22931 };
22932
22933 /* Building the nodes is made simpler by allowing branches to have a single
22934 * exit. These need to be removed.
22935 */
22936 Py_LOCAL_INLINE(void) skip_one_way_branches(PatternObject* pattern) {
22937 BOOL modified;
22938
22939 /* If a node refers to a 1-way branch then make the former refer to the
22940 * latter's destination. Repeat until they're all done.
22941 */
22942 do {
22943 size_t i;
22944
22945 modified = FALSE;
22946
22947 for (i = 0; i < pattern->node_count; i++) {
22948 RE_Node* node;
22949 RE_Node* next;
22950
22951 node = pattern->node_list[i];
22952
22953 /* Check the first destination. */
22954 next = node->next_1.node;
22955 if (next && next->op == RE_OP_BRANCH &&
22956 !next->nonstring.next_2.node) {
22957 node->next_1.node = next->next_1.node;
22958 modified = TRUE;
22959 }
22960
22961 /* Check the second destination. */
22962 next = node->nonstring.next_2.node;
22963 if (next && next->op == RE_OP_BRANCH &&
22964 !next->nonstring.next_2.node) {
22965 node->nonstring.next_2.node = next->next_1.node;
22966 modified = TRUE;
22967 }
22968
22969 /* Check the true branch for CONDITIONAL. */
22970 next = node->nonstring.true_node;
22971 if (next && next->op == RE_OP_BRANCH &&
22972 !next->nonstring.true_node) {
22973 node->nonstring.true_node = next->next_1.node;
22974 modified = TRUE;
22975 }
22976 }
22977 } while (modified);
22978
22979 /* The start node might be a 1-way branch. Skip over it because it'll be
22980 * removed. It might even be the first in a chain.
22981 */
22982 while (pattern->start_node->op == RE_OP_BRANCH &&
22983 !pattern->start_node->nonstring.next_2.node)
22984 pattern->start_node = pattern->start_node->next_1.node;
22985 }
22986
22987 /* Initialises a check stack. */
22988 Py_LOCAL_INLINE(void) CheckStack_init(RE_CheckStack* stack) {
22989 stack->capacity = 0;
22990 stack->count = 0;
22991 stack->items = NULL;
22992 }
22993
22994 /* Finalises a check stack. */
22995 Py_LOCAL_INLINE(void) CheckStack_fini(RE_CheckStack* stack) {
22996 PyMem_Free(stack->items);
22997 stack->capacity = 0;
22998 stack->count = 0;
22999 stack->items = NULL;
23000 }
23001
23002 /* Pushes an item onto a check stack. */
23003 Py_LOCAL_INLINE(BOOL) CheckStack_push(RE_CheckStack* stack, RE_Node* node,
23004 RE_STATUS_T result) {
23005 RE_Check* check;
23006
23007 if (stack->count >= stack->capacity) {
23008 size_t new_capacity;
23009 RE_Check* new_items;
23010
23011 new_capacity = stack->capacity * 2;
23012 if (new_capacity == 0)
23013 new_capacity = 16;
23014
23015 new_items = (RE_Check*)PyMem_Realloc(stack->items, new_capacity *
23016 sizeof(RE_Check));
23017 if (!new_items)
23018 return FALSE;
23019
23020 stack->capacity = new_capacity;
23021 stack->items = new_items;
23022 }
23023
23024 check = &stack->items[stack->count++];
23025 check->node = node;
23026 check->result = result;
23027
23028 return TRUE;
23029 }
23030
23031 /* Pops an item off a check stack. Returns NULL if the stack is empty. */
23032 Py_LOCAL_INLINE(RE_Check*) CheckStack_pop(RE_CheckStack* stack) {
23033 return stack->count > 0 ? &stack->items[--stack->count] : NULL;
23034 }
23035
23036 /* Adds guards to repeats which are followed by a reference to a group. */
23037 Py_LOCAL_INLINE(RE_STATUS_T) add_repeat_guards(PatternObject* pattern, RE_Node*
23038 start_node) {
23039 RE_CheckStack stack;
23040
23041 CheckStack_init(&stack);
23042
23043 CheckStack_push(&stack, start_node, RE_STATUS_NEITHER);
23044
23045 for (;;) {
23046 RE_Check* check;
23047 RE_Node* node;
23048 RE_STATUS_T result;
23049
23050 check = CheckStack_pop(&stack);
23051
23052 if (!check)
23053 break;
23054
23055 node = check->node;
23056 result = check->result;
23057
23058 if (!(node->status & RE_STATUS_VISITED_AG)) {
23059 switch (check->node->op) {
23060 case RE_OP_BRANCH:
23061 {
23062 RE_Node* branch_1;
23063 RE_Node* branch_2;
23064 BOOL visited_branch_1;
23065 BOOL visited_branch_2;
23066
23067 branch_1 = node->next_1.node;
23068 branch_2 = node->nonstring.next_2.node;
23069 visited_branch_1 = (branch_1->status & RE_STATUS_VISITED_AG);
23070 visited_branch_2 = (branch_2->status & RE_STATUS_VISITED_AG);
23071
23072 if (visited_branch_1 && visited_branch_2) {
23073 RE_STATUS_T branch_1_result;
23074 RE_STATUS_T branch_2_result;
23075
23076 branch_1_result = branch_1->status & (RE_STATUS_REPEAT |
23077 RE_STATUS_REF);
23078 branch_2_result = branch_2->status & (RE_STATUS_REPEAT |
23079 RE_STATUS_REF);
23080
23081 node->status |= RE_STATUS_VISITED_AG | max_status_3(result,
23082 branch_1_result, branch_2_result);
23083 } else {
23084 CheckStack_push(&stack, node, result);
23085 if (!visited_branch_2)
23086 CheckStack_push(&stack, branch_2, RE_STATUS_NEITHER);
23087 if (!visited_branch_1)
23088 CheckStack_push(&stack, branch_1, RE_STATUS_NEITHER);
23089 }
23090 break;
23091 }
23092 case RE_OP_END_GREEDY_REPEAT:
23093 case RE_OP_END_LAZY_REPEAT:
23094 node->status |= RE_STATUS_VISITED_AG;
23095 break;
23096 case RE_OP_GREEDY_REPEAT:
23097 case RE_OP_LAZY_REPEAT:
23098 {
23099 BOOL limited;
23100 RE_Node* body;
23101 RE_Node* tail;
23102 BOOL visited_body;
23103 BOOL visited_tail;
23104
23105 limited = ~node->values[2] != 0;
23106
23107 body = node->next_1.node;
23108 tail = node->nonstring.next_2.node;
23109 visited_body = (body->status & RE_STATUS_VISITED_AG);
23110 visited_tail = (tail->status & RE_STATUS_VISITED_AG);
23111
23112 if (visited_body && visited_tail) {
23113 RE_STATUS_T body_result;
23114 RE_STATUS_T tail_result;
23115 RE_RepeatInfo* repeat_info;
23116
23117 body_result = body->status & (RE_STATUS_REPEAT |
23118 RE_STATUS_REF);
23119 tail_result = tail->status & (RE_STATUS_REPEAT |
23120 RE_STATUS_REF);
23121
23122 repeat_info = &pattern->repeat_info[node->values[0]];
23123 if (body_result != RE_STATUS_REF)
23124 repeat_info->status |= RE_STATUS_BODY;
23125 if (tail_result != RE_STATUS_REF)
23126 repeat_info->status |= RE_STATUS_TAIL;
23127
23128 if (limited)
23129 result = max_status_2(result, RE_STATUS_LIMITED);
23130 else
23131 result = max_status_2(result, RE_STATUS_REPEAT);
23132 node->status |= RE_STATUS_VISITED_AG | max_status_3(result,
23133 body_result, tail_result);
23134 } else {
23135 CheckStack_push(&stack, node, result);
23136 if (!visited_tail)
23137 CheckStack_push(&stack, tail, RE_STATUS_NEITHER);
23138 if (!visited_body) {
23139 if (limited)
23140 body->status |= RE_STATUS_VISITED_AG |
23141 RE_STATUS_LIMITED;
23142 else
23143 CheckStack_push(&stack, body, RE_STATUS_NEITHER);
23144 }
23145 }
23146 break;
23147 }
23148 case RE_OP_GREEDY_REPEAT_ONE:
23149 case RE_OP_LAZY_REPEAT_ONE:
23150 {
23151 RE_Node* tail;
23152 BOOL visited_tail;
23153
23154 tail = node->next_1.node;
23155 visited_tail = (tail->status & RE_STATUS_VISITED_AG);
23156
23157 if (visited_tail) {
23158 BOOL limited;
23159 RE_STATUS_T tail_result;
23160 RE_RepeatInfo* repeat_info;
23161
23162 limited = ~node->values[2] != 0;
23163
23164 tail_result = tail->status & (RE_STATUS_REPEAT |
23165 RE_STATUS_REF);
23166
23167 repeat_info = &pattern->repeat_info[node->values[0]];
23168 /* Removing guard here to fix issue 494 and prevent
23169 * regression of issue 495.
23170 */
23171 /* repeat_info->status |= RE_STATUS_BODY; */
23172
23173 if (tail_result != RE_STATUS_REF)
23174 repeat_info->status |= RE_STATUS_TAIL;
23175
23176 if (limited)
23177 result = max_status_2(result, RE_STATUS_LIMITED);
23178 else
23179 result = max_status_2(result, RE_STATUS_REPEAT);
23180 node->status |= RE_STATUS_VISITED_AG | max_status_3(result,
23181 RE_STATUS_REPEAT, tail_result);
23182 } else {
23183 CheckStack_push(&stack, node, result);
23184 CheckStack_push(&stack, tail, RE_STATUS_NEITHER);
23185 }
23186 break;
23187 }
23188 case RE_OP_GROUP_EXISTS:
23189 {
23190 RE_Node* branch_1;
23191 RE_Node* branch_2;
23192 BOOL visited_branch_1;
23193 BOOL visited_branch_2;
23194
23195 branch_1 = node->next_1.node;
23196 branch_2 = node->nonstring.next_2.node;
23197 visited_branch_1 = (branch_1->status & RE_STATUS_VISITED_AG);
23198 visited_branch_2 = (branch_2->status & RE_STATUS_VISITED_AG);
23199
23200 if (visited_branch_1 && visited_branch_2) {
23201 RE_STATUS_T branch_1_result;
23202 RE_STATUS_T branch_2_result;
23203
23204 branch_1_result = branch_1->status & (RE_STATUS_REPEAT |
23205 RE_STATUS_REF);
23206 branch_2_result = branch_2->status & (RE_STATUS_REPEAT |
23207 RE_STATUS_REF);
23208
23209 node->status |= RE_STATUS_VISITED_AG | max_status_4(result,
23210 branch_1_result, branch_2_result, RE_STATUS_REF);
23211 } else {
23212 CheckStack_push(&stack, node, result);
23213 if (!visited_branch_2)
23214 CheckStack_push(&stack, branch_2, RE_STATUS_NEITHER);
23215 if (!visited_branch_1)
23216 CheckStack_push(&stack, branch_1, RE_STATUS_NEITHER);
23217 }
23218 break;
23219 }
23220 case RE_OP_REF_GROUP:
23221 case RE_OP_REF_GROUP_FLD:
23222 case RE_OP_REF_GROUP_FLD_REV:
23223 case RE_OP_REF_GROUP_IGN:
23224 case RE_OP_REF_GROUP_IGN_REV:
23225 case RE_OP_REF_GROUP_REV:
23226 {
23227 RE_Node* tail;
23228 BOOL visited_tail;
23229
23230 tail = node->next_1.node;
23231 visited_tail = (tail->status & RE_STATUS_VISITED_AG);
23232
23233 if (visited_tail)
23234 node->status |= RE_STATUS_VISITED_AG | RE_STATUS_REF;
23235 else {
23236 CheckStack_push(&stack, node, result);
23237 CheckStack_push(&stack, tail, RE_STATUS_NEITHER);
23238 }
23239 break;
23240 }
23241 case RE_OP_SUCCESS:
23242 node->status |= RE_STATUS_VISITED_AG | result;
23243 break;
23244 default:
23245 {
23246 RE_Node* tail;
23247 BOOL visited_tail;
23248 RE_STATUS_T tail_result;
23249
23250 tail = node->next_1.node;
23251
23252 if (!tail) {
23253 node->status |= RE_STATUS_VISITED_AG | result;
23254 break;
23255 }
23256
23257 visited_tail = (tail->status & RE_STATUS_VISITED_AG);
23258
23259 if (visited_tail) {
23260 tail_result = tail->status & (RE_STATUS_REPEAT |
23261 RE_STATUS_REF);
23262 node->status |= RE_STATUS_VISITED_AG | tail_result;
23263 } else {
23264 CheckStack_push(&stack, node, result);
23265 CheckStack_push(&stack, node->next_1.node, result);
23266 }
23267 break;
23268 }
23269 }
23270 }
23271 }
23272
23273 CheckStack_fini(&stack);
23274
23275 return start_node->status & (RE_STATUS_REPEAT | RE_STATUS_REF);
23276 }
23277
23278 /* Adds an index to a node's values unless it's already present.
23279 *
23280 * 'offset' is the offset of the index count within the values.
23281 */
23282 Py_LOCAL_INLINE(BOOL) add_index(RE_Node* node, size_t offset, size_t index) {
23283 size_t index_count;
23284 size_t first_index;
23285 size_t i;
23286 RE_CODE* new_values;
23287
23288 if (!node)
23289 return TRUE;
23290
23291 index_count = node->values[offset];
23292 first_index = offset + 1;
23293
23294 /* Is the index already present? */
23295 for (i = 0; i < index_count; i++) {
23296 if (node->values[first_index + i] == index)
23297 return TRUE;
23298 }
23299
23300 /* Allocate more space for the new index. */
23301 new_values = re_realloc(node->values, (node->value_count + 1) *
23302 sizeof(RE_CODE));
23303 if (!new_values)
23304 return FALSE;
23305
23306 ++node->value_count;
23307 node->values = new_values;
23308
23309 node->values[first_index + node->values[offset]++] = (RE_CODE)index;
23310
23311 return TRUE;
23312 }
23313
23314 /* Records the index of every repeat and fuzzy section within atomic
23315 * subpatterns and lookarounds.
23316 */
23317 Py_LOCAL_INLINE(BOOL) record_subpattern_repeats_and_fuzzy_sections(RE_Node*
23318 parent_node, size_t offset, size_t repeat_count, RE_Node* node) {
23319 while (node) {
23320 if (node->status & RE_STATUS_VISITED_REP)
23321 return TRUE;
23322
23323 node->status |= RE_STATUS_VISITED_REP;
23324
23325 switch (node->op) {
23326 case RE_OP_BRANCH:
23327 case RE_OP_GROUP_EXISTS:
23328 if (!record_subpattern_repeats_and_fuzzy_sections(parent_node,
23329 offset, repeat_count, node->next_1.node))
23330 return FALSE;
23331 node = node->nonstring.next_2.node;
23332 break;
23333 case RE_OP_END_FUZZY:
23334 node = node->next_1.node;
23335 break;
23336 case RE_OP_END_GREEDY_REPEAT:
23337 case RE_OP_END_LAZY_REPEAT:
23338 return TRUE;
23339 case RE_OP_FUZZY:
23340 /* Record the fuzzy index. */
23341 if (!add_index(parent_node, offset, repeat_count +
23342 node->values[0]))
23343 return FALSE;
23344 node = node->next_1.node;
23345 break;
23346 case RE_OP_GREEDY_REPEAT:
23347 case RE_OP_LAZY_REPEAT:
23348 /* Record the repeat index. */
23349 if (!add_index(parent_node, offset, node->values[0]))
23350 return FALSE;
23351 if (!record_subpattern_repeats_and_fuzzy_sections(parent_node,
23352 offset, repeat_count, node->next_1.node))
23353 return FALSE;
23354 node = node->nonstring.next_2.node;
23355 break;
23356 case RE_OP_GREEDY_REPEAT_ONE:
23357 case RE_OP_LAZY_REPEAT_ONE:
23358 /* Record the repeat index. */
23359 if (!add_index(parent_node, offset, node->values[0]))
23360 return FALSE;
23361 node = node->next_1.node;
23362 break;
23363 default:
23364 node = node->next_1.node;
23365 break;
23366 }
23367 }
23368
23369 return TRUE;
23370 }
23371
23372 /* Initialises a node stack. */
23373 Py_LOCAL_INLINE(void) NodeStack_init(RE_NodeStack* stack) {
23374 stack->capacity = 0;
23375 stack->count = 0;
23376 stack->items = NULL;
23377 }
23378
23379 /* Finalises a node stack. */
23380 Py_LOCAL_INLINE(void) NodeStack_fini(RE_NodeStack* stack) {
23381 PyMem_Free(stack->items);
23382 stack->capacity = 0;
23383 stack->count = 0;
23384 stack->items = NULL;
23385 }
23386
23387 /* Pushes an item onto a node stack. */
23388 Py_LOCAL_INLINE(BOOL) NodeStack_push(RE_NodeStack* stack, RE_Node* node) {
23389 if (stack->count >= stack->capacity) {
23390 size_t new_capacity;
23391 RE_Node** new_items;
23392
23393 new_capacity = stack->capacity * 2;
23394 if (new_capacity == 0)
23395 new_capacity = 16;
23396
23397 new_items = (RE_Node**)PyMem_Realloc(stack->items, new_capacity *
23398 sizeof(RE_Node*));
23399 if (!new_items)
23400 return FALSE;
23401
23402 stack->capacity = new_capacity;
23403 stack->items = new_items;
23404 }
23405
23406 stack->items[stack->count++] = node;
23407
23408 return TRUE;
23409 }
23410
23411 /* Pops an item off a node stack. Returns NULL if the stack is empty. */
23412 Py_LOCAL_INLINE(RE_Node*) NodeStack_pop(RE_NodeStack* stack) {
23413 return stack->count > 0 ? stack->items[--stack->count] : NULL;
23414 }
23415
23416 /* Marks nodes which are being used as used. */
23417 Py_LOCAL_INLINE(void) use_nodes(RE_Node* node) {
23418 RE_NodeStack stack;
23419
23420 NodeStack_init(&stack);
23421
23422 while (node) {
23423 while (node && !(node->status & RE_STATUS_USED)) {
23424 node->status |= RE_STATUS_USED;
23425 if (!(node->status & RE_STATUS_STRING)) {
23426 if (node->nonstring.next_2.node)
23427 NodeStack_push(&stack, node->nonstring.next_2.node);
23428 }
23429 node = node->next_1.node;
23430 }
23431 node = NodeStack_pop(&stack);
23432 }
23433
23434 NodeStack_fini(&stack);
23435 }
23436
23437 /* Discards any unused nodes.
23438 *
23439 * Optimising the nodes might result in some nodes no longer being used.
23440 */
23441 Py_LOCAL_INLINE(void) discard_unused_nodes(PatternObject* pattern) {
23442 size_t i;
23443 size_t new_count;
23444
23445 /* Mark the nodes which are being used. */
23446 use_nodes(pattern->start_node);
23447
23448 for (i = 0; i < pattern->call_ref_info_capacity; i++)
23449 use_nodes(pattern->call_ref_info[i].node);
23450
23451 new_count = 0;
23452 for (i = 0; i < pattern->node_count; i++) {
23453 RE_Node* node;
23454
23455 node = pattern->node_list[i];
23456 if (node->status & RE_STATUS_USED)
23457 pattern->node_list[new_count++] = node;
23458 else {
23459 re_dealloc(node->values);
23460 if (node->status & RE_STATUS_STRING) {
23461 re_dealloc(node->string.bad_character_offset);
23462 re_dealloc(node->string.good_suffix_offset);
23463 }
23464 re_dealloc(node);
23465 }
23466 }
23467
23468 pattern->node_count = new_count;
23469 }
23470
23471 /* Marks all the group which are named. Returns FALSE if there's an error. */
23472 Py_LOCAL_INLINE(BOOL) mark_named_groups(PatternObject* pattern) {
23473 size_t i;
23474
23475 for (i = 0; i < pattern->public_group_count; i++) {
23476 RE_GroupInfo* group_info;
23477 PyObject* index;
23478 int status;
23479
23480 group_info = &pattern->group_info[i];
23481 index = Py_BuildValue("n", i + 1);
23482 if (!index)
23483 return FALSE;
23484
23485 status = PyDict_Contains(pattern->indexgroup, index);
23486 Py_DECREF(index);
23487 if (status < 0)
23488 return FALSE;
23489
23490 group_info->has_name = status == 1;
23491 }
23492
23493 return TRUE;
23494 }
23495
23496 /* Checks whether you can look ahead of this node for testing for a match. */
23497 Py_LOCAL_INLINE(BOOL) can_test_past(RE_Node* node) {
23498 switch (node->op) {
23499 case RE_OP_END_GROUP:
23500 case RE_OP_START_GROUP:
23501 return TRUE;
23502 case RE_OP_GREEDY_REPEAT:
23503 case RE_OP_LAZY_REPEAT:
23504 return node->values[1] > 0;
23505 default:
23506 return FALSE;
23507 }
23508 }
23509
23510 /* Gets the test node.
23511 *
23512 * The test node lets the matcher look ahead in the pattern, allowing it to
23513 * avoid the cost of housekeeping, only to find that what follows doesn't match
23514 * anyway.
23515 */
23516 Py_LOCAL_INLINE(void) set_test_node(RE_NextNode* next) {
23517 RE_Node* node = next->node;
23518 RE_Node* test;
23519
23520 next->test = node;
23521 next->match_next = node;
23522 next->match_step = 0;
23523
23524 if (!node)
23525 return;
23526
23527 test = node;
23528 while (can_test_past(test))
23529 test = test->next_1.node;
23530
23531 next->test = test;
23532
23533 if (test != node)
23534 return;
23535
23536 switch (test->op) {
23537 case RE_OP_ANY:
23538 case RE_OP_ANY_ALL:
23539 case RE_OP_ANY_ALL_REV:
23540 case RE_OP_ANY_REV:
23541 case RE_OP_ANY_U:
23542 case RE_OP_ANY_U_REV:
23543 case RE_OP_BOUNDARY:
23544 case RE_OP_CHARACTER:
23545 case RE_OP_CHARACTER_IGN:
23546 case RE_OP_CHARACTER_IGN_REV:
23547 case RE_OP_CHARACTER_REV:
23548 case RE_OP_DEFAULT_BOUNDARY:
23549 case RE_OP_DEFAULT_END_OF_WORD:
23550 case RE_OP_DEFAULT_START_OF_WORD:
23551 case RE_OP_END_OF_LINE:
23552 case RE_OP_END_OF_LINE_U:
23553 case RE_OP_END_OF_STRING:
23554 case RE_OP_END_OF_STRING_LINE:
23555 case RE_OP_END_OF_STRING_LINE_U:
23556 case RE_OP_END_OF_WORD:
23557 case RE_OP_GRAPHEME_BOUNDARY:
23558 case RE_OP_PROPERTY:
23559 case RE_OP_PROPERTY_IGN:
23560 case RE_OP_PROPERTY_IGN_REV:
23561 case RE_OP_PROPERTY_REV:
23562 case RE_OP_RANGE:
23563 case RE_OP_RANGE_IGN:
23564 case RE_OP_RANGE_IGN_REV:
23565 case RE_OP_RANGE_REV:
23566 case RE_OP_SEARCH_ANCHOR:
23567 case RE_OP_SET_DIFF:
23568 case RE_OP_SET_DIFF_IGN:
23569 case RE_OP_SET_DIFF_IGN_REV:
23570 case RE_OP_SET_DIFF_REV:
23571 case RE_OP_SET_INTER:
23572 case RE_OP_SET_INTER_IGN:
23573 case RE_OP_SET_INTER_IGN_REV:
23574 case RE_OP_SET_INTER_REV:
23575 case RE_OP_SET_SYM_DIFF:
23576 case RE_OP_SET_SYM_DIFF_IGN:
23577 case RE_OP_SET_SYM_DIFF_IGN_REV:
23578 case RE_OP_SET_SYM_DIFF_REV:
23579 case RE_OP_SET_UNION:
23580 case RE_OP_SET_UNION_IGN:
23581 case RE_OP_SET_UNION_IGN_REV:
23582 case RE_OP_SET_UNION_REV:
23583 case RE_OP_START_OF_LINE:
23584 case RE_OP_START_OF_LINE_U:
23585 case RE_OP_START_OF_STRING:
23586 case RE_OP_START_OF_WORD:
23587 case RE_OP_STRING:
23588 case RE_OP_STRING_FLD:
23589 case RE_OP_STRING_FLD_REV:
23590 case RE_OP_STRING_IGN:
23591 case RE_OP_STRING_IGN_REV:
23592 case RE_OP_STRING_REV:
23593 next->match_next = test->next_1.node;
23594 next->match_step = test->step;
23595 break;
23596 case RE_OP_GREEDY_REPEAT_ONE:
23597 case RE_OP_LAZY_REPEAT_ONE:
23598 if (test->values[1] > 0)
23599 next->test = test;
23600 break;
23601 }
23602 }
23603
23604 /* Sets the test nodes. */
23605 Py_LOCAL_INLINE(void) set_test_nodes(PatternObject* pattern) {
23606 RE_Node** node_list;
23607 size_t i;
23608
23609 node_list = pattern->node_list;
23610 for (i = 0; i < pattern->node_count; i++) {
23611 RE_Node* node;
23612
23613 node = node_list[i];
23614 set_test_node(&node->next_1);
23615 if (!(node->status & RE_STATUS_STRING))
23616 set_test_node(&node->nonstring.next_2);
23617 }
23618 }
23619
23620 /* Optimises the pattern. */
23621 Py_LOCAL_INLINE(BOOL) optimise_pattern(PatternObject* pattern) {
23622 size_t i;
23623
23624 /* Building the nodes is made simpler by allowing branches to have a single
23625 * exit. These need to be removed.
23626 */
23627 skip_one_way_branches(pattern);
23628
23629 /* Add position guards for repeat bodies containing a reference to a group
23630 * or repeat tails followed at some point by a reference to a group.
23631 */
23632 add_repeat_guards(pattern, pattern->start_node);
23633
23634 /* Record the index of repeats and fuzzy sections within the body of atomic
23635 * and lookaround nodes.
23636 */
23637 if (!record_subpattern_repeats_and_fuzzy_sections(NULL, 0,
23638 pattern->repeat_count, pattern->start_node))
23639 return FALSE;
23640
23641 for (i = 0; i < pattern->call_ref_info_count; i++) {
23642 RE_Node* node;
23643
23644 node = pattern->call_ref_info[i].node;
23645 if (!record_subpattern_repeats_and_fuzzy_sections(NULL, 0,
23646 pattern->repeat_count, node))
23647 return FALSE;
23648 }
23649
23650 /* Discard any unused nodes. */
23651 discard_unused_nodes(pattern);
23652
23653 /* Set the test nodes. */
23654 set_test_nodes(pattern);
23655
23656 /* Mark all the group that are named. */
23657 if (!mark_named_groups(pattern))
23658 return FALSE;
23659
23660 return TRUE;
23661 }
23662
23663 /* Creates a new pattern node. */
23664 Py_LOCAL_INLINE(RE_Node*) create_node(PatternObject* pattern, RE_UINT8 op,
23665 RE_CODE flags, Py_ssize_t step, size_t value_count) {
23666 RE_Node* node;
23667
23668 node = (RE_Node*)re_alloc(sizeof(*node));
23669 if (!node)
23670 return NULL;
23671 memset(node, 0, sizeof(RE_Node));
23672
23673 node->value_count = value_count;
23674
23675 if (node->value_count > 0) {
23676 node->values = (RE_CODE*)re_alloc(node->value_count * sizeof(RE_CODE));
23677 if (!node->values)
23678 goto error;
23679 } else
23680 node->values = NULL;
23681
23682 node->op = op;
23683 node->match = (flags & RE_POSITIVE_OP) != 0;
23684 node->status = (RE_STATUS_T)(flags << RE_STATUS_SHIFT);
23685 node->step = step;
23686
23687 /* Ensure that there's enough storage to record the new node. */
23688 if (pattern->node_count >= pattern->node_capacity) {
23689 size_t new_capacity;
23690 RE_Node** new_node_list;
23691
23692 new_capacity = pattern->node_capacity * 2;
23693
23694 if (new_capacity == 0)
23695 new_capacity = 16;
23696
23697 new_node_list = (RE_Node**)re_realloc(pattern->node_list, new_capacity
23698 * sizeof(RE_Node*));
23699 if (!new_node_list)
23700 goto error;
23701
23702 pattern->node_list = new_node_list;
23703 pattern->node_capacity = new_capacity;
23704 }
23705
23706 /* Record the new node. */
23707 pattern->node_list[pattern->node_count++] = node;
23708
23709 return node;
23710
23711 error:
23712 re_dealloc(node->values);
23713 re_dealloc(node);
23714 return NULL;
23715 }
23716
23717 /* Adds a node as a next node for another node. */
23718 Py_LOCAL_INLINE(void) add_node(RE_Node* node_1, RE_Node* node_2) {
23719 if (!node_1->next_1.node)
23720 node_1->next_1.node = node_2;
23721 else
23722 node_1->nonstring.next_2.node = node_2;
23723 }
23724
23725 /* Ensures that the entry for a group's details actually exists. */
23726 Py_LOCAL_INLINE(BOOL) ensure_group(PatternObject* pattern, size_t group) {
23727 size_t old_capacity;
23728 size_t new_capacity;
23729 RE_GroupInfo* new_group_info;
23730
23731 if (group <= pattern->true_group_count)
23732 /* We already have an entry for the group. */
23733 return TRUE;
23734
23735 /* Increase the storage capacity to include the new entry if it's
23736 * insufficient.
23737 */
23738 old_capacity = pattern->group_info_capacity;
23739 new_capacity = pattern->group_info_capacity;
23740
23741 while (group > new_capacity)
23742 new_capacity += 16;
23743
23744 if (new_capacity > old_capacity) {
23745 new_group_info = (RE_GroupInfo*)re_realloc(pattern->group_info,
23746 new_capacity * sizeof(RE_GroupInfo));
23747 if (!new_group_info)
23748 return FALSE;
23749
23750 memset(new_group_info + old_capacity, 0, (new_capacity - old_capacity)
23751 * sizeof(RE_GroupInfo));
23752
23753 pattern->group_info = new_group_info;
23754 pattern->group_info_capacity = new_capacity;
23755 }
23756
23757 pattern->true_group_count = group;
23758
23759 return TRUE;
23760 }
23761
23762 /* Records that there's a reference to a group. */
23763 Py_LOCAL_INLINE(BOOL) record_ref_group(PatternObject* pattern, size_t group) {
23764 if (!ensure_group(pattern, group))
23765 return FALSE;
23766
23767 pattern->group_info[group - 1].referenced = TRUE;
23768
23769 return TRUE;
23770 }
23771
23772 /* Records that there's a new group. */
23773 Py_LOCAL_INLINE(BOOL) record_group(PatternObject* pattern, size_t group,
23774 RE_Node* node) {
23775 if (!ensure_group(pattern, group))
23776 return FALSE;
23777
23778 if (group >= 1) {
23779 RE_GroupInfo* info;
23780
23781 info = &pattern->group_info[group - 1];
23782 info->end_index = (Py_ssize_t)pattern->true_group_count;
23783 info->node = node;
23784 }
23785
23786 return TRUE;
23787 }
23788
23789 /* Records that a group has closed. */
23790 Py_LOCAL_INLINE(void) record_group_end(PatternObject* pattern, size_t group) {
23791 if (group >= 1)
23792 pattern->group_info[group - 1].end_index = ++pattern->group_end_index;
23793 }
23794
23795 /* Ensures that the entry for a call_ref's details actually exists. */
23796 Py_LOCAL_INLINE(BOOL) ensure_call_ref(PatternObject* pattern, size_t call_ref)
23797 {
23798 size_t old_capacity;
23799 size_t new_capacity;
23800 RE_CallRefInfo* new_call_ref_info;
23801
23802 if (call_ref < pattern->call_ref_info_count)
23803 /* We already have an entry for the call_ref. */
23804 return TRUE;
23805
23806 /* Increase the storage capacity to include the new entry if it's
23807 * insufficient.
23808 */
23809 old_capacity = pattern->call_ref_info_capacity;
23810 new_capacity = pattern->call_ref_info_capacity;
23811 while (call_ref >= new_capacity)
23812 new_capacity += 16;
23813
23814 if (new_capacity > old_capacity) {
23815 new_call_ref_info = (RE_CallRefInfo*)re_realloc(pattern->call_ref_info,
23816 new_capacity * sizeof(RE_CallRefInfo));
23817 if (!new_call_ref_info)
23818 return FALSE;
23819
23820 memset(new_call_ref_info + old_capacity, 0, (new_capacity -
23821 old_capacity) * sizeof(RE_CallRefInfo));
23822
23823 pattern->call_ref_info = new_call_ref_info;
23824 pattern->call_ref_info_capacity = new_capacity;
23825 }
23826
23827 pattern->call_ref_info_count = 1 + call_ref;
23828
23829 return TRUE;
23830 }
23831
23832 /* Records that a call_ref is defined. */
23833 Py_LOCAL_INLINE(BOOL) record_call_ref_defined(PatternObject* pattern, size_t
23834 call_ref, RE_Node* node) {
23835 if (!ensure_call_ref(pattern, call_ref))
23836 return FALSE;
23837
23838 pattern->call_ref_info[call_ref].defined = TRUE;
23839 pattern->call_ref_info[call_ref].node = node;
23840
23841 return TRUE;
23842 }
23843
23844 /* Records that a call_ref is used. */
23845 Py_LOCAL_INLINE(BOOL) record_call_ref_used(PatternObject* pattern, size_t
23846 call_ref) {
23847 if (!ensure_call_ref(pattern, call_ref))
23848 return FALSE;
23849
23850 pattern->call_ref_info[call_ref].used = TRUE;
23851
23852 return TRUE;
23853 }
23854
23855 /* Checks whether a node matches one and only one character. */
23856 Py_LOCAL_INLINE(BOOL) sequence_matches_one(RE_Node* node) {
23857 while (node->op == RE_OP_BRANCH && !node->nonstring.next_2.node)
23858 node = node->next_1.node;
23859
23860 if (node->next_1.node || (node->status & RE_STATUS_FUZZY))
23861 return FALSE;
23862
23863 return node_matches_one_character(node);
23864 }
23865
23866 /* Records a repeat. */
23867 Py_LOCAL_INLINE(BOOL) record_repeat(PatternObject* pattern, size_t index,
23868 size_t repeat_depth) {
23869 size_t old_capacity;
23870 size_t new_capacity;
23871
23872 /* Increase the storage capacity to include the new entry if it's
23873 * insufficient.
23874 */
23875 old_capacity = pattern->repeat_info_capacity;
23876 new_capacity = pattern->repeat_info_capacity;
23877 while (index >= new_capacity)
23878 new_capacity += 16;
23879
23880 if (new_capacity > old_capacity) {
23881 RE_RepeatInfo* new_repeat_info;
23882
23883 new_repeat_info = (RE_RepeatInfo*)re_realloc(pattern->repeat_info,
23884 new_capacity * sizeof(RE_RepeatInfo));
23885 if (!new_repeat_info)
23886 return FALSE;
23887
23888 memset(new_repeat_info + old_capacity, 0, (new_capacity - old_capacity)
23889 * sizeof(RE_RepeatInfo));
23890
23891 pattern->repeat_info = new_repeat_info;
23892 pattern->repeat_info_capacity = new_capacity;
23893 }
23894
23895 if (index >= pattern->repeat_count)
23896 pattern->repeat_count = index + 1;
23897
23898 if (repeat_depth > 0)
23899 pattern->repeat_info[index].status |= RE_STATUS_INNER;
23900
23901 return TRUE;
23902 }
23903
23904 Py_LOCAL_INLINE(Py_ssize_t) get_step(RE_CODE op) {
23905 switch (op) {
23906 case RE_OP_ANY:
23907 case RE_OP_ANY_ALL:
23908 case RE_OP_ANY_U:
23909 case RE_OP_CHARACTER:
23910 case RE_OP_CHARACTER_IGN:
23911 case RE_OP_PROPERTY:
23912 case RE_OP_PROPERTY_IGN:
23913 case RE_OP_RANGE:
23914 case RE_OP_RANGE_IGN:
23915 case RE_OP_SET_DIFF:
23916 case RE_OP_SET_DIFF_IGN:
23917 case RE_OP_SET_INTER:
23918 case RE_OP_SET_INTER_IGN:
23919 case RE_OP_SET_SYM_DIFF:
23920 case RE_OP_SET_SYM_DIFF_IGN:
23921 case RE_OP_SET_UNION:
23922 case RE_OP_SET_UNION_IGN:
23923 case RE_OP_STRING:
23924 case RE_OP_STRING_FLD:
23925 case RE_OP_STRING_IGN:
23926 return 1;
23927 case RE_OP_ANY_ALL_REV:
23928 case RE_OP_ANY_REV:
23929 case RE_OP_ANY_U_REV:
23930 case RE_OP_CHARACTER_IGN_REV:
23931 case RE_OP_CHARACTER_REV:
23932 case RE_OP_PROPERTY_IGN_REV:
23933 case RE_OP_PROPERTY_REV:
23934 case RE_OP_RANGE_IGN_REV:
23935 case RE_OP_RANGE_REV:
23936 case RE_OP_SET_DIFF_IGN_REV:
23937 case RE_OP_SET_DIFF_REV:
23938 case RE_OP_SET_INTER_IGN_REV:
23939 case RE_OP_SET_INTER_REV:
23940 case RE_OP_SET_SYM_DIFF_IGN_REV:
23941 case RE_OP_SET_SYM_DIFF_REV:
23942 case RE_OP_SET_UNION_IGN_REV:
23943 case RE_OP_SET_UNION_REV:
23944 case RE_OP_STRING_FLD_REV:
23945 case RE_OP_STRING_IGN_REV:
23946 case RE_OP_STRING_REV:
23947 return -1;
23948 }
23949
23950 return 0;
23951 }
23952
23953 Py_LOCAL_INLINE(int) build_charset_equiv(RE_CompileArgs* args);
23954 Py_LOCAL_INLINE(int) build_sequence(RE_CompileArgs* args);
23955
23956 /* Builds an ANY node. */
23957 Py_LOCAL_INLINE(int) build_ANY(RE_CompileArgs* args) {
23958 RE_UINT8 op;
23959 RE_CODE flags;
23960 Py_ssize_t step;
23961 RE_Node* node;
23962
23963 /* codes: opcode, flags. */
23964 if (args->code + 1 > args->end_code)
23965 return RE_ERROR_ILLEGAL;
23966
23967 op = (RE_UINT8)args->code[0];
23968 flags = args->code[1];
23969
23970 step = get_step(op);
23971
23972 /* Create the node. */
23973 node = create_node(args->pattern, op, flags, step, 0);
23974 if (!node)
23975 return RE_ERROR_MEMORY;
23976
23977 node->match = TRUE;
23978 args->code += 2;
23979
23980 /* Append the node. */
23981 add_node(args->end, node);
23982 args->end = node;
23983
23984 ++args->min_width;
23985
23986 return RE_ERROR_SUCCESS;
23987 }
23988
23989 /* Builds a FUZZY node. */
23990 Py_LOCAL_INLINE(int) build_FUZZY(RE_CompileArgs* args) {
23991 BOOL is_ext;
23992 RE_CODE flags;
23993 RE_Node* start_node;
23994 RE_Node* end_node;
23995 RE_CODE index;
23996 RE_CompileArgs subargs;
23997 RE_Node* test_node;
23998 int status;
23999
24000 /* codes: FUZZY, flags, constraints, ..., end
24001 * or: FUZZY_EXT, flags,
24002 * constraints, ... next ..., end.
24003 */
24004 is_ext = args->code[0] == RE_OP_FUZZY_EXT;
24005 if (args->code + (is_ext ? 15 : 13) > args->end_code)
24006 return RE_ERROR_ILLEGAL;
24007
24008 flags = args->code[1];
24009
24010 /* Create nodes for the start and end of the fuzzy sequence. */
24011 start_node = create_node(args->pattern, RE_OP_FUZZY, flags, 0, 13);
24012 end_node = create_node(args->pattern, RE_OP_END_FUZZY, flags, 0, 0);
24013 if (!start_node || !end_node)
24014 return RE_ERROR_MEMORY;
24015
24016 index = (RE_CODE)args->pattern->fuzzy_count++;
24017 start_node->values[0] = index;
24018
24019 /* The constraints consist of 4 pairs of limits and the cost equation. */
24020 start_node->values[RE_FUZZY_VAL_MIN_DEL] = args->code[2]; /* Deletion minimum. */
24021 start_node->values[RE_FUZZY_VAL_MIN_INS] = args->code[4]; /* Insertion minimum. */
24022 start_node->values[RE_FUZZY_VAL_MIN_SUB] = args->code[6]; /* Substitution minimum. */
24023 start_node->values[RE_FUZZY_VAL_MIN_ERR] = args->code[8]; /* Error minimum. */
24024
24025 start_node->values[RE_FUZZY_VAL_MAX_DEL] = args->code[3]; /* Deletion maximum. */
24026 start_node->values[RE_FUZZY_VAL_MAX_INS] = args->code[5]; /* Insertion maximum. */
24027 start_node->values[RE_FUZZY_VAL_MAX_SUB] = args->code[7]; /* Substitution maximum. */
24028 start_node->values[RE_FUZZY_VAL_MAX_ERR] = args->code[9]; /* Error maximum. */
24029
24030 start_node->values[RE_FUZZY_VAL_DEL_COST] = args->code[10]; /* Deletion cost. */
24031 start_node->values[RE_FUZZY_VAL_INS_COST] = args->code[11]; /* Insertion cost. */
24032 start_node->values[RE_FUZZY_VAL_SUB_COST] = args->code[12]; /* Substitution cost. */
24033 start_node->values[RE_FUZZY_VAL_MAX_COST] = args->code[13]; /* Total cost. */
24034
24035 args->code += 14;
24036
24037 if (is_ext) {
24038 subargs = *args;
24039 status = build_charset_equiv(&subargs);
24040 if (status != RE_ERROR_SUCCESS)
24041 return status;
24042 args->code = subargs.code;
24043 if (args->code >= args->end_code || args->code[0] != RE_OP_NEXT)
24044 return RE_ERROR_ILLEGAL;
24045 ++args->code;
24046 test_node = subargs.start;
24047 } else
24048 test_node = NULL;
24049
24050 subargs = *args;
24051 subargs.within_fuzzy = TRUE;
24052
24053 /* Compile the sequence and check that we've reached the end of the
24054 * subpattern.
24055 */
24056 status = build_sequence(&subargs);
24057 if (status != RE_ERROR_SUCCESS)
24058 return status;
24059
24060 if (subargs.code[0] != RE_OP_END)
24061 return RE_ERROR_ILLEGAL;
24062
24063 args->code = subargs.code;
24064 args->min_width += subargs.min_width;
24065 args->has_captures |= subargs.has_captures;
24066 args->is_fuzzy = TRUE;
24067 args->has_groups |= subargs.has_groups;
24068 args->has_repeats |= subargs.has_repeats;
24069 args->visible_capture_count = subargs.visible_capture_count;
24070
24071 ++args->code;
24072
24073 /* Append the fuzzy sequence. */
24074 add_node(args->end, start_node);
24075 add_node(start_node, subargs.start);
24076 if (test_node) {
24077 add_node(start_node, test_node);
24078 /* The END_FUZZY node needs access to the charset, if any, in case of
24079 fuzzy insertion at the end.
24080 */
24081 end_node->nonstring.next_2.node = start_node;
24082 }
24083 add_node(subargs.end, end_node);
24084 args->end = end_node;
24085 args->all_atomic = FALSE;
24086
24087 return RE_ERROR_SUCCESS;
24088 }
24089
24090 /* Builds an ATOMIC node. */
24091 Py_LOCAL_INLINE(int) build_ATOMIC(RE_CompileArgs* args) {
24092 RE_Node* atomic_node;
24093 RE_CompileArgs subargs;
24094 int status;
24095 RE_Node* end_node;
24096
24097 /* codes: opcode, ..., end. */
24098 if (args->code + 1 > args->end_code)
24099 return RE_ERROR_ILLEGAL;
24100
24101 atomic_node = create_node(args->pattern, RE_OP_ATOMIC, 0, 0, 0);
24102 if (!atomic_node)
24103 return RE_ERROR_MEMORY;
24104
24105 ++args->code;
24106
24107 /* Compile the sequence and check that we've reached the end of it. */
24108 subargs = *args;
24109
24110 status = build_sequence(&subargs);
24111 if (status != RE_ERROR_SUCCESS)
24112 return status;
24113
24114 if (subargs.code[0] != RE_OP_END)
24115 return RE_ERROR_ILLEGAL;
24116
24117 args->code = subargs.code;
24118 args->min_width += subargs.min_width;
24119 args->has_captures |= subargs.has_captures;
24120 args->is_fuzzy |= subargs.is_fuzzy;
24121 args->has_groups |= subargs.has_groups;
24122 args->has_repeats |= subargs.has_repeats;
24123 args->visible_capture_count = subargs.visible_capture_count;
24124
24125 ++args->code;
24126
24127 /* Check the subpattern. */
24128 if (subargs.has_groups)
24129 atomic_node->status |= RE_STATUS_HAS_GROUPS;
24130
24131 if (subargs.has_repeats)
24132 atomic_node->status |= RE_STATUS_HAS_REPEATS;
24133
24134 /* Create the node to terminate the subpattern. */
24135 end_node = create_node(subargs.pattern, RE_OP_END_ATOMIC, 0, 0, 0);
24136 if (!end_node)
24137 return RE_ERROR_MEMORY;
24138
24139 /* Append the new sequence. */
24140 add_node(args->end, atomic_node);
24141 add_node(atomic_node, subargs.start);
24142 add_node(subargs.end, end_node);
24143 args->end = end_node;
24144
24145 return RE_ERROR_SUCCESS;
24146 }
24147
24148 /* Builds a BOUNDARY node. */
24149 Py_LOCAL_INLINE(int) build_BOUNDARY(RE_CompileArgs* args) {
24150 RE_UINT8 op;
24151 RE_CODE flags;
24152 RE_Node* node;
24153
24154 /* codes: opcode, flags. */
24155 if (args->code + 1 > args->end_code)
24156 return RE_ERROR_ILLEGAL;
24157
24158 op = (RE_UINT8)args->code[0];
24159 flags = args->code[1];
24160
24161 args->code += 2;
24162
24163 /* Create the node. */
24164 node = create_node(args->pattern, op, flags, 0, 0);
24165 if (!node)
24166 return RE_ERROR_MEMORY;
24167
24168 /* Append the node. */
24169 add_node(args->end, node);
24170 args->end = node;
24171
24172 return RE_ERROR_SUCCESS;
24173 }
24174
24175 /* Builds a BRANCH node. */
24176 Py_LOCAL_INLINE(int) build_BRANCH(RE_CompileArgs* args) {
24177 RE_Node* branch_node;
24178 RE_Node* join_node;
24179 Py_ssize_t min_width;
24180 RE_CompileArgs subargs;
24181 int status;
24182
24183 /* codes: opcode, ..., next, ..., end. */
24184 if (args->code + 2 > args->end_code)
24185 return RE_ERROR_ILLEGAL;
24186
24187 /* Create nodes for the start and end of the branch sequence. */
24188 branch_node = create_node(args->pattern, RE_OP_BRANCH, 0, 0, 0);
24189 join_node = create_node(args->pattern, RE_OP_BRANCH, 0, 0, 0);
24190 if (!branch_node || !join_node)
24191 return RE_ERROR_MEMORY;
24192
24193 /* Append the node. */
24194 add_node(args->end, branch_node);
24195 args->end = join_node;
24196
24197 min_width = PY_SSIZE_T_MAX;
24198
24199 subargs = *args;
24200
24201 /* A branch in the regular expression is compiled into a series of 2-way
24202 * branches.
24203 */
24204 do {
24205 RE_Node* next_branch_node;
24206
24207 /* Skip over the 'BRANCH' or 'NEXT' opcode. */
24208 ++subargs.code;
24209
24210 /* Compile the sequence until the next 'BRANCH' or 'NEXT' opcode. */
24211 status = build_sequence(&subargs);
24212 if (status != RE_ERROR_SUCCESS)
24213 return status;
24214
24215 min_width = min_ssize_t(min_width, subargs.min_width);
24216
24217 args->has_captures |= subargs.has_captures;
24218 args->is_fuzzy |= subargs.is_fuzzy;
24219 args->has_groups |= subargs.has_groups;
24220 args->has_repeats |= subargs.has_repeats;
24221
24222 /* Append the sequence. */
24223 add_node(branch_node, subargs.start);
24224 add_node(subargs.end, join_node);
24225
24226 /* Create a start node for the next sequence and append it. */
24227 next_branch_node = create_node(subargs.pattern, RE_OP_BRANCH, 0, 0, 0);
24228 if (!next_branch_node)
24229 return RE_ERROR_MEMORY;
24230
24231 add_node(branch_node, next_branch_node);
24232 branch_node = next_branch_node;
24233 } while (subargs.code < subargs.end_code && subargs.code[0] == RE_OP_NEXT);
24234
24235 /* We should have reached the end of the branch. */
24236 if (subargs.code[0] != RE_OP_END)
24237 return RE_ERROR_ILLEGAL;
24238
24239 args->code = subargs.code;
24240 args->visible_capture_count = subargs.visible_capture_count;
24241
24242 ++args->code;
24243 args->min_width += min_width;
24244 args->all_atomic = FALSE;
24245
24246 return RE_ERROR_SUCCESS;
24247 }
24248
24249 /* Builds a CALL_REF node. */
24250 Py_LOCAL_INLINE(int) build_CALL_REF(RE_CompileArgs* args) {
24251 RE_CODE call_ref;
24252 RE_Node* start_node;
24253 RE_Node* end_node;
24254 RE_CompileArgs subargs;
24255 int status;
24256
24257 /* codes: opcode, call_ref. */
24258 if (args->code + 1 > args->end_code)
24259 return RE_ERROR_ILLEGAL;
24260
24261 call_ref = args->code[1];
24262
24263 args->code += 2;
24264
24265 /* Create nodes for the start and end of the subpattern. */
24266 start_node = create_node(args->pattern, RE_OP_CALL_REF, 0, 0, 1);
24267 end_node = create_node(args->pattern, RE_OP_GROUP_RETURN, 0, 0, 0);
24268 if (!start_node || !end_node)
24269 return RE_ERROR_MEMORY;
24270
24271 start_node->values[0] = call_ref;
24272
24273 /* Compile the sequence and check that we've reached the end of the
24274 * subpattern.
24275 */
24276 subargs = *args;
24277 status = build_sequence(&subargs);
24278 if (status != RE_ERROR_SUCCESS)
24279 return status;
24280
24281 if (subargs.code[0] != RE_OP_END)
24282 return RE_ERROR_ILLEGAL;
24283
24284 args->code = subargs.code;
24285 args->min_width += subargs.min_width;
24286 args->has_captures |= subargs.has_captures;
24287 args->is_fuzzy |= subargs.is_fuzzy;
24288 args->has_groups |= subargs.has_groups;
24289 args->has_repeats |= subargs.has_repeats;
24290 args->visible_capture_count = subargs.visible_capture_count;
24291
24292 ++args->code;
24293
24294 /* Record that we defined a call_ref. */
24295 if (!record_call_ref_defined(args->pattern, call_ref, start_node))
24296 return RE_ERROR_MEMORY;
24297
24298 /* Append the node. */
24299 add_node(args->end, start_node);
24300 add_node(start_node, subargs.start);
24301 add_node(subargs.end, end_node);
24302 args->end = end_node;
24303 args->all_atomic = FALSE;
24304
24305 return RE_ERROR_SUCCESS;
24306 }
24307
24308 /* Builds a CHARACTER or PROPERTY node. */
24309 Py_LOCAL_INLINE(int) build_CHARACTER_or_PROPERTY(RE_CompileArgs* args) {
24310 RE_UINT8 op;
24311 RE_CODE flags;
24312 Py_ssize_t step;
24313 RE_Node* node;
24314
24315 /* codes: opcode, flags, value. */
24316 if (args->code + 2 > args->end_code)
24317 return RE_ERROR_ILLEGAL;
24318
24319 op = (RE_UINT8)args->code[0];
24320 flags = args->code[1];
24321
24322 step = get_step(op);
24323
24324 if (flags & RE_ZEROWIDTH_OP)
24325 step = 0;
24326
24327 /* Create the node. */
24328 node = create_node(args->pattern, op, flags, step, 1);
24329 if (!node)
24330 return RE_ERROR_MEMORY;
24331
24332 node->values[0] = args->code[2];
24333
24334 args->code += 3;
24335
24336 /* Append the node. */
24337 add_node(args->end, node);
24338 args->end = node;
24339
24340 if (step != 0)
24341 ++args->min_width;
24342
24343 return RE_ERROR_SUCCESS;
24344 }
24345
24346 /* Builds a CONDITIONAL node. */
24347 Py_LOCAL_INLINE(int) build_CONDITIONAL(RE_CompileArgs* args) {
24348 RE_CODE flags;
24349 BOOL forward;
24350 RE_Node* test_node;
24351 RE_CompileArgs subargs;
24352 int status;
24353 RE_Node* end_test_node;
24354 RE_Node* end_node;
24355 Py_ssize_t min_width;
24356
24357 /* codes: opcode, flags, forward, ..., next, ..., next, ..., end. */
24358 if (args->code + 4 > args->end_code)
24359 return RE_ERROR_ILLEGAL;
24360
24361 flags = args->code[1];
24362 forward = (BOOL)args->code[2];
24363
24364 /* Create a node for the lookaround. */
24365 test_node = create_node(args->pattern, RE_OP_CONDITIONAL, flags, 0, 0);
24366 if (!test_node)
24367 return RE_ERROR_MEMORY;
24368
24369 args->code += 3;
24370
24371 add_node(args->end, test_node);
24372
24373 /* Compile the lookaround test and check that we've reached the end of the
24374 * subpattern.
24375 */
24376 subargs = *args;
24377 subargs.forward = forward;
24378 status = build_sequence(&subargs);
24379 if (status != RE_ERROR_SUCCESS)
24380 return status;
24381
24382 if (subargs.code[0] != RE_OP_NEXT)
24383 return RE_ERROR_ILLEGAL;
24384
24385 args->code = subargs.code;
24386 args->has_captures |= subargs.has_captures;
24387 args->is_fuzzy |= subargs.is_fuzzy;
24388 args->has_groups |= subargs.has_groups;
24389 args->has_repeats |= subargs.has_repeats;
24390 args->visible_capture_count = subargs.visible_capture_count;
24391
24392 ++args->code;
24393
24394 /* Check the lookaround subpattern. */
24395 if (subargs.has_groups)
24396 test_node->status |= RE_STATUS_HAS_GROUPS;
24397
24398 if (subargs.has_repeats)
24399 test_node->status |= RE_STATUS_HAS_REPEATS;
24400
24401 /* Create the node to terminate the test. */
24402 end_test_node = create_node(args->pattern, RE_OP_END_CONDITIONAL, 0, 0, 0);
24403 if (!end_test_node)
24404 return RE_ERROR_MEMORY;
24405
24406 /* test node -> test -> end test node */
24407 add_node(test_node, subargs.start);
24408 add_node(subargs.end, end_test_node);
24409
24410 /* Compile the true branch. */
24411 subargs = *args;
24412 status = build_sequence(&subargs);
24413 if (status != RE_ERROR_SUCCESS)
24414 return status;
24415
24416 /* Check the true branch. */
24417 args->code = subargs.code;
24418 args->has_captures |= subargs.has_captures;
24419 args->is_fuzzy |= subargs.is_fuzzy;
24420 args->has_groups |= subargs.has_groups;
24421 args->has_repeats |= subargs.has_repeats;
24422 args->visible_capture_count = subargs.visible_capture_count;
24423
24424 min_width = subargs.min_width;
24425
24426 /* Create the terminating node. */
24427 end_node = create_node(args->pattern, RE_OP_BRANCH, 0, 0, 0);
24428 if (!end_node)
24429 return RE_ERROR_MEMORY;
24430
24431 /* end test node -> true branch -> end node */
24432 add_node(end_test_node, subargs.start);
24433 add_node(subargs.end, end_node);
24434 test_node->nonstring.true_node = subargs.start;
24435
24436 if (args->code[0] == RE_OP_NEXT) {
24437 /* There's a false branch. */
24438 ++args->code;
24439
24440 /* Compile the false branch. */
24441 subargs.code = args->code;
24442 status = build_sequence(&subargs);
24443 if (status != RE_ERROR_SUCCESS)
24444 return status;
24445
24446 /* Check the false branch. */
24447 args->code = subargs.code;
24448 args->has_captures |= subargs.has_captures;
24449 args->is_fuzzy |= subargs.is_fuzzy;
24450 args->has_groups |= subargs.has_groups;
24451 args->has_repeats |= subargs.has_repeats;
24452 args->visible_capture_count = subargs.visible_capture_count;
24453
24454 min_width = min_ssize_t(min_width, subargs.min_width);
24455
24456 /* test node -> false branch -> end node */
24457 add_node(test_node, subargs.start);
24458 add_node(subargs.end, end_node);
24459 } else {
24460 min_width = 0;
24461
24462 /* test node -> end node */
24463 add_node(test_node, end_node);
24464 }
24465
24466 if (args->code[0] != RE_OP_END)
24467 return RE_ERROR_ILLEGAL;
24468
24469 args->min_width += min_width;
24470
24471 ++args->code;
24472
24473 args->end = end_node;
24474 args->all_atomic = FALSE;
24475
24476 return RE_ERROR_SUCCESS;
24477 }
24478
24479 /* Builds a GROUP node. */
24480 Py_LOCAL_INLINE(int) build_GROUP(RE_CompileArgs* args) {
24481 BOOL forward;
24482 RE_CODE private_group;
24483 RE_CODE public_group;
24484 RE_Node* start_node;
24485 RE_Node* end_node;
24486 RE_CompileArgs subargs;
24487 int status;
24488
24489 /* codes: opcode, forward, private_group, public_group, ..., end. */
24490 if (args->code + 3 > args->end_code)
24491 return RE_ERROR_ILLEGAL;
24492
24493 forward = (BOOL)args->code[1];
24494 private_group = args->code[2];
24495 public_group = args->code[3];
24496
24497 args->code += 4;
24498
24499 /* Create nodes for the start and end of the capture group. */
24500 start_node = create_node(args->pattern, forward ? RE_OP_START_GROUP :
24501 RE_OP_END_GROUP, 0, 0, 3);
24502 end_node = create_node(args->pattern, forward ? RE_OP_END_GROUP :
24503 RE_OP_START_GROUP, 0, 0, 3);
24504 if (!start_node || !end_node)
24505 return RE_ERROR_MEMORY;
24506
24507 start_node->values[0] = private_group;
24508 end_node->values[0] = private_group;
24509 start_node->values[1] = public_group;
24510 end_node->values[1] = public_group;
24511
24512 /* Signal that the capture should be saved when it's complete. */
24513 start_node->values[2] = 0;
24514 end_node->values[2] = 1;
24515
24516 /* Record that we have a new capture group. */
24517 if (!record_group(args->pattern, private_group, start_node))
24518 return RE_ERROR_MEMORY;
24519
24520 /* Compile the sequence and check that we've reached the end of the capture
24521 * group.
24522 */
24523 subargs = *args;
24524 status = build_sequence(&subargs);
24525 if (status != RE_ERROR_SUCCESS)
24526 return status;
24527
24528 if (subargs.code[0] != RE_OP_END)
24529 return RE_ERROR_ILLEGAL;
24530
24531 args->code = subargs.code;
24532 args->min_width += subargs.min_width;
24533 args->has_captures |= subargs.has_captures | subargs.visible_captures;
24534 args->is_fuzzy |= subargs.is_fuzzy;
24535 args->has_groups |= TRUE;
24536 args->has_repeats |= subargs.has_repeats;
24537 args->visible_capture_count = subargs.visible_capture_count;
24538
24539 if (!args->in_define)
24540 ++args->visible_capture_count;
24541
24542 ++args->code;
24543
24544 /* Record that the capture group has closed. */
24545 record_group_end(args->pattern, private_group);
24546
24547 /* Append the capture group. */
24548 add_node(args->end, start_node);
24549 add_node(start_node, subargs.start);
24550 add_node(subargs.end, end_node);
24551 args->end = end_node;
24552
24553 return RE_ERROR_SUCCESS;
24554 }
24555
24556 /* Builds a GROUP_CALL node. */
24557 Py_LOCAL_INLINE(int) build_GROUP_CALL(RE_CompileArgs* args) {
24558 RE_CODE call_ref;
24559 RE_Node* node;
24560
24561 /* codes: opcode, call_ref. */
24562 if (args->code + 1 > args->end_code)
24563 return RE_ERROR_ILLEGAL;
24564
24565 call_ref = args->code[1];
24566
24567 /* Create the node. */
24568 node = create_node(args->pattern, RE_OP_GROUP_CALL, 0, 0, 1);
24569 if (!node)
24570 return RE_ERROR_MEMORY;
24571
24572 node->values[0] = call_ref;
24573
24574 node->status |= RE_STATUS_HAS_GROUPS;
24575 node->status |= RE_STATUS_HAS_REPEATS;
24576
24577 args->code += 2;
24578
24579 /* Record that we used a call_ref. */
24580 if (!record_call_ref_used(args->pattern, call_ref))
24581 return RE_ERROR_MEMORY;
24582
24583 /* Append the node. */
24584 add_node(args->end, node);
24585 args->end = node;
24586 args->all_atomic = FALSE;
24587
24588 return RE_ERROR_SUCCESS;
24589 }
24590
24591 /* Builds a GROUP_EXISTS node. */
24592 Py_LOCAL_INLINE(int) build_GROUP_EXISTS(RE_CompileArgs* args) {
24593 RE_CODE group;
24594 RE_Node* start_node;
24595 RE_Node* end_node;
24596 RE_CompileArgs subargs;
24597 int status;
24598 Py_ssize_t min_width;
24599
24600 /* codes: opcode, ..., next, ..., end. */
24601 if (args->code + 2 > args->end_code)
24602 return RE_ERROR_ILLEGAL;
24603
24604 group = args->code[1];
24605
24606 args->code += 2;
24607
24608 /* Record that we have a reference to a group. If group is 0, then we have
24609 * a DEFINE and not a true group.
24610 */
24611 if (group > 0 && !record_ref_group(args->pattern, group))
24612 return RE_ERROR_MEMORY;
24613
24614 /* Create nodes for the start and end of the structure. */
24615 start_node = create_node(args->pattern, RE_OP_GROUP_EXISTS, 0, 0, 1);
24616 end_node = create_node(args->pattern, RE_OP_BRANCH, 0, 0, 0);
24617 if (!start_node || !end_node)
24618 return RE_ERROR_MEMORY;
24619
24620 start_node->values[0] = group;
24621
24622 subargs = *args;
24623 subargs.in_define = TRUE;
24624 status = build_sequence(&subargs);
24625 if (status != RE_ERROR_SUCCESS)
24626 return status;
24627
24628 args->code = subargs.code;
24629 args->has_captures |= subargs.has_captures;
24630 args->is_fuzzy |= subargs.is_fuzzy;
24631 args->has_groups |= subargs.has_groups;
24632 args->has_repeats |= subargs.has_repeats;
24633 args->visible_capture_count = subargs.visible_capture_count;
24634
24635 min_width = subargs.min_width;
24636
24637 /* Append the start node. */
24638 add_node(args->end, start_node);
24639 add_node(start_node, subargs.start);
24640
24641 if (args->code[0] == RE_OP_NEXT) {
24642 RE_Node* true_branch_end;
24643
24644 ++args->code;
24645
24646 true_branch_end = subargs.end;
24647
24648 subargs.code = args->code;
24649
24650 status = build_sequence(&subargs);
24651 if (status != RE_ERROR_SUCCESS)
24652 return status;
24653
24654 args->code = subargs.code;
24655 args->has_captures |= subargs.has_captures;
24656 args->is_fuzzy |= subargs.is_fuzzy;
24657 args->visible_capture_count = subargs.visible_capture_count;
24658
24659 if (group == 0) {
24660 /* Join the 2 branches end-to-end and bypass it. The sequence
24661 * itself will never be matched as a whole, so it doesn't matter.
24662 */
24663 min_width = 0;
24664
24665 add_node(start_node, end_node);
24666 add_node(true_branch_end, subargs.start);
24667 } else {
24668 args->has_groups |= subargs.has_groups;
24669 args->has_repeats |= subargs.has_repeats;
24670 args->visible_capture_count = subargs.visible_capture_count;
24671
24672 min_width = min_ssize_t(min_width, subargs.min_width);
24673
24674 add_node(start_node, subargs.start);
24675 add_node(true_branch_end, end_node);
24676 }
24677
24678 add_node(subargs.end, end_node);
24679 } else {
24680 add_node(start_node, end_node);
24681 add_node(subargs.end, end_node);
24682
24683 min_width = 0;
24684 }
24685
24686 args->min_width += min_width;
24687
24688 if (args->code[0] != RE_OP_END)
24689 return RE_ERROR_ILLEGAL;
24690
24691 ++args->code;
24692
24693 args->end = end_node;
24694 args->all_atomic = FALSE;
24695
24696 return RE_ERROR_SUCCESS;
24697 }
24698
24699 /* Builds a LOOKAROUND node. */
24700 Py_LOCAL_INLINE(int) build_LOOKAROUND(RE_CompileArgs* args) {
24701 RE_CODE flags;
24702 BOOL forward;
24703 RE_Node* lookaround_node;
24704 RE_CompileArgs subargs;
24705 int status;
24706 RE_Node* end_node;
24707 RE_Node* next_node;
24708
24709 /* codes: opcode, flags, forward, ..., end. */
24710 if (args->code + 3 > args->end_code)
24711 return RE_ERROR_ILLEGAL;
24712
24713 flags = args->code[1];
24714 forward = (BOOL)args->code[2];
24715
24716 /* Create a node for the lookaround. */
24717 lookaround_node = create_node(args->pattern, RE_OP_LOOKAROUND, flags, 0,
24718 0);
24719 if (!lookaround_node)
24720 return RE_ERROR_MEMORY;
24721
24722 args->code += 3;
24723
24724 /* Compile the sequence and check that we've reached the end of the
24725 * subpattern.
24726 */
24727 subargs = *args;
24728 subargs.forward = forward;
24729 status = build_sequence(&subargs);
24730 if (status != RE_ERROR_SUCCESS)
24731 return status;
24732
24733 if (subargs.code[0] != RE_OP_END)
24734 return RE_ERROR_ILLEGAL;
24735
24736 args->code = subargs.code;
24737 ++args->code;
24738
24739 /* Check the subpattern. */
24740 args->has_captures |= subargs.has_captures;
24741 args->is_fuzzy |= subargs.is_fuzzy;
24742 args->has_groups |= subargs.has_groups;
24743 args->has_repeats |= subargs.has_repeats;
24744 args->visible_capture_count = subargs.visible_capture_count;
24745
24746 if (subargs.has_groups)
24747 lookaround_node->status |= RE_STATUS_HAS_GROUPS;
24748
24749 if (subargs.has_repeats)
24750 lookaround_node->status |= RE_STATUS_HAS_REPEATS;
24751
24752 /* Create the node to terminate the subpattern. */
24753 end_node = create_node(args->pattern, RE_OP_END_LOOKAROUND, 0, 0, 0);
24754 if (!end_node)
24755 return RE_ERROR_MEMORY;
24756
24757 /* Make a continuation node. */
24758 next_node = create_node(args->pattern, RE_OP_BRANCH, 0, 0, 0);
24759 if (!next_node)
24760 return RE_ERROR_MEMORY;
24761
24762 /* Append the new sequence. */
24763 add_node(args->end, lookaround_node);
24764 add_node(lookaround_node, subargs.start);
24765 add_node(lookaround_node, next_node);
24766 add_node(subargs.end, end_node);
24767 add_node(end_node, next_node);
24768
24769 args->end = next_node;
24770 args->all_atomic = FALSE;
24771
24772 return RE_ERROR_SUCCESS;
24773 }
24774
24775 /* Builds a RANGE node. */
24776 Py_LOCAL_INLINE(int) build_RANGE(RE_CompileArgs* args) {
24777 RE_UINT8 op;
24778 RE_CODE flags;
24779 Py_ssize_t step;
24780 RE_Node* node;
24781
24782 /* codes: opcode, flags, lower, upper. */
24783 if (args->code + 3 > args->end_code)
24784 return RE_ERROR_ILLEGAL;
24785
24786 op = (RE_UINT8)args->code[0];
24787 flags = args->code[1];
24788
24789 step = get_step(op);
24790
24791 if (flags & RE_ZEROWIDTH_OP)
24792 step = 0;
24793
24794 /* Create the node. */
24795 node = create_node(args->pattern, op, flags, step, 2);
24796 if (!node)
24797 return RE_ERROR_MEMORY;
24798
24799 node->values[0] = args->code[2];
24800 node->values[1] = args->code[3];
24801
24802 args->code += 4;
24803
24804 /* Append the node. */
24805 add_node(args->end, node);
24806 args->end = node;
24807
24808 if (step != 0)
24809 ++args->min_width;
24810
24811 return RE_ERROR_SUCCESS;
24812 }
24813
24814 /* Builds a REF_GROUP node. */
24815 Py_LOCAL_INLINE(int) build_REF_GROUP(RE_CompileArgs* args) {
24816 RE_CODE flags;
24817 RE_CODE group;
24818 RE_Node* node;
24819
24820 /* codes: opcode, flags, group. */
24821 if (args->code + 2 > args->end_code)
24822 return RE_ERROR_ILLEGAL;
24823
24824 flags = args->code[1];
24825 group = args->code[2];
24826 node = create_node(args->pattern, (RE_UINT8)args->code[0], flags, 0, 1);
24827 if (!node)
24828 return RE_ERROR_MEMORY;
24829
24830 node->values[0] = group;
24831
24832 args->code += 3;
24833
24834 /* Record that we have a reference to a group. */
24835 if (!record_ref_group(args->pattern, group))
24836 return RE_ERROR_MEMORY;
24837
24838 /* Append the reference. */
24839 add_node(args->end, node);
24840 args->end = node;
24841
24842 return RE_ERROR_SUCCESS;
24843 }
24844
24845 /* Builds a REPEAT node. */
24846 Py_LOCAL_INLINE(int) build_REPEAT(RE_CompileArgs* args) {
24847 BOOL greedy;
24848 RE_CODE min_count;
24849 RE_CODE max_count;
24850 int status;
24851
24852 /* codes: opcode, min_count, max_count, ..., end. */
24853 if (args->code + 3 > args->end_code)
24854 return RE_ERROR_ILLEGAL;
24855
24856 greedy = args->code[0] == RE_OP_GREEDY_REPEAT;
24857 min_count = args->code[1];
24858 max_count = args->code[2];
24859 if (args->code[1] > args->code[2])
24860 return RE_ERROR_ILLEGAL;
24861
24862 args->code += 3;
24863
24864 if (min_count == 1 && max_count == 1) {
24865 /* Singly-repeated sequence. */
24866 RE_CompileArgs subargs;
24867
24868 subargs = *args;
24869 status = build_sequence(&subargs);
24870 if (status != RE_ERROR_SUCCESS)
24871 return status;
24872
24873 if (subargs.code[0] != RE_OP_END)
24874 return RE_ERROR_ILLEGAL;
24875
24876 args->code = subargs.code;
24877 args->min_width += subargs.min_width;
24878 args->has_captures |= subargs.has_captures;
24879 args->is_fuzzy |= subargs.is_fuzzy;
24880 args->has_groups |= subargs.has_groups;
24881 args->has_repeats |= subargs.has_repeats;
24882 args->visible_capture_count = subargs.visible_capture_count;
24883
24884 ++args->code;
24885
24886 /* Append the sequence. */
24887 add_node(args->end, subargs.start);
24888 args->end = subargs.end;
24889 } else {
24890 /* Extract the minimum number of repeats out of a repeat if it contains
24891 * a repeat.
24892 */
24893 size_t index;
24894 RE_Node* repeat_node;
24895 RE_CompileArgs subargs;
24896
24897 if (min_count > 0) {
24898 RE_CODE done_count;
24899
24900 for (done_count = 0; done_count < min_count; done_count++) {
24901 subargs = *args;
24902 subargs.visible_captures = TRUE;
24903
24904 status = build_sequence(&subargs);
24905 if (status != RE_ERROR_SUCCESS)
24906 return status;
24907
24908 if (subargs.code[0] != RE_OP_END)
24909 return RE_ERROR_ILLEGAL;
24910
24911 args->visible_capture_count = subargs.visible_capture_count;
24912
24913 add_node(args->end, subargs.start);
24914 args->end = subargs.end;
24915 }
24916
24917 args->min_width += (Py_ssize_t)min_count * subargs.min_width;
24918 args->has_captures |= subargs.has_captures;
24919 args->is_fuzzy |= subargs.is_fuzzy;
24920 args->has_groups |= subargs.has_groups;
24921 args->has_repeats |= subargs.has_repeats;
24922
24923 min_count -= done_count;
24924 if (~max_count != 0)
24925 max_count -= done_count;
24926 }
24927
24928 /* We've extracted the minimum number of repeats. Are there any left? */
24929 if (min_count > 0 && max_count == 0) {
24930 /* All done. */
24931 args->code = subargs.code;
24932 ++args->code;
24933 } else {
24934 /* More to do. */
24935 index = args->pattern->repeat_count;
24936
24937 /* Create the nodes for the repeat. */
24938 repeat_node = create_node(args->pattern, greedy ?
24939 RE_OP_GREEDY_REPEAT : RE_OP_LAZY_REPEAT, 0, args->forward ? 1 :
24940 -1, 4);
24941 if (!repeat_node || !record_repeat(args->pattern, index,
24942 args->repeat_depth))
24943 return RE_ERROR_MEMORY;
24944
24945 repeat_node->values[0] = (RE_CODE)index;
24946 repeat_node->values[1] = min_count;
24947 repeat_node->values[2] = max_count;
24948 repeat_node->values[3] = args->forward;
24949
24950 if (args->within_fuzzy)
24951 args->pattern->repeat_info[index].status |= RE_STATUS_BODY;
24952
24953 /* Compile the 'body' and check that we've reached the end of it.
24954 */
24955 subargs = *args;
24956 subargs.visible_captures = TRUE;
24957 ++subargs.repeat_depth;
24958 status = build_sequence(&subargs);
24959 if (status != RE_ERROR_SUCCESS)
24960 return status;
24961
24962 if (subargs.code[0] != RE_OP_END)
24963 return RE_ERROR_ILLEGAL;
24964
24965 args->code = subargs.code;
24966 args->min_width += (Py_ssize_t)min_count * subargs.min_width;
24967 args->has_captures |= subargs.has_captures;
24968 args->is_fuzzy |= subargs.is_fuzzy;
24969 args->has_groups |= subargs.has_groups;
24970 args->has_repeats = TRUE;
24971 args->visible_capture_count = subargs.visible_capture_count;
24972
24973 ++args->code;
24974
24975 /* Is it a repeat of something which will match a single character?
24976 *
24977 * If it's in a fuzzy section then it won't be optimised as a
24978 * single-character repeat.
24979 */
24980 if (sequence_matches_one(subargs.start)) {
24981 repeat_node->op = greedy ? RE_OP_GREEDY_REPEAT_ONE :
24982 RE_OP_LAZY_REPEAT_ONE;
24983
24984 if (args->all_atomic && args->code < args->end_code &&
24985 args->code[0] == RE_OP_END && !args->within_fuzzy)
24986 repeat_node->status |= RE_STATUS_ALL_ATOMIC;
24987
24988 /* Append the new sequence. */
24989 add_node(args->end, repeat_node);
24990 repeat_node->nonstring.next_2.node = subargs.start;
24991 args->end = repeat_node;
24992 } else {
24993 RE_Node* end_repeat_node;
24994 RE_Node* end_node;
24995
24996 end_repeat_node = create_node(args->pattern, greedy ?
24997 RE_OP_END_GREEDY_REPEAT : RE_OP_END_LAZY_REPEAT, 0,
24998 args->forward ? 1 : -1, 4);
24999 if (!end_repeat_node)
25000 return RE_ERROR_MEMORY;
25001
25002 end_repeat_node->values[0] = repeat_node->values[0];
25003 end_repeat_node->values[1] = repeat_node->values[1];
25004 end_repeat_node->values[2] = repeat_node->values[2];
25005 end_repeat_node->values[3] = args->forward;
25006
25007 end_node = create_node(args->pattern, RE_OP_BRANCH, 0, 0, 0);
25008 if (!end_node)
25009 return RE_ERROR_MEMORY;
25010
25011 if (args->all_atomic && args->code < args->end_code &&
25012 args->code[0] == RE_OP_END && !args->within_fuzzy)
25013 end_repeat_node->status |= RE_STATUS_ALL_ATOMIC;
25014
25015 /* Append the new sequence. */
25016 add_node(args->end, repeat_node);
25017 add_node(repeat_node, subargs.start);
25018 add_node(repeat_node, end_node);
25019 add_node(subargs.end, end_repeat_node);
25020 add_node(end_repeat_node, subargs.start);
25021 add_node(end_repeat_node, end_node);
25022 args->end = end_node;
25023 }
25024 }
25025 }
25026
25027 if (!(args->all_atomic && args->code < args->end_code && args->code[0] !=
25028 RE_OP_END && !args->within_fuzzy))
25029 args->all_atomic = FALSE;
25030
25031 return RE_ERROR_SUCCESS;
25032 }
25033
25034 /* Builds a STRING node. */
25035 Py_LOCAL_INLINE(int) build_STRING(RE_CompileArgs* args, BOOL is_charset) {
25036 RE_CODE flags;
25037 RE_CODE length;
25038 RE_UINT8 op;
25039 Py_ssize_t step;
25040 RE_Node* node;
25041 size_t i;
25042
25043 /* codes: opcode, flags, length, .... */
25044 flags = args->code[1];
25045 length = args->code[2];
25046 if (args->code + 3 + length > args->end_code)
25047 return RE_ERROR_ILLEGAL;
25048
25049 op = (RE_UINT8)args->code[0];
25050
25051 step = get_step(op);
25052
25053 /* Create the node. */
25054 node = create_node(args->pattern, op, flags, step * (Py_ssize_t)length,
25055 length);
25056 if (!node)
25057 return RE_ERROR_MEMORY;
25058 if (!is_charset)
25059 node->status |= RE_STATUS_STRING;
25060
25061 for (i = 0; i < length; i++)
25062 node->values[i] = args->code[3 + i];
25063
25064 args->code += 3 + length;
25065
25066 /* Append the node. */
25067 add_node(args->end, node);
25068 args->end = node;
25069
25070 /* Because of full case-folding, one character in the text could match
25071 * multiple characters in the pattern.
25072 */
25073 if (op == RE_OP_STRING_FLD || op == RE_OP_STRING_FLD_REV)
25074 args->min_width += possible_unfolded_length((Py_ssize_t)length);
25075 else
25076 args->min_width += (Py_ssize_t)length;
25077
25078 return RE_ERROR_SUCCESS;
25079 }
25080
25081 /* Builds a SET node. */
25082 Py_LOCAL_INLINE(int) build_SET(RE_CompileArgs* args) {
25083 RE_UINT8 op;
25084 RE_CODE flags;
25085 Py_ssize_t step;
25086 RE_Node* node;
25087 Py_ssize_t min_width;
25088 int status;
25089
25090 /* codes: opcode, flags, ..., end. */
25091 op = (RE_UINT8)args->code[0];
25092 flags = args->code[1];
25093
25094 step = get_step(op);
25095
25096 if (flags & RE_ZEROWIDTH_OP)
25097 step = 0;
25098
25099 node = create_node(args->pattern, op, flags, step, 0);
25100 if (!node)
25101 return RE_ERROR_MEMORY;
25102
25103 args->code += 2;
25104
25105 /* Append the node. */
25106 add_node(args->end, node);
25107 args->end = node;
25108
25109 min_width = args->min_width;
25110
25111 /* Compile the character set. */
25112 do {
25113 switch (args->code[0]) {
25114 case RE_OP_ANY_ALL:
25115 status = build_ANY(args);
25116 if (status != RE_ERROR_SUCCESS)
25117 return status;
25118 break;
25119 case RE_OP_CHARACTER:
25120 case RE_OP_PROPERTY:
25121 status = build_CHARACTER_or_PROPERTY(args);
25122 if (status != RE_ERROR_SUCCESS)
25123 return status;
25124 break;
25125 case RE_OP_RANGE:
25126 status = build_RANGE(args);
25127 if (status != RE_ERROR_SUCCESS)
25128 return status;
25129 break;
25130 case RE_OP_SET_DIFF:
25131 case RE_OP_SET_INTER:
25132 case RE_OP_SET_SYM_DIFF:
25133 case RE_OP_SET_UNION:
25134 status = build_SET(args);
25135 if (status != RE_ERROR_SUCCESS)
25136 return status;
25137 break;
25138 case RE_OP_STRING:
25139 /* A set of characters. */
25140 status = build_STRING(args, TRUE);
25141 if (status != RE_ERROR_SUCCESS)
25142 return status;
25143 break;
25144 default:
25145 /* Illegal opcode for a character set. */
25146 return RE_ERROR_ILLEGAL;
25147 }
25148 } while (args->code < args->end_code && args->code[0] != RE_OP_END);
25149
25150 /* Check that we've reached the end correctly. (The last opcode should be
25151 * 'END'.)
25152 */
25153 if (args->code >= args->end_code || args->code[0] != RE_OP_END)
25154 return RE_ERROR_ILLEGAL;
25155
25156 ++args->code;
25157
25158 /* At this point the set's members are in the main sequence. They need to
25159 * be moved out-of-line.
25160 */
25161 node->nonstring.next_2.node = node->next_1.node;
25162 node->next_1.node = NULL;
25163 args->end = node;
25164
25165 args->min_width = min_width;
25166
25167 if (step != 0)
25168 ++args->min_width;
25169
25170 return RE_ERROR_SUCCESS;
25171 }
25172
25173 /* Builds a SUCCESS node . */
25174 Py_LOCAL_INLINE(int) build_SUCCESS(RE_CompileArgs* args) {
25175 RE_Node* node;
25176 /* codes: opcode. */
25177
25178 /* Create the node. */
25179 node = create_node(args->pattern, (RE_UINT8)args->code[0], 0, 0, 0);
25180 if (!node)
25181 return RE_ERROR_MEMORY;
25182
25183 ++args->code;
25184
25185 /* Append the node. */
25186 add_node(args->end, node);
25187 args->end = node;
25188
25189 return RE_ERROR_SUCCESS;
25190 }
25191
25192 /* Builds a zero-width node. */
25193 Py_LOCAL_INLINE(int) build_zerowidth(RE_CompileArgs* args) {
25194 RE_CODE flags;
25195 RE_Node* node;
25196
25197 /* codes: opcode, flags. */
25198 if (args->code + 1 > args->end_code)
25199 return RE_ERROR_ILLEGAL;
25200
25201 flags = args->code[1];
25202
25203 /* Create the node. */
25204 node = create_node(args->pattern, (RE_UINT8)args->code[0], flags, 0, 0);
25205 if (!node)
25206 return RE_ERROR_MEMORY;
25207
25208 args->code += 2;
25209
25210 /* Append the node. */
25211 add_node(args->end, node);
25212 args->end = node;
25213
25214 return RE_ERROR_SUCCESS;
25215 }
25216
25217 /* Builds a node that's equivalent to a character set. */
25218 Py_LOCAL_INLINE(int) build_charset_equiv(RE_CompileArgs* args) {
25219 int status;
25220
25221 /* Guarantee that there's something to attach to. */
25222 args->start = create_node(args->pattern, RE_OP_BRANCH, 0, 0, 0);
25223 args->end = args->start;
25224
25225 /* The following code groups opcodes by format, not function. */
25226 switch (args->code[0]) {
25227 case RE_OP_ANY:
25228 case RE_OP_ANY_ALL:
25229 case RE_OP_ANY_U:
25230 case RE_OP_ANY_REV:
25231 case RE_OP_ANY_ALL_REV:
25232 case RE_OP_ANY_U_REV:
25233 /* A simple opcode with no trailing codewords and width of 1. */
25234 status = build_ANY(args);
25235 if (status != RE_ERROR_SUCCESS)
25236 return status;
25237 break;
25238 case RE_OP_CHARACTER:
25239 case RE_OP_PROPERTY:
25240 case RE_OP_CHARACTER_IGN:
25241 case RE_OP_PROPERTY_IGN:
25242 case RE_OP_CHARACTER_REV:
25243 case RE_OP_PROPERTY_REV:
25244 case RE_OP_CHARACTER_IGN_REV:
25245 case RE_OP_PROPERTY_IGN_REV:
25246 /* A character literal or a property. */
25247 status = build_CHARACTER_or_PROPERTY(args);
25248 if (status != RE_ERROR_SUCCESS)
25249 return status;
25250 break;
25251 case RE_OP_RANGE:
25252 case RE_OP_RANGE_IGN:
25253 case RE_OP_RANGE_IGN_REV:
25254 case RE_OP_RANGE_REV:
25255 /* A range. */
25256 status = build_RANGE(args);
25257 if (status != RE_ERROR_SUCCESS)
25258 return status;
25259 break;
25260 case RE_OP_SET_DIFF:
25261 case RE_OP_SET_DIFF_IGN:
25262 case RE_OP_SET_DIFF_IGN_REV:
25263 case RE_OP_SET_DIFF_REV:
25264 case RE_OP_SET_INTER:
25265 case RE_OP_SET_INTER_IGN:
25266 case RE_OP_SET_INTER_IGN_REV:
25267 case RE_OP_SET_INTER_REV:
25268 case RE_OP_SET_SYM_DIFF:
25269 case RE_OP_SET_SYM_DIFF_IGN:
25270 case RE_OP_SET_SYM_DIFF_IGN_REV:
25271 case RE_OP_SET_SYM_DIFF_REV:
25272 case RE_OP_SET_UNION:
25273 case RE_OP_SET_UNION_IGN:
25274 case RE_OP_SET_UNION_IGN_REV:
25275 case RE_OP_SET_UNION_REV:
25276 /* A set. */
25277 status = build_SET(args);
25278 if (status != RE_ERROR_SUCCESS)
25279 return status;
25280 break;
25281 default:
25282 /* We've found an opcode which we don't recognise. */
25283 return RE_ERROR_ILLEGAL;
25284 }
25285
25286 return RE_ERROR_SUCCESS;
25287 }
25288
25289 /* Builds a sequence of nodes from regular expression code. */
25290 Py_LOCAL_INLINE(int) build_sequence(RE_CompileArgs* args) {
25291 int status;
25292
25293 /* Guarantee that there's something to attach to. */
25294 args->start = create_node(args->pattern, RE_OP_BRANCH, 0, 0, 0);
25295 args->end = args->start;
25296
25297 args->min_width = 0;
25298 args->has_captures = FALSE;
25299 args->is_fuzzy = FALSE;
25300 args->has_groups = FALSE;
25301 args->has_repeats = FALSE;
25302 args->all_atomic = TRUE;
25303
25304 /* The sequence should end with an opcode we don't understand. If it
25305 * doesn't then the code is illegal.
25306 */
25307 while (args->code < args->end_code) {
25308 /* The following code groups opcodes by format, not function. */
25309 switch (args->code[0]) {
25310 case RE_OP_ANY:
25311 case RE_OP_ANY_ALL:
25312 case RE_OP_ANY_ALL_REV:
25313 case RE_OP_ANY_REV:
25314 case RE_OP_ANY_U:
25315 case RE_OP_ANY_U_REV:
25316 /* A simple opcode with no trailing codewords and width of 1. */
25317 status = build_ANY(args);
25318 if (status != RE_ERROR_SUCCESS)
25319 return status;
25320 break;
25321 case RE_OP_ATOMIC:
25322 /* An atomic sequence. */
25323 status = build_ATOMIC(args);
25324 if (status != RE_ERROR_SUCCESS)
25325 return status;
25326 break;
25327 case RE_OP_BOUNDARY:
25328 case RE_OP_DEFAULT_BOUNDARY:
25329 case RE_OP_DEFAULT_END_OF_WORD:
25330 case RE_OP_DEFAULT_START_OF_WORD:
25331 case RE_OP_END_OF_WORD:
25332 case RE_OP_GRAPHEME_BOUNDARY:
25333 case RE_OP_KEEP:
25334 case RE_OP_SKIP:
25335 case RE_OP_START_OF_WORD:
25336 /* A word or grapheme boundary. */
25337 status = build_BOUNDARY(args);
25338 if (status != RE_ERROR_SUCCESS)
25339 return status;
25340 break;
25341 case RE_OP_BRANCH:
25342 /* A 2-way branch. */
25343 status = build_BRANCH(args);
25344 if (status != RE_ERROR_SUCCESS)
25345 return status;
25346 break;
25347 case RE_OP_CALL_REF:
25348 /* A group call ref. */
25349 status = build_CALL_REF(args);
25350 if (status != RE_ERROR_SUCCESS)
25351 return status;
25352 break;
25353 case RE_OP_CHARACTER:
25354 case RE_OP_CHARACTER_IGN:
25355 case RE_OP_CHARACTER_IGN_REV:
25356 case RE_OP_CHARACTER_REV:
25357 case RE_OP_PROPERTY:
25358 case RE_OP_PROPERTY_IGN:
25359 case RE_OP_PROPERTY_IGN_REV:
25360 case RE_OP_PROPERTY_REV:
25361 /* A character literal or a property. */
25362 status = build_CHARACTER_or_PROPERTY(args);
25363 if (status != RE_ERROR_SUCCESS)
25364 return status;
25365 break;
25366 case RE_OP_CONDITIONAL:
25367 /* A lookaround conditional. */
25368 status = build_CONDITIONAL(args);
25369 if (status != RE_ERROR_SUCCESS)
25370 return status;
25371 break;
25372 case RE_OP_END_OF_LINE:
25373 case RE_OP_END_OF_LINE_U:
25374 case RE_OP_END_OF_STRING:
25375 case RE_OP_END_OF_STRING_LINE:
25376 case RE_OP_END_OF_STRING_LINE_U:
25377 case RE_OP_SEARCH_ANCHOR:
25378 case RE_OP_START_OF_LINE:
25379 case RE_OP_START_OF_LINE_U:
25380 case RE_OP_START_OF_STRING:
25381 /* A simple opcode with no trailing codewords and width of 0. */
25382 status = build_zerowidth(args);
25383 if (status != RE_ERROR_SUCCESS)
25384 return status;
25385 break;
25386 case RE_OP_FAILURE:
25387 case RE_OP_PRUNE:
25388 case RE_OP_SUCCESS:
25389 status = build_SUCCESS(args);
25390 if (status != RE_ERROR_SUCCESS)
25391 return status;
25392 break;
25393 case RE_OP_FUZZY:
25394 case RE_OP_FUZZY_EXT:
25395 /* A fuzzy sequence. */
25396 status = build_FUZZY(args);
25397 if (status != RE_ERROR_SUCCESS)
25398 return status;
25399 break;
25400 case RE_OP_GREEDY_REPEAT:
25401 case RE_OP_LAZY_REPEAT:
25402 /* A repeated sequence. */
25403 status = build_REPEAT(args);
25404 if (status != RE_ERROR_SUCCESS)
25405 return status;
25406 break;
25407 case RE_OP_GROUP:
25408 /* A capture group. */
25409 status = build_GROUP(args);
25410 if (status != RE_ERROR_SUCCESS)
25411 return status;
25412 break;
25413 case RE_OP_GROUP_CALL:
25414 /* A group call. */
25415 status = build_GROUP_CALL(args);
25416 if (status != RE_ERROR_SUCCESS)
25417 return status;
25418 break;
25419 case RE_OP_GROUP_EXISTS:
25420 /* A conditional sequence. */
25421 status = build_GROUP_EXISTS(args);
25422 if (status != RE_ERROR_SUCCESS)
25423 return status;
25424 break;
25425 case RE_OP_LOOKAROUND:
25426 /* A lookaround. */
25427 status = build_LOOKAROUND(args);
25428 if (status != RE_ERROR_SUCCESS)
25429 return status;
25430 break;
25431 case RE_OP_RANGE:
25432 case RE_OP_RANGE_IGN:
25433 case RE_OP_RANGE_IGN_REV:
25434 case RE_OP_RANGE_REV:
25435 /* A range. */
25436 status = build_RANGE(args);
25437 if (status != RE_ERROR_SUCCESS)
25438 return status;
25439 break;
25440 case RE_OP_REF_GROUP:
25441 case RE_OP_REF_GROUP_FLD:
25442 case RE_OP_REF_GROUP_FLD_REV:
25443 case RE_OP_REF_GROUP_IGN:
25444 case RE_OP_REF_GROUP_IGN_REV:
25445 case RE_OP_REF_GROUP_REV:
25446 /* A reference to a group. */
25447 status = build_REF_GROUP(args);
25448 if (status != RE_ERROR_SUCCESS)
25449 return status;
25450 break;
25451 case RE_OP_SET_DIFF:
25452 case RE_OP_SET_DIFF_IGN:
25453 case RE_OP_SET_DIFF_IGN_REV:
25454 case RE_OP_SET_DIFF_REV:
25455 case RE_OP_SET_INTER:
25456 case RE_OP_SET_INTER_IGN:
25457 case RE_OP_SET_INTER_IGN_REV:
25458 case RE_OP_SET_INTER_REV:
25459 case RE_OP_SET_SYM_DIFF:
25460 case RE_OP_SET_SYM_DIFF_IGN:
25461 case RE_OP_SET_SYM_DIFF_IGN_REV:
25462 case RE_OP_SET_SYM_DIFF_REV:
25463 case RE_OP_SET_UNION:
25464 case RE_OP_SET_UNION_IGN:
25465 case RE_OP_SET_UNION_IGN_REV:
25466 case RE_OP_SET_UNION_REV:
25467 /* A set. */
25468 status = build_SET(args);
25469 if (status != RE_ERROR_SUCCESS)
25470 return status;
25471 break;
25472 case RE_OP_STRING:
25473 case RE_OP_STRING_FLD:
25474 case RE_OP_STRING_FLD_REV:
25475 case RE_OP_STRING_IGN:
25476 case RE_OP_STRING_IGN_REV:
25477 case RE_OP_STRING_REV:
25478 /* A string literal. */
25479 if (!build_STRING(args, FALSE))
25480 return FALSE;
25481 break;
25482 default:
25483 /* We've found an opcode which we don't recognise. We'll leave it
25484 * for the caller.
25485 */
25486 return RE_ERROR_SUCCESS;
25487 }
25488 }
25489
25490 /* If we're here then we should be at the end of the code, otherwise we
25491 * have an error.
25492 */
25493 return args->code == args->end_code;
25494 }
25495
25496 /* Compiles the regular expression code to 'nodes'.
25497 *
25498 * Various details about the regular expression are discovered during
25499 * compilation and stored in the PatternObject.
25500 */
25501 Py_LOCAL_INLINE(BOOL) compile_to_nodes(RE_CODE* code, RE_CODE* end_code,
25502 PatternObject* pattern) {
25503 RE_CompileArgs args;
25504 int status;
25505
25506 /* Compile a regex sequence and then check that we've reached the end
25507 * correctly. (The last opcode should be 'SUCCESS'.)
25508 *
25509 * If successful, 'start' and 'end' will point to the start and end nodes
25510 * of the compiled sequence.
25511 */
25512 args.code = code;
25513 args.end_code = end_code;
25514 args.pattern = pattern;
25515 args.forward = (pattern->flags & RE_FLAG_REVERSE) == 0;
25516 args.visible_captures = FALSE;
25517 args.has_captures = FALSE;
25518 args.repeat_depth = 0;
25519 args.is_fuzzy = FALSE;
25520 args.within_fuzzy = FALSE;
25521 args.visible_capture_count = 0;
25522 args.in_define = FALSE;
25523 status = build_sequence(&args);
25524 if (status == RE_ERROR_ILLEGAL)
25525 set_error(RE_ERROR_ILLEGAL, NULL);
25526
25527 if (status != RE_ERROR_SUCCESS)
25528 return FALSE;
25529
25530 pattern->min_width = args.min_width;
25531 pattern->is_fuzzy = args.is_fuzzy;
25532 pattern->do_search_start = TRUE;
25533 pattern->start_node = args.start;
25534 pattern->visible_capture_count = args.visible_capture_count;
25535
25536 /* Optimise the pattern. */
25537 if (!optimise_pattern(pattern))
25538 return FALSE;
25539
25540 pattern->start_test = locate_test_start(pattern->start_node);
25541
25542 /* Get the call_ref for the entire pattern, if any. */
25543 if (pattern->start_node->op == RE_OP_CALL_REF)
25544 pattern->pattern_call_ref = (Py_ssize_t)pattern->start_node->values[0];
25545 else
25546 pattern->pattern_call_ref = -1;
25547
25548 return TRUE;
25549 }
25550
25551 /* Gets the required characters for a regex.
25552 *
25553 * In the event of an error, it just pretends that there are no required
25554 * characters.
25555 */
25556 Py_LOCAL_INLINE(void) get_required_chars(PyObject* required_chars, RE_CODE**
25557 req_chars, size_t* req_length) {
25558 Py_ssize_t len;
25559 RE_CODE* chars;
25560 Py_ssize_t i;
25561
25562 *req_chars = NULL;
25563 *req_length = 0;
25564
25565 len = PyTuple_GET_SIZE(required_chars);
25566 if (len < 1 || PyErr_Occurred()) {
25567 PyErr_Clear();
25568 return;
25569 }
25570
25571 chars = (RE_CODE*)re_alloc((size_t)len * sizeof(RE_CODE));
25572 if (!chars)
25573 goto error;
25574
25575 for (i = 0; i < len; i++) {
25576 PyObject* o;
25577 size_t value;
25578
25579 /* PyTuple_SET_ITEM borrows the reference. */
25580 o = PyTuple_GET_ITEM(required_chars, i);
25581
25582 value = PyLong_AsUnsignedLong(o);
25583 if ((Py_ssize_t)value == -1 && PyErr_Occurred())
25584 goto error;
25585
25586 chars[i] = (RE_CODE)value;
25587 if (chars[i] != value)
25588 goto error;
25589 }
25590
25591 *req_chars = chars;
25592 *req_length = (size_t)len;
25593
25594 return;
25595
25596 error:
25597 PyErr_Clear();
25598 re_dealloc(chars);
25599 }
25600
25601 /* Makes a STRING node. */
25602 Py_LOCAL_INLINE(RE_Node*) make_STRING_node(PatternObject* pattern, RE_UINT8 op,
25603 size_t length, RE_CODE* chars) {
25604 Py_ssize_t step;
25605 RE_Node* node;
25606 size_t i;
25607
25608 step = get_step(op);
25609
25610 /* Create the node. */
25611 node = create_node(pattern, op, 0, step * (Py_ssize_t)length, length);
25612 if (!node)
25613 return NULL;
25614
25615 node->status |= RE_STATUS_STRING;
25616
25617 for (i = 0; i < length; i++)
25618 node->values[i] = chars[i];
25619
25620 return node;
25621 }
25622
25623 /* Scans all of the characters in the current locale for their properties. */
25624 Py_LOCAL_INLINE(void) scan_locale_chars(RE_LocaleInfo* locale_info) {
25625 int c;
25626
25627 for (c = 0; c < 0x100; c++) {
25628 unsigned short props = 0;
25629
25630 if (isalnum(c))
25631 props |= RE_LOCALE_ALNUM;
25632 if (isalpha(c))
25633 props |= RE_LOCALE_ALPHA;
25634 if (iscntrl(c))
25635 props |= RE_LOCALE_CNTRL;
25636 if (isdigit(c))
25637 props |= RE_LOCALE_DIGIT;
25638 if (isgraph(c))
25639 props |= RE_LOCALE_GRAPH;
25640 if (islower(c))
25641 props |= RE_LOCALE_LOWER;
25642 if (isprint(c))
25643 props |= RE_LOCALE_PRINT;
25644 if (ispunct(c))
25645 props |= RE_LOCALE_PUNCT;
25646 if (isspace(c))
25647 props |= RE_LOCALE_SPACE;
25648 if (isupper(c))
25649 props |= RE_LOCALE_UPPER;
25650
25651 locale_info->properties[c] = props;
25652 locale_info->uppercase[c] = (unsigned char)toupper(c);
25653 locale_info->lowercase[c] = (unsigned char)tolower(c);
25654 }
25655 }
25656
25657 /* Compiles regular expression code to a PatternObject.
25658 *
25659 * The regular expression code is provided as a list and is then compiled to
25660 * 'nodes'. Various details about the regular expression are discovered during
25661 * compilation and stored in the PatternObject.
25662 */
25663 static PyObject* re_compile(PyObject* self_, PyObject* args) {
25664 PyObject* pattern;
25665 Py_ssize_t flags = 0;
25666 PyObject* code_list;
25667 PyObject* groupindex;
25668 PyObject* indexgroup;
25669 PyObject* named_lists;
25670 PyObject* named_list_indexes;
25671 Py_ssize_t req_offset;
25672 PyObject* required_chars;
25673 Py_ssize_t req_flags;
25674 size_t public_group_count;
25675 BOOL unpacked;
25676 Py_ssize_t code_len;
25677 RE_CODE* code;
25678 Py_ssize_t i;
25679 RE_CODE* req_chars;
25680 size_t req_length;
25681 PyObject* packed_code_list;
25682 PatternObject* self;
25683 BOOL unicode;
25684 BOOL locale;
25685 BOOL ascii;
25686 BOOL ok;
25687
25688 if (!PyArg_ParseTuple(args, "OnOOOOOnOnn:re_compile", &pattern, &flags,
25689 &code_list, &groupindex, &indexgroup, &named_lists, &named_list_indexes,
25690 &req_offset, &required_chars, &req_flags, &public_group_count))
25691 return NULL;
25692
25693 /* If it came from a pickled source, code_list will be a packed code list
25694 * in a bytestring.
25695 */
25696 if (PyBytes_Check(code_list)) {
25697 packed_code_list = code_list;
25698 code_list = unpack_code_list(packed_code_list);
25699 if (!code_list)
25700 return NULL;
25701
25702 unpacked = TRUE;
25703 } else
25704 unpacked = FALSE;
25705
25706 /* Read the regex code. */
25707 code_len = PyList_Size(code_list);
25708 code = (RE_CODE*)re_alloc((size_t)code_len * sizeof(RE_CODE));
25709 if (!code) {
25710 if (unpacked) {
25711 /* code_list has been built from a packed code list. */
25712 Py_DECREF(code_list);
25713 }
25714 return NULL;
25715 }
25716
25717 for (i = 0; i < code_len; i++) {
25718 PyObject* o;
25719 size_t value;
25720
25721 /* PyList_GetItem borrows a reference. */
25722 o = PyList_GetItem(code_list, i);
25723
25724 value = PyLong_AsUnsignedLong(o);
25725 if ((Py_ssize_t)value == -1 && PyErr_Occurred())
25726 goto error;
25727
25728 code[i] = (RE_CODE)value;
25729 if (code[i] != value)
25730 goto error;
25731 }
25732
25733 /* Get the required characters. */
25734 get_required_chars(required_chars, &req_chars, &req_length);
25735
25736 if (!unpacked) {
25737 /* Pack the code list in case it's needed for pickling. */
25738 packed_code_list = pack_code_list(code, code_len);
25739 if (!packed_code_list) {
25740 set_error(RE_ERROR_MEMORY, NULL);
25741 re_dealloc(req_chars);
25742 re_dealloc(code);
25743 return NULL;
25744 }
25745 }
25746
25747 /* Create the PatternObject. */
25748 self = PyObject_NEW(PatternObject, &Pattern_Type);
25749 if (!self) {
25750 set_error(RE_ERROR_MEMORY, NULL);
25751 if (unpacked) {
25752 Py_DECREF(code_list);
25753 } else {
25754 Py_DECREF(packed_code_list);
25755 }
25756
25757 re_dealloc(req_chars);
25758 re_dealloc(code);
25759 return NULL;
25760 }
25761
25762 /* Initialise the PatternObject. */
25763 self->pattern = pattern;
25764 self->flags = flags;
25765 self->packed_code_list = packed_code_list;
25766 self->weakreflist = NULL;
25767 self->start_node = NULL;
25768 self->repeat_count = 0;
25769 self->true_group_count = 0;
25770 self->public_group_count = public_group_count;
25771 self->visible_capture_count = 0;
25772 self->group_end_index = 0;
25773 self->groupindex = groupindex;
25774 self->indexgroup = indexgroup;
25775 self->named_lists = named_lists;
25776 self->named_lists_count = (size_t)PyDict_Size(named_lists);
25777 self->partial_named_lists[0] = NULL;
25778 self->partial_named_lists[1] = NULL;
25779 self->named_list_indexes = named_list_indexes;
25780 self->node_capacity = 0;
25781 self->node_count = 0;
25782 self->node_list = NULL;
25783 self->group_info_capacity = 0;
25784 self->group_info = NULL;
25785 self->call_ref_info_capacity = 0;
25786 self->call_ref_info_count = 0;
25787 self->call_ref_info = NULL;
25788 self->repeat_info_capacity = 0;
25789 self->repeat_info = NULL;
25790 self->groups_storage = NULL;
25791 self->repeats_storage = NULL;
25792 self->stack_storage = NULL;
25793 self->stack_capacity = 0;
25794 self->fuzzy_count = 0;
25795 self->req_offset = req_offset;
25796 self->required_chars = required_chars;
25797 self->req_flags = req_flags;
25798 self->req_string = NULL;
25799 self->locale_info = NULL;
25800 Py_INCREF(self->pattern);
25801 if (unpacked) {
25802 Py_INCREF(self->packed_code_list);
25803 }
25804 Py_INCREF(self->groupindex);
25805 Py_INCREF(self->indexgroup);
25806 Py_INCREF(self->named_lists);
25807 Py_INCREF(self->named_list_indexes);
25808 Py_INCREF(self->required_chars);
25809
25810 /* Initialise the character encoding. */
25811 unicode = (flags & RE_FLAG_UNICODE) != 0;
25812 locale = (flags & RE_FLAG_LOCALE) != 0;
25813 ascii = (flags & RE_FLAG_ASCII) != 0;
25814 if (!unicode && !locale && !ascii) {
25815 if (PyBytes_Check(self->pattern))
25816 ascii = RE_FLAG_ASCII;
25817 else
25818 unicode = RE_FLAG_UNICODE;
25819 }
25820 if (unicode)
25821 self->encoding = &unicode_encoding;
25822 else if (locale)
25823 self->encoding = &locale_encoding;
25824 else if (ascii)
25825 self->encoding = &ascii_encoding;
25826
25827 /* Compile the regular expression code to nodes. */
25828 ok = compile_to_nodes(code, code + code_len, self);
25829
25830 /* We no longer need the regular expression code. */
25831 re_dealloc(code);
25832
25833 if (!ok) {
25834 Py_DECREF(self);
25835 re_dealloc(req_chars);
25836 if (unpacked) {
25837 Py_DECREF(code_list);
25838 }
25839 return NULL;
25840 }
25841
25842 /* Make a node for the required string, if there's one. */
25843 if (req_chars) {
25844 /* Remove the FULLCASE flag if it's not a Unicode pattern or not
25845 * ignoring case.
25846 */
25847 if (!(self->flags & RE_FLAG_UNICODE) || !(self->flags &
25848 RE_FLAG_IGNORECASE))
25849 req_flags &= ~RE_FLAG_FULLCASE;
25850
25851 if (self->flags & RE_FLAG_REVERSE) {
25852 switch (req_flags) {
25853 case 0:
25854 self->req_string = make_STRING_node(self, RE_OP_STRING_REV,
25855 req_length, req_chars);
25856 break;
25857 case RE_FLAG_IGNORECASE | RE_FLAG_FULLCASE:
25858 self->req_string = make_STRING_node(self, RE_OP_STRING_FLD_REV,
25859 req_length, req_chars);
25860 break;
25861 case RE_FLAG_IGNORECASE:
25862 self->req_string = make_STRING_node(self, RE_OP_STRING_IGN_REV,
25863 req_length, req_chars);
25864 break;
25865 }
25866 } else {
25867 switch (req_flags) {
25868 case 0:
25869 self->req_string = make_STRING_node(self, RE_OP_STRING,
25870 req_length, req_chars);
25871 break;
25872 case RE_FLAG_IGNORECASE | RE_FLAG_FULLCASE:
25873 self->req_string = make_STRING_node(self, RE_OP_STRING_FLD,
25874 req_length, req_chars);
25875 break;
25876 case RE_FLAG_IGNORECASE:
25877 self->req_string = make_STRING_node(self, RE_OP_STRING_IGN,
25878 req_length, req_chars);
25879 break;
25880 }
25881 }
25882
25883 re_dealloc(req_chars);
25884 }
25885
25886 if (locale) {
25887 /* Store info about the characters in the locale for locale-sensitive
25888 * matching.
25889 */
25890 self->locale_info = re_alloc(sizeof(RE_LocaleInfo));
25891 if (!self->locale_info) {
25892 Py_DECREF(self);
25893 if (unpacked) {
25894 Py_DECREF(code_list);
25895 }
25896 return NULL;
25897 }
25898
25899 scan_locale_chars(self->locale_info);
25900 }
25901
25902 if (unpacked) {
25903 Py_DECREF(code_list);
25904 }
25905
25906 return (PyObject*)self;
25907
25908 error:
25909 re_dealloc(code);
25910 set_error(RE_ERROR_ILLEGAL, NULL);
25911 if (unpacked) {
25912 Py_DECREF(code_list);
25913 }
25914 return NULL;
25915 }
25916
25917 /* Gets the size of the codewords. */
25918 static PyObject* get_code_size(PyObject* self, PyObject* unused) {
25919 return Py_BuildValue("n", sizeof(RE_CODE));
25920 }
25921
25922 /* Gets the property dict. */
25923 static PyObject* get_properties(PyObject* self_, PyObject* args) {
25924 Py_INCREF(property_dict);
25925
25926 return property_dict;
25927 }
25928
25929 /* Folds the case of a string. */
25930 static PyObject* fold_case(PyObject* self_, PyObject* args) {
25931 RE_StringInfo str_info;
25932 Py_UCS4 (*char_at)(void* text, Py_ssize_t pos);
25933 RE_EncodingTable* encoding;
25934 RE_LocaleInfo locale_info;
25935 Py_ssize_t folded_charsize;
25936 void (*set_char_at)(void* text, Py_ssize_t pos, Py_UCS4 ch);
25937 Py_ssize_t buf_size;
25938 void* folded;
25939 Py_ssize_t folded_len;
25940 PyObject* result;
25941
25942 Py_ssize_t flags;
25943 PyObject* string;
25944 if (!PyArg_ParseTuple(args, "nO:fold_case", &flags, &string))
25945 return NULL;
25946
25947 if (!(flags & RE_FLAG_IGNORECASE)) {
25948 Py_INCREF(string);
25949 return string;
25950 }
25951
25952 /* Get the string. */
25953 if (!get_string(string, &str_info))
25954 return NULL;
25955
25956 /* Get the function for reading from the original string. */
25957 switch (str_info.charsize) {
25958 case 1:
25959 char_at = bytes1_char_at;
25960 break;
25961 case 2:
25962 char_at = bytes2_char_at;
25963 break;
25964 case 4:
25965 char_at = bytes4_char_at;
25966 break;
25967 default:
25968 release_buffer(&str_info);
25969 return NULL;
25970 }
25971
25972 /* What's the encoding? */
25973 if (flags & RE_FLAG_UNICODE)
25974 encoding = &unicode_encoding;
25975 else if (flags & RE_FLAG_LOCALE) {
25976 encoding = &locale_encoding;
25977 scan_locale_chars(&locale_info);
25978 } else if (flags & RE_FLAG_ASCII)
25979 encoding = &ascii_encoding;
25980 else
25981 encoding = &unicode_encoding;
25982
25983 /* Initially assume that the folded string will have the same width as the
25984 * original string (usually true).
25985 */
25986 folded_charsize = str_info.charsize;
25987
25988 /* When folding a Unicode string, some codepoints in the range U+00..U+FF
25989 * are mapped to codepoints in the range U+0100..U+FFFF.
25990 */
25991 if (encoding == &unicode_encoding && str_info.charsize == 1)
25992 folded_charsize = 2;
25993
25994 /* Get the function for writing to the folded string. */
25995 switch (folded_charsize) {
25996 case 1:
25997 set_char_at = bytes1_set_char_at;
25998 break;
25999 case 2:
26000 set_char_at = bytes2_set_char_at;
26001 break;
26002 case 4:
26003 set_char_at = bytes4_set_char_at;
26004 break;
26005 default:
26006 release_buffer(&str_info);
26007 return NULL;
26008 }
26009
26010 /* Allocate a buffer for the folded string. */
26011 if (flags & RE_FLAG_FULLCASE)
26012 /* When using full case-folding with Unicode, some single codepoints
26013 * are mapped to multiple codepoints.
26014 */
26015 buf_size = str_info.length * RE_MAX_FOLDED;
26016 else
26017 buf_size = str_info.length;
26018
26019 folded = re_alloc((size_t)(buf_size * folded_charsize));
26020 if (!folded) {
26021 release_buffer(&str_info);
26022 return NULL;
26023 }
26024
26025 /* Fold the case of the string. */
26026 folded_len = 0;
26027
26028 if (flags & RE_FLAG_FULLCASE) {
26029 /* Full case-folding. */
26030 int (*full_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch, Py_UCS4*
26031 folded);
26032 Py_ssize_t i;
26033 Py_UCS4 codepoints[RE_MAX_FOLDED];
26034
26035 full_case_fold = encoding->full_case_fold;
26036
26037 for (i = 0; i < str_info.length; i++) {
26038 int count;
26039 int j;
26040
26041 count = full_case_fold(&locale_info, char_at(str_info.characters,
26042 i), codepoints);
26043 for (j = 0; j < count; j++)
26044 set_char_at(folded, folded_len + j, codepoints[j]);
26045
26046 folded_len += count;
26047 }
26048 } else {
26049 /* Simple case-folding. */
26050 Py_UCS4 (*simple_case_fold)(RE_LocaleInfo* locale_info, Py_UCS4 ch);
26051 Py_ssize_t i;
26052
26053 simple_case_fold = encoding->simple_case_fold;
26054
26055 for (i = 0; i < str_info.length; i++) {
26056 Py_UCS4 ch;
26057
26058 ch = simple_case_fold(&locale_info, char_at(str_info.characters,
26059 i));
26060 set_char_at(folded, i, ch);
26061 }
26062
26063 folded_len = str_info.length;
26064 }
26065
26066 /* Build the result string. */
26067 if (str_info.is_unicode)
26068 result = build_unicode_value(folded, 0, folded_len, folded_charsize);
26069 else
26070 result = build_bytes_value(folded, 0, folded_len, folded_charsize);
26071
26072 re_dealloc(folded);
26073
26074 /* Release the original string's buffer. */
26075 release_buffer(&str_info);
26076
26077 return result;
26078 }
26079
26080 /* Returns a tuple of the Unicode characters that expand on full case-folding.
26081 */
26082 static PyObject* get_expand_on_folding(PyObject* self, PyObject* unused) {
26083 int count;
26084 PyObject* result;
26085 int i;
26086
26087 /* How many characters are there? */
26088 count = sizeof(re_expand_on_folding) / sizeof(re_expand_on_folding[0]);
26089
26090 /* Put all the characters in a tuple. */
26091 result = PyTuple_New(count);
26092 if (!result)
26093 return NULL;
26094
26095 for (i = 0; i < count; i++) {
26096 Py_UCS4 codepoint;
26097 PyObject* item;
26098
26099 codepoint = re_expand_on_folding[i];
26100
26101 item = build_unicode_value(&codepoint, 0, 1, sizeof(codepoint));
26102 if (!item)
26103 goto error;
26104
26105 /* PyTuple_SetItem borrows the reference. */
26106 PyTuple_SetItem(result, i, item);
26107 }
26108
26109 return result;
26110
26111 error:
26112 Py_DECREF(result);
26113 return NULL;
26114 }
26115
26116 /* Returns whether a character has a given value for a Unicode property. */
26117 static PyObject* has_property_value(PyObject* self_, PyObject* args) {
26118 BOOL v;
26119
26120 Py_ssize_t property_value;
26121 Py_ssize_t character;
26122 if (!PyArg_ParseTuple(args, "nn:has_property_value", &property_value,
26123 &character))
26124 return NULL;
26125
26126 v = unicode_has_property((RE_CODE)property_value, (Py_UCS4)character) ? 1 :
26127 0;
26128
26129 return Py_BuildValue("n", v);
26130 }
26131
26132 /* Returns a list of all the simple cases of a character.
26133 *
26134 * If full case-folding is turned on and the character also expands on full
26135 * case-folding, a None is appended to the list.
26136 */
26137 static PyObject* get_all_cases(PyObject* self_, PyObject* args) {
26138 RE_EncodingTable* encoding;
26139 RE_LocaleInfo locale_info;
26140 int count;
26141 Py_UCS4 cases[RE_MAX_CASES];
26142 PyObject* result;
26143 int i;
26144 Py_UCS4 folded[RE_MAX_FOLDED];
26145
26146 Py_ssize_t flags;
26147 Py_ssize_t character;
26148 if (!PyArg_ParseTuple(args, "nn:get_all_cases", &flags, &character))
26149 return NULL;
26150
26151 /* What's the encoding? */
26152 if (flags & RE_FLAG_UNICODE)
26153 encoding = &unicode_encoding;
26154 else if (flags & RE_FLAG_LOCALE) {
26155 encoding = &locale_encoding;
26156 scan_locale_chars(&locale_info);
26157 } else if (flags & RE_FLAG_ASCII)
26158 encoding = &ascii_encoding;
26159 else
26160 encoding = &unicode_encoding;
26161
26162 /* Get all the simple cases. */
26163 count = encoding->all_cases(&locale_info, (Py_UCS4)character, cases);
26164
26165 result = PyList_New(count);
26166 if (!result)
26167 return NULL;
26168
26169 for (i = 0; i < count; i++) {
26170 PyObject* item;
26171
26172 item = Py_BuildValue("n", cases[i]);
26173 if (!item)
26174 goto error;
26175
26176 /* PyList_SetItem borrows the reference. */
26177 PyList_SetItem(result, i, item);
26178 }
26179
26180 /* If the character also expands on full case-folding, append a None. */
26181 if ((flags & RE_FULL_CASE_FOLDING) == RE_FULL_CASE_FOLDING) {
26182 count = encoding->full_case_fold(&locale_info, (Py_UCS4)character,
26183 folded);
26184 if (count > 1)
26185 PyList_Append(result, Py_None);
26186 }
26187
26188 return result;
26189
26190 error:
26191 Py_DECREF(result);
26192 return NULL;
26193 }
26194
26195 /* The table of the module's functions. */
26196 static PyMethodDef _functions[] = {
26197 {"compile", (PyCFunction)re_compile, METH_VARARGS},
26198 {"get_code_size", (PyCFunction)get_code_size, METH_NOARGS},
26199 {"get_properties", (PyCFunction)get_properties, METH_VARARGS},
26200 {"fold_case", (PyCFunction)fold_case, METH_VARARGS},
26201 {"get_expand_on_folding", (PyCFunction)get_expand_on_folding, METH_NOARGS},
26202 {"has_property_value", (PyCFunction)has_property_value, METH_VARARGS},
26203 {"get_all_cases", (PyCFunction)get_all_cases, METH_VARARGS},
26204 {NULL, NULL}
26205 };
26206
26207 /* Munges the name of a property or value. */
26208 void munge_name(char* name, char* munged) {
26209 if (*name == '-')
26210 *munged++ = *name++;
26211
26212 while (*name) {
26213 if (*name == ' ' || *name == '_' || *name == '-')
26214 ++name;
26215 else
26216 *munged++ = toupper(*name++);
26217 }
26218
26219 *munged = '\0';
26220 }
26221
26222 /* Initialises the property dictionary. */
26223 Py_LOCAL_INLINE(BOOL) init_property_dict(void) {
26224 size_t value_set_count;
26225 size_t i;
26226 PyObject** value_dicts;
26227 char munged[256];
26228
26229 property_dict = NULL;
26230
26231 /* How many value sets are there? */
26232 value_set_count = 0;
26233
26234 for (i = 0; i < sizeof(re_property_values) / sizeof(re_property_values[0]);
26235 i++) {
26236 RE_PropertyValue* value;
26237
26238 value = &re_property_values[i];
26239 if (value->value_set >= value_set_count)
26240 value_set_count = (size_t)value->value_set + 1;
26241 }
26242
26243 /* Quick references for the value sets. */
26244 value_dicts = (PyObject**)re_alloc(value_set_count *
26245 sizeof(value_dicts[0]));
26246 if (!value_dicts)
26247 return FALSE;
26248
26249 memset(value_dicts, 0, value_set_count * sizeof(value_dicts[0]));
26250
26251 /* Build the property values dictionaries. */
26252 for (i = 0; i < sizeof(re_property_values) / sizeof(re_property_values[0]);
26253 i++) {
26254 RE_PropertyValue* value;
26255 PyObject* v;
26256 int status;
26257
26258 value = &re_property_values[i];
26259 if (!value_dicts[value->value_set]) {
26260 value_dicts[value->value_set] = PyDict_New();
26261 if (!value_dicts[value->value_set])
26262 goto error;
26263 }
26264
26265 v = Py_BuildValue("i", (int)value->id);
26266 if (!v)
26267 goto error;
26268
26269 munge_name(re_strings[value->name], munged);
26270 status = PyDict_SetItemString(value_dicts[value->value_set],
26271 munged, v);
26272 Py_DECREF(v);
26273 if (status < 0)
26274 goto error;
26275 }
26276
26277 /* Build the property dictionary. */
26278 property_dict = PyDict_New();
26279 if (!property_dict)
26280 goto error;
26281
26282 for (i = 0; i < sizeof(re_properties) / sizeof(re_properties[0]); i++) {
26283 RE_Property* property;
26284 PyObject* v;
26285 int status;
26286
26287 property = &re_properties[i];
26288 v = Py_BuildValue("iO", (int)property->id,
26289 value_dicts[property->value_set]);
26290 if (!v)
26291 goto error;
26292
26293 munge_name(re_strings[property->name], munged);
26294 status = PyDict_SetItemString(property_dict,
26295 munged, v);
26296 Py_DECREF(v);
26297 if (status < 0)
26298 goto error;
26299 }
26300
26301 /* DECREF the value sets. Any unused ones will be deallocated. */
26302 for (i = 0; i < value_set_count; i++)
26303 Py_XDECREF(value_dicts[i]);
26304
26305 re_dealloc(value_dicts);
26306
26307 return TRUE;
26308
26309 error:
26310 Py_XDECREF(property_dict);
26311
26312 /* DECREF the value sets. */
26313 for (i = 0; i < value_set_count; i++)
26314 Py_XDECREF(value_dicts[i]);
26315
26316 re_dealloc(value_dicts);
26317
26318 return FALSE;
26319 }
26320
26321 /* The module definition. */
26322 static struct PyModuleDef regex_module = {
26323 PyModuleDef_HEAD_INIT,
26324 "_regex",
26325 NULL,
26326 -1,
26327 _functions,
26328 NULL,
26329 NULL,
26330 NULL,
26331 NULL
26332 };
26333
26334 /* Initialises the module. */
26335 PyMODINIT_FUNC PyInit__regex(void) {
26336 PyObject* m;
26337 PyObject* d;
26338 PyObject* x;
26339
26340 #if defined(VERBOSE)
26341 /* Unbuffered in case it crashes! */
26342 setvbuf(stdout, NULL, _IONBF, 0);
26343
26344 #endif
26345 /* Initialise Pattern_Type. */
26346 Pattern_Type.tp_dealloc = pattern_dealloc;
26347 Pattern_Type.tp_repr = pattern_repr;
26348 Pattern_Type.tp_flags = Py_TPFLAGS_DEFAULT;
26349 Pattern_Type.tp_doc = pattern_doc;
26350 Pattern_Type.tp_weaklistoffset = offsetof(PatternObject, weakreflist);
26351 Pattern_Type.tp_methods = pattern_methods;
26352 Pattern_Type.tp_members = pattern_members;
26353 Pattern_Type.tp_getset = pattern_getset;
26354
26355 /* Initialise Match_Type. */
26356 Match_Type.tp_dealloc = match_dealloc;
26357 Match_Type.tp_repr = match_repr;
26358 Match_Type.tp_as_mapping = &match_as_mapping;
26359 Match_Type.tp_flags = Py_TPFLAGS_DEFAULT;
26360 Match_Type.tp_doc = match_doc;
26361 Match_Type.tp_methods = match_methods;
26362 Match_Type.tp_members = match_members;
26363 Match_Type.tp_getset = match_getset;
26364
26365 /* Initialise Scanner_Type. */
26366 Scanner_Type.tp_dealloc = scanner_dealloc;
26367 Scanner_Type.tp_flags = Py_TPFLAGS_DEFAULT;
26368 Scanner_Type.tp_doc = scanner_doc;
26369 Scanner_Type.tp_iter = scanner_iter;
26370 Scanner_Type.tp_iternext = scanner_iternext;
26371 Scanner_Type.tp_methods = scanner_methods;
26372 Scanner_Type.tp_members = scanner_members;
26373
26374 /* Initialise Splitter_Type. */
26375 Splitter_Type.tp_dealloc = splitter_dealloc;
26376 Splitter_Type.tp_flags = Py_TPFLAGS_DEFAULT;
26377 Splitter_Type.tp_doc = splitter_doc;
26378 Splitter_Type.tp_iter = splitter_iter;
26379 Splitter_Type.tp_iternext = splitter_iternext;
26380 Splitter_Type.tp_methods = splitter_methods;
26381 Splitter_Type.tp_members = splitter_members;
26382
26383 /* Initialise Capture_Type. */
26384 Capture_Type.tp_dealloc = capture_dealloc;
26385 Capture_Type.tp_str = capture_str;
26386 Capture_Type.tp_as_mapping = &capture_as_mapping;
26387 Capture_Type.tp_flags = Py_TPFLAGS_DEFAULT;
26388 Capture_Type.tp_methods = capture_methods;
26389
26390 /* Initialize object types */
26391 if (PyType_Ready(&Pattern_Type) < 0)
26392 return NULL;
26393 if (PyType_Ready(&Match_Type) < 0)
26394 return NULL;
26395 if (PyType_Ready(&Scanner_Type) < 0)
26396 return NULL;
26397 if (PyType_Ready(&Splitter_Type) < 0)
26398 return NULL;
26399 if (PyType_Ready(&Capture_Type) < 0)
26400 return NULL;
26401
26402 error_exception = NULL;
26403
26404 m = PyModule_Create(&regex_module);
26405 if (!m)
26406 return NULL;
26407
26408 #if defined(Py_GIL_DISABLED)
26409 PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
26410 #endif
26411
26412 d = PyModule_GetDict(m);
26413
26414 x = PyLong_FromLong(RE_MAGIC);
26415 if (x) {
26416 PyDict_SetItemString(d, "MAGIC", x);
26417 Py_DECREF(x);
26418 }
26419
26420 x = PyLong_FromLong(sizeof(RE_CODE));
26421 if (x) {
26422 PyDict_SetItemString(d, "CODE_SIZE", x);
26423 Py_DECREF(x);
26424 }
26425
26426 x = PyUnicode_FromString(copyright);
26427 if (x) {
26428 PyDict_SetItemString(d, "copyright", x);
26429 Py_DECREF(x);
26430 }
26431
26432 /* Initialise the property dictionary. */
26433 if (!init_property_dict()) {
26434 Py_DECREF(m);
26435 return NULL;
26436 }
26437
26438 return m;
26439 }