A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

1408 lignes
36 KiB

  1. /*
  2. Tokenizer for MWParserFromHell
  3. Copyright (C) 2012 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. #include "tokenizer.h"
  21. static PyObject*
  22. Tokenizer_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
  23. {
  24. Tokenizer* self = (Tokenizer*) type->tp_alloc(type, 0);
  25. return (PyObject*) self;
  26. }
  27. static struct Textbuffer*
  28. Textbuffer_new(void)
  29. {
  30. struct Textbuffer* buffer = malloc(sizeof(struct Textbuffer));
  31. if (!buffer) {
  32. PyErr_NoMemory();
  33. return NULL;
  34. }
  35. buffer->size = 0;
  36. buffer->data = malloc(sizeof(Py_UNICODE) * TEXTBUFFER_BLOCKSIZE);
  37. if (!buffer->data) {
  38. free(buffer);
  39. PyErr_NoMemory();
  40. return NULL;
  41. }
  42. buffer->next = NULL;
  43. return buffer;
  44. }
  45. static void
  46. Tokenizer_dealloc(Tokenizer* self)
  47. {
  48. Py_XDECREF(self->text);
  49. struct Stack *this = self->topstack, *next;
  50. while (this) {
  51. Py_DECREF(this->stack);
  52. Textbuffer_dealloc(this->textbuffer);
  53. next = this->next;
  54. free(this);
  55. this = next;
  56. }
  57. self->ob_type->tp_free((PyObject*) self);
  58. }
  59. static void
  60. Textbuffer_dealloc(struct Textbuffer* this)
  61. {
  62. struct Textbuffer* next;
  63. while (this) {
  64. free(this->data);
  65. next = this->next;
  66. free(this);
  67. this = next;
  68. }
  69. }
  70. static int
  71. Tokenizer_init(Tokenizer* self, PyObject* args, PyObject* kwds)
  72. {
  73. static char* kwlist[] = {NULL};
  74. if (!PyArg_ParseTupleAndKeywords(args, kwds, "", kwlist))
  75. return -1;
  76. self->text = Py_None;
  77. Py_INCREF(Py_None);
  78. self->topstack = NULL;
  79. self->head = 0;
  80. self->length = 0;
  81. self->global = 0;
  82. return 0;
  83. }
  84. /*
  85. Add a new token stack, context, and textbuffer to the list.
  86. */
  87. static int
  88. Tokenizer_push(Tokenizer* self, int context)
  89. {
  90. struct Stack* top = malloc(sizeof(struct Stack));
  91. if (!top) {
  92. PyErr_NoMemory();
  93. return -1;
  94. }
  95. top->stack = PyList_New(0);
  96. top->context = context;
  97. top->textbuffer = Textbuffer_new();
  98. if (!top->textbuffer) {
  99. return -1;
  100. }
  101. top->next = self->topstack;
  102. self->topstack = top;
  103. return 0;
  104. }
  105. /*
  106. Return the contents of the textbuffer as a Python Unicode object.
  107. */
  108. static PyObject*
  109. Textbuffer_render(struct Textbuffer* self)
  110. {
  111. return PyUnicode_FromUnicode(self->data, self->size);
  112. }
  113. /*
  114. Push the textbuffer onto the stack as a Text node and clear it.
  115. */
  116. static int
  117. Tokenizer_push_textbuffer(Tokenizer* self)
  118. {
  119. struct Textbuffer* buffer = self->topstack->textbuffer;
  120. if (buffer->size == 0 && !buffer->next) {
  121. return 0;
  122. }
  123. PyObject* text = Textbuffer_render(buffer);
  124. if (!text) return -1;
  125. PyObject* kwargs = PyDict_New();
  126. if (!kwargs) {
  127. Py_DECREF(text);
  128. return -1;
  129. }
  130. PyDict_SetItemString(kwargs, "text", text);
  131. Py_DECREF(text);
  132. PyObject* token = PyObject_Call(Text, NOARGS, kwargs);
  133. Py_DECREF(kwargs);
  134. if (!token) return -1;
  135. if (PyList_Append(self->topstack->stack, token)) {
  136. Py_DECREF(token);
  137. return -1;
  138. }
  139. Py_DECREF(token);
  140. self->topstack->textbuffer = Textbuffer_new();
  141. if (!self->topstack->textbuffer) {
  142. return -1;
  143. }
  144. return 0;
  145. }
  146. static void
  147. Tokenizer_delete_top_of_stack(Tokenizer* self)
  148. {
  149. struct Stack* top = self->topstack;
  150. Py_DECREF(top->stack);
  151. Textbuffer_dealloc(top->textbuffer);
  152. self->topstack = top->next;
  153. free(top);
  154. }
  155. /*
  156. Pop the current stack/context/textbuffer, returing the stack.
  157. */
  158. static PyObject*
  159. Tokenizer_pop(Tokenizer* self)
  160. {
  161. if (Tokenizer_push_textbuffer(self))
  162. return NULL;
  163. PyObject* stack = self->topstack->stack;
  164. Py_INCREF(stack);
  165. Tokenizer_delete_top_of_stack(self);
  166. return stack;
  167. }
  168. /*
  169. Pop the current stack/context/textbuffer, returing the stack. We will also
  170. replace the underlying stack's context with the current stack's.
  171. */
  172. static PyObject*
  173. Tokenizer_pop_keeping_context(Tokenizer* self)
  174. {
  175. if (Tokenizer_push_textbuffer(self))
  176. return NULL;
  177. PyObject* stack = self->topstack->stack;
  178. Py_INCREF(stack);
  179. int context = self->topstack->context;
  180. Tokenizer_delete_top_of_stack(self);
  181. self->topstack->context = context;
  182. return stack;
  183. }
  184. /*
  185. Fail the current tokenization route. Discards the current
  186. stack/context/textbuffer and raises a BadRoute exception.
  187. */
  188. static void*
  189. Tokenizer_fail_route(Tokenizer* self)
  190. {
  191. PyObject* stack = Tokenizer_pop(self);
  192. Py_XDECREF(stack);
  193. FAIL_ROUTE();
  194. return NULL;
  195. }
  196. /*
  197. Write a token to the end of the current token stack.
  198. */
  199. static int
  200. Tokenizer_write(Tokenizer* self, PyObject* token)
  201. {
  202. if (Tokenizer_push_textbuffer(self))
  203. return -1;
  204. if (PyList_Append(self->topstack->stack, token))
  205. return -1;
  206. return 0;
  207. }
  208. /*
  209. Write a token to the beginning of the current token stack.
  210. */
  211. static int
  212. Tokenizer_write_first(Tokenizer* self, PyObject* token)
  213. {
  214. if (Tokenizer_push_textbuffer(self))
  215. return -1;
  216. if (PyList_Insert(self->topstack->stack, 0, token))
  217. return -1;
  218. return 0;
  219. }
  220. /*
  221. Write text to the current textbuffer.
  222. */
  223. static int
  224. Tokenizer_write_text(Tokenizer* self, Py_UNICODE text)
  225. {
  226. struct Textbuffer* buf = self->topstack->textbuffer;
  227. if (buf->size == TEXTBUFFER_BLOCKSIZE) {
  228. struct Textbuffer* new = Textbuffer_new();
  229. if (!new) {
  230. return -1;
  231. }
  232. new->next = buf;
  233. self->topstack->textbuffer = new;
  234. buf = new;
  235. }
  236. buf->data[buf->size] = text;
  237. buf->size++;
  238. return 0;
  239. }
  240. /*
  241. Write a series of tokens to the current stack at once.
  242. */
  243. static int
  244. Tokenizer_write_all(Tokenizer* self, PyObject* tokenlist)
  245. {
  246. int pushed = 0;
  247. if (PyList_GET_SIZE(tokenlist) > 0) {
  248. PyObject* token = PyList_GET_ITEM(tokenlist, 0);
  249. switch (PyObject_IsInstance(token, Text)) {
  250. case 0:
  251. break;
  252. case 1: {
  253. pushed = 1;
  254. struct Textbuffer* buffer = self->topstack->textbuffer;
  255. if (buffer->size == 0 && !buffer->next) {
  256. break;
  257. }
  258. PyObject* left = Textbuffer_render(buffer);
  259. if (!left) return -1;
  260. PyObject* right = PyObject_GetAttrString(token, "text");
  261. if (!right) return -1;
  262. PyObject* text = PyUnicode_Concat(left, right);
  263. Py_DECREF(left);
  264. Py_DECREF(right);
  265. if (!text) return -1;
  266. if (PyObject_SetAttrString(token, "text", text)) {
  267. Py_DECREF(text);
  268. return -1;
  269. }
  270. Py_DECREF(text);
  271. self->topstack->textbuffer = Textbuffer_new();
  272. if (!self->topstack->textbuffer) {
  273. return -1;
  274. }
  275. break;
  276. }
  277. case -1:
  278. return -1;
  279. }
  280. }
  281. if (!pushed) {
  282. if (Tokenizer_push_textbuffer(self))
  283. return -1;
  284. }
  285. PyObject* stack = self->topstack->stack;
  286. Py_ssize_t size = PyList_GET_SIZE(stack);
  287. if (PyList_SetSlice(stack, size, size, tokenlist))
  288. return -1;
  289. return 0;
  290. }
  291. /*
  292. Pop the current stack, write text, and then write the stack. 'text' is a
  293. NULL-terminated array of chars.
  294. */
  295. static int
  296. Tokenizer_write_text_then_stack(Tokenizer* self, const char* text)
  297. {
  298. PyObject* stack = Tokenizer_pop(self);
  299. int i = 0;
  300. while (1) {
  301. if (!text[i]) break;
  302. if (Tokenizer_write_text(self, (Py_UNICODE) text[i])) {
  303. Py_XDECREF(stack);
  304. return -1;
  305. }
  306. i++;
  307. }
  308. if (stack) {
  309. if (PyList_GET_SIZE(stack) > 0) {
  310. if (Tokenizer_write_all(self, stack)) {
  311. Py_DECREF(stack);
  312. return -1;
  313. }
  314. }
  315. Py_DECREF(stack);
  316. }
  317. self->head--;
  318. return 0;
  319. }
  320. /*
  321. Read the value at a relative point in the wikicode, forwards.
  322. */
  323. static PyObject*
  324. Tokenizer_read(Tokenizer* self, Py_ssize_t delta)
  325. {
  326. Py_ssize_t index = self->head + delta;
  327. if (index >= self->length)
  328. return EMPTY;
  329. return PyList_GET_ITEM(self->text, index);
  330. }
  331. /*
  332. Read the value at a relative point in the wikicode, backwards.
  333. */
  334. static PyObject*
  335. Tokenizer_read_backwards(Tokenizer* self, Py_ssize_t delta)
  336. {
  337. if (delta > self->head)
  338. return EMPTY;
  339. Py_ssize_t index = self->head - delta;
  340. return PyList_GET_ITEM(self->text, index);
  341. }
  342. /*
  343. Parse a template or argument at the head of the wikicode string.
  344. */
  345. static int
  346. Tokenizer_parse_template_or_argument(Tokenizer* self)
  347. {
  348. self->head += 2;
  349. unsigned int braces = 2, i;
  350. while (*Tokenizer_READ(self, 0) == *"{") {
  351. self->head++;
  352. braces++;
  353. }
  354. if (Tokenizer_push(self, 0))
  355. return -1;
  356. while (braces) {
  357. if (braces == 1) {
  358. if (Tokenizer_write_text_then_stack(self, "{"))
  359. return -1;
  360. return 0;
  361. }
  362. if (braces == 2) {
  363. if (Tokenizer_parse_template(self))
  364. return -1;
  365. if (BAD_ROUTE) {
  366. RESET_ROUTE();
  367. if (Tokenizer_write_text_then_stack(self, "{{"))
  368. return -1;
  369. return 0;
  370. }
  371. break;
  372. }
  373. if (Tokenizer_parse_argument(self))
  374. return -1;
  375. if (BAD_ROUTE) {
  376. RESET_ROUTE();
  377. if (Tokenizer_parse_template(self))
  378. return -1;
  379. if (BAD_ROUTE) {
  380. RESET_ROUTE();
  381. char text[braces + 1];
  382. for (i = 0; i < braces; i++) text[i] = *"{";
  383. text[braces] = *"";
  384. if (Tokenizer_write_text_then_stack(self, text)) {
  385. Py_XDECREF(text);
  386. return -1;
  387. }
  388. Py_XDECREF(text);
  389. return 0;
  390. }
  391. else {
  392. braces -= 2;
  393. }
  394. }
  395. else {
  396. braces -= 3;
  397. }
  398. if (braces) {
  399. self->head++;
  400. }
  401. }
  402. PyObject* tokenlist = Tokenizer_pop(self);
  403. if (!tokenlist) return -1;
  404. if (Tokenizer_write_all(self, tokenlist)) {
  405. Py_DECREF(tokenlist);
  406. return -1;
  407. }
  408. Py_DECREF(tokenlist);
  409. return 0;
  410. }
  411. /*
  412. Parse a template at the head of the wikicode string.
  413. */
  414. static int
  415. Tokenizer_parse_template(Tokenizer* self)
  416. {
  417. PyObject *template, *token;
  418. Py_ssize_t reset = self->head;
  419. template = Tokenizer_parse(self, LC_TEMPLATE_NAME);
  420. if (BAD_ROUTE) {
  421. self->head = reset;
  422. return 0;
  423. }
  424. if (!template) return -1;
  425. token = PyObject_CallObject(TemplateOpen, NULL);
  426. if (!token) {
  427. Py_DECREF(template);
  428. return -1;
  429. }
  430. if (Tokenizer_write_first(self, token)) {
  431. Py_DECREF(token);
  432. Py_DECREF(template);
  433. return -1;
  434. }
  435. Py_DECREF(token);
  436. if (Tokenizer_write_all(self, template)) {
  437. Py_DECREF(template);
  438. return -1;
  439. }
  440. Py_DECREF(template);
  441. token = PyObject_CallObject(TemplateClose, NULL);
  442. if (!token) return -1;
  443. if (Tokenizer_write(self, token)) {
  444. Py_DECREF(token);
  445. return -1;
  446. }
  447. Py_DECREF(token);
  448. return 0;
  449. }
  450. /*
  451. Parse an argument at the head of the wikicode string.
  452. */
  453. static int
  454. Tokenizer_parse_argument(Tokenizer* self)
  455. {
  456. PyObject *argument, *token;
  457. Py_ssize_t reset = self->head;
  458. argument = Tokenizer_parse(self, LC_ARGUMENT_NAME);
  459. if (BAD_ROUTE) {
  460. self->head = reset;
  461. return 0;
  462. }
  463. if (!argument) return -1;
  464. token = PyObject_CallObject(ArgumentOpen, NULL);
  465. if (!token) {
  466. Py_DECREF(argument);
  467. return -1;
  468. }
  469. if (Tokenizer_write_first(self, token)) {
  470. Py_DECREF(token);
  471. Py_DECREF(argument);
  472. return -1;
  473. }
  474. Py_DECREF(token);
  475. if (Tokenizer_write_all(self, argument)) {
  476. Py_DECREF(argument);
  477. return -1;
  478. }
  479. Py_DECREF(argument);
  480. token = PyObject_CallObject(ArgumentClose, NULL);
  481. if (!token) return -1;
  482. if (Tokenizer_write(self, token)) {
  483. Py_DECREF(token);
  484. return -1;
  485. }
  486. Py_DECREF(token);
  487. return 0;
  488. }
  489. /*
  490. Verify that there are no unsafe characters in the current stack. The route
  491. will be failed if the name contains any element of unsafes in it (not
  492. merely at the beginning or end). This is used when parsing a template name
  493. or parameter key, which cannot contain newlines.
  494. */
  495. static int
  496. Tokenizer_verify_safe(Tokenizer* self, const char* unsafes[])
  497. {
  498. if (Tokenizer_push_textbuffer(self))
  499. return -1;
  500. PyObject* stack = self->topstack->stack;
  501. if (stack) {
  502. PyObject* textlist = PyList_New(0);
  503. if (!textlist) return -1;
  504. int i;
  505. Py_ssize_t length = PyList_GET_SIZE(stack);
  506. PyObject *token, *textdata;
  507. for (i = 0; i < length; i++) {
  508. token = PyList_GET_ITEM(stack, i);
  509. switch (PyObject_IsInstance(token, Text)) {
  510. case 0:
  511. break;
  512. case 1:
  513. textdata = PyObject_GetAttrString(token, "text");
  514. if (!textdata) {
  515. Py_DECREF(textlist);
  516. return -1;
  517. }
  518. if (PyList_Append(textlist, textdata)) {
  519. Py_DECREF(textlist);
  520. Py_DECREF(textdata);
  521. return -1;
  522. }
  523. Py_DECREF(textdata);
  524. break;
  525. case -1:
  526. Py_DECREF(textlist);
  527. return -1;
  528. }
  529. }
  530. PyObject* text = PyUnicode_Join(EMPTY, textlist);
  531. if (!text) {
  532. Py_DECREF(textlist);
  533. return -1;
  534. }
  535. Py_DECREF(textlist);
  536. PyObject* stripped = PyObject_CallMethod(text, "strip", NULL);
  537. if (!stripped) {
  538. Py_DECREF(text);
  539. return -1;
  540. }
  541. Py_DECREF(text);
  542. const char* unsafe_char;
  543. PyObject* unsafe;
  544. i = 0;
  545. while (1) {
  546. unsafe_char = unsafes[i];
  547. if (!unsafe_char) break;
  548. unsafe = PyUnicode_FromString(unsafe_char);
  549. if (!unsafe) {
  550. Py_DECREF(stripped);
  551. return -1;
  552. }
  553. switch (PyUnicode_Contains(stripped, unsafe)) {
  554. case 0:
  555. break;
  556. case 1:
  557. Tokenizer_fail_route(self);
  558. case -1:
  559. Py_DECREF(stripped);
  560. Py_DECREF(unsafe);
  561. return -1;
  562. }
  563. i++;
  564. }
  565. }
  566. return 0;
  567. }
  568. /*
  569. Handle a template parameter at the head of the string.
  570. */
  571. static int
  572. Tokenizer_handle_template_param(Tokenizer* self)
  573. {
  574. if (self->topstack->context & LC_TEMPLATE_NAME) {
  575. const char* unsafes[] = {"\n", "{", "}", "[", "]", NULL};
  576. if (Tokenizer_verify_safe(self, unsafes))
  577. return -1;
  578. if (BAD_ROUTE) return -1;
  579. self->topstack->context ^= LC_TEMPLATE_NAME;
  580. }
  581. else if (self->topstack->context & LC_TEMPLATE_PARAM_VALUE) {
  582. self->topstack->context ^= LC_TEMPLATE_PARAM_VALUE;
  583. }
  584. if (self->topstack->context & LC_TEMPLATE_PARAM_KEY) {
  585. PyObject* stack = Tokenizer_pop_keeping_context(self);
  586. if (!stack) return -1;
  587. if (Tokenizer_write_all(self, stack)) {
  588. Py_DECREF(stack);
  589. return -1;
  590. }
  591. Py_DECREF(stack);
  592. }
  593. else {
  594. self->topstack->context |= LC_TEMPLATE_PARAM_KEY;
  595. }
  596. PyObject* token = PyObject_CallObject(TemplateParamSeparator, NULL);
  597. if (!token) return -1;
  598. if (Tokenizer_write(self, token)) {
  599. Py_DECREF(token);
  600. return -1;
  601. }
  602. Py_DECREF(token);
  603. if (Tokenizer_push(self, self->topstack->context))
  604. return -1;
  605. return 0;
  606. }
  607. /*
  608. Handle a template parameter's value at the head of the string.
  609. */
  610. static int
  611. Tokenizer_handle_template_param_value(Tokenizer* self)
  612. {
  613. const char* unsafes[] = {"\n", "{{", "}}", NULL};
  614. if (Tokenizer_verify_safe(self, unsafes)) {
  615. if (BAD_ROUTE) {
  616. PyObject* stack = Tokenizer_pop(self);
  617. Py_XDECREF(stack);
  618. }
  619. return -1;
  620. }
  621. PyObject* stack = Tokenizer_pop_keeping_context(self);
  622. if (!stack) return -1;
  623. if (Tokenizer_write_all(self, stack)) {
  624. Py_DECREF(stack);
  625. return -1;
  626. }
  627. Py_DECREF(stack);
  628. self->topstack->context ^= LC_TEMPLATE_PARAM_KEY;
  629. self->topstack->context |= LC_TEMPLATE_PARAM_VALUE;
  630. PyObject* token = PyObject_CallObject(TemplateParamEquals, NULL);
  631. if (!token) return -1;
  632. if (Tokenizer_write(self, token)) {
  633. Py_DECREF(token);
  634. return -1;
  635. }
  636. Py_DECREF(token);
  637. return 0;
  638. }
  639. /*
  640. Handle the end of a template at the head of the string.
  641. */
  642. static PyObject*
  643. Tokenizer_handle_template_end(Tokenizer* self)
  644. {
  645. PyObject* stack;
  646. if (self->topstack->context & LC_TEMPLATE_NAME) {
  647. const char* unsafes[] = {"\n", "{", "}", "[", "]", NULL};
  648. if (Tokenizer_verify_safe(self, unsafes))
  649. return NULL;
  650. }
  651. else if (self->topstack->context & LC_TEMPLATE_PARAM_KEY) {
  652. stack = Tokenizer_pop_keeping_context(self);
  653. if (!stack) return NULL;
  654. if (Tokenizer_write_all(self, stack)) {
  655. Py_DECREF(stack);
  656. return NULL;
  657. }
  658. Py_DECREF(stack);
  659. }
  660. self->head++;
  661. stack = Tokenizer_pop(self);
  662. return stack;
  663. }
  664. /*
  665. Handle the separator between an argument's name and default.
  666. */
  667. static int
  668. Tokenizer_handle_argument_separator(Tokenizer* self)
  669. {
  670. const char* unsafes[] = {"\n", "{{", "}}", NULL};
  671. if (Tokenizer_verify_safe(self, unsafes))
  672. return -1;
  673. self->topstack->context ^= LC_ARGUMENT_NAME;
  674. self->topstack->context |= LC_ARGUMENT_DEFAULT;
  675. PyObject* token = PyObject_CallObject(ArgumentSeparator, NULL);
  676. if (!token) return -1;
  677. if (Tokenizer_write(self, token)) {
  678. Py_DECREF(token);
  679. return -1;
  680. }
  681. Py_DECREF(token);
  682. return 0;
  683. }
  684. /*
  685. Handle the end of an argument at the head of the string.
  686. */
  687. static PyObject*
  688. Tokenizer_handle_argument_end(Tokenizer* self)
  689. {
  690. if (self->topstack->context & LC_ARGUMENT_NAME) {
  691. const char* unsafes[] = {"\n", "{{", "}}", NULL};
  692. if (Tokenizer_verify_safe(self, unsafes))
  693. return NULL;
  694. }
  695. self->head += 2;
  696. PyObject* stack = Tokenizer_pop(self);
  697. return stack;
  698. }
  699. /*
  700. Parse an internal wikilink at the head of the wikicode string.
  701. */
  702. static int
  703. Tokenizer_parse_wikilink(Tokenizer* self)
  704. {
  705. self->head += 2;
  706. Py_ssize_t reset = self->head - 1;
  707. PyObject *token;
  708. PyObject *wikilink = Tokenizer_parse(self, LC_WIKILINK_TITLE);
  709. if (!wikilink) return -1;
  710. if (BAD_ROUTE) {
  711. RESET_ROUTE();
  712. self->head = reset;
  713. int i;
  714. for (i = 0; i < 2; i++) {
  715. if (Tokenizer_write_text(self, *"["))
  716. return -1;
  717. }
  718. return 0;
  719. }
  720. token = PyObject_CallObject(WikilinkOpen, NULL);
  721. if (!token) {
  722. Py_DECREF(wikilink);
  723. return -1;
  724. }
  725. if (Tokenizer_write(self, token)) {
  726. Py_DECREF(token);
  727. Py_DECREF(wikilink);
  728. return -1;
  729. }
  730. Py_DECREF(token);
  731. if (Tokenizer_write_all(self, wikilink)) {
  732. Py_DECREF(wikilink);
  733. return -1;
  734. }
  735. Py_DECREF(wikilink);
  736. token = PyObject_CallObject(WikilinkClose, NULL);
  737. if (!token) return -1;
  738. if (Tokenizer_write(self, token)) {
  739. Py_DECREF(token);
  740. return -1;
  741. }
  742. Py_DECREF(token);
  743. return 0;
  744. }
  745. /*
  746. Handle the separator between a wikilink's title and its text.
  747. */
  748. static int
  749. Tokenizer_handle_wikilink_separator(Tokenizer* self)
  750. {
  751. const char* unsafes[] = {"\n", "{", "}", "[", "]", NULL};
  752. if (Tokenizer_verify_safe(self, unsafes))
  753. return -1;
  754. self->topstack->context ^= LC_WIKILINK_TITLE;
  755. self->topstack->context |= LC_WIKILINK_TEXT;
  756. PyObject* token = PyObject_CallObject(WikilinkSeparator, NULL);
  757. if (!token) return -1;
  758. if (Tokenizer_write(self, token)) {
  759. Py_DECREF(token);
  760. return -1;
  761. }
  762. Py_DECREF(token);
  763. return 0;
  764. }
  765. /*
  766. Handle the end of a wikilink at the head of the string.
  767. */
  768. static PyObject*
  769. Tokenizer_handle_wikilink_end(Tokenizer* self)
  770. {
  771. if (self->topstack->context & LC_WIKILINK_TITLE) {
  772. const char* unsafes[] = {"\n", "{", "}", "[", "]", NULL};
  773. if (Tokenizer_verify_safe(self, unsafes))
  774. return NULL;
  775. }
  776. self->head += 1;
  777. PyObject* stack = Tokenizer_pop(self);
  778. return stack;
  779. }
  780. /*
  781. Parse a section heading at the head of the wikicode string.
  782. */
  783. static int
  784. Tokenizer_parse_heading(Tokenizer* self)
  785. {
  786. self->global |= GL_HEADING;
  787. Py_ssize_t reset = self->head;
  788. self->head += 1;
  789. int best = 1, i;
  790. while (*Tokenizer_READ(self, 0) == *"=") {
  791. best++;
  792. self->head++;
  793. }
  794. int context = LC_HEADING_LEVEL_1 << (best > 5 ? 5 : best - 1);
  795. HeadingData* heading = (HeadingData*) Tokenizer_parse(self, context);
  796. if (BAD_ROUTE) {
  797. RESET_ROUTE();
  798. self->head = reset + best - 1;
  799. char text[best + 1];
  800. for (i = 0; i < best; i++) text[i] = *"=";
  801. text[best] = *"";
  802. if (Tokenizer_write_text_then_stack(self, text))
  803. return -1;
  804. self->global ^= GL_HEADING;
  805. return 0;
  806. }
  807. PyObject* level = PyInt_FromSsize_t(heading->level);
  808. if (!level) {
  809. Py_DECREF(heading->title);
  810. free(heading);
  811. return -1;
  812. }
  813. PyObject* kwargs = PyDict_New();
  814. if (!kwargs) {
  815. Py_DECREF(level);
  816. Py_DECREF(heading->title);
  817. free(heading);
  818. return -1;
  819. }
  820. PyDict_SetItemString(kwargs, "level", level);
  821. Py_DECREF(level);
  822. PyObject* token = PyObject_Call(HeadingStart, NOARGS, kwargs);
  823. Py_DECREF(kwargs);
  824. if (!token) {
  825. Py_DECREF(heading->title);
  826. free(heading);
  827. return -1;
  828. }
  829. if (Tokenizer_write(self, token)) {
  830. Py_DECREF(token);
  831. Py_DECREF(heading->title);
  832. free(heading);
  833. return -1;
  834. }
  835. Py_DECREF(token);
  836. if (heading->level < best) {
  837. int diff = best - heading->level;
  838. char difftext[diff + 1];
  839. for (i = 0; i < diff; i++) difftext[i] = *"=";
  840. difftext[diff] = *"";
  841. if (Tokenizer_write_text_then_stack(self, difftext)) {
  842. Py_DECREF(heading->title);
  843. free(heading);
  844. return -1;
  845. }
  846. }
  847. if (Tokenizer_write_all(self, heading->title)) {
  848. Py_DECREF(heading->title);
  849. free(heading);
  850. return -1;
  851. }
  852. Py_DECREF(heading->title);
  853. free(heading);
  854. token = PyObject_CallObject(HeadingEnd, NULL);
  855. if (!token) return -1;
  856. if (Tokenizer_write(self, token)) {
  857. Py_DECREF(token);
  858. return -1;
  859. }
  860. Py_DECREF(token);
  861. self->global ^= GL_HEADING;
  862. return 0;
  863. }
  864. /*
  865. Handle the end of a section heading at the head of the string.
  866. */
  867. static HeadingData*
  868. Tokenizer_handle_heading_end(Tokenizer* self)
  869. {
  870. Py_ssize_t reset = self->head;
  871. self->head += 1;
  872. Py_ssize_t best = 1;
  873. int i;
  874. while (*Tokenizer_READ(self, 0) == *"=") {
  875. best++;
  876. self->head++;
  877. }
  878. int current = log2(self->topstack->context / LC_HEADING_LEVEL_1) + 1;
  879. int level = current > best ? (best > 6 ? 6 : best) : (current > 6 ? 6 : current);
  880. HeadingData* after = (HeadingData*) Tokenizer_parse(self, self->topstack->context);
  881. if (BAD_ROUTE) {
  882. RESET_ROUTE();
  883. if (level < best) {
  884. int diff = best - level;
  885. char difftext[diff + 1];
  886. for (i = 0; i < diff; i++) difftext[i] = *"=";
  887. difftext[diff] = *"";
  888. if (Tokenizer_write_text_then_stack(self, difftext))
  889. return NULL;
  890. }
  891. self->head = reset + best - 1;
  892. }
  893. else {
  894. char text[best + 1];
  895. for (i = 0; i < best; i++) text[i] = *"=";
  896. text[best] = *"";
  897. if (Tokenizer_write_text_then_stack(self, text)) {
  898. Py_DECREF(after->title);
  899. free(after);
  900. return NULL;
  901. }
  902. if (Tokenizer_write_all(self, after->title)) {
  903. Py_DECREF(after->title);
  904. free(after);
  905. return NULL;
  906. }
  907. Py_DECREF(after->title);
  908. level = after->level;
  909. free(after);
  910. }
  911. PyObject* stack = Tokenizer_pop(self);
  912. if (!stack) return NULL;
  913. HeadingData* heading = malloc(sizeof(HeadingData));
  914. if (!heading) {
  915. PyErr_NoMemory();
  916. return NULL;
  917. }
  918. heading->title = stack;
  919. heading->level = level;
  920. return heading;
  921. }
  922. /*
  923. Actually parse an HTML entity and ensure that it is valid.
  924. */
  925. static int
  926. Tokenizer_really_parse_entity(Tokenizer* self)
  927. {
  928. return 0;
  929. }
  930. /*
  931. Parse an HTML entity at the head of the wikicode string.
  932. */
  933. static int
  934. Tokenizer_parse_entity(Tokenizer* self)
  935. {
  936. Py_ssize_t reset = self->head;
  937. if (Tokenizer_push(self, 0))
  938. return -1;
  939. if (Tokenizer_really_parse_entity(self))
  940. return -1;
  941. if (BAD_ROUTE) {
  942. RESET_ROUTE();
  943. self->head = reset;
  944. if (Tokenizer_write_text(self, *PyUnicode_AS_UNICODE(Tokenizer_read(self, 0))))
  945. return -1;
  946. return 0;
  947. }
  948. PyObject* tokenlist = Tokenizer_pop(self);
  949. if (!tokenlist) return -1;
  950. if (Tokenizer_write_all(self, tokenlist)) {
  951. Py_DECREF(tokenlist);
  952. return -1;
  953. }
  954. Py_DECREF(tokenlist);
  955. return 0;
  956. }
  957. /*
  958. Parse an HTML comment at the head of the wikicode string.
  959. */
  960. static int
  961. Tokenizer_parse_comment(Tokenizer* self)
  962. {
  963. self->head += 4;
  964. Py_ssize_t reset = self->head - 1;
  965. PyObject *token;
  966. PyObject *comment = Tokenizer_parse(self, LC_WIKILINK_TITLE);
  967. if (!comment) return -1;
  968. if (BAD_ROUTE) {
  969. RESET_ROUTE();
  970. self->head = reset;
  971. const char* text = "<!--";
  972. int i = 0;
  973. while (1) {
  974. if (!text[i]) return 0;
  975. if (Tokenizer_write_text(self, (Py_UNICODE) text[i])) {
  976. Py_XDECREF(text);
  977. return -1;
  978. }
  979. i++;
  980. }
  981. }
  982. token = PyObject_CallObject(CommentStart, NULL);
  983. if (!token) {
  984. Py_DECREF(comment);
  985. return -1;
  986. }
  987. if (Tokenizer_write(self, token)) {
  988. Py_DECREF(token);
  989. Py_DECREF(comment);
  990. return -1;
  991. }
  992. Py_DECREF(token);
  993. if (Tokenizer_write_all(self, comment)) {
  994. Py_DECREF(comment);
  995. return -1;
  996. }
  997. Py_DECREF(comment);
  998. token = PyObject_CallObject(CommentEnd, NULL);
  999. if (!token) return -1;
  1000. if (Tokenizer_write(self, token)) {
  1001. Py_DECREF(token);
  1002. return -1;
  1003. }
  1004. Py_DECREF(token);
  1005. self->head += 2;
  1006. return 0;
  1007. }
  1008. /*
  1009. Parse the wikicode string, using context for when to stop.
  1010. */
  1011. static PyObject*
  1012. Tokenizer_parse(Tokenizer* self, int context)
  1013. {
  1014. PyObject *this;
  1015. Py_UNICODE this_data, next, next_next, last;
  1016. int this_context;
  1017. int fail_contexts = LC_TEMPLATE | LC_ARGUMENT | LC_WIKILINK | LC_HEADING | LC_COMMENT;
  1018. int is_marker, i;
  1019. if (Tokenizer_push(self, context))
  1020. return NULL;
  1021. while (1) {
  1022. this = Tokenizer_read(self, 0);
  1023. this_data = *PyUnicode_AS_UNICODE(this);
  1024. is_marker = 0;
  1025. for (i = 0; i < NUM_MARKERS; i++) {
  1026. if (*MARKERS[i] == this_data) {
  1027. is_marker = 1;
  1028. break;
  1029. }
  1030. }
  1031. if (!is_marker) {
  1032. Tokenizer_write_text(self, this_data);
  1033. self->head++;
  1034. continue;
  1035. }
  1036. this_context = self->topstack->context;
  1037. if (this_data == *"") {
  1038. if (this_context & LC_TEMPLATE_PARAM_KEY) {
  1039. PyObject* trash = Tokenizer_pop(self);
  1040. Py_XDECREF(trash);
  1041. }
  1042. if (this_context & fail_contexts) {
  1043. return Tokenizer_fail_route(self);
  1044. }
  1045. return Tokenizer_pop(self);
  1046. }
  1047. next = *Tokenizer_READ(self, 1);
  1048. if (this_context & LC_COMMENT) {
  1049. if (this_data == next && next == *"-") {
  1050. if (*Tokenizer_READ(self, 2) == *">") {
  1051. return Tokenizer_pop(self);
  1052. }
  1053. }
  1054. Tokenizer_write_text(self, this_data);
  1055. }
  1056. else if (this_data == next && next == *"{") {
  1057. if (Tokenizer_parse_template_or_argument(self))
  1058. return NULL;
  1059. }
  1060. else if (this_data == *"|" && this_context & LC_TEMPLATE) {
  1061. if (Tokenizer_handle_template_param(self))
  1062. return NULL;
  1063. }
  1064. else if (this_data == *"=" && this_context & LC_TEMPLATE_PARAM_KEY) {
  1065. if (Tokenizer_handle_template_param_value(self))
  1066. return NULL;
  1067. }
  1068. else if (this_data == next && next == *"}" && this_context & LC_TEMPLATE) {
  1069. return Tokenizer_handle_template_end(self);
  1070. }
  1071. else if (this_data == *"|" && this_context & LC_ARGUMENT_NAME) {
  1072. if (Tokenizer_handle_argument_separator(self))
  1073. return NULL;
  1074. }
  1075. else if (this_data == next && next == *"}" && this_context & LC_ARGUMENT) {
  1076. if (*Tokenizer_READ(self, 2) == *"}") {
  1077. return Tokenizer_handle_argument_end(self);
  1078. }
  1079. Tokenizer_write_text(self, this_data);
  1080. }
  1081. else if (this_data == next && next == *"[") {
  1082. if (!(this_context & LC_WIKILINK_TITLE)) {
  1083. if (Tokenizer_parse_wikilink(self))
  1084. return NULL;
  1085. }
  1086. else {
  1087. Tokenizer_write_text(self, this_data);
  1088. }
  1089. }
  1090. else if (this_data == *"|" && this_context & LC_WIKILINK_TITLE) {
  1091. if (Tokenizer_handle_wikilink_separator(self))
  1092. return NULL;
  1093. }
  1094. else if (this_data == next && next == *"]" && this_context & LC_WIKILINK) {
  1095. return Tokenizer_handle_wikilink_end(self);
  1096. }
  1097. else if (this_data == *"=" && !(self->global & GL_HEADING)) {
  1098. last = *PyUnicode_AS_UNICODE(Tokenizer_read_backwards(self, 1));
  1099. if (last == *"\n" || last == *"") {
  1100. if (Tokenizer_parse_heading(self))
  1101. return NULL;
  1102. }
  1103. else {
  1104. Tokenizer_write_text(self, this_data);
  1105. }
  1106. }
  1107. else if (this_data == *"=" && this_context & LC_HEADING) {
  1108. return (PyObject*) Tokenizer_handle_heading_end(self);
  1109. }
  1110. else if (this_data == *"\n" && this_context & LC_HEADING) {
  1111. return Tokenizer_fail_route(self);
  1112. }
  1113. else if (this_data == *"&") {
  1114. if (Tokenizer_parse_entity(self))
  1115. return NULL;
  1116. }
  1117. else if (this_data == *"<" && next == *"!") {
  1118. next_next = *Tokenizer_READ(self, 2);
  1119. if (next_next == *Tokenizer_READ(self, 3) && next_next == *"-") {
  1120. if (Tokenizer_parse_comment(self))
  1121. return NULL;
  1122. }
  1123. else {
  1124. Tokenizer_write_text(self, this_data);
  1125. }
  1126. }
  1127. else {
  1128. Tokenizer_write_text(self, this_data);
  1129. }
  1130. self->head++;
  1131. }
  1132. }
  1133. /*
  1134. Build a list of tokens from a string of wikicode and return it.
  1135. */
  1136. static PyObject*
  1137. Tokenizer_tokenize(Tokenizer* self, PyObject* args)
  1138. {
  1139. PyObject* text;
  1140. if (!PyArg_ParseTuple(args, "U", &text)) {
  1141. /* Failed to parse a Unicode object; try a string instead. */
  1142. PyErr_Clear();
  1143. const char* encoded;
  1144. Py_ssize_t size;
  1145. if (!PyArg_ParseTuple(args, "s#", &encoded, &size)) {
  1146. return NULL;
  1147. }
  1148. PyObject* temp;
  1149. temp = PyUnicode_FromStringAndSize(encoded, size);
  1150. if (!text)
  1151. return NULL;
  1152. Py_XDECREF(self->text);
  1153. text = PySequence_Fast(temp, "expected a sequence");
  1154. Py_XDECREF(temp);
  1155. self->text = text;
  1156. }
  1157. else {
  1158. Py_XDECREF(self->text);
  1159. self->text = PySequence_Fast(text, "expected a sequence");
  1160. }
  1161. self->length = PyList_GET_SIZE(self->text);
  1162. return Tokenizer_parse(self, 0);
  1163. }
  1164. PyMODINIT_FUNC
  1165. init_tokenizer(void)
  1166. {
  1167. PyObject* module;
  1168. TokenizerType.tp_new = PyType_GenericNew;
  1169. if (PyType_Ready(&TokenizerType) < 0)
  1170. return;
  1171. module = Py_InitModule("_tokenizer", module_methods);
  1172. Py_INCREF(&TokenizerType);
  1173. PyModule_AddObject(module, "CTokenizer", (PyObject*) &TokenizerType);
  1174. EMPTY = PyUnicode_FromString("");
  1175. NOARGS = PyTuple_New(0);
  1176. char* name = "mwparserfromhell.parser";
  1177. PyObject* globals = PyEval_GetGlobals();
  1178. PyObject* locals = PyEval_GetLocals();
  1179. PyObject* fromlist = PyList_New(1);
  1180. if (!fromlist) return;
  1181. PyObject* submodname = PyBytes_FromString("tokens");
  1182. if (!submodname) {
  1183. Py_DECREF(fromlist);
  1184. return;
  1185. }
  1186. PyList_SET_ITEM(fromlist, 0, submodname);
  1187. PyObject* tokmodule = PyImport_ImportModuleLevel(name, globals, locals, fromlist, 0);
  1188. Py_DECREF(fromlist);
  1189. if (!tokmodule) {
  1190. return;
  1191. }
  1192. tokens = PyObject_GetAttrString(tokmodule, "tokens");
  1193. Py_DECREF(tokmodule);
  1194. Text = PyObject_GetAttrString(tokens, "Text");
  1195. TemplateOpen = PyObject_GetAttrString(tokens, "TemplateOpen");
  1196. TemplateParamSeparator = PyObject_GetAttrString(tokens, "TemplateParamSeparator");
  1197. TemplateParamEquals = PyObject_GetAttrString(tokens, "TemplateParamEquals");
  1198. TemplateClose = PyObject_GetAttrString(tokens, "TemplateClose");
  1199. ArgumentOpen = PyObject_GetAttrString(tokens, "ArgumentOpen");
  1200. ArgumentSeparator = PyObject_GetAttrString(tokens, "ArgumentSeparator");
  1201. ArgumentClose = PyObject_GetAttrString(tokens, "ArgumentClose");
  1202. WikilinkOpen = PyObject_GetAttrString(tokens, "WikilinkOpen");
  1203. WikilinkSeparator = PyObject_GetAttrString(tokens, "WikilinkSeparator");
  1204. WikilinkClose = PyObject_GetAttrString(tokens, "WikilinkClose");
  1205. HTMLEntityStart = PyObject_GetAttrString(tokens, "HTMLEntityStart");
  1206. HTMLEntityNumeric = PyObject_GetAttrString(tokens, "HTMLEntityNumeric");
  1207. HTMLEntityHex = PyObject_GetAttrString(tokens, "HTMLEntityHex");
  1208. HTMLEntityEnd = PyObject_GetAttrString(tokens, "HTMLEntityEnd");
  1209. HeadingStart = PyObject_GetAttrString(tokens, "HeadingStart");
  1210. HeadingEnd = PyObject_GetAttrString(tokens, "HeadingEnd");
  1211. CommentStart = PyObject_GetAttrString(tokens, "CommentStart");
  1212. CommentEnd = PyObject_GetAttrString(tokens, "CommentEnd");
  1213. TagOpenOpen = PyObject_GetAttrString(tokens, "TagOpenOpen");
  1214. TagAttrStart = PyObject_GetAttrString(tokens, "TagAttrStart");
  1215. TagAttrEquals = PyObject_GetAttrString(tokens, "TagAttrEquals");
  1216. TagAttrQuote = PyObject_GetAttrString(tokens, "TagAttrQuote");
  1217. TagCloseOpen = PyObject_GetAttrString(tokens, "TagCloseOpen");
  1218. TagCloseSelfclose = PyObject_GetAttrString(tokens, "TagCloseSelfclose");
  1219. TagOpenClose = PyObject_GetAttrString(tokens, "TagOpenClose");
  1220. TagCloseClose = PyObject_GetAttrString(tokens, "TagCloseClose");
  1221. }