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.
 
 
 
 

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