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.
 
 
 
 

286 lines
9.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. from math import log
  24. import re
  25. import string
  26. from . import contexts
  27. from . import tokens
  28. __all__ = ["Tokenizer"]
  29. class BadRoute(Exception):
  30. pass
  31. class Tokenizer(object):
  32. START = object()
  33. END = object()
  34. MARKERS = ["{", "}", "[", "]", "<", ">", "|", "=", "&", "#", "*", ";", ":",
  35. "/", "-", "\n", END]
  36. regex = re.compile(r"([{}\[\]<>|=&#*;:/\-\n])", flags=re.IGNORECASE)
  37. def __init__(self):
  38. self._text = None
  39. self._head = 0
  40. self._stacks = []
  41. self._global = 0
  42. @property
  43. def _stack(self):
  44. return self._stacks[-1][0]
  45. @property
  46. def _context(self):
  47. return self._stacks[-1][1]
  48. @_context.setter
  49. def _context(self, value):
  50. self._stacks[-1][1] = value
  51. @property
  52. def _textbuffer(self):
  53. return self._stacks[-1][2]
  54. @_textbuffer.setter
  55. def _textbuffer(self, value):
  56. self._stacks[-1][2] = value
  57. def _push(self, context=0):
  58. self._stacks.append([[], context, []])
  59. def _push_textbuffer(self):
  60. if self._textbuffer:
  61. self._stack.append(tokens.Text(text="".join(self._textbuffer)))
  62. self._textbuffer = []
  63. def _pop(self):
  64. self._push_textbuffer()
  65. return self._stacks.pop()[0]
  66. def _fail_route(self):
  67. self._pop()
  68. raise BadRoute()
  69. def _write(self, token):
  70. self._push_textbuffer()
  71. self._stack.append(token)
  72. def _write_text(self, text):
  73. self._textbuffer.append(text)
  74. def _write_all(self, tokenlist):
  75. if tokenlist and isinstance(tokenlist[0], tokens.Text):
  76. self._write_text(tokenlist.pop(0).text)
  77. self._push_textbuffer()
  78. self._stack.extend(tokenlist)
  79. def _read(self, delta=0, wrap=False, strict=False):
  80. index = self._head + delta
  81. if index < 0 and (not wrap or abs(index) > len(self._text)):
  82. return self.START
  83. try:
  84. return self._text[index]
  85. except IndexError:
  86. if strict:
  87. self._fail_route()
  88. return self.END
  89. def _parse_template(self):
  90. reset = self._head
  91. self._head += 2
  92. try:
  93. template = self._parse(contexts.TEMPLATE_NAME)
  94. except BadRoute:
  95. self._head = reset
  96. self._write_text(self._read())
  97. else:
  98. self._write(tokens.TemplateOpen())
  99. self._write_all(template)
  100. self._write(tokens.TemplateClose())
  101. def _verify_template_name(self):
  102. self._push_textbuffer()
  103. if self._stack:
  104. text = [tok for tok in self._stack if isinstance(tok, tokens.Text)]
  105. text = "".join([token.text for token in text])
  106. if text.strip() and "\n" in text.strip():
  107. self._fail_route()
  108. def _handle_template_param(self):
  109. if self._context & contexts.TEMPLATE_NAME:
  110. self._verify_template_name()
  111. self._context ^= contexts.TEMPLATE_NAME
  112. if self._context & contexts.TEMPLATE_PARAM_VALUE:
  113. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  114. self._context |= contexts.TEMPLATE_PARAM_KEY
  115. self._write(tokens.TemplateParamSeparator())
  116. def _handle_template_param_value(self):
  117. self._context ^= contexts.TEMPLATE_PARAM_KEY
  118. self._context |= contexts.TEMPLATE_PARAM_VALUE
  119. self._write(tokens.TemplateParamEquals())
  120. def _handle_template_end(self):
  121. if self._context & contexts.TEMPLATE_NAME:
  122. self._verify_template_name()
  123. self._head += 1
  124. return self._pop()
  125. def _parse_heading(self):
  126. self._global |= contexts.GL_HEADING
  127. reset = self._head
  128. self._head += 1
  129. best = 1
  130. while self._read() == "=":
  131. best += 1
  132. self._head += 1
  133. context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
  134. try:
  135. title, level = self._parse(context)
  136. except BadRoute:
  137. self._head = reset + best - 1
  138. self._write_text("=" * best)
  139. else:
  140. self._write(tokens.HeadingStart(level=level))
  141. if level < best:
  142. self._write_text("=" * (best - level))
  143. self._write_all(title)
  144. self._write(tokens.HeadingEnd())
  145. finally:
  146. self._global ^= contexts.GL_HEADING
  147. def _handle_heading_end(self):
  148. reset = self._head
  149. self._head += 1
  150. best = 1
  151. while self._read() == "=":
  152. best += 1
  153. self._head += 1
  154. current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
  155. level = min(current, min(best, 6))
  156. try:
  157. after, after_level = self._parse(self._context)
  158. except BadRoute:
  159. if level < best:
  160. self._write_text("=" * (best - level))
  161. self._head = reset + best - 1
  162. return self._pop(), level
  163. else:
  164. self._write_text("=" * best)
  165. self._write_all(after)
  166. return self._pop(), after_level
  167. def _really_parse_entity(self):
  168. self._write(tokens.HTMLEntityStart())
  169. self._head += 1
  170. this = self._read(strict=True)
  171. if this == "#":
  172. numeric = True
  173. self._write(tokens.HTMLEntityNumeric())
  174. self._head += 1
  175. this = self._read(strict=True)
  176. if this[0].lower() == "x":
  177. hexadecimal = True
  178. self._write(tokens.HTMLEntityHex(char=this[0]))
  179. this = this[1:]
  180. if not this:
  181. self._fail_route()
  182. else:
  183. hexadecimal = False
  184. else:
  185. numeric = hexadecimal = False
  186. valid = string.hexdigits if hexadecimal else string.digits
  187. if not numeric and not hexadecimal:
  188. valid += string.ascii_letters
  189. if not all([char in valid for char in this]):
  190. self._fail_route()
  191. self._head += 1
  192. if self._read() != ";":
  193. self._fail_route()
  194. if numeric:
  195. test = int(this, 16) if hexadecimal else int(this)
  196. if test < 1 or test > 0x10FFFF:
  197. self._fail_route()
  198. else:
  199. if this not in htmlentitydefs.entitydefs:
  200. self._fail_route()
  201. self._write(tokens.Text(text=this))
  202. self._write(tokens.HTMLEntityEnd())
  203. def _parse_entity(self):
  204. reset = self._head
  205. self._push()
  206. try:
  207. self._really_parse_entity()
  208. except BadRoute:
  209. self._head = reset
  210. self._write_text(self._read())
  211. else:
  212. self._write_all(self._pop())
  213. def _parse(self, context=0):
  214. self._push(context)
  215. while True:
  216. this = self._read()
  217. if this not in self.MARKERS:
  218. self._write_text(this)
  219. self._head += 1
  220. continue
  221. if this is self.END:
  222. if self._context & (contexts.TEMPLATE | contexts.HEADING):
  223. self._fail_route()
  224. return self._pop()
  225. prev, next = self._read(-1), self._read(1)
  226. if this == next == "{":
  227. self._parse_template()
  228. elif this == "|" and self._context & contexts.TEMPLATE:
  229. self._handle_template_param()
  230. elif this == "=" and self._context & contexts.TEMPLATE_PARAM_KEY:
  231. self._handle_template_param_value()
  232. elif this == next == "}" and self._context & contexts.TEMPLATE:
  233. return self._handle_template_end()
  234. elif (prev == "\n" or prev == self.START) and this == "=" and not self._global & contexts.GL_HEADING:
  235. self._parse_heading()
  236. elif this == "=" and self._context & contexts.HEADING:
  237. return self._handle_heading_end()
  238. elif this == "\n" and self._context & contexts.HEADING:
  239. self._fail_route()
  240. elif this == "&":
  241. self._parse_entity()
  242. else:
  243. self._write_text(this)
  244. self._head += 1
  245. def tokenize(self, text):
  246. split = self.regex.split(text)
  247. self._text = [segment for segment in split if segment]
  248. return self._parse()