PageRenderTime 59ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 1ms

/pypy/module/cpyext/test/_sre.c

https://bitbucket.org/dac_io/pypy
C | 3912 lines | 2977 code | 574 blank | 361 comment | 629 complexity | 7e13b2e9dea5e5f8bb88018fb0811076 MD5 | raw file
  1. /*
  2. * Secret Labs' Regular Expression Engine
  3. *
  4. * regular expression matching engine
  5. *
  6. * partial history:
  7. * 1999-10-24 fl created (based on existing template matcher code)
  8. * 2000-03-06 fl first alpha, sort of
  9. * 2000-08-01 fl fixes for 1.6b1
  10. * 2000-08-07 fl use PyOS_CheckStack() if available
  11. * 2000-09-20 fl added expand method
  12. * 2001-03-20 fl lots of fixes for 2.1b2
  13. * 2001-04-15 fl export copyright as Python attribute, not global
  14. * 2001-04-28 fl added __copy__ methods (work in progress)
  15. * 2001-05-14 fl fixes for 1.5.2 compatibility
  16. * 2001-07-01 fl added BIGCHARSET support (from Martin von Loewis)
  17. * 2001-10-18 fl fixed group reset issue (from Matthew Mueller)
  18. * 2001-10-20 fl added split primitive; reenable unicode for 1.6/2.0/2.1
  19. * 2001-10-21 fl added sub/subn primitive
  20. * 2001-10-24 fl added finditer primitive (for 2.2 only)
  21. * 2001-12-07 fl fixed memory leak in sub/subn (Guido van Rossum)
  22. * 2002-11-09 fl fixed empty sub/subn return type
  23. * 2003-04-18 mvl fully support 4-byte codes
  24. * 2003-10-17 gn implemented non recursive scheme
  25. *
  26. * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved.
  27. *
  28. * This version of the SRE library can be redistributed under CNRI's
  29. * Python 1.6 license. For any other use, please contact Secret Labs
  30. * AB (info@pythonware.com).
  31. *
  32. * Portions of this engine have been developed in cooperation with
  33. * CNRI. Hewlett-Packard provided funding for 1.6 integration and
  34. * other compatibility work.
  35. */
  36. #ifndef SRE_RECURSIVE
  37. static char copyright[] =
  38. " SRE 2.2.2 Copyright (c) 1997-2002 by Secret Labs AB ";
  39. #define PY_SSIZE_T_CLEAN
  40. #include "Python.h"
  41. #include "structmember.h" /* offsetof */
  42. #include "sre.h"
  43. #include <ctype.h>
  44. /* name of this module, minus the leading underscore */
  45. #if !defined(SRE_MODULE)
  46. #define SRE_MODULE "sre"
  47. #endif
  48. #define SRE_PY_MODULE "re"
  49. /* defining this one enables tracing */
  50. #undef VERBOSE
  51. #if PY_VERSION_HEX >= 0x01060000
  52. #if PY_VERSION_HEX < 0x02020000 || defined(Py_USING_UNICODE)
  53. /* defining this enables unicode support (default under 1.6a1 and later) */
  54. #define HAVE_UNICODE
  55. #endif
  56. #endif
  57. /* -------------------------------------------------------------------- */
  58. /* optional features */
  59. /* enables fast searching */
  60. #define USE_FAST_SEARCH
  61. /* enables aggressive inlining (always on for Visual C) */
  62. #undef USE_INLINE
  63. /* enables copy/deepcopy handling (work in progress) */
  64. #undef USE_BUILTIN_COPY
  65. #if PY_VERSION_HEX < 0x01060000
  66. #define PyObject_DEL(op) PyMem_DEL((op))
  67. #endif
  68. #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
  69. #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
  70. /* -------------------------------------------------------------------- */
  71. #if defined(_MSC_VER)
  72. #pragma optimize("agtw", on) /* doesn't seem to make much difference... */
  73. #pragma warning(disable: 4710) /* who cares if functions are not inlined ;-) */
  74. /* fastest possible local call under MSVC */
  75. #define LOCAL(type) static __inline type __fastcall
  76. #elif defined(USE_INLINE)
  77. #define LOCAL(type) static inline type
  78. #else
  79. #define LOCAL(type) static type
  80. #endif
  81. /* error codes */
  82. #define SRE_ERROR_ILLEGAL -1 /* illegal opcode */
  83. #define SRE_ERROR_STATE -2 /* illegal state */
  84. #define SRE_ERROR_RECURSION_LIMIT -3 /* runaway recursion */
  85. #define SRE_ERROR_MEMORY -9 /* out of memory */
  86. #define SRE_ERROR_INTERRUPTED -10 /* signal handler raised exception */
  87. #if defined(VERBOSE)
  88. #define TRACE(v) printf v
  89. #else
  90. #define TRACE(v)
  91. #endif
  92. /* -------------------------------------------------------------------- */
  93. /* search engine state */
  94. /* default character predicates (run sre_chars.py to regenerate tables) */
  95. #define SRE_DIGIT_MASK 1
  96. #define SRE_SPACE_MASK 2
  97. #define SRE_LINEBREAK_MASK 4
  98. #define SRE_ALNUM_MASK 8
  99. #define SRE_WORD_MASK 16
  100. /* FIXME: this assumes ASCII. create tables in init_sre() instead */
  101. static char sre_char_info[128] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 2,
  102. 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0,
  103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 25, 25, 25, 25, 25, 25, 25,
  104. 25, 25, 0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  105. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0,
  106. 0, 0, 16, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  107. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 0, 0, 0 };
  108. static char sre_char_lower[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  109. 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
  110. 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
  111. 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
  112. 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
  113. 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  114. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
  115. 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  116. 120, 121, 122, 123, 124, 125, 126, 127 };
  117. #define SRE_IS_DIGIT(ch)\
  118. ((ch) < 128 ? (sre_char_info[(ch)] & SRE_DIGIT_MASK) : 0)
  119. #define SRE_IS_SPACE(ch)\
  120. ((ch) < 128 ? (sre_char_info[(ch)] & SRE_SPACE_MASK) : 0)
  121. #define SRE_IS_LINEBREAK(ch)\
  122. ((ch) < 128 ? (sre_char_info[(ch)] & SRE_LINEBREAK_MASK) : 0)
  123. #define SRE_IS_ALNUM(ch)\
  124. ((ch) < 128 ? (sre_char_info[(ch)] & SRE_ALNUM_MASK) : 0)
  125. #define SRE_IS_WORD(ch)\
  126. ((ch) < 128 ? (sre_char_info[(ch)] & SRE_WORD_MASK) : 0)
  127. static unsigned int sre_lower(unsigned int ch)
  128. {
  129. return ((ch) < 128 ? (unsigned int)sre_char_lower[ch] : ch);
  130. }
  131. /* locale-specific character predicates */
  132. /* !(c & ~N) == (c < N+1) for any unsigned c, this avoids
  133. * warnings when c's type supports only numbers < N+1 */
  134. #define SRE_LOC_IS_DIGIT(ch) (!((ch) & ~255) ? isdigit((ch)) : 0)
  135. #define SRE_LOC_IS_SPACE(ch) (!((ch) & ~255) ? isspace((ch)) : 0)
  136. #define SRE_LOC_IS_LINEBREAK(ch) ((ch) == '\n')
  137. #define SRE_LOC_IS_ALNUM(ch) (!((ch) & ~255) ? isalnum((ch)) : 0)
  138. #define SRE_LOC_IS_WORD(ch) (SRE_LOC_IS_ALNUM((ch)) || (ch) == '_')
  139. static unsigned int sre_lower_locale(unsigned int ch)
  140. {
  141. return ((ch) < 256 ? (unsigned int)tolower((ch)) : ch);
  142. }
  143. /* unicode-specific character predicates */
  144. #if defined(HAVE_UNICODE)
  145. #define SRE_UNI_IS_DIGIT(ch) Py_UNICODE_ISDECIMAL((Py_UNICODE)(ch))
  146. #define SRE_UNI_IS_SPACE(ch) Py_UNICODE_ISSPACE((Py_UNICODE)(ch))
  147. #define SRE_UNI_IS_LINEBREAK(ch) Py_UNICODE_ISLINEBREAK((Py_UNICODE)(ch))
  148. #define SRE_UNI_IS_ALNUM(ch) Py_UNICODE_ISALNUM((Py_UNICODE)(ch))
  149. #define SRE_UNI_IS_WORD(ch) (SRE_UNI_IS_ALNUM((ch)) || (ch) == '_')
  150. static unsigned int sre_lower_unicode(unsigned int ch)
  151. {
  152. return (unsigned int) Py_UNICODE_TOLOWER((Py_UNICODE)(ch));
  153. }
  154. #endif
  155. LOCAL(int)
  156. sre_category(SRE_CODE category, unsigned int ch)
  157. {
  158. switch (category) {
  159. case SRE_CATEGORY_DIGIT:
  160. return SRE_IS_DIGIT(ch);
  161. case SRE_CATEGORY_NOT_DIGIT:
  162. return !SRE_IS_DIGIT(ch);
  163. case SRE_CATEGORY_SPACE:
  164. return SRE_IS_SPACE(ch);
  165. case SRE_CATEGORY_NOT_SPACE:
  166. return !SRE_IS_SPACE(ch);
  167. case SRE_CATEGORY_WORD:
  168. return SRE_IS_WORD(ch);
  169. case SRE_CATEGORY_NOT_WORD:
  170. return !SRE_IS_WORD(ch);
  171. case SRE_CATEGORY_LINEBREAK:
  172. return SRE_IS_LINEBREAK(ch);
  173. case SRE_CATEGORY_NOT_LINEBREAK:
  174. return !SRE_IS_LINEBREAK(ch);
  175. case SRE_CATEGORY_LOC_WORD:
  176. return SRE_LOC_IS_WORD(ch);
  177. case SRE_CATEGORY_LOC_NOT_WORD:
  178. return !SRE_LOC_IS_WORD(ch);
  179. #if defined(HAVE_UNICODE)
  180. case SRE_CATEGORY_UNI_DIGIT:
  181. return SRE_UNI_IS_DIGIT(ch);
  182. case SRE_CATEGORY_UNI_NOT_DIGIT:
  183. return !SRE_UNI_IS_DIGIT(ch);
  184. case SRE_CATEGORY_UNI_SPACE:
  185. return SRE_UNI_IS_SPACE(ch);
  186. case SRE_CATEGORY_UNI_NOT_SPACE:
  187. return !SRE_UNI_IS_SPACE(ch);
  188. case SRE_CATEGORY_UNI_WORD:
  189. return SRE_UNI_IS_WORD(ch);
  190. case SRE_CATEGORY_UNI_NOT_WORD:
  191. return !SRE_UNI_IS_WORD(ch);
  192. case SRE_CATEGORY_UNI_LINEBREAK:
  193. return SRE_UNI_IS_LINEBREAK(ch);
  194. case SRE_CATEGORY_UNI_NOT_LINEBREAK:
  195. return !SRE_UNI_IS_LINEBREAK(ch);
  196. #else
  197. case SRE_CATEGORY_UNI_DIGIT:
  198. return SRE_IS_DIGIT(ch);
  199. case SRE_CATEGORY_UNI_NOT_DIGIT:
  200. return !SRE_IS_DIGIT(ch);
  201. case SRE_CATEGORY_UNI_SPACE:
  202. return SRE_IS_SPACE(ch);
  203. case SRE_CATEGORY_UNI_NOT_SPACE:
  204. return !SRE_IS_SPACE(ch);
  205. case SRE_CATEGORY_UNI_WORD:
  206. return SRE_LOC_IS_WORD(ch);
  207. case SRE_CATEGORY_UNI_NOT_WORD:
  208. return !SRE_LOC_IS_WORD(ch);
  209. case SRE_CATEGORY_UNI_LINEBREAK:
  210. return SRE_IS_LINEBREAK(ch);
  211. case SRE_CATEGORY_UNI_NOT_LINEBREAK:
  212. return !SRE_IS_LINEBREAK(ch);
  213. #endif
  214. }
  215. return 0;
  216. }
  217. /* helpers */
  218. static void
  219. data_stack_dealloc(SRE_STATE* state)
  220. {
  221. if (state->data_stack) {
  222. PyMem_FREE(state->data_stack);
  223. state->data_stack = NULL;
  224. }
  225. state->data_stack_size = state->data_stack_base = 0;
  226. }
  227. static int
  228. data_stack_grow(SRE_STATE* state, Py_ssize_t size)
  229. {
  230. Py_ssize_t minsize, cursize;
  231. minsize = state->data_stack_base+size;
  232. cursize = state->data_stack_size;
  233. if (cursize < minsize) {
  234. void* stack;
  235. cursize = minsize+minsize/4+1024;
  236. TRACE(("allocate/grow stack %d\n", cursize));
  237. stack = PyMem_REALLOC(state->data_stack, cursize);
  238. if (!stack) {
  239. data_stack_dealloc(state);
  240. return SRE_ERROR_MEMORY;
  241. }
  242. state->data_stack = (char *)stack;
  243. state->data_stack_size = cursize;
  244. }
  245. return 0;
  246. }
  247. /* generate 8-bit version */
  248. #define SRE_CHAR unsigned char
  249. #define SRE_AT sre_at
  250. #define SRE_COUNT sre_count
  251. #define SRE_CHARSET sre_charset
  252. #define SRE_INFO sre_info
  253. #define SRE_MATCH sre_match
  254. #define SRE_MATCH_CONTEXT sre_match_context
  255. #define SRE_SEARCH sre_search
  256. #define SRE_LITERAL_TEMPLATE sre_literal_template
  257. #if defined(HAVE_UNICODE)
  258. #define SRE_RECURSIVE
  259. #include "_sre.c"
  260. #undef SRE_RECURSIVE
  261. #undef SRE_LITERAL_TEMPLATE
  262. #undef SRE_SEARCH
  263. #undef SRE_MATCH
  264. #undef SRE_MATCH_CONTEXT
  265. #undef SRE_INFO
  266. #undef SRE_CHARSET
  267. #undef SRE_COUNT
  268. #undef SRE_AT
  269. #undef SRE_CHAR
  270. /* generate 16-bit unicode version */
  271. #define SRE_CHAR Py_UNICODE
  272. #define SRE_AT sre_uat
  273. #define SRE_COUNT sre_ucount
  274. #define SRE_CHARSET sre_ucharset
  275. #define SRE_INFO sre_uinfo
  276. #define SRE_MATCH sre_umatch
  277. #define SRE_MATCH_CONTEXT sre_umatch_context
  278. #define SRE_SEARCH sre_usearch
  279. #define SRE_LITERAL_TEMPLATE sre_uliteral_template
  280. #endif
  281. #endif /* SRE_RECURSIVE */
  282. /* -------------------------------------------------------------------- */
  283. /* String matching engine */
  284. /* the following section is compiled twice, with different character
  285. settings */
  286. LOCAL(int)
  287. SRE_AT(SRE_STATE* state, SRE_CHAR* ptr, SRE_CODE at)
  288. {
  289. /* check if pointer is at given position */
  290. Py_ssize_t thisp, thatp;
  291. switch (at) {
  292. case SRE_AT_BEGINNING:
  293. case SRE_AT_BEGINNING_STRING:
  294. return ((void*) ptr == state->beginning);
  295. case SRE_AT_BEGINNING_LINE:
  296. return ((void*) ptr == state->beginning ||
  297. SRE_IS_LINEBREAK((int) ptr[-1]));
  298. case SRE_AT_END:
  299. return (((void*) (ptr+1) == state->end &&
  300. SRE_IS_LINEBREAK((int) ptr[0])) ||
  301. ((void*) ptr == state->end));
  302. case SRE_AT_END_LINE:
  303. return ((void*) ptr == state->end ||
  304. SRE_IS_LINEBREAK((int) ptr[0]));
  305. case SRE_AT_END_STRING:
  306. return ((void*) ptr == state->end);
  307. case SRE_AT_BOUNDARY:
  308. if (state->beginning == state->end)
  309. return 0;
  310. thatp = ((void*) ptr > state->beginning) ?
  311. SRE_IS_WORD((int) ptr[-1]) : 0;
  312. thisp = ((void*) ptr < state->end) ?
  313. SRE_IS_WORD((int) ptr[0]) : 0;
  314. return thisp != thatp;
  315. case SRE_AT_NON_BOUNDARY:
  316. if (state->beginning == state->end)
  317. return 0;
  318. thatp = ((void*) ptr > state->beginning) ?
  319. SRE_IS_WORD((int) ptr[-1]) : 0;
  320. thisp = ((void*) ptr < state->end) ?
  321. SRE_IS_WORD((int) ptr[0]) : 0;
  322. return thisp == thatp;
  323. case SRE_AT_LOC_BOUNDARY:
  324. if (state->beginning == state->end)
  325. return 0;
  326. thatp = ((void*) ptr > state->beginning) ?
  327. SRE_LOC_IS_WORD((int) ptr[-1]) : 0;
  328. thisp = ((void*) ptr < state->end) ?
  329. SRE_LOC_IS_WORD((int) ptr[0]) : 0;
  330. return thisp != thatp;
  331. case SRE_AT_LOC_NON_BOUNDARY:
  332. if (state->beginning == state->end)
  333. return 0;
  334. thatp = ((void*) ptr > state->beginning) ?
  335. SRE_LOC_IS_WORD((int) ptr[-1]) : 0;
  336. thisp = ((void*) ptr < state->end) ?
  337. SRE_LOC_IS_WORD((int) ptr[0]) : 0;
  338. return thisp == thatp;
  339. #if defined(HAVE_UNICODE)
  340. case SRE_AT_UNI_BOUNDARY:
  341. if (state->beginning == state->end)
  342. return 0;
  343. thatp = ((void*) ptr > state->beginning) ?
  344. SRE_UNI_IS_WORD((int) ptr[-1]) : 0;
  345. thisp = ((void*) ptr < state->end) ?
  346. SRE_UNI_IS_WORD((int) ptr[0]) : 0;
  347. return thisp != thatp;
  348. case SRE_AT_UNI_NON_BOUNDARY:
  349. if (state->beginning == state->end)
  350. return 0;
  351. thatp = ((void*) ptr > state->beginning) ?
  352. SRE_UNI_IS_WORD((int) ptr[-1]) : 0;
  353. thisp = ((void*) ptr < state->end) ?
  354. SRE_UNI_IS_WORD((int) ptr[0]) : 0;
  355. return thisp == thatp;
  356. #endif
  357. }
  358. return 0;
  359. }
  360. LOCAL(int)
  361. SRE_CHARSET(SRE_CODE* set, SRE_CODE ch)
  362. {
  363. /* check if character is a member of the given set */
  364. int ok = 1;
  365. for (;;) {
  366. switch (*set++) {
  367. case SRE_OP_FAILURE:
  368. return !ok;
  369. case SRE_OP_LITERAL:
  370. /* <LITERAL> <code> */
  371. if (ch == set[0])
  372. return ok;
  373. set++;
  374. break;
  375. case SRE_OP_CATEGORY:
  376. /* <CATEGORY> <code> */
  377. if (sre_category(set[0], (int) ch))
  378. return ok;
  379. set += 1;
  380. break;
  381. case SRE_OP_CHARSET:
  382. if (sizeof(SRE_CODE) == 2) {
  383. /* <CHARSET> <bitmap> (16 bits per code word) */
  384. if (ch < 256 && (set[ch >> 4] & (1 << (ch & 15))))
  385. return ok;
  386. set += 16;
  387. }
  388. else {
  389. /* <CHARSET> <bitmap> (32 bits per code word) */
  390. if (ch < 256 && (set[ch >> 5] & (1 << (ch & 31))))
  391. return ok;
  392. set += 8;
  393. }
  394. break;
  395. case SRE_OP_RANGE:
  396. /* <RANGE> <lower> <upper> */
  397. if (set[0] <= ch && ch <= set[1])
  398. return ok;
  399. set += 2;
  400. break;
  401. case SRE_OP_NEGATE:
  402. ok = !ok;
  403. break;
  404. case SRE_OP_BIGCHARSET:
  405. /* <BIGCHARSET> <blockcount> <256 blockindices> <blocks> */
  406. {
  407. Py_ssize_t count, block;
  408. count = *(set++);
  409. if (sizeof(SRE_CODE) == 2) {
  410. block = ((unsigned char*)set)[ch >> 8];
  411. set += 128;
  412. if (set[block*16 + ((ch & 255)>>4)] & (1 << (ch & 15)))
  413. return ok;
  414. set += count*16;
  415. }
  416. else {
  417. /* !(c & ~N) == (c < N+1) for any unsigned c, this avoids
  418. * warnings when c's type supports only numbers < N+1 */
  419. if (!(ch & ~65535))
  420. block = ((unsigned char*)set)[ch >> 8];
  421. else
  422. block = -1;
  423. set += 64;
  424. if (block >=0 &&
  425. (set[block*8 + ((ch & 255)>>5)] & (1 << (ch & 31))))
  426. return ok;
  427. set += count*8;
  428. }
  429. break;
  430. }
  431. default:
  432. /* internal error -- there's not much we can do about it
  433. here, so let's just pretend it didn't match... */
  434. return 0;
  435. }
  436. }
  437. }
  438. LOCAL(Py_ssize_t) SRE_MATCH(SRE_STATE* state, SRE_CODE* pattern);
  439. LOCAL(Py_ssize_t)
  440. SRE_COUNT(SRE_STATE* state, SRE_CODE* pattern, Py_ssize_t maxcount)
  441. {
  442. SRE_CODE chr;
  443. SRE_CHAR* ptr = (SRE_CHAR *)state->ptr;
  444. SRE_CHAR* end = (SRE_CHAR *)state->end;
  445. Py_ssize_t i;
  446. /* adjust end */
  447. if (maxcount < end - ptr && maxcount != 65535)
  448. end = ptr + maxcount;
  449. switch (pattern[0]) {
  450. case SRE_OP_IN:
  451. /* repeated set */
  452. TRACE(("|%p|%p|COUNT IN\n", pattern, ptr));
  453. while (ptr < end && SRE_CHARSET(pattern + 2, *ptr))
  454. ptr++;
  455. break;
  456. case SRE_OP_ANY:
  457. /* repeated dot wildcard. */
  458. TRACE(("|%p|%p|COUNT ANY\n", pattern, ptr));
  459. while (ptr < end && !SRE_IS_LINEBREAK(*ptr))
  460. ptr++;
  461. break;
  462. case SRE_OP_ANY_ALL:
  463. /* repeated dot wildcard. skip to the end of the target
  464. string, and backtrack from there */
  465. TRACE(("|%p|%p|COUNT ANY_ALL\n", pattern, ptr));
  466. ptr = end;
  467. break;
  468. case SRE_OP_LITERAL:
  469. /* repeated literal */
  470. chr = pattern[1];
  471. TRACE(("|%p|%p|COUNT LITERAL %d\n", pattern, ptr, chr));
  472. while (ptr < end && (SRE_CODE) *ptr == chr)
  473. ptr++;
  474. break;
  475. case SRE_OP_LITERAL_IGNORE:
  476. /* repeated literal */
  477. chr = pattern[1];
  478. TRACE(("|%p|%p|COUNT LITERAL_IGNORE %d\n", pattern, ptr, chr));
  479. while (ptr < end && (SRE_CODE) state->lower(*ptr) == chr)
  480. ptr++;
  481. break;
  482. case SRE_OP_NOT_LITERAL:
  483. /* repeated non-literal */
  484. chr = pattern[1];
  485. TRACE(("|%p|%p|COUNT NOT_LITERAL %d\n", pattern, ptr, chr));
  486. while (ptr < end && (SRE_CODE) *ptr != chr)
  487. ptr++;
  488. break;
  489. case SRE_OP_NOT_LITERAL_IGNORE:
  490. /* repeated non-literal */
  491. chr = pattern[1];
  492. TRACE(("|%p|%p|COUNT NOT_LITERAL_IGNORE %d\n", pattern, ptr, chr));
  493. while (ptr < end && (SRE_CODE) state->lower(*ptr) != chr)
  494. ptr++;
  495. break;
  496. default:
  497. /* repeated single character pattern */
  498. TRACE(("|%p|%p|COUNT SUBPATTERN\n", pattern, ptr));
  499. while ((SRE_CHAR*) state->ptr < end) {
  500. i = SRE_MATCH(state, pattern);
  501. if (i < 0)
  502. return i;
  503. if (!i)
  504. break;
  505. }
  506. TRACE(("|%p|%p|COUNT %d\n", pattern, ptr,
  507. (SRE_CHAR*) state->ptr - ptr));
  508. return (SRE_CHAR*) state->ptr - ptr;
  509. }
  510. TRACE(("|%p|%p|COUNT %d\n", pattern, ptr, ptr - (SRE_CHAR*) state->ptr));
  511. return ptr - (SRE_CHAR*) state->ptr;
  512. }
  513. #if 0 /* not used in this release */
  514. LOCAL(int)
  515. SRE_INFO(SRE_STATE* state, SRE_CODE* pattern)
  516. {
  517. /* check if an SRE_OP_INFO block matches at the current position.
  518. returns the number of SRE_CODE objects to skip if successful, 0
  519. if no match */
  520. SRE_CHAR* end = state->end;
  521. SRE_CHAR* ptr = state->ptr;
  522. Py_ssize_t i;
  523. /* check minimal length */
  524. if (pattern[3] && (end - ptr) < pattern[3])
  525. return 0;
  526. /* check known prefix */
  527. if (pattern[2] & SRE_INFO_PREFIX && pattern[5] > 1) {
  528. /* <length> <skip> <prefix data> <overlap data> */
  529. for (i = 0; i < pattern[5]; i++)
  530. if ((SRE_CODE) ptr[i] != pattern[7 + i])
  531. return 0;
  532. return pattern[0] + 2 * pattern[6];
  533. }
  534. return pattern[0];
  535. }
  536. #endif
  537. /* The macros below should be used to protect recursive SRE_MATCH()
  538. * calls that *failed* and do *not* return immediately (IOW, those
  539. * that will backtrack). Explaining:
  540. *
  541. * - Recursive SRE_MATCH() returned true: that's usually a success
  542. * (besides atypical cases like ASSERT_NOT), therefore there's no
  543. * reason to restore lastmark;
  544. *
  545. * - Recursive SRE_MATCH() returned false but the current SRE_MATCH()
  546. * is returning to the caller: If the current SRE_MATCH() is the
  547. * top function of the recursion, returning false will be a matching
  548. * failure, and it doesn't matter where lastmark is pointing to.
  549. * If it's *not* the top function, it will be a recursive SRE_MATCH()
  550. * failure by itself, and the calling SRE_MATCH() will have to deal
  551. * with the failure by the same rules explained here (it will restore
  552. * lastmark by itself if necessary);
  553. *
  554. * - Recursive SRE_MATCH() returned false, and will continue the
  555. * outside 'for' loop: must be protected when breaking, since the next
  556. * OP could potentially depend on lastmark;
  557. *
  558. * - Recursive SRE_MATCH() returned false, and will be called again
  559. * inside a local for/while loop: must be protected between each
  560. * loop iteration, since the recursive SRE_MATCH() could do anything,
  561. * and could potentially depend on lastmark.
  562. *
  563. * For more information, check the discussion at SF patch #712900.
  564. */
  565. #define LASTMARK_SAVE() \
  566. do { \
  567. ctx->lastmark = state->lastmark; \
  568. ctx->lastindex = state->lastindex; \
  569. } while (0)
  570. #define LASTMARK_RESTORE() \
  571. do { \
  572. state->lastmark = ctx->lastmark; \
  573. state->lastindex = ctx->lastindex; \
  574. } while (0)
  575. #define RETURN_ERROR(i) do { return i; } while(0)
  576. #define RETURN_FAILURE do { ret = 0; goto exit; } while(0)
  577. #define RETURN_SUCCESS do { ret = 1; goto exit; } while(0)
  578. #define RETURN_ON_ERROR(i) \
  579. do { if (i < 0) RETURN_ERROR(i); } while (0)
  580. #define RETURN_ON_SUCCESS(i) \
  581. do { RETURN_ON_ERROR(i); if (i > 0) RETURN_SUCCESS; } while (0)
  582. #define RETURN_ON_FAILURE(i) \
  583. do { RETURN_ON_ERROR(i); if (i == 0) RETURN_FAILURE; } while (0)
  584. #define SFY(x) #x
  585. #define DATA_STACK_ALLOC(state, type, ptr) \
  586. do { \
  587. alloc_pos = state->data_stack_base; \
  588. TRACE(("allocating %s in %d (%d)\n", \
  589. SFY(type), alloc_pos, sizeof(type))); \
  590. if (state->data_stack_size < alloc_pos+sizeof(type)) { \
  591. int j = data_stack_grow(state, sizeof(type)); \
  592. if (j < 0) return j; \
  593. if (ctx_pos != -1) \
  594. DATA_STACK_LOOKUP_AT(state, SRE_MATCH_CONTEXT, ctx, ctx_pos); \
  595. } \
  596. ptr = (type*)(state->data_stack+alloc_pos); \
  597. state->data_stack_base += sizeof(type); \
  598. } while (0)
  599. #define DATA_STACK_LOOKUP_AT(state, type, ptr, pos) \
  600. do { \
  601. TRACE(("looking up %s at %d\n", SFY(type), pos)); \
  602. ptr = (type*)(state->data_stack+pos); \
  603. } while (0)
  604. #define DATA_STACK_PUSH(state, data, size) \
  605. do { \
  606. TRACE(("copy data in %p to %d (%d)\n", \
  607. data, state->data_stack_base, size)); \
  608. if (state->data_stack_size < state->data_stack_base+size) { \
  609. int j = data_stack_grow(state, size); \
  610. if (j < 0) return j; \
  611. if (ctx_pos != -1) \
  612. DATA_STACK_LOOKUP_AT(state, SRE_MATCH_CONTEXT, ctx, ctx_pos); \
  613. } \
  614. memcpy(state->data_stack+state->data_stack_base, data, size); \
  615. state->data_stack_base += size; \
  616. } while (0)
  617. #define DATA_STACK_POP(state, data, size, discard) \
  618. do { \
  619. TRACE(("copy data to %p from %d (%d)\n", \
  620. data, state->data_stack_base-size, size)); \
  621. memcpy(data, state->data_stack+state->data_stack_base-size, size); \
  622. if (discard) \
  623. state->data_stack_base -= size; \
  624. } while (0)
  625. #define DATA_STACK_POP_DISCARD(state, size) \
  626. do { \
  627. TRACE(("discard data from %d (%d)\n", \
  628. state->data_stack_base-size, size)); \
  629. state->data_stack_base -= size; \
  630. } while(0)
  631. #define DATA_PUSH(x) \
  632. DATA_STACK_PUSH(state, (x), sizeof(*(x)))
  633. #define DATA_POP(x) \
  634. DATA_STACK_POP(state, (x), sizeof(*(x)), 1)
  635. #define DATA_POP_DISCARD(x) \
  636. DATA_STACK_POP_DISCARD(state, sizeof(*(x)))
  637. #define DATA_ALLOC(t,p) \
  638. DATA_STACK_ALLOC(state, t, p)
  639. #define DATA_LOOKUP_AT(t,p,pos) \
  640. DATA_STACK_LOOKUP_AT(state,t,p,pos)
  641. #define MARK_PUSH(lastmark) \
  642. do if (lastmark > 0) { \
  643. i = lastmark; /* ctx->lastmark may change if reallocated */ \
  644. DATA_STACK_PUSH(state, state->mark, (i+1)*sizeof(void*)); \
  645. } while (0)
  646. #define MARK_POP(lastmark) \
  647. do if (lastmark > 0) { \
  648. DATA_STACK_POP(state, state->mark, (lastmark+1)*sizeof(void*), 1); \
  649. } while (0)
  650. #define MARK_POP_KEEP(lastmark) \
  651. do if (lastmark > 0) { \
  652. DATA_STACK_POP(state, state->mark, (lastmark+1)*sizeof(void*), 0); \
  653. } while (0)
  654. #define MARK_POP_DISCARD(lastmark) \
  655. do if (lastmark > 0) { \
  656. DATA_STACK_POP_DISCARD(state, (lastmark+1)*sizeof(void*)); \
  657. } while (0)
  658. #define JUMP_NONE 0
  659. #define JUMP_MAX_UNTIL_1 1
  660. #define JUMP_MAX_UNTIL_2 2
  661. #define JUMP_MAX_UNTIL_3 3
  662. #define JUMP_MIN_UNTIL_1 4
  663. #define JUMP_MIN_UNTIL_2 5
  664. #define JUMP_MIN_UNTIL_3 6
  665. #define JUMP_REPEAT 7
  666. #define JUMP_REPEAT_ONE_1 8
  667. #define JUMP_REPEAT_ONE_2 9
  668. #define JUMP_MIN_REPEAT_ONE 10
  669. #define JUMP_BRANCH 11
  670. #define JUMP_ASSERT 12
  671. #define JUMP_ASSERT_NOT 13
  672. #define DO_JUMP(jumpvalue, jumplabel, nextpattern) \
  673. DATA_ALLOC(SRE_MATCH_CONTEXT, nextctx); \
  674. nextctx->last_ctx_pos = ctx_pos; \
  675. nextctx->jump = jumpvalue; \
  676. nextctx->pattern = nextpattern; \
  677. ctx_pos = alloc_pos; \
  678. ctx = nextctx; \
  679. goto entrance; \
  680. jumplabel: \
  681. while (0) /* gcc doesn't like labels at end of scopes */ \
  682. typedef struct {
  683. Py_ssize_t last_ctx_pos;
  684. Py_ssize_t jump;
  685. SRE_CHAR* ptr;
  686. SRE_CODE* pattern;
  687. Py_ssize_t count;
  688. Py_ssize_t lastmark;
  689. Py_ssize_t lastindex;
  690. union {
  691. SRE_CODE chr;
  692. SRE_REPEAT* rep;
  693. } u;
  694. } SRE_MATCH_CONTEXT;
  695. /* check if string matches the given pattern. returns <0 for
  696. error, 0 for failure, and 1 for success */
  697. LOCAL(Py_ssize_t)
  698. SRE_MATCH(SRE_STATE* state, SRE_CODE* pattern)
  699. {
  700. SRE_CHAR* end = (SRE_CHAR *)state->end;
  701. Py_ssize_t alloc_pos, ctx_pos = -1;
  702. Py_ssize_t i, ret = 0;
  703. Py_ssize_t jump;
  704. unsigned int sigcount=0;
  705. SRE_MATCH_CONTEXT* ctx;
  706. SRE_MATCH_CONTEXT* nextctx;
  707. TRACE(("|%p|%p|ENTER\n", pattern, state->ptr));
  708. DATA_ALLOC(SRE_MATCH_CONTEXT, ctx);
  709. ctx->last_ctx_pos = -1;
  710. ctx->jump = JUMP_NONE;
  711. ctx->pattern = pattern;
  712. ctx_pos = alloc_pos;
  713. entrance:
  714. ctx->ptr = (SRE_CHAR *)state->ptr;
  715. if (ctx->pattern[0] == SRE_OP_INFO) {
  716. /* optimization info block */
  717. /* <INFO> <1=skip> <2=flags> <3=min> ... */
  718. if (ctx->pattern[3] && (end - ctx->ptr) < ctx->pattern[3]) {
  719. TRACE(("reject (got %d chars, need %d)\n",
  720. (end - ctx->ptr), ctx->pattern[3]));
  721. RETURN_FAILURE;
  722. }
  723. ctx->pattern += ctx->pattern[1] + 1;
  724. }
  725. for (;;) {
  726. ++sigcount;
  727. if ((0 == (sigcount & 0xfff)) && PyErr_CheckSignals())
  728. RETURN_ERROR(SRE_ERROR_INTERRUPTED);
  729. switch (*ctx->pattern++) {
  730. case SRE_OP_MARK:
  731. /* set mark */
  732. /* <MARK> <gid> */
  733. TRACE(("|%p|%p|MARK %d\n", ctx->pattern,
  734. ctx->ptr, ctx->pattern[0]));
  735. i = ctx->pattern[0];
  736. if (i & 1)
  737. state->lastindex = i/2 + 1;
  738. if (i > state->lastmark) {
  739. /* state->lastmark is the highest valid index in the
  740. state->mark array. If it is increased by more than 1,
  741. the intervening marks must be set to NULL to signal
  742. that these marks have not been encountered. */
  743. Py_ssize_t j = state->lastmark + 1;
  744. while (j < i)
  745. state->mark[j++] = NULL;
  746. state->lastmark = i;
  747. }
  748. state->mark[i] = ctx->ptr;
  749. ctx->pattern++;
  750. break;
  751. case SRE_OP_LITERAL:
  752. /* match literal string */
  753. /* <LITERAL> <code> */
  754. TRACE(("|%p|%p|LITERAL %d\n", ctx->pattern,
  755. ctx->ptr, *ctx->pattern));
  756. if (ctx->ptr >= end || (SRE_CODE) ctx->ptr[0] != ctx->pattern[0])
  757. RETURN_FAILURE;
  758. ctx->pattern++;
  759. ctx->ptr++;
  760. break;
  761. case SRE_OP_NOT_LITERAL:
  762. /* match anything that is not literal character */
  763. /* <NOT_LITERAL> <code> */
  764. TRACE(("|%p|%p|NOT_LITERAL %d\n", ctx->pattern,
  765. ctx->ptr, *ctx->pattern));
  766. if (ctx->ptr >= end || (SRE_CODE) ctx->ptr[0] == ctx->pattern[0])
  767. RETURN_FAILURE;
  768. ctx->pattern++;
  769. ctx->ptr++;
  770. break;
  771. case SRE_OP_SUCCESS:
  772. /* end of pattern */
  773. TRACE(("|%p|%p|SUCCESS\n", ctx->pattern, ctx->ptr));
  774. state->ptr = ctx->ptr;
  775. RETURN_SUCCESS;
  776. case SRE_OP_AT:
  777. /* match at given position */
  778. /* <AT> <code> */
  779. TRACE(("|%p|%p|AT %d\n", ctx->pattern, ctx->ptr, *ctx->pattern));
  780. if (!SRE_AT(state, ctx->ptr, *ctx->pattern))
  781. RETURN_FAILURE;
  782. ctx->pattern++;
  783. break;
  784. case SRE_OP_CATEGORY:
  785. /* match at given category */
  786. /* <CATEGORY> <code> */
  787. TRACE(("|%p|%p|CATEGORY %d\n", ctx->pattern,
  788. ctx->ptr, *ctx->pattern));
  789. if (ctx->ptr >= end || !sre_category(ctx->pattern[0], ctx->ptr[0]))
  790. RETURN_FAILURE;
  791. ctx->pattern++;
  792. ctx->ptr++;
  793. break;
  794. case SRE_OP_ANY:
  795. /* match anything (except a newline) */
  796. /* <ANY> */
  797. TRACE(("|%p|%p|ANY\n", ctx->pattern, ctx->ptr));
  798. if (ctx->ptr >= end || SRE_IS_LINEBREAK(ctx->ptr[0]))
  799. RETURN_FAILURE;
  800. ctx->ptr++;
  801. break;
  802. case SRE_OP_ANY_ALL:
  803. /* match anything */
  804. /* <ANY_ALL> */
  805. TRACE(("|%p|%p|ANY_ALL\n", ctx->pattern, ctx->ptr));
  806. if (ctx->ptr >= end)
  807. RETURN_FAILURE;
  808. ctx->ptr++;
  809. break;
  810. case SRE_OP_IN:
  811. /* match set member (or non_member) */
  812. /* <IN> <skip> <set> */
  813. TRACE(("|%p|%p|IN\n", ctx->pattern, ctx->ptr));
  814. if (ctx->ptr >= end || !SRE_CHARSET(ctx->pattern + 1, *ctx->ptr))
  815. RETURN_FAILURE;
  816. ctx->pattern += ctx->pattern[0];
  817. ctx->ptr++;
  818. break;
  819. case SRE_OP_LITERAL_IGNORE:
  820. TRACE(("|%p|%p|LITERAL_IGNORE %d\n",
  821. ctx->pattern, ctx->ptr, ctx->pattern[0]));
  822. if (ctx->ptr >= end ||
  823. state->lower(*ctx->ptr) != state->lower(*ctx->pattern))
  824. RETURN_FAILURE;
  825. ctx->pattern++;
  826. ctx->ptr++;
  827. break;
  828. case SRE_OP_NOT_LITERAL_IGNORE:
  829. TRACE(("|%p|%p|NOT_LITERAL_IGNORE %d\n",
  830. ctx->pattern, ctx->ptr, *ctx->pattern));
  831. if (ctx->ptr >= end ||
  832. state->lower(*ctx->ptr) == state->lower(*ctx->pattern))
  833. RETURN_FAILURE;
  834. ctx->pattern++;
  835. ctx->ptr++;
  836. break;
  837. case SRE_OP_IN_IGNORE:
  838. TRACE(("|%p|%p|IN_IGNORE\n", ctx->pattern, ctx->ptr));
  839. if (ctx->ptr >= end
  840. || !SRE_CHARSET(ctx->pattern+1,
  841. (SRE_CODE)state->lower(*ctx->ptr)))
  842. RETURN_FAILURE;
  843. ctx->pattern += ctx->pattern[0];
  844. ctx->ptr++;
  845. break;
  846. case SRE_OP_JUMP:
  847. case SRE_OP_INFO:
  848. /* jump forward */
  849. /* <JUMP> <offset> */
  850. TRACE(("|%p|%p|JUMP %d\n", ctx->pattern,
  851. ctx->ptr, ctx->pattern[0]));
  852. ctx->pattern += ctx->pattern[0];
  853. break;
  854. case SRE_OP_BRANCH:
  855. /* alternation */
  856. /* <BRANCH> <0=skip> code <JUMP> ... <NULL> */
  857. TRACE(("|%p|%p|BRANCH\n", ctx->pattern, ctx->ptr));
  858. LASTMARK_SAVE();
  859. ctx->u.rep = state->repeat;
  860. if (ctx->u.rep)
  861. MARK_PUSH(ctx->lastmark);
  862. for (; ctx->pattern[0]; ctx->pattern += ctx->pattern[0]) {
  863. if (ctx->pattern[1] == SRE_OP_LITERAL &&
  864. (ctx->ptr >= end ||
  865. (SRE_CODE) *ctx->ptr != ctx->pattern[2]))
  866. continue;
  867. if (ctx->pattern[1] == SRE_OP_IN &&
  868. (ctx->ptr >= end ||
  869. !SRE_CHARSET(ctx->pattern + 3, (SRE_CODE) *ctx->ptr)))
  870. continue;
  871. state->ptr = ctx->ptr;
  872. DO_JUMP(JUMP_BRANCH, jump_branch, ctx->pattern+1);
  873. if (ret) {
  874. if (ctx->u.rep)
  875. MARK_POP_DISCARD(ctx->lastmark);
  876. RETURN_ON_ERROR(ret);
  877. RETURN_SUCCESS;
  878. }
  879. if (ctx->u.rep)
  880. MARK_POP_KEEP(ctx->lastmark);
  881. LASTMARK_RESTORE();
  882. }
  883. if (ctx->u.rep)
  884. MARK_POP_DISCARD(ctx->lastmark);
  885. RETURN_FAILURE;
  886. case SRE_OP_REPEAT_ONE:
  887. /* match repeated sequence (maximizing regexp) */
  888. /* this operator only works if the repeated item is
  889. exactly one character wide, and we're not already
  890. collecting backtracking points. for other cases,
  891. use the MAX_REPEAT operator */
  892. /* <REPEAT_ONE> <skip> <1=min> <2=max> item <SUCCESS> tail */
  893. TRACE(("|%p|%p|REPEAT_ONE %d %d\n", ctx->pattern, ctx->ptr,
  894. ctx->pattern[1], ctx->pattern[2]));
  895. if (ctx->ptr + ctx->pattern[1] > end)
  896. RETURN_FAILURE; /* cannot match */
  897. state->ptr = ctx->ptr;
  898. ret = SRE_COUNT(state, ctx->pattern+3, ctx->pattern[2]);
  899. RETURN_ON_ERROR(ret);
  900. DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos);
  901. ctx->count = ret;
  902. ctx->ptr += ctx->count;
  903. /* when we arrive here, count contains the number of
  904. matches, and ctx->ptr points to the tail of the target
  905. string. check if the rest of the pattern matches,
  906. and backtrack if not. */
  907. if (ctx->count < (Py_ssize_t) ctx->pattern[1])
  908. RETURN_FAILURE;
  909. if (ctx->pattern[ctx->pattern[0]] == SRE_OP_SUCCESS) {
  910. /* tail is empty. we're finished */
  911. state->ptr = ctx->ptr;
  912. RETURN_SUCCESS;
  913. }
  914. LASTMARK_SAVE();
  915. if (ctx->pattern[ctx->pattern[0]] == SRE_OP_LITERAL) {
  916. /* tail starts with a literal. skip positions where
  917. the rest of the pattern cannot possibly match */
  918. ctx->u.chr = ctx->pattern[ctx->pattern[0]+1];
  919. for (;;) {
  920. while (ctx->count >= (Py_ssize_t) ctx->pattern[1] &&
  921. (ctx->ptr >= end || *ctx->ptr != ctx->u.chr)) {
  922. ctx->ptr--;
  923. ctx->count--;
  924. }
  925. if (ctx->count < (Py_ssize_t) ctx->pattern[1])
  926. break;
  927. state->ptr = ctx->ptr;
  928. DO_JUMP(JUMP_REPEAT_ONE_1, jump_repeat_one_1,
  929. ctx->pattern+ctx->pattern[0]);
  930. if (ret) {
  931. RETURN_ON_ERROR(ret);
  932. RETURN_SUCCESS;
  933. }
  934. LASTMARK_RESTORE();
  935. ctx->ptr--;
  936. ctx->count--;
  937. }
  938. } else {
  939. /* general case */
  940. while (ctx->count >= (Py_ssize_t) ctx->pattern[1]) {
  941. state->ptr = ctx->ptr;
  942. DO_JUMP(JUMP_REPEAT_ONE_2, jump_repeat_one_2,
  943. ctx->pattern+ctx->pattern[0]);
  944. if (ret) {
  945. RETURN_ON_ERROR(ret);
  946. RETURN_SUCCESS;
  947. }
  948. ctx->ptr--;
  949. ctx->count--;
  950. LASTMARK_RESTORE();
  951. }
  952. }
  953. RETURN_FAILURE;
  954. case SRE_OP_MIN_REPEAT_ONE:
  955. /* match repeated sequence (minimizing regexp) */
  956. /* this operator only works if the repeated item is
  957. exactly one character wide, and we're not already
  958. collecting backtracking points. for other cases,
  959. use the MIN_REPEAT operator */
  960. /* <MIN_REPEAT_ONE> <skip> <1=min> <2=max> item <SUCCESS> tail */
  961. TRACE(("|%p|%p|MIN_REPEAT_ONE %d %d\n", ctx->pattern, ctx->ptr,
  962. ctx->pattern[1], ctx->pattern[2]));
  963. if (ctx->ptr + ctx->pattern[1] > end)
  964. RETURN_FAILURE; /* cannot match */
  965. state->ptr = ctx->ptr;
  966. if (ctx->pattern[1] == 0)
  967. ctx->count = 0;
  968. else {
  969. /* count using pattern min as the maximum */
  970. ret = SRE_COUNT(state, ctx->pattern+3, ctx->pattern[1]);
  971. RETURN_ON_ERROR(ret);
  972. DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos);
  973. if (ret < (Py_ssize_t) ctx->pattern[1])
  974. /* didn't match minimum number of times */
  975. RETURN_FAILURE;
  976. /* advance past minimum matches of repeat */
  977. ctx->count = ret;
  978. ctx->ptr += ctx->count;
  979. }
  980. if (ctx->pattern[ctx->pattern[0]] == SRE_OP_SUCCESS) {
  981. /* tail is empty. we're finished */
  982. state->ptr = ctx->ptr;
  983. RETURN_SUCCESS;
  984. } else {
  985. /* general case */
  986. LASTMARK_SAVE();
  987. while ((Py_ssize_t)ctx->pattern[2] == 65535
  988. || ctx->count <= (Py_ssize_t)ctx->pattern[2]) {
  989. state->ptr = ctx->ptr;
  990. DO_JUMP(JUMP_MIN_REPEAT_ONE,jump_min_repeat_one,
  991. ctx->pattern+ctx->pattern[0]);
  992. if (ret) {
  993. RETURN_ON_ERROR(ret);
  994. RETURN_SUCCESS;
  995. }
  996. state->ptr = ctx->ptr;
  997. ret = SRE_COUNT(state, ctx->pattern+3, 1);
  998. RETURN_ON_ERROR(ret);
  999. DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos);
  1000. if (ret == 0)
  1001. break;
  1002. assert(ret == 1);
  1003. ctx->ptr++;
  1004. ctx->count++;
  1005. LASTMARK_RESTORE();
  1006. }
  1007. }
  1008. RETURN_FAILURE;
  1009. case SRE_OP_REPEAT:
  1010. /* create repeat context. all the hard work is done
  1011. by the UNTIL operator (MAX_UNTIL, MIN_UNTIL) */
  1012. /* <REPEAT> <skip> <1=min> <2=max> item <UNTIL> tail */
  1013. TRACE(("|%p|%p|REPEAT %d %d\n", ctx->pattern, ctx->ptr,
  1014. ctx->pattern[1], ctx->pattern[2]));
  1015. /* install new repeat context */
  1016. ctx->u.rep = (SRE_REPEAT*) PyObject_MALLOC(sizeof(*ctx->u.rep));
  1017. if (!ctx->u.rep) {
  1018. PyErr_NoMemory();
  1019. RETURN_FAILURE;
  1020. }
  1021. ctx->u.rep->count = -1;
  1022. ctx->u.rep->pattern = ctx->pattern;
  1023. ctx->u.rep->prev = state->repeat;
  1024. ctx->u.rep->last_ptr = NULL;
  1025. state->repeat = ctx->u.rep;
  1026. state->ptr = ctx->ptr;
  1027. DO_JUMP(JUMP_REPEAT, jump_repeat, ctx->pattern+ctx->pattern[0]);
  1028. state->repeat = ctx->u.rep->prev;
  1029. PyObject_FREE(ctx->u.rep);
  1030. if (ret) {
  1031. RETURN_ON_ERROR(ret);
  1032. RETURN_SUCCESS;
  1033. }
  1034. RETURN_FAILURE;
  1035. case SRE_OP_MAX_UNTIL:
  1036. /* maximizing repeat */
  1037. /* <REPEAT> <skip> <1=min> <2=max> item <MAX_UNTIL> tail */
  1038. /* FIXME: we probably need to deal with zero-width
  1039. matches in here... */
  1040. ctx->u.rep = state->repeat;
  1041. if (!ctx->u.rep)
  1042. RETURN_ERROR(SRE_ERROR_STATE);
  1043. state->ptr = ctx->ptr;
  1044. ctx->count = ctx->u.rep->count+1;
  1045. TRACE(("|%p|%p|MAX_UNTIL %d\n", ctx->pattern,
  1046. ctx->ptr, ctx->count));
  1047. if (ctx->count < ctx->u.rep->pattern[1]) {
  1048. /* not enough matches */
  1049. ctx->u.rep->count = ctx->count;
  1050. DO_JUMP(JUMP_MAX_UNTIL_1, jump_max_until_1,
  1051. ctx->u.rep->pattern+3);
  1052. if (ret) {
  1053. RETURN_ON_ERROR(ret);
  1054. RETURN_SUCCESS;
  1055. }
  1056. ctx->u.rep->count = ctx->count-1;
  1057. state->ptr = ctx->ptr;
  1058. RETURN_FAILURE;
  1059. }
  1060. if ((ctx->count < ctx->u.rep->pattern[2] ||
  1061. ctx->u.rep->pattern[2] == 65535) &&
  1062. state->ptr != ctx->u.rep->last_ptr) {
  1063. /* we may have enough matches, but if we can
  1064. match another item, do so */
  1065. ctx->u.rep->count = ctx->count;
  1066. LASTMARK_SAVE();
  1067. MARK_PUSH(ctx->lastmark);
  1068. /* zero-width match protection */
  1069. DATA_PUSH(&ctx->u.rep->last_ptr);
  1070. ctx->u.rep->last_ptr = state->ptr;
  1071. DO_JUMP(JUMP_MAX_UNTIL_2, jump_max_until_2,
  1072. ctx->u.rep->pattern+3);
  1073. DATA_POP(&ctx->u.rep->last_ptr);
  1074. if (ret) {
  1075. MARK_POP_DISCARD(ctx->lastmark);
  1076. RETURN_ON_ERROR(ret);
  1077. RETURN_SUCCESS;
  1078. }
  1079. MARK_POP(ctx->lastmark);
  1080. LASTMARK_RESTORE();
  1081. ctx->u.rep->count = ctx->count-1;
  1082. state->ptr = ctx->ptr;
  1083. }
  1084. /* cannot match more repeated items here. make sure the
  1085. tail matches */
  1086. state->repeat = ctx->u.rep->prev;
  1087. DO_JUMP(JUMP_MAX_UNTIL_3, jump_max_until_3, ctx->pattern);
  1088. RETURN_ON_SUCCESS(ret);
  1089. state->repeat = ctx->u.rep;
  1090. state->ptr = ctx->ptr;
  1091. RETURN_FAILURE;
  1092. case SRE_OP_MIN_UNTIL:
  1093. /* minimizing repeat */
  1094. /* <REPEAT> <skip> <1=min> <2=max> item <MIN_UNTIL> tail */
  1095. ctx->u.rep = state->repeat;
  1096. if (!ctx->u.rep)
  1097. RETURN_ERROR(SRE_ERROR_STATE);
  1098. state->ptr = ctx->ptr;
  1099. ctx->count = ctx->u.rep->count+1;
  1100. TRACE(("|%p|%p|MIN_UNTIL %d %p\n", ctx->pattern,
  1101. ctx->ptr, ctx->count, ctx->u.rep->pattern));
  1102. if (ctx->count < ctx->u.rep->pattern[1]) {
  1103. /* not enough matches */
  1104. ctx->u.rep->count = ctx->count;
  1105. DO_JUMP(JUMP_MIN_UNTIL_1, jump_min_until_1,
  1106. ctx->u.rep->pattern+3);
  1107. if (ret) {
  1108. RETURN_ON_ERROR(ret);
  1109. RETURN_SUCCESS;
  1110. }
  1111. ctx->u.rep->count = ctx->count-1;
  1112. state->ptr = ctx->ptr;
  1113. RETURN_FAILURE;
  1114. }
  1115. LASTMARK_SAVE();
  1116. /* see if the tail matches */
  1117. state->repeat = ctx->u.rep->prev;
  1118. DO_JUMP(JUMP_MIN_UNTIL_2, jump_min_until_2, ctx->pattern);
  1119. if (ret) {
  1120. RETURN_ON_ERROR(ret);
  1121. RETURN_SUCCESS;
  1122. }
  1123. state->repeat = ctx->u.rep;
  1124. state->ptr = ctx->ptr;
  1125. LASTMARK_RESTORE();
  1126. if (ctx->count >= ctx->u.rep->pattern[2]
  1127. && ctx->u.rep->pattern[2] != 65535)
  1128. RETURN_FAILURE;
  1129. ctx->u.rep->count = ctx->count;
  1130. DO_JUMP(JUMP_MIN_UNTIL_3,jump_min_until_3,
  1131. ctx->u.rep->pattern+3);
  1132. if (ret) {
  1133. RETURN_ON_ERROR(ret);
  1134. RETURN_SUCCESS;
  1135. }
  1136. ctx->u.rep->count = ctx->count-1;
  1137. state->ptr = ctx->ptr;
  1138. RETURN_FAILURE;
  1139. case SRE_OP_GROUPREF:
  1140. /* match backreference */
  1141. TRACE(("|%p|%p|GROUPREF %d\n", ctx->pattern,
  1142. ctx->ptr, ctx->pattern[0]));
  1143. i = ctx->pattern[0];
  1144. {
  1145. Py_ssize_t groupref = i+i;
  1146. if (groupref >= state->lastmark) {
  1147. RETURN_FAILURE;
  1148. } else {
  1149. SRE_CHAR* p = (SRE_CHAR*) state->mark[groupref];
  1150. SRE_CHAR* e = (SRE_CHAR*) state->mark[groupref+1];
  1151. if (!p || !e || e < p)
  1152. RETURN_FAILURE;
  1153. while (p < e) {
  1154. if (ctx->ptr >= end || *ctx->ptr != *p)
  1155. RETURN_FAILURE;
  1156. p++; ctx->ptr++;
  1157. }
  1158. }
  1159. }
  1160. ctx->pattern++;
  1161. break;
  1162. case SRE_OP_GROUPREF_IGNORE:
  1163. /* match backreference */
  1164. TRACE(("|%p|%p|GROUPREF_IGNORE %d\n", ctx->pattern,
  1165. ctx->ptr, ctx->pattern[0]));
  1166. i = ctx->pattern[0];
  1167. {
  1168. Py_ssize_t groupref = i+i;
  1169. if (groupref >= state->lastmark) {
  1170. RETURN_FAILURE;
  1171. } else {
  1172. SRE_CHAR* p = (SRE_CHAR*) state->mark[groupref];
  1173. SRE_CHAR* e = (SRE_CHAR*) state->mark[groupref+1];
  1174. if (!p || !e || e < p)
  1175. RETURN_FAILURE;
  1176. while (p < e) {
  1177. if (ctx->ptr >= end ||
  1178. state->lower(*ctx->ptr) != state->lower(*p))
  1179. RETURN_FAILURE;
  1180. p++; ctx->ptr++;
  1181. }
  1182. }
  1183. }
  1184. ctx->pattern++;
  1185. break;
  1186. case SRE_OP_GROUPREF_EXISTS:
  1187. TRACE(("|%p|%p|GROUPREF_EXISTS %d\n", ctx->pattern,
  1188. ctx->ptr, ctx->pattern[0]));
  1189. /* <GROUPREF_EXISTS> <group> <skip> codeyes <JUMP> codeno ... */
  1190. i = ctx->pattern[0];
  1191. {
  1192. Py_ssize_t groupref = i+i;
  1193. if (groupref >= state->lastmark) {
  1194. ctx->pattern += ctx->pattern[1];
  1195. break;
  1196. } else {
  1197. SRE_CHAR* p = (SRE_CHAR*) state->mark[groupref];
  1198. SRE_CHAR* e = (SRE_CHAR*) state->mark[groupref+1];
  1199. if (!p || !e || e < p) {
  1200. ctx->pattern += ctx->pattern[1];
  1201. break;
  1202. }
  1203. }
  1204. }
  1205. ctx->pattern += 2;
  1206. break;
  1207. case SRE_OP_ASSERT:
  1208. /* assert subpattern */
  1209. /* <ASSERT> <skip> <back> <pattern> */
  1210. TRACE(("|%p|%p|ASSERT %d\n", ctx->pattern,
  1211. ctx->ptr, ctx->pattern[1]));
  1212. state->ptr = ctx->ptr - ctx->pattern[1];
  1213. if (state->ptr < state->beginning)
  1214. RETURN_FAILURE;
  1215. DO_JUMP(JUMP_ASSERT, jump_assert, ctx->pattern+2);
  1216. RETURN_ON_FAILURE(ret);
  1217. ctx->pattern += ctx->pattern[0];
  1218. break;
  1219. case SRE_OP_ASSERT_NOT:
  1220. /* assert not subpattern */
  1221. /* <ASSERT_NOT> <skip> <back> <pattern> */
  1222. TRACE(("|%p|%p|ASSERT_NOT %d\n", ctx->pattern,
  1223. ctx->ptr, ctx->pattern[1]));
  1224. state->ptr = ctx->ptr - ctx->pattern[1];
  1225. if (state->ptr >= state->beginning) {
  1226. DO_JUMP(JUMP_ASSERT_NOT, jump_assert_not, ctx->pattern+2);
  1227. if (ret) {
  1228. RETURN_ON_ERROR(ret);
  1229. RETURN_FAILURE;
  1230. }
  1231. }
  1232. ctx->pattern += ctx->pattern[0];
  1233. break;
  1234. case SRE_OP_FAILURE:
  1235. /* immediate failure */
  1236. TRACE(("|%p|%p|FAILURE\n", ctx->pattern, ctx->ptr));
  1237. RETURN_FAILURE;
  1238. default:
  1239. TRACE(("|%p|%p|UNKNOWN %d\n", ctx->pattern, ctx->ptr,
  1240. ctx->pattern[-1]));
  1241. RETURN_ERROR(SRE_ERROR_ILLEGAL);
  1242. }
  1243. }
  1244. exit:
  1245. ctx_pos = ctx->last_ctx_pos;
  1246. jump = ctx->jump;
  1247. DATA_POP_DISCARD(ctx);
  1248. if (ctx_pos == -1)
  1249. return ret;
  1250. DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos);
  1251. switch (jump) {
  1252. case JUMP_MAX_UNTIL_2:
  1253. TRACE(("|%p|%p|JUMP_MAX_UNTIL_2\n", ctx->pattern, ctx->ptr));
  1254. goto jump_max_until_2;
  1255. case JUMP_MAX_UNTIL_3:
  1256. TRACE(("|%p|%p|JUMP_MAX_UNTIL_3\n", ctx->pattern, ctx->ptr));
  1257. goto jump_max_until_3;
  1258. case JUMP_MIN_UNTIL_2:
  1259. TRACE(("|%p|%p|JUMP_MIN_UNTIL_2\n", ctx->pattern, ctx->ptr));
  1260. goto jump_min_until_2;
  1261. case JUMP_MIN_UNTIL_3:
  1262. TRACE(("|%p|%p|JUMP_MIN_UNTIL_3\n", ctx->pattern, ctx->ptr));
  1263. goto jump_min_until_3;
  1264. case JUMP_BRANCH:
  1265. TRACE(("|%p|%p|JUMP_BRANCH\n", ctx->pattern, ctx->ptr));
  1266. goto jump_branch;
  1267. case JUMP_MAX_UNTIL_1:
  1268. TRACE(("|%p|%p|JUMP_MAX_UNTIL_1\n", ctx->pattern, ctx->ptr));
  1269. goto jump_max_until_1;
  1270. case JUMP_MIN_UNTIL_1:
  1271. TRACE(("|%p|%p|JUMP_MIN_UNTIL_1\n", ctx->pattern, ctx->ptr));
  1272. goto jump_min_until_1;
  1273. case JUMP_REPEAT:
  1274. TRACE(("|%p|%p|JUMP_REPEAT\n", ctx->pattern, ctx->ptr));
  1275. goto jump_repeat;
  1276. case JUMP_REPEAT_ONE_1:
  1277. TRACE(("|%p|%p|JUMP_REPEAT_ONE_1\n", ctx->pattern, ctx->ptr));
  1278. goto jump_repeat_one_1;
  1279. case JUMP_REPEAT_ONE_2:
  1280. TRACE(("|%p|%p|JUMP_REPEAT_ONE_2\n", ctx->pattern, ctx->ptr));
  1281. goto jump_repeat_one_2;
  1282. case JUMP_MIN_REPEAT_ONE:
  1283. TRACE(("|%p|%p|JUMP_MIN_REPEAT_ONE\n", ctx->pattern, ctx->ptr));
  1284. goto jump_min_repeat_one;
  1285. case JUMP_ASSERT:
  1286. TRACE(("|%p|%p|JUMP_ASSERT\n", ctx->pattern, ctx->ptr));
  1287. goto jump_assert;
  1288. case JUMP_ASSERT_NOT:
  1289. TRACE(("|%p|%p|JUMP_ASSERT_NOT\n", ctx->pattern, ctx->ptr));
  1290. goto jump_assert_not;
  1291. case JUMP_NONE:
  1292. TRACE(("|%p|%p|RETURN %d\n", ctx->pattern, ctx->ptr, ret));
  1293. break;
  1294. }
  1295. return ret; /* should never get here */
  1296. }
  1297. LOCAL(Py_ssize_t)
  1298. SRE_SEARCH(SRE_STATE* state, SRE_CODE* pattern)
  1299. {
  1300. SRE_CHAR* ptr = (SRE_CHAR *)state->start;
  1301. SRE_CHAR* end = (SRE_CHAR *)state->end;
  1302. Py_ssize_t status = 0;
  1303. Py_ssize_t prefix_len = 0;
  1304. Py_ssize_t prefix_skip = 0;
  1305. SRE_CODE* prefix = NULL;
  1306. SRE_CODE* charset = NULL;
  1307. SRE_CODE* overlap = NULL;
  1308. int flags = 0;
  1309. if (pattern[0] == SRE_OP_INFO) {
  1310. /* optimization info block */
  1311. /* <INFO> <1=skip> <2=flags> <3=min> <4=max> <5=prefix info> */
  1312. flags = pattern[2];
  1313. if (pattern[3] > 1) {
  1314. /* adjust end point (but make sure we leave at least one
  1315. character in there, so literal search will work) */
  1316. end -= pattern[3]-1;
  1317. if (end <= ptr)
  1318. end = ptr+1;
  1319. }
  1320. if (flags & SRE_INFO_PREFIX) {
  1321. /* pattern starts with a known prefix */
  1322. /* <length> <skip> <prefix data> <overlap data> */
  1323. prefix_len = pattern[5];
  1324. prefix_skip = pattern[6];
  1325. prefix = pattern + 7;
  1326. overlap = prefix + prefix_len - 1;
  1327. } else if (flags & SRE_INFO_CHARSET)
  1328. /* pattern starts with a character from a known set */
  1329. /* <charset> */
  1330. charset = pattern + 5;
  1331. pattern += 1 + pattern[1];
  1332. }
  1333. TRACE(("prefix = %p %d %d\n", prefix, prefix_len, prefix_skip));
  1334. TRACE(("charset = %p\n", charset));
  1335. #if defined(USE_FAST_SEARCH)
  1336. if (prefix_len > 1) {
  1337. /* pattern starts with a known prefix. use the overlap
  1338. table to skip forward as fast as we possibly can */
  1339. Py_ssize_t i = 0;
  1340. end = (SRE_CHAR *)state->end;
  1341. while (ptr < end) {
  1342. for (;;) {
  1343. if ((SRE_CODE) ptr[0] != prefix[i]) {
  1344. if (!i)
  1345. break;
  1346. else
  1347. i = overlap[i];
  1348. } else {
  1349. if (++i == prefix_len) {
  1350. /* found a potential match */
  1351. TRACE(("|%p|%p|SEARCH SCAN\n", pattern, ptr));
  1352. state->start = ptr + 1 - prefix_len;
  1353. state->ptr = ptr + 1 - prefix_len + prefix_skip;
  1354. if (flags & SRE_INFO_LITERAL)
  1355. return 1; /* we got all of it */
  1356. status = SRE_MATCH(state, pattern + 2*prefix_skip);
  1357. if (status != 0)
  1358. return status;
  1359. /* close but no cigar -- try again */
  1360. i = overlap[i];
  1361. }
  1362. break;
  1363. }
  1364. }
  1365. ptr++;
  1366. }
  1367. return 0;
  1368. }
  1369. #endif
  1370. if (pattern[0] == SRE_OP_LITERAL) {
  1371. /* pattern starts with a literal character. this is used
  1372. for short prefixes, and if fast search is disabled */
  1373. SRE_CODE chr = pattern[1];
  1374. end = (SRE_CHAR *)state->end;
  1375. for (;;) {
  1376. while (ptr < end && (SRE_CODE) ptr[0] != chr)
  1377. ptr++;
  1378. if (ptr >= end)
  1379. return 0;
  1380. TRACE(("|%p|%p|SEARCH LITERAL\n", pattern, ptr));
  1381. state->start = ptr;
  1382. state->ptr = ++ptr;
  1383. if (flags & SRE_INFO_LITERAL)
  1384. return 1; /* we got all of it */
  1385. status = SRE_MATCH(state, pattern + 2);
  1386. if (status != 0)
  1387. break;
  1388. }
  1389. } else if (charset) {
  1390. /* pattern starts with a character from a known set */
  1391. end = (SRE_CHAR *)state->end;
  1392. for (;;) {
  1393. while (ptr < end && !SRE_CHARSET(charset, ptr[0]))
  1394. ptr++;
  1395. if (ptr >= end)
  1396. return 0;
  1397. TRACE(("|%p|%p|SEARCH CHARSET\n", pattern, ptr));
  1398. state->start = ptr;
  1399. state->ptr = ptr;
  1400. status = SRE_MATCH(state, pattern);
  1401. if (status != 0)
  1402. break;
  1403. ptr++;
  1404. }
  1405. } else
  1406. /* general case */
  1407. while (ptr <= end) {
  1408. TRACE(("|%p|%p|SEARCH\n", pattern, ptr));
  1409. state->start = state->ptr = ptr++;
  1410. status = SRE_MATCH(state, pattern);
  1411. if (status != 0)
  1412. break;
  1413. }
  1414. return status;
  1415. }
  1416. LOCAL(int)
  1417. SRE_LITERAL_TEMPLATE(SRE_CHAR* ptr, Py_ssize_t len)
  1418. {
  1419. /* check if given string is a literal template (i.e. no escapes) */
  1420. while (len-- > 0)
  1421. if (*ptr++ == '\\')
  1422. return 0;
  1423. return 1;
  1424. }
  1425. #if !defined(SRE_RECURSIVE)
  1426. /* -------------------------------------------------------------------- */
  1427. /* factories and destructors */
  1428. /* see sre.h for object declarations */
  1429. static PyObject*pattern_new_match(PatternObject*, SRE_STATE*, int);
  1430. static PyObject*pattern_scanner(PatternObject*, PyObject*);
  1431. static PyObject *
  1432. sre_codesize(PyObject* self, PyObject *unused)
  1433. {
  1434. return Py_BuildValue("l", sizeof(SRE_CODE));
  1435. }
  1436. static PyObject *
  1437. sre_getlower(PyObject* self, PyObject* args)
  1438. {
  1439. int character, flags;
  1440. if (!PyArg_ParseTuple(args, "ii", &character, &flags))
  1441. return NULL;
  1442. if (flags & SRE_FLAG_LOCALE)
  1443. return Py_BuildValue("i", sre_lower_locale(character));
  1444. if (flags & SRE_FLAG_UNICODE)
  1445. #if defined(HAVE_UNICODE)
  1446. return Py_BuildValue("i", sre_lower_unicode(character));
  1447. #else
  1448. return Py_BuildValue("i", sre_lower_locale(character));
  1449. #endif
  1450. return Py_BuildValue("i", sre_lower(character));
  1451. }
  1452. LOCAL(void)
  1453. state_reset(SRE_STATE* state)
  1454. {
  1455. /* FIXME: dynamic! */
  1456. /*memset(state->mark, 0, sizeof(*state->mark) * SRE_MARK_SIZE);*/
  1457. state->lastmark = -1;
  1458. state->lastindex = -1;
  1459. state->repeat = NULL;
  1460. data_stack_dealloc(state);
  1461. }
  1462. static void*
  1463. getstring(PyObject* string, Py_ssize_t* p_length, int* p_charsize)
  1464. {
  1465. /* given a python object, return a data pointer, a length (in
  1466. characters), and a character size. return NULL if the object
  1467. is not a string (or not compatible) */
  1468. PyBufferProcs *buffer;
  1469. Py_ssize_t size, bytes;
  1470. int charsize;
  1471. void* ptr;
  1472. #if defined(HAVE_UNICODE)
  1473. if (PyUnicode_Check(string)) {
  1474. /* unicode strings doesn't always support the buffer interface */
  1475. ptr = (void*) PyUnicode_AS_DATA(string);
  1476. bytes = PyUnicode_GET_DATA_SIZE(string);
  1477. size = PyUnicode_GET_SIZE(string);
  1478. charsize = sizeof(Py_UNICODE);
  1479. } else {
  1480. #endif
  1481. /* get pointer to string buffer */
  1482. buffer = Py_TYPE(string)->tp_as_buffer;
  1483. if (!buffer || !buffer->bf_getreadbuffer || !buffer->bf_getsegcount ||
  1484. buffer->bf_getsegcount(string, NULL) != 1) {
  1485. PyErr_SetString(PyExc_TypeError, "expected string or buffer");
  1486. return NULL;
  1487. }
  1488. /* determine buffer size */
  1489. bytes = buffer->bf_getreadbuffer(string, 0, &ptr);
  1490. if (bytes < 0) {
  1491. PyErr_SetString(PyExc_TypeError, "buffer has negative size");
  1492. return NULL;
  1493. }
  1494. /* determine character size */
  1495. #if PY_VERSION_HEX >= 0x01060000
  1496. size = PyObject_Size(string);
  1497. #else
  1498. size = PyObject_Length(string);
  1499. #endif
  1500. if (PyString_Check(string) || bytes == size)
  1501. charsize = 1;
  1502. #if defined(HAVE_UNICODE)
  1503. else if (bytes == (Py_ssize_t) (size * sizeof(Py_UNICODE)))
  1504. charsize = sizeof(Py_UNICODE);
  1505. #endif
  1506. else {
  1507. PyErr_SetString(PyExc_TypeError, "buffer size mismatch");
  1508. return NULL;
  1509. }
  1510. #if defined(HAVE_UNICODE)
  1511. }
  1512. #endif
  1513. *p_length = size;
  1514. *p_charsize = charsize;
  1515. return ptr;
  1516. }
  1517. LOCAL(PyObject*)
  1518. state_init(SRE_STATE* state, PatternObject* pattern, PyObject* string,
  1519. Py_ssize_t start, Py_ssize_t end)
  1520. {
  1521. /* prepare state object */
  1522. Py_ssize_t length;
  1523. int charsize;
  1524. void* ptr;
  1525. memset(state, 0, sizeof(SRE_STATE));
  1526. state->lastmark = -1;
  1527. state->lastindex = -1;
  1528. ptr = getstring(string, &length, &charsize);
  1529. if (!ptr)
  1530. return NULL;
  1531. /* adjust boundaries */
  1532. if (start < 0)
  1533. start = 0;
  1534. else if (start > length)
  1535. start = length;
  1536. if (end < 0)
  1537. end = 0;
  1538. else if (end > length)
  1539. end = length;
  1540. state->charsize = charsize;
  1541. state->beginning = ptr;
  1542. state->start = (void*) ((char*) ptr + start * state->charsize);
  1543. state->end = (void*) ((char*) ptr + end * state->charsize);
  1544. Py_INCREF(string);
  1545. state->string = string;
  1546. state->pos = start;
  1547. state->endpos = end;
  1548. if (pattern->flags & SRE_FLAG_LOCALE)
  1549. state->lower = sre_lower_locale;
  1550. else if (pattern->flags & SRE_FLAG_UNICODE)
  1551. #if defined(HAVE_UNICODE)
  1552. state->lower = sre_lower_unicode;
  1553. #else
  1554. state->lower = sre_lower_locale;
  1555. #endif
  1556. else
  1557. state->lower = sre_lower;
  1558. return string;
  1559. }
  1560. LOCAL(void)
  1561. state_fini(SRE_STATE* state)
  1562. {
  1563. Py_XDECREF(state->string);
  1564. data_stack_dealloc(state);
  1565. }
  1566. /* calculate offset from start of string */
  1567. #define STATE_OFFSET(state, member)\
  1568. (((char*)(member) - (char*)(state)->beginning) / (state)->charsize)
  1569. LOCAL(PyObject*)
  1570. state_getslice(SRE_STATE* state, Py_ssize_t index, PyObject* string, int empty)
  1571. {
  1572. Py_ssize_t i, j;
  1573. index = (index - 1) * 2;
  1574. if (string == Py_None || index >= state->lastmark || !state->mark[index] || !state->mark[index+1]) {
  1575. if (empty)
  1576. /* want empty string */
  1577. i = j = 0;
  1578. else {
  1579. Py_INCREF(Py_None);
  1580. return Py_None;
  1581. }
  1582. } else {
  1583. i = STATE_OFFSET(state, state->mark[index]);
  1584. j = STATE_OFFSET(state, state->mark[index+1]);
  1585. }
  1586. return PySequence_GetSlice(string, i, j);
  1587. }
  1588. static void
  1589. pattern_error(int status)
  1590. {
  1591. switch (status) {
  1592. case SRE_ERROR_RECURSION_LIMIT:
  1593. PyErr_SetString(
  1594. PyExc_RuntimeError,
  1595. "maximum recursion limit exceeded"
  1596. );
  1597. break;
  1598. case SRE_ERROR_MEMORY:
  1599. PyErr_NoMemory();
  1600. break;
  1601. case SRE_ERROR_INTERRUPTED:
  1602. /* An exception has already been raised, so let it fly */
  1603. break;
  1604. default:
  1605. /* other error codes indicate compiler/engine bugs */
  1606. PyErr_SetString(
  1607. PyExc_RuntimeError,
  1608. "internal error in regular expression engine"
  1609. );
  1610. }
  1611. }
  1612. static void
  1613. pattern_dealloc(PatternObject* self)
  1614. {
  1615. if (self->weakreflist != NULL)
  1616. PyObject_ClearWeakRefs((PyObject *) self);
  1617. Py_XDECREF(self->pattern);
  1618. Py_XDECREF(self->groupindex);
  1619. Py_XDECREF(self->indexgroup);
  1620. PyObject_DEL(self);
  1621. }
  1622. static PyObject*
  1623. pattern_match(PatternObject* self, PyObject* args, PyObject* kw)
  1624. {
  1625. SRE_STATE state;
  1626. int status;
  1627. PyObject* string;
  1628. Py_ssize_t start = 0;
  1629. Py_ssize_t end = PY_SSIZE_T_MAX;
  1630. static char* kwlist[] = { "pattern", "pos", "endpos", NULL };
  1631. if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:match", kwlist,
  1632. &string, &start, &end))
  1633. return NULL;
  1634. string = state_init(&state, self, string, start, end);
  1635. if (!string)
  1636. return NULL;
  1637. state.ptr = state.start;
  1638. TRACE(("|%p|%p|MATCH\n", PatternObject_GetCode(self), state.ptr));
  1639. if (state.charsize == 1) {
  1640. status = sre_match(&state, PatternObject_GetCode(self));
  1641. } else {
  1642. #if defined(HAVE_UNICODE)
  1643. status = sre_umatch(&state, PatternObject_GetCode(self));
  1644. #endif
  1645. }
  1646. TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
  1647. if (PyErr_Occurred())
  1648. return NULL;
  1649. state_fini(&state);
  1650. return pattern_new_match(self, &state, status);
  1651. }
  1652. static PyObject*
  1653. pattern_search(PatternObject* self, PyObject* args, PyObject* kw)
  1654. {
  1655. SRE_STATE state;
  1656. int status;
  1657. PyObject* string;
  1658. Py_ssize_t start = 0;
  1659. Py_ssize_t end = PY_SSIZE_T_MAX;
  1660. static char* kwlist[] = { "pattern", "pos", "endpos", NULL };
  1661. if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:search", kwlist,
  1662. &string, &start, &end))
  1663. return NULL;
  1664. string = state_init(&state, self, string, start, end);
  1665. if (!string)
  1666. return NULL;
  1667. TRACE(("|%p|%p|SEARCH\n", PatternObject_GetCode(self), state.ptr));
  1668. if (state.charsize == 1) {
  1669. status = sre_search(&state, PatternObject_GetCode(self));
  1670. } else {
  1671. #if defined(HAVE_UNICODE)
  1672. status = sre_usearch(&state, PatternObject_GetCode(self));
  1673. #endif
  1674. }
  1675. TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
  1676. state_fini(&state);
  1677. if (PyErr_Occurred())
  1678. return NULL;
  1679. return pattern_new_match(self, &state, status);
  1680. }
  1681. static PyObject*
  1682. call(char* module, char* function, PyObject* args)
  1683. {
  1684. PyObject* name;
  1685. PyObject* mod;
  1686. PyObject* func;
  1687. PyObject* result;
  1688. if (!args)
  1689. return NULL;
  1690. name = PyString_FromString(module);
  1691. if (!name)
  1692. return NULL;
  1693. mod = PyImport_Import(name);
  1694. Py_DECREF(name);
  1695. if (!mod)
  1696. return NULL;
  1697. func = PyObject_GetAttrString(mod, function);
  1698. Py_DECREF(mod);
  1699. if (!func)
  1700. return NULL;
  1701. result = PyObject_CallObject(func, args);
  1702. Py_DECREF(func);
  1703. Py_DECREF(args);
  1704. return result;
  1705. }
  1706. #ifdef USE_BUILTIN_COPY
  1707. static int
  1708. deepcopy(PyObject** object, PyObject* memo)
  1709. {
  1710. PyObject* copy;
  1711. copy = call(
  1712. "copy", "deepcopy",
  1713. PyTuple_Pack(2, *object, memo)
  1714. );
  1715. if (!copy)
  1716. return 0;
  1717. Py_DECREF(*object);
  1718. *object = copy;
  1719. return 1; /* success */
  1720. }
  1721. #endif
  1722. static PyObject*
  1723. join_list(PyObject* list, PyObject* string)
  1724. {
  1725. /* join list elements */
  1726. PyObject* joiner;
  1727. #if PY_VERSION_HEX >= 0x01060000
  1728. PyObject* function;
  1729. PyObject* args;
  1730. #endif
  1731. PyObject* result;
  1732. joiner = PySequence_GetSlice(string, 0, 0);
  1733. if (!joiner)
  1734. return NULL;
  1735. if (PyList_GET_SIZE(list) == 0) {
  1736. Py_DECREF(list);
  1737. return joiner;
  1738. }
  1739. #if PY_VERSION_HEX >= 0x01060000
  1740. function = PyObject_GetAttrString(joiner, "join");
  1741. if (!function) {
  1742. Py_DECREF(joiner);
  1743. return NULL;
  1744. }
  1745. args = PyTuple_New(1);
  1746. if (!args) {
  1747. Py_DECREF(function);
  1748. Py_DECREF(joiner);
  1749. return NULL;
  1750. }
  1751. PyTuple_SET_ITEM(args, 0, list);
  1752. result = PyObject_CallObject(function, args);
  1753. Py_DECREF(args); /* also removes list */
  1754. Py_DECREF(function);
  1755. #else
  1756. result = call(
  1757. "string", "join",
  1758. PyTuple_Pack(2, list, joiner)
  1759. );
  1760. #endif
  1761. Py_DECREF(joiner);
  1762. return result;
  1763. }
  1764. static PyObject*
  1765. pattern_findall(PatternObject* self, PyObject* args, PyObject* kw)
  1766. {
  1767. SRE_STATE state;
  1768. PyObject* list;
  1769. int status;
  1770. Py_ssize_t i, b, e;
  1771. PyObject* string;
  1772. Py_ssize_t start = 0;
  1773. Py_ssize_t end = PY_SSIZE_T_MAX;
  1774. static char* kwlist[] = { "source", "pos", "endpos", NULL };
  1775. if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:findall", kwlist,
  1776. &string, &start, &end))
  1777. return NULL;
  1778. string = state_init(&state, self, string, start, end);
  1779. if (!string)
  1780. return NULL;
  1781. list = PyList_New(0);
  1782. if (!list) {
  1783. state_fini(&state);
  1784. return NULL;
  1785. }
  1786. while (state.start <= state.end) {
  1787. PyObject* item;
  1788. state_reset(&state);
  1789. state.ptr = state.start;
  1790. if (state.charsize == 1) {
  1791. status = sre_search(&state, PatternObject_GetCode(self));
  1792. } else {
  1793. #if defined(HAVE_UNICODE)
  1794. status = sre_usearch(&state, PatternObject_GetCode(self));
  1795. #endif
  1796. }
  1797. if (PyErr_Occurred())
  1798. goto error;
  1799. if (status <= 0) {
  1800. if (status == 0)
  1801. break;
  1802. pattern_error(status);
  1803. goto error;
  1804. }
  1805. /* don't bother to build a match object */
  1806. switch (self->groups) {
  1807. case 0:
  1808. b = STATE_OFFSET(&state, state.start);
  1809. e = STATE_OFFSET(&state, state.ptr);
  1810. item = PySequence_GetSlice(string, b, e);
  1811. if (!item)
  1812. goto error;
  1813. break;
  1814. case 1:
  1815. item = state_getslice(&state, 1, string, 1);
  1816. if (!item)
  1817. goto error;
  1818. break;
  1819. default:
  1820. item = PyTuple_New(self->groups);
  1821. if (!item)
  1822. goto error;
  1823. for (i = 0; i < self->groups; i++) {
  1824. PyObject* o = state_getslice(&state, i+1, string, 1);
  1825. if (!o) {
  1826. Py_DECREF(item);
  1827. goto error;
  1828. }
  1829. PyTuple_SET_ITEM(item, i, o);
  1830. }
  1831. break;
  1832. }
  1833. status = PyList_Append(list, item);
  1834. Py_DECREF(item);
  1835. if (status < 0)
  1836. goto error;
  1837. if (state.ptr == state.start)
  1838. state.start = (void*) ((char*) state.ptr + state.charsize);
  1839. else
  1840. state.start = state.ptr;
  1841. }
  1842. state_fini(&state);
  1843. return list;
  1844. error:
  1845. Py_DECREF(list);
  1846. state_fini(&state);
  1847. return NULL;
  1848. }
  1849. #if PY_VERSION_HEX >= 0x02020000
  1850. static PyObject*
  1851. pattern_finditer(PatternObject* pattern, PyObject* args)
  1852. {
  1853. PyObject* scanner;
  1854. PyObject* search;
  1855. PyObject* iterator;
  1856. scanner = pattern_scanner(pattern, args);
  1857. if (!scanner)
  1858. return NULL;
  1859. search = PyObject_GetAttrString(scanner, "search");
  1860. Py_DECREF(scanner);
  1861. if (!search)
  1862. return NULL;
  1863. iterator = PyCallIter_New(search, Py_None);
  1864. Py_DECREF(search);
  1865. return iterator;
  1866. }
  1867. #endif
  1868. static PyObject*
  1869. pattern_split(PatternObject* self, PyObject* args, PyObject* kw)
  1870. {
  1871. SRE_STATE state;
  1872. PyObject* list;
  1873. PyObject* item;
  1874. int status;
  1875. Py_ssize_t n;
  1876. Py_ssize_t i;
  1877. void* last;
  1878. PyObject* string;
  1879. Py_ssize_t maxsplit = 0;
  1880. static char* kwlist[] = { "source", "maxsplit", NULL };
  1881. if (!PyArg_ParseTupleAndKeywords(args, kw, "O|n:split", kwlist,
  1882. &string, &maxsplit))
  1883. return NULL;
  1884. string = state_init(&state, self, string, 0, PY_SSIZE_T_MAX);
  1885. if (!string)
  1886. return NULL;
  1887. list = PyList_New(0);
  1888. if (!list) {
  1889. state_fini(&state);
  1890. return NULL;
  1891. }
  1892. n = 0;
  1893. last = state.start;
  1894. while (!maxsplit || n < maxsplit) {
  1895. state_reset(&state);
  1896. state.ptr = state.start;
  1897. if (state.charsize == 1) {
  1898. status = sre_search(&state, PatternObject_GetCode(self));
  1899. } else {
  1900. #if defined(HAVE_UNICODE)
  1901. status = sre_usearch(&state, PatternObject_GetCode(self));
  1902. #endif
  1903. }
  1904. if (PyErr_Occurred())
  1905. goto error;
  1906. if (status <= 0) {
  1907. if (status == 0)
  1908. break;
  1909. pattern_error(status);
  1910. goto error;
  1911. }
  1912. if (state.start == state.ptr) {
  1913. if (last == state.end)
  1914. break;
  1915. /* skip one character */
  1916. state.start = (void*) ((char*) state.ptr + state.charsize);
  1917. continue;
  1918. }
  1919. /* get segment before this match */
  1920. item = PySequence_GetSlice(
  1921. string, STATE_OFFSET(&state, last),
  1922. STATE_OFFSET(&state, state.start)
  1923. );
  1924. if (!item)
  1925. goto error;
  1926. status = PyList_Append(list, item);
  1927. Py_DECREF(item);
  1928. if (status < 0)
  1929. goto error;
  1930. /* add groups (if any) */
  1931. for (i = 0; i < self->groups; i++) {
  1932. item = state_getslice(&state, i+1, string, 0);
  1933. if (!item)
  1934. goto error;
  1935. status = PyList_Append(list, item);
  1936. Py_DECREF(item);
  1937. if (status < 0)
  1938. goto error;
  1939. }
  1940. n = n + 1;
  1941. last = state.start = state.ptr;
  1942. }
  1943. /* get segment following last match (even if empty) */
  1944. item = PySequence_GetSlice(
  1945. string, STATE_OFFSET(&state, last), state.endpos
  1946. );
  1947. if (!item)
  1948. goto error;
  1949. status = PyList_Append(list, item);
  1950. Py_DECREF(item);
  1951. if (status < 0)
  1952. goto error;
  1953. state_fini(&state);
  1954. return list;
  1955. error:
  1956. Py_DECREF(list);
  1957. state_fini(&state);
  1958. return NULL;
  1959. }
  1960. static PyObject*
  1961. pattern_subx(PatternObject* self, PyObject* ptemplate, PyObject* string,
  1962. Py_ssize_t count, Py_ssize_t subn)
  1963. {
  1964. SRE_STATE state;
  1965. PyObject* list;
  1966. PyObject* item;
  1967. PyObject* filter;
  1968. PyObject* args;
  1969. PyObject* match;
  1970. void* ptr;
  1971. int status;
  1972. Py_ssize_t n;
  1973. Py_ssize_t i, b, e;
  1974. int bint;
  1975. int filter_is_callable;
  1976. if (PyCallable_Check(ptemplate)) {
  1977. /* sub/subn takes either a function or a template */
  1978. filter = ptemplate;
  1979. Py_INCREF(filter);
  1980. filter_is_callable = 1;
  1981. } else {
  1982. /* if not callable, check if it's a literal string */
  1983. int literal;
  1984. ptr = getstring(ptemplate, &n, &bint);
  1985. b = bint;
  1986. if (ptr) {
  1987. if (b == 1) {
  1988. literal = sre_literal_template((unsigned char *)ptr, n);
  1989. } else {
  1990. #if defined(HAVE_UNICODE)
  1991. literal = sre_uliteral_template((Py_UNICODE *)ptr, n);
  1992. #endif
  1993. }
  1994. } else {
  1995. PyErr_Clear();
  1996. literal = 0;
  1997. }
  1998. if (literal) {
  1999. filter = ptemplate;
  2000. Py_INCREF(filter);
  2001. filter_is_callable = 0;
  2002. } else {
  2003. /* not a literal; hand it over to the template compiler */
  2004. filter = call(
  2005. SRE_PY_MODULE, "_subx",
  2006. PyTuple_Pack(2, self, ptemplate)
  2007. );
  2008. if (!filter)
  2009. return NULL;
  2010. filter_is_callable = PyCallable_Check(filter);
  2011. }
  2012. }
  2013. string = state_init(&state, self, string, 0, PY_SSIZE_T_MAX);
  2014. if (!string) {
  2015. Py_DECREF(filter);
  2016. return NULL;
  2017. }
  2018. list = PyList_New(0);
  2019. if (!list) {
  2020. Py_DECREF(filter);
  2021. state_fini(&state);
  2022. return NULL;
  2023. }
  2024. n = i = 0;
  2025. while (!count || n < count) {
  2026. state_reset(&state);
  2027. state.ptr = state.start;
  2028. if (state.charsize == 1) {
  2029. status = sre_search(&state, PatternObject_GetCode(self));
  2030. } else {
  2031. #if defined(HAVE_UNICODE)
  2032. status = sre_usearch(&state, PatternObject_GetCode(self));
  2033. #endif
  2034. }
  2035. if (PyErr_Occurred())
  2036. goto error;
  2037. if (status <= 0) {
  2038. if (status == 0)
  2039. break;
  2040. pattern_error(status);
  2041. goto error;
  2042. }
  2043. b = STATE_OFFSET(&state, state.start);
  2044. e = STATE_OFFSET(&state, state.ptr);
  2045. if (i < b) {
  2046. /* get segment before this match */
  2047. item = PySequence_GetSlice(string, i, b);
  2048. if (!item)
  2049. goto error;
  2050. status = PyList_Append(list, item);
  2051. Py_DECREF(item);
  2052. if (status < 0)
  2053. goto error;
  2054. } else if (i == b && i == e && n > 0)
  2055. /* ignore empty match on latest position */
  2056. goto next;
  2057. if (filter_is_callable) {
  2058. /* pass match object through filter */
  2059. match = pattern_new_match(self, &state, 1);
  2060. if (!match)
  2061. goto error;
  2062. args = PyTuple_Pack(1, match);
  2063. if (!args) {
  2064. Py_DECREF(match);
  2065. goto error;
  2066. }
  2067. item = PyObject_CallObject(filter, args);
  2068. Py_DECREF(args);
  2069. Py_DECREF(match);
  2070. if (!item)
  2071. goto error;
  2072. } else {
  2073. /* filter is literal string */
  2074. item = filter;
  2075. Py_INCREF(item);
  2076. }
  2077. /* add to list */
  2078. if (item != Py_None) {
  2079. status = PyList_Append(list, item);
  2080. Py_DECREF(item);
  2081. if (status < 0)
  2082. goto error;
  2083. }
  2084. i = e;
  2085. n = n + 1;
  2086. next:
  2087. /* move on */
  2088. if (state.ptr == state.start)
  2089. state.start = (void*) ((char*) state.ptr + state.charsize);
  2090. else
  2091. state.start = state.ptr;
  2092. }
  2093. /* get segment following last match */
  2094. if (i < state.endpos) {
  2095. item = PySequence_GetSlice(string, i, state.endpos);
  2096. if (!item)
  2097. goto error;
  2098. status = PyList_Append(list, item);
  2099. Py_DECREF(item);
  2100. if (status < 0)
  2101. goto error;
  2102. }
  2103. state_fini(&state);
  2104. Py_DECREF(filter);
  2105. /* convert list to single string (also removes list) */
  2106. item = join_list(list, string);
  2107. if (!item)
  2108. return NULL;
  2109. if (subn)
  2110. return Py_BuildValue("Ni", item, n);
  2111. return item;
  2112. error:
  2113. Py_DECREF(list);
  2114. state_fini(&state);
  2115. Py_DECREF(filter);
  2116. return NULL;
  2117. }
  2118. static PyObject*
  2119. pattern_sub(PatternObject* self, PyObject* args, PyObject* kw)
  2120. {
  2121. PyObject* ptemplate;
  2122. PyObject* string;
  2123. Py_ssize_t count = 0;
  2124. static char* kwlist[] = { "repl", "string", "count", NULL };
  2125. if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|n:sub", kwlist,
  2126. &ptemplate, &string, &count))
  2127. return NULL;
  2128. return pattern_subx(self, ptemplate, string, count, 0);
  2129. }
  2130. static PyObject*
  2131. pattern_subn(PatternObject* self, PyObject* args, PyObject* kw)
  2132. {
  2133. PyObject* ptemplate;
  2134. PyObject* string;
  2135. Py_ssize_t count = 0;
  2136. static char* kwlist[] = { "repl", "string", "count", NULL };
  2137. if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|n:subn", kwlist,
  2138. &ptemplate, &string, &count))
  2139. return NULL;
  2140. return pattern_subx(self, ptemplate, string, count, 1);
  2141. }
  2142. static PyObject*
  2143. pattern_copy(PatternObject* self, PyObject *unused)
  2144. {
  2145. #ifdef USE_BUILTIN_COPY
  2146. PatternObject* copy;
  2147. int offset;
  2148. copy = PyObject_NEW_VAR(PatternObject, &Pattern_Type, self->codesize);
  2149. if (!copy)
  2150. return NULL;
  2151. offset = offsetof(PatternObject, groups);
  2152. Py_XINCREF(self->groupindex);
  2153. Py_XINCREF(self->indexgroup);
  2154. Py_XINCREF(self->pattern);
  2155. memcpy((char*) copy + offset, (char*) self + offset,
  2156. sizeof(PatternObject) + self->codesize * sizeof(SRE_CODE) - offset);
  2157. copy->weakreflist = NULL;
  2158. return (PyObject*) copy;
  2159. #else
  2160. PyErr_SetString(PyExc_TypeError, "cannot copy this pattern object");
  2161. return NULL;
  2162. #endif
  2163. }
  2164. static PyObject*
  2165. pattern_deepcopy(PatternObject* self, PyObject* memo)
  2166. {
  2167. #ifdef USE_BUILTIN_COPY
  2168. PatternObject* copy;
  2169. copy = (PatternObject*) pattern_copy(self);
  2170. if (!copy)
  2171. return NULL;
  2172. if (!deepcopy(&copy->groupindex, memo) ||
  2173. !deepcopy(&copy->indexgroup, memo) ||
  2174. !deepcopy(&copy->pattern, memo)) {
  2175. Py_DECREF(copy);
  2176. return NULL;
  2177. }
  2178. #else
  2179. PyErr_SetString(PyExc_TypeError, "cannot deepcopy this pattern object");
  2180. return NULL;
  2181. #endif
  2182. }
  2183. PyDoc_STRVAR(pattern_match_doc,
  2184. "match(string[, pos[, endpos]]) --> match object or None.\n\
  2185. Matches zero or more characters at the beginning of the string");
  2186. PyDoc_STRVAR(pattern_search_doc,
  2187. "search(string[, pos[, endpos]]) --> match object or None.\n\
  2188. Scan through string looking for a match, and return a corresponding\n\
  2189. MatchObject instance. Return None if no position in the string matches.");
  2190. PyDoc_STRVAR(pattern_split_doc,
  2191. "split(string[, maxsplit = 0]) --> list.\n\
  2192. Split string by the occurrences of pattern.");
  2193. PyDoc_STRVAR(pattern_findall_doc,
  2194. "findall(string[, pos[, endpos]]) --> list.\n\
  2195. Return a list of all non-overlapping matches of pattern in string.");
  2196. PyDoc_STRVAR(pattern_finditer_doc,
  2197. "finditer(string[, pos[, endpos]]) --> iterator.\n\
  2198. Return an iterator over all non-overlapping matches for the \n\
  2199. RE pattern in string. For each match, the iterator returns a\n\
  2200. match object.");
  2201. PyDoc_STRVAR(pattern_sub_doc,
  2202. "sub(repl, string[, count = 0]) --> newstring\n\
  2203. Return the string obtained by replacing the leftmost non-overlapping\n\
  2204. occurrences of pattern in string by the replacement repl.");
  2205. PyDoc_STRVAR(pattern_subn_doc,
  2206. "subn(repl, string[, count = 0]) --> (newstring, number of subs)\n\
  2207. Return the tuple (new_string, number_of_subs_made) found by replacing\n\
  2208. the leftmost non-overlapping occurrences of pattern with the\n\
  2209. replacement repl.");
  2210. PyDoc_STRVAR(pattern_doc, "Compiled regular expression objects");
  2211. static PyMethodDef pattern_methods[] = {
  2212. {"match", (PyCFunction) pattern_match, METH_VARARGS|METH_KEYWORDS,
  2213. pattern_match_doc},
  2214. {"search", (PyCFunction) pattern_search, METH_VARARGS|METH_KEYWORDS,
  2215. pattern_search_doc},
  2216. {"sub", (PyCFunction) pattern_sub, METH_VARARGS|METH_KEYWORDS,
  2217. pattern_sub_doc},
  2218. {"subn", (PyCFunction) pattern_subn, METH_VARARGS|METH_KEYWORDS,
  2219. pattern_subn_doc},
  2220. {"split", (PyCFunction) pattern_split, METH_VARARGS|METH_KEYWORDS,
  2221. pattern_split_doc},
  2222. {"findall", (PyCFunction) pattern_findall, METH_VARARGS|METH_KEYWORDS,
  2223. pattern_findall_doc},
  2224. #if PY_VERSION_HEX >= 0x02020000
  2225. {"finditer", (PyCFunction) pattern_finditer, METH_VARARGS,
  2226. pattern_finditer_doc},
  2227. #endif
  2228. {"scanner", (PyCFunction) pattern_scanner, METH_VARARGS},
  2229. {"__copy__", (PyCFunction) pattern_copy, METH_NOARGS},
  2230. {"__deepcopy__", (PyCFunction) pattern_deepcopy, METH_O},
  2231. {NULL, NULL}
  2232. };
  2233. static PyObject*
  2234. pattern_getattr(PatternObject* self, char* name)
  2235. {
  2236. PyObject* res;
  2237. res = Py_FindMethod(pattern_methods, (PyObject*) self, name);
  2238. if (res)
  2239. return res;
  2240. PyErr_Clear();
  2241. /* attributes */
  2242. if (!strcmp(name, "pattern")) {
  2243. Py_INCREF(self->pattern);
  2244. return self->pattern;
  2245. }
  2246. if (!strcmp(name, "flags"))
  2247. return Py_BuildValue("i", self->flags);
  2248. if (!strcmp(name, "groups"))
  2249. return Py_BuildValue("i", self->groups);
  2250. if (!strcmp(name, "groupindex") && self->groupindex) {
  2251. Py_INCREF(self->groupindex);
  2252. return self->groupindex;
  2253. }
  2254. PyErr_SetString(PyExc_AttributeError, name);
  2255. return NULL;
  2256. }
  2257. statichere PyTypeObject Pattern_Type = {
  2258. PyObject_HEAD_INIT(NULL)
  2259. 0, "_" SRE_MODULE ".SRE_Pattern",
  2260. sizeof(PatternObject), sizeof(SRE_CODE),
  2261. (destructor)pattern_dealloc, /*tp_dealloc*/
  2262. 0, /*tp_print*/
  2263. (getattrfunc)pattern_getattr, /*tp_getattr*/
  2264. 0, /* tp_setattr */
  2265. 0, /* tp_compare */
  2266. 0, /* tp_repr */
  2267. 0, /* tp_as_number */
  2268. 0, /* tp_as_sequence */
  2269. 0, /* tp_as_mapping */
  2270. 0, /* tp_hash */
  2271. 0, /* tp_call */
  2272. 0, /* tp_str */
  2273. 0, /* tp_getattro */
  2274. 0, /* tp_setattro */
  2275. 0, /* tp_as_buffer */
  2276. Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
  2277. pattern_doc, /* tp_doc */
  2278. 0, /* tp_traverse */
  2279. 0, /* tp_clear */
  2280. 0, /* tp_richcompare */
  2281. offsetof(PatternObject, weakreflist), /* tp_weaklistoffset */
  2282. };
  2283. static int _validate(PatternObject *self); /* Forward */
  2284. static PyObject *
  2285. _compile(PyObject* self_, PyObject* args)
  2286. {
  2287. /* "compile" pattern descriptor to pattern object */
  2288. PatternObject* self;
  2289. Py_ssize_t i, n;
  2290. PyObject* pattern;
  2291. int flags = 0;
  2292. PyObject* code;
  2293. Py_ssize_t groups = 0;
  2294. PyObject* groupindex = NULL;
  2295. PyObject* indexgroup = NULL;
  2296. if (!PyArg_ParseTuple(args, "OiO!|nOO", &pattern, &flags,
  2297. &PyList_Type, &code, &groups,
  2298. &groupindex, &indexgroup))
  2299. return NULL;
  2300. n = PyList_GET_SIZE(code);
  2301. /* coverity[ampersand_in_size] */
  2302. self = PyObject_NEW_VAR(PatternObject, &Pattern_Type, n);
  2303. if (!self)
  2304. return NULL;
  2305. self->weakreflist = NULL;
  2306. self->pattern = NULL;
  2307. self->groupindex = NULL;
  2308. self->indexgroup = NULL;
  2309. self->codesize = n;
  2310. for (i = 0; i < n; i++) {
  2311. PyObject *o = PyList_GET_ITEM(code, i);
  2312. unsigned long value = PyInt_Check(o) ? (unsigned long)PyInt_AsLong(o)
  2313. : PyLong_AsUnsignedLong(o);
  2314. self->code[i] = (SRE_CODE) value;
  2315. if ((unsigned long) self->code[i] != value) {
  2316. PyErr_SetString(PyExc_OverflowError,
  2317. "regular expression code size limit exceeded");
  2318. break;
  2319. }
  2320. }
  2321. if (PyErr_Occurred()) {
  2322. Py_DECREF(self);
  2323. return NULL;
  2324. }
  2325. Py_INCREF(pattern);
  2326. self->pattern = pattern;
  2327. self->flags = flags;
  2328. self->groups = groups;
  2329. Py_XINCREF(groupindex);
  2330. self->groupindex = groupindex;
  2331. Py_XINCREF(indexgroup);
  2332. self->indexgroup = indexgroup;
  2333. self->weakreflist = NULL;
  2334. if (!_validate(self)) {
  2335. Py_DECREF(self);
  2336. return NULL;
  2337. }
  2338. return (PyObject*) self;
  2339. }
  2340. /* -------------------------------------------------------------------- */
  2341. /* Code validation */
  2342. /* To learn more about this code, have a look at the _compile() function in
  2343. Lib/sre_compile.py. The validation functions below checks the code array
  2344. for conformance with the code patterns generated there.
  2345. The nice thing about the generated code is that it is position-independent:
  2346. all jumps are relative jumps forward. Also, jumps don't cross each other:
  2347. the target of a later jump is always earlier than the target of an earlier
  2348. jump. IOW, this is okay:
  2349. J---------J-------T--------T
  2350. \ \_____/ /
  2351. \______________________/
  2352. but this is not:
  2353. J---------J-------T--------T
  2354. \_________\_____/ /
  2355. \____________/
  2356. It also helps that SRE_CODE is always an unsigned type, either 2 bytes or 4
  2357. bytes wide (the latter if Python is compiled for "wide" unicode support).
  2358. */
  2359. /* Defining this one enables tracing of the validator */
  2360. #undef VVERBOSE
  2361. /* Trace macro for the validator */
  2362. #if defined(VVERBOSE)
  2363. #define VTRACE(v) printf v
  2364. #else
  2365. #define VTRACE(v)
  2366. #endif
  2367. /* Report failure */
  2368. #define FAIL do { VTRACE(("FAIL: %d\n", __LINE__)); return 0; } while (0)
  2369. /* Extract opcode, argument, or skip count from code array */
  2370. #define GET_OP \
  2371. do { \
  2372. VTRACE(("%p: ", code)); \
  2373. if (code >= end) FAIL; \
  2374. op = *code++; \
  2375. VTRACE(("%lu (op)\n", (unsigned long)op)); \
  2376. } while (0)
  2377. #define GET_ARG \
  2378. do { \
  2379. VTRACE(("%p= ", code)); \
  2380. if (code >= end) FAIL; \
  2381. arg = *code++; \
  2382. VTRACE(("%lu (arg)\n", (unsigned long)arg)); \
  2383. } while (0)
  2384. #define GET_SKIP_ADJ(adj) \
  2385. do { \
  2386. VTRACE(("%p= ", code)); \
  2387. if (code >= end) FAIL; \
  2388. skip = *code; \
  2389. VTRACE(("%lu (skip to %p)\n", \
  2390. (unsigned long)skip, code+skip)); \
  2391. if (code+skip-adj < code || code+skip-adj > end)\
  2392. FAIL; \
  2393. code++; \
  2394. } while (0)
  2395. #define GET_SKIP GET_SKIP_ADJ(0)
  2396. static int
  2397. _validate_charset(SRE_CODE *code, SRE_CODE *end)
  2398. {
  2399. /* Some variables are manipulated by the macros above */
  2400. SRE_CODE op;
  2401. SRE_CODE arg;
  2402. SRE_CODE offset;
  2403. int i;
  2404. while (code < end) {
  2405. GET_OP;
  2406. switch (op) {
  2407. case SRE_OP_NEGATE:
  2408. break;
  2409. case SRE_OP_LITERAL:
  2410. GET_ARG;
  2411. break;
  2412. case SRE_OP_RANGE:
  2413. GET_ARG;
  2414. GET_ARG;
  2415. break;
  2416. case SRE_OP_CHARSET:
  2417. offset = 32/sizeof(SRE_CODE); /* 32-byte bitmap */
  2418. if (code+offset < code || code+offset > end)
  2419. FAIL;
  2420. code += offset;
  2421. break;
  2422. case SRE_OP_BIGCHARSET:
  2423. GET_ARG; /* Number of blocks */
  2424. offset = 256/sizeof(SRE_CODE); /* 256-byte table */
  2425. if (code+offset < code || code+offset > end)
  2426. FAIL;
  2427. /* Make sure that each byte points to a valid block */
  2428. for (i = 0; i < 256; i++) {
  2429. if (((unsigned char *)code)[i] >= arg)
  2430. FAIL;
  2431. }
  2432. code += offset;
  2433. offset = arg * 32/sizeof(SRE_CODE); /* 32-byte bitmap times arg */
  2434. if (code+offset < code || code+offset > end)
  2435. FAIL;
  2436. code += offset;
  2437. break;
  2438. case SRE_OP_CATEGORY:
  2439. GET_ARG;
  2440. switch (arg) {
  2441. case SRE_CATEGORY_DIGIT:
  2442. case SRE_CATEGORY_NOT_DIGIT:
  2443. case SRE_CATEGORY_SPACE:
  2444. case SRE_CATEGORY_NOT_SPACE:
  2445. case SRE_CATEGORY_WORD:
  2446. case SRE_CATEGORY_NOT_WORD:
  2447. case SRE_CATEGORY_LINEBREAK:
  2448. case SRE_CATEGORY_NOT_LINEBREAK:
  2449. case SRE_CATEGORY_LOC_WORD:
  2450. case SRE_CATEGORY_LOC_NOT_WORD:
  2451. case SRE_CATEGORY_UNI_DIGIT:
  2452. case SRE_CATEGORY_UNI_NOT_DIGIT:
  2453. case SRE_CATEGORY_UNI_SPACE:
  2454. case SRE_CATEGORY_UNI_NOT_SPACE:
  2455. case SRE_CATEGORY_UNI_WORD:
  2456. case SRE_CATEGORY_UNI_NOT_WORD:
  2457. case SRE_CATEGORY_UNI_LINEBREAK:
  2458. case SRE_CATEGORY_UNI_NOT_LINEBREAK:
  2459. break;
  2460. default:
  2461. FAIL;
  2462. }
  2463. break;
  2464. default:
  2465. FAIL;
  2466. }
  2467. }
  2468. return 1;
  2469. }
  2470. static int
  2471. _validate_inner(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups)
  2472. {
  2473. /* Some variables are manipulated by the macros above */
  2474. SRE_CODE op;
  2475. SRE_CODE arg;
  2476. SRE_CODE skip;
  2477. VTRACE(("code=%p, end=%p\n", code, end));
  2478. if (code > end)
  2479. FAIL;
  2480. while (code < end) {
  2481. GET_OP;
  2482. switch (op) {
  2483. case SRE_OP_MARK:
  2484. /* We don't check whether marks are properly nested; the
  2485. sre_match() code is robust even if they don't, and the worst
  2486. you can get is nonsensical match results. */
  2487. GET_ARG;
  2488. if (arg > 2*groups+1) {
  2489. VTRACE(("arg=%d, groups=%d\n", (int)arg, (int)groups));
  2490. FAIL;
  2491. }
  2492. break;
  2493. case SRE_OP_LITERAL:
  2494. case SRE_OP_NOT_LITERAL:
  2495. case SRE_OP_LITERAL_IGNORE:
  2496. case SRE_OP_NOT_LITERAL_IGNORE:
  2497. GET_ARG;
  2498. /* The arg is just a character, nothing to check */
  2499. break;
  2500. case SRE_OP_SUCCESS:
  2501. case SRE_OP_FAILURE:
  2502. /* Nothing to check; these normally end the matching process */
  2503. break;
  2504. case SRE_OP_AT:
  2505. GET_ARG;
  2506. switch (arg) {
  2507. case SRE_AT_BEGINNING:
  2508. case SRE_AT_BEGINNING_STRING:
  2509. case SRE_AT_BEGINNING_LINE:
  2510. case SRE_AT_END:
  2511. case SRE_AT_END_LINE:
  2512. case SRE_AT_END_STRING:
  2513. case SRE_AT_BOUNDARY:
  2514. case SRE_AT_NON_BOUNDARY:
  2515. case SRE_AT_LOC_BOUNDARY:
  2516. case SRE_AT_LOC_NON_BOUNDARY:
  2517. case SRE_AT_UNI_BOUNDARY:
  2518. case SRE_AT_UNI_NON_BOUNDARY:
  2519. break;
  2520. default:
  2521. FAIL;
  2522. }
  2523. break;
  2524. case SRE_OP_ANY:
  2525. case SRE_OP_ANY_ALL:
  2526. /* These have no operands */
  2527. break;
  2528. case SRE_OP_IN:
  2529. case SRE_OP_IN_IGNORE:
  2530. GET_SKIP;
  2531. /* Stop 1 before the end; we check the FAILURE below */
  2532. if (!_validate_charset(code, code+skip-2))
  2533. FAIL;
  2534. if (code[skip-2] != SRE_OP_FAILURE)
  2535. FAIL;
  2536. code += skip-1;
  2537. break;
  2538. case SRE_OP_INFO:
  2539. {
  2540. /* A minimal info field is
  2541. <INFO> <1=skip> <2=flags> <3=min> <4=max>;
  2542. If SRE_INFO_PREFIX or SRE_INFO_CHARSET is in the flags,
  2543. more follows. */
  2544. SRE_CODE flags, min, max, i;
  2545. SRE_CODE *newcode;
  2546. GET_SKIP;
  2547. newcode = code+skip-1;
  2548. GET_ARG; flags = arg;
  2549. GET_ARG; min = arg;
  2550. GET_ARG; max = arg;
  2551. /* Check that only valid flags are present */
  2552. if ((flags & ~(SRE_INFO_PREFIX |
  2553. SRE_INFO_LITERAL |
  2554. SRE_INFO_CHARSET)) != 0)
  2555. FAIL;
  2556. /* PREFIX and CHARSET are mutually exclusive */
  2557. if ((flags & SRE_INFO_PREFIX) &&
  2558. (flags & SRE_INFO_CHARSET))
  2559. FAIL;
  2560. /* LITERAL implies PREFIX */
  2561. if ((flags & SRE_INFO_LITERAL) &&
  2562. !(flags & SRE_INFO_PREFIX))
  2563. FAIL;
  2564. /* Validate the prefix */
  2565. if (flags & SRE_INFO_PREFIX) {
  2566. SRE_CODE prefix_len, prefix_skip;
  2567. GET_ARG; prefix_len = arg;
  2568. GET_ARG; prefix_skip = arg;
  2569. /* Here comes the prefix string */
  2570. if (code+prefix_len < code || code+prefix_len > newcode)
  2571. FAIL;
  2572. code += prefix_len;
  2573. /* And here comes the overlap table */
  2574. if (code+prefix_len < code || code+prefix_len > newcode)
  2575. FAIL;
  2576. /* Each overlap value should be < prefix_len */
  2577. for (i = 0; i < prefix_len; i++) {
  2578. if (code[i] >= prefix_len)
  2579. FAIL;
  2580. }
  2581. code += prefix_len;
  2582. }
  2583. /* Validate the charset */
  2584. if (flags & SRE_INFO_CHARSET) {
  2585. if (!_validate_charset(code, newcode-1))
  2586. FAIL;
  2587. if (newcode[-1] != SRE_OP_FAILURE)
  2588. FAIL;
  2589. code = newcode;
  2590. }
  2591. else if (code != newcode) {
  2592. VTRACE(("code=%p, newcode=%p\n", code, newcode));
  2593. FAIL;
  2594. }
  2595. }
  2596. break;
  2597. case SRE_OP_BRANCH:
  2598. {
  2599. SRE_CODE *target = NULL;
  2600. for (;;) {
  2601. GET_SKIP;
  2602. if (skip == 0)
  2603. break;
  2604. /* Stop 2 before the end; we check the JUMP below */
  2605. if (!_validate_inner(code, code+skip-3, groups))
  2606. FAIL;
  2607. code += skip-3;
  2608. /* Check that it ends with a JUMP, and that each JUMP
  2609. has the same target */
  2610. GET_OP;
  2611. if (op != SRE_OP_JUMP)
  2612. FAIL;
  2613. GET_SKIP;
  2614. if (target == NULL)
  2615. target = code+skip-1;
  2616. else if (code+skip-1 != target)
  2617. FAIL;
  2618. }
  2619. }
  2620. break;
  2621. case SRE_OP_REPEAT_ONE:
  2622. case SRE_OP_MIN_REPEAT_ONE:
  2623. {
  2624. SRE_CODE min, max;
  2625. GET_SKIP;
  2626. GET_ARG; min = arg;
  2627. GET_ARG; max = arg;
  2628. if (min > max)
  2629. FAIL;
  2630. #ifdef Py_UNICODE_WIDE
  2631. if (max > 65535)
  2632. FAIL;
  2633. #endif
  2634. if (!_validate_inner(code, code+skip-4, groups))
  2635. FAIL;
  2636. code += skip-4;
  2637. GET_OP;
  2638. if (op != SRE_OP_SUCCESS)
  2639. FAIL;
  2640. }
  2641. break;
  2642. case SRE_OP_REPEAT:
  2643. {
  2644. SRE_CODE min, max;
  2645. GET_SKIP;
  2646. GET_ARG; min = arg;
  2647. GET_ARG; max = arg;
  2648. if (min > max)
  2649. FAIL;
  2650. #ifdef Py_UNICODE_WIDE
  2651. if (max > 65535)
  2652. FAIL;
  2653. #endif
  2654. if (!_validate_inner(code, code+skip-3, groups))
  2655. FAIL;
  2656. code += skip-3;
  2657. GET_OP;
  2658. if (op != SRE_OP_MAX_UNTIL && op != SRE_OP_MIN_UNTIL)
  2659. FAIL;
  2660. }
  2661. break;
  2662. case SRE_OP_GROUPREF:
  2663. case SRE_OP_GROUPREF_IGNORE:
  2664. GET_ARG;
  2665. if (arg >= groups)
  2666. FAIL;
  2667. break;
  2668. case SRE_OP_GROUPREF_EXISTS:
  2669. /* The regex syntax for this is: '(?(group)then|else)', where
  2670. 'group' is either an integer group number or a group name,
  2671. 'then' and 'else' are sub-regexes, and 'else' is optional. */
  2672. GET_ARG;
  2673. if (arg >= groups)
  2674. FAIL;
  2675. GET_SKIP_ADJ(1);
  2676. code--; /* The skip is relative to the first arg! */
  2677. /* There are two possibilities here: if there is both a 'then'
  2678. part and an 'else' part, the generated code looks like:
  2679. GROUPREF_EXISTS
  2680. <group>
  2681. <skipyes>
  2682. ...then part...
  2683. JUMP
  2684. <skipno>
  2685. (<skipyes> jumps here)
  2686. ...else part...
  2687. (<skipno> jumps here)
  2688. If there is only a 'then' part, it looks like:
  2689. GROUPREF_EXISTS
  2690. <group>
  2691. <skip>
  2692. ...then part...
  2693. (<skip> jumps here)
  2694. There is no direct way to decide which it is, and we don't want
  2695. to allow arbitrary jumps anywhere in the code; so we just look
  2696. for a JUMP opcode preceding our skip target.
  2697. */
  2698. if (skip >= 3 && code+skip-3 >= code &&
  2699. code[skip-3] == SRE_OP_JUMP)
  2700. {
  2701. VTRACE(("both then and else parts present\n"));
  2702. if (!_validate_inner(code+1, code+skip-3, groups))
  2703. FAIL;
  2704. code += skip-2; /* Position after JUMP, at <skipno> */
  2705. GET_SKIP;
  2706. if (!_validate_inner(code, code+skip-1, groups))
  2707. FAIL;
  2708. code += skip-1;
  2709. }
  2710. else {
  2711. VTRACE(("only a then part present\n"));
  2712. if (!_validate_inner(code+1, code+skip-1, groups))
  2713. FAIL;
  2714. code += skip-1;
  2715. }
  2716. break;
  2717. case SRE_OP_ASSERT:
  2718. case SRE_OP_ASSERT_NOT:
  2719. GET_SKIP;
  2720. GET_ARG; /* 0 for lookahead, width for lookbehind */
  2721. code--; /* Back up over arg to simplify math below */
  2722. if (arg & 0x80000000)
  2723. FAIL; /* Width too large */
  2724. /* Stop 1 before the end; we check the SUCCESS below */
  2725. if (!_validate_inner(code+1, code+skip-2, groups))
  2726. FAIL;
  2727. code += skip-2;
  2728. GET_OP;
  2729. if (op != SRE_OP_SUCCESS)
  2730. FAIL;
  2731. break;
  2732. default:
  2733. FAIL;
  2734. }
  2735. }
  2736. VTRACE(("okay\n"));
  2737. return 1;
  2738. }
  2739. static int
  2740. _validate_outer(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups)
  2741. {
  2742. if (groups < 0 || groups > 100 || code >= end || end[-1] != SRE_OP_SUCCESS)
  2743. FAIL;
  2744. if (groups == 0) /* fix for simplejson */
  2745. groups = 100; /* 100 groups should always be safe */
  2746. return _validate_inner(code, end-1, groups);
  2747. }
  2748. static int
  2749. _validate(PatternObject *self)
  2750. {
  2751. if (!_validate_outer(self->code, self->code+self->codesize, self->groups))
  2752. {
  2753. PyErr_SetString(PyExc_RuntimeError, "invalid SRE code");
  2754. return 0;
  2755. }
  2756. else
  2757. VTRACE(("Success!\n"));
  2758. return 1;
  2759. }
  2760. /* -------------------------------------------------------------------- */
  2761. /* match methods */
  2762. static void
  2763. match_dealloc(MatchObject* self)
  2764. {
  2765. Py_XDECREF(self->regs);
  2766. Py_XDECREF(self->string);
  2767. Py_DECREF(self->pattern);
  2768. PyObject_DEL(self);
  2769. }
  2770. static PyObject*
  2771. match_getslice_by_index(MatchObject* self, Py_ssize_t index, PyObject* def)
  2772. {
  2773. if (index < 0 || index >= self->groups) {
  2774. /* raise IndexError if we were given a bad group number */
  2775. PyErr_SetString(
  2776. PyExc_IndexError,
  2777. "no such group"
  2778. );
  2779. return NULL;
  2780. }
  2781. index *= 2;
  2782. if (self->string == Py_None || self->mark[index] < 0) {
  2783. /* return default value if the string or group is undefined */
  2784. Py_INCREF(def);
  2785. return def;
  2786. }
  2787. return PySequence_GetSlice(
  2788. self->string, self->mark[index], self->mark[index+1]
  2789. );
  2790. }
  2791. static Py_ssize_t
  2792. match_getindex(MatchObject* self, PyObject* index)
  2793. {
  2794. Py_ssize_t i;
  2795. if (PyInt_Check(index))
  2796. return PyInt_AsSsize_t(index);
  2797. i = -1;
  2798. if (self->pattern->groupindex) {
  2799. index = PyObject_GetItem(self->pattern->groupindex, index);
  2800. if (index) {
  2801. if (PyInt_Check(index) || PyLong_Check(index))
  2802. i = PyInt_AsSsize_t(index);
  2803. Py_DECREF(index);
  2804. } else
  2805. PyErr_Clear();
  2806. }
  2807. return i;
  2808. }
  2809. static PyObject*
  2810. match_getslice(MatchObject* self, PyObject* index, PyObject* def)
  2811. {
  2812. return match_getslice_by_index(self, match_getindex(self, index), def);
  2813. }
  2814. static PyObject*
  2815. match_expand(MatchObject* self, PyObject* ptemplate)
  2816. {
  2817. /* delegate to Python code */
  2818. return call(
  2819. SRE_PY_MODULE, "_expand",
  2820. PyTuple_Pack(3, self->pattern, self, ptemplate)
  2821. );
  2822. }
  2823. static PyObject*
  2824. match_group(MatchObject* self, PyObject* args)
  2825. {
  2826. PyObject* result;
  2827. Py_ssize_t i, size;
  2828. size = PyTuple_GET_SIZE(args);
  2829. switch (size) {
  2830. case 0:
  2831. result = match_getslice(self, Py_False, Py_None);
  2832. break;
  2833. case 1:
  2834. result = match_getslice(self, PyTuple_GET_ITEM(args, 0), Py_None);
  2835. break;
  2836. default:
  2837. /* fetch multiple items */
  2838. result = PyTuple_New(size);
  2839. if (!result)
  2840. return NULL;
  2841. for (i = 0; i < size; i++) {
  2842. PyObject* item = match_getslice(
  2843. self, PyTuple_GET_ITEM(args, i), Py_None
  2844. );
  2845. if (!item) {
  2846. Py_DECREF(result);
  2847. return NULL;
  2848. }
  2849. PyTuple_SET_ITEM(result, i, item);
  2850. }
  2851. break;
  2852. }
  2853. return result;
  2854. }
  2855. static PyObject*
  2856. match_groups(MatchObject* self, PyObject* args, PyObject* kw)
  2857. {
  2858. PyObject* result;
  2859. Py_ssize_t index;
  2860. PyObject* def = Py_None;
  2861. static char* kwlist[] = { "default", NULL };
  2862. if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:groups", kwlist, &def))
  2863. return NULL;
  2864. result = PyTuple_New(self->groups-1);
  2865. if (!result)
  2866. return NULL;
  2867. for (index = 1; index < self->groups; index++) {
  2868. PyObject* item;
  2869. item = match_getslice_by_index(self, index, def);
  2870. if (!item) {
  2871. Py_DECREF(result);
  2872. return NULL;
  2873. }
  2874. PyTuple_SET_ITEM(result, index-1, item);
  2875. }
  2876. return result;
  2877. }
  2878. static PyObject*
  2879. match_groupdict(MatchObject* self, PyObject* args, PyObject* kw)
  2880. {
  2881. PyObject* result;
  2882. PyObject* keys;
  2883. Py_ssize_t index;
  2884. PyObject* def = Py_None;
  2885. static char* kwlist[] = { "default", NULL };
  2886. if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:groupdict", kwlist, &def))
  2887. return NULL;
  2888. result = PyDict_New();
  2889. if (!result || !self->pattern->groupindex)
  2890. return result;
  2891. keys = PyMapping_Keys(self->pattern->groupindex);
  2892. if (!keys)
  2893. goto failed;
  2894. for (index = 0; index < PyList_GET_SIZE(keys); index++) {
  2895. int status;
  2896. PyObject* key;
  2897. PyObject* value;
  2898. key = PyList_GET_ITEM(keys, index);
  2899. if (!key)
  2900. goto failed;
  2901. value = match_getslice(self, key, def);
  2902. if (!value) {
  2903. Py_DECREF(key);
  2904. goto failed;
  2905. }
  2906. status = PyDict_SetItem(result, key, value);
  2907. Py_DECREF(value);
  2908. if (status < 0)
  2909. goto failed;
  2910. }
  2911. Py_DECREF(keys);
  2912. return result;
  2913. failed:
  2914. Py_XDECREF(keys);
  2915. Py_DECREF(result);
  2916. return NULL;
  2917. }
  2918. static PyObject*
  2919. match_start(MatchObject* self, PyObject* args)
  2920. {
  2921. Py_ssize_t index;
  2922. PyObject* index_ = Py_False; /* zero */
  2923. if (!PyArg_UnpackTuple(args, "start", 0, 1, &index_))
  2924. return NULL;
  2925. index = match_getindex(self, index_);
  2926. if (index < 0 || index >= self->groups) {
  2927. PyErr_SetString(
  2928. PyExc_IndexError,
  2929. "no such group"
  2930. );
  2931. return NULL;
  2932. }
  2933. /* mark is -1 if group is undefined */
  2934. return Py_BuildValue("i", self->mark[index*2]);
  2935. }
  2936. static PyObject*
  2937. match_end(MatchObject* self, PyObject* args)
  2938. {
  2939. Py_ssize_t index;
  2940. PyObject* index_ = Py_False; /* zero */
  2941. if (!PyArg_UnpackTuple(args, "end", 0, 1, &index_))
  2942. return NULL;
  2943. index = match_getindex(self, index_);
  2944. if (index < 0 || index >= self->groups) {
  2945. PyErr_SetString(
  2946. PyExc_IndexError,
  2947. "no such group"
  2948. );
  2949. return NULL;
  2950. }
  2951. /* mark is -1 if group is undefined */
  2952. return Py_BuildValue("i", self->mark[index*2+1]);
  2953. }
  2954. LOCAL(PyObject*)
  2955. _pair(Py_ssize_t i1, Py_ssize_t i2)
  2956. {
  2957. PyObject* pair;
  2958. PyObject* item;
  2959. pair = PyTuple_New(2);
  2960. if (!pair)
  2961. return NULL;
  2962. item = PyInt_FromSsize_t(i1);
  2963. if (!item)
  2964. goto error;
  2965. PyTuple_SET_ITEM(pair, 0, item);
  2966. item = PyInt_FromSsize_t(i2);
  2967. if (!item)
  2968. goto error;
  2969. PyTuple_SET_ITEM(pair, 1, item);
  2970. return pair;
  2971. error:
  2972. Py_DECREF(pair);
  2973. return NULL;
  2974. }
  2975. static PyObject*
  2976. match_span(MatchObject* self, PyObject* args)
  2977. {
  2978. Py_ssize_t index;
  2979. PyObject* index_ = Py_False; /* zero */
  2980. if (!PyArg_UnpackTuple(args, "span", 0, 1, &index_))
  2981. return NULL;
  2982. index = match_getindex(self, index_);
  2983. if (index < 0 || index >= self->groups) {
  2984. PyErr_SetString(
  2985. PyExc_IndexError,
  2986. "no such group"
  2987. );
  2988. return NULL;
  2989. }
  2990. /* marks are -1 if group is undefined */
  2991. return _pair(self->mark[index*2], self->mark[index*2+1]);
  2992. }
  2993. static PyObject*
  2994. match_regs(MatchObject* self)
  2995. {
  2996. PyObject* regs;
  2997. PyObject* item;
  2998. Py_ssize_t index;
  2999. regs = PyTuple_New(self->groups);
  3000. if (!regs)
  3001. return NULL;
  3002. for (index = 0; index < self->groups; index++) {
  3003. item = _pair(self->mark[index*2], self->mark[index*2+1]);
  3004. if (!item) {
  3005. Py_DECREF(regs);
  3006. return NULL;
  3007. }
  3008. PyTuple_SET_ITEM(regs, index, item);
  3009. }
  3010. Py_INCREF(regs);
  3011. self->regs = regs;
  3012. return regs;
  3013. }
  3014. static PyObject*
  3015. match_copy(MatchObject* self, PyObject *unused)
  3016. {
  3017. #ifdef USE_BUILTIN_COPY
  3018. MatchObject* copy;
  3019. Py_ssize_t slots, offset;
  3020. slots = 2 * (self->pattern->groups+1);
  3021. copy = PyObject_NEW_VAR(MatchObject, &Match_Type, slots);
  3022. if (!copy)
  3023. return NULL;
  3024. /* this value a constant, but any compiler should be able to
  3025. figure that out all by itself */
  3026. offset = offsetof(MatchObject, string);
  3027. Py_XINCREF(self->pattern);
  3028. Py_XINCREF(self->string);
  3029. Py_XINCREF(self->regs);
  3030. memcpy((char*) copy + offset, (char*) self + offset,
  3031. sizeof(MatchObject) + slots * sizeof(Py_ssize_t) - offset);
  3032. return (PyObject*) copy;
  3033. #else
  3034. PyErr_SetString(PyExc_TypeError, "cannot copy this match object");
  3035. return NULL;
  3036. #endif
  3037. }
  3038. static PyObject*
  3039. match_deepcopy(MatchObject* self, PyObject* memo)
  3040. {
  3041. #ifdef USE_BUILTIN_COPY
  3042. MatchObject* copy;
  3043. copy = (MatchObject*) match_copy(self);
  3044. if (!copy)
  3045. return NULL;
  3046. if (!deepcopy((PyObject**) &copy->pattern, memo) ||
  3047. !deepcopy(&copy->string, memo) ||
  3048. !deepcopy(&copy->regs, memo)) {
  3049. Py_DECREF(copy);
  3050. return NULL;
  3051. }
  3052. #else
  3053. PyErr_SetString(PyExc_TypeError, "cannot deepcopy this match object");
  3054. return NULL;
  3055. #endif
  3056. }
  3057. static PyMethodDef match_methods[] = {
  3058. {"group", (PyCFunction) match_group, METH_VARARGS},
  3059. {"start", (PyCFunction) match_start, METH_VARARGS},
  3060. {"end", (PyCFunction) match_end, METH_VARARGS},
  3061. {"span", (PyCFunction) match_span, METH_VARARGS},
  3062. {"groups", (PyCFunction) match_groups, METH_VARARGS|METH_KEYWORDS},
  3063. {"groupdict", (PyCFunction) match_groupdict, METH_VARARGS|METH_KEYWORDS},
  3064. {"expand", (PyCFunction) match_expand, METH_O},
  3065. {"__copy__", (PyCFunction) match_copy, METH_NOARGS},
  3066. {"__deepcopy__", (PyCFunction) match_deepcopy, METH_O},
  3067. {NULL, NULL}
  3068. };
  3069. static PyObject*
  3070. match_getattr(MatchObject* self, char* name)
  3071. {
  3072. PyObject* res;
  3073. res = Py_FindMethod(match_methods, (PyObject*) self, name);
  3074. if (res)
  3075. return res;
  3076. PyErr_Clear();
  3077. if (!strcmp(name, "lastindex")) {
  3078. if (self->lastindex >= 0)
  3079. return Py_BuildValue("i", self->lastindex);
  3080. Py_INCREF(Py_None);
  3081. return Py_None;
  3082. }
  3083. if (!strcmp(name, "lastgroup")) {
  3084. if (self->pattern->indexgroup && self->lastindex >= 0) {
  3085. PyObject* result = PySequence_GetItem(
  3086. self->pattern->indexgroup, self->lastindex
  3087. );
  3088. if (result)
  3089. return result;
  3090. PyErr_Clear();
  3091. }
  3092. Py_INCREF(Py_None);
  3093. return Py_None;
  3094. }
  3095. if (!strcmp(name, "string")) {
  3096. if (self->string) {
  3097. Py_INCREF(self->string);
  3098. return self->string;
  3099. } else {
  3100. Py_INCREF(Py_None);
  3101. return Py_None;
  3102. }
  3103. }
  3104. if (!strcmp(name, "regs")) {
  3105. if (self->regs) {
  3106. Py_INCREF(self->regs);
  3107. return self->regs;
  3108. } else
  3109. return match_regs(self);
  3110. }
  3111. if (!strcmp(name, "re")) {
  3112. Py_INCREF(self->pattern);
  3113. return (PyObject*) self->pattern;
  3114. }
  3115. if (!strcmp(name, "pos"))
  3116. return Py_BuildValue("i", self->pos);
  3117. if (!strcmp(name, "endpos"))
  3118. return Py_BuildValue("i", self->endpos);
  3119. PyErr_SetString(PyExc_AttributeError, name);
  3120. return NULL;
  3121. }
  3122. /* FIXME: implement setattr("string", None) as a special case (to
  3123. detach the associated string, if any */
  3124. statichere PyTypeObject Match_Type = {
  3125. PyObject_HEAD_INIT(NULL)
  3126. 0, "_" SRE_MODULE ".SRE_Match",
  3127. sizeof(MatchObject), sizeof(Py_ssize_t),
  3128. (destructor)match_dealloc, /*tp_dealloc*/
  3129. 0, /*tp_print*/
  3130. (getattrfunc)match_getattr /*tp_getattr*/
  3131. };
  3132. static PyObject*
  3133. pattern_new_match(PatternObject* pattern, SRE_STATE* state, int status)
  3134. {
  3135. /* create match object (from state object) */
  3136. MatchObject* match;
  3137. Py_ssize_t i, j;
  3138. char* base;
  3139. int n;
  3140. if (status > 0) {
  3141. /* create match object (with room for extra group marks) */
  3142. /* coverity[ampersand_in_size] */
  3143. match = PyObject_NEW_VAR(MatchObject, &Match_Type,
  3144. 2*(pattern->groups+1));
  3145. if (!match)
  3146. return NULL;
  3147. Py_INCREF(pattern);
  3148. match->pattern = pattern;
  3149. Py_INCREF(state->string);
  3150. match->string = state->string;
  3151. match->regs = NULL;
  3152. match->groups = pattern->groups+1;
  3153. /* fill in group slices */
  3154. base = (char*) state->beginning;
  3155. n = state->charsize;
  3156. match->mark[0] = ((char*) state->start - base) / n;
  3157. match->mark[1] = ((char*) state->ptr - base) / n;
  3158. for (i = j = 0; i < pattern->groups; i++, j+=2)
  3159. if (j+1 <= state->lastmark && state->mark[j] && state->mark[j+1]) {
  3160. match->mark[j+2] = ((char*) state->mark[j] - base) / n;
  3161. match->mark[j+3] = ((char*) state->mark[j+1] - base) / n;
  3162. } else
  3163. match->mark[j+2] = match->mark[j+3] = -1; /* undefined */
  3164. match->pos = state->pos;
  3165. match->endpos = state->endpos;
  3166. match->lastindex = state->lastindex;
  3167. return (PyObject*) match;
  3168. } else if (status == 0) {
  3169. /* no match */
  3170. Py_INCREF(Py_None);
  3171. return Py_None;
  3172. }
  3173. /* internal error */
  3174. pattern_error(status);
  3175. return NULL;
  3176. }
  3177. /* -------------------------------------------------------------------- */
  3178. /* scanner methods (experimental) */
  3179. static void
  3180. scanner_dealloc(ScannerObject* self)
  3181. {
  3182. state_fini(&self->state);
  3183. Py_XDECREF(self->pattern);
  3184. PyObject_DEL(self);
  3185. }
  3186. static PyObject*
  3187. scanner_match(ScannerObject* self, PyObject *unused)
  3188. {
  3189. SRE_STATE* state = &self->state;
  3190. PyObject* match;
  3191. int status;
  3192. state_reset(state);
  3193. state->ptr = state->start;
  3194. if (state->charsize == 1) {
  3195. status = sre_match(state, PatternObject_GetCode(self->pattern));
  3196. } else {
  3197. #if defined(HAVE_UNICODE)
  3198. status = sre_umatch(state, PatternObject_GetCode(self->pattern));
  3199. #endif
  3200. }
  3201. if (PyErr_Occurred())
  3202. return NULL;
  3203. match = pattern_new_match((PatternObject*) self->pattern,
  3204. state, status);
  3205. if (status == 0 || state->ptr == state->start)
  3206. state->start = (void*) ((char*) state->ptr + state->charsize);
  3207. else
  3208. state->start = state->ptr;
  3209. return match;
  3210. }
  3211. static PyObject*
  3212. scanner_search(ScannerObject* self, PyObject *unused)
  3213. {
  3214. SRE_STATE* state = &self->state;
  3215. PyObject* match;
  3216. int status;
  3217. state_reset(state);
  3218. state->ptr = state->start;
  3219. if (state->charsize == 1) {
  3220. status = sre_search(state, PatternObject_GetCode(self->pattern));
  3221. } else {
  3222. #if defined(HAVE_UNICODE)
  3223. status = sre_usearch(state, PatternObject_GetCode(self->pattern));
  3224. #endif
  3225. }
  3226. if (PyErr_Occurred())
  3227. return NULL;
  3228. match = pattern_new_match((PatternObject*) self->pattern,
  3229. state, status);
  3230. if (status == 0 || state->ptr == state->start)
  3231. state->start = (void*) ((char*) state->ptr + state->charsize);
  3232. else
  3233. state->start = state->ptr;
  3234. return match;
  3235. }
  3236. static PyMethodDef scanner_methods[] = {
  3237. {"match", (PyCFunction) scanner_match, METH_NOARGS},
  3238. {"search", (PyCFunction) scanner_search, METH_NOARGS},
  3239. {NULL, NULL}
  3240. };
  3241. static PyObject*
  3242. scanner_getattr(ScannerObject* self, char* name)
  3243. {
  3244. PyObject* res;
  3245. res = Py_FindMethod(scanner_methods, (PyObject*) self, name);
  3246. if (res)
  3247. return res;
  3248. PyErr_Clear();
  3249. /* attributes */
  3250. if (!strcmp(name, "pattern")) {
  3251. Py_INCREF(self->pattern);
  3252. return self->pattern;
  3253. }
  3254. PyErr_SetString(PyExc_AttributeError, name);
  3255. return NULL;
  3256. }
  3257. statichere PyTypeObject Scanner_Type = {
  3258. PyObject_HEAD_INIT(NULL)
  3259. 0, "_" SRE_MODULE ".SRE_Scanner",
  3260. sizeof(ScannerObject), 0,
  3261. (destructor)scanner_dealloc, /*tp_dealloc*/
  3262. 0, /*tp_print*/
  3263. (getattrfunc)scanner_getattr, /*tp_getattr*/
  3264. };
  3265. static PyObject*
  3266. pattern_scanner(PatternObject* pattern, PyObject* args)
  3267. {
  3268. /* create search state object */
  3269. ScannerObject* self;
  3270. PyObject* string;
  3271. Py_ssize_t start = 0;
  3272. Py_ssize_t end = PY_SSIZE_T_MAX;
  3273. if (!PyArg_ParseTuple(args, "O|nn:scanner", &string, &start, &end))
  3274. return NULL;
  3275. /* create scanner object */
  3276. self = PyObject_NEW(ScannerObject, &Scanner_Type);
  3277. if (!self)
  3278. return NULL;
  3279. self->pattern = NULL;
  3280. string = state_init(&self->state, pattern, string, start, end);
  3281. if (!string) {
  3282. Py_DECREF(self);
  3283. return NULL;
  3284. }
  3285. Py_INCREF(pattern);
  3286. self->pattern = (PyObject*) pattern;
  3287. return (PyObject*) self;
  3288. }
  3289. static PyMethodDef _functions[] = {
  3290. {"compile", _compile, METH_VARARGS},
  3291. {"getcodesize", sre_codesize, METH_NOARGS},
  3292. {"getlower", sre_getlower, METH_VARARGS},
  3293. {NULL, NULL}
  3294. };
  3295. #if PY_VERSION_HEX < 0x02030000
  3296. DL_EXPORT(void) init_sre(void)
  3297. #else
  3298. PyMODINIT_FUNC init_sre(void)
  3299. #endif
  3300. {
  3301. PyObject* m;
  3302. PyObject* d;
  3303. PyObject* x;
  3304. /* Patch object types */
  3305. Pattern_Type.ob_type = Match_Type.ob_type =
  3306. Scanner_Type.ob_type = &PyType_Type;
  3307. m = Py_InitModule("_" SRE_MODULE, _functions);
  3308. if (m == NULL)
  3309. return;
  3310. d = PyModule_GetDict(m);
  3311. x = PyInt_FromLong(SRE_MAGIC);
  3312. if (x) {
  3313. PyDict_SetItemString(d, "MAGIC", x);
  3314. Py_DECREF(x);
  3315. }
  3316. x = PyInt_FromLong(sizeof(SRE_CODE));
  3317. if (x) {
  3318. PyDict_SetItemString(d, "CODESIZE", x);
  3319. Py_DECREF(x);
  3320. }
  3321. x = PyString_FromString(copyright);
  3322. if (x) {
  3323. PyDict_SetItemString(d, "copyright", x);
  3324. Py_DECREF(x);
  3325. }
  3326. }
  3327. #endif /* !defined(SRE_RECURSIVE) */
  3328. /* vim:ts=4:sw=4:et
  3329. */