A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

213 lignes
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. text = "".join([token.text for token in text])
  99. if text.strip() and "\n" in text.strip():
  100. raise BadRoute(self._pop())
  101. def _handle_template_param(self):
  102. if self._context & contexts.TEMPLATE_NAME:
  103. self._verify_template_name()
  104. self._context ^= contexts.TEMPLATE_NAME
  105. if self._context & contexts.TEMPLATE_PARAM_VALUE:
  106. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  107. self._context |= contexts.TEMPLATE_PARAM_KEY
  108. self._write(tokens.TemplateParamSeparator())
  109. def _handle_template_param_value(self):
  110. self._context ^= contexts.TEMPLATE_PARAM_KEY
  111. self._context |= contexts.TEMPLATE_PARAM_VALUE
  112. self._write(tokens.TemplateParamEquals())
  113. def _handle_template_end(self):
  114. if self._context & contexts.TEMPLATE_NAME:
  115. self._verify_template_name()
  116. self._head += 1
  117. return self._pop()
  118. def _parse_entity(self):
  119. reset = self._head
  120. self._head += 1
  121. try:
  122. self._push()
  123. self._write(tokens.HTMLEntityStart())
  124. numeric = hexadecimal = False
  125. if self._at_head("#"):
  126. numeric = True
  127. self._write(tokens.HTMLEntityNumeric())
  128. if self._read(1).lower() == "x":
  129. hexadecimal = True
  130. self._write(tokens.HTMLEntityHex(char=self._read(1)))
  131. self._head += 2
  132. else:
  133. self._head += 1
  134. text = []
  135. valid = string.hexdigits if hexadecimal else string.digits
  136. if not numeric and not hexadecimal:
  137. valid += string.ascii_letters
  138. while True:
  139. if self._at_head(";"):
  140. text = "".join(text)
  141. if numeric:
  142. test = int(text, 16) if hexadecimal else int(text)
  143. if test < 1 or test > 0x10FFFF:
  144. raise BadRoute(self._pop())
  145. else:
  146. if text not in htmlentitydefs.entitydefs:
  147. raise BadRoute(self._pop())
  148. self._write(tokens.Text(text=text))
  149. self._write(tokens.HTMLEntityEnd())
  150. break
  151. if self._read() is self.END or self._read() not in valid:
  152. raise BadRoute(self._pop())
  153. text.append(self._read())
  154. self._head += 1
  155. except BadRoute:
  156. self._head = reset
  157. self._write(self._read(), text=True)
  158. else:
  159. self._write_all(self._pop())
  160. def _parse(self, context=0):
  161. self._push(context)
  162. while True:
  163. if self._read() not in self.SENTINELS:
  164. self._write(self._read(), text=True)
  165. self._head += 1
  166. continue
  167. if self._read() is self.END:
  168. if self._context & contexts.TEMPLATE:
  169. raise BadRoute(self._pop())
  170. return self._pop()
  171. if self._at_head("{{"):
  172. self._parse_template()
  173. elif self._at_head("|") and self._context & contexts.TEMPLATE:
  174. self._handle_template_param()
  175. elif self._at_head("=") and self._context & contexts.TEMPLATE_PARAM_KEY:
  176. self._handle_template_param_value()
  177. elif self._at_head("}}") and self._context & contexts.TEMPLATE:
  178. return self._handle_template_end()
  179. elif self._at_head("&"):
  180. self._parse_entity()
  181. else:
  182. self._write(self._read(), text=True)
  183. self._head += 1
  184. def tokenize(self, text):
  185. self._text = list(text)
  186. return self._parse()