_compiler.py 25 KB

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