sre_compile.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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 sre.py file for information on usage and redistribution.
  9. #
  10. """Internal support module for sre"""
  11. import _sre, sys
  12. from sre_constants import *
  13. assert _sre.MAGIC == MAGIC, "SRE module mismatch"
  14. if _sre.CODESIZE == 2:
  15. MAXCODE = 65535
  16. else:
  17. MAXCODE = 0xFFFFFFFFL
  18. def _identityfunction(x):
  19. return x
  20. def _compile(code, pattern, flags):
  21. # internal: compile a (sub)pattern
  22. emit = code.append
  23. _len = len
  24. LITERAL_CODES = {LITERAL:1, NOT_LITERAL:1}
  25. REPEATING_CODES = {REPEAT:1, MIN_REPEAT:1, MAX_REPEAT:1}
  26. SUCCESS_CODES = {SUCCESS:1, FAILURE:1}
  27. ASSERT_CODES = {ASSERT:1, ASSERT_NOT:1}
  28. for op, av in pattern:
  29. if op in LITERAL_CODES:
  30. if flags & SRE_FLAG_IGNORECASE:
  31. emit(OPCODES[OP_IGNORE[op]])
  32. emit(_sre.getlower(av, flags))
  33. else:
  34. emit(OPCODES[op])
  35. emit(av)
  36. elif op is IN:
  37. if flags & SRE_FLAG_IGNORECASE:
  38. emit(OPCODES[OP_IGNORE[op]])
  39. def fixup(literal, flags=flags):
  40. return _sre.getlower(literal, flags)
  41. else:
  42. emit(OPCODES[op])
  43. fixup = _identityfunction
  44. skip = _len(code); emit(0)
  45. _compile_charset(av, flags, code, fixup)
  46. code[skip] = _len(code) - skip
  47. elif op is ANY:
  48. if flags & SRE_FLAG_DOTALL:
  49. emit(OPCODES[ANY_ALL])
  50. else:
  51. emit(OPCODES[ANY])
  52. elif op in REPEATING_CODES:
  53. if flags & SRE_FLAG_TEMPLATE:
  54. raise error, "internal: unsupported template operator"
  55. emit(OPCODES[REPEAT])
  56. skip = _len(code); emit(0)
  57. emit(av[0])
  58. emit(av[1])
  59. _compile(code, av[2], flags)
  60. emit(OPCODES[SUCCESS])
  61. code[skip] = _len(code) - skip
  62. elif _simple(av) and op is not REPEAT:
  63. if op is MAX_REPEAT:
  64. emit(OPCODES[REPEAT_ONE])
  65. else:
  66. emit(OPCODES[MIN_REPEAT_ONE])
  67. skip = _len(code); emit(0)
  68. emit(av[0])
  69. emit(av[1])
  70. _compile(code, av[2], flags)
  71. emit(OPCODES[SUCCESS])
  72. code[skip] = _len(code) - skip
  73. else:
  74. emit(OPCODES[REPEAT])
  75. skip = _len(code); emit(0)
  76. emit(av[0])
  77. emit(av[1])
  78. _compile(code, av[2], flags)
  79. code[skip] = _len(code) - skip
  80. if op is MAX_REPEAT:
  81. emit(OPCODES[MAX_UNTIL])
  82. else:
  83. emit(OPCODES[MIN_UNTIL])
  84. elif op is SUBPATTERN:
  85. if av[0]:
  86. emit(OPCODES[MARK])
  87. emit((av[0]-1)*2)
  88. # _compile_info(code, av[1], flags)
  89. _compile(code, av[1], flags)
  90. if av[0]:
  91. emit(OPCODES[MARK])
  92. emit((av[0]-1)*2+1)
  93. elif op in SUCCESS_CODES:
  94. emit(OPCODES[op])
  95. elif op in ASSERT_CODES:
  96. emit(OPCODES[op])
  97. skip = _len(code); emit(0)
  98. if av[0] >= 0:
  99. emit(0) # look ahead
  100. else:
  101. lo, hi = av[1].getwidth()
  102. if lo != hi:
  103. raise error, "look-behind requires fixed-width pattern"
  104. emit(lo) # look behind
  105. _compile(code, av[1], flags)
  106. emit(OPCODES[SUCCESS])
  107. code[skip] = _len(code) - skip
  108. elif op is CALL:
  109. emit(OPCODES[op])
  110. skip = _len(code); emit(0)
  111. _compile(code, av, flags)
  112. emit(OPCODES[SUCCESS])
  113. code[skip] = _len(code) - skip
  114. elif op is AT:
  115. emit(OPCODES[op])
  116. if flags & SRE_FLAG_MULTILINE:
  117. av = AT_MULTILINE.get(av, av)
  118. if flags & SRE_FLAG_LOCALE:
  119. av = AT_LOCALE.get(av, av)
  120. elif flags & SRE_FLAG_UNICODE:
  121. av = AT_UNICODE.get(av, av)
  122. emit(ATCODES[av])
  123. elif op is BRANCH:
  124. emit(OPCODES[op])
  125. tail = []
  126. tailappend = tail.append
  127. for av in av[1]:
  128. skip = _len(code); emit(0)
  129. # _compile_info(code, av, flags)
  130. _compile(code, av, flags)
  131. emit(OPCODES[JUMP])
  132. tailappend(_len(code)); emit(0)
  133. code[skip] = _len(code) - skip
  134. emit(0) # end of branch
  135. for tail in tail:
  136. code[tail] = _len(code) - tail
  137. elif op is CATEGORY:
  138. emit(OPCODES[op])
  139. if flags & SRE_FLAG_LOCALE:
  140. av = CH_LOCALE[av]
  141. elif flags & SRE_FLAG_UNICODE:
  142. av = CH_UNICODE[av]
  143. emit(CHCODES[av])
  144. elif op is GROUPREF:
  145. if flags & SRE_FLAG_IGNORECASE:
  146. emit(OPCODES[OP_IGNORE[op]])
  147. else:
  148. emit(OPCODES[op])
  149. emit(av-1)
  150. elif op is GROUPREF_EXISTS:
  151. emit(OPCODES[op])
  152. emit(av[0]-1)
  153. skipyes = _len(code); emit(0)
  154. _compile(code, av[1], flags)
  155. if av[2]:
  156. emit(OPCODES[JUMP])
  157. skipno = _len(code); emit(0)
  158. code[skipyes] = _len(code) - skipyes + 1
  159. _compile(code, av[2], flags)
  160. code[skipno] = _len(code) - skipno
  161. else:
  162. code[skipyes] = _len(code) - skipyes + 1
  163. else:
  164. raise ValueError, ("unsupported operand type", op)
  165. def _compile_charset(charset, flags, code, fixup=None):
  166. # compile charset subprogram
  167. emit = code.append
  168. if fixup is None:
  169. fixup = _identityfunction
  170. for op, av in _optimize_charset(charset, fixup):
  171. emit(OPCODES[op])
  172. if op is NEGATE:
  173. pass
  174. elif op is LITERAL:
  175. emit(fixup(av))
  176. elif op is RANGE:
  177. emit(fixup(av[0]))
  178. emit(fixup(av[1]))
  179. elif op is CHARSET:
  180. code.extend(av)
  181. elif op is BIGCHARSET:
  182. code.extend(av)
  183. elif op is CATEGORY:
  184. if flags & SRE_FLAG_LOCALE:
  185. emit(CHCODES[CH_LOCALE[av]])
  186. elif flags & SRE_FLAG_UNICODE:
  187. emit(CHCODES[CH_UNICODE[av]])
  188. else:
  189. emit(CHCODES[av])
  190. else:
  191. raise error, "internal: unsupported set operator"
  192. emit(OPCODES[FAILURE])
  193. def _optimize_charset(charset, fixup):
  194. # internal: optimize character set
  195. out = []
  196. outappend = out.append
  197. charmap = [0]*256
  198. try:
  199. for op, av in charset:
  200. if op is NEGATE:
  201. outappend((op, av))
  202. elif op is LITERAL:
  203. charmap[fixup(av)] = 1
  204. elif op is RANGE:
  205. for i in range(fixup(av[0]), fixup(av[1])+1):
  206. charmap[i] = 1
  207. elif op is CATEGORY:
  208. # XXX: could append to charmap tail
  209. return charset # cannot compress
  210. except IndexError:
  211. # character set contains unicode characters
  212. return _optimize_unicode(charset, fixup)
  213. # compress character map
  214. i = p = n = 0
  215. runs = []
  216. runsappend = runs.append
  217. for c in charmap:
  218. if c:
  219. if n == 0:
  220. p = i
  221. n = n + 1
  222. elif n:
  223. runsappend((p, n))
  224. n = 0
  225. i = i + 1
  226. if n:
  227. runsappend((p, n))
  228. if len(runs) <= 2:
  229. # use literal/range
  230. for p, n in runs:
  231. if n == 1:
  232. outappend((LITERAL, p))
  233. else:
  234. outappend((RANGE, (p, p+n-1)))
  235. if len(out) < len(charset):
  236. return out
  237. else:
  238. # use bitmap
  239. data = _mk_bitmap(charmap)
  240. outappend((CHARSET, data))
  241. return out
  242. return charset
  243. def _mk_bitmap(bits):
  244. data = []
  245. dataappend = data.append
  246. if _sre.CODESIZE == 2:
  247. start = (1, 0)
  248. else:
  249. start = (1L, 0L)
  250. m, v = start
  251. for c in bits:
  252. if c:
  253. v = v + m
  254. m = m + m
  255. if m > MAXCODE:
  256. dataappend(v)
  257. m, v = start
  258. return data
  259. # To represent a big charset, first a bitmap of all characters in the
  260. # set is constructed. Then, this bitmap is sliced into chunks of 256
  261. # characters, duplicate chunks are eliminitated, and each chunk is
  262. # given a number. In the compiled expression, the charset is
  263. # represented by a 16-bit word sequence, consisting of one word for
  264. # the number of different chunks, a sequence of 256 bytes (128 words)
  265. # of chunk numbers indexed by their original chunk position, and a
  266. # sequence of chunks (16 words each).
  267. # Compression is normally good: in a typical charset, large ranges of
  268. # Unicode will be either completely excluded (e.g. if only cyrillic
  269. # letters are to be matched), or completely included (e.g. if large
  270. # subranges of Kanji match). These ranges will be represented by
  271. # chunks of all one-bits or all zero-bits.
  272. # Matching can be also done efficiently: the more significant byte of
  273. # the Unicode character is an index into the chunk number, and the
  274. # less significant byte is a bit index in the chunk (just like the
  275. # CHARSET matching).
  276. # In UCS-4 mode, the BIGCHARSET opcode still supports only subsets
  277. # of the basic multilingual plane; an efficient representation
  278. # for all of UTF-16 has not yet been developed. This means,
  279. # in particular, that negated charsets cannot be represented as
  280. # bigcharsets.
  281. def _optimize_unicode(charset, fixup):
  282. try:
  283. import array
  284. except ImportError:
  285. return charset
  286. charmap = [0]*65536
  287. negate = 0
  288. try:
  289. for op, av in charset:
  290. if op is NEGATE:
  291. negate = 1
  292. elif op is LITERAL:
  293. charmap[fixup(av)] = 1
  294. elif op is RANGE:
  295. for i in xrange(fixup(av[0]), fixup(av[1])+1):
  296. charmap[i] = 1
  297. elif op is CATEGORY:
  298. # XXX: could expand category
  299. return charset # cannot compress
  300. except IndexError:
  301. # non-BMP characters
  302. return charset
  303. if negate:
  304. if sys.maxunicode != 65535:
  305. # XXX: negation does not work with big charsets
  306. return charset
  307. for i in xrange(65536):
  308. charmap[i] = not charmap[i]
  309. comps = {}
  310. mapping = [0]*256
  311. block = 0
  312. data = []
  313. for i in xrange(256):
  314. chunk = tuple(charmap[i*256:(i+1)*256])
  315. new = comps.setdefault(chunk, block)
  316. mapping[i] = new
  317. if new == block:
  318. block = block + 1
  319. data = data + _mk_bitmap(chunk)
  320. header = [block]
  321. if _sre.CODESIZE == 2:
  322. code = 'H'
  323. else:
  324. code = 'I'
  325. # Convert block indices to byte array of 256 bytes
  326. mapping = array.array('b', mapping).tostring()
  327. # Convert byte array to word array
  328. mapping = array.array(code, mapping)
  329. assert mapping.itemsize == _sre.CODESIZE
  330. header = header + mapping.tolist()
  331. data[0:0] = header
  332. return [(BIGCHARSET, data)]
  333. def _simple(av):
  334. # check if av is a "simple" operator
  335. lo, hi = av[2].getwidth()
  336. if lo == 0 and hi == MAXREPEAT:
  337. raise error, "nothing to repeat"
  338. return lo == hi == 1 and av[2][0][0] != SUBPATTERN
  339. def _compile_info(code, pattern, flags):
  340. # internal: compile an info block. in the current version,
  341. # this contains min/max pattern width, and an optional literal
  342. # prefix or a character map
  343. lo, hi = pattern.getwidth()
  344. if lo == 0:
  345. return # not worth it
  346. # look for a literal prefix
  347. prefix = []
  348. prefixappend = prefix.append
  349. prefix_skip = 0
  350. charset = [] # not used
  351. charsetappend = charset.append
  352. if not (flags & SRE_FLAG_IGNORECASE):
  353. # look for literal prefix
  354. for op, av in pattern.data:
  355. if op is LITERAL:
  356. if len(prefix) == prefix_skip:
  357. prefix_skip = prefix_skip + 1
  358. prefixappend(av)
  359. elif op is SUBPATTERN and len(av[1]) == 1:
  360. op, av = av[1][0]
  361. if op is LITERAL:
  362. prefixappend(av)
  363. else:
  364. break
  365. else:
  366. break
  367. # if no prefix, look for charset prefix
  368. if not prefix and pattern.data:
  369. op, av = pattern.data[0]
  370. if op is SUBPATTERN and av[1]:
  371. op, av = av[1][0]
  372. if op is LITERAL:
  373. charsetappend((op, av))
  374. elif op is BRANCH:
  375. c = []
  376. cappend = c.append
  377. for p in av[1]:
  378. if not p:
  379. break
  380. op, av = p[0]
  381. if op is LITERAL:
  382. cappend((op, av))
  383. else:
  384. break
  385. else:
  386. charset = c
  387. elif op is BRANCH:
  388. c = []
  389. cappend = c.append
  390. for p in av[1]:
  391. if not p:
  392. break
  393. op, av = p[0]
  394. if op is LITERAL:
  395. cappend((op, av))
  396. else:
  397. break
  398. else:
  399. charset = c
  400. elif op is IN:
  401. charset = av
  402. ## if prefix:
  403. ## print "*** PREFIX", prefix, prefix_skip
  404. ## if charset:
  405. ## print "*** CHARSET", charset
  406. # add an info block
  407. emit = code.append
  408. emit(OPCODES[INFO])
  409. skip = len(code); emit(0)
  410. # literal flag
  411. mask = 0
  412. if prefix:
  413. mask = SRE_INFO_PREFIX
  414. if len(prefix) == prefix_skip == len(pattern.data):
  415. mask = mask + SRE_INFO_LITERAL
  416. elif charset:
  417. mask = mask + SRE_INFO_CHARSET
  418. emit(mask)
  419. # pattern length
  420. if lo < MAXCODE:
  421. emit(lo)
  422. else:
  423. emit(MAXCODE)
  424. prefix = prefix[:MAXCODE]
  425. if hi < MAXCODE:
  426. emit(hi)
  427. else:
  428. emit(0)
  429. # add literal prefix
  430. if prefix:
  431. emit(len(prefix)) # length
  432. emit(prefix_skip) # skip
  433. code.extend(prefix)
  434. # generate overlap table
  435. table = [-1] + ([0]*len(prefix))
  436. for i in xrange(len(prefix)):
  437. table[i+1] = table[i]+1
  438. while table[i+1] > 0 and prefix[i] != prefix[table[i+1]-1]:
  439. table[i+1] = table[table[i+1]-1]+1
  440. code.extend(table[1:]) # don't store first entry
  441. elif charset:
  442. _compile_charset(charset, flags, code)
  443. code[skip] = len(code) - skip
  444. try:
  445. unicode
  446. except NameError:
  447. STRING_TYPES = (type(""),)
  448. else:
  449. STRING_TYPES = (type(""), type(unicode("")))
  450. def isstring(obj):
  451. for tp in STRING_TYPES:
  452. if isinstance(obj, tp):
  453. return 1
  454. return 0
  455. def _code(p, flags):
  456. flags = p.pattern.flags | flags
  457. code = []
  458. # compile info block
  459. _compile_info(code, p, flags)
  460. # compile the pattern
  461. _compile(code, p.data, flags)
  462. code.append(OPCODES[SUCCESS])
  463. return code
  464. def compile(p, flags=0):
  465. # internal: convert pattern list to internal format
  466. if isstring(p):
  467. import sre_parse
  468. pattern = p
  469. p = sre_parse.parse(p, flags)
  470. else:
  471. pattern = None
  472. code = _code(p, flags)
  473. # print code
  474. # XXX: <fl> get rid of this limitation!
  475. if p.pattern.groups > 100:
  476. raise AssertionError(
  477. "sorry, but this version only supports 100 named groups"
  478. )
  479. # map in either direction
  480. groupindex = p.pattern.groupdict
  481. indexgroup = [None] * p.pattern.groups
  482. for k, i in groupindex.items():
  483. indexgroup[i] = k
  484. return _sre.compile(
  485. pattern, flags, code,
  486. p.pattern.groups-1,
  487. groupindex, indexgroup
  488. )