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