A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

405 linhas
13 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2013 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. keystop = maxsize if key.stop is None else key.stop
  68. sliceinfo = [key.start or 0, keystop, key.step or 1]
  69. child = _ListProxy(self, sliceinfo)
  70. self._children[id(child)] = (child, sliceinfo)
  71. return child
  72. def __setitem__(self, key, item):
  73. if not isinstance(key, slice):
  74. return super(SmartList, self).__setitem__(key, item)
  75. item = list(item)
  76. super(SmartList, self).__setitem__(key, item)
  77. key = slice(key.start or 0, maxsize if key.stop is None else key.stop)
  78. diff = len(item) - key.stop + key.start
  79. values = self._children.values if py3k else self._children.itervalues
  80. if diff:
  81. for child, (start, stop, step) in values():
  82. if start > key.stop:
  83. self._children[id(child)][1][0] += diff
  84. if stop >= key.stop and stop != maxsize:
  85. self._children[id(child)][1][1] += diff
  86. def __delitem__(self, key):
  87. super(SmartList, self).__delitem__(key)
  88. if isinstance(key, slice):
  89. keystop = maxsize if key.stop is None else key.stop
  90. key = slice(key.start or 0, keystop)
  91. else:
  92. key = slice(key, key + 1)
  93. diff = key.stop - key.start
  94. values = self._children.values if py3k else self._children.itervalues
  95. for child, (start, stop, step) in values():
  96. if start > key.start:
  97. self._children[id(child)][1][0] -= diff
  98. if stop >= key.stop and stop != maxsize:
  99. self._children[id(child)][1][1] -= diff
  100. if not py3k:
  101. def __getslice__(self, start, stop):
  102. return self.__getitem__(slice(start, stop))
  103. def __setslice__(self, start, stop, iterable):
  104. self.__setitem__(slice(start, stop), iterable)
  105. def __delslice__(self, start, stop):
  106. self.__delitem__(slice(start, stop))
  107. def __add__(self, other):
  108. return SmartList(list(self) + other)
  109. def __radd__(self, other):
  110. return SmartList(other + list(self))
  111. def __iadd__(self, other):
  112. self.extend(other)
  113. return self
  114. @inheritdoc
  115. def append(self, item):
  116. head = len(self)
  117. self[head:head] = [item]
  118. @inheritdoc
  119. def extend(self, item):
  120. head = len(self)
  121. self[head:head] = item
  122. @inheritdoc
  123. def insert(self, index, item):
  124. self[index:index] = [item]
  125. @inheritdoc
  126. def pop(self, index=None):
  127. if index is None:
  128. index = len(self) - 1
  129. item = self[index]
  130. del self[index]
  131. return item
  132. @inheritdoc
  133. def remove(self, item):
  134. del self[self.index(item)]
  135. @inheritdoc
  136. def reverse(self):
  137. copy = list(self)
  138. for child in self._children:
  139. child._parent = copy
  140. super(SmartList, self).reverse()
  141. @inheritdoc
  142. def sort(self, cmp=None, key=None, reverse=None):
  143. copy = list(self)
  144. for child in self._children:
  145. child._parent = copy
  146. kwargs = {}
  147. if cmp is not None:
  148. kwargs["cmp"] = cmp
  149. if key is not None:
  150. kwargs["key"] = key
  151. if reverse is not None:
  152. kwargs["reverse"] = reverse
  153. super(SmartList, self).sort(**kwargs)
  154. class _ListProxy(list):
  155. """Implement the ``list`` interface by getting elements from a parent.
  156. This is created by a :py:class:`~.SmartList` object when slicing. It does
  157. not actually store the list at any time; instead, whenever the list is
  158. needed, it builds it dynamically using the :py:meth:`_render` method.
  159. """
  160. def __init__(self, parent, sliceinfo):
  161. super(_ListProxy, self).__init__()
  162. self._parent = parent
  163. self._sliceinfo = sliceinfo
  164. def __repr__(self):
  165. return repr(self._render())
  166. def __lt__(self, other):
  167. if isinstance(other, _ListProxy):
  168. return self._render() < list(other)
  169. return self._render() < other
  170. def __le__(self, other):
  171. if isinstance(other, _ListProxy):
  172. return self._render() <= list(other)
  173. return self._render() <= other
  174. def __eq__(self, other):
  175. if isinstance(other, _ListProxy):
  176. return self._render() == list(other)
  177. return self._render() == other
  178. def __ne__(self, other):
  179. if isinstance(other, _ListProxy):
  180. return self._render() != list(other)
  181. return self._render() != other
  182. def __gt__(self, other):
  183. if isinstance(other, _ListProxy):
  184. return self._render() > list(other)
  185. return self._render() > other
  186. def __ge__(self, other):
  187. if isinstance(other, _ListProxy):
  188. return self._render() >= list(other)
  189. return self._render() >= other
  190. if py3k:
  191. def __bool__(self):
  192. return bool(self._render())
  193. else:
  194. def __nonzero__(self):
  195. return bool(self._render())
  196. def __len__(self):
  197. return (self._stop - self._start) / self._step
  198. def __getitem__(self, key):
  199. return self._render()[key]
  200. def __setitem__(self, key, item):
  201. if isinstance(key, slice):
  202. keystart = (key.start or 0) + self._start
  203. if key.stop is None or key.stop == maxsize:
  204. keystop = self._stop
  205. else:
  206. keystop = key.stop + self._start
  207. adjusted = slice(keystart, keystop, key.step)
  208. self._parent[adjusted] = item
  209. else:
  210. length = len(self)
  211. if key < 0:
  212. key = length + key
  213. if key < 0 or key >= length:
  214. raise IndexError("list assignment index out of range")
  215. self._parent[self._start + key] = item
  216. def __delitem__(self, key):
  217. if isinstance(key, slice):
  218. keystart = (key.start or 0) + self._start
  219. if key.stop is None or key.stop == maxsize:
  220. keystop = self._stop
  221. else:
  222. keystop = key.stop + self._start
  223. adjusted = slice(keystart, keystop, key.step)
  224. del self._parent[adjusted]
  225. else:
  226. length = len(self)
  227. if key < 0:
  228. key = length + key
  229. if key < 0 or key >= length:
  230. raise IndexError("list assignment index out of range")
  231. del self._parent[self._start + key]
  232. def __iter__(self):
  233. i = self._start
  234. while i < self._stop:
  235. yield self._parent[i]
  236. i += self._step
  237. def __reversed__(self):
  238. i = self._stop - 1
  239. while i >= self._start:
  240. yield self._parent[i]
  241. i -= self._step
  242. def __contains__(self, item):
  243. return item in self._render()
  244. if not py3k:
  245. def __getslice__(self, start, stop):
  246. return self.__getitem__(slice(start, stop))
  247. def __setslice__(self, start, stop, iterable):
  248. self.__setitem__(slice(start, stop), iterable)
  249. def __delslice__(self, start, stop):
  250. self.__delitem__(slice(start, stop))
  251. def __add__(self, other):
  252. return SmartList(list(self) + other)
  253. def __radd__(self, other):
  254. return SmartList(other + list(self))
  255. def __iadd__(self, other):
  256. self.extend(other)
  257. return self
  258. def __mul__(self, other):
  259. return SmartList(list(self) * other)
  260. def __rmul__(self, other):
  261. return SmartList(other * list(self))
  262. def __imul__(self, other):
  263. self.extend(list(self) * (other - 1))
  264. return self
  265. @property
  266. def _start(self):
  267. """The starting index of this list, inclusive."""
  268. return self._sliceinfo[0]
  269. @property
  270. def _stop(self):
  271. """The ending index of this list, exclusive."""
  272. if self._sliceinfo[1] == maxsize:
  273. return len(self._parent)
  274. return self._sliceinfo[1]
  275. @property
  276. def _step(self):
  277. """The number to increase the index by between items."""
  278. return self._sliceinfo[2]
  279. def _render(self):
  280. """Return the actual list from the stored start/stop/step."""
  281. return list(self._parent)[self._start:self._stop:self._step]
  282. @inheritdoc
  283. def append(self, item):
  284. self._parent.insert(self._stop, item)
  285. @inheritdoc
  286. def count(self, item):
  287. return self._render().count(item)
  288. @inheritdoc
  289. def index(self, item, start=None, stop=None):
  290. if start is not None:
  291. if stop is not None:
  292. return self._render().index(item, start, stop)
  293. return self._render().index(item, start)
  294. return self._render().index(item)
  295. @inheritdoc
  296. def extend(self, item):
  297. self._parent[self._stop:self._stop] = item
  298. @inheritdoc
  299. def insert(self, index, item):
  300. if index < 0:
  301. index = len(self) + index
  302. self._parent.insert(self._start + index, item)
  303. @inheritdoc
  304. def pop(self, index=None):
  305. length = len(self)
  306. if index is None:
  307. index = length - 1
  308. elif index < 0:
  309. index = length + index
  310. if index < 0 or index >= length:
  311. raise IndexError("pop index out of range")
  312. return self._parent.pop(self._start + index)
  313. @inheritdoc
  314. def remove(self, item):
  315. index = self.index(item)
  316. del self._parent[self._start + index]
  317. @inheritdoc
  318. def reverse(self):
  319. item = self._render()
  320. item.reverse()
  321. self._parent[self._start:self._stop:self._step] = item
  322. @inheritdoc
  323. def sort(self, cmp=None, key=None, reverse=None):
  324. item = self._render()
  325. kwargs = {}
  326. if cmp is not None:
  327. kwargs["cmp"] = cmp
  328. if key is not None:
  329. kwargs["key"] = key
  330. if reverse is not None:
  331. kwargs["reverse"] = reverse
  332. item.sort(**kwargs)
  333. self._parent[self._start:self._stop:self._step] = item
  334. del inheritdoc