blob: 0821863adcc6e7f40dffc483f7ac6fdf6fb683b7 [file] [log] [blame]
Alex Lorenza75b2ca2017-07-21 12:49:28 +00001//===- ASTDiff.cpp - AST differencing implementation-----------*- C++ -*- -===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alex Lorenza75b2ca2017-07-21 12:49:28 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file contains definitons for the AST differencing interface.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Tooling/ASTDiff/ASTDiff.h"
Reid Kleckner8a81daa2019-12-09 17:03:47 -080014#include "clang/AST/ParentMapContext.h"
Alex Lorenza75b2ca2017-07-21 12:49:28 +000015#include "clang/AST/RecursiveASTVisitor.h"
Reid Kleckner86565c12020-02-27 11:01:58 -080016#include "clang/Basic/SourceManager.h"
Alex Lorenza75b2ca2017-07-21 12:49:28 +000017#include "clang/Lex/Lexer.h"
18#include "llvm/ADT/PriorityQueue.h"
19
20#include <limits>
21#include <memory>
22#include <unordered_set>
23
24using namespace llvm;
25using namespace clang;
26
27namespace clang {
28namespace diff {
29
Johannes Altmanningerfa524d72017-08-18 16:34:15 +000030namespace {
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000031/// Maps nodes of the left tree to ones on the right, and vice versa.
32class Mapping {
33public:
34 Mapping() = default;
35 Mapping(Mapping &&Other) = default;
36 Mapping &operator=(Mapping &&Other) = default;
Johannes Altmanninger51321ae2017-08-19 17:53:01 +000037
38 Mapping(size_t Size) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +000039 SrcToDst = std::make_unique<NodeId[]>(Size);
40 DstToSrc = std::make_unique<NodeId[]>(Size);
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000041 }
42
43 void link(NodeId Src, NodeId Dst) {
Johannes Altmanninger51321ae2017-08-19 17:53:01 +000044 SrcToDst[Src] = Dst, DstToSrc[Dst] = Src;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000045 }
46
Johannes Altmanninger51321ae2017-08-19 17:53:01 +000047 NodeId getDst(NodeId Src) const { return SrcToDst[Src]; }
48 NodeId getSrc(NodeId Dst) const { return DstToSrc[Dst]; }
49 bool hasSrc(NodeId Src) const { return getDst(Src).isValid(); }
50 bool hasDst(NodeId Dst) const { return getSrc(Dst).isValid(); }
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000051
52private:
Johannes Altmanninger51321ae2017-08-19 17:53:01 +000053 std::unique_ptr<NodeId[]> SrcToDst, DstToSrc;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000054};
Johannes Altmanningerfa524d72017-08-18 16:34:15 +000055} // end anonymous namespace
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000056
Alex Lorenza75b2ca2017-07-21 12:49:28 +000057class ASTDiff::Impl {
58public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +000059 SyntaxTree::Impl &T1, &T2;
Alex Lorenza75b2ca2017-07-21 12:49:28 +000060 Mapping TheMapping;
61
Johannes Altmanninger31b52d62017-08-01 20:17:46 +000062 Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +000063 const ComparisonOptions &Options);
Alex Lorenza75b2ca2017-07-21 12:49:28 +000064
65 /// Matches nodes one-by-one based on their similarity.
66 void computeMapping();
67
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +000068 // Compute Change for each node based on similarity.
69 void computeChangeKinds(Mapping &M);
Alex Lorenza75b2ca2017-07-21 12:49:28 +000070
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +000071 NodeId getMapped(const std::unique_ptr<SyntaxTree::Impl> &Tree,
72 NodeId Id) const {
73 if (&*Tree == &T1)
74 return TheMapping.getDst(Id);
75 assert(&*Tree == &T2 && "Invalid tree.");
76 return TheMapping.getSrc(Id);
77 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +000078
79private:
80 // Returns true if the two subtrees are identical.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +000081 bool identical(NodeId Id1, NodeId Id2) const;
Alex Lorenza75b2ca2017-07-21 12:49:28 +000082
Alex Lorenza75b2ca2017-07-21 12:49:28 +000083 // Returns false if the nodes must not be mached.
84 bool isMatchingPossible(NodeId Id1, NodeId Id2) const;
85
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +000086 // Returns true if the nodes' parents are matched.
87 bool haveSameParents(const Mapping &M, NodeId Id1, NodeId Id2) const;
88
Alex Lorenza75b2ca2017-07-21 12:49:28 +000089 // Uses an optimal albeit slow algorithm to compute a mapping between two
90 // subtrees, but only if both have fewer nodes than MaxSize.
91 void addOptimalMapping(Mapping &M, NodeId Id1, NodeId Id2) const;
92
93 // Computes the ratio of common descendants between the two nodes.
94 // Descendants are only considered to be equal when they are mapped in M.
Johannes Altmanningerd1969302017-08-20 12:09:07 +000095 double getJaccardSimilarity(const Mapping &M, NodeId Id1, NodeId Id2) const;
Alex Lorenza75b2ca2017-07-21 12:49:28 +000096
97 // Returns the node that has the highest degree of similarity.
98 NodeId findCandidate(const Mapping &M, NodeId Id1) const;
99
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000100 // Returns a mapping of identical subtrees.
101 Mapping matchTopDown() const;
102
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000103 // Tries to match any yet unmapped nodes, in a bottom-up fashion.
104 void matchBottomUp(Mapping &M) const;
105
106 const ComparisonOptions &Options;
107
108 friend class ZhangShashaMatcher;
109};
110
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000111/// Represents the AST of a TranslationUnit.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000112class SyntaxTree::Impl {
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000113public:
Johannes Altmanninger41395022017-08-27 22:52:20 +0000114 Impl(SyntaxTree *Parent, ASTContext &AST);
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000115 /// Constructs a tree from an AST node.
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000116 Impl(SyntaxTree *Parent, Decl *N, ASTContext &AST);
117 Impl(SyntaxTree *Parent, Stmt *N, ASTContext &AST);
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000118 template <class T>
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000119 Impl(SyntaxTree *Parent,
Justin Lebar027eb712020-02-10 23:23:44 -0800120 std::enable_if_t<std::is_base_of<Stmt, T>::value, T> *Node,
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000121 ASTContext &AST)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000122 : Impl(Parent, dyn_cast<Stmt>(Node), AST) {}
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000123 template <class T>
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000124 Impl(SyntaxTree *Parent,
Justin Lebar027eb712020-02-10 23:23:44 -0800125 std::enable_if_t<std::is_base_of<Decl, T>::value, T> *Node,
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000126 ASTContext &AST)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000127 : Impl(Parent, dyn_cast<Decl>(Node), AST) {}
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000128
129 SyntaxTree *Parent;
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000130 ASTContext &AST;
Johannes Altmanninger41395022017-08-27 22:52:20 +0000131 PrintingPolicy TypePP;
Johannes Altmanningerbc3e9932017-08-25 09:49:49 +0000132 /// Nodes in preorder.
133 std::vector<Node> Nodes;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000134 std::vector<NodeId> Leaves;
135 // Maps preorder indices to postorder ones.
136 std::vector<int> PostorderIds;
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000137 std::vector<NodeId> NodesBfs;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000138
139 int getSize() const { return Nodes.size(); }
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000140 NodeId getRootId() const { return 0; }
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000141 PreorderIterator begin() const { return getRootId(); }
142 PreorderIterator end() const { return getSize(); }
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000143
144 const Node &getNode(NodeId Id) const { return Nodes[Id]; }
145 Node &getMutableNode(NodeId Id) { return Nodes[Id]; }
146 bool isValidNodeId(NodeId Id) const { return Id >= 0 && Id < getSize(); }
147 void addNode(Node &N) { Nodes.push_back(N); }
148 int getNumberOfDescendants(NodeId Id) const;
149 bool isInSubtree(NodeId Id, NodeId SubtreeRoot) const;
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000150 int findPositionInParent(NodeId Id, bool Shifted = false) const;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000151
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000152 std::string getRelativeName(const NamedDecl *ND,
153 const DeclContext *Context) const;
154 std::string getRelativeName(const NamedDecl *ND) const;
155
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000156 std::string getNodeValue(NodeId Id) const;
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000157 std::string getNodeValue(const Node &Node) const;
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000158 std::string getDeclValue(const Decl *D) const;
159 std::string getStmtValue(const Stmt *S) const;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000160
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000161private:
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000162 void initTree();
163 void setLeftMostDescendants();
164};
165
Johannes Altmanningerd5b56a82017-08-20 10:22:32 +0000166static bool isSpecializedNodeExcluded(const Decl *D) { return D->isImplicit(); }
167static bool isSpecializedNodeExcluded(const Stmt *S) { return false; }
Johannes Altmanninger41395022017-08-27 22:52:20 +0000168static bool isSpecializedNodeExcluded(CXXCtorInitializer *I) {
169 return !I->isWritten();
170}
Johannes Altmanningerd5b56a82017-08-20 10:22:32 +0000171
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000172template <class T>
173static bool isNodeExcluded(const SourceManager &SrcMgr, T *N) {
174 if (!N)
175 return true;
Johannes Altmanninger41395022017-08-27 22:52:20 +0000176 SourceLocation SLoc = N->getSourceRange().getBegin();
Johannes Altmanningerd5b56a82017-08-20 10:22:32 +0000177 if (SLoc.isValid()) {
178 // Ignore everything from other files.
179 if (!SrcMgr.isInMainFile(SLoc))
180 return true;
181 // Ignore macros.
182 if (SLoc != SrcMgr.getSpellingLoc(SLoc))
183 return true;
184 }
185 return isSpecializedNodeExcluded(N);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000186}
187
188namespace {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000189// Sets Height, Parent and Children for each node.
190struct PreorderVisitor : public RecursiveASTVisitor<PreorderVisitor> {
191 int Id = 0, Depth = 0;
192 NodeId Parent;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000193 SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000194
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000195 PreorderVisitor(SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000196
197 template <class T> std::tuple<NodeId, NodeId> PreTraverse(T *ASTNode) {
198 NodeId MyId = Id;
Johannes Altmanningerbc3e9932017-08-25 09:49:49 +0000199 Tree.Nodes.emplace_back();
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000200 Node &N = Tree.getMutableNode(MyId);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000201 N.Parent = Parent;
202 N.Depth = Depth;
203 N.ASTNode = DynTypedNode::create(*ASTNode);
204 assert(!N.ASTNode.getNodeKind().isNone() &&
205 "Expected nodes to have a valid kind.");
206 if (Parent.isValid()) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000207 Node &P = Tree.getMutableNode(Parent);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000208 P.Children.push_back(MyId);
209 }
210 Parent = MyId;
211 ++Id;
212 ++Depth;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000213 return std::make_tuple(MyId, Tree.getNode(MyId).Parent);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000214 }
215 void PostTraverse(std::tuple<NodeId, NodeId> State) {
216 NodeId MyId, PreviousParent;
217 std::tie(MyId, PreviousParent) = State;
218 assert(MyId.isValid() && "Expecting to only traverse valid nodes.");
219 Parent = PreviousParent;
220 --Depth;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000221 Node &N = Tree.getMutableNode(MyId);
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000222 N.RightMostDescendant = Id - 1;
223 assert(N.RightMostDescendant >= 0 &&
224 N.RightMostDescendant < Tree.getSize() &&
225 "Rightmost descendant must be a valid tree node.");
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000226 if (N.isLeaf())
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000227 Tree.Leaves.push_back(MyId);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000228 N.Height = 1;
229 for (NodeId Child : N.Children)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000230 N.Height = std::max(N.Height, 1 + Tree.getNode(Child).Height);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000231 }
232 bool TraverseDecl(Decl *D) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000233 if (isNodeExcluded(Tree.AST.getSourceManager(), D))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000234 return true;
235 auto SavedState = PreTraverse(D);
236 RecursiveASTVisitor<PreorderVisitor>::TraverseDecl(D);
237 PostTraverse(SavedState);
238 return true;
239 }
240 bool TraverseStmt(Stmt *S) {
Bruno Riccie64aee82019-02-03 19:50:56 +0000241 if (auto *E = dyn_cast_or_null<Expr>(S))
242 S = E->IgnoreImplicit();
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000243 if (isNodeExcluded(Tree.AST.getSourceManager(), S))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000244 return true;
245 auto SavedState = PreTraverse(S);
246 RecursiveASTVisitor<PreorderVisitor>::TraverseStmt(S);
247 PostTraverse(SavedState);
248 return true;
249 }
250 bool TraverseType(QualType T) { return true; }
Johannes Altmanninger41395022017-08-27 22:52:20 +0000251 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
252 if (isNodeExcluded(Tree.AST.getSourceManager(), Init))
253 return true;
254 auto SavedState = PreTraverse(Init);
255 RecursiveASTVisitor<PreorderVisitor>::TraverseConstructorInitializer(Init);
256 PostTraverse(SavedState);
257 return true;
258 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000259};
260} // end anonymous namespace
261
Johannes Altmanninger41395022017-08-27 22:52:20 +0000262SyntaxTree::Impl::Impl(SyntaxTree *Parent, ASTContext &AST)
263 : Parent(Parent), AST(AST), TypePP(AST.getLangOpts()) {
264 TypePP.AnonymousTagLocations = false;
265}
266
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000267SyntaxTree::Impl::Impl(SyntaxTree *Parent, Decl *N, ASTContext &AST)
Johannes Altmanninger41395022017-08-27 22:52:20 +0000268 : Impl(Parent, AST) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000269 PreorderVisitor PreorderWalker(*this);
270 PreorderWalker.TraverseDecl(N);
271 initTree();
272}
273
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000274SyntaxTree::Impl::Impl(SyntaxTree *Parent, Stmt *N, ASTContext &AST)
Johannes Altmanninger41395022017-08-27 22:52:20 +0000275 : Impl(Parent, AST) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000276 PreorderVisitor PreorderWalker(*this);
277 PreorderWalker.TraverseStmt(N);
278 initTree();
279}
280
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000281static std::vector<NodeId> getSubtreePostorder(const SyntaxTree::Impl &Tree,
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000282 NodeId Root) {
283 std::vector<NodeId> Postorder;
284 std::function<void(NodeId)> Traverse = [&](NodeId Id) {
285 const Node &N = Tree.getNode(Id);
286 for (NodeId Child : N.Children)
287 Traverse(Child);
288 Postorder.push_back(Id);
289 };
290 Traverse(Root);
291 return Postorder;
292}
293
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000294static std::vector<NodeId> getSubtreeBfs(const SyntaxTree::Impl &Tree,
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000295 NodeId Root) {
296 std::vector<NodeId> Ids;
297 size_t Expanded = 0;
298 Ids.push_back(Root);
299 while (Expanded < Ids.size())
300 for (NodeId Child : Tree.getNode(Ids[Expanded++]).Children)
301 Ids.push_back(Child);
302 return Ids;
303}
304
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000305void SyntaxTree::Impl::initTree() {
306 setLeftMostDescendants();
307 int PostorderId = 0;
308 PostorderIds.resize(getSize());
309 std::function<void(NodeId)> PostorderTraverse = [&](NodeId Id) {
310 for (NodeId Child : getNode(Id).Children)
311 PostorderTraverse(Child);
312 PostorderIds[Id] = PostorderId;
313 ++PostorderId;
314 };
315 PostorderTraverse(getRootId());
316 NodesBfs = getSubtreeBfs(*this, getRootId());
317}
318
319void SyntaxTree::Impl::setLeftMostDescendants() {
320 for (NodeId Leaf : Leaves) {
321 getMutableNode(Leaf).LeftMostDescendant = Leaf;
322 NodeId Parent, Cur = Leaf;
323 while ((Parent = getNode(Cur).Parent).isValid() &&
324 getNode(Parent).Children[0] == Cur) {
325 Cur = Parent;
326 getMutableNode(Cur).LeftMostDescendant = Leaf;
327 }
328 }
329}
330
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000331int SyntaxTree::Impl::getNumberOfDescendants(NodeId Id) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000332 return getNode(Id).RightMostDescendant - Id + 1;
333}
334
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000335bool SyntaxTree::Impl::isInSubtree(NodeId Id, NodeId SubtreeRoot) const {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000336 return Id >= SubtreeRoot && Id <= getNode(SubtreeRoot).RightMostDescendant;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000337}
338
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000339int SyntaxTree::Impl::findPositionInParent(NodeId Id, bool Shifted) const {
340 NodeId Parent = getNode(Id).Parent;
341 if (Parent.isInvalid())
342 return 0;
343 const auto &Siblings = getNode(Parent).Children;
344 int Position = 0;
345 for (size_t I = 0, E = Siblings.size(); I < E; ++I) {
346 if (Shifted)
347 Position += getNode(Siblings[I]).Shift;
348 if (Siblings[I] == Id) {
349 Position += I;
350 return Position;
351 }
352 }
353 llvm_unreachable("Node not found in parent's children.");
Johannes Altmanninger69774d62017-08-18 21:26:34 +0000354}
355
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000356// Returns the qualified name of ND. If it is subordinate to Context,
357// then the prefix of the latter is removed from the returned value.
358std::string
359SyntaxTree::Impl::getRelativeName(const NamedDecl *ND,
360 const DeclContext *Context) const {
Johannes Altmanningerbc7d8172017-08-22 08:59:13 +0000361 std::string Val = ND->getQualifiedNameAsString();
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000362 std::string ContextPrefix;
Johannes Altmanningerbc7d8172017-08-22 08:59:13 +0000363 if (!Context)
364 return Val;
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000365 if (auto *Namespace = dyn_cast<NamespaceDecl>(Context))
366 ContextPrefix = Namespace->getQualifiedNameAsString();
367 else if (auto *Record = dyn_cast<RecordDecl>(Context))
368 ContextPrefix = Record->getQualifiedNameAsString();
369 else if (AST.getLangOpts().CPlusPlus11)
370 if (auto *Tag = dyn_cast<TagDecl>(Context))
371 ContextPrefix = Tag->getQualifiedNameAsString();
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000372 // Strip the qualifier, if Val refers to something in the current scope.
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000373 // But leave one leading ':' in place, so that we know that this is a
374 // relative path.
375 if (!ContextPrefix.empty() && StringRef(Val).startswith(ContextPrefix))
376 Val = Val.substr(ContextPrefix.size() + 1);
377 return Val;
378}
379
380std::string SyntaxTree::Impl::getRelativeName(const NamedDecl *ND) const {
381 return getRelativeName(ND, ND->getDeclContext());
382}
383
384static const DeclContext *getEnclosingDeclContext(ASTContext &AST,
385 const Stmt *S) {
386 while (S) {
387 const auto &Parents = AST.getParents(*S);
388 if (Parents.empty())
389 return nullptr;
390 const auto &P = Parents[0];
391 if (const auto *D = P.get<Decl>())
392 return D->getDeclContext();
393 S = P.get<Stmt>();
394 }
Johannes Altmanningerbc7d8172017-08-22 08:59:13 +0000395 return nullptr;
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000396}
397
Johannes Altmanninger41395022017-08-27 22:52:20 +0000398static std::string getInitializerValue(const CXXCtorInitializer *Init,
399 const PrintingPolicy &TypePP) {
400 if (Init->isAnyMemberInitializer())
Benjamin Krameradcd0262020-01-28 20:23:46 +0100401 return std::string(Init->getAnyMember()->getName());
Johannes Altmanninger41395022017-08-27 22:52:20 +0000402 if (Init->isBaseInitializer())
403 return QualType(Init->getBaseClass(), 0).getAsString(TypePP);
404 if (Init->isDelegatingInitializer())
405 return Init->getTypeSourceInfo()->getType().getAsString(TypePP);
406 llvm_unreachable("Unknown initializer type");
407}
408
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000409std::string SyntaxTree::Impl::getNodeValue(NodeId Id) const {
410 return getNodeValue(getNode(Id));
411}
412
413std::string SyntaxTree::Impl::getNodeValue(const Node &N) const {
414 const DynTypedNode &DTN = N.ASTNode;
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000415 if (auto *S = DTN.get<Stmt>())
416 return getStmtValue(S);
417 if (auto *D = DTN.get<Decl>())
418 return getDeclValue(D);
Johannes Altmanninger41395022017-08-27 22:52:20 +0000419 if (auto *Init = DTN.get<CXXCtorInitializer>())
420 return getInitializerValue(Init, TypePP);
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000421 llvm_unreachable("Fatal: unhandled AST node.\n");
422}
423
424std::string SyntaxTree::Impl::getDeclValue(const Decl *D) const {
425 std::string Value;
Johannes Altmanninger41395022017-08-27 22:52:20 +0000426 if (auto *V = dyn_cast<ValueDecl>(D))
427 return getRelativeName(V) + "(" + V->getType().getAsString(TypePP) + ")";
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000428 if (auto *N = dyn_cast<NamedDecl>(D))
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000429 Value += getRelativeName(N) + ";";
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000430 if (auto *T = dyn_cast<TypedefNameDecl>(D))
431 return Value + T->getUnderlyingType().getAsString(TypePP) + ";";
432 if (auto *T = dyn_cast<TypeDecl>(D))
433 if (T->getTypeForDecl())
434 Value +=
435 T->getTypeForDecl()->getCanonicalTypeInternal().getAsString(TypePP) +
436 ";";
437 if (auto *U = dyn_cast<UsingDirectiveDecl>(D))
Benjamin Krameradcd0262020-01-28 20:23:46 +0100438 return std::string(U->getNominatedNamespace()->getName());
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000439 if (auto *A = dyn_cast<AccessSpecDecl>(D)) {
440 CharSourceRange Range(A->getSourceRange(), false);
Benjamin Krameradcd0262020-01-28 20:23:46 +0100441 return std::string(
442 Lexer::getSourceText(Range, AST.getSourceManager(), AST.getLangOpts()));
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000443 }
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000444 return Value;
445}
446
447std::string SyntaxTree::Impl::getStmtValue(const Stmt *S) const {
448 if (auto *U = dyn_cast<UnaryOperator>(S))
Benjamin Krameradcd0262020-01-28 20:23:46 +0100449 return std::string(UnaryOperator::getOpcodeStr(U->getOpcode()));
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000450 if (auto *B = dyn_cast<BinaryOperator>(S))
Benjamin Krameradcd0262020-01-28 20:23:46 +0100451 return std::string(B->getOpcodeStr());
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000452 if (auto *M = dyn_cast<MemberExpr>(S))
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000453 return getRelativeName(M->getMemberDecl());
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000454 if (auto *I = dyn_cast<IntegerLiteral>(S)) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000455 SmallString<256> Str;
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000456 I->getValue().toString(Str, /*Radix=*/10, /*Signed=*/false);
Benjamin Krameradcd0262020-01-28 20:23:46 +0100457 return std::string(Str.str());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000458 }
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000459 if (auto *F = dyn_cast<FloatingLiteral>(S)) {
460 SmallString<256> Str;
461 F->getValue().toString(Str);
Benjamin Krameradcd0262020-01-28 20:23:46 +0100462 return std::string(Str.str());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000463 }
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000464 if (auto *D = dyn_cast<DeclRefExpr>(S))
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000465 return getRelativeName(D->getDecl(), getEnclosingDeclContext(AST, S));
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000466 if (auto *String = dyn_cast<StringLiteral>(S))
Benjamin Krameradcd0262020-01-28 20:23:46 +0100467 return std::string(String->getString());
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000468 if (auto *B = dyn_cast<CXXBoolLiteralExpr>(S))
469 return B->getValue() ? "true" : "false";
470 return "";
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000471}
472
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000473/// Identifies a node in a subtree by its postorder offset, starting at 1.
474struct SNodeId {
475 int Id = 0;
476
477 explicit SNodeId(int Id) : Id(Id) {}
478 explicit SNodeId() = default;
479
480 operator int() const { return Id; }
481 SNodeId &operator++() { return ++Id, *this; }
482 SNodeId &operator--() { return --Id, *this; }
483 SNodeId operator+(int Other) const { return SNodeId(Id + Other); }
484};
485
486class Subtree {
487private:
488 /// The parent tree.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000489 const SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000490 /// Maps SNodeIds to original ids.
491 std::vector<NodeId> RootIds;
492 /// Maps subtree nodes to their leftmost descendants wtihin the subtree.
493 std::vector<SNodeId> LeftMostDescendants;
494
495public:
496 std::vector<SNodeId> KeyRoots;
497
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000498 Subtree(const SyntaxTree::Impl &Tree, NodeId SubtreeRoot) : Tree(Tree) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000499 RootIds = getSubtreePostorder(Tree, SubtreeRoot);
500 int NumLeaves = setLeftMostDescendants();
501 computeKeyRoots(NumLeaves);
502 }
503 int getSize() const { return RootIds.size(); }
504 NodeId getIdInRoot(SNodeId Id) const {
505 assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
506 return RootIds[Id - 1];
507 }
508 const Node &getNode(SNodeId Id) const {
509 return Tree.getNode(getIdInRoot(Id));
510 }
511 SNodeId getLeftMostDescendant(SNodeId Id) const {
512 assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
513 return LeftMostDescendants[Id - 1];
514 }
515 /// Returns the postorder index of the leftmost descendant in the subtree.
516 NodeId getPostorderOffset() const {
517 return Tree.PostorderIds[getIdInRoot(SNodeId(1))];
518 }
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000519 std::string getNodeValue(SNodeId Id) const {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000520 return Tree.getNodeValue(getIdInRoot(Id));
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000521 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000522
523private:
524 /// Returns the number of leafs in the subtree.
525 int setLeftMostDescendants() {
526 int NumLeaves = 0;
527 LeftMostDescendants.resize(getSize());
528 for (int I = 0; I < getSize(); ++I) {
529 SNodeId SI(I + 1);
530 const Node &N = getNode(SI);
531 NumLeaves += N.isLeaf();
532 assert(I == Tree.PostorderIds[getIdInRoot(SI)] - getPostorderOffset() &&
533 "Postorder traversal in subtree should correspond to traversal in "
534 "the root tree by a constant offset.");
535 LeftMostDescendants[I] = SNodeId(Tree.PostorderIds[N.LeftMostDescendant] -
536 getPostorderOffset());
537 }
538 return NumLeaves;
539 }
540 void computeKeyRoots(int Leaves) {
541 KeyRoots.resize(Leaves);
542 std::unordered_set<int> Visited;
543 int K = Leaves - 1;
544 for (SNodeId I(getSize()); I > 0; --I) {
545 SNodeId LeftDesc = getLeftMostDescendant(I);
546 if (Visited.count(LeftDesc))
547 continue;
548 assert(K >= 0 && "K should be non-negative");
549 KeyRoots[K] = I;
550 Visited.insert(LeftDesc);
551 --K;
552 }
553 }
554};
555
556/// Implementation of Zhang and Shasha's Algorithm for tree edit distance.
557/// Computes an optimal mapping between two trees using only insertion,
558/// deletion and update as edit actions (similar to the Levenshtein distance).
559class ZhangShashaMatcher {
560 const ASTDiff::Impl &DiffImpl;
561 Subtree S1;
562 Subtree S2;
563 std::unique_ptr<std::unique_ptr<double[]>[]> TreeDist, ForestDist;
564
565public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000566 ZhangShashaMatcher(const ASTDiff::Impl &DiffImpl, const SyntaxTree::Impl &T1,
567 const SyntaxTree::Impl &T2, NodeId Id1, NodeId Id2)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000568 : DiffImpl(DiffImpl), S1(T1, Id1), S2(T2, Id2) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000569 TreeDist = std::make_unique<std::unique_ptr<double[]>[]>(
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000570 size_t(S1.getSize()) + 1);
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000571 ForestDist = std::make_unique<std::unique_ptr<double[]>[]>(
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000572 size_t(S1.getSize()) + 1);
573 for (int I = 0, E = S1.getSize() + 1; I < E; ++I) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000574 TreeDist[I] = std::make_unique<double[]>(size_t(S2.getSize()) + 1);
575 ForestDist[I] = std::make_unique<double[]>(size_t(S2.getSize()) + 1);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000576 }
577 }
578
579 std::vector<std::pair<NodeId, NodeId>> getMatchingNodes() {
580 std::vector<std::pair<NodeId, NodeId>> Matches;
581 std::vector<std::pair<SNodeId, SNodeId>> TreePairs;
582
583 computeTreeDist();
584
585 bool RootNodePair = true;
586
Alex Lorenz4c0a8662017-07-21 13:04:57 +0000587 TreePairs.emplace_back(SNodeId(S1.getSize()), SNodeId(S2.getSize()));
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000588
589 while (!TreePairs.empty()) {
590 SNodeId LastRow, LastCol, FirstRow, FirstCol, Row, Col;
591 std::tie(LastRow, LastCol) = TreePairs.back();
592 TreePairs.pop_back();
593
594 if (!RootNodePair) {
595 computeForestDist(LastRow, LastCol);
596 }
597
598 RootNodePair = false;
599
600 FirstRow = S1.getLeftMostDescendant(LastRow);
601 FirstCol = S2.getLeftMostDescendant(LastCol);
602
603 Row = LastRow;
604 Col = LastCol;
605
606 while (Row > FirstRow || Col > FirstCol) {
607 if (Row > FirstRow &&
608 ForestDist[Row - 1][Col] + 1 == ForestDist[Row][Col]) {
609 --Row;
610 } else if (Col > FirstCol &&
611 ForestDist[Row][Col - 1] + 1 == ForestDist[Row][Col]) {
612 --Col;
613 } else {
614 SNodeId LMD1 = S1.getLeftMostDescendant(Row);
615 SNodeId LMD2 = S2.getLeftMostDescendant(Col);
616 if (LMD1 == S1.getLeftMostDescendant(LastRow) &&
617 LMD2 == S2.getLeftMostDescendant(LastCol)) {
618 NodeId Id1 = S1.getIdInRoot(Row);
619 NodeId Id2 = S2.getIdInRoot(Col);
620 assert(DiffImpl.isMatchingPossible(Id1, Id2) &&
621 "These nodes must not be matched.");
622 Matches.emplace_back(Id1, Id2);
623 --Row;
624 --Col;
625 } else {
626 TreePairs.emplace_back(Row, Col);
627 Row = LMD1;
628 Col = LMD2;
629 }
630 }
631 }
632 }
633 return Matches;
634 }
635
636private:
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000637 /// We use a simple cost model for edit actions, which seems good enough.
638 /// Simple cost model for edit actions. This seems to make the matching
639 /// algorithm perform reasonably well.
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000640 /// The values range between 0 and 1, or infinity if this edit action should
641 /// always be avoided.
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000642 static constexpr double DeletionCost = 1;
643 static constexpr double InsertionCost = 1;
644
645 double getUpdateCost(SNodeId Id1, SNodeId Id2) {
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000646 if (!DiffImpl.isMatchingPossible(S1.getIdInRoot(Id1), S2.getIdInRoot(Id2)))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000647 return std::numeric_limits<double>::max();
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000648 return S1.getNodeValue(Id1) != S2.getNodeValue(Id2);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000649 }
650
651 void computeTreeDist() {
652 for (SNodeId Id1 : S1.KeyRoots)
653 for (SNodeId Id2 : S2.KeyRoots)
654 computeForestDist(Id1, Id2);
655 }
656
657 void computeForestDist(SNodeId Id1, SNodeId Id2) {
658 assert(Id1 > 0 && Id2 > 0 && "Expecting offsets greater than 0.");
659 SNodeId LMD1 = S1.getLeftMostDescendant(Id1);
660 SNodeId LMD2 = S2.getLeftMostDescendant(Id2);
661
662 ForestDist[LMD1][LMD2] = 0;
663 for (SNodeId D1 = LMD1 + 1; D1 <= Id1; ++D1) {
664 ForestDist[D1][LMD2] = ForestDist[D1 - 1][LMD2] + DeletionCost;
665 for (SNodeId D2 = LMD2 + 1; D2 <= Id2; ++D2) {
666 ForestDist[LMD1][D2] = ForestDist[LMD1][D2 - 1] + InsertionCost;
667 SNodeId DLMD1 = S1.getLeftMostDescendant(D1);
668 SNodeId DLMD2 = S2.getLeftMostDescendant(D2);
669 if (DLMD1 == LMD1 && DLMD2 == LMD2) {
670 double UpdateCost = getUpdateCost(D1, D2);
671 ForestDist[D1][D2] =
672 std::min({ForestDist[D1 - 1][D2] + DeletionCost,
673 ForestDist[D1][D2 - 1] + InsertionCost,
674 ForestDist[D1 - 1][D2 - 1] + UpdateCost});
675 TreeDist[D1][D2] = ForestDist[D1][D2];
676 } else {
677 ForestDist[D1][D2] =
678 std::min({ForestDist[D1 - 1][D2] + DeletionCost,
679 ForestDist[D1][D2 - 1] + InsertionCost,
680 ForestDist[DLMD1][DLMD2] + TreeDist[D1][D2]});
681 }
682 }
683 }
684 }
685};
686
Reid Klecknercd625112020-02-12 11:34:13 -0800687ASTNodeKind Node::getType() const { return ASTNode.getNodeKind(); }
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000688
689StringRef Node::getTypeLabel() const { return getType().asStringRef(); }
690
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000691llvm::Optional<std::string> Node::getQualifiedIdentifier() const {
692 if (auto *ND = ASTNode.get<NamedDecl>()) {
693 if (ND->getDeclName().isIdentifier())
694 return ND->getQualifiedNameAsString();
695 }
696 return llvm::None;
697}
698
699llvm::Optional<StringRef> Node::getIdentifier() const {
700 if (auto *ND = ASTNode.get<NamedDecl>()) {
701 if (ND->getDeclName().isIdentifier())
702 return ND->getName();
703 }
704 return llvm::None;
705}
706
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000707namespace {
708// Compares nodes by their depth.
709struct HeightLess {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000710 const SyntaxTree::Impl &Tree;
711 HeightLess(const SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000712 bool operator()(NodeId Id1, NodeId Id2) const {
713 return Tree.getNode(Id1).Height < Tree.getNode(Id2).Height;
714 }
715};
716} // end anonymous namespace
717
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000718namespace {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000719// Priority queue for nodes, sorted descendingly by their height.
720class PriorityList {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000721 const SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000722 HeightLess Cmp;
723 std::vector<NodeId> Container;
724 PriorityQueue<NodeId, std::vector<NodeId>, HeightLess> List;
725
726public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000727 PriorityList(const SyntaxTree::Impl &Tree)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000728 : Tree(Tree), Cmp(Tree), List(Cmp, Container) {}
729
730 void push(NodeId id) { List.push(id); }
731
732 std::vector<NodeId> pop() {
733 int Max = peekMax();
734 std::vector<NodeId> Result;
735 if (Max == 0)
736 return Result;
737 while (peekMax() == Max) {
738 Result.push_back(List.top());
739 List.pop();
740 }
741 // TODO this is here to get a stable output, not a good heuristic
Fangrui Song55fab262018-09-26 22:16:28 +0000742 llvm::sort(Result);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000743 return Result;
744 }
745 int peekMax() const {
746 if (List.empty())
747 return 0;
748 return Tree.getNode(List.top()).Height;
749 }
750 void open(NodeId Id) {
751 for (NodeId Child : Tree.getNode(Id).Children)
752 push(Child);
753 }
754};
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000755} // end anonymous namespace
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000756
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000757bool ASTDiff::Impl::identical(NodeId Id1, NodeId Id2) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000758 const Node &N1 = T1.getNode(Id1);
759 const Node &N2 = T2.getNode(Id2);
760 if (N1.Children.size() != N2.Children.size() ||
761 !isMatchingPossible(Id1, Id2) ||
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000762 T1.getNodeValue(Id1) != T2.getNodeValue(Id2))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000763 return false;
764 for (size_t Id = 0, E = N1.Children.size(); Id < E; ++Id)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000765 if (!identical(N1.Children[Id], N2.Children[Id]))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000766 return false;
767 return true;
768}
769
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000770bool ASTDiff::Impl::isMatchingPossible(NodeId Id1, NodeId Id2) const {
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000771 return Options.isMatchingAllowed(T1.getNode(Id1), T2.getNode(Id2));
772}
773
774bool ASTDiff::Impl::haveSameParents(const Mapping &M, NodeId Id1,
775 NodeId Id2) const {
776 NodeId P1 = T1.getNode(Id1).Parent;
777 NodeId P2 = T2.getNode(Id2).Parent;
778 return (P1.isInvalid() && P2.isInvalid()) ||
779 (P1.isValid() && P2.isValid() && M.getDst(P1) == P2);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000780}
781
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000782void ASTDiff::Impl::addOptimalMapping(Mapping &M, NodeId Id1,
783 NodeId Id2) const {
Johannes Altmanningerd1969302017-08-20 12:09:07 +0000784 if (std::max(T1.getNumberOfDescendants(Id1), T2.getNumberOfDescendants(Id2)) >
785 Options.MaxSize)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000786 return;
787 ZhangShashaMatcher Matcher(*this, T1, T2, Id1, Id2);
788 std::vector<std::pair<NodeId, NodeId>> R = Matcher.getMatchingNodes();
Mark de Wever8dc7b982020-01-01 17:23:21 +0100789 for (const auto &Tuple : R) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000790 NodeId Src = Tuple.first;
791 NodeId Dst = Tuple.second;
Johannes Altmanninger51321ae2017-08-19 17:53:01 +0000792 if (!M.hasSrc(Src) && !M.hasDst(Dst))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000793 M.link(Src, Dst);
794 }
795}
796
Johannes Altmanningerd1969302017-08-20 12:09:07 +0000797double ASTDiff::Impl::getJaccardSimilarity(const Mapping &M, NodeId Id1,
798 NodeId Id2) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000799 int CommonDescendants = 0;
800 const Node &N1 = T1.getNode(Id1);
Johannes Altmanningerd1969302017-08-20 12:09:07 +0000801 // Count the common descendants, excluding the subtree root.
802 for (NodeId Src = Id1 + 1; Src <= N1.RightMostDescendant; ++Src) {
803 NodeId Dst = M.getDst(Src);
804 CommonDescendants += int(Dst.isValid() && T2.isInSubtree(Dst, Id2));
805 }
806 // We need to subtract 1 to get the number of descendants excluding the root.
807 double Denominator = T1.getNumberOfDescendants(Id1) - 1 +
808 T2.getNumberOfDescendants(Id2) - 1 - CommonDescendants;
809 // CommonDescendants is less than the size of one subtree.
810 assert(Denominator >= 0 && "Expected non-negative denominator.");
811 if (Denominator == 0)
812 return 0;
813 return CommonDescendants / Denominator;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000814}
815
816NodeId ASTDiff::Impl::findCandidate(const Mapping &M, NodeId Id1) const {
817 NodeId Candidate;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000818 double HighestSimilarity = 0.0;
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000819 for (NodeId Id2 : T2) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000820 if (!isMatchingPossible(Id1, Id2))
821 continue;
822 if (M.hasDst(Id2))
823 continue;
Johannes Altmanningerd1969302017-08-20 12:09:07 +0000824 double Similarity = getJaccardSimilarity(M, Id1, Id2);
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000825 if (Similarity >= Options.MinSimilarity && Similarity > HighestSimilarity) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000826 HighestSimilarity = Similarity;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000827 Candidate = Id2;
828 }
829 }
830 return Candidate;
831}
832
833void ASTDiff::Impl::matchBottomUp(Mapping &M) const {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000834 std::vector<NodeId> Postorder = getSubtreePostorder(T1, T1.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000835 for (NodeId Id1 : Postorder) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000836 if (Id1 == T1.getRootId() && !M.hasSrc(T1.getRootId()) &&
837 !M.hasDst(T2.getRootId())) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000838 if (isMatchingPossible(T1.getRootId(), T2.getRootId())) {
839 M.link(T1.getRootId(), T2.getRootId());
840 addOptimalMapping(M, T1.getRootId(), T2.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000841 }
842 break;
843 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000844 bool Matched = M.hasSrc(Id1);
Johannes Altmanningerd1969302017-08-20 12:09:07 +0000845 const Node &N1 = T1.getNode(Id1);
Fangrui Song3117b172018-10-20 17:53:42 +0000846 bool MatchedChildren = llvm::any_of(
847 N1.Children, [&](NodeId Child) { return M.hasSrc(Child); });
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000848 if (Matched || !MatchedChildren)
849 continue;
850 NodeId Id2 = findCandidate(M, Id1);
Johannes Altmanninger51321ae2017-08-19 17:53:01 +0000851 if (Id2.isValid()) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000852 M.link(Id1, Id2);
853 addOptimalMapping(M, Id1, Id2);
854 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000855 }
856}
857
858Mapping ASTDiff::Impl::matchTopDown() const {
859 PriorityList L1(T1);
860 PriorityList L2(T2);
861
Johannes Altmanninger51321ae2017-08-19 17:53:01 +0000862 Mapping M(T1.getSize() + T2.getSize());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000863
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000864 L1.push(T1.getRootId());
865 L2.push(T2.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000866
867 int Max1, Max2;
868 while (std::min(Max1 = L1.peekMax(), Max2 = L2.peekMax()) >
869 Options.MinHeight) {
870 if (Max1 > Max2) {
871 for (NodeId Id : L1.pop())
872 L1.open(Id);
873 continue;
874 }
875 if (Max2 > Max1) {
876 for (NodeId Id : L2.pop())
877 L2.open(Id);
878 continue;
879 }
880 std::vector<NodeId> H1, H2;
881 H1 = L1.pop();
882 H2 = L2.pop();
883 for (NodeId Id1 : H1) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000884 for (NodeId Id2 : H2) {
Johannes Altmanninger51321ae2017-08-19 17:53:01 +0000885 if (identical(Id1, Id2) && !M.hasSrc(Id1) && !M.hasDst(Id2)) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000886 for (int I = 0, E = T1.getNumberOfDescendants(Id1); I < E; ++I)
887 M.link(Id1 + I, Id2 + I);
888 }
889 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000890 }
891 for (NodeId Id1 : H1) {
892 if (!M.hasSrc(Id1))
893 L1.open(Id1);
894 }
895 for (NodeId Id2 : H2) {
896 if (!M.hasDst(Id2))
897 L2.open(Id2);
898 }
899 }
900 return M;
901}
902
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000903ASTDiff::Impl::Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
904 const ComparisonOptions &Options)
905 : T1(T1), T2(T2), Options(Options) {
906 computeMapping();
907 computeChangeKinds(TheMapping);
908}
909
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000910void ASTDiff::Impl::computeMapping() {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000911 TheMapping = matchTopDown();
Johannes Altmanningerd1969302017-08-20 12:09:07 +0000912 if (Options.StopAfterTopDown)
913 return;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000914 matchBottomUp(TheMapping);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000915}
916
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000917void ASTDiff::Impl::computeChangeKinds(Mapping &M) {
918 for (NodeId Id1 : T1) {
919 if (!M.hasSrc(Id1)) {
920 T1.getMutableNode(Id1).Change = Delete;
921 T1.getMutableNode(Id1).Shift -= 1;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000922 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000923 }
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000924 for (NodeId Id2 : T2) {
925 if (!M.hasDst(Id2)) {
926 T2.getMutableNode(Id2).Change = Insert;
927 T2.getMutableNode(Id2).Shift -= 1;
928 }
929 }
930 for (NodeId Id1 : T1.NodesBfs) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000931 NodeId Id2 = M.getDst(Id1);
932 if (Id2.isInvalid())
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000933 continue;
934 if (!haveSameParents(M, Id1, Id2) ||
935 T1.findPositionInParent(Id1, true) !=
936 T2.findPositionInParent(Id2, true)) {
937 T1.getMutableNode(Id1).Shift -= 1;
938 T2.getMutableNode(Id2).Shift -= 1;
939 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000940 }
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000941 for (NodeId Id2 : T2.NodesBfs) {
942 NodeId Id1 = M.getSrc(Id2);
943 if (Id1.isInvalid())
944 continue;
945 Node &N1 = T1.getMutableNode(Id1);
946 Node &N2 = T2.getMutableNode(Id2);
947 if (Id1.isInvalid())
948 continue;
949 if (!haveSameParents(M, Id1, Id2) ||
950 T1.findPositionInParent(Id1, true) !=
951 T2.findPositionInParent(Id2, true)) {
952 N1.Change = N2.Change = Move;
953 }
954 if (T1.getNodeValue(Id1) != T2.getNodeValue(Id2)) {
955 N1.Change = N2.Change = (N1.Change == Move ? UpdateMove : Update);
956 }
957 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000958}
959
960ASTDiff::ASTDiff(SyntaxTree &T1, SyntaxTree &T2,
961 const ComparisonOptions &Options)
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000962 : DiffImpl(std::make_unique<Impl>(*T1.TreeImpl, *T2.TreeImpl, Options)) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000963
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000964ASTDiff::~ASTDiff() = default;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000965
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000966NodeId ASTDiff::getMapped(const SyntaxTree &SourceTree, NodeId Id) const {
967 return DiffImpl->getMapped(SourceTree.TreeImpl, Id);
968}
969
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000970SyntaxTree::SyntaxTree(ASTContext &AST)
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000971 : TreeImpl(std::make_unique<SyntaxTree::Impl>(
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000972 this, AST.getTranslationUnitDecl(), AST)) {}
973
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000974SyntaxTree::~SyntaxTree() = default;
975
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000976const ASTContext &SyntaxTree::getASTContext() const { return TreeImpl->AST; }
977
978const Node &SyntaxTree::getNode(NodeId Id) const {
979 return TreeImpl->getNode(Id);
980}
981
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000982int SyntaxTree::getSize() const { return TreeImpl->getSize(); }
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000983NodeId SyntaxTree::getRootId() const { return TreeImpl->getRootId(); }
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000984SyntaxTree::PreorderIterator SyntaxTree::begin() const {
985 return TreeImpl->begin();
986}
987SyntaxTree::PreorderIterator SyntaxTree::end() const { return TreeImpl->end(); }
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000988
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000989int SyntaxTree::findPositionInParent(NodeId Id) const {
990 return TreeImpl->findPositionInParent(Id);
991}
992
993std::pair<unsigned, unsigned>
994SyntaxTree::getSourceRangeOffsets(const Node &N) const {
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000995 const SourceManager &SrcMgr = TreeImpl->AST.getSourceManager();
996 SourceRange Range = N.ASTNode.getSourceRange();
997 SourceLocation BeginLoc = Range.getBegin();
998 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
999 Range.getEnd(), /*Offset=*/0, SrcMgr, TreeImpl->AST.getLangOpts());
1000 if (auto *ThisExpr = N.ASTNode.get<CXXThisExpr>()) {
1001 if (ThisExpr->isImplicit())
1002 EndLoc = BeginLoc;
1003 }
1004 unsigned Begin = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(BeginLoc));
1005 unsigned End = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(EndLoc));
1006 return {Begin, End};
1007}
Alex Lorenza75b2ca2017-07-21 12:49:28 +00001008
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +00001009std::string SyntaxTree::getNodeValue(NodeId Id) const {
1010 return TreeImpl->getNodeValue(Id);
1011}
1012
1013std::string SyntaxTree::getNodeValue(const Node &N) const {
1014 return TreeImpl->getNodeValue(N);
Alex Lorenza75b2ca2017-07-21 12:49:28 +00001015}
1016
1017} // end namespace diff
1018} // end namespace clang