home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Modules / _sre.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  63.0 KB  |  2,341 lines

  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 (0.5)
  9.  * 2000-06-30 fl  added fast search optimization (0.9.3)
  10.  * 2000-06-30 fl  added assert (lookahead) primitives, etc (0.9.4)
  11.  * 2000-07-02 fl  added charset optimizations, etc (0.9.5)
  12.  * 2000-07-03 fl  store code in pattern object, lookbehind, etc
  13.  * 2000-07-08 fl  added regs attribute
  14.  * 2000-07-21 fl  reset lastindex in scanner methods (0.9.6)
  15.  * 2000-08-01 fl  fixes for 1.6b1 (0.9.8)
  16.  * 2000-08-03 fl  added recursion limit
  17.  * 2000-08-07 fl  use PyOS_CheckStack() if available
  18.  * 2000-08-08 fl  changed findall to return empty strings instead of None
  19.  * 2000-08-27 fl  properly propagate memory errors
  20.  * 2000-09-02 fl  return -1 instead of None for start/end/span
  21.  * 2000-09-20 fl  added expand method
  22.  * 2000-09-21 fl  don't use the buffer interface for unicode strings
  23.  * 2000-10-03 fl  fixed assert_not primitive; support keyword arguments
  24.  *
  25.  * Copyright (c) 1997-2000 by Secret Labs AB.  All rights reserved.
  26.  *
  27.  * This version of the SRE library can be redistributed under CNRI's
  28.  * Python 1.6 license.  For any other use, please contact Secret Labs
  29.  * AB (info@pythonware.com).
  30.  *
  31.  * Portions of this engine have been developed in cooperation with
  32.  * CNRI.  Hewlett-Packard provided funding for 1.6 integration and
  33.  * other compatibility work.
  34.  */
  35.  
  36. #ifndef SRE_RECURSIVE
  37.  
  38. char copyright[] = " SRE 0.9.8 Copyright (c) 1997-2000 by Secret Labs AB ";
  39.  
  40. #include "Python.h"
  41.  
  42. #include "sre.h"
  43.  
  44. #include <ctype.h>
  45.  
  46. /* name of this module, minus the leading underscore */
  47. #define MODULE "sre"
  48.  
  49. /* defining this one enables tracing */
  50. #undef VERBOSE
  51.  
  52. #if PY_VERSION_HEX >= 0x01060000
  53. /* defining this enables unicode support (default under 1.6a1 and later) */
  54. #define HAVE_UNICODE
  55. #endif
  56.  
  57. /* -------------------------------------------------------------------- */
  58. /* optional features */
  59.  
  60. /* prevent run-away recursion (bad patterns on long strings) */
  61.  
  62. #if !defined(USE_STACKCHECK)
  63. #if defined(MS_WIN64) || defined(__LP64__) || defined(_LP64)
  64. /* require smaller recursion limit for a number of 64-bit platforms:
  65.    Win64 (MS_WIN64), Linux64 (__LP64__), Monterey (64-bit AIX) (_LP64) */
  66. /* FIXME: maybe the limit should be 40000 / sizeof(void*) ? */
  67. #define USE_RECURSION_LIMIT 7500
  68. #else
  69. #define USE_RECURSION_LIMIT 10000
  70. #endif
  71. #endif
  72.  
  73. /* enables fast searching */
  74. #define USE_FAST_SEARCH
  75.  
  76. /* enables aggressive inlining (always on for Visual C) */
  77. #undef USE_INLINE
  78.  
  79. /* -------------------------------------------------------------------- */
  80.  
  81. #if defined(_MSC_VER)
  82. #pragma optimize("agtw", on) /* doesn't seem to make much difference... */
  83. #pragma warning(disable: 4710) /* who cares if functions are not inlined ;-) */
  84. /* fastest possible local call under MSVC */
  85. #define LOCAL(type) static __inline type __fastcall
  86. #elif defined(USE_INLINE)
  87. #define LOCAL(type) static inline type
  88. #else
  89. #define LOCAL(type) static type
  90. #endif
  91.  
  92. /* error codes */
  93. #define SRE_ERROR_ILLEGAL -1 /* illegal opcode */
  94. #define SRE_ERROR_STATE -2 /* illegal state */
  95. #define SRE_ERROR_RECURSION_LIMIT -3 /* runaway recursion */
  96. #define SRE_ERROR_MEMORY -9 /* out of memory */
  97.  
  98. #if defined(VERBOSE)
  99. #define TRACE(v) printf v
  100. #else
  101. #define TRACE(v)
  102. #endif
  103.  
  104. /* -------------------------------------------------------------------- */
  105. /* search engine state */
  106.  
  107. /* default character predicates (run sre_chars.py to regenerate tables) */
  108.  
  109. #define SRE_DIGIT_MASK 1
  110. #define SRE_SPACE_MASK 2
  111. #define SRE_LINEBREAK_MASK 4
  112. #define SRE_ALNUM_MASK 8
  113. #define SRE_WORD_MASK 16
  114.  
  115. static char sre_char_info[128] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 2,
  116. 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0,
  117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 25, 25, 25, 25, 25, 25, 25,
  118. 25, 25, 0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  119. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0,
  120. 0, 0, 16, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  121. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 0, 0, 0 };
  122.  
  123. static char sre_char_lower[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  124. 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
  125. 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
  126. 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
  127. 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
  128. 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  129. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
  130. 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  131. 120, 121, 122, 123, 124, 125, 126, 127 };
  132.  
  133. static unsigned int sre_lower(unsigned int ch)
  134. {
  135.     return ((ch) < 128 ? sre_char_lower[ch] : ch);
  136. }
  137.  
  138. #define SRE_IS_DIGIT(ch)\
  139.     ((ch) < 128 ? (sre_char_info[(ch)] & SRE_DIGIT_MASK) : 0)
  140. #define SRE_IS_SPACE(ch)\
  141.     ((ch) < 128 ? (sre_char_info[(ch)] & SRE_SPACE_MASK) : 0)
  142. #define SRE_IS_LINEBREAK(ch)\
  143.     ((ch) < 128 ? (sre_char_info[(ch)] & SRE_LINEBREAK_MASK) : 0)
  144. #define SRE_IS_ALNUM(ch)\
  145.     ((ch) < 128 ? (sre_char_info[(ch)] & SRE_ALNUM_MASK) : 0)
  146. #define SRE_IS_WORD(ch)\
  147.     ((ch) < 128 ? (sre_char_info[(ch)] & SRE_WORD_MASK) : 0)
  148.  
  149. /* locale-specific character predicates */
  150.  
  151. static unsigned int sre_lower_locale(unsigned int ch)
  152. {
  153.     return ((ch) < 256 ? tolower((ch)) : ch);
  154. }
  155. #define SRE_LOC_IS_DIGIT(ch) ((ch) < 256 ? isdigit((ch)) : 0)
  156. #define SRE_LOC_IS_SPACE(ch) ((ch) < 256 ? isspace((ch)) : 0)
  157. #define SRE_LOC_IS_LINEBREAK(ch) ((ch) == '\n')
  158. #define SRE_LOC_IS_ALNUM(ch) ((ch) < 256 ? isalnum((ch)) : 0)
  159. #define SRE_LOC_IS_WORD(ch) (SRE_LOC_IS_ALNUM((ch)) || (ch) == '_')
  160.  
  161. /* unicode-specific character predicates */
  162.  
  163. #if defined(HAVE_UNICODE)
  164. static unsigned int sre_lower_unicode(unsigned int ch)
  165. {
  166.     return (unsigned int) Py_UNICODE_TOLOWER((Py_UNICODE)(ch));
  167. }
  168. #define SRE_UNI_IS_DIGIT(ch) Py_UNICODE_ISDIGIT((Py_UNICODE)(ch))
  169. #define SRE_UNI_IS_SPACE(ch) Py_UNICODE_ISSPACE((Py_UNICODE)(ch))
  170. #define SRE_UNI_IS_LINEBREAK(ch) Py_UNICODE_ISLINEBREAK((Py_UNICODE)(ch))
  171. #define SRE_UNI_IS_ALNUM(ch) Py_UNICODE_ISALNUM((Py_UNICODE)(ch))
  172. #define SRE_UNI_IS_WORD(ch) (SRE_UNI_IS_ALNUM((ch)) || (ch) == '_')
  173. #endif
  174.  
  175. LOCAL(int)
  176. sre_category(SRE_CODE category, unsigned int ch)
  177. {
  178.     switch (category) {
  179.  
  180.     case SRE_CATEGORY_DIGIT:
  181.         return SRE_IS_DIGIT(ch);
  182.     case SRE_CATEGORY_NOT_DIGIT:
  183.         return !SRE_IS_DIGIT(ch);
  184.     case SRE_CATEGORY_SPACE:
  185.         return SRE_IS_SPACE(ch);
  186.     case SRE_CATEGORY_NOT_SPACE:
  187.         return !SRE_IS_SPACE(ch);
  188.     case SRE_CATEGORY_WORD:
  189.         return SRE_IS_WORD(ch);
  190.     case SRE_CATEGORY_NOT_WORD:
  191.         return !SRE_IS_WORD(ch);
  192.     case SRE_CATEGORY_LINEBREAK:
  193.         return SRE_IS_LINEBREAK(ch);
  194.     case SRE_CATEGORY_NOT_LINEBREAK:
  195.         return !SRE_IS_LINEBREAK(ch);
  196.  
  197.     case SRE_CATEGORY_LOC_WORD:
  198.         return SRE_LOC_IS_WORD(ch);
  199.     case SRE_CATEGORY_LOC_NOT_WORD:
  200.         return !SRE_LOC_IS_WORD(ch);
  201.  
  202. #if defined(HAVE_UNICODE)
  203.     case SRE_CATEGORY_UNI_DIGIT:
  204.         return SRE_UNI_IS_DIGIT(ch);
  205.     case SRE_CATEGORY_UNI_NOT_DIGIT:
  206.         return !SRE_UNI_IS_DIGIT(ch);
  207.     case SRE_CATEGORY_UNI_SPACE:
  208.         return SRE_UNI_IS_SPACE(ch);
  209.     case SRE_CATEGORY_UNI_NOT_SPACE:
  210.         return !SRE_UNI_IS_SPACE(ch);
  211.     case SRE_CATEGORY_UNI_WORD:
  212.         return SRE_UNI_IS_WORD(ch);
  213.     case SRE_CATEGORY_UNI_NOT_WORD:
  214.         return !SRE_UNI_IS_WORD(ch);
  215.     case SRE_CATEGORY_UNI_LINEBREAK:
  216.         return SRE_UNI_IS_LINEBREAK(ch);
  217.     case SRE_CATEGORY_UNI_NOT_LINEBREAK:
  218.         return !SRE_UNI_IS_LINEBREAK(ch);
  219. #endif
  220.     }
  221.     return 0;
  222. }
  223.  
  224. /* helpers */
  225.  
  226. static void
  227. mark_fini(SRE_STATE* state)
  228. {
  229.     if (state->mark_stack) {
  230.         free(state->mark_stack);
  231.         state->mark_stack = NULL;
  232.     }
  233.     state->mark_stack_size = state->mark_stack_base = 0;
  234. }
  235.  
  236. static int
  237. mark_save(SRE_STATE* state, int lo, int hi)
  238. {
  239.     void* stack;
  240.     int size;
  241.     int minsize, newsize;
  242.  
  243.     if (hi <= lo)
  244.         return 0;
  245.  
  246.     size = (hi - lo) + 1;
  247.  
  248.     newsize = state->mark_stack_size;
  249.     minsize = state->mark_stack_base + size;
  250.  
  251.     if (newsize < minsize) {
  252.         /* create new stack */
  253.         if (!newsize) {
  254.             newsize = 512;
  255.             if (newsize < minsize)
  256.                 newsize = minsize;
  257.             TRACE(("allocate stack %d\n", newsize));
  258.             stack = malloc(sizeof(void*) * newsize);
  259.         } else {
  260.             /* grow the stack */
  261.             while (newsize < minsize)
  262.                 newsize += newsize;
  263.             TRACE(("grow stack to %d\n", newsize));
  264.             stack = realloc(state->mark_stack, sizeof(void*) * newsize);
  265.         }
  266.         if (!stack) {
  267.             mark_fini(state);
  268.             return SRE_ERROR_MEMORY;
  269.         }
  270.         state->mark_stack = stack;
  271.         state->mark_stack_size = newsize;
  272.     }
  273.  
  274.     TRACE(("copy %d:%d to %d (%d)\n", lo, hi, state->mark_stack_base, size));
  275.  
  276.     memcpy(state->mark_stack + state->mark_stack_base, state->mark + lo,
  277.            size * sizeof(void*));
  278.  
  279.     state->mark_stack_base += size;
  280.  
  281.     return 0;
  282. }
  283.  
  284. static int
  285. mark_restore(SRE_STATE* state, int lo, int hi)
  286. {
  287.     int size;
  288.  
  289.     if (hi <= lo)
  290.         return 0;
  291.  
  292.     size = (hi - lo) + 1;
  293.  
  294.     state->mark_stack_base -= size;
  295.  
  296.     TRACE(("copy %d:%d from %d\n", lo, hi, state->mark_stack_base));
  297.  
  298.     memcpy(state->mark + lo, state->mark_stack + state->mark_stack_base,
  299.            size * sizeof(void*));
  300.  
  301.     return 0;
  302. }
  303.  
  304. /* generate 8-bit version */
  305.  
  306. #define SRE_CHAR unsigned char
  307. #define SRE_AT sre_at
  308. #define SRE_COUNT sre_count
  309. #define SRE_CHARSET sre_charset
  310. #define SRE_INFO sre_info
  311. #define SRE_MATCH sre_match
  312. #define SRE_SEARCH sre_search
  313.  
  314. #if defined(HAVE_UNICODE)
  315.  
  316. #define SRE_RECURSIVE
  317. #include "_sre.c"
  318. #undef SRE_RECURSIVE
  319.  
  320. #undef SRE_SEARCH
  321. #undef SRE_MATCH
  322. #undef SRE_INFO
  323. #undef SRE_CHARSET
  324. #undef SRE_COUNT
  325. #undef SRE_AT
  326. #undef SRE_CHAR
  327.  
  328. /* generate 16-bit unicode version */
  329.  
  330. #define SRE_CHAR Py_UNICODE
  331. #define SRE_AT sre_uat
  332. #define SRE_COUNT sre_ucount
  333. #define SRE_CHARSET sre_ucharset
  334. #define SRE_INFO sre_uinfo
  335. #define SRE_MATCH sre_umatch
  336. #define SRE_SEARCH sre_usearch
  337. #endif
  338.  
  339. #endif /* SRE_RECURSIVE */
  340.  
  341. /* -------------------------------------------------------------------- */
  342. /* String matching engine */
  343.  
  344. /* the following section is compiled twice, with different character
  345.    settings */
  346.  
  347. LOCAL(int)
  348. SRE_AT(SRE_STATE* state, SRE_CHAR* ptr, SRE_CODE at)
  349. {
  350.     /* check if pointer is at given position */
  351.  
  352.     int this, that;
  353.  
  354.     switch (at) {
  355.  
  356.     case SRE_AT_BEGINNING:
  357.         return ((void*) ptr == state->beginning);
  358.  
  359.     case SRE_AT_BEGINNING_LINE:
  360.         return ((void*) ptr == state->beginning ||
  361.                 SRE_IS_LINEBREAK((int) ptr[-1]));
  362.  
  363.     case SRE_AT_END:
  364.         return (((void*) (ptr+1) == state->end &&
  365.                  SRE_IS_LINEBREAK((int) ptr[0])) ||
  366.                 ((void*) ptr == state->end));
  367.  
  368.     case SRE_AT_END_LINE:
  369.         return ((void*) ptr == state->end ||
  370.                 SRE_IS_LINEBREAK((int) ptr[0]));
  371.  
  372.     case SRE_AT_BOUNDARY:
  373.         if (state->beginning == state->end)
  374.             return 0;
  375.         that = ((void*) ptr > state->beginning) ?
  376.             SRE_IS_WORD((int) ptr[-1]) : 0;
  377.         this = ((void*) ptr < state->end) ?
  378.             SRE_IS_WORD((int) ptr[0]) : 0;
  379.         return this != that;
  380.  
  381.     case SRE_AT_NON_BOUNDARY:
  382.         if (state->beginning == state->end)
  383.             return 0;
  384.         that = ((void*) ptr > state->beginning) ?
  385.             SRE_IS_WORD((int) ptr[-1]) : 0;
  386.         this = ((void*) ptr < state->end) ?
  387.             SRE_IS_WORD((int) ptr[0]) : 0;
  388.         return this == that;
  389.     }
  390.  
  391.     return 0;
  392. }
  393.  
  394. LOCAL(int)
  395. SRE_CHARSET(SRE_CODE* set, SRE_CODE ch)
  396. {
  397.     /* check if character is a member of the given set */
  398.  
  399.     int ok = 1;
  400.  
  401.     for (;;) {
  402.         switch (*set++) {
  403.  
  404.         case SRE_OP_LITERAL:
  405.             /* <LITERAL> <code> */
  406.             if (ch == set[0])
  407.                 return ok;
  408.             set++;
  409.             break;
  410.  
  411.         case SRE_OP_RANGE:
  412.             /* <RANGE> <lower> <upper> */
  413.             if (set[0] <= ch && ch <= set[1])
  414.                 return ok;
  415.             set += 2;
  416.             break;
  417.  
  418.         case SRE_OP_CHARSET:
  419.             /* <CHARSET> <bitmap> (16 bits per code word) */
  420.             if (ch < 256 && (set[ch >> 4] & (1 << (ch & 15))))
  421.                 return ok;
  422.             set += 16;
  423.             break;
  424.  
  425.         case SRE_OP_CATEGORY:
  426.             /* <CATEGORY> <code> */
  427.             if (sre_category(set[0], (int) ch))
  428.                 return ok;
  429.             set += 1;
  430.             break;
  431.  
  432.         case SRE_OP_NEGATE:
  433.             ok = !ok;
  434.             break;
  435.  
  436.         case SRE_OP_FAILURE:
  437.             return !ok;
  438.  
  439.         default:
  440.             /* internal error -- there's not much we can do about it
  441.                here, so let's just pretend it didn't match... */
  442.             return 0;
  443.         }
  444.     }
  445. }
  446.  
  447. LOCAL(int) SRE_MATCH(SRE_STATE* state, SRE_CODE* pattern, int level);
  448.  
  449. LOCAL(int)
  450. SRE_COUNT(SRE_STATE* state, SRE_CODE* pattern, int maxcount, int level)
  451. {
  452.     SRE_CODE chr;
  453.     SRE_CHAR* ptr = state->ptr;
  454.     SRE_CHAR* end = state->end;
  455.     int i;
  456.  
  457.     /* adjust end */
  458.     if (maxcount < end - ptr && maxcount != 65535)
  459.         end = ptr + maxcount;
  460.  
  461.     switch (pattern[0]) {
  462.  
  463.     case SRE_OP_ANY:
  464.         /* repeated dot wildcard. */
  465.         TRACE(("|%p|%p|COUNT ANY\n", pattern, ptr));
  466.         while (ptr < end && !SRE_IS_LINEBREAK(*ptr))
  467.             ptr++;
  468.         break;
  469.  
  470.     case SRE_OP_ANY_ALL:
  471.         /* repeated dot wildcare.  skip to the end of the target
  472.            string, and backtrack from there */
  473.         TRACE(("|%p|%p|COUNT ANY_ALL\n", pattern, ptr));
  474.         ptr = end;
  475.         break;
  476.  
  477.     case SRE_OP_LITERAL:
  478.         /* repeated literal */
  479.         chr = pattern[1];
  480.         TRACE(("|%p|%p|COUNT LITERAL %d\n", pattern, ptr, chr));
  481.         while (ptr < end && (SRE_CODE) *ptr == chr)
  482.             ptr++;
  483.         break;
  484.  
  485.     case SRE_OP_LITERAL_IGNORE:
  486.         /* repeated literal */
  487.         chr = pattern[1];
  488.         TRACE(("|%p|%p|COUNT LITERAL_IGNORE %d\n", pattern, ptr, chr));
  489.         while (ptr < end && (SRE_CODE) state->lower(*ptr) == chr)
  490.             ptr++;
  491.         break;
  492.  
  493.     case SRE_OP_NOT_LITERAL:
  494.         /* repeated non-literal */
  495.         chr = pattern[1];
  496.         TRACE(("|%p|%p|COUNT NOT_LITERAL %d\n", pattern, ptr, chr));
  497.         while (ptr < end && (SRE_CODE) *ptr != chr)
  498.             ptr++;
  499.         break;
  500.                 
  501.     case SRE_OP_NOT_LITERAL_IGNORE:
  502.         /* repeated non-literal */
  503.         chr = pattern[1];
  504.         TRACE(("|%p|%p|COUNT NOT_LITERAL_IGNORE %d\n", pattern, ptr, chr));
  505.         while (ptr < end && (SRE_CODE) state->lower(*ptr) != chr)
  506.             ptr++;
  507.         break;
  508.  
  509.     case SRE_OP_IN:
  510.         /* repeated set */
  511.         TRACE(("|%p|%p|COUNT IN\n", pattern, ptr));
  512.         while (ptr < end && SRE_CHARSET(pattern + 2, *ptr))
  513.             ptr++;
  514.         break;
  515.  
  516.     default:
  517.         /* repeated single character pattern */
  518.         TRACE(("|%p|%p|COUNT SUBPATTERN\n", pattern, ptr));
  519.         while ((SRE_CHAR*) state->ptr < end) {
  520.             i = SRE_MATCH(state, pattern, level);
  521.             if (i < 0)
  522.                 return i;
  523.             if (!i)
  524.                 break;
  525.         }
  526.         TRACE(("|%p|%p|COUNT %d\n", pattern, ptr,
  527.                (SRE_CHAR*) state->ptr - ptr));
  528.         return (SRE_CHAR*) state->ptr - ptr;
  529.     }
  530.  
  531.     TRACE(("|%p|%p|COUNT %d\n", pattern, ptr, ptr - (SRE_CHAR*) state->ptr));
  532.     return ptr - (SRE_CHAR*) state->ptr;
  533. }
  534.  
  535. #if 0 /* not used in this release */
  536. LOCAL(int)
  537. SRE_INFO(SRE_STATE* state, SRE_CODE* pattern)
  538. {
  539.     /* check if an SRE_OP_INFO block matches at the current position.
  540.        returns the number of SRE_CODE objects to skip if successful, 0
  541.        if no match */
  542.  
  543.     SRE_CHAR* end = state->end;
  544.     SRE_CHAR* ptr = state->ptr;
  545.     int i;
  546.  
  547.     /* check minimal length */
  548.     if (pattern[3] && (end - ptr) < pattern[3])
  549.         return 0;
  550.  
  551.     /* check known prefix */
  552.     if (pattern[2] & SRE_INFO_PREFIX && pattern[5] > 1) {
  553.         /* <length> <skip> <prefix data> <overlap data> */
  554.         for (i = 0; i < pattern[5]; i++)
  555.             if ((SRE_CODE) ptr[i] != pattern[7 + i])
  556.                 return 0;
  557.         return pattern[0] + 2 * pattern[6];
  558.     }
  559.     return pattern[0];
  560. }
  561. #endif
  562.  
  563. LOCAL(int)
  564. SRE_MATCH(SRE_STATE* state, SRE_CODE* pattern, int level)
  565. {
  566.     /* check if string matches the given pattern.  returns <0 for
  567.        error, 0 for failure, and 1 for success */
  568.  
  569.     SRE_CHAR* end = state->end;
  570.     SRE_CHAR* ptr = state->ptr;
  571.     int i, count;
  572.     SRE_REPEAT* rp;
  573.     int lastmark;
  574.     SRE_CODE chr;
  575.  
  576.     SRE_REPEAT rep; /* FIXME: <fl> allocate in STATE instead */
  577.  
  578.     TRACE(("|%p|%p|ENTER %d\n", pattern, ptr, level));
  579.  
  580. #if defined(USE_STACKCHECK)
  581.     if (level % 10 == 0 && PyOS_CheckStack())
  582.         return SRE_ERROR_RECURSION_LIMIT;
  583. #endif
  584.  
  585. #if defined(USE_RECURSION_LIMIT)
  586.     if (level > USE_RECURSION_LIMIT)
  587.         return SRE_ERROR_RECURSION_LIMIT;
  588. #endif
  589.  
  590.     if (pattern[0] == SRE_OP_INFO) {
  591.         /* optimization info block */
  592.         /* <INFO> <1=skip> <2=flags> <3=min> ... */
  593.         if (pattern[3] && (end - ptr) < pattern[3]) {
  594.             TRACE(("reject (got %d chars, need %d)\n",
  595.                    (end - ptr), pattern[3]));
  596.             return 0;
  597.         }
  598.         pattern += pattern[1] + 1;
  599.     }
  600.  
  601.     for (;;) {
  602.  
  603.         switch (*pattern++) {
  604.  
  605.         case SRE_OP_FAILURE:
  606.             /* immediate failure */
  607.             TRACE(("|%p|%p|FAILURE\n", pattern, ptr));
  608.             return 0;
  609.  
  610.         case SRE_OP_SUCCESS:
  611.             /* end of pattern */
  612.             TRACE(("|%p|%p|SUCCESS\n", pattern, ptr));
  613.             state->ptr = ptr;
  614.             return 1;
  615.  
  616.         case SRE_OP_AT:
  617.             /* match at given position */
  618.             /* <AT> <code> */
  619.             TRACE(("|%p|%p|AT %d\n", pattern, ptr, *pattern));
  620.             if (!SRE_AT(state, ptr, *pattern))
  621.                 return 0;
  622.             pattern++;
  623.             break;
  624.  
  625.         case SRE_OP_CATEGORY:
  626.             /* match at given category */
  627.             /* <CATEGORY> <code> */
  628.             TRACE(("|%p|%p|CATEGORY %d\n", pattern, ptr, *pattern));
  629.             if (ptr >= end || !sre_category(pattern[0], ptr[0]))
  630.                 return 0;
  631.             pattern++;
  632.             ptr++;
  633.             break;
  634.  
  635.         case SRE_OP_LITERAL:
  636.             /* match literal string */
  637.             /* <LITERAL> <code> */
  638.             TRACE(("|%p|%p|LITERAL %d\n", pattern, ptr, *pattern));
  639.             if (ptr >= end || (SRE_CODE) ptr[0] != pattern[0])
  640.                 return 0;
  641.             pattern++;
  642.             ptr++;
  643.             break;
  644.  
  645.         case SRE_OP_NOT_LITERAL:
  646.             /* match anything that is not literal character */
  647.             /* <NOT_LITERAL> <code> */
  648.             TRACE(("|%p|%p|NOT_LITERAL %d\n", pattern, ptr, *pattern));
  649.             if (ptr >= end || (SRE_CODE) ptr[0] == pattern[0])
  650.                 return 0;
  651.             pattern++;
  652.             ptr++;
  653.             break;
  654.  
  655.         case SRE_OP_ANY:
  656.             /* match anything (except a newline) */
  657.             /* <ANY> */
  658.             TRACE(("|%p|%p|ANY\n", pattern, ptr));
  659.             if (ptr >= end || SRE_IS_LINEBREAK(ptr[0]))
  660.                 return 0;
  661.             ptr++;
  662.             break;
  663.  
  664.         case SRE_OP_ANY_ALL:
  665.             /* match anything */
  666.             /* <ANY_ALL> */
  667.             TRACE(("|%p|%p|ANY_ALL\n", pattern, ptr));
  668.             if (ptr >= end)
  669.                 return 0;
  670.             ptr++;
  671.             break;
  672.  
  673.         case SRE_OP_IN:
  674.             /* match set member (or non_member) */
  675.             /* <IN> <skip> <set> */
  676.             TRACE(("|%p|%p|IN\n", pattern, ptr));
  677.             if (ptr >= end || !SRE_CHARSET(pattern + 1, *ptr))
  678.                 return 0;
  679.             pattern += pattern[0];
  680.             ptr++;
  681.             break;
  682.  
  683.         case SRE_OP_GROUPREF:
  684.             /* match backreference */
  685.             TRACE(("|%p|%p|GROUPREF %d\n", pattern, ptr, pattern[0]));
  686.             i = pattern[0];
  687.             {
  688.                 SRE_CHAR* p = (SRE_CHAR*) state->mark[i+i];
  689.                 SRE_CHAR* e = (SRE_CHAR*) state->mark[i+i+1];
  690.                 if (!p || !e || e < p)
  691.                     return 0;
  692.                 while (p < e) {
  693.                     if (ptr >= end || *ptr != *p)
  694.                         return 0;
  695.                     p++; ptr++;
  696.                 }
  697.             }
  698.             pattern++;
  699.             break;
  700.  
  701.         case SRE_OP_GROUPREF_IGNORE:
  702.             /* match backreference */
  703.             TRACE(("|%p|%p|GROUPREF_IGNORE %d\n", pattern, ptr, pattern[0]));
  704.             i = pattern[0];
  705.             {
  706.                 SRE_CHAR* p = (SRE_CHAR*) state->mark[i+i];
  707.                 SRE_CHAR* e = (SRE_CHAR*) state->mark[i+i+1];
  708.                 if (!p || !e || e < p)
  709.                     return 0;
  710.                 while (p < e) {
  711.                     if (ptr >= end ||
  712.                         state->lower(*ptr) != state->lower(*p))
  713.                         return 0;
  714.                     p++; ptr++;
  715.                 }
  716.             }
  717.             pattern++;
  718.             break;
  719.  
  720.         case SRE_OP_LITERAL_IGNORE:
  721.             TRACE(("|%p|%p|LITERAL_IGNORE %d\n", pattern, ptr, pattern[0]));
  722.             if (ptr >= end ||
  723.                 state->lower(*ptr) != state->lower(*pattern))
  724.                 return 0;
  725.             pattern++;
  726.             ptr++;
  727.             break;
  728.  
  729.         case SRE_OP_NOT_LITERAL_IGNORE:
  730.             TRACE(("|%p|%p|NOT_LITERAL_IGNORE %d\n", pattern, ptr, *pattern));
  731.             if (ptr >= end ||
  732.                 state->lower(*ptr) == state->lower(*pattern))
  733.                 return 0;
  734.             pattern++;
  735.             ptr++;
  736.             break;
  737.  
  738.         case SRE_OP_IN_IGNORE:
  739.             TRACE(("|%p|%p|IN_IGNORE\n", pattern, ptr));
  740.             if (ptr >= end
  741.                 || !SRE_CHARSET(pattern + 1, (SRE_CODE) state->lower(*ptr)))
  742.                 return 0;
  743.             pattern += pattern[0];
  744.             ptr++;
  745.             break;
  746.  
  747.         case SRE_OP_MARK:
  748.             /* set mark */
  749.             /* <MARK> <gid> */
  750.             TRACE(("|%p|%p|MARK %d\n", pattern, ptr, pattern[0]));
  751.             i = pattern[0];
  752.             if (i & 1)
  753.                 state->lastindex = i/2 + 1;
  754.             if (i > state->lastmark)
  755.                 state->lastmark = i;
  756.             state->mark[i] = ptr;
  757.             pattern++;
  758.             break;
  759.  
  760.         case SRE_OP_JUMP:
  761.         case SRE_OP_INFO:
  762.             /* jump forward */
  763.             /* <JUMP> <offset> */
  764.             TRACE(("|%p|%p|JUMP %d\n", pattern, ptr, pattern[0]));
  765.             pattern += pattern[0];
  766.             break;
  767.  
  768.         case SRE_OP_ASSERT:
  769.             /* assert subpattern */
  770.             /* <ASSERT> <skip> <back> <pattern> */
  771.             TRACE(("|%p|%p|ASSERT %d\n", pattern, ptr, pattern[1]));
  772.             state->ptr = ptr - pattern[1];
  773.             if (state->ptr < state->beginning)
  774.                 return 0;
  775.             i = SRE_MATCH(state, pattern + 2, level + 1);
  776.             if (i <= 0)
  777.                 return i;
  778.             pattern += pattern[0];
  779.             break;
  780.  
  781.         case SRE_OP_ASSERT_NOT:
  782.             /* assert not subpattern */
  783.             /* <ASSERT_NOT> <skip> <back> <pattern> */
  784.             TRACE(("|%p|%p|ASSERT_NOT %d\n", pattern, ptr, pattern[1]));
  785.             state->ptr = ptr - pattern[1];
  786.             if (state->ptr < state->beginning)
  787.                 return 0;
  788.             i = SRE_MATCH(state, pattern + 2, level + 1);
  789.             if (i < 0)
  790.                 return i;
  791.             if (i)
  792.                 return 0;
  793.             pattern += pattern[0];
  794.             break;
  795.  
  796.         case SRE_OP_BRANCH:
  797.             /* alternation */
  798.             /* <BRANCH> <0=skip> code <JUMP> ... <NULL> */
  799.             TRACE(("|%p|%p|BRANCH\n", pattern, ptr));
  800.             lastmark = state->lastmark;
  801.             for (; pattern[0]; pattern += pattern[0]) {
  802.                 if (pattern[1] == SRE_OP_LITERAL &&
  803.                     (ptr >= end || (SRE_CODE) *ptr != pattern[2]))
  804.                     continue;
  805.                 if (pattern[1] == SRE_OP_IN &&
  806.                     (ptr >= end || !SRE_CHARSET(pattern + 3, (SRE_CODE) *ptr)))
  807.                     continue;
  808.                 state->ptr = ptr;
  809.                 i = SRE_MATCH(state, pattern + 1, level + 1);
  810.                 if (i)
  811.                     return i;
  812.                 if (state->lastmark > lastmark) {
  813.                     memset(
  814.                         state->mark + lastmark + 1, 0,
  815.                         (state->lastmark - lastmark) * sizeof(void*)
  816.                         );
  817.                     state->lastmark = lastmark;
  818.                 }
  819.             }
  820.             return 0;
  821.  
  822.         case SRE_OP_REPEAT_ONE:
  823.             /* match repeated sequence (maximizing regexp) */
  824.  
  825.             /* this operator only works if the repeated item is
  826.                exactly one character wide, and we're not already
  827.                collecting backtracking points.  for other cases,
  828.                use the MAX_REPEAT operator instead */
  829.  
  830.             /* <REPEAT_ONE> <skip> <1=min> <2=max> item <SUCCESS> tail */
  831.  
  832.             TRACE(("|%p|%p|REPEAT_ONE %d %d\n", pattern, ptr,
  833.                    pattern[1], pattern[2]));
  834.  
  835.             if (ptr + pattern[1] > end)
  836.                 return 0; /* cannot match */
  837.  
  838.             state->ptr = ptr;
  839.  
  840.             count = SRE_COUNT(state, pattern + 3, pattern[2], level + 1);
  841.             if (count < 0)
  842.                 return count;
  843.  
  844.             ptr += count;
  845.  
  846.             /* when we arrive here, count contains the number of
  847.                matches, and ptr points to the tail of the target
  848.                string.  check if the rest of the pattern matches,
  849.                and backtrack if not. */
  850.  
  851.             if (count < (int) pattern[1])
  852.                 return 0;
  853.  
  854.             if (pattern[pattern[0]] == SRE_OP_SUCCESS) {
  855.                 /* tail is empty.  we're finished */
  856.                 state->ptr = ptr;
  857.                 return 1;
  858.  
  859.             } else if (pattern[pattern[0]] == SRE_OP_LITERAL) {
  860.                 /* tail starts with a literal. skip positions where
  861.                    the rest of the pattern cannot possibly match */
  862.                 chr = pattern[pattern[0]+1];
  863.                 for (;;) {
  864.                     while (count >= (int) pattern[1] &&
  865.                            (ptr >= end || *ptr != chr)) {
  866.                         ptr--;
  867.                         count--;
  868.                     }
  869.                     if (count < (int) pattern[1])
  870.                         break;
  871.                     state->ptr = ptr;
  872.                     i = SRE_MATCH(state, pattern + pattern[0], level + 1);
  873.                     if (i)
  874.                         return i;
  875.                     ptr--;
  876.                     count--;
  877.                 }
  878.  
  879.             } else {
  880.                 /* general case */
  881.                 lastmark = state->lastmark;
  882.                 while (count >= (int) pattern[1]) {
  883.                     state->ptr = ptr;
  884.                     i = SRE_MATCH(state, pattern + pattern[0], level + 1);
  885.                     if (i)
  886.                         return i;
  887.                     ptr--;
  888.                     count--;
  889.                     if (state->lastmark > lastmark) {
  890.                         memset(
  891.                             state->mark + lastmark + 1, 0,
  892.                             (state->lastmark - lastmark) * sizeof(void*)
  893.                             );
  894.                         state->lastmark = lastmark;
  895.                     }
  896.                 }
  897.             }
  898.             return 0;
  899.  
  900.         case SRE_OP_REPEAT:
  901.             /* create repeat context.  all the hard work is done
  902.                by the UNTIL operator */
  903.             /* <REPEAT> <skip> <1=min> <2=max> item <UNTIL> tail */
  904.             TRACE(("|%p|%p|REPEAT %d %d\n", pattern, ptr,
  905.                    pattern[1], pattern[2]));
  906.  
  907.             rep.count = -1;
  908.             rep.pattern = pattern;
  909.  
  910.             /* install new repeat context */
  911.             rep.prev = state->repeat;
  912.             state->repeat = &rep;
  913.  
  914.             state->ptr = ptr;
  915.             i = SRE_MATCH(state, pattern + pattern[0], level + 1);
  916.  
  917.             state->repeat = rep.prev;
  918.  
  919.             return i;
  920.  
  921.         case SRE_OP_MAX_UNTIL:
  922.             /* maximizing repeat */
  923.             /* <REPEAT> <skip> <1=min> <2=max> item <MAX_UNTIL> tail */
  924.  
  925.             /* FIXME: we probably need to deal with zero-width
  926.                matches in here... */
  927.  
  928.             rp = state->repeat;
  929.             if (!rp)
  930.                 return SRE_ERROR_STATE;
  931.  
  932.             state->ptr = ptr;
  933.  
  934.             count = rp->count + 1;
  935.  
  936.             TRACE(("|%p|%p|MAX_UNTIL %d\n", pattern, ptr, count));
  937.  
  938.             if (count < rp->pattern[1]) {
  939.                 /* not enough matches */
  940.                 rp->count = count;
  941.                 /* RECURSIVE */
  942.                 i = SRE_MATCH(state, rp->pattern + 3, level + 1);
  943.                 if (i)
  944.                     return i;
  945.                 rp->count = count - 1;
  946.                 state->ptr = ptr;
  947.                 return 0;
  948.             }
  949.  
  950.             if (count < rp->pattern[2] || rp->pattern[2] == 65535) {
  951.                 /* we may have enough matches, but if we can
  952.                    match another item, do so */
  953.                 rp->count = count;
  954.                 lastmark = state->lastmark;
  955.                 i = mark_save(state, 0, lastmark);
  956.                 if (i < 0)
  957.                     return i;
  958.                 /* RECURSIVE */
  959.                 i = SRE_MATCH(state, rp->pattern + 3, level + 1);
  960.                 if (i)
  961.                     return i;
  962.                 i = mark_restore(state, 0, lastmark);
  963.                 if (i < 0)
  964.                     return i;
  965.                 rp->count = count - 1;
  966.                 state->ptr = ptr;
  967.             }
  968.  
  969.             /* cannot match more repeated items here.  make sure the
  970.                tail matches */
  971.             state->repeat = rp->prev;
  972.             i = SRE_MATCH(state, pattern, level + 1);
  973.             if (i)
  974.                 return i;
  975.             state->repeat = rp;
  976.             return 0;
  977.  
  978.         case SRE_OP_MIN_UNTIL:
  979.             /* minimizing repeat */
  980.             /* <REPEAT> <skip> <1=min> <2=max> item <MIN_UNTIL> tail */
  981.  
  982.             rp = state->repeat;
  983.             if (!rp)
  984.                 return SRE_ERROR_STATE;
  985.  
  986.             count = rp->count + 1;
  987.  
  988.             TRACE(("|%p|%p|MIN_UNTIL %d\n", pattern, ptr, count));
  989.  
  990.             state->ptr = ptr;
  991.  
  992.             if (count < rp->pattern[1]) {
  993.                 /* not enough matches */
  994.                 rp->count = count;
  995.                 /* RECURSIVE */
  996.                 i = SRE_MATCH(state, rp->pattern + 3, level + 1);
  997.                 if (i)
  998.                     return i;
  999.                 rp->count = count-1;
  1000.                 state->ptr = ptr;
  1001.                 return 0;
  1002.             }
  1003.  
  1004.             /* see if the tail matches */
  1005.             state->repeat = rp->prev;
  1006.             i = SRE_MATCH(state, pattern, level + 1);
  1007.             if (i) {
  1008.                 /* free(rp); */
  1009.                 return i;
  1010.             }
  1011.             state->repeat = rp;
  1012.  
  1013.             if (count >= rp->pattern[2] && rp->pattern[2] != 65535)
  1014.                 return 0;
  1015.  
  1016.             rp->count = count;
  1017.             /* RECURSIVE */
  1018.             i = SRE_MATCH(state, rp->pattern + 3, level + 1);
  1019.             if (i)
  1020.                 return i;
  1021.             rp->count = count - 1;
  1022.             return 0;
  1023.  
  1024.         default:
  1025.             TRACE(("|%p|%p|UNKNOWN %d\n", pattern, ptr, pattern[-1]));
  1026.             return SRE_ERROR_ILLEGAL;
  1027.         }
  1028.     }
  1029.  
  1030.     /* shouldn't end up here */
  1031.     return SRE_ERROR_ILLEGAL;
  1032. }
  1033.  
  1034. LOCAL(int)
  1035. SRE_SEARCH(SRE_STATE* state, SRE_CODE* pattern)
  1036. {
  1037.     SRE_CHAR* ptr = state->start;
  1038.     SRE_CHAR* end = state->end;
  1039.     int status = 0;
  1040.     int prefix_len = 0;
  1041.     int prefix_skip = 0;
  1042.     SRE_CODE* prefix = NULL;
  1043.     SRE_CODE* charset = NULL;
  1044.     SRE_CODE* overlap = NULL;
  1045.     int flags = 0;
  1046.  
  1047.     if (pattern[0] == SRE_OP_INFO) {
  1048.         /* optimization info block */
  1049.         /* <INFO> <1=skip> <2=flags> <3=min> <4=max> <5=prefix info>  */
  1050.  
  1051.         flags = pattern[2];
  1052.  
  1053.         if (pattern[3] > 0) {
  1054.             /* adjust end point (but make sure we leave at least one
  1055.                character in there, so literal search will work) */
  1056.             end -= pattern[3]-1;
  1057.             if (end <= ptr)
  1058.                 end = ptr+1;
  1059.         }
  1060.  
  1061.         if (flags & SRE_INFO_PREFIX) {
  1062.             /* pattern starts with a known prefix */
  1063.             /* <length> <skip> <prefix data> <overlap data> */
  1064.             prefix_len = pattern[5];
  1065.             prefix_skip = pattern[6];
  1066.             prefix = pattern + 7;
  1067.             overlap = prefix + prefix_len - 1;
  1068.         } else if (flags & SRE_INFO_CHARSET)
  1069.             /* pattern starts with a character from a known set */
  1070.             /* <charset> */
  1071.             charset = pattern + 5;
  1072.  
  1073.         pattern += 1 + pattern[1];
  1074.     }
  1075.  
  1076.     TRACE(("prefix = %p %d %d\n", prefix, prefix_len, prefix_skip));
  1077.     TRACE(("charset = %p\n", charset));
  1078.  
  1079. #if defined(USE_FAST_SEARCH)
  1080.     if (prefix_len > 1) {
  1081.         /* pattern starts with a known prefix.  use the overlap
  1082.            table to skip forward as fast as we possibly can */
  1083.         int i = 0;
  1084.         end = state->end;
  1085.         while (ptr < end) {
  1086.             for (;;) {
  1087.                 if ((SRE_CODE) ptr[0] != prefix[i]) {
  1088.                     if (!i)
  1089.                         break;
  1090.                     else
  1091.                         i = overlap[i];
  1092.                 } else {
  1093.                     if (++i == prefix_len) {
  1094.                         /* found a potential match */
  1095.                         TRACE(("|%p|%p|SEARCH SCAN\n", pattern, ptr));
  1096.                         state->start = ptr + 1 - prefix_len;
  1097.                         state->ptr = ptr + 1 - prefix_len + prefix_skip;
  1098.                         if (flags & SRE_INFO_LITERAL)
  1099.                             return 1; /* we got all of it */
  1100.                         status = SRE_MATCH(state, pattern + 2*prefix_skip, 1);
  1101.                         if (status != 0)
  1102.                             return status;
  1103.                         /* close but no cigar -- try again */
  1104.                         i = overlap[i];
  1105.                     }
  1106.                     break;
  1107.                 }
  1108.                 
  1109.             }
  1110.             ptr++;
  1111.         }
  1112.         return 0;
  1113.     }
  1114. #endif
  1115.  
  1116.     if (pattern[0] == SRE_OP_LITERAL) {
  1117.         /* pattern starts with a literal character.  this is used
  1118.            for short prefixes, and if fast search is disabled */
  1119.         SRE_CODE chr = pattern[1];
  1120.         end = state->end;
  1121.         for (;;) {
  1122.             while (ptr < end && (SRE_CODE) ptr[0] != chr)
  1123.                 ptr++;
  1124.             if (ptr == end)
  1125.                 return 0;
  1126.             TRACE(("|%p|%p|SEARCH LITERAL\n", pattern, ptr));
  1127.             state->start = ptr;
  1128.             state->ptr = ++ptr;
  1129.             status = SRE_MATCH(state, pattern + 2, 1);
  1130.             if (status != 0)
  1131.                 break;
  1132.         }
  1133.     } else if (charset) {
  1134.         /* pattern starts with a character from a known set */
  1135.         end = state->end;
  1136.         for (;;) {
  1137.             while (ptr < end && !SRE_CHARSET(charset, ptr[0]))
  1138.                 ptr++;
  1139.             if (ptr == end)
  1140.                 return 0;
  1141.             TRACE(("|%p|%p|SEARCH CHARSET\n", pattern, ptr));
  1142.             state->start = ptr;
  1143.             state->ptr = ptr;
  1144.             status = SRE_MATCH(state, pattern, 1);
  1145.             if (status != 0)
  1146.                 break;
  1147.             ptr++;
  1148.         }
  1149.     } else
  1150.         /* general case */
  1151.         while (ptr <= end) {
  1152.             TRACE(("|%p|%p|SEARCH\n", pattern, ptr));
  1153.             state->start = state->ptr = ptr++;
  1154.             status = SRE_MATCH(state, pattern, 1);
  1155.             if (status != 0)
  1156.                 break;
  1157.         }
  1158.  
  1159.     return status;
  1160. }
  1161.     
  1162.  
  1163. #if !defined(SRE_RECURSIVE)
  1164.  
  1165. /* -------------------------------------------------------------------- */
  1166. /* factories and destructors */
  1167.  
  1168. /* see sre.h for object declarations */
  1169.  
  1170. staticforward PyTypeObject Pattern_Type;
  1171. staticforward PyTypeObject Match_Type;
  1172. staticforward PyTypeObject Scanner_Type;
  1173.  
  1174. static PyObject *
  1175. _compile(PyObject* self_, PyObject* args)
  1176. {
  1177.     /* "compile" pattern descriptor to pattern object */
  1178.  
  1179.     PatternObject* self;
  1180.     int i, n;
  1181.  
  1182.     PyObject* pattern;
  1183.     int flags = 0;
  1184.     PyObject* code;
  1185.     int groups = 0;
  1186.     PyObject* groupindex = NULL;
  1187.     PyObject* indexgroup = NULL;
  1188.     if (!PyArg_ParseTuple(args, "OiO|iOO", &pattern, &flags, &code,
  1189.                           &groups, &groupindex, &indexgroup))
  1190.         return NULL;
  1191.  
  1192.     code = PySequence_Fast(code, "code argument must be a sequence");
  1193.     if (!code)
  1194.         return NULL;
  1195.  
  1196. #if PY_VERSION_HEX >= 0x01060000
  1197.     n = PySequence_Size(code);
  1198. #else
  1199.     n = PySequence_Length(code);
  1200. #endif
  1201.  
  1202.     self = PyObject_NEW_VAR(PatternObject, &Pattern_Type, 100*n);
  1203.     if (!self) {
  1204.         Py_DECREF(code);
  1205.         return NULL;
  1206.     }
  1207.  
  1208.     for (i = 0; i < n; i++) {
  1209.         PyObject *o = PySequence_Fast_GET_ITEM(code, i);
  1210.         self->code[i] = (SRE_CODE) PyInt_AsLong(o);
  1211.     }
  1212.  
  1213.     Py_DECREF(code);
  1214.  
  1215.     if (PyErr_Occurred())
  1216.         return NULL;
  1217.  
  1218.     Py_INCREF(pattern);
  1219.     self->pattern = pattern;
  1220.  
  1221.     self->flags = flags;
  1222.  
  1223.     self->groups = groups;
  1224.  
  1225.     Py_XINCREF(groupindex);
  1226.     self->groupindex = groupindex;
  1227.  
  1228.     Py_XINCREF(indexgroup);
  1229.     self->indexgroup = indexgroup;
  1230.  
  1231.     return (PyObject*) self;
  1232. }
  1233.  
  1234. static PyObject *
  1235. sre_codesize(PyObject* self, PyObject* args)
  1236. {
  1237.     return Py_BuildValue("i", sizeof(SRE_CODE));
  1238. }
  1239.  
  1240. static PyObject *
  1241. sre_getlower(PyObject* self, PyObject* args)
  1242. {
  1243.     int character, flags;
  1244.     if (!PyArg_ParseTuple(args, "ii", &character, &flags))
  1245.         return NULL;
  1246.     if (flags & SRE_FLAG_LOCALE)
  1247.         return Py_BuildValue("i", sre_lower_locale(character));
  1248. #if defined(HAVE_UNICODE)
  1249.     if (flags & SRE_FLAG_UNICODE)
  1250.         return Py_BuildValue("i", sre_lower_unicode(character));
  1251. #endif
  1252.     return Py_BuildValue("i", sre_lower(character));
  1253. }
  1254.  
  1255. LOCAL(void)
  1256. state_reset(SRE_STATE* state)
  1257. {
  1258.     int i;
  1259.  
  1260.     state->lastmark = 0;
  1261.  
  1262.     /* FIXME: dynamic! */
  1263.     for (i = 0; i < SRE_MARK_SIZE; i++)
  1264.         state->mark[i] = NULL;
  1265.  
  1266.     state->lastindex = -1;
  1267.  
  1268.     state->repeat = NULL;
  1269.  
  1270.     mark_fini(state);
  1271. }
  1272.  
  1273. LOCAL(PyObject*)
  1274. state_init(SRE_STATE* state, PatternObject* pattern, PyObject* string,
  1275.            int start, int end)
  1276. {
  1277.     /* prepare state object */
  1278.  
  1279.     PyBufferProcs *buffer;
  1280.     int size, bytes;
  1281.     void* ptr;
  1282.  
  1283.     memset(state, 0, sizeof(SRE_STATE));
  1284.  
  1285.     state->lastindex = -1;
  1286.  
  1287. #if defined(HAVE_UNICODE)
  1288.     if (PyUnicode_Check(string)) {
  1289.         /* unicode strings doesn't always support the buffer interface */
  1290.         ptr = (void*) PyUnicode_AS_DATA(string);
  1291.         bytes = PyUnicode_GET_DATA_SIZE(string);
  1292.         size = PyUnicode_GET_SIZE(string);
  1293.         state->charsize = sizeof(Py_UNICODE);
  1294.  
  1295.     } else {
  1296. #endif
  1297.  
  1298.     /* get pointer to string buffer */
  1299.     buffer = string->ob_type->tp_as_buffer;
  1300.     if (!buffer || !buffer->bf_getreadbuffer || !buffer->bf_getsegcount ||
  1301.         buffer->bf_getsegcount(string, NULL) != 1) {
  1302.         PyErr_SetString(PyExc_TypeError, "expected string or buffer");
  1303.         return NULL;
  1304.     }
  1305.  
  1306.     /* determine buffer size */
  1307.     bytes = buffer->bf_getreadbuffer(string, 0, &ptr);
  1308.     if (bytes < 0) {
  1309.         PyErr_SetString(PyExc_TypeError, "buffer has negative size");
  1310.         return NULL;
  1311.     }
  1312.  
  1313.     /* determine character size */
  1314. #if PY_VERSION_HEX >= 0x01060000
  1315.     size = PyObject_Size(string);
  1316. #else
  1317.     size = PyObject_Length(string);
  1318. #endif
  1319.  
  1320.     if (PyString_Check(string) || bytes == size)
  1321.         state->charsize = 1;
  1322. #if defined(HAVE_UNICODE)
  1323.     else if (bytes == (int) (size * sizeof(Py_UNICODE)))
  1324.         state->charsize = sizeof(Py_UNICODE);
  1325. #endif
  1326.     else {
  1327.         PyErr_SetString(PyExc_TypeError, "buffer size mismatch");
  1328.         return NULL;
  1329.     }
  1330.  
  1331. #if defined(HAVE_UNICODE)
  1332.     }
  1333. #endif
  1334.  
  1335.     /* adjust boundaries */
  1336.     if (start < 0)
  1337.         start = 0;
  1338.     else if (start > size)
  1339.         start = size;
  1340.  
  1341.     if (end < 0)
  1342.         end = 0;
  1343.     else if (end > size)
  1344.         end = size;
  1345.  
  1346.     state->beginning = ptr;
  1347.  
  1348.     state->start = (void*) ((char*) ptr + start * state->charsize);
  1349.     state->end = (void*) ((char*) ptr + end * state->charsize);
  1350.  
  1351.     Py_INCREF(string);
  1352.     state->string = string;
  1353.     state->pos = start;
  1354.     state->endpos = end;
  1355.  
  1356.     if (pattern->flags & SRE_FLAG_LOCALE)
  1357.         state->lower = sre_lower_locale;
  1358. #if defined(HAVE_UNICODE)
  1359.     else if (pattern->flags & SRE_FLAG_UNICODE)
  1360.         state->lower = sre_lower_unicode;
  1361. #endif
  1362.     else
  1363.         state->lower = sre_lower;
  1364.  
  1365.     return string;
  1366. }
  1367.  
  1368. LOCAL(void)
  1369. state_fini(SRE_STATE* state)
  1370. {
  1371.     Py_XDECREF(state->string);
  1372.     mark_fini(state);
  1373. }
  1374.  
  1375. LOCAL(PyObject*)
  1376. state_getslice(SRE_STATE* state, int index, PyObject* string)
  1377. {
  1378.     int i, j;
  1379.  
  1380.     index = (index - 1) * 2;
  1381.  
  1382.     if (string == Py_None || !state->mark[index] || !state->mark[index+1]) {
  1383.         i = j = 0;
  1384.     } else {
  1385.         i = ((char*)state->mark[index] - (char*)state->beginning) /
  1386.             state->charsize;
  1387.         j = ((char*)state->mark[index+1] - (char*)state->beginning) /
  1388.             state->charsize;
  1389.     }
  1390.  
  1391.     return PySequence_GetSlice(string, i, j);
  1392. }
  1393.  
  1394. static void
  1395. pattern_error(int status)
  1396. {
  1397.     switch (status) {
  1398.     case SRE_ERROR_RECURSION_LIMIT:
  1399.         PyErr_SetString(
  1400.             PyExc_RuntimeError,
  1401.             "maximum recursion limit exceeded"
  1402.             );
  1403.         break;
  1404.     case SRE_ERROR_MEMORY:
  1405.         PyErr_NoMemory();
  1406.         break;
  1407.     default:
  1408.         /* other error codes indicate compiler/engine bugs */
  1409.         PyErr_SetString(
  1410.             PyExc_RuntimeError,
  1411.             "internal error in regular expression engine"
  1412.             );
  1413.     }
  1414. }
  1415.  
  1416. static PyObject*
  1417. pattern_new_match(PatternObject* pattern, SRE_STATE* state, int status)
  1418. {
  1419.     /* create match object (from state object) */
  1420.  
  1421.     MatchObject* match;
  1422.     int i, j;
  1423.     char* base;
  1424.     int n;
  1425.  
  1426.     if (status > 0) {
  1427.  
  1428.         /* create match object (with room for extra group marks) */
  1429.         match = PyObject_NEW_VAR(MatchObject, &Match_Type,
  1430.                                  2*(pattern->groups+1));
  1431.         if (!match)
  1432.             return NULL;
  1433.  
  1434.         Py_INCREF(pattern);
  1435.         match->pattern = pattern;
  1436.  
  1437.         Py_INCREF(state->string);
  1438.         match->string = state->string;
  1439.  
  1440.         match->regs = NULL;
  1441.         match->groups = pattern->groups+1;
  1442.  
  1443.         /* fill in group slices */
  1444.  
  1445.         base = (char*) state->beginning;
  1446.         n = state->charsize;
  1447.  
  1448.         match->mark[0] = ((char*) state->start - base) / n;
  1449.         match->mark[1] = ((char*) state->ptr - base) / n;
  1450.  
  1451.         for (i = j = 0; i < pattern->groups; i++, j+=2)
  1452.             if (j+1 <= state->lastmark && state->mark[j] && state->mark[j+1]) {
  1453.                 match->mark[j+2] = ((char*) state->mark[j] - base) / n;
  1454.                 match->mark[j+3] = ((char*) state->mark[j+1] - base) / n;
  1455.             } else
  1456.                 match->mark[j+2] = match->mark[j+3] = -1; /* undefined */
  1457.  
  1458.         match->pos = state->pos;
  1459.         match->endpos = state->endpos;
  1460.  
  1461.         match->lastindex = state->lastindex;
  1462.  
  1463.         return (PyObject*) match;
  1464.  
  1465.     } else if (status == 0) {
  1466.  
  1467.         /* no match */
  1468.         Py_INCREF(Py_None);
  1469.         return Py_None;
  1470.  
  1471.     }
  1472.  
  1473.     /* internal error */
  1474.     pattern_error(status);
  1475.     return NULL;
  1476. }
  1477.  
  1478. static PyObject*
  1479. pattern_scanner(PatternObject* pattern, PyObject* args)
  1480. {
  1481.     /* create search state object */
  1482.  
  1483.     ScannerObject* self;
  1484.  
  1485.     PyObject* string;
  1486.     int start = 0;
  1487.     int end = INT_MAX;
  1488.     if (!PyArg_ParseTuple(args, "O|ii:scanner", &string, &start, &end))
  1489.         return NULL;
  1490.  
  1491.     /* create scanner object */
  1492.     self = PyObject_NEW(ScannerObject, &Scanner_Type);
  1493.     if (!self)
  1494.         return NULL;
  1495.  
  1496.     string = state_init(&self->state, pattern, string, start, end);
  1497.     if (!string) {
  1498.         PyObject_Del(self);
  1499.         return NULL;
  1500.     }
  1501.  
  1502.     Py_INCREF(pattern);
  1503.     self->pattern = (PyObject*) pattern;
  1504.  
  1505.     return (PyObject*) self;
  1506. }
  1507.  
  1508. static void
  1509. pattern_dealloc(PatternObject* self)
  1510. {
  1511.     Py_XDECREF(self->pattern);
  1512.     Py_XDECREF(self->groupindex);
  1513.     PyObject_DEL(self);
  1514. }
  1515.  
  1516. static PyObject*
  1517. pattern_match(PatternObject* self, PyObject* args, PyObject* kw)
  1518. {
  1519.     SRE_STATE state;
  1520.     int status;
  1521.  
  1522.     PyObject* string;
  1523.     int start = 0;
  1524.     int end = INT_MAX;
  1525.     static char* kwlist[] = { "pattern", "pos", "endpos", NULL };
  1526.     if (!PyArg_ParseTupleAndKeywords(args, kw, "O|ii:match", kwlist,
  1527.                                      &string, &start, &end))
  1528.         return NULL;
  1529.  
  1530.     string = state_init(&state, self, string, start, end);
  1531.     if (!string)
  1532.         return NULL;
  1533.  
  1534.     state.ptr = state.start;
  1535.  
  1536.     TRACE(("|%p|%p|MATCH\n", PatternObject_GetCode(self), state.ptr));
  1537.  
  1538.     if (state.charsize == 1) {
  1539.         status = sre_match(&state, PatternObject_GetCode(self), 1);
  1540.     } else {
  1541. #if defined(HAVE_UNICODE)
  1542.         status = sre_umatch(&state, PatternObject_GetCode(self), 1);
  1543. #endif
  1544.     }
  1545.  
  1546.     TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
  1547.  
  1548.     state_fini(&state);
  1549.  
  1550.     return pattern_new_match(self, &state, status);
  1551. }
  1552.  
  1553. static PyObject*
  1554. pattern_search(PatternObject* self, PyObject* args, PyObject* kw)
  1555. {
  1556.     SRE_STATE state;
  1557.     int status;
  1558.  
  1559.     PyObject* string;
  1560.     int start = 0;
  1561.     int end = INT_MAX;
  1562.     static char* kwlist[] = { "pattern", "pos", "endpos", NULL };
  1563.     if (!PyArg_ParseTupleAndKeywords(args, kw, "O|ii:search", kwlist,
  1564.                                      &string, &start, &end))
  1565.         return NULL;
  1566.  
  1567.     string = state_init(&state, self, string, start, end);
  1568.     if (!string)
  1569.         return NULL;
  1570.  
  1571.     TRACE(("|%p|%p|SEARCH\n", PatternObject_GetCode(self), state.ptr));
  1572.  
  1573.     if (state.charsize == 1) {
  1574.         status = sre_search(&state, PatternObject_GetCode(self));
  1575.     } else {
  1576. #if defined(HAVE_UNICODE)
  1577.         status = sre_usearch(&state, PatternObject_GetCode(self));
  1578. #endif
  1579.     }
  1580.  
  1581.     TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
  1582.  
  1583.     state_fini(&state);
  1584.  
  1585.     return pattern_new_match(self, &state, status);
  1586. }
  1587.  
  1588. static PyObject*
  1589. call(char* function, PyObject* args)
  1590. {
  1591.     PyObject* name;
  1592.     PyObject* module;
  1593.     PyObject* func;
  1594.     PyObject* result;
  1595.  
  1596.     name = PyString_FromString(MODULE);
  1597.     if (!name)
  1598.         return NULL;
  1599.     module = PyImport_Import(name);
  1600.     Py_DECREF(name);
  1601.     if (!module)
  1602.         return NULL;
  1603.     func = PyObject_GetAttrString(module, function);
  1604.     Py_DECREF(module);
  1605.     if (!func)
  1606.         return NULL;
  1607.     result = PyObject_CallObject(func, args);
  1608.     Py_DECREF(func);
  1609.     Py_DECREF(args);
  1610.     return result;
  1611. }
  1612.  
  1613. static PyObject*
  1614. pattern_sub(PatternObject* self, PyObject* args, PyObject* kw)
  1615. {
  1616.     PyObject* template;
  1617.     PyObject* string;
  1618.     PyObject* count = Py_False; /* zero */
  1619.     static char* kwlist[] = { "repl", "string", "count", NULL };
  1620.     if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|O:sub", kwlist,
  1621.                                      &template, &string, &count))
  1622.         return NULL;
  1623.  
  1624.     /* delegate to Python code */
  1625.     return call("_sub", Py_BuildValue("OOOO", self, template, string, count));
  1626. }
  1627.  
  1628. static PyObject*
  1629. pattern_subn(PatternObject* self, PyObject* args, PyObject* kw)
  1630. {
  1631.     PyObject* template;
  1632.     PyObject* string;
  1633.     PyObject* count = Py_False; /* zero */
  1634.     static char* kwlist[] = { "repl", "string", "count", NULL };
  1635.     if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|O:subn", kwlist,
  1636.                                      &template, &string, &count))
  1637.         return NULL;
  1638.  
  1639.     /* delegate to Python code */
  1640.     return call("_subn", Py_BuildValue("OOOO", self, template, string, count));
  1641. }
  1642.  
  1643. static PyObject*
  1644. pattern_split(PatternObject* self, PyObject* args, PyObject* kw)
  1645. {
  1646.     PyObject* string;
  1647.     PyObject* maxsplit = Py_False; /* zero */
  1648.     static char* kwlist[] = { "source", "maxsplit", NULL };
  1649.     if (!PyArg_ParseTupleAndKeywords(args, kw, "O|O:split", kwlist,
  1650.                                      &string, &maxsplit))
  1651.         return NULL;
  1652.  
  1653.     /* delegate to Python code */
  1654.     return call("_split", Py_BuildValue("OOO", self, string, maxsplit));
  1655. }
  1656.  
  1657. static PyObject*
  1658. pattern_findall(PatternObject* self, PyObject* args, PyObject* kw)
  1659. {
  1660.     SRE_STATE state;
  1661.     PyObject* list;
  1662.     int status;
  1663.     int i;
  1664.  
  1665.     PyObject* string;
  1666.     int start = 0;
  1667.     int end = INT_MAX;
  1668.     static char* kwlist[] = { "source", "pos", "endpos", NULL };
  1669.     if (!PyArg_ParseTupleAndKeywords(args, kw, "O|ii:findall", kwlist,
  1670.                                      &string, &start, &end))
  1671.         return NULL;
  1672.  
  1673.     string = state_init(&state, self, string, start, end);
  1674.     if (!string)
  1675.         return NULL;
  1676.  
  1677.     list = PyList_New(0);
  1678.  
  1679.     while (state.start <= state.end) {
  1680.  
  1681.         PyObject* item;
  1682.         
  1683.         state.ptr = state.start;
  1684.  
  1685.         if (state.charsize == 1) {
  1686.             status = sre_search(&state, PatternObject_GetCode(self));
  1687.         } else {
  1688. #if defined(HAVE_UNICODE)
  1689.             status = sre_usearch(&state, PatternObject_GetCode(self));
  1690. #endif
  1691.         }
  1692.  
  1693.         if (status > 0) {
  1694.  
  1695.             /* don't bother to build a match object */
  1696.             switch (self->groups) {
  1697.             case 0:
  1698.                 item = PySequence_GetSlice(
  1699.                     string,
  1700.                     ((char*) state.start - (char*) state.beginning) /
  1701.                     state.charsize,
  1702.                     ((char*) state.ptr - (char*) state.beginning) /
  1703.                     state.charsize);
  1704.                 if (!item)
  1705.                     goto error;
  1706.                 break;
  1707.             case 1:
  1708.                 item = state_getslice(&state, 1, string);
  1709.                 if (!item)
  1710.                     goto error;
  1711.                 break;
  1712.             default:
  1713.                 item = PyTuple_New(self->groups);
  1714.                 if (!item)
  1715.                     goto error;
  1716.                 for (i = 0; i < self->groups; i++) {
  1717.                     PyObject* o = state_getslice(&state, i+1, string);
  1718.                     if (!o) {
  1719.                         Py_DECREF(item);
  1720.                         goto error;
  1721.                     }
  1722.                     PyTuple_SET_ITEM(item, i, o);
  1723.                 }
  1724.                 break;
  1725.             }
  1726.  
  1727.             status = PyList_Append(list, item);
  1728.             Py_DECREF(item);
  1729.  
  1730.             if (status < 0)
  1731.                 goto error;
  1732.  
  1733.             if (state.ptr == state.start)
  1734.                 state.start = (void*) ((char*) state.ptr + state.charsize);
  1735.             else
  1736.                 state.start = state.ptr;
  1737.  
  1738.         } else {
  1739.  
  1740.             if (status == 0)
  1741.                 break;
  1742.  
  1743.             pattern_error(status);
  1744.             goto error;
  1745.  
  1746.         }
  1747.     }
  1748.  
  1749.     state_fini(&state);
  1750.     return list;
  1751.  
  1752. error:
  1753.     Py_DECREF(list);
  1754.     state_fini(&state);
  1755.     return NULL;
  1756.     
  1757. }
  1758.  
  1759. static PyMethodDef pattern_methods[] = {
  1760.     {"match", (PyCFunction) pattern_match, METH_VARARGS|METH_KEYWORDS},
  1761.     {"search", (PyCFunction) pattern_search, METH_VARARGS|METH_KEYWORDS},
  1762.     {"sub", (PyCFunction) pattern_sub, METH_VARARGS|METH_KEYWORDS},
  1763.     {"subn", (PyCFunction) pattern_subn, METH_VARARGS|METH_KEYWORDS},
  1764.     {"split", (PyCFunction) pattern_split, METH_VARARGS|METH_KEYWORDS},
  1765.     {"findall", (PyCFunction) pattern_findall, METH_VARARGS|METH_KEYWORDS},
  1766.     /* experimental */
  1767.     {"scanner", (PyCFunction) pattern_scanner, METH_VARARGS},
  1768.     {NULL, NULL}
  1769. };
  1770.  
  1771. static PyObject*  
  1772. pattern_getattr(PatternObject* self, char* name)
  1773. {
  1774.     PyObject* res;
  1775.  
  1776.     res = Py_FindMethod(pattern_methods, (PyObject*) self, name);
  1777.  
  1778.     if (res)
  1779.         return res;
  1780.  
  1781.     PyErr_Clear();
  1782.  
  1783.     /* attributes */
  1784.     if (!strcmp(name, "pattern")) {
  1785.         Py_INCREF(self->pattern);
  1786.         return self->pattern;
  1787.     }
  1788.  
  1789.     if (!strcmp(name, "flags"))
  1790.         return Py_BuildValue("i", self->flags);
  1791.  
  1792.     if (!strcmp(name, "groups"))
  1793.         return Py_BuildValue("i", self->groups);
  1794.  
  1795.     if (!strcmp(name, "groupindex") && self->groupindex) {
  1796.         Py_INCREF(self->groupindex);
  1797.         return self->groupindex;
  1798.     }
  1799.  
  1800.     PyErr_SetString(PyExc_AttributeError, name);
  1801.     return NULL;
  1802. }
  1803.  
  1804. statichere PyTypeObject Pattern_Type = {
  1805.     PyObject_HEAD_INIT(NULL)
  1806.     0, "SRE_Pattern",
  1807.     sizeof(PatternObject), sizeof(SRE_CODE),
  1808.     (destructor)pattern_dealloc, /*tp_dealloc*/
  1809.     0, /*tp_print*/
  1810.     (getattrfunc)pattern_getattr /*tp_getattr*/
  1811. };
  1812.  
  1813. /* -------------------------------------------------------------------- */
  1814. /* match methods */
  1815.  
  1816. static void
  1817. match_dealloc(MatchObject* self)
  1818. {
  1819.     Py_XDECREF(self->regs);
  1820.     Py_XDECREF(self->string);
  1821.     Py_DECREF(self->pattern);
  1822.     PyObject_DEL(self);
  1823. }
  1824.  
  1825. static PyObject*
  1826. match_getslice_by_index(MatchObject* self, int index, PyObject* def)
  1827. {
  1828.     if (index < 0 || index >= self->groups) {
  1829.         /* raise IndexError if we were given a bad group number */
  1830.         PyErr_SetString(
  1831.             PyExc_IndexError,
  1832.             "no such group"
  1833.             );
  1834.         return NULL;
  1835.     }
  1836.  
  1837.     index *= 2;
  1838.  
  1839.     if (self->string == Py_None || self->mark[index] < 0) {
  1840.         /* return default value if the string or group is undefined */
  1841.         Py_INCREF(def);
  1842.         return def;
  1843.     }
  1844.  
  1845.     return PySequence_GetSlice(
  1846.         self->string, self->mark[index], self->mark[index+1]
  1847.         );
  1848. }
  1849.  
  1850. static int
  1851. match_getindex(MatchObject* self, PyObject* index)
  1852. {
  1853.     int i;
  1854.  
  1855.     if (PyInt_Check(index))
  1856.         return (int) PyInt_AS_LONG(index);
  1857.  
  1858.     i = -1;
  1859.  
  1860.     if (self->pattern->groupindex) {
  1861.         index = PyObject_GetItem(self->pattern->groupindex, index);
  1862.         if (index) {
  1863.             if (PyInt_Check(index))
  1864.                 i = (int) PyInt_AS_LONG(index);
  1865.             Py_DECREF(index);
  1866.         } else
  1867.             PyErr_Clear();
  1868.     }
  1869.  
  1870.     return i;
  1871. }
  1872.  
  1873. static PyObject*
  1874. match_getslice(MatchObject* self, PyObject* index, PyObject* def)
  1875. {
  1876.     return match_getslice_by_index(self, match_getindex(self, index), def);
  1877. }
  1878.  
  1879. static PyObject*
  1880. match_expand(MatchObject* self, PyObject* args)
  1881. {
  1882.     PyObject* template;
  1883.     if (!PyArg_ParseTuple(args, "O:expand", &template))
  1884.         return NULL;
  1885.  
  1886.     /* delegate to Python code */
  1887.     return call(
  1888.         "_expand",
  1889.         Py_BuildValue("OOO", self->pattern, self, template)
  1890.         );
  1891. }
  1892.  
  1893. static PyObject*
  1894. match_group(MatchObject* self, PyObject* args)
  1895. {
  1896.     PyObject* result;
  1897.     int i, size;
  1898.  
  1899.     size = PyTuple_GET_SIZE(args);
  1900.  
  1901.     switch (size) {
  1902.     case 0:
  1903.         result = match_getslice(self, Py_False, Py_None);
  1904.         break;
  1905.     case 1:
  1906.         result = match_getslice(self, PyTuple_GET_ITEM(args, 0), Py_None);
  1907.         break;
  1908.     default:
  1909.         /* fetch multiple items */
  1910.         result = PyTuple_New(size);
  1911.         if (!result)
  1912.             return NULL;
  1913.         for (i = 0; i < size; i++) {
  1914.             PyObject* item = match_getslice(
  1915.                 self, PyTuple_GET_ITEM(args, i), Py_None
  1916.                 );
  1917.             if (!item) {
  1918.                 Py_DECREF(result);
  1919.                 return NULL;
  1920.             }
  1921.             PyTuple_SET_ITEM(result, i, item);
  1922.         }
  1923.         break;
  1924.     }
  1925.     return result;
  1926. }
  1927.  
  1928. static PyObject*
  1929. match_groups(MatchObject* self, PyObject* args, PyObject* kw)
  1930. {
  1931.     PyObject* result;
  1932.     int index;
  1933.  
  1934.     PyObject* def = Py_None;
  1935.     static char* kwlist[] = { "default", NULL };
  1936.     if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:groups", kwlist, &def))
  1937.         return NULL;
  1938.  
  1939.     result = PyTuple_New(self->groups-1);
  1940.     if (!result)
  1941.         return NULL;
  1942.  
  1943.     for (index = 1; index < self->groups; index++) {
  1944.         PyObject* item;
  1945.         item = match_getslice_by_index(self, index, def);
  1946.         if (!item) {
  1947.             Py_DECREF(result);
  1948.             return NULL;
  1949.         }
  1950.         PyTuple_SET_ITEM(result, index-1, item);
  1951.     }
  1952.  
  1953.     return result;
  1954. }
  1955.  
  1956. static PyObject*
  1957. match_groupdict(MatchObject* self, PyObject* args, PyObject* kw)
  1958. {
  1959.     PyObject* result;
  1960.     PyObject* keys;
  1961.     int index;
  1962.  
  1963.     PyObject* def = Py_None;
  1964.     static char* kwlist[] = { "default", NULL };
  1965.     if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:groups", kwlist, &def))
  1966.         return NULL;
  1967.  
  1968.     result = PyDict_New();
  1969.     if (!result || !self->pattern->groupindex)
  1970.         return result;
  1971.  
  1972.     keys = PyMapping_Keys(self->pattern->groupindex);
  1973.     if (!keys) {
  1974.         Py_DECREF(result);
  1975.         return NULL;
  1976.     }
  1977.  
  1978.     for (index = 0; index < PyList_GET_SIZE(keys); index++) {
  1979.         PyObject* key;
  1980.         PyObject* item;
  1981.         key = PyList_GET_ITEM(keys, index);
  1982.         if (!key) {
  1983.             Py_DECREF(keys);
  1984.             Py_DECREF(result);
  1985.             return NULL;
  1986.         }
  1987.         item = match_getslice(self, key, def);
  1988.         if (!item) {
  1989.             Py_DECREF(key);
  1990.             Py_DECREF(keys);
  1991.             Py_DECREF(result);
  1992.             return NULL;
  1993.         }
  1994.         /* FIXME: <fl> this can fail, right? */
  1995.         PyDict_SetItem(result, key, item);
  1996.     }
  1997.  
  1998.     Py_DECREF(keys);
  1999.  
  2000.     return result;
  2001. }
  2002.  
  2003. static PyObject*
  2004. match_start(MatchObject* self, PyObject* args)
  2005. {
  2006.     int index;
  2007.  
  2008.     PyObject* index_ = Py_False; /* zero */
  2009.     if (!PyArg_ParseTuple(args, "|O:start", &index_))
  2010.         return NULL;
  2011.  
  2012.     index = match_getindex(self, index_);
  2013.  
  2014.     if (index < 0 || index >= self->groups) {
  2015.         PyErr_SetString(
  2016.             PyExc_IndexError,
  2017.             "no such group"
  2018.             );
  2019.         return NULL;
  2020.     }
  2021.  
  2022.     /* mark is -1 if group is undefined */
  2023.     return Py_BuildValue("i", self->mark[index*2]);
  2024. }
  2025.  
  2026. static PyObject*
  2027. match_end(MatchObject* self, PyObject* args)
  2028. {
  2029.     int index;
  2030.  
  2031.     PyObject* index_ = Py_False; /* zero */
  2032.     if (!PyArg_ParseTuple(args, "|O:end", &index_))
  2033.         return NULL;
  2034.  
  2035.     index = match_getindex(self, index_);
  2036.  
  2037.     if (index < 0 || index >= self->groups) {
  2038.         PyErr_SetString(
  2039.             PyExc_IndexError,
  2040.             "no such group"
  2041.             );
  2042.         return NULL;
  2043.     }
  2044.  
  2045.     /* mark is -1 if group is undefined */
  2046.     return Py_BuildValue("i", self->mark[index*2+1]);
  2047. }
  2048.  
  2049. LOCAL(PyObject*)
  2050. _pair(int i1, int i2)
  2051. {
  2052.     PyObject* pair;
  2053.     PyObject* item;
  2054.  
  2055.     pair = PyTuple_New(2);
  2056.     if (!pair)
  2057.         return NULL;
  2058.  
  2059.     item = PyInt_FromLong(i1);
  2060.     if (!item)
  2061.         goto error;
  2062.     PyTuple_SET_ITEM(pair, 0, item);
  2063.  
  2064.     item = PyInt_FromLong(i2);
  2065.     if (!item)
  2066.         goto error;
  2067.     PyTuple_SET_ITEM(pair, 1, item);
  2068.  
  2069.     return pair;
  2070.  
  2071.   error:
  2072.     Py_DECREF(pair);
  2073.     return NULL;
  2074. }
  2075.  
  2076. static PyObject*
  2077. match_span(MatchObject* self, PyObject* args)
  2078. {
  2079.     int index;
  2080.  
  2081.     PyObject* index_ = Py_False; /* zero */
  2082.     if (!PyArg_ParseTuple(args, "|O:span", &index_))
  2083.         return NULL;
  2084.  
  2085.     index = match_getindex(self, index_);
  2086.  
  2087.     if (index < 0 || index >= self->groups) {
  2088.         PyErr_SetString(
  2089.             PyExc_IndexError,
  2090.             "no such group"
  2091.             );
  2092.         return NULL;
  2093.     }
  2094.  
  2095.     /* marks are -1 if group is undefined */
  2096.     return _pair(self->mark[index*2], self->mark[index*2+1]);
  2097. }
  2098.  
  2099. static PyObject*
  2100. match_regs(MatchObject* self)
  2101. {
  2102.     PyObject* regs;
  2103.     PyObject* item;
  2104.     int index;
  2105.  
  2106.     regs = PyTuple_New(self->groups);
  2107.     if (!regs)
  2108.         return NULL;
  2109.  
  2110.     for (index = 0; index < self->groups; index++) {
  2111.         item = _pair(self->mark[index*2], self->mark[index*2+1]);
  2112.         if (!item) {
  2113.             Py_DECREF(regs);
  2114.             return NULL;
  2115.         }
  2116.         PyTuple_SET_ITEM(regs, index, item);
  2117.     }
  2118.  
  2119.     Py_INCREF(regs);
  2120.     self->regs = regs;
  2121.  
  2122.     return regs;
  2123. }
  2124.  
  2125. static PyMethodDef match_methods[] = {
  2126.     {"group", (PyCFunction) match_group, METH_VARARGS},
  2127.     {"start", (PyCFunction) match_start, METH_VARARGS},
  2128.     {"end", (PyCFunction) match_end, METH_VARARGS},
  2129.     {"span", (PyCFunction) match_span, METH_VARARGS},
  2130.     {"groups", (PyCFunction) match_groups, METH_VARARGS|METH_KEYWORDS},
  2131.     {"groupdict", (PyCFunction) match_groupdict, METH_VARARGS|METH_KEYWORDS},
  2132.     {"expand", (PyCFunction) match_expand, METH_VARARGS},
  2133.     {NULL, NULL}
  2134. };
  2135.  
  2136. static PyObject*  
  2137. match_getattr(MatchObject* self, char* name)
  2138. {
  2139.     PyObject* res;
  2140.  
  2141.     res = Py_FindMethod(match_methods, (PyObject*) self, name);
  2142.     if (res)
  2143.         return res;
  2144.  
  2145.     PyErr_Clear();
  2146.  
  2147.     if (!strcmp(name, "lastindex")) {
  2148.         if (self->lastindex >= 0)
  2149.             return Py_BuildValue("i", self->lastindex);
  2150.         Py_INCREF(Py_None);
  2151.         return Py_None;
  2152.     }
  2153.  
  2154.     if (!strcmp(name, "lastgroup")) {
  2155.         if (self->pattern->indexgroup && self->lastindex >= 0) {
  2156.             PyObject* result = PySequence_GetItem(
  2157.                 self->pattern->indexgroup, self->lastindex
  2158.                 );
  2159.             if (result)
  2160.                 return result;
  2161.             PyErr_Clear();
  2162.         }
  2163.         Py_INCREF(Py_None);
  2164.         return Py_None;
  2165.     }
  2166.  
  2167.     if (!strcmp(name, "string")) {
  2168.         if (self->string) {
  2169.             Py_INCREF(self->string);
  2170.             return self->string;
  2171.         } else {
  2172.             Py_INCREF(Py_None);
  2173.             return Py_None;
  2174.         }
  2175.     }
  2176.  
  2177.     if (!strcmp(name, "regs")) {
  2178.         if (self->regs) {
  2179.             Py_INCREF(self->regs);
  2180.             return self->regs;
  2181.         } else
  2182.             return match_regs(self);
  2183.     }
  2184.  
  2185.     if (!strcmp(name, "re")) {
  2186.         Py_INCREF(self->pattern);
  2187.         return (PyObject*) self->pattern;
  2188.     }
  2189.  
  2190.     if (!strcmp(name, "pos"))
  2191.         return Py_BuildValue("i", self->pos);
  2192.  
  2193.     if (!strcmp(name, "endpos"))
  2194.         return Py_BuildValue("i", self->endpos);
  2195.  
  2196.     PyErr_SetString(PyExc_AttributeError, name);
  2197.     return NULL;
  2198. }
  2199.  
  2200. /* FIXME: implement setattr("string", None) as a special case (to
  2201.    detach the associated string, if any */
  2202.  
  2203. statichere PyTypeObject Match_Type = {
  2204.     PyObject_HEAD_INIT(NULL)
  2205.     0, "SRE_Match",
  2206.     sizeof(MatchObject), sizeof(int),
  2207.     (destructor)match_dealloc, /*tp_dealloc*/
  2208.     0, /*tp_print*/
  2209.     (getattrfunc)match_getattr /*tp_getattr*/
  2210. };
  2211.  
  2212. /* -------------------------------------------------------------------- */
  2213. /* scanner methods (experimental) */
  2214.  
  2215. static void
  2216. scanner_dealloc(ScannerObject* self)
  2217. {
  2218.     state_fini(&self->state);
  2219.     Py_DECREF(self->pattern);
  2220.     PyObject_DEL(self);
  2221. }
  2222.  
  2223. static PyObject*
  2224. scanner_match(ScannerObject* self, PyObject* args)
  2225. {
  2226.     SRE_STATE* state = &self->state;
  2227.     PyObject* match;
  2228.     int status;
  2229.  
  2230.     state_reset(state);
  2231.  
  2232.     state->ptr = state->start;
  2233.  
  2234.     if (state->charsize == 1) {
  2235.         status = sre_match(state, PatternObject_GetCode(self->pattern), 1);
  2236.     } else {
  2237. #if defined(HAVE_UNICODE)
  2238.         status = sre_umatch(state, PatternObject_GetCode(self->pattern), 1);
  2239. #endif
  2240.     }
  2241.  
  2242.     match = pattern_new_match((PatternObject*) self->pattern,
  2243.                                state, status);
  2244.  
  2245.     if (status == 0 || state->ptr == state->start)
  2246.         state->start = (void*) ((char*) state->ptr + state->charsize);
  2247.     else
  2248.         state->start = state->ptr;
  2249.  
  2250.     return match;
  2251. }
  2252.  
  2253.  
  2254. static PyObject*
  2255. scanner_search(ScannerObject* self, PyObject* args)
  2256. {
  2257.     SRE_STATE* state = &self->state;
  2258.     PyObject* match;
  2259.     int status;
  2260.  
  2261.     state_reset(state);
  2262.  
  2263.     state->ptr = state->start;
  2264.  
  2265.     if (state->charsize == 1) {
  2266.         status = sre_search(state, PatternObject_GetCode(self->pattern));
  2267.     } else {
  2268. #if defined(HAVE_UNICODE)
  2269.         status = sre_usearch(state, PatternObject_GetCode(self->pattern));
  2270. #endif
  2271.     }
  2272.  
  2273.     match = pattern_new_match((PatternObject*) self->pattern,
  2274.                                state, status);
  2275.  
  2276.     if (status == 0 || state->ptr == state->start)
  2277.         state->start = (void*) ((char*) state->ptr + state->charsize);
  2278.     else
  2279.         state->start = state->ptr;
  2280.  
  2281.     return match;
  2282. }
  2283.  
  2284. static PyMethodDef scanner_methods[] = {
  2285.     {"match", (PyCFunction) scanner_match, 0},
  2286.     {"search", (PyCFunction) scanner_search, 0},
  2287.     {NULL, NULL}
  2288. };
  2289.  
  2290. static PyObject*  
  2291. scanner_getattr(ScannerObject* self, char* name)
  2292. {
  2293.     PyObject* res;
  2294.  
  2295.     res = Py_FindMethod(scanner_methods, (PyObject*) self, name);
  2296.     if (res)
  2297.         return res;
  2298.  
  2299.     PyErr_Clear();
  2300.  
  2301.     /* attributes */
  2302.     if (!strcmp(name, "pattern")) {
  2303.         Py_INCREF(self->pattern);
  2304.         return self->pattern;
  2305.     }
  2306.  
  2307.     PyErr_SetString(PyExc_AttributeError, name);
  2308.     return NULL;
  2309. }
  2310.  
  2311. statichere PyTypeObject Scanner_Type = {
  2312.     PyObject_HEAD_INIT(NULL)
  2313.     0, "SRE_Scanner",
  2314.     sizeof(ScannerObject), 0,
  2315.     (destructor)scanner_dealloc, /*tp_dealloc*/
  2316.     0, /*tp_print*/
  2317.     (getattrfunc)scanner_getattr, /*tp_getattr*/
  2318. };
  2319.  
  2320. static PyMethodDef _functions[] = {
  2321.     {"compile", _compile, 1},
  2322.     {"getcodesize", sre_codesize, 1},
  2323.     {"getlower", sre_getlower, 1},
  2324.     {NULL, NULL}
  2325. };
  2326.  
  2327. void
  2328. #if defined(WIN32)
  2329. __declspec(dllexport)
  2330. #endif
  2331. init_sre(void)
  2332. {
  2333.     /* Patch object types */
  2334.     Pattern_Type.ob_type = Match_Type.ob_type =
  2335.         Scanner_Type.ob_type = &PyType_Type;
  2336.  
  2337.     Py_InitModule("_" MODULE, _functions);
  2338. }
  2339.  
  2340. #endif /* !defined(SRE_RECURSIVE) */
  2341.