Debian Codegraph @

pypy/module/_sre/interp_sre.py

raw symbols SCIP
1 import sys
2 from pypy.interpreter.baseobjspace import W_Root
3 from pypy.interpreter.typedef import GetSetProperty, TypeDef
4 from pypy.interpreter.typedef import interp_attrproperty, interp_attrproperty_w
5 from pypy.interpreter.typedef import make_weakref_descr
6 from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault
7 from pypy.interpreter.error import OperationError, oefmt
8 from pypy.objspace.std.util import generic_alias_class_getitem
9 from rpython.rlib.objectmodel import compute_hash
10 from rpython.rlib.rarithmetic import intmask, int_between
11 from rpython.rlib import jit, rutf8
12 from rpython.rlib.rstring import StringBuilder
13
14 # ____________________________________________________________
15 #
16 # Constants and exposed functions
17
18 from rpython.rlib.rsre import rsre_core, rsre_char, rsre_utf8, rsre_constants as consts
19 from rpython.rlib.rsre.rsre_char import CODESIZE, MAXREPEAT, MAXGROUPS, set_unicode_db
20
21 from rpython.rlib.rsre.rpy.sre_constants import OPCODES
22
23 ORDERED_OPCODE_NAMES = [name for name, value in sorted(OPCODES.items(), key=lambda element: element[1])]
24
25
26 @unwrap_spec(character=int)
27 def w_ascii_iscased(space, character):
28 return space.newbool(rsre_char.iscased_ascii(character))
29
30 @unwrap_spec(character=int)
31 def w_unicode_iscased(space, character):
32 return space.newbool(rsre_char.iscased_unicode(character))
33
34 @unwrap_spec(character=int)
35 def w_ascii_tolower(space, character):
36 return space.newint(rsre_char.getlower_ascii(character))
37
38 @unwrap_spec(character=int)
39 def w_unicode_tolower(space, character):
40 return space.newint(rsre_char.getlower_unicode(character))
41
42 def w_getcodesize(space):
43 return space.newint(CODESIZE)
44
45 # use the same version of unicodedb as the standard objspace
46 import pypy.objspace.std.unicodeobject
47 set_unicode_db(pypy.objspace.std.unicodeobject.unicodedb)
48
49 # ____________________________________________________________
50 #
51
52 class UnicodeAsciiMatchContext(rsre_core.StrMatchContext):
53 # we make a subclass just to mark that it originates from a W_UnicodeObject
54 pass
55
56
57 def slice_w(space, ctx, start, end, w_default):
58 # 'start' and 'end' are byte positions
59 if ctx.ZERO <= start <= end:
60 if isinstance(ctx, rsre_core.BufMatchContext):
61 length = ctx._buffer.getlength()
62 start = min(start, length)
63 end = min(end, length)
64 return space.newbytes(ctx._buffer.getslice(start, 1,
65 end-start))
66 elif isinstance(ctx, UnicodeAsciiMatchContext):
67 s = ctx._string[start:end]
68 return space.newutf8(s, len(s))
69 elif isinstance(ctx, rsre_core.StrMatchContext):
70 start = ctx._real_pos(start)
71 end = ctx._real_pos(end)
72 return space.newbytes(ctx._string[start:end])
73 elif isinstance(ctx, rsre_utf8.Utf8MatchContext):
74 s = ctx._utf8[start:end]
75 lgt = rutf8.codepoints_in_utf8(s)
76 return space.newutf8(s, lgt)
77 else:
78 # unreachable
79 raise SystemError
80 return w_default
81
82
83 @jit.look_inside_iff(lambda ctx, num_groups: jit.isconstant(num_groups))
84 def do_flatten_marks(ctx, num_groups):
85 # Returns a list of RPython-level integers.
86 # Unlike the app-level groups() method, groups are numbered from 0
87 # and the returned list does not start with the whole match range.
88 # The integers are byte positions, not character indexes (for utf8).
89 if num_groups == 0:
90 return None
91 result = [-1] * (2 * num_groups)
92 mark = ctx.match_marks
93 while mark is not None:
94 index = jit.promote(mark.gid)
95 if result[index] == -1:
96 result[index] = mark.position
97 mark = mark.prev
98 return result
99
100
101 @jit.look_inside_iff(lambda space, ctx, fmarks, num_groups, w_default: jit.isconstant(num_groups))
102 def allgroups_w(space, ctx, fmarks, num_groups, w_default):
103 grps = [slice_w(space, ctx, fmarks[i * 2], fmarks[i * 2 + 1], w_default)
104 for i in range(num_groups)]
105 return space.newtuple(grps)
106
107
108 def import_re(space):
109 return space.fromcache(AppReCache).get_re()
110
111 def matchcontext(space, ctx, pattern):
112 try:
113 return rsre_core.match_context(ctx, pattern)
114 except rsre_core.Error as e:
115 raise OperationError(space.w_RuntimeError, space.newtext(e.msg))
116
117 def searchcontext(space, ctx, pattern):
118 try:
119 return rsre_core.search_context(ctx, pattern)
120 except rsre_core.Error as e:
121 raise OperationError(space.w_RuntimeError, space.newtext(e.msg))
122
123 # ____________________________________________________________
124 #
125 # SRE_Pattern class
126
127 FLAG_NAMES = ["re.TEMPLATE", "re.IGNORECASE", "re.LOCALE", "re.MULTILINE",
128 "re.DOTALL", "re.UNICODE", "re.VERBOSE", "re.DEBUG",
129 "re.ASCII"]
130
131
132 class AppReCache(object):
133 def __init__(self, space):
134 self.space = space
135 self.w_re = None
136
137 def get_re(self):
138 if self.w_re is not None:
139 return self.w_re
140 space = self.space
141 w_import = space.getattr(space.builtin, space.newtext("__import__"))
142 w_re = space.call_function(w_import, space.newtext("re"))
143 self.w_re = w_re
144 return w_re
145
146
147 class W_SRE_Pattern(W_Root):
148 _immutable_fields_ = ["code", "flags", "num_groups", "w_groupindex"]
149
150 def copy_identity_w(self, args_w):
151 return self
152
153 def repr_w(self):
154 space = self.space
155 w_s = space.repr(self.w_pattern)
156 w_s = space.getslice(w_s, space.newint(0), space.newint(200))
157 u = space.utf8_w(w_s)
158 flag_items = []
159 flags = self.flags
160 if self.is_known_unicode():
161 if ((flags & (consts.SRE_FLAG_LOCALE |
162 consts.SRE_FLAG_UNICODE |
163 256)) # consts.SRE_FLAG_ASCII
164 == consts.SRE_FLAG_UNICODE):
165 flags &= ~consts.SRE_FLAG_UNICODE
166 for i, name in enumerate(FLAG_NAMES):
167 if flags & (1 << i):
168 flags -= (1 << i)
169 flag_items.append(name)
170 if flags != 0:
171 flag_items.append('0x%x' % flags)
172 if len(flag_items) == 0:
173 usep = ''
174 uflags = ''
175 else:
176 usep = ', '
177 uflags = '|'.join(flag_items)
178 return space.newtext('re.compile(%s%s%s)' % (u, usep, uflags))
179
180 def descr_eq(self, space, w_other):
181 if not isinstance(w_other, W_SRE_Pattern):
182 return space.w_NotImplemented
183 other = w_other
184 # Compare the code and the pattern because the same pattern can
185 # produce different codes depending on the locale used to compile the
186 # pattern when the re.LOCALE flag is used. Don't compare groups,
187 # indexgroup nor groupindex: they are derivated from the pattern.
188 return space.newbool(
189 self.flags == other.flags and
190 self.code.pattern == other.code.pattern and
191 space.eq_w(self.w_pattern, other.w_pattern))
192
193 def descr_hash(self, space):
194 from rpython.rlib.rarithmetic import intmask
195 x = 0x345678
196 for c in self.code.pattern:
197 x = intmask((1000003 * x) ^ c)
198 x = intmask((1000003 * x) ^ self.flags)
199 x = intmask((1000003 * x) ^ space.hash_w(self.w_pattern))
200 return space.newint(x)
201
202 def fget_groupindex(self, space):
203 w_groupindex = self.w_groupindex
204 if space.isinstance_w(w_groupindex, space.w_dict):
205 w_groupindex = space.newdictproxy(w_groupindex)
206 return w_groupindex
207
208 def is_known_bytes(self):
209 space = self.space
210 if space.is_none(self.w_pattern):
211 return False
212 return not space.isinstance_w(self.w_pattern, space.w_unicode)
213
214 def is_known_unicode(self):
215 space = self.space
216 if space.is_none(self.w_pattern):
217 return False
218 return space.isinstance_w(self.w_pattern, space.w_unicode)
219
220 def make_ctx(self, w_string, pos=0, endpos=sys.maxint):
221 """Make a StrMatchContext, BufMatchContext or a Utf8MatchContext for
222 searching in the given w_string object."""
223 space = self.space
224 if pos < 0:
225 pos = 0
226 if endpos < pos:
227 endpos = pos
228 if space.isinstance_w(w_string, space.w_unicode):
229 if self.is_known_bytes():
230 raise oefmt(space.w_TypeError,
231 "can't use a bytes pattern on a string-like "
232 "object")
233 w_unicode_obj = space.convert_arg_to_w_unicode(w_string)
234 utf8str = w_unicode_obj._utf8
235 length = w_unicode_obj._len()
236 if pos <= 0:
237 bytepos = 0
238 elif pos >= length:
239 bytepos = len(utf8str)
240 else:
241 bytepos = w_unicode_obj._index_to_byte(pos)
242 if endpos >= length:
243 endbytepos = len(utf8str)
244 else:
245 endbytepos = w_unicode_obj._index_to_byte(endpos)
246 if w_unicode_obj.is_ascii():
247 ctx = UnicodeAsciiMatchContext(
248 utf8str, bytepos, endbytepos)
249 else:
250 ctx = rsre_utf8.Utf8MatchContext(
251 utf8str, bytepos, endbytepos)
252 # we store the w_string on the ctx too, for
253 # W_SRE_Match.bytepos_to_charindex()
254 ctx.w_unicode_obj = w_unicode_obj
255 return ctx
256 elif self.is_known_unicode():
257 if not space.isinstance_w(w_string, space.w_bytes):
258 try:
259 space.readbuf_w(w_string)
260 except OperationError as e:
261 if not e.match(space, space.w_TypeError):
262 raise
263 raise oefmt(space.w_TypeError,
264 "expected string or bytes-like object, "
265 "got '%T'", w_string)
266 raise oefmt(space.w_TypeError,
267 "can't use a string pattern on a bytes-like "
268 "object")
269 elif space.isinstance_w(w_string, space.w_bytes):
270 string = space.bytes_w(w_string)
271 length = len(string)
272 if pos > length:
273 pos = length
274 if endpos > length:
275 endpos = length
276 return rsre_core.StrMatchContext(string, pos, endpos)
277 else:
278 buf = space.readbuf_w(w_string)
279 size = buf.getlength()
280 assert size >= 0
281 if pos > size:
282 pos = size
283 if endpos > size:
284 endpos = size
285 return rsre_core.BufMatchContext(buf, pos, endpos)
286
287 def fresh_copy(self, ctx):
288 if isinstance(ctx, rsre_utf8.Utf8MatchContext):
289 result = rsre_utf8.Utf8MatchContext(
290 ctx._utf8, ctx.match_start, ctx.end)
291 result.w_unicode_obj = ctx.w_unicode_obj
292 elif isinstance(ctx, UnicodeAsciiMatchContext):
293 result = UnicodeAsciiMatchContext(
294 ctx._string, ctx.match_start, ctx.end)
295 elif isinstance(ctx, rsre_core.StrMatchContext):
296 result = self._make_str_match_context(
297 ctx._string, ctx.match_start, ctx.end)
298 elif isinstance(ctx, rsre_core.BufMatchContext):
299 result = rsre_core.BufMatchContext(
300 ctx._buffer, ctx.match_start, ctx.end)
301 else:
302 raise AssertionError("bad ctx type")
303 result.match_end = ctx.match_end
304 return result
305
306 def _make_str_match_context(self, str, pos, endpos):
307 # for tests to override
308 return rsre_core.StrMatchContext(str,
309 pos, endpos)
310
311 def getmatch(self, ctx, found, w_string):
312 if found:
313 return W_SRE_Match(self, ctx, w_string)
314 else:
315 return self.space.w_None
316
317 @unwrap_spec(pos=int, endpos=int)
318 def match_w(self, w_string, pos=0, endpos=sys.maxint):
319 """Matches zero or more characters at the beginning of the string."""
320 ctx = self.make_ctx(w_string, pos, endpos)
321 return self.getmatch(ctx, matchcontext(self.space, ctx, self.code), w_string)
322
323 @unwrap_spec(pos=int, endpos=int)
324 def fullmatch_w(self, w_string, pos=0, endpos=sys.maxint):
325 """Matches against all of the string."""
326 ctx = self.make_ctx(w_string, pos, endpos)
327 ctx.match_mode = rsre_core.MODE_FULL
328 return self.getmatch(ctx, matchcontext(self.space, ctx, self.code), w_string)
329
330 @unwrap_spec(pos=int, endpos=int)
331 def search_w(self, w_string, pos=0, endpos=sys.maxint):
332 """Scan through string looking for a match, and return a corresponding match object instance.
333
334 Return None if no position in the string matches."""
335 ctx = self.make_ctx(w_string, pos, endpos)
336 return self.getmatch(ctx, searchcontext(self.space, ctx, self.code), w_string)
337
338 @unwrap_spec(pos=int, endpos=int)
339 def findall_w(self, w_string, pos=0, endpos=sys.maxint):
340 """Return a list of all non-overlapping matches of pattern in string."""
341 space = self.space
342 matchlist_w = []
343 ctx = self.make_ctx(w_string, pos, endpos)
344 if space.isinstance_w(w_string, space.w_unicode):
345 w_emptystr = space.newutf8('', 0)
346 else:
347 w_emptystr = space.newbytes('')
348 while True:
349 if not searchcontext(space, ctx, self.code):
350 break
351 num_groups = self.num_groups
352 if num_groups == 0:
353 w_item = slice_w(space, ctx, ctx.match_start, ctx.match_end,
354 w_emptystr)
355 else:
356 fmarks = do_flatten_marks(ctx, num_groups)
357 if num_groups == 1:
358 w_item = slice_w(space, ctx, fmarks[0], fmarks[1],
359 w_emptystr)
360 else:
361 w_item = allgroups_w(space, ctx, fmarks, num_groups,
362 w_emptystr)
363 matchlist_w.append(w_item)
364 ctx.reset(ctx.match_end, ctx.match_start == ctx.match_end)
365 return space.newlist(matchlist_w)
366
367 @unwrap_spec(pos=int, endpos=int)
368 def finditer_w(self, w_string, pos=0, endpos=sys.maxint):
369 """Return an iterator over all non-overlapping matches for the RE pattern in string.
370
371 For each match, the iterator returns a match object."""
372 # this also works as the implementation of the undocumented
373 # scanner() method.
374 ctx = self.make_ctx(w_string, pos, endpos)
375 scanner = W_SRE_Scanner(self, ctx, self.code, w_string)
376 return scanner
377
378 @unwrap_spec(maxsplit=int)
379 def split_w(self, w_string, maxsplit=0):
380 """Split string by the occurrences of pattern."""
381 space = self.space
382 #
383 splitlist = []
384 n = 0
385 ctx = self.make_ctx(w_string)
386 last = ctx.ZERO
387 while not maxsplit or n < maxsplit:
388 pattern = self.code
389 num_groups = self.num_groups
390 split_jitdriver.jit_merge_point(
391 pattern=pattern, num_groups=num_groups, ctx_type=type(ctx))
392 if not searchcontext(space, ctx, pattern):
393 break
394 splitlist.append(slice_w(space, ctx, last, ctx.match_start,
395 space.w_None))
396 # add groups (if any)
397 fmarks = do_flatten_marks(ctx, num_groups)
398 for groupnum in range(num_groups):
399 groupstart, groupend = fmarks[groupnum*2], fmarks[groupnum*2+1]
400 splitlist.append(slice_w(space, ctx, groupstart, groupend,
401 space.w_None))
402 n += 1
403 last = ctx.match_end
404 ctx.reset(last, ctx.match_start == last)
405 splitlist.append(slice_w(space, ctx, last, ctx.end, space.w_None))
406 return space.newlist(splitlist)
407
408 @unwrap_spec(count=int)
409 def sub_w(self, w_repl, w_string, count=0):
410 """Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl."""
411 w_item, n = self.subx(w_repl, w_string, count)
412 return w_item
413
414 @unwrap_spec(count=int)
415 def subn_w(self, w_repl, w_string, count=0):
416 """Return the tuple (new_string, number_of_subs_made) found by replacing the leftmost non-overlapping occurrences of pattern with the replacement repl."""
417 w_item, n = self.subx(w_repl, w_string, count)
418 space = self.space
419 return space.newtuple2(w_item, space.newint(n))
420
421 def subx(self, w_ptemplate, w_string, count):
422 space = self.space
423 # use a (much faster) string builder (possibly utf8) if w_ptemplate and
424 # w_string are both string or both unicode objects, and if w_ptemplate
425 # is a literal
426 use_builder = '\x00' # or 'S'tring or 'U'nicode/UTF8
427 is_buffer = False
428 filter_as_string = None
429 if space.isinstance_w(w_string, space.w_unicode):
430 if not self.is_known_unicode():
431 raise oefmt(space.w_TypeError,
432 "cannot use a bytes pattern on a string-like object")
433 else:
434 if self.is_known_unicode():
435 raise oefmt(space.w_TypeError,
436 "cannot use a string pattern on a bytes-like object")
437 if space.is_true(space.callable(w_ptemplate)):
438 w_filter = w_ptemplate
439 filter_is_callable = True
440 else:
441 if space.isinstance_w(w_ptemplate, space.w_unicode):
442 filter_as_string = space.utf8_w(w_ptemplate)
443 literal = '\\' not in filter_as_string
444 if space.isinstance_w(w_string, space.w_unicode) and literal:
445 use_builder = 'U'
446 elif space.isinstance_w(w_ptemplate, space.w_bytes):
447 filter_as_string = space.bytes_w(w_ptemplate)
448 literal = '\\' not in filter_as_string
449 if space.isinstance_w(w_string, space.w_bytes) and literal:
450 use_builder = 'S'
451 else:
452 if space.isinstance_w(w_ptemplate, space.w_bytes):
453 filter_as_string = space.bytes_w(w_ptemplate)
454 else:
455 filter_as_string = space.readbuf_w(w_ptemplate).as_str()
456 is_buffer = True
457 literal = '\\' not in filter_as_string
458 if space.isinstance_w(w_string, space.w_bytes) and literal:
459 use_builder = 'S'
460 if literal:
461 w_filter = w_ptemplate
462 filter_is_callable = False
463 else:
464 # not a literal; hand it over to the template compiler
465 # FIX for a CPython 3.5 bug: if w_ptemplate is a buffer
466 # (e.g. a bytearray), convert it to a byte string here.
467 if is_buffer:
468 w_ptemplate = space.newbytes(filter_as_string)
469 w_re = import_re(space)
470 w_filter = space.call_method(w_re, '_subx',
471 self, w_ptemplate)
472 filter_is_callable = space.is_true(space.callable(w_filter))
473 #
474 ctx = self.make_ctx(w_string)
475 ctx_end = ctx.end
476 pattern = self.code
477
478 # shortcut if the pattern doesn't occur at all (relatively common, eg
479 # when escaping things)
480 if not searchcontext(space, ctx, pattern):
481 w_typ = space.type(w_string)
482 if w_typ is not space.w_unicode and w_typ is not space.w_bytes:
483 w_string = slice_w(space, ctx, ctx.ZERO, ctx_end, space.w_None)
484 return w_string, 0
485
486 # XXX this is a bit of a mess, but it improves performance a lot
487 sublist_w = strbuilder = None
488 if use_builder != '\x00':
489 assert filter_as_string is not None
490 strbuilder = StringBuilder(ctx_end)
491 else:
492 sublist_w = []
493 n = 0
494 last_pos = ctx.ZERO
495 while not count or n < count:
496 # on entering this loop for the first time, we have already
497 # performed one match above
498 space = self.space
499 if last_pos < ctx.match_start:
500 _sub_append_slice(
501 ctx, space, use_builder, sublist_w,
502 strbuilder, last_pos, ctx.match_start)
503 if 1: # keeps the following block indented
504 last_pos = ctx.match_end
505 if filter_is_callable:
506 w_match = self.getmatch(ctx, True, w_string)
507 # make a copy of 'ctx'; see test_sub_matches_stay_valid
508 ctx = self.fresh_copy(ctx)
509 w_piece = space.call_function(w_filter, w_match)
510 if not space.is_w(w_piece, space.w_None):
511 assert strbuilder is None
512 assert use_builder == '\x00'
513 sublist_w.append(w_piece)
514 else:
515 if use_builder != '\x00':
516 assert filter_as_string is not None
517 assert strbuilder is not None
518 strbuilder.append(filter_as_string)
519 else:
520 sublist_w.append(w_filter)
521 n += 1
522
523 start = ctx.match_end
524 ctx.reset(start, ctx.match_start == start)
525
526 sub_jitdriver.jit_merge_point(
527 use_builder=use_builder,
528 filter_is_callable=filter_is_callable,
529 filter_type=type(w_filter),
530 pattern=pattern,
531 )
532 if not searchcontext(space, ctx, pattern):
533 break
534
535 if last_pos < ctx.end:
536 _sub_append_slice(ctx, space, use_builder, sublist_w,
537 strbuilder, last_pos, ctx.end)
538 if use_builder != '\x00':
539 assert strbuilder is not None
540 result_bytes = strbuilder.build()
541 if use_builder == 'S':
542 assert not isinstance(ctx, rsre_utf8.Utf8MatchContext)
543 return space.newbytes(result_bytes), n
544 elif use_builder == 'U':
545 assert (isinstance(ctx, UnicodeAsciiMatchContext) or
546 isinstance(ctx, rsre_utf8.Utf8MatchContext))
547 return space.newutf8(result_bytes,
548 rutf8.codepoints_in_utf8(result_bytes)), n
549 else:
550 raise AssertionError(use_builder)
551 else:
552 if space.isinstance_w(w_string, space.w_unicode):
553 w_emptystr = space.newutf8('', 0)
554 else:
555 w_emptystr = space.newbytes('')
556 w_item = space.call_method(w_emptystr, 'join',
557 space.newlist(sublist_w))
558 return w_item, n
559
560 def sub_get_printable_location(filter_is_callable, use_builder, filter_type, pattern):
561 s = str(pattern.pattern)
562 if len(s) > 120:
563 s = s[:110] + '...'
564 if use_builder == '\x00':
565 use_builder = 'list'
566 else:
567 use_builder = "%sBuilder" % use_builder
568
569 return "re.sub %s %s %s %s" % (s, filter_is_callable, use_builder, filter_type)
570
571 sub_jitdriver = jit.JitDriver(
572 reds="auto",
573 greens=["filter_is_callable", "use_builder", "filter_type", "pattern"],
574 get_printable_location=sub_get_printable_location,
575 )
576
577
578 def split_get_printable_location(num_groups, ctx_type, pattern):
579 s = str(pattern.pattern)
580 if len(s) > 120:
581 s = s[:110] + '...'
582
583 return "re.split %s %s %s" % (s, num_groups, ctx_type)
584
585 split_jitdriver = jit.JitDriver(
586 reds="auto",
587 greens=["num_groups", "ctx_type", "pattern"],
588 get_printable_location=split_get_printable_location,
589 )
590
591 def _sub_append_slice(ctx, space, use_builder, sublist_w,
592 strbuilder, start, end):
593 if use_builder != '\x00':
594 assert strbuilder is not None
595 if isinstance(ctx, rsre_core.BufMatchContext):
596 assert use_builder == 'S'
597 return strbuilder.append(ctx._buffer.getslice(start, 1, end-start))
598 if isinstance(ctx, UnicodeAsciiMatchContext):
599 assert use_builder == 'U'
600 return strbuilder.append_slice(ctx._string, start, end)
601 if isinstance(ctx, rsre_core.StrMatchContext):
602 assert use_builder == 'S'
603 start = ctx._real_pos(start)
604 end = ctx._real_pos(end)
605 return strbuilder.append_slice(ctx._string, start, end)
606 if isinstance(ctx, rsre_utf8.Utf8MatchContext):
607 assert use_builder == 'U'
608 return strbuilder.append_slice(ctx._utf8, start, end)
609 assert 0, "unreachable"
610 else:
611 sublist_w.append(slice_w(space, ctx, start, end, space.w_None))
612
613 @unwrap_spec(flags=int, groups=int, w_groupindex=WrappedDefault(None),
614 w_indexgroup=WrappedDefault(None))
615 def SRE_Pattern__new__(space, w_subtype, w_pattern, flags, w_code,
616 groups=0, w_groupindex=None, w_indexgroup=None):
617 n = space.len_w(w_code)
618 code = [intmask(space.uint_w(space.getitem(w_code, space.newint(i))))
619 for i in range(n)]
620 #
621 w_srepat = space.allocate_instance(W_SRE_Pattern, w_subtype)
622 srepat = space.interp_w(W_SRE_Pattern, w_srepat)
623 srepat.space = space
624 # Type check
625 if not (space.is_none(w_pattern) or
626 space.isinstance_w(w_pattern, space.w_unicode)):
627 space.readbuf_w(w_pattern)
628 srepat.w_pattern = w_pattern # the original uncompiled pattern
629 srepat.flags = flags
630 # note: we assume that the app-level is caching SRE_Pattern objects,
631 # so that we don't need to do it here. Creating new SRE_Pattern
632 # objects all the time would be bad for the JIT, which relies on the
633 # identity of the CompiledPattern() object.
634 srepat.code = rsre_core.CompiledPattern(code, flags)
635 srepat.num_groups = groups
636 srepat.w_groupindex = w_groupindex
637 srepat.w_indexgroup = w_indexgroup
638 return w_srepat
639
640
641 W_SRE_Pattern.typedef = TypeDef(
642 're.Pattern',
643 __doc__ = "Compiled regular expression object.",
644 __new__ = interp2app(SRE_Pattern__new__),
645 __copy__ = interp2app(W_SRE_Pattern.copy_identity_w),
646 __deepcopy__ = interp2app(W_SRE_Pattern.copy_identity_w),
647 __repr__ = interp2app(W_SRE_Pattern.repr_w),
648 __weakref__ = make_weakref_descr(W_SRE_Pattern),
649 __eq__ = interp2app(W_SRE_Pattern.descr_eq),
650 __hash__ = interp2app(W_SRE_Pattern.descr_hash),
651 findall = interp2app(W_SRE_Pattern.findall_w),
652 finditer = interp2app(W_SRE_Pattern.finditer_w),
653 match = interp2app(W_SRE_Pattern.match_w),
654 fullmatch = interp2app(W_SRE_Pattern.fullmatch_w),
655 scanner = interp2app(W_SRE_Pattern.finditer_w), # reuse finditer()
656 search = interp2app(W_SRE_Pattern.search_w),
657 split = interp2app(W_SRE_Pattern.split_w),
658 sub = interp2app(W_SRE_Pattern.sub_w),
659 subn = interp2app(W_SRE_Pattern.subn_w),
660 flags = interp_attrproperty('flags', W_SRE_Pattern,
661 wrapfn="newint"),
662 groupindex = GetSetProperty(W_SRE_Pattern.fget_groupindex),
663 groups = interp_attrproperty('num_groups', W_SRE_Pattern,
664 wrapfn="newint"),
665 pattern = interp_attrproperty_w('w_pattern', W_SRE_Pattern),
666 __class_getitem__ = interp2app(
667 generic_alias_class_getitem, as_classmethod=True),
668 )
669 W_SRE_Pattern.typedef.acceptable_as_base_class = False
670
671 # ____________________________________________________________
672 #
673 # SRE_Match class
674
675 class W_SRE_Match(W_Root):
676 flatten_cache = None
677
678 def __init__(self, srepat, ctx, w_string):
679 self.space = srepat.space
680 self.srepat = srepat
681 self.ctx = ctx
682 self.w_string = w_string
683
684 def repr_w(self):
685 space = self.space
686 ctx = self.ctx
687 start, end = ctx.match_start, ctx.match_end
688 w_s = slice_w(space, ctx, start, end, space.w_None)
689 # follow the same logic as CPython, repr'ing the whole match
690 # before deciding to throw away everything beyond the 50th unichar
691 # (which will leave the opening quote unbalanced, and might be
692 # cutting in the middle of a '\' escape)
693 w_s = space.repr(w_s)
694 w_s = space.getslice(w_s, space.newint(0), space.newint(50))
695 u = space.utf8_w(w_s)
696 start = self.bytepos_to_charindex(start)
697 end = self.bytepos_to_charindex(end)
698 return space.newtext('<re.Match object; span=(%d, %d), match=%s>' %
699 (start, end, u))
700
701 def copy_identity_w(self, args_w):
702 return self
703
704 def descr_getitem(self, space, w_index):
705 start, end = self.do_span(w_index)
706 return slice_w(space, self.ctx, start, end, space.w_None)
707
708 @jit.look_inside_iff(lambda self, args_w: jit.isconstant(len(args_w)))
709 def group_w(self, args_w):
710 """group([group1, ...]) -> str or tuple.
711 Return subgroup(s) of the match by indices or names.
712 For 0 returns the entire match."""
713 space = self.space
714 ctx = self.ctx
715 if len(args_w) <= 1:
716 if len(args_w) == 0:
717 start, end = ctx.match_start, ctx.match_end
718 else:
719 start, end = self.do_span(args_w[0])
720 return slice_w(space, ctx, start, end, space.w_None)
721 else:
722 results = [None] * len(args_w)
723 for i in range(len(args_w)):
724 start, end = self.do_span(args_w[i])
725 results[i] = slice_w(space, ctx, start, end, space.w_None)
726 return space.newtuple(results)
727
728 @unwrap_spec(w_default=WrappedDefault(None))
729 def groups_w(self, w_default=None):
730 fmarks = self.flatten_marks()
731 num_groups = self.srepat.num_groups
732 return allgroups_w(self.space, self.ctx, fmarks, num_groups, w_default)
733
734 @unwrap_spec(w_default=WrappedDefault(None))
735 def groupdict_w(self, w_default=None):
736 space = self.space
737 w_dict = space.newdict()
738 w_groupindex = self.srepat.w_groupindex
739 w_iterator = space.iter(w_groupindex)
740 while True:
741 try:
742 w_key = space.next(w_iterator)
743 except OperationError as e:
744 if not e.match(space, space.w_StopIteration):
745 raise
746 break # done
747 w_value = space.getitem(w_groupindex, w_key)
748 start, end = self.do_span(w_value)
749 w_grp = slice_w(space, self.ctx, start, end, w_default)
750 space.setitem(w_dict, w_key, w_grp)
751 return w_dict
752
753 def expand_w(self, w_template):
754 space = self.space
755 w_re = import_re(space)
756 return space.call_method(w_re, '_expand', self.srepat,
757 self, w_template)
758
759 @unwrap_spec(w_groupnum=WrappedDefault(0))
760 def start_w(self, w_groupnum):
761 start, end = self.do_span(w_groupnum)
762 start = self.bytepos_to_charindex(start)
763 return self.space.newint(start)
764
765 @unwrap_spec(w_groupnum=WrappedDefault(0))
766 def end_w(self, w_groupnum):
767 start, end = self.do_span(w_groupnum)
768 end = self.bytepos_to_charindex(end)
769 return self.space.newint(end)
770
771 @unwrap_spec(w_groupnum=WrappedDefault(0))
772 def span_w(self, w_groupnum):
773 start, end = self.do_span(w_groupnum)
774 return self.new_charindex_tuple(start, end)
775
776 def new_charindex_tuple(self, start, end):
777 start = self.bytepos_to_charindex(start)
778 end = self.bytepos_to_charindex(end)
779 return self.space.newtuple2(self.space.newint(start),
780 self.space.newint(end))
781
782 def bytepos_to_charindex(self, bytepos):
783 # Transform a 'byte position', as returned by all methods from
784 # rsre_core, back into a 'character index'. This is for UTF8
785 # handling.
786 ctx = self.ctx
787 if isinstance(ctx, rsre_utf8.Utf8MatchContext):
788 return ctx.w_unicode_obj._byte_to_index(bytepos)
789 else:
790 return bytepos
791
792 def flatten_marks(self):
793 if self.flatten_cache is None:
794 num_groups = self.srepat.num_groups
795 self.flatten_cache = do_flatten_marks(self.ctx, num_groups)
796 return self.flatten_cache
797
798 def do_span(self, w_arg):
799 # return a pair of integers, which are byte positions, not
800 # character indexes (for utf8)
801 space = self.space
802 try:
803 groupnum = space.getindex_w(w_arg, space.w_OverflowError)
804 except OperationError as e:
805 if not e.match(space, space.w_TypeError) and \
806 not e.match(space, space.w_OverflowError):
807 raise
808 try:
809 w_groupnum = space.getitem(self.srepat.w_groupindex, w_arg)
810 except OperationError as e:
811 if not e.match(space, space.w_KeyError):
812 raise
813 raise oefmt(space.w_IndexError, "no such group")
814 groupnum = space.int_w(w_groupnum)
815 if groupnum == 0:
816 return self.ctx.match_start, self.ctx.match_end
817 elif 1 <= groupnum <= self.srepat.num_groups:
818 fmarks = self.flatten_marks()
819 idx = 2*(groupnum-1)
820 assert idx >= 0
821 return fmarks[idx], fmarks[idx+1]
822 else:
823 raise oefmt(space.w_IndexError, "no such group")
824
825 def _last_index(self):
826 mark = self.ctx.match_marks
827 if mark is not None:
828 return mark.gid // 2 + 1
829 return -1
830
831 def fget_lastgroup(self, space):
832 lastindex = self._last_index()
833 if lastindex < 0:
834 return space.w_None
835 w_result = space.finditem(self.srepat.w_indexgroup,
836 space.newint(lastindex))
837 if w_result is None:
838 return space.w_None
839 return w_result
840
841 def fget_lastindex(self, space):
842 lastindex = self._last_index()
843 if lastindex >= 0:
844 return space.newint(lastindex)
845 return space.w_None
846
847 def fget_pos(self, space):
848 return space.newint(self.bytepos_to_charindex(self.ctx.original_pos))
849
850 def fget_endpos(self, space):
851 return space.newint(self.bytepos_to_charindex(self.ctx.end))
852
853 def fget_regs(self, space):
854 space = self.space
855 fmarks = self.flatten_marks()
856 num_groups = self.srepat.num_groups
857 result_w = [None] * (num_groups + 1)
858 ctx = self.ctx
859 result_w[0] = self.new_charindex_tuple(ctx.match_start,
860 ctx.match_end)
861 for i in range(num_groups):
862 result_w[i + 1] = self.new_charindex_tuple(fmarks[i*2],
863 fmarks[i*2+1])
864 return space.newtuple(result_w)
865
866 def fget_string(self, space):
867 return self.w_string
868
869 W_SRE_Match.typedef = TypeDef(
870 're.Match',
871 __doc__ = """The result of re.match() and re.search().
872 Match objects always have a boolean value of True.""",
873 __copy__ = interp2app(W_SRE_Match.copy_identity_w),
874 __deepcopy__ = interp2app(W_SRE_Match.copy_identity_w),
875 __repr__ = interp2app(W_SRE_Match.repr_w),
876 __getitem__ = interp2app(W_SRE_Match.descr_getitem),
877 #
878 group = interp2app(W_SRE_Match.group_w),
879 groups = interp2app(W_SRE_Match.groups_w),
880 groupdict = interp2app(W_SRE_Match.groupdict_w),
881 start = interp2app(W_SRE_Match.start_w),
882 end = interp2app(W_SRE_Match.end_w),
883 span = interp2app(W_SRE_Match.span_w),
884 expand = interp2app(W_SRE_Match.expand_w),
885 #
886 re = interp_attrproperty_w('srepat', W_SRE_Match),
887 string = GetSetProperty(W_SRE_Match.fget_string),
888 pos = GetSetProperty(W_SRE_Match.fget_pos),
889 endpos = GetSetProperty(W_SRE_Match.fget_endpos),
890 lastgroup = GetSetProperty(W_SRE_Match.fget_lastgroup),
891 lastindex = GetSetProperty(W_SRE_Match.fget_lastindex),
892 regs = GetSetProperty(W_SRE_Match.fget_regs),
893 __class_getitem__ = interp2app(
894 generic_alias_class_getitem, as_classmethod=True),
895 )
896 W_SRE_Match.typedef.acceptable_as_base_class = False
897
898 # ____________________________________________________________
899 #
900 # SRE_Scanner class
901 # This is mostly an internal class in CPython.
902 # Our version is also directly iterable, to make finditer() easier.
903
904 class W_SRE_Scanner(W_Root):
905 def __init__(self, pattern, ctx, code, w_string):
906 self.space = pattern.space
907 self.srepat = pattern
908 self.ctx = ctx
909 self.code = code
910 self.w_string = w_string
911 # 'self.ctx' is always a fresh context in which no searching
912 # or matching succeeded so far. It is None when the iterator is
913 # exhausted.
914
915 def iter_w(self):
916 return self
917
918 def next_w(self):
919 if self.ctx is None:
920 raise OperationError(self.space.w_StopIteration, self.space.w_None)
921 if not searchcontext(self.space, self.ctx, self.code):
922 raise OperationError(self.space.w_StopIteration, self.space.w_None)
923 return self.getmatch(True)
924
925 def match_w(self):
926 if self.ctx is None:
927 return self.space.w_None
928 return self.getmatch(matchcontext(self.space, self.ctx, self.code))
929
930 def search_w(self):
931 if self.ctx is None:
932 return self.space.w_None
933 return self.getmatch(searchcontext(self.space, self.ctx, self.code))
934
935 def getmatch(self, found):
936 ctx = self.ctx
937 assert ctx is not None
938 if found:
939 thisstart = ctx.match_start
940 nextstart = ctx.match_end
941 self.ctx = self.srepat.fresh_copy(ctx)
942 self.ctx.reset(nextstart, thisstart == nextstart)
943 match = W_SRE_Match(self.srepat, ctx, self.w_string)
944 return match
945 else:
946 self.ctx = None
947 return None
948
949 W_SRE_Scanner.typedef = TypeDef(
950 '_sre.SRE_Scanner',
951 __iter__ = interp2app(W_SRE_Scanner.iter_w),
952 __next__ = interp2app(W_SRE_Scanner.next_w),
953 match = interp2app(W_SRE_Scanner.match_w),
954 search = interp2app(W_SRE_Scanner.search_w),
955 pattern = interp_attrproperty_w('srepat', W_SRE_Scanner),
956 )
957 W_SRE_Scanner.typedef.acceptable_as_base_class = False