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.
 
 
 
 

211 lines
7.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. import htmlentitydefs
  23. import re
  24. import string
  25. from . import contexts
  26. from . import tokens
  27. __all__ = ["Tokenizer"]
  28. class BadRoute(Exception):
  29. pass
  30. class Tokenizer(object):
  31. START = object()
  32. END = object()
  33. SENTINELS = ["{", "}", "[", "]", "|", "=", "&", END]
  34. REGEX = r"([{}\[\]|=&;])"
  35. def __init__(self):
  36. self._text = None
  37. self._head = 0
  38. self._stacks = []
  39. @property
  40. def _stack(self):
  41. return self._stacks[-1][0]
  42. @property
  43. def _context(self):
  44. return self._stacks[-1][1]
  45. @_context.setter
  46. def _context(self, value):
  47. self._stacks[-1][1] = value
  48. @property
  49. def _textbuffer(self):
  50. return self._stacks[-1][2]
  51. @_textbuffer.setter
  52. def _textbuffer(self, value):
  53. self._stacks[-1][2] = value
  54. def _push(self, context=0):
  55. self._stacks.append([[], context, []])
  56. def _push_textbuffer(self):
  57. if self._textbuffer:
  58. self._stack.append(tokens.Text(text="".join(self._textbuffer)))
  59. self._textbuffer = []
  60. def _pop(self):
  61. self._push_textbuffer()
  62. return self._stacks.pop()[0]
  63. def _write(self, token):
  64. self._push_textbuffer()
  65. self._stack.append(token)
  66. def _write_text(self, text):
  67. self._textbuffer.append(text)
  68. def _write_all(self, tokenlist):
  69. self._push_textbuffer()
  70. self._stack.extend(tokenlist)
  71. def _read(self, delta=0, wrap=False):
  72. index = self._head + delta
  73. if index < 0 and (not wrap or abs(index) > len(self._text)):
  74. return self.START
  75. try:
  76. return self._text[index]
  77. except IndexError:
  78. return self.END
  79. def _parse_template(self):
  80. reset = self._head
  81. self._head += 2
  82. try:
  83. template = self._parse(contexts.TEMPLATE_NAME)
  84. except BadRoute:
  85. self._head = reset
  86. self._write_text(self._read())
  87. else:
  88. self._write(tokens.TemplateOpen())
  89. self._write_all(template)
  90. self._write(tokens.TemplateClose())
  91. def _verify_template_name(self):
  92. self._push_textbuffer()
  93. if self._stack:
  94. text = [tok for tok in self._stack if isinstance(tok, tokens.Text)]
  95. text = "".join([token.text for token in text])
  96. if text.strip() and "\n" in text.strip():
  97. raise BadRoute(self._pop())
  98. def _handle_template_param(self):
  99. if self._context & contexts.TEMPLATE_NAME:
  100. self._verify_template_name()
  101. self._context ^= contexts.TEMPLATE_NAME
  102. if self._context & contexts.TEMPLATE_PARAM_VALUE:
  103. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  104. self._context |= contexts.TEMPLATE_PARAM_KEY
  105. self._write(tokens.TemplateParamSeparator())
  106. def _handle_template_param_value(self):
  107. self._context ^= contexts.TEMPLATE_PARAM_KEY
  108. self._context |= contexts.TEMPLATE_PARAM_VALUE
  109. self._write(tokens.TemplateParamEquals())
  110. def _handle_template_end(self):
  111. if self._context & contexts.TEMPLATE_NAME:
  112. self._verify_template_name()
  113. self._head += 1
  114. return self._pop()
  115. def _parse_entity(self):
  116. self._push()
  117. try:
  118. self._write(tokens.HTMLEntityStart())
  119. this = self._read(1)
  120. if this is self.END:
  121. raise BadRoute(self._pop())
  122. numeric = hexadecimal = False
  123. skip = 0
  124. if this.startswith("#"):
  125. numeric = True
  126. self._write(tokens.HTMLEntityNumeric())
  127. if this[1:].lower().startswith("x"):
  128. hexadecimal = True
  129. self._write(tokens.HTMLEntityHex(char=this[1]))
  130. skip = 2
  131. else:
  132. skip = 1
  133. text = this[skip:]
  134. valid = string.hexdigits if hexadecimal else string.digits
  135. if not numeric and not hexadecimal:
  136. valid += string.ascii_letters
  137. if not text or not all([char in valid for char in text]):
  138. raise BadRoute(self._pop())
  139. if self._read(2) != ";":
  140. raise BadRoute(self._pop())
  141. if numeric:
  142. test = int(text, 16) if hexadecimal else int(text)
  143. if test < 1 or test > 0x10FFFF:
  144. raise BadRoute(self._pop())
  145. else:
  146. if text not in htmlentitydefs.entitydefs:
  147. raise BadRoute(self._pop())
  148. self._write(tokens.Text(text=text))
  149. self._write(tokens.HTMLEntityEnd())
  150. except BadRoute:
  151. self._write_text(self._read())
  152. else:
  153. self._write_all(self._pop())
  154. self._head += 2
  155. def _parse(self, context=0):
  156. self._push(context)
  157. while True:
  158. this = self._read()
  159. if this not in self.SENTINELS:
  160. self._write_text(this)
  161. self._head += 1
  162. continue
  163. if this is self.END:
  164. if self._context & contexts.TEMPLATE:
  165. raise BadRoute(self._pop())
  166. return self._pop()
  167. next = self._read(1)
  168. if this == next == "{":
  169. self._parse_template()
  170. elif this == "|" and self._context & contexts.TEMPLATE:
  171. self._handle_template_param()
  172. elif this == "=" and self._context & contexts.TEMPLATE_PARAM_KEY:
  173. self._handle_template_param_value()
  174. elif this == next == "}" and self._context & contexts.TEMPLATE:
  175. return self._handle_template_end()
  176. elif this == "&":
  177. self._parse_entity()
  178. else:
  179. self._write_text(this)
  180. self._head += 1
  181. def tokenize(self, text):
  182. split = re.split(self.REGEX, text, flags=re.I)
  183. self._text = [segment for segment in split if segment]
  184. return self._parse()