1 //===--- ImmutableSet.h - Immutable (functional) set interface --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ImutAVLTree and ImmutableSet classes.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_IMSET_H
15 #define LLVM_ADT_IMSET_H
17 #include "llvm/Support/Allocator.h"
18 #include "llvm/ADT/FoldingSet.h"
23 //===----------------------------------------------------------------------===//
24 // Immutable AVL-Tree Definition.
25 //===----------------------------------------------------------------------===//
27 template <typename ImutInfo> class ImutAVLFactory;
29 template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
31 template <typename ImutInfo >
32 class ImutAVLTree : public FoldingSetNode {
34 typedef typename ImutInfo::key_type_ref key_type_ref;
35 typedef typename ImutInfo::value_type value_type;
36 typedef typename ImutInfo::value_type_ref value_type_ref;
38 typedef ImutAVLFactory<ImutInfo> Factory;
39 friend class ImutAVLFactory<ImutInfo>;
41 typedef ImutAVLTreeInOrderIterator<ImutInfo> iterator;
43 //===----------------------------------------------------===//
45 //===----------------------------------------------------===//
47 /// getLeft - Returns a pointer to the left subtree. This value
48 /// is NULL if there is no left subtree.
49 ImutAVLTree* getLeft() const {
50 assert (!isMutable() && "Node is incorrectly marked mutable.");
52 return reinterpret_cast<ImutAVLTree*>(Left);
55 /// getRight - Returns a pointer to the right subtree. This value is
56 /// NULL if there is no right subtree.
57 ImutAVLTree* getRight() const { return Right; }
60 /// getHeight - Returns the height of the tree. A tree with no subtrees
61 /// has a height of 1.
62 unsigned getHeight() const { return Height; }
64 /// getValue - Returns the data value associated with the tree node.
65 const value_type& getValue() const { return Value; }
67 /// find - Finds the subtree associated with the specified key value.
68 /// This method returns NULL if no matching subtree is found.
69 ImutAVLTree* find(key_type_ref K) {
70 ImutAVLTree *T = this;
73 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
75 if (ImutInfo::isEqual(K,CurrentKey))
77 else if (ImutInfo::isLess(K,CurrentKey))
86 /// size - Returns the number of nodes in the tree, which includes
87 /// both leaves and non-leaf nodes.
88 unsigned size() const {
91 if (const ImutAVLTree* L = getLeft()) n += L->size();
92 if (const ImutAVLTree* R = getRight()) n += R->size();
97 /// begin - Returns an iterator that iterates over the nodes of the tree
98 /// in an inorder traversal. The returned iterator thus refers to the
99 /// the tree node with the minimum data element.
100 iterator begin() const { return iterator(this); }
102 /// end - Returns an iterator for the tree that denotes the end of an
103 /// inorder traversal.
104 iterator end() const { return iterator(); }
106 /// isEqual - Compares two trees for structural equality and returns true
107 /// if they are equal. This worst case performance of this operation is
108 // linear in the sizes of the trees.
109 bool isEqual(const ImutAVLTree& RHS) const {
113 iterator LItr = begin(), LEnd = end();
114 iterator RItr = RHS.begin(), REnd = RHS.end();
116 while (LItr != LEnd && RItr != REnd) {
117 if (*LItr == *RItr) {
124 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(LItr->getValue()),
125 ImutInfo::KeyOfValue(RItr->getValue())))
128 // Also compare the data values.
129 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(LItr->getValue()),
130 ImutInfo::DataOfValue(RItr->getValue())))
137 return LItr == LEnd && RItr == REnd;
140 /// isNotEqual - Compares two trees for structural inequality. Performance
141 /// is the same is isEqual.
142 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
144 /// contains - Returns true if this tree contains a subtree (node) that
145 /// has an data element that matches the specified key. Complexity
146 /// is logarithmic in the size of the tree.
147 bool contains(const key_type_ref K) { return (bool) find(K); }
149 /// foreach - A member template the accepts invokes operator() on a functor
150 /// object (specifed by Callback) for every node/subtree in the tree.
151 /// Nodes are visited using an inorder traversal.
152 template <typename Callback>
153 void foreach(Callback& C) {
154 if (ImutAVLTree* L = getLeft()) L->foreach(C);
158 if (ImutAVLTree* R = getRight()) R->foreach(C);
161 /// verify - A utility method that checks that the balancing and
162 /// ordering invariants of the tree are satisifed. It is a recursive
163 /// method that returns the height of the tree, which is then consumed
164 /// by the enclosing verify call. External callers should ignore the
165 /// return value. An invalid tree will cause an assertion to fire in
167 unsigned verify() const {
168 unsigned HL = getLeft() ? getLeft()->verify() : 0;
169 unsigned HR = getRight() ? getRight()->verify() : 0;
171 assert (getHeight() == ( HL > HR ? HL : HR ) + 1
172 && "Height calculation wrong.");
174 assert ((HL > HR ? HL-HR : HR-HL) <= 2
175 && "Balancing invariant violated.");
179 || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
180 ImutInfo::KeyOfValue(getValue()))
181 && "Value in left child is not less that current value.");
185 || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
186 ImutInfo::KeyOfValue(getRight()->getValue()))
187 && "Current value is not less that value of right child.");
192 //===----------------------------------------------------===//
194 //===----------------------------------------------------===//
202 //===----------------------------------------------------===//
203 // Profiling or FoldingSet.
204 //===----------------------------------------------------===//
208 /// Profile - Generates a FoldingSet profile for a tree node before it is
209 /// created. This is used by the ImutAVLFactory when creating
212 void Profile(FoldingSetNodeID& ID, ImutAVLTree* L, ImutAVLTree* R,
216 ImutInfo::Profile(ID,V);
221 /// Profile - Generates a FoldingSet profile for an existing tree node.
222 void Profile(FoldingSetNodeID& ID) {
223 Profile(ID,getSafeLeft(),getRight(),getValue());
226 //===----------------------------------------------------===//
227 // Internal methods (node manipulation; used by Factory).
228 //===----------------------------------------------------===//
232 enum { Mutable = 0x1 };
234 /// ImutAVLTree - Internal constructor that is only called by
236 ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
237 : Left(reinterpret_cast<uintptr_t>(l) | Mutable),
238 Right(r), Height(height), Value(v) {}
241 /// isMutable - Returns true if the left and right subtree references
242 /// (as well as height) can be changed. If this method returns false,
243 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
244 /// object should always have this method return true. Further, if this
245 /// method returns false for an instance of ImutAVLTree, all subtrees
246 /// will also have this method return false. The converse is not true.
247 bool isMutable() const { return Left & Mutable; }
249 /// getSafeLeft - Returns the pointer to the left tree by always masking
250 /// out the mutable bit. This is used internally by ImutAVLFactory,
251 /// as no trees returned to the client should have the mutable flag set.
252 ImutAVLTree* getSafeLeft() const {
253 return reinterpret_cast<ImutAVLTree*>(Left & ~Mutable);
256 //===----------------------------------------------------===//
257 // Mutating operations. A tree root can be manipulated as
258 // long as its reference has not "escaped" from internal
259 // methods of a factory object (see below). When a tree
260 // pointer is externally viewable by client code, the
261 // internal "mutable bit" is cleared to mark the tree
262 // immutable. Note that a tree that still has its mutable
263 // bit set may have children (subtrees) that are themselves
265 //===----------------------------------------------------===//
268 /// MarkImmutable - Clears the mutable flag for a tree. After this happens,
269 /// it is an error to call setLeft(), setRight(), and setHeight(). It
270 /// is also then safe to call getLeft() instead of getSafeLeft().
271 void MarkImmutable() {
272 assert (isMutable() && "Mutable flag already removed.");
276 /// setLeft - Changes the reference of the left subtree. Used internally
277 /// by ImutAVLFactory.
278 void setLeft(ImutAVLTree* NewLeft) {
279 assert (isMutable() &&
280 "Only a mutable tree can have its left subtree changed.");
282 Left = reinterpret_cast<uintptr_t>(NewLeft) | Mutable;
285 /// setRight - Changes the reference of the right subtree. Used internally
286 /// by ImutAVLFactory.
287 void setRight(ImutAVLTree* NewRight) {
288 assert (isMutable() &&
289 "Only a mutable tree can have its right subtree changed.");
294 /// setHeight - Changes the height of the tree. Used internally by
296 void setHeight(unsigned h) {
297 assert (isMutable() && "Only a mutable tree can have its height changed.");
302 //===----------------------------------------------------------------------===//
303 // Immutable AVL-Tree Factory class.
304 //===----------------------------------------------------------------------===//
306 template <typename ImutInfo >
307 class ImutAVLFactory {
308 typedef ImutAVLTree<ImutInfo> TreeTy;
309 typedef typename TreeTy::value_type_ref value_type_ref;
310 typedef typename TreeTy::key_type_ref key_type_ref;
312 typedef FoldingSet<TreeTy> CacheTy;
315 BumpPtrAllocator Allocator;
317 //===--------------------------------------------------===//
319 //===--------------------------------------------------===//
324 TreeTy* Add(TreeTy* T, value_type_ref V) {
325 T = Add_internal(V,T);
330 TreeTy* Remove(TreeTy* T, key_type_ref V) {
331 T = Remove_internal(V,T);
336 TreeTy* GetEmptyTree() const { return NULL; }
338 BumpPtrAllocator& getAllocator() { return Allocator; }
340 //===--------------------------------------------------===//
341 // A bunch of quick helper functions used for reasoning
342 // about the properties of trees and their children.
343 // These have succinct names so that the balancing code
344 // is as terse (and readable) as possible.
345 //===--------------------------------------------------===//
348 bool isEmpty(TreeTy* T) const { return !T; }
349 unsigned Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
350 TreeTy* Left(TreeTy* T) const { return T->getSafeLeft(); }
351 TreeTy* Right(TreeTy* T) const { return T->getRight(); }
352 value_type_ref Value(TreeTy* T) const { return T->Value; }
354 unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
355 unsigned hl = Height(L);
356 unsigned hr = Height(R);
357 return ( hl > hr ? hl : hr ) + 1;
360 //===--------------------------------------------------===//
361 // "CreateNode" is used to generate new tree roots that link
362 // to other trees. The functon may also simply move links
363 // in an existing root if that root is still marked mutable.
364 // This is necessary because otherwise our balancing code
365 // would leak memory as it would create nodes that are
366 // then discarded later before the finished tree is
367 // returned to the caller.
368 //===--------------------------------------------------===//
370 TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
372 TreeTy::Profile(ID,L,R,V);
375 if (TreeTy* T = Cache.FindNodeOrInsertPos(ID,InsertPos))
378 assert (InsertPos != NULL);
380 // Allocate the new tree node and insert it into the cache.
381 TreeTy* T = (TreeTy*) Allocator.Allocate<TreeTy>();
382 new (T) TreeTy(L,R,V,IncrementHeight(L,R));
383 Cache.InsertNode(T,InsertPos);
388 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
389 assert (!isEmpty(OldTree));
391 if (OldTree->isMutable()) {
393 OldTree->setRight(R);
394 OldTree->setHeight(IncrementHeight(L,R));
397 else return CreateNode(L, Value(OldTree), R);
400 /// Balance - Used by Add_internal and Remove_internal to
401 /// balance a newly created tree.
402 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
404 unsigned hl = Height(L);
405 unsigned hr = Height(R);
408 assert (!isEmpty(L) &&
409 "Left tree cannot be empty to have a height >= 2.");
411 TreeTy* LL = Left(L);
412 TreeTy* LR = Right(L);
414 if (Height(LL) >= Height(LR))
415 return CreateNode(LL, L, CreateNode(LR,V,R));
417 assert (!isEmpty(LR) &&
418 "LR cannot be empty because it has a height >= 1.");
420 TreeTy* LRL = Left(LR);
421 TreeTy* LRR = Right(LR);
423 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
425 else if (hr > hl + 2) {
426 assert (!isEmpty(R) &&
427 "Right tree cannot be empty to have a height >= 2.");
429 TreeTy* RL = Left(R);
430 TreeTy* RR = Right(R);
432 if (Height(RR) >= Height(RL))
433 return CreateNode(CreateNode(L,V,RL), R, RR);
435 assert (!isEmpty(RL) &&
436 "RL cannot be empty because it has a height >= 1.");
438 TreeTy* RLL = Left(RL);
439 TreeTy* RLR = Right(RL);
441 return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
444 return CreateNode(L,V,R);
447 /// Add_internal - Creates a new tree that includes the specified
448 /// data and the data from the original tree. If the original tree
449 /// already contained the data item, the original tree is returned.
450 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
452 return CreateNode(T, V, T);
454 assert (!T->isMutable());
456 key_type_ref K = ImutInfo::KeyOfValue(V);
457 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
459 if (ImutInfo::isEqual(K,KCurrent))
460 return CreateNode(Left(T), V, Right(T));
461 else if (ImutInfo::isLess(K,KCurrent))
462 return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
464 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
467 /// Remove_interal - Creates a new tree that includes all the data
468 /// from the original tree except the specified data. If the
469 /// specified data did not exist in the original tree, the original
470 /// tree is returned.
471 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
475 assert (!T->isMutable());
477 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
479 if (ImutInfo::isEqual(K,KCurrent))
480 return CombineLeftRightTrees(Left(T),Right(T));
481 else if (ImutInfo::isLess(K,KCurrent))
482 return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
484 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
487 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
488 if (isEmpty(L)) return R;
489 if (isEmpty(R)) return L;
492 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
493 return Balance(L,Value(OldNode),NewRight);
496 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
497 assert (!isEmpty(T));
499 if (isEmpty(Left(T))) {
504 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
507 /// MarkImmutable - Clears the mutable bits of a root and all of its
509 void MarkImmutable(TreeTy* T) {
510 if (!T || !T->isMutable())
514 MarkImmutable(Left(T));
515 MarkImmutable(Right(T));
520 //===----------------------------------------------------------------------===//
521 // Immutable AVL-Tree Iterators.
522 //===----------------------------------------------------------------------===//
524 template <typename ImutInfo>
525 class ImutAVLTreeGenericIterator {
526 SmallVector<uintptr_t,20> stack;
528 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
531 typedef ImutAVLTree<ImutInfo> TreeTy;
532 typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
534 inline ImutAVLTreeGenericIterator() {}
535 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
536 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
539 TreeTy* operator*() const {
540 assert (!stack.empty());
541 return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
544 uintptr_t getVisitState() {
545 assert (!stack.empty());
546 return stack.back() & Flags;
550 bool AtEnd() const { return stack.empty(); }
552 bool AtBeginning() const {
553 return stack.size() == 1 && getVisitState() == VisitedNone;
556 void SkipToParent() {
557 assert (!stack.empty());
563 switch (getVisitState()) {
565 stack.back() |= VisitedLeft;
568 stack.back() |= VisitedRight;
571 assert (false && "Unreachable.");
575 inline bool operator==(const _Self& x) const {
576 if (stack.size() != x.stack.size())
579 for (unsigned i = 0 ; i < stack.size(); i++)
580 if (stack[i] != x.stack[i])
586 inline bool operator!=(const _Self& x) const { return !operator==(x); }
588 _Self& operator++() {
589 assert (!stack.empty());
591 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
594 switch (getVisitState()) {
596 if (TreeTy* L = Current->getLeft())
597 stack.push_back(reinterpret_cast<uintptr_t>(L));
599 stack.back() |= VisitedLeft;
604 if (TreeTy* R = Current->getRight())
605 stack.push_back(reinterpret_cast<uintptr_t>(R));
607 stack.back() |= VisitedRight;
616 assert (false && "Unreachable.");
622 _Self& operator--() {
623 assert (!stack.empty());
625 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
628 switch (getVisitState()) {
634 stack.back() &= ~Flags; // Set state to "VisitedNone."
636 if (TreeTy* L = Current->getLeft())
637 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
642 stack.back() &= ~Flags;
643 stack.back() |= VisitedLeft;
645 if (TreeTy* R = Current->getRight())
646 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
651 assert (false && "Unreachable.");
658 template <typename ImutInfo>
659 class ImutAVLTreeInOrderIterator {
660 typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
661 InternalIteratorTy InternalItr;
664 typedef ImutAVLTree<ImutInfo> TreeTy;
665 typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
667 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
668 if (Root) operator++(); // Advance to first element.
671 ImutAVLTreeInOrderIterator() : InternalItr() {}
673 inline bool operator==(const _Self& x) const {
674 return InternalItr == x.InternalItr;
677 inline bool operator!=(const _Self& x) const { return !operator==(x); }
679 inline TreeTy* operator*() const { return *InternalItr; }
680 inline TreeTy* operator->() const { return *InternalItr; }
682 inline _Self& operator++() {
684 while (!InternalItr.AtEnd() &&
685 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
690 inline _Self& operator--() {
692 while (!InternalItr.AtBeginning() &&
693 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
698 inline void SkipSubTree() {
699 InternalItr.SkipToParent();
701 while (!InternalItr.AtEnd() &&
702 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
707 //===----------------------------------------------------------------------===//
708 // Trait classes for Profile information.
709 //===----------------------------------------------------------------------===//
711 /// Generic profile template. The default behavior is to invoke the
712 /// profile method of an object. Specializations for primitive integers
713 /// and generic handling of pointers is done below.
714 template <typename T>
715 struct ImutProfileInfo {
716 typedef const T value_type;
717 typedef const T& value_type_ref;
719 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
720 FoldingSetTrait<T>::Profile(X,ID);
724 /// Profile traits for integers.
725 template <typename T>
726 struct ImutProfileInteger {
727 typedef const T value_type;
728 typedef const T& value_type_ref;
730 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
735 #define PROFILE_INTEGER_INFO(X)\
736 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
738 PROFILE_INTEGER_INFO(char)
739 PROFILE_INTEGER_INFO(unsigned char)
740 PROFILE_INTEGER_INFO(short)
741 PROFILE_INTEGER_INFO(unsigned short)
742 PROFILE_INTEGER_INFO(unsigned)
743 PROFILE_INTEGER_INFO(signed)
744 PROFILE_INTEGER_INFO(long)
745 PROFILE_INTEGER_INFO(unsigned long)
746 PROFILE_INTEGER_INFO(long long)
747 PROFILE_INTEGER_INFO(unsigned long long)
749 #undef PROFILE_INTEGER_INFO
751 /// Generic profile trait for pointer types. We treat pointers as
752 /// references to unique objects.
753 template <typename T>
754 struct ImutProfileInfo<T*> {
755 typedef const T* value_type;
756 typedef value_type value_type_ref;
758 static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
763 //===----------------------------------------------------------------------===//
764 // Trait classes that contain element comparison operators and type
765 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
766 // inherit from the profile traits (ImutProfileInfo) to include operations
767 // for element profiling.
768 //===----------------------------------------------------------------------===//
771 /// ImutContainerInfo - Generic definition of comparison operations for
772 /// elements of immutable containers that defaults to using
773 /// std::equal_to<> and std::less<> to perform comparison of elements.
774 template <typename T>
775 struct ImutContainerInfo : public ImutProfileInfo<T> {
776 typedef typename ImutProfileInfo<T>::value_type value_type;
777 typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
778 typedef value_type key_type;
779 typedef value_type_ref key_type_ref;
780 typedef bool data_type;
781 typedef bool data_type_ref;
783 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
784 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
786 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
787 return std::equal_to<key_type>()(LHS,RHS);
790 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
791 return std::less<key_type>()(LHS,RHS);
794 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
797 /// ImutContainerInfo - Specialization for pointer values to treat pointers
798 /// as references to unique objects. Pointers are thus compared by
800 template <typename T>
801 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
802 typedef typename ImutProfileInfo<T*>::value_type value_type;
803 typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
804 typedef value_type key_type;
805 typedef value_type_ref key_type_ref;
806 typedef bool data_type;
807 typedef bool data_type_ref;
809 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
810 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
812 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
816 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
820 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
823 //===----------------------------------------------------------------------===//
825 //===----------------------------------------------------------------------===//
827 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
830 typedef typename ValInfo::value_type value_type;
831 typedef typename ValInfo::value_type_ref value_type_ref;
834 typedef ImutAVLTree<ValInfo> TreeTy;
837 ImmutableSet(TreeTy* R) : Root(R) {}
842 typename TreeTy::Factory F;
847 /// GetEmptySet - Returns an immutable set that contains no elements.
848 ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
850 /// Add - Creates a new immutable set that contains all of the values
851 /// of the original set with the addition of the specified value. If
852 /// the original set already included the value, then the original set is
853 /// returned and no memory is allocated. The time and space complexity
854 /// of this operation is logarithmic in the size of the original set.
855 /// The memory allocated to represent the set is released when the
856 /// factory object that created the set is destroyed.
857 ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
858 return ImmutableSet(F.Add(Old.Root,V));
861 /// Remove - Creates a new immutable set that contains all of the values
862 /// of the original set with the exception of the specified value. If
863 /// the original set did not contain the value, the original set is
864 /// returned and no memory is allocated. The time and space complexity
865 /// of this operation is logarithmic in the size of the original set.
866 /// The memory allocated to represent the set is released when the
867 /// factory object that created the set is destroyed.
868 ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
869 return ImmutableSet(F.Remove(Old.Root,V));
872 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
875 Factory(const Factory& RHS) {};
876 void operator=(const Factory& RHS) {};
879 friend class Factory;
881 /// contains - Returns true if the set contains the specified value.
882 bool contains(const value_type_ref V) const {
883 return Root ? Root->contains(V) : false;
886 bool operator==(ImmutableSet RHS) const {
887 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
890 bool operator!=(ImmutableSet RHS) const {
891 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
894 /// isEmpty - Return true if the set contains no elements.
895 bool isEmpty() const { return !Root; }
897 template <typename Callback>
898 void foreach(Callback& C) { if (Root) Root->foreach(C); }
900 template <typename Callback>
901 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
903 //===--------------------------------------------------===//
905 //===--------------------------------------------------===//
908 typename TreeTy::iterator itr;
911 iterator(TreeTy* t) : itr(t) {}
912 friend class ImmutableSet<ValT,ValInfo>;
914 inline value_type_ref operator*() const { return itr->getValue(); }
915 inline iterator& operator++() { ++itr; return *this; }
916 inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
917 inline iterator& operator--() { --itr; return *this; }
918 inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
919 inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
920 inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
923 iterator begin() const { return iterator(Root); }
924 iterator end() const { return iterator(); }
926 //===--------------------------------------------------===//
928 //===--------------------------------------------------===//
930 void verify() const { if (Root) Root->verify(); }
931 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
934 } // end namespace llvm