A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

323 lines
9.8 KiB

  1. /*
  2. Tokenizer for MWParserFromHell
  3. Copyright (C) 2012 Ben Kurtovic <ben.kurtovic@verizon.net>
  4. Permission is hereby granted, free of charge, to any person obtaining a copy of
  5. this software and associated documentation files (the "Software"), to deal in
  6. the Software without restriction, including without limitation the rights to
  7. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  8. of the Software, and to permit persons to whom the Software is furnished to do
  9. so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. */
  20. #ifndef PY_SSIZE_T_CLEAN
  21. #define PY_SSIZE_T_CLEAN
  22. #endif
  23. #include <Python.h>
  24. #include "structmember.h"
  25. static const Py_UNICODE* OUT_OF_BOUNDS = "";
  26. static const Py_UNICODE* MARKERS[] = {"{", "}", "[", "]", "<", ">", "|", "=",
  27. "&", "#", "*", ";", ":", "/", "-", "!",
  28. "\n", OUT_OF_BOUNDS};
  29. static PyMethodDef
  30. module_methods[] = {
  31. {NULL}
  32. };
  33. typedef struct {
  34. PyObject_HEAD
  35. PyObject* text; /* text to tokenize */
  36. PyObject* stacks; /* token stacks */
  37. PyObject* topstack; /* topmost stack */
  38. Py_ssize_t head; /* current position in text */
  39. Py_ssize_t length; /* length of text */
  40. Py_ssize_t global; /* global context */
  41. } Tokenizer;
  42. static PyObject*
  43. Tokenizer_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
  44. {
  45. Tokenizer *self;
  46. self = (Tokenizer*) type->tp_alloc(type, 0);
  47. if (self != NULL) {
  48. self->text = Py_None;
  49. Py_INCREF(Py_None);
  50. self->stacks = PyList_New(0);
  51. if (self->stacks == NULL) {
  52. Py_DECREF(self);
  53. return NULL;
  54. }
  55. self->head = 0;
  56. self->length = 0;
  57. self->global = 0;
  58. }
  59. return (PyObject*) self;
  60. }
  61. static void
  62. Tokenizer_dealloc(Tokenizer* self)
  63. {
  64. Py_XDECREF(self->text);
  65. Py_XDECREF(self->stacks);
  66. Py_XDECREF(self->topstack);
  67. self->ob_type->tp_free((PyObject*) self);
  68. }
  69. static int
  70. Tokenizer_init(Tokenizer* self, PyObject* args, PyObject* kwds)
  71. {
  72. static char* kwlist[] = {NULL};
  73. if (!PyArg_ParseTupleAndKeywords(args, kwds, "", kwlist))
  74. return -1;
  75. return 0;
  76. }
  77. #define Tokenizer_STACK(self) PyList_GET_ITEM(self->topstack, 0)
  78. #define Tokenizer_CONTEXT(self) PyList_GET_ITEM(self->topstack, 1)
  79. #define Tokenizer_TEXTBUFFER(self) PyList_GET_ITEM(self->topstack, 2)
  80. static int
  81. Tokenizer_set_context(Tokenizer* self, Py_ssize_t value)
  82. {
  83. if (PyList_SetItem(self->topstack, 1, PyInt_FromSsize_t(value)))
  84. return -1;
  85. return 0;
  86. }
  87. static int
  88. Tokenizer_set_textbuffer(Tokenizer* self, PyObject* value)
  89. {
  90. if (PyList_SetItem(self->topstack, 2, value))
  91. return -1;
  92. return 0;
  93. }
  94. /*
  95. Add a new token stack, context, and textbuffer to the list.
  96. */
  97. static int
  98. Tokenizer_push(Tokenizer* self, int context)
  99. {
  100. PyObject* top = PyList_New(3);
  101. PyList_SET_ITEM(top, 0, PyList_New(0));
  102. PyList_SET_ITEM(top, 1, PyInt_FromSsize_t(0));
  103. PyList_SET_ITEM(top, 2, PyList_New(0));
  104. Py_XDECREF(self->topstack);
  105. self->topstack = top;
  106. if (PyList_Append(self->stacks, top))
  107. return -1;
  108. return 0;
  109. }
  110. /*
  111. Push the textbuffer onto the stack as a Text node and clear it.
  112. */
  113. static int
  114. Tokenizer_push_textbuffer(Tokenizer* self)
  115. {
  116. if (PyList_GET_SIZE(Tokenizer_TEXTBUFFER(self)) > 0) {
  117. PyObject* text;
  118. // tokens.Text(text="".join(self._textbuffer))
  119. if (PyList_Append(Tokenizer_STACK(self), text)
  120. return -1;
  121. if (Tokenizer_set_textbuffer(self, PyList_New(0)))
  122. return -1;
  123. return 0;
  124. }
  125. }
  126. /*
  127. Pop the current stack/context/textbuffer, returing the stack.
  128. */
  129. static PyObject*
  130. Tokenizer_pop(Tokenizer* self)
  131. {
  132. if (Tokenizer_push_textbuffer(self))
  133. return NULL;
  134. self->stacks // POP!?
  135. }
  136. /*
  137. Pop the current stack/context/textbuffer, returing the stack. We will also
  138. replace the underlying stack's context with the current stack's.
  139. */
  140. static PyObject*
  141. Tokenizer_pop_keeping_context(Tokenizer* self)
  142. {
  143. if (Tokenizer_push_textbuffer(self))
  144. return NULL;
  145. }
  146. /*
  147. Read the value at a relative point in the wikicode.
  148. */
  149. static Py_UNICODE*
  150. Tokenizer_read(Tokenizer* self, Py_ssize_t delta)
  151. {
  152. Py_ssize_t index = self->head + delta;
  153. if (index >= self->length) {
  154. return OUT_OF_BOUNDS;
  155. }
  156. PyObject* item = PySequence_Fast_GET_ITEM(self->text, index);
  157. return PyUnicode_AS_UNICODE(item);
  158. }
  159. /*
  160. Parse the wikicode string, using *context* for when to stop.
  161. */
  162. static PyObject*
  163. Tokenizer_parse(Tokenizer* self, int context)
  164. {
  165. Py_UNICODE* this;
  166. Tokenizer_push(self, context);
  167. while (1) {
  168. this = Tokenizer_read(self, 0);
  169. if (this not in MARKERS) {
  170. WRITE TEXT
  171. }
  172. if (this == OUT_OF_BOUNDS) {
  173. return Tokenizer_push(self);
  174. }
  175. printf("%p %i %c\n", this, *this, *this);
  176. self->head++;
  177. }
  178. }
  179. /*
  180. Build a list of tokens from a string of wikicode and return it.
  181. */
  182. static PyObject*
  183. Tokenizer_tokenize(Tokenizer* self, PyObject *args)
  184. {
  185. PyObject* text;
  186. if (!PyArg_ParseTuple(args, "U", &text)) {
  187. /* Failed to parse a Unicode object; try a string instead. */
  188. PyErr_Clear();
  189. const char* encoded;
  190. Py_ssize_t size;
  191. if (!PyArg_ParseTuple(args, "s#", &encoded, &size)) {
  192. return NULL;
  193. }
  194. PyObject* temp;
  195. temp = PyUnicode_FromStringAndSize(encoded, size);
  196. if (text == NULL)
  197. return NULL;
  198. Py_XDECREF(self->text);
  199. text = PySequence_Fast(temp, "expected a sequence");
  200. Py_XDECREF(temp);
  201. self->text = text;
  202. }
  203. else {
  204. Py_XDECREF(self->text);
  205. self->text = PySequence_Fast(text, "expected a sequence");
  206. }
  207. self->length = PySequence_Length(self->text);
  208. return Tokenizer_parse(self, 0);
  209. }
  210. static PyMethodDef
  211. Tokenizer_methods[] = {
  212. {"tokenize", (PyCFunction) Tokenizer_tokenize, METH_VARARGS,
  213. "Build a list of tokens from a string of wikicode and return it."},
  214. {NULL}
  215. };
  216. static PyMemberDef
  217. Tokenizer_members[] = {
  218. {NULL}
  219. };
  220. static PyTypeObject
  221. TokenizerType = {
  222. PyObject_HEAD_INIT(NULL)
  223. 0, /* ob_size */
  224. "_tokenizer.CTokenizer", /* tp_name */
  225. sizeof(Tokenizer), /* tp_basicsize */
  226. 0, /* tp_itemsize */
  227. (destructor) Tokenizer_dealloc, /* tp_dealloc */
  228. 0, /* tp_print */
  229. 0, /* tp_getattr */
  230. 0, /* tp_setattr */
  231. 0, /* tp_compare */
  232. 0, /* tp_repr */
  233. 0, /* tp_as_number */
  234. 0, /* tp_as_sequence */
  235. 0, /* tp_as_mapping */
  236. 0, /* tp_hash */
  237. 0, /* tp_call */
  238. 0, /* tp_str */
  239. 0, /* tp_getattro */
  240. 0, /* tp_setattro */
  241. 0, /* tp_as_buffer */
  242. Py_TPFLAGS_DEFAULT, /* tp_flags */
  243. "Creates a list of tokens from a string of wikicode.", /* tp_doc */
  244. 0, /* tp_traverse */
  245. 0, /* tp_clear */
  246. 0, /* tp_richcompare */
  247. 0, /* tp_weaklistoffset */
  248. 0, /* tp_iter */
  249. 0, /* tp_iternext */
  250. Tokenizer_methods, /* tp_methods */
  251. Tokenizer_members, /* tp_members */
  252. 0, /* tp_getset */
  253. 0, /* tp_base */
  254. 0, /* tp_dict */
  255. 0, /* tp_descr_get */
  256. 0, /* tp_descr_set */
  257. 0, /* tp_dictoffset */
  258. (initproc) Tokenizer_init, /* tp_init */
  259. 0, /* tp_alloc */
  260. Tokenizer_new, /* tp_new */
  261. };
  262. PyMODINIT_FUNC
  263. init_tokenizer(void)
  264. {
  265. PyObject* module;
  266. TokenizerType.tp_new = PyType_GenericNew;
  267. if (PyType_Ready(&TokenizerType) < 0)
  268. return;
  269. module = Py_InitModule("_tokenizer", module_methods);
  270. Py_INCREF(&TokenizerType);
  271. PyModule_AddObject(module, "CTokenizer", (PyObject*) &TokenizerType);
  272. }