15572614b0ee6af8d90abac09a6a69716c0721a3
[oota-llvm.git] / include / llvm / ADT / Tree.h
1 //===- Support/Tree.h - Generic n-way tree structure ------------*- C++ -*-===//
2 //
3 // This class defines a generic N way tree node structure.  The tree structure
4 // is immutable after creation, but the payload contained within it is not.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #ifndef SUPPORT_TREE_H
9 #define SUPPORT_TREE_H
10
11 #include <vector>
12
13 template<class ConcreteTreeNode, class Payload>
14 class Tree {
15   std::vector<ConcreteTreeNode*> Children;        // This nodes children, if any
16   ConcreteTreeNode              *Parent;          // Parent of this node...
17   Payload                        Data;            // Data held in this node...
18
19 protected:
20   void setChildren(const std::vector<ConcreteTreeNode*> &children) {
21     Children = children;
22   }
23 public:
24   inline Tree(ConcreteTreeNode *parent) : Parent(parent) {}
25   inline Tree(const std::vector<ConcreteTreeNode*> &children,
26               ConcreteTreeNode *par) : Children(children), Parent(par) {}
27
28   inline Tree(const std::vector<ConcreteTreeNode*> &children,
29               ConcreteTreeNode *par, const Payload &data) 
30     : Children(children), Parent(parent), Data(data) {}
31
32   // Tree dtor - Free all children
33   inline ~Tree() {
34     for (unsigned i = Children.size(); i > 0; --i)
35       delete Children[i-1];
36   }
37
38   // Tree manipulation/walking routines...
39   inline ConcreteTreeNode *getParent() const { return Parent; }
40   inline unsigned getNumChildren() const { return Children.size(); }
41   inline ConcreteTreeNode *getChild(unsigned i) const {
42     assert(i < Children.size() && "Tree::getChild with index out of range!");
43     return Children[i];
44   }
45
46   // Payload access...
47   inline Payload &getTreeData() { return Data; }
48   inline const Payload &getTreeData() const { return Data; }
49 };
50
51
52 #endif