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