blob: db84a613d7dae1fb22dc86be9b8836036a150990 [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 Altmanninger8b0e0662017-08-01 20:17:40 +000030/// Maps nodes of the left tree to ones on the right, and vice versa.
31class Mapping {
32public:
33 Mapping() = default;
34 Mapping(Mapping &&Other) = default;
35 Mapping &operator=(Mapping &&Other) = default;
36 Mapping(int Size1, int Size2) {
37 // Maximum possible size after patching one tree.
38 int Size = Size1 + Size2;
39 SrcToDst = llvm::make_unique<SmallVector<NodeId, 2>[]>(Size);
40 DstToSrc = llvm::make_unique<SmallVector<NodeId, 2>[]>(Size);
41 }
42
43 void link(NodeId Src, NodeId Dst) {
44 SrcToDst[Src].push_back(Dst);
45 DstToSrc[Dst].push_back(Src);
46 }
47
48 NodeId getDst(NodeId Src) const {
49 if (hasSrc(Src))
50 return SrcToDst[Src][0];
51 return NodeId();
52 }
53 NodeId getSrc(NodeId Dst) const {
54 if (hasDst(Dst))
55 return DstToSrc[Dst][0];
56 return NodeId();
57 }
58 const SmallVector<NodeId, 2> &getAllDsts(NodeId Src) const {
59 return SrcToDst[Src];
60 }
61 const SmallVector<NodeId, 2> &getAllSrcs(NodeId Dst) const {
62 return DstToSrc[Dst];
63 }
64 bool hasSrc(NodeId Src) const { return !SrcToDst[Src].empty(); }
65 bool hasDst(NodeId Dst) const { return !DstToSrc[Dst].empty(); }
66 bool hasSrcDst(NodeId Src, NodeId Dst) const {
67 for (NodeId DstId : SrcToDst[Src])
68 if (DstId == Dst)
69 return true;
70 for (NodeId SrcId : DstToSrc[Dst])
71 if (SrcId == Src)
72 return true;
73 return false;
74 }
75
76private:
77 std::unique_ptr<SmallVector<NodeId, 2>[]> SrcToDst, DstToSrc;
78};
79
Alex Lorenza75b2ca2017-07-21 12:49:28 +000080class ASTDiff::Impl {
81public:
82 SyntaxTreeImpl &T1, &T2;
83 bool IsMappingDone = false;
84 Mapping TheMapping;
85
86 Impl(SyntaxTreeImpl &T1, SyntaxTreeImpl &T2, const ComparisonOptions &Options)
87 : T1(T1), T2(T2), Options(Options) {}
88
89 /// Matches nodes one-by-one based on their similarity.
90 void computeMapping();
91
92 std::vector<Match> getMatches(Mapping &M);
93
94 /// Finds an edit script that converts T1 to T2.
95 std::vector<Change> computeChanges(Mapping &M);
96
97 void printChangeImpl(raw_ostream &OS, const Change &Chg) const;
98 void printMatchImpl(raw_ostream &OS, const Match &M) const;
99
100 // Returns a mapping of isomorphic subtrees.
101 Mapping matchTopDown() const;
102
103private:
104 // Returns true if the two subtrees are identical.
105 bool isomorphic(NodeId Id1, NodeId Id2) const;
106
107 bool canBeAddedToMapping(const Mapping &M, NodeId Id1, NodeId Id2) const;
108
109 // Returns false if the nodes must not be mached.
110 bool isMatchingPossible(NodeId Id1, NodeId Id2) const;
111
112 // Adds all corresponding subtrees of the two nodes to the mapping.
113 // The two nodes must be isomorphic.
114 void addIsomorphicSubTrees(Mapping &M, NodeId Id1, NodeId Id2) const;
115
116 // Uses an optimal albeit slow algorithm to compute a mapping between two
117 // subtrees, but only if both have fewer nodes than MaxSize.
118 void addOptimalMapping(Mapping &M, NodeId Id1, NodeId Id2) const;
119
120 // Computes the ratio of common descendants between the two nodes.
121 // Descendants are only considered to be equal when they are mapped in M.
122 double getSimilarity(const Mapping &M, NodeId Id1, NodeId Id2) const;
123
124 // Returns the node that has the highest degree of similarity.
125 NodeId findCandidate(const Mapping &M, NodeId Id1) const;
126
127 // Tries to match any yet unmapped nodes, in a bottom-up fashion.
128 void matchBottomUp(Mapping &M) const;
129
130 const ComparisonOptions &Options;
131
132 friend class ZhangShashaMatcher;
133};
134
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000135/// Represents the AST of a TranslationUnit.
136class SyntaxTreeImpl {
137public:
138 /// Constructs a tree from the entire translation unit.
139 SyntaxTreeImpl(SyntaxTree *Parent, const ASTContext &AST);
140 /// Constructs a tree from an AST node.
141 SyntaxTreeImpl(SyntaxTree *Parent, Decl *N, const ASTContext &AST);
142 SyntaxTreeImpl(SyntaxTree *Parent, Stmt *N, const ASTContext &AST);
143 template <class T>
144 SyntaxTreeImpl(
145 SyntaxTree *Parent,
146 typename std::enable_if<std::is_base_of<Stmt, T>::value, T>::type *Node,
147 const ASTContext &AST)
148 : SyntaxTreeImpl(Parent, dyn_cast<Stmt>(Node), AST) {}
149 template <class T>
150 SyntaxTreeImpl(
151 SyntaxTree *Parent,
152 typename std::enable_if<std::is_base_of<Decl, T>::value, T>::type *Node,
153 const ASTContext &AST)
154 : SyntaxTreeImpl(Parent, dyn_cast<Decl>(Node), AST) {}
155
156 SyntaxTree *Parent;
157 const ASTContext &AST;
158 std::vector<NodeId> Leaves;
159 // Maps preorder indices to postorder ones.
160 std::vector<int> PostorderIds;
161
162 int getSize() const { return Nodes.size(); }
163 NodeId root() const { return 0; }
164
165 const Node &getNode(NodeId Id) const { return Nodes[Id]; }
166 Node &getMutableNode(NodeId Id) { return Nodes[Id]; }
167 bool isValidNodeId(NodeId Id) const { return Id >= 0 && Id < getSize(); }
168 void addNode(Node &N) { Nodes.push_back(N); }
169 int getNumberOfDescendants(NodeId Id) const;
170 bool isInSubtree(NodeId Id, NodeId SubtreeRoot) const;
171
172 std::string getNodeValueImpl(NodeId Id) const;
173 std::string getNodeValueImpl(const DynTypedNode &DTN) const;
174 /// Prints the node as "<type>[: <value>](<postorder-id)"
175 void printNode(NodeId Id) const { printNode(llvm::outs(), Id); }
176 void printNode(raw_ostream &OS, NodeId Id) const;
177
178 void printTree() const;
179 void printTree(NodeId Root) const;
180 void printTree(raw_ostream &OS, NodeId Root) const;
181
182 void printAsJsonImpl(raw_ostream &OS) const;
183 void printNodeAsJson(raw_ostream &OS, NodeId Id) const;
184
185private:
186 /// Nodes in preorder.
187 std::vector<Node> Nodes;
188
189 void initTree();
190 void setLeftMostDescendants();
191};
192
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000193template <class T>
194static bool isNodeExcluded(const SourceManager &SrcMgr, T *N) {
195 if (!N)
196 return true;
197 SourceLocation SLoc = N->getLocStart();
198 return SLoc.isValid() && SrcMgr.isInSystemHeader(SLoc);
199}
200
201namespace {
202/// Counts the number of nodes that will be compared.
203struct NodeCountVisitor : public RecursiveASTVisitor<NodeCountVisitor> {
204 int Count = 0;
205 const SyntaxTreeImpl &Root;
206 NodeCountVisitor(const SyntaxTreeImpl &Root) : Root(Root) {}
207 bool TraverseDecl(Decl *D) {
208 if (isNodeExcluded(Root.AST.getSourceManager(), D))
209 return true;
210 ++Count;
211 RecursiveASTVisitor<NodeCountVisitor>::TraverseDecl(D);
212 return true;
213 }
214 bool TraverseStmt(Stmt *S) {
215 if (isNodeExcluded(Root.AST.getSourceManager(), S))
216 return true;
217 ++Count;
218 RecursiveASTVisitor<NodeCountVisitor>::TraverseStmt(S);
219 return true;
220 }
221 bool TraverseType(QualType T) { return true; }
222};
223} // end anonymous namespace
224
225namespace {
226// Sets Height, Parent and Children for each node.
227struct PreorderVisitor : public RecursiveASTVisitor<PreorderVisitor> {
228 int Id = 0, Depth = 0;
229 NodeId Parent;
230 SyntaxTreeImpl &Root;
231
232 PreorderVisitor(SyntaxTreeImpl &Root) : Root(Root) {}
233
234 template <class T> std::tuple<NodeId, NodeId> PreTraverse(T *ASTNode) {
235 NodeId MyId = Id;
236 Node &N = Root.getMutableNode(MyId);
237 N.Parent = Parent;
238 N.Depth = Depth;
239 N.ASTNode = DynTypedNode::create(*ASTNode);
240 assert(!N.ASTNode.getNodeKind().isNone() &&
241 "Expected nodes to have a valid kind.");
242 if (Parent.isValid()) {
243 Node &P = Root.getMutableNode(Parent);
244 P.Children.push_back(MyId);
245 }
246 Parent = MyId;
247 ++Id;
248 ++Depth;
Alex Lorenz158063e2017-07-21 12:57:40 +0000249 return std::make_tuple(MyId, Root.getNode(MyId).Parent);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000250 }
251 void PostTraverse(std::tuple<NodeId, NodeId> State) {
252 NodeId MyId, PreviousParent;
253 std::tie(MyId, PreviousParent) = State;
254 assert(MyId.isValid() && "Expecting to only traverse valid nodes.");
255 Parent = PreviousParent;
256 --Depth;
257 Node &N = Root.getMutableNode(MyId);
258 N.RightMostDescendant = Id;
259 if (N.isLeaf())
260 Root.Leaves.push_back(MyId);
261 N.Height = 1;
262 for (NodeId Child : N.Children)
263 N.Height = std::max(N.Height, 1 + Root.getNode(Child).Height);
264 }
265 bool TraverseDecl(Decl *D) {
266 if (isNodeExcluded(Root.AST.getSourceManager(), D))
267 return true;
268 auto SavedState = PreTraverse(D);
269 RecursiveASTVisitor<PreorderVisitor>::TraverseDecl(D);
270 PostTraverse(SavedState);
271 return true;
272 }
273 bool TraverseStmt(Stmt *S) {
274 if (isNodeExcluded(Root.AST.getSourceManager(), S))
275 return true;
276 auto SavedState = PreTraverse(S);
277 RecursiveASTVisitor<PreorderVisitor>::TraverseStmt(S);
278 PostTraverse(SavedState);
279 return true;
280 }
281 bool TraverseType(QualType T) { return true; }
282};
283} // end anonymous namespace
284
285SyntaxTreeImpl::SyntaxTreeImpl(SyntaxTree *Parent, const ASTContext &AST)
286 : SyntaxTreeImpl(Parent, AST.getTranslationUnitDecl(), AST) {}
287
288SyntaxTreeImpl::SyntaxTreeImpl(SyntaxTree *Parent, Decl *N,
289 const ASTContext &AST)
290 : Parent(Parent), AST(AST) {
291 NodeCountVisitor NodeCounter(*this);
292 NodeCounter.TraverseDecl(N);
293 Nodes.resize(NodeCounter.Count);
294 PreorderVisitor PreorderWalker(*this);
295 PreorderWalker.TraverseDecl(N);
296 initTree();
297}
298
299SyntaxTreeImpl::SyntaxTreeImpl(SyntaxTree *Parent, Stmt *N,
300 const ASTContext &AST)
301 : Parent(Parent), AST(AST) {
302 NodeCountVisitor NodeCounter(*this);
303 NodeCounter.TraverseStmt(N);
304 Nodes.resize(NodeCounter.Count);
305 PreorderVisitor PreorderWalker(*this);
306 PreorderWalker.TraverseStmt(N);
307 initTree();
308}
309
310void SyntaxTreeImpl::initTree() {
311 setLeftMostDescendants();
312 int PostorderId = 0;
313 PostorderIds.resize(getSize());
314 std::function<void(NodeId)> PostorderTraverse = [&](NodeId Id) {
315 for (NodeId Child : getNode(Id).Children)
316 PostorderTraverse(Child);
317 PostorderIds[Id] = PostorderId;
318 ++PostorderId;
319 };
320 PostorderTraverse(root());
321}
322
323void SyntaxTreeImpl::setLeftMostDescendants() {
324 for (NodeId Leaf : Leaves) {
325 getMutableNode(Leaf).LeftMostDescendant = Leaf;
326 NodeId Parent, Cur = Leaf;
327 while ((Parent = getNode(Cur).Parent).isValid() &&
328 getNode(Parent).Children[0] == Cur) {
329 Cur = Parent;
330 getMutableNode(Cur).LeftMostDescendant = Leaf;
331 }
332 }
333}
334
335static std::vector<NodeId> getSubtreePostorder(const SyntaxTreeImpl &Tree,
336 NodeId Root) {
337 std::vector<NodeId> Postorder;
338 std::function<void(NodeId)> Traverse = [&](NodeId Id) {
339 const Node &N = Tree.getNode(Id);
340 for (NodeId Child : N.Children)
341 Traverse(Child);
342 Postorder.push_back(Id);
343 };
344 Traverse(Root);
345 return Postorder;
346}
347
348static std::vector<NodeId> getSubtreeBfs(const SyntaxTreeImpl &Tree,
349 NodeId Root) {
350 std::vector<NodeId> Ids;
351 size_t Expanded = 0;
352 Ids.push_back(Root);
353 while (Expanded < Ids.size())
354 for (NodeId Child : Tree.getNode(Ids[Expanded++]).Children)
355 Ids.push_back(Child);
356 return Ids;
357}
358
359int SyntaxTreeImpl::getNumberOfDescendants(NodeId Id) const {
360 return getNode(Id).RightMostDescendant - Id + 1;
361}
362
363bool SyntaxTreeImpl::isInSubtree(NodeId Id, NodeId SubtreeRoot) const {
364 NodeId Lower = SubtreeRoot;
365 NodeId Upper = getNode(SubtreeRoot).RightMostDescendant;
366 return Id >= Lower && Id <= Upper;
367}
368
369std::string SyntaxTreeImpl::getNodeValueImpl(NodeId Id) const {
370 return getNodeValueImpl(getNode(Id).ASTNode);
371}
372
373std::string SyntaxTreeImpl::getNodeValueImpl(const DynTypedNode &DTN) const {
374 if (auto *X = DTN.get<BinaryOperator>())
375 return X->getOpcodeStr();
376 if (auto *X = DTN.get<AccessSpecDecl>()) {
377 CharSourceRange Range(X->getSourceRange(), false);
378 return Lexer::getSourceText(Range, AST.getSourceManager(),
379 AST.getLangOpts());
380 }
381 if (auto *X = DTN.get<IntegerLiteral>()) {
382 SmallString<256> Str;
383 X->getValue().toString(Str, /*Radix=*/10, /*Signed=*/false);
384 return Str.str();
385 }
386 if (auto *X = DTN.get<StringLiteral>())
387 return X->getString();
388 if (auto *X = DTN.get<ValueDecl>())
389 return X->getNameAsString() + "(" + X->getType().getAsString() + ")";
Alex Lorenz04184a62017-07-21 13:18:51 +0000390 if (DTN.get<DeclStmt>() || DTN.get<TranslationUnitDecl>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000391 return "";
392 std::string Value;
393 if (auto *X = DTN.get<DeclRefExpr>()) {
394 if (X->hasQualifier()) {
395 llvm::raw_string_ostream OS(Value);
396 PrintingPolicy PP(AST.getLangOpts());
397 X->getQualifier()->print(OS, PP);
398 }
399 Value += X->getDecl()->getNameAsString();
400 return Value;
401 }
402 if (auto *X = DTN.get<NamedDecl>())
403 Value += X->getNameAsString() + ";";
404 if (auto *X = DTN.get<TypedefNameDecl>())
405 return Value + X->getUnderlyingType().getAsString() + ";";
Alex Lorenz04184a62017-07-21 13:18:51 +0000406 if (DTN.get<NamespaceDecl>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000407 return Value;
408 if (auto *X = DTN.get<TypeDecl>())
409 if (X->getTypeForDecl())
410 Value +=
411 X->getTypeForDecl()->getCanonicalTypeInternal().getAsString() + ";";
Alex Lorenz04184a62017-07-21 13:18:51 +0000412 if (DTN.get<Decl>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000413 return Value;
Alex Lorenz04184a62017-07-21 13:18:51 +0000414 if (DTN.get<Stmt>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000415 return "";
416 llvm_unreachable("Fatal: unhandled AST node.\n");
417}
418
419void SyntaxTreeImpl::printTree() const { printTree(root()); }
420void SyntaxTreeImpl::printTree(NodeId Root) const {
421 printTree(llvm::outs(), Root);
422}
423
424void SyntaxTreeImpl::printTree(raw_ostream &OS, NodeId Root) const {
425 const Node &N = getNode(Root);
426 for (int I = 0; I < N.Depth; ++I)
427 OS << " ";
428 printNode(OS, Root);
429 OS << "\n";
430 for (NodeId Child : N.Children)
431 printTree(OS, Child);
432}
433
434void SyntaxTreeImpl::printNode(raw_ostream &OS, NodeId Id) const {
435 if (Id.isInvalid()) {
436 OS << "None";
437 return;
438 }
439 OS << getNode(Id).getTypeLabel();
440 if (getNodeValueImpl(Id) != "")
441 OS << ": " << getNodeValueImpl(Id);
442 OS << "(" << PostorderIds[Id] << ")";
443}
444
445void SyntaxTreeImpl::printNodeAsJson(raw_ostream &OS, NodeId Id) const {
446 auto N = getNode(Id);
447 OS << R"({"type":")" << N.getTypeLabel() << R"(")";
448 if (getNodeValueImpl(Id) != "")
449 OS << R"(,"value":")" << getNodeValueImpl(Id) << R"(")";
450 OS << R"(,"children":[)";
451 if (N.Children.size() > 0) {
452 printNodeAsJson(OS, N.Children[0]);
453 for (size_t I = 1, E = N.Children.size(); I < E; ++I) {
454 OS << ",";
455 printNodeAsJson(OS, N.Children[I]);
456 }
457 }
458 OS << "]}";
459}
460
461void SyntaxTreeImpl::printAsJsonImpl(raw_ostream &OS) const {
462 OS << R"({"root":)";
463 printNodeAsJson(OS, root());
464 OS << "}\n";
465}
466
467/// Identifies a node in a subtree by its postorder offset, starting at 1.
468struct SNodeId {
469 int Id = 0;
470
471 explicit SNodeId(int Id) : Id(Id) {}
472 explicit SNodeId() = default;
473
474 operator int() const { return Id; }
475 SNodeId &operator++() { return ++Id, *this; }
476 SNodeId &operator--() { return --Id, *this; }
477 SNodeId operator+(int Other) const { return SNodeId(Id + Other); }
478};
479
480class Subtree {
481private:
482 /// The parent tree.
483 const SyntaxTreeImpl &Tree;
484 /// Maps SNodeIds to original ids.
485 std::vector<NodeId> RootIds;
486 /// Maps subtree nodes to their leftmost descendants wtihin the subtree.
487 std::vector<SNodeId> LeftMostDescendants;
488
489public:
490 std::vector<SNodeId> KeyRoots;
491
492 Subtree(const SyntaxTreeImpl &Tree, NodeId SubtreeRoot) : Tree(Tree) {
493 RootIds = getSubtreePostorder(Tree, SubtreeRoot);
494 int NumLeaves = setLeftMostDescendants();
495 computeKeyRoots(NumLeaves);
496 }
497 int getSize() const { return RootIds.size(); }
498 NodeId getIdInRoot(SNodeId Id) const {
499 assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
500 return RootIds[Id - 1];
501 }
502 const Node &getNode(SNodeId Id) const {
503 return Tree.getNode(getIdInRoot(Id));
504 }
505 SNodeId getLeftMostDescendant(SNodeId Id) const {
506 assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
507 return LeftMostDescendants[Id - 1];
508 }
509 /// Returns the postorder index of the leftmost descendant in the subtree.
510 NodeId getPostorderOffset() const {
511 return Tree.PostorderIds[getIdInRoot(SNodeId(1))];
512 }
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000513 std::string getNodeValue(SNodeId Id) const {
514 return Tree.getNodeValueImpl(getIdInRoot(Id));
515 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000516
517private:
518 /// Returns the number of leafs in the subtree.
519 int setLeftMostDescendants() {
520 int NumLeaves = 0;
521 LeftMostDescendants.resize(getSize());
522 for (int I = 0; I < getSize(); ++I) {
523 SNodeId SI(I + 1);
524 const Node &N = getNode(SI);
525 NumLeaves += N.isLeaf();
526 assert(I == Tree.PostorderIds[getIdInRoot(SI)] - getPostorderOffset() &&
527 "Postorder traversal in subtree should correspond to traversal in "
528 "the root tree by a constant offset.");
529 LeftMostDescendants[I] = SNodeId(Tree.PostorderIds[N.LeftMostDescendant] -
530 getPostorderOffset());
531 }
532 return NumLeaves;
533 }
534 void computeKeyRoots(int Leaves) {
535 KeyRoots.resize(Leaves);
536 std::unordered_set<int> Visited;
537 int K = Leaves - 1;
538 for (SNodeId I(getSize()); I > 0; --I) {
539 SNodeId LeftDesc = getLeftMostDescendant(I);
540 if (Visited.count(LeftDesc))
541 continue;
542 assert(K >= 0 && "K should be non-negative");
543 KeyRoots[K] = I;
544 Visited.insert(LeftDesc);
545 --K;
546 }
547 }
548};
549
550/// Implementation of Zhang and Shasha's Algorithm for tree edit distance.
551/// Computes an optimal mapping between two trees using only insertion,
552/// deletion and update as edit actions (similar to the Levenshtein distance).
553class ZhangShashaMatcher {
554 const ASTDiff::Impl &DiffImpl;
555 Subtree S1;
556 Subtree S2;
557 std::unique_ptr<std::unique_ptr<double[]>[]> TreeDist, ForestDist;
558
559public:
560 ZhangShashaMatcher(const ASTDiff::Impl &DiffImpl, const SyntaxTreeImpl &T1,
561 const SyntaxTreeImpl &T2, NodeId Id1, NodeId Id2)
562 : DiffImpl(DiffImpl), S1(T1, Id1), S2(T2, Id2) {
563 TreeDist = llvm::make_unique<std::unique_ptr<double[]>[]>(
564 size_t(S1.getSize()) + 1);
565 ForestDist = llvm::make_unique<std::unique_ptr<double[]>[]>(
566 size_t(S1.getSize()) + 1);
567 for (int I = 0, E = S1.getSize() + 1; I < E; ++I) {
568 TreeDist[I] = llvm::make_unique<double[]>(size_t(S2.getSize()) + 1);
569 ForestDist[I] = llvm::make_unique<double[]>(size_t(S2.getSize()) + 1);
570 }
571 }
572
573 std::vector<std::pair<NodeId, NodeId>> getMatchingNodes() {
574 std::vector<std::pair<NodeId, NodeId>> Matches;
575 std::vector<std::pair<SNodeId, SNodeId>> TreePairs;
576
577 computeTreeDist();
578
579 bool RootNodePair = true;
580
Alex Lorenz4c0a8662017-07-21 13:04:57 +0000581 TreePairs.emplace_back(SNodeId(S1.getSize()), SNodeId(S2.getSize()));
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000582
583 while (!TreePairs.empty()) {
584 SNodeId LastRow, LastCol, FirstRow, FirstCol, Row, Col;
585 std::tie(LastRow, LastCol) = TreePairs.back();
586 TreePairs.pop_back();
587
588 if (!RootNodePair) {
589 computeForestDist(LastRow, LastCol);
590 }
591
592 RootNodePair = false;
593
594 FirstRow = S1.getLeftMostDescendant(LastRow);
595 FirstCol = S2.getLeftMostDescendant(LastCol);
596
597 Row = LastRow;
598 Col = LastCol;
599
600 while (Row > FirstRow || Col > FirstCol) {
601 if (Row > FirstRow &&
602 ForestDist[Row - 1][Col] + 1 == ForestDist[Row][Col]) {
603 --Row;
604 } else if (Col > FirstCol &&
605 ForestDist[Row][Col - 1] + 1 == ForestDist[Row][Col]) {
606 --Col;
607 } else {
608 SNodeId LMD1 = S1.getLeftMostDescendant(Row);
609 SNodeId LMD2 = S2.getLeftMostDescendant(Col);
610 if (LMD1 == S1.getLeftMostDescendant(LastRow) &&
611 LMD2 == S2.getLeftMostDescendant(LastCol)) {
612 NodeId Id1 = S1.getIdInRoot(Row);
613 NodeId Id2 = S2.getIdInRoot(Col);
614 assert(DiffImpl.isMatchingPossible(Id1, Id2) &&
615 "These nodes must not be matched.");
616 Matches.emplace_back(Id1, Id2);
617 --Row;
618 --Col;
619 } else {
620 TreePairs.emplace_back(Row, Col);
621 Row = LMD1;
622 Col = LMD2;
623 }
624 }
625 }
626 }
627 return Matches;
628 }
629
630private:
631 /// Simple cost model for edit actions.
632 /// The values range between 0 and 1, or infinity if this edit action should
633 /// always be avoided.
634
635 /// These costs could be modified to better model the estimated cost of /
636 /// inserting / deleting the current node.
637 static constexpr double DeletionCost = 1;
638 static constexpr double InsertionCost = 1;
639
640 double getUpdateCost(SNodeId Id1, SNodeId Id2) {
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000641 if (!DiffImpl.isMatchingPossible(S1.getIdInRoot(Id1), S2.getIdInRoot(Id2)))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000642 return std::numeric_limits<double>::max();
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000643 return S1.getNodeValue(Id1) != S2.getNodeValue(Id2);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000644 }
645
646 void computeTreeDist() {
647 for (SNodeId Id1 : S1.KeyRoots)
648 for (SNodeId Id2 : S2.KeyRoots)
649 computeForestDist(Id1, Id2);
650 }
651
652 void computeForestDist(SNodeId Id1, SNodeId Id2) {
653 assert(Id1 > 0 && Id2 > 0 && "Expecting offsets greater than 0.");
654 SNodeId LMD1 = S1.getLeftMostDescendant(Id1);
655 SNodeId LMD2 = S2.getLeftMostDescendant(Id2);
656
657 ForestDist[LMD1][LMD2] = 0;
658 for (SNodeId D1 = LMD1 + 1; D1 <= Id1; ++D1) {
659 ForestDist[D1][LMD2] = ForestDist[D1 - 1][LMD2] + DeletionCost;
660 for (SNodeId D2 = LMD2 + 1; D2 <= Id2; ++D2) {
661 ForestDist[LMD1][D2] = ForestDist[LMD1][D2 - 1] + InsertionCost;
662 SNodeId DLMD1 = S1.getLeftMostDescendant(D1);
663 SNodeId DLMD2 = S2.getLeftMostDescendant(D2);
664 if (DLMD1 == LMD1 && DLMD2 == LMD2) {
665 double UpdateCost = getUpdateCost(D1, D2);
666 ForestDist[D1][D2] =
667 std::min({ForestDist[D1 - 1][D2] + DeletionCost,
668 ForestDist[D1][D2 - 1] + InsertionCost,
669 ForestDist[D1 - 1][D2 - 1] + UpdateCost});
670 TreeDist[D1][D2] = ForestDist[D1][D2];
671 } else {
672 ForestDist[D1][D2] =
673 std::min({ForestDist[D1 - 1][D2] + DeletionCost,
674 ForestDist[D1][D2 - 1] + InsertionCost,
675 ForestDist[DLMD1][DLMD2] + TreeDist[D1][D2]});
676 }
677 }
678 }
679 }
680};
681
682namespace {
683// Compares nodes by their depth.
684struct HeightLess {
685 const SyntaxTreeImpl &Tree;
686 HeightLess(const SyntaxTreeImpl &Tree) : Tree(Tree) {}
687 bool operator()(NodeId Id1, NodeId Id2) const {
688 return Tree.getNode(Id1).Height < Tree.getNode(Id2).Height;
689 }
690};
691} // end anonymous namespace
692
693// Priority queue for nodes, sorted descendingly by their height.
694class PriorityList {
695 const SyntaxTreeImpl &Tree;
696 HeightLess Cmp;
697 std::vector<NodeId> Container;
698 PriorityQueue<NodeId, std::vector<NodeId>, HeightLess> List;
699
700public:
701 PriorityList(const SyntaxTreeImpl &Tree)
702 : Tree(Tree), Cmp(Tree), List(Cmp, Container) {}
703
704 void push(NodeId id) { List.push(id); }
705
706 std::vector<NodeId> pop() {
707 int Max = peekMax();
708 std::vector<NodeId> Result;
709 if (Max == 0)
710 return Result;
711 while (peekMax() == Max) {
712 Result.push_back(List.top());
713 List.pop();
714 }
715 // TODO this is here to get a stable output, not a good heuristic
716 std::sort(Result.begin(), Result.end());
717 return Result;
718 }
719 int peekMax() const {
720 if (List.empty())
721 return 0;
722 return Tree.getNode(List.top()).Height;
723 }
724 void open(NodeId Id) {
725 for (NodeId Child : Tree.getNode(Id).Children)
726 push(Child);
727 }
728};
729
730bool ASTDiff::Impl::isomorphic(NodeId Id1, NodeId Id2) const {
731 const Node &N1 = T1.getNode(Id1);
732 const Node &N2 = T2.getNode(Id2);
733 if (N1.Children.size() != N2.Children.size() ||
734 !isMatchingPossible(Id1, Id2) ||
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000735 T1.getNodeValueImpl(Id1) != T2.getNodeValueImpl(Id2))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000736 return false;
737 for (size_t Id = 0, E = N1.Children.size(); Id < E; ++Id)
738 if (!isomorphic(N1.Children[Id], N2.Children[Id]))
739 return false;
740 return true;
741}
742
743bool ASTDiff::Impl::canBeAddedToMapping(const Mapping &M, NodeId Id1,
744 NodeId Id2) const {
745 assert(isMatchingPossible(Id1, Id2) &&
746 "Matching must be possible in the first place.");
747 if (M.hasSrcDst(Id1, Id2))
748 return false;
749 if (Options.EnableMatchingWithUnmatchableParents)
750 return true;
751 const Node &N1 = T1.getNode(Id1);
752 const Node &N2 = T2.getNode(Id2);
753 NodeId P1 = N1.Parent;
754 NodeId P2 = N2.Parent;
755 // Only allow matching if parents can be matched.
756 return (P1.isInvalid() && P2.isInvalid()) ||
757 (P1.isValid() && P2.isValid() && isMatchingPossible(P1, P2));
758}
759
760bool ASTDiff::Impl::isMatchingPossible(NodeId Id1, NodeId Id2) const {
761 return Options.isMatchingAllowed(T1.getNode(Id1).ASTNode,
762 T2.getNode(Id2).ASTNode);
763}
764
765void ASTDiff::Impl::addIsomorphicSubTrees(Mapping &M, NodeId Id1,
766 NodeId Id2) const {
767 assert(isomorphic(Id1, Id2) && "Can only be called on isomorphic subtrees.");
768 M.link(Id1, Id2);
769 const Node &N1 = T1.getNode(Id1);
770 const Node &N2 = T2.getNode(Id2);
771 for (size_t Id = 0, E = N1.Children.size(); Id < E; ++Id)
772 addIsomorphicSubTrees(M, N1.Children[Id], N2.Children[Id]);
773}
774
775void ASTDiff::Impl::addOptimalMapping(Mapping &M, NodeId Id1,
776 NodeId Id2) const {
777 if (std::max(T1.getNumberOfDescendants(Id1),
778 T2.getNumberOfDescendants(Id2)) >= Options.MaxSize)
779 return;
780 ZhangShashaMatcher Matcher(*this, T1, T2, Id1, Id2);
781 std::vector<std::pair<NodeId, NodeId>> R = Matcher.getMatchingNodes();
782 for (const auto Tuple : R) {
783 NodeId Src = Tuple.first;
784 NodeId Dst = Tuple.second;
785 if (canBeAddedToMapping(M, Src, Dst))
786 M.link(Src, Dst);
787 }
788}
789
790double ASTDiff::Impl::getSimilarity(const Mapping &M, NodeId Id1,
791 NodeId Id2) const {
792 if (Id1.isInvalid() || Id2.isInvalid())
793 return 0.0;
794 int CommonDescendants = 0;
795 const Node &N1 = T1.getNode(Id1);
796 for (NodeId Id = Id1 + 1; Id <= N1.RightMostDescendant; ++Id)
797 CommonDescendants += int(T2.isInSubtree(M.getDst(Id), Id2));
798 return 2.0 * CommonDescendants /
799 (T1.getNumberOfDescendants(Id1) + T2.getNumberOfDescendants(Id2));
800}
801
802NodeId ASTDiff::Impl::findCandidate(const Mapping &M, NodeId Id1) const {
803 NodeId Candidate;
804 double MaxSimilarity = 0.0;
805 for (NodeId Id2 = 0, E = T2.getSize(); Id2 < E; ++Id2) {
806 if (!isMatchingPossible(Id1, Id2))
807 continue;
808 if (M.hasDst(Id2))
809 continue;
810 double Similarity = getSimilarity(M, Id1, Id2);
811 if (Similarity > MaxSimilarity) {
812 MaxSimilarity = Similarity;
813 Candidate = Id2;
814 }
815 }
816 return Candidate;
817}
818
819void ASTDiff::Impl::matchBottomUp(Mapping &M) const {
820 std::vector<NodeId> Postorder = getSubtreePostorder(T1, T1.root());
821 for (NodeId Id1 : Postorder) {
822 if (Id1 == T1.root()) {
823 if (isMatchingPossible(T1.root(), T2.root())) {
824 M.link(T1.root(), T2.root());
825 addOptimalMapping(M, T1.root(), T2.root());
826 }
827 break;
828 }
829 const Node &N1 = T1.getNode(Id1);
830 bool Matched = M.hasSrc(Id1);
831 bool MatchedChildren =
832 std::any_of(N1.Children.begin(), N1.Children.end(),
833 [&](NodeId Child) { return M.hasSrc(Child); });
834 if (Matched || !MatchedChildren)
835 continue;
836 NodeId Id2 = findCandidate(M, Id1);
837 if (Id2.isInvalid() || !canBeAddedToMapping(M, Id1, Id2) ||
838 getSimilarity(M, Id1, Id2) < Options.MinSimilarity)
839 continue;
840 M.link(Id1, Id2);
841 addOptimalMapping(M, Id1, Id2);
842 }
843}
844
845Mapping ASTDiff::Impl::matchTopDown() const {
846 PriorityList L1(T1);
847 PriorityList L2(T2);
848
849 Mapping M(T1.getSize(), T2.getSize());
850
851 L1.push(T1.root());
852 L2.push(T2.root());
853
854 int Max1, Max2;
855 while (std::min(Max1 = L1.peekMax(), Max2 = L2.peekMax()) >
856 Options.MinHeight) {
857 if (Max1 > Max2) {
858 for (NodeId Id : L1.pop())
859 L1.open(Id);
860 continue;
861 }
862 if (Max2 > Max1) {
863 for (NodeId Id : L2.pop())
864 L2.open(Id);
865 continue;
866 }
867 std::vector<NodeId> H1, H2;
868 H1 = L1.pop();
869 H2 = L2.pop();
870 for (NodeId Id1 : H1) {
871 for (NodeId Id2 : H2)
872 if (isomorphic(Id1, Id2) && canBeAddedToMapping(M, Id1, Id2))
873 addIsomorphicSubTrees(M, Id1, Id2);
874 }
875 for (NodeId Id1 : H1) {
876 if (!M.hasSrc(Id1))
877 L1.open(Id1);
878 }
879 for (NodeId Id2 : H2) {
880 if (!M.hasDst(Id2))
881 L2.open(Id2);
882 }
883 }
884 return M;
885}
886
887void ASTDiff::Impl::computeMapping() {
888 if (IsMappingDone)
889 return;
890 TheMapping = matchTopDown();
891 matchBottomUp(TheMapping);
892 IsMappingDone = true;
893}
894
895std::vector<Match> ASTDiff::Impl::getMatches(Mapping &M) {
896 std::vector<Match> Matches;
897 for (NodeId Id1 = 0, Id2, E = T1.getSize(); Id1 < E; ++Id1)
898 if ((Id2 = M.getDst(Id1)).isValid())
899 Matches.push_back({Id1, Id2});
900 return Matches;
901}
902
903std::vector<Change> ASTDiff::Impl::computeChanges(Mapping &M) {
904 std::vector<Change> Changes;
905 for (NodeId Id2 : getSubtreeBfs(T2, T2.root())) {
906 const Node &N2 = T2.getNode(Id2);
907 NodeId Id1 = M.getSrc(Id2);
908 if (Id1.isValid()) {
909 assert(isMatchingPossible(Id1, Id2) && "Invalid matching.");
910 if (T1.getNodeValueImpl(Id1) != T2.getNodeValueImpl(Id2)) {
911 Changes.emplace_back(Update, Id1, Id2);
912 }
913 continue;
914 }
915 NodeId P2 = N2.Parent;
916 NodeId P1 = M.getSrc(P2);
917 assert(P1.isValid() &&
918 "Parents must be matched for determining the change type.");
919 Node &Parent1 = T1.getMutableNode(P1);
920 const Node &Parent2 = T2.getNode(P2);
921 auto &Siblings1 = Parent1.Children;
922 const auto &Siblings2 = Parent2.Children;
923 size_t Position;
924 for (Position = 0; Position < Siblings2.size(); ++Position)
925 if (Siblings2[Position] == Id2 || Position >= Siblings1.size())
926 break;
927 Changes.emplace_back(Insert, Id2, P2, Position);
928 Node PatchNode;
929 PatchNode.Parent = P1;
930 PatchNode.LeftMostDescendant = N2.LeftMostDescendant;
931 PatchNode.RightMostDescendant = N2.RightMostDescendant;
932 PatchNode.Depth = N2.Depth;
933 PatchNode.ASTNode = N2.ASTNode;
934 // TODO update Depth if needed
935 NodeId PatchNodeId = T1.getSize();
936 // TODO maybe choose a different data structure for Children.
937 Siblings1.insert(Siblings1.begin() + Position, PatchNodeId);
938 T1.addNode(PatchNode);
939 M.link(PatchNodeId, Id2);
940 }
941 for (NodeId Id1 = 0; Id1 < T1.getSize(); ++Id1) {
942 NodeId Id2 = M.getDst(Id1);
943 if (Id2.isInvalid())
944 Changes.emplace_back(Delete, Id1, Id2);
945 }
946 return Changes;
947}
948
949void ASTDiff::Impl::printChangeImpl(raw_ostream &OS, const Change &Chg) const {
950 switch (Chg.Kind) {
951 case Delete:
952 OS << "Delete ";
953 T1.printNode(OS, Chg.Src);
954 OS << "\n";
955 break;
956 case Update:
957 OS << "Update ";
958 T1.printNode(OS, Chg.Src);
959 OS << " to " << T2.getNodeValueImpl(Chg.Dst) << "\n";
960 break;
961 case Insert:
962 OS << "Insert ";
963 T2.printNode(OS, Chg.Src);
964 OS << " into ";
965 T2.printNode(OS, Chg.Dst);
966 OS << " at " << Chg.Position << "\n";
967 break;
968 case Move:
969 llvm_unreachable("TODO");
970 break;
971 };
972}
973
974void ASTDiff::Impl::printMatchImpl(raw_ostream &OS, const Match &M) const {
975 OS << "Match ";
976 T1.printNode(OS, M.Src);
977 OS << " to ";
978 T2.printNode(OS, M.Dst);
979 OS << "\n";
980}
981
982ASTDiff::ASTDiff(SyntaxTree &T1, SyntaxTree &T2,
983 const ComparisonOptions &Options)
984 : DiffImpl(llvm::make_unique<Impl>(*T1.TreeImpl, *T2.TreeImpl, Options)) {}
985
986ASTDiff::~ASTDiff() {}
987
988SyntaxTree::SyntaxTree(const ASTContext &AST)
989 : TreeImpl(llvm::make_unique<SyntaxTreeImpl>(
990 this, AST.getTranslationUnitDecl(), AST)) {}
991
992std::vector<Match> ASTDiff::getMatches() {
993 DiffImpl->computeMapping();
994 return DiffImpl->getMatches(DiffImpl->TheMapping);
995}
996
997std::vector<Change> ASTDiff::getChanges() {
998 DiffImpl->computeMapping();
999 return DiffImpl->computeChanges(DiffImpl->TheMapping);
1000}
1001
1002void ASTDiff::printChange(raw_ostream &OS, const Change &Chg) const {
1003 DiffImpl->printChangeImpl(OS, Chg);
1004}
1005
1006void ASTDiff::printMatch(raw_ostream &OS, const Match &M) const {
1007 DiffImpl->printMatchImpl(OS, M);
1008}
1009
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +00001010SyntaxTree::~SyntaxTree() = default;
1011
Alex Lorenza75b2ca2017-07-21 12:49:28 +00001012void SyntaxTree::printAsJson(raw_ostream &OS) { TreeImpl->printAsJsonImpl(OS); }
1013
1014std::string SyntaxTree::getNodeValue(const DynTypedNode &DTN) const {
1015 return TreeImpl->getNodeValueImpl(DTN);
1016}
1017
1018} // end namespace diff
1019} // end namespace clang