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.
 
 
 
 

303 lines
12 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2016 Ben Kurtovic <ben.kurtovic@gmail.com>
  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 . import tokens, ParserError
  24. from ..compat import str
  25. from ..nodes import (Argument, Comment, ExternalLink, Heading, HTMLEntity, Tag,
  26. Template, Text, Wikilink)
  27. from ..nodes.extras import Attribute, Parameter
  28. from ..smart_list import smart_list
  29. from ..wikicode import Wikicode
  30. __all__ = ["Builder"]
  31. _HANDLERS = {
  32. tokens.Text: lambda self, token: Text(token.text)
  33. }
  34. def _add_handler(token_type):
  35. """Create a decorator that adds a handler function to the lookup table."""
  36. def decorator(func):
  37. """Add a handler function to the lookup table."""
  38. _HANDLERS[token_type] = func
  39. return func
  40. return decorator
  41. class Builder(object):
  42. """Builds a tree of nodes out of a sequence of tokens.
  43. To use, pass a list of :class:`.Token`\\ s to the :meth:`build` method. The
  44. list will be exhausted as it is parsed and a :class:`.Wikicode` object
  45. containing the node tree will be returned.
  46. """
  47. def __init__(self):
  48. self._tokens = []
  49. self._stacks = []
  50. def _push(self):
  51. """Push a new node list onto the stack."""
  52. self._stacks.append([])
  53. def _pop(self):
  54. """Pop the current node list off of the stack.
  55. The raw node list is wrapped in a :class:`.SmartList` and then in a
  56. :class:`.Wikicode` object.
  57. """
  58. return Wikicode(smart_list(self._stacks.pop()))
  59. def _write(self, item):
  60. """Append a node to the current node list."""
  61. self._stacks[-1].append(item)
  62. def _handle_parameter(self, default):
  63. """Handle a case where a parameter is at the head of the tokens.
  64. *default* is the value to use if no parameter name is defined.
  65. """
  66. key = None
  67. showkey = False
  68. self._push()
  69. while self._tokens:
  70. token = self._tokens.pop()
  71. if isinstance(token, tokens.TemplateParamEquals):
  72. key = self._pop()
  73. showkey = True
  74. self._push()
  75. elif isinstance(token, (tokens.TemplateParamSeparator,
  76. tokens.TemplateClose)):
  77. self._tokens.append(token)
  78. value = self._pop()
  79. if key is None:
  80. key = Wikicode(smart_list([Text(str(default))]))
  81. return Parameter(key, value, showkey)
  82. else:
  83. self._write(self._handle_token(token))
  84. raise ParserError("_handle_parameter() missed a close token")
  85. @_add_handler(tokens.TemplateOpen)
  86. def _handle_template(self, token):
  87. """Handle a case where a template is at the head of the tokens."""
  88. params = []
  89. default = 1
  90. self._push()
  91. while self._tokens:
  92. token = self._tokens.pop()
  93. if isinstance(token, tokens.TemplateParamSeparator):
  94. if not params:
  95. name = self._pop()
  96. param = self._handle_parameter(default)
  97. params.append(param)
  98. if not param.showkey:
  99. default += 1
  100. elif isinstance(token, tokens.TemplateClose):
  101. if not params:
  102. name = self._pop()
  103. return Template(name, params)
  104. else:
  105. self._write(self._handle_token(token))
  106. raise ParserError("_handle_template() missed a close token")
  107. @_add_handler(tokens.ArgumentOpen)
  108. def _handle_argument(self, token):
  109. """Handle a case where an argument is at the head of the tokens."""
  110. name = None
  111. self._push()
  112. while self._tokens:
  113. token = self._tokens.pop()
  114. if isinstance(token, tokens.ArgumentSeparator):
  115. name = self._pop()
  116. self._push()
  117. elif isinstance(token, tokens.ArgumentClose):
  118. if name is not None:
  119. return Argument(name, self._pop())
  120. return Argument(self._pop())
  121. else:
  122. self._write(self._handle_token(token))
  123. raise ParserError("_handle_argument() missed a close token")
  124. @_add_handler(tokens.WikilinkOpen)
  125. def _handle_wikilink(self, token):
  126. """Handle a case where a wikilink is at the head of the tokens."""
  127. title = None
  128. self._push()
  129. while self._tokens:
  130. token = self._tokens.pop()
  131. if isinstance(token, tokens.WikilinkSeparator):
  132. title = self._pop()
  133. self._push()
  134. elif isinstance(token, tokens.WikilinkClose):
  135. if title is not None:
  136. return Wikilink(title, self._pop())
  137. return Wikilink(self._pop())
  138. else:
  139. self._write(self._handle_token(token))
  140. raise ParserError("_handle_wikilink() missed a close token")
  141. @_add_handler(tokens.ExternalLinkOpen)
  142. def _handle_external_link(self, token):
  143. """Handle when an external link is at the head of the tokens."""
  144. brackets, url = token.brackets, None
  145. self._push()
  146. while self._tokens:
  147. token = self._tokens.pop()
  148. if isinstance(token, tokens.ExternalLinkSeparator):
  149. url = self._pop()
  150. self._push()
  151. elif isinstance(token, tokens.ExternalLinkClose):
  152. if url is not None:
  153. return ExternalLink(url, self._pop(), brackets)
  154. return ExternalLink(self._pop(), brackets=brackets)
  155. else:
  156. self._write(self._handle_token(token))
  157. raise ParserError("_handle_external_link() missed a close token")
  158. @_add_handler(tokens.HTMLEntityStart)
  159. def _handle_entity(self, token):
  160. """Handle a case where an HTML entity is at the head of the tokens."""
  161. token = self._tokens.pop()
  162. if isinstance(token, tokens.HTMLEntityNumeric):
  163. token = self._tokens.pop()
  164. if isinstance(token, tokens.HTMLEntityHex):
  165. text = self._tokens.pop()
  166. self._tokens.pop() # Remove HTMLEntityEnd
  167. return HTMLEntity(text.text, named=False, hexadecimal=True,
  168. hex_char=token.char)
  169. self._tokens.pop() # Remove HTMLEntityEnd
  170. return HTMLEntity(token.text, named=False, hexadecimal=False)
  171. self._tokens.pop() # Remove HTMLEntityEnd
  172. return HTMLEntity(token.text, named=True, hexadecimal=False)
  173. @_add_handler(tokens.HeadingStart)
  174. def _handle_heading(self, token):
  175. """Handle a case where a heading is at the head of the tokens."""
  176. level = token.level
  177. self._push()
  178. while self._tokens:
  179. token = self._tokens.pop()
  180. if isinstance(token, tokens.HeadingEnd):
  181. title = self._pop()
  182. return Heading(title, level)
  183. else:
  184. self._write(self._handle_token(token))
  185. raise ParserError("_handle_heading() missed a close token")
  186. @_add_handler(tokens.CommentStart)
  187. def _handle_comment(self, token):
  188. """Handle a case where an HTML comment is at the head of the tokens."""
  189. self._push()
  190. while self._tokens:
  191. token = self._tokens.pop()
  192. if isinstance(token, tokens.CommentEnd):
  193. contents = self._pop()
  194. return Comment(contents)
  195. else:
  196. self._write(self._handle_token(token))
  197. raise ParserError("_handle_comment() missed a close token")
  198. def _handle_attribute(self, start):
  199. """Handle a case where a tag attribute is at the head of the tokens."""
  200. name = quotes = None
  201. self._push()
  202. while self._tokens:
  203. token = self._tokens.pop()
  204. if isinstance(token, tokens.TagAttrEquals):
  205. name = self._pop()
  206. self._push()
  207. elif isinstance(token, tokens.TagAttrQuote):
  208. quotes = token.char
  209. elif isinstance(token, (tokens.TagAttrStart, tokens.TagCloseOpen,
  210. tokens.TagCloseSelfclose)):
  211. self._tokens.append(token)
  212. if name:
  213. value = self._pop()
  214. else:
  215. name, value = self._pop(), None
  216. return Attribute(name, value, quotes, start.pad_first,
  217. start.pad_before_eq, start.pad_after_eq)
  218. else:
  219. self._write(self._handle_token(token))
  220. raise ParserError("_handle_attribute() missed a close token")
  221. @_add_handler(tokens.TagOpenOpen)
  222. def _handle_tag(self, token):
  223. """Handle a case where a tag is at the head of the tokens."""
  224. close_tokens = (tokens.TagCloseSelfclose, tokens.TagCloseClose)
  225. implicit, attrs, contents, closing_tag = False, [], None, None
  226. wiki_markup, invalid = token.wiki_markup, token.invalid or False
  227. wiki_style_separator, closing_wiki_markup = None, wiki_markup
  228. self._push()
  229. while self._tokens:
  230. token = self._tokens.pop()
  231. if isinstance(token, tokens.TagAttrStart):
  232. attrs.append(self._handle_attribute(token))
  233. elif isinstance(token, tokens.TagCloseOpen):
  234. wiki_style_separator = token.wiki_markup
  235. padding = token.padding or ""
  236. tag = self._pop()
  237. self._push()
  238. elif isinstance(token, tokens.TagOpenClose):
  239. closing_wiki_markup = token.wiki_markup
  240. contents = self._pop()
  241. self._push()
  242. elif isinstance(token, close_tokens):
  243. if isinstance(token, tokens.TagCloseSelfclose):
  244. closing_wiki_markup = token.wiki_markup
  245. tag = self._pop()
  246. self_closing = True
  247. padding = token.padding or ""
  248. implicit = token.implicit or False
  249. else:
  250. self_closing = False
  251. closing_tag = self._pop()
  252. return Tag(tag, contents, attrs, wiki_markup, self_closing,
  253. invalid, implicit, padding, closing_tag,
  254. wiki_style_separator, closing_wiki_markup)
  255. else:
  256. self._write(self._handle_token(token))
  257. raise ParserError("_handle_tag() missed a close token")
  258. def _handle_token(self, token):
  259. """Handle a single token."""
  260. try:
  261. return _HANDLERS[type(token)](self, token)
  262. except KeyError:
  263. err = "_handle_token() got unexpected {0}"
  264. raise ParserError(err.format(type(token).__name__))
  265. def build(self, tokenlist):
  266. """Build a Wikicode object from a list tokens and return it."""
  267. self._tokens = tokenlist
  268. self._tokens.reverse()
  269. self._push()
  270. while self._tokens:
  271. node = self._handle_token(self._tokens.pop())
  272. self._write(node)
  273. return self._pop()
  274. del _add_handler