summaryrefslogtreecommitdiffstats
path: root/Tests/CMakeLists.txt
Commit message (Expand)AuthorAgeFilesLines
...
* | FindICU: New moduleRoger Leigh2016-07-131-0/+4
* | Merge topic 'ninja-no-rsp-for-rc'Brad King2016-06-281-0/+3
|\ \ | |/
| * ninja, rc: ignore CMAKE_NINJA_FORCE_RESPONSE_FILE for RC filesBen Boeckel2016-06-271-0/+3
* | Merge topic 'java-export-targets'Brad King2016-06-091-0/+4
|\ \
| * | Tests: Add test for exported JARsMatthew Woehlke2016-06-071-0/+4
* | | Merge topic 'add-FindVulkan'Brad King2016-06-081-0/+4
|\ \ \ | |/ / |/| |
| * | Add FindVulkan.cmake.Matthäus G. Chajdas2016-06-081-0/+4
* | | Merge topic 'productbuild'Brad King2016-06-061-0/+11
|\ \ \ | |/ / |/| |
| * | productbuild: Add new productbuild cpack generator.Clinton Stimpson2016-06-031-0/+11
| |/
* | FindOpenCL: Add an imported targetMatthäus G. Chajdas2016-06-021-0/+4
|/
* GHS: Fix handling of duplicate source filenames (#16046)Geoff Viola2016-04-251-0/+11
* Utilities/Release: Create a Windows 64-bit binaryBrad King2016-03-171-0/+3
* Utilities/Release: Rename scripts to match target platformBrad King2016-03-171-4/+4
* Merge topic 'remove-vs6-generator'Brad King2016-03-101-5/+4
|\
| * Drop Visual Studio 6 generatorBrad King2016-03-091-5/+4
* | Tests: do not build PrecompiledHeader on Clang/C2Mariusz Pluciński2016-03-101-1/+3
|/
* Add FindLTTngUST module to find LTTng-UST libraryPhilippe Proulx2016-03-071-0/+4
* Merge topic 'update-osx-release'Brad King2016-03-071-1/+1
|\
| * Utilities/Release: Switch to OS X 10.7 and Qt 5.5 for Mac binaryBrad King2016-02-191-1/+1
* | Tests: Fix XCTest when ENV{SDKROOT} is setBrad King2016-02-191-1/+1
|/
* Merge topic 'FindPNG-imported-targets'Brad King2016-01-221-0/+4
|\
| * FindPNG: Create an imported PNG::PNG target (#15911)Sam Thursfield2016-01-211-0/+4
* | FindXalanC: New module to find the Apache Xalan-C++ libraryRoger Leigh2016-01-201-0/+4
|/
* Utilities/Release: Switch to .msi builder for Windows binaryBrad King2015-12-211-1/+1
* Tests: Add tests for FindGTestRoger Leigh2015-12-101-0/+5
* Merge topic 'FindTIFF-imported-targets'Brad King2015-12-071-0/+4
|\
| * FindTIFF: Add imported targets and update documentationRoger Leigh2015-12-071-0/+4
* | Merge topic 'improve-embarcadero'Brad King2015-12-041-2/+1
|\ \
| * | Embarcadero/Watcom: Properly skip VSResource test for other generators.James Johnston2015-12-031-2/+1
| |/
* | Tests: Add FindBoost testcase for imported targetsRoger Leigh2015-12-021-0/+4
|/
* Merge topic 'FindXercesC-imported-targets'Brad King2015-11-241-0/+4
|\
| * FindXercesC: Add imported targets and unit testRoger Leigh2015-11-231-0/+4
* | CTest: Expand directories for Cobertura searchJoseph Snyder2015-11-231-0/+1
|/
* Merge topic 'cpack-deb-config-file-source-field'Brad King2015-11-061-0/+1
|\
| * CPackDEB: added config file optional Source fieldRaffi Enficiaud2015-11-041-0/+1
* | CPackDeb: ctest tests for compression scheme leakRaffi Enficiaud2015-11-031-1/+2
|/
* Tests: Fix DelphiCoverage test file selectionJoseph Snyder2015-10-201-2/+3
* Tests: Add a nightly Linux 64-bit binaryBrad King2015-10-061-0/+2
* Tests: Rename Linux nightly release binary test to Linux32Brad King2015-10-061-1/+1
* Tests: Rename OS X nightly release binary testBrad King2015-10-051-1/+1
* Tests: Drop nightly OS X ppc/i386 binaryBrad King2015-10-051-2/+0
* VS: Add support for Windows 10 Universal (Store) ApplicationsGilles Khouzam2015-10-051-1/+8
* FindThreads: add simple testcaseRolf Eike Beer2015-09-211-0/+2
* Add support for *.manifest source files with MSVC toolsBrad King2015-09-171-0/+1
* Swift: Require Xcode 6.1 and for MacOS X at least SDK 10.10Gregor Jasny2015-09-051-4/+31
* UseJava: Add support for javah toolMarc Chevrier2015-08-211-0/+25
* FindOpenSSL: Provide imported targets OpenSSL::{SSL,Crypto}Konstantin Podsvirov2015-08-131-0/+4
* UseJava: Teach add_jar to support file syntax for sourcesMarc Chevrier2015-08-041-4/+17
* Tests: Move CTestTestConfigFileInBuildDir into RunCMake.ctest_startBrad King2015-07-141-33/+0
* Add rudimentary support for the Apple Swift language with XcodeBrad King2015-07-061-0/+6
ef='#n753'>753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
#include "Python.h"
#include <ctype.h>

#include "frameobject.h"
#include "expat.h"

#include "pyexpat.h"

/* Do not emit Clinic output to a file as that wreaks havoc with conditionally
   included methods. */
/*[clinic input]
module pyexpat
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b168d503a4490c15]*/

#define XML_COMBINED_VERSION (10000*XML_MAJOR_VERSION+100*XML_MINOR_VERSION+XML_MICRO_VERSION)

static XML_Memory_Handling_Suite ExpatMemoryHandler = {
    PyObject_Malloc, PyObject_Realloc, PyObject_Free};

enum HandlerTypes {
    StartElement,
    EndElement,
    ProcessingInstruction,
    CharacterData,
    UnparsedEntityDecl,
    NotationDecl,
    StartNamespaceDecl,
    EndNamespaceDecl,
    Comment,
    StartCdataSection,
    EndCdataSection,
    Default,
    DefaultHandlerExpand,
    NotStandalone,
    ExternalEntityRef,
    StartDoctypeDecl,
    EndDoctypeDecl,
    EntityDecl,
    XmlDecl,
    ElementDecl,
    AttlistDecl,
#if XML_COMBINED_VERSION >= 19504
    SkippedEntity,
#endif
    _DummyDecl
};

static PyObject *ErrorObject;

/* ----------------------------------------------------- */

/* Declarations for objects of type xmlparser */

typedef struct {
    PyObject_HEAD

    XML_Parser itself;
    int ordered_attributes;     /* Return attributes as a list. */
    int specified_attributes;   /* Report only specified attributes. */
    int in_callback;            /* Is a callback active? */
    int ns_prefixes;            /* Namespace-triplets mode? */
    XML_Char *buffer;           /* Buffer used when accumulating characters */
                                /* NULL if not enabled */
    int buffer_size;            /* Size of buffer, in XML_Char units */
    int buffer_used;            /* Buffer units in use */
    PyObject *intern;           /* Dictionary to intern strings */
    PyObject **handlers;
} xmlparseobject;

#define CHARACTER_DATA_BUFFER_SIZE 8192

static PyTypeObject Xmlparsetype;

typedef void (*xmlhandlersetter)(XML_Parser self, void *meth);
typedef void* xmlhandler;

struct HandlerInfo {
    const char *name;
    xmlhandlersetter setter;
    xmlhandler handler;
    PyCodeObject *tb_code;
    PyObject *nameobj;
};

static struct HandlerInfo handler_info[64];

/* Set an integer attribute on the error object; return true on success,
 * false on an exception.
 */
static int
set_error_attr(PyObject *err, char *name, int value)
{
    PyObject *v = PyLong_FromLong(value);

    if (v == NULL || PyObject_SetAttrString(err, name, v) == -1) {
        Py_XDECREF(v);
        return 0;
    }
    Py_DECREF(v);
    return 1;
}

/* Build and set an Expat exception, including positioning
 * information.  Always returns NULL.
 */
static PyObject *
set_error(xmlparseobject *self, enum XML_Error code)
{
    PyObject *err;
    PyObject *buffer;
    XML_Parser parser = self->itself;
    int lineno = XML_GetErrorLineNumber(parser);
    int column = XML_GetErrorColumnNumber(parser);

    buffer = PyUnicode_FromFormat("%s: line %i, column %i",
                                  XML_ErrorString(code), lineno, column);
    if (buffer == NULL)
        return NULL;
    err = PyObject_CallFunction(ErrorObject, "O", buffer);
    Py_DECREF(buffer);
    if (  err != NULL
          && set_error_attr(err, "code", code)
          && set_error_attr(err, "offset", column)
          && set_error_attr(err, "lineno", lineno)) {
        PyErr_SetObject(ErrorObject, err);
    }
    Py_XDECREF(err);
    return NULL;
}

static int
have_handler(xmlparseobject *self, int type)
{
    PyObject *handler = self->handlers[type];
    return handler != NULL;
}

static PyObject *
get_handler_name(struct HandlerInfo *hinfo)
{
    PyObject *name = hinfo->nameobj;
    if (name == NULL) {
        name = PyUnicode_FromString(hinfo->name);
        hinfo->nameobj = name;
    }
    Py_XINCREF(name);
    return name;
}


/* Convert a string of XML_Chars into a Unicode string.
   Returns None if str is a null pointer. */

static PyObject *
conv_string_to_unicode(const XML_Char *str)
{
    /* XXX currently this code assumes that XML_Char is 8-bit,
       and hence in UTF-8.  */
    /* UTF-8 from Expat, Unicode desired */
    if (str == NULL) {
        Py_INCREF(Py_None);
        return Py_None;
    }
    return PyUnicode_DecodeUTF8(str, strlen(str), "strict");
}

static PyObject *
conv_string_len_to_unicode(const XML_Char *str, int len)
{
    /* XXX currently this code assumes that XML_Char is 8-bit,
       and hence in UTF-8.  */
    /* UTF-8 from Expat, Unicode desired */
    if (str == NULL) {
        Py_INCREF(Py_None);
        return Py_None;
    }
    return PyUnicode_DecodeUTF8((const char *)str, len, "strict");
}

/* Callback routines */

static void clear_handlers(xmlparseobject *self, int initial);

/* This handler is used when an error has been detected, in the hope
   that actual parsing can be terminated early.  This will only help
   if an external entity reference is encountered. */
static int
error_external_entity_ref_handler(XML_Parser parser,
                                  const XML_Char *context,
                                  const XML_Char *base,
                                  const XML_Char *systemId,
                                  const XML_Char *publicId)
{
    return 0;
}

/* Dummy character data handler used when an error (exception) has
   been detected, and the actual parsing can be terminated early.
   This is needed since character data handler can't be safely removed
   from within the character data handler, but can be replaced.  It is
   used only from the character data handler trampoline, and must be
   used right after `flag_error()` is called. */
static void
noop_character_data_handler(void *userData, const XML_Char *data, int len)
{
    /* Do nothing. */
}

static void
flag_error(xmlparseobject *self)
{
    clear_handlers(self, 0);
    XML_SetExternalEntityRefHandler(self->itself,
                                    error_external_entity_ref_handler);
}

static PyObject*
call_with_frame(char *funcname, int lineno, PyObject* func, PyObject* args,
                xmlparseobject *self)
{
    PyObject *res;

    res = PyEval_CallObject(func, args);
    if (res == NULL) {
        _PyTraceback_Add(funcname, __FILE__, lineno);
        XML_StopParser(self->itself, XML_FALSE);
    }
    return res;
}

static PyObject*
string_intern(xmlparseobject *self, const char* str)
{
    PyObject *result = conv_string_to_unicode(str);
    PyObject *value;
    /* result can be NULL if the unicode conversion failed. */
    if (!result)
        return result;
    if (!self->intern)
        return result;
    value = PyDict_GetItem(self->intern, result);
    if (!value) {
        if (PyDict_SetItem(self->intern, result, result) == 0)
            return result;
        else
            return NULL;
    }
    Py_INCREF(value);
    Py_DECREF(result);
    return value;
}

/* Return 0 on success, -1 on exception.
 * flag_error() will be called before return if needed.
 */
static int
call_character_handler(xmlparseobject *self, const XML_Char *buffer, int len)
{
    PyObject *args;
    PyObject *temp;

    if (!have_handler(self, CharacterData))
        return -1;

    args = PyTuple_New(1);
    if (args == NULL)
        return -1;
    temp = (conv_string_len_to_unicode(buffer, len));
    if (temp == NULL) {
        Py_DECREF(args);
        flag_error(self);
        XML_SetCharacterDataHandler(self->itself,
                                    noop_character_data_handler);
        return -1;
    }
    PyTuple_SET_ITEM(args, 0, temp);
    /* temp is now a borrowed reference; consider it unused. */
    self->in_callback = 1;
    temp = call_with_frame("CharacterData", __LINE__,
                           self->handlers[CharacterData], args, self);
    /* temp is an owned reference again, or NULL */
    self->in_callback = 0;
    Py_DECREF(args);
    if (temp == NULL) {
        flag_error(self);
        XML_SetCharacterDataHandler(self->itself,
                                    noop_character_data_handler);
        return -1;
    }
    Py_DECREF(temp);
    return 0;
}

static int
flush_character_buffer(xmlparseobject *self)
{
    int rc;
    if (self->buffer == NULL || self->buffer_used == 0)
        return 0;
    rc = call_character_handler(self, self->buffer, self->buffer_used);
    self->buffer_used = 0;
    return rc;
}

static void
my_CharacterDataHandler(void *userData, const XML_Char *data, int len)
{
    xmlparseobject *self = (xmlparseobject *) userData;

    if (PyErr_Occurred())
        return;

    if (self->buffer == NULL)
        call_character_handler(self, data, len);
    else {
        if ((self->buffer_used + len) > self->buffer_size) {
            if (flush_character_buffer(self) < 0)
                return;
            /* handler might have changed; drop the rest on the floor
             * if there isn't a handler anymore
             */
            if (!have_handler(self, CharacterData))
                return;
        }
        if (len > self->buffer_size) {
            call_character_handler(self, data, len);
            self->buffer_used = 0;
        }
        else {
            memcpy(self->buffer + self->buffer_used,
                   data, len * sizeof(XML_Char));
            self->buffer_used += len;
        }
    }
}

static void
my_StartElementHandler(void *userData,
                       const XML_Char *name, const XML_Char *atts[])
{
    xmlparseobject *self = (xmlparseobject *)userData;

    if (have_handler(self, StartElement)) {
        PyObject *container, *rv, *args;
        int i, max;

        if (PyErr_Occurred())
            return;

        if (flush_character_buffer(self) < 0)
            return;
        /* Set max to the number of slots filled in atts[]; max/2 is
         * the number of attributes we need to process.
         */
        if (self->specified_attributes) {
            max = XML_GetSpecifiedAttributeCount(self->itself);
        }
        else {
            max = 0;
            while (atts[max] != NULL)
                max += 2;
        }
        /* Build the container. */
        if (self->ordered_attributes)
            container = PyList_New(max);
        else
            container = PyDict_New();
        if (container == NULL) {
            flag_error(self);
            return;
        }
        for (i = 0; i < max; i += 2) {
            PyObject *n = string_intern(self, (XML_Char *) atts[i]);
            PyObject *v;
            if (n == NULL) {
                flag_error(self);
                Py_DECREF(container);
                return;
            }
            v = conv_string_to_unicode((XML_Char *) atts[i+1]);
            if (v == NULL) {
                flag_error(self);
                Py_DECREF(container);
                Py_DECREF(n);
                return;
            }
            if (self->ordered_attributes) {
                PyList_SET_ITEM(container, i, n);
                PyList_SET_ITEM(container, i+1, v);
            }
            else if (PyDict_SetItem(container, n, v)) {
                flag_error(self);
                Py_DECREF(n);
                Py_DECREF(v);
                return;
            }
            else {
                Py_DECREF(n);
                Py_DECREF(v);
            }
        }
        args = string_intern(self, name);
        if (args != NULL)
            args = Py_BuildValue("(NN)", args, container);
        if (args == NULL) {
            Py_DECREF(container);
            return;
        }
        /* Container is now a borrowed reference; ignore it. */
        self->in_callback = 1;
        rv = call_with_frame("StartElement", __LINE__,
                             self->handlers[StartElement], args, self);
        self->in_callback = 0;
        Py_DECREF(args);
        if (rv == NULL) {
            flag_error(self);
            return;
        }
        Py_DECREF(rv);
    }
}

#define RC_HANDLER(RC, NAME, PARAMS, INIT, PARAM_FORMAT, CONVERSION, \
                RETURN, GETUSERDATA) \
static RC \
my_##NAME##Handler PARAMS {\
    xmlparseobject *self = GETUSERDATA ; \
    PyObject *args = NULL; \
    PyObject *rv = NULL; \
    INIT \
\
    if (have_handler(self, NAME)) { \
        if (PyErr_Occurred()) \
            return RETURN; \
        if (flush_character_buffer(self) < 0) \
            return RETURN; \
        args = Py_BuildValue PARAM_FORMAT ;\
        if (!args) { flag_error(self); return RETURN;} \
        self->in_callback = 1; \
        rv = call_with_frame(#NAME,__LINE__, \
                             self->handlers[NAME], args, self); \
        self->in_callback = 0; \
        Py_DECREF(args); \
        if (rv == NULL) { \
            flag_error(self); \
            return RETURN; \
        } \
        CONVERSION \
        Py_DECREF(rv); \
    } \
    return RETURN; \
}

#define VOID_HANDLER(NAME, PARAMS, PARAM_FORMAT) \
        RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\
        (xmlparseobject *)userData)

#define INT_HANDLER(NAME, PARAMS, PARAM_FORMAT)\
        RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \
                        rc = PyLong_AsLong(rv);, rc, \
        (xmlparseobject *)userData)

VOID_HANDLER(EndElement,
             (void *userData, const XML_Char *name),
             ("(N)", string_intern(self, name)))

VOID_HANDLER(ProcessingInstruction,
             (void *userData,
              const XML_Char *target,
              const XML_Char *data),
             ("(NO&)", string_intern(self, target), conv_string_to_unicode ,data))

VOID_HANDLER(UnparsedEntityDecl,
             (void *userData,
              const XML_Char *entityName,
              const XML_Char *base,
              const XML_Char *systemId,
              const XML_Char *publicId,
              const XML_Char *notationName),
             ("(NNNNN)",
              string_intern(self, entityName), string_intern(self, base),
              string_intern(self, systemId), string_intern(self, publicId),
              string_intern(self, notationName)))

VOID_HANDLER(EntityDecl,
             (void *userData,
              const XML_Char *entityName,
              int is_parameter_entity,
              const XML_Char *value,
              int value_length,
              const XML_Char *base,
              const XML_Char *systemId,
              const XML_Char *publicId,
              const XML_Char *notationName),
             ("NiNNNNN",
              string_intern(self, entityName), is_parameter_entity,
              (conv_string_len_to_unicode(value, value_length)),
              string_intern(self, base), string_intern(self, systemId),
              string_intern(self, publicId),
              string_intern(self, notationName)))

VOID_HANDLER(XmlDecl,
             (void *userData,
              const XML_Char *version,
              const XML_Char *encoding,
              int standalone),
             ("(O&O&i)",
              conv_string_to_unicode ,version, conv_string_to_unicode ,encoding,
              standalone))

static PyObject *
conv_content_model(XML_Content * const model,
                   PyObject *(*conv_string)(const XML_Char *))
{
    PyObject *result = NULL;
    PyObject *children = PyTuple_New(model->numchildren);
    int i;

    if (children != NULL) {
        assert(model->numchildren < INT_MAX);
        for (i = 0; i < (int)model->numchildren; ++i) {
            PyObject *child = conv_content_model(&model->children[i],
                                                 conv_string);
            if (child == NULL) {
                Py_XDECREF(children);
                return NULL;
            }
            PyTuple_SET_ITEM(children, i, child);
        }
        result = Py_BuildValue("(iiO&N)",
                               model->type, model->quant,
                               conv_string,model->name, children);
    }
    return result;
}

static void
my_ElementDeclHandler(void *userData,
                      const XML_Char *name,
                      XML_Content *model)
{
    xmlparseobject *self = (xmlparseobject *)userData;
    PyObject *args = NULL;

    if (have_handler(self, ElementDecl)) {
        PyObject *rv = NULL;
        PyObject *modelobj, *nameobj;

        if (PyErr_Occurred())
            return;

        if (flush_character_buffer(self) < 0)
            goto finally;
        modelobj = conv_content_model(model, (conv_string_to_unicode));
        if (modelobj == NULL) {
            flag_error(self);
            goto finally;
        }
        nameobj = string_intern(self, name);
        if (nameobj == NULL) {
            Py_DECREF(modelobj);
            flag_error(self);
            goto finally;
        }
        args = Py_BuildValue("NN", nameobj, modelobj);
        if (args == NULL) {
            Py_DECREF(modelobj);
            flag_error(self);
            goto finally;
        }
        self->in_callback = 1;
        rv = call_with_frame("ElementDecl", __LINE__,
                             self->handlers[ElementDecl], args, self);
        self->in_callback = 0;
        if (rv == NULL) {
            flag_error(self);
            goto finally;
        }
        Py_DECREF(rv);
    }
 finally:
    Py_XDECREF(args);
    XML_FreeContentModel(self->itself, model);
    return;
}

VOID_HANDLER(AttlistDecl,
             (void *userData,
              const XML_Char *elname,
              const XML_Char *attname,
              const XML_Char *att_type,
              const XML_Char *dflt,
              int isrequired),
             ("(NNO&O&i)",
              string_intern(self, elname), string_intern(self, attname),
              conv_string_to_unicode ,att_type, conv_string_to_unicode ,dflt,
              isrequired))

#if XML_COMBINED_VERSION >= 19504
VOID_HANDLER(SkippedEntity,
             (void *userData,
              const XML_Char *entityName,
              int is_parameter_entity),
             ("Ni",
              string_intern(self, entityName), is_parameter_entity))
#endif

VOID_HANDLER(NotationDecl,
                (void *userData,
                        const XML_Char *notationName,
                        const XML_Char *base,
                        const XML_Char *systemId,
                        const XML_Char *publicId),
                ("(NNNN)",
                 string_intern(self, notationName), string_intern(self, base),
                 string_intern(self, systemId), string_intern(self, publicId)))

VOID_HANDLER(StartNamespaceDecl,
                (void *userData,
                      const XML_Char *prefix,
                      const XML_Char *uri),
                ("(NN)",
                 string_intern(self, prefix), string_intern(self, uri)))

VOID_HANDLER(EndNamespaceDecl,
                (void *userData,
                    const XML_Char *prefix),
                ("(N)", string_intern(self, prefix)))

VOID_HANDLER(Comment,
               (void *userData, const XML_Char *data),
                ("(O&)", conv_string_to_unicode ,data))

VOID_HANDLER(StartCdataSection,
               (void *userData),
                ("()"))

VOID_HANDLER(EndCdataSection,
               (void *userData),
                ("()"))

VOID_HANDLER(Default,
              (void *userData, const XML_Char *s, int len),
              ("(N)", (conv_string_len_to_unicode(s,len))))

VOID_HANDLER(DefaultHandlerExpand,
              (void *userData, const XML_Char *s, int len),
              ("(N)", (conv_string_len_to_unicode(s,len))))

INT_HANDLER(NotStandalone,
                (void *userData),
                ("()"))

RC_HANDLER(int, ExternalEntityRef,
                (XML_Parser parser,
                    const XML_Char *context,
                    const XML_Char *base,
                    const XML_Char *systemId,
                    const XML_Char *publicId),
                int rc=0;,
                ("(O&NNN)",
                 conv_string_to_unicode ,context, string_intern(self, base),
                 string_intern(self, systemId), string_intern(self, publicId)),
                rc = PyLong_AsLong(rv);, rc,
                XML_GetUserData(parser))

/* XXX UnknownEncodingHandler */

VOID_HANDLER(StartDoctypeDecl,
             (void *userData, const XML_Char *doctypeName,
              const XML_Char *sysid, const XML_Char *pubid,
              int has_internal_subset),
             ("(NNNi)", string_intern(self, doctypeName),
              string_intern(self, sysid), string_intern(self, pubid),
              has_internal_subset))

VOID_HANDLER(EndDoctypeDecl, (void *userData), ("()"))

/* ---------------------------------------------------------------- */
/*[clinic input]
class pyexpat.xmlparser "xmlparseobject *" "&Xmlparsetype"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=2393162385232e1c]*/


static PyObject *
get_parse_result(xmlparseobject *self, int rv)
{
    if (PyErr_Occurred()) {
        return NULL;
    }
    if (rv == 0) {
        return set_error(self, XML_GetErrorCode(self->itself));
    }
    if (flush_character_buffer(self) < 0) {
        return NULL;
    }
    return PyLong_FromLong(rv);
}

#define MAX_CHUNK_SIZE (1 << 20)

/*[clinic input]
pyexpat.xmlparser.Parse

    data: object
    isFinal: int = 0
    /

Parse XML data.

`isfinal' should be true at end of input.
[clinic start generated code]*/

PyDoc_STRVAR(pyexpat_xmlparser_Parse__doc__,
"Parse($self, data, isFinal=0, /)\n"
"--\n"
"\n"
"Parse XML data.\n"
"\n"
"`isfinal\' should be true at end of input.");

#define PYEXPAT_XMLPARSER_PARSE_METHODDEF    \
    {"Parse", (PyCFunction)pyexpat_xmlparser_Parse, METH_VARARGS, pyexpat_xmlparser_Parse__doc__},

static PyObject *
pyexpat_xmlparser_Parse_impl(xmlparseobject *self, PyObject *data, int isFinal);

static PyObject *
pyexpat_xmlparser_Parse(xmlparseobject *self, PyObject *args)
{
    PyObject *return_value = NULL;
    PyObject *data;
    int isFinal = 0;

    if (!PyArg_ParseTuple(args,
        "O|i:Parse",
        &data, &isFinal))
        goto exit;
    return_value = pyexpat_xmlparser_Parse_impl(self, data, isFinal);

exit:
    return return_value;
}

static PyObject *
pyexpat_xmlparser_Parse_impl(xmlparseobject *self, PyObject *data, int isFinal)
/*[clinic end generated code: output=65b1652b01f20856 input=e37b81b8948ca7e0]*/
{
    const char *s;
    Py_ssize_t slen;
    Py_buffer view;
    int rc;

    if (PyUnicode_Check(data)) {
        view.buf = NULL;
        s = PyUnicode_AsUTF8AndSize(data, &slen);
        if (s == NULL)
            return NULL;
        /* Explicitly set UTF-8 encoding. Return code ignored. */
        (void)XML_SetEncoding(self->itself, "utf-8");
    }
    else {
        if (PyObject_GetBuffer(data, &view, PyBUF_SIMPLE) < 0)
            return NULL;
        s = view.buf;
        slen = view.len;
    }

    while (slen > MAX_CHUNK_SIZE) {
        rc = XML_Parse(self->itself, s, MAX_CHUNK_SIZE, 0);
        if (!rc)
            goto done;
        s += MAX_CHUNK_SIZE;
        slen -= MAX_CHUNK_SIZE;
    }
    assert(MAX_CHUNK_SIZE < INT_MAX && slen < INT_MAX);
    rc = XML_Parse(self->itself, s, (int)slen, isFinal);

done:
    if (view.buf != NULL)
        PyBuffer_Release(&view);
    return get_parse_result(self, rc);
}

/* File reading copied from cPickle */

#define BUF_SIZE 2048

static int
readinst(char *buf, int buf_size, PyObject *meth)
{
    PyObject *str;
    Py_ssize_t len;
    char *ptr;

    str = PyObject_CallFunction(meth, "n", buf_size);
    if (str == NULL)
        goto error;

    if (PyBytes_Check(str))
        ptr = PyBytes_AS_STRING(str);
    else if (PyByteArray_Check(str))
        ptr = PyByteArray_AS_STRING(str);
    else {
        PyErr_Format(PyExc_TypeError,
                     "read() did not return a bytes object (type=%.400s)",
                     Py_TYPE(str)->tp_name);
        goto error;
    }
    len = Py_SIZE(str);
    if (len > buf_size) {
        PyErr_Format(PyExc_ValueError,
                     "read() returned too much data: "
                     "%i bytes requested, %zd returned",
                     buf_size, len);
        goto error;
    }
    memcpy(buf, ptr, len);
    Py_DECREF(str);
    /* len <= buf_size <= INT_MAX */
    return (int)len;

error:
    Py_XDECREF(str);
    return -1;
}

/*[clinic input]
pyexpat.xmlparser.ParseFile

    file: object
    /

Parse XML data from file-like object.
[clinic start generated code]*/

PyDoc_STRVAR(pyexpat_xmlparser_ParseFile__doc__,
"ParseFile($self, file, /)\n"
"--\n"
"\n"
"Parse XML data from file-like object.");

#define PYEXPAT_XMLPARSER_PARSEFILE_METHODDEF    \
    {"ParseFile", (PyCFunction)pyexpat_xmlparser_ParseFile, METH_O, pyexpat_xmlparser_ParseFile__doc__},

static PyObject *
pyexpat_xmlparser_ParseFile(xmlparseobject *self, PyObject *file)
/*[clinic end generated code: output=2e13803c3d8c22b2 input=fbb5a12b6038d735]*/
{
    int rv = 1;
    PyObject *readmethod = NULL;
    _Py_IDENTIFIER(read);

    readmethod = _PyObject_GetAttrId(file, &PyId_read);
    if (readmethod == NULL) {
        PyErr_SetString(PyExc_TypeError,
                        "argument must have 'read' attribute");
        return NULL;
    }
    for (;;) {
        int bytes_read;
        void *buf = XML_GetBuffer(self->itself, BUF_SIZE);
        if (buf == NULL) {
            Py_XDECREF(readmethod);
            return get_parse_result(self, 0);
        }

        bytes_read = readinst(buf, BUF_SIZE, readmethod);
        if (bytes_read < 0) {
            Py_DECREF(readmethod);
            return NULL;
        }
        rv = XML_ParseBuffer(self->itself, bytes_read, bytes_read == 0);
        if (PyErr_Occurred()) {
            Py_XDECREF(readmethod);
            return NULL;
        }

        if (!rv || bytes_read == 0)
            break;
    }
    Py_XDECREF(readmethod);
    return get_parse_result(self, rv);
}

/*[clinic input]
pyexpat.xmlparser.SetBase

    base: str
    /

Set the base URL for the parser.
[clinic start generated code]*/

PyDoc_STRVAR(pyexpat_xmlparser_SetBase__doc__,
"SetBase($self, base, /)\n"
"--\n"
"\n"
"Set the base URL for the parser.");

#define PYEXPAT_XMLPARSER_SETBASE_METHODDEF    \
    {"SetBase", (PyCFunction)pyexpat_xmlparser_SetBase, METH_VARARGS, pyexpat_xmlparser_SetBase__doc__},

static PyObject *
pyexpat_xmlparser_SetBase_impl(xmlparseobject *self, const char *base);

static PyObject *
pyexpat_xmlparser_SetBase(xmlparseobject *self, PyObject *args)
{
    PyObject *return_value = NULL;
    const char *base;

    if (!PyArg_ParseTuple(args,
        "s:SetBase",
        &base))
        goto exit;
    return_value = pyexpat_xmlparser_SetBase_impl(self, base);

exit:
    return return_value;
}

static PyObject *
pyexpat_xmlparser_SetBase_impl(xmlparseobject *self, const char *base)
/*[clinic end generated code: output=5bdb49f6689a5f93 input=c684e5de895ee1a8]*/
{
    if (!XML_SetBase(self->itself, base)) {
        return PyErr_NoMemory();
    }
    Py_RETURN_NONE;
}

/*[clinic input]
pyexpat.xmlparser.GetBase

Return base URL string for the parser.
[clinic start generated code]*/

PyDoc_STRVAR(pyexpat_xmlparser_GetBase__doc__,
"GetBase($self, /)\n"
"--\n"
"\n"
"Return base URL string for the parser.");

#define PYEXPAT_XMLPARSER_GETBASE_METHODDEF    \
    {"GetBase", (PyCFunction)pyexpat_xmlparser_GetBase, METH_NOARGS, pyexpat_xmlparser_GetBase__doc__},

static PyObject *
pyexpat_xmlparser_GetBase_impl(xmlparseobject *self);

static PyObject *
pyexpat_xmlparser_GetBase(xmlparseobject *self, PyObject *Py_UNUSED(ignored))
{
    return pyexpat_xmlparser_GetBase_impl(self);
}

static PyObject *
pyexpat_xmlparser_GetBase_impl(xmlparseobject *self)
/*[clinic end generated code: output=ef6046ee28f2b8ee input=918d71c38009620e]*/
{
    return Py_BuildValue("z", XML_GetBase(self->itself));
}

/*[clinic input]
pyexpat.xmlparser.GetInputContext

Return the untranslated text of the input that caused the current event.

If the event was generated by a large amount of text (such as a start tag
for an element with many attributes), not all of the text may be available.
[clinic start generated code]*/

PyDoc_STRVAR(pyexpat_xmlparser_GetInputContext__doc__,
"GetInputContext($self, /)\n"
"--\n"
"\n"
"Return the untranslated text of the input that caused the current event.\n"
"\n"
"If the event was generated by a large amount of text (such as a start tag\n"
"for an element with many attributes), not all of the text may be available.");

#define PYEXPAT_XMLPARSER_GETINPUTCONTEXT_METHODDEF    \
    {"GetInputContext", (PyCFunction)pyexpat_xmlparser_GetInputContext, METH_NOARGS, pyexpat_xmlparser_GetInputContext__doc__},

static PyObject *
pyexpat_xmlparser_GetInputContext_impl(xmlparseobject *self);

static PyObject *
pyexpat_xmlparser_GetInputContext(xmlparseobject *self, PyObject *Py_UNUSED(ignored))
{
    return pyexpat_xmlparser_GetInputContext_impl(self);
}

static PyObject *
pyexpat_xmlparser_GetInputContext_impl(xmlparseobject *self)
/*[clinic end generated code: output=62ff03390f074cd2 input=034df8712db68379]*/
{
    if (self->in_callback) {
        int offset, size;
        const char *buffer
            = XML_GetInputContext(self->itself, &offset, &size);

        if (buffer != NULL)
            return PyBytes_FromStringAndSize(buffer + offset,
                                              size - offset);
        else
            Py_RETURN_NONE;
    }
    else
        Py_RETURN_NONE;
}

/*[clinic input]
pyexpat.xmlparser.ExternalEntityParserCreate

    context: str(nullable=True)
    encoding: str = NULL
    /

Create a parser for parsing an external entity based on the information passed to the ExternalEntityRefHandler.
[clinic start generated code]*/

PyDoc_STRVAR(pyexpat_xmlparser_ExternalEntityParserCreate__doc__,
"ExternalEntityParserCreate($self, context, encoding=None, /)\n"
"--\n"
"\n"
"Create a parser for parsing an external entity based on the information passed to the ExternalEntityRefHandler.");

#define PYEXPAT_XMLPARSER_EXTERNALENTITYPARSERCREATE_METHODDEF    \
    {"ExternalEntityParserCreate", (PyCFunction)pyexpat_xmlparser_ExternalEntityParserCreate, METH_VARARGS, pyexpat_xmlparser_ExternalEntityParserCreate__doc__},

static PyObject *
pyexpat_xmlparser_ExternalEntityParserCreate_impl(xmlparseobject *self, const char *context, const char *encoding);

static PyObject *
pyexpat_xmlparser_ExternalEntityParserCreate(xmlparseobject *self, PyObject *args)
{
    PyObject *return_value = NULL;
    const char *context;
    const char *encoding = NULL;

    if (!PyArg_ParseTuple(args,
        "z|s:ExternalEntityParserCreate",
        &context, &encoding))
        goto exit;
    return_value = pyexpat_xmlparser_ExternalEntityParserCreate_impl(self, context, encoding);

exit:
    return return_value;
}

static PyObject *
pyexpat_xmlparser_ExternalEntityParserCreate_impl(xmlparseobject *self, const char *context, const char *encoding)
/*[clinic end generated code: output=4948c35f3dd01133 input=283206575d960272]*/
{
    xmlparseobject *new_parser;
    int i;

    new_parser = PyObject_GC_New(xmlparseobject, &Xmlparsetype);
    if (new_parser == NULL)
        return NULL;
    new_parser->buffer_size = self->buffer_size;
    new_parser->buffer_used = 0;
    new_parser->buffer = NULL;
    new_parser->ordered_attributes = self->ordered_attributes;
    new_parser->specified_attributes = self->specified_attributes;
    new_parser->in_callback = 0;
    new_parser->ns_prefixes = self->ns_prefixes;
    new_parser->itself = XML_ExternalEntityParserCreate(self->itself, context,
                                                        encoding);
    new_parser->handlers = 0;
    new_parser->intern = self->intern;
    Py_XINCREF(new_parser->intern);
    PyObject_GC_Track(new_parser);

    if (self->buffer != NULL) {
        new_parser->buffer = PyMem_Malloc(new_parser->buffer_size);
        if (new_parser->buffer == NULL) {
            Py_DECREF(new_parser);
            return PyErr_NoMemory();
        }
    }
    if (!new_parser->itself) {
        Py_DECREF(new_parser);
        return PyErr_NoMemory();
    }

    XML_SetUserData(new_parser->itself, (void *)new_parser);

    /* allocate and clear handlers first */
    for (i = 0; handler_info[i].name != NULL; i++)
        /* do nothing */;

    new_parser->handlers = PyMem_Malloc(sizeof(PyObject *) * i);
    if (!new_parser->handlers) {
        Py_DECREF(new_parser);
        return PyErr_NoMemory();
    }
    clear_handlers(new_parser, 1);

    /* then copy handlers from self */
    for (i = 0; handler_info[i].name != NULL; i++) {
        PyObject *handler = self->handlers[i];
        if (handler != NULL) {
            Py_INCREF(handler);
            new_parser->handlers[i] = handler;
            handler_info[i].setter(new_parser->itself,
                                   handler_info[i].handler);
        }
    }
    return (PyObject *)new_parser;
}

/*[clinic input]
pyexpat.xmlparser.SetParamEntityParsing

    flag: int
    /

Controls parsing of parameter entities (including the external DTD subset).

Possible flag values are XML_PARAM_ENTITY_PARSING_NEVER,
XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE and
XML_PARAM_ENTITY_PARSING_ALWAYS. Returns true if setting the flag
was successful.
[clinic start generated code]*/

PyDoc_STRVAR(pyexpat_xmlparser_SetParamEntityParsing__doc__,
"SetParamEntityParsing($self, flag, /)\n"
"--\n"
"\n"
"Controls parsing of parameter entities (including the external DTD subset).\n"
"\n"
"Possible flag values are XML_PARAM_ENTITY_PARSING_NEVER,\n"
"XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE and\n"
"XML_PARAM_ENTITY_PARSING_ALWAYS. Returns true if setting the flag\n"
"was successful.");

#define PYEXPAT_XMLPARSER_SETPARAMENTITYPARSING_METHODDEF    \
    {"SetParamEntityParsing", (PyCFunction)pyexpat_xmlparser_SetParamEntityParsing, METH_VARARGS, pyexpat_xmlparser_SetParamEntityParsing__doc__},

static PyObject *
pyexpat_xmlparser_SetParamEntityParsing_impl(xmlparseobject *self, int flag);

static PyObject *
pyexpat_xmlparser_SetParamEntityParsing(xmlparseobject *self, PyObject *args)
{
    PyObject *return_value = NULL;
    int flag;

    if (!PyArg_ParseTuple(args,
        "i:SetParamEntityParsing",
        &flag))
        goto exit;
    return_value = pyexpat_xmlparser_SetParamEntityParsing_impl(self, flag);

exit:
    return return_value;
}

static PyObject *
pyexpat_xmlparser_SetParamEntityParsing_impl(xmlparseobject *self, int flag)
/*[clinic end generated code: output=0f820882bc7768cc input=8aea19b4b15e9af1]*/
{
    flag = XML_SetParamEntityParsing(self->itself, flag);
    return PyLong_FromLong(flag);
}


#if XML_COMBINED_VERSION >= 19505
/*[clinic input]
pyexpat.xmlparser.UseForeignDTD

    flag: bool = True
    /

Allows the application to provide an artificial external subset if one is not specified as part of the document instance.

This readily allows the use of a 'default' document type controlled by the
application, while still getting the advantage of providing document type
information to the parser. 'flag' defaults to True if not provided.
[clinic start generated code]*/

PyDoc_STRVAR(pyexpat_xmlparser_UseForeignDTD__doc__,
"UseForeignDTD($self, flag=True, /)\n"
"--\n"
"\n"
"Allows the application to provide an artificial external subset if one is not specified as part of the document instance.\n"
"\n"
"This readily allows the use of a \'default\' document type controlled by the\n"
"application, while still getting the advantage of providing document type\n"
"information to the parser. \'flag\' defaults to True if not provided.");

#define PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF    \
    {"UseForeignDTD", (PyCFunction)pyexpat_xmlparser_UseForeignDTD, METH_VARARGS, pyexpat_xmlparser_UseForeignDTD__doc__},

static PyObject *
pyexpat_xmlparser_UseForeignDTD_impl(xmlparseobject *self, int flag);

static PyObject *
pyexpat_xmlparser_UseForeignDTD(xmlparseobject *self, PyObject *args)
{
    PyObject *return_value = NULL;
    int flag = 1;

    if (!PyArg_ParseTuple(args,
        "|p:UseForeignDTD",
        &flag))
        goto exit;
    return_value = pyexpat_xmlparser_UseForeignDTD_impl(self, flag);

exit:
    return return_value;
}

static PyObject *
pyexpat_xmlparser_UseForeignDTD_impl(xmlparseobject *self, int flag)
/*[clinic end generated code: output=22e924ae6cad67d6 input=78144c519d116a6e]*/
{
    enum XML_Error rc;

    rc = XML_UseForeignDTD(self->itself, flag ? XML_TRUE : XML_FALSE);
    if (rc != XML_ERROR_NONE) {
        return set_error(self, rc);
    }
    Py_INCREF(Py_None);
    return Py_None;
}
#endif

/*[clinic input]
pyexpat.xmlparser.__dir__
[clinic start generated code]*/

PyDoc_STRVAR(pyexpat_xmlparser___dir____doc__,
"__dir__($self, /)\n"
"--");

#define PYEXPAT_XMLPARSER___DIR___METHODDEF    \
    {"__dir__", (PyCFunction)pyexpat_xmlparser___dir__, METH_NOARGS, pyexpat_xmlparser___dir____doc__},

static PyObject *
pyexpat_xmlparser___dir___impl(xmlparseobject *self);

static PyObject *
pyexpat_xmlparser___dir__(xmlparseobject *self, PyObject *Py_UNUSED(ignored))
{
    return pyexpat_xmlparser___dir___impl(self);
}

static PyObject *
pyexpat_xmlparser___dir___impl(xmlparseobject *self)
/*[clinic end generated code: output=1ed6efe83bc304cc input=76aa455f2a661384]*/
{
#define APPEND(list, str)                               \
        do {                                            \
                PyObject *o = PyUnicode_FromString(str);        \
                if (o != NULL)                          \
                        PyList_Append(list, o);         \
                Py_XDECREF(o);                          \
        } while (0)

    int i;
    PyObject *rc = PyList_New(0);
    if (!rc)
        return NULL;
    for (i = 0; handler_info[i].name != NULL; i++) {
        PyObject *o = get_handler_name(&handler_info[i]);
        if (o != NULL)
            PyList_Append(rc, o);
        Py_XDECREF(o);
    }
    APPEND(rc, "ErrorCode");
    APPEND(rc, "ErrorLineNumber");
    APPEND(rc, "ErrorColumnNumber");
    APPEND(rc, "ErrorByteIndex");
    APPEND(rc, "CurrentLineNumber");
    APPEND(rc, "CurrentColumnNumber");
    APPEND(rc, "CurrentByteIndex");
    APPEND(rc, "buffer_size");
    APPEND(rc, "buffer_text");
    APPEND(rc, "buffer_used");
    APPEND(rc, "namespace_prefixes");
    APPEND(rc, "ordered_attributes");
    APPEND(rc, "specified_attributes");
    APPEND(rc, "intern");

#undef APPEND

    if (PyErr_Occurred()) {
        Py_DECREF(rc);
        rc = NULL;
    }

    return rc;
}

static struct PyMethodDef xmlparse_methods[] = {
    PYEXPAT_XMLPARSER_PARSE_METHODDEF
    PYEXPAT_XMLPARSER_PARSEFILE_METHODDEF
    PYEXPAT_XMLPARSER_SETBASE_METHODDEF
    PYEXPAT_XMLPARSER_GETBASE_METHODDEF
    PYEXPAT_XMLPARSER_GETINPUTCONTEXT_METHODDEF
    PYEXPAT_XMLPARSER_EXTERNALENTITYPARSERCREATE_METHODDEF
    PYEXPAT_XMLPARSER_SETPARAMENTITYPARSING_METHODDEF
#if XML_COMBINED_VERSION >= 19505
    PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF
#endif
    PYEXPAT_XMLPARSER___DIR___METHODDEF
    {NULL, NULL}  /* sentinel */
};

/* ---------- */



/* pyexpat international encoding support.
   Make it as simple as possible.
*/

static int
PyUnknownEncodingHandler(void *encodingHandlerData,
                         const XML_Char *name,
                         XML_Encoding *info)
{
    static unsigned char template_buffer[256] = {0};
    PyObject* u;
    int i;
    void *data;
    unsigned int kind;

    if (PyErr_Occurred())
        return XML_STATUS_ERROR;

    if (template_buffer[1] == 0) {
        for (i = 0; i < 256; i++)
            template_buffer[i] = i;
    }

    u = PyUnicode_Decode((char*) template_buffer, 256, name, "replace");
    if (u == NULL || PyUnicode_READY(u)) {
        Py_XDECREF(u);
        return XML_STATUS_ERROR;
    }

    if (PyUnicode_GET_LENGTH(u) != 256) {
        Py_DECREF(u);
        PyErr_SetString(PyExc_ValueError,
                        "multi-byte encodings are not supported");
        return XML_STATUS_ERROR;
    }

    kind = PyUnicode_KIND(u);
    data = PyUnicode_DATA(u);
    for (i = 0; i < 256; i++) {
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
        if (ch != Py_UNICODE_REPLACEMENT_CHARACTER)
            info->map[i] = ch;
        else
            info->map[i] = -1;
    }

    info->data = NULL;
    info->convert = NULL;
    info->release = NULL;
    Py_DECREF(u);

    return XML_STATUS_OK;
}


static PyObject *
newxmlparseobject(const char *encoding, const char *namespace_separator, PyObject *intern)
{
    int i;
    xmlparseobject *self;

    self = PyObject_GC_New(xmlparseobject, &Xmlparsetype);
    if (self == NULL)
        return NULL;

    self->buffer = NULL;
    self->buffer_size = CHARACTER_DATA_BUFFER_SIZE;
    self->buffer_used = 0;
    self->ordered_attributes = 0;
    self->specified_attributes = 0;
    self->in_callback = 0;
    self->ns_prefixes = 0;
    self->handlers = NULL;
    self->intern = intern;
    Py_XINCREF(self->intern);
    PyObject_GC_Track(self);

    /* namespace_separator is either NULL or contains one char + \0 */
    self->itself = XML_ParserCreate_MM(encoding, &ExpatMemoryHandler,
                                       namespace_separator);
    if (self->itself == NULL) {
        PyErr_SetString(PyExc_RuntimeError,
                        "XML_ParserCreate failed");
        Py_DECREF(self);
        return NULL;
    }
#if ((XML_MAJOR_VERSION >= 2) && (XML_MINOR_VERSION >= 1)) || defined(XML_HAS_SET_HASH_SALT)
    /* This feature was added upstream in libexpat 2.1.0.  Our expat copy
     * has a backport of this feature where we also define XML_HAS_SET_HASH_SALT
     * to indicate that we can still use it. */
    XML_SetHashSalt(self->itself,
                    (unsigned long)_Py_HashSecret.expat.hashsalt);
#endif
    XML_SetUserData(self->itself, (void *)self);
    XML_SetUnknownEncodingHandler(self->itself,
                  (XML_UnknownEncodingHandler) PyUnknownEncodingHandler, NULL);

    for (i = 0; handler_info[i].name != NULL; i++)
        /* do nothing */;

    self->handlers = PyMem_Malloc(sizeof(PyObject *) * i);
    if (!self->handlers) {
        Py_DECREF(self);
        return PyErr_NoMemory();
    }
    clear_handlers(self, 1);

    return (PyObject*)self;
}


static void
xmlparse_dealloc(xmlparseobject *self)
{
    int i;
    PyObject_GC_UnTrack(self);
    if (self->itself != NULL)
        XML_ParserFree(self->itself);
    self->itself = NULL;

    if (self->handlers != NULL) {
        PyObject *temp;
        for (i = 0; handler_info[i].name != NULL; i++) {
            temp = self->handlers[i];
            self->handlers[i] = NULL;
            Py_XDECREF(temp);
        }
        PyMem_Free(self->handlers);
        self->handlers = NULL;
    }
    if (self->buffer != NULL) {
        PyMem_Free(self->buffer);
        self->buffer = NULL;
    }
    Py_XDECREF(self->intern);
    PyObject_GC_Del(self);
}

static int
handlername2int(PyObject *name)
{
    int i;
    for (i = 0; handler_info[i].name != NULL; i++) {
        if (PyUnicode_CompareWithASCIIString(
                name, handler_info[i].name) == 0) {
            return i;
        }
    }
    return -1;
}

static PyObject *
get_pybool(int istrue)
{
    PyObject *result = istrue ? Py_True : Py_False;
    Py_INCREF(result);
    return result;
}

static PyObject *
xmlparse_getattro(xmlparseobject *self, PyObject *nameobj)
{
    Py_UCS4 first_char;
    int handlernum = -1;

    if (!PyUnicode_Check(nameobj))
        goto generic;
    if (PyUnicode_READY(nameobj))
        return NULL;

    handlernum = handlername2int(nameobj);

    if (handlernum != -1) {
        PyObject *result = self->handlers[handlernum];
        if (result == NULL)
            result = Py_None;
        Py_INCREF(result);
        return result;
    }

    first_char = PyUnicode_READ_CHAR(nameobj, 0);
    if (first_char == 'E') {
        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorCode") == 0)
            return PyLong_FromLong((long)
                                  XML_GetErrorCode(self->itself));
        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorLineNumber") == 0)
            return PyLong_FromLong((long)
                                  XML_GetErrorLineNumber(self->itself));
        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorColumnNumber") == 0)
            return PyLong_FromLong((long)
                                  XML_GetErrorColumnNumber(self->itself));
        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorByteIndex") == 0)
            return PyLong_FromLong((long)
                                  XML_GetErrorByteIndex(self->itself));
    }
    if (first_char == 'C') {
        if (PyUnicode_CompareWithASCIIString(nameobj, "CurrentLineNumber") == 0)
            return PyLong_FromLong((long)
                                  XML_GetCurrentLineNumber(self->itself));
        if (PyUnicode_CompareWithASCIIString(nameobj, "CurrentColumnNumber") == 0)
            return PyLong_FromLong((long)
                                  XML_GetCurrentColumnNumber(self->itself));
        if (PyUnicode_CompareWithASCIIString(nameobj, "CurrentByteIndex") == 0)
            return PyLong_FromLong((long)
                                  XML_GetCurrentByteIndex(self->itself));
    }
    if (first_char == 'b') {
        if (PyUnicode_CompareWithASCIIString(nameobj, "buffer_size") == 0)
            return PyLong_FromLong((long) self->buffer_size);
        if (PyUnicode_CompareWithASCIIString(nameobj, "buffer_text") == 0)
            return get_pybool(self->buffer != NULL);
        if (PyUnicode_CompareWithASCIIString(nameobj, "buffer_used") == 0)
            return PyLong_FromLong((long) self->buffer_used);
    }
    if (PyUnicode_CompareWithASCIIString(nameobj, "namespace_prefixes") == 0)
        return get_pybool(self->ns_prefixes);
    if (PyUnicode_CompareWithASCIIString(nameobj, "ordered_attributes") == 0)
        return get_pybool(self->ordered_attributes);
    if (PyUnicode_CompareWithASCIIString(nameobj, "specified_attributes") == 0)
        return get_pybool((long) self->specified_attributes);
    if (PyUnicode_CompareWithASCIIString(nameobj, "intern") == 0) {
        if (self->intern == NULL) {
            Py_INCREF(Py_None);
            return Py_None;
        }
        else {
            Py_INCREF(self->intern);
            return self->intern;
        }
    }
  generic:
    return PyObject_GenericGetAttr((PyObject*)self, nameobj);
}

static int
sethandler(xmlparseobject *self, PyObject *name, PyObject* v)
{
    int handlernum = handlername2int(name);
    if (handlernum >= 0) {
        xmlhandler c_handler = NULL;
        PyObject *temp = self->handlers[handlernum];

        if (v == Py_None) {
            /* If this is the character data handler, and a character
               data handler is already active, we need to be more
               careful.  What we can safely do is replace the existing
               character data handler callback function with a no-op
               function that will refuse to call Python.  The downside
               is that this doesn't completely remove the character
               data handler from the C layer if there's any callback
               active, so Expat does a little more work than it
               otherwise would, but that's really an odd case.  A more
               elaborate system of handlers and state could remove the
               C handler more effectively. */
            if (handlernum == CharacterData && self->in_callback)
                c_handler = noop_character_data_handler;
            v = NULL;
        }
        else if (v != NULL) {
            Py_INCREF(v);
            c_handler = handler_info[handlernum].handler;
        }
        self->handlers[handlernum] = v;
        Py_XDECREF(temp);
        handler_info[handlernum].setter(self->itself, c_handler);
        return 1;
    }
    return 0;
}

static int
xmlparse_setattro(xmlparseobject *self, PyObject *name, PyObject *v)
{
    /* Set attribute 'name' to value 'v'. v==NULL means delete */
    if (v == NULL) {
        PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute");
        return -1;
    }
    assert(PyUnicode_Check(name));
    if (PyUnicode_CompareWithASCIIString(name, "buffer_text") == 0) {
        int b = PyObject_IsTrue(v);
        if (b < 0)
            return -1;
        if (b) {
            if (self->buffer == NULL) {
                self->buffer = PyMem_Malloc(self->buffer_size);
                if (self->buffer == NULL) {
                    PyErr_NoMemory();
                    return -1;
                }
                self->buffer_used = 0;
            }
        }
        else if (self->buffer != NULL) {
            if (flush_character_buffer(self) < 0)
                return -1;
            PyMem_Free(self->buffer);
            self->buffer = NULL;
        }
        return 0;
    }
    if (PyUnicode_CompareWithASCIIString(name, "namespace_prefixes") == 0) {
        int b = PyObject_IsTrue(v);
        if (b < 0)
            return -1;
        self->ns_prefixes = b;
        XML_SetReturnNSTriplet(self->itself, self->ns_prefixes);
        return 0;
    }
    if (PyUnicode_CompareWithASCIIString(name, "ordered_attributes") == 0) {
        int b = PyObject_IsTrue(v);
        if (b < 0)
            return -1;
        self->ordered_attributes = b;
        return 0;
    }
    if (PyUnicode_CompareWithASCIIString(name, "specified_attributes") == 0) {
        int b = PyObject_IsTrue(v);
        if (b < 0)
            return -1;
        self->specified_attributes = b;
        return 0;
    }

    if (PyUnicode_CompareWithASCIIString(name, "buffer_size") == 0) {
      long new_buffer_size;
      if (!PyLong_Check(v)) {
        PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
        return -1;
      }

      new_buffer_size=PyLong_AS_LONG(v);
      /* trivial case -- no change */
      if (new_buffer_size == self->buffer_size) {
        return 0;
      }

      if (new_buffer_size <= 0) {
        PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero");
        return -1;
      }

      /* check maximum */
      if (new_buffer_size > INT_MAX) {
        char errmsg[100];
        sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX);
        PyErr_SetString(PyExc_ValueError, errmsg);
        return -1;
      }

      if (self->buffer != NULL) {
        /* there is already a buffer */
        if (self->buffer_used != 0) {
            if (flush_character_buffer(self) < 0) {
                return -1;
            }
        }
        /* free existing buffer */
        PyMem_Free(self->buffer);
      }
      self->buffer = PyMem_Malloc(new_buffer_size);
      if (self->buffer == NULL) {
        PyErr_NoMemory();
        return -1;
      }
      self->buffer_size = new_buffer_size;
      return 0;
    }

    if (PyUnicode_CompareWithASCIIString(name, "CharacterDataHandler") == 0) {
        /* If we're changing the character data handler, flush all
         * cached data with the old handler.  Not sure there's a
         * "right" thing to do, though, but this probably won't
         * happen.
         */
        if (flush_character_buffer(self) < 0)
            return -1;
    }
    if (sethandler(self, name, v)) {
        return 0;
    }
    PyErr_SetObject(PyExc_AttributeError, name);
    return -1;
}

static int
xmlparse_traverse(xmlparseobject *op, visitproc visit, void *arg)
{
    int i;
    for (i = 0; handler_info[i].name != NULL; i++)
        Py_VISIT(op->handlers[i]);
    return 0;
}

static int
xmlparse_clear(xmlparseobject *op)
{
    clear_handlers(op, 0);
    Py_CLEAR(op->intern);
    return 0;
}

PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser");

static PyTypeObject Xmlparsetype = {
        PyVarObject_HEAD_INIT(NULL, 0)
        "pyexpat.xmlparser",            /*tp_name*/
        sizeof(xmlparseobject),         /*tp_basicsize*/
        0,                              /*tp_itemsize*/
        /* methods */
        (destructor)xmlparse_dealloc,   /*tp_dealloc*/
        (printfunc)0,           /*tp_print*/
        0,                      /*tp_getattr*/
        0,  /*tp_setattr*/
        0,                      /*tp_reserved*/
        (reprfunc)0,            /*tp_repr*/
        0,                      /*tp_as_number*/
        0,              /*tp_as_sequence*/
        0,              /*tp_as_mapping*/
        (hashfunc)0,            /*tp_hash*/
        (ternaryfunc)0,         /*tp_call*/
        (reprfunc)0,            /*tp_str*/
        (getattrofunc)xmlparse_getattro, /* tp_getattro */
        (setattrofunc)xmlparse_setattro,              /* tp_setattro */
        0,              /* tp_as_buffer */
        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
        Xmlparsetype__doc__, /* tp_doc - Documentation string */
        (traverseproc)xmlparse_traverse,        /* tp_traverse */
        (inquiry)xmlparse_clear,                /* tp_clear */
        0,                              /* tp_richcompare */
        0,                              /* tp_weaklistoffset */
        0,                              /* tp_iter */
        0,                              /* tp_iternext */
        xmlparse_methods,               /* tp_methods */
};

/* End of code for xmlparser objects */
/* -------------------------------------------------------- */

/*[clinic input]
pyexpat.ParserCreate

    encoding: str(nullable=True) = NULL
    namespace_separator: str(nullable=True) = NULL
    intern: object = NULL

Return a new XML parser object.
[clinic start generated code]*/

PyDoc_STRVAR(pyexpat_ParserCreate__doc__,
"ParserCreate($module, /, encoding=None, namespace_separator=None,\n"
"             intern=None)\n"
"--\n"
"\n"
"Return a new XML parser object.");

#define PYEXPAT_PARSERCREATE_METHODDEF    \
    {"ParserCreate", (PyCFunction)pyexpat_ParserCreate, METH_VARARGS|METH_KEYWORDS, pyexpat_ParserCreate__doc__},

static PyObject *
pyexpat_ParserCreate_impl(PyModuleDef *module, const char *encoding, const char *namespace_separator, PyObject *intern);

static PyObject *
pyexpat_ParserCreate(PyModuleDef *module, PyObject *args, PyObject *kwargs)
{
    PyObject *return_value = NULL;
    static char *_keywords[] = {"encoding", "namespace_separator", "intern", NULL};
    const char *encoding = NULL;
    const char *namespace_separator = NULL;
    PyObject *intern = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
        "|zzO:ParserCreate", _keywords,
        &encoding, &namespace_separator, &intern))
        goto exit;
    return_value = pyexpat_ParserCreate_impl(module, encoding, namespace_separator, intern);

exit:
    return return_value;
}

static PyObject *
pyexpat_ParserCreate_impl(PyModuleDef *module, const char *encoding, const char *namespace_separator, PyObject *intern)
/*[clinic end generated code: output=4fc027dd33b7a2ac input=71b9f471aa6f8f86]*/
{
    PyObject *result;
    int intern_decref = 0;

    if (namespace_separator != NULL
        && strlen(namespace_separator) > 1) {
        PyErr_SetString(PyExc_ValueError,
                        "namespace_separator must be at most one"
                        " character, omitted, or None");
        return NULL;
    }
    /* Explicitly passing None means no interning is desired.
       Not passing anything means that a new dictionary is used. */
    if (intern == Py_None)
        intern = NULL;
    else if (intern == NULL) {
        intern = PyDict_New();
        if (!intern)
            return NULL;
        intern_decref = 1;
    }
    else if (!PyDict_Check(intern)) {
        PyErr_SetString(PyExc_TypeError, "intern must be a dictionary");
        return NULL;
    }

    result = newxmlparseobject(encoding, namespace_separator, intern);
    if (intern_decref) {
        Py_DECREF(intern);
    }
    return result;
}

/*[clinic input]
pyexpat.ErrorString

    code: long
    /

Returns string error for given number.
[clinic start generated code]*/

PyDoc_STRVAR(pyexpat_ErrorString__doc__,
"ErrorString($module, code, /)\n"
"--\n"
"\n"
"Returns string error for given number.");

#define PYEXPAT_ERRORSTRING_METHODDEF    \
    {"ErrorString", (PyCFunction)pyexpat_ErrorString, METH_VARARGS, pyexpat_ErrorString__doc__},

static PyObject *
pyexpat_ErrorString_impl(PyModuleDef *module, long code);

static PyObject *
pyexpat_ErrorString(PyModuleDef *module, PyObject *args)
{
    PyObject *return_value = NULL;
    long code;

    if (!PyArg_ParseTuple(args,
        "l:ErrorString",
        &code))
        goto exit;
    return_value = pyexpat_ErrorString_impl(module, code);

exit:
    return return_value;
}

static PyObject *
pyexpat_ErrorString_impl(PyModuleDef *module, long code)
/*[clinic end generated code: output=c70f3cd82bfaf067 input=cc67de010d9e62b3]*/
{
    return Py_BuildValue("z", XML_ErrorString((int)code));
}

/* List of methods defined in the module */

static struct PyMethodDef pyexpat_methods[] = {
    PYEXPAT_PARSERCREATE_METHODDEF
    PYEXPAT_ERRORSTRING_METHODDEF
    {NULL, NULL}  /* sentinel */
};

/* Module docstring */

PyDoc_STRVAR(pyexpat_module_documentation,
"Python wrapper for Expat parser.");

/* Initialization function for the module */

#ifndef MODULE_NAME
#define MODULE_NAME "pyexpat"
#endif

#ifndef MODULE_INITFUNC
#define MODULE_INITFUNC PyInit_pyexpat
#endif

#ifndef PyMODINIT_FUNC
#   ifdef MS_WINDOWS
#       define PyMODINIT_FUNC __declspec(dllexport) void
#   else
#       define PyMODINIT_FUNC void
#   endif
#endif

PyMODINIT_FUNC MODULE_INITFUNC(void);  /* avoid compiler warnings */

static struct PyModuleDef pyexpatmodule = {
        PyModuleDef_HEAD_INIT,
        MODULE_NAME,
        pyexpat_module_documentation,
        -1,
        pyexpat_methods,
        NULL,
        NULL,
        NULL,
        NULL
};

PyMODINIT_FUNC
MODULE_INITFUNC(void)
{
    PyObject *m, *d;
    PyObject *errmod_name = PyUnicode_FromString(MODULE_NAME ".errors");
    PyObject *errors_module;
    PyObject *modelmod_name;
    PyObject *model_module;
    PyObject *sys_modules;
    PyObject *tmpnum, *tmpstr;
    PyObject *codes_dict;
    PyObject *rev_codes_dict;
    int res;
    static struct PyExpat_CAPI capi;
    PyObject *capi_object;

    if (errmod_name == NULL)
        return NULL;
    modelmod_name = PyUnicode_FromString(MODULE_NAME ".model");
    if (modelmod_name == NULL)
        return NULL;

    if (PyType_Ready(&Xmlparsetype) < 0)
        return NULL;

    /* Create the module and add the functions */
    m = PyModule_Create(&pyexpatmodule);
    if (m == NULL)
        return NULL;

    /* Add some symbolic constants to the module */
    if (ErrorObject == NULL) {
        ErrorObject = PyErr_NewException("xml.parsers.expat.ExpatError",
                                         NULL, NULL);
        if (ErrorObject == NULL)
            return NULL;
    }
    Py_INCREF(ErrorObject);
    PyModule_AddObject(m, "error", ErrorObject);
    Py_INCREF(ErrorObject);
    PyModule_AddObject(m, "ExpatError", ErrorObject);
    Py_INCREF(&Xmlparsetype);
    PyModule_AddObject(m, "XMLParserType", (PyObject *) &Xmlparsetype);

    PyModule_AddStringConstant(m, "EXPAT_VERSION",
                               XML_ExpatVersion());
    {
        XML_Expat_Version info = XML_ExpatVersionInfo();
        PyModule_AddObject(m, "version_info",
                           Py_BuildValue("(iii)", info.major,
                                         info.minor, info.micro));
    }
    /* XXX When Expat supports some way of figuring out how it was
       compiled, this should check and set native_encoding
       appropriately.
    */
    PyModule_AddStringConstant(m, "native_encoding", "UTF-8");

    sys_modules = PySys_GetObject("modules");
    d = PyModule_GetDict(m);
    errors_module = PyDict_GetItem(d, errmod_name);
    if (errors_module == NULL) {
        errors_module = PyModule_New(MODULE_NAME ".errors");
        if (errors_module != NULL) {
            PyDict_SetItem(sys_modules, errmod_name, errors_module);
            /* gives away the reference to errors_module */
            PyModule_AddObject(m, "errors", errors_module);
        }
    }
    Py_DECREF(errmod_name);
    model_module = PyDict_GetItem(d, modelmod_name);
    if (model_module == NULL) {
        model_module = PyModule_New(MODULE_NAME ".model");
        if (model_module != NULL) {
            PyDict_SetItem(sys_modules, modelmod_name, model_module);
            /* gives away the reference to model_module */
            PyModule_AddObject(m, "model", model_module);
        }
    }
    Py_DECREF(modelmod_name);
    if (errors_module == NULL || model_module == NULL)
        /* Don't core dump later! */
        return NULL;

#if XML_COMBINED_VERSION > 19505
    {
        const XML_Feature *features = XML_GetFeatureList();
        PyObject *list = PyList_New(0);
        if (list == NULL)
            /* just ignore it */
            PyErr_Clear();
        else {
            int i = 0;
            for (; features[i].feature != XML_FEATURE_END; ++i) {
                int ok;
                PyObject *item = Py_BuildValue("si", features[i].name,
                                               features[i].value);
                if (item == NULL) {
                    Py_DECREF(list);
                    list = NULL;
                    break;
                }
                ok = PyList_Append(list, item);
                Py_DECREF(item);
                if (ok < 0) {
                    PyErr_Clear();
                    break;
                }
            }
            if (list != NULL)
                PyModule_AddObject(m, "features", list);
        }
    }
#endif

    codes_dict = PyDict_New();
    rev_codes_dict = PyDict_New();
    if (codes_dict == NULL || rev_codes_dict == NULL) {
        Py_XDECREF(codes_dict);
        Py_XDECREF(rev_codes_dict);
        return NULL;
    }

#define MYCONST(name) \
    if (PyModule_AddStringConstant(errors_module, #name,               \
                                   XML_ErrorString(name)) < 0)         \
        return NULL;                                                   \
    tmpnum = PyLong_FromLong(name);                                    \
    if (tmpnum == NULL) return NULL;                                   \
    res = PyDict_SetItemString(codes_dict,                             \
                               XML_ErrorString(name), tmpnum);         \
    if (res < 0) return NULL;                                          \
    tmpstr = PyUnicode_FromString(XML_ErrorString(name));              \
    if (tmpstr == NULL) return NULL;                                   \
    res = PyDict_SetItem(rev_codes_dict, tmpnum, tmpstr);              \
    Py_DECREF(tmpstr);                                                 \
    Py_DECREF(tmpnum);                                                 \
    if (res < 0) return NULL;                                          \

    MYCONST(XML_ERROR_NO_MEMORY);
    MYCONST(XML_ERROR_SYNTAX);
    MYCONST(XML_ERROR_NO_ELEMENTS);
    MYCONST(XML_ERROR_INVALID_TOKEN);
    MYCONST(XML_ERROR_UNCLOSED_TOKEN);
    MYCONST(XML_ERROR_PARTIAL_CHAR);
    MYCONST(XML_ERROR_TAG_MISMATCH);
    MYCONST(XML_ERROR_DUPLICATE_ATTRIBUTE);
    MYCONST(XML_ERROR_JUNK_AFTER_DOC_ELEMENT);
    MYCONST(XML_ERROR_PARAM_ENTITY_REF);
    MYCONST(XML_ERROR_UNDEFINED_ENTITY);
    MYCONST(XML_ERROR_RECURSIVE_ENTITY_REF);
    MYCONST(XML_ERROR_ASYNC_ENTITY);
    MYCONST(XML_ERROR_BAD_CHAR_REF);
    MYCONST(XML_ERROR_BINARY_ENTITY_REF);
    MYCONST(XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF);
    MYCONST(XML_ERROR_MISPLACED_XML_PI);
    MYCONST(XML_ERROR_UNKNOWN_ENCODING);
    MYCONST(XML_ERROR_INCORRECT_ENCODING);
    MYCONST(XML_ERROR_UNCLOSED_CDATA_SECTION);
    MYCONST(XML_ERROR_EXTERNAL_ENTITY_HANDLING);
    MYCONST(XML_ERROR_NOT_STANDALONE);
    MYCONST(XML_ERROR_UNEXPECTED_STATE);
    MYCONST(XML_ERROR_ENTITY_DECLARED_IN_PE);
    MYCONST(XML_ERROR_FEATURE_REQUIRES_XML_DTD);
    MYCONST(XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING);
    /* Added in Expat 1.95.7. */
    MYCONST(XML_ERROR_UNBOUND_PREFIX);
    /* Added in Expat 1.95.8. */
    MYCONST(XML_ERROR_UNDECLARING_PREFIX);
    MYCONST(XML_ERROR_INCOMPLETE_PE);
    MYCONST(XML_ERROR_XML_DECL);
    MYCONST(XML_ERROR_TEXT_DECL);
    MYCONST(XML_ERROR_PUBLICID);
    MYCONST(XML_ERROR_SUSPENDED);
    MYCONST(XML_ERROR_NOT_SUSPENDED);
    MYCONST(XML_ERROR_ABORTED);
    MYCONST(XML_ERROR_FINISHED);
    MYCONST(XML_ERROR_SUSPEND_PE);

    if (PyModule_AddStringConstant(errors_module, "__doc__",
                                   "Constants used to describe "
                                   "error conditions.") < 0)
        return NULL;

    if (PyModule_AddObject(errors_module, "codes", codes_dict) < 0)
        return NULL;
    if (PyModule_AddObject(errors_module, "messages", rev_codes_dict) < 0)
        return NULL;

#undef MYCONST

#define MYCONST(c) PyModule_AddIntConstant(m, #c, c)
    MYCONST(XML_PARAM_ENTITY_PARSING_NEVER);
    MYCONST(XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE);
    MYCONST(XML_PARAM_ENTITY_PARSING_ALWAYS);
#undef MYCONST

#define MYCONST(c) PyModule_AddIntConstant(model_module, #c, c)
    PyModule_AddStringConstant(model_module, "__doc__",
                     "Constants used to interpret content model information.");

    MYCONST(XML_CTYPE_EMPTY);
    MYCONST(XML_CTYPE_ANY);
    MYCONST(XML_CTYPE_MIXED);
    MYCONST(XML_CTYPE_NAME);
    MYCONST(XML_CTYPE_CHOICE);
    MYCONST(XML_CTYPE_SEQ);

    MYCONST(XML_CQUANT_NONE);
    MYCONST(XML_CQUANT_OPT);
    MYCONST(XML_CQUANT_REP);
    MYCONST(XML_CQUANT_PLUS);
#undef MYCONST

    /* initialize pyexpat dispatch table */
    capi.size = sizeof(capi);
    capi.magic = PyExpat_CAPI_MAGIC;
    capi.MAJOR_VERSION = XML_MAJOR_VERSION;
    capi.MINOR_VERSION = XML_MINOR_VERSION;
    capi.MICRO_VERSION = XML_MICRO_VERSION;
    capi.ErrorString = XML_ErrorString;
    capi.GetErrorCode = XML_GetErrorCode;
    capi.GetErrorColumnNumber = XML_GetErrorColumnNumber;
    capi.GetErrorLineNumber = XML_GetErrorLineNumber;
    capi.Parse = XML_Parse;
    capi.ParserCreate_MM = XML_ParserCreate_MM;
    capi.ParserFree = XML_ParserFree;
    capi.SetCharacterDataHandler = XML_SetCharacterDataHandler;
    capi.SetCommentHandler = XML_SetCommentHandler;
    capi.SetDefaultHandlerExpand = XML_SetDefaultHandlerExpand;
    capi.SetElementHandler = XML_SetElementHandler;
    capi.SetNamespaceDeclHandler = XML_SetNamespaceDeclHandler;
    capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler;
    capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler;
    capi.SetUserData = XML_SetUserData;
    capi.SetStartDoctypeDeclHandler = XML_SetStartDoctypeDeclHandler;
    capi.SetEncoding = XML_SetEncoding;
    capi.DefaultUnknownEncodingHandler = PyUnknownEncodingHandler;

    /* export using capsule */
    capi_object = PyCapsule_New(&capi, PyExpat_CAPSULE_NAME, NULL);
    if (capi_object)
        PyModule_AddObject(m, "expat_CAPI", capi_object);
    return m;
}

static void
clear_handlers(xmlparseobject *self, int initial)
{
    int i = 0;
    PyObject *temp;

    for (; handler_info[i].name != NULL; i++) {
        if (initial)
            self->handlers[i] = NULL;
        else {
            temp = self->handlers[i];
            self->handlers[i] = NULL;
            Py_XDECREF(temp);
            handler_info[i].setter(self->itself, NULL);
        }
    }
}

static struct HandlerInfo handler_info[] = {
    {"StartElementHandler",
     (xmlhandlersetter)XML_SetStartElementHandler,
     (xmlhandler)my_StartElementHandler},
    {"EndElementHandler",
     (xmlhandlersetter)XML_SetEndElementHandler,
     (xmlhandler)my_EndElementHandler},
    {"ProcessingInstructionHandler",
     (xmlhandlersetter)XML_SetProcessingInstructionHandler,
     (xmlhandler)my_ProcessingInstructionHandler},
    {"CharacterDataHandler",
     (xmlhandlersetter)XML_SetCharacterDataHandler,
     (xmlhandler)my_CharacterDataHandler},
    {"UnparsedEntityDeclHandler",
     (xmlhandlersetter)XML_SetUnparsedEntityDeclHandler,
     (xmlhandler)my_UnparsedEntityDeclHandler},
    {"NotationDeclHandler",
     (xmlhandlersetter)XML_SetNotationDeclHandler,
     (xmlhandler)my_NotationDeclHandler},
    {"StartNamespaceDeclHandler",
     (xmlhandlersetter)XML_SetStartNamespaceDeclHandler,
     (xmlhandler)my_StartNamespaceDeclHandler},
    {"EndNamespaceDeclHandler",
     (xmlhandlersetter)XML_SetEndNamespaceDeclHandler,
     (xmlhandler)my_EndNamespaceDeclHandler},
    {"CommentHandler",
     (xmlhandlersetter)XML_SetCommentHandler,
     (xmlhandler)my_CommentHandler},
    {"StartCdataSectionHandler",
     (xmlhandlersetter)XML_SetStartCdataSectionHandler,
     (xmlhandler)my_StartCdataSectionHandler},
    {"EndCdataSectionHandler",
     (xmlhandlersetter)XML_SetEndCdataSectionHandler,
     (xmlhandler)my_EndCdataSectionHandler},
    {"DefaultHandler",
     (xmlhandlersetter)XML_SetDefaultHandler,
     (xmlhandler)my_DefaultHandler},
    {"DefaultHandlerExpand",
     (xmlhandlersetter)XML_SetDefaultHandlerExpand,
     (xmlhandler)my_DefaultHandlerExpandHandler},
    {"NotStandaloneHandler",
     (xmlhandlersetter)XML_SetNotStandaloneHandler,
     (xmlhandler)my_NotStandaloneHandler},
    {"ExternalEntityRefHandler",
     (xmlhandlersetter)XML_SetExternalEntityRefHandler,
     (xmlhandler)my_ExternalEntityRefHandler},
    {"StartDoctypeDeclHandler",
     (xmlhandlersetter)XML_SetStartDoctypeDeclHandler,
     (xmlhandler)my_StartDoctypeDeclHandler},
    {"EndDoctypeDeclHandler",
     (xmlhandlersetter)XML_SetEndDoctypeDeclHandler,
     (xmlhandler)my_EndDoctypeDeclHandler},
    {"EntityDeclHandler",
     (xmlhandlersetter)XML_SetEntityDeclHandler,
     (xmlhandler)my_EntityDeclHandler},
    {"XmlDeclHandler",
     (xmlhandlersetter)XML_SetXmlDeclHandler,
     (xmlhandler)my_XmlDeclHandler},
    {"ElementDeclHandler",
     (xmlhandlersetter)XML_SetElementDeclHandler,
     (xmlhandler)my_ElementDeclHandler},
    {"AttlistDeclHandler",
     (xmlhandlersetter)XML_SetAttlistDeclHandler,
     (xmlhandler)my_AttlistDeclHandler},
#if XML_COMBINED_VERSION >= 19504
    {"SkippedEntityHandler",
     (xmlhandlersetter)XML_SetSkippedEntityHandler,
     (xmlhandler)my_SkippedEntityHandler},
#endif

    {NULL, NULL, NULL} /* sentinel */
};

/*[clinic input]
dump buffer
[clinic start generated code]*/

#ifndef PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF
    #define PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF
#endif /* !defined(PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF) */
/*[clinic end generated code: output=a7880cb78bbd58ce input=524ce2e021e4eba6]*/