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.
 
 
 
 

401 lines
12 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. #define PU (Py_UNICODE*)
  26. static const Py_UNICODE* OUT_OF_BOUNDS = PU"";
  27. static const Py_UNICODE* MARKERS[] = {PU"{", PU"}", PU"[", PU"]", PU"<", PU">",
  28. PU"|", PU"=", PU"&", PU"#", PU"*", PU";",
  29. PU":", PU"/", PU"-", PU"!", PU"\n", PU""};
  30. #undef PU
  31. static PyObject* contexts;
  32. static PyObject* tokens;
  33. static PyMethodDef
  34. module_methods[] = {
  35. {NULL}
  36. };
  37. typedef struct {
  38. PyObject_HEAD
  39. PyObject* text; /* text to tokenize */
  40. PyObject* stacks; /* token stacks */
  41. PyObject* topstack; /* topmost stack */
  42. Py_ssize_t head; /* current position in text */
  43. Py_ssize_t length; /* length of text */
  44. Py_ssize_t global; /* global context */
  45. } Tokenizer;
  46. static PyObject*
  47. Tokenizer_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
  48. {
  49. Tokenizer *self;
  50. self = (Tokenizer*) type->tp_alloc(type, 0);
  51. if (self != NULL) {
  52. self->text = Py_None;
  53. Py_INCREF(Py_None);
  54. self->stacks = PyList_New(0);
  55. if (!self->stacks) {
  56. Py_DECREF(self);
  57. return NULL;
  58. }
  59. self->head = 0;
  60. self->length = 0;
  61. self->global = 0;
  62. }
  63. return (PyObject*) self;
  64. }
  65. static void
  66. Tokenizer_dealloc(Tokenizer* self)
  67. {
  68. Py_XDECREF(self->text);
  69. Py_XDECREF(self->stacks);
  70. Py_XDECREF(self->topstack);
  71. self->ob_type->tp_free((PyObject*) self);
  72. }
  73. static int
  74. Tokenizer_init(Tokenizer* self, PyObject* args, PyObject* kwds)
  75. {
  76. static char* kwlist[] = {NULL};
  77. if (!PyArg_ParseTupleAndKeywords(args, kwds, "", kwlist))
  78. return -1;
  79. return 0;
  80. }
  81. #define Tokenizer_STACK(self) PySequence_Fast_GET_ITEM(self->topstack, 0)
  82. #define Tokenizer_CONTEXT(self) PySequence_Fast_GET_ITEM(self->topstack, 1)
  83. #define Tokenizer_TEXTBUFFER(self) PySequence_Fast_GET_ITEM(self->topstack, 2)
  84. static int
  85. Tokenizer_set_context(Tokenizer* self, Py_ssize_t value)
  86. {
  87. if (PyList_SetItem(self->topstack, 1, PyInt_FromSsize_t(value)))
  88. return -1;
  89. return 0;
  90. }
  91. static int
  92. Tokenizer_set_textbuffer(Tokenizer* self, PyObject* value)
  93. {
  94. if (PyList_SetItem(self->topstack, 2, value))
  95. return -1;
  96. return 0;
  97. }
  98. /*
  99. Add a new token stack, context, and textbuffer to the list.
  100. */
  101. static int
  102. Tokenizer_push(Tokenizer* self, int context)
  103. {
  104. PyObject* top = PyList_New(3);
  105. PyList_SET_ITEM(top, 0, PyList_New(0));
  106. PyList_SET_ITEM(top, 1, PyInt_FromSsize_t(0));
  107. PyList_SET_ITEM(top, 2, PyList_New(0));
  108. Py_XDECREF(self->topstack);
  109. self->topstack = top;
  110. if (PyList_Append(self->stacks, top))
  111. return -1;
  112. return 0;
  113. }
  114. /*
  115. Push the textbuffer onto the stack as a Text node and clear it.
  116. */
  117. static int
  118. Tokenizer_push_textbuffer(Tokenizer* self)
  119. {
  120. if (PySequence_Fast_GET_SIZE(Tokenizer_TEXTBUFFER(self)) > 0) {
  121. PyObject* sep = PyUnicode_FromString("");
  122. if (!sep) return -1;
  123. PyObject* text = PyUnicode_Join(sep, Tokenizer_TEXTBUFFER(self));
  124. Py_DECREF(sep);
  125. if (!text) return -1;
  126. PyObject* klass = PyObject_GetAttrString(tokens, "Text");
  127. if (!klass) return -1;
  128. PyObject* args = PyTuple_New(0);
  129. if (!args) return -1;
  130. PyObject* kwargs = PyDict_New();
  131. if (!kwargs) return -1;
  132. PyDict_SetItemString(kwargs, "text", text);
  133. Py_DECREF(text);
  134. PyObject* token = PyInstance_New(klass, args, kwargs);
  135. if (!token) {
  136. Py_DECREF(klass);
  137. Py_DECREF(args);
  138. Py_DECREF(kwargs);
  139. return -1;
  140. }
  141. Py_DECREF(klass);
  142. Py_DECREF(args);
  143. Py_DECREF(kwargs);
  144. if (PyList_Append(Tokenizer_STACK(self), token)) {
  145. Py_XDECREF(token);
  146. return -1;
  147. }
  148. Py_XDECREF(token);
  149. if (Tokenizer_set_textbuffer(self, PyList_New(0)))
  150. return -1;
  151. }
  152. return 0;
  153. }
  154. static int
  155. Tokenizer_delete_top_of_stack(Tokenizer* self)
  156. {
  157. if (PySequence_DelItem(self->stacks, -1))
  158. return -1;
  159. Py_DECREF(self->topstack);
  160. Py_ssize_t size = PySequence_Fast_GET_SIZE(self->stacks);
  161. if (size > 0) {
  162. PyObject* top = PySequence_Fast_GET_ITEM(self->stacks, size - 1);
  163. self->topstack = top;
  164. Py_INCREF(top);
  165. }
  166. else {
  167. self->topstack = NULL;
  168. }
  169. return 0;
  170. }
  171. /*
  172. Pop the current stack/context/textbuffer, returing the stack.
  173. */
  174. static PyObject*
  175. Tokenizer_pop(Tokenizer* self)
  176. {
  177. if (Tokenizer_push_textbuffer(self))
  178. return NULL;
  179. PyObject* stack = Tokenizer_STACK(self);
  180. Py_INCREF(stack);
  181. if (Tokenizer_delete_top_of_stack(self))
  182. return NULL;
  183. return stack;
  184. }
  185. /*
  186. Pop the current stack/context/textbuffer, returing the stack. We will also
  187. replace the underlying stack's context with the current stack's.
  188. */
  189. static PyObject*
  190. Tokenizer_pop_keeping_context(Tokenizer* self)
  191. {
  192. if (Tokenizer_push_textbuffer(self))
  193. return NULL;
  194. PyObject* stack = Tokenizer_STACK(self);
  195. PyObject* context = Tokenizer_CONTEXT(self);
  196. Py_INCREF(stack);
  197. Py_INCREF(context);
  198. if (Tokenizer_delete_top_of_stack(self))
  199. return NULL;
  200. if (PyList_SetItem(self->topstack, 1, context))
  201. return NULL;
  202. return stack;
  203. }
  204. /*
  205. Read the value at a relative point in the wikicode.
  206. */
  207. static Py_UNICODE*
  208. Tokenizer_read(Tokenizer* self, Py_ssize_t delta)
  209. {
  210. Py_ssize_t index = self->head + delta;
  211. if (index >= self->length) {
  212. return (Py_UNICODE*) OUT_OF_BOUNDS;
  213. }
  214. PyObject* item = PySequence_Fast_GET_ITEM(self->text, index);
  215. return PyUnicode_AS_UNICODE(item);
  216. }
  217. /*
  218. Parse the wikicode string, using *context* for when to stop.
  219. */
  220. static PyObject*
  221. Tokenizer_parse(Tokenizer* self, int context)
  222. {
  223. Py_UNICODE* this;
  224. Tokenizer_push(self, context);
  225. while (1) {
  226. this = Tokenizer_read(self, 0);
  227. /* if (this not in MARKERS) {
  228. WRITE TEXT
  229. } */
  230. if (this == OUT_OF_BOUNDS) {
  231. return Tokenizer_pop(self);
  232. }
  233. printf("%p %i %c\n", this, *this, *this);
  234. self->head++;
  235. }
  236. }
  237. /*
  238. Build a list of tokens from a string of wikicode and return it.
  239. */
  240. static PyObject*
  241. Tokenizer_tokenize(Tokenizer* self, PyObject *args)
  242. {
  243. PyObject* text;
  244. if (!PyArg_ParseTuple(args, "U", &text)) {
  245. /* Failed to parse a Unicode object; try a string instead. */
  246. PyErr_Clear();
  247. const char* encoded;
  248. Py_ssize_t size;
  249. if (!PyArg_ParseTuple(args, "s#", &encoded, &size)) {
  250. return NULL;
  251. }
  252. PyObject* temp;
  253. temp = PyUnicode_FromStringAndSize(encoded, size);
  254. if (!text)
  255. return NULL;
  256. Py_XDECREF(self->text);
  257. text = PySequence_Fast(temp, "expected a sequence");
  258. Py_XDECREF(temp);
  259. self->text = text;
  260. }
  261. else {
  262. Py_XDECREF(self->text);
  263. self->text = PySequence_Fast(text, "expected a sequence");
  264. }
  265. self->length = PySequence_Length(self->text);
  266. return Tokenizer_parse(self, 0);
  267. }
  268. static PyMethodDef
  269. Tokenizer_methods[] = {
  270. {"tokenize", (PyCFunction) Tokenizer_tokenize, METH_VARARGS,
  271. "Build a list of tokens from a string of wikicode and return it."},
  272. {NULL}
  273. };
  274. static PyMemberDef
  275. Tokenizer_members[] = {
  276. {NULL}
  277. };
  278. static PyTypeObject
  279. TokenizerType = {
  280. PyObject_HEAD_INIT(NULL)
  281. 0, /* ob_size */
  282. "_tokenizer.CTokenizer", /* tp_name */
  283. sizeof(Tokenizer), /* tp_basicsize */
  284. 0, /* tp_itemsize */
  285. (destructor) Tokenizer_dealloc, /* tp_dealloc */
  286. 0, /* tp_print */
  287. 0, /* tp_getattr */
  288. 0, /* tp_setattr */
  289. 0, /* tp_compare */
  290. 0, /* tp_repr */
  291. 0, /* tp_as_number */
  292. 0, /* tp_as_sequence */
  293. 0, /* tp_as_mapping */
  294. 0, /* tp_hash */
  295. 0, /* tp_call */
  296. 0, /* tp_str */
  297. 0, /* tp_getattro */
  298. 0, /* tp_setattro */
  299. 0, /* tp_as_buffer */
  300. Py_TPFLAGS_DEFAULT, /* tp_flags */
  301. "Creates a list of tokens from a string of wikicode.", /* tp_doc */
  302. 0, /* tp_traverse */
  303. 0, /* tp_clear */
  304. 0, /* tp_richcompare */
  305. 0, /* tp_weaklistoffset */
  306. 0, /* tp_iter */
  307. 0, /* tp_iternext */
  308. Tokenizer_methods, /* tp_methods */
  309. Tokenizer_members, /* tp_members */
  310. 0, /* tp_getset */
  311. 0, /* tp_base */
  312. 0, /* tp_dict */
  313. 0, /* tp_descr_get */
  314. 0, /* tp_descr_set */
  315. 0, /* tp_dictoffset */
  316. (initproc) Tokenizer_init, /* tp_init */
  317. 0, /* tp_alloc */
  318. Tokenizer_new, /* tp_new */
  319. };
  320. PyMODINIT_FUNC
  321. init_tokenizer(void)
  322. {
  323. PyObject* module;
  324. TokenizerType.tp_new = PyType_GenericNew;
  325. if (PyType_Ready(&TokenizerType) < 0)
  326. return;
  327. module = Py_InitModule("_tokenizer", module_methods);
  328. Py_INCREF(&TokenizerType);
  329. PyModule_AddObject(module, "CTokenizer", (PyObject*) &TokenizerType);
  330. PyObject* globals = PyEval_GetGlobals();
  331. PyObject* locals = PyEval_GetLocals();
  332. PyObject* fromlist = PyList_New(0);
  333. contexts = PyImport_ImportModuleLevel("contexts", globals, locals, fromlist, 1);
  334. tokens = PyImport_ImportModuleLevel("tokens", globals, locals, fromlist, 1);
  335. Py_DECREF(fromlist);
  336. }