_compiler.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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: # IGNORECASE and not LOCALE
  245. av = fixup(av)
  246. charmap[av] = 1
  247. if fixes and av in fixes:
  248. for k in fixes[av]:
  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: # IGNORECASE and not LOCALE
  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: # IGNORECASE and not LOCALE
  284. # For now, IN_UNI_IGNORE+LITERAL and
  285. # IN_UNI_IGNORE+RANGE_UNI_IGNORE work for all non-BMP
  286. # characters, because two characters (at least one of
  287. # which is not in the BMP) match case-insensitively
  288. # if and only if:
  289. # 1) c1.lower() == c2.lower()
  290. # 2) c1.lower() == c2 or c1.lower().upper() == c2
  291. # Also, both c.lower() and c.lower().upper() are single
  292. # characters for every non-BMP character.
  293. if op is RANGE:
  294. if fixes: # not ASCII
  295. op = RANGE_UNI_IGNORE
  296. hascased = True
  297. else:
  298. assert op is LITERAL
  299. if not hascased and iscased(av):
  300. hascased = True
  301. tail.append((op, av))
  302. break
  303. # compress character map
  304. runs = []
  305. q = 0
  306. while True:
  307. p = charmap.find(1, q)
  308. if p < 0:
  309. break
  310. if len(runs) >= 2:
  311. runs = None
  312. break
  313. q = charmap.find(0, p)
  314. if q < 0:
  315. runs.append((p, len(charmap)))
  316. break
  317. runs.append((p, q))
  318. if runs is not None:
  319. # use literal/range
  320. for p, q in runs:
  321. if q - p == 1:
  322. out.append((LITERAL, p))
  323. else:
  324. out.append((RANGE, (p, q - 1)))
  325. out += tail
  326. # if the case was changed or new representation is more compact
  327. if hascased or len(out) < len(charset):
  328. return out, hascased
  329. # else original character set is good enough
  330. return charset, hascased
  331. # use bitmap
  332. if len(charmap) == 256:
  333. data = _mk_bitmap(charmap)
  334. out.append((CHARSET, data))
  335. out += tail
  336. return out, hascased
  337. # To represent a big charset, first a bitmap of all characters in the
  338. # set is constructed. Then, this bitmap is sliced into chunks of 256
  339. # characters, duplicate chunks are eliminated, and each chunk is
  340. # given a number. In the compiled expression, the charset is
  341. # represented by a 32-bit word sequence, consisting of one word for
  342. # the number of different chunks, a sequence of 256 bytes (64 words)
  343. # of chunk numbers indexed by their original chunk position, and a
  344. # sequence of 256-bit chunks (8 words each).
  345. # Compression is normally good: in a typical charset, large ranges of
  346. # Unicode will be either completely excluded (e.g. if only cyrillic
  347. # letters are to be matched), or completely included (e.g. if large
  348. # subranges of Kanji match). These ranges will be represented by
  349. # chunks of all one-bits or all zero-bits.
  350. # Matching can be also done efficiently: the more significant byte of
  351. # the Unicode character is an index into the chunk number, and the
  352. # less significant byte is a bit index in the chunk (just like the
  353. # CHARSET matching).
  354. charmap = bytes(charmap) # should be hashable
  355. comps = {}
  356. mapping = bytearray(256)
  357. block = 0
  358. data = bytearray()
  359. for i in range(0, 65536, 256):
  360. chunk = charmap[i: i + 256]
  361. if chunk in comps:
  362. mapping[i // 256] = comps[chunk]
  363. else:
  364. mapping[i // 256] = comps[chunk] = block
  365. block += 1
  366. data += chunk
  367. data = _mk_bitmap(data)
  368. data[0:0] = [block] + _bytes_to_codes(mapping)
  369. out.append((BIGCHARSET, data))
  370. out += tail
  371. return out, hascased
  372. _CODEBITS = _sre.CODESIZE * 8
  373. MAXCODE = (1 << _CODEBITS) - 1
  374. _BITS_TRANS = b'0' + b'1' * 255
  375. def _mk_bitmap(bits, _CODEBITS=_CODEBITS, _int=int):
  376. s = bits.translate(_BITS_TRANS)[::-1]
  377. return [_int(s[i - _CODEBITS: i], 2)
  378. for i in range(len(s), 0, -_CODEBITS)]
  379. def _bytes_to_codes(b):
  380. # Convert block indices to word array
  381. a = memoryview(b).cast('I')
  382. assert a.itemsize == _sre.CODESIZE
  383. assert len(a) * a.itemsize == len(b)
  384. return a.tolist()
  385. def _simple(p):
  386. # check if this subpattern is a "simple" operator
  387. if len(p) != 1:
  388. return False
  389. op, av = p[0]
  390. if op is SUBPATTERN:
  391. return av[0] is None and _simple(av[-1])
  392. return op in _UNIT_CODES
  393. def _generate_overlap_table(prefix):
  394. """
  395. Generate an overlap table for the following prefix.
  396. An overlap table is a table of the same size as the prefix which
  397. informs about the potential self-overlap for each index in the prefix:
  398. - if overlap[i] == 0, prefix[i:] can't overlap prefix[0:...]
  399. - if overlap[i] == k with 0 < k <= i, prefix[i-k+1:i+1] overlaps with
  400. prefix[0:k]
  401. """
  402. table = [0] * len(prefix)
  403. for i in range(1, len(prefix)):
  404. idx = table[i - 1]
  405. while prefix[i] != prefix[idx]:
  406. if idx == 0:
  407. table[i] = 0
  408. break
  409. idx = table[idx - 1]
  410. else:
  411. table[i] = idx + 1
  412. return table
  413. def _get_iscased(flags):
  414. if not flags & SRE_FLAG_IGNORECASE:
  415. return None
  416. elif flags & SRE_FLAG_UNICODE:
  417. return _sre.unicode_iscased
  418. else:
  419. return _sre.ascii_iscased
  420. def _get_literal_prefix(pattern, flags):
  421. # look for literal prefix
  422. prefix = []
  423. prefixappend = prefix.append
  424. prefix_skip = None
  425. iscased = _get_iscased(flags)
  426. for op, av in pattern.data:
  427. if op is LITERAL:
  428. if iscased and iscased(av):
  429. break
  430. prefixappend(av)
  431. elif op is SUBPATTERN:
  432. group, add_flags, del_flags, p = av
  433. flags1 = _combine_flags(flags, add_flags, del_flags)
  434. if flags1 & SRE_FLAG_IGNORECASE and flags1 & SRE_FLAG_LOCALE:
  435. break
  436. prefix1, prefix_skip1, got_all = _get_literal_prefix(p, flags1)
  437. if prefix_skip is None:
  438. if group is not None:
  439. prefix_skip = len(prefix)
  440. elif prefix_skip1 is not None:
  441. prefix_skip = len(prefix) + prefix_skip1
  442. prefix.extend(prefix1)
  443. if not got_all:
  444. break
  445. else:
  446. break
  447. else:
  448. return prefix, prefix_skip, True
  449. return prefix, prefix_skip, False
  450. def _get_charset_prefix(pattern, flags):
  451. while True:
  452. if not pattern.data:
  453. return None
  454. op, av = pattern.data[0]
  455. if op is not SUBPATTERN:
  456. break
  457. group, add_flags, del_flags, pattern = av
  458. flags = _combine_flags(flags, add_flags, del_flags)
  459. if flags & SRE_FLAG_IGNORECASE and flags & SRE_FLAG_LOCALE:
  460. return None
  461. iscased = _get_iscased(flags)
  462. if op is LITERAL:
  463. if iscased and iscased(av):
  464. return None
  465. return [(op, av)]
  466. elif op is BRANCH:
  467. charset = []
  468. charsetappend = charset.append
  469. for p in av[1]:
  470. if not p:
  471. return None
  472. op, av = p[0]
  473. if op is LITERAL and not (iscased and iscased(av)):
  474. charsetappend((op, av))
  475. else:
  476. return None
  477. return charset
  478. elif op is IN:
  479. charset = av
  480. if iscased:
  481. for op, av in charset:
  482. if op is LITERAL:
  483. if iscased(av):
  484. return None
  485. elif op is RANGE:
  486. if av[1] > 0xffff:
  487. return None
  488. if any(map(iscased, range(av[0], av[1]+1))):
  489. return None
  490. return charset
  491. return None
  492. def _compile_info(code, pattern, flags):
  493. # internal: compile an info block. in the current version,
  494. # this contains min/max pattern width, and an optional literal
  495. # prefix or a character map
  496. lo, hi = pattern.getwidth()
  497. if hi > MAXCODE:
  498. hi = MAXCODE
  499. if lo == 0:
  500. code.extend([INFO, 4, 0, lo, hi])
  501. return
  502. # look for a literal prefix
  503. prefix = []
  504. prefix_skip = 0
  505. charset = [] # not used
  506. if not (flags & SRE_FLAG_IGNORECASE and flags & SRE_FLAG_LOCALE):
  507. # look for literal prefix
  508. prefix, prefix_skip, got_all = _get_literal_prefix(pattern, flags)
  509. # if no prefix, look for charset prefix
  510. if not prefix:
  511. charset = _get_charset_prefix(pattern, flags)
  512. ## if prefix:
  513. ## print("*** PREFIX", prefix, prefix_skip)
  514. ## if charset:
  515. ## print("*** CHARSET", charset)
  516. # add an info block
  517. emit = code.append
  518. emit(INFO)
  519. skip = len(code); emit(0)
  520. # literal flag
  521. mask = 0
  522. if prefix:
  523. mask = SRE_INFO_PREFIX
  524. if prefix_skip is None and got_all:
  525. mask = mask | SRE_INFO_LITERAL
  526. elif charset:
  527. mask = mask | SRE_INFO_CHARSET
  528. emit(mask)
  529. # pattern length
  530. if lo < MAXCODE:
  531. emit(lo)
  532. else:
  533. emit(MAXCODE)
  534. prefix = prefix[:MAXCODE]
  535. emit(hi)
  536. # add literal prefix
  537. if prefix:
  538. emit(len(prefix)) # length
  539. if prefix_skip is None:
  540. prefix_skip = len(prefix)
  541. emit(prefix_skip) # skip
  542. code.extend(prefix)
  543. # generate overlap table
  544. code.extend(_generate_overlap_table(prefix))
  545. elif charset:
  546. charset, hascased = _optimize_charset(charset)
  547. assert not hascased
  548. _compile_charset(charset, flags, code)
  549. code[skip] = len(code) - skip
  550. def isstring(obj):
  551. return isinstance(obj, (str, bytes))
  552. def _code(p, flags):
  553. flags = p.state.flags | flags
  554. code = []
  555. # compile info block
  556. _compile_info(code, p, flags)
  557. # compile the pattern
  558. _compile(code, p.data, flags)
  559. code.append(SUCCESS)
  560. return code
  561. def _hex_code(code):
  562. return '[%s]' % ', '.join('%#0*x' % (_sre.CODESIZE*2+2, x) for x in code)
  563. def dis(code):
  564. import sys
  565. labels = set()
  566. level = 0
  567. offset_width = len(str(len(code) - 1))
  568. def dis_(start, end):
  569. def print_(*args, to=None):
  570. if to is not None:
  571. labels.add(to)
  572. args += ('(to %d)' % (to,),)
  573. print('%*d%s ' % (offset_width, start, ':' if start in labels else '.'),
  574. end=' '*(level-1))
  575. print(*args)
  576. def print_2(*args):
  577. print(end=' '*(offset_width + 2*level))
  578. print(*args)
  579. nonlocal level
  580. level += 1
  581. i = start
  582. while i < end:
  583. start = i
  584. op = code[i]
  585. i += 1
  586. op = OPCODES[op]
  587. if op in (SUCCESS, FAILURE, ANY, ANY_ALL,
  588. MAX_UNTIL, MIN_UNTIL, NEGATE):
  589. print_(op)
  590. elif op in (LITERAL, NOT_LITERAL,
  591. LITERAL_IGNORE, NOT_LITERAL_IGNORE,
  592. LITERAL_UNI_IGNORE, NOT_LITERAL_UNI_IGNORE,
  593. LITERAL_LOC_IGNORE, NOT_LITERAL_LOC_IGNORE):
  594. arg = code[i]
  595. i += 1
  596. print_(op, '%#02x (%r)' % (arg, chr(arg)))
  597. elif op is AT:
  598. arg = code[i]
  599. i += 1
  600. arg = str(ATCODES[arg])
  601. assert arg[:3] == 'AT_'
  602. print_(op, arg[3:])
  603. elif op is CATEGORY:
  604. arg = code[i]
  605. i += 1
  606. arg = str(CHCODES[arg])
  607. assert arg[:9] == 'CATEGORY_'
  608. print_(op, arg[9:])
  609. elif op in (IN, IN_IGNORE, IN_UNI_IGNORE, IN_LOC_IGNORE):
  610. skip = code[i]
  611. print_(op, skip, to=i+skip)
  612. dis_(i+1, i+skip)
  613. i += skip
  614. elif op in (RANGE, RANGE_UNI_IGNORE):
  615. lo, hi = code[i: i+2]
  616. i += 2
  617. print_(op, '%#02x %#02x (%r-%r)' % (lo, hi, chr(lo), chr(hi)))
  618. elif op is CHARSET:
  619. print_(op, _hex_code(code[i: i + 256//_CODEBITS]))
  620. i += 256//_CODEBITS
  621. elif op is BIGCHARSET:
  622. arg = code[i]
  623. i += 1
  624. mapping = list(b''.join(x.to_bytes(_sre.CODESIZE, sys.byteorder)
  625. for x in code[i: i + 256//_sre.CODESIZE]))
  626. print_(op, arg, mapping)
  627. i += 256//_sre.CODESIZE
  628. level += 1
  629. for j in range(arg):
  630. print_2(_hex_code(code[i: i + 256//_CODEBITS]))
  631. i += 256//_CODEBITS
  632. level -= 1
  633. elif op in (MARK, GROUPREF, GROUPREF_IGNORE, GROUPREF_UNI_IGNORE,
  634. GROUPREF_LOC_IGNORE):
  635. arg = code[i]
  636. i += 1
  637. print_(op, arg)
  638. elif op is JUMP:
  639. skip = code[i]
  640. print_(op, skip, to=i+skip)
  641. i += 1
  642. elif op is BRANCH:
  643. skip = code[i]
  644. print_(op, skip, to=i+skip)
  645. while skip:
  646. dis_(i+1, i+skip)
  647. i += skip
  648. start = i
  649. skip = code[i]
  650. if skip:
  651. print_('branch', skip, to=i+skip)
  652. else:
  653. print_(FAILURE)
  654. i += 1
  655. elif op in (REPEAT, REPEAT_ONE, MIN_REPEAT_ONE,
  656. POSSESSIVE_REPEAT, POSSESSIVE_REPEAT_ONE):
  657. skip, min, max = code[i: i+3]
  658. if max == MAXREPEAT:
  659. max = 'MAXREPEAT'
  660. print_(op, skip, min, max, to=i+skip)
  661. dis_(i+3, i+skip)
  662. i += skip
  663. elif op is GROUPREF_EXISTS:
  664. arg, skip = code[i: i+2]
  665. print_(op, arg, skip, to=i+skip)
  666. i += 2
  667. elif op in (ASSERT, ASSERT_NOT):
  668. skip, arg = code[i: i+2]
  669. print_(op, skip, arg, to=i+skip)
  670. dis_(i+2, i+skip)
  671. i += skip
  672. elif op is ATOMIC_GROUP:
  673. skip = code[i]
  674. print_(op, skip, to=i+skip)
  675. dis_(i+1, i+skip)
  676. i += skip
  677. elif op is INFO:
  678. skip, flags, min, max = code[i: i+4]
  679. if max == MAXREPEAT:
  680. max = 'MAXREPEAT'
  681. print_(op, skip, bin(flags), min, max, to=i+skip)
  682. start = i+4
  683. if flags & SRE_INFO_PREFIX:
  684. prefix_len, prefix_skip = code[i+4: i+6]
  685. print_2(' prefix_skip', prefix_skip)
  686. start = i + 6
  687. prefix = code[start: start+prefix_len]
  688. print_2(' prefix',
  689. '[%s]' % ', '.join('%#02x' % x for x in prefix),
  690. '(%r)' % ''.join(map(chr, prefix)))
  691. start += prefix_len
  692. print_2(' overlap', code[start: start+prefix_len])
  693. start += prefix_len
  694. if flags & SRE_INFO_CHARSET:
  695. level += 1
  696. print_2('in')
  697. dis_(start, i+skip)
  698. level -= 1
  699. i += skip
  700. else:
  701. raise ValueError(op)
  702. level -= 1
  703. dis_(0, len(code))
  704. def compile(p, flags=0):
  705. # internal: convert pattern list to internal format
  706. if isstring(p):
  707. pattern = p
  708. p = _parser.parse(p, flags)
  709. else:
  710. pattern = None
  711. code = _code(p, flags)
  712. if flags & SRE_FLAG_DEBUG:
  713. print()
  714. dis(code)
  715. # map in either direction
  716. groupindex = p.state.groupdict
  717. indexgroup = [None] * p.state.groups
  718. for k, i in groupindex.items():
  719. indexgroup[i] = k
  720. return _sre.compile(
  721. pattern, flags | p.state.flags, code,
  722. p.state.groups-1,
  723. groupindex, tuple(indexgroup)
  724. )