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.
 
 
 
 

499 lines
18 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. from . import contexts
  26. from . import tokens
  27. from ..compat import htmlentities
  28. __all__ = ["Tokenizer"]
  29. class BadRoute(Exception):
  30. """Raised internally when the current tokenization route is invalid."""
  31. pass
  32. class Tokenizer(object):
  33. """Creates a list of tokens from a string of wikicode."""
  34. START = object()
  35. END = object()
  36. MARKERS = ["{", "}", "[", "]", "<", ">", "|", "=", "&", "#", "*", ";", ":",
  37. "/", "-", "!", "\n", END]
  38. regex = re.compile(r"([{}\[\]<>|=&#*;:/\-!\n])", flags=re.IGNORECASE)
  39. def __init__(self):
  40. self._text = None
  41. self._head = 0
  42. self._stacks = []
  43. self._global = 0
  44. @property
  45. def _stack(self):
  46. """The current token stack."""
  47. return self._stacks[-1][0]
  48. @property
  49. def _context(self):
  50. """The current token context."""
  51. return self._stacks[-1][1]
  52. @_context.setter
  53. def _context(self, value):
  54. self._stacks[-1][1] = value
  55. @property
  56. def _textbuffer(self):
  57. """The current textbuffer."""
  58. return self._stacks[-1][2]
  59. @_textbuffer.setter
  60. def _textbuffer(self, value):
  61. self._stacks[-1][2] = value
  62. def _push(self, context=0):
  63. """Add a new token stack, context, and textbuffer to the list."""
  64. self._stacks.append([[], context, []])
  65. def _push_textbuffer(self):
  66. """Push the textbuffer onto the stack as a Text node and clear it."""
  67. if self._textbuffer:
  68. self._stack.append(tokens.Text(text="".join(self._textbuffer)))
  69. self._textbuffer = []
  70. def _pop(self, keep_context=False):
  71. """Pop the current stack/context/textbuffer, returing the stack.
  72. If *keep_context* is ``True``, then we will replace the underlying
  73. stack's context with the current stack's.
  74. """
  75. self._push_textbuffer()
  76. if keep_context:
  77. context = self._context
  78. stack = self._stacks.pop()[0]
  79. self._context = context
  80. return stack
  81. return self._stacks.pop()[0]
  82. def _fail_route(self):
  83. """Fail the current tokenization route.
  84. Discards the current stack/context/textbuffer and raises
  85. :py:exc:`~.BadRoute`.
  86. """
  87. self._pop()
  88. raise BadRoute()
  89. def _write(self, token):
  90. """Write a token to the end of the current token stack."""
  91. self._push_textbuffer()
  92. self._stack.append(token)
  93. def _write_first(self, token):
  94. """Write a token to the beginning of the current token stack."""
  95. self._push_textbuffer()
  96. self._stack.insert(0, token)
  97. def _write_text(self, text):
  98. """Write text to the current textbuffer."""
  99. self._textbuffer.append(text)
  100. def _write_all(self, tokenlist):
  101. """Write a series of tokens to the current stack at once."""
  102. if tokenlist and isinstance(tokenlist[0], tokens.Text):
  103. self._write_text(tokenlist.pop(0).text)
  104. self._push_textbuffer()
  105. self._stack.extend(tokenlist)
  106. def _write_text_then_stack(self, text):
  107. """Pop the current stack, write *text*, and then write the stack."""
  108. stack = self._pop()
  109. self._write_text(text)
  110. if stack:
  111. self._write_all(stack)
  112. self._head -= 1
  113. def _read(self, delta=0, wrap=False, strict=False):
  114. """Read the value at a relative point in the wikicode.
  115. The value is read from :py:attr:`self._head <_head>` plus the value of
  116. *delta* (which can be negative). If *wrap* is ``False``, we will not
  117. allow attempts to read from the end of the string if ``self._head +
  118. delta`` is negative. If *strict* is ``True``, the route will be failed
  119. (with :py:meth:`_fail_route`) if we try to read from past the end of
  120. the string; otherwise, :py:attr:`self.END <END>` is returned. If we try
  121. to read from before the start of the string, :py:attr:`self.START
  122. <START>` is returned.
  123. """
  124. index = self._head + delta
  125. if index < 0 and (not wrap or abs(index) > len(self._text)):
  126. return self.START
  127. try:
  128. return self._text[index]
  129. except IndexError:
  130. if strict:
  131. self._fail_route()
  132. return self.END
  133. def _parse_template_or_argument(self):
  134. """Parse a template or argument at the head of the wikicode string."""
  135. self._head += 2
  136. braces = 2
  137. while self._read() == "{":
  138. self._head += 1
  139. braces += 1
  140. self._push()
  141. while braces:
  142. if braces == 1:
  143. return self._write_text_then_stack("{")
  144. if braces == 2:
  145. try:
  146. self._parse_template()
  147. except BadRoute:
  148. return self._write_text_then_stack("{{")
  149. break
  150. try:
  151. self._parse_argument()
  152. braces -= 3
  153. except BadRoute:
  154. try:
  155. self._parse_template()
  156. braces -= 2
  157. except BadRoute:
  158. return self._write_text_then_stack("{" * braces)
  159. if braces:
  160. self._head += 1
  161. self._write_all(self._pop())
  162. def _parse_template(self):
  163. """Parse a template at the head of the wikicode string."""
  164. reset = self._head
  165. try:
  166. template = self._parse(contexts.TEMPLATE_NAME)
  167. except BadRoute:
  168. self._head = reset
  169. raise
  170. self._write_first(tokens.TemplateOpen())
  171. self._write_all(template)
  172. self._write(tokens.TemplateClose())
  173. def _parse_argument(self):
  174. """Parse an argument at the head of the wikicode string."""
  175. reset = self._head
  176. try:
  177. argument = self._parse(contexts.ARGUMENT_NAME)
  178. except BadRoute:
  179. self._head = reset
  180. raise
  181. self._write_first(tokens.ArgumentOpen())
  182. self._write_all(argument)
  183. self._write(tokens.ArgumentClose())
  184. def _verify_safe(self, unsafes, strip=True):
  185. """Verify that there are no unsafe characters in the current stack.
  186. The route will be failed if the name contains any element of *unsafes*
  187. in it. This is used when parsing template names, parameter keys, and so
  188. on, which cannot contain newlines and some other characters. If *strip*
  189. is ``True``, the text will be stripped of whitespace, since this is
  190. allowed at the ends of certain elements but not between text.
  191. """
  192. self._push_textbuffer()
  193. if self._stack:
  194. text = [tok for tok in self._stack if isinstance(tok, tokens.Text)]
  195. text = "".join([token.text for token in text])
  196. if strip:
  197. text = text.strip()
  198. if text and any([unsafe in text for unsafe in unsafes]):
  199. self._fail_route()
  200. def _handle_template_param(self):
  201. """Handle a template parameter at the head of the string."""
  202. if self._context & contexts.TEMPLATE_NAME:
  203. self._verify_safe(["\n", "{", "}", "[", "]"])
  204. self._context ^= contexts.TEMPLATE_NAME
  205. elif self._context & contexts.TEMPLATE_PARAM_VALUE:
  206. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  207. elif self._context & contexts.TEMPLATE_PARAM_KEY:
  208. self._write_all(self._pop(keep_context=True))
  209. self._context |= contexts.TEMPLATE_PARAM_KEY
  210. self._write(tokens.TemplateParamSeparator())
  211. self._push(self._context)
  212. def _handle_template_param_value(self):
  213. """Handle a template parameter's value at the head of the string."""
  214. try:
  215. self._verify_safe(["\n", "{{", "}}"])
  216. except BadRoute:
  217. self._pop()
  218. raise
  219. self._write_all(self._pop(keep_context=True))
  220. self._context ^= contexts.TEMPLATE_PARAM_KEY
  221. self._context |= contexts.TEMPLATE_PARAM_VALUE
  222. self._write(tokens.TemplateParamEquals())
  223. def _handle_template_end(self):
  224. """Handle the end of a template at the head of the string."""
  225. if self._context & contexts.TEMPLATE_NAME:
  226. self._verify_safe(["\n", "{", "}", "[", "]"])
  227. elif self._context & contexts.TEMPLATE_PARAM_KEY:
  228. self._write_all(self._pop(keep_context=True))
  229. self._head += 1
  230. return self._pop()
  231. def _handle_argument_separator(self):
  232. """Handle the separator between an argument's name and default."""
  233. self._verify_safe(["\n", "{{", "}}"])
  234. self._context ^= contexts.ARGUMENT_NAME
  235. self._context |= contexts.ARGUMENT_DEFAULT
  236. self._write(tokens.ArgumentSeparator())
  237. def _handle_argument_end(self):
  238. """Handle the end of an argument at the head of the string."""
  239. if self._context & contexts.ARGUMENT_NAME:
  240. self._verify_safe(["\n", "{{", "}}"])
  241. self._head += 2
  242. return self._pop()
  243. def _parse_wikilink(self):
  244. """Parse an internal wikilink at the head of the wikicode string."""
  245. self._head += 2
  246. reset = self._head - 1
  247. try:
  248. wikilink = self._parse(contexts.WIKILINK_TITLE)
  249. except BadRoute:
  250. self._head = reset
  251. self._write_text("[[")
  252. else:
  253. self._write(tokens.WikilinkOpen())
  254. self._write_all(wikilink)
  255. self._write(tokens.WikilinkClose())
  256. def _handle_wikilink_separator(self):
  257. """Handle the separator between a wikilink's title and its text."""
  258. self._verify_safe(["\n", "{", "}", "[", "]"], strip=False)
  259. self._context ^= contexts.WIKILINK_TITLE
  260. self._context |= contexts.WIKILINK_TEXT
  261. self._write(tokens.WikilinkSeparator())
  262. def _handle_wikilink_end(self):
  263. """Handle the end of a wikilink at the head of the string."""
  264. if self._context & contexts.WIKILINK_TITLE:
  265. self._verify_safe(["\n", "{", "}", "[", "]"], strip=False)
  266. self._head += 1
  267. return self._pop()
  268. def _parse_heading(self):
  269. """Parse a section heading at the head of the wikicode string."""
  270. self._global |= contexts.GL_HEADING
  271. reset = self._head
  272. self._head += 1
  273. best = 1
  274. while self._read() == "=":
  275. best += 1
  276. self._head += 1
  277. context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
  278. try:
  279. title, level = self._parse(context)
  280. except BadRoute:
  281. self._head = reset + best - 1
  282. self._write_text("=" * best)
  283. else:
  284. self._write(tokens.HeadingStart(level=level))
  285. if level < best:
  286. self._write_text("=" * (best - level))
  287. self._write_all(title)
  288. self._write(tokens.HeadingEnd())
  289. finally:
  290. self._global ^= contexts.GL_HEADING
  291. def _handle_heading_end(self):
  292. """Handle the end of a section heading at the head of the string."""
  293. reset = self._head
  294. self._head += 1
  295. best = 1
  296. while self._read() == "=":
  297. best += 1
  298. self._head += 1
  299. current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
  300. level = min(current, min(best, 6))
  301. try: # Try to check for a heading closure after this one
  302. after, after_level = self._parse(self._context)
  303. except BadRoute:
  304. if level < best:
  305. self._write_text("=" * (best - level))
  306. self._head = reset + best - 1
  307. return self._pop(), level
  308. else: # Found another closure
  309. self._write_text("=" * best)
  310. self._write_all(after)
  311. return self._pop(), after_level
  312. def _really_parse_entity(self):
  313. """Actually parse an HTML entity and ensure that it is valid."""
  314. self._write(tokens.HTMLEntityStart())
  315. self._head += 1
  316. this = self._read(strict=True)
  317. if this == "#":
  318. numeric = True
  319. self._write(tokens.HTMLEntityNumeric())
  320. self._head += 1
  321. this = self._read(strict=True)
  322. if this[0].lower() == "x":
  323. hexadecimal = True
  324. self._write(tokens.HTMLEntityHex(char=this[0]))
  325. this = this[1:]
  326. if not this:
  327. self._fail_route()
  328. else:
  329. hexadecimal = False
  330. else:
  331. numeric = hexadecimal = False
  332. valid = "0123456789abcdefABCDEF" if hexadecimal else "0123456789"
  333. if not numeric and not hexadecimal:
  334. valid += "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  335. if not all([char in valid for char in this]):
  336. self._fail_route()
  337. self._head += 1
  338. if self._read() != ";":
  339. self._fail_route()
  340. if numeric:
  341. test = int(this, 16) if hexadecimal else int(this)
  342. if test < 1 or test > 0x10FFFF:
  343. self._fail_route()
  344. else:
  345. if this not in htmlentities.entitydefs:
  346. self._fail_route()
  347. self._write(tokens.Text(text=this))
  348. self._write(tokens.HTMLEntityEnd())
  349. def _parse_entity(self):
  350. """Parse an HTML entity at the head of the wikicode string."""
  351. reset = self._head
  352. self._push()
  353. try:
  354. self._really_parse_entity()
  355. except BadRoute:
  356. self._head = reset
  357. self._write_text(self._read())
  358. else:
  359. self._write_all(self._pop())
  360. def _parse_comment(self):
  361. """Parse an HTML comment at the head of the wikicode string."""
  362. self._head += 4
  363. reset = self._head - 1
  364. try:
  365. comment = self._parse(contexts.COMMENT)
  366. except BadRoute:
  367. self._head = reset
  368. self._write_text("<!--")
  369. else:
  370. self._write(tokens.CommentStart())
  371. self._write_all(comment)
  372. self._write(tokens.CommentEnd())
  373. self._head += 2
  374. def _parse(self, context=0):
  375. """Parse the wikicode string, using *context* for when to stop."""
  376. self._push(context)
  377. while True:
  378. this = self._read()
  379. if this not in self.MARKERS:
  380. self._write_text(this)
  381. self._head += 1
  382. continue
  383. if this is self.END:
  384. fail = (contexts.TEMPLATE | contexts.ARGUMENT |
  385. contexts.WIKILINK | contexts.HEADING |
  386. contexts.COMMENT)
  387. if self._context & contexts.TEMPLATE_PARAM_KEY:
  388. self._pop()
  389. if self._context & fail:
  390. self._fail_route()
  391. return self._pop()
  392. next = self._read(1)
  393. if self._context & contexts.COMMENT:
  394. if this == next == "-" and self._read(2) == ">":
  395. return self._pop()
  396. else:
  397. self._write_text(this)
  398. elif this == next == "{":
  399. self._parse_template_or_argument()
  400. elif this == "|" and self._context & contexts.TEMPLATE:
  401. self._handle_template_param()
  402. elif this == "=" and self._context & contexts.TEMPLATE_PARAM_KEY:
  403. self._handle_template_param_value()
  404. elif this == next == "}" and self._context & contexts.TEMPLATE:
  405. return self._handle_template_end()
  406. elif this == "|" and self._context & contexts.ARGUMENT_NAME:
  407. self._handle_argument_separator()
  408. elif this == next == "}" and self._context & contexts.ARGUMENT:
  409. if self._read(2) == "}":
  410. return self._handle_argument_end()
  411. else:
  412. self._write_text("}")
  413. elif this == next == "[":
  414. if not self._context & contexts.WIKILINK_TITLE:
  415. self._parse_wikilink()
  416. else:
  417. self._write_text("[")
  418. elif this == "|" and self._context & contexts.WIKILINK_TITLE:
  419. self._handle_wikilink_separator()
  420. elif this == next == "]" and self._context & contexts.WIKILINK:
  421. return self._handle_wikilink_end()
  422. elif this == "=" and not self._global & contexts.GL_HEADING:
  423. if self._read(-1) in ("\n", self.START):
  424. self._parse_heading()
  425. else:
  426. self._write_text("=")
  427. elif this == "=" and self._context & contexts.HEADING:
  428. return self._handle_heading_end()
  429. elif this == "\n" and self._context & contexts.HEADING:
  430. self._fail_route()
  431. elif this == "&":
  432. self._parse_entity()
  433. elif this == "<" and next == "!":
  434. if self._read(2) == self._read(3) == "-":
  435. self._parse_comment()
  436. else:
  437. self._write_text(this)
  438. else:
  439. self._write_text(this)
  440. self._head += 1
  441. def tokenize(self, text):
  442. """Build a list of tokens from a string of wikicode and return it."""
  443. split = self.regex.split(text)
  444. self._text = [segment for segment in split if segment]
  445. return self._parse()