http://scons.tigris.org/issues/show_bug.cgi?id=2345
[scons.git] / src / engine / SCons / compat / _scons_sets.py
1 """Classes to represent arbitrary sets (including sets of sets).
2
3 This module implements sets using dictionaries whose values are
4 ignored.  The usual operations (union, intersection, deletion, etc.)
5 are provided as both methods and operators.
6
7 Important: sets are not sequences!  While they support 'x in s',
8 'len(s)', and 'for x in s', none of those operations are unique for
9 sequences; for example, mappings support all three as well.  The
10 characteristic operation for sequences is subscripting with small
11 integers: s[i], for i in range(len(s)).  Sets don't support
12 subscripting at all.  Also, sequences allow multiple occurrences and
13 their elements have a definite order; sets on the other hand don't
14 record multiple occurrences and don't remember the order of element
15 insertion (which is why they don't support s[i]).
16
17 The following classes are provided:
18
19 BaseSet -- All the operations common to both mutable and immutable
20     sets. This is an abstract class, not meant to be directly
21     instantiated.
22
23 Set -- Mutable sets, subclass of BaseSet; not hashable.
24
25 ImmutableSet -- Immutable sets, subclass of BaseSet; hashable.
26     An iterable argument is mandatory to create an ImmutableSet.
27
28 _TemporarilyImmutableSet -- A wrapper around a Set, hashable,
29     giving the same hash value as the immutable set equivalent
30     would have.  Do not use this class directly.
31
32 Only hashable objects can be added to a Set. In particular, you cannot
33 really add a Set as an element to another Set; if you try, what is
34 actually added is an ImmutableSet built from it (it compares equal to
35 the one you tried adding).
36
37 When you ask if `x in y' where x is a Set and y is a Set or
38 ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and
39 what's tested is actually `z in y'.
40
41 """
42
43 # Code history:
44 #
45 # - Greg V. Wilson wrote the first version, using a different approach
46 #   to the mutable/immutable problem, and inheriting from dict.
47 #
48 # - Alex Martelli modified Greg's version to implement the current
49 #   Set/ImmutableSet approach, and make the data an attribute.
50 #
51 # - Guido van Rossum rewrote much of the code, made some API changes,
52 #   and cleaned up the docstrings.
53 #
54 # - Raymond Hettinger added a number of speedups and other
55 #   improvements.
56
57 from __future__ import generators
58 try:
59     from itertools import ifilter, ifilterfalse
60 except ImportError:
61     # Code to make the module run under Py2.2
62     def ifilter(predicate, iterable):
63         if predicate is None:
64             def predicate(x):
65                 return x
66         for x in iterable:
67             if predicate(x):
68                 yield x
69     def ifilterfalse(predicate, iterable):
70         if predicate is None:
71             def predicate(x):
72                 return x
73         for x in iterable:
74             if not predicate(x):
75                 yield x
76     try:
77         True, False
78     except NameError:
79         True, False = (0==0, 0!=0)
80
81 __all__ = ['BaseSet', 'Set', 'ImmutableSet']
82
83 class BaseSet(object):
84     """Common base class for mutable and immutable sets."""
85
86     __slots__ = ['_data']
87
88     # Constructor
89
90     def __init__(self):
91         """This is an abstract class."""
92         # Don't call this from a concrete subclass!
93         if self.__class__ is BaseSet:
94             raise TypeError("BaseSet is an abstract class.  "
95                               "Use Set or ImmutableSet.")
96
97     # Standard protocols: __len__, __repr__, __str__, __iter__
98
99     def __len__(self):
100         """Return the number of elements of a set."""
101         return len(self._data)
102
103     def __repr__(self):
104         """Return string representation of a set.
105
106         This looks like 'Set([<list of elements>])'.
107         """
108         return self._repr()
109
110     # __str__ is the same as __repr__
111     __str__ = __repr__
112
113     def _repr(self, sort_them=False):
114         elements = self._data.keys()
115         if sort_them:
116             elements.sort()
117         return '%s(%r)' % (self.__class__.__name__, elements)
118
119     def __iter__(self):
120         """Return an iterator over the elements or a set.
121
122         This is the keys iterator for the underlying dict.
123         """
124         # Wrapping name in () prevents fixer from "fixing" this
125         return (self._data.iterkeys)()
126
127     # Three-way comparison is not supported.  However, because __eq__ is
128     # tried before __cmp__, if Set x == Set y, x.__eq__(y) returns True and
129     # then cmp(x, y) returns 0 (Python doesn't actually call __cmp__ in this
130     # case).
131
132     def __cmp__(self, other):
133         raise TypeError("can't compare sets using cmp()")
134
135     # Equality comparisons using the underlying dicts.  Mixed-type comparisons
136     # are allowed here, where Set == z for non-Set z always returns False,
137     # and Set != z always True.  This allows expressions like "x in y" to
138     # give the expected result when y is a sequence of mixed types, not
139     # raising a pointless TypeError just because y contains a Set, or x is
140     # a Set and y contain's a non-set ("in" invokes only __eq__).
141     # Subtle:  it would be nicer if __eq__ and __ne__ could return
142     # NotImplemented instead of True or False.  Then the other comparand
143     # would get a chance to determine the result, and if the other comparand
144     # also returned NotImplemented then it would fall back to object address
145     # comparison (which would always return False for __eq__ and always
146     # True for __ne__).  However, that doesn't work, because this type
147     # *also* implements __cmp__:  if, e.g., __eq__ returns NotImplemented,
148     # Python tries __cmp__ next, and the __cmp__ here then raises TypeError.
149
150     def __eq__(self, other):
151         if isinstance(other, BaseSet):
152             return self._data == other._data
153         else:
154             return False
155
156     def __ne__(self, other):
157         if isinstance(other, BaseSet):
158             return self._data != other._data
159         else:
160             return True
161
162     # Copying operations
163
164     def copy(self):
165         """Return a shallow copy of a set."""
166         result = self.__class__()
167         result._data.update(self._data)
168         return result
169
170     __copy__ = copy # For the copy module
171
172     def __deepcopy__(self, memo):
173         """Return a deep copy of a set; used by copy module."""
174         # This pre-creates the result and inserts it in the memo
175         # early, in case the deep copy recurses into another reference
176         # to this same set.  A set can't be an element of itself, but
177         # it can certainly contain an object that has a reference to
178         # itself.
179         from copy import deepcopy
180         result = self.__class__()
181         memo[id(self)] = result
182         data = result._data
183         value = True
184         for elt in self:
185             data[deepcopy(elt, memo)] = value
186         return result
187
188     # Standard set operations: union, intersection, both differences.
189     # Each has an operator version (e.g. __or__, invoked with |) and a
190     # method version (e.g. union).
191     # Subtle:  Each pair requires distinct code so that the outcome is
192     # correct when the type of other isn't suitable.  For example, if
193     # we did "union = __or__" instead, then Set().union(3) would return
194     # NotImplemented instead of raising TypeError (albeit that *why* it
195     # raises TypeError as-is is also a bit subtle).
196
197     def __or__(self, other):
198         """Return the union of two sets as a new set.
199
200         (I.e. all elements that are in either set.)
201         """
202         if not isinstance(other, BaseSet):
203             return NotImplemented
204         return self.union(other)
205
206     def union(self, other):
207         """Return the union of two sets as a new set.
208
209         (I.e. all elements that are in either set.)
210         """
211         result = self.__class__(self)
212         result._update(other)
213         return result
214
215     def __and__(self, other):
216         """Return the intersection of two sets as a new set.
217
218         (I.e. all elements that are in both sets.)
219         """
220         if not isinstance(other, BaseSet):
221             return NotImplemented
222         return self.intersection(other)
223
224     def intersection(self, other):
225         """Return the intersection of two sets as a new set.
226
227         (I.e. all elements that are in both sets.)
228         """
229         if not isinstance(other, BaseSet):
230             other = Set(other)
231         if len(self) <= len(other):
232             little, big = self, other
233         else:
234             little, big = other, self
235         common = ifilter(big._data.has_key, little)
236         return self.__class__(common)
237
238     def __xor__(self, other):
239         """Return the symmetric difference of two sets as a new set.
240
241         (I.e. all elements that are in exactly one of the sets.)
242         """
243         if not isinstance(other, BaseSet):
244             return NotImplemented
245         return self.symmetric_difference(other)
246
247     def symmetric_difference(self, other):
248         """Return the symmetric difference of two sets as a new set.
249
250         (I.e. all elements that are in exactly one of the sets.)
251         """
252         result = self.__class__()
253         data = result._data
254         value = True
255         selfdata = self._data
256         try:
257             otherdata = other._data
258         except AttributeError:
259             otherdata = Set(other)._data
260         for elt in ifilterfalse(otherdata.has_key, selfdata):
261             data[elt] = value
262         for elt in ifilterfalse(selfdata.has_key, otherdata):
263             data[elt] = value
264         return result
265
266     def  __sub__(self, other):
267         """Return the difference of two sets as a new Set.
268
269         (I.e. all elements that are in this set and not in the other.)
270         """
271         if not isinstance(other, BaseSet):
272             return NotImplemented
273         return self.difference(other)
274
275     def difference(self, other):
276         """Return the difference of two sets as a new Set.
277
278         (I.e. all elements that are in this set and not in the other.)
279         """
280         result = self.__class__()
281         data = result._data
282         try:
283             otherdata = other._data
284         except AttributeError:
285             otherdata = Set(other)._data
286         value = True
287         for elt in ifilterfalse(otherdata.has_key, self):
288             data[elt] = value
289         return result
290
291     # Membership test
292
293     def __contains__(self, element):
294         """Report whether an element is a member of a set.
295
296         (Called in response to the expression `element in self'.)
297         """
298         try:
299             return element in self._data
300         except TypeError:
301             transform = getattr(element, "__as_temporarily_immutable__", None)
302             if transform is None:
303                 raise # re-raise the TypeError exception we caught
304             return transform() in self._data
305
306     # Subset and superset test
307
308     def issubset(self, other):
309         """Report whether another set contains this set."""
310         self._binary_sanity_check(other)
311         if len(self) > len(other):  # Fast check for obvious cases
312             return False
313         for elt in ifilterfalse(other._data.has_key, self):
314             return False
315         return True
316
317     def issuperset(self, other):
318         """Report whether this set contains another set."""
319         self._binary_sanity_check(other)
320         if len(self) < len(other):  # Fast check for obvious cases
321             return False
322         for elt in ifilterfalse(self._data.has_key, other):
323             return False
324         return True
325
326     # Inequality comparisons using the is-subset relation.
327     __le__ = issubset
328     __ge__ = issuperset
329
330     def __lt__(self, other):
331         self._binary_sanity_check(other)
332         return len(self) < len(other) and self.issubset(other)
333
334     def __gt__(self, other):
335         self._binary_sanity_check(other)
336         return len(self) > len(other) and self.issuperset(other)
337
338     # Assorted helpers
339
340     def _binary_sanity_check(self, other):
341         # Check that the other argument to a binary operation is also
342         # a set, raising a TypeError otherwise.
343         if not isinstance(other, BaseSet):
344             raise TypeError("Binary operation only permitted between sets")
345
346     def _compute_hash(self):
347         # Calculate hash code for a set by xor'ing the hash codes of
348         # the elements.  This ensures that the hash code does not depend
349         # on the order in which elements are added to the set.  This is
350         # not called __hash__ because a BaseSet should not be hashable;
351         # only an ImmutableSet is hashable.
352         result = 0
353         for elt in self:
354             result ^= hash(elt)
355         return result
356
357     def _update(self, iterable):
358         # The main loop for update() and the subclass __init__() methods.
359         data = self._data
360
361         # Use the fast update() method when a dictionary is available.
362         if isinstance(iterable, BaseSet):
363             data.update(iterable._data)
364             return
365
366         value = True
367
368         if type(iterable) in (list, tuple, xrange):
369             # Optimized: we know that __iter__() and next() can't
370             # raise TypeError, so we can move 'try:' out of the loop.
371             it = iter(iterable)
372             while True:
373                 try:
374                     for element in it:
375                         data[element] = value
376                     return
377                 except TypeError:
378                     transform = getattr(element, "__as_immutable__", None)
379                     if transform is None:
380                         raise # re-raise the TypeError exception we caught
381                     data[transform()] = value
382         else:
383             # Safe: only catch TypeError where intended
384             for element in iterable:
385                 try:
386                     data[element] = value
387                 except TypeError:
388                     transform = getattr(element, "__as_immutable__", None)
389                     if transform is None:
390                         raise # re-raise the TypeError exception we caught
391                     data[transform()] = value
392
393
394 class ImmutableSet(BaseSet):
395     """Immutable set class."""
396
397     __slots__ = ['_hashcode']
398
399     # BaseSet + hashing
400
401     def __init__(self, iterable=None):
402         """Construct an immutable set from an optional iterable."""
403         self._hashcode = None
404         self._data = {}
405         if iterable is not None:
406             self._update(iterable)
407
408     def __hash__(self):
409         if self._hashcode is None:
410             self._hashcode = self._compute_hash()
411         return self._hashcode
412
413     def __getstate__(self):
414         return self._data, self._hashcode
415
416     def __setstate__(self, state):
417         self._data, self._hashcode = state
418
419 class Set(BaseSet):
420     """ Mutable set class."""
421
422     __slots__ = []
423
424     # BaseSet + operations requiring mutability; no hashing
425
426     def __init__(self, iterable=None):
427         """Construct a set from an optional iterable."""
428         self._data = {}
429         if iterable is not None:
430             self._update(iterable)
431
432     def __getstate__(self):
433         # getstate's results are ignored if it is not
434         return self._data,
435
436     def __setstate__(self, data):
437         self._data, = data
438
439     def __hash__(self):
440         """A Set cannot be hashed."""
441         # We inherit object.__hash__, so we must deny this explicitly
442         raise TypeError("Can't hash a Set, only an ImmutableSet.")
443
444     # In-place union, intersection, differences.
445     # Subtle:  The xyz_update() functions deliberately return None,
446     # as do all mutating operations on built-in container types.
447     # The __xyz__ spellings have to return self, though.
448
449     def __ior__(self, other):
450         """Update a set with the union of itself and another."""
451         self._binary_sanity_check(other)
452         self._data.update(other._data)
453         return self
454
455     def union_update(self, other):
456         """Update a set with the union of itself and another."""
457         self._update(other)
458
459     def __iand__(self, other):
460         """Update a set with the intersection of itself and another."""
461         self._binary_sanity_check(other)
462         self._data = (self & other)._data
463         return self
464
465     def intersection_update(self, other):
466         """Update a set with the intersection of itself and another."""
467         if isinstance(other, BaseSet):
468             self &= other
469         else:
470             self._data = (self.intersection(other))._data
471
472     def __ixor__(self, other):
473         """Update a set with the symmetric difference of itself and another."""
474         self._binary_sanity_check(other)
475         self.symmetric_difference_update(other)
476         return self
477
478     def symmetric_difference_update(self, other):
479         """Update a set with the symmetric difference of itself and another."""
480         data = self._data
481         value = True
482         if not isinstance(other, BaseSet):
483             other = Set(other)
484         if self is other:
485             self.clear()
486         for elt in other:
487             if elt in data:
488                 del data[elt]
489             else:
490                 data[elt] = value
491
492     def __isub__(self, other):
493         """Remove all elements of another set from this set."""
494         self._binary_sanity_check(other)
495         self.difference_update(other)
496         return self
497
498     def difference_update(self, other):
499         """Remove all elements of another set from this set."""
500         data = self._data
501         if not isinstance(other, BaseSet):
502             other = Set(other)
503         if self is other:
504             self.clear()
505         for elt in ifilter(data.has_key, other):
506             del data[elt]
507
508     # Python dict-like mass mutations: update, clear
509
510     def update(self, iterable):
511         """Add all values from an iterable (such as a list or file)."""
512         self._update(iterable)
513
514     def clear(self):
515         """Remove all elements from this set."""
516         self._data.clear()
517
518     # Single-element mutations: add, remove, discard
519
520     def add(self, element):
521         """Add an element to a set.
522
523         This has no effect if the element is already present.
524         """
525         try:
526             self._data[element] = True
527         except TypeError:
528             transform = getattr(element, "__as_immutable__", None)
529             if transform is None:
530                 raise # re-raise the TypeError exception we caught
531             self._data[transform()] = True
532
533     def remove(self, element):
534         """Remove an element from a set; it must be a member.
535
536         If the element is not a member, raise a KeyError.
537         """
538         try:
539             del self._data[element]
540         except TypeError:
541             transform = getattr(element, "__as_temporarily_immutable__", None)
542             if transform is None:
543                 raise # re-raise the TypeError exception we caught
544             del self._data[transform()]
545
546     def discard(self, element):
547         """Remove an element from a set if it is a member.
548
549         If the element is not a member, do nothing.
550         """
551         try:
552             self.remove(element)
553         except KeyError:
554             pass
555
556     def pop(self):
557         """Remove and return an arbitrary set element."""
558         return self._data.popitem()[0]
559
560     def __as_immutable__(self):
561         # Return a copy of self as an immutable set
562         return ImmutableSet(self)
563
564     def __as_temporarily_immutable__(self):
565         # Return self wrapped in a temporarily immutable set
566         return _TemporarilyImmutableSet(self)
567
568
569 class _TemporarilyImmutableSet(BaseSet):
570     # Wrap a mutable set as if it was temporarily immutable.
571     # This only supplies hashing and equality comparisons.
572
573     def __init__(self, set):
574         self._set = set
575         self._data = set._data  # Needed by ImmutableSet.__eq__()
576
577     def __hash__(self):
578         return self._set._compute_hash()
579
580 # Local Variables:
581 # tab-width:4
582 # indent-tabs-mode:nil
583 # End:
584 # vim: set expandtab tabstop=4 shiftwidth=4: