clang API Documentation
00001 //===--- DeltaTree.cpp - B-Tree for Rewrite Delta tracking ----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the DeltaTree and related classes. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Rewrite/Core/DeltaTree.h" 00015 #include "clang/Basic/LLVM.h" 00016 #include <cstdio> 00017 #include <cstring> 00018 using namespace clang; 00019 00020 /// The DeltaTree class is a multiway search tree (BTree) structure with some 00021 /// fancy features. B-Trees are generally more memory and cache efficient 00022 /// than binary trees, because they store multiple keys/values in each node. 00023 /// 00024 /// DeltaTree implements a key/value mapping from FileIndex to Delta, allowing 00025 /// fast lookup by FileIndex. However, an added (important) bonus is that it 00026 /// can also efficiently tell us the full accumulated delta for a specific 00027 /// file offset as well, without traversing the whole tree. 00028 /// 00029 /// The nodes of the tree are made up of instances of two classes: 00030 /// DeltaTreeNode and DeltaTreeInteriorNode. The later subclasses the 00031 /// former and adds children pointers. Each node knows the full delta of all 00032 /// entries (recursively) contained inside of it, which allows us to get the 00033 /// full delta implied by a whole subtree in constant time. 00034 00035 namespace { 00036 /// SourceDelta - As code in the original input buffer is added and deleted, 00037 /// SourceDelta records are used to keep track of how the input SourceLocation 00038 /// object is mapped into the output buffer. 00039 struct SourceDelta { 00040 unsigned FileLoc; 00041 int Delta; 00042 00043 static SourceDelta get(unsigned Loc, int D) { 00044 SourceDelta Delta; 00045 Delta.FileLoc = Loc; 00046 Delta.Delta = D; 00047 return Delta; 00048 } 00049 }; 00050 00051 /// DeltaTreeNode - The common part of all nodes. 00052 /// 00053 class DeltaTreeNode { 00054 public: 00055 struct InsertResult { 00056 DeltaTreeNode *LHS, *RHS; 00057 SourceDelta Split; 00058 }; 00059 00060 private: 00061 friend class DeltaTreeInteriorNode; 00062 00063 /// WidthFactor - This controls the number of K/V slots held in the BTree: 00064 /// how wide it is. Each level of the BTree is guaranteed to have at least 00065 /// WidthFactor-1 K/V pairs (except the root) and may have at most 00066 /// 2*WidthFactor-1 K/V pairs. 00067 enum { WidthFactor = 8 }; 00068 00069 /// Values - This tracks the SourceDelta's currently in this node. 00070 /// 00071 SourceDelta Values[2*WidthFactor-1]; 00072 00073 /// NumValuesUsed - This tracks the number of values this node currently 00074 /// holds. 00075 unsigned char NumValuesUsed; 00076 00077 /// IsLeaf - This is true if this is a leaf of the btree. If false, this is 00078 /// an interior node, and is actually an instance of DeltaTreeInteriorNode. 00079 bool IsLeaf; 00080 00081 /// FullDelta - This is the full delta of all the values in this node and 00082 /// all children nodes. 00083 int FullDelta; 00084 public: 00085 DeltaTreeNode(bool isLeaf = true) 00086 : NumValuesUsed(0), IsLeaf(isLeaf), FullDelta(0) {} 00087 00088 bool isLeaf() const { return IsLeaf; } 00089 int getFullDelta() const { return FullDelta; } 00090 bool isFull() const { return NumValuesUsed == 2*WidthFactor-1; } 00091 00092 unsigned getNumValuesUsed() const { return NumValuesUsed; } 00093 const SourceDelta &getValue(unsigned i) const { 00094 assert(i < NumValuesUsed && "Invalid value #"); 00095 return Values[i]; 00096 } 00097 SourceDelta &getValue(unsigned i) { 00098 assert(i < NumValuesUsed && "Invalid value #"); 00099 return Values[i]; 00100 } 00101 00102 /// DoInsertion - Do an insertion of the specified FileIndex/Delta pair into 00103 /// this node. If insertion is easy, do it and return false. Otherwise, 00104 /// split the node, populate InsertRes with info about the split, and return 00105 /// true. 00106 bool DoInsertion(unsigned FileIndex, int Delta, InsertResult *InsertRes); 00107 00108 void DoSplit(InsertResult &InsertRes); 00109 00110 00111 /// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a 00112 /// local walk over our contained deltas. 00113 void RecomputeFullDeltaLocally(); 00114 00115 void Destroy(); 00116 }; 00117 } // end anonymous namespace 00118 00119 namespace { 00120 /// DeltaTreeInteriorNode - When isLeaf = false, a node has child pointers. 00121 /// This class tracks them. 00122 class DeltaTreeInteriorNode : public DeltaTreeNode { 00123 DeltaTreeNode *Children[2*WidthFactor]; 00124 ~DeltaTreeInteriorNode() { 00125 for (unsigned i = 0, e = NumValuesUsed+1; i != e; ++i) 00126 Children[i]->Destroy(); 00127 } 00128 friend class DeltaTreeNode; 00129 public: 00130 DeltaTreeInteriorNode() : DeltaTreeNode(false /*nonleaf*/) {} 00131 00132 DeltaTreeInteriorNode(const InsertResult &IR) 00133 : DeltaTreeNode(false /*nonleaf*/) { 00134 Children[0] = IR.LHS; 00135 Children[1] = IR.RHS; 00136 Values[0] = IR.Split; 00137 FullDelta = IR.LHS->getFullDelta()+IR.RHS->getFullDelta()+IR.Split.Delta; 00138 NumValuesUsed = 1; 00139 } 00140 00141 const DeltaTreeNode *getChild(unsigned i) const { 00142 assert(i < getNumValuesUsed()+1 && "Invalid child"); 00143 return Children[i]; 00144 } 00145 DeltaTreeNode *getChild(unsigned i) { 00146 assert(i < getNumValuesUsed()+1 && "Invalid child"); 00147 return Children[i]; 00148 } 00149 00150 static inline bool classof(const DeltaTreeNode *N) { return !N->isLeaf(); } 00151 }; 00152 } 00153 00154 00155 /// Destroy - A 'virtual' destructor. 00156 void DeltaTreeNode::Destroy() { 00157 if (isLeaf()) 00158 delete this; 00159 else 00160 delete cast<DeltaTreeInteriorNode>(this); 00161 } 00162 00163 /// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a 00164 /// local walk over our contained deltas. 00165 void DeltaTreeNode::RecomputeFullDeltaLocally() { 00166 int NewFullDelta = 0; 00167 for (unsigned i = 0, e = getNumValuesUsed(); i != e; ++i) 00168 NewFullDelta += Values[i].Delta; 00169 if (DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(this)) 00170 for (unsigned i = 0, e = getNumValuesUsed()+1; i != e; ++i) 00171 NewFullDelta += IN->getChild(i)->getFullDelta(); 00172 FullDelta = NewFullDelta; 00173 } 00174 00175 /// DoInsertion - Do an insertion of the specified FileIndex/Delta pair into 00176 /// this node. If insertion is easy, do it and return false. Otherwise, 00177 /// split the node, populate InsertRes with info about the split, and return 00178 /// true. 00179 bool DeltaTreeNode::DoInsertion(unsigned FileIndex, int Delta, 00180 InsertResult *InsertRes) { 00181 // Maintain full delta for this node. 00182 FullDelta += Delta; 00183 00184 // Find the insertion point, the first delta whose index is >= FileIndex. 00185 unsigned i = 0, e = getNumValuesUsed(); 00186 while (i != e && FileIndex > getValue(i).FileLoc) 00187 ++i; 00188 00189 // If we found an a record for exactly this file index, just merge this 00190 // value into the pre-existing record and finish early. 00191 if (i != e && getValue(i).FileLoc == FileIndex) { 00192 // NOTE: Delta could drop to zero here. This means that the delta entry is 00193 // useless and could be removed. Supporting erases is more complex than 00194 // leaving an entry with Delta=0, so we just leave an entry with Delta=0 in 00195 // the tree. 00196 Values[i].Delta += Delta; 00197 return false; 00198 } 00199 00200 // Otherwise, we found an insertion point, and we know that the value at the 00201 // specified index is > FileIndex. Handle the leaf case first. 00202 if (isLeaf()) { 00203 if (!isFull()) { 00204 // For an insertion into a non-full leaf node, just insert the value in 00205 // its sorted position. This requires moving later values over. 00206 if (i != e) 00207 memmove(&Values[i+1], &Values[i], sizeof(Values[0])*(e-i)); 00208 Values[i] = SourceDelta::get(FileIndex, Delta); 00209 ++NumValuesUsed; 00210 return false; 00211 } 00212 00213 // Otherwise, if this is leaf is full, split the node at its median, insert 00214 // the value into one of the children, and return the result. 00215 assert(InsertRes && "No result location specified"); 00216 DoSplit(*InsertRes); 00217 00218 if (InsertRes->Split.FileLoc > FileIndex) 00219 InsertRes->LHS->DoInsertion(FileIndex, Delta, nullptr /*can't fail*/); 00220 else 00221 InsertRes->RHS->DoInsertion(FileIndex, Delta, nullptr /*can't fail*/); 00222 return true; 00223 } 00224 00225 // Otherwise, this is an interior node. Send the request down the tree. 00226 DeltaTreeInteriorNode *IN = cast<DeltaTreeInteriorNode>(this); 00227 if (!IN->Children[i]->DoInsertion(FileIndex, Delta, InsertRes)) 00228 return false; // If there was space in the child, just return. 00229 00230 // Okay, this split the subtree, producing a new value and two children to 00231 // insert here. If this node is non-full, we can just insert it directly. 00232 if (!isFull()) { 00233 // Now that we have two nodes and a new element, insert the perclated value 00234 // into ourself by moving all the later values/children down, then inserting 00235 // the new one. 00236 if (i != e) 00237 memmove(&IN->Children[i+2], &IN->Children[i+1], 00238 (e-i)*sizeof(IN->Children[0])); 00239 IN->Children[i] = InsertRes->LHS; 00240 IN->Children[i+1] = InsertRes->RHS; 00241 00242 if (e != i) 00243 memmove(&Values[i+1], &Values[i], (e-i)*sizeof(Values[0])); 00244 Values[i] = InsertRes->Split; 00245 ++NumValuesUsed; 00246 return false; 00247 } 00248 00249 // Finally, if this interior node was full and a node is percolated up, split 00250 // ourself and return that up the chain. Start by saving all our info to 00251 // avoid having the split clobber it. 00252 IN->Children[i] = InsertRes->LHS; 00253 DeltaTreeNode *SubRHS = InsertRes->RHS; 00254 SourceDelta SubSplit = InsertRes->Split; 00255 00256 // Do the split. 00257 DoSplit(*InsertRes); 00258 00259 // Figure out where to insert SubRHS/NewSplit. 00260 DeltaTreeInteriorNode *InsertSide; 00261 if (SubSplit.FileLoc < InsertRes->Split.FileLoc) 00262 InsertSide = cast<DeltaTreeInteriorNode>(InsertRes->LHS); 00263 else 00264 InsertSide = cast<DeltaTreeInteriorNode>(InsertRes->RHS); 00265 00266 // We now have a non-empty interior node 'InsertSide' to insert 00267 // SubRHS/SubSplit into. Find out where to insert SubSplit. 00268 00269 // Find the insertion point, the first delta whose index is >SubSplit.FileLoc. 00270 i = 0; e = InsertSide->getNumValuesUsed(); 00271 while (i != e && SubSplit.FileLoc > InsertSide->getValue(i).FileLoc) 00272 ++i; 00273 00274 // Now we know that i is the place to insert the split value into. Insert it 00275 // and the child right after it. 00276 if (i != e) 00277 memmove(&InsertSide->Children[i+2], &InsertSide->Children[i+1], 00278 (e-i)*sizeof(IN->Children[0])); 00279 InsertSide->Children[i+1] = SubRHS; 00280 00281 if (e != i) 00282 memmove(&InsertSide->Values[i+1], &InsertSide->Values[i], 00283 (e-i)*sizeof(Values[0])); 00284 InsertSide->Values[i] = SubSplit; 00285 ++InsertSide->NumValuesUsed; 00286 InsertSide->FullDelta += SubSplit.Delta + SubRHS->getFullDelta(); 00287 return true; 00288 } 00289 00290 /// DoSplit - Split the currently full node (which has 2*WidthFactor-1 values) 00291 /// into two subtrees each with "WidthFactor-1" values and a pivot value. 00292 /// Return the pieces in InsertRes. 00293 void DeltaTreeNode::DoSplit(InsertResult &InsertRes) { 00294 assert(isFull() && "Why split a non-full node?"); 00295 00296 // Since this node is full, it contains 2*WidthFactor-1 values. We move 00297 // the first 'WidthFactor-1' values to the LHS child (which we leave in this 00298 // node), propagate one value up, and move the last 'WidthFactor-1' values 00299 // into the RHS child. 00300 00301 // Create the new child node. 00302 DeltaTreeNode *NewNode; 00303 if (DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(this)) { 00304 // If this is an interior node, also move over 'WidthFactor' children 00305 // into the new node. 00306 DeltaTreeInteriorNode *New = new DeltaTreeInteriorNode(); 00307 memcpy(&New->Children[0], &IN->Children[WidthFactor], 00308 WidthFactor*sizeof(IN->Children[0])); 00309 NewNode = New; 00310 } else { 00311 // Just create the new leaf node. 00312 NewNode = new DeltaTreeNode(); 00313 } 00314 00315 // Move over the last 'WidthFactor-1' values from here to NewNode. 00316 memcpy(&NewNode->Values[0], &Values[WidthFactor], 00317 (WidthFactor-1)*sizeof(Values[0])); 00318 00319 // Decrease the number of values in the two nodes. 00320 NewNode->NumValuesUsed = NumValuesUsed = WidthFactor-1; 00321 00322 // Recompute the two nodes' full delta. 00323 NewNode->RecomputeFullDeltaLocally(); 00324 RecomputeFullDeltaLocally(); 00325 00326 InsertRes.LHS = this; 00327 InsertRes.RHS = NewNode; 00328 InsertRes.Split = Values[WidthFactor-1]; 00329 } 00330 00331 00332 00333 //===----------------------------------------------------------------------===// 00334 // DeltaTree Implementation 00335 //===----------------------------------------------------------------------===// 00336 00337 //#define VERIFY_TREE 00338 00339 #ifdef VERIFY_TREE 00340 /// VerifyTree - Walk the btree performing assertions on various properties to 00341 /// verify consistency. This is useful for debugging new changes to the tree. 00342 static void VerifyTree(const DeltaTreeNode *N) { 00343 const DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(N); 00344 if (IN == 0) { 00345 // Verify leaves, just ensure that FullDelta matches up and the elements 00346 // are in proper order. 00347 int FullDelta = 0; 00348 for (unsigned i = 0, e = N->getNumValuesUsed(); i != e; ++i) { 00349 if (i) 00350 assert(N->getValue(i-1).FileLoc < N->getValue(i).FileLoc); 00351 FullDelta += N->getValue(i).Delta; 00352 } 00353 assert(FullDelta == N->getFullDelta()); 00354 return; 00355 } 00356 00357 // Verify interior nodes: Ensure that FullDelta matches up and the 00358 // elements are in proper order and the children are in proper order. 00359 int FullDelta = 0; 00360 for (unsigned i = 0, e = IN->getNumValuesUsed(); i != e; ++i) { 00361 const SourceDelta &IVal = N->getValue(i); 00362 const DeltaTreeNode *IChild = IN->getChild(i); 00363 if (i) 00364 assert(IN->getValue(i-1).FileLoc < IVal.FileLoc); 00365 FullDelta += IVal.Delta; 00366 FullDelta += IChild->getFullDelta(); 00367 00368 // The largest value in child #i should be smaller than FileLoc. 00369 assert(IChild->getValue(IChild->getNumValuesUsed()-1).FileLoc < 00370 IVal.FileLoc); 00371 00372 // The smallest value in child #i+1 should be larger than FileLoc. 00373 assert(IN->getChild(i+1)->getValue(0).FileLoc > IVal.FileLoc); 00374 VerifyTree(IChild); 00375 } 00376 00377 FullDelta += IN->getChild(IN->getNumValuesUsed())->getFullDelta(); 00378 00379 assert(FullDelta == N->getFullDelta()); 00380 } 00381 #endif // VERIFY_TREE 00382 00383 static DeltaTreeNode *getRoot(void *Root) { 00384 return (DeltaTreeNode*)Root; 00385 } 00386 00387 DeltaTree::DeltaTree() { 00388 Root = new DeltaTreeNode(); 00389 } 00390 DeltaTree::DeltaTree(const DeltaTree &RHS) { 00391 // Currently we only support copying when the RHS is empty. 00392 assert(getRoot(RHS.Root)->getNumValuesUsed() == 0 && 00393 "Can only copy empty tree"); 00394 Root = new DeltaTreeNode(); 00395 } 00396 00397 DeltaTree::~DeltaTree() { 00398 getRoot(Root)->Destroy(); 00399 } 00400 00401 /// getDeltaAt - Return the accumulated delta at the specified file offset. 00402 /// This includes all insertions or delections that occurred *before* the 00403 /// specified file index. 00404 int DeltaTree::getDeltaAt(unsigned FileIndex) const { 00405 const DeltaTreeNode *Node = getRoot(Root); 00406 00407 int Result = 0; 00408 00409 // Walk down the tree. 00410 while (1) { 00411 // For all nodes, include any local deltas before the specified file 00412 // index by summing them up directly. Keep track of how many were 00413 // included. 00414 unsigned NumValsGreater = 0; 00415 for (unsigned e = Node->getNumValuesUsed(); NumValsGreater != e; 00416 ++NumValsGreater) { 00417 const SourceDelta &Val = Node->getValue(NumValsGreater); 00418 00419 if (Val.FileLoc >= FileIndex) 00420 break; 00421 Result += Val.Delta; 00422 } 00423 00424 // If we have an interior node, include information about children and 00425 // recurse. Otherwise, if we have a leaf, we're done. 00426 const DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(Node); 00427 if (!IN) return Result; 00428 00429 // Include any children to the left of the values we skipped, all of 00430 // their deltas should be included as well. 00431 for (unsigned i = 0; i != NumValsGreater; ++i) 00432 Result += IN->getChild(i)->getFullDelta(); 00433 00434 // If we found exactly the value we were looking for, break off the 00435 // search early. There is no need to search the RHS of the value for 00436 // partial results. 00437 if (NumValsGreater != Node->getNumValuesUsed() && 00438 Node->getValue(NumValsGreater).FileLoc == FileIndex) 00439 return Result+IN->getChild(NumValsGreater)->getFullDelta(); 00440 00441 // Otherwise, traverse down the tree. The selected subtree may be 00442 // partially included in the range. 00443 Node = IN->getChild(NumValsGreater); 00444 } 00445 // NOT REACHED. 00446 } 00447 00448 /// AddDelta - When a change is made that shifts around the text buffer, 00449 /// this method is used to record that info. It inserts a delta of 'Delta' 00450 /// into the current DeltaTree at offset FileIndex. 00451 void DeltaTree::AddDelta(unsigned FileIndex, int Delta) { 00452 assert(Delta && "Adding a noop?"); 00453 DeltaTreeNode *MyRoot = getRoot(Root); 00454 00455 DeltaTreeNode::InsertResult InsertRes; 00456 if (MyRoot->DoInsertion(FileIndex, Delta, &InsertRes)) { 00457 Root = MyRoot = new DeltaTreeInteriorNode(InsertRes); 00458 } 00459 00460 #ifdef VERIFY_TREE 00461 VerifyTree(MyRoot); 00462 #endif 00463 } 00464