A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

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