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.
 
 
 
 

364 lines
11 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. """
  23. This module contains the :py:class:`~.SmartList` type, as well as its
  24. :py:class:`~._ListProxy` child, which together implement a list whose sublists
  25. reflect changes made to the main list, and vice-versa.
  26. """
  27. from __future__ import unicode_literals
  28. from .compat import maxsize, py3k
  29. __all__ = ["SmartList"]
  30. def inheritdoc(method):
  31. """Set __doc__ of *method* to __doc__ of *method* in its parent class.
  32. Since this is used on :py:class:`~.SmartList`, the "parent class" used is
  33. ``list``. This function can be used as a decorator.
  34. """
  35. method.__doc__ = getattr(list, method.__name__).__doc__
  36. return method
  37. class SmartList(list):
  38. """Implements the ``list`` interface with special handling of sublists.
  39. When a sublist is created (by ``list[i:j]``), any changes made to this
  40. list (such as the addition, removal, or replacement of elements) will be
  41. reflected in the sublist, or vice-versa, to the greatest degree possible.
  42. This is implemented by having sublists - instances of the
  43. :py:class:`~._ListProxy` type - dynamically determine their elements by
  44. storing their slice info and retrieving that slice from the parent. Methods
  45. that change the size of the list also change the slice info. For example::
  46. >>> parent = SmartList([0, 1, 2, 3])
  47. >>> parent
  48. [0, 1, 2, 3]
  49. >>> child = parent[2:]
  50. >>> child
  51. [2, 3]
  52. >>> child.append(4)
  53. >>> child
  54. [2, 3, 4]
  55. >>> parent
  56. [0, 1, 2, 3, 4]
  57. """
  58. def __init__(self, iterable=None):
  59. if iterable:
  60. super(SmartList, self).__init__(iterable)
  61. else:
  62. super(SmartList, self).__init__()
  63. self._children = {}
  64. def __getitem__(self, key):
  65. if not isinstance(key, slice):
  66. return super(SmartList, self).__getitem__(key)
  67. sliceinfo = [key.start, key.stop, 1 if not key.step else key.step]
  68. child = _ListProxy(self, sliceinfo)
  69. self._children[id(child)] = (child, sliceinfo)
  70. return child
  71. def __setitem__(self, key, item):
  72. if not isinstance(key, slice):
  73. return super(SmartList, self).__setitem__(key, item)
  74. item = list(item)
  75. super(SmartList, self).__setitem__(key, item)
  76. diff = len(item) - key.stop + key.start
  77. values = self._children.values if py3k else self._children.itervalues
  78. if diff:
  79. for child, (start, stop, step) in values():
  80. if start >= key.stop:
  81. self._children[id(child)][1][0] += diff
  82. if stop >= key.stop and stop != maxsize:
  83. self._children[id(child)][1][1] += diff
  84. def __delitem__(self, key):
  85. super(SmartList, self).__delitem__(key)
  86. if not isinstance(key, slice):
  87. key = slice(key, key + 1)
  88. diff = key.stop - key.start
  89. values = self._children.values if py3k else self._children.itervalues
  90. for child, (start, stop, step) in values():
  91. if start > key.start:
  92. self._children[id(child)][1][0] -= diff
  93. if stop >= key.stop:
  94. self._children[id(child)][1][1] -= diff
  95. if not py3k:
  96. def __getslice__(self, start, stop):
  97. return self.__getitem__(slice(start, stop))
  98. def __setslice__(self, start, stop, iterable):
  99. self.__setitem__(slice(start, stop), iterable)
  100. def __delslice__(self, start, stop):
  101. self.__delitem__(slice(start, stop))
  102. def __add__(self, other):
  103. return SmartList(list(self) + other)
  104. def __radd__(self, other):
  105. return SmartList(other + list(self))
  106. def __iadd__(self, other):
  107. self.extend(other)
  108. return self
  109. @inheritdoc
  110. def append(self, item):
  111. head = len(self)
  112. self[head:head] = [item]
  113. @inheritdoc
  114. def extend(self, item):
  115. head = len(self)
  116. self[head:head] = item
  117. @inheritdoc
  118. def insert(self, index, item):
  119. self[index:index] = [item]
  120. @inheritdoc
  121. def pop(self, index=None):
  122. if index is None:
  123. index = len(self) - 1
  124. item = self[index]
  125. del self[index]
  126. return item
  127. @inheritdoc
  128. def remove(self, item):
  129. del self[self.index(item)]
  130. @inheritdoc
  131. def reverse(self):
  132. copy = list(self)
  133. for child in self._children:
  134. child._parent = copy
  135. super(SmartList, self).reverse()
  136. @inheritdoc
  137. def sort(self, cmp=None, key=None, reverse=None):
  138. copy = list(self)
  139. for child in self._children:
  140. child._parent = copy
  141. if cmp is not None:
  142. if key is not None:
  143. if reverse is not None:
  144. super(SmartList, self).sort(cmp, key, reverse)
  145. else:
  146. super(SmartList, self).sort(cmp, key)
  147. else:
  148. super(SmartList, self).sort(cmp)
  149. else:
  150. super(SmartList, self).sort()
  151. class _ListProxy(list):
  152. """Implement the ``list`` interface by getting elements from a parent.
  153. This is created by a :py:class:`~.SmartList` object when slicing. It does
  154. not actually store the list at any time; instead, whenever the list is
  155. needed, it builds it dynamically using the :py:meth:`_render` method.
  156. """
  157. def __init__(self, parent, sliceinfo):
  158. super(_ListProxy, self).__init__()
  159. self._parent = parent
  160. self._sliceinfo = sliceinfo
  161. def __repr__(self):
  162. return repr(self._render())
  163. def __lt__(self, other):
  164. if isinstance(other, _ListProxy):
  165. return self._render() < list(other)
  166. return self._render() < other
  167. def __le__(self, other):
  168. if isinstance(other, _ListProxy):
  169. return self._render() <= list(other)
  170. return self._render() <= other
  171. def __eq__(self, other):
  172. if isinstance(other, _ListProxy):
  173. return self._render() == list(other)
  174. return self._render() == other
  175. def __ne__(self, other):
  176. if isinstance(other, _ListProxy):
  177. return self._render() != list(other)
  178. return self._render() != other
  179. def __gt__(self, other):
  180. if isinstance(other, _ListProxy):
  181. return self._render() > list(other)
  182. return self._render() > other
  183. def __ge__(self, other):
  184. if isinstance(other, _ListProxy):
  185. return self._render() >= list(other)
  186. return self._render() >= other
  187. if py3k:
  188. def __bool__(self):
  189. return bool(self._render())
  190. else:
  191. def __nonzero__(self):
  192. return bool(self._render())
  193. def __len__(self):
  194. return (self._stop - self._start) / self._step
  195. def __getitem__(self, key):
  196. return self._render()[key]
  197. def __setitem__(self, key, item):
  198. if isinstance(key, slice):
  199. adjusted = slice(key.start + self._start, key.stop + self._stop,
  200. key.step)
  201. self._parent[adjusted] = item
  202. else:
  203. self._parent[self._start + key] = item
  204. def __delitem__(self, key):
  205. if isinstance(key, slice):
  206. adjusted = slice(key.start + self._start, key.stop + self._stop,
  207. key.step)
  208. del self._parent[adjusted]
  209. else:
  210. del self._parent[self._start + key]
  211. def __iter__(self):
  212. i = self._start
  213. while i < self._stop:
  214. yield self._parent[i]
  215. i += self._step
  216. def __reversed__(self):
  217. i = self._stop - 1
  218. while i >= self._start:
  219. yield self._parent[i]
  220. i -= self._step
  221. def __contains__(self, item):
  222. return item in self._render()
  223. if not py3k:
  224. def __getslice__(self, start, stop):
  225. return self.__getitem__(slice(start, stop))
  226. def __setslice__(self, start, stop, iterable):
  227. self.__setitem__(slice(start, stop), iterable)
  228. def __delslice__(self, start, stop):
  229. self.__delitem__(slice(start, stop))
  230. def __add__(self, other):
  231. return SmartList(list(self) + other)
  232. def __radd__(self, other):
  233. return SmartList(other + list(self))
  234. def __iadd__(self, other):
  235. self.extend(other)
  236. return self
  237. @property
  238. def _start(self):
  239. """The starting index of this list, inclusive."""
  240. return self._sliceinfo[0]
  241. @property
  242. def _stop(self):
  243. """The ending index of this list, exclusive."""
  244. return self._sliceinfo[1]
  245. @property
  246. def _step(self):
  247. """The number to increase the index by between items."""
  248. return self._sliceinfo[2]
  249. def _render(self):
  250. """Return the actual list from the stored start/stop/step."""
  251. return list(self._parent)[self._start:self._stop:self._step]
  252. @inheritdoc
  253. def append(self, item):
  254. self._parent.insert(self._stop, item)
  255. @inheritdoc
  256. def count(self, item):
  257. return self._render().count(item)
  258. @inheritdoc
  259. def index(self, item, start=None, stop=None):
  260. if start is not None:
  261. if stop is not None:
  262. return self._render().index(item, start, stop)
  263. return self._render().index(item, start)
  264. return self._render().index(item)
  265. @inheritdoc
  266. def extend(self, item):
  267. self._parent[self._stop:self._stop] = item
  268. @inheritdoc
  269. def insert(self, index, item):
  270. self._parent.insert(self._start + index, item)
  271. @inheritdoc
  272. def pop(self, index=None):
  273. if index is None:
  274. index = len(self) - 1
  275. return self._parent.pop(self._start + index)
  276. @inheritdoc
  277. def remove(self, item):
  278. index = self.index(item)
  279. del self._parent[index]
  280. @inheritdoc
  281. def reverse(self):
  282. item = self._render()
  283. item.reverse()
  284. self._parent[self._start:self._stop:self._step] = item
  285. @inheritdoc
  286. def sort(self, cmp=None, key=None, reverse=None):
  287. item = self._render()
  288. if cmp is not None:
  289. if key is not None:
  290. if reverse is not None:
  291. item.sort(cmp, key, reverse)
  292. else:
  293. item.sort(cmp, key)
  294. else:
  295. item.sort(cmp)
  296. else:
  297. item.sort()
  298. self._parent[self._start:self._stop:self._step] = item