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.
 
 
 
 

534 lines
20 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2013 Ben Kurtovic <ben.kurtovic@verizon.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from __future__ import unicode_literals
  23. from math import log
  24. import re
  25. import string
  26. from . import contexts
  27. from . import tokens
  28. from ..compat import htmlentities
  29. __all__ = ["Tokenizer"]
  30. class BadRoute(Exception):
  31. """Raised internally when the current tokenization route is invalid."""
  32. pass
  33. class Tokenizer(object):
  34. """Creates a list of tokens from a string of wikicode."""
  35. START = object()
  36. END = object()
  37. MARKERS = ["{", "}", "[", "]", "<", ">", "|", "=", "&", "#", "*", ";", ":",
  38. "/", "-", "!", "\n", END]
  39. regex = re.compile(r"([{}\[\]<>|=&#*;:/\-!\n])", flags=re.IGNORECASE)
  40. def __init__(self):
  41. self._text = None
  42. self._head = 0
  43. self._stacks = []
  44. self._global = 0
  45. @property
  46. def _stack(self):
  47. """The current token stack."""
  48. return self._stacks[-1][0]
  49. @property
  50. def _context(self):
  51. """The current token context."""
  52. return self._stacks[-1][1]
  53. @_context.setter
  54. def _context(self, value):
  55. self._stacks[-1][1] = value
  56. @property
  57. def _textbuffer(self):
  58. """The current textbuffer."""
  59. return self._stacks[-1][2]
  60. @_textbuffer.setter
  61. def _textbuffer(self, value):
  62. self._stacks[-1][2] = value
  63. def _push(self, context=0):
  64. """Add a new token stack, context, and textbuffer to the list."""
  65. self._stacks.append([[], context, []])
  66. def _push_textbuffer(self):
  67. """Push the textbuffer onto the stack as a Text node and clear it."""
  68. if self._textbuffer:
  69. self._stack.append(tokens.Text(text="".join(self._textbuffer)))
  70. self._textbuffer = []
  71. def _pop(self, keep_context=False):
  72. """Pop the current stack/context/textbuffer, returing the stack.
  73. If *keep_context* is ``True``, then we will replace the underlying
  74. stack's context with the current stack's.
  75. """
  76. self._push_textbuffer()
  77. if keep_context:
  78. context = self._context
  79. stack = self._stacks.pop()[0]
  80. self._context = context
  81. return stack
  82. return self._stacks.pop()[0]
  83. def _fail_route(self):
  84. """Fail the current tokenization route.
  85. Discards the current stack/context/textbuffer and raises
  86. :py:exc:`~.BadRoute`.
  87. """
  88. self._pop()
  89. raise BadRoute()
  90. def _write(self, token):
  91. """Write a token to the end of the current token stack."""
  92. self._push_textbuffer()
  93. self._stack.append(token)
  94. def _write_first(self, token):
  95. """Write a token to the beginning of the current token stack."""
  96. self._push_textbuffer()
  97. self._stack.insert(0, token)
  98. def _write_text(self, text):
  99. """Write text to the current textbuffer."""
  100. self._textbuffer.append(text)
  101. def _write_all(self, tokenlist):
  102. """Write a series of tokens to the current stack at once."""
  103. if tokenlist and isinstance(tokenlist[0], tokens.Text):
  104. self._write_text(tokenlist.pop(0).text)
  105. self._push_textbuffer()
  106. self._stack.extend(tokenlist)
  107. def _write_text_then_stack(self, text):
  108. """Pop the current stack, write *text*, and then write the stack."""
  109. stack = self._pop()
  110. self._write_text(text)
  111. if stack:
  112. self._write_all(stack)
  113. self._head -= 1
  114. def _read(self, delta=0, wrap=False, strict=False):
  115. """Read the value at a relative point in the wikicode.
  116. The value is read from :py:attr:`self._head <_head>` plus the value of
  117. *delta* (which can be negative). If *wrap* is ``False``, we will not
  118. allow attempts to read from the end of the string if ``self._head +
  119. delta`` is negative. If *strict* is ``True``, the route will be failed
  120. (with :py:meth:`_fail_route`) if we try to read from past the end of
  121. the string; otherwise, :py:attr:`self.END <END>` is returned. If we try
  122. to read from before the start of the string, :py:attr:`self.START
  123. <START>` is returned.
  124. """
  125. index = self._head + delta
  126. if index < 0 and (not wrap or abs(index) > len(self._text)):
  127. return self.START
  128. try:
  129. return self._text[index]
  130. except IndexError:
  131. if strict:
  132. self._fail_route()
  133. return self.END
  134. def _parse_template_or_argument(self):
  135. """Parse a template or argument at the head of the wikicode string."""
  136. self._head += 2
  137. braces = 2
  138. while self._read() == "{":
  139. self._head += 1
  140. braces += 1
  141. self._push()
  142. while braces:
  143. if braces == 1:
  144. return self._write_text_then_stack("{")
  145. if braces == 2:
  146. try:
  147. self._parse_template()
  148. except BadRoute:
  149. return self._write_text_then_stack("{{")
  150. break
  151. try:
  152. self._parse_argument()
  153. braces -= 3
  154. except BadRoute:
  155. try:
  156. self._parse_template()
  157. braces -= 2
  158. except BadRoute:
  159. return self._write_text_then_stack("{" * braces)
  160. if braces:
  161. self._head += 1
  162. self._write_all(self._pop())
  163. def _parse_template(self):
  164. """Parse a template at the head of the wikicode string."""
  165. reset = self._head
  166. try:
  167. template = self._parse(contexts.TEMPLATE_NAME)
  168. except BadRoute:
  169. self._head = reset
  170. raise
  171. self._write_first(tokens.TemplateOpen())
  172. self._write_all(template)
  173. self._write(tokens.TemplateClose())
  174. def _parse_argument(self):
  175. """Parse an argument at the head of the wikicode string."""
  176. reset = self._head
  177. try:
  178. argument = self._parse(contexts.ARGUMENT_NAME)
  179. except BadRoute:
  180. self._head = reset
  181. raise
  182. self._write_first(tokens.ArgumentOpen())
  183. self._write_all(argument)
  184. self._write(tokens.ArgumentClose())
  185. def _handle_template_param(self):
  186. """Handle a template parameter at the head of the string."""
  187. if self._context & contexts.TEMPLATE_NAME:
  188. self._context ^= contexts.TEMPLATE_NAME
  189. elif self._context & contexts.TEMPLATE_PARAM_VALUE:
  190. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  191. elif self._context & contexts.TEMPLATE_PARAM_KEY:
  192. self._write_all(self._pop(keep_context=True))
  193. self._context |= contexts.TEMPLATE_PARAM_KEY
  194. self._write(tokens.TemplateParamSeparator())
  195. self._push(self._context)
  196. def _handle_template_param_value(self):
  197. """Handle a template parameter's value at the head of the string."""
  198. self._write_all(self._pop(keep_context=True))
  199. self._context ^= contexts.TEMPLATE_PARAM_KEY
  200. self._context |= contexts.TEMPLATE_PARAM_VALUE
  201. self._write(tokens.TemplateParamEquals())
  202. def _handle_template_end(self):
  203. """Handle the end of a template at the head of the string."""
  204. if self._context & contexts.TEMPLATE_PARAM_KEY:
  205. self._write_all(self._pop(keep_context=True))
  206. self._head += 1
  207. return self._pop()
  208. def _handle_argument_separator(self):
  209. """Handle the separator between an argument's name and default."""
  210. self._context ^= contexts.ARGUMENT_NAME
  211. self._context |= contexts.ARGUMENT_DEFAULT
  212. self._write(tokens.ArgumentSeparator())
  213. def _handle_argument_end(self):
  214. """Handle the end of an argument at the head of the string."""
  215. self._head += 2
  216. return self._pop()
  217. def _parse_wikilink(self):
  218. """Parse an internal wikilink at the head of the wikicode string."""
  219. self._head += 2
  220. reset = self._head - 1
  221. try:
  222. wikilink = self._parse(contexts.WIKILINK_TITLE)
  223. except BadRoute:
  224. self._head = reset
  225. self._write_text("[[")
  226. else:
  227. self._write(tokens.WikilinkOpen())
  228. self._write_all(wikilink)
  229. self._write(tokens.WikilinkClose())
  230. def _handle_wikilink_separator(self):
  231. """Handle the separator between a wikilink's title and its text."""
  232. self._context ^= contexts.WIKILINK_TITLE
  233. self._context |= contexts.WIKILINK_TEXT
  234. self._write(tokens.WikilinkSeparator())
  235. def _handle_wikilink_end(self):
  236. """Handle the end of a wikilink at the head of the string."""
  237. self._head += 1
  238. return self._pop()
  239. def _parse_heading(self):
  240. """Parse a section heading at the head of the wikicode string."""
  241. self._global |= contexts.GL_HEADING
  242. reset = self._head
  243. self._head += 1
  244. best = 1
  245. while self._read() == "=":
  246. best += 1
  247. self._head += 1
  248. context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
  249. try:
  250. title, level = self._parse(context)
  251. except BadRoute:
  252. self._head = reset + best - 1
  253. self._write_text("=" * best)
  254. else:
  255. self._write(tokens.HeadingStart(level=level))
  256. if level < best:
  257. self._write_text("=" * (best - level))
  258. self._write_all(title)
  259. self._write(tokens.HeadingEnd())
  260. finally:
  261. self._global ^= contexts.GL_HEADING
  262. def _handle_heading_end(self):
  263. """Handle the end of a section heading at the head of the string."""
  264. reset = self._head
  265. self._head += 1
  266. best = 1
  267. while self._read() == "=":
  268. best += 1
  269. self._head += 1
  270. current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
  271. level = min(current, min(best, 6))
  272. try: # Try to check for a heading closure after this one
  273. after, after_level = self._parse(self._context)
  274. except BadRoute:
  275. if level < best:
  276. self._write_text("=" * (best - level))
  277. self._head = reset + best - 1
  278. return self._pop(), level
  279. else: # Found another closure
  280. self._write_text("=" * best)
  281. self._write_all(after)
  282. return self._pop(), after_level
  283. def _really_parse_entity(self):
  284. """Actually parse an HTML entity and ensure that it is valid."""
  285. self._write(tokens.HTMLEntityStart())
  286. self._head += 1
  287. this = self._read(strict=True)
  288. if this == "#":
  289. numeric = True
  290. self._write(tokens.HTMLEntityNumeric())
  291. self._head += 1
  292. this = self._read(strict=True)
  293. if this[0].lower() == "x":
  294. hexadecimal = True
  295. self._write(tokens.HTMLEntityHex(char=this[0]))
  296. this = this[1:]
  297. if not this:
  298. self._fail_route()
  299. else:
  300. hexadecimal = False
  301. else:
  302. numeric = hexadecimal = False
  303. valid = string.hexdigits if hexadecimal else string.digits
  304. if not numeric and not hexadecimal:
  305. valid += string.ascii_letters
  306. if not all([char in valid for char in this]):
  307. self._fail_route()
  308. self._head += 1
  309. if self._read() != ";":
  310. self._fail_route()
  311. if numeric:
  312. test = int(this, 16) if hexadecimal else int(this)
  313. if test < 1 or test > 0x10FFFF:
  314. self._fail_route()
  315. else:
  316. if this not in htmlentities.entitydefs:
  317. self._fail_route()
  318. self._write(tokens.Text(text=this))
  319. self._write(tokens.HTMLEntityEnd())
  320. def _parse_entity(self):
  321. """Parse an HTML entity at the head of the wikicode string."""
  322. reset = self._head
  323. self._push()
  324. try:
  325. self._really_parse_entity()
  326. except BadRoute:
  327. self._head = reset
  328. self._write_text(self._read())
  329. else:
  330. self._write_all(self._pop())
  331. def _parse_comment(self):
  332. """Parse an HTML comment at the head of the wikicode string."""
  333. self._head += 4
  334. reset = self._head - 1
  335. try:
  336. comment = self._parse(contexts.COMMENT)
  337. except BadRoute:
  338. self._head = reset
  339. self._write_text("<!--")
  340. else:
  341. self._write(tokens.CommentStart())
  342. self._write_all(comment)
  343. self._write(tokens.CommentEnd())
  344. self._head += 2
  345. def _verify_safe(self, this):
  346. """Make sure we are not trying to write an invalid character."""
  347. context = self._context
  348. if context & contexts.FAIL_NEXT:
  349. return False
  350. if context & contexts.WIKILINK_TITLE:
  351. if this == "]" or this == "{":
  352. self._context |= contexts.FAIL_NEXT
  353. elif this == "\n" or this == "[" or this == "}":
  354. return False
  355. return True
  356. if context & contexts.TEMPLATE_NAME:
  357. if this == "{" or this == "}" or this == "[":
  358. self._context |= contexts.FAIL_NEXT
  359. return True
  360. if this == "]":
  361. return False
  362. if this == "|":
  363. return True
  364. if context & contexts.HAS_TEXT:
  365. if context & contexts.FAIL_ON_TEXT:
  366. if this is self.END or not this.isspace():
  367. return False
  368. else:
  369. if this == "\n":
  370. self._context |= contexts.FAIL_ON_TEXT
  371. elif this is not self.END or not this.isspace():
  372. self._context |= contexts.HAS_TEXT
  373. return True
  374. else:
  375. if context & contexts.FAIL_ON_EQUALS:
  376. if this == "=":
  377. return False
  378. elif context & contexts.FAIL_ON_LBRACE:
  379. if this == "{" or (self._read(-1) == self._read(-2) == "{"):
  380. if context & contexts.TEMPLATE:
  381. self._context |= contexts.FAIL_ON_EQUALS
  382. else:
  383. self._context |= contexts.FAIL_NEXT
  384. return True
  385. self._context ^= contexts.FAIL_ON_LBRACE
  386. elif context & contexts.FAIL_ON_RBRACE:
  387. if this == "}":
  388. if context & contexts.TEMPLATE:
  389. self._context |= contexts.FAIL_ON_EQUALS
  390. else:
  391. self._context |= contexts.FAIL_NEXT
  392. return True
  393. self._context ^= contexts.FAIL_ON_RBRACE
  394. elif this == "{":
  395. self._context |= contexts.FAIL_ON_LBRACE
  396. elif this == "}":
  397. self._context |= contexts.FAIL_ON_RBRACE
  398. return True
  399. def _parse(self, context=0):
  400. """Parse the wikicode string, using *context* for when to stop."""
  401. self._push(context)
  402. while True:
  403. this = self._read()
  404. unsafe = (contexts.TEMPLATE_NAME | contexts.WIKILINK_TITLE |
  405. contexts.TEMPLATE_PARAM_KEY | contexts.ARGUMENT_NAME)
  406. if self._context & unsafe:
  407. if not self._verify_safe(this):
  408. if self._context & contexts.TEMPLATE_PARAM_KEY:
  409. self._pop()
  410. self._fail_route()
  411. if this not in self.MARKERS:
  412. self._write_text(this)
  413. self._head += 1
  414. continue
  415. if this is self.END:
  416. fail = (contexts.TEMPLATE | contexts.ARGUMENT |
  417. contexts.WIKILINK | contexts.HEADING |
  418. contexts.COMMENT)
  419. if self._context & contexts.TEMPLATE_PARAM_KEY:
  420. self._pop()
  421. if self._context & fail:
  422. self._fail_route()
  423. return self._pop()
  424. next = self._read(1)
  425. if self._context & contexts.COMMENT:
  426. if this == next == "-" and self._read(2) == ">":
  427. return self._pop()
  428. else:
  429. self._write_text(this)
  430. elif this == next == "{":
  431. self._parse_template_or_argument()
  432. if self._context & contexts.FAIL_NEXT:
  433. self._context ^= contexts.FAIL_NEXT
  434. elif this == "|" and self._context & contexts.TEMPLATE:
  435. self._handle_template_param()
  436. elif this == "=" and self._context & contexts.TEMPLATE_PARAM_KEY:
  437. self._handle_template_param_value()
  438. elif this == next == "}" and self._context & contexts.TEMPLATE:
  439. return self._handle_template_end()
  440. elif this == "|" and self._context & contexts.ARGUMENT_NAME:
  441. self._handle_argument_separator()
  442. elif this == next == "}" and self._context & contexts.ARGUMENT:
  443. if self._read(2) == "}":
  444. return self._handle_argument_end()
  445. else:
  446. self._write_text("}")
  447. elif this == next == "[":
  448. if not self._context & contexts.WIKILINK_TITLE:
  449. self._parse_wikilink()
  450. if self._context & contexts.FAIL_NEXT:
  451. self._context ^= contexts.FAIL_NEXT
  452. else:
  453. self._write_text("[")
  454. elif this == "|" and self._context & contexts.WIKILINK_TITLE:
  455. self._handle_wikilink_separator()
  456. elif this == next == "]" and self._context & contexts.WIKILINK:
  457. return self._handle_wikilink_end()
  458. elif this == "=" and not self._global & contexts.GL_HEADING:
  459. if self._read(-1) in ("\n", self.START):
  460. self._parse_heading()
  461. else:
  462. self._write_text("=")
  463. elif this == "=" and self._context & contexts.HEADING:
  464. return self._handle_heading_end()
  465. elif this == "\n" and self._context & contexts.HEADING:
  466. self._fail_route()
  467. elif this == "&":
  468. self._parse_entity()
  469. elif this == "<" and next == "!":
  470. if self._read(2) == self._read(3) == "-":
  471. self._parse_comment()
  472. else:
  473. self._write_text(this)
  474. else:
  475. self._write_text(this)
  476. self._head += 1
  477. def tokenize(self, text):
  478. """Build a list of tokens from a string of wikicode and return it."""
  479. split = self.regex.split(text)
  480. self._text = [segment for segment in split if segment]
  481. return self._parse()