xref: /src/contrib/llvm-project/clang/lib/Tooling/ASTDiff/ASTDiff.cpp (revision 7a6dacaca14b62ca4b74406814becb87a3fefac0)
1461a67faSDimitry Andric //===- ASTDiff.cpp - AST differencing implementation-----------*- C++ -*- -===//
2461a67faSDimitry Andric //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6461a67faSDimitry Andric //
7461a67faSDimitry Andric //===----------------------------------------------------------------------===//
8461a67faSDimitry Andric //
9461a67faSDimitry Andric // This file contains definitons for the AST differencing interface.
10461a67faSDimitry Andric //
11461a67faSDimitry Andric //===----------------------------------------------------------------------===//
12461a67faSDimitry Andric 
13461a67faSDimitry Andric #include "clang/Tooling/ASTDiff/ASTDiff.h"
14cfca06d7SDimitry Andric #include "clang/AST/ParentMapContext.h"
15461a67faSDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
16cfca06d7SDimitry Andric #include "clang/Basic/SourceManager.h"
17461a67faSDimitry Andric #include "clang/Lex/Lexer.h"
18461a67faSDimitry Andric #include "llvm/ADT/PriorityQueue.h"
19461a67faSDimitry Andric 
20461a67faSDimitry Andric #include <limits>
21461a67faSDimitry Andric #include <memory>
22e3b55780SDimitry Andric #include <optional>
23461a67faSDimitry Andric #include <unordered_set>
24461a67faSDimitry Andric 
25461a67faSDimitry Andric using namespace llvm;
26461a67faSDimitry Andric using namespace clang;
27461a67faSDimitry Andric 
28461a67faSDimitry Andric namespace clang {
29461a67faSDimitry Andric namespace diff {
30461a67faSDimitry Andric 
31461a67faSDimitry Andric namespace {
32461a67faSDimitry Andric /// Maps nodes of the left tree to ones on the right, and vice versa.
33461a67faSDimitry Andric class Mapping {
34461a67faSDimitry Andric public:
35461a67faSDimitry Andric   Mapping() = default;
36461a67faSDimitry Andric   Mapping(Mapping &&Other) = default;
37461a67faSDimitry Andric   Mapping &operator=(Mapping &&Other) = default;
38461a67faSDimitry Andric 
Mapping(size_t Size)39461a67faSDimitry Andric   Mapping(size_t Size) {
40519fc96cSDimitry Andric     SrcToDst = std::make_unique<NodeId[]>(Size);
41519fc96cSDimitry Andric     DstToSrc = std::make_unique<NodeId[]>(Size);
42461a67faSDimitry Andric   }
43461a67faSDimitry Andric 
link(NodeId Src,NodeId Dst)44461a67faSDimitry Andric   void link(NodeId Src, NodeId Dst) {
45461a67faSDimitry Andric     SrcToDst[Src] = Dst, DstToSrc[Dst] = Src;
46461a67faSDimitry Andric   }
47461a67faSDimitry Andric 
getDst(NodeId Src) const48461a67faSDimitry Andric   NodeId getDst(NodeId Src) const { return SrcToDst[Src]; }
getSrc(NodeId Dst) const49461a67faSDimitry Andric   NodeId getSrc(NodeId Dst) const { return DstToSrc[Dst]; }
hasSrc(NodeId Src) const50461a67faSDimitry Andric   bool hasSrc(NodeId Src) const { return getDst(Src).isValid(); }
hasDst(NodeId Dst) const51461a67faSDimitry Andric   bool hasDst(NodeId Dst) const { return getSrc(Dst).isValid(); }
52461a67faSDimitry Andric 
53461a67faSDimitry Andric private:
54461a67faSDimitry Andric   std::unique_ptr<NodeId[]> SrcToDst, DstToSrc;
55461a67faSDimitry Andric };
56461a67faSDimitry Andric } // end anonymous namespace
57461a67faSDimitry Andric 
58461a67faSDimitry Andric class ASTDiff::Impl {
59461a67faSDimitry Andric public:
60461a67faSDimitry Andric   SyntaxTree::Impl &T1, &T2;
61461a67faSDimitry Andric   Mapping TheMapping;
62461a67faSDimitry Andric 
63461a67faSDimitry Andric   Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
64461a67faSDimitry Andric        const ComparisonOptions &Options);
65461a67faSDimitry Andric 
66461a67faSDimitry Andric   /// Matches nodes one-by-one based on their similarity.
67461a67faSDimitry Andric   void computeMapping();
68461a67faSDimitry Andric 
69461a67faSDimitry Andric   // Compute Change for each node based on similarity.
70461a67faSDimitry Andric   void computeChangeKinds(Mapping &M);
71461a67faSDimitry Andric 
getMapped(const std::unique_ptr<SyntaxTree::Impl> & Tree,NodeId Id) const72461a67faSDimitry Andric   NodeId getMapped(const std::unique_ptr<SyntaxTree::Impl> &Tree,
73461a67faSDimitry Andric                    NodeId Id) const {
74461a67faSDimitry Andric     if (&*Tree == &T1)
75461a67faSDimitry Andric       return TheMapping.getDst(Id);
76461a67faSDimitry Andric     assert(&*Tree == &T2 && "Invalid tree.");
77461a67faSDimitry Andric     return TheMapping.getSrc(Id);
78461a67faSDimitry Andric   }
79461a67faSDimitry Andric 
80461a67faSDimitry Andric private:
81461a67faSDimitry Andric   // Returns true if the two subtrees are identical.
82461a67faSDimitry Andric   bool identical(NodeId Id1, NodeId Id2) const;
83461a67faSDimitry Andric 
84461a67faSDimitry Andric   // Returns false if the nodes must not be mached.
85461a67faSDimitry Andric   bool isMatchingPossible(NodeId Id1, NodeId Id2) const;
86461a67faSDimitry Andric 
87461a67faSDimitry Andric   // Returns true if the nodes' parents are matched.
88461a67faSDimitry Andric   bool haveSameParents(const Mapping &M, NodeId Id1, NodeId Id2) const;
89461a67faSDimitry Andric 
90461a67faSDimitry Andric   // Uses an optimal albeit slow algorithm to compute a mapping between two
91461a67faSDimitry Andric   // subtrees, but only if both have fewer nodes than MaxSize.
92461a67faSDimitry Andric   void addOptimalMapping(Mapping &M, NodeId Id1, NodeId Id2) const;
93461a67faSDimitry Andric 
94461a67faSDimitry Andric   // Computes the ratio of common descendants between the two nodes.
95461a67faSDimitry Andric   // Descendants are only considered to be equal when they are mapped in M.
96461a67faSDimitry Andric   double getJaccardSimilarity(const Mapping &M, NodeId Id1, NodeId Id2) const;
97461a67faSDimitry Andric 
98461a67faSDimitry Andric   // Returns the node that has the highest degree of similarity.
99461a67faSDimitry Andric   NodeId findCandidate(const Mapping &M, NodeId Id1) const;
100461a67faSDimitry Andric 
101461a67faSDimitry Andric   // Returns a mapping of identical subtrees.
102461a67faSDimitry Andric   Mapping matchTopDown() const;
103461a67faSDimitry Andric 
104461a67faSDimitry Andric   // Tries to match any yet unmapped nodes, in a bottom-up fashion.
105461a67faSDimitry Andric   void matchBottomUp(Mapping &M) const;
106461a67faSDimitry Andric 
107461a67faSDimitry Andric   const ComparisonOptions &Options;
108461a67faSDimitry Andric 
109461a67faSDimitry Andric   friend class ZhangShashaMatcher;
110461a67faSDimitry Andric };
111461a67faSDimitry Andric 
112461a67faSDimitry Andric /// Represents the AST of a TranslationUnit.
113461a67faSDimitry Andric class SyntaxTree::Impl {
114461a67faSDimitry Andric public:
115461a67faSDimitry Andric   Impl(SyntaxTree *Parent, ASTContext &AST);
116461a67faSDimitry Andric   /// Constructs a tree from an AST node.
117461a67faSDimitry Andric   Impl(SyntaxTree *Parent, Decl *N, ASTContext &AST);
118461a67faSDimitry Andric   Impl(SyntaxTree *Parent, Stmt *N, ASTContext &AST);
119461a67faSDimitry Andric   template <class T>
Impl(SyntaxTree * Parent,std::enable_if_t<std::is_base_of_v<Stmt,T>,T> * Node,ASTContext & AST)120461a67faSDimitry Andric   Impl(SyntaxTree *Parent,
121e3b55780SDimitry Andric        std::enable_if_t<std::is_base_of_v<Stmt, T>, T> *Node, ASTContext &AST)
122461a67faSDimitry Andric       : Impl(Parent, dyn_cast<Stmt>(Node), AST) {}
123461a67faSDimitry Andric   template <class T>
Impl(SyntaxTree * Parent,std::enable_if_t<std::is_base_of_v<Decl,T>,T> * Node,ASTContext & AST)124461a67faSDimitry Andric   Impl(SyntaxTree *Parent,
125e3b55780SDimitry Andric        std::enable_if_t<std::is_base_of_v<Decl, T>, T> *Node, ASTContext &AST)
126461a67faSDimitry Andric       : Impl(Parent, dyn_cast<Decl>(Node), AST) {}
127461a67faSDimitry Andric 
128461a67faSDimitry Andric   SyntaxTree *Parent;
129461a67faSDimitry Andric   ASTContext &AST;
130461a67faSDimitry Andric   PrintingPolicy TypePP;
131461a67faSDimitry Andric   /// Nodes in preorder.
132461a67faSDimitry Andric   std::vector<Node> Nodes;
133461a67faSDimitry Andric   std::vector<NodeId> Leaves;
134461a67faSDimitry Andric   // Maps preorder indices to postorder ones.
135461a67faSDimitry Andric   std::vector<int> PostorderIds;
136461a67faSDimitry Andric   std::vector<NodeId> NodesBfs;
137461a67faSDimitry Andric 
getSize() const138461a67faSDimitry Andric   int getSize() const { return Nodes.size(); }
getRootId() const139461a67faSDimitry Andric   NodeId getRootId() const { return 0; }
begin() const140461a67faSDimitry Andric   PreorderIterator begin() const { return getRootId(); }
end() const141461a67faSDimitry Andric   PreorderIterator end() const { return getSize(); }
142461a67faSDimitry Andric 
getNode(NodeId Id) const143461a67faSDimitry Andric   const Node &getNode(NodeId Id) const { return Nodes[Id]; }
getMutableNode(NodeId Id)144461a67faSDimitry Andric   Node &getMutableNode(NodeId Id) { return Nodes[Id]; }
isValidNodeId(NodeId Id) const145461a67faSDimitry Andric   bool isValidNodeId(NodeId Id) const { return Id >= 0 && Id < getSize(); }
addNode(Node & N)146461a67faSDimitry Andric   void addNode(Node &N) { Nodes.push_back(N); }
147461a67faSDimitry Andric   int getNumberOfDescendants(NodeId Id) const;
148461a67faSDimitry Andric   bool isInSubtree(NodeId Id, NodeId SubtreeRoot) const;
149461a67faSDimitry Andric   int findPositionInParent(NodeId Id, bool Shifted = false) const;
150461a67faSDimitry Andric 
151461a67faSDimitry Andric   std::string getRelativeName(const NamedDecl *ND,
152461a67faSDimitry Andric                               const DeclContext *Context) const;
153461a67faSDimitry Andric   std::string getRelativeName(const NamedDecl *ND) const;
154461a67faSDimitry Andric 
155461a67faSDimitry Andric   std::string getNodeValue(NodeId Id) const;
156461a67faSDimitry Andric   std::string getNodeValue(const Node &Node) const;
157461a67faSDimitry Andric   std::string getDeclValue(const Decl *D) const;
158461a67faSDimitry Andric   std::string getStmtValue(const Stmt *S) const;
159461a67faSDimitry Andric 
160461a67faSDimitry Andric private:
161461a67faSDimitry Andric   void initTree();
162461a67faSDimitry Andric   void setLeftMostDescendants();
163461a67faSDimitry Andric };
164461a67faSDimitry Andric 
isSpecializedNodeExcluded(const Decl * D)165461a67faSDimitry Andric static bool isSpecializedNodeExcluded(const Decl *D) { return D->isImplicit(); }
isSpecializedNodeExcluded(const Stmt * S)166461a67faSDimitry Andric static bool isSpecializedNodeExcluded(const Stmt *S) { return false; }
isSpecializedNodeExcluded(CXXCtorInitializer * I)167461a67faSDimitry Andric static bool isSpecializedNodeExcluded(CXXCtorInitializer *I) {
168461a67faSDimitry Andric   return !I->isWritten();
169461a67faSDimitry Andric }
170461a67faSDimitry Andric 
171461a67faSDimitry Andric template <class T>
isNodeExcluded(const SourceManager & SrcMgr,T * N)172461a67faSDimitry Andric static bool isNodeExcluded(const SourceManager &SrcMgr, T *N) {
173461a67faSDimitry Andric   if (!N)
174461a67faSDimitry Andric     return true;
175461a67faSDimitry Andric   SourceLocation SLoc = N->getSourceRange().getBegin();
176461a67faSDimitry Andric   if (SLoc.isValid()) {
177461a67faSDimitry Andric     // Ignore everything from other files.
178461a67faSDimitry Andric     if (!SrcMgr.isInMainFile(SLoc))
179461a67faSDimitry Andric       return true;
180461a67faSDimitry Andric     // Ignore macros.
181461a67faSDimitry Andric     if (SLoc != SrcMgr.getSpellingLoc(SLoc))
182461a67faSDimitry Andric       return true;
183461a67faSDimitry Andric   }
184461a67faSDimitry Andric   return isSpecializedNodeExcluded(N);
185461a67faSDimitry Andric }
186461a67faSDimitry Andric 
187461a67faSDimitry Andric namespace {
188461a67faSDimitry Andric // Sets Height, Parent and Children for each node.
189461a67faSDimitry Andric struct PreorderVisitor : public RecursiveASTVisitor<PreorderVisitor> {
190461a67faSDimitry Andric   int Id = 0, Depth = 0;
191461a67faSDimitry Andric   NodeId Parent;
192461a67faSDimitry Andric   SyntaxTree::Impl &Tree;
193461a67faSDimitry Andric 
PreorderVisitorclang::diff::__anon0b30a76b0211::PreorderVisitor194461a67faSDimitry Andric   PreorderVisitor(SyntaxTree::Impl &Tree) : Tree(Tree) {}
195461a67faSDimitry Andric 
PreTraverseclang::diff::__anon0b30a76b0211::PreorderVisitor196461a67faSDimitry Andric   template <class T> std::tuple<NodeId, NodeId> PreTraverse(T *ASTNode) {
197461a67faSDimitry Andric     NodeId MyId = Id;
198461a67faSDimitry Andric     Tree.Nodes.emplace_back();
199461a67faSDimitry Andric     Node &N = Tree.getMutableNode(MyId);
200461a67faSDimitry Andric     N.Parent = Parent;
201461a67faSDimitry Andric     N.Depth = Depth;
202461a67faSDimitry Andric     N.ASTNode = DynTypedNode::create(*ASTNode);
203461a67faSDimitry Andric     assert(!N.ASTNode.getNodeKind().isNone() &&
204461a67faSDimitry Andric            "Expected nodes to have a valid kind.");
205461a67faSDimitry Andric     if (Parent.isValid()) {
206461a67faSDimitry Andric       Node &P = Tree.getMutableNode(Parent);
207461a67faSDimitry Andric       P.Children.push_back(MyId);
208461a67faSDimitry Andric     }
209461a67faSDimitry Andric     Parent = MyId;
210461a67faSDimitry Andric     ++Id;
211461a67faSDimitry Andric     ++Depth;
212461a67faSDimitry Andric     return std::make_tuple(MyId, Tree.getNode(MyId).Parent);
213461a67faSDimitry Andric   }
PostTraverseclang::diff::__anon0b30a76b0211::PreorderVisitor214461a67faSDimitry Andric   void PostTraverse(std::tuple<NodeId, NodeId> State) {
215461a67faSDimitry Andric     NodeId MyId, PreviousParent;
216461a67faSDimitry Andric     std::tie(MyId, PreviousParent) = State;
217461a67faSDimitry Andric     assert(MyId.isValid() && "Expecting to only traverse valid nodes.");
218461a67faSDimitry Andric     Parent = PreviousParent;
219461a67faSDimitry Andric     --Depth;
220461a67faSDimitry Andric     Node &N = Tree.getMutableNode(MyId);
221461a67faSDimitry Andric     N.RightMostDescendant = Id - 1;
222461a67faSDimitry Andric     assert(N.RightMostDescendant >= 0 &&
223461a67faSDimitry Andric            N.RightMostDescendant < Tree.getSize() &&
224461a67faSDimitry Andric            "Rightmost descendant must be a valid tree node.");
225461a67faSDimitry Andric     if (N.isLeaf())
226461a67faSDimitry Andric       Tree.Leaves.push_back(MyId);
227461a67faSDimitry Andric     N.Height = 1;
228461a67faSDimitry Andric     for (NodeId Child : N.Children)
229461a67faSDimitry Andric       N.Height = std::max(N.Height, 1 + Tree.getNode(Child).Height);
230461a67faSDimitry Andric   }
TraverseDeclclang::diff::__anon0b30a76b0211::PreorderVisitor231461a67faSDimitry Andric   bool TraverseDecl(Decl *D) {
232461a67faSDimitry Andric     if (isNodeExcluded(Tree.AST.getSourceManager(), D))
233461a67faSDimitry Andric       return true;
234461a67faSDimitry Andric     auto SavedState = PreTraverse(D);
235461a67faSDimitry Andric     RecursiveASTVisitor<PreorderVisitor>::TraverseDecl(D);
236461a67faSDimitry Andric     PostTraverse(SavedState);
237461a67faSDimitry Andric     return true;
238461a67faSDimitry Andric   }
TraverseStmtclang::diff::__anon0b30a76b0211::PreorderVisitor239461a67faSDimitry Andric   bool TraverseStmt(Stmt *S) {
24022989816SDimitry Andric     if (auto *E = dyn_cast_or_null<Expr>(S))
24122989816SDimitry Andric       S = E->IgnoreImplicit();
242461a67faSDimitry Andric     if (isNodeExcluded(Tree.AST.getSourceManager(), S))
243461a67faSDimitry Andric       return true;
244461a67faSDimitry Andric     auto SavedState = PreTraverse(S);
245461a67faSDimitry Andric     RecursiveASTVisitor<PreorderVisitor>::TraverseStmt(S);
246461a67faSDimitry Andric     PostTraverse(SavedState);
247461a67faSDimitry Andric     return true;
248461a67faSDimitry Andric   }
TraverseTypeclang::diff::__anon0b30a76b0211::PreorderVisitor249461a67faSDimitry Andric   bool TraverseType(QualType T) { return true; }
TraverseConstructorInitializerclang::diff::__anon0b30a76b0211::PreorderVisitor250461a67faSDimitry Andric   bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
251461a67faSDimitry Andric     if (isNodeExcluded(Tree.AST.getSourceManager(), Init))
252461a67faSDimitry Andric       return true;
253461a67faSDimitry Andric     auto SavedState = PreTraverse(Init);
254461a67faSDimitry Andric     RecursiveASTVisitor<PreorderVisitor>::TraverseConstructorInitializer(Init);
255461a67faSDimitry Andric     PostTraverse(SavedState);
256461a67faSDimitry Andric     return true;
257461a67faSDimitry Andric   }
258461a67faSDimitry Andric };
259461a67faSDimitry Andric } // end anonymous namespace
260461a67faSDimitry Andric 
Impl(SyntaxTree * Parent,ASTContext & AST)261461a67faSDimitry Andric SyntaxTree::Impl::Impl(SyntaxTree *Parent, ASTContext &AST)
262461a67faSDimitry Andric     : Parent(Parent), AST(AST), TypePP(AST.getLangOpts()) {
263461a67faSDimitry Andric   TypePP.AnonymousTagLocations = false;
264461a67faSDimitry Andric }
265461a67faSDimitry Andric 
Impl(SyntaxTree * Parent,Decl * N,ASTContext & AST)266461a67faSDimitry Andric SyntaxTree::Impl::Impl(SyntaxTree *Parent, Decl *N, ASTContext &AST)
267461a67faSDimitry Andric     : Impl(Parent, AST) {
268461a67faSDimitry Andric   PreorderVisitor PreorderWalker(*this);
269461a67faSDimitry Andric   PreorderWalker.TraverseDecl(N);
270461a67faSDimitry Andric   initTree();
271461a67faSDimitry Andric }
272461a67faSDimitry Andric 
Impl(SyntaxTree * Parent,Stmt * N,ASTContext & AST)273461a67faSDimitry Andric SyntaxTree::Impl::Impl(SyntaxTree *Parent, Stmt *N, ASTContext &AST)
274461a67faSDimitry Andric     : Impl(Parent, AST) {
275461a67faSDimitry Andric   PreorderVisitor PreorderWalker(*this);
276461a67faSDimitry Andric   PreorderWalker.TraverseStmt(N);
277461a67faSDimitry Andric   initTree();
278461a67faSDimitry Andric }
279461a67faSDimitry Andric 
getSubtreePostorder(const SyntaxTree::Impl & Tree,NodeId Root)280461a67faSDimitry Andric static std::vector<NodeId> getSubtreePostorder(const SyntaxTree::Impl &Tree,
281461a67faSDimitry Andric                                                NodeId Root) {
282461a67faSDimitry Andric   std::vector<NodeId> Postorder;
283461a67faSDimitry Andric   std::function<void(NodeId)> Traverse = [&](NodeId Id) {
284461a67faSDimitry Andric     const Node &N = Tree.getNode(Id);
285461a67faSDimitry Andric     for (NodeId Child : N.Children)
286461a67faSDimitry Andric       Traverse(Child);
287461a67faSDimitry Andric     Postorder.push_back(Id);
288461a67faSDimitry Andric   };
289461a67faSDimitry Andric   Traverse(Root);
290461a67faSDimitry Andric   return Postorder;
291461a67faSDimitry Andric }
292461a67faSDimitry Andric 
getSubtreeBfs(const SyntaxTree::Impl & Tree,NodeId Root)293461a67faSDimitry Andric static std::vector<NodeId> getSubtreeBfs(const SyntaxTree::Impl &Tree,
294461a67faSDimitry Andric                                          NodeId Root) {
295461a67faSDimitry Andric   std::vector<NodeId> Ids;
296461a67faSDimitry Andric   size_t Expanded = 0;
297461a67faSDimitry Andric   Ids.push_back(Root);
298461a67faSDimitry Andric   while (Expanded < Ids.size())
299461a67faSDimitry Andric     for (NodeId Child : Tree.getNode(Ids[Expanded++]).Children)
300461a67faSDimitry Andric       Ids.push_back(Child);
301461a67faSDimitry Andric   return Ids;
302461a67faSDimitry Andric }
303461a67faSDimitry Andric 
initTree()304461a67faSDimitry Andric void SyntaxTree::Impl::initTree() {
305461a67faSDimitry Andric   setLeftMostDescendants();
306461a67faSDimitry Andric   int PostorderId = 0;
307461a67faSDimitry Andric   PostorderIds.resize(getSize());
308461a67faSDimitry Andric   std::function<void(NodeId)> PostorderTraverse = [&](NodeId Id) {
309461a67faSDimitry Andric     for (NodeId Child : getNode(Id).Children)
310461a67faSDimitry Andric       PostorderTraverse(Child);
311461a67faSDimitry Andric     PostorderIds[Id] = PostorderId;
312461a67faSDimitry Andric     ++PostorderId;
313461a67faSDimitry Andric   };
314461a67faSDimitry Andric   PostorderTraverse(getRootId());
315461a67faSDimitry Andric   NodesBfs = getSubtreeBfs(*this, getRootId());
316461a67faSDimitry Andric }
317461a67faSDimitry Andric 
setLeftMostDescendants()318461a67faSDimitry Andric void SyntaxTree::Impl::setLeftMostDescendants() {
319461a67faSDimitry Andric   for (NodeId Leaf : Leaves) {
320461a67faSDimitry Andric     getMutableNode(Leaf).LeftMostDescendant = Leaf;
321461a67faSDimitry Andric     NodeId Parent, Cur = Leaf;
322461a67faSDimitry Andric     while ((Parent = getNode(Cur).Parent).isValid() &&
323461a67faSDimitry Andric            getNode(Parent).Children[0] == Cur) {
324461a67faSDimitry Andric       Cur = Parent;
325461a67faSDimitry Andric       getMutableNode(Cur).LeftMostDescendant = Leaf;
326461a67faSDimitry Andric     }
327461a67faSDimitry Andric   }
328461a67faSDimitry Andric }
329461a67faSDimitry Andric 
getNumberOfDescendants(NodeId Id) const330461a67faSDimitry Andric int SyntaxTree::Impl::getNumberOfDescendants(NodeId Id) const {
331461a67faSDimitry Andric   return getNode(Id).RightMostDescendant - Id + 1;
332461a67faSDimitry Andric }
333461a67faSDimitry Andric 
isInSubtree(NodeId Id,NodeId SubtreeRoot) const334461a67faSDimitry Andric bool SyntaxTree::Impl::isInSubtree(NodeId Id, NodeId SubtreeRoot) const {
335461a67faSDimitry Andric   return Id >= SubtreeRoot && Id <= getNode(SubtreeRoot).RightMostDescendant;
336461a67faSDimitry Andric }
337461a67faSDimitry Andric 
findPositionInParent(NodeId Id,bool Shifted) const338461a67faSDimitry Andric int SyntaxTree::Impl::findPositionInParent(NodeId Id, bool Shifted) const {
339461a67faSDimitry Andric   NodeId Parent = getNode(Id).Parent;
340461a67faSDimitry Andric   if (Parent.isInvalid())
341461a67faSDimitry Andric     return 0;
342461a67faSDimitry Andric   const auto &Siblings = getNode(Parent).Children;
343461a67faSDimitry Andric   int Position = 0;
344461a67faSDimitry Andric   for (size_t I = 0, E = Siblings.size(); I < E; ++I) {
345461a67faSDimitry Andric     if (Shifted)
346461a67faSDimitry Andric       Position += getNode(Siblings[I]).Shift;
347461a67faSDimitry Andric     if (Siblings[I] == Id) {
348461a67faSDimitry Andric       Position += I;
349461a67faSDimitry Andric       return Position;
350461a67faSDimitry Andric     }
351461a67faSDimitry Andric   }
352461a67faSDimitry Andric   llvm_unreachable("Node not found in parent's children.");
353461a67faSDimitry Andric }
354461a67faSDimitry Andric 
355461a67faSDimitry Andric // Returns the qualified name of ND. If it is subordinate to Context,
356461a67faSDimitry Andric // then the prefix of the latter is removed from the returned value.
357461a67faSDimitry Andric std::string
getRelativeName(const NamedDecl * ND,const DeclContext * Context) const358461a67faSDimitry Andric SyntaxTree::Impl::getRelativeName(const NamedDecl *ND,
359461a67faSDimitry Andric                                   const DeclContext *Context) const {
360461a67faSDimitry Andric   std::string Val = ND->getQualifiedNameAsString();
361461a67faSDimitry Andric   std::string ContextPrefix;
362461a67faSDimitry Andric   if (!Context)
363461a67faSDimitry Andric     return Val;
364461a67faSDimitry Andric   if (auto *Namespace = dyn_cast<NamespaceDecl>(Context))
365461a67faSDimitry Andric     ContextPrefix = Namespace->getQualifiedNameAsString();
366461a67faSDimitry Andric   else if (auto *Record = dyn_cast<RecordDecl>(Context))
367461a67faSDimitry Andric     ContextPrefix = Record->getQualifiedNameAsString();
368461a67faSDimitry Andric   else if (AST.getLangOpts().CPlusPlus11)
369461a67faSDimitry Andric     if (auto *Tag = dyn_cast<TagDecl>(Context))
370461a67faSDimitry Andric       ContextPrefix = Tag->getQualifiedNameAsString();
37148675466SDimitry Andric   // Strip the qualifier, if Val refers to something in the current scope.
372461a67faSDimitry Andric   // But leave one leading ':' in place, so that we know that this is a
373461a67faSDimitry Andric   // relative path.
374312c0ed1SDimitry Andric   if (!ContextPrefix.empty() && StringRef(Val).starts_with(ContextPrefix))
375461a67faSDimitry Andric     Val = Val.substr(ContextPrefix.size() + 1);
376461a67faSDimitry Andric   return Val;
377461a67faSDimitry Andric }
378461a67faSDimitry Andric 
getRelativeName(const NamedDecl * ND) const379461a67faSDimitry Andric std::string SyntaxTree::Impl::getRelativeName(const NamedDecl *ND) const {
380461a67faSDimitry Andric   return getRelativeName(ND, ND->getDeclContext());
381461a67faSDimitry Andric }
382461a67faSDimitry Andric 
getEnclosingDeclContext(ASTContext & AST,const Stmt * S)383461a67faSDimitry Andric static const DeclContext *getEnclosingDeclContext(ASTContext &AST,
384461a67faSDimitry Andric                                                   const Stmt *S) {
385461a67faSDimitry Andric   while (S) {
386461a67faSDimitry Andric     const auto &Parents = AST.getParents(*S);
387461a67faSDimitry Andric     if (Parents.empty())
388461a67faSDimitry Andric       return nullptr;
389461a67faSDimitry Andric     const auto &P = Parents[0];
390461a67faSDimitry Andric     if (const auto *D = P.get<Decl>())
391461a67faSDimitry Andric       return D->getDeclContext();
392461a67faSDimitry Andric     S = P.get<Stmt>();
393461a67faSDimitry Andric   }
394461a67faSDimitry Andric   return nullptr;
395461a67faSDimitry Andric }
396461a67faSDimitry Andric 
getInitializerValue(const CXXCtorInitializer * Init,const PrintingPolicy & TypePP)397461a67faSDimitry Andric static std::string getInitializerValue(const CXXCtorInitializer *Init,
398461a67faSDimitry Andric                                        const PrintingPolicy &TypePP) {
399461a67faSDimitry Andric   if (Init->isAnyMemberInitializer())
400cfca06d7SDimitry Andric     return std::string(Init->getAnyMember()->getName());
401461a67faSDimitry Andric   if (Init->isBaseInitializer())
402461a67faSDimitry Andric     return QualType(Init->getBaseClass(), 0).getAsString(TypePP);
403461a67faSDimitry Andric   if (Init->isDelegatingInitializer())
404461a67faSDimitry Andric     return Init->getTypeSourceInfo()->getType().getAsString(TypePP);
405461a67faSDimitry Andric   llvm_unreachable("Unknown initializer type");
406461a67faSDimitry Andric }
407461a67faSDimitry Andric 
getNodeValue(NodeId Id) const408461a67faSDimitry Andric std::string SyntaxTree::Impl::getNodeValue(NodeId Id) const {
409461a67faSDimitry Andric   return getNodeValue(getNode(Id));
410461a67faSDimitry Andric }
411461a67faSDimitry Andric 
getNodeValue(const Node & N) const412461a67faSDimitry Andric std::string SyntaxTree::Impl::getNodeValue(const Node &N) const {
413461a67faSDimitry Andric   const DynTypedNode &DTN = N.ASTNode;
414461a67faSDimitry Andric   if (auto *S = DTN.get<Stmt>())
415461a67faSDimitry Andric     return getStmtValue(S);
416461a67faSDimitry Andric   if (auto *D = DTN.get<Decl>())
417461a67faSDimitry Andric     return getDeclValue(D);
418461a67faSDimitry Andric   if (auto *Init = DTN.get<CXXCtorInitializer>())
419461a67faSDimitry Andric     return getInitializerValue(Init, TypePP);
420461a67faSDimitry Andric   llvm_unreachable("Fatal: unhandled AST node.\n");
421461a67faSDimitry Andric }
422461a67faSDimitry Andric 
getDeclValue(const Decl * D) const423461a67faSDimitry Andric std::string SyntaxTree::Impl::getDeclValue(const Decl *D) const {
424461a67faSDimitry Andric   std::string Value;
425461a67faSDimitry Andric   if (auto *V = dyn_cast<ValueDecl>(D))
426461a67faSDimitry Andric     return getRelativeName(V) + "(" + V->getType().getAsString(TypePP) + ")";
427461a67faSDimitry Andric   if (auto *N = dyn_cast<NamedDecl>(D))
428461a67faSDimitry Andric     Value += getRelativeName(N) + ";";
429461a67faSDimitry Andric   if (auto *T = dyn_cast<TypedefNameDecl>(D))
430461a67faSDimitry Andric     return Value + T->getUnderlyingType().getAsString(TypePP) + ";";
431461a67faSDimitry Andric   if (auto *T = dyn_cast<TypeDecl>(D))
432461a67faSDimitry Andric     if (T->getTypeForDecl())
433461a67faSDimitry Andric       Value +=
434461a67faSDimitry Andric           T->getTypeForDecl()->getCanonicalTypeInternal().getAsString(TypePP) +
435461a67faSDimitry Andric           ";";
436461a67faSDimitry Andric   if (auto *U = dyn_cast<UsingDirectiveDecl>(D))
437cfca06d7SDimitry Andric     return std::string(U->getNominatedNamespace()->getName());
438461a67faSDimitry Andric   if (auto *A = dyn_cast<AccessSpecDecl>(D)) {
439461a67faSDimitry Andric     CharSourceRange Range(A->getSourceRange(), false);
440cfca06d7SDimitry Andric     return std::string(
441cfca06d7SDimitry Andric         Lexer::getSourceText(Range, AST.getSourceManager(), AST.getLangOpts()));
442461a67faSDimitry Andric   }
443461a67faSDimitry Andric   return Value;
444461a67faSDimitry Andric }
445461a67faSDimitry Andric 
getStmtValue(const Stmt * S) const446461a67faSDimitry Andric std::string SyntaxTree::Impl::getStmtValue(const Stmt *S) const {
447461a67faSDimitry Andric   if (auto *U = dyn_cast<UnaryOperator>(S))
448cfca06d7SDimitry Andric     return std::string(UnaryOperator::getOpcodeStr(U->getOpcode()));
449461a67faSDimitry Andric   if (auto *B = dyn_cast<BinaryOperator>(S))
450cfca06d7SDimitry Andric     return std::string(B->getOpcodeStr());
451461a67faSDimitry Andric   if (auto *M = dyn_cast<MemberExpr>(S))
452461a67faSDimitry Andric     return getRelativeName(M->getMemberDecl());
453461a67faSDimitry Andric   if (auto *I = dyn_cast<IntegerLiteral>(S)) {
454461a67faSDimitry Andric     SmallString<256> Str;
455461a67faSDimitry Andric     I->getValue().toString(Str, /*Radix=*/10, /*Signed=*/false);
4564df029ccSDimitry Andric     return std::string(Str);
457461a67faSDimitry Andric   }
458461a67faSDimitry Andric   if (auto *F = dyn_cast<FloatingLiteral>(S)) {
459461a67faSDimitry Andric     SmallString<256> Str;
460461a67faSDimitry Andric     F->getValue().toString(Str);
4614df029ccSDimitry Andric     return std::string(Str);
462461a67faSDimitry Andric   }
463461a67faSDimitry Andric   if (auto *D = dyn_cast<DeclRefExpr>(S))
464461a67faSDimitry Andric     return getRelativeName(D->getDecl(), getEnclosingDeclContext(AST, S));
465461a67faSDimitry Andric   if (auto *String = dyn_cast<StringLiteral>(S))
466cfca06d7SDimitry Andric     return std::string(String->getString());
467461a67faSDimitry Andric   if (auto *B = dyn_cast<CXXBoolLiteralExpr>(S))
468461a67faSDimitry Andric     return B->getValue() ? "true" : "false";
469461a67faSDimitry Andric   return "";
470461a67faSDimitry Andric }
471461a67faSDimitry Andric 
472461a67faSDimitry Andric /// Identifies a node in a subtree by its postorder offset, starting at 1.
473461a67faSDimitry Andric struct SNodeId {
474461a67faSDimitry Andric   int Id = 0;
475461a67faSDimitry Andric 
SNodeIdclang::diff::SNodeId476461a67faSDimitry Andric   explicit SNodeId(int Id) : Id(Id) {}
477461a67faSDimitry Andric   explicit SNodeId() = default;
478461a67faSDimitry Andric 
operator intclang::diff::SNodeId479461a67faSDimitry Andric   operator int() const { return Id; }
operator ++clang::diff::SNodeId480461a67faSDimitry Andric   SNodeId &operator++() { return ++Id, *this; }
operator --clang::diff::SNodeId481461a67faSDimitry Andric   SNodeId &operator--() { return --Id, *this; }
operator +clang::diff::SNodeId482461a67faSDimitry Andric   SNodeId operator+(int Other) const { return SNodeId(Id + Other); }
483461a67faSDimitry Andric };
484461a67faSDimitry Andric 
485461a67faSDimitry Andric class Subtree {
486461a67faSDimitry Andric private:
487461a67faSDimitry Andric   /// The parent tree.
488461a67faSDimitry Andric   const SyntaxTree::Impl &Tree;
489461a67faSDimitry Andric   /// Maps SNodeIds to original ids.
490461a67faSDimitry Andric   std::vector<NodeId> RootIds;
491461a67faSDimitry Andric   /// Maps subtree nodes to their leftmost descendants wtihin the subtree.
492461a67faSDimitry Andric   std::vector<SNodeId> LeftMostDescendants;
493461a67faSDimitry Andric 
494461a67faSDimitry Andric public:
495461a67faSDimitry Andric   std::vector<SNodeId> KeyRoots;
496461a67faSDimitry Andric 
Subtree(const SyntaxTree::Impl & Tree,NodeId SubtreeRoot)497461a67faSDimitry Andric   Subtree(const SyntaxTree::Impl &Tree, NodeId SubtreeRoot) : Tree(Tree) {
498461a67faSDimitry Andric     RootIds = getSubtreePostorder(Tree, SubtreeRoot);
499461a67faSDimitry Andric     int NumLeaves = setLeftMostDescendants();
500461a67faSDimitry Andric     computeKeyRoots(NumLeaves);
501461a67faSDimitry Andric   }
getSize() const502461a67faSDimitry Andric   int getSize() const { return RootIds.size(); }
getIdInRoot(SNodeId Id) const503461a67faSDimitry Andric   NodeId getIdInRoot(SNodeId Id) const {
504461a67faSDimitry Andric     assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
505461a67faSDimitry Andric     return RootIds[Id - 1];
506461a67faSDimitry Andric   }
getNode(SNodeId Id) const507461a67faSDimitry Andric   const Node &getNode(SNodeId Id) const {
508461a67faSDimitry Andric     return Tree.getNode(getIdInRoot(Id));
509461a67faSDimitry Andric   }
getLeftMostDescendant(SNodeId Id) const510461a67faSDimitry Andric   SNodeId getLeftMostDescendant(SNodeId Id) const {
511461a67faSDimitry Andric     assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
512461a67faSDimitry Andric     return LeftMostDescendants[Id - 1];
513461a67faSDimitry Andric   }
514461a67faSDimitry Andric   /// Returns the postorder index of the leftmost descendant in the subtree.
getPostorderOffset() const515461a67faSDimitry Andric   NodeId getPostorderOffset() const {
516461a67faSDimitry Andric     return Tree.PostorderIds[getIdInRoot(SNodeId(1))];
517461a67faSDimitry Andric   }
getNodeValue(SNodeId Id) const518461a67faSDimitry Andric   std::string getNodeValue(SNodeId Id) const {
519461a67faSDimitry Andric     return Tree.getNodeValue(getIdInRoot(Id));
520461a67faSDimitry Andric   }
521461a67faSDimitry Andric 
522461a67faSDimitry Andric private:
523461a67faSDimitry Andric   /// Returns the number of leafs in the subtree.
setLeftMostDescendants()524461a67faSDimitry Andric   int setLeftMostDescendants() {
525461a67faSDimitry Andric     int NumLeaves = 0;
526461a67faSDimitry Andric     LeftMostDescendants.resize(getSize());
527461a67faSDimitry Andric     for (int I = 0; I < getSize(); ++I) {
528461a67faSDimitry Andric       SNodeId SI(I + 1);
529461a67faSDimitry Andric       const Node &N = getNode(SI);
530461a67faSDimitry Andric       NumLeaves += N.isLeaf();
531461a67faSDimitry Andric       assert(I == Tree.PostorderIds[getIdInRoot(SI)] - getPostorderOffset() &&
532461a67faSDimitry Andric              "Postorder traversal in subtree should correspond to traversal in "
533461a67faSDimitry Andric              "the root tree by a constant offset.");
534461a67faSDimitry Andric       LeftMostDescendants[I] = SNodeId(Tree.PostorderIds[N.LeftMostDescendant] -
535461a67faSDimitry Andric                                        getPostorderOffset());
536461a67faSDimitry Andric     }
537461a67faSDimitry Andric     return NumLeaves;
538461a67faSDimitry Andric   }
computeKeyRoots(int Leaves)539461a67faSDimitry Andric   void computeKeyRoots(int Leaves) {
540461a67faSDimitry Andric     KeyRoots.resize(Leaves);
541461a67faSDimitry Andric     std::unordered_set<int> Visited;
542461a67faSDimitry Andric     int K = Leaves - 1;
543461a67faSDimitry Andric     for (SNodeId I(getSize()); I > 0; --I) {
544461a67faSDimitry Andric       SNodeId LeftDesc = getLeftMostDescendant(I);
545461a67faSDimitry Andric       if (Visited.count(LeftDesc))
546461a67faSDimitry Andric         continue;
547461a67faSDimitry Andric       assert(K >= 0 && "K should be non-negative");
548461a67faSDimitry Andric       KeyRoots[K] = I;
549461a67faSDimitry Andric       Visited.insert(LeftDesc);
550461a67faSDimitry Andric       --K;
551461a67faSDimitry Andric     }
552461a67faSDimitry Andric   }
553461a67faSDimitry Andric };
554461a67faSDimitry Andric 
555461a67faSDimitry Andric /// Implementation of Zhang and Shasha's Algorithm for tree edit distance.
556461a67faSDimitry Andric /// Computes an optimal mapping between two trees using only insertion,
557461a67faSDimitry Andric /// deletion and update as edit actions (similar to the Levenshtein distance).
558461a67faSDimitry Andric class ZhangShashaMatcher {
559461a67faSDimitry Andric   const ASTDiff::Impl &DiffImpl;
560461a67faSDimitry Andric   Subtree S1;
561461a67faSDimitry Andric   Subtree S2;
562461a67faSDimitry Andric   std::unique_ptr<std::unique_ptr<double[]>[]> TreeDist, ForestDist;
563461a67faSDimitry Andric 
564461a67faSDimitry Andric public:
ZhangShashaMatcher(const ASTDiff::Impl & DiffImpl,const SyntaxTree::Impl & T1,const SyntaxTree::Impl & T2,NodeId Id1,NodeId Id2)565461a67faSDimitry Andric   ZhangShashaMatcher(const ASTDiff::Impl &DiffImpl, const SyntaxTree::Impl &T1,
566461a67faSDimitry Andric                      const SyntaxTree::Impl &T2, NodeId Id1, NodeId Id2)
567461a67faSDimitry Andric       : DiffImpl(DiffImpl), S1(T1, Id1), S2(T2, Id2) {
568519fc96cSDimitry Andric     TreeDist = std::make_unique<std::unique_ptr<double[]>[]>(
569461a67faSDimitry Andric         size_t(S1.getSize()) + 1);
570519fc96cSDimitry Andric     ForestDist = std::make_unique<std::unique_ptr<double[]>[]>(
571461a67faSDimitry Andric         size_t(S1.getSize()) + 1);
572461a67faSDimitry Andric     for (int I = 0, E = S1.getSize() + 1; I < E; ++I) {
573519fc96cSDimitry Andric       TreeDist[I] = std::make_unique<double[]>(size_t(S2.getSize()) + 1);
574519fc96cSDimitry Andric       ForestDist[I] = std::make_unique<double[]>(size_t(S2.getSize()) + 1);
575461a67faSDimitry Andric     }
576461a67faSDimitry Andric   }
577461a67faSDimitry Andric 
getMatchingNodes()578461a67faSDimitry Andric   std::vector<std::pair<NodeId, NodeId>> getMatchingNodes() {
579461a67faSDimitry Andric     std::vector<std::pair<NodeId, NodeId>> Matches;
580461a67faSDimitry Andric     std::vector<std::pair<SNodeId, SNodeId>> TreePairs;
581461a67faSDimitry Andric 
582461a67faSDimitry Andric     computeTreeDist();
583461a67faSDimitry Andric 
584461a67faSDimitry Andric     bool RootNodePair = true;
585461a67faSDimitry Andric 
586461a67faSDimitry Andric     TreePairs.emplace_back(SNodeId(S1.getSize()), SNodeId(S2.getSize()));
587461a67faSDimitry Andric 
588461a67faSDimitry Andric     while (!TreePairs.empty()) {
589461a67faSDimitry Andric       SNodeId LastRow, LastCol, FirstRow, FirstCol, Row, Col;
590461a67faSDimitry Andric       std::tie(LastRow, LastCol) = TreePairs.back();
591461a67faSDimitry Andric       TreePairs.pop_back();
592461a67faSDimitry Andric 
593461a67faSDimitry Andric       if (!RootNodePair) {
594461a67faSDimitry Andric         computeForestDist(LastRow, LastCol);
595461a67faSDimitry Andric       }
596461a67faSDimitry Andric 
597461a67faSDimitry Andric       RootNodePair = false;
598461a67faSDimitry Andric 
599461a67faSDimitry Andric       FirstRow = S1.getLeftMostDescendant(LastRow);
600461a67faSDimitry Andric       FirstCol = S2.getLeftMostDescendant(LastCol);
601461a67faSDimitry Andric 
602461a67faSDimitry Andric       Row = LastRow;
603461a67faSDimitry Andric       Col = LastCol;
604461a67faSDimitry Andric 
605461a67faSDimitry Andric       while (Row > FirstRow || Col > FirstCol) {
606461a67faSDimitry Andric         if (Row > FirstRow &&
607461a67faSDimitry Andric             ForestDist[Row - 1][Col] + 1 == ForestDist[Row][Col]) {
608461a67faSDimitry Andric           --Row;
609461a67faSDimitry Andric         } else if (Col > FirstCol &&
610461a67faSDimitry Andric                    ForestDist[Row][Col - 1] + 1 == ForestDist[Row][Col]) {
611461a67faSDimitry Andric           --Col;
612461a67faSDimitry Andric         } else {
613461a67faSDimitry Andric           SNodeId LMD1 = S1.getLeftMostDescendant(Row);
614461a67faSDimitry Andric           SNodeId LMD2 = S2.getLeftMostDescendant(Col);
615461a67faSDimitry Andric           if (LMD1 == S1.getLeftMostDescendant(LastRow) &&
616461a67faSDimitry Andric               LMD2 == S2.getLeftMostDescendant(LastCol)) {
617461a67faSDimitry Andric             NodeId Id1 = S1.getIdInRoot(Row);
618461a67faSDimitry Andric             NodeId Id2 = S2.getIdInRoot(Col);
619461a67faSDimitry Andric             assert(DiffImpl.isMatchingPossible(Id1, Id2) &&
620461a67faSDimitry Andric                    "These nodes must not be matched.");
621461a67faSDimitry Andric             Matches.emplace_back(Id1, Id2);
622461a67faSDimitry Andric             --Row;
623461a67faSDimitry Andric             --Col;
624461a67faSDimitry Andric           } else {
625461a67faSDimitry Andric             TreePairs.emplace_back(Row, Col);
626461a67faSDimitry Andric             Row = LMD1;
627461a67faSDimitry Andric             Col = LMD2;
628461a67faSDimitry Andric           }
629461a67faSDimitry Andric         }
630461a67faSDimitry Andric       }
631461a67faSDimitry Andric     }
632461a67faSDimitry Andric     return Matches;
633461a67faSDimitry Andric   }
634461a67faSDimitry Andric 
635461a67faSDimitry Andric private:
636461a67faSDimitry Andric   /// We use a simple cost model for edit actions, which seems good enough.
637461a67faSDimitry Andric   /// Simple cost model for edit actions. This seems to make the matching
638461a67faSDimitry Andric   /// algorithm perform reasonably well.
639461a67faSDimitry Andric   /// The values range between 0 and 1, or infinity if this edit action should
640461a67faSDimitry Andric   /// always be avoided.
641461a67faSDimitry Andric   static constexpr double DeletionCost = 1;
642461a67faSDimitry Andric   static constexpr double InsertionCost = 1;
643461a67faSDimitry Andric 
getUpdateCost(SNodeId Id1,SNodeId Id2)644461a67faSDimitry Andric   double getUpdateCost(SNodeId Id1, SNodeId Id2) {
645461a67faSDimitry Andric     if (!DiffImpl.isMatchingPossible(S1.getIdInRoot(Id1), S2.getIdInRoot(Id2)))
646461a67faSDimitry Andric       return std::numeric_limits<double>::max();
647461a67faSDimitry Andric     return S1.getNodeValue(Id1) != S2.getNodeValue(Id2);
648461a67faSDimitry Andric   }
649461a67faSDimitry Andric 
computeTreeDist()650461a67faSDimitry Andric   void computeTreeDist() {
651461a67faSDimitry Andric     for (SNodeId Id1 : S1.KeyRoots)
652461a67faSDimitry Andric       for (SNodeId Id2 : S2.KeyRoots)
653461a67faSDimitry Andric         computeForestDist(Id1, Id2);
654461a67faSDimitry Andric   }
655461a67faSDimitry Andric 
computeForestDist(SNodeId Id1,SNodeId Id2)656461a67faSDimitry Andric   void computeForestDist(SNodeId Id1, SNodeId Id2) {
657461a67faSDimitry Andric     assert(Id1 > 0 && Id2 > 0 && "Expecting offsets greater than 0.");
658461a67faSDimitry Andric     SNodeId LMD1 = S1.getLeftMostDescendant(Id1);
659461a67faSDimitry Andric     SNodeId LMD2 = S2.getLeftMostDescendant(Id2);
660461a67faSDimitry Andric 
661461a67faSDimitry Andric     ForestDist[LMD1][LMD2] = 0;
662461a67faSDimitry Andric     for (SNodeId D1 = LMD1 + 1; D1 <= Id1; ++D1) {
663461a67faSDimitry Andric       ForestDist[D1][LMD2] = ForestDist[D1 - 1][LMD2] + DeletionCost;
664461a67faSDimitry Andric       for (SNodeId D2 = LMD2 + 1; D2 <= Id2; ++D2) {
665461a67faSDimitry Andric         ForestDist[LMD1][D2] = ForestDist[LMD1][D2 - 1] + InsertionCost;
666461a67faSDimitry Andric         SNodeId DLMD1 = S1.getLeftMostDescendant(D1);
667461a67faSDimitry Andric         SNodeId DLMD2 = S2.getLeftMostDescendant(D2);
668461a67faSDimitry Andric         if (DLMD1 == LMD1 && DLMD2 == LMD2) {
669461a67faSDimitry Andric           double UpdateCost = getUpdateCost(D1, D2);
670461a67faSDimitry Andric           ForestDist[D1][D2] =
671461a67faSDimitry Andric               std::min({ForestDist[D1 - 1][D2] + DeletionCost,
672461a67faSDimitry Andric                         ForestDist[D1][D2 - 1] + InsertionCost,
673461a67faSDimitry Andric                         ForestDist[D1 - 1][D2 - 1] + UpdateCost});
674461a67faSDimitry Andric           TreeDist[D1][D2] = ForestDist[D1][D2];
675461a67faSDimitry Andric         } else {
676461a67faSDimitry Andric           ForestDist[D1][D2] =
677461a67faSDimitry Andric               std::min({ForestDist[D1 - 1][D2] + DeletionCost,
678461a67faSDimitry Andric                         ForestDist[D1][D2 - 1] + InsertionCost,
679461a67faSDimitry Andric                         ForestDist[DLMD1][DLMD2] + TreeDist[D1][D2]});
680461a67faSDimitry Andric         }
681461a67faSDimitry Andric       }
682461a67faSDimitry Andric     }
683461a67faSDimitry Andric   }
684461a67faSDimitry Andric };
685461a67faSDimitry Andric 
getType() const686cfca06d7SDimitry Andric ASTNodeKind Node::getType() const { return ASTNode.getNodeKind(); }
687461a67faSDimitry Andric 
getTypeLabel() const688461a67faSDimitry Andric StringRef Node::getTypeLabel() const { return getType().asStringRef(); }
689461a67faSDimitry Andric 
getQualifiedIdentifier() const690e3b55780SDimitry Andric std::optional<std::string> Node::getQualifiedIdentifier() const {
691461a67faSDimitry Andric   if (auto *ND = ASTNode.get<NamedDecl>()) {
692461a67faSDimitry Andric     if (ND->getDeclName().isIdentifier())
693461a67faSDimitry Andric       return ND->getQualifiedNameAsString();
694461a67faSDimitry Andric   }
695e3b55780SDimitry Andric   return std::nullopt;
696461a67faSDimitry Andric }
697461a67faSDimitry Andric 
getIdentifier() const698e3b55780SDimitry Andric std::optional<StringRef> Node::getIdentifier() const {
699461a67faSDimitry Andric   if (auto *ND = ASTNode.get<NamedDecl>()) {
700461a67faSDimitry Andric     if (ND->getDeclName().isIdentifier())
701461a67faSDimitry Andric       return ND->getName();
702461a67faSDimitry Andric   }
703e3b55780SDimitry Andric   return std::nullopt;
704461a67faSDimitry Andric }
705461a67faSDimitry Andric 
706461a67faSDimitry Andric namespace {
707461a67faSDimitry Andric // Compares nodes by their depth.
708461a67faSDimitry Andric struct HeightLess {
709461a67faSDimitry Andric   const SyntaxTree::Impl &Tree;
HeightLessclang::diff::__anon0b30a76b0511::HeightLess710461a67faSDimitry Andric   HeightLess(const SyntaxTree::Impl &Tree) : Tree(Tree) {}
operator ()clang::diff::__anon0b30a76b0511::HeightLess711461a67faSDimitry Andric   bool operator()(NodeId Id1, NodeId Id2) const {
712461a67faSDimitry Andric     return Tree.getNode(Id1).Height < Tree.getNode(Id2).Height;
713461a67faSDimitry Andric   }
714461a67faSDimitry Andric };
715461a67faSDimitry Andric } // end anonymous namespace
716461a67faSDimitry Andric 
717461a67faSDimitry Andric namespace {
718461a67faSDimitry Andric // Priority queue for nodes, sorted descendingly by their height.
719461a67faSDimitry Andric class PriorityList {
720461a67faSDimitry Andric   const SyntaxTree::Impl &Tree;
721461a67faSDimitry Andric   HeightLess Cmp;
722461a67faSDimitry Andric   std::vector<NodeId> Container;
723461a67faSDimitry Andric   PriorityQueue<NodeId, std::vector<NodeId>, HeightLess> List;
724461a67faSDimitry Andric 
725461a67faSDimitry Andric public:
PriorityList(const SyntaxTree::Impl & Tree)726461a67faSDimitry Andric   PriorityList(const SyntaxTree::Impl &Tree)
727461a67faSDimitry Andric       : Tree(Tree), Cmp(Tree), List(Cmp, Container) {}
728461a67faSDimitry Andric 
push(NodeId id)729461a67faSDimitry Andric   void push(NodeId id) { List.push(id); }
730461a67faSDimitry Andric 
pop()731461a67faSDimitry Andric   std::vector<NodeId> pop() {
732461a67faSDimitry Andric     int Max = peekMax();
733461a67faSDimitry Andric     std::vector<NodeId> Result;
734461a67faSDimitry Andric     if (Max == 0)
735461a67faSDimitry Andric       return Result;
736461a67faSDimitry Andric     while (peekMax() == Max) {
737461a67faSDimitry Andric       Result.push_back(List.top());
738461a67faSDimitry Andric       List.pop();
739461a67faSDimitry Andric     }
740461a67faSDimitry Andric     // TODO this is here to get a stable output, not a good heuristic
741676fbe81SDimitry Andric     llvm::sort(Result);
742461a67faSDimitry Andric     return Result;
743461a67faSDimitry Andric   }
peekMax() const744461a67faSDimitry Andric   int peekMax() const {
745461a67faSDimitry Andric     if (List.empty())
746461a67faSDimitry Andric       return 0;
747461a67faSDimitry Andric     return Tree.getNode(List.top()).Height;
748461a67faSDimitry Andric   }
open(NodeId Id)749461a67faSDimitry Andric   void open(NodeId Id) {
750461a67faSDimitry Andric     for (NodeId Child : Tree.getNode(Id).Children)
751461a67faSDimitry Andric       push(Child);
752461a67faSDimitry Andric   }
753461a67faSDimitry Andric };
754461a67faSDimitry Andric } // end anonymous namespace
755461a67faSDimitry Andric 
identical(NodeId Id1,NodeId Id2) const756461a67faSDimitry Andric bool ASTDiff::Impl::identical(NodeId Id1, NodeId Id2) const {
757461a67faSDimitry Andric   const Node &N1 = T1.getNode(Id1);
758461a67faSDimitry Andric   const Node &N2 = T2.getNode(Id2);
759461a67faSDimitry Andric   if (N1.Children.size() != N2.Children.size() ||
760461a67faSDimitry Andric       !isMatchingPossible(Id1, Id2) ||
761461a67faSDimitry Andric       T1.getNodeValue(Id1) != T2.getNodeValue(Id2))
762461a67faSDimitry Andric     return false;
763461a67faSDimitry Andric   for (size_t Id = 0, E = N1.Children.size(); Id < E; ++Id)
764461a67faSDimitry Andric     if (!identical(N1.Children[Id], N2.Children[Id]))
765461a67faSDimitry Andric       return false;
766461a67faSDimitry Andric   return true;
767461a67faSDimitry Andric }
768461a67faSDimitry Andric 
isMatchingPossible(NodeId Id1,NodeId Id2) const769461a67faSDimitry Andric bool ASTDiff::Impl::isMatchingPossible(NodeId Id1, NodeId Id2) const {
770461a67faSDimitry Andric   return Options.isMatchingAllowed(T1.getNode(Id1), T2.getNode(Id2));
771461a67faSDimitry Andric }
772461a67faSDimitry Andric 
haveSameParents(const Mapping & M,NodeId Id1,NodeId Id2) const773461a67faSDimitry Andric bool ASTDiff::Impl::haveSameParents(const Mapping &M, NodeId Id1,
774461a67faSDimitry Andric                                     NodeId Id2) const {
775461a67faSDimitry Andric   NodeId P1 = T1.getNode(Id1).Parent;
776461a67faSDimitry Andric   NodeId P2 = T2.getNode(Id2).Parent;
777461a67faSDimitry Andric   return (P1.isInvalid() && P2.isInvalid()) ||
778461a67faSDimitry Andric          (P1.isValid() && P2.isValid() && M.getDst(P1) == P2);
779461a67faSDimitry Andric }
780461a67faSDimitry Andric 
addOptimalMapping(Mapping & M,NodeId Id1,NodeId Id2) const781461a67faSDimitry Andric void ASTDiff::Impl::addOptimalMapping(Mapping &M, NodeId Id1,
782461a67faSDimitry Andric                                       NodeId Id2) const {
783461a67faSDimitry Andric   if (std::max(T1.getNumberOfDescendants(Id1), T2.getNumberOfDescendants(Id2)) >
784461a67faSDimitry Andric       Options.MaxSize)
785461a67faSDimitry Andric     return;
786461a67faSDimitry Andric   ZhangShashaMatcher Matcher(*this, T1, T2, Id1, Id2);
787461a67faSDimitry Andric   std::vector<std::pair<NodeId, NodeId>> R = Matcher.getMatchingNodes();
788706b4fc4SDimitry Andric   for (const auto &Tuple : R) {
789461a67faSDimitry Andric     NodeId Src = Tuple.first;
790461a67faSDimitry Andric     NodeId Dst = Tuple.second;
791461a67faSDimitry Andric     if (!M.hasSrc(Src) && !M.hasDst(Dst))
792461a67faSDimitry Andric       M.link(Src, Dst);
793461a67faSDimitry Andric   }
794461a67faSDimitry Andric }
795461a67faSDimitry Andric 
getJaccardSimilarity(const Mapping & M,NodeId Id1,NodeId Id2) const796461a67faSDimitry Andric double ASTDiff::Impl::getJaccardSimilarity(const Mapping &M, NodeId Id1,
797461a67faSDimitry Andric                                            NodeId Id2) const {
798461a67faSDimitry Andric   int CommonDescendants = 0;
799461a67faSDimitry Andric   const Node &N1 = T1.getNode(Id1);
800461a67faSDimitry Andric   // Count the common descendants, excluding the subtree root.
801461a67faSDimitry Andric   for (NodeId Src = Id1 + 1; Src <= N1.RightMostDescendant; ++Src) {
802461a67faSDimitry Andric     NodeId Dst = M.getDst(Src);
803461a67faSDimitry Andric     CommonDescendants += int(Dst.isValid() && T2.isInSubtree(Dst, Id2));
804461a67faSDimitry Andric   }
805461a67faSDimitry Andric   // We need to subtract 1 to get the number of descendants excluding the root.
806461a67faSDimitry Andric   double Denominator = T1.getNumberOfDescendants(Id1) - 1 +
807461a67faSDimitry Andric                        T2.getNumberOfDescendants(Id2) - 1 - CommonDescendants;
808461a67faSDimitry Andric   // CommonDescendants is less than the size of one subtree.
809461a67faSDimitry Andric   assert(Denominator >= 0 && "Expected non-negative denominator.");
810461a67faSDimitry Andric   if (Denominator == 0)
811461a67faSDimitry Andric     return 0;
812461a67faSDimitry Andric   return CommonDescendants / Denominator;
813461a67faSDimitry Andric }
814461a67faSDimitry Andric 
findCandidate(const Mapping & M,NodeId Id1) const815461a67faSDimitry Andric NodeId ASTDiff::Impl::findCandidate(const Mapping &M, NodeId Id1) const {
816461a67faSDimitry Andric   NodeId Candidate;
817461a67faSDimitry Andric   double HighestSimilarity = 0.0;
818461a67faSDimitry Andric   for (NodeId Id2 : T2) {
819461a67faSDimitry Andric     if (!isMatchingPossible(Id1, Id2))
820461a67faSDimitry Andric       continue;
821461a67faSDimitry Andric     if (M.hasDst(Id2))
822461a67faSDimitry Andric       continue;
823461a67faSDimitry Andric     double Similarity = getJaccardSimilarity(M, Id1, Id2);
824461a67faSDimitry Andric     if (Similarity >= Options.MinSimilarity && Similarity > HighestSimilarity) {
825461a67faSDimitry Andric       HighestSimilarity = Similarity;
826461a67faSDimitry Andric       Candidate = Id2;
827461a67faSDimitry Andric     }
828461a67faSDimitry Andric   }
829461a67faSDimitry Andric   return Candidate;
830461a67faSDimitry Andric }
831461a67faSDimitry Andric 
matchBottomUp(Mapping & M) const832461a67faSDimitry Andric void ASTDiff::Impl::matchBottomUp(Mapping &M) const {
833461a67faSDimitry Andric   std::vector<NodeId> Postorder = getSubtreePostorder(T1, T1.getRootId());
834461a67faSDimitry Andric   for (NodeId Id1 : Postorder) {
835461a67faSDimitry Andric     if (Id1 == T1.getRootId() && !M.hasSrc(T1.getRootId()) &&
836461a67faSDimitry Andric         !M.hasDst(T2.getRootId())) {
837461a67faSDimitry Andric       if (isMatchingPossible(T1.getRootId(), T2.getRootId())) {
838461a67faSDimitry Andric         M.link(T1.getRootId(), T2.getRootId());
839461a67faSDimitry Andric         addOptimalMapping(M, T1.getRootId(), T2.getRootId());
840461a67faSDimitry Andric       }
841461a67faSDimitry Andric       break;
842461a67faSDimitry Andric     }
843461a67faSDimitry Andric     bool Matched = M.hasSrc(Id1);
844461a67faSDimitry Andric     const Node &N1 = T1.getNode(Id1);
845676fbe81SDimitry Andric     bool MatchedChildren = llvm::any_of(
846676fbe81SDimitry Andric         N1.Children, [&](NodeId Child) { return M.hasSrc(Child); });
847461a67faSDimitry Andric     if (Matched || !MatchedChildren)
848461a67faSDimitry Andric       continue;
849461a67faSDimitry Andric     NodeId Id2 = findCandidate(M, Id1);
850461a67faSDimitry Andric     if (Id2.isValid()) {
851461a67faSDimitry Andric       M.link(Id1, Id2);
852461a67faSDimitry Andric       addOptimalMapping(M, Id1, Id2);
853461a67faSDimitry Andric     }
854461a67faSDimitry Andric   }
855461a67faSDimitry Andric }
856461a67faSDimitry Andric 
matchTopDown() const857461a67faSDimitry Andric Mapping ASTDiff::Impl::matchTopDown() const {
858461a67faSDimitry Andric   PriorityList L1(T1);
859461a67faSDimitry Andric   PriorityList L2(T2);
860461a67faSDimitry Andric 
861461a67faSDimitry Andric   Mapping M(T1.getSize() + T2.getSize());
862461a67faSDimitry Andric 
863461a67faSDimitry Andric   L1.push(T1.getRootId());
864461a67faSDimitry Andric   L2.push(T2.getRootId());
865461a67faSDimitry Andric 
866461a67faSDimitry Andric   int Max1, Max2;
867461a67faSDimitry Andric   while (std::min(Max1 = L1.peekMax(), Max2 = L2.peekMax()) >
868461a67faSDimitry Andric          Options.MinHeight) {
869461a67faSDimitry Andric     if (Max1 > Max2) {
870461a67faSDimitry Andric       for (NodeId Id : L1.pop())
871461a67faSDimitry Andric         L1.open(Id);
872461a67faSDimitry Andric       continue;
873461a67faSDimitry Andric     }
874461a67faSDimitry Andric     if (Max2 > Max1) {
875461a67faSDimitry Andric       for (NodeId Id : L2.pop())
876461a67faSDimitry Andric         L2.open(Id);
877461a67faSDimitry Andric       continue;
878461a67faSDimitry Andric     }
879461a67faSDimitry Andric     std::vector<NodeId> H1, H2;
880461a67faSDimitry Andric     H1 = L1.pop();
881461a67faSDimitry Andric     H2 = L2.pop();
882461a67faSDimitry Andric     for (NodeId Id1 : H1) {
883461a67faSDimitry Andric       for (NodeId Id2 : H2) {
884461a67faSDimitry Andric         if (identical(Id1, Id2) && !M.hasSrc(Id1) && !M.hasDst(Id2)) {
885461a67faSDimitry Andric           for (int I = 0, E = T1.getNumberOfDescendants(Id1); I < E; ++I)
886461a67faSDimitry Andric             M.link(Id1 + I, Id2 + I);
887461a67faSDimitry Andric         }
888461a67faSDimitry Andric       }
889461a67faSDimitry Andric     }
890461a67faSDimitry Andric     for (NodeId Id1 : H1) {
891461a67faSDimitry Andric       if (!M.hasSrc(Id1))
892461a67faSDimitry Andric         L1.open(Id1);
893461a67faSDimitry Andric     }
894461a67faSDimitry Andric     for (NodeId Id2 : H2) {
895461a67faSDimitry Andric       if (!M.hasDst(Id2))
896461a67faSDimitry Andric         L2.open(Id2);
897461a67faSDimitry Andric     }
898461a67faSDimitry Andric   }
899461a67faSDimitry Andric   return M;
900461a67faSDimitry Andric }
901461a67faSDimitry Andric 
Impl(SyntaxTree::Impl & T1,SyntaxTree::Impl & T2,const ComparisonOptions & Options)902461a67faSDimitry Andric ASTDiff::Impl::Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
903461a67faSDimitry Andric                     const ComparisonOptions &Options)
904461a67faSDimitry Andric     : T1(T1), T2(T2), Options(Options) {
905461a67faSDimitry Andric   computeMapping();
906461a67faSDimitry Andric   computeChangeKinds(TheMapping);
907461a67faSDimitry Andric }
908461a67faSDimitry Andric 
computeMapping()909461a67faSDimitry Andric void ASTDiff::Impl::computeMapping() {
910461a67faSDimitry Andric   TheMapping = matchTopDown();
911461a67faSDimitry Andric   if (Options.StopAfterTopDown)
912461a67faSDimitry Andric     return;
913461a67faSDimitry Andric   matchBottomUp(TheMapping);
914461a67faSDimitry Andric }
915461a67faSDimitry Andric 
computeChangeKinds(Mapping & M)916461a67faSDimitry Andric void ASTDiff::Impl::computeChangeKinds(Mapping &M) {
917461a67faSDimitry Andric   for (NodeId Id1 : T1) {
918461a67faSDimitry Andric     if (!M.hasSrc(Id1)) {
919461a67faSDimitry Andric       T1.getMutableNode(Id1).Change = Delete;
920461a67faSDimitry Andric       T1.getMutableNode(Id1).Shift -= 1;
921461a67faSDimitry Andric     }
922461a67faSDimitry Andric   }
923461a67faSDimitry Andric   for (NodeId Id2 : T2) {
924461a67faSDimitry Andric     if (!M.hasDst(Id2)) {
925461a67faSDimitry Andric       T2.getMutableNode(Id2).Change = Insert;
926461a67faSDimitry Andric       T2.getMutableNode(Id2).Shift -= 1;
927461a67faSDimitry Andric     }
928461a67faSDimitry Andric   }
929461a67faSDimitry Andric   for (NodeId Id1 : T1.NodesBfs) {
930461a67faSDimitry Andric     NodeId Id2 = M.getDst(Id1);
931461a67faSDimitry Andric     if (Id2.isInvalid())
932461a67faSDimitry Andric       continue;
933461a67faSDimitry Andric     if (!haveSameParents(M, Id1, Id2) ||
934461a67faSDimitry Andric         T1.findPositionInParent(Id1, true) !=
935461a67faSDimitry Andric             T2.findPositionInParent(Id2, true)) {
936461a67faSDimitry Andric       T1.getMutableNode(Id1).Shift -= 1;
937461a67faSDimitry Andric       T2.getMutableNode(Id2).Shift -= 1;
938461a67faSDimitry Andric     }
939461a67faSDimitry Andric   }
940461a67faSDimitry Andric   for (NodeId Id2 : T2.NodesBfs) {
941461a67faSDimitry Andric     NodeId Id1 = M.getSrc(Id2);
942461a67faSDimitry Andric     if (Id1.isInvalid())
943461a67faSDimitry Andric       continue;
944461a67faSDimitry Andric     Node &N1 = T1.getMutableNode(Id1);
945461a67faSDimitry Andric     Node &N2 = T2.getMutableNode(Id2);
946461a67faSDimitry Andric     if (Id1.isInvalid())
947461a67faSDimitry Andric       continue;
948461a67faSDimitry Andric     if (!haveSameParents(M, Id1, Id2) ||
949461a67faSDimitry Andric         T1.findPositionInParent(Id1, true) !=
950461a67faSDimitry Andric             T2.findPositionInParent(Id2, true)) {
951461a67faSDimitry Andric       N1.Change = N2.Change = Move;
952461a67faSDimitry Andric     }
953461a67faSDimitry Andric     if (T1.getNodeValue(Id1) != T2.getNodeValue(Id2)) {
954461a67faSDimitry Andric       N1.Change = N2.Change = (N1.Change == Move ? UpdateMove : Update);
955461a67faSDimitry Andric     }
956461a67faSDimitry Andric   }
957461a67faSDimitry Andric }
958461a67faSDimitry Andric 
ASTDiff(SyntaxTree & T1,SyntaxTree & T2,const ComparisonOptions & Options)959461a67faSDimitry Andric ASTDiff::ASTDiff(SyntaxTree &T1, SyntaxTree &T2,
960461a67faSDimitry Andric                  const ComparisonOptions &Options)
961519fc96cSDimitry Andric     : DiffImpl(std::make_unique<Impl>(*T1.TreeImpl, *T2.TreeImpl, Options)) {}
962461a67faSDimitry Andric 
963461a67faSDimitry Andric ASTDiff::~ASTDiff() = default;
964461a67faSDimitry Andric 
getMapped(const SyntaxTree & SourceTree,NodeId Id) const965461a67faSDimitry Andric NodeId ASTDiff::getMapped(const SyntaxTree &SourceTree, NodeId Id) const {
966461a67faSDimitry Andric   return DiffImpl->getMapped(SourceTree.TreeImpl, Id);
967461a67faSDimitry Andric }
968461a67faSDimitry Andric 
SyntaxTree(ASTContext & AST)969461a67faSDimitry Andric SyntaxTree::SyntaxTree(ASTContext &AST)
970519fc96cSDimitry Andric     : TreeImpl(std::make_unique<SyntaxTree::Impl>(
971461a67faSDimitry Andric           this, AST.getTranslationUnitDecl(), AST)) {}
972461a67faSDimitry Andric 
973461a67faSDimitry Andric SyntaxTree::~SyntaxTree() = default;
974461a67faSDimitry Andric 
getASTContext() const975461a67faSDimitry Andric const ASTContext &SyntaxTree::getASTContext() const { return TreeImpl->AST; }
976461a67faSDimitry Andric 
getNode(NodeId Id) const977461a67faSDimitry Andric const Node &SyntaxTree::getNode(NodeId Id) const {
978461a67faSDimitry Andric   return TreeImpl->getNode(Id);
979461a67faSDimitry Andric }
980461a67faSDimitry Andric 
getSize() const981461a67faSDimitry Andric int SyntaxTree::getSize() const { return TreeImpl->getSize(); }
getRootId() const982461a67faSDimitry Andric NodeId SyntaxTree::getRootId() const { return TreeImpl->getRootId(); }
begin() const983461a67faSDimitry Andric SyntaxTree::PreorderIterator SyntaxTree::begin() const {
984461a67faSDimitry Andric   return TreeImpl->begin();
985461a67faSDimitry Andric }
end() const986461a67faSDimitry Andric SyntaxTree::PreorderIterator SyntaxTree::end() const { return TreeImpl->end(); }
987461a67faSDimitry Andric 
findPositionInParent(NodeId Id) const988461a67faSDimitry Andric int SyntaxTree::findPositionInParent(NodeId Id) const {
989461a67faSDimitry Andric   return TreeImpl->findPositionInParent(Id);
990461a67faSDimitry Andric }
991461a67faSDimitry Andric 
992461a67faSDimitry Andric std::pair<unsigned, unsigned>
getSourceRangeOffsets(const Node & N) const993461a67faSDimitry Andric SyntaxTree::getSourceRangeOffsets(const Node &N) const {
994461a67faSDimitry Andric   const SourceManager &SrcMgr = TreeImpl->AST.getSourceManager();
995461a67faSDimitry Andric   SourceRange Range = N.ASTNode.getSourceRange();
996461a67faSDimitry Andric   SourceLocation BeginLoc = Range.getBegin();
997461a67faSDimitry Andric   SourceLocation EndLoc = Lexer::getLocForEndOfToken(
998461a67faSDimitry Andric       Range.getEnd(), /*Offset=*/0, SrcMgr, TreeImpl->AST.getLangOpts());
999461a67faSDimitry Andric   if (auto *ThisExpr = N.ASTNode.get<CXXThisExpr>()) {
1000461a67faSDimitry Andric     if (ThisExpr->isImplicit())
1001461a67faSDimitry Andric       EndLoc = BeginLoc;
1002461a67faSDimitry Andric   }
1003461a67faSDimitry Andric   unsigned Begin = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(BeginLoc));
1004461a67faSDimitry Andric   unsigned End = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(EndLoc));
1005461a67faSDimitry Andric   return {Begin, End};
1006461a67faSDimitry Andric }
1007461a67faSDimitry Andric 
getNodeValue(NodeId Id) const1008461a67faSDimitry Andric std::string SyntaxTree::getNodeValue(NodeId Id) const {
1009461a67faSDimitry Andric   return TreeImpl->getNodeValue(Id);
1010461a67faSDimitry Andric }
1011461a67faSDimitry Andric 
getNodeValue(const Node & N) const1012461a67faSDimitry Andric std::string SyntaxTree::getNodeValue(const Node &N) const {
1013461a67faSDimitry Andric   return TreeImpl->getNodeValue(N);
1014461a67faSDimitry Andric }
1015461a67faSDimitry Andric 
1016461a67faSDimitry Andric } // end namespace diff
1017461a67faSDimitry Andric } // end namespace clang
1018