1 //===- ASTDiff.cpp - AST differencing implementation-----------*- C++ -*- -===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains definitons for the AST differencing interface. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Tooling/ASTDiff/ASTDiff.h" 14 #include "clang/AST/ParentMapContext.h" 15 #include "clang/AST/RecursiveASTVisitor.h" 16 #include "clang/Basic/SourceManager.h" 17 #include "clang/Lex/Lexer.h" 18 #include "llvm/ADT/PriorityQueue.h" 19 #include "llvm/Support/ConvertUTF.h" 20 21 #include <limits> 22 #include <memory> 23 #include <unordered_set> 24 25 using namespace llvm; 26 using namespace clang; 27 28 namespace clang { 29 namespace diff { 30 31 namespace { 32 /// Maps nodes of the left tree to ones on the right, and vice versa. 33 class Mapping { 34 public: 35 Mapping() = default; 36 Mapping(Mapping &&Other) = default; 37 Mapping &operator=(Mapping &&Other) = default; 38 39 Mapping(size_t Size) { 40 SrcToDst = std::make_unique<NodeId[]>(Size); 41 DstToSrc = std::make_unique<NodeId[]>(Size); 42 } 43 44 void link(NodeId Src, NodeId Dst) { 45 SrcToDst[Src] = Dst, DstToSrc[Dst] = Src; 46 } 47 48 NodeId getDst(NodeId Src) const { return SrcToDst[Src]; } 49 NodeId getSrc(NodeId Dst) const { return DstToSrc[Dst]; } 50 bool hasSrc(NodeId Src) const { return getDst(Src).isValid(); } 51 bool hasDst(NodeId Dst) const { return getSrc(Dst).isValid(); } 52 53 private: 54 std::unique_ptr<NodeId[]> SrcToDst, DstToSrc; 55 }; 56 } // end anonymous namespace 57 58 class ASTDiff::Impl { 59 public: 60 SyntaxTree::Impl &T1, &T2; 61 Mapping TheMapping; 62 63 Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2, 64 const ComparisonOptions &Options); 65 66 /// Matches nodes one-by-one based on their similarity. 67 void computeMapping(); 68 69 // Compute Change for each node based on similarity. 70 void computeChangeKinds(Mapping &M); 71 72 NodeId getMapped(const std::unique_ptr<SyntaxTree::Impl> &Tree, 73 NodeId Id) const { 74 if (&*Tree == &T1) 75 return TheMapping.getDst(Id); 76 assert(&*Tree == &T2 && "Invalid tree."); 77 return TheMapping.getSrc(Id); 78 } 79 80 private: 81 // Returns true if the two subtrees are identical. 82 bool identical(NodeId Id1, NodeId Id2) const; 83 84 // Returns false if the nodes must not be mached. 85 bool isMatchingPossible(NodeId Id1, NodeId Id2) const; 86 87 // Returns true if the nodes' parents are matched. 88 bool haveSameParents(const Mapping &M, NodeId Id1, NodeId Id2) const; 89 90 // Uses an optimal albeit slow algorithm to compute a mapping between two 91 // subtrees, but only if both have fewer nodes than MaxSize. 92 void addOptimalMapping(Mapping &M, NodeId Id1, NodeId Id2) const; 93 94 // Computes the ratio of common descendants between the two nodes. 95 // Descendants are only considered to be equal when they are mapped in M. 96 double getJaccardSimilarity(const Mapping &M, NodeId Id1, NodeId Id2) const; 97 98 // Returns the node that has the highest degree of similarity. 99 NodeId findCandidate(const Mapping &M, NodeId Id1) const; 100 101 // Returns a mapping of identical subtrees. 102 Mapping matchTopDown() const; 103 104 // Tries to match any yet unmapped nodes, in a bottom-up fashion. 105 void matchBottomUp(Mapping &M) const; 106 107 const ComparisonOptions &Options; 108 109 friend class ZhangShashaMatcher; 110 }; 111 112 /// Represents the AST of a TranslationUnit. 113 class SyntaxTree::Impl { 114 public: 115 Impl(SyntaxTree *Parent, ASTContext &AST); 116 /// Constructs a tree from an AST node. 117 Impl(SyntaxTree *Parent, Decl *N, ASTContext &AST); 118 Impl(SyntaxTree *Parent, Stmt *N, ASTContext &AST); 119 template <class T> 120 Impl(SyntaxTree *Parent, 121 std::enable_if_t<std::is_base_of<Stmt, T>::value, T> *Node, 122 ASTContext &AST) 123 : Impl(Parent, dyn_cast<Stmt>(Node), AST) {} 124 template <class T> 125 Impl(SyntaxTree *Parent, 126 std::enable_if_t<std::is_base_of<Decl, T>::value, T> *Node, 127 ASTContext &AST) 128 : Impl(Parent, dyn_cast<Decl>(Node), AST) {} 129 130 SyntaxTree *Parent; 131 ASTContext &AST; 132 PrintingPolicy TypePP; 133 /// Nodes in preorder. 134 std::vector<Node> Nodes; 135 std::vector<NodeId> Leaves; 136 // Maps preorder indices to postorder ones. 137 std::vector<int> PostorderIds; 138 std::vector<NodeId> NodesBfs; 139 140 int getSize() const { return Nodes.size(); } 141 NodeId getRootId() const { return 0; } 142 PreorderIterator begin() const { return getRootId(); } 143 PreorderIterator end() const { return getSize(); } 144 145 const Node &getNode(NodeId Id) const { return Nodes[Id]; } 146 Node &getMutableNode(NodeId Id) { return Nodes[Id]; } 147 bool isValidNodeId(NodeId Id) const { return Id >= 0 && Id < getSize(); } 148 void addNode(Node &N) { Nodes.push_back(N); } 149 int getNumberOfDescendants(NodeId Id) const; 150 bool isInSubtree(NodeId Id, NodeId SubtreeRoot) const; 151 int findPositionInParent(NodeId Id, bool Shifted = false) const; 152 153 std::string getRelativeName(const NamedDecl *ND, 154 const DeclContext *Context) const; 155 std::string getRelativeName(const NamedDecl *ND) const; 156 157 std::string getNodeValue(NodeId Id) const; 158 std::string getNodeValue(const Node &Node) const; 159 std::string getDeclValue(const Decl *D) const; 160 std::string getStmtValue(const Stmt *S) const; 161 162 private: 163 void initTree(); 164 void setLeftMostDescendants(); 165 }; 166 167 static bool isSpecializedNodeExcluded(const Decl *D) { return D->isImplicit(); } 168 static bool isSpecializedNodeExcluded(const Stmt *S) { return false; } 169 static bool isSpecializedNodeExcluded(CXXCtorInitializer *I) { 170 return !I->isWritten(); 171 } 172 173 template <class T> 174 static bool isNodeExcluded(const SourceManager &SrcMgr, T *N) { 175 if (!N) 176 return true; 177 SourceLocation SLoc = N->getSourceRange().getBegin(); 178 if (SLoc.isValid()) { 179 // Ignore everything from other files. 180 if (!SrcMgr.isInMainFile(SLoc)) 181 return true; 182 // Ignore macros. 183 if (SLoc != SrcMgr.getSpellingLoc(SLoc)) 184 return true; 185 } 186 return isSpecializedNodeExcluded(N); 187 } 188 189 namespace { 190 // Sets Height, Parent and Children for each node. 191 struct PreorderVisitor : public RecursiveASTVisitor<PreorderVisitor> { 192 int Id = 0, Depth = 0; 193 NodeId Parent; 194 SyntaxTree::Impl &Tree; 195 196 PreorderVisitor(SyntaxTree::Impl &Tree) : Tree(Tree) {} 197 198 template <class T> std::tuple<NodeId, NodeId> PreTraverse(T *ASTNode) { 199 NodeId MyId = Id; 200 Tree.Nodes.emplace_back(); 201 Node &N = Tree.getMutableNode(MyId); 202 N.Parent = Parent; 203 N.Depth = Depth; 204 N.ASTNode = DynTypedNode::create(*ASTNode); 205 assert(!N.ASTNode.getNodeKind().isNone() && 206 "Expected nodes to have a valid kind."); 207 if (Parent.isValid()) { 208 Node &P = Tree.getMutableNode(Parent); 209 P.Children.push_back(MyId); 210 } 211 Parent = MyId; 212 ++Id; 213 ++Depth; 214 return std::make_tuple(MyId, Tree.getNode(MyId).Parent); 215 } 216 void PostTraverse(std::tuple<NodeId, NodeId> State) { 217 NodeId MyId, PreviousParent; 218 std::tie(MyId, PreviousParent) = State; 219 assert(MyId.isValid() && "Expecting to only traverse valid nodes."); 220 Parent = PreviousParent; 221 --Depth; 222 Node &N = Tree.getMutableNode(MyId); 223 N.RightMostDescendant = Id - 1; 224 assert(N.RightMostDescendant >= 0 && 225 N.RightMostDescendant < Tree.getSize() && 226 "Rightmost descendant must be a valid tree node."); 227 if (N.isLeaf()) 228 Tree.Leaves.push_back(MyId); 229 N.Height = 1; 230 for (NodeId Child : N.Children) 231 N.Height = std::max(N.Height, 1 + Tree.getNode(Child).Height); 232 } 233 bool TraverseDecl(Decl *D) { 234 if (isNodeExcluded(Tree.AST.getSourceManager(), D)) 235 return true; 236 auto SavedState = PreTraverse(D); 237 RecursiveASTVisitor<PreorderVisitor>::TraverseDecl(D); 238 PostTraverse(SavedState); 239 return true; 240 } 241 bool TraverseStmt(Stmt *S) { 242 if (auto *E = dyn_cast_or_null<Expr>(S)) 243 S = E->IgnoreImplicit(); 244 if (isNodeExcluded(Tree.AST.getSourceManager(), S)) 245 return true; 246 auto SavedState = PreTraverse(S); 247 RecursiveASTVisitor<PreorderVisitor>::TraverseStmt(S); 248 PostTraverse(SavedState); 249 return true; 250 } 251 bool TraverseType(QualType T) { return true; } 252 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { 253 if (isNodeExcluded(Tree.AST.getSourceManager(), Init)) 254 return true; 255 auto SavedState = PreTraverse(Init); 256 RecursiveASTVisitor<PreorderVisitor>::TraverseConstructorInitializer(Init); 257 PostTraverse(SavedState); 258 return true; 259 } 260 }; 261 } // end anonymous namespace 262 263 SyntaxTree::Impl::Impl(SyntaxTree *Parent, ASTContext &AST) 264 : Parent(Parent), AST(AST), TypePP(AST.getLangOpts()) { 265 TypePP.AnonymousTagLocations = false; 266 } 267 268 SyntaxTree::Impl::Impl(SyntaxTree *Parent, Decl *N, ASTContext &AST) 269 : Impl(Parent, AST) { 270 PreorderVisitor PreorderWalker(*this); 271 PreorderWalker.TraverseDecl(N); 272 initTree(); 273 } 274 275 SyntaxTree::Impl::Impl(SyntaxTree *Parent, Stmt *N, ASTContext &AST) 276 : Impl(Parent, AST) { 277 PreorderVisitor PreorderWalker(*this); 278 PreorderWalker.TraverseStmt(N); 279 initTree(); 280 } 281 282 static std::vector<NodeId> getSubtreePostorder(const SyntaxTree::Impl &Tree, 283 NodeId Root) { 284 std::vector<NodeId> Postorder; 285 std::function<void(NodeId)> Traverse = [&](NodeId Id) { 286 const Node &N = Tree.getNode(Id); 287 for (NodeId Child : N.Children) 288 Traverse(Child); 289 Postorder.push_back(Id); 290 }; 291 Traverse(Root); 292 return Postorder; 293 } 294 295 static std::vector<NodeId> getSubtreeBfs(const SyntaxTree::Impl &Tree, 296 NodeId Root) { 297 std::vector<NodeId> Ids; 298 size_t Expanded = 0; 299 Ids.push_back(Root); 300 while (Expanded < Ids.size()) 301 for (NodeId Child : Tree.getNode(Ids[Expanded++]).Children) 302 Ids.push_back(Child); 303 return Ids; 304 } 305 306 void SyntaxTree::Impl::initTree() { 307 setLeftMostDescendants(); 308 int PostorderId = 0; 309 PostorderIds.resize(getSize()); 310 std::function<void(NodeId)> PostorderTraverse = [&](NodeId Id) { 311 for (NodeId Child : getNode(Id).Children) 312 PostorderTraverse(Child); 313 PostorderIds[Id] = PostorderId; 314 ++PostorderId; 315 }; 316 PostorderTraverse(getRootId()); 317 NodesBfs = getSubtreeBfs(*this, getRootId()); 318 } 319 320 void SyntaxTree::Impl::setLeftMostDescendants() { 321 for (NodeId Leaf : Leaves) { 322 getMutableNode(Leaf).LeftMostDescendant = Leaf; 323 NodeId Parent, Cur = Leaf; 324 while ((Parent = getNode(Cur).Parent).isValid() && 325 getNode(Parent).Children[0] == Cur) { 326 Cur = Parent; 327 getMutableNode(Cur).LeftMostDescendant = Leaf; 328 } 329 } 330 } 331 332 int SyntaxTree::Impl::getNumberOfDescendants(NodeId Id) const { 333 return getNode(Id).RightMostDescendant - Id + 1; 334 } 335 336 bool SyntaxTree::Impl::isInSubtree(NodeId Id, NodeId SubtreeRoot) const { 337 return Id >= SubtreeRoot && Id <= getNode(SubtreeRoot).RightMostDescendant; 338 } 339 340 int SyntaxTree::Impl::findPositionInParent(NodeId Id, bool Shifted) const { 341 NodeId Parent = getNode(Id).Parent; 342 if (Parent.isInvalid()) 343 return 0; 344 const auto &Siblings = getNode(Parent).Children; 345 int Position = 0; 346 for (size_t I = 0, E = Siblings.size(); I < E; ++I) { 347 if (Shifted) 348 Position += getNode(Siblings[I]).Shift; 349 if (Siblings[I] == Id) { 350 Position += I; 351 return Position; 352 } 353 } 354 llvm_unreachable("Node not found in parent's children."); 355 } 356 357 // Returns the qualified name of ND. If it is subordinate to Context, 358 // then the prefix of the latter is removed from the returned value. 359 std::string 360 SyntaxTree::Impl::getRelativeName(const NamedDecl *ND, 361 const DeclContext *Context) const { 362 std::string Val = ND->getQualifiedNameAsString(); 363 std::string ContextPrefix; 364 if (!Context) 365 return Val; 366 if (auto *Namespace = dyn_cast<NamespaceDecl>(Context)) 367 ContextPrefix = Namespace->getQualifiedNameAsString(); 368 else if (auto *Record = dyn_cast<RecordDecl>(Context)) 369 ContextPrefix = Record->getQualifiedNameAsString(); 370 else if (AST.getLangOpts().CPlusPlus11) 371 if (auto *Tag = dyn_cast<TagDecl>(Context)) 372 ContextPrefix = Tag->getQualifiedNameAsString(); 373 // Strip the qualifier, if Val refers to something in the current scope. 374 // But leave one leading ':' in place, so that we know that this is a 375 // relative path. 376 if (!ContextPrefix.empty() && StringRef(Val).startswith(ContextPrefix)) 377 Val = Val.substr(ContextPrefix.size() + 1); 378 return Val; 379 } 380 381 std::string SyntaxTree::Impl::getRelativeName(const NamedDecl *ND) const { 382 return getRelativeName(ND, ND->getDeclContext()); 383 } 384 385 static const DeclContext *getEnclosingDeclContext(ASTContext &AST, 386 const Stmt *S) { 387 while (S) { 388 const auto &Parents = AST.getParents(*S); 389 if (Parents.empty()) 390 return nullptr; 391 const auto &P = Parents[0]; 392 if (const auto *D = P.get<Decl>()) 393 return D->getDeclContext(); 394 S = P.get<Stmt>(); 395 } 396 return nullptr; 397 } 398 399 static std::string getInitializerValue(const CXXCtorInitializer *Init, 400 const PrintingPolicy &TypePP) { 401 if (Init->isAnyMemberInitializer()) 402 return std::string(Init->getAnyMember()->getName()); 403 if (Init->isBaseInitializer()) 404 return QualType(Init->getBaseClass(), 0).getAsString(TypePP); 405 if (Init->isDelegatingInitializer()) 406 return Init->getTypeSourceInfo()->getType().getAsString(TypePP); 407 llvm_unreachable("Unknown initializer type"); 408 } 409 410 std::string SyntaxTree::Impl::getNodeValue(NodeId Id) const { 411 return getNodeValue(getNode(Id)); 412 } 413 414 std::string SyntaxTree::Impl::getNodeValue(const Node &N) const { 415 const DynTypedNode &DTN = N.ASTNode; 416 if (auto *S = DTN.get<Stmt>()) 417 return getStmtValue(S); 418 if (auto *D = DTN.get<Decl>()) 419 return getDeclValue(D); 420 if (auto *Init = DTN.get<CXXCtorInitializer>()) 421 return getInitializerValue(Init, TypePP); 422 llvm_unreachable("Fatal: unhandled AST node.\n"); 423 } 424 425 std::string SyntaxTree::Impl::getDeclValue(const Decl *D) const { 426 std::string Value; 427 if (auto *V = dyn_cast<ValueDecl>(D)) 428 return getRelativeName(V) + "(" + V->getType().getAsString(TypePP) + ")"; 429 if (auto *N = dyn_cast<NamedDecl>(D)) 430 Value += getRelativeName(N) + ";"; 431 if (auto *T = dyn_cast<TypedefNameDecl>(D)) 432 return Value + T->getUnderlyingType().getAsString(TypePP) + ";"; 433 if (auto *T = dyn_cast<TypeDecl>(D)) 434 if (T->getTypeForDecl()) 435 Value += 436 T->getTypeForDecl()->getCanonicalTypeInternal().getAsString(TypePP) + 437 ";"; 438 if (auto *U = dyn_cast<UsingDirectiveDecl>(D)) 439 return std::string(U->getNominatedNamespace()->getName()); 440 if (auto *A = dyn_cast<AccessSpecDecl>(D)) { 441 CharSourceRange Range(A->getSourceRange(), false); 442 return std::string( 443 Lexer::getSourceText(Range, AST.getSourceManager(), AST.getLangOpts())); 444 } 445 return Value; 446 } 447 448 std::string SyntaxTree::Impl::getStmtValue(const Stmt *S) const { 449 if (auto *U = dyn_cast<UnaryOperator>(S)) 450 return std::string(UnaryOperator::getOpcodeStr(U->getOpcode())); 451 if (auto *B = dyn_cast<BinaryOperator>(S)) 452 return std::string(B->getOpcodeStr()); 453 if (auto *M = dyn_cast<MemberExpr>(S)) 454 return getRelativeName(M->getMemberDecl()); 455 if (auto *I = dyn_cast<IntegerLiteral>(S)) { 456 SmallString<256> Str; 457 I->getValue().toString(Str, /*Radix=*/10, /*Signed=*/false); 458 return std::string(Str.str()); 459 } 460 if (auto *F = dyn_cast<FloatingLiteral>(S)) { 461 SmallString<256> Str; 462 F->getValue().toString(Str); 463 return std::string(Str.str()); 464 } 465 if (auto *D = dyn_cast<DeclRefExpr>(S)) 466 return getRelativeName(D->getDecl(), getEnclosingDeclContext(AST, S)); 467 if (auto *String = dyn_cast<StringLiteral>(S)) { 468 if (String->isWide() || String->isUTF16() || String->isUTF32()) { 469 std::string UTF8Str; 470 unsigned int NumChars = String->getLength(); 471 const char *Bytes = String->getBytes().data(); 472 if (String->isWide()) { 473 const auto *Chars = reinterpret_cast<const wchar_t *>(Bytes); 474 if (!convertWideToUTF8({Chars, NumChars}, UTF8Str)) 475 return ""; 476 } else if (String->isUTF16()) { 477 const auto *Chars = reinterpret_cast<const UTF16 *>(Bytes); 478 if (!convertUTF16ToUTF8String({Chars, NumChars}, UTF8Str)) 479 return ""; 480 } else { 481 assert(String->isUTF32() && "Unsupported string encoding."); 482 const auto *Chars = reinterpret_cast<const UTF32 *>(Bytes); 483 if (!convertUTF32ToUTF8String({Chars, NumChars}, UTF8Str)) 484 return ""; 485 } 486 return UTF8Str; 487 } 488 return std::string(String->getString()); 489 } 490 if (auto *B = dyn_cast<CXXBoolLiteralExpr>(S)) 491 return B->getValue() ? "true" : "false"; 492 return ""; 493 } 494 495 /// Identifies a node in a subtree by its postorder offset, starting at 1. 496 struct SNodeId { 497 int Id = 0; 498 499 explicit SNodeId(int Id) : Id(Id) {} 500 explicit SNodeId() = default; 501 502 operator int() const { return Id; } 503 SNodeId &operator++() { return ++Id, *this; } 504 SNodeId &operator--() { return --Id, *this; } 505 SNodeId operator+(int Other) const { return SNodeId(Id + Other); } 506 }; 507 508 class Subtree { 509 private: 510 /// The parent tree. 511 const SyntaxTree::Impl &Tree; 512 /// Maps SNodeIds to original ids. 513 std::vector<NodeId> RootIds; 514 /// Maps subtree nodes to their leftmost descendants wtihin the subtree. 515 std::vector<SNodeId> LeftMostDescendants; 516 517 public: 518 std::vector<SNodeId> KeyRoots; 519 520 Subtree(const SyntaxTree::Impl &Tree, NodeId SubtreeRoot) : Tree(Tree) { 521 RootIds = getSubtreePostorder(Tree, SubtreeRoot); 522 int NumLeaves = setLeftMostDescendants(); 523 computeKeyRoots(NumLeaves); 524 } 525 int getSize() const { return RootIds.size(); } 526 NodeId getIdInRoot(SNodeId Id) const { 527 assert(Id > 0 && Id <= getSize() && "Invalid subtree node index."); 528 return RootIds[Id - 1]; 529 } 530 const Node &getNode(SNodeId Id) const { 531 return Tree.getNode(getIdInRoot(Id)); 532 } 533 SNodeId getLeftMostDescendant(SNodeId Id) const { 534 assert(Id > 0 && Id <= getSize() && "Invalid subtree node index."); 535 return LeftMostDescendants[Id - 1]; 536 } 537 /// Returns the postorder index of the leftmost descendant in the subtree. 538 NodeId getPostorderOffset() const { 539 return Tree.PostorderIds[getIdInRoot(SNodeId(1))]; 540 } 541 std::string getNodeValue(SNodeId Id) const { 542 return Tree.getNodeValue(getIdInRoot(Id)); 543 } 544 545 private: 546 /// Returns the number of leafs in the subtree. 547 int setLeftMostDescendants() { 548 int NumLeaves = 0; 549 LeftMostDescendants.resize(getSize()); 550 for (int I = 0; I < getSize(); ++I) { 551 SNodeId SI(I + 1); 552 const Node &N = getNode(SI); 553 NumLeaves += N.isLeaf(); 554 assert(I == Tree.PostorderIds[getIdInRoot(SI)] - getPostorderOffset() && 555 "Postorder traversal in subtree should correspond to traversal in " 556 "the root tree by a constant offset."); 557 LeftMostDescendants[I] = SNodeId(Tree.PostorderIds[N.LeftMostDescendant] - 558 getPostorderOffset()); 559 } 560 return NumLeaves; 561 } 562 void computeKeyRoots(int Leaves) { 563 KeyRoots.resize(Leaves); 564 std::unordered_set<int> Visited; 565 int K = Leaves - 1; 566 for (SNodeId I(getSize()); I > 0; --I) { 567 SNodeId LeftDesc = getLeftMostDescendant(I); 568 if (Visited.count(LeftDesc)) 569 continue; 570 assert(K >= 0 && "K should be non-negative"); 571 KeyRoots[K] = I; 572 Visited.insert(LeftDesc); 573 --K; 574 } 575 } 576 }; 577 578 /// Implementation of Zhang and Shasha's Algorithm for tree edit distance. 579 /// Computes an optimal mapping between two trees using only insertion, 580 /// deletion and update as edit actions (similar to the Levenshtein distance). 581 class ZhangShashaMatcher { 582 const ASTDiff::Impl &DiffImpl; 583 Subtree S1; 584 Subtree S2; 585 std::unique_ptr<std::unique_ptr<double[]>[]> TreeDist, ForestDist; 586 587 public: 588 ZhangShashaMatcher(const ASTDiff::Impl &DiffImpl, const SyntaxTree::Impl &T1, 589 const SyntaxTree::Impl &T2, NodeId Id1, NodeId Id2) 590 : DiffImpl(DiffImpl), S1(T1, Id1), S2(T2, Id2) { 591 TreeDist = std::make_unique<std::unique_ptr<double[]>[]>( 592 size_t(S1.getSize()) + 1); 593 ForestDist = std::make_unique<std::unique_ptr<double[]>[]>( 594 size_t(S1.getSize()) + 1); 595 for (int I = 0, E = S1.getSize() + 1; I < E; ++I) { 596 TreeDist[I] = std::make_unique<double[]>(size_t(S2.getSize()) + 1); 597 ForestDist[I] = std::make_unique<double[]>(size_t(S2.getSize()) + 1); 598 } 599 } 600 601 std::vector<std::pair<NodeId, NodeId>> getMatchingNodes() { 602 std::vector<std::pair<NodeId, NodeId>> Matches; 603 std::vector<std::pair<SNodeId, SNodeId>> TreePairs; 604 605 computeTreeDist(); 606 607 bool RootNodePair = true; 608 609 TreePairs.emplace_back(SNodeId(S1.getSize()), SNodeId(S2.getSize())); 610 611 while (!TreePairs.empty()) { 612 SNodeId LastRow, LastCol, FirstRow, FirstCol, Row, Col; 613 std::tie(LastRow, LastCol) = TreePairs.back(); 614 TreePairs.pop_back(); 615 616 if (!RootNodePair) { 617 computeForestDist(LastRow, LastCol); 618 } 619 620 RootNodePair = false; 621 622 FirstRow = S1.getLeftMostDescendant(LastRow); 623 FirstCol = S2.getLeftMostDescendant(LastCol); 624 625 Row = LastRow; 626 Col = LastCol; 627 628 while (Row > FirstRow || Col > FirstCol) { 629 if (Row > FirstRow && 630 ForestDist[Row - 1][Col] + 1 == ForestDist[Row][Col]) { 631 --Row; 632 } else if (Col > FirstCol && 633 ForestDist[Row][Col - 1] + 1 == ForestDist[Row][Col]) { 634 --Col; 635 } else { 636 SNodeId LMD1 = S1.getLeftMostDescendant(Row); 637 SNodeId LMD2 = S2.getLeftMostDescendant(Col); 638 if (LMD1 == S1.getLeftMostDescendant(LastRow) && 639 LMD2 == S2.getLeftMostDescendant(LastCol)) { 640 NodeId Id1 = S1.getIdInRoot(Row); 641 NodeId Id2 = S2.getIdInRoot(Col); 642 assert(DiffImpl.isMatchingPossible(Id1, Id2) && 643 "These nodes must not be matched."); 644 Matches.emplace_back(Id1, Id2); 645 --Row; 646 --Col; 647 } else { 648 TreePairs.emplace_back(Row, Col); 649 Row = LMD1; 650 Col = LMD2; 651 } 652 } 653 } 654 } 655 return Matches; 656 } 657 658 private: 659 /// We use a simple cost model for edit actions, which seems good enough. 660 /// Simple cost model for edit actions. This seems to make the matching 661 /// algorithm perform reasonably well. 662 /// The values range between 0 and 1, or infinity if this edit action should 663 /// always be avoided. 664 static constexpr double DeletionCost = 1; 665 static constexpr double InsertionCost = 1; 666 667 double getUpdateCost(SNodeId Id1, SNodeId Id2) { 668 if (!DiffImpl.isMatchingPossible(S1.getIdInRoot(Id1), S2.getIdInRoot(Id2))) 669 return std::numeric_limits<double>::max(); 670 return S1.getNodeValue(Id1) != S2.getNodeValue(Id2); 671 } 672 673 void computeTreeDist() { 674 for (SNodeId Id1 : S1.KeyRoots) 675 for (SNodeId Id2 : S2.KeyRoots) 676 computeForestDist(Id1, Id2); 677 } 678 679 void computeForestDist(SNodeId Id1, SNodeId Id2) { 680 assert(Id1 > 0 && Id2 > 0 && "Expecting offsets greater than 0."); 681 SNodeId LMD1 = S1.getLeftMostDescendant(Id1); 682 SNodeId LMD2 = S2.getLeftMostDescendant(Id2); 683 684 ForestDist[LMD1][LMD2] = 0; 685 for (SNodeId D1 = LMD1 + 1; D1 <= Id1; ++D1) { 686 ForestDist[D1][LMD2] = ForestDist[D1 - 1][LMD2] + DeletionCost; 687 for (SNodeId D2 = LMD2 + 1; D2 <= Id2; ++D2) { 688 ForestDist[LMD1][D2] = ForestDist[LMD1][D2 - 1] + InsertionCost; 689 SNodeId DLMD1 = S1.getLeftMostDescendant(D1); 690 SNodeId DLMD2 = S2.getLeftMostDescendant(D2); 691 if (DLMD1 == LMD1 && DLMD2 == LMD2) { 692 double UpdateCost = getUpdateCost(D1, D2); 693 ForestDist[D1][D2] = 694 std::min({ForestDist[D1 - 1][D2] + DeletionCost, 695 ForestDist[D1][D2 - 1] + InsertionCost, 696 ForestDist[D1 - 1][D2 - 1] + UpdateCost}); 697 TreeDist[D1][D2] = ForestDist[D1][D2]; 698 } else { 699 ForestDist[D1][D2] = 700 std::min({ForestDist[D1 - 1][D2] + DeletionCost, 701 ForestDist[D1][D2 - 1] + InsertionCost, 702 ForestDist[DLMD1][DLMD2] + TreeDist[D1][D2]}); 703 } 704 } 705 } 706 } 707 }; 708 709 ASTNodeKind Node::getType() const { return ASTNode.getNodeKind(); } 710 711 StringRef Node::getTypeLabel() const { return getType().asStringRef(); } 712 713 llvm::Optional<std::string> Node::getQualifiedIdentifier() const { 714 if (auto *ND = ASTNode.get<NamedDecl>()) { 715 if (ND->getDeclName().isIdentifier()) 716 return ND->getQualifiedNameAsString(); 717 } 718 return llvm::None; 719 } 720 721 llvm::Optional<StringRef> Node::getIdentifier() const { 722 if (auto *ND = ASTNode.get<NamedDecl>()) { 723 if (ND->getDeclName().isIdentifier()) 724 return ND->getName(); 725 } 726 return llvm::None; 727 } 728 729 namespace { 730 // Compares nodes by their depth. 731 struct HeightLess { 732 const SyntaxTree::Impl &Tree; 733 HeightLess(const SyntaxTree::Impl &Tree) : Tree(Tree) {} 734 bool operator()(NodeId Id1, NodeId Id2) const { 735 return Tree.getNode(Id1).Height < Tree.getNode(Id2).Height; 736 } 737 }; 738 } // end anonymous namespace 739 740 namespace { 741 // Priority queue for nodes, sorted descendingly by their height. 742 class PriorityList { 743 const SyntaxTree::Impl &Tree; 744 HeightLess Cmp; 745 std::vector<NodeId> Container; 746 PriorityQueue<NodeId, std::vector<NodeId>, HeightLess> List; 747 748 public: 749 PriorityList(const SyntaxTree::Impl &Tree) 750 : Tree(Tree), Cmp(Tree), List(Cmp, Container) {} 751 752 void push(NodeId id) { List.push(id); } 753 754 std::vector<NodeId> pop() { 755 int Max = peekMax(); 756 std::vector<NodeId> Result; 757 if (Max == 0) 758 return Result; 759 while (peekMax() == Max) { 760 Result.push_back(List.top()); 761 List.pop(); 762 } 763 // TODO this is here to get a stable output, not a good heuristic 764 llvm::sort(Result); 765 return Result; 766 } 767 int peekMax() const { 768 if (List.empty()) 769 return 0; 770 return Tree.getNode(List.top()).Height; 771 } 772 void open(NodeId Id) { 773 for (NodeId Child : Tree.getNode(Id).Children) 774 push(Child); 775 } 776 }; 777 } // end anonymous namespace 778 779 bool ASTDiff::Impl::identical(NodeId Id1, NodeId Id2) const { 780 const Node &N1 = T1.getNode(Id1); 781 const Node &N2 = T2.getNode(Id2); 782 if (N1.Children.size() != N2.Children.size() || 783 !isMatchingPossible(Id1, Id2) || 784 T1.getNodeValue(Id1) != T2.getNodeValue(Id2)) 785 return false; 786 for (size_t Id = 0, E = N1.Children.size(); Id < E; ++Id) 787 if (!identical(N1.Children[Id], N2.Children[Id])) 788 return false; 789 return true; 790 } 791 792 bool ASTDiff::Impl::isMatchingPossible(NodeId Id1, NodeId Id2) const { 793 return Options.isMatchingAllowed(T1.getNode(Id1), T2.getNode(Id2)); 794 } 795 796 bool ASTDiff::Impl::haveSameParents(const Mapping &M, NodeId Id1, 797 NodeId Id2) const { 798 NodeId P1 = T1.getNode(Id1).Parent; 799 NodeId P2 = T2.getNode(Id2).Parent; 800 return (P1.isInvalid() && P2.isInvalid()) || 801 (P1.isValid() && P2.isValid() && M.getDst(P1) == P2); 802 } 803 804 void ASTDiff::Impl::addOptimalMapping(Mapping &M, NodeId Id1, 805 NodeId Id2) const { 806 if (std::max(T1.getNumberOfDescendants(Id1), T2.getNumberOfDescendants(Id2)) > 807 Options.MaxSize) 808 return; 809 ZhangShashaMatcher Matcher(*this, T1, T2, Id1, Id2); 810 std::vector<std::pair<NodeId, NodeId>> R = Matcher.getMatchingNodes(); 811 for (const auto &Tuple : R) { 812 NodeId Src = Tuple.first; 813 NodeId Dst = Tuple.second; 814 if (!M.hasSrc(Src) && !M.hasDst(Dst)) 815 M.link(Src, Dst); 816 } 817 } 818 819 double ASTDiff::Impl::getJaccardSimilarity(const Mapping &M, NodeId Id1, 820 NodeId Id2) const { 821 int CommonDescendants = 0; 822 const Node &N1 = T1.getNode(Id1); 823 // Count the common descendants, excluding the subtree root. 824 for (NodeId Src = Id1 + 1; Src <= N1.RightMostDescendant; ++Src) { 825 NodeId Dst = M.getDst(Src); 826 CommonDescendants += int(Dst.isValid() && T2.isInSubtree(Dst, Id2)); 827 } 828 // We need to subtract 1 to get the number of descendants excluding the root. 829 double Denominator = T1.getNumberOfDescendants(Id1) - 1 + 830 T2.getNumberOfDescendants(Id2) - 1 - CommonDescendants; 831 // CommonDescendants is less than the size of one subtree. 832 assert(Denominator >= 0 && "Expected non-negative denominator."); 833 if (Denominator == 0) 834 return 0; 835 return CommonDescendants / Denominator; 836 } 837 838 NodeId ASTDiff::Impl::findCandidate(const Mapping &M, NodeId Id1) const { 839 NodeId Candidate; 840 double HighestSimilarity = 0.0; 841 for (NodeId Id2 : T2) { 842 if (!isMatchingPossible(Id1, Id2)) 843 continue; 844 if (M.hasDst(Id2)) 845 continue; 846 double Similarity = getJaccardSimilarity(M, Id1, Id2); 847 if (Similarity >= Options.MinSimilarity && Similarity > HighestSimilarity) { 848 HighestSimilarity = Similarity; 849 Candidate = Id2; 850 } 851 } 852 return Candidate; 853 } 854 855 void ASTDiff::Impl::matchBottomUp(Mapping &M) const { 856 std::vector<NodeId> Postorder = getSubtreePostorder(T1, T1.getRootId()); 857 for (NodeId Id1 : Postorder) { 858 if (Id1 == T1.getRootId() && !M.hasSrc(T1.getRootId()) && 859 !M.hasDst(T2.getRootId())) { 860 if (isMatchingPossible(T1.getRootId(), T2.getRootId())) { 861 M.link(T1.getRootId(), T2.getRootId()); 862 addOptimalMapping(M, T1.getRootId(), T2.getRootId()); 863 } 864 break; 865 } 866 bool Matched = M.hasSrc(Id1); 867 const Node &N1 = T1.getNode(Id1); 868 bool MatchedChildren = llvm::any_of( 869 N1.Children, [&](NodeId Child) { return M.hasSrc(Child); }); 870 if (Matched || !MatchedChildren) 871 continue; 872 NodeId Id2 = findCandidate(M, Id1); 873 if (Id2.isValid()) { 874 M.link(Id1, Id2); 875 addOptimalMapping(M, Id1, Id2); 876 } 877 } 878 } 879 880 Mapping ASTDiff::Impl::matchTopDown() const { 881 PriorityList L1(T1); 882 PriorityList L2(T2); 883 884 Mapping M(T1.getSize() + T2.getSize()); 885 886 L1.push(T1.getRootId()); 887 L2.push(T2.getRootId()); 888 889 int Max1, Max2; 890 while (std::min(Max1 = L1.peekMax(), Max2 = L2.peekMax()) > 891 Options.MinHeight) { 892 if (Max1 > Max2) { 893 for (NodeId Id : L1.pop()) 894 L1.open(Id); 895 continue; 896 } 897 if (Max2 > Max1) { 898 for (NodeId Id : L2.pop()) 899 L2.open(Id); 900 continue; 901 } 902 std::vector<NodeId> H1, H2; 903 H1 = L1.pop(); 904 H2 = L2.pop(); 905 for (NodeId Id1 : H1) { 906 for (NodeId Id2 : H2) { 907 if (identical(Id1, Id2) && !M.hasSrc(Id1) && !M.hasDst(Id2)) { 908 for (int I = 0, E = T1.getNumberOfDescendants(Id1); I < E; ++I) 909 M.link(Id1 + I, Id2 + I); 910 } 911 } 912 } 913 for (NodeId Id1 : H1) { 914 if (!M.hasSrc(Id1)) 915 L1.open(Id1); 916 } 917 for (NodeId Id2 : H2) { 918 if (!M.hasDst(Id2)) 919 L2.open(Id2); 920 } 921 } 922 return M; 923 } 924 925 ASTDiff::Impl::Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2, 926 const ComparisonOptions &Options) 927 : T1(T1), T2(T2), Options(Options) { 928 computeMapping(); 929 computeChangeKinds(TheMapping); 930 } 931 932 void ASTDiff::Impl::computeMapping() { 933 TheMapping = matchTopDown(); 934 if (Options.StopAfterTopDown) 935 return; 936 matchBottomUp(TheMapping); 937 } 938 939 void ASTDiff::Impl::computeChangeKinds(Mapping &M) { 940 for (NodeId Id1 : T1) { 941 if (!M.hasSrc(Id1)) { 942 T1.getMutableNode(Id1).Change = Delete; 943 T1.getMutableNode(Id1).Shift -= 1; 944 } 945 } 946 for (NodeId Id2 : T2) { 947 if (!M.hasDst(Id2)) { 948 T2.getMutableNode(Id2).Change = Insert; 949 T2.getMutableNode(Id2).Shift -= 1; 950 } 951 } 952 for (NodeId Id1 : T1.NodesBfs) { 953 NodeId Id2 = M.getDst(Id1); 954 if (Id2.isInvalid()) 955 continue; 956 if (!haveSameParents(M, Id1, Id2) || 957 T1.findPositionInParent(Id1, true) != 958 T2.findPositionInParent(Id2, true)) { 959 T1.getMutableNode(Id1).Shift -= 1; 960 T2.getMutableNode(Id2).Shift -= 1; 961 } 962 } 963 for (NodeId Id2 : T2.NodesBfs) { 964 NodeId Id1 = M.getSrc(Id2); 965 if (Id1.isInvalid()) 966 continue; 967 Node &N1 = T1.getMutableNode(Id1); 968 Node &N2 = T2.getMutableNode(Id2); 969 if (Id1.isInvalid()) 970 continue; 971 if (!haveSameParents(M, Id1, Id2) || 972 T1.findPositionInParent(Id1, true) != 973 T2.findPositionInParent(Id2, true)) { 974 N1.Change = N2.Change = Move; 975 } 976 if (T1.getNodeValue(Id1) != T2.getNodeValue(Id2)) { 977 N1.Change = N2.Change = (N1.Change == Move ? UpdateMove : Update); 978 } 979 } 980 } 981 982 ASTDiff::ASTDiff(SyntaxTree &T1, SyntaxTree &T2, 983 const ComparisonOptions &Options) 984 : DiffImpl(std::make_unique<Impl>(*T1.TreeImpl, *T2.TreeImpl, Options)) {} 985 986 ASTDiff::~ASTDiff() = default; 987 988 NodeId ASTDiff::getMapped(const SyntaxTree &SourceTree, NodeId Id) const { 989 return DiffImpl->getMapped(SourceTree.TreeImpl, Id); 990 } 991 992 SyntaxTree::SyntaxTree(ASTContext &AST) 993 : TreeImpl(std::make_unique<SyntaxTree::Impl>( 994 this, AST.getTranslationUnitDecl(), AST)) {} 995 996 SyntaxTree::~SyntaxTree() = default; 997 998 const ASTContext &SyntaxTree::getASTContext() const { return TreeImpl->AST; } 999 1000 const Node &SyntaxTree::getNode(NodeId Id) const { 1001 return TreeImpl->getNode(Id); 1002 } 1003 1004 int SyntaxTree::getSize() const { return TreeImpl->getSize(); } 1005 NodeId SyntaxTree::getRootId() const { return TreeImpl->getRootId(); } 1006 SyntaxTree::PreorderIterator SyntaxTree::begin() const { 1007 return TreeImpl->begin(); 1008 } 1009 SyntaxTree::PreorderIterator SyntaxTree::end() const { return TreeImpl->end(); } 1010 1011 int SyntaxTree::findPositionInParent(NodeId Id) const { 1012 return TreeImpl->findPositionInParent(Id); 1013 } 1014 1015 std::pair<unsigned, unsigned> 1016 SyntaxTree::getSourceRangeOffsets(const Node &N) const { 1017 const SourceManager &SrcMgr = TreeImpl->AST.getSourceManager(); 1018 SourceRange Range = N.ASTNode.getSourceRange(); 1019 SourceLocation BeginLoc = Range.getBegin(); 1020 SourceLocation EndLoc = Lexer::getLocForEndOfToken( 1021 Range.getEnd(), /*Offset=*/0, SrcMgr, TreeImpl->AST.getLangOpts()); 1022 if (auto *ThisExpr = N.ASTNode.get<CXXThisExpr>()) { 1023 if (ThisExpr->isImplicit()) 1024 EndLoc = BeginLoc; 1025 } 1026 unsigned Begin = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(BeginLoc)); 1027 unsigned End = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(EndLoc)); 1028 return {Begin, End}; 1029 } 1030 1031 std::string SyntaxTree::getNodeValue(NodeId Id) const { 1032 return TreeImpl->getNodeValue(Id); 1033 } 1034 1035 std::string SyntaxTree::getNodeValue(const Node &N) const { 1036 return TreeImpl->getNodeValue(N); 1037 } 1038 1039 } // end namespace diff 1040 } // end namespace clang 1041