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.
 
 
 
 

415 lines
15 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012 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):
  72. """Pop the current stack/context/textbuffer, returing the stack."""
  73. self._push_textbuffer()
  74. return self._stacks.pop()[0]
  75. def _fail_route(self):
  76. """Fail the current tokenization route.
  77. Discards the current stack/context/textbuffer and raises
  78. :py:exc:`~.BadRoute`.
  79. """
  80. self._pop()
  81. raise BadRoute()
  82. def _write(self, token):
  83. """Write a token to the end of the current token stack."""
  84. self._push_textbuffer()
  85. self._stack.append(token)
  86. def _write_first(self, token):
  87. """Write a token to the beginning of the current token stack."""
  88. self._push_textbuffer()
  89. self._stack.insert(0, token)
  90. def _write_text(self, text):
  91. """Write text to the current textbuffer."""
  92. self._textbuffer.append(text)
  93. def _write_all(self, tokenlist):
  94. """Write a series of tokens to the current stack at once."""
  95. if tokenlist and isinstance(tokenlist[0], tokens.Text):
  96. self._write_text(tokenlist.pop(0).text)
  97. self._push_textbuffer()
  98. self._stack.extend(tokenlist)
  99. def _write_text_then_stack(self, text):
  100. """Pop the current stack, write *text*, and then write the stack."""
  101. stack = self._pop()
  102. self._write_text(text)
  103. self._write_all(stack)
  104. self._head -= 1
  105. def _read(self, delta=0, wrap=False, strict=False):
  106. """Read the value at a relative point in the wikicode.
  107. The value is read from :py:attr:`self._head <_head>` plus the value of
  108. *delta* (which can be negative). If *wrap* is ``False``, we will not
  109. allow attempts to read from the end of the string if ``self._head +
  110. delta`` is negative. If *strict* is ``True``, the route will be failed
  111. (with :py:meth:`_fail_route`) if we try to read from past the end of
  112. the string; otherwise, :py:attr:`self.END <END>` is returned. If we try
  113. to read from before the start of the string, :py:attr:`self.START
  114. <START>` is returned.
  115. """
  116. index = self._head + delta
  117. if index < 0 and (not wrap or abs(index) > len(self._text)):
  118. return self.START
  119. try:
  120. return self._text[index]
  121. except IndexError:
  122. if strict:
  123. self._fail_route()
  124. return self.END
  125. def _parse_template_or_argument(self):
  126. """Parse a template or argument at the head of the wikicode string."""
  127. self._head += 2
  128. braces = 2
  129. while self._read() == "{":
  130. braces += 1
  131. self._head += 1
  132. self._push()
  133. while braces:
  134. if braces == 1:
  135. return self._write_text_then_stack("{")
  136. if braces == 2:
  137. try:
  138. self._parse_template()
  139. except BadRoute:
  140. return self._write_text_then_stack("{{")
  141. break
  142. try:
  143. self._parse_argument()
  144. except BadRoute:
  145. try:
  146. self._parse_template()
  147. except BadRoute:
  148. return self._write_text_then_stack("{" * braces)
  149. stack = self._pop()
  150. self._write_text("{")
  151. self._push()
  152. self._write_all(stack)
  153. braces -= 3
  154. if braces:
  155. self._head += 1
  156. self._write_all(self._pop())
  157. def _parse_template(self):
  158. """Parse a template at the head of the wikicode string."""
  159. reset = self._head
  160. try:
  161. template = self._parse(contexts.TEMPLATE_NAME)
  162. except BadRoute:
  163. self._head = reset
  164. raise
  165. else:
  166. self._write_first(tokens.TemplateOpen())
  167. self._write_all(template)
  168. self._write(tokens.TemplateClose())
  169. def _parse_argument(self):
  170. """Parse an argument at the head of the wikicode string."""
  171. reset = self._head
  172. try:
  173. argument = self._parse(contexts.ARGUMENT_NAME)
  174. except BadRoute:
  175. self._head = reset
  176. raise
  177. else:
  178. self._write_first(tokens.ArgumentOpen())
  179. self._write_all(argument)
  180. self._write(tokens.ArgumentClose())
  181. def _verify_safe(self, unsafes):
  182. """Verify that there are no unsafe characters in the current stack.
  183. The route will be failed if the name contains any element of *unsafes*
  184. in it (not merely at the beginning or end). This is used when parsing a
  185. template name or parameter key, which cannot contain newlines.
  186. """
  187. self._push_textbuffer()
  188. if self._stack:
  189. text = [tok for tok in self._stack if isinstance(tok, tokens.Text)]
  190. text = "".join([token.text for token in text]).strip()
  191. if text and any([unsafe in text for unsafe in unsafes]):
  192. self._fail_route()
  193. def _handle_template_param(self):
  194. """Handle a template parameter at the head of the string."""
  195. if self._context & contexts.TEMPLATE_NAME:
  196. self._verify_safe(["\n", "{", "}", "[", "]"])
  197. self._context ^= contexts.TEMPLATE_NAME
  198. if self._context & contexts.TEMPLATE_PARAM_VALUE:
  199. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  200. self._context |= contexts.TEMPLATE_PARAM_KEY
  201. self._write(tokens.TemplateParamSeparator())
  202. def _handle_template_param_value(self):
  203. """Handle a template parameter's value at the head of the string."""
  204. self._verify_safe(["\n", "{{", "}}"])
  205. self._context ^= contexts.TEMPLATE_PARAM_KEY
  206. self._context |= contexts.TEMPLATE_PARAM_VALUE
  207. self._write(tokens.TemplateParamEquals())
  208. def _handle_template_end(self):
  209. """Handle the end of a template at the head of the string."""
  210. if self._context & contexts.TEMPLATE_NAME:
  211. self._verify_safe(["\n", "{", "}", "[", "]"])
  212. self._head += 1
  213. return self._pop()
  214. def _handle_argument_separator(self):
  215. """Handle the separator between an argument's name and default."""
  216. self._verify_safe(["\n", "{{", "}}"])
  217. self._context ^= contexts.ARGUMENT_NAME
  218. self._context |= contexts.ARGUMENT_DEFAULT
  219. self._write(tokens.ArgumentSeparator())
  220. def _handle_argument_end(self):
  221. """Handle the end of an argument at the head of the string."""
  222. if self._context & contexts.ARGUMENT_NAME:
  223. self._verify_safe(["\n", "{{", "}}"])
  224. self._head += 2
  225. return self._pop()
  226. def _parse_heading(self):
  227. """Parse a section heading at the head of the wikicode string."""
  228. self._global |= contexts.GL_HEADING
  229. reset = self._head
  230. self._head += 1
  231. best = 1
  232. while self._read() == "=":
  233. best += 1
  234. self._head += 1
  235. context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
  236. try:
  237. title, level = self._parse(context)
  238. except BadRoute:
  239. self._head = reset + best - 1
  240. self._write_text("=" * best)
  241. else:
  242. self._write(tokens.HeadingStart(level=level))
  243. if level < best:
  244. self._write_text("=" * (best - level))
  245. self._write_all(title)
  246. self._write(tokens.HeadingEnd())
  247. finally:
  248. self._global ^= contexts.GL_HEADING
  249. def _handle_heading_end(self):
  250. """Handle the end of a section heading at the head of the string."""
  251. reset = self._head
  252. self._head += 1
  253. best = 1
  254. while self._read() == "=":
  255. best += 1
  256. self._head += 1
  257. current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
  258. level = min(current, min(best, 6))
  259. try:
  260. after, after_level = self._parse(self._context)
  261. except BadRoute:
  262. if level < best:
  263. self._write_text("=" * (best - level))
  264. self._head = reset + best - 1
  265. return self._pop(), level
  266. else:
  267. self._write_text("=" * best)
  268. self._write_all(after)
  269. return self._pop(), after_level
  270. def _really_parse_entity(self):
  271. """Actually parse a HTML entity and ensure that it is valid."""
  272. self._write(tokens.HTMLEntityStart())
  273. self._head += 1
  274. this = self._read(strict=True)
  275. if this == "#":
  276. numeric = True
  277. self._write(tokens.HTMLEntityNumeric())
  278. self._head += 1
  279. this = self._read(strict=True)
  280. if this[0].lower() == "x":
  281. hexadecimal = True
  282. self._write(tokens.HTMLEntityHex(char=this[0]))
  283. this = this[1:]
  284. if not this:
  285. self._fail_route()
  286. else:
  287. hexadecimal = False
  288. else:
  289. numeric = hexadecimal = False
  290. valid = string.hexdigits if hexadecimal else string.digits
  291. if not numeric and not hexadecimal:
  292. valid += string.ascii_letters
  293. if not all([char in valid for char in this]):
  294. self._fail_route()
  295. self._head += 1
  296. if self._read() != ";":
  297. self._fail_route()
  298. if numeric:
  299. test = int(this, 16) if hexadecimal else int(this)
  300. if test < 1 or test > 0x10FFFF:
  301. self._fail_route()
  302. else:
  303. if this not in htmlentities.entitydefs:
  304. self._fail_route()
  305. self._write(tokens.Text(text=this))
  306. self._write(tokens.HTMLEntityEnd())
  307. def _parse_entity(self):
  308. """Parse a HTML entity at the head of the wikicode string."""
  309. reset = self._head
  310. self._push()
  311. try:
  312. self._really_parse_entity()
  313. except BadRoute:
  314. self._head = reset
  315. self._write_text(self._read())
  316. else:
  317. self._write_all(self._pop())
  318. def _parse(self, context=0):
  319. """Parse the wikicode string, using *context* for when to stop."""
  320. self._push(context)
  321. while True:
  322. this = self._read()
  323. if this not in self.MARKERS:
  324. self._write_text(this)
  325. self._head += 1
  326. continue
  327. if this is self.END:
  328. fail = contexts.TEMPLATE | contexts.ARGUMENT | contexts.HEADING
  329. if self._context & fail:
  330. self._fail_route()
  331. return self._pop()
  332. next = self._read(1)
  333. if this == next == "{":
  334. self._parse_template_or_argument()
  335. elif this == "|" and self._context & contexts.TEMPLATE:
  336. self._handle_template_param()
  337. elif this == "=" and self._context & contexts.TEMPLATE_PARAM_KEY:
  338. self._handle_template_param_value()
  339. elif this == next == "}" and self._context & contexts.TEMPLATE:
  340. return self._handle_template_end()
  341. elif this == "|" and self._context & contexts.ARGUMENT_NAME:
  342. self._handle_argument_separator()
  343. elif this == next == "}" and self._context & contexts.ARGUMENT:
  344. if self._read(2) == "}":
  345. return self._handle_argument_end()
  346. else:
  347. self._write_text("}")
  348. elif this == "=" and not self._global & contexts.GL_HEADING:
  349. if self._read(-1) in ("\n", self.START):
  350. self._parse_heading()
  351. else:
  352. self._write_text("=")
  353. elif this == "=" and self._context & contexts.HEADING:
  354. return self._handle_heading_end()
  355. elif this == "\n" and self._context & contexts.HEADING:
  356. self._fail_route()
  357. elif this == "&":
  358. self._parse_entity()
  359. else:
  360. self._write_text(this)
  361. self._head += 1
  362. def tokenize(self, text):
  363. """Build a list of tokens from a string of wikicode and return it."""
  364. split = self.regex.split(text)
  365. self._text = [segment for segment in split if segment]
  366. return self._parse()