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