A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

352 satır
12 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* 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_URI 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_EXT_LINK_TITLE | LC_HEADING | LC_TAG | LC_STYLE)
  128. #define AGG_UNSAFE (LC_TEMPLATE_NAME | LC_WIKILINK | 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_INVALID_LINK (LC_TEMPLATE_NAME | LC_ARGUMENT_NAME | LC_WIKILINK | LC_EXT_LINK)
  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* prev;
  145. struct Textbuffer* next;
  146. };
  147. struct Stack {
  148. PyObject* stack;
  149. int context;
  150. struct Textbuffer* textbuffer;
  151. struct Stack* next;
  152. };
  153. typedef struct {
  154. PyObject* title;
  155. int level;
  156. } HeadingData;
  157. typedef struct {
  158. int context;
  159. struct Textbuffer* pad_first;
  160. struct Textbuffer* pad_before_eq;
  161. struct Textbuffer* pad_after_eq;
  162. Py_ssize_t reset;
  163. } TagData;
  164. typedef struct Textbuffer Textbuffer;
  165. typedef struct Stack Stack;
  166. /* Tokenizer object definition: */
  167. typedef struct {
  168. PyObject_HEAD
  169. PyObject* text; /* text to tokenize */
  170. Stack* topstack; /* topmost stack */
  171. Py_ssize_t head; /* current position in text */
  172. Py_ssize_t length; /* length of text */
  173. int global; /* global context */
  174. int depth; /* stack recursion depth */
  175. int cycles; /* total number of stack recursions */
  176. int skip_style_tags; /* temporary fix for the sometimes broken tag parser */
  177. } Tokenizer;
  178. /* Macros related to Tokenizer functions: */
  179. #define Tokenizer_READ(self, delta) (*PyUnicode_AS_UNICODE(Tokenizer_read(self, delta)))
  180. #define Tokenizer_READ_BACKWARDS(self, delta) \
  181. (*PyUnicode_AS_UNICODE(Tokenizer_read_backwards(self, delta)))
  182. #define Tokenizer_CAN_RECURSE(self) (self->depth < MAX_DEPTH && self->cycles < MAX_CYCLES)
  183. #define Tokenizer_emit(self, token) Tokenizer_emit_token(self, token, 0)
  184. #define Tokenizer_emit_first(self, token) Tokenizer_emit_token(self, token, 1)
  185. #define Tokenizer_emit_kwargs(self, token, kwargs) Tokenizer_emit_token_kwargs(self, token, kwargs, 0)
  186. #define Tokenizer_emit_first_kwargs(self, token, kwargs) Tokenizer_emit_token_kwargs(self, token, kwargs, 1)
  187. /* Macros for accessing definitions: */
  188. #define GET_HTML_TAG(markup) (markup == ':' ? "dd" : markup == ';' ? "dt" : "li")
  189. #define IS_PARSABLE(tag) (call_def_func("is_parsable", tag, NULL, NULL))
  190. #define IS_SINGLE(tag) (call_def_func("is_single", tag, NULL, NULL))
  191. #define IS_SINGLE_ONLY(tag) (call_def_func("is_single_only", tag, NULL, NULL))
  192. #define IS_SCHEME(scheme, slashes, reverse) \
  193. (call_def_func("is_scheme", scheme, slashes ? Py_True : Py_False, reverse ? Py_True : Py_False))
  194. /* Function prototypes: */
  195. static Textbuffer* Textbuffer_new(void);
  196. static void Textbuffer_dealloc(Textbuffer*);
  197. static TagData* TagData_new(void);
  198. static void TagData_dealloc(TagData*);
  199. static PyObject* Tokenizer_new(PyTypeObject*, PyObject*, PyObject*);
  200. static void Tokenizer_dealloc(Tokenizer*);
  201. static int Tokenizer_init(Tokenizer*, PyObject*, PyObject*);
  202. static int Tokenizer_parse_entity(Tokenizer*);
  203. static int Tokenizer_parse_comment(Tokenizer*);
  204. static int Tokenizer_handle_dl_term(Tokenizer*);
  205. static int Tokenizer_parse_tag(Tokenizer*);
  206. static PyObject* Tokenizer_parse(Tokenizer*, int, int);
  207. static PyObject* Tokenizer_tokenize(Tokenizer*, PyObject*);
  208. /* Macros for Python 2/3 compatibility: */
  209. #ifdef IS_PY3K
  210. #define NEW_INT_FUNC PyLong_FromSsize_t
  211. #define IMPORT_NAME_FUNC PyUnicode_FromString
  212. #define CREATE_MODULE PyModule_Create(&module_def);
  213. #define ENTITYDEFS_MODULE "html.entities"
  214. #define INIT_FUNC_NAME PyInit__tokenizer
  215. #define INIT_ERROR return NULL
  216. #else
  217. #define NEW_INT_FUNC PyInt_FromSsize_t
  218. #define IMPORT_NAME_FUNC PyBytes_FromString
  219. #define CREATE_MODULE Py_InitModule("_tokenizer", NULL);
  220. #define ENTITYDEFS_MODULE "htmlentitydefs"
  221. #define INIT_FUNC_NAME init_tokenizer
  222. #define INIT_ERROR return
  223. #endif
  224. /* More structs for creating the Tokenizer type: */
  225. static PyMethodDef Tokenizer_methods[] = {
  226. {"tokenize", (PyCFunction) Tokenizer_tokenize, METH_VARARGS,
  227. "Build a list of tokens from a string of wikicode and return it."},
  228. {NULL}
  229. };
  230. static PyMemberDef Tokenizer_members[] = {
  231. {NULL}
  232. };
  233. static PyTypeObject TokenizerType = {
  234. PyVarObject_HEAD_INIT(NULL, 0)
  235. "_tokenizer.CTokenizer", /* tp_name */
  236. sizeof(Tokenizer), /* tp_basicsize */
  237. 0, /* tp_itemsize */
  238. (destructor) Tokenizer_dealloc, /* tp_dealloc */
  239. 0, /* tp_print */
  240. 0, /* tp_getattr */
  241. 0, /* tp_setattr */
  242. 0, /* tp_compare */
  243. 0, /* tp_repr */
  244. 0, /* tp_as_number */
  245. 0, /* tp_as_sequence */
  246. 0, /* tp_as_mapping */
  247. 0, /* tp_hash */
  248. 0, /* tp_call */
  249. 0, /* tp_str */
  250. 0, /* tp_getattro */
  251. 0, /* tp_setattro */
  252. 0, /* tp_as_buffer */
  253. Py_TPFLAGS_DEFAULT, /* tp_flags */
  254. "Creates a list of tokens from a string of wikicode.", /* tp_doc */
  255. 0, /* tp_traverse */
  256. 0, /* tp_clear */
  257. 0, /* tp_richcompare */
  258. 0, /* tp_weaklistoffset */
  259. 0, /* tp_iter */
  260. 0, /* tp_iternext */
  261. Tokenizer_methods, /* tp_methods */
  262. Tokenizer_members, /* tp_members */
  263. 0, /* tp_getset */
  264. 0, /* tp_base */
  265. 0, /* tp_dict */
  266. 0, /* tp_descr_get */
  267. 0, /* tp_descr_set */
  268. 0, /* tp_dictoffset */
  269. (initproc) Tokenizer_init, /* tp_init */
  270. 0, /* tp_alloc */
  271. Tokenizer_new, /* tp_new */
  272. };
  273. #ifdef IS_PY3K
  274. static PyModuleDef module_def = {
  275. PyModuleDef_HEAD_INIT,
  276. "_tokenizer",
  277. "Creates a list of tokens from a string of wikicode.",
  278. -1, NULL, NULL, NULL, NULL, NULL
  279. };
  280. #endif