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.
 
 
 
 

159 lines
5.4 KiB

  1. # Copyright (C) 2012-2020 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. # Copyright (C) 2019-2020 Yuri Astrakhan <YuriAstrakhan@gmail.com>
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a copy
  5. # of this software and associated documentation files (the "Software"), to deal
  6. # in the Software without restriction, including without limitation the rights
  7. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. # copies of the Software, and to permit persons to whom the Software is
  9. # furnished to do so, subject to the following conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included in
  12. # all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. from weakref import ref
  22. from .list_proxy import ListProxy
  23. from .utils import _SliceNormalizerMixIn, inheritdoc
  24. class SmartList(_SliceNormalizerMixIn, list):
  25. """Implements the ``list`` interface with special handling of sublists.
  26. When a sublist is created (by ``list[i:j]``), any changes made to this
  27. list (such as the addition, removal, or replacement of elements) will be
  28. reflected in the sublist, or vice-versa, to the greatest degree possible.
  29. This is implemented by having sublists - instances of the
  30. :class:`.ListProxy` type - dynamically determine their elements by storing
  31. their slice info and retrieving that slice from the parent. Methods that
  32. change the size of the list also change the slice info. For example::
  33. >>> parent = SmartList([0, 1, 2, 3])
  34. >>> parent
  35. [0, 1, 2, 3]
  36. >>> child = parent[2:]
  37. >>> child
  38. [2, 3]
  39. >>> child.append(4)
  40. >>> child
  41. [2, 3, 4]
  42. >>> parent
  43. [0, 1, 2, 3, 4]
  44. """
  45. def __init__(self, iterable=None):
  46. if iterable:
  47. super().__init__(iterable)
  48. else:
  49. super().__init__()
  50. self._children = {}
  51. def __getitem__(self, key):
  52. if not isinstance(key, slice):
  53. return super().__getitem__(key)
  54. key = self._normalize_slice(key, clamp=False)
  55. sliceinfo = [key.start, key.stop, key.step]
  56. child = ListProxy(self, sliceinfo)
  57. child_ref = ref(child, self._delete_child)
  58. self._children[id(child_ref)] = (child_ref, sliceinfo)
  59. return child
  60. def __setitem__(self, key, item):
  61. if not isinstance(key, slice):
  62. super().__setitem__(key, item)
  63. return
  64. item = list(item)
  65. super().__setitem__(key, item)
  66. key = self._normalize_slice(key, clamp=True)
  67. diff = len(item) + (key.start - key.stop) // key.step
  68. if not diff:
  69. return
  70. for child, (start, stop, _step) in self._children.values():
  71. if start > key.stop:
  72. self._children[id(child)][1][0] += diff
  73. if stop is not None and stop >= key.stop:
  74. self._children[id(child)][1][1] += diff
  75. def __delitem__(self, key):
  76. super().__delitem__(key)
  77. if isinstance(key, slice):
  78. key = self._normalize_slice(key, clamp=True)
  79. else:
  80. key = slice(key, key + 1, 1)
  81. diff = (key.stop - key.start) // key.step
  82. for child, (start, stop, _step) in self._children.values():
  83. if start > key.start:
  84. self._children[id(child)][1][0] -= diff
  85. if stop is not None and stop >= key.stop:
  86. self._children[id(child)][1][1] -= diff
  87. def __add__(self, other):
  88. return SmartList(list(self) + other)
  89. def __radd__(self, other):
  90. return SmartList(other + list(self))
  91. def __iadd__(self, other):
  92. self.extend(other)
  93. return self
  94. def _delete_child(self, child_ref):
  95. """Remove a child reference that is about to be garbage-collected."""
  96. del self._children[id(child_ref)]
  97. def _detach_children(self):
  98. """Remove all children and give them independent parent copies."""
  99. children = [val[0] for val in self._children.values()]
  100. for child in children:
  101. child()._parent = list(self)
  102. self._children.clear()
  103. @inheritdoc
  104. def append(self, item):
  105. head = len(self)
  106. self[head:head] = [item]
  107. @inheritdoc
  108. def extend(self, item):
  109. head = len(self)
  110. self[head:head] = item
  111. @inheritdoc
  112. def insert(self, index, item):
  113. self[index:index] = [item]
  114. @inheritdoc
  115. def pop(self, index=None):
  116. if index is None:
  117. index = len(self) - 1
  118. item = self[index]
  119. del self[index]
  120. return item
  121. @inheritdoc
  122. def remove(self, item):
  123. del self[self.index(item)]
  124. @inheritdoc
  125. def reverse(self):
  126. self._detach_children()
  127. super().reverse()
  128. @inheritdoc
  129. def sort(self, key=None, reverse=None):
  130. self._detach_children()
  131. kwargs = {}
  132. if key is not None:
  133. kwargs["key"] = key
  134. if reverse is not None:
  135. kwargs["reverse"] = reverse
  136. super().sort(**kwargs)