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.
 
 
 
 

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