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 //===----------------------------------------------------===//
203 //===----------------------------------------------------===//
204 // Profiling or FoldingSet.
205 //===----------------------------------------------------===//
210 unsigned ComputeHash(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
213 if (L) ID.AddInteger(L->ComputeHash());
214 ImutInfo::Profile(ID,V);
216 // Compute the "intermediate" hash. Basically, we want the net profile to
217 // be: H(H(....H(H(H(item0),item1),item2)...),itemN), where
218 // H(item) is the hash of the data item and H(hash,item) is a hash
219 // of the last item hash and the the next item.
221 unsigned X = ID.ComputeHash();
226 ID.AddInteger(R->ComputeHash());
227 X = ID.ComputeHash();
233 inline unsigned ComputeHash() {
234 if (!isMutable() && Hash) return Hash;
235 Hash = ComputeHash(getSafeLeft(), getRight(), getValue());
239 /// Profile - Generates a FoldingSet profile for a tree node before it is
240 /// created. This is used by the ImutAVLFactory when creating
243 void Profile(FoldingSetNodeID& ID, ImutAVLTree* L, ImutAVLTree* R,
246 ID.AddInteger(ComputeHash(L, R, V));
251 /// Profile - Generates a FoldingSet profile for an existing tree node.
252 void Profile(FoldingSetNodeID& ID) {
253 ID.AddInteger(ComputeHash());
256 //===----------------------------------------------------===//
257 // Internal methods (node manipulation; used by Factory).
258 //===----------------------------------------------------===//
262 enum { Mutable = 0x1 };
264 /// ImutAVLTree - Internal constructor that is only called by
266 ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
267 : Left(reinterpret_cast<uintptr_t>(l) | Mutable),
268 Right(r), Height(height), Value(v), Hash(0) {}
271 /// isMutable - Returns true if the left and right subtree references
272 /// (as well as height) can be changed. If this method returns false,
273 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
274 /// object should always have this method return true. Further, if this
275 /// method returns false for an instance of ImutAVLTree, all subtrees
276 /// will also have this method return false. The converse is not true.
277 bool isMutable() const { return Left & Mutable; }
279 /// getSafeLeft - Returns the pointer to the left tree by always masking
280 /// out the mutable bit. This is used internally by ImutAVLFactory,
281 /// as no trees returned to the client should have the mutable flag set.
282 ImutAVLTree* getSafeLeft() const {
283 return reinterpret_cast<ImutAVLTree*>(Left & ~Mutable);
286 //===----------------------------------------------------===//
287 // Mutating operations. A tree root can be manipulated as
288 // long as its reference has not "escaped" from internal
289 // methods of a factory object (see below). When a tree
290 // pointer is externally viewable by client code, the
291 // internal "mutable bit" is cleared to mark the tree
292 // immutable. Note that a tree that still has its mutable
293 // bit set may have children (subtrees) that are themselves
295 //===----------------------------------------------------===//
298 /// MarkImmutable - Clears the mutable flag for a tree. After this happens,
299 /// it is an error to call setLeft(), setRight(), and setHeight(). It
300 /// is also then safe to call getLeft() instead of getSafeLeft().
301 void MarkImmutable() {
302 assert (isMutable() && "Mutable flag already removed.");
306 /// setLeft - Changes the reference of the left subtree. Used internally
307 /// by ImutAVLFactory.
308 void setLeft(ImutAVLTree* NewLeft) {
309 assert (isMutable() &&
310 "Only a mutable tree can have its left subtree changed.");
312 Left = reinterpret_cast<uintptr_t>(NewLeft) | Mutable;
315 /// setRight - Changes the reference of the right subtree. Used internally
316 /// by ImutAVLFactory.
317 void setRight(ImutAVLTree* NewRight) {
318 assert (isMutable() &&
319 "Only a mutable tree can have its right subtree changed.");
324 /// setHeight - Changes the height of the tree. Used internally by
326 void setHeight(unsigned h) {
327 assert (isMutable() && "Only a mutable tree can have its height changed.");
332 //===----------------------------------------------------------------------===//
333 // Immutable AVL-Tree Factory class.
334 //===----------------------------------------------------------------------===//
336 template <typename ImutInfo >
337 class ImutAVLFactory {
338 typedef ImutAVLTree<ImutInfo> TreeTy;
339 typedef typename TreeTy::value_type_ref value_type_ref;
340 typedef typename TreeTy::key_type_ref key_type_ref;
342 typedef FoldingSet<TreeTy> CacheTy;
345 BumpPtrAllocator Allocator;
347 //===--------------------------------------------------===//
349 //===--------------------------------------------------===//
354 TreeTy* Add(TreeTy* T, value_type_ref V) {
355 T = Add_internal(V,T);
360 TreeTy* Remove(TreeTy* T, key_type_ref V) {
361 T = Remove_internal(V,T);
366 TreeTy* GetEmptyTree() const { return NULL; }
368 BumpPtrAllocator& getAllocator() { return Allocator; }
370 //===--------------------------------------------------===//
371 // A bunch of quick helper functions used for reasoning
372 // about the properties of trees and their children.
373 // These have succinct names so that the balancing code
374 // is as terse (and readable) as possible.
375 //===--------------------------------------------------===//
378 bool isEmpty(TreeTy* T) const { return !T; }
379 unsigned Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
380 TreeTy* Left(TreeTy* T) const { return T->getSafeLeft(); }
381 TreeTy* Right(TreeTy* T) const { return T->getRight(); }
382 value_type_ref Value(TreeTy* T) const { return T->Value; }
384 unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
385 unsigned hl = Height(L);
386 unsigned hr = Height(R);
387 return ( hl > hr ? hl : hr ) + 1;
390 //===--------------------------------------------------===//
391 // "CreateNode" is used to generate new tree roots that link
392 // to other trees. The functon may also simply move links
393 // in an existing root if that root is still marked mutable.
394 // This is necessary because otherwise our balancing code
395 // would leak memory as it would create nodes that are
396 // then discarded later before the finished tree is
397 // returned to the caller.
398 //===--------------------------------------------------===//
400 TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
402 TreeTy::Profile(ID,L,R,V);
405 if (TreeTy* T = Cache.FindNodeOrInsertPos(ID,InsertPos))
408 assert (InsertPos != NULL);
410 // Allocate the new tree node and insert it into the cache.
411 TreeTy* T = (TreeTy*) Allocator.Allocate<TreeTy>();
412 new (T) TreeTy(L,R,V,IncrementHeight(L,R));
413 Cache.InsertNode(T,InsertPos);
418 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
419 assert (!isEmpty(OldTree));
421 if (OldTree->isMutable()) {
423 OldTree->setRight(R);
424 OldTree->setHeight(IncrementHeight(L,R));
427 else return CreateNode(L, Value(OldTree), R);
430 /// Balance - Used by Add_internal and Remove_internal to
431 /// balance a newly created tree.
432 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
434 unsigned hl = Height(L);
435 unsigned hr = Height(R);
438 assert (!isEmpty(L) &&
439 "Left tree cannot be empty to have a height >= 2.");
441 TreeTy* LL = Left(L);
442 TreeTy* LR = Right(L);
444 if (Height(LL) >= Height(LR))
445 return CreateNode(LL, L, CreateNode(LR,V,R));
447 assert (!isEmpty(LR) &&
448 "LR cannot be empty because it has a height >= 1.");
450 TreeTy* LRL = Left(LR);
451 TreeTy* LRR = Right(LR);
453 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
455 else if (hr > hl + 2) {
456 assert (!isEmpty(R) &&
457 "Right tree cannot be empty to have a height >= 2.");
459 TreeTy* RL = Left(R);
460 TreeTy* RR = Right(R);
462 if (Height(RR) >= Height(RL))
463 return CreateNode(CreateNode(L,V,RL), R, RR);
465 assert (!isEmpty(RL) &&
466 "RL cannot be empty because it has a height >= 1.");
468 TreeTy* RLL = Left(RL);
469 TreeTy* RLR = Right(RL);
471 return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
474 return CreateNode(L,V,R);
477 /// Add_internal - Creates a new tree that includes the specified
478 /// data and the data from the original tree. If the original tree
479 /// already contained the data item, the original tree is returned.
480 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
482 return CreateNode(T, V, T);
484 assert (!T->isMutable());
486 key_type_ref K = ImutInfo::KeyOfValue(V);
487 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
489 if (ImutInfo::isEqual(K,KCurrent))
490 return CreateNode(Left(T), V, Right(T));
491 else if (ImutInfo::isLess(K,KCurrent))
492 return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
494 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
497 /// Remove_interal - Creates a new tree that includes all the data
498 /// from the original tree except the specified data. If the
499 /// specified data did not exist in the original tree, the original
500 /// tree is returned.
501 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
505 assert (!T->isMutable());
507 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
509 if (ImutInfo::isEqual(K,KCurrent))
510 return CombineLeftRightTrees(Left(T),Right(T));
511 else if (ImutInfo::isLess(K,KCurrent))
512 return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
514 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
517 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
518 if (isEmpty(L)) return R;
519 if (isEmpty(R)) return L;
522 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
523 return Balance(L,Value(OldNode),NewRight);
526 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
527 assert (!isEmpty(T));
529 if (isEmpty(Left(T))) {
534 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
537 /// MarkImmutable - Clears the mutable bits of a root and all of its
539 void MarkImmutable(TreeTy* T) {
540 if (!T || !T->isMutable())
544 MarkImmutable(Left(T));
545 MarkImmutable(Right(T));
550 //===----------------------------------------------------------------------===//
551 // Immutable AVL-Tree Iterators.
552 //===----------------------------------------------------------------------===//
554 template <typename ImutInfo>
555 class ImutAVLTreeGenericIterator {
556 SmallVector<uintptr_t,20> stack;
558 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
561 typedef ImutAVLTree<ImutInfo> TreeTy;
562 typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
564 inline ImutAVLTreeGenericIterator() {}
565 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
566 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
569 TreeTy* operator*() const {
570 assert (!stack.empty());
571 return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
574 uintptr_t getVisitState() {
575 assert (!stack.empty());
576 return stack.back() & Flags;
580 bool AtEnd() const { return stack.empty(); }
582 bool AtBeginning() const {
583 return stack.size() == 1 && getVisitState() == VisitedNone;
586 void SkipToParent() {
587 assert (!stack.empty());
593 switch (getVisitState()) {
595 stack.back() |= VisitedLeft;
598 stack.back() |= VisitedRight;
601 assert (false && "Unreachable.");
605 inline bool operator==(const _Self& x) const {
606 if (stack.size() != x.stack.size())
609 for (unsigned i = 0 ; i < stack.size(); i++)
610 if (stack[i] != x.stack[i])
616 inline bool operator!=(const _Self& x) const { return !operator==(x); }
618 _Self& operator++() {
619 assert (!stack.empty());
621 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
624 switch (getVisitState()) {
626 if (TreeTy* L = Current->getLeft())
627 stack.push_back(reinterpret_cast<uintptr_t>(L));
629 stack.back() |= VisitedLeft;
634 if (TreeTy* R = Current->getRight())
635 stack.push_back(reinterpret_cast<uintptr_t>(R));
637 stack.back() |= VisitedRight;
646 assert (false && "Unreachable.");
652 _Self& operator--() {
653 assert (!stack.empty());
655 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
658 switch (getVisitState()) {
664 stack.back() &= ~Flags; // Set state to "VisitedNone."
666 if (TreeTy* L = Current->getLeft())
667 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
672 stack.back() &= ~Flags;
673 stack.back() |= VisitedLeft;
675 if (TreeTy* R = Current->getRight())
676 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
681 assert (false && "Unreachable.");
688 template <typename ImutInfo>
689 class ImutAVLTreeInOrderIterator {
690 typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
691 InternalIteratorTy InternalItr;
694 typedef ImutAVLTree<ImutInfo> TreeTy;
695 typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
697 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
698 if (Root) operator++(); // Advance to first element.
701 ImutAVLTreeInOrderIterator() : InternalItr() {}
703 inline bool operator==(const _Self& x) const {
704 return InternalItr == x.InternalItr;
707 inline bool operator!=(const _Self& x) const { return !operator==(x); }
709 inline TreeTy* operator*() const { return *InternalItr; }
710 inline TreeTy* operator->() const { return *InternalItr; }
712 inline _Self& operator++() {
714 while (!InternalItr.AtEnd() &&
715 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
720 inline _Self& operator--() {
722 while (!InternalItr.AtBeginning() &&
723 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
728 inline void SkipSubTree() {
729 InternalItr.SkipToParent();
731 while (!InternalItr.AtEnd() &&
732 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
737 //===----------------------------------------------------------------------===//
738 // Trait classes for Profile information.
739 //===----------------------------------------------------------------------===//
741 /// Generic profile template. The default behavior is to invoke the
742 /// profile method of an object. Specializations for primitive integers
743 /// and generic handling of pointers is done below.
744 template <typename T>
745 struct ImutProfileInfo {
746 typedef const T value_type;
747 typedef const T& value_type_ref;
749 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
750 FoldingSetTrait<T>::Profile(X,ID);
754 /// Profile traits for integers.
755 template <typename T>
756 struct ImutProfileInteger {
757 typedef const T value_type;
758 typedef const T& value_type_ref;
760 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
765 #define PROFILE_INTEGER_INFO(X)\
766 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
768 PROFILE_INTEGER_INFO(char)
769 PROFILE_INTEGER_INFO(unsigned char)
770 PROFILE_INTEGER_INFO(short)
771 PROFILE_INTEGER_INFO(unsigned short)
772 PROFILE_INTEGER_INFO(unsigned)
773 PROFILE_INTEGER_INFO(signed)
774 PROFILE_INTEGER_INFO(long)
775 PROFILE_INTEGER_INFO(unsigned long)
776 PROFILE_INTEGER_INFO(long long)
777 PROFILE_INTEGER_INFO(unsigned long long)
779 #undef PROFILE_INTEGER_INFO
781 /// Generic profile trait for pointer types. We treat pointers as
782 /// references to unique objects.
783 template <typename T>
784 struct ImutProfileInfo<T*> {
785 typedef const T* value_type;
786 typedef value_type value_type_ref;
788 static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
793 //===----------------------------------------------------------------------===//
794 // Trait classes that contain element comparison operators and type
795 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
796 // inherit from the profile traits (ImutProfileInfo) to include operations
797 // for element profiling.
798 //===----------------------------------------------------------------------===//
801 /// ImutContainerInfo - Generic definition of comparison operations for
802 /// elements of immutable containers that defaults to using
803 /// std::equal_to<> and std::less<> to perform comparison of elements.
804 template <typename T>
805 struct ImutContainerInfo : public ImutProfileInfo<T> {
806 typedef typename ImutProfileInfo<T>::value_type value_type;
807 typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
808 typedef value_type key_type;
809 typedef value_type_ref key_type_ref;
810 typedef bool data_type;
811 typedef bool data_type_ref;
813 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
814 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
816 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
817 return std::equal_to<key_type>()(LHS,RHS);
820 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
821 return std::less<key_type>()(LHS,RHS);
824 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
827 /// ImutContainerInfo - Specialization for pointer values to treat pointers
828 /// as references to unique objects. Pointers are thus compared by
830 template <typename T>
831 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
832 typedef typename ImutProfileInfo<T*>::value_type value_type;
833 typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
834 typedef value_type key_type;
835 typedef value_type_ref key_type_ref;
836 typedef bool data_type;
837 typedef bool data_type_ref;
839 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
840 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
842 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
846 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
850 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
853 //===----------------------------------------------------------------------===//
855 //===----------------------------------------------------------------------===//
857 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
860 typedef typename ValInfo::value_type value_type;
861 typedef typename ValInfo::value_type_ref value_type_ref;
864 typedef ImutAVLTree<ValInfo> TreeTy;
867 ImmutableSet(TreeTy* R) : Root(R) {}
872 typename TreeTy::Factory F;
877 /// GetEmptySet - Returns an immutable set that contains no elements.
878 ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
880 /// Add - Creates a new immutable set that contains all of the values
881 /// of the original set with the addition of the specified value. If
882 /// the original set already included the value, then the original set is
883 /// returned and no memory is allocated. The time and space complexity
884 /// of this operation is logarithmic in the size of the original set.
885 /// The memory allocated to represent the set is released when the
886 /// factory object that created the set is destroyed.
887 ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
888 return ImmutableSet(F.Add(Old.Root,V));
891 /// Remove - Creates a new immutable set that contains all of the values
892 /// of the original set with the exception of the specified value. If
893 /// the original set did not contain the value, the original set is
894 /// returned and no memory is allocated. The time and space complexity
895 /// of this operation is logarithmic in the size of the original set.
896 /// The memory allocated to represent the set is released when the
897 /// factory object that created the set is destroyed.
898 ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
899 return ImmutableSet(F.Remove(Old.Root,V));
902 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
905 Factory(const Factory& RHS) {};
906 void operator=(const Factory& RHS) {};
909 friend class Factory;
911 /// contains - Returns true if the set contains the specified value.
912 bool contains(const value_type_ref V) const {
913 return Root ? Root->contains(V) : false;
916 bool operator==(ImmutableSet RHS) const {
917 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
920 bool operator!=(ImmutableSet RHS) const {
921 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
924 /// isEmpty - Return true if the set contains no elements.
925 bool isEmpty() const { return !Root; }
927 template <typename Callback>
928 void foreach(Callback& C) { if (Root) Root->foreach(C); }
930 template <typename Callback>
931 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
933 //===--------------------------------------------------===//
935 //===--------------------------------------------------===//
938 typename TreeTy::iterator itr;
941 iterator(TreeTy* t) : itr(t) {}
942 friend class ImmutableSet<ValT,ValInfo>;
944 inline value_type_ref operator*() const { return itr->getValue(); }
945 inline iterator& operator++() { ++itr; return *this; }
946 inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
947 inline iterator& operator--() { --itr; return *this; }
948 inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
949 inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
950 inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
953 iterator begin() const { return iterator(Root); }
954 iterator end() const { return iterator(); }
956 //===--------------------------------------------------===//
958 //===--------------------------------------------------===//
960 void verify() const { if (Root) Root->verify(); }
961 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
964 } // end namespace llvm