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.
 
 
 
 

367 lines
14 KiB

  1. /*
  2. Tokenizer Header File for MWParserFromHell
  3. Copyright (C) 2012-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  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 <math.h>
  25. #include <structmember.h>
  26. #include <bytesobject.h>
  27. #include <stdint.h>
  28. #if PY_MAJOR_VERSION >= 3
  29. #define IS_PY3K
  30. #endif
  31. #define malloc PyObject_Malloc
  32. #define free PyObject_Free
  33. #define DIGITS "0123456789"
  34. #define HEXDIGITS "0123456789abcdefABCDEF"
  35. #define ALPHANUM "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  36. static const char MARKERS[] = {
  37. '{', '}', '[', ']', '<', '>', '|', '=', '&', '\'', '#', '*', ';', ':', '/',
  38. '-', '!', '\n', '\0'};
  39. #define NUM_MARKERS 19
  40. #define TEXTBUFFER_BLOCKSIZE 1024
  41. #define MAX_DEPTH 40
  42. #define MAX_CYCLES 100000
  43. #define MAX_BRACES 255
  44. #define MAX_ENTITY_SIZE 8
  45. static int route_state = 0;
  46. static uint64_t route_context = 0;
  47. #define BAD_ROUTE route_state
  48. #define BAD_ROUTE_CONTEXT route_context
  49. #define FAIL_ROUTE(context) route_state = 1; route_context = context
  50. #define RESET_ROUTE() route_state = 0
  51. static char** entitydefs;
  52. static PyObject* EMPTY;
  53. static PyObject* NOARGS;
  54. static PyObject* ParserError;
  55. static PyObject* definitions;
  56. /* Tokens: */
  57. static PyObject* Text;
  58. static PyObject* TemplateOpen;
  59. static PyObject* TemplateParamSeparator;
  60. static PyObject* TemplateParamEquals;
  61. static PyObject* TemplateClose;
  62. static PyObject* ArgumentOpen;
  63. static PyObject* ArgumentSeparator;
  64. static PyObject* ArgumentClose;
  65. static PyObject* WikilinkOpen;
  66. static PyObject* WikilinkSeparator;
  67. static PyObject* WikilinkClose;
  68. static PyObject* ExternalLinkOpen;
  69. static PyObject* ExternalLinkSeparator;
  70. static PyObject* ExternalLinkClose;
  71. static PyObject* HTMLEntityStart;
  72. static PyObject* HTMLEntityNumeric;
  73. static PyObject* HTMLEntityHex;
  74. static PyObject* HTMLEntityEnd;
  75. static PyObject* HeadingStart;
  76. static PyObject* HeadingEnd;
  77. static PyObject* CommentStart;
  78. static PyObject* CommentEnd;
  79. static PyObject* TagOpenOpen;
  80. static PyObject* TagAttrStart;
  81. static PyObject* TagAttrEquals;
  82. static PyObject* TagAttrQuote;
  83. static PyObject* TagCloseOpen;
  84. static PyObject* TagCloseSelfclose;
  85. static PyObject* TagOpenClose;
  86. static PyObject* TagCloseClose;
  87. /* Local contexts: */
  88. #define LC_TEMPLATE 0x0000000000000007
  89. #define LC_TEMPLATE_NAME 0x0000000000000001
  90. #define LC_TEMPLATE_PARAM_KEY 0x0000000000000002
  91. #define LC_TEMPLATE_PARAM_VALUE 0x0000000000000004
  92. #define LC_ARGUMENT 0x0000000000000018
  93. #define LC_ARGUMENT_NAME 0x0000000000000008
  94. #define LC_ARGUMENT_DEFAULT 0x0000000000000010
  95. #define LC_WIKILINK 0x0000000000000060
  96. #define LC_WIKILINK_TITLE 0x0000000000000020
  97. #define LC_WIKILINK_TEXT 0x0000000000000040
  98. #define LC_EXT_LINK 0x0000000000000180
  99. #define LC_EXT_LINK_URI 0x0000000000000080
  100. #define LC_EXT_LINK_TITLE 0x0000000000000100
  101. #define LC_HEADING 0x0000000000007E00
  102. #define LC_HEADING_LEVEL_1 0x0000000000000200
  103. #define LC_HEADING_LEVEL_2 0x0000000000000400
  104. #define LC_HEADING_LEVEL_3 0x0000000000000800
  105. #define LC_HEADING_LEVEL_4 0x0000000000001000
  106. #define LC_HEADING_LEVEL_5 0x0000000000002000
  107. #define LC_HEADING_LEVEL_6 0x0000000000004000
  108. #define LC_TAG 0x0000000000078000
  109. #define LC_TAG_OPEN 0x0000000000008000
  110. #define LC_TAG_ATTR 0x0000000000010000
  111. #define LC_TAG_BODY 0x0000000000020000
  112. #define LC_TAG_CLOSE 0x0000000000040000
  113. #define LC_STYLE 0x0000000000780000
  114. #define LC_STYLE_ITALICS 0x0000000000080000
  115. #define LC_STYLE_BOLD 0x0000000000100000
  116. #define LC_STYLE_PASS_AGAIN 0x0000000000200000
  117. #define LC_STYLE_SECOND_PASS 0x0000000000400000
  118. #define LC_DLTERM 0x0000000000800000
  119. #define LC_SAFETY_CHECK 0x000000003F000000
  120. #define LC_HAS_TEXT 0x0000000001000000
  121. #define LC_FAIL_ON_TEXT 0x0000000002000000
  122. #define LC_FAIL_NEXT 0x0000000004000000
  123. #define LC_FAIL_ON_LBRACE 0x0000000008000000
  124. #define LC_FAIL_ON_RBRACE 0x0000000010000000
  125. #define LC_FAIL_ON_EQUALS 0x0000000020000000
  126. #define LC_TABLE 0x0000000FC0000000
  127. #define LC_TABLE_CELL_LINE_CONTEXTS 0x0000000D00000000
  128. #define LC_TABLE_OPEN 0x0000000040000000
  129. #define LC_TABLE_CELL_OPEN 0x0000000080000000
  130. #define LC_TABLE_CELL_STYLE 0x0000000100000000
  131. #define LC_TABLE_ROW_OPEN 0x0000000200000000
  132. #define LC_TABLE_TD_LINE 0x0000000400000000
  133. #define LC_TABLE_TH_LINE 0x0000000800000000
  134. /* Global contexts: */
  135. #define GL_HEADING 0x1
  136. /* Aggregate contexts: */
  137. #define AGG_FAIL (LC_TEMPLATE | LC_ARGUMENT | LC_WIKILINK | LC_EXT_LINK_TITLE | LC_HEADING | LC_TAG | LC_STYLE | LC_TABLE_OPEN)
  138. #define AGG_UNSAFE (LC_TEMPLATE_NAME | LC_WIKILINK_TITLE | LC_EXT_LINK_TITLE | LC_TEMPLATE_PARAM_KEY | LC_ARGUMENT_NAME)
  139. #define AGG_DOUBLE (LC_TEMPLATE_PARAM_KEY | LC_TAG_CLOSE | LC_TABLE_ROW_OPEN)
  140. #define AGG_NO_WIKILINKS (LC_TEMPLATE_NAME | LC_ARGUMENT_NAME | LC_WIKILINK_TITLE | LC_EXT_LINK_URI)
  141. #define AGG_NO_EXT_LINKS (LC_TEMPLATE_NAME | LC_ARGUMENT_NAME | LC_WIKILINK_TITLE | LC_EXT_LINK)
  142. /* Tag contexts: */
  143. #define TAG_NAME 0x01
  144. #define TAG_ATTR_READY 0x02
  145. #define TAG_ATTR_NAME 0x04
  146. #define TAG_ATTR_VALUE 0x08
  147. #define TAG_QUOTED 0x10
  148. #define TAG_NOTE_SPACE 0x20
  149. #define TAG_NOTE_EQUALS 0x40
  150. #define TAG_NOTE_QUOTE 0x80
  151. /* Miscellaneous structs: */
  152. struct Textbuffer {
  153. Py_ssize_t size;
  154. Py_UNICODE* data;
  155. struct Textbuffer* prev;
  156. struct Textbuffer* next;
  157. };
  158. struct Stack {
  159. PyObject* stack;
  160. uint64_t context;
  161. struct Textbuffer* textbuffer;
  162. struct Stack* next;
  163. };
  164. typedef struct {
  165. PyObject* title;
  166. int level;
  167. } HeadingData;
  168. typedef struct {
  169. uint64_t context;
  170. struct Textbuffer* pad_first;
  171. struct Textbuffer* pad_before_eq;
  172. struct Textbuffer* pad_after_eq;
  173. Py_UNICODE quoter;
  174. Py_ssize_t reset;
  175. } TagData;
  176. typedef struct Textbuffer Textbuffer;
  177. typedef struct Stack Stack;
  178. /* Tokenizer object definition: */
  179. typedef struct {
  180. PyObject_HEAD
  181. PyObject* text; /* text to tokenize */
  182. Stack* topstack; /* topmost stack */
  183. Py_ssize_t head; /* current position in text */
  184. Py_ssize_t length; /* length of text */
  185. int global; /* global context */
  186. int depth; /* stack recursion depth */
  187. int cycles; /* total number of stack recursions */
  188. int skip_style_tags; /* temporary fix for the sometimes broken tag parser */
  189. } Tokenizer;
  190. /* Macros related to Tokenizer functions: */
  191. #define Tokenizer_READ(self, delta) (*PyUnicode_AS_UNICODE(Tokenizer_read(self, delta)))
  192. #define Tokenizer_READ_BACKWARDS(self, delta) \
  193. (*PyUnicode_AS_UNICODE(Tokenizer_read_backwards(self, delta)))
  194. #define Tokenizer_CAN_RECURSE(self) (self->depth < MAX_DEPTH && self->cycles < MAX_CYCLES)
  195. #define Tokenizer_emit(self, token) Tokenizer_emit_token(self, token, 0)
  196. #define Tokenizer_emit_first(self, token) Tokenizer_emit_token(self, token, 1)
  197. #define Tokenizer_emit_kwargs(self, token, kwargs) Tokenizer_emit_token_kwargs(self, token, kwargs, 0)
  198. #define Tokenizer_emit_first_kwargs(self, token, kwargs) Tokenizer_emit_token_kwargs(self, token, kwargs, 1)
  199. /* Macros for accessing definitions: */
  200. #define GET_HTML_TAG(markup) (markup == ':' ? "dd" : markup == ';' ? "dt" : "li")
  201. #define IS_PARSABLE(tag) (call_def_func("is_parsable", tag, NULL, NULL))
  202. #define IS_SINGLE(tag) (call_def_func("is_single", tag, NULL, NULL))
  203. #define IS_SINGLE_ONLY(tag) (call_def_func("is_single_only", tag, NULL, NULL))
  204. #define IS_SCHEME(scheme, slashes, reverse) \
  205. (call_def_func("is_scheme", scheme, slashes ? Py_True : Py_False, reverse ? Py_True : Py_False))
  206. /* Function prototypes: */
  207. static Textbuffer* Textbuffer_new(void);
  208. static void Textbuffer_dealloc(Textbuffer*);
  209. static TagData* TagData_new(void);
  210. static void TagData_dealloc(TagData*);
  211. static PyObject* Tokenizer_new(PyTypeObject*, PyObject*, PyObject*);
  212. static void Tokenizer_dealloc(Tokenizer*);
  213. static int Tokenizer_init(Tokenizer*, PyObject*, PyObject*);
  214. static int Tokenizer_parse_entity(Tokenizer*);
  215. static int Tokenizer_parse_comment(Tokenizer*);
  216. static int Tokenizer_handle_dl_term(Tokenizer*);
  217. static int Tokenizer_parse_tag(Tokenizer*);
  218. static PyObject* Tokenizer_parse(Tokenizer*, uint64_t, int);
  219. static PyObject* Tokenizer_tokenize(Tokenizer*, PyObject*);
  220. static int load_exceptions(void);
  221. /* Macros for Python 2/3 compatibility: */
  222. #ifdef IS_PY3K
  223. #define NEW_INT_FUNC PyLong_FromSsize_t
  224. #define IMPORT_NAME_FUNC PyUnicode_FromString
  225. #define CREATE_MODULE PyModule_Create(&module_def);
  226. #define ENTITYDEFS_MODULE "html.entities"
  227. #define INIT_FUNC_NAME PyInit__tokenizer
  228. #define INIT_ERROR return NULL
  229. #else
  230. #define NEW_INT_FUNC PyInt_FromSsize_t
  231. #define IMPORT_NAME_FUNC PyBytes_FromString
  232. #define CREATE_MODULE Py_InitModule("_tokenizer", NULL);
  233. #define ENTITYDEFS_MODULE "htmlentitydefs"
  234. #define INIT_FUNC_NAME init_tokenizer
  235. #define INIT_ERROR return
  236. #endif
  237. /* More structs for creating the Tokenizer type: */
  238. static PyMethodDef Tokenizer_methods[] = {
  239. {"tokenize", (PyCFunction) Tokenizer_tokenize, METH_VARARGS,
  240. "Build a list of tokens from a string of wikicode and return it."},
  241. {NULL}
  242. };
  243. static PyMemberDef Tokenizer_members[] = {
  244. {NULL}
  245. };
  246. static PyTypeObject TokenizerType = {
  247. PyVarObject_HEAD_INIT(NULL, 0)
  248. "_tokenizer.CTokenizer", /* tp_name */
  249. sizeof(Tokenizer), /* tp_basicsize */
  250. 0, /* tp_itemsize */
  251. (destructor) Tokenizer_dealloc, /* tp_dealloc */
  252. 0, /* tp_print */
  253. 0, /* tp_getattr */
  254. 0, /* tp_setattr */
  255. 0, /* tp_compare */
  256. 0, /* tp_repr */
  257. 0, /* tp_as_number */
  258. 0, /* tp_as_sequence */
  259. 0, /* tp_as_mapping */
  260. 0, /* tp_hash */
  261. 0, /* tp_call */
  262. 0, /* tp_str */
  263. 0, /* tp_getattro */
  264. 0, /* tp_setattro */
  265. 0, /* tp_as_buffer */
  266. Py_TPFLAGS_DEFAULT, /* tp_flags */
  267. "Creates a list of tokens from a string of wikicode.", /* tp_doc */
  268. 0, /* tp_traverse */
  269. 0, /* tp_clear */
  270. 0, /* tp_richcompare */
  271. 0, /* tp_weaklistoffset */
  272. 0, /* tp_iter */
  273. 0, /* tp_iternext */
  274. Tokenizer_methods, /* tp_methods */
  275. Tokenizer_members, /* tp_members */
  276. 0, /* tp_getset */
  277. 0, /* tp_base */
  278. 0, /* tp_dict */
  279. 0, /* tp_descr_get */
  280. 0, /* tp_descr_set */
  281. 0, /* tp_dictoffset */
  282. (initproc) Tokenizer_init, /* tp_init */
  283. 0, /* tp_alloc */
  284. Tokenizer_new, /* tp_new */
  285. };
  286. #ifdef IS_PY3K
  287. static PyModuleDef module_def = {
  288. PyModuleDef_HEAD_INIT,
  289. "_tokenizer",
  290. "Creates a list of tokens from a string of wikicode.",
  291. -1, NULL, NULL, NULL, NULL, NULL
  292. };
  293. #endif