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.
 
 
 
 

214 lines
7.3 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. if index >= len(self._text):
  75. return self.END
  76. return self._text[index]
  77. def _at_head(self, chars):
  78. length = len(chars)
  79. if length == 1:
  80. return self._read() == chars
  81. return all([self._read(i) == chars[i] for i in xrange(len(chars))])
  82. def _parse_template(self):
  83. reset = self._head
  84. self._head += 2
  85. try:
  86. template = self._parse(contexts.TEMPLATE_NAME)
  87. except BadRoute:
  88. self._head = reset
  89. self._write(self._read(), text=True)
  90. else:
  91. self._write(tokens.TemplateOpen())
  92. self._write_all(template)
  93. self._write(tokens.TemplateClose())
  94. def _verify_template_name(self):
  95. self._push_textbuffer()
  96. if self._stack:
  97. text = [tok for tok in self._stack if isinstance(tok, tokens.Text)]
  98. print text
  99. text = "".join([token.text for token in text])
  100. if text.strip() and "\n" in text.strip():
  101. raise BadRoute(self._pop())
  102. def _handle_template_param(self):
  103. if self._context & contexts.TEMPLATE_NAME:
  104. self._verify_template_name()
  105. self._context ^= contexts.TEMPLATE_NAME
  106. if self._context & contexts.TEMPLATE_PARAM_VALUE:
  107. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  108. self._context |= contexts.TEMPLATE_PARAM_KEY
  109. self._write(tokens.TemplateParamSeparator())
  110. def _handle_template_param_value(self):
  111. self._context ^= contexts.TEMPLATE_PARAM_KEY
  112. self._context |= contexts.TEMPLATE_PARAM_VALUE
  113. self._write(tokens.TemplateParamEquals())
  114. def _handle_template_end(self):
  115. if self._context & contexts.TEMPLATE_NAME:
  116. self._verify_template_name()
  117. self._head += 1
  118. return self._pop()
  119. def _parse_entity(self):
  120. reset = self._head
  121. self._head += 1
  122. try:
  123. self._push()
  124. self._write(tokens.HTMLEntityStart())
  125. numeric = hexadecimal = False
  126. if self._at_head("#"):
  127. numeric = True
  128. self._write(tokens.HTMLEntityNumeric())
  129. if self._read(1).lower() == "x":
  130. hexadecimal = True
  131. self._write(tokens.HTMLEntityHex(char=self._read(1)))
  132. self._head += 2
  133. else:
  134. self._head += 1
  135. text = []
  136. valid = string.hexdigits if hexadecimal else string.digits
  137. if not numeric and not hexadecimal:
  138. valid += string.ascii_letters
  139. while True:
  140. if self._at_head(";"):
  141. text = "".join(text)
  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. break
  152. if self._read() is self.END or self._read() not in valid:
  153. raise BadRoute(self._pop())
  154. text.append(self._read())
  155. self._head += 1
  156. except BadRoute:
  157. self._head = reset
  158. self._write(self._read(), text=True)
  159. else:
  160. self._write_all(self._pop())
  161. def _parse(self, context=0):
  162. self._push(context)
  163. while True:
  164. if self._read() not in self.SENTINELS:
  165. self._write(self._read(), text=True)
  166. self._head += 1
  167. continue
  168. if self._read() is self.END:
  169. if self._context & contexts.TEMPLATE:
  170. raise BadRoute(self._pop())
  171. return self._pop()
  172. if self._at_head("{{"):
  173. self._parse_template()
  174. elif self._at_head("|") and self._context & contexts.TEMPLATE:
  175. self._handle_template_param()
  176. elif self._at_head("=") and self._context & contexts.TEMPLATE_PARAM_KEY:
  177. self._handle_template_param_value()
  178. elif self._at_head("}}") and self._context & contexts.TEMPLATE:
  179. return self._handle_template_end()
  180. elif self._at_head("&"):
  181. self._parse_entity()
  182. else:
  183. self._write(self._read(), text=True)
  184. self._head += 1
  185. def tokenize(self, text):
  186. self._text = list(text)
  187. return self._parse()