Debian Codegraph @

Lib/re/_compiler.py

raw
1 #
2 # Secret Labs' Regular Expression Engine
3 #
4 # convert template to internal format
5 #
6 # Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved.
7 #
8 # See the __init__.py file for information on usage and redistribution.
9 #
10
11 """Internal support module for sre"""
12
13 import _sre
14 from . import _parser
15 from ._constants import *
16 from ._casefix import _EXTRA_CASES
17
18 assert _sre.MAGIC == MAGIC, "SRE module mismatch"
19
20 _LITERAL_CODES = {LITERAL, NOT_LITERAL}
21 _SUCCESS_CODES = {SUCCESS, FAILURE}
22 _ASSERT_CODES = {ASSERT, ASSERT_NOT}
23 _UNIT_CODES = _LITERAL_CODES | {ANY, IN}
24
25 _REPEATING_CODES = {
26 MIN_REPEAT: (REPEAT, MIN_UNTIL, MIN_REPEAT_ONE),
27 MAX_REPEAT: (REPEAT, MAX_UNTIL, REPEAT_ONE),
28 POSSESSIVE_REPEAT: (POSSESSIVE_REPEAT, SUCCESS, POSSESSIVE_REPEAT_ONE),
29 }
30
31 _CHARSET_ALL = [(NEGATE, None)]
32
33 def _combine_flags(flags, add_flags, del_flags,
34 TYPE_FLAGS=_parser.TYPE_FLAGS):
35 if add_flags & TYPE_FLAGS:
36 flags &= ~TYPE_FLAGS
37 return (flags | add_flags) & ~del_flags
38
39 def _compile(code, pattern, flags):
40 # internal: compile a (sub)pattern
41 emit = code.append
42 _len = len
43 LITERAL_CODES = _LITERAL_CODES
44 REPEATING_CODES = _REPEATING_CODES
45 SUCCESS_CODES = _SUCCESS_CODES
46 ASSERT_CODES = _ASSERT_CODES
47 iscased = None
48 tolower = None
49 fixes = None
50 if flags & SRE_FLAG_IGNORECASE and not flags & SRE_FLAG_LOCALE:
51 if flags & SRE_FLAG_UNICODE:
52 iscased = _sre.unicode_iscased
53 tolower = _sre.unicode_tolower
54 fixes = _EXTRA_CASES
55 else:
56 iscased = _sre.ascii_iscased
57 tolower = _sre.ascii_tolower
58 for op, av in pattern:
59 if op in LITERAL_CODES:
60 if not flags & SRE_FLAG_IGNORECASE:
61 emit(op)
62 emit(av)
63 elif flags & SRE_FLAG_LOCALE:
64 emit(OP_LOCALE_IGNORE[op])
65 emit(av)
66 elif not iscased(av):
67 emit(op)
68 emit(av)
69 else:
70 lo = tolower(av)
71 if not fixes: # ascii
72 emit(OP_IGNORE[op])
73 emit(lo)
74 elif lo not in fixes:
75 emit(OP_UNICODE_IGNORE[op])
76 emit(lo)
77 else:
78 emit(IN_UNI_IGNORE)
79 skip = _len(code); emit(0)
80 if op is NOT_LITERAL:
81 emit(NEGATE)
82 for k in (lo,) + fixes[lo]:
83 emit(LITERAL)
84 emit(k)
85 emit(FAILURE)
86 code[skip] = _len(code) - skip
87 elif op is IN:
88 charset, hascased = _optimize_charset(av, iscased, tolower, fixes)
89 if not charset:
90 emit(FAILURE)
91 elif charset == _CHARSET_ALL:
92 emit(ANY_ALL)
93 else:
94 if flags & SRE_FLAG_IGNORECASE and flags & SRE_FLAG_LOCALE:
95 emit(IN_LOC_IGNORE)
96 elif not hascased:
97 emit(IN)
98 elif not fixes: # ascii
99 emit(IN_IGNORE)
100 else:
101 emit(IN_UNI_IGNORE)
102 skip = _len(code); emit(0)
103 _compile_charset(charset, flags, code)
104 code[skip] = _len(code) - skip
105 elif op is ANY:
106 if flags & SRE_FLAG_DOTALL:
107 emit(ANY_ALL)
108 else:
109 emit(ANY)
110 elif op in REPEATING_CODES:
111 if _simple(av[2]):
112 emit(REPEATING_CODES[op][2])
113 skip = _len(code); emit(0)
114 emit(av[0])
115 emit(av[1])
116 _compile(code, av[2], flags)
117 emit(SUCCESS)
118 code[skip] = _len(code) - skip
119 else:
120 emit(REPEATING_CODES[op][0])
121 skip = _len(code); emit(0)
122 emit(av[0])
123 emit(av[1])
124 _compile(code, av[2], flags)
125 code[skip] = _len(code) - skip
126 emit(REPEATING_CODES[op][1])
127 elif op is SUBPATTERN:
128 group, add_flags, del_flags, p = av
129 if group:
130 emit(MARK)
131 emit((group-1)*2)
132 # _compile_info(code, p, _combine_flags(flags, add_flags, del_flags))
133 _compile(code, p, _combine_flags(flags, add_flags, del_flags))
134 if group:
135 emit(MARK)
136 emit((group-1)*2+1)
137 elif op is ATOMIC_GROUP:
138 # Atomic Groups are handled by starting with an Atomic
139 # Group op code, then putting in the atomic group pattern
140 # and finally a success op code to tell any repeat
141 # operations within the Atomic Group to stop eating and
142 # pop their stack if they reach it
143 emit(ATOMIC_GROUP)
144 skip = _len(code); emit(0)
145 _compile(code, av, flags)
146 emit(SUCCESS)
147 code[skip] = _len(code) - skip
148 elif op in SUCCESS_CODES:
149 emit(op)
150 elif op in ASSERT_CODES:
151 emit(op)
152 skip = _len(code); emit(0)
153 if av[0] >= 0:
154 emit(0) # look ahead
155 else:
156 lo, hi = av[1].getwidth()
157 if lo > MAXCODE:
158 raise error("looks too much behind")
159 if lo != hi:
160 raise PatternError("look-behind requires fixed-width pattern")
161 emit(lo) # look behind
162 _compile(code, av[1], flags)
163 emit(SUCCESS)
164 code[skip] = _len(code) - skip
165 elif op is AT:
166 emit(op)
167 if flags & SRE_FLAG_MULTILINE:
168 av = AT_MULTILINE.get(av, av)
169 if flags & SRE_FLAG_LOCALE:
170 av = AT_LOCALE.get(av, av)
171 elif flags & SRE_FLAG_UNICODE:
172 av = AT_UNICODE.get(av, av)
173 emit(av)
174 elif op is BRANCH:
175 emit(op)
176 tail = []
177 tailappend = tail.append
178 for av in av[1]:
179 skip = _len(code); emit(0)
180 # _compile_info(code, av, flags)
181 _compile(code, av, flags)
182 emit(JUMP)
183 tailappend(_len(code)); emit(0)
184 code[skip] = _len(code) - skip
185 emit(FAILURE) # end of branch
186 for tail in tail:
187 code[tail] = _len(code) - tail
188 elif op is CATEGORY:
189 emit(op)
190 if flags & SRE_FLAG_LOCALE:
191 av = CH_LOCALE[av]
192 elif flags & SRE_FLAG_UNICODE:
193 av = CH_UNICODE[av]
194 emit(av)
195 elif op is GROUPREF:
196 if not flags & SRE_FLAG_IGNORECASE:
197 emit(op)
198 elif flags & SRE_FLAG_LOCALE:
199 emit(GROUPREF_LOC_IGNORE)
200 elif not fixes: # ascii
201 emit(GROUPREF_IGNORE)
202 else:
203 emit(GROUPREF_UNI_IGNORE)
204 emit(av-1)
205 elif op is GROUPREF_EXISTS:
206 emit(op)
207 emit(av[0]-1)
208 skipyes = _len(code); emit(0)
209 _compile(code, av[1], flags)
210 if av[2]:
211 emit(JUMP)
212 skipno = _len(code); emit(0)
213 code[skipyes] = _len(code) - skipyes + 1
214 _compile(code, av[2], flags)
215 code[skipno] = _len(code) - skipno
216 else:
217 code[skipyes] = _len(code) - skipyes + 1
218 else:
219 raise PatternError(f"internal: unsupported operand type {op!r}")
220
221 def _compile_charset(charset, flags, code):
222 # compile charset subprogram
223 emit = code.append
224 for op, av in charset:
225 emit(op)
226 if op is NEGATE:
227 pass
228 elif op is LITERAL:
229 emit(av)
230 elif op is RANGE or op is RANGE_UNI_IGNORE:
231 emit(av[0])
232 emit(av[1])
233 elif op is CHARSET:
234 code.extend(av)
235 elif op is BIGCHARSET:
236 code.extend(av)
237 elif op is CATEGORY:
238 if flags & SRE_FLAG_LOCALE:
239 emit(CH_LOCALE[av])
240 elif flags & SRE_FLAG_UNICODE:
241 emit(CH_UNICODE[av])
242 else:
243 emit(av)
244 else:
245 raise PatternError(f"internal: unsupported set operator {op!r}")
246 emit(FAILURE)
247
248 def _optimize_charset(charset, iscased=None, fixup=None, fixes=None):
249 # internal: optimize character set
250 out = []
251 tail = []
252 charmap = bytearray(256)
253 hascased = False
254 for op, av in charset:
255 while True:
256 try:
257 if op is LITERAL:
258 if fixup: # IGNORECASE and not LOCALE
259 av = fixup(av)
260 charmap[av] = 1
261 if fixes and av in fixes:
262 for k in fixes[av]:
263 charmap[k] = 1
264 if not hascased and iscased(av):
265 hascased = True
266 else:
267 charmap[av] = 1
268 elif op is RANGE:
269 r = range(av[0], av[1]+1)
270 if fixup: # IGNORECASE and not LOCALE
271 if fixes:
272 for i in map(fixup, r):
273 charmap[i] = 1
274 if i in fixes:
275 for k in fixes[i]:
276 charmap[k] = 1
277 else:
278 for i in map(fixup, r):
279 charmap[i] = 1
280 if not hascased:
281 hascased = any(map(iscased, r))
282 else:
283 for i in r:
284 charmap[i] = 1
285 elif op is NEGATE:
286 out.append((op, av))
287 elif op is CATEGORY and tail and (CATEGORY, CH_NEGATE[av]) in tail:
288 # Optimize [\s\S] etc.
289 out = [] if out else _CHARSET_ALL
290 return out, False
291 else:
292 tail.append((op, av))
293 except IndexError:
294 if len(charmap) == 256:
295 # character set contains non-UCS1 character codes
296 charmap += b'\0' * 0xff00
297 continue
298 # Character set contains non-BMP character codes.
299 # For range, all BMP characters in the range are already
300 # proceeded.
301 if fixup: # IGNORECASE and not LOCALE
302 # For now, IN_UNI_IGNORE+LITERAL and
303 # IN_UNI_IGNORE+RANGE_UNI_IGNORE work for all non-BMP
304 # characters, because two characters (at least one of
305 # which is not in the BMP) match case-insensitively
306 # if and only if:
307 # 1) c1.lower() == c2.lower()
308 # 2) c1.lower() == c2 or c1.lower().upper() == c2
309 # Also, both c.lower() and c.lower().upper() are single
310 # characters for every non-BMP character.
311 if op is RANGE:
312 if fixes: # not ASCII
313 op = RANGE_UNI_IGNORE
314 hascased = True
315 else:
316 assert op is LITERAL
317 if not hascased and iscased(av):
318 hascased = True
319 tail.append((op, av))
320 break
321
322 # compress character map
323 runs = []
324 q = 0
325 while True:
326 p = charmap.find(1, q)
327 if p < 0:
328 break
329 if len(runs) >= 2:
330 runs = None
331 break
332 q = charmap.find(0, p)
333 if q < 0:
334 runs.append((p, len(charmap)))
335 break
336 runs.append((p, q))
337 if runs is not None:
338 # use literal/range
339 for p, q in runs:
340 if q - p == 1:
341 out.append((LITERAL, p))
342 else:
343 out.append((RANGE, (p, q - 1)))
344 out += tail
345 # if the case was changed or new representation is more compact
346 if hascased or len(out) < len(charset):
347 return out, hascased
348 # else original character set is good enough
349 return charset, hascased
350
351 # use bitmap
352 if len(charmap) == 256:
353 data = _mk_bitmap(charmap)
354 out.append((CHARSET, data))
355 out += tail
356 return out, hascased
357
358 # To represent a big charset, first a bitmap of all characters in the
359 # set is constructed. Then, this bitmap is sliced into chunks of 256
360 # characters, duplicate chunks are eliminated, and each chunk is
361 # given a number. In the compiled expression, the charset is
362 # represented by a 32-bit word sequence, consisting of one word for
363 # the number of different chunks, a sequence of 256 bytes (64 words)
364 # of chunk numbers indexed by their original chunk position, and a
365 # sequence of 256-bit chunks (8 words each).
366
367 # Compression is normally good: in a typical charset, large ranges of
368 # Unicode will be either completely excluded (e.g. if only cyrillic
369 # letters are to be matched), or completely included (e.g. if large
370 # subranges of Kanji match). These ranges will be represented by
371 # chunks of all one-bits or all zero-bits.
372
373 # Matching can be also done efficiently: the more significant byte of
374 # the Unicode character is an index into the chunk number, and the
375 # less significant byte is a bit index in the chunk (just like the
376 # CHARSET matching).
377
378 charmap = bytes(charmap) # should be hashable
379 comps = {}
380 mapping = bytearray(256)
381 block = 0
382 data = bytearray()
383 for i in range(0, 65536, 256):
384 chunk = charmap[i: i + 256]
385 if chunk in comps:
386 mapping[i // 256] = comps[chunk]
387 else:
388 mapping[i // 256] = comps[chunk] = block
389 block += 1
390 data += chunk
391 data = _mk_bitmap(data)
392 data[0:0] = [block] + _bytes_to_codes(mapping)
393 out.append((BIGCHARSET, data))
394 out += tail
395 return out, hascased
396
397 _CODEBITS = _sre.CODESIZE * 8
398 MAXCODE = (1 << _CODEBITS) - 1
399 _BITS_TRANS = b'0' + b'1' * 255
400 def _mk_bitmap(bits, _CODEBITS=_CODEBITS, _int=int):
401 s = bits.translate(_BITS_TRANS)[::-1]
402 return [_int(s[i - _CODEBITS: i], 2)
403 for i in range(len(s), 0, -_CODEBITS)]
404
405 def _bytes_to_codes(b):
406 # Convert block indices to word array
407 a = memoryview(b).cast('I')
408 assert a.itemsize == _sre.CODESIZE
409 assert len(a) * a.itemsize == len(b)
410 return a.tolist()
411
412 def _simple(p):
413 # check if this subpattern is a "simple" operator
414 if len(p) != 1:
415 return False
416 op, av = p[0]
417 if op is SUBPATTERN:
418 return av[0] is None and _simple(av[-1])
419 return op in _UNIT_CODES
420
421 def _generate_overlap_table(prefix):
422 """
423 Generate an overlap table for the following prefix.
424 An overlap table is a table of the same size as the prefix which
425 informs about the potential self-overlap for each index in the prefix:
426 - if overlap[i] == 0, prefix[i:] can't overlap prefix[0:...]
427 - if overlap[i] == k with 0 < k <= i, prefix[i-k+1:i+1] overlaps with
428 prefix[0:k]
429 """
430 table = [0] * len(prefix)
431 for i in range(1, len(prefix)):
432 idx = table[i - 1]
433 while prefix[i] != prefix[idx]:
434 if idx == 0:
435 table[i] = 0
436 break
437 idx = table[idx - 1]
438 else:
439 table[i] = idx + 1
440 return table
441
442 def _get_iscased(flags):
443 if not flags & SRE_FLAG_IGNORECASE:
444 return None
445 elif flags & SRE_FLAG_UNICODE:
446 return _sre.unicode_iscased
447 else:
448 return _sre.ascii_iscased
449
450 def _get_literal_prefix(pattern, flags):
451 # look for literal prefix
452 prefix = []
453 prefixappend = prefix.append
454 prefix_skip = None
455 iscased = _get_iscased(flags)
456 for op, av in pattern.data:
457 if op is LITERAL:
458 if iscased and iscased(av):
459 break
460 prefixappend(av)
461 elif op is SUBPATTERN:
462 group, add_flags, del_flags, p = av
463 flags1 = _combine_flags(flags, add_flags, del_flags)
464 if flags1 & SRE_FLAG_IGNORECASE and flags1 & SRE_FLAG_LOCALE:
465 break
466 prefix1, prefix_skip1, got_all = _get_literal_prefix(p, flags1)
467 if prefix_skip is None:
468 if group is not None:
469 prefix_skip = len(prefix)
470 elif prefix_skip1 is not None:
471 prefix_skip = len(prefix) + prefix_skip1
472 prefix.extend(prefix1)
473 if not got_all:
474 break
475 else:
476 break
477 else:
478 return prefix, prefix_skip, True
479 return prefix, prefix_skip, False
480
481 def _get_charset_prefix(pattern, flags):
482 while True:
483 if not pattern.data:
484 return None
485 op, av = pattern.data[0]
486 if op is not SUBPATTERN:
487 break
488 group, add_flags, del_flags, pattern = av
489 flags = _combine_flags(flags, add_flags, del_flags)
490 if flags & SRE_FLAG_IGNORECASE and flags & SRE_FLAG_LOCALE:
491 return None
492
493 iscased = _get_iscased(flags)
494 if op is LITERAL:
495 if iscased and iscased(av):
496 return None
497 return [(op, av)]
498 elif op is BRANCH:
499 charset = []
500 charsetappend = charset.append
501 for p in av[1]:
502 if not p:
503 return None
504 op, av = p[0]
505 if op is LITERAL and not (iscased and iscased(av)):
506 charsetappend((op, av))
507 else:
508 return None
509 return charset
510 elif op is IN:
511 charset = av
512 if iscased:
513 for op, av in charset:
514 if op is LITERAL:
515 if iscased(av):
516 return None
517 elif op is RANGE:
518 if av[1] > 0xffff:
519 return None
520 if any(map(iscased, range(av[0], av[1]+1))):
521 return None
522 return charset
523 return None
524
525 def _compile_info(code, pattern, flags):
526 # internal: compile an info block. in the current version,
527 # this contains min/max pattern width, and an optional literal
528 # prefix or a character map
529 lo, hi = pattern.getwidth()
530 if hi > MAXCODE:
531 hi = MAXCODE
532 if lo == 0:
533 code.extend([INFO, 4, 0, lo, hi])
534 return
535 # look for a literal prefix
536 prefix = []
537 prefix_skip = 0
538 charset = None # not used
539 if not (flags & SRE_FLAG_IGNORECASE and flags & SRE_FLAG_LOCALE):
540 # look for literal prefix
541 prefix, prefix_skip, got_all = _get_literal_prefix(pattern, flags)
542 # if no prefix, look for charset prefix
543 if not prefix:
544 charset = _get_charset_prefix(pattern, flags)
545 if charset:
546 charset, hascased = _optimize_charset(charset)
547 assert not hascased
548 if charset == _CHARSET_ALL:
549 charset = None
550 ## if prefix:
551 ## print("*** PREFIX", prefix, prefix_skip)
552 ## if charset:
553 ## print("*** CHARSET", charset)
554 # add an info block
555 emit = code.append
556 emit(INFO)
557 skip = len(code); emit(0)
558 # literal flag
559 mask = 0
560 if prefix:
561 mask = SRE_INFO_PREFIX
562 if prefix_skip is None and got_all:
563 mask = mask | SRE_INFO_LITERAL
564 elif charset:
565 mask = mask | SRE_INFO_CHARSET
566 emit(mask)
567 # pattern length
568 if lo < MAXCODE:
569 emit(lo)
570 else:
571 emit(MAXCODE)
572 prefix = prefix[:MAXCODE]
573 emit(hi)
574 # add literal prefix
575 if prefix:
576 emit(len(prefix)) # length
577 if prefix_skip is None:
578 prefix_skip = len(prefix)
579 emit(prefix_skip) # skip
580 code.extend(prefix)
581 # generate overlap table
582 code.extend(_generate_overlap_table(prefix))
583 elif charset:
584 _compile_charset(charset, flags, code)
585 code[skip] = len(code) - skip
586
587 def isstring(obj):
588 return isinstance(obj, (str, bytes))
589
590 def _code(p, flags):
591
592 flags = p.state.flags | flags
593 code = []
594
595 # compile info block
596 _compile_info(code, p, flags)
597
598 # compile the pattern
599 _compile(code, p.data, flags)
600
601 code.append(SUCCESS)
602
603 return code
604
605 def _hex_code(code):
606 return '[%s]' % ', '.join('%#0*x' % (_sre.CODESIZE*2+2, x) for x in code)
607
608 def dis(code):
609 import sys
610
611 labels = set()
612 level = 0
613 offset_width = len(str(len(code) - 1))
614
615 def dis_(start, end):
616 def print_(*args, to=None):
617 if to is not None:
618 labels.add(to)
619 args += ('(to %d)' % (to,),)
620 print('%*d%s ' % (offset_width, start, ':' if start in labels else '.'),
621 end=' '*(level-1))
622 print(*args)
623
624 def print_2(*args):
625 print(end=' '*(offset_width + 2*level))
626 print(*args)
627
628 nonlocal level
629 level += 1
630 i = start
631 while i < end:
632 start = i
633 op = code[i]
634 i += 1
635 op = OPCODES[op]
636 if op in (SUCCESS, FAILURE, ANY, ANY_ALL,
637 MAX_UNTIL, MIN_UNTIL, NEGATE):
638 print_(op)
639 elif op in (LITERAL, NOT_LITERAL,
640 LITERAL_IGNORE, NOT_LITERAL_IGNORE,
641 LITERAL_UNI_IGNORE, NOT_LITERAL_UNI_IGNORE,
642 LITERAL_LOC_IGNORE, NOT_LITERAL_LOC_IGNORE):
643 arg = code[i]
644 i += 1
645 print_(op, '%#02x (%r)' % (arg, chr(arg)))
646 elif op is AT:
647 arg = code[i]
648 i += 1
649 arg = str(ATCODES[arg])
650 assert arg[:3] == 'AT_'
651 print_(op, arg[3:])
652 elif op is CATEGORY:
653 arg = code[i]
654 i += 1
655 arg = str(CHCODES[arg])
656 assert arg[:9] == 'CATEGORY_'
657 print_(op, arg[9:])
658 elif op in (IN, IN_IGNORE, IN_UNI_IGNORE, IN_LOC_IGNORE):
659 skip = code[i]
660 print_(op, skip, to=i+skip)
661 dis_(i+1, i+skip)
662 i += skip
663 elif op in (RANGE, RANGE_UNI_IGNORE):
664 lo, hi = code[i: i+2]
665 i += 2
666 print_(op, '%#02x %#02x (%r-%r)' % (lo, hi, chr(lo), chr(hi)))
667 elif op is CHARSET:
668 print_(op, _hex_code(code[i: i + 256//_CODEBITS]))
669 i += 256//_CODEBITS
670 elif op is BIGCHARSET:
671 arg = code[i]
672 i += 1
673 mapping = list(b''.join(x.to_bytes(_sre.CODESIZE, sys.byteorder)
674 for x in code[i: i + 256//_sre.CODESIZE]))
675 print_(op, arg, mapping)
676 i += 256//_sre.CODESIZE
677 level += 1
678 for j in range(arg):
679 print_2(_hex_code(code[i: i + 256//_CODEBITS]))
680 i += 256//_CODEBITS
681 level -= 1
682 elif op in (MARK, GROUPREF, GROUPREF_IGNORE, GROUPREF_UNI_IGNORE,
683 GROUPREF_LOC_IGNORE):
684 arg = code[i]
685 i += 1
686 print_(op, arg)
687 elif op is JUMP:
688 skip = code[i]
689 print_(op, skip, to=i+skip)
690 i += 1
691 elif op is BRANCH:
692 skip = code[i]
693 print_(op, skip, to=i+skip)
694 while skip:
695 dis_(i+1, i+skip)
696 i += skip
697 start = i
698 skip = code[i]
699 if skip:
700 print_('branch', skip, to=i+skip)
701 else:
702 print_(FAILURE)
703 i += 1
704 elif op in (REPEAT, REPEAT_ONE, MIN_REPEAT_ONE,
705 POSSESSIVE_REPEAT, POSSESSIVE_REPEAT_ONE):
706 skip, min, max = code[i: i+3]
707 if max == MAXREPEAT:
708 max = 'MAXREPEAT'
709 print_(op, skip, min, max, to=i+skip)
710 dis_(i+3, i+skip)
711 i += skip
712 elif op is GROUPREF_EXISTS:
713 arg, skip = code[i: i+2]
714 print_(op, arg, skip, to=i+skip)
715 i += 2
716 elif op in (ASSERT, ASSERT_NOT):
717 skip, arg = code[i: i+2]
718 print_(op, skip, arg, to=i+skip)
719 dis_(i+2, i+skip)
720 i += skip
721 elif op is ATOMIC_GROUP:
722 skip = code[i]
723 print_(op, skip, to=i+skip)
724 dis_(i+1, i+skip)
725 i += skip
726 elif op is INFO:
727 skip, flags, min, max = code[i: i+4]
728 if max == MAXREPEAT:
729 max = 'MAXREPEAT'
730 print_(op, skip, bin(flags), min, max, to=i+skip)
731 start = i+4
732 if flags & SRE_INFO_PREFIX:
733 prefix_len, prefix_skip = code[i+4: i+6]
734 print_2(' prefix_skip', prefix_skip)
735 start = i + 6
736 prefix = code[start: start+prefix_len]
737 print_2(' prefix',
738 '[%s]' % ', '.join('%#02x' % x for x in prefix),
739 '(%r)' % ''.join(map(chr, prefix)))
740 start += prefix_len
741 print_2(' overlap', code[start: start+prefix_len])
742 start += prefix_len
743 if flags & SRE_INFO_CHARSET:
744 level += 1
745 print_2('in')
746 dis_(start, i+skip)
747 level -= 1
748 i += skip
749 else:
750 raise ValueError(op)
751
752 level -= 1
753
754 dis_(0, len(code))
755
756
757 def compile(p, flags=0):
758 # internal: convert pattern list to internal format
759
760 if isstring(p):
761 pattern = p
762 p = _parser.parse(p, flags)
763 else:
764 pattern = None
765
766 code = _code(p, flags)
767
768 if flags & SRE_FLAG_DEBUG:
769 print()
770 dis(code)
771
772 # map in either direction
773 groupindex = p.state.groupdict
774 indexgroup = [None] * p.state.groups
775 for k, i in groupindex.items():
776 indexgroup[i] = k
777
778 return _sre.compile(
779 pattern, flags | p.state.flags, code,
780 p.state.groups-1,
781 groupindex, tuple(indexgroup)
782 )