Debian Codegraph @

rpython/rlib/rsre/rsre_core.py

raw symbols SCIP
1 import sys
2 from rpython.rlib.debug import check_nonneg
3 from rpython.rlib.unroll import unrolling_iterable
4 from rpython.rlib.rsre import rsre_char, rsre_constants as consts
5 from rpython.tool.sourcetools import func_with_new_name
6 from rpython.rlib.objectmodel import we_are_translated, not_rpython
7 from rpython.rlib import jit
8 from rpython.rlib.rsre.rsre_jit import install_jitdriver, install_jitdriver_spec
9
10 _seen_specname = {}
11
12 def specializectx(func):
13 """A decorator that specializes 'func(ctx,...)' for each concrete subclass
14 of AbstractMatchContext. During annotation, if 'ctx' is known to be a
15 specific subclass, calling 'func' is a direct call; if 'ctx' is only known
16 to be of class AbstractMatchContext, calling 'func' is an indirect call.
17 """
18 from rpython.rlib.rsre.rsre_utf8 import Utf8MatchContext
19
20 assert func.__code__.co_varnames[0] == 'ctx'
21 specname = '_spec_' + func.__name__
22 while specname in _seen_specname:
23 specname += '_'
24 _seen_specname[specname] = True
25 # Install a copy of the function under the name '_spec_funcname' in each
26 # concrete subclass
27 specialized_methods = []
28 for prefix, concreteclass in [('buf', BufMatchContext),
29 ('str', StrMatchContext),
30 ('uni', UnicodeMatchContext),
31 ('utf8', Utf8MatchContext),
32 ]:
33 newfunc = func_with_new_name(func, prefix + specname)
34 assert not hasattr(concreteclass, specname)
35 setattr(concreteclass, specname, newfunc)
36 specialized_methods.append(newfunc)
37 # Return a dispatcher function, specialized on the exact type of 'ctx'
38 def dispatch(ctx, *args):
39 return getattr(ctx, specname)(*args)
40 dispatch._annspecialcase_ = 'specialize:argtype(0)'
41 dispatch._specialized_methods_ = specialized_methods
42 return func_with_new_name(dispatch, specname)
43
44 # ____________________________________________________________
45
46 class Error(Exception):
47 def __init__(self, msg):
48 self.msg = msg
49
50 class EndOfString(Exception):
51 pass
52
53 class CompiledPattern(object):
54 _immutable_fields_ = ['pattern[*]', 'flags']
55
56 def __init__(self, pattern, flags):
57 self.pattern = pattern
58 if not consts.V37: # 'flags' is ignored in >=3.7 mode
59 self.flags = flags
60 # check we don't get the old value of MAXREPEAT
61 # during the untranslated tests.
62 # On python3, MAXCODE can appear in patterns. It will be 65535
63 # when CODESIZE is 2
64 if not we_are_translated() and rsre_char.CODESIZE != 2:
65 assert 65535 not in pattern
66
67 def lowa(self, char_ord):
68 """Pre-3.7: uses getlower(flags).
69 Post-3.7: this is always getlower_ascii().
70 """
71 if not consts.V37:
72 return rsre_char.getlower(char_ord, self.flags)
73 else:
74 return rsre_char.getlower_ascii(char_ord)
75
76 def char_loc_ignore(self, index, char_ord):
77 assert consts.V37
78 pattern = self.pat(index)
79 return (char_ord == pattern or
80 rsre_char.getlower_locale(char_ord) == pattern or
81 rsre_char.getupper_locale(char_ord) == pattern)
82
83 def charset_loc_ignore(self, ctx, ppos, char_ord):
84 lo = rsre_char.getlower_locale(char_ord)
85 if rsre_char.check_charset(ctx, self, ppos, lo):
86 return True
87 up = rsre_char.getupper_locale(char_ord)
88 return up != lo and rsre_char.check_charset(ctx, self, ppos, up)
89
90 def pat(self, index):
91 jit.promote(self)
92 check_nonneg(index)
93 result = self.pattern[index]
94 # Check that we only return non-negative integers from this helper.
95 # It is possible that self.pattern contains negative integers
96 # (see set_charset() and set_bigcharset() in rsre_char.py)
97 # but they should not be fetched via this helper here.
98 assert result >= 0
99 return result
100
101 MODE_ANY = '\x00' # an empty match is fine
102 MODE_NONEMPTY = '\x01' # must have a non-empty match
103 MODE_FULL = '\x02' # must match the whole string
104
105 class AbstractMatchContext(object):
106 """Abstract base class"""
107 _immutable_fields_ = ['end']
108 match_start = 0
109 match_end = 0
110 match_marks = None
111 match_marks_flat = None
112 match_mode = MODE_ANY
113
114 def __init__(self, match_start, end):
115 # 'match_start' and 'end' must be known to be non-negative
116 # and they must not be more than len(string).
117 check_nonneg(match_start)
118 check_nonneg(end)
119 self.match_start = match_start
120 self.end = end
121
122 def reset(self, start, must_advance=False):
123 self.match_start = start
124 self.match_marks = None
125 self.match_marks_flat = None
126 #
127 assert MODE_ANY == chr(False)
128 assert MODE_NONEMPTY == chr(True)
129 self.match_mode = chr(must_advance)
130
131 @not_rpython
132 def _fullmatch_only(self, x=None):
133 raise Exception("'ctx.fullmatch_only' was replaced with"
134 " 'ctx.match_mode'")
135 fullmatch_only = property(_fullmatch_only, _fullmatch_only)
136
137 @not_rpython
138 def str(self, index):
139 """Must be overridden in a concrete subclass.
140 The @not_rpython is used to generate a translation-time crash
141 if there is a call to str() that is indirect. All calls must
142 be direct for performance reasons; you need to specialize the
143 caller with @specializectx."""
144 raise NotImplementedError
145
146 # The following methods are provided to be overriden in
147 # Utf8MatchContext. The non-utf8 implementation is provided
148 # by the FixedMatchContext abstract subclass, in order to use
149 # the same @not_rpython safety trick as above. If you get a
150 # "not_rpython" error during translation, either consider
151 # calling the methods xxx_indirect() instead of xxx(), or if
152 # applicable add the @specializectx decorator.
153 ZERO = 0
154 @not_rpython
155 def next(self, position):
156 raise NotImplementedError
157 @not_rpython
158 def prev(self, position):
159 raise NotImplementedError
160 @not_rpython
161 def next_n(self, position, n):
162 raise NotImplementedError
163 @not_rpython
164 def prev_n(self, position, n, start_position):
165 raise NotImplementedError
166 @not_rpython
167 def debug_check_pos(self, position):
168 raise NotImplementedError
169 @not_rpython
170 def maximum_distance(self, position_low, position_high):
171 raise NotImplementedError
172 @not_rpython
173 def get_single_byte(self, base_position, index):
174 raise NotImplementedError
175
176 def bytes_difference(self, position1, position2):
177 return position1 - position2
178 def go_forward_by_bytes(self, base_position, index):
179 return base_position + index
180 def next_indirect(self, position):
181 assert position < self.end
182 return position + 1 # like next(), but can be called indirectly
183 def prev_indirect(self, position):
184 position -= 1 # like prev(), but can be called indirectly
185 if position < 0:
186 raise EndOfString
187 return position
188
189 def get_mark(self, gid):
190 return find_mark(self.match_marks, gid)
191
192 def flatten_marks(self):
193 # for testing
194 if self.match_marks_flat is None:
195 self._compute_flattened_marks()
196 return self.match_marks_flat
197
198 def _compute_flattened_marks(self):
199 self.match_marks_flat = [self.match_start, self.match_end]
200 mark = self.match_marks
201 if mark is not None:
202 self.match_lastindex = mark.gid
203 else:
204 self.match_lastindex = -1
205 while mark is not None:
206 index = mark.gid + 2
207 while index >= len(self.match_marks_flat):
208 self.match_marks_flat.append(-1)
209 if self.match_marks_flat[index] == -1:
210 self.match_marks_flat[index] = mark.position
211 mark = mark.prev
212 self.match_marks = None # clear
213
214 def span(self, groupnum=0):
215 # compatibility
216 fmarks = self.flatten_marks()
217 groupnum *= 2
218 if groupnum >= len(fmarks):
219 return (-1, -1)
220 return (fmarks[groupnum], fmarks[groupnum+1])
221
222 def group(self, groupnum=0):
223 frm, to = self.span(groupnum)
224 if 0 <= frm <= to:
225 return self._string[frm:to]
226 else:
227 return None
228
229 def fresh_copy(self, start):
230 raise NotImplementedError
231
232 class FixedMatchContext(AbstractMatchContext):
233 """Abstract subclass to introduce the default implementation for
234 these position methods. The Utf8MatchContext subclass doesn't
235 inherit from here."""
236
237 next = AbstractMatchContext.next_indirect
238 prev = AbstractMatchContext.prev_indirect
239
240 def next_n(self, position, n, end_position):
241 position += n
242 if position > end_position:
243 raise EndOfString
244 return position
245
246 def prev_n(self, position, n, start_position):
247 position -= n
248 if position < start_position:
249 raise EndOfString
250 return position
251
252 def debug_check_pos(self, position):
253 pass
254
255 def maximum_distance(self, position_low, position_high):
256 return position_high - position_low
257
258
259 class BufMatchContext(FixedMatchContext):
260 """Concrete subclass for matching in a buffer."""
261
262 _immutable_fields_ = ["_buffer"]
263
264 def __init__(self, buf, match_start, end):
265 FixedMatchContext.__init__(self, match_start, end)
266 self._buffer = buf
267
268 def str(self, index):
269 check_nonneg(index)
270 return ord(self._buffer.getitem(index))
271
272 def fresh_copy(self, start):
273 return BufMatchContext(self._buffer, start,
274 self.end)
275
276 def get_single_byte(self, base_position, index):
277 return self.str(base_position + index)
278
279
280 class StrMatchContext(FixedMatchContext):
281 """Concrete subclass for matching in a plain string."""
282
283 _immutable_fields_ = ["_string"]
284
285 def __init__(self, string, match_start, end):
286 FixedMatchContext.__init__(self, match_start, end)
287 self._string = string
288
289 def str(self, index):
290 check_nonneg(index)
291 return ord(self._string[index])
292
293 def fresh_copy(self, start):
294 return StrMatchContext(self._string, start,
295 self.end)
296
297 def get_single_byte(self, base_position, index):
298 return self.str(base_position + index)
299
300 def _real_pos(self, index):
301 return index # overridden by tests
302
303
304 class UnicodeMatchContext(FixedMatchContext):
305 """Concrete subclass for matching in a unicode string."""
306
307 _immutable_fields_ = ["_unicodestr"]
308
309 def __init__(self, unicodestr, match_start, end):
310 FixedMatchContext.__init__(self, match_start, end)
311 self._unicodestr = unicodestr
312
313 def str(self, index):
314 check_nonneg(index)
315 return ord(self._unicodestr[index])
316
317 def fresh_copy(self, start):
318 return UnicodeMatchContext(self._unicodestr, start,
319 self.end)
320
321 def get_single_byte(self, base_position, index):
322 return self.str(base_position + index)
323
324 # ____________________________________________________________
325
326 class Mark(object):
327 _immutable_ = True
328
329 def __init__(self, gid, position, prev):
330 self.gid = gid
331 self.position = position
332 self.prev = prev # chained list
333
334 def __repr__(self):
335 return "Mark(%r, %r, %r)" % (self.gid, self.position, self.prev)
336
337 def find_mark(mark, gid):
338 while mark is not None:
339 if mark.gid == gid:
340 return mark.position
341 mark = mark.prev
342 return -1
343
344 # ____________________________________________________________
345
346 class MatchResult(object):
347 subresult = None
348
349 def move_to_next_result(self, ctx, pattern):
350 # returns either 'self' or None
351 result = self.subresult
352 if result is None:
353 return
354 if result.move_to_next_result(ctx, pattern):
355 return self
356 return self.find_next_result(ctx, pattern)
357
358 def find_next_result(self, ctx, pattern):
359 raise NotImplementedError
360
361 MATCHED_OK = MatchResult()
362
363 class BranchMatchResult(MatchResult):
364
365 def __init__(self, ppos, ptr, marks):
366 self.ppos = ppos
367 self.start_ptr = ptr
368 self.start_marks = marks
369
370 @jit.unroll_safe
371 def find_first_result(self, ctx, pattern):
372 ppos = jit.hint(self.ppos, promote=True)
373 while pattern.pat(ppos):
374 result = sre_match(ctx, pattern, ppos + 1, self.start_ptr, self.start_marks)
375 ppos += pattern.pat(ppos)
376 if result is not None:
377 self.subresult = result
378 self.ppos = ppos
379 return self
380 find_next_result = find_first_result
381
382 class RepeatOneMatchResult(MatchResult):
383 install_jitdriver('RepeatOne',
384 greens=['nextppos', 'pattern'],
385 reds=['ptr', 'self', 'ctx'],
386 debugprint=(1, 0)) # indices in 'greens'
387
388 def __init__(self, nextppos, minptr, ptr, marks):
389 self.nextppos = nextppos
390 self.minptr = minptr
391 self.start_ptr = ptr
392 self.start_marks = marks
393
394 def find_first_result(self, ctx, pattern):
395 ptr = self.start_ptr
396 nextppos = self.nextppos
397 while ptr >= self.minptr:
398 ctx.jitdriver_RepeatOne.jit_merge_point(
399 self=self, ptr=ptr, ctx=ctx, nextppos=nextppos,
400 pattern=pattern)
401 result = sre_match(ctx, pattern, nextppos, ptr, self.start_marks)
402 try:
403 ptr = ctx.prev_indirect(ptr)
404 except EndOfString:
405 ptr = -1
406 if result is not None:
407 self.subresult = result
408 self.start_ptr = ptr
409 return self
410 find_next_result = find_first_result
411
412
413 class MinRepeatOneMatchResult(MatchResult):
414 install_jitdriver('MinRepeatOne',
415 greens=['nextppos', 'ppos3', 'pattern'],
416 reds=['max_count', 'ptr', 'self', 'ctx'],
417 debugprint=(2, 0)) # indices in 'greens'
418
419 def __init__(self, nextppos, ppos3, max_count, ptr, marks):
420 self.nextppos = nextppos
421 self.ppos3 = ppos3
422 self.max_count = max_count
423 self.start_ptr = ptr
424 self.start_marks = marks
425
426 def find_first_result(self, ctx, pattern):
427 ptr = self.start_ptr
428 nextppos = self.nextppos
429 max_count = self.max_count
430 ppos3 = self.ppos3
431 while max_count >= 0:
432 ctx.jitdriver_MinRepeatOne.jit_merge_point(
433 self=self, ptr=ptr, ctx=ctx, nextppos=nextppos, ppos3=ppos3,
434 max_count=max_count, pattern=pattern)
435 result = sre_match(ctx, pattern, nextppos, ptr, self.start_marks)
436 if result is not None:
437 self.subresult = result
438 self.start_ptr = ptr
439 self.max_count = max_count
440 return self
441 if not self.next_char_ok(ctx, pattern, ptr, ppos3):
442 break
443 ptr = ctx.next_indirect(ptr)
444 max_count -= 1
445
446 def find_next_result(self, ctx, pattern):
447 ptr = self.start_ptr
448 if not self.next_char_ok(ctx, pattern, ptr, self.ppos3):
449 return
450 self.start_ptr = ctx.next_indirect(ptr)
451 return self.find_first_result(ctx, pattern)
452
453 def next_char_ok(self, ctx, pattern, ptr, ppos):
454 if ptr == ctx.end:
455 return False
456 op = pattern.pat(ppos)
457 for op1, checkerfn in unroll_char_checker:
458 if op1 == op:
459 return checkerfn(ctx, pattern, ptr, ppos)
460 # obscure case: it should be a single char pattern, but isn't
461 # one of the opcodes in unroll_char_checker (see test_ext_opcode)
462 return sre_match(ctx, pattern, ppos, ptr, self.start_marks) is not None
463
464 class AbstractUntilMatchResult(MatchResult):
465
466 def __init__(self, ppos, tailppos, ptr, marks):
467 self.ppos = ppos
468 self.tailppos = tailppos
469 self.cur_ptr = ptr
470 self.cur_marks = marks
471 self.pending = None
472 self.num_pending = 0
473
474 class Pending(object):
475 def __init__(self, ptr, marks, enum, next):
476 self.ptr = ptr
477 self.marks = marks
478 self.enum = enum
479 self.next = next # chained list
480
481 class MaxUntilMatchResult(AbstractUntilMatchResult):
482 install_jitdriver('MaxUntil',
483 greens=['ppos', 'tailppos', 'match_more', 'pattern'],
484 reds=['ptr', 'marks', 'self', 'ctx'],
485 debugprint=(3, 0, 2))
486
487 def find_first_result(self, ctx, pattern):
488 return self.search_next(ctx, pattern, match_more=True)
489
490 def find_next_result(self, ctx, pattern):
491 return self.search_next(ctx, pattern, match_more=False)
492
493 def search_next(self, ctx, pattern, match_more):
494 ppos = self.ppos
495 tailppos = self.tailppos
496 ptr = self.cur_ptr
497 marks = self.cur_marks
498 while True:
499 ctx.jitdriver_MaxUntil.jit_merge_point(
500 ppos=ppos, tailppos=tailppos, match_more=match_more,
501 ptr=ptr, marks=marks, self=self, ctx=ctx,
502 pattern=pattern)
503 if match_more:
504 max = pattern.pat(ppos+2)
505 if max == rsre_char.MAXREPEAT or self.num_pending < max:
506 # try to match one more 'item'
507 enum = sre_match(ctx, pattern, ppos + 3, ptr, marks)
508 else:
509 enum = None # 'max' reached, no more matches
510 else:
511 p = self.pending
512 if p is None:
513 return
514 self.pending = p.next
515 self.num_pending -= 1
516 ptr = p.ptr
517 marks = p.marks
518 enum = p.enum.move_to_next_result(ctx, pattern)
519 #
520 min = pattern.pat(ppos+1)
521 if enum is not None:
522 # matched one more 'item'. record it and continue.
523 last_match_zero_length = (ctx.match_end == ptr)
524 self.pending = Pending(ptr, marks, enum, self.pending)
525 self.num_pending += 1
526 ptr = ctx.match_end
527 marks = ctx.match_marks
528 if last_match_zero_length and self.num_pending >= min:
529 # zero-width protection: after an empty match, if there
530 # are enough matches, don't try to match more. Instead,
531 # fall through to trying to match 'tail'.
532 pass
533 else:
534 match_more = True
535 continue
536
537 # 'item' no longer matches.
538 if self.num_pending >= min:
539 # try to match 'tail' if we have enough 'item'
540 result = sre_match(ctx, pattern, tailppos, ptr, marks)
541 if result is not None:
542 self.subresult = result
543 self.cur_ptr = ptr
544 self.cur_marks = marks
545 return self
546 match_more = False
547
548 class MinUntilMatchResult(AbstractUntilMatchResult):
549 install_jitdriver('MinUntil',
550 greens=['ppos', 'tailppos', 'resume', 'pattern'],
551 reds=['ptr', 'marks', 'self', 'ctx'],
552 debugprint=(3, 0, 2))
553
554 def find_first_result(self, ctx, pattern):
555 return self.search_next(ctx, pattern, resume=False)
556
557 def find_next_result(self, ctx, pattern):
558 return self.search_next(ctx, pattern, resume=True)
559
560 def search_next(self, ctx, pattern, resume):
561 ppos = self.ppos
562 ptr = self.cur_ptr
563 marks = self.cur_marks
564 tailppos = self.tailppos
565 while True:
566 ctx.jitdriver_MinUntil.jit_merge_point(
567 ppos=ppos, tailppos=tailppos, resume=resume,
568 ptr=ptr, marks=marks, self=self, ctx=ctx,
569 pattern=pattern)
570 # try to match 'tail' if we have enough 'item'
571 min = pattern.pat(ppos+1)
572 if not resume and self.num_pending >= min:
573 result = sre_match(ctx, pattern, tailppos, ptr, marks)
574 if result is not None:
575 self.subresult = result
576 self.cur_ptr = ptr
577 self.cur_marks = marks
578 return self
579 resume = False
580
581 max = pattern.pat(ppos+2)
582 if max == rsre_char.MAXREPEAT or self.num_pending < max:
583 # try to match one more 'item'
584 enum = sre_match(ctx, pattern, ppos + 3, ptr, marks)
585 #
586 # zero-width match protection
587 if self.num_pending >= min:
588 while enum is not None and ptr == ctx.match_end:
589 enum = enum.move_to_next_result(ctx, pattern)
590 else:
591 enum = None # 'max' reached, no more matches
592
593 while enum is None:
594 # 'item' does not match; try to get further results from
595 # the 'pending' list.
596 p = self.pending
597 if p is None:
598 return
599 self.pending = p.next
600 self.num_pending -= 1
601 ptr = p.ptr
602 marks = p.marks
603 enum = p.enum.move_to_next_result(ctx, pattern)
604
605 # matched one more 'item'. record it and continue
606 self.pending = Pending(ptr, marks, enum, self.pending)
607 self.num_pending += 1
608 ptr = ctx.match_end
609 marks = ctx.match_marks
610
611 install_jitdriver_spec('MaxUntilPossessive',
612 greens=['ppos', 'pattern'],
613 reds=['ptr', 'matches_done', 'marks', 'ctx'],
614 debugprint=(1, 0))
615
616 @specializectx
617 def find_repetition_end_possessive(ctx, pattern, ppos, ptr, marks):
618 matches_done = 0
619 enum = None
620 while True:
621 ctx.jitdriver_MaxUntilPossessive.jit_merge_point(
622 ppos=ppos,
623 ptr=ptr, marks=marks, ctx=ctx, matches_done=matches_done,
624 pattern=pattern)
625 maxmatch = pattern.pat(ppos+2)
626 if maxmatch == rsre_char.MAXREPEAT or matches_done < maxmatch:
627 # try to match one more 'item'
628 enum = sre_match(ctx, pattern, ppos + 3, ptr, marks)
629 else:
630 enum = None # 'max' reached, no more matches
631 minmatch = pattern.pat(ppos+1)
632 if enum is not None:
633 matches_done += 1
634 # matched one more 'item'.
635 last_match_zero_length = (ctx.match_end == ptr)
636 ptr = ctx.match_end
637 marks = ctx.match_marks
638 if last_match_zero_length and matches_done >= minmatch:
639 # zero-width protection: after an empty match, if there
640 # are enough matches, don't try to match more. Instead,
641 # fall through to trying to match 'tail'.
642 pass
643 else:
644 continue
645 if matches_done >= minmatch:
646 ctx.match_marks = marks
647 return ptr
648 return -1
649
650
651 # ____________________________________________________________
652
653 @specializectx
654 @jit.unroll_safe
655 def sre_match(ctx, pattern, ppos, ptr, marks):
656 """Returns either None or a MatchResult object. Usually we only need
657 the first result, but there is the case of REPEAT...UNTIL where we
658 need all results; in that case we use the method move_to_next_result()
659 of the MatchResult."""
660 while True:
661 op = pattern.pat(ppos)
662 ppos += 1
663
664 #jit.jit_debug("sre_match", op, ppos, ptr)
665 #
666 # When using the JIT, calls to sre_match() must always have a constant
667 # (green) argument for 'ppos'. If not, the following assert fails.
668 jit.assert_green(op)
669
670 if op == consts.OPCODE_FAILURE:
671 return
672
673 elif op == consts.OPCODE_SUCCESS:
674 mode = ctx.match_mode
675 if mode == MODE_FULL:
676 if ptr != ctx.end:
677 return # not a full match
678 elif mode == MODE_NONEMPTY:
679 if ptr == ctx.match_start:
680 return # empty match
681 ctx.match_end = ptr
682 ctx.match_marks = marks
683 return MATCHED_OK
684
685 elif (op == consts.OPCODE_MAX_UNTIL or
686 op == consts.OPCODE_MIN_UNTIL):
687 ctx.match_end = ptr
688 ctx.match_marks = marks
689 return MATCHED_OK
690
691 elif op == consts.OPCODE_ANY:
692 # match anything (except a newline)
693 # <ANY>
694 if ptr >= ctx.end or rsre_char.is_linebreak(ctx.str(ptr)):
695 return
696 ptr = ctx.next(ptr)
697
698 elif op == consts.OPCODE_ANY_ALL:
699 # match anything
700 # <ANY_ALL>
701 if ptr >= ctx.end:
702 return
703 ptr = ctx.next(ptr)
704
705 elif op == consts.OPCODE_ASSERT:
706 # assert subpattern
707 # <ASSERT> <0=skip> <1=back> <pattern>
708 try:
709 ptr1 = ctx.prev_n(ptr, pattern.pat(ppos+1), ctx.ZERO)
710 except EndOfString:
711 return
712 saved = ctx.match_mode
713 ctx.match_mode = MODE_ANY
714 stop = sre_match(ctx, pattern, ppos + 2, ptr1, marks) is None
715 ctx.match_mode = saved
716 if stop:
717 return
718 marks = ctx.match_marks
719 ppos += pattern.pat(ppos)
720
721 elif op == consts.OPCODE_ASSERT_NOT:
722 # assert not subpattern
723 # <ASSERT_NOT> <0=skip> <1=back> <pattern>
724
725 try:
726 ptr1 = ctx.prev_n(ptr, pattern.pat(ppos+1), ctx.ZERO)
727 except EndOfString:
728 pass
729 else:
730 saved = ctx.match_mode
731 ctx.match_mode = MODE_ANY
732 stop = sre_match(ctx, pattern, ppos + 2, ptr1, marks) is not None
733 ctx.match_mode = saved
734 if stop:
735 return
736 ppos += pattern.pat(ppos)
737
738 elif op == consts.OPCODE_AT:
739 # match at given position (e.g. at beginning, at boundary, etc.)
740 # <AT> <code>
741 if not sre_at(ctx, pattern.pat(ppos), ptr):
742 return
743 ppos += 1
744
745 elif op == consts.OPCODE_BRANCH:
746 # alternation
747 # <BRANCH> <0=skip> code <JUMP> ... <NULL>
748 result = BranchMatchResult(ppos, ptr, marks)
749 return result.find_first_result(ctx, pattern)
750
751 elif op == consts.OPCODE_CATEGORY:
752 # seems to be never produced, but used by some tests from
753 # pypy/module/_sre/test
754 # <CATEGORY> <category>
755 if (ptr == ctx.end or
756 not rsre_char.category_dispatch(pattern.pat(ppos), ctx.str(ptr))):
757 return
758 ptr = ctx.next(ptr)
759 ppos += 1
760
761 elif op == consts.OPCODE_GROUPREF:
762 # match backreference
763 # <GROUPREF> <groupnum>
764 startptr, length_bytes = get_group_ref(ctx, marks, pattern.pat(ppos))
765 if length_bytes < 0:
766 return # group was not previously defined
767 if not match_repeated(ctx, ptr, startptr, length_bytes):
768 return # no match
769 ptr = ctx.go_forward_by_bytes(ptr, length_bytes)
770 ppos += 1
771
772 elif op == consts.OPCODE_GROUPREF_IGNORE:
773 # match backreference
774 # <GROUPREF> <groupnum>
775 startptr, length_bytes = get_group_ref(ctx, marks, pattern.pat(ppos))
776 if length_bytes < 0:
777 return # group was not previously defined
778 ptr = match_repeated_ignore(ctx, ptr, startptr, length_bytes, pattern)
779 if ptr < ctx.ZERO:
780 return # no match
781 ppos += 1
782
783 elif consts.eq(op, consts.OPCODE37_GROUPREF_UNI_IGNORE):
784 # unicode version of OPCODE_GROUPREF_IGNORE
785 # <GROUPREF> <groupnum>
786 startptr, length_bytes = get_group_ref(ctx, marks, pattern.pat(ppos))
787 if length_bytes < 0:
788 return # group was not previously defined
789 ptr = match_repeated_uni_ignore(ctx, ptr, startptr, length_bytes)
790 if ptr < ctx.ZERO:
791 return # no match
792 ppos += 1
793
794 elif consts.eq(op, consts.OPCODE37_GROUPREF_LOC_IGNORE):
795 # locale version of OPCODE_GROUPREF_IGNORE
796 # <GROUPREF> <groupnum>
797 startptr, length_bytes = get_group_ref(ctx, marks, pattern.pat(ppos))
798 if length_bytes < 0:
799 return # group was not previously defined
800 ptr = match_repeated_loc_ignore(ctx, ptr, startptr, length_bytes)
801 if ptr < ctx.ZERO:
802 return # no match
803 ppos += 1
804
805 elif op == consts.OPCODE_GROUPREF_EXISTS:
806 # conditional match depending on the existence of a group
807 # <GROUPREF_EXISTS> <group> <skip> codeyes <JUMP> codeno ...
808 _, length_bytes = get_group_ref(ctx, marks, pattern.pat(ppos))
809 if length_bytes >= 0:
810 ppos += 2 # jump to 'codeyes'
811 else:
812 ppos += pattern.pat(ppos+1) # jump to 'codeno'
813
814 elif op == consts.OPCODE_IN:
815 # match set member (or non_member)
816 # <IN> <skip> <set>
817 if ptr >= ctx.end or not rsre_char.check_charset(ctx, pattern, ppos+1,
818 ctx.str(ptr)):
819 return
820 ppos += pattern.pat(ppos)
821 ptr = ctx.next(ptr)
822
823 elif op == consts.OPCODE_IN_IGNORE:
824 # match set member (or non_member), ignoring case
825 # <IN> <skip> <set>
826 if ptr >= ctx.end or not rsre_char.check_charset(ctx, pattern, ppos+1,
827 pattern.lowa(ctx.str(ptr))):
828 return
829 ppos += pattern.pat(ppos)
830 ptr = ctx.next(ptr)
831
832 elif consts.eq(op, consts.OPCODE37_IN_UNI_IGNORE):
833 # match set member (or non_member), ignoring case, unicode mode
834 # <IN> <skip> <set>
835 if ptr >= ctx.end or not rsre_char.check_charset(ctx, pattern, ppos+1,
836 rsre_char.getlower_unicode(ctx.str(ptr))):
837 return
838 ppos += pattern.pat(ppos)
839 ptr = ctx.next(ptr)
840
841 elif consts.eq(op, consts.OPCODE37_IN_LOC_IGNORE):
842 # match set member (or non_member), ignoring case, locale mode
843 # <IN> <skip> <set>
844 if ptr >= ctx.end or not pattern.charset_loc_ignore(ctx, ppos+1,
845 ctx.str(ptr)):
846 return
847 ppos += pattern.pat(ppos)
848 ptr = ctx.next(ptr)
849
850 elif op == consts.OPCODE_INFO:
851 # optimization info block
852 # <INFO> <0=skip> <1=flags> <2=min> ...
853 if ctx.maximum_distance(ptr, ctx.end) < pattern.pat(ppos+2):
854 return
855 ppos += pattern.pat(ppos)
856
857 elif op == consts.OPCODE_JUMP:
858 ppos += pattern.pat(ppos)
859
860 elif op == consts.OPCODE_LITERAL:
861 # match literal string
862 # <LITERAL> <code>
863 if ptr >= ctx.end or ctx.str(ptr) != pattern.pat(ppos):
864 return
865 ppos += 1
866 ptr = ctx.next(ptr)
867
868 elif op == consts.OPCODE_LITERAL_IGNORE:
869 # match literal string, ignoring case
870 # <LITERAL_IGNORE> <code>
871 if ptr >= ctx.end or pattern.lowa(ctx.str(ptr)) != pattern.pat(ppos):
872 return
873 ppos += 1
874 ptr = ctx.next(ptr)
875
876 elif consts.eq(op, consts.OPCODE37_LITERAL_UNI_IGNORE):
877 # match literal string, ignoring case, unicode mode
878 # <LITERAL_IGNORE> <code>
879 if ptr >= ctx.end or rsre_char.getlower_unicode(ctx.str(ptr)) != pattern.pat(ppos):
880 return
881 ppos += 1
882 ptr = ctx.next(ptr)
883
884 elif consts.eq(op, consts.OPCODE37_LITERAL_LOC_IGNORE):
885 # match literal string, ignoring case, locale mode
886 # <LITERAL_IGNORE> <code>
887 if ptr >= ctx.end or not pattern.char_loc_ignore(ppos, ctx.str(ptr)):
888 return
889 ppos += 1
890 ptr = ctx.next(ptr)
891
892 elif op == consts.OPCODE_MARK:
893 # set mark
894 # <MARK> <gid>
895 gid = pattern.pat(ppos)
896 marks = Mark(gid, ptr, marks)
897 ppos += 1
898
899 elif op == consts.OPCODE_NOT_LITERAL:
900 # match if it's not a literal string
901 # <NOT_LITERAL> <code>
902 if ptr >= ctx.end or ctx.str(ptr) == pattern.pat(ppos):
903 return
904 ppos += 1
905 ptr = ctx.next(ptr)
906
907 elif op == consts.OPCODE_NOT_LITERAL_IGNORE:
908 # match if it's not a literal string, ignoring case
909 # <NOT_LITERAL> <code>
910 if ptr >= ctx.end or pattern.lowa(ctx.str(ptr)) == pattern.pat(ppos):
911 return
912 ppos += 1
913 ptr = ctx.next(ptr)
914
915 elif consts.eq(op, consts.OPCODE37_NOT_LITERAL_UNI_IGNORE):
916 # match if it's not a literal string, ignoring case, unicode mode
917 # <NOT_LITERAL> <code>
918 if ptr >= ctx.end or rsre_char.getlower_unicode(ctx.str(ptr)) == pattern.pat(ppos):
919 return
920 ppos += 1
921 ptr = ctx.next(ptr)
922
923 elif consts.eq(op, consts.OPCODE37_NOT_LITERAL_LOC_IGNORE):
924 # match if it's not a literal string, ignoring case, locale mode
925 # <NOT_LITERAL> <code>
926 if ptr >= ctx.end or pattern.char_loc_ignore(ppos, ctx.str(ptr)):
927 return
928 ppos += 1
929 ptr = ctx.next(ptr)
930
931 elif op == consts.OPCODE_REPEAT:
932 # general repeat. in this version of the re module, all the work
933 # is done here, and not on the later UNTIL operator.
934 # <REPEAT> <skip> <1=min> <2=max> item <UNTIL> tail
935 # FIXME: we probably need to deal with zero-width matches in here..
936
937 # decode the later UNTIL operator to see if it is actually
938 # a MAX_UNTIL or MIN_UNTIL
939 untilppos = ppos + pattern.pat(ppos)
940 tailppos = untilppos + 1
941 op = pattern.pat(untilppos)
942 if op == consts.OPCODE_MAX_UNTIL:
943 # the hard case: we have to match as many repetitions as
944 # possible, followed by the 'tail'. we do this by
945 # remembering each state for each possible number of
946 # 'item' matching.
947 result = MaxUntilMatchResult(ppos, tailppos, ptr, marks)
948 return result.find_first_result(ctx, pattern)
949
950 elif op == consts.OPCODE_MIN_UNTIL:
951 # first try to match the 'tail', and if it fails, try
952 # to match one more 'item' and try again
953 result = MinUntilMatchResult(ppos, tailppos, ptr, marks)
954 return result.find_first_result(ctx, pattern)
955
956 else:
957 raise Error("missing UNTIL after REPEAT")
958
959 elif op == consts.OPCODE_REPEAT_ONE:
960 # match repeated sequence (maximizing regexp).
961 # this operator only works if the repeated item is
962 # exactly one character wide, and we're not already
963 # collecting backtracking points. for other cases,
964 # use the MAX_REPEAT operator.
965 # <REPEAT_ONE> <skip> <1=min> <2=max> item <SUCCESS> tail
966 start = ptr
967
968 try:
969 minptr = ctx.next_n(start, pattern.pat(ppos+1), ctx.end)
970 except EndOfString:
971 return # cannot match
972 ptr = find_repetition_end(ctx, pattern, ppos+3, start,
973 pattern.pat(ppos+2),
974 marks)
975 # when we arrive here, ptr points to the tail of the target
976 # string. check if the rest of the pattern matches,
977 # and backtrack if not.
978 nextppos = ppos + pattern.pat(ppos)
979 result = RepeatOneMatchResult(nextppos, minptr, ptr, marks)
980 return result.find_first_result(ctx, pattern)
981
982 elif op == consts.OPCODE_MIN_REPEAT_ONE:
983 # match repeated sequence (minimizing regexp).
984 # this operator only works if the repeated item is
985 # exactly one character wide, and we're not already
986 # collecting backtracking points. for other cases,
987 # use the MIN_REPEAT operator.
988 # <MIN_REPEAT_ONE> <skip> <1=min> <2=max> item <SUCCESS> tail
989 start = ptr
990 min = pattern.pat(ppos+1)
991 if min > 0:
992 try:
993 minptr = ctx.next_n(ptr, min, ctx.end)
994 except EndOfString:
995 return # cannot match
996 # count using pattern min as the maximum
997 ptr = find_repetition_end(ctx, pattern, ppos+3, ptr, min, marks)
998 if ptr < minptr:
999 return # did not match minimum number of times
1000
1001 max_count = sys.maxint
1002 max = pattern.pat(ppos+2)
1003 if max != rsre_char.MAXREPEAT:
1004 max_count = max - min
1005 assert max_count >= 0
1006 nextppos = ppos + pattern.pat(ppos)
1007 result = MinRepeatOneMatchResult(nextppos, ppos+3, max_count,
1008 ptr, marks)
1009 return result.find_first_result(ctx, pattern)
1010 elif consts.eq(op, consts.OPCODE_POSSESSIVE_REPEAT_ONE):
1011 # match repeated sequence (maximizing regexp) without
1012 # backtracking
1013
1014 # this operator only works if the repeated item is
1015 # exactly one character wide, and we're not already
1016 # collecting backtracking points. for other cases,
1017 # use the MAX_REPEAT operator
1018
1019 # <POSSESSIVE_REPEAT_ONE> <skip> <1=min> <2=max> item <SUCCESS>
1020 # tail
1021 start = ptr
1022
1023 try:
1024 minptr = ctx.next_n(start, pattern.pat(ppos+1), ctx.end)
1025 except EndOfString:
1026 return # cannot match
1027 ptr = find_repetition_end(ctx, pattern, ppos+3, start,
1028 pattern.pat(ppos+2),
1029 marks)
1030 if ptr < minptr:
1031 return # did not match minimum number of times
1032 # when we arrive here, ptr points to the tail of the target
1033 # string. match the rest of the pattern.
1034 ppos += pattern.pat(ppos)
1035 elif consts.eq(op, consts.OPCODE_POSSESSIVE_REPEAT):
1036 # create possessive repeat contexts.
1037 # <POSSESSIVE_REPEAT> <skip> <1=min> <2=max> pattern
1038 # <SUCCESS> tail
1039 start = ptr
1040 saved = ctx.match_mode
1041 ctx.match_mode = MODE_ANY
1042 ptr = find_repetition_end_possessive(
1043 ctx, pattern,
1044 ppos, start,
1045 marks)
1046 ctx.match_mode = saved
1047 if ptr < 0:
1048 return None
1049 marks = ctx.match_marks
1050 ppos += pattern.pat(ppos) + 1 # match tail now
1051 elif consts.eq(op, consts.OPCODE_ATOMIC_GROUP):
1052 # Atomic Group Sub Pattern
1053 # <ATOMIC_GROUP> <skip> pattern <SUCCESS> tail
1054
1055 saved = ctx.match_mode
1056 ctx.match_mode = MODE_ANY
1057 match = sre_match(ctx, pattern, ppos + 1, ptr, marks)
1058 ctx.match_mode = saved
1059 if match is None:
1060 return None
1061 ptr = ctx.match_end
1062 ppos += pattern.pat(ppos) # match tail now
1063 else:
1064 raise Error("bad pattern code %d" % op)
1065
1066
1067 def get_group_ref(ctx, marks, groupnum):
1068 gid = groupnum * 2
1069 startptr = find_mark(marks, gid)
1070 if startptr < ctx.ZERO:
1071 return 0, -1
1072 endptr = find_mark(marks, gid + 1)
1073 length_bytes = ctx.bytes_difference(endptr, startptr)
1074 return startptr, length_bytes
1075
1076 @specializectx
1077 def match_repeated(ctx, ptr, oldptr, length_bytes):
1078 if ctx.bytes_difference(ctx.end, ptr) < length_bytes:
1079 return False
1080 for i in range(length_bytes):
1081 if ctx.get_single_byte(ptr, i) != ctx.get_single_byte(oldptr, i):
1082 return False
1083 return True
1084
1085 @specializectx
1086 def match_repeated_ignore(ctx, ptr, oldptr, length_bytes, pattern):
1087 oldend = ctx.go_forward_by_bytes(oldptr, length_bytes)
1088 while oldptr < oldend:
1089 if ptr >= ctx.end:
1090 return -1
1091 if pattern.lowa(ctx.str(ptr)) != pattern.lowa(ctx.str(oldptr)):
1092 return -1
1093 ptr = ctx.next(ptr)
1094 oldptr = ctx.next(oldptr)
1095 return ptr
1096
1097 @specializectx
1098 def match_repeated_uni_ignore(ctx, ptr, oldptr, length_bytes):
1099 oldend = ctx.go_forward_by_bytes(oldptr, length_bytes)
1100 while oldptr < oldend:
1101 if ptr >= ctx.end:
1102 return -1
1103 if rsre_char.getlower_unicode(ctx.str(ptr)) != rsre_char.getlower_unicode(ctx.str(oldptr)):
1104 return -1
1105 ptr = ctx.next(ptr)
1106 oldptr = ctx.next(oldptr)
1107 return ptr
1108
1109 @specializectx
1110 def match_repeated_loc_ignore(ctx, ptr, oldptr, length_bytes):
1111 oldend = ctx.go_forward_by_bytes(oldptr, length_bytes)
1112 while oldptr < oldend:
1113 if ptr >= ctx.end:
1114 return -1
1115 if rsre_char.getlower_locale(ctx.str(ptr)) != rsre_char.getlower_locale(ctx.str(oldptr)):
1116 return -1
1117 ptr = ctx.next(ptr)
1118 oldptr = ctx.next(oldptr)
1119 return ptr
1120
1121 @specializectx
1122 def find_repetition_end(ctx, pattern, ppos, ptr, maxcount, marks):
1123 end = ctx.end
1124 # First get rid of the cases where we don't have room for any match.
1125 if maxcount <= 0 or ptr >= end:
1126 return ptr
1127 ptrp1 = ctx.next(ptr)
1128 # Check the first character directly. If it doesn't match, we are done.
1129 # The idea is to be fast for cases like re.search("b+"), where we expect
1130 # the common case to be a non-match. It's much faster with the JIT to
1131 # have the non-match inlined here rather than detect it in the fre() call.
1132 op = pattern.pat(ppos)
1133 for op1, checkerfn in unroll_char_checker:
1134 if op1 == op:
1135 if checkerfn(ctx, pattern, ptr, ppos):
1136 break
1137 return ptr
1138 else:
1139 # obscure case: it should be a single char pattern, but isn't
1140 # one of the opcodes in unroll_char_checker (see test_ext_opcode)
1141 return general_find_repetition_end(ctx, pattern, ppos, ptr, maxcount, marks)
1142 # It matches at least once. If maxcount == 1 (relatively common),
1143 # then we are done.
1144 if maxcount == 1:
1145 return ptrp1
1146 # Else we really need to count how many times it matches.
1147 if maxcount != rsre_char.MAXREPEAT:
1148 # adjust end
1149 try:
1150 end = ctx.next_n(ptr, maxcount, end)
1151 except EndOfString:
1152 pass
1153 op = pattern.pat(ppos)
1154 for op1, fre in unroll_fre_checker:
1155 if op1 == op:
1156 return fre(ctx, pattern, ptrp1, end, ppos)
1157 raise Error("rsre.find_repetition_end[%d]" % op)
1158
1159 @specializectx
1160 def general_find_repetition_end(ctx, pattern, ppos, ptr, maxcount, marks):
1161 # moved into its own JIT-opaque function
1162 end = ctx.end
1163 if maxcount != rsre_char.MAXREPEAT:
1164 # adjust end
1165 end1 = ptr + maxcount
1166 if end1 <= end:
1167 end = end1
1168 while ptr < end and sre_match(ctx, pattern, ppos, ptr, marks) is not None:
1169 ptr = ctx.next(ptr)
1170 return ptr
1171
1172 @specializectx
1173 def match_ANY(ctx, pattern, ptr, ppos): # dot wildcard.
1174 return not rsre_char.is_linebreak(ctx.str(ptr))
1175 def match_ANY_ALL(ctx, pattern, ptr, ppos):
1176 return True # match anything (including a newline)
1177 @specializectx
1178 def match_IN(ctx, pattern, ptr, ppos):
1179 return rsre_char.check_charset(ctx, pattern, ppos+2, ctx.str(ptr))
1180 @specializectx
1181 def match_IN_IGNORE(ctx, pattern, ptr, ppos):
1182 return rsre_char.check_charset(ctx, pattern, ppos+2, pattern.lowa(ctx.str(ptr)))
1183 @specializectx
1184 def match_IN_UNI_IGNORE(ctx, pattern, ptr, ppos):
1185 return rsre_char.check_charset(ctx, pattern, ppos+2, rsre_char.getlower_unicode(ctx.str(ptr)))
1186 @specializectx
1187 def match_IN_LOC_IGNORE(ctx, pattern, ptr, ppos):
1188 return pattern.charset_loc_ignore(ctx, ppos+2, ctx.str(ptr))
1189 @specializectx
1190 def match_LITERAL(ctx, pattern, ptr, ppos):
1191 return ctx.str(ptr) == pattern.pat(ppos+1)
1192 @specializectx
1193 def match_LITERAL_IGNORE(ctx, pattern, ptr, ppos):
1194 return pattern.lowa(ctx.str(ptr)) == pattern.pat(ppos+1)
1195 @specializectx
1196 def match_LITERAL_UNI_IGNORE(ctx, pattern, ptr, ppos):
1197 return rsre_char.getlower_unicode(ctx.str(ptr)) == pattern.pat(ppos+1)
1198 @specializectx
1199 def match_LITERAL_LOC_IGNORE(ctx, pattern, ptr, ppos):
1200 return pattern.char_loc_ignore(ppos+1, ctx.str(ptr))
1201 @specializectx
1202 def match_NOT_LITERAL(ctx, pattern, ptr, ppos):
1203 return ctx.str(ptr) != pattern.pat(ppos+1)
1204 @specializectx
1205 def match_NOT_LITERAL_IGNORE(ctx, pattern, ptr, ppos):
1206 return pattern.lowa(ctx.str(ptr)) != pattern.pat(ppos+1)
1207 @specializectx
1208 def match_NOT_LITERAL_UNI_IGNORE(ctx, pattern, ptr, ppos):
1209 return rsre_char.getlower_unicode(ctx.str(ptr)) != pattern.pat(ppos+1)
1210 @specializectx
1211 def match_NOT_LITERAL_LOC_IGNORE(ctx, pattern, ptr, ppos):
1212 return not pattern.char_loc_ignore(ppos+1, ctx.str(ptr))
1213
1214 def _make_fre(checkerfn):
1215 if checkerfn == match_ANY_ALL:
1216 def fre(ctx, pattern, ptr, end, ppos):
1217 return end
1218 elif checkerfn in (match_IN, match_IN_IGNORE, match_IN_UNI_IGNORE):
1219 # produces three jitdrivers:
1220 # MatchIn
1221 # MatchInIgnore
1222 # MatchInUniIgnore
1223 name = checkerfn.__name__.title().replace('_', '')
1224 method_name = "jitdriver_" + name
1225 install_jitdriver_spec(name,
1226 greens=['ppos', 'pattern'],
1227 reds=['ptr', 'end', 'ctx'],
1228 debugprint=(1, 0))
1229 @specializectx
1230 def fre(ctx, pattern, ptr, end, ppos):
1231 while True:
1232 getattr(ctx, method_name).jit_merge_point(ctx=ctx, ptr=ptr,
1233 end=end, ppos=ppos,
1234 pattern=pattern)
1235 if ptr < end and checkerfn(ctx, pattern, ptr, ppos):
1236 ptr = ctx.next(ptr)
1237 else:
1238 return ptr
1239 else:
1240 # in the other cases, the fre() function is not JITted at all
1241 # and is present as a residual call.
1242 @specializectx
1243 def fre(ctx, pattern, ptr, end, ppos):
1244 while ptr < end and checkerfn(ctx, pattern, ptr, ppos):
1245 ptr = ctx.next(ptr)
1246 return ptr
1247 fre = func_with_new_name(fre, 'fre_' + checkerfn.__name__)
1248 return fre
1249
1250 unroll_char_checker = [
1251 (consts.OPCODE_ANY, match_ANY),
1252 (consts.OPCODE_ANY_ALL, match_ANY_ALL),
1253 (consts.OPCODE_IN, match_IN),
1254 (consts.OPCODE_IN_IGNORE, match_IN_IGNORE),
1255 (consts.OPCODE37_IN_UNI_IGNORE, match_IN_UNI_IGNORE),
1256 (consts.OPCODE37_IN_LOC_IGNORE, match_IN_LOC_IGNORE),
1257 (consts.OPCODE_LITERAL, match_LITERAL),
1258 (consts.OPCODE_LITERAL_IGNORE, match_LITERAL_IGNORE),
1259 (consts.OPCODE37_LITERAL_UNI_IGNORE, match_LITERAL_UNI_IGNORE),
1260 (consts.OPCODE37_LITERAL_LOC_IGNORE, match_LITERAL_LOC_IGNORE),
1261 (consts.OPCODE_NOT_LITERAL, match_NOT_LITERAL),
1262 (consts.OPCODE_NOT_LITERAL_IGNORE, match_NOT_LITERAL_IGNORE),
1263 (consts.OPCODE37_NOT_LITERAL_UNI_IGNORE, match_NOT_LITERAL_UNI_IGNORE),
1264 (consts.OPCODE37_NOT_LITERAL_LOC_IGNORE, match_NOT_LITERAL_LOC_IGNORE),
1265 ]
1266 unroll_char_checker = [(_op, _fn) for (_op, _fn) in unroll_char_checker
1267 if _op is not None] # possibly removes the OPCODE37_*
1268 unroll_fre_checker = [(_op, _make_fre(_fn))
1269 for (_op, _fn) in unroll_char_checker]
1270
1271 unroll_char_checker = unrolling_iterable(unroll_char_checker)
1272 unroll_fre_checker = unrolling_iterable(unroll_fre_checker)
1273
1274 ##### At dispatch
1275
1276 @specializectx
1277 def sre_at(ctx, atcode, ptr):
1278 if (atcode == consts.AT_BEGINNING or
1279 atcode == consts.AT_BEGINNING_STRING):
1280 return ptr == ctx.ZERO
1281
1282 elif atcode == consts.AT_BEGINNING_LINE:
1283 try:
1284 prevptr = ctx.prev(ptr)
1285 except EndOfString:
1286 return True
1287 return rsre_char.is_linebreak(ctx.str(prevptr))
1288
1289 elif atcode == consts.AT_BOUNDARY:
1290 return at_boundary(ctx, ptr)
1291
1292 elif atcode == consts.AT_NON_BOUNDARY:
1293 return at_non_boundary(ctx, ptr)
1294
1295 elif atcode == consts.AT_END:
1296 return (ptr == ctx.end or
1297 (ctx.next(ptr) == ctx.end and rsre_char.is_linebreak(ctx.str(ptr))))
1298
1299 elif atcode == consts.AT_END_LINE:
1300 return ptr == ctx.end or rsre_char.is_linebreak(ctx.str(ptr))
1301
1302 elif atcode == consts.AT_END_STRING:
1303 return ptr == ctx.end
1304
1305 elif atcode == consts.AT_LOC_BOUNDARY:
1306 return at_loc_boundary(ctx, ptr)
1307
1308 elif atcode == consts.AT_LOC_NON_BOUNDARY:
1309 return at_loc_non_boundary(ctx, ptr)
1310
1311 elif atcode == consts.AT_UNI_BOUNDARY:
1312 return at_uni_boundary(ctx, ptr)
1313
1314 elif atcode == consts.AT_UNI_NON_BOUNDARY:
1315 return at_uni_non_boundary(ctx, ptr)
1316
1317 return False
1318
1319 def _make_boundary(word_checker):
1320 @specializectx
1321 def at_boundary(ctx, ptr):
1322 if ctx.end == ctx.ZERO:
1323 return False
1324 try:
1325 prevptr = ctx.prev(ptr)
1326 except EndOfString:
1327 that = False
1328 else:
1329 that = word_checker(ctx.str(prevptr))
1330 this = ptr < ctx.end and word_checker(ctx.str(ptr))
1331 return this != that
1332 @specializectx
1333 def at_non_boundary(ctx, ptr):
1334 if ctx.end == ctx.ZERO:
1335 return False
1336 try:
1337 prevptr = ctx.prev(ptr)
1338 except EndOfString:
1339 that = False
1340 else:
1341 that = word_checker(ctx.str(prevptr))
1342 this = ptr < ctx.end and word_checker(ctx.str(ptr))
1343 return this == that
1344 return at_boundary, at_non_boundary
1345
1346 at_boundary, at_non_boundary = _make_boundary(rsre_char.is_word)
1347 at_loc_boundary, at_loc_non_boundary = _make_boundary(rsre_char.is_loc_word)
1348 at_uni_boundary, at_uni_non_boundary = _make_boundary(rsre_char.is_uni_word)
1349
1350 # ____________________________________________________________
1351
1352 def _adjust(start, end, length):
1353 if start < 0: start = 0
1354 elif start > length: start = length
1355 if end < 0: end = 0
1356 elif end > length: end = length
1357 return start, end
1358
1359 def match(pattern, string, start=0, end=sys.maxint, fullmatch=False):
1360 assert isinstance(pattern, CompiledPattern)
1361 start, end = _adjust(start, end, len(string))
1362 ctx = StrMatchContext(string, start, end)
1363 if fullmatch:
1364 ctx.match_mode = MODE_FULL
1365 if match_context(ctx, pattern):
1366 return ctx
1367 else:
1368 return None
1369
1370 def fullmatch(pattern, string, start=0, end=sys.maxint):
1371 return match(pattern, string, start, end, fullmatch=True)
1372
1373 def search(pattern, string, start=0, end=sys.maxint):
1374 assert isinstance(pattern, CompiledPattern)
1375 start, end = _adjust(start, end, len(string))
1376 ctx = StrMatchContext(string, start, end)
1377 if search_context(ctx, pattern):
1378 return ctx
1379 else:
1380 return None
1381
1382 install_jitdriver('Match',
1383 greens=['pattern'], reds=['ctx'],
1384 debugprint=(0,))
1385
1386 def match_context(ctx, pattern):
1387 ctx.original_pos = ctx.match_start
1388 if ctx.end < ctx.match_start:
1389 return False
1390 ctx.jitdriver_Match.jit_merge_point(ctx=ctx, pattern=pattern)
1391 return sre_match(ctx, pattern, 0, ctx.match_start, None) is not None
1392
1393 def search_context(ctx, pattern):
1394 ctx.original_pos = ctx.match_start
1395 if ctx.end < ctx.match_start:
1396 return False
1397 base = 0
1398 charset = False
1399 if pattern.pat(base) == consts.OPCODE_INFO:
1400 flags = pattern.pat(2)
1401 if flags & consts.SRE_INFO_PREFIX:
1402 if pattern.pat(5) > 1:
1403 return fast_search(ctx, pattern)
1404 else:
1405 charset = (flags & consts.SRE_INFO_CHARSET)
1406 base += 1 + pattern.pat(1)
1407 if pattern.pat(base) == consts.OPCODE_LITERAL:
1408 return literal_search(ctx, pattern, base)
1409 if charset:
1410 return charset_search(ctx, pattern, base)
1411 return regular_search(ctx, pattern, base)
1412
1413 install_jitdriver('RegularSearch',
1414 greens=['base', 'pattern'],
1415 reds=['start', 'ctx'],
1416 debugprint=(1, 0))
1417
1418 def regular_search(ctx, pattern, base):
1419 start = ctx.match_start
1420 while True:
1421 ctx.jitdriver_RegularSearch.jit_merge_point(ctx=ctx, pattern=pattern,
1422 start=start, base=base)
1423 if sre_match(ctx, pattern, base, start, None) is not None:
1424 ctx.match_start = start
1425 return True
1426 if start >= ctx.end:
1427 break
1428 start = ctx.next_indirect(start)
1429 return False
1430
1431 install_jitdriver_spec("LiteralSearch",
1432 greens=['base', 'character', 'pattern'],
1433 reds=['start', 'ctx'],
1434 debugprint=(2, 0, 1))
1435 @specializectx
1436 def literal_search(ctx, pattern, base):
1437 # pattern starts with a literal character. this is used
1438 # for short prefixes, and if fast search is disabled
1439 character = pattern.pat(base + 1)
1440 base += 2
1441 start = ctx.match_start
1442 while start < ctx.end:
1443 ctx.jitdriver_LiteralSearch.jit_merge_point(ctx=ctx, start=start,
1444 base=base, character=character, pattern=pattern)
1445 start1 = ctx.next(start)
1446 if ctx.str(start) == character:
1447 if sre_match(ctx, pattern, base, start1, None) is not None:
1448 ctx.match_start = start
1449 return True
1450 start = start1
1451 return False
1452
1453 install_jitdriver_spec("CharsetSearch",
1454 greens=['base', 'pattern'],
1455 reds=['start', 'ctx'],
1456 debugprint=(1, 0))
1457 @specializectx
1458 def charset_search(ctx, pattern, base):
1459 # pattern starts with a character from a known set
1460 start = ctx.match_start
1461 while start < ctx.end:
1462 ctx.jitdriver_CharsetSearch.jit_merge_point(ctx=ctx, start=start,
1463 base=base, pattern=pattern)
1464 if rsre_char.check_charset(ctx, pattern, 5, ctx.str(start)):
1465 if sre_match(ctx, pattern, base, start, None) is not None:
1466 ctx.match_start = start
1467 return True
1468 start = ctx.next(start)
1469 return False
1470
1471 install_jitdriver_spec('FastSearch',
1472 greens=['i', 'prefix_len', 'pattern'],
1473 reds=['string_position', 'ctx'],
1474 debugprint=(2, 0))
1475 @specializectx
1476 def fast_search(ctx, pattern):
1477 # skips forward in a string as fast as possible using information from
1478 # an optimization info block
1479 # <INFO> <1=skip> <2=flags> <3=min> <4=...>
1480 # <5=length> <6=skip> <7=prefix data> <overlap data>
1481 string_position = ctx.match_start
1482 if string_position >= ctx.end:
1483 return False
1484 prefix_len = pattern.pat(5)
1485 assert prefix_len >= 0
1486 i = 0
1487 while True:
1488 ctx.jitdriver_FastSearch.jit_merge_point(ctx=ctx,
1489 string_position=string_position, i=i, prefix_len=prefix_len,
1490 pattern=pattern)
1491 char_ord = ctx.str(string_position)
1492 if char_ord != pattern.pat(7 + i):
1493 if i > 0:
1494 overlap_offset = prefix_len + (7 - 1)
1495 i = pattern.pat(overlap_offset + i)
1496 continue
1497 else:
1498 i += 1
1499 if i == prefix_len:
1500 # start = string_position + 1 - prefix_len: computed later
1501 ptr = string_position
1502 prefix_skip = pattern.pat(6)
1503 if prefix_skip == prefix_len:
1504 ptr = ctx.next(ptr)
1505 else:
1506 assert prefix_skip < prefix_len
1507 ptr = ctx.prev_n(ptr, prefix_len-1 - prefix_skip, ctx.ZERO)
1508 #flags = pattern.pat(2)
1509 #if flags & rsre_char.SRE_INFO_LITERAL:
1510 # # matched all of pure literal pattern
1511 # ctx.match_start = start
1512 # ctx.match_end = ptr
1513 # ctx.match_marks = None
1514 # return True
1515 pattern_offset = pattern.pat(1) + 1
1516 ppos_start = pattern_offset + 2 * prefix_skip
1517 if sre_match(ctx, pattern, ppos_start, ptr, None) is not None:
1518 start = ctx.prev_n(ptr, prefix_skip, ctx.ZERO)
1519 ctx.match_start = start
1520 return True
1521 overlap_offset = prefix_len + (7 - 1)
1522 i = pattern.pat(overlap_offset + i)
1523 string_position = ctx.next(string_position)
1524 if string_position >= ctx.end:
1525 return False