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.
 
 
 
 

207 lines
8.0 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 . import tokens
  24. from ..compat import str
  25. from ..nodes import Heading, HTMLEntity, Tag, Template, Text
  26. from ..nodes.extras import Attribute, Parameter
  27. from ..smart_list import SmartList
  28. from ..wikicode import Wikicode
  29. __all__ = ["Builder"]
  30. class Builder(object):
  31. """Combines a sequence of tokens into a tree of ``Wikicode`` objects.
  32. To use, pass a list of :py:class:`~mwparserfromhell.parser.tokens.Token`\ s
  33. to the :py:meth:`build` method. The list will be exhausted as it is parsed
  34. and a :py:class:`~mwparserfromhell.wikicode.Wikicode` object will be
  35. returned.
  36. """
  37. def __init__(self):
  38. self._tokens = []
  39. self._stacks = []
  40. def _wrap(self, nodes):
  41. """Properly wrap a list of nodes in a ``Wikicode`` object."""
  42. return Wikicode(SmartList(nodes))
  43. def _push(self):
  44. """Push a new node list onto the stack."""
  45. self._stacks.append([])
  46. def _pop(self, wrap=True):
  47. """Pop the current node list off of the stack.
  48. If *wrap* is ``True``, we will call :py:meth:`_wrap` on the list.
  49. """
  50. if wrap:
  51. return self._wrap(self._stacks.pop())
  52. return self._stacks.pop()
  53. def _write(self, item):
  54. """Append a node to the current node list."""
  55. self._stacks[-1].append(item)
  56. def _handle_parameter(self, default):
  57. """Handle a case where a parameter is at the head of the tokens.
  58. *default* is the value to use if no parameter name is defined.
  59. """
  60. key = None
  61. showkey = False
  62. self._push()
  63. while self._tokens:
  64. token = self._tokens.pop()
  65. if isinstance(token, tokens.TemplateParamEquals):
  66. key = self._pop()
  67. showkey = True
  68. self._push()
  69. elif isinstance(token, (tokens.TemplateParamSeparator,
  70. tokens.TemplateClose)):
  71. self._tokens.append(token)
  72. value = self._pop()
  73. if not key:
  74. key = self._wrap([Text(str(default))])
  75. return Parameter(key, value, showkey)
  76. else:
  77. self._write(self._handle_token(token))
  78. def _handle_template(self):
  79. """Handle a case where a template is at the head of the tokens."""
  80. params = []
  81. default = 1
  82. self._push()
  83. while self._tokens:
  84. token = self._tokens.pop()
  85. if isinstance(token, tokens.TemplateParamSeparator):
  86. if not params:
  87. name = self._pop()
  88. param = self._handle_parameter(default)
  89. params.append(param)
  90. if not param.showkey:
  91. default += 1
  92. elif isinstance(token, tokens.TemplateClose):
  93. if not params:
  94. name = self._pop()
  95. return Template(name, params)
  96. else:
  97. self._write(self._handle_token(token))
  98. def _handle_entity(self):
  99. """Handle a case where a HTML entity is at the head of the tokens."""
  100. token = self._tokens.pop()
  101. if isinstance(token, tokens.HTMLEntityNumeric):
  102. token = self._tokens.pop()
  103. if isinstance(token, tokens.HTMLEntityHex):
  104. text = self._tokens.pop()
  105. self._tokens.pop() # Remove HTMLEntityEnd
  106. return HTMLEntity(text.text, named=False, hexadecimal=True,
  107. hex_char=token.char)
  108. self._tokens.pop() # Remove HTMLEntityEnd
  109. return HTMLEntity(token.text, named=False, hexadecimal=False)
  110. self._tokens.pop() # Remove HTMLEntityEnd
  111. return HTMLEntity(token.text, named=True, hexadecimal=False)
  112. def _handle_heading(self, token):
  113. """Handle a case where a heading is at the head of the tokens."""
  114. level = token.level
  115. self._push()
  116. while self._tokens:
  117. token = self._tokens.pop()
  118. if isinstance(token, tokens.HeadingEnd):
  119. title = self._pop()
  120. return Heading(title, level)
  121. else:
  122. self._write(self._handle_token(token))
  123. def _handle_attribute(self):
  124. """Handle a case where a tag attribute is at the head of the tokens."""
  125. name, quoted = None, False
  126. self._push()
  127. while self._tokens:
  128. token = self._tokens.pop()
  129. if isinstance(token, tokens.TagAttrEquals):
  130. name = self._pop()
  131. self._push()
  132. elif isinstance(token, tokens.TagAttrQuote):
  133. quoted = True
  134. elif isinstance(token, (tokens.TagAttrStart,
  135. tokens.TagCloseOpen)):
  136. self._tokens.append(token)
  137. if name is not None:
  138. return Attribute(name, self._pop(), quoted)
  139. return Attribute(self._pop(), quoted=quoted)
  140. else:
  141. self._write(self._handle_token(token))
  142. def _handle_tag(self, token):
  143. """Handle a case where a tag is at the head of the tokens."""
  144. type_, showtag = token.type, token.showtag
  145. attrs = []
  146. self._push()
  147. while self._tokens:
  148. token = self._tokens.pop()
  149. if isinstance(token, tokens.TagAttrStart):
  150. attrs.append(self._handle_attribute())
  151. elif isinstance(token, tokens.TagCloseOpen):
  152. open_pad = token.padding
  153. tag = self._pop()
  154. self._push()
  155. elif isinstance(token, tokens.TagCloseSelfclose):
  156. tag = self._pop()
  157. return Tag(type_, tag, attrs=attrs, showtag=showtag,
  158. self_closing=True, open_padding=token.padding)
  159. elif isinstance(token, tokens.TagOpenClose):
  160. contents = self._pop()
  161. elif isinstance(token, tokens.TagCloseClose):
  162. return Tag(type_, tag, contents, attrs, showtag, False,
  163. open_pad, token.padding)
  164. else:
  165. self._write(self._handle_token(token))
  166. def _handle_token(self, token):
  167. """Handle a single token."""
  168. if isinstance(token, tokens.Text):
  169. return Text(token.text)
  170. elif isinstance(token, tokens.TemplateOpen):
  171. return self._handle_template()
  172. elif isinstance(token, tokens.HTMLEntityStart):
  173. return self._handle_entity()
  174. elif isinstance(token, tokens.HeadingStart):
  175. return self._handle_heading(token)
  176. elif isinstance(token, tokens.TagOpenOpen):
  177. return self._handle_tag(token)
  178. def build(self, tokenlist):
  179. """Build a Wikicode object from a list tokens and return it."""
  180. self._tokens = tokenlist
  181. self._tokens.reverse()
  182. self._push()
  183. while self._tokens:
  184. node = self._handle_token(self._tokens.pop())
  185. self._write(node)
  186. return self._pop()