xref: /llvm-project/clang/lib/Tooling/ASTDiff/ASTDiff.cpp (revision 9b2c25c70466d6f081a2915e661840f965b6056a)
1a75b2cacSAlex Lorenz //===- ASTDiff.cpp - AST differencing implementation-----------*- C++ -*- -===//
2a75b2cacSAlex Lorenz //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6a75b2cacSAlex Lorenz //
7a75b2cacSAlex Lorenz //===----------------------------------------------------------------------===//
8a75b2cacSAlex Lorenz //
9a75b2cacSAlex Lorenz // This file contains definitons for the AST differencing interface.
10a75b2cacSAlex Lorenz //
11a75b2cacSAlex Lorenz //===----------------------------------------------------------------------===//
12a75b2cacSAlex Lorenz 
13a75b2cacSAlex Lorenz #include "clang/Tooling/ASTDiff/ASTDiff.h"
148a81daaaSReid Kleckner #include "clang/AST/ParentMapContext.h"
15a75b2cacSAlex Lorenz #include "clang/AST/RecursiveASTVisitor.h"
1686565c13SReid Kleckner #include "clang/Basic/SourceManager.h"
17a75b2cacSAlex Lorenz #include "clang/Lex/Lexer.h"
18a75b2cacSAlex Lorenz #include "llvm/ADT/PriorityQueue.h"
19a75b2cacSAlex Lorenz 
20a75b2cacSAlex Lorenz #include <limits>
21a75b2cacSAlex Lorenz #include <memory>
22a1580d7bSKazu Hirata #include <optional>
23a75b2cacSAlex Lorenz #include <unordered_set>
24a75b2cacSAlex Lorenz 
25a75b2cacSAlex Lorenz using namespace llvm;
26a75b2cacSAlex Lorenz using namespace clang;
27a75b2cacSAlex Lorenz 
28a75b2cacSAlex Lorenz namespace clang {
29a75b2cacSAlex Lorenz namespace diff {
30a75b2cacSAlex Lorenz 
31fa524d7bSJohannes Altmanninger namespace {
328b0e0663SJohannes Altmanninger /// Maps nodes of the left tree to ones on the right, and vice versa.
338b0e0663SJohannes Altmanninger class Mapping {
348b0e0663SJohannes Altmanninger public:
358b0e0663SJohannes Altmanninger   Mapping() = default;
368b0e0663SJohannes Altmanninger   Mapping(Mapping &&Other) = default;
378b0e0663SJohannes Altmanninger   Mapping &operator=(Mapping &&Other) = default;
3851321aefSJohannes Altmanninger 
Mapping(size_t Size)3951321aefSJohannes Altmanninger   Mapping(size_t Size) {
402b3d49b6SJonas Devlieghere     SrcToDst = std::make_unique<NodeId[]>(Size);
412b3d49b6SJonas Devlieghere     DstToSrc = std::make_unique<NodeId[]>(Size);
428b0e0663SJohannes Altmanninger   }
438b0e0663SJohannes Altmanninger 
link(NodeId Src,NodeId Dst)448b0e0663SJohannes Altmanninger   void link(NodeId Src, NodeId Dst) {
4551321aefSJohannes Altmanninger     SrcToDst[Src] = Dst, DstToSrc[Dst] = Src;
468b0e0663SJohannes Altmanninger   }
478b0e0663SJohannes Altmanninger 
getDst(NodeId Src) const4851321aefSJohannes Altmanninger   NodeId getDst(NodeId Src) const { return SrcToDst[Src]; }
getSrc(NodeId Dst) const4951321aefSJohannes Altmanninger   NodeId getSrc(NodeId Dst) const { return DstToSrc[Dst]; }
hasSrc(NodeId Src) const5051321aefSJohannes Altmanninger   bool hasSrc(NodeId Src) const { return getDst(Src).isValid(); }
hasDst(NodeId Dst) const5151321aefSJohannes Altmanninger   bool hasDst(NodeId Dst) const { return getSrc(Dst).isValid(); }
528b0e0663SJohannes Altmanninger 
538b0e0663SJohannes Altmanninger private:
5451321aefSJohannes Altmanninger   std::unique_ptr<NodeId[]> SrcToDst, DstToSrc;
558b0e0663SJohannes Altmanninger };
56fa524d7bSJohannes Altmanninger } // end anonymous namespace
578b0e0663SJohannes Altmanninger 
58a75b2cacSAlex Lorenz class ASTDiff::Impl {
59a75b2cacSAlex Lorenz public:
6031b52d63SJohannes Altmanninger   SyntaxTree::Impl &T1, &T2;
61a75b2cacSAlex Lorenz   Mapping TheMapping;
62a75b2cacSAlex Lorenz 
6331b52d63SJohannes Altmanninger   Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
64e0fe5cd4SJohannes Altmanninger        const ComparisonOptions &Options);
65a75b2cacSAlex Lorenz 
66a75b2cacSAlex Lorenz   /// Matches nodes one-by-one based on their similarity.
67a75b2cacSAlex Lorenz   void computeMapping();
68a75b2cacSAlex Lorenz 
69e0fe5cd4SJohannes Altmanninger   // Compute Change for each node based on similarity.
70e0fe5cd4SJohannes Altmanninger   void computeChangeKinds(Mapping &M);
71a75b2cacSAlex Lorenz 
getMapped(const std::unique_ptr<SyntaxTree::Impl> & Tree,NodeId Id) const72e0fe5cd4SJohannes Altmanninger   NodeId getMapped(const std::unique_ptr<SyntaxTree::Impl> &Tree,
73e0fe5cd4SJohannes Altmanninger                    NodeId Id) const {
74e0fe5cd4SJohannes Altmanninger     if (&*Tree == &T1)
75e0fe5cd4SJohannes Altmanninger       return TheMapping.getDst(Id);
76e0fe5cd4SJohannes Altmanninger     assert(&*Tree == &T2 && "Invalid tree.");
77e0fe5cd4SJohannes Altmanninger     return TheMapping.getSrc(Id);
78e0fe5cd4SJohannes Altmanninger   }
79a75b2cacSAlex Lorenz 
80a75b2cacSAlex Lorenz private:
81a75b2cacSAlex Lorenz   // Returns true if the two subtrees are identical.
8231b52d63SJohannes Altmanninger   bool identical(NodeId Id1, NodeId Id2) const;
83a75b2cacSAlex Lorenz 
84a75b2cacSAlex Lorenz   // Returns false if the nodes must not be mached.
85a75b2cacSAlex Lorenz   bool isMatchingPossible(NodeId Id1, NodeId Id2) const;
86a75b2cacSAlex Lorenz 
87e0fe5cd4SJohannes Altmanninger   // Returns true if the nodes' parents are matched.
88e0fe5cd4SJohannes Altmanninger   bool haveSameParents(const Mapping &M, NodeId Id1, NodeId Id2) const;
89e0fe5cd4SJohannes Altmanninger 
90a75b2cacSAlex Lorenz   // Uses an optimal albeit slow algorithm to compute a mapping between two
91a75b2cacSAlex Lorenz   // subtrees, but only if both have fewer nodes than MaxSize.
92a75b2cacSAlex Lorenz   void addOptimalMapping(Mapping &M, NodeId Id1, NodeId Id2) const;
93a75b2cacSAlex Lorenz 
94a75b2cacSAlex Lorenz   // Computes the ratio of common descendants between the two nodes.
95a75b2cacSAlex Lorenz   // Descendants are only considered to be equal when they are mapped in M.
96d1969307SJohannes Altmanninger   double getJaccardSimilarity(const Mapping &M, NodeId Id1, NodeId Id2) const;
97a75b2cacSAlex Lorenz 
98a75b2cacSAlex Lorenz   // Returns the node that has the highest degree of similarity.
99a75b2cacSAlex Lorenz   NodeId findCandidate(const Mapping &M, NodeId Id1) const;
100a75b2cacSAlex Lorenz 
101e0fe5cd4SJohannes Altmanninger   // Returns a mapping of identical subtrees.
102e0fe5cd4SJohannes Altmanninger   Mapping matchTopDown() const;
103e0fe5cd4SJohannes Altmanninger 
104a75b2cacSAlex Lorenz   // Tries to match any yet unmapped nodes, in a bottom-up fashion.
105a75b2cacSAlex Lorenz   void matchBottomUp(Mapping &M) const;
106a75b2cacSAlex Lorenz 
107a75b2cacSAlex Lorenz   const ComparisonOptions &Options;
108a75b2cacSAlex Lorenz 
109a75b2cacSAlex Lorenz   friend class ZhangShashaMatcher;
110a75b2cacSAlex Lorenz };
111a75b2cacSAlex Lorenz 
1128b0e0663SJohannes Altmanninger /// Represents the AST of a TranslationUnit.
11331b52d63SJohannes Altmanninger class SyntaxTree::Impl {
1148b0e0663SJohannes Altmanninger public:
11541395022SJohannes Altmanninger   Impl(SyntaxTree *Parent, ASTContext &AST);
1168b0e0663SJohannes Altmanninger   /// Constructs a tree from an AST node.
1172b955ffaSJohannes Altmanninger   Impl(SyntaxTree *Parent, Decl *N, ASTContext &AST);
1182b955ffaSJohannes Altmanninger   Impl(SyntaxTree *Parent, Stmt *N, ASTContext &AST);
1198b0e0663SJohannes Altmanninger   template <class T>
Impl(SyntaxTree * Parent,std::enable_if_t<std::is_base_of_v<Stmt,T>,T> * Node,ASTContext & AST)12031b52d63SJohannes Altmanninger   Impl(SyntaxTree *Parent,
121108e41d9SNathan James        std::enable_if_t<std::is_base_of_v<Stmt, T>, T> *Node, ASTContext &AST)
12231b52d63SJohannes Altmanninger       : Impl(Parent, dyn_cast<Stmt>(Node), AST) {}
1238b0e0663SJohannes Altmanninger   template <class T>
Impl(SyntaxTree * Parent,std::enable_if_t<std::is_base_of_v<Decl,T>,T> * Node,ASTContext & AST)12431b52d63SJohannes Altmanninger   Impl(SyntaxTree *Parent,
125108e41d9SNathan James        std::enable_if_t<std::is_base_of_v<Decl, T>, T> *Node, ASTContext &AST)
12631b52d63SJohannes Altmanninger       : Impl(Parent, dyn_cast<Decl>(Node), AST) {}
1278b0e0663SJohannes Altmanninger 
1288b0e0663SJohannes Altmanninger   SyntaxTree *Parent;
1292b955ffaSJohannes Altmanninger   ASTContext &AST;
13041395022SJohannes Altmanninger   PrintingPolicy TypePP;
131bc3e993cSJohannes Altmanninger   /// Nodes in preorder.
132bc3e993cSJohannes Altmanninger   std::vector<Node> Nodes;
1338b0e0663SJohannes Altmanninger   std::vector<NodeId> Leaves;
1348b0e0663SJohannes Altmanninger   // Maps preorder indices to postorder ones.
1358b0e0663SJohannes Altmanninger   std::vector<int> PostorderIds;
136e0fe5cd4SJohannes Altmanninger   std::vector<NodeId> NodesBfs;
1378b0e0663SJohannes Altmanninger 
getSize() const1388b0e0663SJohannes Altmanninger   int getSize() const { return Nodes.size(); }
getRootId() const13931b52d63SJohannes Altmanninger   NodeId getRootId() const { return 0; }
begin() const140e0fe5cd4SJohannes Altmanninger   PreorderIterator begin() const { return getRootId(); }
end() const141e0fe5cd4SJohannes Altmanninger   PreorderIterator end() const { return getSize(); }
1428b0e0663SJohannes Altmanninger 
getNode(NodeId Id) const1438b0e0663SJohannes Altmanninger   const Node &getNode(NodeId Id) const { return Nodes[Id]; }
getMutableNode(NodeId Id)1448b0e0663SJohannes Altmanninger   Node &getMutableNode(NodeId Id) { return Nodes[Id]; }
isValidNodeId(NodeId Id) const1458b0e0663SJohannes Altmanninger   bool isValidNodeId(NodeId Id) const { return Id >= 0 && Id < getSize(); }
addNode(Node & N)1468b0e0663SJohannes Altmanninger   void addNode(Node &N) { Nodes.push_back(N); }
1478b0e0663SJohannes Altmanninger   int getNumberOfDescendants(NodeId Id) const;
1488b0e0663SJohannes Altmanninger   bool isInSubtree(NodeId Id, NodeId SubtreeRoot) const;
149e0fe5cd4SJohannes Altmanninger   int findPositionInParent(NodeId Id, bool Shifted = false) const;
1508b0e0663SJohannes Altmanninger 
1512b955ffaSJohannes Altmanninger   std::string getRelativeName(const NamedDecl *ND,
1522b955ffaSJohannes Altmanninger                               const DeclContext *Context) const;
1532b955ffaSJohannes Altmanninger   std::string getRelativeName(const NamedDecl *ND) const;
1542b955ffaSJohannes Altmanninger 
15531b52d63SJohannes Altmanninger   std::string getNodeValue(NodeId Id) const;
156e0fe5cd4SJohannes Altmanninger   std::string getNodeValue(const Node &Node) const;
1570dd86dc5SJohannes Altmanninger   std::string getDeclValue(const Decl *D) const;
1580dd86dc5SJohannes Altmanninger   std::string getStmtValue(const Stmt *S) const;
1598b0e0663SJohannes Altmanninger 
1608b0e0663SJohannes Altmanninger private:
1618b0e0663SJohannes Altmanninger   void initTree();
1628b0e0663SJohannes Altmanninger   void setLeftMostDescendants();
1638b0e0663SJohannes Altmanninger };
1648b0e0663SJohannes Altmanninger 
isSpecializedNodeExcluded(const Decl * D)165d5b56a86SJohannes Altmanninger static bool isSpecializedNodeExcluded(const Decl *D) { return D->isImplicit(); }
isSpecializedNodeExcluded(const Stmt * S)166d5b56a86SJohannes Altmanninger static bool isSpecializedNodeExcluded(const Stmt *S) { return false; }
isSpecializedNodeExcluded(CXXCtorInitializer * I)16741395022SJohannes Altmanninger static bool isSpecializedNodeExcluded(CXXCtorInitializer *I) {
16841395022SJohannes Altmanninger   return !I->isWritten();
16941395022SJohannes Altmanninger }
170d5b56a86SJohannes Altmanninger 
171a75b2cacSAlex Lorenz template <class T>
isNodeExcluded(const SourceManager & SrcMgr,T * N)172a75b2cacSAlex Lorenz static bool isNodeExcluded(const SourceManager &SrcMgr, T *N) {
173a75b2cacSAlex Lorenz   if (!N)
174a75b2cacSAlex Lorenz     return true;
17541395022SJohannes Altmanninger   SourceLocation SLoc = N->getSourceRange().getBegin();
176d5b56a86SJohannes Altmanninger   if (SLoc.isValid()) {
177d5b56a86SJohannes Altmanninger     // Ignore everything from other files.
178d5b56a86SJohannes Altmanninger     if (!SrcMgr.isInMainFile(SLoc))
179d5b56a86SJohannes Altmanninger       return true;
180d5b56a86SJohannes Altmanninger     // Ignore macros.
181d5b56a86SJohannes Altmanninger     if (SLoc != SrcMgr.getSpellingLoc(SLoc))
182d5b56a86SJohannes Altmanninger       return true;
183d5b56a86SJohannes Altmanninger   }
184d5b56a86SJohannes Altmanninger   return isSpecializedNodeExcluded(N);
185a75b2cacSAlex Lorenz }
186a75b2cacSAlex Lorenz 
187a75b2cacSAlex Lorenz namespace {
188a75b2cacSAlex Lorenz // Sets Height, Parent and Children for each node.
189a75b2cacSAlex Lorenz struct PreorderVisitor : public RecursiveASTVisitor<PreorderVisitor> {
190a75b2cacSAlex Lorenz   int Id = 0, Depth = 0;
191a75b2cacSAlex Lorenz   NodeId Parent;
19231b52d63SJohannes Altmanninger   SyntaxTree::Impl &Tree;
193a75b2cacSAlex Lorenz 
PreorderVisitorclang::diff::__anonef34e5090211::PreorderVisitor19431b52d63SJohannes Altmanninger   PreorderVisitor(SyntaxTree::Impl &Tree) : Tree(Tree) {}
195a75b2cacSAlex Lorenz 
PreTraverseclang::diff::__anonef34e5090211::PreorderVisitor196a75b2cacSAlex Lorenz   template <class T> std::tuple<NodeId, NodeId> PreTraverse(T *ASTNode) {
197a75b2cacSAlex Lorenz     NodeId MyId = Id;
198bc3e993cSJohannes Altmanninger     Tree.Nodes.emplace_back();
19931b52d63SJohannes Altmanninger     Node &N = Tree.getMutableNode(MyId);
200a75b2cacSAlex Lorenz     N.Parent = Parent;
201a75b2cacSAlex Lorenz     N.Depth = Depth;
202a75b2cacSAlex Lorenz     N.ASTNode = DynTypedNode::create(*ASTNode);
203a75b2cacSAlex Lorenz     assert(!N.ASTNode.getNodeKind().isNone() &&
204a75b2cacSAlex Lorenz            "Expected nodes to have a valid kind.");
205a75b2cacSAlex Lorenz     if (Parent.isValid()) {
20631b52d63SJohannes Altmanninger       Node &P = Tree.getMutableNode(Parent);
207a75b2cacSAlex Lorenz       P.Children.push_back(MyId);
208a75b2cacSAlex Lorenz     }
209a75b2cacSAlex Lorenz     Parent = MyId;
210a75b2cacSAlex Lorenz     ++Id;
211a75b2cacSAlex Lorenz     ++Depth;
21231b52d63SJohannes Altmanninger     return std::make_tuple(MyId, Tree.getNode(MyId).Parent);
213a75b2cacSAlex Lorenz   }
PostTraverseclang::diff::__anonef34e5090211::PreorderVisitor214a75b2cacSAlex Lorenz   void PostTraverse(std::tuple<NodeId, NodeId> State) {
215a75b2cacSAlex Lorenz     NodeId MyId, PreviousParent;
216a75b2cacSAlex Lorenz     std::tie(MyId, PreviousParent) = State;
217a75b2cacSAlex Lorenz     assert(MyId.isValid() && "Expecting to only traverse valid nodes.");
218a75b2cacSAlex Lorenz     Parent = PreviousParent;
219a75b2cacSAlex Lorenz     --Depth;
22031b52d63SJohannes Altmanninger     Node &N = Tree.getMutableNode(MyId);
221fa524d7bSJohannes Altmanninger     N.RightMostDescendant = Id - 1;
222fa524d7bSJohannes Altmanninger     assert(N.RightMostDescendant >= 0 &&
223fa524d7bSJohannes Altmanninger            N.RightMostDescendant < Tree.getSize() &&
224fa524d7bSJohannes Altmanninger            "Rightmost descendant must be a valid tree node.");
225a75b2cacSAlex Lorenz     if (N.isLeaf())
22631b52d63SJohannes Altmanninger       Tree.Leaves.push_back(MyId);
227a75b2cacSAlex Lorenz     N.Height = 1;
228a75b2cacSAlex Lorenz     for (NodeId Child : N.Children)
22931b52d63SJohannes Altmanninger       N.Height = std::max(N.Height, 1 + Tree.getNode(Child).Height);
230a75b2cacSAlex Lorenz   }
TraverseDeclclang::diff::__anonef34e5090211::PreorderVisitor231a75b2cacSAlex Lorenz   bool TraverseDecl(Decl *D) {
23231b52d63SJohannes Altmanninger     if (isNodeExcluded(Tree.AST.getSourceManager(), D))
233a75b2cacSAlex Lorenz       return true;
234a75b2cacSAlex Lorenz     auto SavedState = PreTraverse(D);
235a75b2cacSAlex Lorenz     RecursiveASTVisitor<PreorderVisitor>::TraverseDecl(D);
236a75b2cacSAlex Lorenz     PostTraverse(SavedState);
237a75b2cacSAlex Lorenz     return true;
238a75b2cacSAlex Lorenz   }
TraverseStmtclang::diff::__anonef34e5090211::PreorderVisitor239a75b2cacSAlex Lorenz   bool TraverseStmt(Stmt *S) {
240e64aee87SBruno Ricci     if (auto *E = dyn_cast_or_null<Expr>(S))
241e64aee87SBruno Ricci       S = E->IgnoreImplicit();
24231b52d63SJohannes Altmanninger     if (isNodeExcluded(Tree.AST.getSourceManager(), S))
243a75b2cacSAlex Lorenz       return true;
244a75b2cacSAlex Lorenz     auto SavedState = PreTraverse(S);
245a75b2cacSAlex Lorenz     RecursiveASTVisitor<PreorderVisitor>::TraverseStmt(S);
246a75b2cacSAlex Lorenz     PostTraverse(SavedState);
247a75b2cacSAlex Lorenz     return true;
248a75b2cacSAlex Lorenz   }
TraverseTypeclang::diff::__anonef34e5090211::PreorderVisitor249a75b2cacSAlex Lorenz   bool TraverseType(QualType T) { return true; }
TraverseConstructorInitializerclang::diff::__anonef34e5090211::PreorderVisitor25041395022SJohannes Altmanninger   bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
25141395022SJohannes Altmanninger     if (isNodeExcluded(Tree.AST.getSourceManager(), Init))
25241395022SJohannes Altmanninger       return true;
25341395022SJohannes Altmanninger     auto SavedState = PreTraverse(Init);
25441395022SJohannes Altmanninger     RecursiveASTVisitor<PreorderVisitor>::TraverseConstructorInitializer(Init);
25541395022SJohannes Altmanninger     PostTraverse(SavedState);
25641395022SJohannes Altmanninger     return true;
25741395022SJohannes Altmanninger   }
258a75b2cacSAlex Lorenz };
259a75b2cacSAlex Lorenz } // end anonymous namespace
260a75b2cacSAlex Lorenz 
Impl(SyntaxTree * Parent,ASTContext & AST)26141395022SJohannes Altmanninger SyntaxTree::Impl::Impl(SyntaxTree *Parent, ASTContext &AST)
26241395022SJohannes Altmanninger     : Parent(Parent), AST(AST), TypePP(AST.getLangOpts()) {
26341395022SJohannes Altmanninger   TypePP.AnonymousTagLocations = false;
26441395022SJohannes Altmanninger }
26541395022SJohannes Altmanninger 
Impl(SyntaxTree * Parent,Decl * N,ASTContext & AST)2662b955ffaSJohannes Altmanninger SyntaxTree::Impl::Impl(SyntaxTree *Parent, Decl *N, ASTContext &AST)
26741395022SJohannes Altmanninger     : Impl(Parent, AST) {
268a75b2cacSAlex Lorenz   PreorderVisitor PreorderWalker(*this);
269a75b2cacSAlex Lorenz   PreorderWalker.TraverseDecl(N);
270a75b2cacSAlex Lorenz   initTree();
271a75b2cacSAlex Lorenz }
272a75b2cacSAlex Lorenz 
Impl(SyntaxTree * Parent,Stmt * N,ASTContext & AST)2732b955ffaSJohannes Altmanninger SyntaxTree::Impl::Impl(SyntaxTree *Parent, Stmt *N, ASTContext &AST)
27441395022SJohannes Altmanninger     : Impl(Parent, AST) {
275a75b2cacSAlex Lorenz   PreorderVisitor PreorderWalker(*this);
276a75b2cacSAlex Lorenz   PreorderWalker.TraverseStmt(N);
277a75b2cacSAlex Lorenz   initTree();
278a75b2cacSAlex Lorenz }
279a75b2cacSAlex Lorenz 
getSubtreePostorder(const SyntaxTree::Impl & Tree,NodeId Root)28031b52d63SJohannes Altmanninger static std::vector<NodeId> getSubtreePostorder(const SyntaxTree::Impl &Tree,
281a75b2cacSAlex Lorenz                                                NodeId Root) {
282a75b2cacSAlex Lorenz   std::vector<NodeId> Postorder;
283a75b2cacSAlex Lorenz   std::function<void(NodeId)> Traverse = [&](NodeId Id) {
284a75b2cacSAlex Lorenz     const Node &N = Tree.getNode(Id);
285a75b2cacSAlex Lorenz     for (NodeId Child : N.Children)
286a75b2cacSAlex Lorenz       Traverse(Child);
287a75b2cacSAlex Lorenz     Postorder.push_back(Id);
288a75b2cacSAlex Lorenz   };
289a75b2cacSAlex Lorenz   Traverse(Root);
290a75b2cacSAlex Lorenz   return Postorder;
291a75b2cacSAlex Lorenz }
292a75b2cacSAlex Lorenz 
getSubtreeBfs(const SyntaxTree::Impl & Tree,NodeId Root)29331b52d63SJohannes Altmanninger static std::vector<NodeId> getSubtreeBfs(const SyntaxTree::Impl &Tree,
294a75b2cacSAlex Lorenz                                          NodeId Root) {
295a75b2cacSAlex Lorenz   std::vector<NodeId> Ids;
296a75b2cacSAlex Lorenz   size_t Expanded = 0;
297a75b2cacSAlex Lorenz   Ids.push_back(Root);
298a75b2cacSAlex Lorenz   while (Expanded < Ids.size())
299a75b2cacSAlex Lorenz     for (NodeId Child : Tree.getNode(Ids[Expanded++]).Children)
300a75b2cacSAlex Lorenz       Ids.push_back(Child);
301a75b2cacSAlex Lorenz   return Ids;
302a75b2cacSAlex Lorenz }
303a75b2cacSAlex Lorenz 
initTree()304e0fe5cd4SJohannes Altmanninger void SyntaxTree::Impl::initTree() {
305e0fe5cd4SJohannes Altmanninger   setLeftMostDescendants();
306e0fe5cd4SJohannes Altmanninger   int PostorderId = 0;
307e0fe5cd4SJohannes Altmanninger   PostorderIds.resize(getSize());
308e0fe5cd4SJohannes Altmanninger   std::function<void(NodeId)> PostorderTraverse = [&](NodeId Id) {
309e0fe5cd4SJohannes Altmanninger     for (NodeId Child : getNode(Id).Children)
310e0fe5cd4SJohannes Altmanninger       PostorderTraverse(Child);
311e0fe5cd4SJohannes Altmanninger     PostorderIds[Id] = PostorderId;
312e0fe5cd4SJohannes Altmanninger     ++PostorderId;
313e0fe5cd4SJohannes Altmanninger   };
314e0fe5cd4SJohannes Altmanninger   PostorderTraverse(getRootId());
315e0fe5cd4SJohannes Altmanninger   NodesBfs = getSubtreeBfs(*this, getRootId());
316e0fe5cd4SJohannes Altmanninger }
317e0fe5cd4SJohannes Altmanninger 
setLeftMostDescendants()318e0fe5cd4SJohannes Altmanninger void SyntaxTree::Impl::setLeftMostDescendants() {
319e0fe5cd4SJohannes Altmanninger   for (NodeId Leaf : Leaves) {
320e0fe5cd4SJohannes Altmanninger     getMutableNode(Leaf).LeftMostDescendant = Leaf;
321e0fe5cd4SJohannes Altmanninger     NodeId Parent, Cur = Leaf;
322e0fe5cd4SJohannes Altmanninger     while ((Parent = getNode(Cur).Parent).isValid() &&
323e0fe5cd4SJohannes Altmanninger            getNode(Parent).Children[0] == Cur) {
324e0fe5cd4SJohannes Altmanninger       Cur = Parent;
325e0fe5cd4SJohannes Altmanninger       getMutableNode(Cur).LeftMostDescendant = Leaf;
326e0fe5cd4SJohannes Altmanninger     }
327e0fe5cd4SJohannes Altmanninger   }
328e0fe5cd4SJohannes Altmanninger }
329e0fe5cd4SJohannes Altmanninger 
getNumberOfDescendants(NodeId Id) const33031b52d63SJohannes Altmanninger int SyntaxTree::Impl::getNumberOfDescendants(NodeId Id) const {
331a75b2cacSAlex Lorenz   return getNode(Id).RightMostDescendant - Id + 1;
332a75b2cacSAlex Lorenz }
333a75b2cacSAlex Lorenz 
isInSubtree(NodeId Id,NodeId SubtreeRoot) const33431b52d63SJohannes Altmanninger bool SyntaxTree::Impl::isInSubtree(NodeId Id, NodeId SubtreeRoot) const {
335fa524d7bSJohannes Altmanninger   return Id >= SubtreeRoot && Id <= getNode(SubtreeRoot).RightMostDescendant;
336a75b2cacSAlex Lorenz }
337a75b2cacSAlex Lorenz 
findPositionInParent(NodeId Id,bool Shifted) const338e0fe5cd4SJohannes Altmanninger int SyntaxTree::Impl::findPositionInParent(NodeId Id, bool Shifted) const {
339e0fe5cd4SJohannes Altmanninger   NodeId Parent = getNode(Id).Parent;
340e0fe5cd4SJohannes Altmanninger   if (Parent.isInvalid())
341e0fe5cd4SJohannes Altmanninger     return 0;
342e0fe5cd4SJohannes Altmanninger   const auto &Siblings = getNode(Parent).Children;
343e0fe5cd4SJohannes Altmanninger   int Position = 0;
344e0fe5cd4SJohannes Altmanninger   for (size_t I = 0, E = Siblings.size(); I < E; ++I) {
345e0fe5cd4SJohannes Altmanninger     if (Shifted)
346e0fe5cd4SJohannes Altmanninger       Position += getNode(Siblings[I]).Shift;
347e0fe5cd4SJohannes Altmanninger     if (Siblings[I] == Id) {
348e0fe5cd4SJohannes Altmanninger       Position += I;
349e0fe5cd4SJohannes Altmanninger       return Position;
350e0fe5cd4SJohannes Altmanninger     }
351e0fe5cd4SJohannes Altmanninger   }
352e0fe5cd4SJohannes Altmanninger   llvm_unreachable("Node not found in parent's children.");
35369774d67SJohannes Altmanninger }
35469774d67SJohannes Altmanninger 
3552b955ffaSJohannes Altmanninger // Returns the qualified name of ND. If it is subordinate to Context,
3562b955ffaSJohannes Altmanninger // then the prefix of the latter is removed from the returned value.
3572b955ffaSJohannes Altmanninger std::string
getRelativeName(const NamedDecl * ND,const DeclContext * Context) const3582b955ffaSJohannes Altmanninger SyntaxTree::Impl::getRelativeName(const NamedDecl *ND,
3592b955ffaSJohannes Altmanninger                                   const DeclContext *Context) const {
360bc7d817cSJohannes Altmanninger   std::string Val = ND->getQualifiedNameAsString();
3612b955ffaSJohannes Altmanninger   std::string ContextPrefix;
362bc7d817cSJohannes Altmanninger   if (!Context)
363bc7d817cSJohannes Altmanninger     return Val;
3642b955ffaSJohannes Altmanninger   if (auto *Namespace = dyn_cast<NamespaceDecl>(Context))
3652b955ffaSJohannes Altmanninger     ContextPrefix = Namespace->getQualifiedNameAsString();
3662b955ffaSJohannes Altmanninger   else if (auto *Record = dyn_cast<RecordDecl>(Context))
3672b955ffaSJohannes Altmanninger     ContextPrefix = Record->getQualifiedNameAsString();
3682b955ffaSJohannes Altmanninger   else if (AST.getLangOpts().CPlusPlus11)
3692b955ffaSJohannes Altmanninger     if (auto *Tag = dyn_cast<TagDecl>(Context))
3702b955ffaSJohannes Altmanninger       ContextPrefix = Tag->getQualifiedNameAsString();
3712a8c18d9SAlexander Kornienko   // Strip the qualifier, if Val refers to something in the current scope.
3722b955ffaSJohannes Altmanninger   // But leave one leading ':' in place, so that we know that this is a
3732b955ffaSJohannes Altmanninger   // relative path.
374f3dcc235SKazu Hirata   if (!ContextPrefix.empty() && StringRef(Val).starts_with(ContextPrefix))
3752b955ffaSJohannes Altmanninger     Val = Val.substr(ContextPrefix.size() + 1);
3762b955ffaSJohannes Altmanninger   return Val;
3772b955ffaSJohannes Altmanninger }
3782b955ffaSJohannes Altmanninger 
getRelativeName(const NamedDecl * ND) const3792b955ffaSJohannes Altmanninger std::string SyntaxTree::Impl::getRelativeName(const NamedDecl *ND) const {
3802b955ffaSJohannes Altmanninger   return getRelativeName(ND, ND->getDeclContext());
3812b955ffaSJohannes Altmanninger }
3822b955ffaSJohannes Altmanninger 
getEnclosingDeclContext(ASTContext & AST,const Stmt * S)3832b955ffaSJohannes Altmanninger static const DeclContext *getEnclosingDeclContext(ASTContext &AST,
3842b955ffaSJohannes Altmanninger                                                   const Stmt *S) {
3852b955ffaSJohannes Altmanninger   while (S) {
3862b955ffaSJohannes Altmanninger     const auto &Parents = AST.getParents(*S);
3872b955ffaSJohannes Altmanninger     if (Parents.empty())
3882b955ffaSJohannes Altmanninger       return nullptr;
3892b955ffaSJohannes Altmanninger     const auto &P = Parents[0];
3902b955ffaSJohannes Altmanninger     if (const auto *D = P.get<Decl>())
3912b955ffaSJohannes Altmanninger       return D->getDeclContext();
3922b955ffaSJohannes Altmanninger     S = P.get<Stmt>();
3932b955ffaSJohannes Altmanninger   }
394bc7d817cSJohannes Altmanninger   return nullptr;
3952b955ffaSJohannes Altmanninger }
3962b955ffaSJohannes Altmanninger 
getInitializerValue(const CXXCtorInitializer * Init,const PrintingPolicy & TypePP)39741395022SJohannes Altmanninger static std::string getInitializerValue(const CXXCtorInitializer *Init,
39841395022SJohannes Altmanninger                                        const PrintingPolicy &TypePP) {
39941395022SJohannes Altmanninger   if (Init->isAnyMemberInitializer())
400adcd0268SBenjamin Kramer     return std::string(Init->getAnyMember()->getName());
40141395022SJohannes Altmanninger   if (Init->isBaseInitializer())
40241395022SJohannes Altmanninger     return QualType(Init->getBaseClass(), 0).getAsString(TypePP);
40341395022SJohannes Altmanninger   if (Init->isDelegatingInitializer())
40441395022SJohannes Altmanninger     return Init->getTypeSourceInfo()->getType().getAsString(TypePP);
40541395022SJohannes Altmanninger   llvm_unreachable("Unknown initializer type");
40641395022SJohannes Altmanninger }
40741395022SJohannes Altmanninger 
getNodeValue(NodeId Id) const408e0fe5cd4SJohannes Altmanninger std::string SyntaxTree::Impl::getNodeValue(NodeId Id) const {
409e0fe5cd4SJohannes Altmanninger   return getNodeValue(getNode(Id));
410e0fe5cd4SJohannes Altmanninger }
411e0fe5cd4SJohannes Altmanninger 
getNodeValue(const Node & N) const412e0fe5cd4SJohannes Altmanninger std::string SyntaxTree::Impl::getNodeValue(const Node &N) const {
413e0fe5cd4SJohannes Altmanninger   const DynTypedNode &DTN = N.ASTNode;
4140dd86dc5SJohannes Altmanninger   if (auto *S = DTN.get<Stmt>())
4150dd86dc5SJohannes Altmanninger     return getStmtValue(S);
4160dd86dc5SJohannes Altmanninger   if (auto *D = DTN.get<Decl>())
4170dd86dc5SJohannes Altmanninger     return getDeclValue(D);
41841395022SJohannes Altmanninger   if (auto *Init = DTN.get<CXXCtorInitializer>())
41941395022SJohannes Altmanninger     return getInitializerValue(Init, TypePP);
4200dd86dc5SJohannes Altmanninger   llvm_unreachable("Fatal: unhandled AST node.\n");
4210dd86dc5SJohannes Altmanninger }
4220dd86dc5SJohannes Altmanninger 
getDeclValue(const Decl * D) const4230dd86dc5SJohannes Altmanninger std::string SyntaxTree::Impl::getDeclValue(const Decl *D) const {
4240dd86dc5SJohannes Altmanninger   std::string Value;
42541395022SJohannes Altmanninger   if (auto *V = dyn_cast<ValueDecl>(D))
42641395022SJohannes Altmanninger     return getRelativeName(V) + "(" + V->getType().getAsString(TypePP) + ")";
4270dd86dc5SJohannes Altmanninger   if (auto *N = dyn_cast<NamedDecl>(D))
4282b955ffaSJohannes Altmanninger     Value += getRelativeName(N) + ";";
4290dd86dc5SJohannes Altmanninger   if (auto *T = dyn_cast<TypedefNameDecl>(D))
4300dd86dc5SJohannes Altmanninger     return Value + T->getUnderlyingType().getAsString(TypePP) + ";";
4310dd86dc5SJohannes Altmanninger   if (auto *T = dyn_cast<TypeDecl>(D))
4320dd86dc5SJohannes Altmanninger     if (T->getTypeForDecl())
4330dd86dc5SJohannes Altmanninger       Value +=
4340dd86dc5SJohannes Altmanninger           T->getTypeForDecl()->getCanonicalTypeInternal().getAsString(TypePP) +
4350dd86dc5SJohannes Altmanninger           ";";
4360dd86dc5SJohannes Altmanninger   if (auto *U = dyn_cast<UsingDirectiveDecl>(D))
437adcd0268SBenjamin Kramer     return std::string(U->getNominatedNamespace()->getName());
4380dd86dc5SJohannes Altmanninger   if (auto *A = dyn_cast<AccessSpecDecl>(D)) {
4390dd86dc5SJohannes Altmanninger     CharSourceRange Range(A->getSourceRange(), false);
440adcd0268SBenjamin Kramer     return std::string(
441adcd0268SBenjamin Kramer         Lexer::getSourceText(Range, AST.getSourceManager(), AST.getLangOpts()));
442a75b2cacSAlex Lorenz   }
4430dd86dc5SJohannes Altmanninger   return Value;
4440dd86dc5SJohannes Altmanninger }
4450dd86dc5SJohannes Altmanninger 
getStmtValue(const Stmt * S) const4460dd86dc5SJohannes Altmanninger std::string SyntaxTree::Impl::getStmtValue(const Stmt *S) const {
4470dd86dc5SJohannes Altmanninger   if (auto *U = dyn_cast<UnaryOperator>(S))
448adcd0268SBenjamin Kramer     return std::string(UnaryOperator::getOpcodeStr(U->getOpcode()));
4490dd86dc5SJohannes Altmanninger   if (auto *B = dyn_cast<BinaryOperator>(S))
450adcd0268SBenjamin Kramer     return std::string(B->getOpcodeStr());
4510dd86dc5SJohannes Altmanninger   if (auto *M = dyn_cast<MemberExpr>(S))
4522b955ffaSJohannes Altmanninger     return getRelativeName(M->getMemberDecl());
4530dd86dc5SJohannes Altmanninger   if (auto *I = dyn_cast<IntegerLiteral>(S)) {
454a75b2cacSAlex Lorenz     SmallString<256> Str;
4550dd86dc5SJohannes Altmanninger     I->getValue().toString(Str, /*Radix=*/10, /*Signed=*/false);
456*9b2c25c7SKazu Hirata     return std::string(Str);
457a75b2cacSAlex Lorenz   }
4580dd86dc5SJohannes Altmanninger   if (auto *F = dyn_cast<FloatingLiteral>(S)) {
4590dd86dc5SJohannes Altmanninger     SmallString<256> Str;
4600dd86dc5SJohannes Altmanninger     F->getValue().toString(Str);
461*9b2c25c7SKazu Hirata     return std::string(Str);
462a75b2cacSAlex Lorenz   }
4630dd86dc5SJohannes Altmanninger   if (auto *D = dyn_cast<DeclRefExpr>(S))
4642b955ffaSJohannes Altmanninger     return getRelativeName(D->getDecl(), getEnclosingDeclContext(AST, S));
4657805ae25SDouglas Yung   if (auto *String = dyn_cast<StringLiteral>(S))
466adcd0268SBenjamin Kramer     return std::string(String->getString());
4670dd86dc5SJohannes Altmanninger   if (auto *B = dyn_cast<CXXBoolLiteralExpr>(S))
4680dd86dc5SJohannes Altmanninger     return B->getValue() ? "true" : "false";
469a75b2cacSAlex Lorenz   return "";
470a75b2cacSAlex Lorenz }
471a75b2cacSAlex Lorenz 
472a75b2cacSAlex Lorenz /// Identifies a node in a subtree by its postorder offset, starting at 1.
473a75b2cacSAlex Lorenz struct SNodeId {
474a75b2cacSAlex Lorenz   int Id = 0;
475a75b2cacSAlex Lorenz 
SNodeIdclang::diff::SNodeId476a75b2cacSAlex Lorenz   explicit SNodeId(int Id) : Id(Id) {}
477a75b2cacSAlex Lorenz   explicit SNodeId() = default;
478a75b2cacSAlex Lorenz 
operator intclang::diff::SNodeId479a75b2cacSAlex Lorenz   operator int() const { return Id; }
operator ++clang::diff::SNodeId480a75b2cacSAlex Lorenz   SNodeId &operator++() { return ++Id, *this; }
operator --clang::diff::SNodeId481a75b2cacSAlex Lorenz   SNodeId &operator--() { return --Id, *this; }
operator +clang::diff::SNodeId482a75b2cacSAlex Lorenz   SNodeId operator+(int Other) const { return SNodeId(Id + Other); }
483a75b2cacSAlex Lorenz };
484a75b2cacSAlex Lorenz 
485a75b2cacSAlex Lorenz class Subtree {
486a75b2cacSAlex Lorenz private:
487a75b2cacSAlex Lorenz   /// The parent tree.
48831b52d63SJohannes Altmanninger   const SyntaxTree::Impl &Tree;
489a75b2cacSAlex Lorenz   /// Maps SNodeIds to original ids.
490a75b2cacSAlex Lorenz   std::vector<NodeId> RootIds;
491a75b2cacSAlex Lorenz   /// Maps subtree nodes to their leftmost descendants wtihin the subtree.
492a75b2cacSAlex Lorenz   std::vector<SNodeId> LeftMostDescendants;
493a75b2cacSAlex Lorenz 
494a75b2cacSAlex Lorenz public:
495a75b2cacSAlex Lorenz   std::vector<SNodeId> KeyRoots;
496a75b2cacSAlex Lorenz 
Subtree(const SyntaxTree::Impl & Tree,NodeId SubtreeRoot)49731b52d63SJohannes Altmanninger   Subtree(const SyntaxTree::Impl &Tree, NodeId SubtreeRoot) : Tree(Tree) {
498a75b2cacSAlex Lorenz     RootIds = getSubtreePostorder(Tree, SubtreeRoot);
499a75b2cacSAlex Lorenz     int NumLeaves = setLeftMostDescendants();
500a75b2cacSAlex Lorenz     computeKeyRoots(NumLeaves);
501a75b2cacSAlex Lorenz   }
getSize() const502a75b2cacSAlex Lorenz   int getSize() const { return RootIds.size(); }
getIdInRoot(SNodeId Id) const503a75b2cacSAlex Lorenz   NodeId getIdInRoot(SNodeId Id) const {
504a75b2cacSAlex Lorenz     assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
505a75b2cacSAlex Lorenz     return RootIds[Id - 1];
506a75b2cacSAlex Lorenz   }
getNode(SNodeId Id) const507a75b2cacSAlex Lorenz   const Node &getNode(SNodeId Id) const {
508a75b2cacSAlex Lorenz     return Tree.getNode(getIdInRoot(Id));
509a75b2cacSAlex Lorenz   }
getLeftMostDescendant(SNodeId Id) const510a75b2cacSAlex Lorenz   SNodeId getLeftMostDescendant(SNodeId Id) const {
511a75b2cacSAlex Lorenz     assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
512a75b2cacSAlex Lorenz     return LeftMostDescendants[Id - 1];
513a75b2cacSAlex Lorenz   }
514a75b2cacSAlex Lorenz   /// Returns the postorder index of the leftmost descendant in the subtree.
getPostorderOffset() const515a75b2cacSAlex Lorenz   NodeId getPostorderOffset() const {
516a75b2cacSAlex Lorenz     return Tree.PostorderIds[getIdInRoot(SNodeId(1))];
517a75b2cacSAlex Lorenz   }
getNodeValue(SNodeId Id) const5188b0e0663SJohannes Altmanninger   std::string getNodeValue(SNodeId Id) const {
51931b52d63SJohannes Altmanninger     return Tree.getNodeValue(getIdInRoot(Id));
5208b0e0663SJohannes Altmanninger   }
521a75b2cacSAlex Lorenz 
522a75b2cacSAlex Lorenz private:
523a75b2cacSAlex Lorenz   /// Returns the number of leafs in the subtree.
setLeftMostDescendants()524a75b2cacSAlex Lorenz   int setLeftMostDescendants() {
525a75b2cacSAlex Lorenz     int NumLeaves = 0;
526a75b2cacSAlex Lorenz     LeftMostDescendants.resize(getSize());
527a75b2cacSAlex Lorenz     for (int I = 0; I < getSize(); ++I) {
528a75b2cacSAlex Lorenz       SNodeId SI(I + 1);
529a75b2cacSAlex Lorenz       const Node &N = getNode(SI);
530a75b2cacSAlex Lorenz       NumLeaves += N.isLeaf();
531a75b2cacSAlex Lorenz       assert(I == Tree.PostorderIds[getIdInRoot(SI)] - getPostorderOffset() &&
532a75b2cacSAlex Lorenz              "Postorder traversal in subtree should correspond to traversal in "
533a75b2cacSAlex Lorenz              "the root tree by a constant offset.");
534a75b2cacSAlex Lorenz       LeftMostDescendants[I] = SNodeId(Tree.PostorderIds[N.LeftMostDescendant] -
535a75b2cacSAlex Lorenz                                        getPostorderOffset());
536a75b2cacSAlex Lorenz     }
537a75b2cacSAlex Lorenz     return NumLeaves;
538a75b2cacSAlex Lorenz   }
computeKeyRoots(int Leaves)539a75b2cacSAlex Lorenz   void computeKeyRoots(int Leaves) {
540a75b2cacSAlex Lorenz     KeyRoots.resize(Leaves);
541a75b2cacSAlex Lorenz     std::unordered_set<int> Visited;
542a75b2cacSAlex Lorenz     int K = Leaves - 1;
543a75b2cacSAlex Lorenz     for (SNodeId I(getSize()); I > 0; --I) {
544a75b2cacSAlex Lorenz       SNodeId LeftDesc = getLeftMostDescendant(I);
545a75b2cacSAlex Lorenz       if (Visited.count(LeftDesc))
546a75b2cacSAlex Lorenz         continue;
547a75b2cacSAlex Lorenz       assert(K >= 0 && "K should be non-negative");
548a75b2cacSAlex Lorenz       KeyRoots[K] = I;
549a75b2cacSAlex Lorenz       Visited.insert(LeftDesc);
550a75b2cacSAlex Lorenz       --K;
551a75b2cacSAlex Lorenz     }
552a75b2cacSAlex Lorenz   }
553a75b2cacSAlex Lorenz };
554a75b2cacSAlex Lorenz 
555a75b2cacSAlex Lorenz /// Implementation of Zhang and Shasha's Algorithm for tree edit distance.
556a75b2cacSAlex Lorenz /// Computes an optimal mapping between two trees using only insertion,
557a75b2cacSAlex Lorenz /// deletion and update as edit actions (similar to the Levenshtein distance).
558a75b2cacSAlex Lorenz class ZhangShashaMatcher {
559a75b2cacSAlex Lorenz   const ASTDiff::Impl &DiffImpl;
560a75b2cacSAlex Lorenz   Subtree S1;
561a75b2cacSAlex Lorenz   Subtree S2;
562a75b2cacSAlex Lorenz   std::unique_ptr<std::unique_ptr<double[]>[]> TreeDist, ForestDist;
563a75b2cacSAlex Lorenz 
564a75b2cacSAlex Lorenz public:
ZhangShashaMatcher(const ASTDiff::Impl & DiffImpl,const SyntaxTree::Impl & T1,const SyntaxTree::Impl & T2,NodeId Id1,NodeId Id2)56531b52d63SJohannes Altmanninger   ZhangShashaMatcher(const ASTDiff::Impl &DiffImpl, const SyntaxTree::Impl &T1,
56631b52d63SJohannes Altmanninger                      const SyntaxTree::Impl &T2, NodeId Id1, NodeId Id2)
567a75b2cacSAlex Lorenz       : DiffImpl(DiffImpl), S1(T1, Id1), S2(T2, Id2) {
5682b3d49b6SJonas Devlieghere     TreeDist = std::make_unique<std::unique_ptr<double[]>[]>(
569a75b2cacSAlex Lorenz         size_t(S1.getSize()) + 1);
5702b3d49b6SJonas Devlieghere     ForestDist = std::make_unique<std::unique_ptr<double[]>[]>(
571a75b2cacSAlex Lorenz         size_t(S1.getSize()) + 1);
572a75b2cacSAlex Lorenz     for (int I = 0, E = S1.getSize() + 1; I < E; ++I) {
5732b3d49b6SJonas Devlieghere       TreeDist[I] = std::make_unique<double[]>(size_t(S2.getSize()) + 1);
5742b3d49b6SJonas Devlieghere       ForestDist[I] = std::make_unique<double[]>(size_t(S2.getSize()) + 1);
575a75b2cacSAlex Lorenz     }
576a75b2cacSAlex Lorenz   }
577a75b2cacSAlex Lorenz 
getMatchingNodes()578a75b2cacSAlex Lorenz   std::vector<std::pair<NodeId, NodeId>> getMatchingNodes() {
579a75b2cacSAlex Lorenz     std::vector<std::pair<NodeId, NodeId>> Matches;
580a75b2cacSAlex Lorenz     std::vector<std::pair<SNodeId, SNodeId>> TreePairs;
581a75b2cacSAlex Lorenz 
582a75b2cacSAlex Lorenz     computeTreeDist();
583a75b2cacSAlex Lorenz 
584a75b2cacSAlex Lorenz     bool RootNodePair = true;
585a75b2cacSAlex Lorenz 
5864c0a8660SAlex Lorenz     TreePairs.emplace_back(SNodeId(S1.getSize()), SNodeId(S2.getSize()));
587a75b2cacSAlex Lorenz 
588a75b2cacSAlex Lorenz     while (!TreePairs.empty()) {
589a75b2cacSAlex Lorenz       SNodeId LastRow, LastCol, FirstRow, FirstCol, Row, Col;
590a75b2cacSAlex Lorenz       std::tie(LastRow, LastCol) = TreePairs.back();
591a75b2cacSAlex Lorenz       TreePairs.pop_back();
592a75b2cacSAlex Lorenz 
593a75b2cacSAlex Lorenz       if (!RootNodePair) {
594a75b2cacSAlex Lorenz         computeForestDist(LastRow, LastCol);
595a75b2cacSAlex Lorenz       }
596a75b2cacSAlex Lorenz 
597a75b2cacSAlex Lorenz       RootNodePair = false;
598a75b2cacSAlex Lorenz 
599a75b2cacSAlex Lorenz       FirstRow = S1.getLeftMostDescendant(LastRow);
600a75b2cacSAlex Lorenz       FirstCol = S2.getLeftMostDescendant(LastCol);
601a75b2cacSAlex Lorenz 
602a75b2cacSAlex Lorenz       Row = LastRow;
603a75b2cacSAlex Lorenz       Col = LastCol;
604a75b2cacSAlex Lorenz 
605a75b2cacSAlex Lorenz       while (Row > FirstRow || Col > FirstCol) {
606a75b2cacSAlex Lorenz         if (Row > FirstRow &&
607a75b2cacSAlex Lorenz             ForestDist[Row - 1][Col] + 1 == ForestDist[Row][Col]) {
608a75b2cacSAlex Lorenz           --Row;
609a75b2cacSAlex Lorenz         } else if (Col > FirstCol &&
610a75b2cacSAlex Lorenz                    ForestDist[Row][Col - 1] + 1 == ForestDist[Row][Col]) {
611a75b2cacSAlex Lorenz           --Col;
612a75b2cacSAlex Lorenz         } else {
613a75b2cacSAlex Lorenz           SNodeId LMD1 = S1.getLeftMostDescendant(Row);
614a75b2cacSAlex Lorenz           SNodeId LMD2 = S2.getLeftMostDescendant(Col);
615a75b2cacSAlex Lorenz           if (LMD1 == S1.getLeftMostDescendant(LastRow) &&
616a75b2cacSAlex Lorenz               LMD2 == S2.getLeftMostDescendant(LastCol)) {
617a75b2cacSAlex Lorenz             NodeId Id1 = S1.getIdInRoot(Row);
618a75b2cacSAlex Lorenz             NodeId Id2 = S2.getIdInRoot(Col);
619a75b2cacSAlex Lorenz             assert(DiffImpl.isMatchingPossible(Id1, Id2) &&
620a75b2cacSAlex Lorenz                    "These nodes must not be matched.");
621a75b2cacSAlex Lorenz             Matches.emplace_back(Id1, Id2);
622a75b2cacSAlex Lorenz             --Row;
623a75b2cacSAlex Lorenz             --Col;
624a75b2cacSAlex Lorenz           } else {
625a75b2cacSAlex Lorenz             TreePairs.emplace_back(Row, Col);
626a75b2cacSAlex Lorenz             Row = LMD1;
627a75b2cacSAlex Lorenz             Col = LMD2;
628a75b2cacSAlex Lorenz           }
629a75b2cacSAlex Lorenz         }
630a75b2cacSAlex Lorenz       }
631a75b2cacSAlex Lorenz     }
632a75b2cacSAlex Lorenz     return Matches;
633a75b2cacSAlex Lorenz   }
634a75b2cacSAlex Lorenz 
635a75b2cacSAlex Lorenz private:
636fa524d7bSJohannes Altmanninger   /// We use a simple cost model for edit actions, which seems good enough.
637fa524d7bSJohannes Altmanninger   /// Simple cost model for edit actions. This seems to make the matching
638fa524d7bSJohannes Altmanninger   /// algorithm perform reasonably well.
639a75b2cacSAlex Lorenz   /// The values range between 0 and 1, or infinity if this edit action should
640a75b2cacSAlex Lorenz   /// always be avoided.
641a75b2cacSAlex Lorenz   static constexpr double DeletionCost = 1;
642a75b2cacSAlex Lorenz   static constexpr double InsertionCost = 1;
643a75b2cacSAlex Lorenz 
getUpdateCost(SNodeId Id1,SNodeId Id2)644a75b2cacSAlex Lorenz   double getUpdateCost(SNodeId Id1, SNodeId Id2) {
6458b0e0663SJohannes Altmanninger     if (!DiffImpl.isMatchingPossible(S1.getIdInRoot(Id1), S2.getIdInRoot(Id2)))
646a75b2cacSAlex Lorenz       return std::numeric_limits<double>::max();
6478b0e0663SJohannes Altmanninger     return S1.getNodeValue(Id1) != S2.getNodeValue(Id2);
648a75b2cacSAlex Lorenz   }
649a75b2cacSAlex Lorenz 
computeTreeDist()650a75b2cacSAlex Lorenz   void computeTreeDist() {
651a75b2cacSAlex Lorenz     for (SNodeId Id1 : S1.KeyRoots)
652a75b2cacSAlex Lorenz       for (SNodeId Id2 : S2.KeyRoots)
653a75b2cacSAlex Lorenz         computeForestDist(Id1, Id2);
654a75b2cacSAlex Lorenz   }
655a75b2cacSAlex Lorenz 
computeForestDist(SNodeId Id1,SNodeId Id2)656a75b2cacSAlex Lorenz   void computeForestDist(SNodeId Id1, SNodeId Id2) {
657a75b2cacSAlex Lorenz     assert(Id1 > 0 && Id2 > 0 && "Expecting offsets greater than 0.");
658a75b2cacSAlex Lorenz     SNodeId LMD1 = S1.getLeftMostDescendant(Id1);
659a75b2cacSAlex Lorenz     SNodeId LMD2 = S2.getLeftMostDescendant(Id2);
660a75b2cacSAlex Lorenz 
661a75b2cacSAlex Lorenz     ForestDist[LMD1][LMD2] = 0;
662a75b2cacSAlex Lorenz     for (SNodeId D1 = LMD1 + 1; D1 <= Id1; ++D1) {
663a75b2cacSAlex Lorenz       ForestDist[D1][LMD2] = ForestDist[D1 - 1][LMD2] + DeletionCost;
664a75b2cacSAlex Lorenz       for (SNodeId D2 = LMD2 + 1; D2 <= Id2; ++D2) {
665a75b2cacSAlex Lorenz         ForestDist[LMD1][D2] = ForestDist[LMD1][D2 - 1] + InsertionCost;
666a75b2cacSAlex Lorenz         SNodeId DLMD1 = S1.getLeftMostDescendant(D1);
667a75b2cacSAlex Lorenz         SNodeId DLMD2 = S2.getLeftMostDescendant(D2);
668a75b2cacSAlex Lorenz         if (DLMD1 == LMD1 && DLMD2 == LMD2) {
669a75b2cacSAlex Lorenz           double UpdateCost = getUpdateCost(D1, D2);
670a75b2cacSAlex Lorenz           ForestDist[D1][D2] =
671a75b2cacSAlex Lorenz               std::min({ForestDist[D1 - 1][D2] + DeletionCost,
672a75b2cacSAlex Lorenz                         ForestDist[D1][D2 - 1] + InsertionCost,
673a75b2cacSAlex Lorenz                         ForestDist[D1 - 1][D2 - 1] + UpdateCost});
674a75b2cacSAlex Lorenz           TreeDist[D1][D2] = ForestDist[D1][D2];
675a75b2cacSAlex Lorenz         } else {
676a75b2cacSAlex Lorenz           ForestDist[D1][D2] =
677a75b2cacSAlex Lorenz               std::min({ForestDist[D1 - 1][D2] + DeletionCost,
678a75b2cacSAlex Lorenz                         ForestDist[D1][D2 - 1] + InsertionCost,
679a75b2cacSAlex Lorenz                         ForestDist[DLMD1][DLMD2] + TreeDist[D1][D2]});
680a75b2cacSAlex Lorenz         }
681a75b2cacSAlex Lorenz       }
682a75b2cacSAlex Lorenz     }
683a75b2cacSAlex Lorenz   }
684a75b2cacSAlex Lorenz };
685a75b2cacSAlex Lorenz 
getType() const686cd625114SReid Kleckner ASTNodeKind Node::getType() const { return ASTNode.getNodeKind(); }
6870da12c84SJohannes Altmanninger 
getTypeLabel() const6880da12c84SJohannes Altmanninger StringRef Node::getTypeLabel() const { return getType().asStringRef(); }
6890da12c84SJohannes Altmanninger 
getQualifiedIdentifier() const6906ad0788cSKazu Hirata std::optional<std::string> Node::getQualifiedIdentifier() const {
6910dd86dc5SJohannes Altmanninger   if (auto *ND = ASTNode.get<NamedDecl>()) {
6920dd86dc5SJohannes Altmanninger     if (ND->getDeclName().isIdentifier())
6930dd86dc5SJohannes Altmanninger       return ND->getQualifiedNameAsString();
6940dd86dc5SJohannes Altmanninger   }
6955891420eSKazu Hirata   return std::nullopt;
6960dd86dc5SJohannes Altmanninger }
6970dd86dc5SJohannes Altmanninger 
getIdentifier() const6986ad0788cSKazu Hirata std::optional<StringRef> Node::getIdentifier() const {
6990dd86dc5SJohannes Altmanninger   if (auto *ND = ASTNode.get<NamedDecl>()) {
7000dd86dc5SJohannes Altmanninger     if (ND->getDeclName().isIdentifier())
7010dd86dc5SJohannes Altmanninger       return ND->getName();
7020dd86dc5SJohannes Altmanninger   }
7035891420eSKazu Hirata   return std::nullopt;
7040dd86dc5SJohannes Altmanninger }
7050dd86dc5SJohannes Altmanninger 
706a75b2cacSAlex Lorenz namespace {
707a75b2cacSAlex Lorenz // Compares nodes by their depth.
708a75b2cacSAlex Lorenz struct HeightLess {
70931b52d63SJohannes Altmanninger   const SyntaxTree::Impl &Tree;
HeightLessclang::diff::__anonef34e5090511::HeightLess71031b52d63SJohannes Altmanninger   HeightLess(const SyntaxTree::Impl &Tree) : Tree(Tree) {}
operator ()clang::diff::__anonef34e5090511::HeightLess711a75b2cacSAlex Lorenz   bool operator()(NodeId Id1, NodeId Id2) const {
712a75b2cacSAlex Lorenz     return Tree.getNode(Id1).Height < Tree.getNode(Id2).Height;
713a75b2cacSAlex Lorenz   }
714a75b2cacSAlex Lorenz };
715a75b2cacSAlex Lorenz } // end anonymous namespace
716a75b2cacSAlex Lorenz 
717fa524d7bSJohannes Altmanninger namespace {
718a75b2cacSAlex Lorenz // Priority queue for nodes, sorted descendingly by their height.
719a75b2cacSAlex Lorenz class PriorityList {
72031b52d63SJohannes Altmanninger   const SyntaxTree::Impl &Tree;
721a75b2cacSAlex Lorenz   HeightLess Cmp;
722a75b2cacSAlex Lorenz   std::vector<NodeId> Container;
723a75b2cacSAlex Lorenz   PriorityQueue<NodeId, std::vector<NodeId>, HeightLess> List;
724a75b2cacSAlex Lorenz 
725a75b2cacSAlex Lorenz public:
PriorityList(const SyntaxTree::Impl & Tree)72631b52d63SJohannes Altmanninger   PriorityList(const SyntaxTree::Impl &Tree)
727a75b2cacSAlex Lorenz       : Tree(Tree), Cmp(Tree), List(Cmp, Container) {}
728a75b2cacSAlex Lorenz 
push(NodeId id)729a75b2cacSAlex Lorenz   void push(NodeId id) { List.push(id); }
730a75b2cacSAlex Lorenz 
pop()731a75b2cacSAlex Lorenz   std::vector<NodeId> pop() {
732a75b2cacSAlex Lorenz     int Max = peekMax();
733a75b2cacSAlex Lorenz     std::vector<NodeId> Result;
734a75b2cacSAlex Lorenz     if (Max == 0)
735a75b2cacSAlex Lorenz       return Result;
736a75b2cacSAlex Lorenz     while (peekMax() == Max) {
737a75b2cacSAlex Lorenz       Result.push_back(List.top());
738a75b2cacSAlex Lorenz       List.pop();
739a75b2cacSAlex Lorenz     }
740a75b2cacSAlex Lorenz     // TODO this is here to get a stable output, not a good heuristic
74155fab260SFangrui Song     llvm::sort(Result);
742a75b2cacSAlex Lorenz     return Result;
743a75b2cacSAlex Lorenz   }
peekMax() const744a75b2cacSAlex Lorenz   int peekMax() const {
745a75b2cacSAlex Lorenz     if (List.empty())
746a75b2cacSAlex Lorenz       return 0;
747a75b2cacSAlex Lorenz     return Tree.getNode(List.top()).Height;
748a75b2cacSAlex Lorenz   }
open(NodeId Id)749a75b2cacSAlex Lorenz   void open(NodeId Id) {
750a75b2cacSAlex Lorenz     for (NodeId Child : Tree.getNode(Id).Children)
751a75b2cacSAlex Lorenz       push(Child);
752a75b2cacSAlex Lorenz   }
753a75b2cacSAlex Lorenz };
754fa524d7bSJohannes Altmanninger } // end anonymous namespace
755a75b2cacSAlex Lorenz 
identical(NodeId Id1,NodeId Id2) const75631b52d63SJohannes Altmanninger bool ASTDiff::Impl::identical(NodeId Id1, NodeId Id2) const {
757a75b2cacSAlex Lorenz   const Node &N1 = T1.getNode(Id1);
758a75b2cacSAlex Lorenz   const Node &N2 = T2.getNode(Id2);
759a75b2cacSAlex Lorenz   if (N1.Children.size() != N2.Children.size() ||
760a75b2cacSAlex Lorenz       !isMatchingPossible(Id1, Id2) ||
76131b52d63SJohannes Altmanninger       T1.getNodeValue(Id1) != T2.getNodeValue(Id2))
762a75b2cacSAlex Lorenz     return false;
763a75b2cacSAlex Lorenz   for (size_t Id = 0, E = N1.Children.size(); Id < E; ++Id)
76431b52d63SJohannes Altmanninger     if (!identical(N1.Children[Id], N2.Children[Id]))
765a75b2cacSAlex Lorenz       return false;
766a75b2cacSAlex Lorenz   return true;
767a75b2cacSAlex Lorenz }
768a75b2cacSAlex Lorenz 
isMatchingPossible(NodeId Id1,NodeId Id2) const769a75b2cacSAlex Lorenz bool ASTDiff::Impl::isMatchingPossible(NodeId Id1, NodeId Id2) const {
770e0fe5cd4SJohannes Altmanninger   return Options.isMatchingAllowed(T1.getNode(Id1), T2.getNode(Id2));
771e0fe5cd4SJohannes Altmanninger }
772e0fe5cd4SJohannes Altmanninger 
haveSameParents(const Mapping & M,NodeId Id1,NodeId Id2) const773e0fe5cd4SJohannes Altmanninger bool ASTDiff::Impl::haveSameParents(const Mapping &M, NodeId Id1,
774e0fe5cd4SJohannes Altmanninger                                     NodeId Id2) const {
775e0fe5cd4SJohannes Altmanninger   NodeId P1 = T1.getNode(Id1).Parent;
776e0fe5cd4SJohannes Altmanninger   NodeId P2 = T2.getNode(Id2).Parent;
777e0fe5cd4SJohannes Altmanninger   return (P1.isInvalid() && P2.isInvalid()) ||
778e0fe5cd4SJohannes Altmanninger          (P1.isValid() && P2.isValid() && M.getDst(P1) == P2);
779a75b2cacSAlex Lorenz }
780a75b2cacSAlex Lorenz 
addOptimalMapping(Mapping & M,NodeId Id1,NodeId Id2) const781a75b2cacSAlex Lorenz void ASTDiff::Impl::addOptimalMapping(Mapping &M, NodeId Id1,
782a75b2cacSAlex Lorenz                                       NodeId Id2) const {
783d1969307SJohannes Altmanninger   if (std::max(T1.getNumberOfDescendants(Id1), T2.getNumberOfDescendants(Id2)) >
784d1969307SJohannes Altmanninger       Options.MaxSize)
785a75b2cacSAlex Lorenz     return;
786a75b2cacSAlex Lorenz   ZhangShashaMatcher Matcher(*this, T1, T2, Id1, Id2);
787a75b2cacSAlex Lorenz   std::vector<std::pair<NodeId, NodeId>> R = Matcher.getMatchingNodes();
7888dc7b982SMark de Wever   for (const auto &Tuple : R) {
789a75b2cacSAlex Lorenz     NodeId Src = Tuple.first;
790a75b2cacSAlex Lorenz     NodeId Dst = Tuple.second;
79151321aefSJohannes Altmanninger     if (!M.hasSrc(Src) && !M.hasDst(Dst))
792a75b2cacSAlex Lorenz       M.link(Src, Dst);
793a75b2cacSAlex Lorenz   }
794a75b2cacSAlex Lorenz }
795a75b2cacSAlex Lorenz 
getJaccardSimilarity(const Mapping & M,NodeId Id1,NodeId Id2) const796d1969307SJohannes Altmanninger double ASTDiff::Impl::getJaccardSimilarity(const Mapping &M, NodeId Id1,
797a75b2cacSAlex Lorenz                                            NodeId Id2) const {
798a75b2cacSAlex Lorenz   int CommonDescendants = 0;
799a75b2cacSAlex Lorenz   const Node &N1 = T1.getNode(Id1);
800d1969307SJohannes Altmanninger   // Count the common descendants, excluding the subtree root.
801d1969307SJohannes Altmanninger   for (NodeId Src = Id1 + 1; Src <= N1.RightMostDescendant; ++Src) {
802d1969307SJohannes Altmanninger     NodeId Dst = M.getDst(Src);
803d1969307SJohannes Altmanninger     CommonDescendants += int(Dst.isValid() && T2.isInSubtree(Dst, Id2));
804d1969307SJohannes Altmanninger   }
805d1969307SJohannes Altmanninger   // We need to subtract 1 to get the number of descendants excluding the root.
806d1969307SJohannes Altmanninger   double Denominator = T1.getNumberOfDescendants(Id1) - 1 +
807d1969307SJohannes Altmanninger                        T2.getNumberOfDescendants(Id2) - 1 - CommonDescendants;
808d1969307SJohannes Altmanninger   // CommonDescendants is less than the size of one subtree.
809d1969307SJohannes Altmanninger   assert(Denominator >= 0 && "Expected non-negative denominator.");
810d1969307SJohannes Altmanninger   if (Denominator == 0)
811d1969307SJohannes Altmanninger     return 0;
812d1969307SJohannes Altmanninger   return CommonDescendants / Denominator;
813a75b2cacSAlex Lorenz }
814a75b2cacSAlex Lorenz 
findCandidate(const Mapping & M,NodeId Id1) const815a75b2cacSAlex Lorenz NodeId ASTDiff::Impl::findCandidate(const Mapping &M, NodeId Id1) const {
816a75b2cacSAlex Lorenz   NodeId Candidate;
81731b52d63SJohannes Altmanninger   double HighestSimilarity = 0.0;
818e0fe5cd4SJohannes Altmanninger   for (NodeId Id2 : T2) {
819a75b2cacSAlex Lorenz     if (!isMatchingPossible(Id1, Id2))
820a75b2cacSAlex Lorenz       continue;
821a75b2cacSAlex Lorenz     if (M.hasDst(Id2))
822a75b2cacSAlex Lorenz       continue;
823d1969307SJohannes Altmanninger     double Similarity = getJaccardSimilarity(M, Id1, Id2);
824fa524d7bSJohannes Altmanninger     if (Similarity >= Options.MinSimilarity && Similarity > HighestSimilarity) {
82531b52d63SJohannes Altmanninger       HighestSimilarity = Similarity;
826a75b2cacSAlex Lorenz       Candidate = Id2;
827a75b2cacSAlex Lorenz     }
828a75b2cacSAlex Lorenz   }
829a75b2cacSAlex Lorenz   return Candidate;
830a75b2cacSAlex Lorenz }
831a75b2cacSAlex Lorenz 
matchBottomUp(Mapping & M) const832a75b2cacSAlex Lorenz void ASTDiff::Impl::matchBottomUp(Mapping &M) const {
83331b52d63SJohannes Altmanninger   std::vector<NodeId> Postorder = getSubtreePostorder(T1, T1.getRootId());
834a75b2cacSAlex Lorenz   for (NodeId Id1 : Postorder) {
835fa524d7bSJohannes Altmanninger     if (Id1 == T1.getRootId() && !M.hasSrc(T1.getRootId()) &&
836fa524d7bSJohannes Altmanninger         !M.hasDst(T2.getRootId())) {
83731b52d63SJohannes Altmanninger       if (isMatchingPossible(T1.getRootId(), T2.getRootId())) {
83831b52d63SJohannes Altmanninger         M.link(T1.getRootId(), T2.getRootId());
83931b52d63SJohannes Altmanninger         addOptimalMapping(M, T1.getRootId(), T2.getRootId());
840a75b2cacSAlex Lorenz       }
841a75b2cacSAlex Lorenz       break;
842a75b2cacSAlex Lorenz     }
843a75b2cacSAlex Lorenz     bool Matched = M.hasSrc(Id1);
844d1969307SJohannes Altmanninger     const Node &N1 = T1.getNode(Id1);
8453117b17bSFangrui Song     bool MatchedChildren = llvm::any_of(
8463117b17bSFangrui Song         N1.Children, [&](NodeId Child) { return M.hasSrc(Child); });
847a75b2cacSAlex Lorenz     if (Matched || !MatchedChildren)
848a75b2cacSAlex Lorenz       continue;
849a75b2cacSAlex Lorenz     NodeId Id2 = findCandidate(M, Id1);
85051321aefSJohannes Altmanninger     if (Id2.isValid()) {
851a75b2cacSAlex Lorenz       M.link(Id1, Id2);
852a75b2cacSAlex Lorenz       addOptimalMapping(M, Id1, Id2);
853a75b2cacSAlex Lorenz     }
854a75b2cacSAlex Lorenz   }
855fa524d7bSJohannes Altmanninger }
856a75b2cacSAlex Lorenz 
matchTopDown() const857a75b2cacSAlex Lorenz Mapping ASTDiff::Impl::matchTopDown() const {
858a75b2cacSAlex Lorenz   PriorityList L1(T1);
859a75b2cacSAlex Lorenz   PriorityList L2(T2);
860a75b2cacSAlex Lorenz 
86151321aefSJohannes Altmanninger   Mapping M(T1.getSize() + T2.getSize());
862a75b2cacSAlex Lorenz 
86331b52d63SJohannes Altmanninger   L1.push(T1.getRootId());
86431b52d63SJohannes Altmanninger   L2.push(T2.getRootId());
865a75b2cacSAlex Lorenz 
866a75b2cacSAlex Lorenz   int Max1, Max2;
867a75b2cacSAlex Lorenz   while (std::min(Max1 = L1.peekMax(), Max2 = L2.peekMax()) >
868a75b2cacSAlex Lorenz          Options.MinHeight) {
869a75b2cacSAlex Lorenz     if (Max1 > Max2) {
870a75b2cacSAlex Lorenz       for (NodeId Id : L1.pop())
871a75b2cacSAlex Lorenz         L1.open(Id);
872a75b2cacSAlex Lorenz       continue;
873a75b2cacSAlex Lorenz     }
874a75b2cacSAlex Lorenz     if (Max2 > Max1) {
875a75b2cacSAlex Lorenz       for (NodeId Id : L2.pop())
876a75b2cacSAlex Lorenz         L2.open(Id);
877a75b2cacSAlex Lorenz       continue;
878a75b2cacSAlex Lorenz     }
879a75b2cacSAlex Lorenz     std::vector<NodeId> H1, H2;
880a75b2cacSAlex Lorenz     H1 = L1.pop();
881a75b2cacSAlex Lorenz     H2 = L2.pop();
882a75b2cacSAlex Lorenz     for (NodeId Id1 : H1) {
883fa524d7bSJohannes Altmanninger       for (NodeId Id2 : H2) {
88451321aefSJohannes Altmanninger         if (identical(Id1, Id2) && !M.hasSrc(Id1) && !M.hasDst(Id2)) {
885fa524d7bSJohannes Altmanninger           for (int I = 0, E = T1.getNumberOfDescendants(Id1); I < E; ++I)
886fa524d7bSJohannes Altmanninger             M.link(Id1 + I, Id2 + I);
887fa524d7bSJohannes Altmanninger         }
888fa524d7bSJohannes Altmanninger       }
889a75b2cacSAlex Lorenz     }
890a75b2cacSAlex Lorenz     for (NodeId Id1 : H1) {
891a75b2cacSAlex Lorenz       if (!M.hasSrc(Id1))
892a75b2cacSAlex Lorenz         L1.open(Id1);
893a75b2cacSAlex Lorenz     }
894a75b2cacSAlex Lorenz     for (NodeId Id2 : H2) {
895a75b2cacSAlex Lorenz       if (!M.hasDst(Id2))
896a75b2cacSAlex Lorenz         L2.open(Id2);
897a75b2cacSAlex Lorenz     }
898a75b2cacSAlex Lorenz   }
899a75b2cacSAlex Lorenz   return M;
900a75b2cacSAlex Lorenz }
901a75b2cacSAlex Lorenz 
Impl(SyntaxTree::Impl & T1,SyntaxTree::Impl & T2,const ComparisonOptions & Options)902e0fe5cd4SJohannes Altmanninger ASTDiff::Impl::Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
903e0fe5cd4SJohannes Altmanninger                     const ComparisonOptions &Options)
904e0fe5cd4SJohannes Altmanninger     : T1(T1), T2(T2), Options(Options) {
905e0fe5cd4SJohannes Altmanninger   computeMapping();
906e0fe5cd4SJohannes Altmanninger   computeChangeKinds(TheMapping);
907e0fe5cd4SJohannes Altmanninger }
908e0fe5cd4SJohannes Altmanninger 
computeMapping()909a75b2cacSAlex Lorenz void ASTDiff::Impl::computeMapping() {
910a75b2cacSAlex Lorenz   TheMapping = matchTopDown();
911d1969307SJohannes Altmanninger   if (Options.StopAfterTopDown)
912d1969307SJohannes Altmanninger     return;
913a75b2cacSAlex Lorenz   matchBottomUp(TheMapping);
914a75b2cacSAlex Lorenz }
915a75b2cacSAlex Lorenz 
computeChangeKinds(Mapping & M)916e0fe5cd4SJohannes Altmanninger void ASTDiff::Impl::computeChangeKinds(Mapping &M) {
917e0fe5cd4SJohannes Altmanninger   for (NodeId Id1 : T1) {
918e0fe5cd4SJohannes Altmanninger     if (!M.hasSrc(Id1)) {
919e0fe5cd4SJohannes Altmanninger       T1.getMutableNode(Id1).Change = Delete;
920e0fe5cd4SJohannes Altmanninger       T1.getMutableNode(Id1).Shift -= 1;
921a75b2cacSAlex Lorenz     }
922a75b2cacSAlex Lorenz   }
923e0fe5cd4SJohannes Altmanninger   for (NodeId Id2 : T2) {
924e0fe5cd4SJohannes Altmanninger     if (!M.hasDst(Id2)) {
925e0fe5cd4SJohannes Altmanninger       T2.getMutableNode(Id2).Change = Insert;
926e0fe5cd4SJohannes Altmanninger       T2.getMutableNode(Id2).Shift -= 1;
927a75b2cacSAlex Lorenz     }
928a75b2cacSAlex Lorenz   }
929e0fe5cd4SJohannes Altmanninger   for (NodeId Id1 : T1.NodesBfs) {
930a75b2cacSAlex Lorenz     NodeId Id2 = M.getDst(Id1);
931a75b2cacSAlex Lorenz     if (Id2.isInvalid())
932e0fe5cd4SJohannes Altmanninger       continue;
933e0fe5cd4SJohannes Altmanninger     if (!haveSameParents(M, Id1, Id2) ||
934e0fe5cd4SJohannes Altmanninger         T1.findPositionInParent(Id1, true) !=
935e0fe5cd4SJohannes Altmanninger             T2.findPositionInParent(Id2, true)) {
936e0fe5cd4SJohannes Altmanninger       T1.getMutableNode(Id1).Shift -= 1;
937e0fe5cd4SJohannes Altmanninger       T2.getMutableNode(Id2).Shift -= 1;
938a75b2cacSAlex Lorenz     }
939a75b2cacSAlex Lorenz   }
940e0fe5cd4SJohannes Altmanninger   for (NodeId Id2 : T2.NodesBfs) {
941e0fe5cd4SJohannes Altmanninger     NodeId Id1 = M.getSrc(Id2);
942e0fe5cd4SJohannes Altmanninger     if (Id1.isInvalid())
943e0fe5cd4SJohannes Altmanninger       continue;
944e0fe5cd4SJohannes Altmanninger     Node &N1 = T1.getMutableNode(Id1);
945e0fe5cd4SJohannes Altmanninger     Node &N2 = T2.getMutableNode(Id2);
946e0fe5cd4SJohannes Altmanninger     if (Id1.isInvalid())
947e0fe5cd4SJohannes Altmanninger       continue;
948e0fe5cd4SJohannes Altmanninger     if (!haveSameParents(M, Id1, Id2) ||
949e0fe5cd4SJohannes Altmanninger         T1.findPositionInParent(Id1, true) !=
950e0fe5cd4SJohannes Altmanninger             T2.findPositionInParent(Id2, true)) {
951e0fe5cd4SJohannes Altmanninger       N1.Change = N2.Change = Move;
952a75b2cacSAlex Lorenz     }
953e0fe5cd4SJohannes Altmanninger     if (T1.getNodeValue(Id1) != T2.getNodeValue(Id2)) {
954e0fe5cd4SJohannes Altmanninger       N1.Change = N2.Change = (N1.Change == Move ? UpdateMove : Update);
955e0fe5cd4SJohannes Altmanninger     }
956e0fe5cd4SJohannes Altmanninger   }
957a75b2cacSAlex Lorenz }
958a75b2cacSAlex Lorenz 
ASTDiff(SyntaxTree & T1,SyntaxTree & T2,const ComparisonOptions & Options)959a75b2cacSAlex Lorenz ASTDiff::ASTDiff(SyntaxTree &T1, SyntaxTree &T2,
960a75b2cacSAlex Lorenz                  const ComparisonOptions &Options)
9612b3d49b6SJonas Devlieghere     : DiffImpl(std::make_unique<Impl>(*T1.TreeImpl, *T2.TreeImpl, Options)) {}
962a75b2cacSAlex Lorenz 
96331b52d63SJohannes Altmanninger ASTDiff::~ASTDiff() = default;
964a75b2cacSAlex Lorenz 
getMapped(const SyntaxTree & SourceTree,NodeId Id) const965e0fe5cd4SJohannes Altmanninger NodeId ASTDiff::getMapped(const SyntaxTree &SourceTree, NodeId Id) const {
966e0fe5cd4SJohannes Altmanninger   return DiffImpl->getMapped(SourceTree.TreeImpl, Id);
967e0fe5cd4SJohannes Altmanninger }
968e0fe5cd4SJohannes Altmanninger 
SyntaxTree(ASTContext & AST)9692b955ffaSJohannes Altmanninger SyntaxTree::SyntaxTree(ASTContext &AST)
9702b3d49b6SJonas Devlieghere     : TreeImpl(std::make_unique<SyntaxTree::Impl>(
971a75b2cacSAlex Lorenz           this, AST.getTranslationUnitDecl(), AST)) {}
972a75b2cacSAlex Lorenz 
9738b0e0663SJohannes Altmanninger SyntaxTree::~SyntaxTree() = default;
9748b0e0663SJohannes Altmanninger 
getASTContext() const9750da12c84SJohannes Altmanninger const ASTContext &SyntaxTree::getASTContext() const { return TreeImpl->AST; }
9760da12c84SJohannes Altmanninger 
getNode(NodeId Id) const9770da12c84SJohannes Altmanninger const Node &SyntaxTree::getNode(NodeId Id) const {
9780da12c84SJohannes Altmanninger   return TreeImpl->getNode(Id);
9790da12c84SJohannes Altmanninger }
9800da12c84SJohannes Altmanninger 
getSize() const981e0fe5cd4SJohannes Altmanninger int SyntaxTree::getSize() const { return TreeImpl->getSize(); }
getRootId() const9820da12c84SJohannes Altmanninger NodeId SyntaxTree::getRootId() const { return TreeImpl->getRootId(); }
begin() const983e0fe5cd4SJohannes Altmanninger SyntaxTree::PreorderIterator SyntaxTree::begin() const {
984e0fe5cd4SJohannes Altmanninger   return TreeImpl->begin();
985e0fe5cd4SJohannes Altmanninger }
end() const986e0fe5cd4SJohannes Altmanninger SyntaxTree::PreorderIterator SyntaxTree::end() const { return TreeImpl->end(); }
9870da12c84SJohannes Altmanninger 
findPositionInParent(NodeId Id) const988e0fe5cd4SJohannes Altmanninger int SyntaxTree::findPositionInParent(NodeId Id) const {
989e0fe5cd4SJohannes Altmanninger   return TreeImpl->findPositionInParent(Id);
990e0fe5cd4SJohannes Altmanninger }
991e0fe5cd4SJohannes Altmanninger 
992e0fe5cd4SJohannes Altmanninger std::pair<unsigned, unsigned>
getSourceRangeOffsets(const Node & N) const993e0fe5cd4SJohannes Altmanninger SyntaxTree::getSourceRangeOffsets(const Node &N) const {
9940da12c84SJohannes Altmanninger   const SourceManager &SrcMgr = TreeImpl->AST.getSourceManager();
9950da12c84SJohannes Altmanninger   SourceRange Range = N.ASTNode.getSourceRange();
9960da12c84SJohannes Altmanninger   SourceLocation BeginLoc = Range.getBegin();
9970da12c84SJohannes Altmanninger   SourceLocation EndLoc = Lexer::getLocForEndOfToken(
9980da12c84SJohannes Altmanninger       Range.getEnd(), /*Offset=*/0, SrcMgr, TreeImpl->AST.getLangOpts());
9990da12c84SJohannes Altmanninger   if (auto *ThisExpr = N.ASTNode.get<CXXThisExpr>()) {
10000da12c84SJohannes Altmanninger     if (ThisExpr->isImplicit())
10010da12c84SJohannes Altmanninger       EndLoc = BeginLoc;
10020da12c84SJohannes Altmanninger   }
10030da12c84SJohannes Altmanninger   unsigned Begin = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(BeginLoc));
10040da12c84SJohannes Altmanninger   unsigned End = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(EndLoc));
10050da12c84SJohannes Altmanninger   return {Begin, End};
10060da12c84SJohannes Altmanninger }
1007a75b2cacSAlex Lorenz 
getNodeValue(NodeId Id) const1008e0fe5cd4SJohannes Altmanninger std::string SyntaxTree::getNodeValue(NodeId Id) const {
1009e0fe5cd4SJohannes Altmanninger   return TreeImpl->getNodeValue(Id);
1010e0fe5cd4SJohannes Altmanninger }
1011e0fe5cd4SJohannes Altmanninger 
getNodeValue(const Node & N) const1012e0fe5cd4SJohannes Altmanninger std::string SyntaxTree::getNodeValue(const Node &N) const {
1013e0fe5cd4SJohannes Altmanninger   return TreeImpl->getNodeValue(N);
1014a75b2cacSAlex Lorenz }
1015a75b2cacSAlex Lorenz 
1016a75b2cacSAlex Lorenz } // end namespace diff
1017a75b2cacSAlex Lorenz } // end namespace clang
1018