PageRenderTime 60ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Modules/pyexpat.c

http://unladen-swallow.googlecode.com/
C | 2192 lines | 1854 code | 209 blank | 129 comment | 379 complexity | de349d48b15df78297e2329ac8e47f20 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. #include "Python.h"
  2. #include <ctype.h>
  3. #include "frameobject.h"
  4. #include "expat.h"
  5. #include "pyexpat.h"
  6. #define XML_COMBINED_VERSION (10000*XML_MAJOR_VERSION+100*XML_MINOR_VERSION+XML_MICRO_VERSION)
  7. #ifndef PyDoc_STRVAR
  8. /*
  9. * fdrake says:
  10. * Don't change the PyDoc_STR macro definition to (str), because
  11. * '''the parentheses cause compile failures
  12. * ("non-constant static initializer" or something like that)
  13. * on some platforms (Irix?)'''
  14. */
  15. #define PyDoc_STR(str) str
  16. #define PyDoc_VAR(name) static char name[]
  17. #define PyDoc_STRVAR(name,str) PyDoc_VAR(name) = PyDoc_STR(str)
  18. #endif
  19. #if (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION < 2)
  20. /* In Python 2.0 and 2.1, disabling Unicode was not possible. */
  21. #define Py_USING_UNICODE
  22. #else
  23. #define FIX_TRACE
  24. #endif
  25. enum HandlerTypes {
  26. StartElement,
  27. EndElement,
  28. ProcessingInstruction,
  29. CharacterData,
  30. UnparsedEntityDecl,
  31. NotationDecl,
  32. StartNamespaceDecl,
  33. EndNamespaceDecl,
  34. Comment,
  35. StartCdataSection,
  36. EndCdataSection,
  37. Default,
  38. DefaultHandlerExpand,
  39. NotStandalone,
  40. ExternalEntityRef,
  41. StartDoctypeDecl,
  42. EndDoctypeDecl,
  43. EntityDecl,
  44. XmlDecl,
  45. ElementDecl,
  46. AttlistDecl,
  47. #if XML_COMBINED_VERSION >= 19504
  48. SkippedEntity,
  49. #endif
  50. _DummyDecl
  51. };
  52. static PyObject *ErrorObject;
  53. /* ----------------------------------------------------- */
  54. /* Declarations for objects of type xmlparser */
  55. typedef struct {
  56. PyObject_HEAD
  57. XML_Parser itself;
  58. int returns_unicode; /* True if Unicode strings are returned;
  59. if false, UTF-8 strings are returned */
  60. int ordered_attributes; /* Return attributes as a list. */
  61. int specified_attributes; /* Report only specified attributes. */
  62. int in_callback; /* Is a callback active? */
  63. int ns_prefixes; /* Namespace-triplets mode? */
  64. XML_Char *buffer; /* Buffer used when accumulating characters */
  65. /* NULL if not enabled */
  66. int buffer_size; /* Size of buffer, in XML_Char units */
  67. int buffer_used; /* Buffer units in use */
  68. PyObject *intern; /* Dictionary to intern strings */
  69. PyObject **handlers;
  70. } xmlparseobject;
  71. #define CHARACTER_DATA_BUFFER_SIZE 8192
  72. static PyTypeObject Xmlparsetype;
  73. typedef void (*xmlhandlersetter)(XML_Parser self, void *meth);
  74. typedef void* xmlhandler;
  75. struct HandlerInfo {
  76. const char *name;
  77. xmlhandlersetter setter;
  78. xmlhandler handler;
  79. PyCodeObject *tb_code;
  80. PyObject *nameobj;
  81. };
  82. static struct HandlerInfo handler_info[64];
  83. /* Set an integer attribute on the error object; return true on success,
  84. * false on an exception.
  85. */
  86. static int
  87. set_error_attr(PyObject *err, char *name, int value)
  88. {
  89. PyObject *v = PyInt_FromLong(value);
  90. if (v == NULL || PyObject_SetAttrString(err, name, v) == -1) {
  91. Py_XDECREF(v);
  92. return 0;
  93. }
  94. Py_DECREF(v);
  95. return 1;
  96. }
  97. /* Build and set an Expat exception, including positioning
  98. * information. Always returns NULL.
  99. */
  100. static PyObject *
  101. set_error(xmlparseobject *self, enum XML_Error code)
  102. {
  103. PyObject *err;
  104. char buffer[256];
  105. XML_Parser parser = self->itself;
  106. int lineno = XML_GetErrorLineNumber(parser);
  107. int column = XML_GetErrorColumnNumber(parser);
  108. /* There is no risk of overflowing this buffer, since
  109. even for 64-bit integers, there is sufficient space. */
  110. sprintf(buffer, "%.200s: line %i, column %i",
  111. XML_ErrorString(code), lineno, column);
  112. err = PyObject_CallFunction(ErrorObject, "s", buffer);
  113. if ( err != NULL
  114. && set_error_attr(err, "code", code)
  115. && set_error_attr(err, "offset", column)
  116. && set_error_attr(err, "lineno", lineno)) {
  117. PyErr_SetObject(ErrorObject, err);
  118. }
  119. Py_XDECREF(err);
  120. return NULL;
  121. }
  122. static int
  123. have_handler(xmlparseobject *self, int type)
  124. {
  125. PyObject *handler = self->handlers[type];
  126. return handler != NULL;
  127. }
  128. static PyObject *
  129. get_handler_name(struct HandlerInfo *hinfo)
  130. {
  131. PyObject *name = hinfo->nameobj;
  132. if (name == NULL) {
  133. name = PyString_FromString(hinfo->name);
  134. hinfo->nameobj = name;
  135. }
  136. Py_XINCREF(name);
  137. return name;
  138. }
  139. #ifdef Py_USING_UNICODE
  140. /* Convert a string of XML_Chars into a Unicode string.
  141. Returns None if str is a null pointer. */
  142. static PyObject *
  143. conv_string_to_unicode(const XML_Char *str)
  144. {
  145. /* XXX currently this code assumes that XML_Char is 8-bit,
  146. and hence in UTF-8. */
  147. /* UTF-8 from Expat, Unicode desired */
  148. if (str == NULL) {
  149. Py_INCREF(Py_None);
  150. return Py_None;
  151. }
  152. return PyUnicode_DecodeUTF8(str, strlen(str), "strict");
  153. }
  154. static PyObject *
  155. conv_string_len_to_unicode(const XML_Char *str, int len)
  156. {
  157. /* XXX currently this code assumes that XML_Char is 8-bit,
  158. and hence in UTF-8. */
  159. /* UTF-8 from Expat, Unicode desired */
  160. if (str == NULL) {
  161. Py_INCREF(Py_None);
  162. return Py_None;
  163. }
  164. return PyUnicode_DecodeUTF8((const char *)str, len, "strict");
  165. }
  166. #endif
  167. /* Convert a string of XML_Chars into an 8-bit Python string.
  168. Returns None if str is a null pointer. */
  169. static PyObject *
  170. conv_string_to_utf8(const XML_Char *str)
  171. {
  172. /* XXX currently this code assumes that XML_Char is 8-bit,
  173. and hence in UTF-8. */
  174. /* UTF-8 from Expat, UTF-8 desired */
  175. if (str == NULL) {
  176. Py_INCREF(Py_None);
  177. return Py_None;
  178. }
  179. return PyString_FromString(str);
  180. }
  181. static PyObject *
  182. conv_string_len_to_utf8(const XML_Char *str, int len)
  183. {
  184. /* XXX currently this code assumes that XML_Char is 8-bit,
  185. and hence in UTF-8. */
  186. /* UTF-8 from Expat, UTF-8 desired */
  187. if (str == NULL) {
  188. Py_INCREF(Py_None);
  189. return Py_None;
  190. }
  191. return PyString_FromStringAndSize((const char *)str, len);
  192. }
  193. /* Callback routines */
  194. static void clear_handlers(xmlparseobject *self, int initial);
  195. /* This handler is used when an error has been detected, in the hope
  196. that actual parsing can be terminated early. This will only help
  197. if an external entity reference is encountered. */
  198. static int
  199. error_external_entity_ref_handler(XML_Parser parser,
  200. const XML_Char *context,
  201. const XML_Char *base,
  202. const XML_Char *systemId,
  203. const XML_Char *publicId)
  204. {
  205. return 0;
  206. }
  207. /* Dummy character data handler used when an error (exception) has
  208. been detected, and the actual parsing can be terminated early.
  209. This is needed since character data handler can't be safely removed
  210. from within the character data handler, but can be replaced. It is
  211. used only from the character data handler trampoline, and must be
  212. used right after `flag_error()` is called. */
  213. static void
  214. noop_character_data_handler(void *userData, const XML_Char *data, int len)
  215. {
  216. /* Do nothing. */
  217. }
  218. static void
  219. flag_error(xmlparseobject *self)
  220. {
  221. clear_handlers(self, 0);
  222. XML_SetExternalEntityRefHandler(self->itself,
  223. error_external_entity_ref_handler);
  224. }
  225. static PyCodeObject*
  226. getcode(enum HandlerTypes slot, char* func_name, int lineno)
  227. {
  228. PyObject *code = NULL;
  229. PyObject *name = NULL;
  230. PyObject *nulltuple = NULL;
  231. PyObject *filename = NULL;
  232. if (handler_info[slot].tb_code == NULL) {
  233. code = PyString_FromString("");
  234. if (code == NULL)
  235. goto failed;
  236. name = PyString_FromString(func_name);
  237. if (name == NULL)
  238. goto failed;
  239. nulltuple = PyTuple_New(0);
  240. if (nulltuple == NULL)
  241. goto failed;
  242. filename = PyString_FromString(__FILE__);
  243. handler_info[slot].tb_code =
  244. PyCode_New(0, /* argcount */
  245. 0, /* nlocals */
  246. 0, /* stacksize */
  247. 0, /* flags */
  248. code, /* code */
  249. nulltuple, /* consts */
  250. nulltuple, /* names */
  251. nulltuple, /* varnames */
  252. #if PYTHON_API_VERSION >= 1010
  253. nulltuple, /* freevars */
  254. nulltuple, /* cellvars */
  255. #endif
  256. filename, /* filename */
  257. name, /* name */
  258. lineno, /* firstlineno */
  259. code /* lnotab */
  260. );
  261. if (handler_info[slot].tb_code == NULL)
  262. goto failed;
  263. Py_DECREF(code);
  264. Py_DECREF(nulltuple);
  265. Py_DECREF(filename);
  266. Py_DECREF(name);
  267. }
  268. return handler_info[slot].tb_code;
  269. failed:
  270. Py_XDECREF(code);
  271. Py_XDECREF(name);
  272. return NULL;
  273. }
  274. #ifdef FIX_TRACE
  275. static int
  276. trace_frame(PyThreadState *tstate, PyFrameObject *f, int code, PyObject *val)
  277. {
  278. int result = 0;
  279. if (!tstate->use_tracing || tstate->tracing)
  280. return 0;
  281. if (tstate->c_profilefunc != NULL) {
  282. tstate->tracing++;
  283. result = tstate->c_profilefunc(tstate->c_profileobj,
  284. f, code , val);
  285. tstate->use_tracing = ((tstate->c_tracefunc != NULL)
  286. || (tstate->c_profilefunc != NULL));
  287. tstate->tracing--;
  288. if (result)
  289. return result;
  290. }
  291. if (tstate->c_tracefunc != NULL) {
  292. tstate->tracing++;
  293. result = tstate->c_tracefunc(tstate->c_traceobj,
  294. f, code , val);
  295. tstate->use_tracing = ((tstate->c_tracefunc != NULL)
  296. || (tstate->c_profilefunc != NULL));
  297. tstate->tracing--;
  298. }
  299. return result;
  300. }
  301. static int
  302. trace_frame_exc(PyThreadState *tstate, PyFrameObject *f)
  303. {
  304. PyObject *type, *value, *traceback, *arg;
  305. int err;
  306. if (tstate->c_tracefunc == NULL)
  307. return 0;
  308. PyErr_Fetch(&type, &value, &traceback);
  309. if (value == NULL) {
  310. value = Py_None;
  311. Py_INCREF(value);
  312. }
  313. #if PY_VERSION_HEX < 0x02040000
  314. arg = Py_BuildValue("(OOO)", type, value, traceback);
  315. #else
  316. arg = PyTuple_Pack(3, type, value, traceback);
  317. #endif
  318. if (arg == NULL) {
  319. PyErr_Restore(type, value, traceback);
  320. return 0;
  321. }
  322. err = trace_frame(tstate, f, PyTrace_EXCEPTION, arg);
  323. Py_DECREF(arg);
  324. if (err == 0)
  325. PyErr_Restore(type, value, traceback);
  326. else {
  327. Py_XDECREF(type);
  328. Py_XDECREF(value);
  329. Py_XDECREF(traceback);
  330. }
  331. return err;
  332. }
  333. #endif
  334. static PyObject*
  335. call_with_frame(PyCodeObject *c, PyObject* func, PyObject* args,
  336. xmlparseobject *self)
  337. {
  338. PyThreadState *tstate = PyThreadState_GET();
  339. PyFrameObject *f;
  340. PyObject *res;
  341. if (c == NULL)
  342. return NULL;
  343. f = PyFrame_New(tstate, c, PyEval_GetGlobals(), NULL);
  344. if (f == NULL)
  345. return NULL;
  346. tstate->frame = f;
  347. #ifdef FIX_TRACE
  348. if (trace_frame(tstate, f, PyTrace_CALL, Py_None) < 0) {
  349. return NULL;
  350. }
  351. #endif
  352. res = PyEval_CallObject(func, args);
  353. if (res == NULL) {
  354. if (tstate->curexc_traceback == NULL)
  355. PyTraceBack_Here(f);
  356. XML_StopParser(self->itself, XML_FALSE);
  357. #ifdef FIX_TRACE
  358. if (trace_frame_exc(tstate, f) < 0) {
  359. return NULL;
  360. }
  361. }
  362. else {
  363. if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) {
  364. Py_XDECREF(res);
  365. res = NULL;
  366. }
  367. }
  368. #else
  369. }
  370. #endif
  371. tstate->frame = f->f_back;
  372. Py_DECREF(f);
  373. return res;
  374. }
  375. #ifndef Py_USING_UNICODE
  376. #define STRING_CONV_FUNC conv_string_to_utf8
  377. #else
  378. /* Python 2.0 and later versions, when built with Unicode support */
  379. #define STRING_CONV_FUNC (self->returns_unicode \
  380. ? conv_string_to_unicode : conv_string_to_utf8)
  381. #endif
  382. static PyObject*
  383. string_intern(xmlparseobject *self, const char* str)
  384. {
  385. PyObject *result = STRING_CONV_FUNC(str);
  386. PyObject *value;
  387. /* result can be NULL if the unicode conversion failed. */
  388. if (!result)
  389. return result;
  390. if (!self->intern)
  391. return result;
  392. value = PyDict_GetItem(self->intern, result);
  393. if (!value) {
  394. if (PyDict_SetItem(self->intern, result, result) == 0)
  395. return result;
  396. else
  397. return NULL;
  398. }
  399. Py_INCREF(value);
  400. Py_DECREF(result);
  401. return value;
  402. }
  403. /* Return 0 on success, -1 on exception.
  404. * flag_error() will be called before return if needed.
  405. */
  406. static int
  407. call_character_handler(xmlparseobject *self, const XML_Char *buffer, int len)
  408. {
  409. PyObject *args;
  410. PyObject *temp;
  411. args = PyTuple_New(1);
  412. if (args == NULL)
  413. return -1;
  414. #ifdef Py_USING_UNICODE
  415. temp = (self->returns_unicode
  416. ? conv_string_len_to_unicode(buffer, len)
  417. : conv_string_len_to_utf8(buffer, len));
  418. #else
  419. temp = conv_string_len_to_utf8(buffer, len);
  420. #endif
  421. if (temp == NULL) {
  422. Py_DECREF(args);
  423. flag_error(self);
  424. XML_SetCharacterDataHandler(self->itself,
  425. noop_character_data_handler);
  426. return -1;
  427. }
  428. PyTuple_SET_ITEM(args, 0, temp);
  429. /* temp is now a borrowed reference; consider it unused. */
  430. self->in_callback = 1;
  431. temp = call_with_frame(getcode(CharacterData, "CharacterData", __LINE__),
  432. self->handlers[CharacterData], args, self);
  433. /* temp is an owned reference again, or NULL */
  434. self->in_callback = 0;
  435. Py_DECREF(args);
  436. if (temp == NULL) {
  437. flag_error(self);
  438. XML_SetCharacterDataHandler(self->itself,
  439. noop_character_data_handler);
  440. return -1;
  441. }
  442. Py_DECREF(temp);
  443. return 0;
  444. }
  445. static int
  446. flush_character_buffer(xmlparseobject *self)
  447. {
  448. int rc;
  449. if (self->buffer == NULL || self->buffer_used == 0)
  450. return 0;
  451. rc = call_character_handler(self, self->buffer, self->buffer_used);
  452. self->buffer_used = 0;
  453. return rc;
  454. }
  455. static void
  456. my_CharacterDataHandler(void *userData, const XML_Char *data, int len)
  457. {
  458. xmlparseobject *self = (xmlparseobject *) userData;
  459. if (self->buffer == NULL)
  460. call_character_handler(self, data, len);
  461. else {
  462. if ((self->buffer_used + len) > self->buffer_size) {
  463. if (flush_character_buffer(self) < 0)
  464. return;
  465. /* handler might have changed; drop the rest on the floor
  466. * if there isn't a handler anymore
  467. */
  468. if (!have_handler(self, CharacterData))
  469. return;
  470. }
  471. if (len > self->buffer_size) {
  472. call_character_handler(self, data, len);
  473. self->buffer_used = 0;
  474. }
  475. else {
  476. memcpy(self->buffer + self->buffer_used,
  477. data, len * sizeof(XML_Char));
  478. self->buffer_used += len;
  479. }
  480. }
  481. }
  482. static void
  483. my_StartElementHandler(void *userData,
  484. const XML_Char *name, const XML_Char *atts[])
  485. {
  486. xmlparseobject *self = (xmlparseobject *)userData;
  487. if (have_handler(self, StartElement)) {
  488. PyObject *container, *rv, *args;
  489. int i, max;
  490. if (flush_character_buffer(self) < 0)
  491. return;
  492. /* Set max to the number of slots filled in atts[]; max/2 is
  493. * the number of attributes we need to process.
  494. */
  495. if (self->specified_attributes) {
  496. max = XML_GetSpecifiedAttributeCount(self->itself);
  497. }
  498. else {
  499. max = 0;
  500. while (atts[max] != NULL)
  501. max += 2;
  502. }
  503. /* Build the container. */
  504. if (self->ordered_attributes)
  505. container = PyList_New(max);
  506. else
  507. container = PyDict_New();
  508. if (container == NULL) {
  509. flag_error(self);
  510. return;
  511. }
  512. for (i = 0; i < max; i += 2) {
  513. PyObject *n = string_intern(self, (XML_Char *) atts[i]);
  514. PyObject *v;
  515. if (n == NULL) {
  516. flag_error(self);
  517. Py_DECREF(container);
  518. return;
  519. }
  520. v = STRING_CONV_FUNC((XML_Char *) atts[i+1]);
  521. if (v == NULL) {
  522. flag_error(self);
  523. Py_DECREF(container);
  524. Py_DECREF(n);
  525. return;
  526. }
  527. if (self->ordered_attributes) {
  528. PyList_SET_ITEM(container, i, n);
  529. PyList_SET_ITEM(container, i+1, v);
  530. }
  531. else if (PyDict_SetItem(container, n, v)) {
  532. flag_error(self);
  533. Py_DECREF(n);
  534. Py_DECREF(v);
  535. return;
  536. }
  537. else {
  538. Py_DECREF(n);
  539. Py_DECREF(v);
  540. }
  541. }
  542. args = string_intern(self, name);
  543. if (args != NULL)
  544. args = Py_BuildValue("(NN)", args, container);
  545. if (args == NULL) {
  546. Py_DECREF(container);
  547. return;
  548. }
  549. /* Container is now a borrowed reference; ignore it. */
  550. self->in_callback = 1;
  551. rv = call_with_frame(getcode(StartElement, "StartElement", __LINE__),
  552. self->handlers[StartElement], args, self);
  553. self->in_callback = 0;
  554. Py_DECREF(args);
  555. if (rv == NULL) {
  556. flag_error(self);
  557. return;
  558. }
  559. Py_DECREF(rv);
  560. }
  561. }
  562. #define RC_HANDLER(RC, NAME, PARAMS, INIT, PARAM_FORMAT, CONVERSION, \
  563. RETURN, GETUSERDATA) \
  564. static RC \
  565. my_##NAME##Handler PARAMS {\
  566. xmlparseobject *self = GETUSERDATA ; \
  567. PyObject *args = NULL; \
  568. PyObject *rv = NULL; \
  569. INIT \
  570. \
  571. if (have_handler(self, NAME)) { \
  572. if (flush_character_buffer(self) < 0) \
  573. return RETURN; \
  574. args = Py_BuildValue PARAM_FORMAT ;\
  575. if (!args) { flag_error(self); return RETURN;} \
  576. self->in_callback = 1; \
  577. rv = call_with_frame(getcode(NAME,#NAME,__LINE__), \
  578. self->handlers[NAME], args, self); \
  579. self->in_callback = 0; \
  580. Py_DECREF(args); \
  581. if (rv == NULL) { \
  582. flag_error(self); \
  583. return RETURN; \
  584. } \
  585. CONVERSION \
  586. Py_DECREF(rv); \
  587. } \
  588. return RETURN; \
  589. }
  590. #define VOID_HANDLER(NAME, PARAMS, PARAM_FORMAT) \
  591. RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\
  592. (xmlparseobject *)userData)
  593. #define INT_HANDLER(NAME, PARAMS, PARAM_FORMAT)\
  594. RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \
  595. rc = PyInt_AsLong(rv);, rc, \
  596. (xmlparseobject *)userData)
  597. VOID_HANDLER(EndElement,
  598. (void *userData, const XML_Char *name),
  599. ("(N)", string_intern(self, name)))
  600. VOID_HANDLER(ProcessingInstruction,
  601. (void *userData,
  602. const XML_Char *target,
  603. const XML_Char *data),
  604. ("(NO&)", string_intern(self, target), STRING_CONV_FUNC,data))
  605. VOID_HANDLER(UnparsedEntityDecl,
  606. (void *userData,
  607. const XML_Char *entityName,
  608. const XML_Char *base,
  609. const XML_Char *systemId,
  610. const XML_Char *publicId,
  611. const XML_Char *notationName),
  612. ("(NNNNN)",
  613. string_intern(self, entityName), string_intern(self, base),
  614. string_intern(self, systemId), string_intern(self, publicId),
  615. string_intern(self, notationName)))
  616. #ifndef Py_USING_UNICODE
  617. VOID_HANDLER(EntityDecl,
  618. (void *userData,
  619. const XML_Char *entityName,
  620. int is_parameter_entity,
  621. const XML_Char *value,
  622. int value_length,
  623. const XML_Char *base,
  624. const XML_Char *systemId,
  625. const XML_Char *publicId,
  626. const XML_Char *notationName),
  627. ("NiNNNNN",
  628. string_intern(self, entityName), is_parameter_entity,
  629. conv_string_len_to_utf8(value, value_length),
  630. string_intern(self, base), string_intern(self, systemId),
  631. string_intern(self, publicId),
  632. string_intern(self, notationName)))
  633. #else
  634. VOID_HANDLER(EntityDecl,
  635. (void *userData,
  636. const XML_Char *entityName,
  637. int is_parameter_entity,
  638. const XML_Char *value,
  639. int value_length,
  640. const XML_Char *base,
  641. const XML_Char *systemId,
  642. const XML_Char *publicId,
  643. const XML_Char *notationName),
  644. ("NiNNNNN",
  645. string_intern(self, entityName), is_parameter_entity,
  646. (self->returns_unicode
  647. ? conv_string_len_to_unicode(value, value_length)
  648. : conv_string_len_to_utf8(value, value_length)),
  649. string_intern(self, base), string_intern(self, systemId),
  650. string_intern(self, publicId),
  651. string_intern(self, notationName)))
  652. #endif
  653. VOID_HANDLER(XmlDecl,
  654. (void *userData,
  655. const XML_Char *version,
  656. const XML_Char *encoding,
  657. int standalone),
  658. ("(O&O&i)",
  659. STRING_CONV_FUNC,version, STRING_CONV_FUNC,encoding,
  660. standalone))
  661. static PyObject *
  662. conv_content_model(XML_Content * const model,
  663. PyObject *(*conv_string)(const XML_Char *))
  664. {
  665. PyObject *result = NULL;
  666. PyObject *children = PyTuple_New(model->numchildren);
  667. int i;
  668. if (children != NULL) {
  669. assert(model->numchildren < INT_MAX);
  670. for (i = 0; i < (int)model->numchildren; ++i) {
  671. PyObject *child = conv_content_model(&model->children[i],
  672. conv_string);
  673. if (child == NULL) {
  674. Py_XDECREF(children);
  675. return NULL;
  676. }
  677. PyTuple_SET_ITEM(children, i, child);
  678. }
  679. result = Py_BuildValue("(iiO&N)",
  680. model->type, model->quant,
  681. conv_string,model->name, children);
  682. }
  683. return result;
  684. }
  685. static void
  686. my_ElementDeclHandler(void *userData,
  687. const XML_Char *name,
  688. XML_Content *model)
  689. {
  690. xmlparseobject *self = (xmlparseobject *)userData;
  691. PyObject *args = NULL;
  692. if (have_handler(self, ElementDecl)) {
  693. PyObject *rv = NULL;
  694. PyObject *modelobj, *nameobj;
  695. if (flush_character_buffer(self) < 0)
  696. goto finally;
  697. #ifdef Py_USING_UNICODE
  698. modelobj = conv_content_model(model,
  699. (self->returns_unicode
  700. ? conv_string_to_unicode
  701. : conv_string_to_utf8));
  702. #else
  703. modelobj = conv_content_model(model, conv_string_to_utf8);
  704. #endif
  705. if (modelobj == NULL) {
  706. flag_error(self);
  707. goto finally;
  708. }
  709. nameobj = string_intern(self, name);
  710. if (nameobj == NULL) {
  711. Py_DECREF(modelobj);
  712. flag_error(self);
  713. goto finally;
  714. }
  715. args = Py_BuildValue("NN", nameobj, modelobj);
  716. if (args == NULL) {
  717. Py_DECREF(modelobj);
  718. flag_error(self);
  719. goto finally;
  720. }
  721. self->in_callback = 1;
  722. rv = call_with_frame(getcode(ElementDecl, "ElementDecl", __LINE__),
  723. self->handlers[ElementDecl], args, self);
  724. self->in_callback = 0;
  725. if (rv == NULL) {
  726. flag_error(self);
  727. goto finally;
  728. }
  729. Py_DECREF(rv);
  730. }
  731. finally:
  732. Py_XDECREF(args);
  733. XML_FreeContentModel(self->itself, model);
  734. return;
  735. }
  736. VOID_HANDLER(AttlistDecl,
  737. (void *userData,
  738. const XML_Char *elname,
  739. const XML_Char *attname,
  740. const XML_Char *att_type,
  741. const XML_Char *dflt,
  742. int isrequired),
  743. ("(NNO&O&i)",
  744. string_intern(self, elname), string_intern(self, attname),
  745. STRING_CONV_FUNC,att_type, STRING_CONV_FUNC,dflt,
  746. isrequired))
  747. #if XML_COMBINED_VERSION >= 19504
  748. VOID_HANDLER(SkippedEntity,
  749. (void *userData,
  750. const XML_Char *entityName,
  751. int is_parameter_entity),
  752. ("Ni",
  753. string_intern(self, entityName), is_parameter_entity))
  754. #endif
  755. VOID_HANDLER(NotationDecl,
  756. (void *userData,
  757. const XML_Char *notationName,
  758. const XML_Char *base,
  759. const XML_Char *systemId,
  760. const XML_Char *publicId),
  761. ("(NNNN)",
  762. string_intern(self, notationName), string_intern(self, base),
  763. string_intern(self, systemId), string_intern(self, publicId)))
  764. VOID_HANDLER(StartNamespaceDecl,
  765. (void *userData,
  766. const XML_Char *prefix,
  767. const XML_Char *uri),
  768. ("(NN)",
  769. string_intern(self, prefix), string_intern(self, uri)))
  770. VOID_HANDLER(EndNamespaceDecl,
  771. (void *userData,
  772. const XML_Char *prefix),
  773. ("(N)", string_intern(self, prefix)))
  774. VOID_HANDLER(Comment,
  775. (void *userData, const XML_Char *data),
  776. ("(O&)", STRING_CONV_FUNC,data))
  777. VOID_HANDLER(StartCdataSection,
  778. (void *userData),
  779. ("()"))
  780. VOID_HANDLER(EndCdataSection,
  781. (void *userData),
  782. ("()"))
  783. #ifndef Py_USING_UNICODE
  784. VOID_HANDLER(Default,
  785. (void *userData, const XML_Char *s, int len),
  786. ("(N)", conv_string_len_to_utf8(s,len)))
  787. VOID_HANDLER(DefaultHandlerExpand,
  788. (void *userData, const XML_Char *s, int len),
  789. ("(N)", conv_string_len_to_utf8(s,len)))
  790. #else
  791. VOID_HANDLER(Default,
  792. (void *userData, const XML_Char *s, int len),
  793. ("(N)", (self->returns_unicode
  794. ? conv_string_len_to_unicode(s,len)
  795. : conv_string_len_to_utf8(s,len))))
  796. VOID_HANDLER(DefaultHandlerExpand,
  797. (void *userData, const XML_Char *s, int len),
  798. ("(N)", (self->returns_unicode
  799. ? conv_string_len_to_unicode(s,len)
  800. : conv_string_len_to_utf8(s,len))))
  801. #endif
  802. INT_HANDLER(NotStandalone,
  803. (void *userData),
  804. ("()"))
  805. RC_HANDLER(int, ExternalEntityRef,
  806. (XML_Parser parser,
  807. const XML_Char *context,
  808. const XML_Char *base,
  809. const XML_Char *systemId,
  810. const XML_Char *publicId),
  811. int rc=0;,
  812. ("(O&NNN)",
  813. STRING_CONV_FUNC,context, string_intern(self, base),
  814. string_intern(self, systemId), string_intern(self, publicId)),
  815. rc = PyInt_AsLong(rv);, rc,
  816. XML_GetUserData(parser))
  817. /* XXX UnknownEncodingHandler */
  818. VOID_HANDLER(StartDoctypeDecl,
  819. (void *userData, const XML_Char *doctypeName,
  820. const XML_Char *sysid, const XML_Char *pubid,
  821. int has_internal_subset),
  822. ("(NNNi)", string_intern(self, doctypeName),
  823. string_intern(self, sysid), string_intern(self, pubid),
  824. has_internal_subset))
  825. VOID_HANDLER(EndDoctypeDecl, (void *userData), ("()"))
  826. /* ---------------------------------------------------------------- */
  827. static PyObject *
  828. get_parse_result(xmlparseobject *self, int rv)
  829. {
  830. if (PyErr_Occurred()) {
  831. return NULL;
  832. }
  833. if (rv == 0) {
  834. return set_error(self, XML_GetErrorCode(self->itself));
  835. }
  836. if (flush_character_buffer(self) < 0) {
  837. return NULL;
  838. }
  839. return PyInt_FromLong(rv);
  840. }
  841. PyDoc_STRVAR(xmlparse_Parse__doc__,
  842. "Parse(data[, isfinal])\n\
  843. Parse XML data. `isfinal' should be true at end of input.");
  844. static PyObject *
  845. xmlparse_Parse(xmlparseobject *self, PyObject *args)
  846. {
  847. char *s;
  848. int slen;
  849. int isFinal = 0;
  850. if (!PyArg_ParseTuple(args, "s#|i:Parse", &s, &slen, &isFinal))
  851. return NULL;
  852. return get_parse_result(self, XML_Parse(self->itself, s, slen, isFinal));
  853. }
  854. /* File reading copied from cPickle */
  855. #define BUF_SIZE 2048
  856. static int
  857. readinst(char *buf, int buf_size, PyObject *meth)
  858. {
  859. PyObject *arg = NULL;
  860. PyObject *bytes = NULL;
  861. PyObject *str = NULL;
  862. int len = -1;
  863. if ((bytes = PyInt_FromLong(buf_size)) == NULL)
  864. goto finally;
  865. if ((arg = PyTuple_New(1)) == NULL) {
  866. Py_DECREF(bytes);
  867. goto finally;
  868. }
  869. PyTuple_SET_ITEM(arg, 0, bytes);
  870. #if PY_VERSION_HEX < 0x02020000
  871. str = PyObject_CallObject(meth, arg);
  872. #else
  873. str = PyObject_Call(meth, arg, NULL);
  874. #endif
  875. if (str == NULL)
  876. goto finally;
  877. /* XXX what to do if it returns a Unicode string? */
  878. if (!PyString_Check(str)) {
  879. PyErr_Format(PyExc_TypeError,
  880. "read() did not return a string object (type=%.400s)",
  881. Py_TYPE(str)->tp_name);
  882. goto finally;
  883. }
  884. len = PyString_GET_SIZE(str);
  885. if (len > buf_size) {
  886. PyErr_Format(PyExc_ValueError,
  887. "read() returned too much data: "
  888. "%i bytes requested, %i returned",
  889. buf_size, len);
  890. goto finally;
  891. }
  892. memcpy(buf, PyString_AsString(str), len);
  893. finally:
  894. Py_XDECREF(arg);
  895. Py_XDECREF(str);
  896. return len;
  897. }
  898. PyDoc_STRVAR(xmlparse_ParseFile__doc__,
  899. "ParseFile(file)\n\
  900. Parse XML data from file-like object.");
  901. static PyObject *
  902. xmlparse_ParseFile(xmlparseobject *self, PyObject *f)
  903. {
  904. int rv = 1;
  905. FILE *fp;
  906. PyObject *readmethod = NULL;
  907. if (PyFile_Check(f)) {
  908. fp = PyFile_AsFile(f);
  909. }
  910. else {
  911. fp = NULL;
  912. readmethod = PyObject_GetAttrString(f, "read");
  913. if (readmethod == NULL) {
  914. PyErr_Clear();
  915. PyErr_SetString(PyExc_TypeError,
  916. "argument must have 'read' attribute");
  917. return NULL;
  918. }
  919. }
  920. for (;;) {
  921. int bytes_read;
  922. void *buf = XML_GetBuffer(self->itself, BUF_SIZE);
  923. if (buf == NULL) {
  924. Py_XDECREF(readmethod);
  925. return PyErr_NoMemory();
  926. }
  927. if (fp) {
  928. bytes_read = fread(buf, sizeof(char), BUF_SIZE, fp);
  929. if (bytes_read < 0) {
  930. PyErr_SetFromErrno(PyExc_IOError);
  931. return NULL;
  932. }
  933. }
  934. else {
  935. bytes_read = readinst(buf, BUF_SIZE, readmethod);
  936. if (bytes_read < 0) {
  937. Py_DECREF(readmethod);
  938. return NULL;
  939. }
  940. }
  941. rv = XML_ParseBuffer(self->itself, bytes_read, bytes_read == 0);
  942. if (PyErr_Occurred()) {
  943. Py_XDECREF(readmethod);
  944. return NULL;
  945. }
  946. if (!rv || bytes_read == 0)
  947. break;
  948. }
  949. Py_XDECREF(readmethod);
  950. return get_parse_result(self, rv);
  951. }
  952. PyDoc_STRVAR(xmlparse_SetBase__doc__,
  953. "SetBase(base_url)\n\
  954. Set the base URL for the parser.");
  955. static PyObject *
  956. xmlparse_SetBase(xmlparseobject *self, PyObject *args)
  957. {
  958. char *base;
  959. if (!PyArg_ParseTuple(args, "s:SetBase", &base))
  960. return NULL;
  961. if (!XML_SetBase(self->itself, base)) {
  962. return PyErr_NoMemory();
  963. }
  964. Py_INCREF(Py_None);
  965. return Py_None;
  966. }
  967. PyDoc_STRVAR(xmlparse_GetBase__doc__,
  968. "GetBase() -> url\n\
  969. Return base URL string for the parser.");
  970. static PyObject *
  971. xmlparse_GetBase(xmlparseobject *self, PyObject *unused)
  972. {
  973. return Py_BuildValue("z", XML_GetBase(self->itself));
  974. }
  975. PyDoc_STRVAR(xmlparse_GetInputContext__doc__,
  976. "GetInputContext() -> string\n\
  977. Return the untranslated text of the input that caused the current event.\n\
  978. If the event was generated by a large amount of text (such as a start tag\n\
  979. for an element with many attributes), not all of the text may be available.");
  980. static PyObject *
  981. xmlparse_GetInputContext(xmlparseobject *self, PyObject *unused)
  982. {
  983. if (self->in_callback) {
  984. int offset, size;
  985. const char *buffer
  986. = XML_GetInputContext(self->itself, &offset, &size);
  987. if (buffer != NULL)
  988. return PyString_FromStringAndSize(buffer + offset,
  989. size - offset);
  990. else
  991. Py_RETURN_NONE;
  992. }
  993. else
  994. Py_RETURN_NONE;
  995. }
  996. PyDoc_STRVAR(xmlparse_ExternalEntityParserCreate__doc__,
  997. "ExternalEntityParserCreate(context[, encoding])\n\
  998. Create a parser for parsing an external entity based on the\n\
  999. information passed to the ExternalEntityRefHandler.");
  1000. static PyObject *
  1001. xmlparse_ExternalEntityParserCreate(xmlparseobject *self, PyObject *args)
  1002. {
  1003. char *context;
  1004. char *encoding = NULL;
  1005. xmlparseobject *new_parser;
  1006. int i;
  1007. if (!PyArg_ParseTuple(args, "z|s:ExternalEntityParserCreate",
  1008. &context, &encoding)) {
  1009. return NULL;
  1010. }
  1011. #ifndef Py_TPFLAGS_HAVE_GC
  1012. /* Python versions 2.0 and 2.1 */
  1013. new_parser = PyObject_New(xmlparseobject, &Xmlparsetype);
  1014. #else
  1015. /* Python versions 2.2 and later */
  1016. new_parser = PyObject_GC_New(xmlparseobject, &Xmlparsetype);
  1017. #endif
  1018. if (new_parser == NULL)
  1019. return NULL;
  1020. new_parser->buffer_size = self->buffer_size;
  1021. new_parser->buffer_used = 0;
  1022. if (self->buffer != NULL) {
  1023. new_parser->buffer = malloc(new_parser->buffer_size);
  1024. if (new_parser->buffer == NULL) {
  1025. #ifndef Py_TPFLAGS_HAVE_GC
  1026. /* Code for versions 2.0 and 2.1 */
  1027. PyObject_Del(new_parser);
  1028. #else
  1029. /* Code for versions 2.2 and later. */
  1030. PyObject_GC_Del(new_parser);
  1031. #endif
  1032. return PyErr_NoMemory();
  1033. }
  1034. }
  1035. else
  1036. new_parser->buffer = NULL;
  1037. new_parser->returns_unicode = self->returns_unicode;
  1038. new_parser->ordered_attributes = self->ordered_attributes;
  1039. new_parser->specified_attributes = self->specified_attributes;
  1040. new_parser->in_callback = 0;
  1041. new_parser->ns_prefixes = self->ns_prefixes;
  1042. new_parser->itself = XML_ExternalEntityParserCreate(self->itself, context,
  1043. encoding);
  1044. new_parser->handlers = 0;
  1045. new_parser->intern = self->intern;
  1046. Py_XINCREF(new_parser->intern);
  1047. #ifdef Py_TPFLAGS_HAVE_GC
  1048. PyObject_GC_Track(new_parser);
  1049. #else
  1050. PyObject_GC_Init(new_parser);
  1051. #endif
  1052. if (!new_parser->itself) {
  1053. Py_DECREF(new_parser);
  1054. return PyErr_NoMemory();
  1055. }
  1056. XML_SetUserData(new_parser->itself, (void *)new_parser);
  1057. /* allocate and clear handlers first */
  1058. for (i = 0; handler_info[i].name != NULL; i++)
  1059. /* do nothing */;
  1060. new_parser->handlers = malloc(sizeof(PyObject *) * i);
  1061. if (!new_parser->handlers) {
  1062. Py_DECREF(new_parser);
  1063. return PyErr_NoMemory();
  1064. }
  1065. clear_handlers(new_parser, 1);
  1066. /* then copy handlers from self */
  1067. for (i = 0; handler_info[i].name != NULL; i++) {
  1068. PyObject *handler = self->handlers[i];
  1069. if (handler != NULL) {
  1070. Py_INCREF(handler);
  1071. new_parser->handlers[i] = handler;
  1072. handler_info[i].setter(new_parser->itself,
  1073. handler_info[i].handler);
  1074. }
  1075. }
  1076. return (PyObject *)new_parser;
  1077. }
  1078. PyDoc_STRVAR(xmlparse_SetParamEntityParsing__doc__,
  1079. "SetParamEntityParsing(flag) -> success\n\
  1080. Controls parsing of parameter entities (including the external DTD\n\
  1081. subset). Possible flag values are XML_PARAM_ENTITY_PARSING_NEVER,\n\
  1082. XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE and\n\
  1083. XML_PARAM_ENTITY_PARSING_ALWAYS. Returns true if setting the flag\n\
  1084. was successful.");
  1085. static PyObject*
  1086. xmlparse_SetParamEntityParsing(xmlparseobject *p, PyObject* args)
  1087. {
  1088. int flag;
  1089. if (!PyArg_ParseTuple(args, "i", &flag))
  1090. return NULL;
  1091. flag = XML_SetParamEntityParsing(p->itself, flag);
  1092. return PyInt_FromLong(flag);
  1093. }
  1094. #if XML_COMBINED_VERSION >= 19505
  1095. PyDoc_STRVAR(xmlparse_UseForeignDTD__doc__,
  1096. "UseForeignDTD([flag])\n\
  1097. Allows the application to provide an artificial external subset if one is\n\
  1098. not specified as part of the document instance. This readily allows the\n\
  1099. use of a 'default' document type controlled by the application, while still\n\
  1100. getting the advantage of providing document type information to the parser.\n\
  1101. 'flag' defaults to True if not provided.");
  1102. static PyObject *
  1103. xmlparse_UseForeignDTD(xmlparseobject *self, PyObject *args)
  1104. {
  1105. PyObject *flagobj = NULL;
  1106. XML_Bool flag = XML_TRUE;
  1107. enum XML_Error rc;
  1108. if (!PyArg_UnpackTuple(args, "UseForeignDTD", 0, 1, &flagobj))
  1109. return NULL;
  1110. if (flagobj != NULL)
  1111. flag = PyObject_IsTrue(flagobj) ? XML_TRUE : XML_FALSE;
  1112. rc = XML_UseForeignDTD(self->itself, flag);
  1113. if (rc != XML_ERROR_NONE) {
  1114. return set_error(self, rc);
  1115. }
  1116. Py_INCREF(Py_None);
  1117. return Py_None;
  1118. }
  1119. #endif
  1120. static struct PyMethodDef xmlparse_methods[] = {
  1121. {"Parse", (PyCFunction)xmlparse_Parse,
  1122. METH_VARARGS, xmlparse_Parse__doc__},
  1123. {"ParseFile", (PyCFunction)xmlparse_ParseFile,
  1124. METH_O, xmlparse_ParseFile__doc__},
  1125. {"SetBase", (PyCFunction)xmlparse_SetBase,
  1126. METH_VARARGS, xmlparse_SetBase__doc__},
  1127. {"GetBase", (PyCFunction)xmlparse_GetBase,
  1128. METH_NOARGS, xmlparse_GetBase__doc__},
  1129. {"ExternalEntityParserCreate", (PyCFunction)xmlparse_ExternalEntityParserCreate,
  1130. METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__},
  1131. {"SetParamEntityParsing", (PyCFunction)xmlparse_SetParamEntityParsing,
  1132. METH_VARARGS, xmlparse_SetParamEntityParsing__doc__},
  1133. {"GetInputContext", (PyCFunction)xmlparse_GetInputContext,
  1134. METH_NOARGS, xmlparse_GetInputContext__doc__},
  1135. #if XML_COMBINED_VERSION >= 19505
  1136. {"UseForeignDTD", (PyCFunction)xmlparse_UseForeignDTD,
  1137. METH_VARARGS, xmlparse_UseForeignDTD__doc__},
  1138. #endif
  1139. {NULL, NULL} /* sentinel */
  1140. };
  1141. /* ---------- */
  1142. #ifdef Py_USING_UNICODE
  1143. /* pyexpat international encoding support.
  1144. Make it as simple as possible.
  1145. */
  1146. static char template_buffer[257];
  1147. PyObject *template_string = NULL;
  1148. static void
  1149. init_template_buffer(void)
  1150. {
  1151. int i;
  1152. for (i = 0; i < 256; i++) {
  1153. template_buffer[i] = i;
  1154. }
  1155. template_buffer[256] = 0;
  1156. }
  1157. static int
  1158. PyUnknownEncodingHandler(void *encodingHandlerData,
  1159. const XML_Char *name,
  1160. XML_Encoding *info)
  1161. {
  1162. PyUnicodeObject *_u_string = NULL;
  1163. int result = 0;
  1164. int i;
  1165. /* Yes, supports only 8bit encodings */
  1166. _u_string = (PyUnicodeObject *)
  1167. PyUnicode_Decode(template_buffer, 256, name, "replace");
  1168. if (_u_string == NULL)
  1169. return result;
  1170. for (i = 0; i < 256; i++) {
  1171. /* Stupid to access directly, but fast */
  1172. Py_UNICODE c = _u_string->str[i];
  1173. if (c == Py_UNICODE_REPLACEMENT_CHARACTER)
  1174. info->map[i] = -1;
  1175. else
  1176. info->map[i] = c;
  1177. }
  1178. info->data = NULL;
  1179. info->convert = NULL;
  1180. info->release = NULL;
  1181. result = 1;
  1182. Py_DECREF(_u_string);
  1183. return result;
  1184. }
  1185. #endif
  1186. static PyObject *
  1187. newxmlparseobject(char *encoding, char *namespace_separator, PyObject *intern)
  1188. {
  1189. int i;
  1190. xmlparseobject *self;
  1191. #ifdef Py_TPFLAGS_HAVE_GC
  1192. /* Code for versions 2.2 and later */
  1193. self = PyObject_GC_New(xmlparseobject, &Xmlparsetype);
  1194. #else
  1195. self = PyObject_New(xmlparseobject, &Xmlparsetype);
  1196. #endif
  1197. if (self == NULL)
  1198. return NULL;
  1199. #ifdef Py_USING_UNICODE
  1200. self->returns_unicode = 1;
  1201. #else
  1202. self->returns_unicode = 0;
  1203. #endif
  1204. self->buffer = NULL;
  1205. self->buffer_size = CHARACTER_DATA_BUFFER_SIZE;
  1206. self->buffer_used = 0;
  1207. self->ordered_attributes = 0;
  1208. self->specified_attributes = 0;
  1209. self->in_callback = 0;
  1210. self->ns_prefixes = 0;
  1211. self->handlers = NULL;
  1212. if (namespace_separator != NULL) {
  1213. self->itself = XML_ParserCreateNS(encoding, *namespace_separator);
  1214. }
  1215. else {
  1216. self->itself = XML_ParserCreate(encoding);
  1217. }
  1218. self->intern = intern;
  1219. Py_XINCREF(self->intern);
  1220. #ifdef Py_TPFLAGS_HAVE_GC
  1221. PyObject_GC_Track(self);
  1222. #else
  1223. PyObject_GC_Init(self);
  1224. #endif
  1225. if (self->itself == NULL) {
  1226. PyErr_SetString(PyExc_RuntimeError,
  1227. "XML_ParserCreate failed");
  1228. Py_DECREF(self);
  1229. return NULL;
  1230. }
  1231. XML_SetUserData(self->itself, (void *)self);
  1232. #ifdef Py_USING_UNICODE
  1233. XML_SetUnknownEncodingHandler(self->itself,
  1234. (XML_UnknownEncodingHandler) PyUnknownEncodingHandler, NULL);
  1235. #endif
  1236. for (i = 0; handler_info[i].name != NULL; i++)
  1237. /* do nothing */;
  1238. self->handlers = malloc(sizeof(PyObject *) * i);
  1239. if (!self->handlers) {
  1240. Py_DECREF(self);
  1241. return PyErr_NoMemory();
  1242. }
  1243. clear_handlers(self, 1);
  1244. return (PyObject*)self;
  1245. }
  1246. static void
  1247. xmlparse_dealloc(xmlparseobject *self)
  1248. {
  1249. int i;
  1250. #ifdef Py_TPFLAGS_HAVE_GC
  1251. PyObject_GC_UnTrack(self);
  1252. #else
  1253. PyObject_GC_Fini(self);
  1254. #endif
  1255. if (self->itself != NULL)
  1256. XML_ParserFree(self->itself);
  1257. self->itself = NULL;
  1258. if (self->handlers != NULL) {
  1259. PyObject *temp;
  1260. for (i = 0; handler_info[i].name != NULL; i++) {
  1261. temp = self->handlers[i];
  1262. self->handlers[i] = NULL;
  1263. Py_XDECREF(temp);
  1264. }
  1265. free(self->handlers);
  1266. self->handlers = NULL;
  1267. }
  1268. if (self->buffer != NULL) {
  1269. free(self->buffer);
  1270. self->buffer = NULL;
  1271. }
  1272. Py_XDECREF(self->intern);
  1273. #ifndef Py_TPFLAGS_HAVE_GC
  1274. /* Code for versions 2.0 and 2.1 */
  1275. PyObject_Del(self);
  1276. #else
  1277. /* Code for versions 2.2 and later. */
  1278. PyObject_GC_Del(self);
  1279. #endif
  1280. }
  1281. static int
  1282. handlername2int(const char *name)
  1283. {
  1284. int i;
  1285. for (i = 0; handler_info[i].name != NULL; i++) {
  1286. if (strcmp(name, handler_info[i].name) == 0) {
  1287. return i;
  1288. }
  1289. }
  1290. return -1;
  1291. }
  1292. static PyObject *
  1293. get_pybool(int istrue)
  1294. {
  1295. PyObject *result = istrue ? Py_True : Py_False;
  1296. Py_INCREF(result);
  1297. return result;
  1298. }
  1299. static PyObject *
  1300. xmlparse_getattr(xmlparseobject *self, char *name)
  1301. {
  1302. int handlernum = handlername2int(name);
  1303. if (handlernum != -1) {
  1304. PyObject *result = self->handlers[handlernum];
  1305. if (result == NULL)
  1306. result = Py_None;
  1307. Py_INCREF(result);
  1308. return result;
  1309. }
  1310. if (name[0] == 'E') {
  1311. if (strcmp(name, "ErrorCode") == 0)
  1312. return PyInt_FromLong((long)
  1313. XML_GetErrorCode(self->itself));
  1314. if (strcmp(name, "ErrorLineNumber") == 0)
  1315. return PyInt_FromLong((long)
  1316. XML_GetErrorLineNumber(self->itself));
  1317. if (strcmp(name, "ErrorColumnNumber") == 0)
  1318. return PyInt_FromLong((long)
  1319. XML_GetErrorColumnNumber(self->itself));
  1320. if (strcmp(name, "ErrorByteIndex") == 0)
  1321. return PyInt_FromLong((long)
  1322. XML_GetErrorByteIndex(self->itself));
  1323. }
  1324. if (name[0] == 'C') {
  1325. if (strcmp(name, "CurrentLineNumber") == 0)
  1326. return PyInt_FromLong((long)
  1327. XML_GetCurrentLineNumber(self->itself));
  1328. if (strcmp(name, "CurrentColumnNumber") == 0)
  1329. return PyInt_FromLong((long)
  1330. XML_GetCurrentColumnNumber(self->itself));
  1331. if (strcmp(name, "CurrentByteIndex") == 0)
  1332. return PyInt_FromLong((long)
  1333. XML_GetCurrentByteIndex(self->itself));
  1334. }
  1335. if (name[0] == 'b') {
  1336. if (strcmp(name, "buffer_size") == 0)
  1337. return PyInt_FromLong((long) self->buffer_size);
  1338. if (strcmp(name, "buffer_text") == 0)
  1339. return get_pybool(self->buffer != NULL);
  1340. if (strcmp(name, "buffer_used") == 0)
  1341. return PyInt_FromLong((long) self->buffer_used);
  1342. }
  1343. if (strcmp(name, "namespace_prefixes") == 0)
  1344. return get_pybool(self->ns_prefixes);
  1345. if (strcmp(name, "ordered_attributes") == 0)
  1346. return get_pybool(self->ordered_attributes);
  1347. if (strcmp(name, "returns_unicode") == 0)
  1348. return get_pybool((long) self->returns_unicode);
  1349. if (strcmp(name, "specified_attributes") == 0)
  1350. return get_pybool((long) self->specified_attributes);
  1351. if (strcmp(name, "intern") == 0) {
  1352. if (self->intern == NULL) {
  1353. Py_INCREF(Py_None);
  1354. return Py_None;
  1355. }
  1356. else {
  1357. Py_INCREF(self->intern);
  1358. return self->intern;
  1359. }
  1360. }
  1361. #define APPEND(list, str) \
  1362. do { \
  1363. PyObject *o = PyString_FromString(str); \
  1364. if (o != NULL) \
  1365. PyList_Append(list, o); \
  1366. Py_XDECREF(o); \
  1367. } while (0)
  1368. if (strcmp(name, "__members__") == 0) {
  1369. int i;
  1370. PyObject *rc = PyList_New(0);
  1371. if (!rc)
  1372. return NULL;
  1373. for (i = 0; handler_info[i].name != NULL; i++) {
  1374. PyObject *o = get_handler_name(&handler_info[i]);
  1375. if (o != NULL)
  1376. PyList_Append(rc, o);
  1377. Py_XDECREF(o);
  1378. }
  1379. APPEND(rc, "ErrorCode");
  1380. APPEND(rc, "ErrorLineNumber");
  1381. APPEND(rc, "ErrorColumnNumber");
  1382. APPEND(rc, "ErrorByteIndex");
  1383. APPEND(rc, "CurrentLineNumber");
  1384. APPEND(rc, "CurrentColumnNumber");
  1385. APPEND(rc, "CurrentByteIndex");
  1386. APPEND(rc, "buffer_size");
  1387. APPEND(rc, "buffer_text");
  1388. APPEND(rc, "buffer_used");
  1389. APPEND(rc, "namespace_prefixes");
  1390. APPEND(rc, "ordered_attributes");
  1391. APPEND(rc, "returns_unicode");
  1392. APPEND(rc, "specified_attributes");
  1393. APPEND(rc, "intern");
  1394. #undef APPEND
  1395. return rc;
  1396. }
  1397. return Py_FindMethod(xmlparse_methods, (PyObject *)self, name);
  1398. }
  1399. static int
  1400. sethandler(xmlparseobject *self, const char *name, PyObject* v)
  1401. {
  1402. int handlernum = handlername2int(name);
  1403. if (handlernum >= 0) {
  1404. xmlhandler c_handler = NULL;
  1405. PyObject *temp = self->handlers[handlernum];
  1406. if (v == Py_None) {
  1407. /* If this is the character data handler, and a character
  1408. data handler is already active, we need to be more
  1409. careful. What we can safely do is replace the existing
  1410. character data handler callback function with a no-op
  1411. function that will refuse to call Python. The downside
  1412. is that this doesn't completely remove the character
  1413. data handler from the C layer if there's any callback
  1414. active, so Expat does a little more work than it
  1415. otherwise would, but that's really an odd case. A more
  1416. elaborate system of handlers and state could remove the
  1417. C handler more effectively. */
  1418. if (handlernum == CharacterData && self->in_callback)
  1419. c_handler = noop_character_data_handler;
  1420. v = NULL;
  1421. }
  1422. else if (v != NULL) {
  1423. Py_INCREF(v);
  1424. c_handler = handler_info[handlernum].handler;
  1425. }
  1426. self->handlers[handlernum] = v;
  1427. Py_XDECREF(temp);
  1428. handler_info[handlernum].setter(self->itself, c_handler);
  1429. return 1;
  1430. }
  1431. return 0;
  1432. }
  1433. static int
  1434. xmlparse_setattr(xmlparseobject *self, char *name, PyObject *v)
  1435. {
  1436. /* Set attribute 'name' to value 'v'. v==NULL means delete */
  1437. if (v == NULL) {
  1438. PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute");
  1439. return -1;
  1440. }
  1441. if (strcmp(name, "buffer_text") == 0) {
  1442. if (PyObject_IsTrue(v)) {
  1443. if (self->buffer == NULL) {
  1444. self->buffer = malloc(self->buffer_size);
  1445. if (self->buffer == NULL) {
  1446. PyErr_NoMemory();
  1447. return -1;
  1448. }
  1449. self->buffer_used = 0;
  1450. }
  1451. }
  1452. else if (self->buffer != NULL) {
  1453. if (flush_character_buffer(self) < 0)
  1454. return -1;
  1455. free(self->buffer);
  1456. self->buffer = NULL;
  1457. }
  1458. return 0;
  1459. }
  1460. if (strcmp(name, "namespace_prefixes") == 0) {
  1461. if (PyObject_IsTrue(v))
  1462. self->ns_prefixes = 1;
  1463. else
  1464. self->ns_prefixes = 0;
  1465. XML_SetReturnNSTriplet(self->itself, self->ns_prefixes);
  1466. return 0;
  1467. }
  1468. if (strcmp(name, "ordered_attributes") == 0) {
  1469. if (PyObject_IsTrue(v))
  1470. self->ordered_attributes = 1;
  1471. else
  1472. self->ordered_attributes = 0;
  1473. return 0;
  1474. }
  1475. if (strcmp(name, "returns_unicode") == 0) {
  1476. if (PyObject_IsTrue(v)) {
  1477. #ifndef Py_USING_UNICODE
  1478. PyErr_SetString(PyExc_ValueError,
  1479. "Unicode support not available");
  1480. return -1;
  1481. #else
  1482. self->returns_unicode = 1;
  1483. #endif
  1484. }
  1485. else
  1486. self->returns_unicode = 0;
  1487. return 0;
  1488. }
  1489. if (strcmp(name, "specified_attributes") == 0) {
  1490. if (PyObject_IsTrue(v))
  1491. self->specified_attributes = 1;
  1492. else
  1493. self->specified_attributes = 0;
  1494. return 0;
  1495. }
  1496. if (strcmp(name, "buffer_size") == 0) {
  1497. long new_buffer_size;
  1498. if (!PyInt_Check(v)) {
  1499. PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
  1500. return -1;
  1501. }
  1502. new_buffer_size=PyInt_AS_LONG(v);
  1503. /* trivial case -- no change */
  1504. if (new_buffer_size == self->buffer_size) {
  1505. return 0;
  1506. }
  1507. if (new_buffer_size <= 0) {
  1508. PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero");
  1509. return -1;
  1510. }
  1511. /* check maximum */
  1512. if (new_buffer_size > INT_MAX) {
  1513. char errmsg[100];
  1514. sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX);
  1515. PyErr_SetString(PyExc_ValueError, errmsg);
  1516. return -1;
  1517. }
  1518. if (self->buffer != NULL) {
  1519. /* there is already a buffer */
  1520. if (self->buffer_used != 0) {
  1521. flush_character_buffer(self);
  1522. }
  1523. /* free existing buffer */
  1524. free(self->buffer);
  1525. }
  1526. self->buffer = malloc(new_buffer_size);
  1527. if (self->buffer == NULL) {
  1528. PyErr_NoMemory();
  1529. return -1;
  1530. }
  1531. self->buffer_size = new_buffer_size;
  1532. return 0;
  1533. }
  1534. if (strcmp(name, "CharacterDataHandler") == 0) {
  1535. /* If we're changing the character data handler, flush all
  1536. * cached data with the old handler. Not sure there's a
  1537. * "right" thing to do, though, but this probably won't
  1538. * happen.
  1539. */
  1540. if (flush_character_buffer(self) < 0)
  1541. return -1;
  1542. }
  1543. if (sethandler(self, name, v)) {
  1544. return 0;
  1545. }
  1546. PyErr_SetString(PyExc_AttributeError, name);
  1547. return -1;
  1548. }
  1549. #ifdef WITH_CYCLE_GC
  1550. static int
  1551. xmlparse_traverse(xmlparseobject *op, visitproc visit, void *arg)
  1552. {
  1553. int i;
  1554. for (i = 0; handler_info[i].name != NULL; i++)
  1555. Py_VISIT(op->handlers[i]);
  1556. return 0;
  1557. }
  1558. static int
  1559. xmlparse_clear(xmlparseobject *op)
  1560. {
  1561. clear_handlers(op, 0);
  1562. Py_CLEAR(op->intern);
  1563. return 0;
  1564. }
  1565. #endif
  1566. PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser");
  1567. static PyTypeObject Xmlparsetype = {
  1568. PyVarObject_HEAD_INIT(NULL, 0)
  1569. "pyexpat.xmlparser", /*tp_name*/
  1570. sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/
  1571. 0, /*tp_itemsize*/
  1572. /* methods */
  1573. (destructor)xmlparse_dealloc, /*tp_dealloc*/
  1574. (printfunc)0, /*tp_print*/
  1575. (getattrfunc)xmlparse_getattr, /*tp_getattr*/
  1576. (setattrfunc)xmlparse_setattr, /*tp_setattr*/
  1577. (cmpfunc)0, /*tp_compare*/
  1578. (reprfunc)0, /*tp_repr*/
  1579. 0, /*tp_as_number*/
  1580. 0, /*tp_as_sequence*/
  1581. 0, /*tp_as_mapping*/
  1582. (hashfunc)0, /*tp_hash*/
  1583. (ternaryfunc)0, /*tp_call*/
  1584. (reprfunc)0, /*tp_str*/
  1585. 0, /* tp_getattro */
  1586. 0, /* tp_setattro */
  1587. 0, /* tp_as_buffer */
  1588. #ifdef Py_TPFLAGS_HAVE_GC
  1589. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
  1590. #else
  1591. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
  1592. #endif
  1593. Xmlparsetype__doc__, /* tp_doc - Documentation string */
  1594. #ifdef WITH_CYCLE_GC
  1595. (traverseproc)xmlparse_traverse, /* tp_traverse */
  1596. (inquiry)xmlparse_clear /* tp_clear */
  1597. #else
  1598. 0, 0
  1599. #endif
  1600. };
  1601. /* End of code for xmlparser objects */
  1602. /* -------------------------------------------------------- */
  1603. PyDoc_STRVAR(pyexpat_ParserCreate__doc__,
  1604. "ParserCreate([encoding[, namespace_separator]]) -> parser\n\
  1605. Return a new XML parser object.");
  1606. static PyObject *
  1607. pyexpat_ParserCreate(PyObject *notused, PyObject *args, PyObject *kw)
  1608. {
  1609. char *encoding = NULL;
  1610. char *namespace_separator = NULL;
  1611. PyObject *intern = NULL;
  1612. PyObject *result;
  1613. int intern_decref = 0;
  1614. static char *kwlist[] = {"encoding", "namespace_separator",
  1615. "intern", NULL};
  1616. if (!PyArg_ParseTupleAndKeywords(args, kw, "|zzO:ParserCreate", kwlist,
  1617. &encoding, &namespace_separator, &intern))
  1618. return NULL;
  1619. if (namespace_separator != NULL
  1620. && strlen(namespace_separator) > 1) {
  1621. PyErr_SetString(PyExc_ValueError,
  1622. "namespace_separator must be at most one"
  1623. " character, omitted, or None");
  1624. return NULL;
  1625. }
  1626. /* Explicitly passing None means no interning is desired.
  1627. Not passing anything means that a new dictionary is used. */
  1628. if (intern == Py_None)
  1629. intern = NULL;
  1630. else if (intern == NULL) {
  1631. intern = PyDict_New();
  1632. if (!intern)
  1633. return NULL;
  1634. intern_decref = 1;
  1635. }
  1636. else if (!PyDict_Check(intern)) {
  1637. PyErr_SetString(PyExc_TypeError, "intern must be a dictionary");
  1638. return NULL;
  1639. }
  1640. result = newxmlparseobject(encoding, namespace_separator, intern);
  1641. if (intern_decref) {
  1642. Py_DECREF(intern);
  1643. }
  1644. return result;
  1645. }
  1646. PyDoc_STRVAR(pyexpat_ErrorString__doc__,
  1647. "ErrorString(errno) -> string\n\
  1648. Returns string error for given number.");
  1649. static PyObject *
  1650. pyexpat_ErrorString(PyObject *self, PyObject *args)
  1651. {
  1652. long code = 0;
  1653. if (!PyArg_ParseTuple(args, "l:ErrorString", &code))
  1654. return NULL;
  1655. return Py_BuildValue("z", XML_ErrorString((int)code));
  1656. }
  1657. /* List of methods defined in the module */
  1658. static struct PyMethodDef pyexpat_methods[] = {
  1659. {"ParserCreate", (PyCFunction)pyexpat_ParserCreate,
  1660. METH_VARARGS|METH_KEYWORDS, pyexpat_ParserCreate__doc__},
  1661. {"ErrorString", (PyCFunction)pyexpat_ErrorString,
  1662. METH_VARARGS, pyexpat_ErrorString__doc__},
  1663. {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
  1664. };
  1665. /* Module docstring */
  1666. PyDoc_STRVAR(pyexpat_module_documentation,
  1667. "Python wrapper for Expat parser.");
  1668. /* Return a Python string that represents the version number without the
  1669. * extra cruft added by revision control, even if the right options were
  1670. * given to the "cvs export" command to make it not include the extra
  1671. * cruft.
  1672. */
  1673. static PyObject *
  1674. get_version_string(void)
  1675. {
  1676. static char *rcsid = "$Revision: 64048 $";
  1677. char *rev = rcsid;
  1678. int i = 0;
  1679. while (!isdigit(Py_CHARMASK(*rev)))
  1680. ++rev;
  1681. while (rev[i] != ' ' && rev[i] != '\0')
  1682. ++i;
  1683. return PyString_FromStringAndSize(rev, i);
  1684. }
  1685. /* Initialization function for the module */
  1686. #ifndef MODULE_NAME
  1687. #define MODULE_NAME "pyexpat"
  1688. #endif
  1689. #ifndef MODULE_INITFUNC
  1690. #define MODULE_INITFUNC initpyexpat
  1691. #endif
  1692. #ifndef PyMODINIT_FUNC
  1693. # ifdef MS_WINDOWS
  1694. # define PyMODINIT_FUNC __declspec(dllexport) void
  1695. # else
  1696. # define PyMODINIT_FUNC void
  1697. # endif
  1698. #endif
  1699. PyMODINIT_FUNC MODULE_INITFUNC(void); /* avoid compiler warnings */
  1700. PyMODINIT_FUNC
  1701. MODULE_INITFUNC(void)
  1702. {
  1703. PyObject *m, *d;
  1704. PyObject *errmod_name = PyString_FromString(MODULE_NAME ".errors");
  1705. PyObject *errors_module;
  1706. PyObject *modelmod_name;
  1707. PyObject *model_module;
  1708. PyObject *sys_modules;
  1709. static struct PyExpat_CAPI capi;
  1710. PyObject* capi_object;
  1711. if (errmod_name == NULL)
  1712. return;
  1713. modelmod_name = PyString_FromString(MODULE_NAME ".model");
  1714. if (modelmod_name == NULL)
  1715. return;
  1716. Py_TYPE(&Xmlparsetype) = &PyType_Type;
  1717. /* Create the module and add the functions */
  1718. m = Py_InitModule3(MODULE_NAME, pyexpat_methods,
  1719. pyexpat_module_documentation);
  1720. if (m == NULL)
  1721. return;
  1722. /* Add some symbolic constants to the module */
  1723. if (ErrorObject == NULL) {
  1724. ErrorObject = PyErr_NewException("xml.parsers.expat.ExpatError",
  1725. NULL, NULL);
  1726. if (ErrorObject == NULL)
  1727. return;
  1728. }
  1729. Py_INCREF(ErrorObject);
  1730. PyModule_AddObject(m, "error", ErrorObject);
  1731. Py_INCREF(ErrorObject);
  1732. PyModule_AddObject(m, "ExpatError", ErrorObject);
  1733. Py_INCREF(&Xmlparsetype);
  1734. PyModule_AddObject(m, "XMLParserType", (PyObject *) &Xmlparsetype);
  1735. PyModule_AddObject(m, "__version__", get_version_string());
  1736. PyModule_AddStringConstant(m, "EXPAT_VERSION",
  1737. (char *) XML_ExpatVersion());
  1738. {
  1739. XML_Expat_Version info = XML_ExpatVersionInfo();
  1740. PyModule_AddObject(m, "version_info",
  1741. Py_BuildValue("(iii)", info.major,
  1742. info.minor, info.micro));
  1743. }
  1744. #ifdef Py_USING_UNICODE
  1745. init_template_buffer();
  1746. #endif
  1747. /* XXX When Expat supports some way of figuring out how it was
  1748. compiled, this should check and set native_encoding
  1749. appropriately.
  1750. */
  1751. PyModule_AddStringConstant(m, "native_encoding", "UTF-8");
  1752. sys_modules = PySys_GetObject("modules");
  1753. d = PyModule_GetDict(m);
  1754. errors_module = PyDict_GetItem(d, errmod_name);
  1755. if (errors_module == NULL) {
  1756. errors_module = PyModule_New(MODULE_NAME ".errors");
  1757. if (errors_module != NULL) {
  1758. PyDict_SetItem(sys_modules, errmod_name, errors_module);
  1759. /* gives away the reference to errors_module */
  1760. PyModule_AddObject(m, "errors", errors_module);
  1761. }
  1762. }
  1763. Py_DECREF(errmod_name);
  1764. model_module = PyDict_GetItem(d, modelmod_name);
  1765. if (model_module == NULL) {
  1766. model_module = PyModule_New(MODULE_NAME ".model");
  1767. if (model_module != NULL) {
  1768. PyDict_SetItem(sys_modules, modelmod_name, model_module);
  1769. /* gives away the reference to model_module */
  1770. PyModule_AddObject(m, "model", model_module);
  1771. }
  1772. }
  1773. Py_DECREF(modelmod_name);
  1774. if (errors_module == NULL || model_module == NULL)
  1775. /* Don't core dump later! */
  1776. return;
  1777. #if XML_COMBINED_VERSION > 19505
  1778. {
  1779. const XML_Feature *features = XML_GetFeatureList();
  1780. PyObject *list = PyList_New(0);
  1781. if (list == NULL)
  1782. /* just ignore it */
  1783. PyErr_Clear();
  1784. else {
  1785. int i = 0;
  1786. for (; features[i].feature != XML_FEATURE_END; ++i) {
  1787. int ok;
  1788. PyObject *item = Py_BuildValue("si", features[i].name,
  1789. features[i].value);
  1790. if (item == NULL) {
  1791. Py_DECREF(list);
  1792. list = NULL;
  1793. break;
  1794. }
  1795. ok = PyList_Append(list, item);
  1796. Py_DECREF(item);
  1797. if (ok < 0) {
  1798. PyErr_Clear();
  1799. break;
  1800. }
  1801. }
  1802. if (list != NULL)
  1803. PyModule_AddObject(m, "features", list);
  1804. }
  1805. }
  1806. #endif
  1807. #define MYCONST(name) \
  1808. PyModule_AddStringConstant(errors_module, #name, \
  1809. (char*)XML_ErrorString(name))
  1810. MYCONST(XML_ERROR_NO_MEMORY);
  1811. MYCONST(XML_ERROR_SYNTAX);
  1812. MYCONST(XML_ERROR_NO_ELEMENTS);
  1813. MYCONST(XML_ERROR_INVALID_TOKEN);
  1814. MYCONST(XML_ERROR_UNCLOSED_TOKEN);
  1815. MYCONST(XML_ERROR_PARTIAL_CHAR);
  1816. MYCONST(XML_ERROR_TAG_MISMATCH);
  1817. MYCONST(XML_ERROR_DUPLICATE_ATTRIBUTE);
  1818. MYCONST(XML_ERROR_JUNK_AFTER_DOC_ELEMENT);
  1819. MYCONST(XML_ERROR_PARAM_ENTITY_REF);
  1820. MYCONST(XML_ERROR_UNDEFINED_ENTITY);
  1821. MYCONST(XML_ERROR_RECURSIVE_ENTITY_REF);
  1822. MYCONST(XML_ERROR_ASYNC_ENTITY);
  1823. MYCONST(XML_ERROR_BAD_CHAR_REF);
  1824. MYCONST(XML_ERROR_BINARY_ENTITY_REF);
  1825. MYCONST(XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF);
  1826. MYCONST(XML_ERROR_MISPLACED_XML_PI);
  1827. MYCONST(XML_ERROR_UNKNOWN_ENCODING);
  1828. MYCONST(XML_ERROR_INCORRECT_ENCODING);
  1829. MYCONST(XML_ERROR_UNCLOSED_CDATA_SECTION);
  1830. MYCONST(XML_ERROR_EXTERNAL_ENTITY_HANDLING);
  1831. MYCONST(XML_ERROR_NOT_STANDALONE);
  1832. MYCONST(XML_ERROR_UNEXPECTED_STATE);
  1833. MYCONST(XML_ERROR_ENTITY_DECLARED_IN_PE);
  1834. MYCONST(XML_ERROR_FEATURE_REQUIRES_XML_DTD);
  1835. MYCONST(XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING);
  1836. /* Added in Expat 1.95.7. */
  1837. MYCONST(XML_ERROR_UNBOUND_PREFIX);
  1838. /* Added in Expat 1.95.8. */
  1839. MYCONST(XML_ERROR_UNDECLARING_PREFIX);
  1840. MYCONST(XML_ERROR_INCOMPLETE_PE);
  1841. MYCONST(XML_ERROR_XML_DECL);
  1842. MYCONST(XML_ERROR_TEXT_DECL);
  1843. MYCONST(XML_ERROR_PUBLICID);
  1844. MYCONST(XML_ERROR_SUSPENDED);
  1845. MYCONST(XML_ERROR_NOT_SUSPENDED);
  1846. MYCONST(XML_ERROR_ABORTED);
  1847. MYCONST(XML_ERROR_FINISHED);
  1848. MYCONST(XML_ERROR_SUSPEND_PE);
  1849. PyModule_AddStringConstant(errors_module, "__doc__",
  1850. "Constants used to describe error conditions.");
  1851. #undef MYCONST
  1852. #define MYCONST(c) PyModule_AddIntConstant(m, #c, c)
  1853. MYCONST(XML_PARAM_ENTITY_PARSING_NEVER);
  1854. MYCONST(XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE);
  1855. MYCONST(XML_PARAM_ENTITY_PARSING_ALWAYS);
  1856. #undef MYCONST
  1857. #define MYCONST(c) PyModule_AddIntConstant(model_module, #c, c)
  1858. PyModule_AddStringConstant(model_module, "__doc__",
  1859. "Constants used to interpret content model information.");
  1860. MYCONST(XML_CTYPE_EMPTY);
  1861. MYCONST(XML_CTYPE_ANY);
  1862. MYCONST(XML_CTYPE_MIXED);
  1863. MYCONST(XML_CTYPE_NAME);
  1864. MYCONST(XML_CTYPE_CHOICE);
  1865. MYCONST(XML_CTYPE_SEQ);
  1866. MYCONST(XML_CQUANT_NONE);
  1867. MYCONST(XML_CQUANT_OPT);
  1868. MYCONST(XML_CQUANT_REP);
  1869. MYCONST(XML_CQUANT_PLUS);
  1870. #undef MYCONST
  1871. /* initialize pyexpat dispatch table */
  1872. capi.size = sizeof(capi);
  1873. capi.magic = PyExpat_CAPI_MAGIC;
  1874. capi.MAJOR_VERSION = XML_MAJOR_VERSION;
  1875. capi.MINOR_VERSION = XML_MINOR_VERSION;
  1876. capi.MICRO_VERSION = XML_MICRO_VERSION;
  1877. capi.ErrorString = XML_ErrorString;
  1878. capi.GetErrorCode = XML_GetErrorCode;
  1879. capi.GetErrorColumnNumber = XML_GetErrorColumnNumber;
  1880. capi.GetErrorLineNumber = XML_GetErrorLineNumber;
  1881. capi.Parse = XML_Parse;
  1882. capi.ParserCreate_MM = XML_ParserCreate_MM;
  1883. capi.ParserFree = XML_ParserFree;
  1884. capi.SetCharacterDataHandler = XML_SetCharacterDataHandler;
  1885. capi.SetCommentHandler = XML_SetCommentHandler;
  1886. capi.SetDefaultHandlerExpand = XML_SetDefaultHandlerExpand;
  1887. capi.SetElementHandler = XML_SetElementHandler;
  1888. capi.SetNamespaceDeclHandler = XML_SetNamespaceDeclHandler;
  1889. capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler;
  1890. capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler;
  1891. capi.SetUserData = XML_SetUserData;
  1892. /* export as cobject */
  1893. capi_object = PyCObject_FromVoidPtr(&capi, NULL);
  1894. if (capi_object)
  1895. PyModule_AddObject(m, "expat_CAPI", capi_object);
  1896. }
  1897. static void
  1898. clear_handlers(xmlparseobject *self, int initial)
  1899. {
  1900. int i = 0;
  1901. PyObject *temp;
  1902. for (; handler_info[i].name != NULL; i++) {
  1903. if (initial)
  1904. self->handlers[i] = NULL;
  1905. else {
  1906. temp = self->handlers[i];
  1907. self->handlers[i] = NULL;
  1908. Py_XDECREF(temp);
  1909. handler_info[i].setter(self->itself, NULL);
  1910. }
  1911. }
  1912. }
  1913. static struct HandlerInfo handler_info[] = {
  1914. {"StartElementHandler",
  1915. (xmlhandlersetter)XML_SetStartElementHandler,
  1916. (xmlhandler)my_StartElementHandler},
  1917. {"EndElementHandler",
  1918. (xmlhandlersetter)XML_SetEndElementHandler,
  1919. (xmlhandler)my_EndElementHandler},
  1920. {"ProcessingInstructionHandler",
  1921. (xmlhandlersetter)XML_SetProcessingInstructionHandler,
  1922. (xmlhandler)my_ProcessingInstructionHandler},
  1923. {"CharacterDataHandler",
  1924. (xmlhandlersetter)XML_SetCharacterDataHandler,
  1925. (xmlhandler)my_CharacterDataHandler},
  1926. {"UnparsedEntityDeclHandler",
  1927. (xmlhandlersetter)XML_SetUnparsedEntityDeclHandler,
  1928. (xmlhandler)my_UnparsedEntityDeclHandler},
  1929. {"NotationDeclHandler",
  1930. (xmlhandlersetter)XML_SetNotationDeclHandler,
  1931. (xmlhandler)my_NotationDeclHandler},
  1932. {"StartNamespaceDeclHandler",
  1933. (xmlhandlersetter)XML_SetStartNamespaceDeclHandler,
  1934. (xmlhandler)my_StartNamespaceDeclHandler},
  1935. {"EndNamespaceDeclHandler",
  1936. (xmlhandlersetter)XML_SetEndNamespaceDeclHandler,
  1937. (xmlhandler)my_EndNamespaceDeclHandler},
  1938. {"CommentHandler",
  1939. (xmlhandlersetter)XML_SetCommentHandler,
  1940. (xmlhandler)my_CommentHandler},
  1941. {"StartCdataSectionHandler",
  1942. (xmlhandlersetter)XML_SetStartCdataSectionHandler,
  1943. (xmlhandler)my_StartCdataSectionHandler},
  1944. {"EndCdataSectionHandler",
  1945. (xmlhandlersetter)XML_SetEndCdataSectionHandler,
  1946. (xmlhandler)my_EndCdataSectionHandler},
  1947. {"DefaultHandler",
  1948. (xmlhandlersetter)XML_SetDefaultHandler,
  1949. (xmlhandler)my_DefaultHandler},
  1950. {"DefaultHandlerExpand",
  1951. (xmlhandlersetter)XML_SetDefaultHandlerExpand,
  1952. (xmlhandler)my_DefaultHandlerExpandHandler},
  1953. {"NotStandaloneHandler",
  1954. (xmlhandlersetter)XML_SetNotStandaloneHandler,
  1955. (xmlhandler)my_NotStandaloneHandler},
  1956. {"ExternalEntityRefHandler",
  1957. (xmlhandlersetter)XML_SetExternalEntityRefHandler,
  1958. (xmlhandler)my_ExternalEntityRefHandler},
  1959. {"StartDoctypeDeclHandler",
  1960. (xmlhandlersetter)XML_SetStartDoctypeDeclHandler,
  1961. (xmlhandler)my_StartDoctypeDeclHandler},
  1962. {"EndDoctypeDeclHandler",
  1963. (xmlhandlersetter)XML_SetEndDoctypeDeclHandler,
  1964. (xmlhandler)my_EndDoctypeDeclHandler},
  1965. {"EntityDeclHandler",
  1966. (xmlhandlersetter)XML_SetEntityDeclHandler,
  1967. (xmlhandler)my_EntityDeclHandler},
  1968. {"XmlDeclHandler",
  1969. (xmlhandlersetter)XML_SetXmlDeclHandler,
  1970. (xmlhandler)my_XmlDeclHandler},
  1971. {"ElementDeclHandler",
  1972. (xmlhandlersetter)XML_SetElementDeclHandler,
  1973. (xmlhandler)my_ElementDeclHandler},
  1974. {"AttlistDeclHandler",
  1975. (xmlhandlersetter)XML_SetAttlistDeclHandler,
  1976. (xmlhandler)my_AttlistDeclHandler},
  1977. #if XML_COMBINED_VERSION >= 19504
  1978. {"SkippedEntityHandler",
  1979. (xmlhandlersetter)XML_SetSkippedEntityHandler,
  1980. (xmlhandler)my_SkippedEntityHandler},
  1981. #endif
  1982. {NULL, NULL, NULL} /* sentinel */
  1983. };