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.
 
 
 
 

160 lines
5.4 KiB

  1. #
  2. # Copyright (C) 2012-2020 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. from weakref import ref
  23. from .list_proxy import ListProxy
  24. from .utils import _SliceNormalizerMixIn, inheritdoc
  25. class SmartList(_SliceNormalizerMixIn, list):
  26. """Implements the ``list`` interface with special handling of sublists.
  27. When a sublist is created (by ``list[i:j]``), any changes made to this
  28. list (such as the addition, removal, or replacement of elements) will be
  29. reflected in the sublist, or vice-versa, to the greatest degree possible.
  30. This is implemented by having sublists - instances of the
  31. :class:`.ListProxy` type - dynamically determine their elements by storing
  32. their slice info and retrieving that slice from the parent. Methods that
  33. change the size of the list also change the slice info. For example::
  34. >>> parent = SmartList([0, 1, 2, 3])
  35. >>> parent
  36. [0, 1, 2, 3]
  37. >>> child = parent[2:]
  38. >>> child
  39. [2, 3]
  40. >>> child.append(4)
  41. >>> child
  42. [2, 3, 4]
  43. >>> parent
  44. [0, 1, 2, 3, 4]
  45. """
  46. def __init__(self, iterable=None):
  47. if iterable:
  48. super().__init__(iterable)
  49. else:
  50. super().__init__()
  51. self._children = {}
  52. def __getitem__(self, key):
  53. if not isinstance(key, slice):
  54. return super().__getitem__(key)
  55. key = self._normalize_slice(key, clamp=False)
  56. sliceinfo = [key.start, key.stop, key.step]
  57. child = ListProxy(self, sliceinfo)
  58. child_ref = ref(child, self._delete_child)
  59. self._children[id(child_ref)] = (child_ref, sliceinfo)
  60. return child
  61. def __setitem__(self, key, item):
  62. if not isinstance(key, slice):
  63. super().__setitem__(key, item)
  64. return
  65. item = list(item)
  66. super().__setitem__(key, item)
  67. key = self._normalize_slice(key, clamp=True)
  68. diff = len(item) + (key.start - key.stop) // key.step
  69. if not diff:
  70. return
  71. for child, (start, stop, _step) in self._children.values():
  72. if start > key.stop:
  73. self._children[id(child)][1][0] += diff
  74. if stop is not None and stop >= key.stop:
  75. self._children[id(child)][1][1] += diff
  76. def __delitem__(self, key):
  77. super().__delitem__(key)
  78. if isinstance(key, slice):
  79. key = self._normalize_slice(key, clamp=True)
  80. else:
  81. key = slice(key, key + 1, 1)
  82. diff = (key.stop - key.start) // key.step
  83. for child, (start, stop, _step) in self._children.values():
  84. if start > key.start:
  85. self._children[id(child)][1][0] -= diff
  86. if stop is not None and stop >= key.stop:
  87. self._children[id(child)][1][1] -= diff
  88. def __add__(self, other):
  89. return SmartList(list(self) + other)
  90. def __radd__(self, other):
  91. return SmartList(other + list(self))
  92. def __iadd__(self, other):
  93. self.extend(other)
  94. return self
  95. def _delete_child(self, child_ref):
  96. """Remove a child reference that is about to be garbage-collected."""
  97. del self._children[id(child_ref)]
  98. def _detach_children(self):
  99. """Remove all children and give them independent parent copies."""
  100. children = [val[0] for val in self._children.values()]
  101. for child in children:
  102. child()._parent = list(self)
  103. self._children.clear()
  104. @inheritdoc
  105. def append(self, item):
  106. head = len(self)
  107. self[head:head] = [item]
  108. @inheritdoc
  109. def extend(self, item):
  110. head = len(self)
  111. self[head:head] = item
  112. @inheritdoc
  113. def insert(self, index, item):
  114. self[index:index] = [item]
  115. @inheritdoc
  116. def pop(self, index=None):
  117. if index is None:
  118. index = len(self) - 1
  119. item = self[index]
  120. del self[index]
  121. return item
  122. @inheritdoc
  123. def remove(self, item):
  124. del self[self.index(item)]
  125. @inheritdoc
  126. def reverse(self):
  127. self._detach_children()
  128. super().reverse()
  129. @inheritdoc
  130. def sort(self, key=None, reverse=None):
  131. self._detach_children()
  132. kwargs = {}
  133. if key is not None:
  134. kwargs["key"] = key
  135. if reverse is not None:
  136. kwargs["reverse"] = reverse
  137. super().sort(**kwargs)