blob: 56832a30b7b215366330fb743bc92ef6fa949f53 [file] [log] [blame]
Alex Lorenza75b2ca2017-07-21 12:49:28 +00001//===- ASTDiff.cpp - AST differencing implementation-----------*- C++ -*- -===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains definitons for the AST differencing interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Tooling/ASTDiff/ASTDiff.h"
15
16#include "clang/AST/RecursiveASTVisitor.h"
17#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) {
39 SrcToDst = llvm::make_unique<NodeId[]>(Size);
40 DstToSrc = llvm::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 Altmanninger8b0e0662017-08-01 20:17:40 +0000114 /// Constructs a tree from an AST node.
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000115 Impl(SyntaxTree *Parent, Decl *N, ASTContext &AST);
116 Impl(SyntaxTree *Parent, Stmt *N, ASTContext &AST);
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000117 template <class T>
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000118 Impl(SyntaxTree *Parent,
119 typename std::enable_if<std::is_base_of<Stmt, T>::value, T>::type *Node,
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000120 ASTContext &AST)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000121 : Impl(Parent, dyn_cast<Stmt>(Node), AST) {}
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000122 template <class T>
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000123 Impl(SyntaxTree *Parent,
124 typename std::enable_if<std::is_base_of<Decl, T>::value, T>::type *Node,
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000125 ASTContext &AST)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000126 : Impl(Parent, dyn_cast<Decl>(Node), AST) {}
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000127
128 SyntaxTree *Parent;
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000129 ASTContext &AST;
Johannes Altmanningerbc3e9932017-08-25 09:49:49 +0000130 /// Nodes in preorder.
131 std::vector<Node> Nodes;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000132 std::vector<NodeId> Leaves;
133 // Maps preorder indices to postorder ones.
134 std::vector<int> PostorderIds;
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000135 std::vector<NodeId> NodesBfs;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000136
137 int getSize() const { return Nodes.size(); }
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000138 NodeId getRootId() const { return 0; }
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000139 PreorderIterator begin() const { return getRootId(); }
140 PreorderIterator end() const { return getSize(); }
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000141
142 const Node &getNode(NodeId Id) const { return Nodes[Id]; }
143 Node &getMutableNode(NodeId Id) { return Nodes[Id]; }
144 bool isValidNodeId(NodeId Id) const { return Id >= 0 && Id < getSize(); }
145 void addNode(Node &N) { Nodes.push_back(N); }
146 int getNumberOfDescendants(NodeId Id) const;
147 bool isInSubtree(NodeId Id, NodeId SubtreeRoot) const;
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000148 int findPositionInParent(NodeId Id, bool Shifted = false) const;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000149
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000150 std::string getRelativeName(const NamedDecl *ND,
151 const DeclContext *Context) const;
152 std::string getRelativeName(const NamedDecl *ND) const;
153
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000154 std::string getNodeValue(NodeId Id) const;
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000155 std::string getNodeValue(const Node &Node) const;
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000156 std::string getDeclValue(const Decl *D) const;
157 std::string getStmtValue(const Stmt *S) const;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000158
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000159private:
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000160 void initTree();
161 void setLeftMostDescendants();
162};
163
Johannes Altmanningerd5b56a82017-08-20 10:22:32 +0000164static bool isSpecializedNodeExcluded(const Decl *D) { return D->isImplicit(); }
165static bool isSpecializedNodeExcluded(const Stmt *S) { return false; }
166
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000167template <class T>
168static bool isNodeExcluded(const SourceManager &SrcMgr, T *N) {
169 if (!N)
170 return true;
171 SourceLocation SLoc = N->getLocStart();
Johannes Altmanningerd5b56a82017-08-20 10:22:32 +0000172 if (SLoc.isValid()) {
173 // Ignore everything from other files.
174 if (!SrcMgr.isInMainFile(SLoc))
175 return true;
176 // Ignore macros.
177 if (SLoc != SrcMgr.getSpellingLoc(SLoc))
178 return true;
179 }
180 return isSpecializedNodeExcluded(N);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000181}
182
183namespace {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000184// Sets Height, Parent and Children for each node.
185struct PreorderVisitor : public RecursiveASTVisitor<PreorderVisitor> {
186 int Id = 0, Depth = 0;
187 NodeId Parent;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000188 SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000189
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000190 PreorderVisitor(SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000191
192 template <class T> std::tuple<NodeId, NodeId> PreTraverse(T *ASTNode) {
193 NodeId MyId = Id;
Johannes Altmanningerbc3e9932017-08-25 09:49:49 +0000194 Tree.Nodes.emplace_back();
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000195 Node &N = Tree.getMutableNode(MyId);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000196 N.Parent = Parent;
197 N.Depth = Depth;
198 N.ASTNode = DynTypedNode::create(*ASTNode);
199 assert(!N.ASTNode.getNodeKind().isNone() &&
200 "Expected nodes to have a valid kind.");
201 if (Parent.isValid()) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000202 Node &P = Tree.getMutableNode(Parent);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000203 P.Children.push_back(MyId);
204 }
205 Parent = MyId;
206 ++Id;
207 ++Depth;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000208 return std::make_tuple(MyId, Tree.getNode(MyId).Parent);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000209 }
210 void PostTraverse(std::tuple<NodeId, NodeId> State) {
211 NodeId MyId, PreviousParent;
212 std::tie(MyId, PreviousParent) = State;
213 assert(MyId.isValid() && "Expecting to only traverse valid nodes.");
214 Parent = PreviousParent;
215 --Depth;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000216 Node &N = Tree.getMutableNode(MyId);
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000217 N.RightMostDescendant = Id - 1;
218 assert(N.RightMostDescendant >= 0 &&
219 N.RightMostDescendant < Tree.getSize() &&
220 "Rightmost descendant must be a valid tree node.");
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000221 if (N.isLeaf())
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000222 Tree.Leaves.push_back(MyId);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000223 N.Height = 1;
224 for (NodeId Child : N.Children)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000225 N.Height = std::max(N.Height, 1 + Tree.getNode(Child).Height);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000226 }
227 bool TraverseDecl(Decl *D) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000228 if (isNodeExcluded(Tree.AST.getSourceManager(), D))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000229 return true;
230 auto SavedState = PreTraverse(D);
231 RecursiveASTVisitor<PreorderVisitor>::TraverseDecl(D);
232 PostTraverse(SavedState);
233 return true;
234 }
235 bool TraverseStmt(Stmt *S) {
Johannes Altmanningerd5b56a82017-08-20 10:22:32 +0000236 if (S)
237 S = S->IgnoreImplicit();
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000238 if (isNodeExcluded(Tree.AST.getSourceManager(), S))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000239 return true;
240 auto SavedState = PreTraverse(S);
241 RecursiveASTVisitor<PreorderVisitor>::TraverseStmt(S);
242 PostTraverse(SavedState);
243 return true;
244 }
245 bool TraverseType(QualType T) { return true; }
246};
247} // end anonymous namespace
248
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000249SyntaxTree::Impl::Impl(SyntaxTree *Parent, Decl *N, ASTContext &AST)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000250 : Parent(Parent), AST(AST) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000251 PreorderVisitor PreorderWalker(*this);
252 PreorderWalker.TraverseDecl(N);
253 initTree();
254}
255
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000256SyntaxTree::Impl::Impl(SyntaxTree *Parent, Stmt *N, ASTContext &AST)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000257 : Parent(Parent), AST(AST) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000258 PreorderVisitor PreorderWalker(*this);
259 PreorderWalker.TraverseStmt(N);
260 initTree();
261}
262
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000263static std::vector<NodeId> getSubtreePostorder(const SyntaxTree::Impl &Tree,
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000264 NodeId Root) {
265 std::vector<NodeId> Postorder;
266 std::function<void(NodeId)> Traverse = [&](NodeId Id) {
267 const Node &N = Tree.getNode(Id);
268 for (NodeId Child : N.Children)
269 Traverse(Child);
270 Postorder.push_back(Id);
271 };
272 Traverse(Root);
273 return Postorder;
274}
275
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000276static std::vector<NodeId> getSubtreeBfs(const SyntaxTree::Impl &Tree,
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000277 NodeId Root) {
278 std::vector<NodeId> Ids;
279 size_t Expanded = 0;
280 Ids.push_back(Root);
281 while (Expanded < Ids.size())
282 for (NodeId Child : Tree.getNode(Ids[Expanded++]).Children)
283 Ids.push_back(Child);
284 return Ids;
285}
286
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000287void SyntaxTree::Impl::initTree() {
288 setLeftMostDescendants();
289 int PostorderId = 0;
290 PostorderIds.resize(getSize());
291 std::function<void(NodeId)> PostorderTraverse = [&](NodeId Id) {
292 for (NodeId Child : getNode(Id).Children)
293 PostorderTraverse(Child);
294 PostorderIds[Id] = PostorderId;
295 ++PostorderId;
296 };
297 PostorderTraverse(getRootId());
298 NodesBfs = getSubtreeBfs(*this, getRootId());
299}
300
301void SyntaxTree::Impl::setLeftMostDescendants() {
302 for (NodeId Leaf : Leaves) {
303 getMutableNode(Leaf).LeftMostDescendant = Leaf;
304 NodeId Parent, Cur = Leaf;
305 while ((Parent = getNode(Cur).Parent).isValid() &&
306 getNode(Parent).Children[0] == Cur) {
307 Cur = Parent;
308 getMutableNode(Cur).LeftMostDescendant = Leaf;
309 }
310 }
311}
312
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000313int SyntaxTree::Impl::getNumberOfDescendants(NodeId Id) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000314 return getNode(Id).RightMostDescendant - Id + 1;
315}
316
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000317bool SyntaxTree::Impl::isInSubtree(NodeId Id, NodeId SubtreeRoot) const {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000318 return Id >= SubtreeRoot && Id <= getNode(SubtreeRoot).RightMostDescendant;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000319}
320
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000321int SyntaxTree::Impl::findPositionInParent(NodeId Id, bool Shifted) const {
322 NodeId Parent = getNode(Id).Parent;
323 if (Parent.isInvalid())
324 return 0;
325 const auto &Siblings = getNode(Parent).Children;
326 int Position = 0;
327 for (size_t I = 0, E = Siblings.size(); I < E; ++I) {
328 if (Shifted)
329 Position += getNode(Siblings[I]).Shift;
330 if (Siblings[I] == Id) {
331 Position += I;
332 return Position;
333 }
334 }
335 llvm_unreachable("Node not found in parent's children.");
Johannes Altmanninger69774d62017-08-18 21:26:34 +0000336}
337
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000338// Returns the qualified name of ND. If it is subordinate to Context,
339// then the prefix of the latter is removed from the returned value.
340std::string
341SyntaxTree::Impl::getRelativeName(const NamedDecl *ND,
342 const DeclContext *Context) const {
Johannes Altmanningerbc7d8172017-08-22 08:59:13 +0000343 std::string Val = ND->getQualifiedNameAsString();
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000344 std::string ContextPrefix;
Johannes Altmanningerbc7d8172017-08-22 08:59:13 +0000345 if (!Context)
346 return Val;
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000347 if (auto *Namespace = dyn_cast<NamespaceDecl>(Context))
348 ContextPrefix = Namespace->getQualifiedNameAsString();
349 else if (auto *Record = dyn_cast<RecordDecl>(Context))
350 ContextPrefix = Record->getQualifiedNameAsString();
351 else if (AST.getLangOpts().CPlusPlus11)
352 if (auto *Tag = dyn_cast<TagDecl>(Context))
353 ContextPrefix = Tag->getQualifiedNameAsString();
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000354 // Strip the qualifier, if Val refers to somthing in the current scope.
355 // But leave one leading ':' in place, so that we know that this is a
356 // relative path.
357 if (!ContextPrefix.empty() && StringRef(Val).startswith(ContextPrefix))
358 Val = Val.substr(ContextPrefix.size() + 1);
359 return Val;
360}
361
362std::string SyntaxTree::Impl::getRelativeName(const NamedDecl *ND) const {
363 return getRelativeName(ND, ND->getDeclContext());
364}
365
366static const DeclContext *getEnclosingDeclContext(ASTContext &AST,
367 const Stmt *S) {
368 while (S) {
369 const auto &Parents = AST.getParents(*S);
370 if (Parents.empty())
371 return nullptr;
372 const auto &P = Parents[0];
373 if (const auto *D = P.get<Decl>())
374 return D->getDeclContext();
375 S = P.get<Stmt>();
376 }
Johannes Altmanningerbc7d8172017-08-22 08:59:13 +0000377 return nullptr;
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000378}
379
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000380std::string SyntaxTree::Impl::getNodeValue(NodeId Id) const {
381 return getNodeValue(getNode(Id));
382}
383
384std::string SyntaxTree::Impl::getNodeValue(const Node &N) const {
385 const DynTypedNode &DTN = N.ASTNode;
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000386 if (auto *S = DTN.get<Stmt>())
387 return getStmtValue(S);
388 if (auto *D = DTN.get<Decl>())
389 return getDeclValue(D);
390 llvm_unreachable("Fatal: unhandled AST node.\n");
391}
392
393std::string SyntaxTree::Impl::getDeclValue(const Decl *D) const {
394 std::string Value;
395 PrintingPolicy TypePP(AST.getLangOpts());
396 TypePP.AnonymousTagLocations = false;
397
398 if (auto *V = dyn_cast<ValueDecl>(D)) {
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000399 Value += getRelativeName(V) + "(" + V->getType().getAsString(TypePP) + ")";
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000400 if (auto *C = dyn_cast<CXXConstructorDecl>(D)) {
401 for (auto *Init : C->inits()) {
402 if (!Init->isWritten())
403 continue;
404 if (Init->isBaseInitializer()) {
405 Value += Init->getBaseClass()->getCanonicalTypeInternal().getAsString(
406 TypePP);
407 } else if (Init->isDelegatingInitializer()) {
408 Value += C->getNameAsString();
409 } else {
410 assert(Init->isAnyMemberInitializer());
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000411 Value += getRelativeName(Init->getMember());
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000412 }
413 Value += ",";
414 }
415 }
416 return Value;
417 }
418 if (auto *N = dyn_cast<NamedDecl>(D))
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000419 Value += getRelativeName(N) + ";";
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000420 if (auto *T = dyn_cast<TypedefNameDecl>(D))
421 return Value + T->getUnderlyingType().getAsString(TypePP) + ";";
422 if (auto *T = dyn_cast<TypeDecl>(D))
423 if (T->getTypeForDecl())
424 Value +=
425 T->getTypeForDecl()->getCanonicalTypeInternal().getAsString(TypePP) +
426 ";";
427 if (auto *U = dyn_cast<UsingDirectiveDecl>(D))
428 return U->getNominatedNamespace()->getName();
429 if (auto *A = dyn_cast<AccessSpecDecl>(D)) {
430 CharSourceRange Range(A->getSourceRange(), false);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000431 return Lexer::getSourceText(Range, AST.getSourceManager(),
432 AST.getLangOpts());
433 }
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000434 return Value;
435}
436
437std::string SyntaxTree::Impl::getStmtValue(const Stmt *S) const {
438 if (auto *U = dyn_cast<UnaryOperator>(S))
439 return UnaryOperator::getOpcodeStr(U->getOpcode());
440 if (auto *B = dyn_cast<BinaryOperator>(S))
441 return B->getOpcodeStr();
442 if (auto *M = dyn_cast<MemberExpr>(S))
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000443 return getRelativeName(M->getMemberDecl());
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000444 if (auto *I = dyn_cast<IntegerLiteral>(S)) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000445 SmallString<256> Str;
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000446 I->getValue().toString(Str, /*Radix=*/10, /*Signed=*/false);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000447 return Str.str();
448 }
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000449 if (auto *F = dyn_cast<FloatingLiteral>(S)) {
450 SmallString<256> Str;
451 F->getValue().toString(Str);
452 return Str.str();
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000453 }
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000454 if (auto *D = dyn_cast<DeclRefExpr>(S))
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000455 return getRelativeName(D->getDecl(), getEnclosingDeclContext(AST, S));
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000456 if (auto *String = dyn_cast<StringLiteral>(S))
457 return String->getString();
458 if (auto *B = dyn_cast<CXXBoolLiteralExpr>(S))
459 return B->getValue() ? "true" : "false";
460 return "";
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000461}
462
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000463/// Identifies a node in a subtree by its postorder offset, starting at 1.
464struct SNodeId {
465 int Id = 0;
466
467 explicit SNodeId(int Id) : Id(Id) {}
468 explicit SNodeId() = default;
469
470 operator int() const { return Id; }
471 SNodeId &operator++() { return ++Id, *this; }
472 SNodeId &operator--() { return --Id, *this; }
473 SNodeId operator+(int Other) const { return SNodeId(Id + Other); }
474};
475
476class Subtree {
477private:
478 /// The parent tree.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000479 const SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000480 /// Maps SNodeIds to original ids.
481 std::vector<NodeId> RootIds;
482 /// Maps subtree nodes to their leftmost descendants wtihin the subtree.
483 std::vector<SNodeId> LeftMostDescendants;
484
485public:
486 std::vector<SNodeId> KeyRoots;
487
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000488 Subtree(const SyntaxTree::Impl &Tree, NodeId SubtreeRoot) : Tree(Tree) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000489 RootIds = getSubtreePostorder(Tree, SubtreeRoot);
490 int NumLeaves = setLeftMostDescendants();
491 computeKeyRoots(NumLeaves);
492 }
493 int getSize() const { return RootIds.size(); }
494 NodeId getIdInRoot(SNodeId Id) const {
495 assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
496 return RootIds[Id - 1];
497 }
498 const Node &getNode(SNodeId Id) const {
499 return Tree.getNode(getIdInRoot(Id));
500 }
501 SNodeId getLeftMostDescendant(SNodeId Id) const {
502 assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
503 return LeftMostDescendants[Id - 1];
504 }
505 /// Returns the postorder index of the leftmost descendant in the subtree.
506 NodeId getPostorderOffset() const {
507 return Tree.PostorderIds[getIdInRoot(SNodeId(1))];
508 }
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000509 std::string getNodeValue(SNodeId Id) const {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000510 return Tree.getNodeValue(getIdInRoot(Id));
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000511 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000512
513private:
514 /// Returns the number of leafs in the subtree.
515 int setLeftMostDescendants() {
516 int NumLeaves = 0;
517 LeftMostDescendants.resize(getSize());
518 for (int I = 0; I < getSize(); ++I) {
519 SNodeId SI(I + 1);
520 const Node &N = getNode(SI);
521 NumLeaves += N.isLeaf();
522 assert(I == Tree.PostorderIds[getIdInRoot(SI)] - getPostorderOffset() &&
523 "Postorder traversal in subtree should correspond to traversal in "
524 "the root tree by a constant offset.");
525 LeftMostDescendants[I] = SNodeId(Tree.PostorderIds[N.LeftMostDescendant] -
526 getPostorderOffset());
527 }
528 return NumLeaves;
529 }
530 void computeKeyRoots(int Leaves) {
531 KeyRoots.resize(Leaves);
532 std::unordered_set<int> Visited;
533 int K = Leaves - 1;
534 for (SNodeId I(getSize()); I > 0; --I) {
535 SNodeId LeftDesc = getLeftMostDescendant(I);
536 if (Visited.count(LeftDesc))
537 continue;
538 assert(K >= 0 && "K should be non-negative");
539 KeyRoots[K] = I;
540 Visited.insert(LeftDesc);
541 --K;
542 }
543 }
544};
545
546/// Implementation of Zhang and Shasha's Algorithm for tree edit distance.
547/// Computes an optimal mapping between two trees using only insertion,
548/// deletion and update as edit actions (similar to the Levenshtein distance).
549class ZhangShashaMatcher {
550 const ASTDiff::Impl &DiffImpl;
551 Subtree S1;
552 Subtree S2;
553 std::unique_ptr<std::unique_ptr<double[]>[]> TreeDist, ForestDist;
554
555public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000556 ZhangShashaMatcher(const ASTDiff::Impl &DiffImpl, const SyntaxTree::Impl &T1,
557 const SyntaxTree::Impl &T2, NodeId Id1, NodeId Id2)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000558 : DiffImpl(DiffImpl), S1(T1, Id1), S2(T2, Id2) {
559 TreeDist = llvm::make_unique<std::unique_ptr<double[]>[]>(
560 size_t(S1.getSize()) + 1);
561 ForestDist = llvm::make_unique<std::unique_ptr<double[]>[]>(
562 size_t(S1.getSize()) + 1);
563 for (int I = 0, E = S1.getSize() + 1; I < E; ++I) {
564 TreeDist[I] = llvm::make_unique<double[]>(size_t(S2.getSize()) + 1);
565 ForestDist[I] = llvm::make_unique<double[]>(size_t(S2.getSize()) + 1);
566 }
567 }
568
569 std::vector<std::pair<NodeId, NodeId>> getMatchingNodes() {
570 std::vector<std::pair<NodeId, NodeId>> Matches;
571 std::vector<std::pair<SNodeId, SNodeId>> TreePairs;
572
573 computeTreeDist();
574
575 bool RootNodePair = true;
576
Alex Lorenz4c0a8662017-07-21 13:04:57 +0000577 TreePairs.emplace_back(SNodeId(S1.getSize()), SNodeId(S2.getSize()));
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000578
579 while (!TreePairs.empty()) {
580 SNodeId LastRow, LastCol, FirstRow, FirstCol, Row, Col;
581 std::tie(LastRow, LastCol) = TreePairs.back();
582 TreePairs.pop_back();
583
584 if (!RootNodePair) {
585 computeForestDist(LastRow, LastCol);
586 }
587
588 RootNodePair = false;
589
590 FirstRow = S1.getLeftMostDescendant(LastRow);
591 FirstCol = S2.getLeftMostDescendant(LastCol);
592
593 Row = LastRow;
594 Col = LastCol;
595
596 while (Row > FirstRow || Col > FirstCol) {
597 if (Row > FirstRow &&
598 ForestDist[Row - 1][Col] + 1 == ForestDist[Row][Col]) {
599 --Row;
600 } else if (Col > FirstCol &&
601 ForestDist[Row][Col - 1] + 1 == ForestDist[Row][Col]) {
602 --Col;
603 } else {
604 SNodeId LMD1 = S1.getLeftMostDescendant(Row);
605 SNodeId LMD2 = S2.getLeftMostDescendant(Col);
606 if (LMD1 == S1.getLeftMostDescendant(LastRow) &&
607 LMD2 == S2.getLeftMostDescendant(LastCol)) {
608 NodeId Id1 = S1.getIdInRoot(Row);
609 NodeId Id2 = S2.getIdInRoot(Col);
610 assert(DiffImpl.isMatchingPossible(Id1, Id2) &&
611 "These nodes must not be matched.");
612 Matches.emplace_back(Id1, Id2);
613 --Row;
614 --Col;
615 } else {
616 TreePairs.emplace_back(Row, Col);
617 Row = LMD1;
618 Col = LMD2;
619 }
620 }
621 }
622 }
623 return Matches;
624 }
625
626private:
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000627 /// We use a simple cost model for edit actions, which seems good enough.
628 /// Simple cost model for edit actions. This seems to make the matching
629 /// algorithm perform reasonably well.
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000630 /// The values range between 0 and 1, or infinity if this edit action should
631 /// always be avoided.
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000632 static constexpr double DeletionCost = 1;
633 static constexpr double InsertionCost = 1;
634
635 double getUpdateCost(SNodeId Id1, SNodeId Id2) {
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000636 if (!DiffImpl.isMatchingPossible(S1.getIdInRoot(Id1), S2.getIdInRoot(Id2)))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000637 return std::numeric_limits<double>::max();
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000638 return S1.getNodeValue(Id1) != S2.getNodeValue(Id2);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000639 }
640
641 void computeTreeDist() {
642 for (SNodeId Id1 : S1.KeyRoots)
643 for (SNodeId Id2 : S2.KeyRoots)
644 computeForestDist(Id1, Id2);
645 }
646
647 void computeForestDist(SNodeId Id1, SNodeId Id2) {
648 assert(Id1 > 0 && Id2 > 0 && "Expecting offsets greater than 0.");
649 SNodeId LMD1 = S1.getLeftMostDescendant(Id1);
650 SNodeId LMD2 = S2.getLeftMostDescendant(Id2);
651
652 ForestDist[LMD1][LMD2] = 0;
653 for (SNodeId D1 = LMD1 + 1; D1 <= Id1; ++D1) {
654 ForestDist[D1][LMD2] = ForestDist[D1 - 1][LMD2] + DeletionCost;
655 for (SNodeId D2 = LMD2 + 1; D2 <= Id2; ++D2) {
656 ForestDist[LMD1][D2] = ForestDist[LMD1][D2 - 1] + InsertionCost;
657 SNodeId DLMD1 = S1.getLeftMostDescendant(D1);
658 SNodeId DLMD2 = S2.getLeftMostDescendant(D2);
659 if (DLMD1 == LMD1 && DLMD2 == LMD2) {
660 double UpdateCost = getUpdateCost(D1, D2);
661 ForestDist[D1][D2] =
662 std::min({ForestDist[D1 - 1][D2] + DeletionCost,
663 ForestDist[D1][D2 - 1] + InsertionCost,
664 ForestDist[D1 - 1][D2 - 1] + UpdateCost});
665 TreeDist[D1][D2] = ForestDist[D1][D2];
666 } else {
667 ForestDist[D1][D2] =
668 std::min({ForestDist[D1 - 1][D2] + DeletionCost,
669 ForestDist[D1][D2 - 1] + InsertionCost,
670 ForestDist[DLMD1][DLMD2] + TreeDist[D1][D2]});
671 }
672 }
673 }
674 }
675};
676
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000677ast_type_traits::ASTNodeKind Node::getType() const {
678 return ASTNode.getNodeKind();
679}
680
681StringRef Node::getTypeLabel() const { return getType().asStringRef(); }
682
Johannes Altmanninger0dd86dc2017-08-20 16:18:43 +0000683llvm::Optional<std::string> Node::getQualifiedIdentifier() const {
684 if (auto *ND = ASTNode.get<NamedDecl>()) {
685 if (ND->getDeclName().isIdentifier())
686 return ND->getQualifiedNameAsString();
687 }
688 return llvm::None;
689}
690
691llvm::Optional<StringRef> Node::getIdentifier() const {
692 if (auto *ND = ASTNode.get<NamedDecl>()) {
693 if (ND->getDeclName().isIdentifier())
694 return ND->getName();
695 }
696 return llvm::None;
697}
698
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000699namespace {
700// Compares nodes by their depth.
701struct HeightLess {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000702 const SyntaxTree::Impl &Tree;
703 HeightLess(const SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000704 bool operator()(NodeId Id1, NodeId Id2) const {
705 return Tree.getNode(Id1).Height < Tree.getNode(Id2).Height;
706 }
707};
708} // end anonymous namespace
709
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000710namespace {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000711// Priority queue for nodes, sorted descendingly by their height.
712class PriorityList {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000713 const SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000714 HeightLess Cmp;
715 std::vector<NodeId> Container;
716 PriorityQueue<NodeId, std::vector<NodeId>, HeightLess> List;
717
718public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000719 PriorityList(const SyntaxTree::Impl &Tree)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000720 : Tree(Tree), Cmp(Tree), List(Cmp, Container) {}
721
722 void push(NodeId id) { List.push(id); }
723
724 std::vector<NodeId> pop() {
725 int Max = peekMax();
726 std::vector<NodeId> Result;
727 if (Max == 0)
728 return Result;
729 while (peekMax() == Max) {
730 Result.push_back(List.top());
731 List.pop();
732 }
733 // TODO this is here to get a stable output, not a good heuristic
734 std::sort(Result.begin(), Result.end());
735 return Result;
736 }
737 int peekMax() const {
738 if (List.empty())
739 return 0;
740 return Tree.getNode(List.top()).Height;
741 }
742 void open(NodeId Id) {
743 for (NodeId Child : Tree.getNode(Id).Children)
744 push(Child);
745 }
746};
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000747} // end anonymous namespace
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000748
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000749bool ASTDiff::Impl::identical(NodeId Id1, NodeId Id2) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000750 const Node &N1 = T1.getNode(Id1);
751 const Node &N2 = T2.getNode(Id2);
752 if (N1.Children.size() != N2.Children.size() ||
753 !isMatchingPossible(Id1, Id2) ||
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000754 T1.getNodeValue(Id1) != T2.getNodeValue(Id2))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000755 return false;
756 for (size_t Id = 0, E = N1.Children.size(); Id < E; ++Id)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000757 if (!identical(N1.Children[Id], N2.Children[Id]))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000758 return false;
759 return true;
760}
761
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000762bool ASTDiff::Impl::isMatchingPossible(NodeId Id1, NodeId Id2) const {
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000763 return Options.isMatchingAllowed(T1.getNode(Id1), T2.getNode(Id2));
764}
765
766bool ASTDiff::Impl::haveSameParents(const Mapping &M, NodeId Id1,
767 NodeId Id2) const {
768 NodeId P1 = T1.getNode(Id1).Parent;
769 NodeId P2 = T2.getNode(Id2).Parent;
770 return (P1.isInvalid() && P2.isInvalid()) ||
771 (P1.isValid() && P2.isValid() && M.getDst(P1) == P2);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000772}
773
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000774void ASTDiff::Impl::addOptimalMapping(Mapping &M, NodeId Id1,
775 NodeId Id2) const {
Johannes Altmanningerd1969302017-08-20 12:09:07 +0000776 if (std::max(T1.getNumberOfDescendants(Id1), T2.getNumberOfDescendants(Id2)) >
777 Options.MaxSize)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000778 return;
779 ZhangShashaMatcher Matcher(*this, T1, T2, Id1, Id2);
780 std::vector<std::pair<NodeId, NodeId>> R = Matcher.getMatchingNodes();
781 for (const auto Tuple : R) {
782 NodeId Src = Tuple.first;
783 NodeId Dst = Tuple.second;
Johannes Altmanninger51321ae2017-08-19 17:53:01 +0000784 if (!M.hasSrc(Src) && !M.hasDst(Dst))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000785 M.link(Src, Dst);
786 }
787}
788
Johannes Altmanningerd1969302017-08-20 12:09:07 +0000789double ASTDiff::Impl::getJaccardSimilarity(const Mapping &M, NodeId Id1,
790 NodeId Id2) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000791 int CommonDescendants = 0;
792 const Node &N1 = T1.getNode(Id1);
Johannes Altmanningerd1969302017-08-20 12:09:07 +0000793 // Count the common descendants, excluding the subtree root.
794 for (NodeId Src = Id1 + 1; Src <= N1.RightMostDescendant; ++Src) {
795 NodeId Dst = M.getDst(Src);
796 CommonDescendants += int(Dst.isValid() && T2.isInSubtree(Dst, Id2));
797 }
798 // We need to subtract 1 to get the number of descendants excluding the root.
799 double Denominator = T1.getNumberOfDescendants(Id1) - 1 +
800 T2.getNumberOfDescendants(Id2) - 1 - CommonDescendants;
801 // CommonDescendants is less than the size of one subtree.
802 assert(Denominator >= 0 && "Expected non-negative denominator.");
803 if (Denominator == 0)
804 return 0;
805 return CommonDescendants / Denominator;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000806}
807
808NodeId ASTDiff::Impl::findCandidate(const Mapping &M, NodeId Id1) const {
809 NodeId Candidate;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000810 double HighestSimilarity = 0.0;
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000811 for (NodeId Id2 : T2) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000812 if (!isMatchingPossible(Id1, Id2))
813 continue;
814 if (M.hasDst(Id2))
815 continue;
Johannes Altmanningerd1969302017-08-20 12:09:07 +0000816 double Similarity = getJaccardSimilarity(M, Id1, Id2);
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000817 if (Similarity >= Options.MinSimilarity && Similarity > HighestSimilarity) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000818 HighestSimilarity = Similarity;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000819 Candidate = Id2;
820 }
821 }
822 return Candidate;
823}
824
825void ASTDiff::Impl::matchBottomUp(Mapping &M) const {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000826 std::vector<NodeId> Postorder = getSubtreePostorder(T1, T1.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000827 for (NodeId Id1 : Postorder) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000828 if (Id1 == T1.getRootId() && !M.hasSrc(T1.getRootId()) &&
829 !M.hasDst(T2.getRootId())) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000830 if (isMatchingPossible(T1.getRootId(), T2.getRootId())) {
831 M.link(T1.getRootId(), T2.getRootId());
832 addOptimalMapping(M, T1.getRootId(), T2.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000833 }
834 break;
835 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000836 bool Matched = M.hasSrc(Id1);
Johannes Altmanningerd1969302017-08-20 12:09:07 +0000837 const Node &N1 = T1.getNode(Id1);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000838 bool MatchedChildren =
839 std::any_of(N1.Children.begin(), N1.Children.end(),
840 [&](NodeId Child) { return M.hasSrc(Child); });
841 if (Matched || !MatchedChildren)
842 continue;
843 NodeId Id2 = findCandidate(M, Id1);
Johannes Altmanninger51321ae2017-08-19 17:53:01 +0000844 if (Id2.isValid()) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000845 M.link(Id1, Id2);
846 addOptimalMapping(M, Id1, Id2);
847 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000848 }
849}
850
851Mapping ASTDiff::Impl::matchTopDown() const {
852 PriorityList L1(T1);
853 PriorityList L2(T2);
854
Johannes Altmanninger51321ae2017-08-19 17:53:01 +0000855 Mapping M(T1.getSize() + T2.getSize());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000856
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000857 L1.push(T1.getRootId());
858 L2.push(T2.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000859
860 int Max1, Max2;
861 while (std::min(Max1 = L1.peekMax(), Max2 = L2.peekMax()) >
862 Options.MinHeight) {
863 if (Max1 > Max2) {
864 for (NodeId Id : L1.pop())
865 L1.open(Id);
866 continue;
867 }
868 if (Max2 > Max1) {
869 for (NodeId Id : L2.pop())
870 L2.open(Id);
871 continue;
872 }
873 std::vector<NodeId> H1, H2;
874 H1 = L1.pop();
875 H2 = L2.pop();
876 for (NodeId Id1 : H1) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000877 for (NodeId Id2 : H2) {
Johannes Altmanninger51321ae2017-08-19 17:53:01 +0000878 if (identical(Id1, Id2) && !M.hasSrc(Id1) && !M.hasDst(Id2)) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000879 for (int I = 0, E = T1.getNumberOfDescendants(Id1); I < E; ++I)
880 M.link(Id1 + I, Id2 + I);
881 }
882 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000883 }
884 for (NodeId Id1 : H1) {
885 if (!M.hasSrc(Id1))
886 L1.open(Id1);
887 }
888 for (NodeId Id2 : H2) {
889 if (!M.hasDst(Id2))
890 L2.open(Id2);
891 }
892 }
893 return M;
894}
895
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000896ASTDiff::Impl::Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
897 const ComparisonOptions &Options)
898 : T1(T1), T2(T2), Options(Options) {
899 computeMapping();
900 computeChangeKinds(TheMapping);
901}
902
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000903void ASTDiff::Impl::computeMapping() {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000904 TheMapping = matchTopDown();
Johannes Altmanningerd1969302017-08-20 12:09:07 +0000905 if (Options.StopAfterTopDown)
906 return;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000907 matchBottomUp(TheMapping);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000908}
909
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000910void ASTDiff::Impl::computeChangeKinds(Mapping &M) {
911 for (NodeId Id1 : T1) {
912 if (!M.hasSrc(Id1)) {
913 T1.getMutableNode(Id1).Change = Delete;
914 T1.getMutableNode(Id1).Shift -= 1;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000915 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000916 }
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000917 for (NodeId Id2 : T2) {
918 if (!M.hasDst(Id2)) {
919 T2.getMutableNode(Id2).Change = Insert;
920 T2.getMutableNode(Id2).Shift -= 1;
921 }
922 }
923 for (NodeId Id1 : T1.NodesBfs) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000924 NodeId Id2 = M.getDst(Id1);
925 if (Id2.isInvalid())
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000926 continue;
927 if (!haveSameParents(M, Id1, Id2) ||
928 T1.findPositionInParent(Id1, true) !=
929 T2.findPositionInParent(Id2, true)) {
930 T1.getMutableNode(Id1).Shift -= 1;
931 T2.getMutableNode(Id2).Shift -= 1;
932 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000933 }
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000934 for (NodeId Id2 : T2.NodesBfs) {
935 NodeId Id1 = M.getSrc(Id2);
936 if (Id1.isInvalid())
937 continue;
938 Node &N1 = T1.getMutableNode(Id1);
939 Node &N2 = T2.getMutableNode(Id2);
940 if (Id1.isInvalid())
941 continue;
942 if (!haveSameParents(M, Id1, Id2) ||
943 T1.findPositionInParent(Id1, true) !=
944 T2.findPositionInParent(Id2, true)) {
945 N1.Change = N2.Change = Move;
946 }
947 if (T1.getNodeValue(Id1) != T2.getNodeValue(Id2)) {
948 N1.Change = N2.Change = (N1.Change == Move ? UpdateMove : Update);
949 }
950 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000951}
952
953ASTDiff::ASTDiff(SyntaxTree &T1, SyntaxTree &T2,
954 const ComparisonOptions &Options)
955 : DiffImpl(llvm::make_unique<Impl>(*T1.TreeImpl, *T2.TreeImpl, Options)) {}
956
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000957ASTDiff::~ASTDiff() = default;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000958
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000959NodeId ASTDiff::getMapped(const SyntaxTree &SourceTree, NodeId Id) const {
960 return DiffImpl->getMapped(SourceTree.TreeImpl, Id);
961}
962
Johannes Altmanninger2b955ff2017-08-22 08:56:26 +0000963SyntaxTree::SyntaxTree(ASTContext &AST)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000964 : TreeImpl(llvm::make_unique<SyntaxTree::Impl>(
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000965 this, AST.getTranslationUnitDecl(), AST)) {}
966
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000967SyntaxTree::~SyntaxTree() = default;
968
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000969const ASTContext &SyntaxTree::getASTContext() const { return TreeImpl->AST; }
970
971const Node &SyntaxTree::getNode(NodeId Id) const {
972 return TreeImpl->getNode(Id);
973}
974
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000975int SyntaxTree::getSize() const { return TreeImpl->getSize(); }
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000976NodeId SyntaxTree::getRootId() const { return TreeImpl->getRootId(); }
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000977SyntaxTree::PreorderIterator SyntaxTree::begin() const {
978 return TreeImpl->begin();
979}
980SyntaxTree::PreorderIterator SyntaxTree::end() const { return TreeImpl->end(); }
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000981
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000982int SyntaxTree::findPositionInParent(NodeId Id) const {
983 return TreeImpl->findPositionInParent(Id);
984}
985
986std::pair<unsigned, unsigned>
987SyntaxTree::getSourceRangeOffsets(const Node &N) const {
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000988 const SourceManager &SrcMgr = TreeImpl->AST.getSourceManager();
989 SourceRange Range = N.ASTNode.getSourceRange();
990 SourceLocation BeginLoc = Range.getBegin();
991 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
992 Range.getEnd(), /*Offset=*/0, SrcMgr, TreeImpl->AST.getLangOpts());
993 if (auto *ThisExpr = N.ASTNode.get<CXXThisExpr>()) {
994 if (ThisExpr->isImplicit())
995 EndLoc = BeginLoc;
996 }
997 unsigned Begin = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(BeginLoc));
998 unsigned End = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(EndLoc));
999 return {Begin, End};
1000}
Alex Lorenza75b2ca2017-07-21 12:49:28 +00001001
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +00001002std::string SyntaxTree::getNodeValue(NodeId Id) const {
1003 return TreeImpl->getNodeValue(Id);
1004}
1005
1006std::string SyntaxTree::getNodeValue(const Node &N) const {
1007 return TreeImpl->getNodeValue(N);
Alex Lorenza75b2ca2017-07-21 12:49:28 +00001008}
1009
1010} // end namespace diff
1011} // end namespace clang