A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

275 рядки
7.8 KiB

  1. /*
  2. Copyright (C) 2012-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  3. Permission is hereby granted, free of charge, to any person obtaining a copy of
  4. this software and associated documentation files (the "Software"), to deal in
  5. the Software without restriction, including without limitation the rights to
  6. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  7. of the Software, and to permit persons to whom the Software is furnished to do
  8. so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in all
  10. copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. SOFTWARE.
  18. */
  19. #include "tokenizer.h"
  20. #include "tok_parse.h"
  21. #include "tokens.h"
  22. /* Globals */
  23. int route_state;
  24. uint64_t route_context;
  25. char** entitydefs;
  26. PyObject* EMPTY;
  27. PyObject* NOARGS;
  28. PyObject* definitions;
  29. static PyObject* ParserError;
  30. /* Forward declarations */
  31. static int load_exceptions(void);
  32. /*
  33. Create a new tokenizer object.
  34. */
  35. static PyObject*
  36. Tokenizer_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
  37. {
  38. Tokenizer* self = (Tokenizer*) type->tp_alloc(type, 0);
  39. return (PyObject*) self;
  40. }
  41. /*
  42. Deallocate the given tokenizer object.
  43. */
  44. static void Tokenizer_dealloc(Tokenizer* self)
  45. {
  46. Stack *this = self->topstack, *next;
  47. Py_XDECREF(self->text);
  48. while (this) {
  49. Py_DECREF(this->stack);
  50. Textbuffer_dealloc(this->textbuffer);
  51. next = this->next;
  52. free(this);
  53. this = next;
  54. }
  55. Py_TYPE(self)->tp_free((PyObject*) self);
  56. }
  57. /*
  58. Initialize a new tokenizer instance by setting instance attributes.
  59. */
  60. static int Tokenizer_init(Tokenizer* self, PyObject* args, PyObject* kwds)
  61. {
  62. static char* kwlist[] = {NULL};
  63. if (!PyArg_ParseTupleAndKeywords(args, kwds, "", kwlist))
  64. return -1;
  65. self->text = Py_None;
  66. Py_INCREF(Py_None);
  67. self->topstack = NULL;
  68. self->head = self->length = self->global = self->depth = self->cycles = 0;
  69. // TODO: should be member variables!
  70. route_state = 0;
  71. route_context = 0;
  72. return 0;
  73. }
  74. /*
  75. Build a list of tokens from a string of wikicode and return it.
  76. */
  77. static PyObject* Tokenizer_tokenize(Tokenizer* self, PyObject* args)
  78. {
  79. PyObject *text, *temp, *tokens;
  80. uint64_t context = 0;
  81. int skip_style_tags = 0;
  82. if (PyArg_ParseTuple(args, "U|ii", &text, &context, &skip_style_tags)) {
  83. Py_XDECREF(self->text);
  84. self->text = PySequence_Fast(text, "expected a sequence");
  85. }
  86. else {
  87. const char* encoded;
  88. Py_ssize_t size;
  89. /* Failed to parse a Unicode object; try a string instead. */
  90. PyErr_Clear();
  91. if (!PyArg_ParseTuple(args, "s#|ii", &encoded, &size, &context,
  92. &skip_style_tags))
  93. return NULL;
  94. temp = PyUnicode_FromStringAndSize(encoded, size);
  95. if (!text)
  96. return NULL;
  97. Py_XDECREF(self->text);
  98. text = PySequence_Fast(temp, "expected a sequence");
  99. Py_XDECREF(temp);
  100. self->text = text;
  101. }
  102. self->head = self->global = self->depth = self->cycles = 0;
  103. self->length = PyList_GET_SIZE(self->text);
  104. self->skip_style_tags = skip_style_tags;
  105. tokens = Tokenizer_parse(self, context, 1);
  106. if ((!tokens && !PyErr_Occurred()) || self->topstack) {
  107. if (!ParserError) {
  108. if (load_exceptions())
  109. return NULL;
  110. }
  111. if (BAD_ROUTE) {
  112. RESET_ROUTE();
  113. PyErr_SetString(ParserError, "C tokenizer exited with BAD_ROUTE");
  114. }
  115. else if (self->topstack)
  116. PyErr_SetString(ParserError,
  117. "C tokenizer exited with non-empty token stack");
  118. else
  119. PyErr_SetString(ParserError, "C tokenizer exited unexpectedly");
  120. return NULL;
  121. }
  122. return tokens;
  123. }
  124. static int load_entities(void)
  125. {
  126. PyObject *tempmod, *defmap, *deflist;
  127. unsigned numdefs, i;
  128. #ifdef IS_PY3K
  129. PyObject *string;
  130. #endif
  131. tempmod = PyImport_ImportModule(ENTITYDEFS_MODULE);
  132. if (!tempmod)
  133. return -1;
  134. defmap = PyObject_GetAttrString(tempmod, "entitydefs");
  135. if (!defmap)
  136. return -1;
  137. Py_DECREF(tempmod);
  138. deflist = PyDict_Keys(defmap);
  139. if (!deflist)
  140. return -1;
  141. Py_DECREF(defmap);
  142. numdefs = (unsigned) PyList_GET_SIZE(defmap);
  143. entitydefs = calloc(numdefs + 1, sizeof(char*));
  144. if (!entitydefs)
  145. return -1;
  146. for (i = 0; i < numdefs; i++) {
  147. #ifdef IS_PY3K
  148. string = PyUnicode_AsASCIIString(PyList_GET_ITEM(deflist, i));
  149. if (!string)
  150. return -1;
  151. entitydefs[i] = PyBytes_AsString(string);
  152. #else
  153. entitydefs[i] = PyBytes_AsString(PyList_GET_ITEM(deflist, i));
  154. #endif
  155. if (!entitydefs[i])
  156. return -1;
  157. }
  158. Py_DECREF(deflist);
  159. return 0;
  160. }
  161. static int load_tokens(void)
  162. {
  163. PyObject *tempmod, *tokens,
  164. *globals = PyEval_GetGlobals(),
  165. *locals = PyEval_GetLocals(),
  166. *fromlist = PyList_New(1),
  167. *modname = IMPORT_NAME_FUNC("tokens");
  168. char *name = "mwparserfromhell.parser";
  169. if (!fromlist || !modname)
  170. return -1;
  171. PyList_SET_ITEM(fromlist, 0, modname);
  172. tempmod = PyImport_ImportModuleLevel(name, globals, locals, fromlist, 0);
  173. Py_DECREF(fromlist);
  174. if (!tempmod)
  175. return -1;
  176. tokens = PyObject_GetAttrString(tempmod, "tokens");
  177. Py_DECREF(tempmod);
  178. load_tokens_from_module(tokens);
  179. Py_DECREF(tokens);
  180. return 0;
  181. }
  182. static int load_defs(void)
  183. {
  184. PyObject *tempmod,
  185. *globals = PyEval_GetGlobals(),
  186. *locals = PyEval_GetLocals(),
  187. *fromlist = PyList_New(1),
  188. *modname = IMPORT_NAME_FUNC("definitions");
  189. char *name = "mwparserfromhell";
  190. if (!fromlist || !modname)
  191. return -1;
  192. PyList_SET_ITEM(fromlist, 0, modname);
  193. tempmod = PyImport_ImportModuleLevel(name, globals, locals, fromlist, 0);
  194. Py_DECREF(fromlist);
  195. if (!tempmod)
  196. return -1;
  197. definitions = PyObject_GetAttrString(tempmod, "definitions");
  198. Py_DECREF(tempmod);
  199. return 0;
  200. }
  201. static int load_exceptions(void)
  202. {
  203. PyObject *tempmod, *parsermod,
  204. *globals = PyEval_GetGlobals(),
  205. *locals = PyEval_GetLocals(),
  206. *fromlist = PyList_New(1),
  207. *modname = IMPORT_NAME_FUNC("parser");
  208. char *name = "mwparserfromhell";
  209. if (!fromlist || !modname)
  210. return -1;
  211. PyList_SET_ITEM(fromlist, 0, modname);
  212. tempmod = PyImport_ImportModuleLevel(name, globals, locals, fromlist, 0);
  213. Py_DECREF(fromlist);
  214. if (!tempmod)
  215. return -1;
  216. parsermod = PyObject_GetAttrString(tempmod, "parser");
  217. Py_DECREF(tempmod);
  218. ParserError = PyObject_GetAttrString(parsermod, "ParserError");
  219. Py_DECREF(parsermod);
  220. return 0;
  221. }
  222. PyMODINIT_FUNC INIT_FUNC_NAME(void)
  223. {
  224. PyObject *module;
  225. TokenizerType.tp_new = PyType_GenericNew;
  226. if (PyType_Ready(&TokenizerType) < 0)
  227. INIT_ERROR;
  228. module = CREATE_MODULE;
  229. if (!module)
  230. INIT_ERROR;
  231. Py_INCREF(&TokenizerType);
  232. PyModule_AddObject(module, "CTokenizer", (PyObject*) &TokenizerType);
  233. Py_INCREF(Py_True);
  234. PyDict_SetItemString(TokenizerType.tp_dict, "USES_C", Py_True);
  235. EMPTY = PyUnicode_FromString("");
  236. NOARGS = PyTuple_New(0);
  237. if (!EMPTY || !NOARGS || load_entities() || load_tokens() || load_defs())
  238. INIT_ERROR;
  239. #ifdef IS_PY3K
  240. return module;
  241. #endif
  242. }