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.
 
 
 
 

264 lines
8.7 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2016 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. # Copyright (C) 2019-2020 Yuri Astrakhan <YuriAstrakhan@gmail.com>
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a copy
  7. # of this software and associated documentation files (the "Software"), to deal
  8. # in the Software without restriction, including without limitation the rights
  9. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. # copies of the Software, and to permit persons to whom the Software is
  11. # furnished to do so, subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included in
  14. # all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. # SmartList has to be a full import in order to avoid cyclical import errors
  24. import mwparserfromhell.smart_list.SmartList
  25. from .utils import _SliceNormalizerMixIn, inheritdoc
  26. from ..compat import py3k
  27. class _ListProxy(_SliceNormalizerMixIn, list):
  28. """Implement the ``list`` interface by getting elements from a parent.
  29. This is created by a :class:`.SmartList` object when slicing. It does not
  30. actually store the list at any time; instead, whenever the list is needed,
  31. it builds it dynamically using the :meth:`_render` method.
  32. """
  33. def __init__(self, parent, sliceinfo):
  34. super(_ListProxy, self).__init__()
  35. self._parent = parent
  36. self._sliceinfo = sliceinfo
  37. def __repr__(self):
  38. return repr(self._render())
  39. def __lt__(self, other):
  40. if isinstance(other, _ListProxy):
  41. return self._render() < list(other)
  42. return self._render() < other
  43. def __le__(self, other):
  44. if isinstance(other, _ListProxy):
  45. return self._render() <= list(other)
  46. return self._render() <= other
  47. def __eq__(self, other):
  48. if isinstance(other, _ListProxy):
  49. return self._render() == list(other)
  50. return self._render() == other
  51. def __ne__(self, other):
  52. if isinstance(other, _ListProxy):
  53. return self._render() != list(other)
  54. return self._render() != other
  55. def __gt__(self, other):
  56. if isinstance(other, _ListProxy):
  57. return self._render() > list(other)
  58. return self._render() > other
  59. def __ge__(self, other):
  60. if isinstance(other, _ListProxy):
  61. return self._render() >= list(other)
  62. return self._render() >= other
  63. if py3k:
  64. def __bool__(self):
  65. return bool(self._render())
  66. else:
  67. def __nonzero__(self):
  68. return bool(self._render())
  69. def __len__(self):
  70. return max((self._stop - self._start) // self._step, 0)
  71. def __getitem__(self, key):
  72. if isinstance(key, slice):
  73. key = self._normalize_slice(key, clamp=True)
  74. keystart = min(self._start + key.start, self._stop)
  75. keystop = min(self._start + key.stop, self._stop)
  76. adjusted = slice(keystart, keystop, key.step)
  77. return self._parent[adjusted]
  78. else:
  79. return self._render()[key]
  80. def __setitem__(self, key, item):
  81. if isinstance(key, slice):
  82. key = self._normalize_slice(key, clamp=True)
  83. keystart = min(self._start + key.start, self._stop)
  84. keystop = min(self._start + key.stop, self._stop)
  85. adjusted = slice(keystart, keystop, key.step)
  86. self._parent[adjusted] = item
  87. else:
  88. length = len(self)
  89. if key < 0:
  90. key = length + key
  91. if key < 0 or key >= length:
  92. raise IndexError("list assignment index out of range")
  93. self._parent[self._start + key] = item
  94. def __delitem__(self, key):
  95. if isinstance(key, slice):
  96. key = self._normalize_slice(key, clamp=True)
  97. keystart = min(self._start + key.start, self._stop)
  98. keystop = min(self._start + key.stop, self._stop)
  99. adjusted = slice(keystart, keystop, key.step)
  100. del self._parent[adjusted]
  101. else:
  102. length = len(self)
  103. if key < 0:
  104. key = length + key
  105. if key < 0 or key >= length:
  106. raise IndexError("list assignment index out of range")
  107. del self._parent[self._start + key]
  108. def __iter__(self):
  109. i = self._start
  110. while i < self._stop:
  111. yield self._parent[i]
  112. i += self._step
  113. def __reversed__(self):
  114. i = self._stop - 1
  115. while i >= self._start:
  116. yield self._parent[i]
  117. i -= self._step
  118. def __contains__(self, item):
  119. return item in self._render()
  120. if not py3k:
  121. def __getslice__(self, start, stop):
  122. return self.__getitem__(slice(start, stop))
  123. def __setslice__(self, start, stop, iterable):
  124. self.__setitem__(slice(start, stop), iterable)
  125. def __delslice__(self, start, stop):
  126. self.__delitem__(slice(start, stop))
  127. def __add__(self, other):
  128. return mwparserfromhell.smart_list.SmartList(list(self) + other)
  129. def __radd__(self, other):
  130. return mwparserfromhell.smart_list.SmartList(other + list(self))
  131. def __iadd__(self, other):
  132. self.extend(other)
  133. return self
  134. def __mul__(self, other):
  135. return mwparserfromhell.smart_list.SmartList(list(self) * other)
  136. def __rmul__(self, other):
  137. return mwparserfromhell.smart_list.SmartList(other * list(self))
  138. def __imul__(self, other):
  139. self.extend(list(self) * (other - 1))
  140. return self
  141. @property
  142. def _start(self):
  143. """The starting index of this list, inclusive."""
  144. return self._sliceinfo[0]
  145. @property
  146. def _stop(self):
  147. """The ending index of this list, exclusive."""
  148. if self._sliceinfo[1] is None:
  149. return len(self._parent)
  150. return self._sliceinfo[1]
  151. @property
  152. def _step(self):
  153. """The number to increase the index by between items."""
  154. return self._sliceinfo[2]
  155. def _render(self):
  156. """Return the actual list from the stored start/stop/step."""
  157. return list(self._parent)[self._start:self._stop:self._step]
  158. @inheritdoc
  159. def append(self, item):
  160. self._parent.insert(self._stop, item)
  161. @inheritdoc
  162. def count(self, item):
  163. return self._render().count(item)
  164. @inheritdoc
  165. def index(self, item, start=None, stop=None):
  166. if start is not None:
  167. if stop is not None:
  168. return self._render().index(item, start, stop)
  169. return self._render().index(item, start)
  170. return self._render().index(item)
  171. @inheritdoc
  172. def extend(self, item):
  173. self._parent[self._stop:self._stop] = item
  174. @inheritdoc
  175. def insert(self, index, item):
  176. if index < 0:
  177. index = len(self) + index
  178. self._parent.insert(self._start + index, item)
  179. @inheritdoc
  180. def pop(self, index=None):
  181. length = len(self)
  182. if index is None:
  183. index = length - 1
  184. elif index < 0:
  185. index = length + index
  186. if index < 0 or index >= length:
  187. raise IndexError("pop index out of range")
  188. return self._parent.pop(self._start + index)
  189. @inheritdoc
  190. def remove(self, item):
  191. index = self.index(item)
  192. del self._parent[self._start + index]
  193. @inheritdoc
  194. def reverse(self):
  195. item = self._render()
  196. item.reverse()
  197. self._parent[self._start:self._stop:self._step] = item
  198. if py3k:
  199. @inheritdoc
  200. def sort(self, key=None, reverse=None):
  201. item = self._render()
  202. kwargs = {}
  203. if key is not None:
  204. kwargs["key"] = key
  205. if reverse is not None:
  206. kwargs["reverse"] = reverse
  207. item.sort(**kwargs)
  208. self._parent[self._start:self._stop:self._step] = item
  209. else:
  210. @inheritdoc
  211. def sort(self, cmp=None, key=None, reverse=None):
  212. item = self._render()
  213. kwargs = {}
  214. if cmp is not None:
  215. kwargs["cmp"] = cmp
  216. if key is not None:
  217. kwargs["key"] = key
  218. if reverse is not None:
  219. kwargs["reverse"] = reverse
  220. item.sort(**kwargs)
  221. self._parent[self._start:self._stop:self._step] = item