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