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