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.
 
 
 
 

234 lines
7.7 KiB

  1. #
  2. # Copyright (C) 2012-2016 Ben Kurtovic <ben.kurtovic@gmail.com>
  3. # Copyright (C) 2019-2020 Yuri Astrakhan <YuriAstrakhan@gmail.com>
  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. # SmartList has to be a full import in order to avoid cyclical import errors
  23. import mwparserfromhell.smart_list.SmartList
  24. from .utils import _SliceNormalizerMixIn, inheritdoc
  25. class _ListProxy(_SliceNormalizerMixIn, list):
  26. """Implement the ``list`` interface by getting elements from a parent.
  27. This is created by a :class:`.SmartList` object when slicing. It does not
  28. actually store the list at any time; instead, whenever the list is needed,
  29. it builds it dynamically using the :meth:`_render` method.
  30. """
  31. def __init__(self, parent, sliceinfo):
  32. super().__init__()
  33. self._parent = parent
  34. self._sliceinfo = sliceinfo
  35. def __repr__(self):
  36. return repr(self._render())
  37. def __lt__(self, other):
  38. if isinstance(other, _ListProxy):
  39. return self._render() < list(other)
  40. return self._render() < other
  41. def __le__(self, other):
  42. if isinstance(other, _ListProxy):
  43. return self._render() <= list(other)
  44. return self._render() <= other
  45. def __eq__(self, other):
  46. if isinstance(other, _ListProxy):
  47. return self._render() == list(other)
  48. return self._render() == other
  49. def __ne__(self, other):
  50. if isinstance(other, _ListProxy):
  51. return self._render() != list(other)
  52. return self._render() != other
  53. def __gt__(self, other):
  54. if isinstance(other, _ListProxy):
  55. return self._render() > list(other)
  56. return self._render() > other
  57. def __ge__(self, other):
  58. if isinstance(other, _ListProxy):
  59. return self._render() >= list(other)
  60. return self._render() >= other
  61. def __bool__(self):
  62. return bool(self._render())
  63. def __len__(self):
  64. return max((self._stop - self._start) // self._step, 0)
  65. def __getitem__(self, key):
  66. if isinstance(key, slice):
  67. key = self._normalize_slice(key, clamp=True)
  68. keystart = min(self._start + key.start, self._stop)
  69. keystop = min(self._start + key.stop, self._stop)
  70. adjusted = slice(keystart, keystop, key.step)
  71. return self._parent[adjusted]
  72. else:
  73. return self._render()[key]
  74. def __setitem__(self, key, item):
  75. if isinstance(key, slice):
  76. key = self._normalize_slice(key, clamp=True)
  77. keystart = min(self._start + key.start, self._stop)
  78. keystop = min(self._start + key.stop, self._stop)
  79. adjusted = slice(keystart, keystop, key.step)
  80. self._parent[adjusted] = item
  81. else:
  82. length = len(self)
  83. if key < 0:
  84. key = length + key
  85. if key < 0 or key >= length:
  86. raise IndexError("list assignment index out of range")
  87. self._parent[self._start + key] = item
  88. def __delitem__(self, key):
  89. if isinstance(key, slice):
  90. key = self._normalize_slice(key, clamp=True)
  91. keystart = min(self._start + key.start, self._stop)
  92. keystop = min(self._start + key.stop, self._stop)
  93. adjusted = slice(keystart, keystop, key.step)
  94. del self._parent[adjusted]
  95. else:
  96. length = len(self)
  97. if key < 0:
  98. key = length + key
  99. if key < 0 or key >= length:
  100. raise IndexError("list assignment index out of range")
  101. del self._parent[self._start + key]
  102. def __iter__(self):
  103. i = self._start
  104. while i < self._stop:
  105. yield self._parent[i]
  106. i += self._step
  107. def __reversed__(self):
  108. i = self._stop - 1
  109. while i >= self._start:
  110. yield self._parent[i]
  111. i -= self._step
  112. def __contains__(self, item):
  113. return item in self._render()
  114. def __add__(self, other):
  115. return mwparserfromhell.smart_list.SmartList(list(self) + other)
  116. def __radd__(self, other):
  117. return mwparserfromhell.smart_list.SmartList(other + list(self))
  118. def __iadd__(self, other):
  119. self.extend(other)
  120. return self
  121. def __mul__(self, other):
  122. return mwparserfromhell.smart_list.SmartList(list(self) * other)
  123. def __rmul__(self, other):
  124. return mwparserfromhell.smart_list.SmartList(other * list(self))
  125. def __imul__(self, other):
  126. self.extend(list(self) * (other - 1))
  127. return self
  128. @property
  129. def _start(self):
  130. """The starting index of this list, inclusive."""
  131. return self._sliceinfo[0]
  132. @property
  133. def _stop(self):
  134. """The ending index of this list, exclusive."""
  135. if self._sliceinfo[1] is None:
  136. return len(self._parent)
  137. return self._sliceinfo[1]
  138. @property
  139. def _step(self):
  140. """The number to increase the index by between items."""
  141. return self._sliceinfo[2]
  142. def _render(self):
  143. """Return the actual list from the stored start/stop/step."""
  144. return list(self._parent)[self._start:self._stop:self._step]
  145. @inheritdoc
  146. def append(self, item):
  147. self._parent.insert(self._stop, item)
  148. @inheritdoc
  149. def count(self, item):
  150. return self._render().count(item)
  151. @inheritdoc
  152. def index(self, item, start=None, stop=None):
  153. if start is not None:
  154. if stop is not None:
  155. return self._render().index(item, start, stop)
  156. return self._render().index(item, start)
  157. return self._render().index(item)
  158. @inheritdoc
  159. def extend(self, item):
  160. self._parent[self._stop:self._stop] = item
  161. @inheritdoc
  162. def insert(self, index, item):
  163. if index < 0:
  164. index = len(self) + index
  165. self._parent.insert(self._start + index, item)
  166. @inheritdoc
  167. def pop(self, index=None):
  168. length = len(self)
  169. if index is None:
  170. index = length - 1
  171. elif index < 0:
  172. index = length + index
  173. if index < 0 or index >= length:
  174. raise IndexError("pop index out of range")
  175. return self._parent.pop(self._start + index)
  176. @inheritdoc
  177. def remove(self, item):
  178. index = self.index(item)
  179. del self._parent[self._start + index]
  180. @inheritdoc
  181. def reverse(self):
  182. item = self._render()
  183. item.reverse()
  184. self._parent[self._start:self._stop:self._step] = item
  185. @inheritdoc
  186. def sort(self, key=None, reverse=None):
  187. item = self._render()
  188. kwargs = {}
  189. if key is not None:
  190. kwargs["key"] = key
  191. if reverse is not None:
  192. kwargs["reverse"] = reverse
  193. item.sort(**kwargs)
  194. self._parent[self._start:self._stop:self._step] = item