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.
 
 
 
 

355 lines
13 KiB

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