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.
 
 
 
 

345 regels
12 KiB

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