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>
22a75b2cacSAlex Lorenz #include <unordered_set>
23a75b2cacSAlex Lorenz 
24a75b2cacSAlex Lorenz using namespace llvm;
25a75b2cacSAlex Lorenz using namespace clang;
26a75b2cacSAlex Lorenz 
27a75b2cacSAlex Lorenz namespace clang {
28a75b2cacSAlex Lorenz namespace diff {
29a75b2cacSAlex Lorenz 
30fa524d7bSJohannes Altmanninger namespace {
318b0e0663SJohannes Altmanninger /// Maps nodes of the left tree to ones on the right, and vice versa.
328b0e0663SJohannes Altmanninger class Mapping {
338b0e0663SJohannes Altmanninger public:
348b0e0663SJohannes Altmanninger   Mapping() = default;
358b0e0663SJohannes Altmanninger   Mapping(Mapping &&Other) = default;
368b0e0663SJohannes Altmanninger   Mapping &operator=(Mapping &&Other) = default;
3751321aefSJohannes Altmanninger 
Mapping(size_t Size)3851321aefSJohannes Altmanninger   Mapping(size_t Size) {
392b3d49b6SJonas Devlieghere     SrcToDst = std::make_unique<NodeId[]>(Size);
402b3d49b6SJonas Devlieghere     DstToSrc = std::make_unique<NodeId[]>(Size);
418b0e0663SJohannes Altmanninger   }
428b0e0663SJohannes Altmanninger 
link(NodeId Src,NodeId Dst)438b0e0663SJohannes Altmanninger   void link(NodeId Src, NodeId Dst) {
4451321aefSJohannes Altmanninger     SrcToDst[Src] = Dst, DstToSrc[Dst] = Src;
458b0e0663SJohannes Altmanninger   }
468b0e0663SJohannes Altmanninger 
getDst(NodeId Src) const4751321aefSJohannes Altmanninger   NodeId getDst(NodeId Src) const { return SrcToDst[Src]; }
getSrc(NodeId Dst) const4851321aefSJohannes Altmanninger   NodeId getSrc(NodeId Dst) const { return DstToSrc[Dst]; }
hasSrc(NodeId Src) const4951321aefSJohannes Altmanninger   bool hasSrc(NodeId Src) const { return getDst(Src).isValid(); }
hasDst(NodeId Dst) const5051321aefSJohannes Altmanninger   bool hasDst(NodeId Dst) const { return getSrc(Dst).isValid(); }
518b0e0663SJohannes Altmanninger 
528b0e0663SJohannes Altmanninger private:
5351321aefSJohannes Altmanninger   std::unique_ptr<NodeId[]> SrcToDst, DstToSrc;
548b0e0663SJohannes Altmanninger };
55fa524d7bSJohannes Altmanninger } // end anonymous namespace
568b0e0663SJohannes Altmanninger 
57a75b2cacSAlex Lorenz class ASTDiff::Impl {
58a75b2cacSAlex Lorenz public:
5931b52d63SJohannes Altmanninger   SyntaxTree::Impl &T1, &T2;
60a75b2cacSAlex Lorenz   Mapping TheMapping;
61a75b2cacSAlex Lorenz 
6231b52d63SJohannes Altmanninger   Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
63e0fe5cd4SJohannes Altmanninger        const ComparisonOptions &Options);
64a75b2cacSAlex Lorenz 
65a75b2cacSAlex Lorenz   /// Matches nodes one-by-one based on their similarity.
66a75b2cacSAlex Lorenz   void computeMapping();
67a75b2cacSAlex Lorenz 
68e0fe5cd4SJohannes Altmanninger   // Compute Change for each node based on similarity.
69e0fe5cd4SJohannes Altmanninger   void computeChangeKinds(Mapping &M);
70a75b2cacSAlex Lorenz 
getMapped(const std::unique_ptr<SyntaxTree::Impl> & Tree,NodeId Id) const71e0fe5cd4SJohannes Altmanninger   NodeId getMapped(const std::unique_ptr<SyntaxTree::Impl> &Tree,
72e0fe5cd4SJohannes Altmanninger                    NodeId Id) const {
73e0fe5cd4SJohannes Altmanninger     if (&*Tree == &T1)
74e0fe5cd4SJohannes Altmanninger       return TheMapping.getDst(Id);
75e0fe5cd4SJohannes Altmanninger     assert(&*Tree == &T2 && "Invalid tree.");
76e0fe5cd4SJohannes Altmanninger     return TheMapping.getSrc(Id);
77e0fe5cd4SJohannes Altmanninger   }
78a75b2cacSAlex Lorenz 
79a75b2cacSAlex Lorenz private:
80a75b2cacSAlex Lorenz   // Returns true if the two subtrees are identical.
8131b52d63SJohannes Altmanninger   bool identical(NodeId Id1, NodeId Id2) const;
82a75b2cacSAlex Lorenz 
83a75b2cacSAlex Lorenz   // Returns false if the nodes must not be mached.
84a75b2cacSAlex Lorenz   bool isMatchingPossible(NodeId Id1, NodeId Id2) const;
85a75b2cacSAlex Lorenz 
86e0fe5cd4SJohannes Altmanninger   // Returns true if the nodes' parents are matched.
87e0fe5cd4SJohannes Altmanninger   bool haveSameParents(const Mapping &M, NodeId Id1, NodeId Id2) const;
88e0fe5cd4SJohannes Altmanninger 
89a75b2cacSAlex Lorenz   // Uses an optimal albeit slow algorithm to compute a mapping between two
90a75b2cacSAlex Lorenz   // subtrees, but only if both have fewer nodes than MaxSize.
91a75b2cacSAlex Lorenz   void addOptimalMapping(Mapping &M, NodeId Id1, NodeId Id2) const;
92a75b2cacSAlex Lorenz 
93a75b2cacSAlex Lorenz   // Computes the ratio of common descendants between the two nodes.
94a75b2cacSAlex Lorenz   // Descendants are only considered to be equal when they are mapped in M.
95d1969307SJohannes Altmanninger   double getJaccardSimilarity(const Mapping &M, NodeId Id1, NodeId Id2) const;
96a75b2cacSAlex Lorenz 
97a75b2cacSAlex Lorenz   // Returns the node that has the highest degree of similarity.
98a75b2cacSAlex Lorenz   NodeId findCandidate(const Mapping &M, NodeId Id1) const;
99a75b2cacSAlex Lorenz 
100e0fe5cd4SJohannes Altmanninger   // Returns a mapping of identical subtrees.
101e0fe5cd4SJohannes Altmanninger   Mapping matchTopDown() const;
102e0fe5cd4SJohannes Altmanninger 
103a75b2cacSAlex Lorenz   // Tries to match any yet unmapped nodes, in a bottom-up fashion.
104a75b2cacSAlex Lorenz   void matchBottomUp(Mapping &M) const;
105a75b2cacSAlex Lorenz 
106a75b2cacSAlex Lorenz   const ComparisonOptions &Options;
107a75b2cacSAlex Lorenz 
108a75b2cacSAlex Lorenz   friend class ZhangShashaMatcher;
109a75b2cacSAlex Lorenz };
110a75b2cacSAlex Lorenz 
1118b0e0663SJohannes Altmanninger /// Represents the AST of a TranslationUnit.
11231b52d63SJohannes Altmanninger class SyntaxTree::Impl {
1138b0e0663SJohannes Altmanninger public:
11441395022SJohannes Altmanninger   Impl(SyntaxTree *Parent, ASTContext &AST);
1158b0e0663SJohannes Altmanninger   /// Constructs a tree from an AST node.
1162b955ffaSJohannes Altmanninger   Impl(SyntaxTree *Parent, Decl *N, ASTContext &AST);
1172b955ffaSJohannes Altmanninger   Impl(SyntaxTree *Parent, Stmt *N, ASTContext &AST);
1188b0e0663SJohannes Altmanninger   template <class T>
Impl(SyntaxTree * Parent,std::enable_if_t<std::is_base_of<Stmt,T>::value,T> * Node,ASTContext & AST)11931b52d63SJohannes Altmanninger   Impl(SyntaxTree *Parent,
120027eb716SJustin Lebar        std::enable_if_t<std::is_base_of<Stmt, T>::value, T> *Node,
1212b955ffaSJohannes Altmanninger        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<Decl,T>::value,T> * Node,ASTContext & AST)12431b52d63SJohannes Altmanninger   Impl(SyntaxTree *Parent,
125027eb716SJustin Lebar        std::enable_if_t<std::is_base_of<Decl, T>::value, T> *Node,
1262b955ffaSJohannes Altmanninger        ASTContext &AST)
12731b52d63SJohannes Altmanninger       : Impl(Parent, dyn_cast<Decl>(Node), AST) {}
1288b0e0663SJohannes Altmanninger 
1298b0e0663SJohannes Altmanninger   SyntaxTree *Parent;
1302b955ffaSJohannes Altmanninger   ASTContext &AST;
13141395022SJohannes Altmanninger   PrintingPolicy TypePP;
132bc3e993cSJohannes Altmanninger   /// Nodes in preorder.
133bc3e993cSJohannes Altmanninger   std::vector<Node> Nodes;
1348b0e0663SJohannes Altmanninger   std::vector<NodeId> Leaves;
1358b0e0663SJohannes Altmanninger   // Maps preorder indices to postorder ones.
1368b0e0663SJohannes Altmanninger   std::vector<int> PostorderIds;
137e0fe5cd4SJohannes Altmanninger   std::vector<NodeId> NodesBfs;
1388b0e0663SJohannes Altmanninger 
getSize() const1398b0e0663SJohannes Altmanninger   int getSize() const { return Nodes.size(); }
getRootId() const14031b52d63SJohannes Altmanninger   NodeId getRootId() const { return 0; }
begin() const141e0fe5cd4SJohannes Altmanninger   PreorderIterator begin() const { return getRootId(); }
end() const142e0fe5cd4SJohannes Altmanninger   PreorderIterator end() const { return getSize(); }
1438b0e0663SJohannes Altmanninger 
getNode(NodeId Id) const1448b0e0663SJohannes Altmanninger   const Node &getNode(NodeId Id) const { return Nodes[Id]; }
getMutableNode(NodeId Id)1458b0e0663SJohannes Altmanninger   Node &getMutableNode(NodeId Id) { return Nodes[Id]; }
isValidNodeId(NodeId Id) const1468b0e0663SJohannes Altmanninger   bool isValidNodeId(NodeId Id) const { return Id >= 0 && Id < getSize(); }
addNode(Node & N)1478b0e0663SJohannes Altmanninger   void addNode(Node &N) { Nodes.push_back(N); }
1488b0e0663SJohannes Altmanninger   int getNumberOfDescendants(NodeId Id) const;
1498b0e0663SJohannes Altmanninger   bool isInSubtree(NodeId Id, NodeId SubtreeRoot) const;
150e0fe5cd4SJohannes Altmanninger   int findPositionInParent(NodeId Id, bool Shifted = false) const;
1518b0e0663SJohannes Altmanninger 
1522b955ffaSJohannes Altmanninger   std::string getRelativeName(const NamedDecl *ND,
1532b955ffaSJohannes Altmanninger                               const DeclContext *Context) const;
1542b955ffaSJohannes Altmanninger   std::string getRelativeName(const NamedDecl *ND) const;
1552b955ffaSJohannes Altmanninger 
15631b52d63SJohannes Altmanninger   std::string getNodeValue(NodeId Id) const;
157e0fe5cd4SJohannes Altmanninger   std::string getNodeValue(const Node &Node) const;
1580dd86dc5SJohannes Altmanninger   std::string getDeclValue(const Decl *D) const;
1590dd86dc5SJohannes Altmanninger   std::string getStmtValue(const Stmt *S) const;
1608b0e0663SJohannes Altmanninger 
1618b0e0663SJohannes Altmanninger private:
1628b0e0663SJohannes Altmanninger   void initTree();
1638b0e0663SJohannes Altmanninger   void setLeftMostDescendants();
1648b0e0663SJohannes Altmanninger };
1658b0e0663SJohannes Altmanninger 
isSpecializedNodeExcluded(const Decl * D)166d5b56a86SJohannes Altmanninger static bool isSpecializedNodeExcluded(const Decl *D) { return D->isImplicit(); }
isSpecializedNodeExcluded(const Stmt * S)167d5b56a86SJohannes Altmanninger static bool isSpecializedNodeExcluded(const Stmt *S) { return false; }
isSpecializedNodeExcluded(CXXCtorInitializer * I)16841395022SJohannes Altmanninger static bool isSpecializedNodeExcluded(CXXCtorInitializer *I) {
16941395022SJohannes Altmanninger   return !I->isWritten();
17041395022SJohannes Altmanninger }
171d5b56a86SJohannes Altmanninger 
172a75b2cacSAlex Lorenz template <class T>
isNodeExcluded(const SourceManager & SrcMgr,T * N)173a75b2cacSAlex Lorenz static bool isNodeExcluded(const SourceManager &SrcMgr, T *N) {
174a75b2cacSAlex Lorenz   if (!N)
175a75b2cacSAlex Lorenz     return true;
17641395022SJohannes Altmanninger   SourceLocation SLoc = N->getSourceRange().getBegin();
177d5b56a86SJohannes Altmanninger   if (SLoc.isValid()) {
178d5b56a86SJohannes Altmanninger     // Ignore everything from other files.
179d5b56a86SJohannes Altmanninger     if (!SrcMgr.isInMainFile(SLoc))
180d5b56a86SJohannes Altmanninger       return true;
181d5b56a86SJohannes Altmanninger     // Ignore macros.
182d5b56a86SJohannes Altmanninger     if (SLoc != SrcMgr.getSpellingLoc(SLoc))
183d5b56a86SJohannes Altmanninger       return true;
184d5b56a86SJohannes Altmanninger   }
185d5b56a86SJohannes Altmanninger   return isSpecializedNodeExcluded(N);
186a75b2cacSAlex Lorenz }
187a75b2cacSAlex Lorenz 
188a75b2cacSAlex Lorenz namespace {
189a75b2cacSAlex Lorenz // Sets Height, Parent and Children for each node.
190a75b2cacSAlex Lorenz struct PreorderVisitor : public RecursiveASTVisitor<PreorderVisitor> {
191a75b2cacSAlex Lorenz   int Id = 0, Depth = 0;
192a75b2cacSAlex Lorenz   NodeId Parent;
19331b52d63SJohannes Altmanninger   SyntaxTree::Impl &Tree;
194a75b2cacSAlex Lorenz 
PreorderVisitorclang::diff::__anonb3398b060211::PreorderVisitor19531b52d63SJohannes Altmanninger   PreorderVisitor(SyntaxTree::Impl &Tree) : Tree(Tree) {}
196a75b2cacSAlex Lorenz 
PreTraverseclang::diff::__anonb3398b060211::PreorderVisitor197a75b2cacSAlex Lorenz   template <class T> std::tuple<NodeId, NodeId> PreTraverse(T *ASTNode) {
198a75b2cacSAlex Lorenz     NodeId MyId = Id;
199bc3e993cSJohannes Altmanninger     Tree.Nodes.emplace_back();
20031b52d63SJohannes Altmanninger     Node &N = Tree.getMutableNode(MyId);
201a75b2cacSAlex Lorenz     N.Parent = Parent;
202a75b2cacSAlex Lorenz     N.Depth = Depth;
203a75b2cacSAlex Lorenz     N.ASTNode = DynTypedNode::create(*ASTNode);
204a75b2cacSAlex Lorenz     assert(!N.ASTNode.getNodeKind().isNone() &&
205a75b2cacSAlex Lorenz            "Expected nodes to have a valid kind.");
206a75b2cacSAlex Lorenz     if (Parent.isValid()) {
20731b52d63SJohannes Altmanninger       Node &P = Tree.getMutableNode(Parent);
208a75b2cacSAlex Lorenz       P.Children.push_back(MyId);
209a75b2cacSAlex Lorenz     }
210a75b2cacSAlex Lorenz     Parent = MyId;
211a75b2cacSAlex Lorenz     ++Id;
212a75b2cacSAlex Lorenz     ++Depth;
21331b52d63SJohannes Altmanninger     return std::make_tuple(MyId, Tree.getNode(MyId).Parent);
214a75b2cacSAlex Lorenz   }
PostTraverseclang::diff::__anonb3398b060211::PreorderVisitor215a75b2cacSAlex Lorenz   void PostTraverse(std::tuple<NodeId, NodeId> State) {
216a75b2cacSAlex Lorenz     NodeId MyId, PreviousParent;
217a75b2cacSAlex Lorenz     std::tie(MyId, PreviousParent) = State;
218a75b2cacSAlex Lorenz     assert(MyId.isValid() && "Expecting to only traverse valid nodes.");
219a75b2cacSAlex Lorenz     Parent = PreviousParent;
220a75b2cacSAlex Lorenz     --Depth;
22131b52d63SJohannes Altmanninger     Node &N = Tree.getMutableNode(MyId);
222fa524d7bSJohannes Altmanninger     N.RightMostDescendant = Id - 1;
223fa524d7bSJohannes Altmanninger     assert(N.RightMostDescendant >= 0 &&
224fa524d7bSJohannes Altmanninger            N.RightMostDescendant < Tree.getSize() &&
225fa524d7bSJohannes Altmanninger            "Rightmost descendant must be a valid tree node.");
226a75b2cacSAlex Lorenz     if (N.isLeaf())
22731b52d63SJohannes Altmanninger       Tree.Leaves.push_back(MyId);
228a75b2cacSAlex Lorenz     N.Height = 1;
229a75b2cacSAlex Lorenz     for (NodeId Child : N.Children)
23031b52d63SJohannes Altmanninger       N.Height = std::max(N.Height, 1 + Tree.getNode(Child).Height);
231a75b2cacSAlex Lorenz   }
TraverseDeclclang::diff::__anonb3398b060211::PreorderVisitor232a75b2cacSAlex Lorenz   bool TraverseDecl(Decl *D) {
23331b52d63SJohannes Altmanninger     if (isNodeExcluded(Tree.AST.getSourceManager(), D))
234a75b2cacSAlex Lorenz       return true;
235a75b2cacSAlex Lorenz     auto SavedState = PreTraverse(D);
236a75b2cacSAlex Lorenz     RecursiveASTVisitor<PreorderVisitor>::TraverseDecl(D);
237a75b2cacSAlex Lorenz     PostTraverse(SavedState);
238a75b2cacSAlex Lorenz     return true;
239a75b2cacSAlex Lorenz   }
TraverseStmtclang::diff::__anonb3398b060211::PreorderVisitor240a75b2cacSAlex Lorenz   bool TraverseStmt(Stmt *S) {
241e64aee87SBruno Ricci     if (auto *E = dyn_cast_or_null<Expr>(S))
242e64aee87SBruno Ricci       S = E->IgnoreImplicit();
24331b52d63SJohannes Altmanninger     if (isNodeExcluded(Tree.AST.getSourceManager(), S))
244a75b2cacSAlex Lorenz       return true;
245a75b2cacSAlex Lorenz     auto SavedState = PreTraverse(S);
246a75b2cacSAlex Lorenz     RecursiveASTVisitor<PreorderVisitor>::TraverseStmt(S);
247a75b2cacSAlex Lorenz     PostTraverse(SavedState);
248a75b2cacSAlex Lorenz     return true;
249a75b2cacSAlex Lorenz   }
TraverseTypeclang::diff::__anonb3398b060211::PreorderVisitor250a75b2cacSAlex Lorenz   bool TraverseType(QualType T) { return true; }
TraverseConstructorInitializerclang::diff::__anonb3398b060211::PreorderVisitor25141395022SJohannes Altmanninger   bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
25241395022SJohannes Altmanninger     if (isNodeExcluded(Tree.AST.getSourceManager(), Init))
25341395022SJohannes Altmanninger       return true;
25441395022SJohannes Altmanninger     auto SavedState = PreTraverse(Init);
25541395022SJohannes Altmanninger     RecursiveASTVisitor<PreorderVisitor>::TraverseConstructorInitializer(Init);
25641395022SJohannes Altmanninger     PostTraverse(SavedState);
25741395022SJohannes Altmanninger     return true;
25841395022SJohannes Altmanninger   }
259a75b2cacSAlex Lorenz };
260a75b2cacSAlex Lorenz } // end anonymous namespace
261a75b2cacSAlex Lorenz 
Impl(SyntaxTree * Parent,ASTContext & AST)26241395022SJohannes Altmanninger SyntaxTree::Impl::Impl(SyntaxTree *Parent, ASTContext &AST)
26341395022SJohannes Altmanninger     : Parent(Parent), AST(AST), TypePP(AST.getLangOpts()) {
26441395022SJohannes Altmanninger   TypePP.AnonymousTagLocations = false;
26541395022SJohannes Altmanninger }
26641395022SJohannes Altmanninger 
Impl(SyntaxTree * Parent,Decl * N,ASTContext & AST)2672b955ffaSJohannes Altmanninger SyntaxTree::Impl::Impl(SyntaxTree *Parent, Decl *N, ASTContext &AST)
26841395022SJohannes Altmanninger     : Impl(Parent, AST) {
269a75b2cacSAlex Lorenz   PreorderVisitor PreorderWalker(*this);
270a75b2cacSAlex Lorenz   PreorderWalker.TraverseDecl(N);
271a75b2cacSAlex Lorenz   initTree();
272a75b2cacSAlex Lorenz }
273a75b2cacSAlex Lorenz 
Impl(SyntaxTree * Parent,Stmt * N,ASTContext & AST)2742b955ffaSJohannes Altmanninger SyntaxTree::Impl::Impl(SyntaxTree *Parent, Stmt *N, ASTContext &AST)
27541395022SJohannes Altmanninger     : Impl(Parent, AST) {
276a75b2cacSAlex Lorenz   PreorderVisitor PreorderWalker(*this);
277a75b2cacSAlex Lorenz   PreorderWalker.TraverseStmt(N);
278a75b2cacSAlex Lorenz   initTree();
279a75b2cacSAlex Lorenz }
280a75b2cacSAlex Lorenz 
getSubtreePostorder(const SyntaxTree::Impl & Tree,NodeId Root)28131b52d63SJohannes Altmanninger static std::vector<NodeId> getSubtreePostorder(const SyntaxTree::Impl &Tree,
282a75b2cacSAlex Lorenz                                                NodeId Root) {
283a75b2cacSAlex Lorenz   std::vector<NodeId> Postorder;
284a75b2cacSAlex Lorenz   std::function<void(NodeId)> Traverse = [&](NodeId Id) {
285a75b2cacSAlex Lorenz     const Node &N = Tree.getNode(Id);
286a75b2cacSAlex Lorenz     for (NodeId Child : N.Children)
287a75b2cacSAlex Lorenz       Traverse(Child);
288a75b2cacSAlex Lorenz     Postorder.push_back(Id);
289a75b2cacSAlex Lorenz   };
290a75b2cacSAlex Lorenz   Traverse(Root);
291a75b2cacSAlex Lorenz   return Postorder;
292a75b2cacSAlex Lorenz }
293a75b2cacSAlex Lorenz 
getSubtreeBfs(const SyntaxTree::Impl & Tree,NodeId Root)29431b52d63SJohannes Altmanninger static std::vector<NodeId> getSubtreeBfs(const SyntaxTree::Impl &Tree,
295a75b2cacSAlex Lorenz                                          NodeId Root) {
296a75b2cacSAlex Lorenz   std::vector<NodeId> Ids;
297a75b2cacSAlex Lorenz   size_t Expanded = 0;
298a75b2cacSAlex Lorenz   Ids.push_back(Root);
299a75b2cacSAlex Lorenz   while (Expanded < Ids.size())
300a75b2cacSAlex Lorenz     for (NodeId Child : Tree.getNode(Ids[Expanded++]).Children)
301a75b2cacSAlex Lorenz       Ids.push_back(Child);
302a75b2cacSAlex Lorenz   return Ids;
303a75b2cacSAlex Lorenz }
304a75b2cacSAlex Lorenz 
initTree()305e0fe5cd4SJohannes Altmanninger void SyntaxTree::Impl::initTree() {
306e0fe5cd4SJohannes Altmanninger   setLeftMostDescendants();
307e0fe5cd4SJohannes Altmanninger   int PostorderId = 0;
308e0fe5cd4SJohannes Altmanninger   PostorderIds.resize(getSize());
309e0fe5cd4SJohannes Altmanninger   std::function<void(NodeId)> PostorderTraverse = [&](NodeId Id) {
310e0fe5cd4SJohannes Altmanninger     for (NodeId Child : getNode(Id).Children)
311e0fe5cd4SJohannes Altmanninger       PostorderTraverse(Child);
312e0fe5cd4SJohannes Altmanninger     PostorderIds[Id] = PostorderId;
313e0fe5cd4SJohannes Altmanninger     ++PostorderId;
314e0fe5cd4SJohannes Altmanninger   };
315e0fe5cd4SJohannes Altmanninger   PostorderTraverse(getRootId());
316e0fe5cd4SJohannes Altmanninger   NodesBfs = getSubtreeBfs(*this, getRootId());
317e0fe5cd4SJohannes Altmanninger }
318e0fe5cd4SJohannes Altmanninger 
setLeftMostDescendants()319e0fe5cd4SJohannes Altmanninger void SyntaxTree::Impl::setLeftMostDescendants() {
320e0fe5cd4SJohannes Altmanninger   for (NodeId Leaf : Leaves) {
321e0fe5cd4SJohannes Altmanninger     getMutableNode(Leaf).LeftMostDescendant = Leaf;
322e0fe5cd4SJohannes Altmanninger     NodeId Parent, Cur = Leaf;
323e0fe5cd4SJohannes Altmanninger     while ((Parent = getNode(Cur).Parent).isValid() &&
324e0fe5cd4SJohannes Altmanninger            getNode(Parent).Children[0] == Cur) {
325e0fe5cd4SJohannes Altmanninger       Cur = Parent;
326e0fe5cd4SJohannes Altmanninger       getMutableNode(Cur).LeftMostDescendant = Leaf;
327e0fe5cd4SJohannes Altmanninger     }
328e0fe5cd4SJohannes Altmanninger   }
329e0fe5cd4SJohannes Altmanninger }
330e0fe5cd4SJohannes Altmanninger 
getNumberOfDescendants(NodeId Id) const33131b52d63SJohannes Altmanninger int SyntaxTree::Impl::getNumberOfDescendants(NodeId Id) const {
332a75b2cacSAlex Lorenz   return getNode(Id).RightMostDescendant - Id + 1;
333a75b2cacSAlex Lorenz }
334a75b2cacSAlex Lorenz 
isInSubtree(NodeId Id,NodeId SubtreeRoot) const33531b52d63SJohannes Altmanninger bool SyntaxTree::Impl::isInSubtree(NodeId Id, NodeId SubtreeRoot) const {
336fa524d7bSJohannes Altmanninger   return Id >= SubtreeRoot && Id <= getNode(SubtreeRoot).RightMostDescendant;
337a75b2cacSAlex Lorenz }
338a75b2cacSAlex Lorenz 
findPositionInParent(NodeId Id,bool Shifted) const339e0fe5cd4SJohannes Altmanninger int SyntaxTree::Impl::findPositionInParent(NodeId Id, bool Shifted) const {
340e0fe5cd4SJohannes Altmanninger   NodeId Parent = getNode(Id).Parent;
341e0fe5cd4SJohannes Altmanninger   if (Parent.isInvalid())
342e0fe5cd4SJohannes Altmanninger     return 0;
343e0fe5cd4SJohannes Altmanninger   const auto &Siblings = getNode(Parent).Children;
344e0fe5cd4SJohannes Altmanninger   int Position = 0;
345e0fe5cd4SJohannes Altmanninger   for (size_t I = 0, E = Siblings.size(); I < E; ++I) {
346e0fe5cd4SJohannes Altmanninger     if (Shifted)
347e0fe5cd4SJohannes Altmanninger       Position += getNode(Siblings[I]).Shift;
348e0fe5cd4SJohannes Altmanninger     if (Siblings[I] == Id) {
349e0fe5cd4SJohannes Altmanninger       Position += I;
350e0fe5cd4SJohannes Altmanninger       return Position;
351e0fe5cd4SJohannes Altmanninger     }
352e0fe5cd4SJohannes Altmanninger   }
353e0fe5cd4SJohannes Altmanninger   llvm_unreachable("Node not found in parent's children.");
35469774d67SJohannes Altmanninger }
35569774d67SJohannes Altmanninger 
3562b955ffaSJohannes Altmanninger // Returns the qualified name of ND. If it is subordinate to Context,
3572b955ffaSJohannes Altmanninger // then the prefix of the latter is removed from the returned value.
3582b955ffaSJohannes Altmanninger std::string
getRelativeName(const NamedDecl * ND,const DeclContext * Context) const3592b955ffaSJohannes Altmanninger SyntaxTree::Impl::getRelativeName(const NamedDecl *ND,
3602b955ffaSJohannes Altmanninger                                   const DeclContext *Context) const {
361bc7d817cSJohannes Altmanninger   std::string Val = ND->getQualifiedNameAsString();
3622b955ffaSJohannes Altmanninger   std::string ContextPrefix;
363bc7d817cSJohannes Altmanninger   if (!Context)
364bc7d817cSJohannes Altmanninger     return Val;
3652b955ffaSJohannes Altmanninger   if (auto *Namespace = dyn_cast<NamespaceDecl>(Context))
3662b955ffaSJohannes Altmanninger     ContextPrefix = Namespace->getQualifiedNameAsString();
3672b955ffaSJohannes Altmanninger   else if (auto *Record = dyn_cast<RecordDecl>(Context))
3682b955ffaSJohannes Altmanninger     ContextPrefix = Record->getQualifiedNameAsString();
3692b955ffaSJohannes Altmanninger   else if (AST.getLangOpts().CPlusPlus11)
3702b955ffaSJohannes Altmanninger     if (auto *Tag = dyn_cast<TagDecl>(Context))
3712b955ffaSJohannes Altmanninger       ContextPrefix = Tag->getQualifiedNameAsString();
3722a8c18d9SAlexander Kornienko   // Strip the qualifier, if Val refers to something in the current scope.
3732b955ffaSJohannes Altmanninger   // But leave one leading ':' in place, so that we know that this is a
3742b955ffaSJohannes Altmanninger   // relative path.
3752b955ffaSJohannes Altmanninger   if (!ContextPrefix.empty() && StringRef(Val).startswith(ContextPrefix))
3762b955ffaSJohannes Altmanninger     Val = Val.substr(ContextPrefix.size() + 1);
3772b955ffaSJohannes Altmanninger   return Val;
3782b955ffaSJohannes Altmanninger }
3792b955ffaSJohannes Altmanninger 
getRelativeName(const NamedDecl * ND) const3802b955ffaSJohannes Altmanninger std::string SyntaxTree::Impl::getRelativeName(const NamedDecl *ND) const {
3812b955ffaSJohannes Altmanninger   return getRelativeName(ND, ND->getDeclContext());
3822b955ffaSJohannes Altmanninger }
3832b955ffaSJohannes Altmanninger 
getEnclosingDeclContext(ASTContext & AST,const Stmt * S)3842b955ffaSJohannes Altmanninger static const DeclContext *getEnclosingDeclContext(ASTContext &AST,
3852b955ffaSJohannes Altmanninger                                                   const Stmt *S) {
3862b955ffaSJohannes Altmanninger   while (S) {
3872b955ffaSJohannes Altmanninger     const auto &Parents = AST.getParents(*S);
3882b955ffaSJohannes Altmanninger     if (Parents.empty())
3892b955ffaSJohannes Altmanninger       return nullptr;
3902b955ffaSJohannes Altmanninger     const auto &P = Parents[0];
3912b955ffaSJohannes Altmanninger     if (const auto *D = P.get<Decl>())
3922b955ffaSJohannes Altmanninger       return D->getDeclContext();
3932b955ffaSJohannes Altmanninger     S = P.get<Stmt>();
3942b955ffaSJohannes Altmanninger   }
395bc7d817cSJohannes Altmanninger   return nullptr;
3962b955ffaSJohannes Altmanninger }
3972b955ffaSJohannes Altmanninger 
getInitializerValue(const CXXCtorInitializer * Init,const PrintingPolicy & TypePP)39841395022SJohannes Altmanninger static std::string getInitializerValue(const CXXCtorInitializer *Init,
39941395022SJohannes Altmanninger                                        const PrintingPolicy &TypePP) {
40041395022SJohannes Altmanninger   if (Init->isAnyMemberInitializer())
401adcd0268SBenjamin Kramer     return std::string(Init->getAnyMember()->getName());
40241395022SJohannes Altmanninger   if (Init->isBaseInitializer())
40341395022SJohannes Altmanninger     return QualType(Init->getBaseClass(), 0).getAsString(TypePP);
40441395022SJohannes Altmanninger   if (Init->isDelegatingInitializer())
40541395022SJohannes Altmanninger     return Init->getTypeSourceInfo()->getType().getAsString(TypePP);
40641395022SJohannes Altmanninger   llvm_unreachable("Unknown initializer type");
40741395022SJohannes Altmanninger }
40841395022SJohannes Altmanninger 
getNodeValue(NodeId Id) const409e0fe5cd4SJohannes Altmanninger std::string SyntaxTree::Impl::getNodeValue(NodeId Id) const {
410e0fe5cd4SJohannes Altmanninger   return getNodeValue(getNode(Id));
411e0fe5cd4SJohannes Altmanninger }
412e0fe5cd4SJohannes Altmanninger 
getNodeValue(const Node & N) const413e0fe5cd4SJohannes Altmanninger std::string SyntaxTree::Impl::getNodeValue(const Node &N) const {
414e0fe5cd4SJohannes Altmanninger   const DynTypedNode &DTN = N.ASTNode;
4150dd86dc5SJohannes Altmanninger   if (auto *S = DTN.get<Stmt>())
4160dd86dc5SJohannes Altmanninger     return getStmtValue(S);
4170dd86dc5SJohannes Altmanninger   if (auto *D = DTN.get<Decl>())
4180dd86dc5SJohannes Altmanninger     return getDeclValue(D);
41941395022SJohannes Altmanninger   if (auto *Init = DTN.get<CXXCtorInitializer>())
42041395022SJohannes Altmanninger     return getInitializerValue(Init, TypePP);
4210dd86dc5SJohannes Altmanninger   llvm_unreachable("Fatal: unhandled AST node.\n");
4220dd86dc5SJohannes Altmanninger }
4230dd86dc5SJohannes Altmanninger 
getDeclValue(const Decl * D) const4240dd86dc5SJohannes Altmanninger std::string SyntaxTree::Impl::getDeclValue(const Decl *D) const {
4250dd86dc5SJohannes Altmanninger   std::string Value;
42641395022SJohannes Altmanninger   if (auto *V = dyn_cast<ValueDecl>(D))
42741395022SJohannes Altmanninger     return getRelativeName(V) + "(" + V->getType().getAsString(TypePP) + ")";
4280dd86dc5SJohannes Altmanninger   if (auto *N = dyn_cast<NamedDecl>(D))
4292b955ffaSJohannes Altmanninger     Value += getRelativeName(N) + ";";
4300dd86dc5SJohannes Altmanninger   if (auto *T = dyn_cast<TypedefNameDecl>(D))
4310dd86dc5SJohannes Altmanninger     return Value + T->getUnderlyingType().getAsString(TypePP) + ";";
4320dd86dc5SJohannes Altmanninger   if (auto *T = dyn_cast<TypeDecl>(D))
4330dd86dc5SJohannes Altmanninger     if (T->getTypeForDecl())
4340dd86dc5SJohannes Altmanninger       Value +=
4350dd86dc5SJohannes Altmanninger           T->getTypeForDecl()->getCanonicalTypeInternal().getAsString(TypePP) +
4360dd86dc5SJohannes Altmanninger           ";";
4370dd86dc5SJohannes Altmanninger   if (auto *U = dyn_cast<UsingDirectiveDecl>(D))
438adcd0268SBenjamin Kramer     return std::string(U->getNominatedNamespace()->getName());
4390dd86dc5SJohannes Altmanninger   if (auto *A = dyn_cast<AccessSpecDecl>(D)) {
4400dd86dc5SJohannes Altmanninger     CharSourceRange Range(A->getSourceRange(), false);
441adcd0268SBenjamin Kramer     return std::string(
442adcd0268SBenjamin Kramer         Lexer::getSourceText(Range, AST.getSourceManager(), AST.getLangOpts()));
443a75b2cacSAlex Lorenz   }
4440dd86dc5SJohannes Altmanninger   return Value;
4450dd86dc5SJohannes Altmanninger }
4460dd86dc5SJohannes Altmanninger 
getStmtValue(const Stmt * S) const4470dd86dc5SJohannes Altmanninger std::string SyntaxTree::Impl::getStmtValue(const Stmt *S) const {
4480dd86dc5SJohannes Altmanninger   if (auto *U = dyn_cast<UnaryOperator>(S))
449adcd0268SBenjamin Kramer     return std::string(UnaryOperator::getOpcodeStr(U->getOpcode()));
4500dd86dc5SJohannes Altmanninger   if (auto *B = dyn_cast<BinaryOperator>(S))
451adcd0268SBenjamin Kramer     return std::string(B->getOpcodeStr());
4520dd86dc5SJohannes Altmanninger   if (auto *M = dyn_cast<MemberExpr>(S))
4532b955ffaSJohannes Altmanninger     return getRelativeName(M->getMemberDecl());
4540dd86dc5SJohannes Altmanninger   if (auto *I = dyn_cast<IntegerLiteral>(S)) {
455a75b2cacSAlex Lorenz     SmallString<256> Str;
4560dd86dc5SJohannes Altmanninger     I->getValue().toString(Str, /*Radix=*/10, /*Signed=*/false);
457adcd0268SBenjamin Kramer     return std::string(Str.str());
458a75b2cacSAlex Lorenz   }
4590dd86dc5SJohannes Altmanninger   if (auto *F = dyn_cast<FloatingLiteral>(S)) {
4600dd86dc5SJohannes Altmanninger     SmallString<256> Str;
4610dd86dc5SJohannes Altmanninger     F->getValue().toString(Str);
462adcd0268SBenjamin Kramer     return std::string(Str.str());
463a75b2cacSAlex Lorenz   }
4640dd86dc5SJohannes Altmanninger   if (auto *D = dyn_cast<DeclRefExpr>(S))
4652b955ffaSJohannes Altmanninger     return getRelativeName(D->getDecl(), getEnclosingDeclContext(AST, S));
466*7805ae25SDouglas Yung   if (auto *String = dyn_cast<StringLiteral>(S))
467adcd0268SBenjamin Kramer     return std::string(String->getString());
4680dd86dc5SJohannes Altmanninger   if (auto *B = dyn_cast<CXXBoolLiteralExpr>(S))
4690dd86dc5SJohannes Altmanninger     return B->getValue() ? "true" : "false";
470a75b2cacSAlex Lorenz   return "";
471a75b2cacSAlex Lorenz }
472a75b2cacSAlex Lorenz 
473a75b2cacSAlex Lorenz /// Identifies a node in a subtree by its postorder offset, starting at 1.
474a75b2cacSAlex Lorenz struct SNodeId {
475a75b2cacSAlex Lorenz   int Id = 0;
476a75b2cacSAlex Lorenz 
SNodeIdclang::diff::SNodeId477a75b2cacSAlex Lorenz   explicit SNodeId(int Id) : Id(Id) {}
478a75b2cacSAlex Lorenz   explicit SNodeId() = default;
479a75b2cacSAlex Lorenz 
operator intclang::diff::SNodeId480a75b2cacSAlex Lorenz   operator int() const { return Id; }
operator ++clang::diff::SNodeId481a75b2cacSAlex Lorenz   SNodeId &operator++() { return ++Id, *this; }
operator --clang::diff::SNodeId482a75b2cacSAlex Lorenz   SNodeId &operator--() { return --Id, *this; }
operator +clang::diff::SNodeId483a75b2cacSAlex Lorenz   SNodeId operator+(int Other) const { return SNodeId(Id + Other); }
484a75b2cacSAlex Lorenz };
485a75b2cacSAlex Lorenz 
486a75b2cacSAlex Lorenz class Subtree {
487a75b2cacSAlex Lorenz private:
488a75b2cacSAlex Lorenz   /// The parent tree.
48931b52d63SJohannes Altmanninger   const SyntaxTree::Impl &Tree;
490a75b2cacSAlex Lorenz   /// Maps SNodeIds to original ids.
491a75b2cacSAlex Lorenz   std::vector<NodeId> RootIds;
492a75b2cacSAlex Lorenz   /// Maps subtree nodes to their leftmost descendants wtihin the subtree.
493a75b2cacSAlex Lorenz   std::vector<SNodeId> LeftMostDescendants;
494a75b2cacSAlex Lorenz 
495a75b2cacSAlex Lorenz public:
496a75b2cacSAlex Lorenz   std::vector<SNodeId> KeyRoots;
497a75b2cacSAlex Lorenz 
Subtree(const SyntaxTree::Impl & Tree,NodeId SubtreeRoot)49831b52d63SJohannes Altmanninger   Subtree(const SyntaxTree::Impl &Tree, NodeId SubtreeRoot) : Tree(Tree) {
499a75b2cacSAlex Lorenz     RootIds = getSubtreePostorder(Tree, SubtreeRoot);
500a75b2cacSAlex Lorenz     int NumLeaves = setLeftMostDescendants();
501a75b2cacSAlex Lorenz     computeKeyRoots(NumLeaves);
502a75b2cacSAlex Lorenz   }
getSize() const503a75b2cacSAlex Lorenz   int getSize() const { return RootIds.size(); }
getIdInRoot(SNodeId Id) const504a75b2cacSAlex Lorenz   NodeId getIdInRoot(SNodeId Id) const {
505a75b2cacSAlex Lorenz     assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
506a75b2cacSAlex Lorenz     return RootIds[Id - 1];
507a75b2cacSAlex Lorenz   }
getNode(SNodeId Id) const508a75b2cacSAlex Lorenz   const Node &getNode(SNodeId Id) const {
509a75b2cacSAlex Lorenz     return Tree.getNode(getIdInRoot(Id));
510a75b2cacSAlex Lorenz   }
getLeftMostDescendant(SNodeId Id) const511a75b2cacSAlex Lorenz   SNodeId getLeftMostDescendant(SNodeId Id) const {
512a75b2cacSAlex Lorenz     assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
513a75b2cacSAlex Lorenz     return LeftMostDescendants[Id - 1];
514a75b2cacSAlex Lorenz   }
515a75b2cacSAlex Lorenz   /// Returns the postorder index of the leftmost descendant in the subtree.
getPostorderOffset() const516a75b2cacSAlex Lorenz   NodeId getPostorderOffset() const {
517a75b2cacSAlex Lorenz     return Tree.PostorderIds[getIdInRoot(SNodeId(1))];
518a75b2cacSAlex Lorenz   }
getNodeValue(SNodeId Id) const5198b0e0663SJohannes Altmanninger   std::string getNodeValue(SNodeId Id) const {
52031b52d63SJohannes Altmanninger     return Tree.getNodeValue(getIdInRoot(Id));
5218b0e0663SJohannes Altmanninger   }
522a75b2cacSAlex Lorenz 
523a75b2cacSAlex Lorenz private:
524a75b2cacSAlex Lorenz   /// Returns the number of leafs in the subtree.
setLeftMostDescendants()525a75b2cacSAlex Lorenz   int setLeftMostDescendants() {
526a75b2cacSAlex Lorenz     int NumLeaves = 0;
527a75b2cacSAlex Lorenz     LeftMostDescendants.resize(getSize());
528a75b2cacSAlex Lorenz     for (int I = 0; I < getSize(); ++I) {
529a75b2cacSAlex Lorenz       SNodeId SI(I + 1);
530a75b2cacSAlex Lorenz       const Node &N = getNode(SI);
531a75b2cacSAlex Lorenz       NumLeaves += N.isLeaf();
532a75b2cacSAlex Lorenz       assert(I == Tree.PostorderIds[getIdInRoot(SI)] - getPostorderOffset() &&
533a75b2cacSAlex Lorenz              "Postorder traversal in subtree should correspond to traversal in "
534a75b2cacSAlex Lorenz              "the root tree by a constant offset.");
535a75b2cacSAlex Lorenz       LeftMostDescendants[I] = SNodeId(Tree.PostorderIds[N.LeftMostDescendant] -
536a75b2cacSAlex Lorenz                                        getPostorderOffset());
537a75b2cacSAlex Lorenz     }
538a75b2cacSAlex Lorenz     return NumLeaves;
539a75b2cacSAlex Lorenz   }
computeKeyRoots(int Leaves)540a75b2cacSAlex Lorenz   void computeKeyRoots(int Leaves) {
541a75b2cacSAlex Lorenz     KeyRoots.resize(Leaves);
542a75b2cacSAlex Lorenz     std::unordered_set<int> Visited;
543a75b2cacSAlex Lorenz     int K = Leaves - 1;
544a75b2cacSAlex Lorenz     for (SNodeId I(getSize()); I > 0; --I) {
545a75b2cacSAlex Lorenz       SNodeId LeftDesc = getLeftMostDescendant(I);
546a75b2cacSAlex Lorenz       if (Visited.count(LeftDesc))
547a75b2cacSAlex Lorenz         continue;
548a75b2cacSAlex Lorenz       assert(K >= 0 && "K should be non-negative");
549a75b2cacSAlex Lorenz       KeyRoots[K] = I;
550a75b2cacSAlex Lorenz       Visited.insert(LeftDesc);
551a75b2cacSAlex Lorenz       --K;
552a75b2cacSAlex Lorenz     }
553a75b2cacSAlex Lorenz   }
554a75b2cacSAlex Lorenz };
555a75b2cacSAlex Lorenz 
556a75b2cacSAlex Lorenz /// Implementation of Zhang and Shasha's Algorithm for tree edit distance.
557a75b2cacSAlex Lorenz /// Computes an optimal mapping between two trees using only insertion,
558a75b2cacSAlex Lorenz /// deletion and update as edit actions (similar to the Levenshtein distance).
559a75b2cacSAlex Lorenz class ZhangShashaMatcher {
560a75b2cacSAlex Lorenz   const ASTDiff::Impl &DiffImpl;
561a75b2cacSAlex Lorenz   Subtree S1;
562a75b2cacSAlex Lorenz   Subtree S2;
563a75b2cacSAlex Lorenz   std::unique_ptr<std::unique_ptr<double[]>[]> TreeDist, ForestDist;
564a75b2cacSAlex Lorenz 
565a75b2cacSAlex Lorenz public:
ZhangShashaMatcher(const ASTDiff::Impl & DiffImpl,const SyntaxTree::Impl & T1,const SyntaxTree::Impl & T2,NodeId Id1,NodeId Id2)56631b52d63SJohannes Altmanninger   ZhangShashaMatcher(const ASTDiff::Impl &DiffImpl, const SyntaxTree::Impl &T1,
56731b52d63SJohannes Altmanninger                      const SyntaxTree::Impl &T2, NodeId Id1, NodeId Id2)
568a75b2cacSAlex Lorenz       : DiffImpl(DiffImpl), S1(T1, Id1), S2(T2, Id2) {
5692b3d49b6SJonas Devlieghere     TreeDist = std::make_unique<std::unique_ptr<double[]>[]>(
570a75b2cacSAlex Lorenz         size_t(S1.getSize()) + 1);
5712b3d49b6SJonas Devlieghere     ForestDist = std::make_unique<std::unique_ptr<double[]>[]>(
572a75b2cacSAlex Lorenz         size_t(S1.getSize()) + 1);
573a75b2cacSAlex Lorenz     for (int I = 0, E = S1.getSize() + 1; I < E; ++I) {
5742b3d49b6SJonas Devlieghere       TreeDist[I] = std::make_unique<double[]>(size_t(S2.getSize()) + 1);
5752b3d49b6SJonas Devlieghere       ForestDist[I] = std::make_unique<double[]>(size_t(S2.getSize()) + 1);
576a75b2cacSAlex Lorenz     }
577a75b2cacSAlex Lorenz   }
578a75b2cacSAlex Lorenz 
getMatchingNodes()579a75b2cacSAlex Lorenz   std::vector<std::pair<NodeId, NodeId>> getMatchingNodes() {
580a75b2cacSAlex Lorenz     std::vector<std::pair<NodeId, NodeId>> Matches;
581a75b2cacSAlex Lorenz     std::vector<std::pair<SNodeId, SNodeId>> TreePairs;
582a75b2cacSAlex Lorenz 
583a75b2cacSAlex Lorenz     computeTreeDist();
584a75b2cacSAlex Lorenz 
585a75b2cacSAlex Lorenz     bool RootNodePair = true;
586a75b2cacSAlex Lorenz 
5874c0a8660SAlex Lorenz     TreePairs.emplace_back(SNodeId(S1.getSize()), SNodeId(S2.getSize()));
588a75b2cacSAlex Lorenz 
589a75b2cacSAlex Lorenz     while (!TreePairs.empty()) {
590a75b2cacSAlex Lorenz       SNodeId LastRow, LastCol, FirstRow, FirstCol, Row, Col;
591a75b2cacSAlex Lorenz       std::tie(LastRow, LastCol) = TreePairs.back();
592a75b2cacSAlex Lorenz       TreePairs.pop_back();
593a75b2cacSAlex Lorenz 
594a75b2cacSAlex Lorenz       if (!RootNodePair) {
595a75b2cacSAlex Lorenz         computeForestDist(LastRow, LastCol);
596a75b2cacSAlex Lorenz       }
597a75b2cacSAlex Lorenz 
598a75b2cacSAlex Lorenz       RootNodePair = false;
599a75b2cacSAlex Lorenz 
600a75b2cacSAlex Lorenz       FirstRow = S1.getLeftMostDescendant(LastRow);
601a75b2cacSAlex Lorenz       FirstCol = S2.getLeftMostDescendant(LastCol);
602a75b2cacSAlex Lorenz 
603a75b2cacSAlex Lorenz       Row = LastRow;
604a75b2cacSAlex Lorenz       Col = LastCol;
605a75b2cacSAlex Lorenz 
606a75b2cacSAlex Lorenz       while (Row > FirstRow || Col > FirstCol) {
607a75b2cacSAlex Lorenz         if (Row > FirstRow &&
608a75b2cacSAlex Lorenz             ForestDist[Row - 1][Col] + 1 == ForestDist[Row][Col]) {
609a75b2cacSAlex Lorenz           --Row;
610a75b2cacSAlex Lorenz         } else if (Col > FirstCol &&
611a75b2cacSAlex Lorenz                    ForestDist[Row][Col - 1] + 1 == ForestDist[Row][Col]) {
612a75b2cacSAlex Lorenz           --Col;
613a75b2cacSAlex Lorenz         } else {
614a75b2cacSAlex Lorenz           SNodeId LMD1 = S1.getLeftMostDescendant(Row);
615a75b2cacSAlex Lorenz           SNodeId LMD2 = S2.getLeftMostDescendant(Col);
616a75b2cacSAlex Lorenz           if (LMD1 == S1.getLeftMostDescendant(LastRow) &&
617a75b2cacSAlex Lorenz               LMD2 == S2.getLeftMostDescendant(LastCol)) {
618a75b2cacSAlex Lorenz             NodeId Id1 = S1.getIdInRoot(Row);
619a75b2cacSAlex Lorenz             NodeId Id2 = S2.getIdInRoot(Col);
620a75b2cacSAlex Lorenz             assert(DiffImpl.isMatchingPossible(Id1, Id2) &&
621a75b2cacSAlex Lorenz                    "These nodes must not be matched.");
622a75b2cacSAlex Lorenz             Matches.emplace_back(Id1, Id2);
623a75b2cacSAlex Lorenz             --Row;
624a75b2cacSAlex Lorenz             --Col;
625a75b2cacSAlex Lorenz           } else {
626a75b2cacSAlex Lorenz             TreePairs.emplace_back(Row, Col);
627a75b2cacSAlex Lorenz             Row = LMD1;
628a75b2cacSAlex Lorenz             Col = LMD2;
629a75b2cacSAlex Lorenz           }
630a75b2cacSAlex Lorenz         }
631a75b2cacSAlex Lorenz       }
632a75b2cacSAlex Lorenz     }
633a75b2cacSAlex Lorenz     return Matches;
634a75b2cacSAlex Lorenz   }
635a75b2cacSAlex Lorenz 
636a75b2cacSAlex Lorenz private:
637fa524d7bSJohannes Altmanninger   /// We use a simple cost model for edit actions, which seems good enough.
638fa524d7bSJohannes Altmanninger   /// Simple cost model for edit actions. This seems to make the matching
639fa524d7bSJohannes Altmanninger   /// algorithm perform reasonably well.
640a75b2cacSAlex Lorenz   /// The values range between 0 and 1, or infinity if this edit action should
641a75b2cacSAlex Lorenz   /// always be avoided.
642a75b2cacSAlex Lorenz   static constexpr double DeletionCost = 1;
643a75b2cacSAlex Lorenz   static constexpr double InsertionCost = 1;
644a75b2cacSAlex Lorenz 
getUpdateCost(SNodeId Id1,SNodeId Id2)645a75b2cacSAlex Lorenz   double getUpdateCost(SNodeId Id1, SNodeId Id2) {
6468b0e0663SJohannes Altmanninger     if (!DiffImpl.isMatchingPossible(S1.getIdInRoot(Id1), S2.getIdInRoot(Id2)))
647a75b2cacSAlex Lorenz       return std::numeric_limits<double>::max();
6488b0e0663SJohannes Altmanninger     return S1.getNodeValue(Id1) != S2.getNodeValue(Id2);
649a75b2cacSAlex Lorenz   }
650a75b2cacSAlex Lorenz 
computeTreeDist()651a75b2cacSAlex Lorenz   void computeTreeDist() {
652a75b2cacSAlex Lorenz     for (SNodeId Id1 : S1.KeyRoots)
653a75b2cacSAlex Lorenz       for (SNodeId Id2 : S2.KeyRoots)
654a75b2cacSAlex Lorenz         computeForestDist(Id1, Id2);
655a75b2cacSAlex Lorenz   }
656a75b2cacSAlex Lorenz 
computeForestDist(SNodeId Id1,SNodeId Id2)657a75b2cacSAlex Lorenz   void computeForestDist(SNodeId Id1, SNodeId Id2) {
658a75b2cacSAlex Lorenz     assert(Id1 > 0 && Id2 > 0 && "Expecting offsets greater than 0.");
659a75b2cacSAlex Lorenz     SNodeId LMD1 = S1.getLeftMostDescendant(Id1);
660a75b2cacSAlex Lorenz     SNodeId LMD2 = S2.getLeftMostDescendant(Id2);
661a75b2cacSAlex Lorenz 
662a75b2cacSAlex Lorenz     ForestDist[LMD1][LMD2] = 0;
663a75b2cacSAlex Lorenz     for (SNodeId D1 = LMD1 + 1; D1 <= Id1; ++D1) {
664a75b2cacSAlex Lorenz       ForestDist[D1][LMD2] = ForestDist[D1 - 1][LMD2] + DeletionCost;
665a75b2cacSAlex Lorenz       for (SNodeId D2 = LMD2 + 1; D2 <= Id2; ++D2) {
666a75b2cacSAlex Lorenz         ForestDist[LMD1][D2] = ForestDist[LMD1][D2 - 1] + InsertionCost;
667a75b2cacSAlex Lorenz         SNodeId DLMD1 = S1.getLeftMostDescendant(D1);
668a75b2cacSAlex Lorenz         SNodeId DLMD2 = S2.getLeftMostDescendant(D2);
669a75b2cacSAlex Lorenz         if (DLMD1 == LMD1 && DLMD2 == LMD2) {
670a75b2cacSAlex Lorenz           double UpdateCost = getUpdateCost(D1, D2);
671a75b2cacSAlex Lorenz           ForestDist[D1][D2] =
672a75b2cacSAlex Lorenz               std::min({ForestDist[D1 - 1][D2] + DeletionCost,
673a75b2cacSAlex Lorenz                         ForestDist[D1][D2 - 1] + InsertionCost,
674a75b2cacSAlex Lorenz                         ForestDist[D1 - 1][D2 - 1] + UpdateCost});
675a75b2cacSAlex Lorenz           TreeDist[D1][D2] = ForestDist[D1][D2];
676a75b2cacSAlex Lorenz         } else {
677a75b2cacSAlex Lorenz           ForestDist[D1][D2] =
678a75b2cacSAlex Lorenz               std::min({ForestDist[D1 - 1][D2] + DeletionCost,
679a75b2cacSAlex Lorenz                         ForestDist[D1][D2 - 1] + InsertionCost,
680a75b2cacSAlex Lorenz                         ForestDist[DLMD1][DLMD2] + TreeDist[D1][D2]});
681a75b2cacSAlex Lorenz         }
682a75b2cacSAlex Lorenz       }
683a75b2cacSAlex Lorenz     }
684a75b2cacSAlex Lorenz   }
685a75b2cacSAlex Lorenz };
686a75b2cacSAlex Lorenz 
getType() const687cd625114SReid Kleckner ASTNodeKind Node::getType() const { return ASTNode.getNodeKind(); }
6880da12c84SJohannes Altmanninger 
getTypeLabel() const6890da12c84SJohannes Altmanninger StringRef Node::getTypeLabel() const { return getType().asStringRef(); }
6900da12c84SJohannes Altmanninger 
getQualifiedIdentifier() const6910dd86dc5SJohannes Altmanninger llvm::Optional<std::string> Node::getQualifiedIdentifier() const {
6920dd86dc5SJohannes Altmanninger   if (auto *ND = ASTNode.get<NamedDecl>()) {
6930dd86dc5SJohannes Altmanninger     if (ND->getDeclName().isIdentifier())
6940dd86dc5SJohannes Altmanninger       return ND->getQualifiedNameAsString();
6950dd86dc5SJohannes Altmanninger   }
6960dd86dc5SJohannes Altmanninger   return llvm::None;
6970dd86dc5SJohannes Altmanninger }
6980dd86dc5SJohannes Altmanninger 
getIdentifier() const6990dd86dc5SJohannes Altmanninger llvm::Optional<StringRef> Node::getIdentifier() const {
7000dd86dc5SJohannes Altmanninger   if (auto *ND = ASTNode.get<NamedDecl>()) {
7010dd86dc5SJohannes Altmanninger     if (ND->getDeclName().isIdentifier())
7020dd86dc5SJohannes Altmanninger       return ND->getName();
7030dd86dc5SJohannes Altmanninger   }
7040dd86dc5SJohannes Altmanninger   return llvm::None;
7050dd86dc5SJohannes Altmanninger }
7060dd86dc5SJohannes Altmanninger 
707a75b2cacSAlex Lorenz namespace {
708a75b2cacSAlex Lorenz // Compares nodes by their depth.
709a75b2cacSAlex Lorenz struct HeightLess {
71031b52d63SJohannes Altmanninger   const SyntaxTree::Impl &Tree;
HeightLessclang::diff::__anonb3398b060511::HeightLess71131b52d63SJohannes Altmanninger   HeightLess(const SyntaxTree::Impl &Tree) : Tree(Tree) {}
operator ()clang::diff::__anonb3398b060511::HeightLess712a75b2cacSAlex Lorenz   bool operator()(NodeId Id1, NodeId Id2) const {
713a75b2cacSAlex Lorenz     return Tree.getNode(Id1).Height < Tree.getNode(Id2).Height;
714a75b2cacSAlex Lorenz   }
715a75b2cacSAlex Lorenz };
716a75b2cacSAlex Lorenz } // end anonymous namespace
717a75b2cacSAlex Lorenz 
718fa524d7bSJohannes Altmanninger namespace {
719a75b2cacSAlex Lorenz // Priority queue for nodes, sorted descendingly by their height.
720a75b2cacSAlex Lorenz class PriorityList {
72131b52d63SJohannes Altmanninger   const SyntaxTree::Impl &Tree;
722a75b2cacSAlex Lorenz   HeightLess Cmp;
723a75b2cacSAlex Lorenz   std::vector<NodeId> Container;
724a75b2cacSAlex Lorenz   PriorityQueue<NodeId, std::vector<NodeId>, HeightLess> List;
725a75b2cacSAlex Lorenz 
726a75b2cacSAlex Lorenz public:
PriorityList(const SyntaxTree::Impl & Tree)72731b52d63SJohannes Altmanninger   PriorityList(const SyntaxTree::Impl &Tree)
728a75b2cacSAlex Lorenz       : Tree(Tree), Cmp(Tree), List(Cmp, Container) {}
729a75b2cacSAlex Lorenz 
push(NodeId id)730a75b2cacSAlex Lorenz   void push(NodeId id) { List.push(id); }
731a75b2cacSAlex Lorenz 
pop()732a75b2cacSAlex Lorenz   std::vector<NodeId> pop() {
733a75b2cacSAlex Lorenz     int Max = peekMax();
734a75b2cacSAlex Lorenz     std::vector<NodeId> Result;
735a75b2cacSAlex Lorenz     if (Max == 0)
736a75b2cacSAlex Lorenz       return Result;
737a75b2cacSAlex Lorenz     while (peekMax() == Max) {
738a75b2cacSAlex Lorenz       Result.push_back(List.top());
739a75b2cacSAlex Lorenz       List.pop();
740a75b2cacSAlex Lorenz     }
741a75b2cacSAlex Lorenz     // TODO this is here to get a stable output, not a good heuristic
74255fab260SFangrui Song     llvm::sort(Result);
743a75b2cacSAlex Lorenz     return Result;
744a75b2cacSAlex Lorenz   }
peekMax() const745a75b2cacSAlex Lorenz   int peekMax() const {
746a75b2cacSAlex Lorenz     if (List.empty())
747a75b2cacSAlex Lorenz       return 0;
748a75b2cacSAlex Lorenz     return Tree.getNode(List.top()).Height;
749a75b2cacSAlex Lorenz   }
open(NodeId Id)750a75b2cacSAlex Lorenz   void open(NodeId Id) {
751a75b2cacSAlex Lorenz     for (NodeId Child : Tree.getNode(Id).Children)
752a75b2cacSAlex Lorenz       push(Child);
753a75b2cacSAlex Lorenz   }
754a75b2cacSAlex Lorenz };
755fa524d7bSJohannes Altmanninger } // end anonymous namespace
756a75b2cacSAlex Lorenz 
identical(NodeId Id1,NodeId Id2) const75731b52d63SJohannes Altmanninger bool ASTDiff::Impl::identical(NodeId Id1, NodeId Id2) const {
758a75b2cacSAlex Lorenz   const Node &N1 = T1.getNode(Id1);
759a75b2cacSAlex Lorenz   const Node &N2 = T2.getNode(Id2);
760a75b2cacSAlex Lorenz   if (N1.Children.size() != N2.Children.size() ||
761a75b2cacSAlex Lorenz       !isMatchingPossible(Id1, Id2) ||
76231b52d63SJohannes Altmanninger       T1.getNodeValue(Id1) != T2.getNodeValue(Id2))
763a75b2cacSAlex Lorenz     return false;
764a75b2cacSAlex Lorenz   for (size_t Id = 0, E = N1.Children.size(); Id < E; ++Id)
76531b52d63SJohannes Altmanninger     if (!identical(N1.Children[Id], N2.Children[Id]))
766a75b2cacSAlex Lorenz       return false;
767a75b2cacSAlex Lorenz   return true;
768a75b2cacSAlex Lorenz }
769a75b2cacSAlex Lorenz 
isMatchingPossible(NodeId Id1,NodeId Id2) const770a75b2cacSAlex Lorenz bool ASTDiff::Impl::isMatchingPossible(NodeId Id1, NodeId Id2) const {
771e0fe5cd4SJohannes Altmanninger   return Options.isMatchingAllowed(T1.getNode(Id1), T2.getNode(Id2));
772e0fe5cd4SJohannes Altmanninger }
773e0fe5cd4SJohannes Altmanninger 
haveSameParents(const Mapping & M,NodeId Id1,NodeId Id2) const774e0fe5cd4SJohannes Altmanninger bool ASTDiff::Impl::haveSameParents(const Mapping &M, NodeId Id1,
775e0fe5cd4SJohannes Altmanninger                                     NodeId Id2) const {
776e0fe5cd4SJohannes Altmanninger   NodeId P1 = T1.getNode(Id1).Parent;
777e0fe5cd4SJohannes Altmanninger   NodeId P2 = T2.getNode(Id2).Parent;
778e0fe5cd4SJohannes Altmanninger   return (P1.isInvalid() && P2.isInvalid()) ||
779e0fe5cd4SJohannes Altmanninger          (P1.isValid() && P2.isValid() && M.getDst(P1) == P2);
780a75b2cacSAlex Lorenz }
781a75b2cacSAlex Lorenz 
addOptimalMapping(Mapping & M,NodeId Id1,NodeId Id2) const782a75b2cacSAlex Lorenz void ASTDiff::Impl::addOptimalMapping(Mapping &M, NodeId Id1,
783a75b2cacSAlex Lorenz                                       NodeId Id2) const {
784d1969307SJohannes Altmanninger   if (std::max(T1.getNumberOfDescendants(Id1), T2.getNumberOfDescendants(Id2)) >
785d1969307SJohannes Altmanninger       Options.MaxSize)
786a75b2cacSAlex Lorenz     return;
787a75b2cacSAlex Lorenz   ZhangShashaMatcher Matcher(*this, T1, T2, Id1, Id2);
788a75b2cacSAlex Lorenz   std::vector<std::pair<NodeId, NodeId>> R = Matcher.getMatchingNodes();
7898dc7b982SMark de Wever   for (const auto &Tuple : R) {
790a75b2cacSAlex Lorenz     NodeId Src = Tuple.first;
791a75b2cacSAlex Lorenz     NodeId Dst = Tuple.second;
79251321aefSJohannes Altmanninger     if (!M.hasSrc(Src) && !M.hasDst(Dst))
793a75b2cacSAlex Lorenz       M.link(Src, Dst);
794a75b2cacSAlex Lorenz   }
795a75b2cacSAlex Lorenz }
796a75b2cacSAlex Lorenz 
getJaccardSimilarity(const Mapping & M,NodeId Id1,NodeId Id2) const797d1969307SJohannes Altmanninger double ASTDiff::Impl::getJaccardSimilarity(const Mapping &M, NodeId Id1,
798a75b2cacSAlex Lorenz                                            NodeId Id2) const {
799a75b2cacSAlex Lorenz   int CommonDescendants = 0;
800a75b2cacSAlex Lorenz   const Node &N1 = T1.getNode(Id1);
801d1969307SJohannes Altmanninger   // Count the common descendants, excluding the subtree root.
802d1969307SJohannes Altmanninger   for (NodeId Src = Id1 + 1; Src <= N1.RightMostDescendant; ++Src) {
803d1969307SJohannes Altmanninger     NodeId Dst = M.getDst(Src);
804d1969307SJohannes Altmanninger     CommonDescendants += int(Dst.isValid() && T2.isInSubtree(Dst, Id2));
805d1969307SJohannes Altmanninger   }
806d1969307SJohannes Altmanninger   // We need to subtract 1 to get the number of descendants excluding the root.
807d1969307SJohannes Altmanninger   double Denominator = T1.getNumberOfDescendants(Id1) - 1 +
808d1969307SJohannes Altmanninger                        T2.getNumberOfDescendants(Id2) - 1 - CommonDescendants;
809d1969307SJohannes Altmanninger   // CommonDescendants is less than the size of one subtree.
810d1969307SJohannes Altmanninger   assert(Denominator >= 0 && "Expected non-negative denominator.");
811d1969307SJohannes Altmanninger   if (Denominator == 0)
812d1969307SJohannes Altmanninger     return 0;
813d1969307SJohannes Altmanninger   return CommonDescendants / Denominator;
814a75b2cacSAlex Lorenz }
815a75b2cacSAlex Lorenz 
findCandidate(const Mapping & M,NodeId Id1) const816a75b2cacSAlex Lorenz NodeId ASTDiff::Impl::findCandidate(const Mapping &M, NodeId Id1) const {
817a75b2cacSAlex Lorenz   NodeId Candidate;
81831b52d63SJohannes Altmanninger   double HighestSimilarity = 0.0;
819e0fe5cd4SJohannes Altmanninger   for (NodeId Id2 : T2) {
820a75b2cacSAlex Lorenz     if (!isMatchingPossible(Id1, Id2))
821a75b2cacSAlex Lorenz       continue;
822a75b2cacSAlex Lorenz     if (M.hasDst(Id2))
823a75b2cacSAlex Lorenz       continue;
824d1969307SJohannes Altmanninger     double Similarity = getJaccardSimilarity(M, Id1, Id2);
825fa524d7bSJohannes Altmanninger     if (Similarity >= Options.MinSimilarity && Similarity > HighestSimilarity) {
82631b52d63SJohannes Altmanninger       HighestSimilarity = Similarity;
827a75b2cacSAlex Lorenz       Candidate = Id2;
828a75b2cacSAlex Lorenz     }
829a75b2cacSAlex Lorenz   }
830a75b2cacSAlex Lorenz   return Candidate;
831a75b2cacSAlex Lorenz }
832a75b2cacSAlex Lorenz 
matchBottomUp(Mapping & M) const833a75b2cacSAlex Lorenz void ASTDiff::Impl::matchBottomUp(Mapping &M) const {
83431b52d63SJohannes Altmanninger   std::vector<NodeId> Postorder = getSubtreePostorder(T1, T1.getRootId());
835a75b2cacSAlex Lorenz   for (NodeId Id1 : Postorder) {
836fa524d7bSJohannes Altmanninger     if (Id1 == T1.getRootId() && !M.hasSrc(T1.getRootId()) &&
837fa524d7bSJohannes Altmanninger         !M.hasDst(T2.getRootId())) {
83831b52d63SJohannes Altmanninger       if (isMatchingPossible(T1.getRootId(), T2.getRootId())) {
83931b52d63SJohannes Altmanninger         M.link(T1.getRootId(), T2.getRootId());
84031b52d63SJohannes Altmanninger         addOptimalMapping(M, T1.getRootId(), T2.getRootId());
841a75b2cacSAlex Lorenz       }
842a75b2cacSAlex Lorenz       break;
843a75b2cacSAlex Lorenz     }
844a75b2cacSAlex Lorenz     bool Matched = M.hasSrc(Id1);
845d1969307SJohannes Altmanninger     const Node &N1 = T1.getNode(Id1);
8463117b17bSFangrui Song     bool MatchedChildren = llvm::any_of(
8473117b17bSFangrui Song         N1.Children, [&](NodeId Child) { return M.hasSrc(Child); });
848a75b2cacSAlex Lorenz     if (Matched || !MatchedChildren)
849a75b2cacSAlex Lorenz       continue;
850a75b2cacSAlex Lorenz     NodeId Id2 = findCandidate(M, Id1);
85151321aefSJohannes Altmanninger     if (Id2.isValid()) {
852a75b2cacSAlex Lorenz       M.link(Id1, Id2);
853a75b2cacSAlex Lorenz       addOptimalMapping(M, Id1, Id2);
854a75b2cacSAlex Lorenz     }
855a75b2cacSAlex Lorenz   }
856fa524d7bSJohannes Altmanninger }
857a75b2cacSAlex Lorenz 
matchTopDown() const858a75b2cacSAlex Lorenz Mapping ASTDiff::Impl::matchTopDown() const {
859a75b2cacSAlex Lorenz   PriorityList L1(T1);
860a75b2cacSAlex Lorenz   PriorityList L2(T2);
861a75b2cacSAlex Lorenz 
86251321aefSJohannes Altmanninger   Mapping M(T1.getSize() + T2.getSize());
863a75b2cacSAlex Lorenz 
86431b52d63SJohannes Altmanninger   L1.push(T1.getRootId());
86531b52d63SJohannes Altmanninger   L2.push(T2.getRootId());
866a75b2cacSAlex Lorenz 
867a75b2cacSAlex Lorenz   int Max1, Max2;
868a75b2cacSAlex Lorenz   while (std::min(Max1 = L1.peekMax(), Max2 = L2.peekMax()) >
869a75b2cacSAlex Lorenz          Options.MinHeight) {
870a75b2cacSAlex Lorenz     if (Max1 > Max2) {
871a75b2cacSAlex Lorenz       for (NodeId Id : L1.pop())
872a75b2cacSAlex Lorenz         L1.open(Id);
873a75b2cacSAlex Lorenz       continue;
874a75b2cacSAlex Lorenz     }
875a75b2cacSAlex Lorenz     if (Max2 > Max1) {
876a75b2cacSAlex Lorenz       for (NodeId Id : L2.pop())
877a75b2cacSAlex Lorenz         L2.open(Id);
878a75b2cacSAlex Lorenz       continue;
879a75b2cacSAlex Lorenz     }
880a75b2cacSAlex Lorenz     std::vector<NodeId> H1, H2;
881a75b2cacSAlex Lorenz     H1 = L1.pop();
882a75b2cacSAlex Lorenz     H2 = L2.pop();
883a75b2cacSAlex Lorenz     for (NodeId Id1 : H1) {
884fa524d7bSJohannes Altmanninger       for (NodeId Id2 : H2) {
88551321aefSJohannes Altmanninger         if (identical(Id1, Id2) && !M.hasSrc(Id1) && !M.hasDst(Id2)) {
886fa524d7bSJohannes Altmanninger           for (int I = 0, E = T1.getNumberOfDescendants(Id1); I < E; ++I)
887fa524d7bSJohannes Altmanninger             M.link(Id1 + I, Id2 + I);
888fa524d7bSJohannes Altmanninger         }
889fa524d7bSJohannes Altmanninger       }
890a75b2cacSAlex Lorenz     }
891a75b2cacSAlex Lorenz     for (NodeId Id1 : H1) {
892a75b2cacSAlex Lorenz       if (!M.hasSrc(Id1))
893a75b2cacSAlex Lorenz         L1.open(Id1);
894a75b2cacSAlex Lorenz     }
895a75b2cacSAlex Lorenz     for (NodeId Id2 : H2) {
896a75b2cacSAlex Lorenz       if (!M.hasDst(Id2))
897a75b2cacSAlex Lorenz         L2.open(Id2);
898a75b2cacSAlex Lorenz     }
899a75b2cacSAlex Lorenz   }
900a75b2cacSAlex Lorenz   return M;
901a75b2cacSAlex Lorenz }
902a75b2cacSAlex Lorenz 
Impl(SyntaxTree::Impl & T1,SyntaxTree::Impl & T2,const ComparisonOptions & Options)903e0fe5cd4SJohannes Altmanninger ASTDiff::Impl::Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
904e0fe5cd4SJohannes Altmanninger                     const ComparisonOptions &Options)
905e0fe5cd4SJohannes Altmanninger     : T1(T1), T2(T2), Options(Options) {
906e0fe5cd4SJohannes Altmanninger   computeMapping();
907e0fe5cd4SJohannes Altmanninger   computeChangeKinds(TheMapping);
908e0fe5cd4SJohannes Altmanninger }
909e0fe5cd4SJohannes Altmanninger 
computeMapping()910a75b2cacSAlex Lorenz void ASTDiff::Impl::computeMapping() {
911a75b2cacSAlex Lorenz   TheMapping = matchTopDown();
912d1969307SJohannes Altmanninger   if (Options.StopAfterTopDown)
913d1969307SJohannes Altmanninger     return;
914a75b2cacSAlex Lorenz   matchBottomUp(TheMapping);
915a75b2cacSAlex Lorenz }
916a75b2cacSAlex Lorenz 
computeChangeKinds(Mapping & M)917e0fe5cd4SJohannes Altmanninger void ASTDiff::Impl::computeChangeKinds(Mapping &M) {
918e0fe5cd4SJohannes Altmanninger   for (NodeId Id1 : T1) {
919e0fe5cd4SJohannes Altmanninger     if (!M.hasSrc(Id1)) {
920e0fe5cd4SJohannes Altmanninger       T1.getMutableNode(Id1).Change = Delete;
921e0fe5cd4SJohannes Altmanninger       T1.getMutableNode(Id1).Shift -= 1;
922a75b2cacSAlex Lorenz     }
923a75b2cacSAlex Lorenz   }
924e0fe5cd4SJohannes Altmanninger   for (NodeId Id2 : T2) {
925e0fe5cd4SJohannes Altmanninger     if (!M.hasDst(Id2)) {
926e0fe5cd4SJohannes Altmanninger       T2.getMutableNode(Id2).Change = Insert;
927e0fe5cd4SJohannes Altmanninger       T2.getMutableNode(Id2).Shift -= 1;
928a75b2cacSAlex Lorenz     }
929a75b2cacSAlex Lorenz   }
930e0fe5cd4SJohannes Altmanninger   for (NodeId Id1 : T1.NodesBfs) {
931a75b2cacSAlex Lorenz     NodeId Id2 = M.getDst(Id1);
932a75b2cacSAlex Lorenz     if (Id2.isInvalid())
933e0fe5cd4SJohannes Altmanninger       continue;
934e0fe5cd4SJohannes Altmanninger     if (!haveSameParents(M, Id1, Id2) ||
935e0fe5cd4SJohannes Altmanninger         T1.findPositionInParent(Id1, true) !=
936e0fe5cd4SJohannes Altmanninger             T2.findPositionInParent(Id2, true)) {
937e0fe5cd4SJohannes Altmanninger       T1.getMutableNode(Id1).Shift -= 1;
938e0fe5cd4SJohannes Altmanninger       T2.getMutableNode(Id2).Shift -= 1;
939a75b2cacSAlex Lorenz     }
940a75b2cacSAlex Lorenz   }
941e0fe5cd4SJohannes Altmanninger   for (NodeId Id2 : T2.NodesBfs) {
942e0fe5cd4SJohannes Altmanninger     NodeId Id1 = M.getSrc(Id2);
943e0fe5cd4SJohannes Altmanninger     if (Id1.isInvalid())
944e0fe5cd4SJohannes Altmanninger       continue;
945e0fe5cd4SJohannes Altmanninger     Node &N1 = T1.getMutableNode(Id1);
946e0fe5cd4SJohannes Altmanninger     Node &N2 = T2.getMutableNode(Id2);
947e0fe5cd4SJohannes Altmanninger     if (Id1.isInvalid())
948e0fe5cd4SJohannes Altmanninger       continue;
949e0fe5cd4SJohannes Altmanninger     if (!haveSameParents(M, Id1, Id2) ||
950e0fe5cd4SJohannes Altmanninger         T1.findPositionInParent(Id1, true) !=
951e0fe5cd4SJohannes Altmanninger             T2.findPositionInParent(Id2, true)) {
952e0fe5cd4SJohannes Altmanninger       N1.Change = N2.Change = Move;
953a75b2cacSAlex Lorenz     }
954e0fe5cd4SJohannes Altmanninger     if (T1.getNodeValue(Id1) != T2.getNodeValue(Id2)) {
955e0fe5cd4SJohannes Altmanninger       N1.Change = N2.Change = (N1.Change == Move ? UpdateMove : Update);
956e0fe5cd4SJohannes Altmanninger     }
957e0fe5cd4SJohannes Altmanninger   }
958a75b2cacSAlex Lorenz }
959a75b2cacSAlex Lorenz 
ASTDiff(SyntaxTree & T1,SyntaxTree & T2,const ComparisonOptions & Options)960a75b2cacSAlex Lorenz ASTDiff::ASTDiff(SyntaxTree &T1, SyntaxTree &T2,
961a75b2cacSAlex Lorenz                  const ComparisonOptions &Options)
9622b3d49b6SJonas Devlieghere     : DiffImpl(std::make_unique<Impl>(*T1.TreeImpl, *T2.TreeImpl, Options)) {}
963a75b2cacSAlex Lorenz 
96431b52d63SJohannes Altmanninger ASTDiff::~ASTDiff() = default;
965a75b2cacSAlex Lorenz 
getMapped(const SyntaxTree & SourceTree,NodeId Id) const966e0fe5cd4SJohannes Altmanninger NodeId ASTDiff::getMapped(const SyntaxTree &SourceTree, NodeId Id) const {
967e0fe5cd4SJohannes Altmanninger   return DiffImpl->getMapped(SourceTree.TreeImpl, Id);
968e0fe5cd4SJohannes Altmanninger }
969e0fe5cd4SJohannes Altmanninger 
SyntaxTree(ASTContext & AST)9702b955ffaSJohannes Altmanninger SyntaxTree::SyntaxTree(ASTContext &AST)
9712b3d49b6SJonas Devlieghere     : TreeImpl(std::make_unique<SyntaxTree::Impl>(
972a75b2cacSAlex Lorenz           this, AST.getTranslationUnitDecl(), AST)) {}
973a75b2cacSAlex Lorenz 
9748b0e0663SJohannes Altmanninger SyntaxTree::~SyntaxTree() = default;
9758b0e0663SJohannes Altmanninger 
getASTContext() const9760da12c84SJohannes Altmanninger const ASTContext &SyntaxTree::getASTContext() const { return TreeImpl->AST; }
9770da12c84SJohannes Altmanninger 
getNode(NodeId Id) const9780da12c84SJohannes Altmanninger const Node &SyntaxTree::getNode(NodeId Id) const {
9790da12c84SJohannes Altmanninger   return TreeImpl->getNode(Id);
9800da12c84SJohannes Altmanninger }
9810da12c84SJohannes Altmanninger 
getSize() const982e0fe5cd4SJohannes Altmanninger int SyntaxTree::getSize() const { return TreeImpl->getSize(); }
getRootId() const9830da12c84SJohannes Altmanninger NodeId SyntaxTree::getRootId() const { return TreeImpl->getRootId(); }
begin() const984e0fe5cd4SJohannes Altmanninger SyntaxTree::PreorderIterator SyntaxTree::begin() const {
985e0fe5cd4SJohannes Altmanninger   return TreeImpl->begin();
986e0fe5cd4SJohannes Altmanninger }
end() const987e0fe5cd4SJohannes Altmanninger SyntaxTree::PreorderIterator SyntaxTree::end() const { return TreeImpl->end(); }
9880da12c84SJohannes Altmanninger 
findPositionInParent(NodeId Id) const989e0fe5cd4SJohannes Altmanninger int SyntaxTree::findPositionInParent(NodeId Id) const {
990e0fe5cd4SJohannes Altmanninger   return TreeImpl->findPositionInParent(Id);
991e0fe5cd4SJohannes Altmanninger }
992e0fe5cd4SJohannes Altmanninger 
993e0fe5cd4SJohannes Altmanninger std::pair<unsigned, unsigned>
getSourceRangeOffsets(const Node & N) const994e0fe5cd4SJohannes Altmanninger SyntaxTree::getSourceRangeOffsets(const Node &N) const {
9950da12c84SJohannes Altmanninger   const SourceManager &SrcMgr = TreeImpl->AST.getSourceManager();
9960da12c84SJohannes Altmanninger   SourceRange Range = N.ASTNode.getSourceRange();
9970da12c84SJohannes Altmanninger   SourceLocation BeginLoc = Range.getBegin();
9980da12c84SJohannes Altmanninger   SourceLocation EndLoc = Lexer::getLocForEndOfToken(
9990da12c84SJohannes Altmanninger       Range.getEnd(), /*Offset=*/0, SrcMgr, TreeImpl->AST.getLangOpts());
10000da12c84SJohannes Altmanninger   if (auto *ThisExpr = N.ASTNode.get<CXXThisExpr>()) {
10010da12c84SJohannes Altmanninger     if (ThisExpr->isImplicit())
10020da12c84SJohannes Altmanninger       EndLoc = BeginLoc;
10030da12c84SJohannes Altmanninger   }
10040da12c84SJohannes Altmanninger   unsigned Begin = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(BeginLoc));
10050da12c84SJohannes Altmanninger   unsigned End = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(EndLoc));
10060da12c84SJohannes Altmanninger   return {Begin, End};
10070da12c84SJohannes Altmanninger }
1008a75b2cacSAlex Lorenz 
getNodeValue(NodeId Id) const1009e0fe5cd4SJohannes Altmanninger std::string SyntaxTree::getNodeValue(NodeId Id) const {
1010e0fe5cd4SJohannes Altmanninger   return TreeImpl->getNodeValue(Id);
1011e0fe5cd4SJohannes Altmanninger }
1012e0fe5cd4SJohannes Altmanninger 
getNodeValue(const Node & N) const1013e0fe5cd4SJohannes Altmanninger std::string SyntaxTree::getNodeValue(const Node &N) const {
1014e0fe5cd4SJohannes Altmanninger   return TreeImpl->getNodeValue(N);
1015a75b2cacSAlex Lorenz }
1016a75b2cacSAlex Lorenz 
1017a75b2cacSAlex Lorenz } // end namespace diff
1018a75b2cacSAlex Lorenz } // end namespace clang
1019