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