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.
 
 
 
 

186 lines
6.5 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. from _weakref import ref
  24. from .ListProxy import _ListProxy
  25. from .utils import _SliceNormalizerMixIn, inheritdoc
  26. from ..compat import py3k
  27. class SmartList(_SliceNormalizerMixIn, list):
  28. """Implements the ``list`` interface with special handling of sublists.
  29. When a sublist is created (by ``list[i:j]``), any changes made to this
  30. list (such as the addition, removal, or replacement of elements) will be
  31. reflected in the sublist, or vice-versa, to the greatest degree possible.
  32. This is implemented by having sublists - instances of the
  33. :class:`._ListProxy` type - dynamically determine their elements by storing
  34. their slice info and retrieving that slice from the parent. Methods that
  35. change the size of the list also change the slice info. For example::
  36. >>> parent = SmartList([0, 1, 2, 3])
  37. >>> parent
  38. [0, 1, 2, 3]
  39. >>> child = parent[2:]
  40. >>> child
  41. [2, 3]
  42. >>> child.append(4)
  43. >>> child
  44. [2, 3, 4]
  45. >>> parent
  46. [0, 1, 2, 3, 4]
  47. """
  48. def __init__(self, iterable=None):
  49. if iterable:
  50. super(SmartList, self).__init__(iterable)
  51. else:
  52. super(SmartList, self).__init__()
  53. self._children = {}
  54. def __getitem__(self, key):
  55. if not isinstance(key, slice):
  56. return super(SmartList, self).__getitem__(key)
  57. key = self._normalize_slice(key, clamp=False)
  58. sliceinfo = [key.start, key.stop, key.step]
  59. child = _ListProxy(self, sliceinfo)
  60. child_ref = ref(child, self._delete_child)
  61. self._children[id(child_ref)] = (child_ref, sliceinfo)
  62. return child
  63. def __setitem__(self, key, item):
  64. if not isinstance(key, slice):
  65. return super(SmartList, self).__setitem__(key, item)
  66. item = list(item)
  67. super(SmartList, self).__setitem__(key, item)
  68. key = self._normalize_slice(key, clamp=True)
  69. diff = len(item) + (key.start - key.stop) // key.step
  70. if not diff:
  71. return
  72. values = self._children.values if py3k else self._children.itervalues
  73. for child, (start, stop, step) in values():
  74. if start > key.stop:
  75. self._children[id(child)][1][0] += diff
  76. if stop is not None and stop >= key.stop:
  77. self._children[id(child)][1][1] += diff
  78. def __delitem__(self, key):
  79. super(SmartList, self).__delitem__(key)
  80. if isinstance(key, slice):
  81. key = self._normalize_slice(key, clamp=True)
  82. else:
  83. key = slice(key, key + 1, 1)
  84. diff = (key.stop - key.start) // key.step
  85. values = self._children.values if py3k else self._children.itervalues
  86. for child, (start, stop, step) in values():
  87. if start > key.start:
  88. self._children[id(child)][1][0] -= diff
  89. if stop is not None and stop >= key.stop:
  90. self._children[id(child)][1][1] -= diff
  91. if not py3k:
  92. def __getslice__(self, start, stop):
  93. return self.__getitem__(slice(start, stop))
  94. def __setslice__(self, start, stop, iterable):
  95. self.__setitem__(slice(start, stop), iterable)
  96. def __delslice__(self, start, stop):
  97. self.__delitem__(slice(start, stop))
  98. def __add__(self, other):
  99. return SmartList(list(self) + other)
  100. def __radd__(self, other):
  101. return SmartList(other + list(self))
  102. def __iadd__(self, other):
  103. self.extend(other)
  104. return self
  105. def _delete_child(self, child_ref):
  106. """Remove a child reference that is about to be garbage-collected."""
  107. del self._children[id(child_ref)]
  108. def _detach_children(self):
  109. """Remove all children and give them independent parent copies."""
  110. children = [val[0] for val in self._children.values()]
  111. for child in children:
  112. child()._parent = list(self)
  113. self._children.clear()
  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. self._detach_children()
  138. super(SmartList, self).reverse()
  139. if py3k:
  140. @inheritdoc
  141. def sort(self, key=None, reverse=None):
  142. self._detach_children()
  143. kwargs = {}
  144. if key is not None:
  145. kwargs["key"] = key
  146. if reverse is not None:
  147. kwargs["reverse"] = reverse
  148. super(SmartList, self).sort(**kwargs)
  149. else:
  150. @inheritdoc
  151. def sort(self, cmp=None, key=None, reverse=None):
  152. self._detach_children()
  153. kwargs = {}
  154. if cmp is not None:
  155. kwargs["cmp"] = cmp
  156. if key is not None:
  157. kwargs["key"] = key
  158. if reverse is not None:
  159. kwargs["reverse"] = reverse
  160. super(SmartList, self).sort(**kwargs)