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.
 
 
 
 

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