]> git.proxmox.com Git - mirror_edk2.git/blobdiff - AppPkg/Applications/Python/Python-2.7.10/PyMod-2.7.10/Modules/_sre.c
AppPkg/Applications/Python/Python-2.7.10: Initial Checkin part 5/5.
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.10 / PyMod-2.7.10 / Modules / _sre.c
diff --git a/AppPkg/Applications/Python/Python-2.7.10/PyMod-2.7.10/Modules/_sre.c b/AppPkg/Applications/Python/Python-2.7.10/PyMod-2.7.10/Modules/_sre.c
new file mode 100644 (file)
index 0000000..399ea74
--- /dev/null
@@ -0,0 +1,4034 @@
+/*\r
+ * Secret Labs' Regular Expression Engine\r
+ *\r
+ * regular expression matching engine\r
+ *\r
+ * partial history:\r
+ * 1999-10-24 fl  created (based on existing template matcher code)\r
+ * 2000-03-06 fl  first alpha, sort of\r
+ * 2000-08-01 fl  fixes for 1.6b1\r
+ * 2000-08-07 fl  use PyOS_CheckStack() if available\r
+ * 2000-09-20 fl  added expand method\r
+ * 2001-03-20 fl  lots of fixes for 2.1b2\r
+ * 2001-04-15 fl  export copyright as Python attribute, not global\r
+ * 2001-04-28 fl  added __copy__ methods (work in progress)\r
+ * 2001-05-14 fl  fixes for 1.5.2 compatibility\r
+ * 2001-07-01 fl  added BIGCHARSET support (from Martin von Loewis)\r
+ * 2001-10-18 fl  fixed group reset issue (from Matthew Mueller)\r
+ * 2001-10-20 fl  added split primitive; reenable unicode for 1.6/2.0/2.1\r
+ * 2001-10-21 fl  added sub/subn primitive\r
+ * 2001-10-24 fl  added finditer primitive (for 2.2 only)\r
+ * 2001-12-07 fl  fixed memory leak in sub/subn (Guido van Rossum)\r
+ * 2002-11-09 fl  fixed empty sub/subn return type\r
+ * 2003-04-18 mvl fully support 4-byte codes\r
+ * 2003-10-17 gn  implemented non recursive scheme\r
+ *\r
+ * Copyright (c) 1997-2001 by Secret Labs AB.  All rights reserved.\r
+ *\r
+ * This version of the SRE library can be redistributed under CNRI's\r
+ * Python 1.6 license.  For any other use, please contact Secret Labs\r
+ * AB (info@pythonware.com).\r
+ *\r
+ * Portions of this engine have been developed in cooperation with\r
+ * CNRI.  Hewlett-Packard provided funding for 1.6 integration and\r
+ * other compatibility work.\r
+ */\r
+\r
+#ifndef SRE_RECURSIVE\r
+\r
+static char copyright[] =\r
+    " SRE 2.2.2 Copyright (c) 1997-2002 by Secret Labs AB ";\r
+\r
+#define PY_SSIZE_T_CLEAN\r
+\r
+#include "Python.h"\r
+#include "structmember.h" /* offsetof */\r
+\r
+#include "sre.h"\r
+\r
+#include <ctype.h>\r
+\r
+/* name of this module, minus the leading underscore */\r
+#if !defined(SRE_MODULE)\r
+#define SRE_MODULE "sre"\r
+#endif\r
+\r
+#define SRE_PY_MODULE "re"\r
+\r
+/* defining this one enables tracing */\r
+#undef VERBOSE\r
+\r
+#if PY_VERSION_HEX >= 0x01060000\r
+#if PY_VERSION_HEX  < 0x02020000 || defined(Py_USING_UNICODE)\r
+/* defining this enables unicode support (default under 1.6a1 and later) */\r
+#define HAVE_UNICODE\r
+#endif\r
+#endif\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* optional features */\r
+\r
+/* enables fast searching */\r
+#define USE_FAST_SEARCH\r
+\r
+/* enables aggressive inlining (always on for Visual C) */\r
+#undef USE_INLINE\r
+\r
+/* enables copy/deepcopy handling (work in progress) */\r
+#undef USE_BUILTIN_COPY\r
+\r
+#if PY_VERSION_HEX < 0x01060000\r
+#define PyObject_DEL(op) PyMem_DEL((op))\r
+#endif\r
+\r
+/* -------------------------------------------------------------------- */\r
+\r
+#if defined(_MSC_VER)\r
+#pragma optimize("agtw", on) /* doesn't seem to make much difference... */\r
+#pragma warning(disable: 4710) /* who cares if functions are not inlined ;-) */\r
+/* fastest possible local call under MSVC */\r
+#define LOCAL(type) static __inline type __fastcall\r
+#elif defined(USE_INLINE)\r
+#define LOCAL(type) static inline type\r
+#else\r
+#define LOCAL(type) static type\r
+#endif\r
+\r
+/* error codes */\r
+#define SRE_ERROR_ILLEGAL -1 /* illegal opcode */\r
+#define SRE_ERROR_STATE -2 /* illegal state */\r
+#define SRE_ERROR_RECURSION_LIMIT -3 /* runaway recursion */\r
+#define SRE_ERROR_MEMORY -9 /* out of memory */\r
+#define SRE_ERROR_INTERRUPTED -10 /* signal handler raised exception */\r
+\r
+#if defined(VERBOSE)\r
+#define TRACE(v) printf v\r
+#else\r
+#define TRACE(v)\r
+#endif\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* search engine state */\r
+\r
+/* default character predicates (run sre_chars.py to regenerate tables) */\r
+\r
+#define SRE_DIGIT_MASK 1\r
+#define SRE_SPACE_MASK 2\r
+#define SRE_LINEBREAK_MASK 4\r
+#define SRE_ALNUM_MASK 8\r
+#define SRE_WORD_MASK 16\r
+\r
+/* FIXME: this assumes ASCII.  create tables in init_sre() instead */\r
+\r
+static char sre_char_info[128] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 2,\r
+2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0,\r
+0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 25, 25, 25, 25, 25, 25, 25,\r
+25, 25, 0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\r
+24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0,\r
+0, 0, 16, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\r
+24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 0, 0, 0 };\r
+\r
+static char sre_char_lower[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\r
+10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,\r
+27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,\r
+44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,\r
+61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,\r
+108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,\r
+122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,\r
+106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,\r
+120, 121, 122, 123, 124, 125, 126, 127 };\r
+\r
+#define SRE_IS_DIGIT(ch)\\r
+    ((ch) < 128 ? (sre_char_info[(ch)] & SRE_DIGIT_MASK) : 0)\r
+#define SRE_IS_SPACE(ch)\\r
+    ((ch) < 128 ? (sre_char_info[(ch)] & SRE_SPACE_MASK) : 0)\r
+#define SRE_IS_LINEBREAK(ch)\\r
+    ((ch) < 128 ? (sre_char_info[(ch)] & SRE_LINEBREAK_MASK) : 0)\r
+#define SRE_IS_ALNUM(ch)\\r
+    ((ch) < 128 ? (sre_char_info[(ch)] & SRE_ALNUM_MASK) : 0)\r
+#define SRE_IS_WORD(ch)\\r
+    ((ch) < 128 ? (sre_char_info[(ch)] & SRE_WORD_MASK) : 0)\r
+\r
+static unsigned int sre_lower(unsigned int ch)\r
+{\r
+    return ((ch) < 128 ? (unsigned int)sre_char_lower[ch] : ch);\r
+}\r
+\r
+/* locale-specific character predicates */\r
+/* !(c & ~N) == (c < N+1) for any unsigned c, this avoids\r
+ * warnings when c's type supports only numbers < N+1 */\r
+#define SRE_LOC_IS_DIGIT(ch) (!((ch) & ~255) ? isdigit((ch)) : 0)\r
+#define SRE_LOC_IS_SPACE(ch) (!((ch) & ~255) ? isspace((ch)) : 0)\r
+#define SRE_LOC_IS_LINEBREAK(ch) ((ch) == '\n')\r
+#define SRE_LOC_IS_ALNUM(ch) (!((ch) & ~255) ? isalnum((ch)) : 0)\r
+#define SRE_LOC_IS_WORD(ch) (SRE_LOC_IS_ALNUM((ch)) || (ch) == '_')\r
+\r
+static unsigned int sre_lower_locale(unsigned int ch)\r
+{\r
+    return ((ch) < 256 ? (unsigned int)tolower((ch)) : ch);\r
+}\r
+\r
+/* unicode-specific character predicates */\r
+\r
+#if defined(HAVE_UNICODE)\r
+\r
+#define SRE_UNI_IS_DIGIT(ch) Py_UNICODE_ISDECIMAL((Py_UNICODE)(ch))\r
+#define SRE_UNI_IS_SPACE(ch) Py_UNICODE_ISSPACE((Py_UNICODE)(ch))\r
+#define SRE_UNI_IS_LINEBREAK(ch) Py_UNICODE_ISLINEBREAK((Py_UNICODE)(ch))\r
+#define SRE_UNI_IS_ALNUM(ch) Py_UNICODE_ISALNUM((Py_UNICODE)(ch))\r
+#define SRE_UNI_IS_WORD(ch) (SRE_UNI_IS_ALNUM((ch)) || (ch) == '_')\r
+\r
+static unsigned int sre_lower_unicode(unsigned int ch)\r
+{\r
+    return (unsigned int) Py_UNICODE_TOLOWER((Py_UNICODE)(ch));\r
+}\r
+\r
+#endif\r
+\r
+LOCAL(int)\r
+sre_category(SRE_CODE category, unsigned int ch)\r
+{\r
+    switch (category) {\r
+\r
+    case SRE_CATEGORY_DIGIT:\r
+        return SRE_IS_DIGIT(ch);\r
+    case SRE_CATEGORY_NOT_DIGIT:\r
+        return !SRE_IS_DIGIT(ch);\r
+    case SRE_CATEGORY_SPACE:\r
+        return SRE_IS_SPACE(ch);\r
+    case SRE_CATEGORY_NOT_SPACE:\r
+        return !SRE_IS_SPACE(ch);\r
+    case SRE_CATEGORY_WORD:\r
+        return SRE_IS_WORD(ch);\r
+    case SRE_CATEGORY_NOT_WORD:\r
+        return !SRE_IS_WORD(ch);\r
+    case SRE_CATEGORY_LINEBREAK:\r
+        return SRE_IS_LINEBREAK(ch);\r
+    case SRE_CATEGORY_NOT_LINEBREAK:\r
+        return !SRE_IS_LINEBREAK(ch);\r
+\r
+    case SRE_CATEGORY_LOC_WORD:\r
+        return SRE_LOC_IS_WORD(ch);\r
+    case SRE_CATEGORY_LOC_NOT_WORD:\r
+        return !SRE_LOC_IS_WORD(ch);\r
+\r
+#if defined(HAVE_UNICODE)\r
+    case SRE_CATEGORY_UNI_DIGIT:\r
+        return SRE_UNI_IS_DIGIT(ch);\r
+    case SRE_CATEGORY_UNI_NOT_DIGIT:\r
+        return !SRE_UNI_IS_DIGIT(ch);\r
+    case SRE_CATEGORY_UNI_SPACE:\r
+        return SRE_UNI_IS_SPACE(ch);\r
+    case SRE_CATEGORY_UNI_NOT_SPACE:\r
+        return !SRE_UNI_IS_SPACE(ch);\r
+    case SRE_CATEGORY_UNI_WORD:\r
+        return SRE_UNI_IS_WORD(ch);\r
+    case SRE_CATEGORY_UNI_NOT_WORD:\r
+        return !SRE_UNI_IS_WORD(ch);\r
+    case SRE_CATEGORY_UNI_LINEBREAK:\r
+        return SRE_UNI_IS_LINEBREAK(ch);\r
+    case SRE_CATEGORY_UNI_NOT_LINEBREAK:\r
+        return !SRE_UNI_IS_LINEBREAK(ch);\r
+#else\r
+    case SRE_CATEGORY_UNI_DIGIT:\r
+        return SRE_IS_DIGIT(ch);\r
+    case SRE_CATEGORY_UNI_NOT_DIGIT:\r
+        return !SRE_IS_DIGIT(ch);\r
+    case SRE_CATEGORY_UNI_SPACE:\r
+        return SRE_IS_SPACE(ch);\r
+    case SRE_CATEGORY_UNI_NOT_SPACE:\r
+        return !SRE_IS_SPACE(ch);\r
+    case SRE_CATEGORY_UNI_WORD:\r
+        return SRE_LOC_IS_WORD(ch);\r
+    case SRE_CATEGORY_UNI_NOT_WORD:\r
+        return !SRE_LOC_IS_WORD(ch);\r
+    case SRE_CATEGORY_UNI_LINEBREAK:\r
+        return SRE_IS_LINEBREAK(ch);\r
+    case SRE_CATEGORY_UNI_NOT_LINEBREAK:\r
+        return !SRE_IS_LINEBREAK(ch);\r
+#endif\r
+    }\r
+    return 0;\r
+}\r
+\r
+/* helpers */\r
+\r
+static void\r
+data_stack_dealloc(SRE_STATE* state)\r
+{\r
+    if (state->data_stack) {\r
+        PyMem_FREE(state->data_stack);\r
+        state->data_stack = NULL;\r
+    }\r
+    state->data_stack_size = state->data_stack_base = 0;\r
+}\r
+\r
+static int\r
+data_stack_grow(SRE_STATE* state, Py_ssize_t size)\r
+{\r
+    Py_ssize_t minsize, cursize;\r
+    minsize = state->data_stack_base+size;\r
+    cursize = state->data_stack_size;\r
+    if (cursize < minsize) {\r
+        void* stack;\r
+        cursize = minsize+minsize/4+1024;\r
+        TRACE(("allocate/grow stack %" PY_FORMAT_SIZE_T "d\n", cursize));\r
+        stack = PyMem_REALLOC(state->data_stack, cursize);\r
+        if (!stack) {\r
+            data_stack_dealloc(state);\r
+            return SRE_ERROR_MEMORY;\r
+        }\r
+        state->data_stack = (char *)stack;\r
+        state->data_stack_size = cursize;\r
+    }\r
+    return 0;\r
+}\r
+\r
+/* generate 8-bit version */\r
+\r
+#define SRE_CHAR unsigned char\r
+#define SRE_AT sre_at\r
+#define SRE_COUNT sre_count\r
+#define SRE_CHARSET sre_charset\r
+#define SRE_INFO sre_info\r
+#define SRE_MATCH sre_match\r
+#define SRE_MATCH_CONTEXT sre_match_context\r
+#define SRE_SEARCH sre_search\r
+#define SRE_LITERAL_TEMPLATE sre_literal_template\r
+\r
+#if defined(HAVE_UNICODE)\r
+\r
+#define SRE_RECURSIVE\r
+#include "_sre.c"\r
+#undef SRE_RECURSIVE\r
+\r
+#undef SRE_LITERAL_TEMPLATE\r
+#undef SRE_SEARCH\r
+#undef SRE_MATCH\r
+#undef SRE_MATCH_CONTEXT\r
+#undef SRE_INFO\r
+#undef SRE_CHARSET\r
+#undef SRE_COUNT\r
+#undef SRE_AT\r
+#undef SRE_CHAR\r
+\r
+/* generate 16-bit unicode version */\r
+\r
+#define SRE_CHAR Py_UNICODE\r
+#define SRE_AT sre_uat\r
+#define SRE_COUNT sre_ucount\r
+#define SRE_CHARSET sre_ucharset\r
+#define SRE_INFO sre_uinfo\r
+#define SRE_MATCH sre_umatch\r
+#define SRE_MATCH_CONTEXT sre_umatch_context\r
+#define SRE_SEARCH sre_usearch\r
+#define SRE_LITERAL_TEMPLATE sre_uliteral_template\r
+#endif\r
+\r
+#endif /* SRE_RECURSIVE */\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* String matching engine */\r
+\r
+/* the following section is compiled twice, with different character\r
+   settings */\r
+\r
+LOCAL(int)\r
+SRE_AT(SRE_STATE* state, SRE_CHAR* ptr, SRE_CODE at)\r
+{\r
+    /* check if pointer is at given position */\r
+\r
+    Py_ssize_t thisp, thatp;\r
+\r
+    switch (at) {\r
+\r
+    case SRE_AT_BEGINNING:\r
+    case SRE_AT_BEGINNING_STRING:\r
+        return ((void*) ptr == state->beginning);\r
+\r
+    case SRE_AT_BEGINNING_LINE:\r
+        return ((void*) ptr == state->beginning ||\r
+                SRE_IS_LINEBREAK((int) ptr[-1]));\r
+\r
+    case SRE_AT_END:\r
+        return (((void*) (ptr+1) == state->end &&\r
+                 SRE_IS_LINEBREAK((int) ptr[0])) ||\r
+                ((void*) ptr == state->end));\r
+\r
+    case SRE_AT_END_LINE:\r
+        return ((void*) ptr == state->end ||\r
+                SRE_IS_LINEBREAK((int) ptr[0]));\r
+\r
+    case SRE_AT_END_STRING:\r
+        return ((void*) ptr == state->end);\r
+\r
+    case SRE_AT_BOUNDARY:\r
+        if (state->beginning == state->end)\r
+            return 0;\r
+        thatp = ((void*) ptr > state->beginning) ?\r
+            SRE_IS_WORD((int) ptr[-1]) : 0;\r
+        thisp = ((void*) ptr < state->end) ?\r
+            SRE_IS_WORD((int) ptr[0]) : 0;\r
+        return thisp != thatp;\r
+\r
+    case SRE_AT_NON_BOUNDARY:\r
+        if (state->beginning == state->end)\r
+            return 0;\r
+        thatp = ((void*) ptr > state->beginning) ?\r
+            SRE_IS_WORD((int) ptr[-1]) : 0;\r
+        thisp = ((void*) ptr < state->end) ?\r
+            SRE_IS_WORD((int) ptr[0]) : 0;\r
+        return thisp == thatp;\r
+\r
+    case SRE_AT_LOC_BOUNDARY:\r
+        if (state->beginning == state->end)\r
+            return 0;\r
+        thatp = ((void*) ptr > state->beginning) ?\r
+            SRE_LOC_IS_WORD((int) ptr[-1]) : 0;\r
+        thisp = ((void*) ptr < state->end) ?\r
+            SRE_LOC_IS_WORD((int) ptr[0]) : 0;\r
+        return thisp != thatp;\r
+\r
+    case SRE_AT_LOC_NON_BOUNDARY:\r
+        if (state->beginning == state->end)\r
+            return 0;\r
+        thatp = ((void*) ptr > state->beginning) ?\r
+            SRE_LOC_IS_WORD((int) ptr[-1]) : 0;\r
+        thisp = ((void*) ptr < state->end) ?\r
+            SRE_LOC_IS_WORD((int) ptr[0]) : 0;\r
+        return thisp == thatp;\r
+\r
+#if defined(HAVE_UNICODE)\r
+    case SRE_AT_UNI_BOUNDARY:\r
+        if (state->beginning == state->end)\r
+            return 0;\r
+        thatp = ((void*) ptr > state->beginning) ?\r
+            SRE_UNI_IS_WORD((int) ptr[-1]) : 0;\r
+        thisp = ((void*) ptr < state->end) ?\r
+            SRE_UNI_IS_WORD((int) ptr[0]) : 0;\r
+        return thisp != thatp;\r
+\r
+    case SRE_AT_UNI_NON_BOUNDARY:\r
+        if (state->beginning == state->end)\r
+            return 0;\r
+        thatp = ((void*) ptr > state->beginning) ?\r
+            SRE_UNI_IS_WORD((int) ptr[-1]) : 0;\r
+        thisp = ((void*) ptr < state->end) ?\r
+            SRE_UNI_IS_WORD((int) ptr[0]) : 0;\r
+        return thisp == thatp;\r
+#endif\r
+\r
+    }\r
+\r
+    return 0;\r
+}\r
+\r
+LOCAL(int)\r
+SRE_CHARSET(SRE_CODE* set, SRE_CODE ch)\r
+{\r
+    /* check if character is a member of the given set */\r
+\r
+    int ok = 1;\r
+\r
+    for (;;) {\r
+        switch (*set++) {\r
+\r
+        case SRE_OP_FAILURE:\r
+            return !ok;\r
+\r
+        case SRE_OP_LITERAL:\r
+            /* <LITERAL> <code> */\r
+            if (ch == set[0])\r
+                return ok;\r
+            set++;\r
+            break;\r
+\r
+        case SRE_OP_CATEGORY:\r
+            /* <CATEGORY> <code> */\r
+            if (sre_category(set[0], (int) ch))\r
+                return ok;\r
+            set += 1;\r
+            break;\r
+\r
+        case SRE_OP_CHARSET:\r
+            if (sizeof(SRE_CODE) == 2) {\r
+                /* <CHARSET> <bitmap> (16 bits per code word) */\r
+                if (ch < 256 && (set[ch >> 4] & (1 << (ch & 15))))\r
+                    return ok;\r
+                set += 16;\r
+            }\r
+            else {\r
+                /* <CHARSET> <bitmap> (32 bits per code word) */\r
+                if (ch < 256 && (set[ch >> 5] & (1u << (ch & 31))))\r
+                    return ok;\r
+                set += 8;\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_RANGE:\r
+            /* <RANGE> <lower> <upper> */\r
+            if (set[0] <= ch && ch <= set[1])\r
+                return ok;\r
+            set += 2;\r
+            break;\r
+\r
+        case SRE_OP_NEGATE:\r
+            ok = !ok;\r
+            break;\r
+\r
+        case SRE_OP_BIGCHARSET:\r
+            /* <BIGCHARSET> <blockcount> <256 blockindices> <blocks> */\r
+        {\r
+            Py_ssize_t count, block;\r
+            count = *(set++);\r
+\r
+            if (sizeof(SRE_CODE) == 2) {\r
+                block = ((unsigned char*)set)[ch >> 8];\r
+                set += 128;\r
+                if (set[block*16 + ((ch & 255)>>4)] & (1 << (ch & 15)))\r
+                    return ok;\r
+                set += count*16;\r
+            }\r
+            else {\r
+                /* !(c & ~N) == (c < N+1) for any unsigned c, this avoids\r
+                 * warnings when c's type supports only numbers < N+1 */\r
+                if (!(ch & ~65535))\r
+                    block = ((unsigned char*)set)[ch >> 8];\r
+                else\r
+                    block = -1;\r
+                set += 64;\r
+                if (block >=0 &&\r
+                    (set[block*8 + ((ch & 255)>>5)] & (1u << (ch & 31))))\r
+                    return ok;\r
+                set += count*8;\r
+            }\r
+            break;\r
+        }\r
+\r
+        default:\r
+            /* internal error -- there's not much we can do about it\r
+               here, so let's just pretend it didn't match... */\r
+            return 0;\r
+        }\r
+    }\r
+}\r
+\r
+LOCAL(Py_ssize_t) SRE_MATCH(SRE_STATE* state, SRE_CODE* pattern);\r
+\r
+LOCAL(Py_ssize_t)\r
+SRE_COUNT(SRE_STATE* state, SRE_CODE* pattern, Py_ssize_t maxcount)\r
+{\r
+    SRE_CODE chr;\r
+    SRE_CHAR* ptr = (SRE_CHAR *)state->ptr;\r
+    SRE_CHAR* end = (SRE_CHAR *)state->end;\r
+    Py_ssize_t i;\r
+\r
+    /* adjust end */\r
+    if (maxcount < end - ptr && maxcount != SRE_MAXREPEAT)\r
+        end = ptr + maxcount;\r
+\r
+    switch (pattern[0]) {\r
+\r
+    case SRE_OP_IN:\r
+        /* repeated set */\r
+        TRACE(("|%p|%p|COUNT IN\n", pattern, ptr));\r
+        while (ptr < end && SRE_CHARSET(pattern + 2, *ptr))\r
+            ptr++;\r
+        break;\r
+\r
+    case SRE_OP_ANY:\r
+        /* repeated dot wildcard. */\r
+        TRACE(("|%p|%p|COUNT ANY\n", pattern, ptr));\r
+        while (ptr < end && !SRE_IS_LINEBREAK(*ptr))\r
+            ptr++;\r
+        break;\r
+\r
+    case SRE_OP_ANY_ALL:\r
+        /* repeated dot wildcard.  skip to the end of the target\r
+           string, and backtrack from there */\r
+        TRACE(("|%p|%p|COUNT ANY_ALL\n", pattern, ptr));\r
+        ptr = end;\r
+        break;\r
+\r
+    case SRE_OP_LITERAL:\r
+        /* repeated literal */\r
+        chr = pattern[1];\r
+        TRACE(("|%p|%p|COUNT LITERAL %d\n", pattern, ptr, chr));\r
+        while (ptr < end && (SRE_CODE) *ptr == chr)\r
+            ptr++;\r
+        break;\r
+\r
+    case SRE_OP_LITERAL_IGNORE:\r
+        /* repeated literal */\r
+        chr = pattern[1];\r
+        TRACE(("|%p|%p|COUNT LITERAL_IGNORE %d\n", pattern, ptr, chr));\r
+        while (ptr < end && (SRE_CODE) state->lower(*ptr) == chr)\r
+            ptr++;\r
+        break;\r
+\r
+    case SRE_OP_NOT_LITERAL:\r
+        /* repeated non-literal */\r
+        chr = pattern[1];\r
+        TRACE(("|%p|%p|COUNT NOT_LITERAL %d\n", pattern, ptr, chr));\r
+        while (ptr < end && (SRE_CODE) *ptr != chr)\r
+            ptr++;\r
+        break;\r
+\r
+    case SRE_OP_NOT_LITERAL_IGNORE:\r
+        /* repeated non-literal */\r
+        chr = pattern[1];\r
+        TRACE(("|%p|%p|COUNT NOT_LITERAL_IGNORE %d\n", pattern, ptr, chr));\r
+        while (ptr < end && (SRE_CODE) state->lower(*ptr) != chr)\r
+            ptr++;\r
+        break;\r
+\r
+    default:\r
+        /* repeated single character pattern */\r
+        TRACE(("|%p|%p|COUNT SUBPATTERN\n", pattern, ptr));\r
+        while ((SRE_CHAR*) state->ptr < end) {\r
+            i = SRE_MATCH(state, pattern);\r
+            if (i < 0)\r
+                return i;\r
+            if (!i)\r
+                break;\r
+        }\r
+        TRACE(("|%p|%p|COUNT %" PY_FORMAT_SIZE_T "d\n", pattern, ptr,\r
+               (SRE_CHAR*) state->ptr - ptr));\r
+        return (SRE_CHAR*) state->ptr - ptr;\r
+    }\r
+\r
+    TRACE(("|%p|%p|COUNT %" PY_FORMAT_SIZE_T "d\n", pattern, ptr,\r
+           ptr - (SRE_CHAR*) state->ptr));\r
+    return ptr - (SRE_CHAR*) state->ptr;\r
+}\r
+\r
+#if 0 /* not used in this release */\r
+LOCAL(int)\r
+SRE_INFO(SRE_STATE* state, SRE_CODE* pattern)\r
+{\r
+    /* check if an SRE_OP_INFO block matches at the current position.\r
+       returns the number of SRE_CODE objects to skip if successful, 0\r
+       if no match */\r
+\r
+    SRE_CHAR* end = state->end;\r
+    SRE_CHAR* ptr = state->ptr;\r
+    Py_ssize_t i;\r
+\r
+    /* check minimal length */\r
+    if (pattern[3] && (end - ptr) < pattern[3])\r
+        return 0;\r
+\r
+    /* check known prefix */\r
+    if (pattern[2] & SRE_INFO_PREFIX && pattern[5] > 1) {\r
+        /* <length> <skip> <prefix data> <overlap data> */\r
+        for (i = 0; i < pattern[5]; i++)\r
+            if ((SRE_CODE) ptr[i] != pattern[7 + i])\r
+                return 0;\r
+        return pattern[0] + 2 * pattern[6];\r
+    }\r
+    return pattern[0];\r
+}\r
+#endif\r
+\r
+/* The macros below should be used to protect recursive SRE_MATCH()\r
+ * calls that *failed* and do *not* return immediately (IOW, those\r
+ * that will backtrack). Explaining:\r
+ *\r
+ * - Recursive SRE_MATCH() returned true: that's usually a success\r
+ *   (besides atypical cases like ASSERT_NOT), therefore there's no\r
+ *   reason to restore lastmark;\r
+ *\r
+ * - Recursive SRE_MATCH() returned false but the current SRE_MATCH()\r
+ *   is returning to the caller: If the current SRE_MATCH() is the\r
+ *   top function of the recursion, returning false will be a matching\r
+ *   failure, and it doesn't matter where lastmark is pointing to.\r
+ *   If it's *not* the top function, it will be a recursive SRE_MATCH()\r
+ *   failure by itself, and the calling SRE_MATCH() will have to deal\r
+ *   with the failure by the same rules explained here (it will restore\r
+ *   lastmark by itself if necessary);\r
+ *\r
+ * - Recursive SRE_MATCH() returned false, and will continue the\r
+ *   outside 'for' loop: must be protected when breaking, since the next\r
+ *   OP could potentially depend on lastmark;\r
+ *\r
+ * - Recursive SRE_MATCH() returned false, and will be called again\r
+ *   inside a local for/while loop: must be protected between each\r
+ *   loop iteration, since the recursive SRE_MATCH() could do anything,\r
+ *   and could potentially depend on lastmark.\r
+ *\r
+ * For more information, check the discussion at SF patch #712900.\r
+ */\r
+#define LASTMARK_SAVE()     \\r
+    do { \\r
+        ctx->lastmark = state->lastmark; \\r
+        ctx->lastindex = state->lastindex; \\r
+    } while (0)\r
+#define LASTMARK_RESTORE()  \\r
+    do { \\r
+        state->lastmark = ctx->lastmark; \\r
+        state->lastindex = ctx->lastindex; \\r
+    } while (0)\r
+\r
+#define RETURN_ERROR(i) do { return i; } while(0)\r
+#define RETURN_FAILURE do { ret = 0; goto exit; } while(0)\r
+#define RETURN_SUCCESS do { ret = 1; goto exit; } while(0)\r
+\r
+#define RETURN_ON_ERROR(i) \\r
+    do { if (i < 0) RETURN_ERROR(i); } while (0)\r
+#define RETURN_ON_SUCCESS(i) \\r
+    do { RETURN_ON_ERROR(i); if (i > 0) RETURN_SUCCESS; } while (0)\r
+#define RETURN_ON_FAILURE(i) \\r
+    do { RETURN_ON_ERROR(i); if (i == 0) RETURN_FAILURE; } while (0)\r
+\r
+#define SFY(x) #x\r
+\r
+#define DATA_STACK_ALLOC(state, type, ptr) \\r
+do { \\r
+    alloc_pos = state->data_stack_base; \\r
+    TRACE(("allocating %s in %" PY_FORMAT_SIZE_T "d " \\r
+           "(%" PY_FORMAT_SIZE_T "d)\n", \\r
+           SFY(type), alloc_pos, sizeof(type))); \\r
+    if (sizeof(type) > state->data_stack_size - alloc_pos) { \\r
+        int j = data_stack_grow(state, sizeof(type)); \\r
+        if (j < 0) return j; \\r
+        if (ctx_pos != -1) \\r
+            DATA_STACK_LOOKUP_AT(state, SRE_MATCH_CONTEXT, ctx, ctx_pos); \\r
+    } \\r
+    ptr = (type*)(state->data_stack+alloc_pos); \\r
+    state->data_stack_base += sizeof(type); \\r
+} while (0)\r
+\r
+#define DATA_STACK_LOOKUP_AT(state, type, ptr, pos) \\r
+do { \\r
+    TRACE(("looking up %s at %" PY_FORMAT_SIZE_T "d\n", SFY(type), pos)); \\r
+    ptr = (type*)(state->data_stack+pos); \\r
+} while (0)\r
+\r
+#define DATA_STACK_PUSH(state, data, size) \\r
+do { \\r
+    TRACE(("copy data in %p to %" PY_FORMAT_SIZE_T "d " \\r
+           "(%" PY_FORMAT_SIZE_T "d)\n", \\r
+           data, state->data_stack_base, size)); \\r
+    if (size > state->data_stack_size - state->data_stack_base) { \\r
+        int j = data_stack_grow(state, size); \\r
+        if (j < 0) return j; \\r
+        if (ctx_pos != -1) \\r
+            DATA_STACK_LOOKUP_AT(state, SRE_MATCH_CONTEXT, ctx, ctx_pos); \\r
+    } \\r
+    memcpy(state->data_stack+state->data_stack_base, data, size); \\r
+    state->data_stack_base += size; \\r
+} while (0)\r
+\r
+#define DATA_STACK_POP(state, data, size, discard) \\r
+do { \\r
+    TRACE(("copy data to %p from %" PY_FORMAT_SIZE_T "d " \\r
+           "(%" PY_FORMAT_SIZE_T "d)\n", \\r
+           data, state->data_stack_base-size, size)); \\r
+    memcpy(data, state->data_stack+state->data_stack_base-size, size); \\r
+    if (discard) \\r
+        state->data_stack_base -= size; \\r
+} while (0)\r
+\r
+#define DATA_STACK_POP_DISCARD(state, size) \\r
+do { \\r
+    TRACE(("discard data from %" PY_FORMAT_SIZE_T "d " \\r
+           "(%" PY_FORMAT_SIZE_T "d)\n", \\r
+           state->data_stack_base-size, size)); \\r
+    state->data_stack_base -= size; \\r
+} while(0)\r
+\r
+#define DATA_PUSH(x) \\r
+    DATA_STACK_PUSH(state, (x), sizeof(*(x)))\r
+#define DATA_POP(x) \\r
+    DATA_STACK_POP(state, (x), sizeof(*(x)), 1)\r
+#define DATA_POP_DISCARD(x) \\r
+    DATA_STACK_POP_DISCARD(state, sizeof(*(x)))\r
+#define DATA_ALLOC(t,p) \\r
+    DATA_STACK_ALLOC(state, t, p)\r
+#define DATA_LOOKUP_AT(t,p,pos) \\r
+    DATA_STACK_LOOKUP_AT(state,t,p,pos)\r
+\r
+#define MARK_PUSH(lastmark) \\r
+    do if (lastmark > 0) { \\r
+        i = lastmark; /* ctx->lastmark may change if reallocated */ \\r
+        DATA_STACK_PUSH(state, state->mark, (i+1)*sizeof(void*)); \\r
+    } while (0)\r
+#define MARK_POP(lastmark) \\r
+    do if (lastmark > 0) { \\r
+        DATA_STACK_POP(state, state->mark, (lastmark+1)*sizeof(void*), 1); \\r
+    } while (0)\r
+#define MARK_POP_KEEP(lastmark) \\r
+    do if (lastmark > 0) { \\r
+        DATA_STACK_POP(state, state->mark, (lastmark+1)*sizeof(void*), 0); \\r
+    } while (0)\r
+#define MARK_POP_DISCARD(lastmark) \\r
+    do if (lastmark > 0) { \\r
+        DATA_STACK_POP_DISCARD(state, (lastmark+1)*sizeof(void*)); \\r
+    } while (0)\r
+\r
+#define JUMP_NONE            0\r
+#define JUMP_MAX_UNTIL_1     1\r
+#define JUMP_MAX_UNTIL_2     2\r
+#define JUMP_MAX_UNTIL_3     3\r
+#define JUMP_MIN_UNTIL_1     4\r
+#define JUMP_MIN_UNTIL_2     5\r
+#define JUMP_MIN_UNTIL_3     6\r
+#define JUMP_REPEAT          7\r
+#define JUMP_REPEAT_ONE_1    8\r
+#define JUMP_REPEAT_ONE_2    9\r
+#define JUMP_MIN_REPEAT_ONE  10\r
+#define JUMP_BRANCH          11\r
+#define JUMP_ASSERT          12\r
+#define JUMP_ASSERT_NOT      13\r
+\r
+#define DO_JUMP(jumpvalue, jumplabel, nextpattern) \\r
+    DATA_ALLOC(SRE_MATCH_CONTEXT, nextctx); \\r
+    nextctx->last_ctx_pos = ctx_pos; \\r
+    nextctx->jump = jumpvalue; \\r
+    nextctx->pattern = nextpattern; \\r
+    ctx_pos = alloc_pos; \\r
+    ctx = nextctx; \\r
+    goto entrance; \\r
+    jumplabel: \\r
+    while (0) /* gcc doesn't like labels at end of scopes */ \\r
+\r
+typedef struct {\r
+    Py_ssize_t last_ctx_pos;\r
+    Py_ssize_t jump;\r
+    SRE_CHAR* ptr;\r
+    SRE_CODE* pattern;\r
+    Py_ssize_t count;\r
+    Py_ssize_t lastmark;\r
+    Py_ssize_t lastindex;\r
+    union {\r
+        SRE_CODE chr;\r
+        SRE_REPEAT* rep;\r
+    } u;\r
+} SRE_MATCH_CONTEXT;\r
+\r
+/* check if string matches the given pattern.  returns <0 for\r
+   error, 0 for failure, and 1 for success */\r
+LOCAL(Py_ssize_t)\r
+SRE_MATCH(SRE_STATE* state, SRE_CODE* pattern)\r
+{\r
+    SRE_CHAR* end = (SRE_CHAR *)state->end;\r
+    Py_ssize_t alloc_pos, ctx_pos = -1;\r
+    Py_ssize_t i, ret = 0;\r
+    Py_ssize_t jump;\r
+    unsigned int sigcount=0;\r
+\r
+    SRE_MATCH_CONTEXT* ctx;\r
+    SRE_MATCH_CONTEXT* nextctx;\r
+\r
+    TRACE(("|%p|%p|ENTER\n", pattern, state->ptr));\r
+\r
+    DATA_ALLOC(SRE_MATCH_CONTEXT, ctx);\r
+    ctx->last_ctx_pos = -1;\r
+    ctx->jump = JUMP_NONE;\r
+    ctx->pattern = pattern;\r
+    ctx_pos = alloc_pos;\r
+\r
+entrance:\r
+\r
+    ctx->ptr = (SRE_CHAR *)state->ptr;\r
+\r
+    if (ctx->pattern[0] == SRE_OP_INFO) {\r
+        /* optimization info block */\r
+        /* <INFO> <1=skip> <2=flags> <3=min> ... */\r
+        if (ctx->pattern[3] && (end - ctx->ptr) < ctx->pattern[3]) {\r
+            TRACE(("reject (got %" PY_FORMAT_SIZE_T "d chars, "\r
+                   "need %" PY_FORMAT_SIZE_T "d)\n",\r
+                   (end - ctx->ptr), (Py_ssize_t) ctx->pattern[3]));\r
+            RETURN_FAILURE;\r
+        }\r
+        ctx->pattern += ctx->pattern[1] + 1;\r
+    }\r
+\r
+    for (;;) {\r
+        ++sigcount;\r
+        if ((0 == (sigcount & 0xfff)) && PyErr_CheckSignals())\r
+            RETURN_ERROR(SRE_ERROR_INTERRUPTED);\r
+\r
+        switch (*ctx->pattern++) {\r
+\r
+        case SRE_OP_MARK:\r
+            /* set mark */\r
+            /* <MARK> <gid> */\r
+            TRACE(("|%p|%p|MARK %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[0]));\r
+            i = ctx->pattern[0];\r
+            if (i & 1)\r
+                state->lastindex = i/2 + 1;\r
+            if (i > state->lastmark) {\r
+                /* state->lastmark is the highest valid index in the\r
+                   state->mark array.  If it is increased by more than 1,\r
+                   the intervening marks must be set to NULL to signal\r
+                   that these marks have not been encountered. */\r
+                Py_ssize_t j = state->lastmark + 1;\r
+                while (j < i)\r
+                    state->mark[j++] = NULL;\r
+                state->lastmark = i;\r
+            }\r
+            state->mark[i] = ctx->ptr;\r
+            ctx->pattern++;\r
+            break;\r
+\r
+        case SRE_OP_LITERAL:\r
+            /* match literal string */\r
+            /* <LITERAL> <code> */\r
+            TRACE(("|%p|%p|LITERAL %d\n", ctx->pattern,\r
+                   ctx->ptr, *ctx->pattern));\r
+            if (ctx->ptr >= end || (SRE_CODE) ctx->ptr[0] != ctx->pattern[0])\r
+                RETURN_FAILURE;\r
+            ctx->pattern++;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_NOT_LITERAL:\r
+            /* match anything that is not literal character */\r
+            /* <NOT_LITERAL> <code> */\r
+            TRACE(("|%p|%p|NOT_LITERAL %d\n", ctx->pattern,\r
+                   ctx->ptr, *ctx->pattern));\r
+            if (ctx->ptr >= end || (SRE_CODE) ctx->ptr[0] == ctx->pattern[0])\r
+                RETURN_FAILURE;\r
+            ctx->pattern++;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_SUCCESS:\r
+            /* end of pattern */\r
+            TRACE(("|%p|%p|SUCCESS\n", ctx->pattern, ctx->ptr));\r
+            state->ptr = ctx->ptr;\r
+            RETURN_SUCCESS;\r
+\r
+        case SRE_OP_AT:\r
+            /* match at given position */\r
+            /* <AT> <code> */\r
+            TRACE(("|%p|%p|AT %d\n", ctx->pattern, ctx->ptr, *ctx->pattern));\r
+            if (!SRE_AT(state, ctx->ptr, *ctx->pattern))\r
+                RETURN_FAILURE;\r
+            ctx->pattern++;\r
+            break;\r
+\r
+        case SRE_OP_CATEGORY:\r
+            /* match at given category */\r
+            /* <CATEGORY> <code> */\r
+            TRACE(("|%p|%p|CATEGORY %d\n", ctx->pattern,\r
+                   ctx->ptr, *ctx->pattern));\r
+            if (ctx->ptr >= end || !sre_category(ctx->pattern[0], ctx->ptr[0]))\r
+                RETURN_FAILURE;\r
+            ctx->pattern++;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_ANY:\r
+            /* match anything (except a newline) */\r
+            /* <ANY> */\r
+            TRACE(("|%p|%p|ANY\n", ctx->pattern, ctx->ptr));\r
+            if (ctx->ptr >= end || SRE_IS_LINEBREAK(ctx->ptr[0]))\r
+                RETURN_FAILURE;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_ANY_ALL:\r
+            /* match anything */\r
+            /* <ANY_ALL> */\r
+            TRACE(("|%p|%p|ANY_ALL\n", ctx->pattern, ctx->ptr));\r
+            if (ctx->ptr >= end)\r
+                RETURN_FAILURE;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_IN:\r
+            /* match set member (or non_member) */\r
+            /* <IN> <skip> <set> */\r
+            TRACE(("|%p|%p|IN\n", ctx->pattern, ctx->ptr));\r
+            if (ctx->ptr >= end || !SRE_CHARSET(ctx->pattern + 1, *ctx->ptr))\r
+                RETURN_FAILURE;\r
+            ctx->pattern += ctx->pattern[0];\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_LITERAL_IGNORE:\r
+            TRACE(("|%p|%p|LITERAL_IGNORE %d\n",\r
+                   ctx->pattern, ctx->ptr, ctx->pattern[0]));\r
+            if (ctx->ptr >= end ||\r
+                state->lower(*ctx->ptr) != state->lower(*ctx->pattern))\r
+                RETURN_FAILURE;\r
+            ctx->pattern++;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_NOT_LITERAL_IGNORE:\r
+            TRACE(("|%p|%p|NOT_LITERAL_IGNORE %d\n",\r
+                   ctx->pattern, ctx->ptr, *ctx->pattern));\r
+            if (ctx->ptr >= end ||\r
+                state->lower(*ctx->ptr) == state->lower(*ctx->pattern))\r
+                RETURN_FAILURE;\r
+            ctx->pattern++;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_IN_IGNORE:\r
+            TRACE(("|%p|%p|IN_IGNORE\n", ctx->pattern, ctx->ptr));\r
+            if (ctx->ptr >= end\r
+                || !SRE_CHARSET(ctx->pattern+1,\r
+                                (SRE_CODE)state->lower(*ctx->ptr)))\r
+                RETURN_FAILURE;\r
+            ctx->pattern += ctx->pattern[0];\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_JUMP:\r
+        case SRE_OP_INFO:\r
+            /* jump forward */\r
+            /* <JUMP> <offset> */\r
+            TRACE(("|%p|%p|JUMP %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[0]));\r
+            ctx->pattern += ctx->pattern[0];\r
+            break;\r
+\r
+        case SRE_OP_BRANCH:\r
+            /* alternation */\r
+            /* <BRANCH> <0=skip> code <JUMP> ... <NULL> */\r
+            TRACE(("|%p|%p|BRANCH\n", ctx->pattern, ctx->ptr));\r
+            LASTMARK_SAVE();\r
+            ctx->u.rep = state->repeat;\r
+            if (ctx->u.rep)\r
+                MARK_PUSH(ctx->lastmark);\r
+            for (; ctx->pattern[0]; ctx->pattern += ctx->pattern[0]) {\r
+                if (ctx->pattern[1] == SRE_OP_LITERAL &&\r
+                    (ctx->ptr >= end ||\r
+                     (SRE_CODE) *ctx->ptr != ctx->pattern[2]))\r
+                    continue;\r
+                if (ctx->pattern[1] == SRE_OP_IN &&\r
+                    (ctx->ptr >= end ||\r
+                     !SRE_CHARSET(ctx->pattern + 3, (SRE_CODE) *ctx->ptr)))\r
+                    continue;\r
+                state->ptr = ctx->ptr;\r
+                DO_JUMP(JUMP_BRANCH, jump_branch, ctx->pattern+1);\r
+                if (ret) {\r
+                    if (ctx->u.rep)\r
+                        MARK_POP_DISCARD(ctx->lastmark);\r
+                    RETURN_ON_ERROR(ret);\r
+                    RETURN_SUCCESS;\r
+                }\r
+                if (ctx->u.rep)\r
+                    MARK_POP_KEEP(ctx->lastmark);\r
+                LASTMARK_RESTORE();\r
+            }\r
+            if (ctx->u.rep)\r
+                MARK_POP_DISCARD(ctx->lastmark);\r
+            RETURN_FAILURE;\r
+\r
+        case SRE_OP_REPEAT_ONE:\r
+            /* match repeated sequence (maximizing regexp) */\r
+\r
+            /* this operator only works if the repeated item is\r
+               exactly one character wide, and we're not already\r
+               collecting backtracking points.  for other cases,\r
+               use the MAX_REPEAT operator */\r
+\r
+            /* <REPEAT_ONE> <skip> <1=min> <2=max> item <SUCCESS> tail */\r
+\r
+            TRACE(("|%p|%p|REPEAT_ONE %d %d\n", ctx->pattern, ctx->ptr,\r
+                   ctx->pattern[1], ctx->pattern[2]));\r
+\r
+            if ((Py_ssize_t) ctx->pattern[1] > end - ctx->ptr)\r
+                RETURN_FAILURE; /* cannot match */\r
+\r
+            state->ptr = ctx->ptr;\r
+\r
+            ret = SRE_COUNT(state, ctx->pattern+3, ctx->pattern[2]);\r
+            RETURN_ON_ERROR(ret);\r
+            DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos);\r
+            ctx->count = ret;\r
+            ctx->ptr += ctx->count;\r
+\r
+            /* when we arrive here, count contains the number of\r
+               matches, and ctx->ptr points to the tail of the target\r
+               string.  check if the rest of the pattern matches,\r
+               and backtrack if not. */\r
+\r
+            if (ctx->count < (Py_ssize_t) ctx->pattern[1])\r
+                RETURN_FAILURE;\r
+\r
+            if (ctx->pattern[ctx->pattern[0]] == SRE_OP_SUCCESS) {\r
+                /* tail is empty.  we're finished */\r
+                state->ptr = ctx->ptr;\r
+                RETURN_SUCCESS;\r
+            }\r
+\r
+            LASTMARK_SAVE();\r
+\r
+            if (ctx->pattern[ctx->pattern[0]] == SRE_OP_LITERAL) {\r
+                /* tail starts with a literal. skip positions where\r
+                   the rest of the pattern cannot possibly match */\r
+                ctx->u.chr = ctx->pattern[ctx->pattern[0]+1];\r
+                for (;;) {\r
+                    while (ctx->count >= (Py_ssize_t) ctx->pattern[1] &&\r
+                           (ctx->ptr >= end || *ctx->ptr != ctx->u.chr)) {\r
+                        ctx->ptr--;\r
+                        ctx->count--;\r
+                    }\r
+                    if (ctx->count < (Py_ssize_t) ctx->pattern[1])\r
+                        break;\r
+                    state->ptr = ctx->ptr;\r
+                    DO_JUMP(JUMP_REPEAT_ONE_1, jump_repeat_one_1,\r
+                            ctx->pattern+ctx->pattern[0]);\r
+                    if (ret) {\r
+                        RETURN_ON_ERROR(ret);\r
+                        RETURN_SUCCESS;\r
+                    }\r
+\r
+                    LASTMARK_RESTORE();\r
+\r
+                    ctx->ptr--;\r
+                    ctx->count--;\r
+                }\r
+\r
+            } else {\r
+                /* general case */\r
+                while (ctx->count >= (Py_ssize_t) ctx->pattern[1]) {\r
+                    state->ptr = ctx->ptr;\r
+                    DO_JUMP(JUMP_REPEAT_ONE_2, jump_repeat_one_2,\r
+                            ctx->pattern+ctx->pattern[0]);\r
+                    if (ret) {\r
+                        RETURN_ON_ERROR(ret);\r
+                        RETURN_SUCCESS;\r
+                    }\r
+                    ctx->ptr--;\r
+                    ctx->count--;\r
+                    LASTMARK_RESTORE();\r
+                }\r
+            }\r
+            RETURN_FAILURE;\r
+\r
+        case SRE_OP_MIN_REPEAT_ONE:\r
+            /* match repeated sequence (minimizing regexp) */\r
+\r
+            /* this operator only works if the repeated item is\r
+               exactly one character wide, and we're not already\r
+               collecting backtracking points.  for other cases,\r
+               use the MIN_REPEAT operator */\r
+\r
+            /* <MIN_REPEAT_ONE> <skip> <1=min> <2=max> item <SUCCESS> tail */\r
+\r
+            TRACE(("|%p|%p|MIN_REPEAT_ONE %d %d\n", ctx->pattern, ctx->ptr,\r
+                   ctx->pattern[1], ctx->pattern[2]));\r
+\r
+            if ((Py_ssize_t) ctx->pattern[1] > end - ctx->ptr)\r
+                RETURN_FAILURE; /* cannot match */\r
+\r
+            state->ptr = ctx->ptr;\r
+\r
+            if (ctx->pattern[1] == 0)\r
+                ctx->count = 0;\r
+            else {\r
+                /* count using pattern min as the maximum */\r
+                ret = SRE_COUNT(state, ctx->pattern+3, ctx->pattern[1]);\r
+                RETURN_ON_ERROR(ret);\r
+                DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos);\r
+                if (ret < (Py_ssize_t) ctx->pattern[1])\r
+                    /* didn't match minimum number of times */\r
+                    RETURN_FAILURE;\r
+                /* advance past minimum matches of repeat */\r
+                ctx->count = ret;\r
+                ctx->ptr += ctx->count;\r
+            }\r
+\r
+            if (ctx->pattern[ctx->pattern[0]] == SRE_OP_SUCCESS) {\r
+                /* tail is empty.  we're finished */\r
+                state->ptr = ctx->ptr;\r
+                RETURN_SUCCESS;\r
+\r
+            } else {\r
+                /* general case */\r
+                LASTMARK_SAVE();\r
+                while ((Py_ssize_t)ctx->pattern[2] == SRE_MAXREPEAT\r
+                       || ctx->count <= (Py_ssize_t)ctx->pattern[2]) {\r
+                    state->ptr = ctx->ptr;\r
+                    DO_JUMP(JUMP_MIN_REPEAT_ONE,jump_min_repeat_one,\r
+                            ctx->pattern+ctx->pattern[0]);\r
+                    if (ret) {\r
+                        RETURN_ON_ERROR(ret);\r
+                        RETURN_SUCCESS;\r
+                    }\r
+                    state->ptr = ctx->ptr;\r
+                    ret = SRE_COUNT(state, ctx->pattern+3, 1);\r
+                    RETURN_ON_ERROR(ret);\r
+                    DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos);\r
+                    if (ret == 0)\r
+                        break;\r
+                    assert(ret == 1);\r
+                    ctx->ptr++;\r
+                    ctx->count++;\r
+                    LASTMARK_RESTORE();\r
+                }\r
+            }\r
+            RETURN_FAILURE;\r
+\r
+        case SRE_OP_REPEAT:\r
+            /* create repeat context.  all the hard work is done\r
+               by the UNTIL operator (MAX_UNTIL, MIN_UNTIL) */\r
+            /* <REPEAT> <skip> <1=min> <2=max> item <UNTIL> tail */\r
+            TRACE(("|%p|%p|REPEAT %d %d\n", ctx->pattern, ctx->ptr,\r
+                   ctx->pattern[1], ctx->pattern[2]));\r
+\r
+            /* install new repeat context */\r
+            ctx->u.rep = (SRE_REPEAT*) PyObject_MALLOC(sizeof(*ctx->u.rep));\r
+            if (!ctx->u.rep) {\r
+                PyErr_NoMemory();\r
+                RETURN_FAILURE;\r
+            }\r
+            ctx->u.rep->count = -1;\r
+            ctx->u.rep->pattern = ctx->pattern;\r
+            ctx->u.rep->prev = state->repeat;\r
+            ctx->u.rep->last_ptr = NULL;\r
+            state->repeat = ctx->u.rep;\r
+\r
+            state->ptr = ctx->ptr;\r
+            DO_JUMP(JUMP_REPEAT, jump_repeat, ctx->pattern+ctx->pattern[0]);\r
+            state->repeat = ctx->u.rep->prev;\r
+            PyObject_FREE(ctx->u.rep);\r
+\r
+            if (ret) {\r
+                RETURN_ON_ERROR(ret);\r
+                RETURN_SUCCESS;\r
+            }\r
+            RETURN_FAILURE;\r
+\r
+        case SRE_OP_MAX_UNTIL:\r
+            /* maximizing repeat */\r
+            /* <REPEAT> <skip> <1=min> <2=max> item <MAX_UNTIL> tail */\r
+\r
+            /* FIXME: we probably need to deal with zero-width\r
+               matches in here... */\r
+\r
+            ctx->u.rep = state->repeat;\r
+            if (!ctx->u.rep)\r
+                RETURN_ERROR(SRE_ERROR_STATE);\r
+\r
+            state->ptr = ctx->ptr;\r
+\r
+            ctx->count = ctx->u.rep->count+1;\r
+\r
+            TRACE(("|%p|%p|MAX_UNTIL %" PY_FORMAT_SIZE_T "d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->count));\r
+\r
+            if (ctx->count < (Py_ssize_t) ctx->u.rep->pattern[1]) {\r
+                /* not enough matches */\r
+                ctx->u.rep->count = ctx->count;\r
+                DO_JUMP(JUMP_MAX_UNTIL_1, jump_max_until_1,\r
+                        ctx->u.rep->pattern+3);\r
+                if (ret) {\r
+                    RETURN_ON_ERROR(ret);\r
+                    RETURN_SUCCESS;\r
+                }\r
+                ctx->u.rep->count = ctx->count-1;\r
+                state->ptr = ctx->ptr;\r
+                RETURN_FAILURE;\r
+            }\r
+\r
+            if ((ctx->count < (Py_ssize_t) ctx->u.rep->pattern[2] ||\r
+                ctx->u.rep->pattern[2] == SRE_MAXREPEAT) &&\r
+                state->ptr != ctx->u.rep->last_ptr) {\r
+                /* we may have enough matches, but if we can\r
+                   match another item, do so */\r
+                ctx->u.rep->count = ctx->count;\r
+                LASTMARK_SAVE();\r
+                MARK_PUSH(ctx->lastmark);\r
+                /* zero-width match protection */\r
+                DATA_PUSH(&ctx->u.rep->last_ptr);\r
+                ctx->u.rep->last_ptr = state->ptr;\r
+                DO_JUMP(JUMP_MAX_UNTIL_2, jump_max_until_2,\r
+                        ctx->u.rep->pattern+3);\r
+                DATA_POP(&ctx->u.rep->last_ptr);\r
+                if (ret) {\r
+                    MARK_POP_DISCARD(ctx->lastmark);\r
+                    RETURN_ON_ERROR(ret);\r
+                    RETURN_SUCCESS;\r
+                }\r
+                MARK_POP(ctx->lastmark);\r
+                LASTMARK_RESTORE();\r
+                ctx->u.rep->count = ctx->count-1;\r
+                state->ptr = ctx->ptr;\r
+            }\r
+\r
+            /* cannot match more repeated items here.  make sure the\r
+               tail matches */\r
+            state->repeat = ctx->u.rep->prev;\r
+            DO_JUMP(JUMP_MAX_UNTIL_3, jump_max_until_3, ctx->pattern);\r
+            RETURN_ON_SUCCESS(ret);\r
+            state->repeat = ctx->u.rep;\r
+            state->ptr = ctx->ptr;\r
+            RETURN_FAILURE;\r
+\r
+        case SRE_OP_MIN_UNTIL:\r
+            /* minimizing repeat */\r
+            /* <REPEAT> <skip> <1=min> <2=max> item <MIN_UNTIL> tail */\r
+\r
+            ctx->u.rep = state->repeat;\r
+            if (!ctx->u.rep)\r
+                RETURN_ERROR(SRE_ERROR_STATE);\r
+\r
+            state->ptr = ctx->ptr;\r
+\r
+            ctx->count = ctx->u.rep->count+1;\r
+\r
+            TRACE(("|%p|%p|MIN_UNTIL %" PY_FORMAT_SIZE_T "d %p\n", ctx->pattern,\r
+                   ctx->ptr, ctx->count, ctx->u.rep->pattern));\r
+\r
+            if (ctx->count < (Py_ssize_t) ctx->u.rep->pattern[1]) {\r
+                /* not enough matches */\r
+                ctx->u.rep->count = ctx->count;\r
+                DO_JUMP(JUMP_MIN_UNTIL_1, jump_min_until_1,\r
+                        ctx->u.rep->pattern+3);\r
+                if (ret) {\r
+                    RETURN_ON_ERROR(ret);\r
+                    RETURN_SUCCESS;\r
+                }\r
+                ctx->u.rep->count = ctx->count-1;\r
+                state->ptr = ctx->ptr;\r
+                RETURN_FAILURE;\r
+            }\r
+\r
+            LASTMARK_SAVE();\r
+\r
+            /* see if the tail matches */\r
+            state->repeat = ctx->u.rep->prev;\r
+            DO_JUMP(JUMP_MIN_UNTIL_2, jump_min_until_2, ctx->pattern);\r
+            if (ret) {\r
+                RETURN_ON_ERROR(ret);\r
+                RETURN_SUCCESS;\r
+            }\r
+\r
+            state->repeat = ctx->u.rep;\r
+            state->ptr = ctx->ptr;\r
+\r
+            LASTMARK_RESTORE();\r
+\r
+            if ((ctx->count >= (Py_ssize_t) ctx->u.rep->pattern[2]\r
+                && ctx->u.rep->pattern[2] != SRE_MAXREPEAT) ||\r
+                state->ptr == ctx->u.rep->last_ptr)\r
+                RETURN_FAILURE;\r
+\r
+            ctx->u.rep->count = ctx->count;\r
+            /* zero-width match protection */\r
+            DATA_PUSH(&ctx->u.rep->last_ptr);\r
+            ctx->u.rep->last_ptr = state->ptr;\r
+            DO_JUMP(JUMP_MIN_UNTIL_3,jump_min_until_3,\r
+                    ctx->u.rep->pattern+3);\r
+            DATA_POP(&ctx->u.rep->last_ptr);\r
+            if (ret) {\r
+                RETURN_ON_ERROR(ret);\r
+                RETURN_SUCCESS;\r
+            }\r
+            ctx->u.rep->count = ctx->count-1;\r
+            state->ptr = ctx->ptr;\r
+            RETURN_FAILURE;\r
+\r
+        case SRE_OP_GROUPREF:\r
+            /* match backreference */\r
+            TRACE(("|%p|%p|GROUPREF %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[0]));\r
+            i = ctx->pattern[0];\r
+            {\r
+                Py_ssize_t groupref = i+i;\r
+                if (groupref >= state->lastmark) {\r
+                    RETURN_FAILURE;\r
+                } else {\r
+                    SRE_CHAR* p = (SRE_CHAR*) state->mark[groupref];\r
+                    SRE_CHAR* e = (SRE_CHAR*) state->mark[groupref+1];\r
+                    if (!p || !e || e < p)\r
+                        RETURN_FAILURE;\r
+                    while (p < e) {\r
+                        if (ctx->ptr >= end || *ctx->ptr != *p)\r
+                            RETURN_FAILURE;\r
+                        p++; ctx->ptr++;\r
+                    }\r
+                }\r
+            }\r
+            ctx->pattern++;\r
+            break;\r
+\r
+        case SRE_OP_GROUPREF_IGNORE:\r
+            /* match backreference */\r
+            TRACE(("|%p|%p|GROUPREF_IGNORE %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[0]));\r
+            i = ctx->pattern[0];\r
+            {\r
+                Py_ssize_t groupref = i+i;\r
+                if (groupref >= state->lastmark) {\r
+                    RETURN_FAILURE;\r
+                } else {\r
+                    SRE_CHAR* p = (SRE_CHAR*) state->mark[groupref];\r
+                    SRE_CHAR* e = (SRE_CHAR*) state->mark[groupref+1];\r
+                    if (!p || !e || e < p)\r
+                        RETURN_FAILURE;\r
+                    while (p < e) {\r
+                        if (ctx->ptr >= end ||\r
+                            state->lower(*ctx->ptr) != state->lower(*p))\r
+                            RETURN_FAILURE;\r
+                        p++; ctx->ptr++;\r
+                    }\r
+                }\r
+            }\r
+            ctx->pattern++;\r
+            break;\r
+\r
+        case SRE_OP_GROUPREF_EXISTS:\r
+            TRACE(("|%p|%p|GROUPREF_EXISTS %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[0]));\r
+            /* <GROUPREF_EXISTS> <group> <skip> codeyes <JUMP> codeno ... */\r
+            i = ctx->pattern[0];\r
+            {\r
+                Py_ssize_t groupref = i+i;\r
+                if (groupref >= state->lastmark) {\r
+                    ctx->pattern += ctx->pattern[1];\r
+                    break;\r
+                } else {\r
+                    SRE_CHAR* p = (SRE_CHAR*) state->mark[groupref];\r
+                    SRE_CHAR* e = (SRE_CHAR*) state->mark[groupref+1];\r
+                    if (!p || !e || e < p) {\r
+                        ctx->pattern += ctx->pattern[1];\r
+                        break;\r
+                    }\r
+                }\r
+            }\r
+            ctx->pattern += 2;\r
+            break;\r
+\r
+        case SRE_OP_ASSERT:\r
+            /* assert subpattern */\r
+            /* <ASSERT> <skip> <back> <pattern> */\r
+            TRACE(("|%p|%p|ASSERT %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[1]));\r
+            state->ptr = ctx->ptr - ctx->pattern[1];\r
+            if (state->ptr < state->beginning)\r
+                RETURN_FAILURE;\r
+            DO_JUMP(JUMP_ASSERT, jump_assert, ctx->pattern+2);\r
+            RETURN_ON_FAILURE(ret);\r
+            ctx->pattern += ctx->pattern[0];\r
+            break;\r
+\r
+        case SRE_OP_ASSERT_NOT:\r
+            /* assert not subpattern */\r
+            /* <ASSERT_NOT> <skip> <back> <pattern> */\r
+            TRACE(("|%p|%p|ASSERT_NOT %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[1]));\r
+            state->ptr = ctx->ptr - ctx->pattern[1];\r
+            if (state->ptr >= state->beginning) {\r
+                DO_JUMP(JUMP_ASSERT_NOT, jump_assert_not, ctx->pattern+2);\r
+                if (ret) {\r
+                    RETURN_ON_ERROR(ret);\r
+                    RETURN_FAILURE;\r
+                }\r
+            }\r
+            ctx->pattern += ctx->pattern[0];\r
+            break;\r
+\r
+        case SRE_OP_FAILURE:\r
+            /* immediate failure */\r
+            TRACE(("|%p|%p|FAILURE\n", ctx->pattern, ctx->ptr));\r
+            RETURN_FAILURE;\r
+\r
+        default:\r
+            TRACE(("|%p|%p|UNKNOWN %d\n", ctx->pattern, ctx->ptr,\r
+                   ctx->pattern[-1]));\r
+            RETURN_ERROR(SRE_ERROR_ILLEGAL);\r
+        }\r
+    }\r
+\r
+exit:\r
+    ctx_pos = ctx->last_ctx_pos;\r
+    jump = ctx->jump;\r
+    DATA_POP_DISCARD(ctx);\r
+    if (ctx_pos == -1)\r
+        return ret;\r
+    DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos);\r
+\r
+    switch (jump) {\r
+        case JUMP_MAX_UNTIL_2:\r
+            TRACE(("|%p|%p|JUMP_MAX_UNTIL_2\n", ctx->pattern, ctx->ptr));\r
+            goto jump_max_until_2;\r
+        case JUMP_MAX_UNTIL_3:\r
+            TRACE(("|%p|%p|JUMP_MAX_UNTIL_3\n", ctx->pattern, ctx->ptr));\r
+            goto jump_max_until_3;\r
+        case JUMP_MIN_UNTIL_2:\r
+            TRACE(("|%p|%p|JUMP_MIN_UNTIL_2\n", ctx->pattern, ctx->ptr));\r
+            goto jump_min_until_2;\r
+        case JUMP_MIN_UNTIL_3:\r
+            TRACE(("|%p|%p|JUMP_MIN_UNTIL_3\n", ctx->pattern, ctx->ptr));\r
+            goto jump_min_until_3;\r
+        case JUMP_BRANCH:\r
+            TRACE(("|%p|%p|JUMP_BRANCH\n", ctx->pattern, ctx->ptr));\r
+            goto jump_branch;\r
+        case JUMP_MAX_UNTIL_1:\r
+            TRACE(("|%p|%p|JUMP_MAX_UNTIL_1\n", ctx->pattern, ctx->ptr));\r
+            goto jump_max_until_1;\r
+        case JUMP_MIN_UNTIL_1:\r
+            TRACE(("|%p|%p|JUMP_MIN_UNTIL_1\n", ctx->pattern, ctx->ptr));\r
+            goto jump_min_until_1;\r
+        case JUMP_REPEAT:\r
+            TRACE(("|%p|%p|JUMP_REPEAT\n", ctx->pattern, ctx->ptr));\r
+            goto jump_repeat;\r
+        case JUMP_REPEAT_ONE_1:\r
+            TRACE(("|%p|%p|JUMP_REPEAT_ONE_1\n", ctx->pattern, ctx->ptr));\r
+            goto jump_repeat_one_1;\r
+        case JUMP_REPEAT_ONE_2:\r
+            TRACE(("|%p|%p|JUMP_REPEAT_ONE_2\n", ctx->pattern, ctx->ptr));\r
+            goto jump_repeat_one_2;\r
+        case JUMP_MIN_REPEAT_ONE:\r
+            TRACE(("|%p|%p|JUMP_MIN_REPEAT_ONE\n", ctx->pattern, ctx->ptr));\r
+            goto jump_min_repeat_one;\r
+        case JUMP_ASSERT:\r
+            TRACE(("|%p|%p|JUMP_ASSERT\n", ctx->pattern, ctx->ptr));\r
+            goto jump_assert;\r
+        case JUMP_ASSERT_NOT:\r
+            TRACE(("|%p|%p|JUMP_ASSERT_NOT\n", ctx->pattern, ctx->ptr));\r
+            goto jump_assert_not;\r
+        case JUMP_NONE:\r
+            TRACE(("|%p|%p|RETURN %" PY_FORMAT_SIZE_T "d\n", ctx->pattern,\r
+                   ctx->ptr, ret));\r
+            break;\r
+    }\r
+\r
+    return ret; /* should never get here */\r
+}\r
+\r
+LOCAL(Py_ssize_t)\r
+SRE_SEARCH(SRE_STATE* state, SRE_CODE* pattern)\r
+{\r
+    SRE_CHAR* ptr = (SRE_CHAR *)state->start;\r
+    SRE_CHAR* end = (SRE_CHAR *)state->end;\r
+    Py_ssize_t status = 0;\r
+    Py_ssize_t prefix_len = 0;\r
+    Py_ssize_t prefix_skip = 0;\r
+    SRE_CODE* prefix = NULL;\r
+    SRE_CODE* charset = NULL;\r
+    SRE_CODE* overlap = NULL;\r
+    int flags = 0;\r
+\r
+    if (pattern[0] == SRE_OP_INFO) {\r
+        /* optimization info block */\r
+        /* <INFO> <1=skip> <2=flags> <3=min> <4=max> <5=prefix info>  */\r
+\r
+        flags = pattern[2];\r
+\r
+        if (pattern[3] > 1) {\r
+            /* adjust end point (but make sure we leave at least one\r
+               character in there, so literal search will work) */\r
+            end -= pattern[3]-1;\r
+            if (end <= ptr)\r
+                end = ptr+1;\r
+        }\r
+\r
+        if (flags & SRE_INFO_PREFIX) {\r
+            /* pattern starts with a known prefix */\r
+            /* <length> <skip> <prefix data> <overlap data> */\r
+            prefix_len = pattern[5];\r
+            prefix_skip = pattern[6];\r
+            prefix = pattern + 7;\r
+            overlap = prefix + prefix_len - 1;\r
+        } else if (flags & SRE_INFO_CHARSET)\r
+            /* pattern starts with a character from a known set */\r
+            /* <charset> */\r
+            charset = pattern + 5;\r
+\r
+        pattern += 1 + pattern[1];\r
+    }\r
+\r
+    TRACE(("prefix = %p %" PY_FORMAT_SIZE_T "d %" PY_FORMAT_SIZE_T "d\n",\r
+           prefix, prefix_len, prefix_skip));\r
+    TRACE(("charset = %p\n", charset));\r
+\r
+#if defined(USE_FAST_SEARCH)\r
+    if (prefix_len > 1) {\r
+        /* pattern starts with a known prefix.  use the overlap\r
+           table to skip forward as fast as we possibly can */\r
+        Py_ssize_t i = 0;\r
+        end = (SRE_CHAR *)state->end;\r
+        while (ptr < end) {\r
+            for (;;) {\r
+                if ((SRE_CODE) ptr[0] != prefix[i]) {\r
+                    if (!i)\r
+                        break;\r
+                    else\r
+                        i = overlap[i];\r
+                } else {\r
+                    if (++i == prefix_len) {\r
+                        /* found a potential match */\r
+                        TRACE(("|%p|%p|SEARCH SCAN\n", pattern, ptr));\r
+                        state->start = ptr + 1 - prefix_len;\r
+                        state->ptr = ptr + 1 - prefix_len + prefix_skip;\r
+                        if (flags & SRE_INFO_LITERAL)\r
+                            return 1; /* we got all of it */\r
+                        status = SRE_MATCH(state, pattern + 2*prefix_skip);\r
+                        if (status != 0)\r
+                            return status;\r
+                        /* close but no cigar -- try again */\r
+                        i = overlap[i];\r
+                    }\r
+                    break;\r
+                }\r
+            }\r
+            ptr++;\r
+        }\r
+        return 0;\r
+    }\r
+#endif\r
+\r
+    if (pattern[0] == SRE_OP_LITERAL) {\r
+        /* pattern starts with a literal character.  this is used\r
+           for short prefixes, and if fast search is disabled */\r
+        SRE_CODE chr = pattern[1];\r
+        end = (SRE_CHAR *)state->end;\r
+        for (;;) {\r
+            while (ptr < end && (SRE_CODE) ptr[0] != chr)\r
+                ptr++;\r
+            if (ptr >= end)\r
+                return 0;\r
+            TRACE(("|%p|%p|SEARCH LITERAL\n", pattern, ptr));\r
+            state->start = ptr;\r
+            state->ptr = ++ptr;\r
+            if (flags & SRE_INFO_LITERAL)\r
+                return 1; /* we got all of it */\r
+            status = SRE_MATCH(state, pattern + 2);\r
+            if (status != 0)\r
+                break;\r
+        }\r
+    } else if (charset) {\r
+        /* pattern starts with a character from a known set */\r
+        end = (SRE_CHAR *)state->end;\r
+        for (;;) {\r
+            while (ptr < end && !SRE_CHARSET(charset, ptr[0]))\r
+                ptr++;\r
+            if (ptr >= end)\r
+                return 0;\r
+            TRACE(("|%p|%p|SEARCH CHARSET\n", pattern, ptr));\r
+            state->start = ptr;\r
+            state->ptr = ptr;\r
+            status = SRE_MATCH(state, pattern);\r
+            if (status != 0)\r
+                break;\r
+            ptr++;\r
+        }\r
+    } else\r
+        /* general case */\r
+        while (ptr <= end) {\r
+            TRACE(("|%p|%p|SEARCH\n", pattern, ptr));\r
+            state->start = state->ptr = ptr++;\r
+            status = SRE_MATCH(state, pattern);\r
+            if (status != 0)\r
+                break;\r
+        }\r
+\r
+    return status;\r
+}\r
+\r
+LOCAL(int)\r
+SRE_LITERAL_TEMPLATE(SRE_CHAR* ptr, Py_ssize_t len)\r
+{\r
+    /* check if given string is a literal template (i.e. no escapes) */\r
+    while (len-- > 0)\r
+        if (*ptr++ == '\\')\r
+            return 0;\r
+    return 1;\r
+}\r
+\r
+#if !defined(SRE_RECURSIVE)\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* factories and destructors */\r
+\r
+/* see sre.h for object declarations */\r
+static PyObject*pattern_new_match(PatternObject*, SRE_STATE*, int);\r
+static PyObject*pattern_scanner(PatternObject*, PyObject*);\r
+\r
+static PyObject *\r
+sre_codesize(PyObject* self, PyObject *unused)\r
+{\r
+    return PyInt_FromSize_t(sizeof(SRE_CODE));\r
+}\r
+\r
+static PyObject *\r
+sre_getlower(PyObject* self, PyObject* args)\r
+{\r
+    int character, flags;\r
+    if (!PyArg_ParseTuple(args, "ii", &character, &flags))\r
+        return NULL;\r
+    if (flags & SRE_FLAG_LOCALE)\r
+        return Py_BuildValue("i", sre_lower_locale(character));\r
+    if (flags & SRE_FLAG_UNICODE)\r
+#if defined(HAVE_UNICODE)\r
+        return Py_BuildValue("i", sre_lower_unicode(character));\r
+#else\r
+        return Py_BuildValue("i", sre_lower_locale(character));\r
+#endif\r
+    return Py_BuildValue("i", sre_lower(character));\r
+}\r
+\r
+LOCAL(void)\r
+state_reset(SRE_STATE* state)\r
+{\r
+    /* FIXME: dynamic! */\r
+    /*memset(state->mark, 0, sizeof(*state->mark) * SRE_MARK_SIZE);*/\r
+\r
+    state->lastmark = -1;\r
+    state->lastindex = -1;\r
+\r
+    state->repeat = NULL;\r
+\r
+    data_stack_dealloc(state);\r
+}\r
+\r
+static void*\r
+getstring(PyObject* string, Py_ssize_t* p_length, int* p_charsize)\r
+{\r
+    /* given a python object, return a data pointer, a length (in\r
+       characters), and a character size.  return NULL if the object\r
+       is not a string (or not compatible) */\r
+\r
+    PyBufferProcs *buffer;\r
+    Py_ssize_t size, bytes;\r
+    int charsize;\r
+    void* ptr;\r
+\r
+#if defined(HAVE_UNICODE)\r
+    if (PyUnicode_Check(string)) {\r
+        /* unicode strings doesn't always support the buffer interface */\r
+        ptr = (void*) PyUnicode_AS_DATA(string);\r
+        /* bytes = PyUnicode_GET_DATA_SIZE(string); */\r
+        size = PyUnicode_GET_SIZE(string);\r
+        charsize = sizeof(Py_UNICODE);\r
+\r
+    } else {\r
+#endif\r
+\r
+    /* get pointer to string buffer */\r
+    buffer = Py_TYPE(string)->tp_as_buffer;\r
+    if (!buffer || !buffer->bf_getreadbuffer || !buffer->bf_getsegcount ||\r
+        buffer->bf_getsegcount(string, NULL) != 1) {\r
+        PyErr_SetString(PyExc_TypeError, "expected string or buffer");\r
+        return NULL;\r
+    }\r
+\r
+    /* determine buffer size */\r
+    bytes = buffer->bf_getreadbuffer(string, 0, &ptr);\r
+    if (bytes < 0) {\r
+        PyErr_SetString(PyExc_TypeError, "buffer has negative size");\r
+        return NULL;\r
+    }\r
+\r
+    /* determine character size */\r
+#if PY_VERSION_HEX >= 0x01060000\r
+    size = PyObject_Size(string);\r
+#else\r
+    size = PyObject_Length(string);\r
+#endif\r
+\r
+    if (PyString_Check(string) || bytes == size)\r
+        charsize = 1;\r
+#if defined(HAVE_UNICODE)\r
+    else if (bytes == (Py_ssize_t) (size * sizeof(Py_UNICODE)))\r
+        charsize = sizeof(Py_UNICODE);\r
+#endif\r
+    else {\r
+        PyErr_SetString(PyExc_TypeError, "buffer size mismatch");\r
+        return NULL;\r
+    }\r
+\r
+#if defined(HAVE_UNICODE)\r
+    }\r
+#endif\r
+\r
+    *p_length = size;\r
+    *p_charsize = charsize;\r
+\r
+    return ptr;\r
+}\r
+\r
+LOCAL(PyObject*)\r
+state_init(SRE_STATE* state, PatternObject* pattern, PyObject* string,\r
+           Py_ssize_t start, Py_ssize_t end)\r
+{\r
+    /* prepare state object */\r
+\r
+    Py_ssize_t length;\r
+    int charsize;\r
+    void* ptr;\r
+\r
+    memset(state, 0, sizeof(SRE_STATE));\r
+\r
+    state->lastmark = -1;\r
+    state->lastindex = -1;\r
+\r
+    ptr = getstring(string, &length, &charsize);\r
+    if (!ptr)\r
+        return NULL;\r
+\r
+    /* adjust boundaries */\r
+    if (start < 0)\r
+        start = 0;\r
+    else if (start > length)\r
+        start = length;\r
+\r
+    if (end < 0)\r
+        end = 0;\r
+    else if (end > length)\r
+        end = length;\r
+\r
+    state->charsize = charsize;\r
+\r
+    state->beginning = ptr;\r
+\r
+    state->start = (void*) ((char*) ptr + start * state->charsize);\r
+    state->end = (void*) ((char*) ptr + end * state->charsize);\r
+\r
+    Py_INCREF(string);\r
+    state->string = string;\r
+    state->pos = start;\r
+    state->endpos = end;\r
+\r
+    if (pattern->flags & SRE_FLAG_LOCALE)\r
+        state->lower = sre_lower_locale;\r
+    else if (pattern->flags & SRE_FLAG_UNICODE)\r
+#if defined(HAVE_UNICODE)\r
+        state->lower = sre_lower_unicode;\r
+#else\r
+        state->lower = sre_lower_locale;\r
+#endif\r
+    else\r
+        state->lower = sre_lower;\r
+\r
+    return string;\r
+}\r
+\r
+LOCAL(void)\r
+state_fini(SRE_STATE* state)\r
+{\r
+    Py_XDECREF(state->string);\r
+    data_stack_dealloc(state);\r
+}\r
+\r
+/* calculate offset from start of string */\r
+#define STATE_OFFSET(state, member)\\r
+    (((char*)(member) - (char*)(state)->beginning) / (state)->charsize)\r
+\r
+LOCAL(PyObject*)\r
+state_getslice(SRE_STATE* state, Py_ssize_t index, PyObject* string, int empty)\r
+{\r
+    Py_ssize_t i, j;\r
+\r
+    index = (index - 1) * 2;\r
+\r
+    if (string == Py_None || index >= state->lastmark || !state->mark[index] || !state->mark[index+1]) {\r
+        if (empty)\r
+            /* want empty string */\r
+            i = j = 0;\r
+        else {\r
+            Py_INCREF(Py_None);\r
+            return Py_None;\r
+        }\r
+    } else {\r
+        i = STATE_OFFSET(state, state->mark[index]);\r
+        j = STATE_OFFSET(state, state->mark[index+1]);\r
+    }\r
+\r
+    return PySequence_GetSlice(string, i, j);\r
+}\r
+\r
+static void\r
+pattern_error(int status)\r
+{\r
+    switch (status) {\r
+    case SRE_ERROR_RECURSION_LIMIT:\r
+        PyErr_SetString(\r
+            PyExc_RuntimeError,\r
+            "maximum recursion limit exceeded"\r
+            );\r
+        break;\r
+    case SRE_ERROR_MEMORY:\r
+        PyErr_NoMemory();\r
+        break;\r
+    case SRE_ERROR_INTERRUPTED:\r
+    /* An exception has already been raised, so let it fly */\r
+        break;\r
+    default:\r
+        /* other error codes indicate compiler/engine bugs */\r
+        PyErr_SetString(\r
+            PyExc_RuntimeError,\r
+            "internal error in regular expression engine"\r
+            );\r
+    }\r
+}\r
+\r
+static void\r
+pattern_dealloc(PatternObject* self)\r
+{\r
+    if (self->weakreflist != NULL)\r
+        PyObject_ClearWeakRefs((PyObject *) self);\r
+    Py_XDECREF(self->pattern);\r
+    Py_XDECREF(self->groupindex);\r
+    Py_XDECREF(self->indexgroup);\r
+    PyObject_DEL(self);\r
+}\r
+\r
+static int\r
+check_args_size(const char *name, PyObject* args, PyObject* kw, int n)\r
+{\r
+    Py_ssize_t m = PyTuple_GET_SIZE(args) + (kw ? PyDict_Size(kw) : 0);\r
+    if (m <= n)\r
+        return 1;\r
+    PyErr_Format(PyExc_TypeError,\r
+                 "%s() takes at most %d positional arguments (%zd given)",\r
+                 name, n, m);\r
+    return 0;\r
+}\r
+\r
+static PyObject*\r
+fix_string_param(PyObject *string, PyObject *string2, const char *oldname)\r
+{\r
+    if (string2 != NULL) {\r
+        char buf[100];\r
+        if (string != NULL) {\r
+            PyErr_Format(PyExc_TypeError,\r
+                         "Argument given by name ('%s') and position (1)",\r
+                         oldname);\r
+            return NULL;\r
+        }\r
+        sprintf(buf, "The '%s' keyword parameter name is deprecated.  "\r
+                     "Use 'string' instead.", oldname);\r
+        if (PyErr_Warn(PyExc_DeprecationWarning, buf) < 0)\r
+            return NULL;\r
+        return string2;\r
+    }\r
+    if (string == NULL) {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "Required argument 'string' (pos 1) not found");\r
+        return NULL;\r
+    }\r
+    return string;\r
+}\r
+\r
+static PyObject*\r
+pattern_match(PatternObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    SRE_STATE state;\r
+    int status;\r
+\r
+    PyObject *string = NULL, *string2 = NULL;\r
+    Py_ssize_t start = 0;\r
+    Py_ssize_t end = PY_SSIZE_T_MAX;\r
+    static char* kwlist[] = { "string", "pos", "endpos", "pattern", NULL };\r
+    if (!check_args_size("match", args, kw, 3))\r
+        return NULL;\r
+\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "|OnnO:match", kwlist,\r
+                                     &string, &start, &end, &string2))\r
+        return NULL;\r
+\r
+    string = fix_string_param(string, string2, "pattern");\r
+    if (!string)\r
+        return NULL;\r
+\r
+    string = state_init(&state, self, string, start, end);\r
+    if (!string)\r
+        return NULL;\r
+\r
+    state.ptr = state.start;\r
+\r
+    TRACE(("|%p|%p|MATCH\n", PatternObject_GetCode(self), state.ptr));\r
+\r
+    if (state.charsize == 1) {\r
+        status = sre_match(&state, PatternObject_GetCode(self));\r
+    } else {\r
+#if defined(HAVE_UNICODE)\r
+        status = sre_umatch(&state, PatternObject_GetCode(self));\r
+#endif\r
+    }\r
+\r
+    TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));\r
+    if (PyErr_Occurred())\r
+        return NULL;\r
+\r
+    state_fini(&state);\r
+\r
+    return pattern_new_match(self, &state, status);\r
+}\r
+\r
+static PyObject*\r
+pattern_search(PatternObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    SRE_STATE state;\r
+    int status;\r
+\r
+    PyObject *string = NULL, *string2 = NULL;\r
+    Py_ssize_t start = 0;\r
+    Py_ssize_t end = PY_SSIZE_T_MAX;\r
+    static char* kwlist[] = { "string", "pos", "endpos", "pattern", NULL };\r
+    if (!check_args_size("search", args, kw, 3))\r
+        return NULL;\r
+\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "|OnnO:search", kwlist,\r
+                                     &string, &start, &end, &string2))\r
+        return NULL;\r
+\r
+    string = fix_string_param(string, string2, "pattern");\r
+    if (!string)\r
+        return NULL;\r
+\r
+    string = state_init(&state, self, string, start, end);\r
+    if (!string)\r
+        return NULL;\r
+\r
+    TRACE(("|%p|%p|SEARCH\n", PatternObject_GetCode(self), state.ptr));\r
+\r
+    if (state.charsize == 1) {\r
+        status = sre_search(&state, PatternObject_GetCode(self));\r
+    } else {\r
+#if defined(HAVE_UNICODE)\r
+        status = sre_usearch(&state, PatternObject_GetCode(self));\r
+#endif\r
+    }\r
+\r
+    TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));\r
+\r
+    state_fini(&state);\r
+\r
+    if (PyErr_Occurred())\r
+        return NULL;\r
+\r
+    return pattern_new_match(self, &state, status);\r
+}\r
+\r
+static PyObject*\r
+call(char* module, char* function, PyObject* args)\r
+{\r
+    PyObject* name;\r
+    PyObject* mod;\r
+    PyObject* func;\r
+    PyObject* result;\r
+\r
+    if (!args)\r
+        return NULL;\r
+    name = PyString_FromString(module);\r
+    if (!name)\r
+        return NULL;\r
+    mod = PyImport_Import(name);\r
+    Py_DECREF(name);\r
+    if (!mod)\r
+        return NULL;\r
+    func = PyObject_GetAttrString(mod, function);\r
+    Py_DECREF(mod);\r
+    if (!func)\r
+        return NULL;\r
+    result = PyObject_CallObject(func, args);\r
+    Py_DECREF(func);\r
+    Py_DECREF(args);\r
+    return result;\r
+}\r
+\r
+#ifdef USE_BUILTIN_COPY\r
+static int\r
+deepcopy(PyObject** object, PyObject* memo)\r
+{\r
+    PyObject* copy;\r
+\r
+    copy = call(\r
+        "copy", "deepcopy",\r
+        PyTuple_Pack(2, *object, memo)\r
+        );\r
+    if (!copy)\r
+        return 0;\r
+\r
+    Py_DECREF(*object);\r
+    *object = copy;\r
+\r
+    return 1; /* success */\r
+}\r
+#endif\r
+\r
+static PyObject*\r
+join_list(PyObject* list, PyObject* string)\r
+{\r
+    /* join list elements */\r
+\r
+    PyObject* joiner;\r
+#if PY_VERSION_HEX >= 0x01060000\r
+    PyObject* function;\r
+    PyObject* args;\r
+#endif\r
+    PyObject* result;\r
+\r
+    joiner = PySequence_GetSlice(string, 0, 0);\r
+    if (!joiner)\r
+        return NULL;\r
+\r
+    if (PyList_GET_SIZE(list) == 0) {\r
+        Py_DECREF(list);\r
+        return joiner;\r
+    }\r
+\r
+#if PY_VERSION_HEX >= 0x01060000\r
+    function = PyObject_GetAttrString(joiner, "join");\r
+    if (!function) {\r
+        Py_DECREF(joiner);\r
+        return NULL;\r
+    }\r
+    args = PyTuple_New(1);\r
+    if (!args) {\r
+        Py_DECREF(function);\r
+        Py_DECREF(joiner);\r
+        return NULL;\r
+    }\r
+    PyTuple_SET_ITEM(args, 0, list);\r
+    result = PyObject_CallObject(function, args);\r
+    Py_DECREF(args); /* also removes list */\r
+    Py_DECREF(function);\r
+#else\r
+    result = call(\r
+        "string", "join",\r
+        PyTuple_Pack(2, list, joiner)\r
+        );\r
+#endif\r
+    Py_DECREF(joiner);\r
+\r
+    return result;\r
+}\r
+\r
+static PyObject*\r
+pattern_findall(PatternObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    SRE_STATE state;\r
+    PyObject* list;\r
+    int status;\r
+    Py_ssize_t i, b, e;\r
+\r
+    PyObject *string = NULL, *string2 = NULL;\r
+    Py_ssize_t start = 0;\r
+    Py_ssize_t end = PY_SSIZE_T_MAX;\r
+    static char* kwlist[] = { "string", "pos", "endpos", "source", NULL };\r
+    if (!check_args_size("findall", args, kw, 3))\r
+        return NULL;\r
+\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "|OnnO:findall", kwlist,\r
+                                     &string, &start, &end, &string2))\r
+        return NULL;\r
+\r
+    string = fix_string_param(string, string2, "source");\r
+    if (!string)\r
+        return NULL;\r
+\r
+    string = state_init(&state, self, string, start, end);\r
+    if (!string)\r
+        return NULL;\r
+\r
+    list = PyList_New(0);\r
+    if (!list) {\r
+        state_fini(&state);\r
+        return NULL;\r
+    }\r
+\r
+    while (state.start <= state.end) {\r
+\r
+        PyObject* item;\r
+\r
+        state_reset(&state);\r
+\r
+        state.ptr = state.start;\r
+\r
+        if (state.charsize == 1) {\r
+            status = sre_search(&state, PatternObject_GetCode(self));\r
+        } else {\r
+#if defined(HAVE_UNICODE)\r
+            status = sre_usearch(&state, PatternObject_GetCode(self));\r
+#endif\r
+        }\r
+\r
+       if (PyErr_Occurred())\r
+           goto error;\r
+\r
+        if (status <= 0) {\r
+            if (status == 0)\r
+                break;\r
+            pattern_error(status);\r
+            goto error;\r
+        }\r
+\r
+        /* don't bother to build a match object */\r
+        switch (self->groups) {\r
+        case 0:\r
+            b = STATE_OFFSET(&state, state.start);\r
+            e = STATE_OFFSET(&state, state.ptr);\r
+            item = PySequence_GetSlice(string, b, e);\r
+            if (!item)\r
+                goto error;\r
+            break;\r
+        case 1:\r
+            item = state_getslice(&state, 1, string, 1);\r
+            if (!item)\r
+                goto error;\r
+            break;\r
+        default:\r
+            item = PyTuple_New(self->groups);\r
+            if (!item)\r
+                goto error;\r
+            for (i = 0; i < self->groups; i++) {\r
+                PyObject* o = state_getslice(&state, i+1, string, 1);\r
+                if (!o) {\r
+                    Py_DECREF(item);\r
+                    goto error;\r
+                }\r
+                PyTuple_SET_ITEM(item, i, o);\r
+            }\r
+            break;\r
+        }\r
+\r
+        status = PyList_Append(list, item);\r
+        Py_DECREF(item);\r
+        if (status < 0)\r
+            goto error;\r
+\r
+        if (state.ptr == state.start)\r
+            state.start = (void*) ((char*) state.ptr + state.charsize);\r
+        else\r
+            state.start = state.ptr;\r
+\r
+    }\r
+\r
+    state_fini(&state);\r
+    return list;\r
+\r
+error:\r
+    Py_DECREF(list);\r
+    state_fini(&state);\r
+    return NULL;\r
+\r
+}\r
+\r
+#if PY_VERSION_HEX >= 0x02020000\r
+static PyObject*\r
+pattern_finditer(PatternObject* pattern, PyObject* args)\r
+{\r
+    PyObject* scanner;\r
+    PyObject* search;\r
+    PyObject* iterator;\r
+\r
+    scanner = pattern_scanner(pattern, args);\r
+    if (!scanner)\r
+        return NULL;\r
+\r
+    search = PyObject_GetAttrString(scanner, "search");\r
+    Py_DECREF(scanner);\r
+    if (!search)\r
+        return NULL;\r
+\r
+    iterator = PyCallIter_New(search, Py_None);\r
+    Py_DECREF(search);\r
+\r
+    return iterator;\r
+}\r
+#endif\r
+\r
+static PyObject*\r
+pattern_split(PatternObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    SRE_STATE state;\r
+    PyObject* list;\r
+    PyObject* item;\r
+    int status;\r
+    Py_ssize_t n;\r
+    Py_ssize_t i;\r
+    void* last;\r
+\r
+    PyObject *string = NULL, *string2 = NULL;\r
+    Py_ssize_t maxsplit = 0;\r
+    static char* kwlist[] = { "string", "maxsplit", "source", NULL };\r
+    if (!check_args_size("split", args, kw, 2))\r
+        return NULL;\r
+\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "|OnO:split", kwlist,\r
+                                     &string, &maxsplit, &string2))\r
+        return NULL;\r
+\r
+    string = fix_string_param(string, string2, "source");\r
+    if (!string)\r
+        return NULL;\r
+\r
+    string = state_init(&state, self, string, 0, PY_SSIZE_T_MAX);\r
+    if (!string)\r
+        return NULL;\r
+\r
+    list = PyList_New(0);\r
+    if (!list) {\r
+        state_fini(&state);\r
+        return NULL;\r
+    }\r
+\r
+    n = 0;\r
+    last = state.start;\r
+\r
+    while (!maxsplit || n < maxsplit) {\r
+\r
+        state_reset(&state);\r
+\r
+        state.ptr = state.start;\r
+\r
+        if (state.charsize == 1) {\r
+            status = sre_search(&state, PatternObject_GetCode(self));\r
+        } else {\r
+#if defined(HAVE_UNICODE)\r
+            status = sre_usearch(&state, PatternObject_GetCode(self));\r
+#endif\r
+        }\r
+\r
+       if (PyErr_Occurred())\r
+           goto error;\r
+\r
+        if (status <= 0) {\r
+            if (status == 0)\r
+                break;\r
+            pattern_error(status);\r
+            goto error;\r
+        }\r
+\r
+        if (state.start == state.ptr) {\r
+            if (last == state.end)\r
+                break;\r
+            /* skip one character */\r
+            state.start = (void*) ((char*) state.ptr + state.charsize);\r
+            continue;\r
+        }\r
+\r
+        /* get segment before this match */\r
+        item = PySequence_GetSlice(\r
+            string, STATE_OFFSET(&state, last),\r
+            STATE_OFFSET(&state, state.start)\r
+            );\r
+        if (!item)\r
+            goto error;\r
+        status = PyList_Append(list, item);\r
+        Py_DECREF(item);\r
+        if (status < 0)\r
+            goto error;\r
+\r
+        /* add groups (if any) */\r
+        for (i = 0; i < self->groups; i++) {\r
+            item = state_getslice(&state, i+1, string, 0);\r
+            if (!item)\r
+                goto error;\r
+            status = PyList_Append(list, item);\r
+            Py_DECREF(item);\r
+            if (status < 0)\r
+                goto error;\r
+        }\r
+\r
+        n = n + 1;\r
+\r
+        last = state.start = state.ptr;\r
+\r
+    }\r
+\r
+    /* get segment following last match (even if empty) */\r
+    item = PySequence_GetSlice(\r
+        string, STATE_OFFSET(&state, last), state.endpos\r
+        );\r
+    if (!item)\r
+        goto error;\r
+    status = PyList_Append(list, item);\r
+    Py_DECREF(item);\r
+    if (status < 0)\r
+        goto error;\r
+\r
+    state_fini(&state);\r
+    return list;\r
+\r
+error:\r
+    Py_DECREF(list);\r
+    state_fini(&state);\r
+    return NULL;\r
+\r
+}\r
+\r
+static PyObject*\r
+pattern_subx(PatternObject* self, PyObject* ptemplate, PyObject* string,\r
+             Py_ssize_t count, Py_ssize_t subn)\r
+{\r
+    SRE_STATE state;\r
+    PyObject* list;\r
+    PyObject* item;\r
+    PyObject* filter;\r
+    PyObject* args;\r
+    PyObject* match;\r
+    void* ptr;\r
+    int status;\r
+    Py_ssize_t n;\r
+    Py_ssize_t i, b, e;\r
+    int bint;\r
+    int filter_is_callable;\r
+\r
+    if (PyCallable_Check(ptemplate)) {\r
+        /* sub/subn takes either a function or a template */\r
+        filter = ptemplate;\r
+        Py_INCREF(filter);\r
+        filter_is_callable = 1;\r
+    } else {\r
+        /* if not callable, check if it's a literal string */\r
+        int literal;\r
+        ptr = getstring(ptemplate, &n, &bint);\r
+        b = bint;\r
+        if (ptr) {\r
+            if (b == 1) {\r
+                   literal = sre_literal_template((unsigned char *)ptr, n);\r
+            } else {\r
+#if defined(HAVE_UNICODE)\r
+                   literal = sre_uliteral_template((Py_UNICODE *)ptr, n);\r
+#endif\r
+            }\r
+        } else {\r
+            PyErr_Clear();\r
+            literal = 0;\r
+        }\r
+        if (literal) {\r
+            filter = ptemplate;\r
+            Py_INCREF(filter);\r
+            filter_is_callable = 0;\r
+        } else {\r
+            /* not a literal; hand it over to the template compiler */\r
+            filter = call(\r
+                SRE_PY_MODULE, "_subx",\r
+                PyTuple_Pack(2, self, ptemplate)\r
+                );\r
+            if (!filter)\r
+                return NULL;\r
+            filter_is_callable = PyCallable_Check(filter);\r
+        }\r
+    }\r
+\r
+    string = state_init(&state, self, string, 0, PY_SSIZE_T_MAX);\r
+    if (!string) {\r
+        Py_DECREF(filter);\r
+        return NULL;\r
+    }\r
+\r
+    list = PyList_New(0);\r
+    if (!list) {\r
+        Py_DECREF(filter);\r
+        state_fini(&state);\r
+        return NULL;\r
+    }\r
+\r
+    n = i = 0;\r
+\r
+    while (!count || n < count) {\r
+\r
+        state_reset(&state);\r
+\r
+        state.ptr = state.start;\r
+\r
+        if (state.charsize == 1) {\r
+            status = sre_search(&state, PatternObject_GetCode(self));\r
+        } else {\r
+#if defined(HAVE_UNICODE)\r
+            status = sre_usearch(&state, PatternObject_GetCode(self));\r
+#endif\r
+        }\r
+\r
+       if (PyErr_Occurred())\r
+           goto error;\r
+\r
+        if (status <= 0) {\r
+            if (status == 0)\r
+                break;\r
+            pattern_error(status);\r
+            goto error;\r
+        }\r
+\r
+        b = STATE_OFFSET(&state, state.start);\r
+        e = STATE_OFFSET(&state, state.ptr);\r
+\r
+        if (i < b) {\r
+            /* get segment before this match */\r
+            item = PySequence_GetSlice(string, i, b);\r
+            if (!item)\r
+                goto error;\r
+            status = PyList_Append(list, item);\r
+            Py_DECREF(item);\r
+            if (status < 0)\r
+                goto error;\r
+\r
+        } else if (i == b && i == e && n > 0)\r
+            /* ignore empty match on latest position */\r
+            goto next;\r
+\r
+        if (filter_is_callable) {\r
+            /* pass match object through filter */\r
+            match = pattern_new_match(self, &state, 1);\r
+            if (!match)\r
+                goto error;\r
+            args = PyTuple_Pack(1, match);\r
+            if (!args) {\r
+                Py_DECREF(match);\r
+                goto error;\r
+            }\r
+            item = PyObject_CallObject(filter, args);\r
+            Py_DECREF(args);\r
+            Py_DECREF(match);\r
+            if (!item)\r
+                goto error;\r
+        } else {\r
+            /* filter is literal string */\r
+            item = filter;\r
+            Py_INCREF(item);\r
+        }\r
+\r
+        /* add to list */\r
+        if (item != Py_None) {\r
+            status = PyList_Append(list, item);\r
+            Py_DECREF(item);\r
+            if (status < 0)\r
+                goto error;\r
+        }\r
+\r
+        i = e;\r
+        n = n + 1;\r
+\r
+next:\r
+        /* move on */\r
+        if (state.ptr == state.start)\r
+            state.start = (void*) ((char*) state.ptr + state.charsize);\r
+        else\r
+            state.start = state.ptr;\r
+\r
+    }\r
+\r
+    /* get segment following last match */\r
+    if (i < state.endpos) {\r
+        item = PySequence_GetSlice(string, i, state.endpos);\r
+        if (!item)\r
+            goto error;\r
+        status = PyList_Append(list, item);\r
+        Py_DECREF(item);\r
+        if (status < 0)\r
+            goto error;\r
+    }\r
+\r
+    state_fini(&state);\r
+\r
+    Py_DECREF(filter);\r
+\r
+    /* convert list to single string (also removes list) */\r
+    item = join_list(list, string);\r
+\r
+    if (!item)\r
+        return NULL;\r
+\r
+    if (subn)\r
+        return Py_BuildValue("Nn", item, n);\r
+\r
+    return item;\r
+\r
+error:\r
+    Py_DECREF(list);\r
+    state_fini(&state);\r
+    Py_DECREF(filter);\r
+    return NULL;\r
+\r
+}\r
+\r
+static PyObject*\r
+pattern_sub(PatternObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    PyObject* ptemplate;\r
+    PyObject* string;\r
+    Py_ssize_t count = 0;\r
+    static char* kwlist[] = { "repl", "string", "count", NULL };\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|n:sub", kwlist,\r
+                                     &ptemplate, &string, &count))\r
+        return NULL;\r
+\r
+    return pattern_subx(self, ptemplate, string, count, 0);\r
+}\r
+\r
+static PyObject*\r
+pattern_subn(PatternObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    PyObject* ptemplate;\r
+    PyObject* string;\r
+    Py_ssize_t count = 0;\r
+    static char* kwlist[] = { "repl", "string", "count", NULL };\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|n:subn", kwlist,\r
+                                     &ptemplate, &string, &count))\r
+        return NULL;\r
+\r
+    return pattern_subx(self, ptemplate, string, count, 1);\r
+}\r
+\r
+static PyObject*\r
+pattern_copy(PatternObject* self, PyObject *unused)\r
+{\r
+#ifdef USE_BUILTIN_COPY\r
+    PatternObject* copy;\r
+    int offset;\r
+\r
+    copy = PyObject_NEW_VAR(PatternObject, &Pattern_Type, self->codesize);\r
+    if (!copy)\r
+        return NULL;\r
+\r
+    offset = offsetof(PatternObject, groups);\r
+\r
+    Py_XINCREF(self->groupindex);\r
+    Py_XINCREF(self->indexgroup);\r
+    Py_XINCREF(self->pattern);\r
+\r
+    memcpy((char*) copy + offset, (char*) self + offset,\r
+           sizeof(PatternObject) + self->codesize * sizeof(SRE_CODE) - offset);\r
+    copy->weakreflist = NULL;\r
+\r
+    return (PyObject*) copy;\r
+#else\r
+    PyErr_SetString(PyExc_TypeError, "cannot copy this pattern object");\r
+    return NULL;\r
+#endif\r
+}\r
+\r
+static PyObject*\r
+pattern_deepcopy(PatternObject* self, PyObject* memo)\r
+{\r
+#ifdef USE_BUILTIN_COPY\r
+    PatternObject* copy;\r
+\r
+    copy = (PatternObject*) pattern_copy(self);\r
+    if (!copy)\r
+        return NULL;\r
+\r
+    if (!deepcopy(&copy->groupindex, memo) ||\r
+        !deepcopy(&copy->indexgroup, memo) ||\r
+        !deepcopy(&copy->pattern, memo)) {\r
+        Py_DECREF(copy);\r
+        return NULL;\r
+    }\r
+\r
+#else\r
+    PyErr_SetString(PyExc_TypeError, "cannot deepcopy this pattern object");\r
+    return NULL;\r
+#endif\r
+}\r
+\r
+PyDoc_STRVAR(pattern_match_doc,\r
+"match(string[, pos[, endpos]]) --> match object or None.\n\\r
+    Matches zero or more characters at the beginning of the string");\r
+\r
+PyDoc_STRVAR(pattern_search_doc,\r
+"search(string[, pos[, endpos]]) --> match object or None.\n\\r
+    Scan through string looking for a match, and return a corresponding\n\\r
+    match object instance. Return None if no position in the string matches.");\r
+\r
+PyDoc_STRVAR(pattern_split_doc,\r
+"split(string[, maxsplit = 0])  --> list.\n\\r
+    Split string by the occurrences of pattern.");\r
+\r
+PyDoc_STRVAR(pattern_findall_doc,\r
+"findall(string[, pos[, endpos]]) --> list.\n\\r
+   Return a list of all non-overlapping matches of pattern in string.");\r
+\r
+PyDoc_STRVAR(pattern_finditer_doc,\r
+"finditer(string[, pos[, endpos]]) --> iterator.\n\\r
+    Return an iterator over all non-overlapping matches for the \n\\r
+    RE pattern in string. For each match, the iterator returns a\n\\r
+    match object.");\r
+\r
+PyDoc_STRVAR(pattern_sub_doc,\r
+"sub(repl, string[, count = 0]) --> newstring\n\\r
+    Return the string obtained by replacing the leftmost non-overlapping\n\\r
+    occurrences of pattern in string by the replacement repl.");\r
+\r
+PyDoc_STRVAR(pattern_subn_doc,\r
+"subn(repl, string[, count = 0]) --> (newstring, number of subs)\n\\r
+    Return the tuple (new_string, number_of_subs_made) found by replacing\n\\r
+    the leftmost non-overlapping occurrences of pattern with the\n\\r
+    replacement repl.");\r
+\r
+PyDoc_STRVAR(pattern_doc, "Compiled regular expression objects");\r
+\r
+static PyMethodDef pattern_methods[] = {\r
+    {"match", (PyCFunction) pattern_match, METH_VARARGS|METH_KEYWORDS,\r
+       pattern_match_doc},\r
+    {"search", (PyCFunction) pattern_search, METH_VARARGS|METH_KEYWORDS,\r
+       pattern_search_doc},\r
+    {"sub", (PyCFunction) pattern_sub, METH_VARARGS|METH_KEYWORDS,\r
+       pattern_sub_doc},\r
+    {"subn", (PyCFunction) pattern_subn, METH_VARARGS|METH_KEYWORDS,\r
+       pattern_subn_doc},\r
+    {"split", (PyCFunction) pattern_split, METH_VARARGS|METH_KEYWORDS,\r
+       pattern_split_doc},\r
+    {"findall", (PyCFunction) pattern_findall, METH_VARARGS|METH_KEYWORDS,\r
+       pattern_findall_doc},\r
+#if PY_VERSION_HEX >= 0x02020000\r
+    {"finditer", (PyCFunction) pattern_finditer, METH_VARARGS,\r
+       pattern_finditer_doc},\r
+#endif\r
+    {"scanner", (PyCFunction) pattern_scanner, METH_VARARGS},\r
+    {"__copy__", (PyCFunction) pattern_copy, METH_NOARGS},\r
+    {"__deepcopy__", (PyCFunction) pattern_deepcopy, METH_O},\r
+    {NULL, NULL}\r
+};\r
+\r
+#define PAT_OFF(x) offsetof(PatternObject, x)\r
+static PyMemberDef pattern_members[] = {\r
+    {"pattern",    T_OBJECT,    PAT_OFF(pattern),       READONLY},\r
+    {"flags",      T_INT,       PAT_OFF(flags),         READONLY},\r
+    {"groups",     T_PYSSIZET,  PAT_OFF(groups),        READONLY},\r
+    {"groupindex", T_OBJECT,    PAT_OFF(groupindex),    READONLY},\r
+    {NULL}  /* Sentinel */\r
+};\r
+\r
+statichere PyTypeObject Pattern_Type = {\r
+    PyObject_HEAD_INIT(NULL)\r
+    0, "_" SRE_MODULE ".SRE_Pattern",\r
+    sizeof(PatternObject), sizeof(SRE_CODE),\r
+    (destructor)pattern_dealloc, /*tp_dealloc*/\r
+    0,                                  /* tp_print */\r
+    0,                                  /* tp_getattrn */\r
+    0,                                 /* tp_setattr */\r
+    0,                                 /* tp_compare */\r
+    0,                                 /* tp_repr */\r
+    0,                                 /* tp_as_number */\r
+    0,                                 /* tp_as_sequence */\r
+    0,                                 /* tp_as_mapping */\r
+    0,                                 /* tp_hash */\r
+    0,                                 /* tp_call */\r
+    0,                                 /* tp_str */\r
+    0,                                 /* tp_getattro */\r
+    0,                                 /* tp_setattro */\r
+    0,                                 /* tp_as_buffer */\r
+    Py_TPFLAGS_DEFAULT,                        /* tp_flags */\r
+    pattern_doc,                       /* tp_doc */\r
+    0,                                 /* tp_traverse */\r
+    0,                                 /* tp_clear */\r
+    0,                                 /* tp_richcompare */\r
+    offsetof(PatternObject, weakreflist),      /* tp_weaklistoffset */\r
+    0,                                 /* tp_iter */\r
+    0,                                 /* tp_iternext */\r
+    pattern_methods,                   /* tp_methods */\r
+    pattern_members,                   /* tp_members */\r
+};\r
+\r
+static int _validate(PatternObject *self); /* Forward */\r
+\r
+static PyObject *\r
+_compile(PyObject* self_, PyObject* args)\r
+{\r
+    /* "compile" pattern descriptor to pattern object */\r
+\r
+    PatternObject* self;\r
+    Py_ssize_t i, n;\r
+\r
+    PyObject* pattern;\r
+    int flags = 0;\r
+    PyObject* code;\r
+    Py_ssize_t groups = 0;\r
+    PyObject* groupindex = NULL;\r
+    PyObject* indexgroup = NULL;\r
+    if (!PyArg_ParseTuple(args, "OiO!|nOO", &pattern, &flags,\r
+                          &PyList_Type, &code, &groups,\r
+                          &groupindex, &indexgroup))\r
+        return NULL;\r
+\r
+    n = PyList_GET_SIZE(code);\r
+    /* coverity[ampersand_in_size] */\r
+    self = PyObject_NEW_VAR(PatternObject, &Pattern_Type, n);\r
+    if (!self)\r
+        return NULL;\r
+    self->weakreflist = NULL;\r
+    self->pattern = NULL;\r
+    self->groupindex = NULL;\r
+    self->indexgroup = NULL;\r
+\r
+    self->codesize = n;\r
+\r
+    for (i = 0; i < n; i++) {\r
+        PyObject *o = PyList_GET_ITEM(code, i);\r
+        unsigned long value = PyInt_Check(o) ? (unsigned long)PyInt_AsLong(o)\r
+                                              : PyLong_AsUnsignedLong(o);\r
+        if (value == (unsigned long)-1 && PyErr_Occurred()) {\r
+            if (PyErr_ExceptionMatches(PyExc_OverflowError)) {\r
+                PyErr_SetString(PyExc_OverflowError,\r
+                                "regular expression code size limit exceeded");\r
+            }\r
+            break;\r
+        }\r
+        self->code[i] = (SRE_CODE) value;\r
+        if ((unsigned long) self->code[i] != value) {\r
+            PyErr_SetString(PyExc_OverflowError,\r
+                            "regular expression code size limit exceeded");\r
+            break;\r
+        }\r
+    }\r
+\r
+    if (PyErr_Occurred()) {\r
+        Py_DECREF(self);\r
+        return NULL;\r
+    }\r
+\r
+    Py_INCREF(pattern);\r
+    self->pattern = pattern;\r
+\r
+    self->flags = flags;\r
+\r
+    self->groups = groups;\r
+\r
+    Py_XINCREF(groupindex);\r
+    self->groupindex = groupindex;\r
+\r
+    Py_XINCREF(indexgroup);\r
+    self->indexgroup = indexgroup;\r
+\r
+    self->weakreflist = NULL;\r
+\r
+    if (!_validate(self)) {\r
+        Py_DECREF(self);\r
+        return NULL;\r
+    }\r
+\r
+    return (PyObject*) self;\r
+}\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* Code validation */\r
+\r
+/* To learn more about this code, have a look at the _compile() function in\r
+   Lib/sre_compile.py.  The validation functions below checks the code array\r
+   for conformance with the code patterns generated there.\r
+\r
+   The nice thing about the generated code is that it is position-independent:\r
+   all jumps are relative jumps forward.  Also, jumps don't cross each other:\r
+   the target of a later jump is always earlier than the target of an earlier\r
+   jump.  IOW, this is okay:\r
+\r
+   J---------J-------T--------T\r
+    \         \_____/        /\r
+     \______________________/\r
+\r
+   but this is not:\r
+\r
+   J---------J-------T--------T\r
+    \_________\_____/        /\r
+               \____________/\r
+\r
+   It also helps that SRE_CODE is always an unsigned type.\r
+*/\r
+\r
+/* Defining this one enables tracing of the validator */\r
+#undef VVERBOSE\r
+\r
+/* Trace macro for the validator */\r
+#if defined(VVERBOSE)\r
+#define VTRACE(v) printf v\r
+#else\r
+#define VTRACE(v) do {} while(0)  /* do nothing */\r
+#endif\r
+\r
+/* Report failure */\r
+#define FAIL do { VTRACE(("FAIL: %d\n", __LINE__)); return 0; } while (0)\r
+\r
+/* Extract opcode, argument, or skip count from code array */\r
+#define GET_OP                                          \\r
+    do {                                                \\r
+        VTRACE(("%p: ", code));                         \\r
+        if (code >= end) FAIL;                          \\r
+        op = *code++;                                   \\r
+        VTRACE(("%lu (op)\n", (unsigned long)op));      \\r
+    } while (0)\r
+#define GET_ARG                                         \\r
+    do {                                                \\r
+        VTRACE(("%p= ", code));                         \\r
+        if (code >= end) FAIL;                          \\r
+        arg = *code++;                                  \\r
+        VTRACE(("%lu (arg)\n", (unsigned long)arg));    \\r
+    } while (0)\r
+#define GET_SKIP_ADJ(adj)                               \\r
+    do {                                                \\r
+        VTRACE(("%p= ", code));                         \\r
+        if (code >= end) FAIL;                          \\r
+        skip = *code;                                   \\r
+        VTRACE(("%lu (skip to %p)\n",                   \\r
+               (unsigned long)skip, code+skip));        \\r
+        if (skip-adj > end-code)                        \\r
+            FAIL;                                       \\r
+        code++;                                         \\r
+    } while (0)\r
+#define GET_SKIP GET_SKIP_ADJ(0)\r
+\r
+static int\r
+_validate_charset(SRE_CODE *code, SRE_CODE *end)\r
+{\r
+    /* Some variables are manipulated by the macros above */\r
+    SRE_CODE op;\r
+    SRE_CODE arg;\r
+    SRE_CODE offset;\r
+    int i;\r
+\r
+    while (code < end) {\r
+        GET_OP;\r
+        switch (op) {\r
+\r
+        case SRE_OP_NEGATE:\r
+            break;\r
+\r
+        case SRE_OP_LITERAL:\r
+            GET_ARG;\r
+            break;\r
+\r
+        case SRE_OP_RANGE:\r
+            GET_ARG;\r
+            GET_ARG;\r
+            break;\r
+\r
+        case SRE_OP_CHARSET:\r
+            offset = 32/sizeof(SRE_CODE); /* 32-byte bitmap */\r
+            if (offset > end-code)\r
+                FAIL;\r
+            code += offset;\r
+            break;\r
+\r
+        case SRE_OP_BIGCHARSET:\r
+            GET_ARG; /* Number of blocks */\r
+            offset = 256/sizeof(SRE_CODE); /* 256-byte table */\r
+            if (offset > end-code)\r
+                FAIL;\r
+            /* Make sure that each byte points to a valid block */\r
+            for (i = 0; i < 256; i++) {\r
+                if (((unsigned char *)code)[i] >= arg)\r
+                    FAIL;\r
+            }\r
+            code += offset;\r
+            offset = arg * 32/sizeof(SRE_CODE); /* 32-byte bitmap times arg */\r
+            if (offset > end-code)\r
+                FAIL;\r
+            code += offset;\r
+            break;\r
+\r
+        case SRE_OP_CATEGORY:\r
+            GET_ARG;\r
+            switch (arg) {\r
+            case SRE_CATEGORY_DIGIT:\r
+            case SRE_CATEGORY_NOT_DIGIT:\r
+            case SRE_CATEGORY_SPACE:\r
+            case SRE_CATEGORY_NOT_SPACE:\r
+            case SRE_CATEGORY_WORD:\r
+            case SRE_CATEGORY_NOT_WORD:\r
+            case SRE_CATEGORY_LINEBREAK:\r
+            case SRE_CATEGORY_NOT_LINEBREAK:\r
+            case SRE_CATEGORY_LOC_WORD:\r
+            case SRE_CATEGORY_LOC_NOT_WORD:\r
+            case SRE_CATEGORY_UNI_DIGIT:\r
+            case SRE_CATEGORY_UNI_NOT_DIGIT:\r
+            case SRE_CATEGORY_UNI_SPACE:\r
+            case SRE_CATEGORY_UNI_NOT_SPACE:\r
+            case SRE_CATEGORY_UNI_WORD:\r
+            case SRE_CATEGORY_UNI_NOT_WORD:\r
+            case SRE_CATEGORY_UNI_LINEBREAK:\r
+            case SRE_CATEGORY_UNI_NOT_LINEBREAK:\r
+                break;\r
+            default:\r
+                FAIL;\r
+            }\r
+            break;\r
+\r
+        default:\r
+            FAIL;\r
+\r
+        }\r
+    }\r
+\r
+    return 1;\r
+}\r
+\r
+static int\r
+_validate_inner(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups)\r
+{\r
+    /* Some variables are manipulated by the macros above */\r
+    SRE_CODE op;\r
+    SRE_CODE arg;\r
+    SRE_CODE skip;\r
+\r
+    VTRACE(("code=%p, end=%p\n", code, end));\r
+\r
+    if (code > end)\r
+        FAIL;\r
+\r
+    while (code < end) {\r
+        GET_OP;\r
+        switch (op) {\r
+\r
+        case SRE_OP_MARK:\r
+            /* We don't check whether marks are properly nested; the\r
+               sre_match() code is robust even if they don't, and the worst\r
+               you can get is nonsensical match results. */\r
+            GET_ARG;\r
+            if (arg > 2*groups+1) {\r
+                VTRACE(("arg=%d, groups=%d\n", (int)arg, (int)groups));\r
+                FAIL;\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_LITERAL:\r
+        case SRE_OP_NOT_LITERAL:\r
+        case SRE_OP_LITERAL_IGNORE:\r
+        case SRE_OP_NOT_LITERAL_IGNORE:\r
+            GET_ARG;\r
+            /* The arg is just a character, nothing to check */\r
+            break;\r
+\r
+        case SRE_OP_SUCCESS:\r
+        case SRE_OP_FAILURE:\r
+            /* Nothing to check; these normally end the matching process */\r
+            break;\r
+\r
+        case SRE_OP_AT:\r
+            GET_ARG;\r
+            switch (arg) {\r
+            case SRE_AT_BEGINNING:\r
+            case SRE_AT_BEGINNING_STRING:\r
+            case SRE_AT_BEGINNING_LINE:\r
+            case SRE_AT_END:\r
+            case SRE_AT_END_LINE:\r
+            case SRE_AT_END_STRING:\r
+            case SRE_AT_BOUNDARY:\r
+            case SRE_AT_NON_BOUNDARY:\r
+            case SRE_AT_LOC_BOUNDARY:\r
+            case SRE_AT_LOC_NON_BOUNDARY:\r
+            case SRE_AT_UNI_BOUNDARY:\r
+            case SRE_AT_UNI_NON_BOUNDARY:\r
+                break;\r
+            default:\r
+                FAIL;\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_ANY:\r
+        case SRE_OP_ANY_ALL:\r
+            /* These have no operands */\r
+            break;\r
+\r
+        case SRE_OP_IN:\r
+        case SRE_OP_IN_IGNORE:\r
+            GET_SKIP;\r
+            /* Stop 1 before the end; we check the FAILURE below */\r
+            if (!_validate_charset(code, code+skip-2))\r
+                FAIL;\r
+            if (code[skip-2] != SRE_OP_FAILURE)\r
+                FAIL;\r
+            code += skip-1;\r
+            break;\r
+\r
+        case SRE_OP_INFO:\r
+            {\r
+                /* A minimal info field is\r
+                   <INFO> <1=skip> <2=flags> <3=min> <4=max>;\r
+                   If SRE_INFO_PREFIX or SRE_INFO_CHARSET is in the flags,\r
+                   more follows. */\r
+                SRE_CODE flags, i;\r
+                SRE_CODE *newcode;\r
+                GET_SKIP;\r
+                newcode = code+skip-1;\r
+                GET_ARG; flags = arg;\r
+                GET_ARG; /* min */\r
+                GET_ARG; /* max */\r
+                /* Check that only valid flags are present */\r
+                if ((flags & ~(SRE_INFO_PREFIX |\r
+                               SRE_INFO_LITERAL |\r
+                               SRE_INFO_CHARSET)) != 0)\r
+                    FAIL;\r
+                /* PREFIX and CHARSET are mutually exclusive */\r
+                if ((flags & SRE_INFO_PREFIX) &&\r
+                    (flags & SRE_INFO_CHARSET))\r
+                    FAIL;\r
+                /* LITERAL implies PREFIX */\r
+                if ((flags & SRE_INFO_LITERAL) &&\r
+                    !(flags & SRE_INFO_PREFIX))\r
+                    FAIL;\r
+                /* Validate the prefix */\r
+                if (flags & SRE_INFO_PREFIX) {\r
+                    SRE_CODE prefix_len;\r
+                    GET_ARG; prefix_len = arg;\r
+                    GET_ARG; /* prefix skip */\r
+                    /* Here comes the prefix string */\r
+                    if (prefix_len > newcode-code)\r
+                        FAIL;\r
+                    code += prefix_len;\r
+                    /* And here comes the overlap table */\r
+                    if (prefix_len > newcode-code)\r
+                        FAIL;\r
+                    /* Each overlap value should be < prefix_len */\r
+                    for (i = 0; i < prefix_len; i++) {\r
+                        if (code[i] >= prefix_len)\r
+                            FAIL;\r
+                    }\r
+                    code += prefix_len;\r
+                }\r
+                /* Validate the charset */\r
+                if (flags & SRE_INFO_CHARSET) {\r
+                    if (!_validate_charset(code, newcode-1))\r
+                        FAIL;\r
+                    if (newcode[-1] != SRE_OP_FAILURE)\r
+                        FAIL;\r
+                    code = newcode;\r
+                }\r
+                else if (code != newcode) {\r
+                  VTRACE(("code=%p, newcode=%p\n", code, newcode));\r
+                    FAIL;\r
+                }\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_BRANCH:\r
+            {\r
+                SRE_CODE *target = NULL;\r
+                for (;;) {\r
+                    GET_SKIP;\r
+                    if (skip == 0)\r
+                        break;\r
+                    /* Stop 2 before the end; we check the JUMP below */\r
+                    if (!_validate_inner(code, code+skip-3, groups))\r
+                        FAIL;\r
+                    code += skip-3;\r
+                    /* Check that it ends with a JUMP, and that each JUMP\r
+                       has the same target */\r
+                    GET_OP;\r
+                    if (op != SRE_OP_JUMP)\r
+                        FAIL;\r
+                    GET_SKIP;\r
+                    if (target == NULL)\r
+                        target = code+skip-1;\r
+                    else if (code+skip-1 != target)\r
+                        FAIL;\r
+                }\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_REPEAT_ONE:\r
+        case SRE_OP_MIN_REPEAT_ONE:\r
+            {\r
+                SRE_CODE min, max;\r
+                GET_SKIP;\r
+                GET_ARG; min = arg;\r
+                GET_ARG; max = arg;\r
+                if (min > max)\r
+                    FAIL;\r
+                if (max > SRE_MAXREPEAT)\r
+                    FAIL;\r
+                if (!_validate_inner(code, code+skip-4, groups))\r
+                    FAIL;\r
+                code += skip-4;\r
+                GET_OP;\r
+                if (op != SRE_OP_SUCCESS)\r
+                    FAIL;\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_REPEAT:\r
+            {\r
+                SRE_CODE min, max;\r
+                GET_SKIP;\r
+                GET_ARG; min = arg;\r
+                GET_ARG; max = arg;\r
+                if (min > max)\r
+                    FAIL;\r
+                if (max > SRE_MAXREPEAT)\r
+                    FAIL;\r
+                if (!_validate_inner(code, code+skip-3, groups))\r
+                    FAIL;\r
+                code += skip-3;\r
+                GET_OP;\r
+                if (op != SRE_OP_MAX_UNTIL && op != SRE_OP_MIN_UNTIL)\r
+                    FAIL;\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_GROUPREF:\r
+        case SRE_OP_GROUPREF_IGNORE:\r
+            GET_ARG;\r
+            if (arg >= groups)\r
+                FAIL;\r
+            break;\r
+\r
+        case SRE_OP_GROUPREF_EXISTS:\r
+            /* The regex syntax for this is: '(?(group)then|else)', where\r
+               'group' is either an integer group number or a group name,\r
+               'then' and 'else' are sub-regexes, and 'else' is optional. */\r
+            GET_ARG;\r
+            if (arg >= groups)\r
+                FAIL;\r
+            GET_SKIP_ADJ(1);\r
+            code--; /* The skip is relative to the first arg! */\r
+            /* There are two possibilities here: if there is both a 'then'\r
+               part and an 'else' part, the generated code looks like:\r
+\r
+               GROUPREF_EXISTS\r
+               <group>\r
+               <skipyes>\r
+               ...then part...\r
+               JUMP\r
+               <skipno>\r
+               (<skipyes> jumps here)\r
+               ...else part...\r
+               (<skipno> jumps here)\r
+\r
+               If there is only a 'then' part, it looks like:\r
+\r
+               GROUPREF_EXISTS\r
+               <group>\r
+               <skip>\r
+               ...then part...\r
+               (<skip> jumps here)\r
+\r
+               There is no direct way to decide which it is, and we don't want\r
+               to allow arbitrary jumps anywhere in the code; so we just look\r
+               for a JUMP opcode preceding our skip target.\r
+            */\r
+            if (skip >= 3 && skip-3 < end-code &&\r
+                code[skip-3] == SRE_OP_JUMP)\r
+            {\r
+                VTRACE(("both then and else parts present\n"));\r
+                if (!_validate_inner(code+1, code+skip-3, groups))\r
+                    FAIL;\r
+                code += skip-2; /* Position after JUMP, at <skipno> */\r
+                GET_SKIP;\r
+                if (!_validate_inner(code, code+skip-1, groups))\r
+                    FAIL;\r
+                code += skip-1;\r
+            }\r
+            else {\r
+                VTRACE(("only a then part present\n"));\r
+                if (!_validate_inner(code+1, code+skip-1, groups))\r
+                    FAIL;\r
+                code += skip-1;\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_ASSERT:\r
+        case SRE_OP_ASSERT_NOT:\r
+            GET_SKIP;\r
+            GET_ARG; /* 0 for lookahead, width for lookbehind */\r
+            code--; /* Back up over arg to simplify math below */\r
+            if (arg & 0x80000000)\r
+                FAIL; /* Width too large */\r
+            /* Stop 1 before the end; we check the SUCCESS below */\r
+            if (!_validate_inner(code+1, code+skip-2, groups))\r
+                FAIL;\r
+            code += skip-2;\r
+            GET_OP;\r
+            if (op != SRE_OP_SUCCESS)\r
+                FAIL;\r
+            break;\r
+\r
+        default:\r
+            FAIL;\r
+\r
+        }\r
+    }\r
+\r
+    VTRACE(("okay\n"));\r
+    return 1;\r
+}\r
+\r
+static int\r
+_validate_outer(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups)\r
+{\r
+    if (groups < 0 || groups > 100 || code >= end || end[-1] != SRE_OP_SUCCESS)\r
+        FAIL;\r
+    if (groups == 0)  /* fix for simplejson */\r
+        groups = 100; /* 100 groups should always be safe */\r
+    return _validate_inner(code, end-1, groups);\r
+}\r
+\r
+static int\r
+_validate(PatternObject *self)\r
+{\r
+    if (!_validate_outer(self->code, self->code+self->codesize, self->groups))\r
+    {\r
+        PyErr_SetString(PyExc_RuntimeError, "invalid SRE code");\r
+        return 0;\r
+    }\r
+    else\r
+        VTRACE(("Success!\n"));\r
+    return 1;\r
+}\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* match methods */\r
+\r
+static void\r
+match_dealloc(MatchObject* self)\r
+{\r
+    Py_XDECREF(self->regs);\r
+    Py_XDECREF(self->string);\r
+    Py_DECREF(self->pattern);\r
+    PyObject_DEL(self);\r
+}\r
+\r
+static PyObject*\r
+match_getslice_by_index(MatchObject* self, Py_ssize_t index, PyObject* def)\r
+{\r
+    if (index < 0 || index >= self->groups) {\r
+        /* raise IndexError if we were given a bad group number */\r
+        PyErr_SetString(\r
+            PyExc_IndexError,\r
+            "no such group"\r
+            );\r
+        return NULL;\r
+    }\r
+\r
+    index *= 2;\r
+\r
+    if (self->string == Py_None || self->mark[index] < 0) {\r
+        /* return default value if the string or group is undefined */\r
+        Py_INCREF(def);\r
+        return def;\r
+    }\r
+\r
+    return PySequence_GetSlice(\r
+        self->string, self->mark[index], self->mark[index+1]\r
+        );\r
+}\r
+\r
+static Py_ssize_t\r
+match_getindex(MatchObject* self, PyObject* index)\r
+{\r
+    Py_ssize_t i;\r
+\r
+    if (PyInt_Check(index) || PyLong_Check(index))\r
+        return PyInt_AsSsize_t(index);\r
+\r
+    i = -1;\r
+\r
+    if (self->pattern->groupindex) {\r
+        index = PyObject_GetItem(self->pattern->groupindex, index);\r
+        if (index) {\r
+            if (PyInt_Check(index) || PyLong_Check(index))\r
+                i = PyInt_AsSsize_t(index);\r
+            Py_DECREF(index);\r
+        } else\r
+            PyErr_Clear();\r
+    }\r
+\r
+    return i;\r
+}\r
+\r
+static PyObject*\r
+match_getslice(MatchObject* self, PyObject* index, PyObject* def)\r
+{\r
+    return match_getslice_by_index(self, match_getindex(self, index), def);\r
+}\r
+\r
+static PyObject*\r
+match_expand(MatchObject* self, PyObject* ptemplate)\r
+{\r
+    /* delegate to Python code */\r
+    return call(\r
+        SRE_PY_MODULE, "_expand",\r
+        PyTuple_Pack(3, self->pattern, self, ptemplate)\r
+        );\r
+}\r
+\r
+static PyObject*\r
+match_group(MatchObject* self, PyObject* args)\r
+{\r
+    PyObject* result;\r
+    Py_ssize_t i, size;\r
+\r
+    size = PyTuple_GET_SIZE(args);\r
+\r
+    switch (size) {\r
+    case 0:\r
+        result = match_getslice(self, Py_False, Py_None);\r
+        break;\r
+    case 1:\r
+        result = match_getslice(self, PyTuple_GET_ITEM(args, 0), Py_None);\r
+        break;\r
+    default:\r
+        /* fetch multiple items */\r
+        result = PyTuple_New(size);\r
+        if (!result)\r
+            return NULL;\r
+        for (i = 0; i < size; i++) {\r
+            PyObject* item = match_getslice(\r
+                self, PyTuple_GET_ITEM(args, i), Py_None\r
+                );\r
+            if (!item) {\r
+                Py_DECREF(result);\r
+                return NULL;\r
+            }\r
+            PyTuple_SET_ITEM(result, i, item);\r
+        }\r
+        break;\r
+    }\r
+    return result;\r
+}\r
+\r
+static PyObject*\r
+match_groups(MatchObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    PyObject* result;\r
+    Py_ssize_t index;\r
+\r
+    PyObject* def = Py_None;\r
+    static char* kwlist[] = { "default", NULL };\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:groups", kwlist, &def))\r
+        return NULL;\r
+\r
+    result = PyTuple_New(self->groups-1);\r
+    if (!result)\r
+        return NULL;\r
+\r
+    for (index = 1; index < self->groups; index++) {\r
+        PyObject* item;\r
+        item = match_getslice_by_index(self, index, def);\r
+        if (!item) {\r
+            Py_DECREF(result);\r
+            return NULL;\r
+        }\r
+        PyTuple_SET_ITEM(result, index-1, item);\r
+    }\r
+\r
+    return result;\r
+}\r
+\r
+static PyObject*\r
+match_groupdict(MatchObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    PyObject* result;\r
+    PyObject* keys;\r
+    Py_ssize_t index;\r
+\r
+    PyObject* def = Py_None;\r
+    static char* kwlist[] = { "default", NULL };\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:groupdict", kwlist, &def))\r
+        return NULL;\r
+\r
+    result = PyDict_New();\r
+    if (!result || !self->pattern->groupindex)\r
+        return result;\r
+\r
+    keys = PyMapping_Keys(self->pattern->groupindex);\r
+    if (!keys)\r
+        goto failed;\r
+\r
+    for (index = 0; index < PyList_GET_SIZE(keys); index++) {\r
+        int status;\r
+        PyObject* key;\r
+        PyObject* value;\r
+        key = PyList_GET_ITEM(keys, index);\r
+        if (!key)\r
+            goto failed;\r
+        value = match_getslice(self, key, def);\r
+        if (!value) {\r
+            Py_DECREF(key);\r
+            goto failed;\r
+        }\r
+        status = PyDict_SetItem(result, key, value);\r
+        Py_DECREF(value);\r
+        if (status < 0)\r
+            goto failed;\r
+    }\r
+\r
+    Py_DECREF(keys);\r
+\r
+    return result;\r
+\r
+failed:\r
+    Py_XDECREF(keys);\r
+    Py_DECREF(result);\r
+    return NULL;\r
+}\r
+\r
+static PyObject*\r
+match_start(MatchObject* self, PyObject* args)\r
+{\r
+    Py_ssize_t index;\r
+\r
+    PyObject* index_ = Py_False; /* zero */\r
+    if (!PyArg_UnpackTuple(args, "start", 0, 1, &index_))\r
+        return NULL;\r
+\r
+    index = match_getindex(self, index_);\r
+\r
+    if (index < 0 || index >= self->groups) {\r
+        PyErr_SetString(\r
+            PyExc_IndexError,\r
+            "no such group"\r
+            );\r
+        return NULL;\r
+    }\r
+\r
+    /* mark is -1 if group is undefined */\r
+    return PyInt_FromSsize_t(self->mark[index*2]);\r
+}\r
+\r
+static PyObject*\r
+match_end(MatchObject* self, PyObject* args)\r
+{\r
+    Py_ssize_t index;\r
+\r
+    PyObject* index_ = Py_False; /* zero */\r
+    if (!PyArg_UnpackTuple(args, "end", 0, 1, &index_))\r
+        return NULL;\r
+\r
+    index = match_getindex(self, index_);\r
+\r
+    if (index < 0 || index >= self->groups) {\r
+        PyErr_SetString(\r
+            PyExc_IndexError,\r
+            "no such group"\r
+            );\r
+        return NULL;\r
+    }\r
+\r
+    /* mark is -1 if group is undefined */\r
+    return PyInt_FromSsize_t(self->mark[index*2+1]);\r
+}\r
+\r
+LOCAL(PyObject*)\r
+_pair(Py_ssize_t i1, Py_ssize_t i2)\r
+{\r
+    PyObject* pair;\r
+    PyObject* item;\r
+\r
+    pair = PyTuple_New(2);\r
+    if (!pair)\r
+        return NULL;\r
+\r
+    item = PyInt_FromSsize_t(i1);\r
+    if (!item)\r
+        goto error;\r
+    PyTuple_SET_ITEM(pair, 0, item);\r
+\r
+    item = PyInt_FromSsize_t(i2);\r
+    if (!item)\r
+        goto error;\r
+    PyTuple_SET_ITEM(pair, 1, item);\r
+\r
+    return pair;\r
+\r
+  error:\r
+    Py_DECREF(pair);\r
+    return NULL;\r
+}\r
+\r
+static PyObject*\r
+match_span(MatchObject* self, PyObject* args)\r
+{\r
+    Py_ssize_t index;\r
+\r
+    PyObject* index_ = Py_False; /* zero */\r
+    if (!PyArg_UnpackTuple(args, "span", 0, 1, &index_))\r
+        return NULL;\r
+\r
+    index = match_getindex(self, index_);\r
+\r
+    if (index < 0 || index >= self->groups) {\r
+        PyErr_SetString(\r
+            PyExc_IndexError,\r
+            "no such group"\r
+            );\r
+        return NULL;\r
+    }\r
+\r
+    /* marks are -1 if group is undefined */\r
+    return _pair(self->mark[index*2], self->mark[index*2+1]);\r
+}\r
+\r
+static PyObject*\r
+match_regs(MatchObject* self)\r
+{\r
+    PyObject* regs;\r
+    PyObject* item;\r
+    Py_ssize_t index;\r
+\r
+    regs = PyTuple_New(self->groups);\r
+    if (!regs)\r
+        return NULL;\r
+\r
+    for (index = 0; index < self->groups; index++) {\r
+        item = _pair(self->mark[index*2], self->mark[index*2+1]);\r
+        if (!item) {\r
+            Py_DECREF(regs);\r
+            return NULL;\r
+        }\r
+        PyTuple_SET_ITEM(regs, index, item);\r
+    }\r
+\r
+    Py_INCREF(regs);\r
+    self->regs = regs;\r
+\r
+    return regs;\r
+}\r
+\r
+static PyObject*\r
+match_copy(MatchObject* self, PyObject *unused)\r
+{\r
+#ifdef USE_BUILTIN_COPY\r
+    MatchObject* copy;\r
+    Py_ssize_t slots, offset;\r
+\r
+    slots = 2 * (self->pattern->groups+1);\r
+\r
+    copy = PyObject_NEW_VAR(MatchObject, &Match_Type, slots);\r
+    if (!copy)\r
+        return NULL;\r
+\r
+    /* this value a constant, but any compiler should be able to\r
+       figure that out all by itself */\r
+    offset = offsetof(MatchObject, string);\r
+\r
+    Py_XINCREF(self->pattern);\r
+    Py_XINCREF(self->string);\r
+    Py_XINCREF(self->regs);\r
+\r
+    memcpy((char*) copy + offset, (char*) self + offset,\r
+           sizeof(MatchObject) + slots * sizeof(Py_ssize_t) - offset);\r
+\r
+    return (PyObject*) copy;\r
+#else\r
+    PyErr_SetString(PyExc_TypeError, "cannot copy this match object");\r
+    return NULL;\r
+#endif\r
+}\r
+\r
+static PyObject*\r
+match_deepcopy(MatchObject* self, PyObject* memo)\r
+{\r
+#ifdef USE_BUILTIN_COPY\r
+    MatchObject* copy;\r
+\r
+    copy = (MatchObject*) match_copy(self);\r
+    if (!copy)\r
+        return NULL;\r
+\r
+    if (!deepcopy((PyObject**) &copy->pattern, memo) ||\r
+        !deepcopy(&copy->string, memo) ||\r
+        !deepcopy(&copy->regs, memo)) {\r
+        Py_DECREF(copy);\r
+        return NULL;\r
+    }\r
+\r
+#else\r
+    PyErr_SetString(PyExc_TypeError, "cannot deepcopy this match object");\r
+    return NULL;\r
+#endif\r
+}\r
+\r
+PyDoc_STRVAR(match_doc,\r
+"The result of re.match() and re.search().\n\\r
+Match objects always have a boolean value of True.");\r
+\r
+PyDoc_STRVAR(match_group_doc,\r
+"group([group1, ...]) -> str or tuple.\n\\r
+    Return subgroup(s) of the match by indices or names.\n\\r
+    For 0 returns the entire match.");\r
+\r
+PyDoc_STRVAR(match_start_doc,\r
+"start([group=0]) -> int.\n\\r
+    Return index of the start of the substring matched by group.");\r
+\r
+PyDoc_STRVAR(match_end_doc,\r
+"end([group=0]) -> int.\n\\r
+    Return index of the end of the substring matched by group.");\r
+\r
+PyDoc_STRVAR(match_span_doc,\r
+"span([group]) -> tuple.\n\\r
+    For MatchObject m, return the 2-tuple (m.start(group), m.end(group)).");\r
+\r
+PyDoc_STRVAR(match_groups_doc,\r
+"groups([default=None]) -> tuple.\n\\r
+    Return a tuple containing all the subgroups of the match, from 1.\n\\r
+    The default argument is used for groups\n\\r
+    that did not participate in the match");\r
+\r
+PyDoc_STRVAR(match_groupdict_doc,\r
+"groupdict([default=None]) -> dict.\n\\r
+    Return a dictionary containing all the named subgroups of the match,\n\\r
+    keyed by the subgroup name. The default argument is used for groups\n\\r
+    that did not participate in the match");\r
+\r
+PyDoc_STRVAR(match_expand_doc,\r
+"expand(template) -> str.\n\\r
+    Return the string obtained by doing backslash substitution\n\\r
+    on the string template, as done by the sub() method.");\r
+\r
+static PyMethodDef match_methods[] = {\r
+    {"group", (PyCFunction) match_group, METH_VARARGS, match_group_doc},\r
+    {"start", (PyCFunction) match_start, METH_VARARGS, match_start_doc},\r
+    {"end", (PyCFunction) match_end, METH_VARARGS, match_end_doc},\r
+    {"span", (PyCFunction) match_span, METH_VARARGS, match_span_doc},\r
+    {"groups", (PyCFunction) match_groups, METH_VARARGS|METH_KEYWORDS,\r
+        match_groups_doc},\r
+    {"groupdict", (PyCFunction) match_groupdict, METH_VARARGS|METH_KEYWORDS,\r
+        match_groupdict_doc},\r
+    {"expand", (PyCFunction) match_expand, METH_O, match_expand_doc},\r
+    {"__copy__", (PyCFunction) match_copy, METH_NOARGS},\r
+    {"__deepcopy__", (PyCFunction) match_deepcopy, METH_O},\r
+    {NULL, NULL}\r
+};\r
+\r
+static PyObject *\r
+match_lastindex_get(MatchObject *self)\r
+{\r
+    if (self->lastindex >= 0)\r
+        return PyInt_FromSsize_t(self->lastindex);\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+static PyObject *\r
+match_lastgroup_get(MatchObject *self)\r
+{\r
+    if (self->pattern->indexgroup && self->lastindex >= 0) {\r
+        PyObject* result = PySequence_GetItem(\r
+            self->pattern->indexgroup, self->lastindex\r
+            );\r
+        if (result)\r
+            return result;\r
+        PyErr_Clear();\r
+    }\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+static PyObject *\r
+match_regs_get(MatchObject *self)\r
+{\r
+    if (self->regs) {\r
+        Py_INCREF(self->regs);\r
+        return self->regs;\r
+    } else\r
+        return match_regs(self);\r
+}\r
+\r
+static PyGetSetDef match_getset[] = {\r
+    {"lastindex", (getter)match_lastindex_get, (setter)NULL},\r
+    {"lastgroup", (getter)match_lastgroup_get, (setter)NULL},\r
+    {"regs",      (getter)match_regs_get,      (setter)NULL},\r
+    {NULL}\r
+};\r
+\r
+#define MATCH_OFF(x) offsetof(MatchObject, x)\r
+static PyMemberDef match_members[] = {\r
+    {"string",  T_OBJECT,   MATCH_OFF(string),  READONLY},\r
+    {"re",      T_OBJECT,   MATCH_OFF(pattern), READONLY},\r
+    {"pos",     T_PYSSIZET, MATCH_OFF(pos),     READONLY},\r
+    {"endpos",  T_PYSSIZET, MATCH_OFF(endpos),  READONLY},\r
+    {NULL}\r
+};\r
+\r
+\r
+/* FIXME: implement setattr("string", None) as a special case (to\r
+   detach the associated string, if any */\r
+\r
+static PyTypeObject Match_Type = {\r
+    PyVarObject_HEAD_INIT(NULL, 0)\r
+    "_" SRE_MODULE ".SRE_Match",\r
+    sizeof(MatchObject), sizeof(Py_ssize_t),\r
+    (destructor)match_dealloc,  /* tp_dealloc */\r
+    0,                          /* tp_print */\r
+    0,                          /* tp_getattr */\r
+    0,                          /* tp_setattr */\r
+    0,                          /* tp_compare */\r
+    0,                          /* tp_repr */\r
+    0,                          /* tp_as_number */\r
+    0,                          /* tp_as_sequence */\r
+    0,                          /* tp_as_mapping */\r
+    0,                          /* tp_hash */\r
+    0,                          /* tp_call */\r
+    0,                          /* tp_str */\r
+    0,                          /* tp_getattro */\r
+    0,                          /* tp_setattro */\r
+    0,                          /* tp_as_buffer */\r
+    Py_TPFLAGS_DEFAULT,\r
+    match_doc,                  /* tp_doc */\r
+    0,                          /* tp_traverse */\r
+    0,                          /* tp_clear */\r
+    0,                          /* tp_richcompare */\r
+    0,                          /* tp_weaklistoffset */\r
+    0,                          /* tp_iter */\r
+    0,                          /* tp_iternext */\r
+    match_methods,             /* tp_methods */\r
+    match_members,             /* tp_members */\r
+    match_getset,              /* tp_getset */\r
+};\r
+\r
+static PyObject*\r
+pattern_new_match(PatternObject* pattern, SRE_STATE* state, int status)\r
+{\r
+    /* create match object (from state object) */\r
+\r
+    MatchObject* match;\r
+    Py_ssize_t i, j;\r
+    char* base;\r
+    int n;\r
+\r
+    if (status > 0) {\r
+\r
+        /* create match object (with room for extra group marks) */\r
+        /* coverity[ampersand_in_size] */\r
+        match = PyObject_NEW_VAR(MatchObject, &Match_Type,\r
+                                 2*(pattern->groups+1));\r
+        if (!match)\r
+            return NULL;\r
+\r
+        Py_INCREF(pattern);\r
+        match->pattern = pattern;\r
+\r
+        Py_INCREF(state->string);\r
+        match->string = state->string;\r
+\r
+        match->regs = NULL;\r
+        match->groups = pattern->groups+1;\r
+\r
+        /* fill in group slices */\r
+\r
+        base = (char*) state->beginning;\r
+        n = state->charsize;\r
+\r
+        match->mark[0] = ((char*) state->start - base) / n;\r
+        match->mark[1] = ((char*) state->ptr - base) / n;\r
+\r
+        for (i = j = 0; i < pattern->groups; i++, j+=2)\r
+            if (j+1 <= state->lastmark && state->mark[j] && state->mark[j+1]) {\r
+                match->mark[j+2] = ((char*) state->mark[j] - base) / n;\r
+                match->mark[j+3] = ((char*) state->mark[j+1] - base) / n;\r
+            } else\r
+                match->mark[j+2] = match->mark[j+3] = -1; /* undefined */\r
+\r
+        match->pos = state->pos;\r
+        match->endpos = state->endpos;\r
+\r
+        match->lastindex = state->lastindex;\r
+\r
+        return (PyObject*) match;\r
+\r
+    } else if (status == 0) {\r
+\r
+        /* no match */\r
+        Py_INCREF(Py_None);\r
+        return Py_None;\r
+\r
+    }\r
+\r
+    /* internal error */\r
+    pattern_error(status);\r
+    return NULL;\r
+}\r
+\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* scanner methods (experimental) */\r
+\r
+static void\r
+scanner_dealloc(ScannerObject* self)\r
+{\r
+    state_fini(&self->state);\r
+    Py_XDECREF(self->pattern);\r
+    PyObject_DEL(self);\r
+}\r
+\r
+static PyObject*\r
+scanner_match(ScannerObject* self, PyObject *unused)\r
+{\r
+    SRE_STATE* state = &self->state;\r
+    PyObject* match;\r
+    int status;\r
+\r
+    state_reset(state);\r
+\r
+    state->ptr = state->start;\r
+\r
+    if (state->charsize == 1) {\r
+        status = sre_match(state, PatternObject_GetCode(self->pattern));\r
+    } else {\r
+#if defined(HAVE_UNICODE)\r
+        status = sre_umatch(state, PatternObject_GetCode(self->pattern));\r
+#endif\r
+    }\r
+    if (PyErr_Occurred())\r
+        return NULL;\r
+\r
+    match = pattern_new_match((PatternObject*) self->pattern,\r
+                               state, status);\r
+\r
+    if (status == 0 || state->ptr == state->start)\r
+        state->start = (void*) ((char*) state->ptr + state->charsize);\r
+    else\r
+        state->start = state->ptr;\r
+\r
+    return match;\r
+}\r
+\r
+\r
+static PyObject*\r
+scanner_search(ScannerObject* self, PyObject *unused)\r
+{\r
+    SRE_STATE* state = &self->state;\r
+    PyObject* match;\r
+    int status;\r
+\r
+    state_reset(state);\r
+\r
+    state->ptr = state->start;\r
+\r
+    if (state->charsize == 1) {\r
+        status = sre_search(state, PatternObject_GetCode(self->pattern));\r
+    } else {\r
+#if defined(HAVE_UNICODE)\r
+        status = sre_usearch(state, PatternObject_GetCode(self->pattern));\r
+#endif\r
+    }\r
+    if (PyErr_Occurred())\r
+        return NULL;\r
+\r
+    match = pattern_new_match((PatternObject*) self->pattern,\r
+                               state, status);\r
+\r
+    if (status == 0 || state->ptr == state->start)\r
+        state->start = (void*) ((char*) state->ptr + state->charsize);\r
+    else\r
+        state->start = state->ptr;\r
+\r
+    return match;\r
+}\r
+\r
+static PyMethodDef scanner_methods[] = {\r
+    {"match", (PyCFunction) scanner_match, METH_NOARGS},\r
+    {"search", (PyCFunction) scanner_search, METH_NOARGS},\r
+    {NULL, NULL}\r
+};\r
+\r
+#define SCAN_OFF(x) offsetof(ScannerObject, x)\r
+static PyMemberDef scanner_members[] = {\r
+    {"pattern",        T_OBJECT,       SCAN_OFF(pattern),      READONLY},\r
+    {NULL}  /* Sentinel */\r
+};\r
+\r
+statichere PyTypeObject Scanner_Type = {\r
+    PyObject_HEAD_INIT(NULL)\r
+    0, "_" SRE_MODULE ".SRE_Scanner",\r
+    sizeof(ScannerObject), 0,\r
+    (destructor)scanner_dealloc, /*tp_dealloc*/\r
+    0,                         /* tp_print */\r
+    0,                         /* tp_getattr */\r
+    0,                         /* tp_setattr */\r
+    0,                         /* tp_reserved */\r
+    0,                         /* tp_repr */\r
+    0,                         /* tp_as_number */\r
+    0,                         /* tp_as_sequence */\r
+    0,                         /* tp_as_mapping */\r
+    0,                         /* tp_hash */\r
+    0,                         /* tp_call */\r
+    0,                         /* tp_str */\r
+    0,                         /* tp_getattro */\r
+    0,                         /* tp_setattro */\r
+    0,                         /* tp_as_buffer */\r
+    Py_TPFLAGS_DEFAULT,                /* tp_flags */\r
+    0,                         /* tp_doc */\r
+    0,                         /* tp_traverse */\r
+    0,                         /* tp_clear */\r
+    0,                         /* tp_richcompare */\r
+    0,                         /* tp_weaklistoffset */\r
+    0,                         /* tp_iter */\r
+    0,                         /* tp_iternext */\r
+    scanner_methods,           /* tp_methods */\r
+    scanner_members,           /* tp_members */\r
+    0,                         /* tp_getset */\r
+};\r
+\r
+static PyObject*\r
+pattern_scanner(PatternObject* pattern, PyObject* args)\r
+{\r
+    /* create search state object */\r
+\r
+    ScannerObject* self;\r
+\r
+    PyObject* string;\r
+    Py_ssize_t start = 0;\r
+    Py_ssize_t end = PY_SSIZE_T_MAX;\r
+    if (!PyArg_ParseTuple(args, "O|nn:scanner", &string, &start, &end))\r
+        return NULL;\r
+\r
+    /* create scanner object */\r
+    self = PyObject_NEW(ScannerObject, &Scanner_Type);\r
+    if (!self)\r
+        return NULL;\r
+    self->pattern = NULL;\r
+\r
+    string = state_init(&self->state, pattern, string, start, end);\r
+    if (!string) {\r
+        Py_DECREF(self);\r
+        return NULL;\r
+    }\r
+\r
+    Py_INCREF(pattern);\r
+    self->pattern = (PyObject*) pattern;\r
+\r
+    return (PyObject*) self;\r
+}\r
+\r
+static PyMethodDef _functions[] = {\r
+    {"compile", _compile, METH_VARARGS},\r
+    {"getcodesize", sre_codesize, METH_NOARGS},\r
+    {"getlower", sre_getlower, METH_VARARGS},\r
+    {NULL, NULL}\r
+};\r
+\r
+#if PY_VERSION_HEX < 0x02030000\r
+DL_EXPORT(void) init_sre(void)\r
+#else\r
+PyMODINIT_FUNC init_sre(void)\r
+#endif\r
+{\r
+    PyObject* m;\r
+    PyObject* d;\r
+    PyObject* x;\r
+\r
+    /* Patch object types */\r
+    if (PyType_Ready(&Pattern_Type) || PyType_Ready(&Match_Type) ||\r
+        PyType_Ready(&Scanner_Type))\r
+        return;\r
+\r
+    m = Py_InitModule("_" SRE_MODULE, _functions);\r
+    if (m == NULL)\r
+       return;\r
+    d = PyModule_GetDict(m);\r
+\r
+    x = PyInt_FromLong(SRE_MAGIC);\r
+    if (x) {\r
+        PyDict_SetItemString(d, "MAGIC", x);\r
+        Py_DECREF(x);\r
+    }\r
+\r
+    x = PyInt_FromLong(sizeof(SRE_CODE));\r
+    if (x) {\r
+        PyDict_SetItemString(d, "CODESIZE", x);\r
+        Py_DECREF(x);\r
+    }\r
+\r
+    x = PyLong_FromUnsignedLong(SRE_MAXREPEAT);\r
+    if (x) {\r
+        PyDict_SetItemString(d, "MAXREPEAT", x);\r
+        Py_DECREF(x);\r
+    }\r
+\r
+    x = PyString_FromString(copyright);\r
+    if (x) {\r
+        PyDict_SetItemString(d, "copyright", x);\r
+        Py_DECREF(x);\r
+    }\r
+}\r
+\r
+#endif /* !defined(SRE_RECURSIVE) */\r
+\r
+/* vim:ts=4:sw=4:et\r
+*/\r