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.
 
 
 
 

141 righe
4.7 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. from . import contexts
  23. from . import tokens
  24. __all__ = ["Tokenizer"]
  25. class BadRoute(Exception):
  26. pass
  27. class Tokenizer(object):
  28. START = object()
  29. END = object()
  30. def __init__(self):
  31. self._text = None
  32. self._head = 0
  33. self._stacks = []
  34. @property
  35. def _context(self):
  36. return self._stacks[-1][1]
  37. @_context.setter
  38. def _context(self, value):
  39. self._stacks[-1][1] = value
  40. def _push(self):
  41. self._stacks.append([[], 0])
  42. def _pop(self):
  43. return self._stacks.pop()[0]
  44. def _write(self, token, stack=None):
  45. if stack is None:
  46. stack = self._stacks[-1][0]
  47. if not stack:
  48. stack.append(token)
  49. return
  50. last = stack[-1]
  51. if isinstance(token, tokens.Text) and isinstance(last, tokens.Text):
  52. last.text += token.text
  53. else:
  54. stack.append(token)
  55. def _write_all(self, tokenlist, stack=None):
  56. if stack is None:
  57. stack = self._stacks[-1][0]
  58. stack.extend(tokenlist)
  59. def _read(self, delta=0, wrap=False):
  60. index = self._head + delta
  61. if index < 0 and (not wrap or abs(index) > len(self._text)):
  62. return self.START
  63. if index >= len(self._text):
  64. return self.END
  65. return self._text[index]
  66. def _at_head(self, chars):
  67. return all([self._read(i) == chars[i] for i in xrange(len(chars))])
  68. def _verify_context(self):
  69. if self._read() is self.END:
  70. if self._context & contexts.TEMPLATE:
  71. raise BadRoute(self._pop())
  72. def _catch_stop(self, stop):
  73. if self._read() is self.END:
  74. return True
  75. try:
  76. iter(stop)
  77. except TypeError:
  78. if self._read() is stop:
  79. return True
  80. else:
  81. if all([self._read(i) == stop[i] for i in xrange(len(stop))]):
  82. self._head += len(stop) - 1
  83. return True
  84. return False
  85. def _parse_template(self):
  86. reset = self._head
  87. self._head += 2
  88. try:
  89. template = self._parse_until("}}", contexts.TEMPLATE_NAME)
  90. except BadRoute:
  91. self._head = reset
  92. self._write(tokens.Text(text=self._read()))
  93. else:
  94. self._write(tokens.TemplateOpen())
  95. self._write_all(template)
  96. self._write(tokens.TemplateClose())
  97. def _parse_until(self, stop, context=0):
  98. self._push()
  99. self._context = context
  100. while True:
  101. self._verify_context()
  102. if self._catch_stop(stop):
  103. return self._pop()
  104. if self._at_head("{{"):
  105. self._parse_template()
  106. elif self._at_head("|") and self._context & contexts.TEMPLATE:
  107. if self._context & contexts.TEMPLATE_NAME:
  108. self._context ^= contexts.TEMPLATE_NAME
  109. if self._context & contexts.TEMPLATE_PARAM_VALUE:
  110. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  111. self._context |= contexts.TEMPLATE_PARAM_KEY
  112. self._write(tokens.TemplateParamSeparator())
  113. elif self._at_head("=") and self._context & contexts.TEMPLATE_PARAM_KEY:
  114. self._context ^= contexts.TEMPLATE_PARAM_KEY
  115. self._context |= contexts.TEMPLATE_PARAM_VALUE
  116. self._write(tokens.TemplateParamEquals())
  117. else:
  118. self._write(tokens.Text(text=self._read()))
  119. self._head += 1
  120. def tokenize(self, text):
  121. self._text = list(text)
  122. return self._parse_until(stop=self.END)