blob: 3c8d0024dd631f51c8e2b59bb0d61fd54c1cae67 [file] [log] [blame]
Alex Lorenza75b2ca2017-07-21 12:49:28 +00001//===- ASTDiff.cpp - AST differencing implementation-----------*- C++ -*- -===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains definitons for the AST differencing interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Tooling/ASTDiff/ASTDiff.h"
15
16#include "clang/AST/RecursiveASTVisitor.h"
17#include "clang/Lex/Lexer.h"
18#include "llvm/ADT/PriorityQueue.h"
19
20#include <limits>
21#include <memory>
22#include <unordered_set>
23
24using namespace llvm;
25using namespace clang;
26
27namespace clang {
28namespace diff {
29
Johannes Altmanningerfa524d72017-08-18 16:34:15 +000030namespace {
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000031/// Maps nodes of the left tree to ones on the right, and vice versa.
32class Mapping {
33public:
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
77private:
78 std::unique_ptr<SmallVector<NodeId, 2>[]> SrcToDst, DstToSrc;
79};
Johannes Altmanningerfa524d72017-08-18 16:34:15 +000080} // end anonymous namespace
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000081
Alex Lorenza75b2ca2017-07-21 12:49:28 +000082class ASTDiff::Impl {
83public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +000084 SyntaxTree::Impl &T1, &T2;
Alex Lorenza75b2ca2017-07-21 12:49:28 +000085 bool IsMappingDone = false;
86 Mapping TheMapping;
87
Johannes Altmanninger31b52d62017-08-01 20:17:46 +000088 Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
89 const ComparisonOptions &Options)
Alex Lorenza75b2ca2017-07-21 12:49:28 +000090 : 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
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000103 // Returns a mapping of identical subtrees.
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000104 Mapping matchTopDown() const;
105
106private:
107 // Returns true if the two subtrees are identical.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000108 bool identical(NodeId Id1, NodeId Id2) const;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000109
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
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000115 // 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
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000134/// Represents the AST of a TranslationUnit.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000135class SyntaxTree::Impl {
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000136public:
137 /// Constructs a tree from the entire translation unit.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000138 Impl(SyntaxTree *Parent, const ASTContext &AST);
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000139 /// Constructs a tree from an AST node.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000140 Impl(SyntaxTree *Parent, Decl *N, const ASTContext &AST);
141 Impl(SyntaxTree *Parent, Stmt *N, const ASTContext &AST);
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000142 template <class T>
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000143 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) {}
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000147 template <class T>
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000148 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) {}
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000152
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(); }
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000160 NodeId getRootId() const { return 0; }
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000161
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
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000169 std::string getNodeValue(NodeId Id) const;
170 std::string getNodeValue(const DynTypedNode &DTN) const;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000171 /// 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 void printAsJsonImpl(raw_ostream &OS) const;
180 void printNodeAsJson(raw_ostream &OS, NodeId Id) const;
181
182private:
183 /// Nodes in preorder.
184 std::vector<Node> Nodes;
185
186 void initTree();
187 void setLeftMostDescendants();
188};
189
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000190template <class T>
191static bool isNodeExcluded(const SourceManager &SrcMgr, T *N) {
192 if (!N)
193 return true;
194 SourceLocation SLoc = N->getLocStart();
195 return SLoc.isValid() && SrcMgr.isInSystemHeader(SLoc);
196}
197
198namespace {
199/// Counts the number of nodes that will be compared.
200struct NodeCountVisitor : public RecursiveASTVisitor<NodeCountVisitor> {
201 int Count = 0;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000202 const SyntaxTree::Impl &Tree;
203 NodeCountVisitor(const SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000204 bool TraverseDecl(Decl *D) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000205 if (isNodeExcluded(Tree.AST.getSourceManager(), D))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000206 return true;
207 ++Count;
208 RecursiveASTVisitor<NodeCountVisitor>::TraverseDecl(D);
209 return true;
210 }
211 bool TraverseStmt(Stmt *S) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000212 if (isNodeExcluded(Tree.AST.getSourceManager(), S))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000213 return true;
214 ++Count;
215 RecursiveASTVisitor<NodeCountVisitor>::TraverseStmt(S);
216 return true;
217 }
218 bool TraverseType(QualType T) { return true; }
219};
220} // end anonymous namespace
221
222namespace {
223// Sets Height, Parent and Children for each node.
224struct PreorderVisitor : public RecursiveASTVisitor<PreorderVisitor> {
225 int Id = 0, Depth = 0;
226 NodeId Parent;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000227 SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000228
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000229 PreorderVisitor(SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000230
231 template <class T> std::tuple<NodeId, NodeId> PreTraverse(T *ASTNode) {
232 NodeId MyId = Id;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000233 Node &N = Tree.getMutableNode(MyId);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000234 N.Parent = Parent;
235 N.Depth = Depth;
236 N.ASTNode = DynTypedNode::create(*ASTNode);
237 assert(!N.ASTNode.getNodeKind().isNone() &&
238 "Expected nodes to have a valid kind.");
239 if (Parent.isValid()) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000240 Node &P = Tree.getMutableNode(Parent);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000241 P.Children.push_back(MyId);
242 }
243 Parent = MyId;
244 ++Id;
245 ++Depth;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000246 return std::make_tuple(MyId, Tree.getNode(MyId).Parent);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000247 }
248 void PostTraverse(std::tuple<NodeId, NodeId> State) {
249 NodeId MyId, PreviousParent;
250 std::tie(MyId, PreviousParent) = State;
251 assert(MyId.isValid() && "Expecting to only traverse valid nodes.");
252 Parent = PreviousParent;
253 --Depth;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000254 Node &N = Tree.getMutableNode(MyId);
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000255 N.RightMostDescendant = Id - 1;
256 assert(N.RightMostDescendant >= 0 &&
257 N.RightMostDescendant < Tree.getSize() &&
258 "Rightmost descendant must be a valid tree node.");
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000259 if (N.isLeaf())
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000260 Tree.Leaves.push_back(MyId);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000261 N.Height = 1;
262 for (NodeId Child : N.Children)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000263 N.Height = std::max(N.Height, 1 + Tree.getNode(Child).Height);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000264 }
265 bool TraverseDecl(Decl *D) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000266 if (isNodeExcluded(Tree.AST.getSourceManager(), D))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000267 return true;
268 auto SavedState = PreTraverse(D);
269 RecursiveASTVisitor<PreorderVisitor>::TraverseDecl(D);
270 PostTraverse(SavedState);
271 return true;
272 }
273 bool TraverseStmt(Stmt *S) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000274 if (isNodeExcluded(Tree.AST.getSourceManager(), S))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000275 return true;
276 auto SavedState = PreTraverse(S);
277 RecursiveASTVisitor<PreorderVisitor>::TraverseStmt(S);
278 PostTraverse(SavedState);
279 return true;
280 }
281 bool TraverseType(QualType T) { return true; }
282};
283} // end anonymous namespace
284
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000285SyntaxTree::Impl::Impl(SyntaxTree *Parent, const ASTContext &AST)
286 : Impl(Parent, AST.getTranslationUnitDecl(), AST) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000287
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000288SyntaxTree::Impl::Impl(SyntaxTree *Parent, Decl *N, const ASTContext &AST)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000289 : Parent(Parent), AST(AST) {
290 NodeCountVisitor NodeCounter(*this);
291 NodeCounter.TraverseDecl(N);
292 Nodes.resize(NodeCounter.Count);
293 PreorderVisitor PreorderWalker(*this);
294 PreorderWalker.TraverseDecl(N);
295 initTree();
296}
297
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000298SyntaxTree::Impl::Impl(SyntaxTree *Parent, Stmt *N, const ASTContext &AST)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000299 : Parent(Parent), AST(AST) {
300 NodeCountVisitor NodeCounter(*this);
301 NodeCounter.TraverseStmt(N);
302 Nodes.resize(NodeCounter.Count);
303 PreorderVisitor PreorderWalker(*this);
304 PreorderWalker.TraverseStmt(N);
305 initTree();
306}
307
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000308void SyntaxTree::Impl::initTree() {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000309 setLeftMostDescendants();
310 int PostorderId = 0;
311 PostorderIds.resize(getSize());
312 std::function<void(NodeId)> PostorderTraverse = [&](NodeId Id) {
313 for (NodeId Child : getNode(Id).Children)
314 PostorderTraverse(Child);
315 PostorderIds[Id] = PostorderId;
316 ++PostorderId;
317 };
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000318 PostorderTraverse(getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000319}
320
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000321void SyntaxTree::Impl::setLeftMostDescendants() {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000322 for (NodeId Leaf : Leaves) {
323 getMutableNode(Leaf).LeftMostDescendant = Leaf;
324 NodeId Parent, Cur = Leaf;
325 while ((Parent = getNode(Cur).Parent).isValid() &&
326 getNode(Parent).Children[0] == Cur) {
327 Cur = Parent;
328 getMutableNode(Cur).LeftMostDescendant = Leaf;
329 }
330 }
331}
332
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000333static std::vector<NodeId> getSubtreePostorder(const SyntaxTree::Impl &Tree,
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000334 NodeId Root) {
335 std::vector<NodeId> Postorder;
336 std::function<void(NodeId)> Traverse = [&](NodeId Id) {
337 const Node &N = Tree.getNode(Id);
338 for (NodeId Child : N.Children)
339 Traverse(Child);
340 Postorder.push_back(Id);
341 };
342 Traverse(Root);
343 return Postorder;
344}
345
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000346static std::vector<NodeId> getSubtreeBfs(const SyntaxTree::Impl &Tree,
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000347 NodeId Root) {
348 std::vector<NodeId> Ids;
349 size_t Expanded = 0;
350 Ids.push_back(Root);
351 while (Expanded < Ids.size())
352 for (NodeId Child : Tree.getNode(Ids[Expanded++]).Children)
353 Ids.push_back(Child);
354 return Ids;
355}
356
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000357int SyntaxTree::Impl::getNumberOfDescendants(NodeId Id) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000358 return getNode(Id).RightMostDescendant - Id + 1;
359}
360
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000361bool SyntaxTree::Impl::isInSubtree(NodeId Id, NodeId SubtreeRoot) const {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000362 return Id >= SubtreeRoot && Id <= getNode(SubtreeRoot).RightMostDescendant;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000363}
364
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000365std::string SyntaxTree::Impl::getNodeValue(NodeId Id) const {
366 return getNodeValue(getNode(Id).ASTNode);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000367}
368
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000369std::string SyntaxTree::Impl::getNodeValue(const DynTypedNode &DTN) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000370 if (auto *X = DTN.get<BinaryOperator>())
371 return X->getOpcodeStr();
372 if (auto *X = DTN.get<AccessSpecDecl>()) {
373 CharSourceRange Range(X->getSourceRange(), false);
374 return Lexer::getSourceText(Range, AST.getSourceManager(),
375 AST.getLangOpts());
376 }
377 if (auto *X = DTN.get<IntegerLiteral>()) {
378 SmallString<256> Str;
379 X->getValue().toString(Str, /*Radix=*/10, /*Signed=*/false);
380 return Str.str();
381 }
382 if (auto *X = DTN.get<StringLiteral>())
383 return X->getString();
384 if (auto *X = DTN.get<ValueDecl>())
385 return X->getNameAsString() + "(" + X->getType().getAsString() + ")";
Alex Lorenz04184a62017-07-21 13:18:51 +0000386 if (DTN.get<DeclStmt>() || DTN.get<TranslationUnitDecl>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000387 return "";
388 std::string Value;
389 if (auto *X = DTN.get<DeclRefExpr>()) {
390 if (X->hasQualifier()) {
391 llvm::raw_string_ostream OS(Value);
392 PrintingPolicy PP(AST.getLangOpts());
393 X->getQualifier()->print(OS, PP);
394 }
395 Value += X->getDecl()->getNameAsString();
396 return Value;
397 }
398 if (auto *X = DTN.get<NamedDecl>())
399 Value += X->getNameAsString() + ";";
400 if (auto *X = DTN.get<TypedefNameDecl>())
401 return Value + X->getUnderlyingType().getAsString() + ";";
Alex Lorenz04184a62017-07-21 13:18:51 +0000402 if (DTN.get<NamespaceDecl>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000403 return Value;
404 if (auto *X = DTN.get<TypeDecl>())
405 if (X->getTypeForDecl())
406 Value +=
407 X->getTypeForDecl()->getCanonicalTypeInternal().getAsString() + ";";
Alex Lorenz04184a62017-07-21 13:18:51 +0000408 if (DTN.get<Decl>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000409 return Value;
Alex Lorenz04184a62017-07-21 13:18:51 +0000410 if (DTN.get<Stmt>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000411 return "";
412 llvm_unreachable("Fatal: unhandled AST node.\n");
413}
414
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000415void SyntaxTree::Impl::printTree() const { printTree(getRootId()); }
416void SyntaxTree::Impl::printTree(NodeId Root) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000417 printTree(llvm::outs(), Root);
418}
419
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000420void SyntaxTree::Impl::printTree(raw_ostream &OS, NodeId Root) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000421 const Node &N = getNode(Root);
422 for (int I = 0; I < N.Depth; ++I)
423 OS << " ";
424 printNode(OS, Root);
425 OS << "\n";
426 for (NodeId Child : N.Children)
427 printTree(OS, Child);
428}
429
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000430void SyntaxTree::Impl::printNode(raw_ostream &OS, NodeId Id) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000431 if (Id.isInvalid()) {
432 OS << "None";
433 return;
434 }
435 OS << getNode(Id).getTypeLabel();
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000436 if (getNodeValue(Id) != "")
437 OS << ": " << getNodeValue(Id);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000438 OS << "(" << PostorderIds[Id] << ")";
439}
440
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000441void SyntaxTree::Impl::printNodeAsJson(raw_ostream &OS, NodeId Id) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000442 auto N = getNode(Id);
443 OS << R"({"type":")" << N.getTypeLabel() << R"(")";
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000444 if (getNodeValue(Id) != "")
445 OS << R"(,"value":")" << getNodeValue(Id) << R"(")";
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000446 OS << R"(,"children":[)";
447 if (N.Children.size() > 0) {
448 printNodeAsJson(OS, N.Children[0]);
449 for (size_t I = 1, E = N.Children.size(); I < E; ++I) {
450 OS << ",";
451 printNodeAsJson(OS, N.Children[I]);
452 }
453 }
454 OS << "]}";
455}
456
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000457void SyntaxTree::Impl::printAsJsonImpl(raw_ostream &OS) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000458 OS << R"({"root":)";
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000459 printNodeAsJson(OS, getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000460 OS << "}\n";
461}
462
463/// Identifies a node in a subtree by its postorder offset, starting at 1.
464struct 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
476class Subtree {
477private:
478 /// The parent tree.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000479 const SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000480 /// 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
485public:
486 std::vector<SNodeId> KeyRoots;
487
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000488 Subtree(const SyntaxTree::Impl &Tree, NodeId SubtreeRoot) : Tree(Tree) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000489 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 }
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000509 std::string getNodeValue(SNodeId Id) const {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000510 return Tree.getNodeValue(getIdInRoot(Id));
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000511 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000512
513private:
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).
549class ZhangShashaMatcher {
550 const ASTDiff::Impl &DiffImpl;
551 Subtree S1;
552 Subtree S2;
553 std::unique_ptr<std::unique_ptr<double[]>[]> TreeDist, ForestDist;
554
555public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000556 ZhangShashaMatcher(const ASTDiff::Impl &DiffImpl, const SyntaxTree::Impl &T1,
557 const SyntaxTree::Impl &T2, NodeId Id1, NodeId Id2)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000558 : 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
Alex Lorenz4c0a8662017-07-21 13:04:57 +0000577 TreePairs.emplace_back(SNodeId(S1.getSize()), SNodeId(S2.getSize()));
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000578
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
626private:
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000627 /// 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.
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000630 /// The values range between 0 and 1, or infinity if this edit action should
631 /// always be avoided.
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000632 static constexpr double DeletionCost = 1;
633 static constexpr double InsertionCost = 1;
634
635 double getUpdateCost(SNodeId Id1, SNodeId Id2) {
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000636 if (!DiffImpl.isMatchingPossible(S1.getIdInRoot(Id1), S2.getIdInRoot(Id2)))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000637 return std::numeric_limits<double>::max();
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000638 return S1.getNodeValue(Id1) != S2.getNodeValue(Id2);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000639 }
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
677namespace {
678// Compares nodes by their depth.
679struct HeightLess {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000680 const SyntaxTree::Impl &Tree;
681 HeightLess(const SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000682 bool operator()(NodeId Id1, NodeId Id2) const {
683 return Tree.getNode(Id1).Height < Tree.getNode(Id2).Height;
684 }
685};
686} // end anonymous namespace
687
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000688namespace {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000689// Priority queue for nodes, sorted descendingly by their height.
690class PriorityList {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000691 const SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000692 HeightLess Cmp;
693 std::vector<NodeId> Container;
694 PriorityQueue<NodeId, std::vector<NodeId>, HeightLess> List;
695
696public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000697 PriorityList(const SyntaxTree::Impl &Tree)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000698 : Tree(Tree), Cmp(Tree), List(Cmp, Container) {}
699
700 void push(NodeId id) { List.push(id); }
701
702 std::vector<NodeId> pop() {
703 int Max = peekMax();
704 std::vector<NodeId> Result;
705 if (Max == 0)
706 return Result;
707 while (peekMax() == Max) {
708 Result.push_back(List.top());
709 List.pop();
710 }
711 // TODO this is here to get a stable output, not a good heuristic
712 std::sort(Result.begin(), Result.end());
713 return Result;
714 }
715 int peekMax() const {
716 if (List.empty())
717 return 0;
718 return Tree.getNode(List.top()).Height;
719 }
720 void open(NodeId Id) {
721 for (NodeId Child : Tree.getNode(Id).Children)
722 push(Child);
723 }
724};
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000725} // end anonymous namespace
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000726
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000727bool ASTDiff::Impl::identical(NodeId Id1, NodeId Id2) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000728 const Node &N1 = T1.getNode(Id1);
729 const Node &N2 = T2.getNode(Id2);
730 if (N1.Children.size() != N2.Children.size() ||
731 !isMatchingPossible(Id1, Id2) ||
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000732 T1.getNodeValue(Id1) != T2.getNodeValue(Id2))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000733 return false;
734 for (size_t Id = 0, E = N1.Children.size(); Id < E; ++Id)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000735 if (!identical(N1.Children[Id], N2.Children[Id]))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000736 return false;
737 return true;
738}
739
740bool ASTDiff::Impl::canBeAddedToMapping(const Mapping &M, NodeId Id1,
741 NodeId Id2) const {
742 assert(isMatchingPossible(Id1, Id2) &&
743 "Matching must be possible in the first place.");
744 if (M.hasSrcDst(Id1, Id2))
745 return false;
746 if (Options.EnableMatchingWithUnmatchableParents)
747 return true;
748 const Node &N1 = T1.getNode(Id1);
749 const Node &N2 = T2.getNode(Id2);
750 NodeId P1 = N1.Parent;
751 NodeId P2 = N2.Parent;
752 // Only allow matching if parents can be matched.
753 return (P1.isInvalid() && P2.isInvalid()) ||
754 (P1.isValid() && P2.isValid() && isMatchingPossible(P1, P2));
755}
756
757bool ASTDiff::Impl::isMatchingPossible(NodeId Id1, NodeId Id2) const {
758 return Options.isMatchingAllowed(T1.getNode(Id1).ASTNode,
759 T2.getNode(Id2).ASTNode);
760}
761
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000762void ASTDiff::Impl::addOptimalMapping(Mapping &M, NodeId Id1,
763 NodeId Id2) const {
764 if (std::max(T1.getNumberOfDescendants(Id1),
765 T2.getNumberOfDescendants(Id2)) >= Options.MaxSize)
766 return;
767 ZhangShashaMatcher Matcher(*this, T1, T2, Id1, Id2);
768 std::vector<std::pair<NodeId, NodeId>> R = Matcher.getMatchingNodes();
769 for (const auto Tuple : R) {
770 NodeId Src = Tuple.first;
771 NodeId Dst = Tuple.second;
772 if (canBeAddedToMapping(M, Src, Dst))
773 M.link(Src, Dst);
774 }
775}
776
777double ASTDiff::Impl::getSimilarity(const Mapping &M, NodeId Id1,
778 NodeId Id2) const {
779 if (Id1.isInvalid() || Id2.isInvalid())
780 return 0.0;
781 int CommonDescendants = 0;
782 const Node &N1 = T1.getNode(Id1);
783 for (NodeId Id = Id1 + 1; Id <= N1.RightMostDescendant; ++Id)
784 CommonDescendants += int(T2.isInSubtree(M.getDst(Id), Id2));
785 return 2.0 * CommonDescendants /
786 (T1.getNumberOfDescendants(Id1) + T2.getNumberOfDescendants(Id2));
787}
788
789NodeId ASTDiff::Impl::findCandidate(const Mapping &M, NodeId Id1) const {
790 NodeId Candidate;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000791 double HighestSimilarity = 0.0;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000792 for (NodeId Id2 = 0, E = T2.getSize(); Id2 < E; ++Id2) {
793 if (!isMatchingPossible(Id1, Id2))
794 continue;
795 if (M.hasDst(Id2))
796 continue;
797 double Similarity = getSimilarity(M, Id1, Id2);
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000798 if (Similarity >= Options.MinSimilarity && Similarity > HighestSimilarity) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000799 HighestSimilarity = Similarity;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000800 Candidate = Id2;
801 }
802 }
803 return Candidate;
804}
805
806void ASTDiff::Impl::matchBottomUp(Mapping &M) const {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000807 std::vector<NodeId> Postorder = getSubtreePostorder(T1, T1.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000808 for (NodeId Id1 : Postorder) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000809 if (Id1 == T1.getRootId() && !M.hasSrc(T1.getRootId()) &&
810 !M.hasDst(T2.getRootId())) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000811 if (isMatchingPossible(T1.getRootId(), T2.getRootId())) {
812 M.link(T1.getRootId(), T2.getRootId());
813 addOptimalMapping(M, T1.getRootId(), T2.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000814 }
815 break;
816 }
817 const Node &N1 = T1.getNode(Id1);
818 bool Matched = M.hasSrc(Id1);
819 bool MatchedChildren =
820 std::any_of(N1.Children.begin(), N1.Children.end(),
821 [&](NodeId Child) { return M.hasSrc(Child); });
822 if (Matched || !MatchedChildren)
823 continue;
824 NodeId Id2 = findCandidate(M, Id1);
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000825 if (Id2.isValid() && canBeAddedToMapping(M, Id1, Id2)) {
826 M.link(Id1, Id2);
827 addOptimalMapping(M, Id1, Id2);
828 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000829 }
830}
831
832Mapping ASTDiff::Impl::matchTopDown() const {
833 PriorityList L1(T1);
834 PriorityList L2(T2);
835
836 Mapping M(T1.getSize(), T2.getSize());
837
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000838 L1.push(T1.getRootId());
839 L2.push(T2.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000840
841 int Max1, Max2;
842 while (std::min(Max1 = L1.peekMax(), Max2 = L2.peekMax()) >
843 Options.MinHeight) {
844 if (Max1 > Max2) {
845 for (NodeId Id : L1.pop())
846 L1.open(Id);
847 continue;
848 }
849 if (Max2 > Max1) {
850 for (NodeId Id : L2.pop())
851 L2.open(Id);
852 continue;
853 }
854 std::vector<NodeId> H1, H2;
855 H1 = L1.pop();
856 H2 = L2.pop();
857 for (NodeId Id1 : H1) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000858 for (NodeId Id2 : H2) {
859 if (identical(Id1, Id2) && canBeAddedToMapping(M, Id1, Id2)) {
860 for (int I = 0, E = T1.getNumberOfDescendants(Id1); I < E; ++I)
861 M.link(Id1 + I, Id2 + I);
862 }
863 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000864 }
865 for (NodeId Id1 : H1) {
866 if (!M.hasSrc(Id1))
867 L1.open(Id1);
868 }
869 for (NodeId Id2 : H2) {
870 if (!M.hasDst(Id2))
871 L2.open(Id2);
872 }
873 }
874 return M;
875}
876
877void ASTDiff::Impl::computeMapping() {
878 if (IsMappingDone)
879 return;
880 TheMapping = matchTopDown();
881 matchBottomUp(TheMapping);
882 IsMappingDone = true;
883}
884
885std::vector<Match> ASTDiff::Impl::getMatches(Mapping &M) {
886 std::vector<Match> Matches;
887 for (NodeId Id1 = 0, Id2, E = T1.getSize(); Id1 < E; ++Id1)
888 if ((Id2 = M.getDst(Id1)).isValid())
889 Matches.push_back({Id1, Id2});
890 return Matches;
891}
892
893std::vector<Change> ASTDiff::Impl::computeChanges(Mapping &M) {
894 std::vector<Change> Changes;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000895 for (NodeId Id2 : getSubtreeBfs(T2, T2.getRootId())) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000896 const Node &N2 = T2.getNode(Id2);
897 NodeId Id1 = M.getSrc(Id2);
898 if (Id1.isValid()) {
899 assert(isMatchingPossible(Id1, Id2) && "Invalid matching.");
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000900 if (T1.getNodeValue(Id1) != T2.getNodeValue(Id2)) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000901 Changes.emplace_back(Update, Id1, Id2);
902 }
903 continue;
904 }
905 NodeId P2 = N2.Parent;
906 NodeId P1 = M.getSrc(P2);
907 assert(P1.isValid() &&
908 "Parents must be matched for determining the change type.");
909 Node &Parent1 = T1.getMutableNode(P1);
910 const Node &Parent2 = T2.getNode(P2);
911 auto &Siblings1 = Parent1.Children;
912 const auto &Siblings2 = Parent2.Children;
913 size_t Position;
914 for (Position = 0; Position < Siblings2.size(); ++Position)
915 if (Siblings2[Position] == Id2 || Position >= Siblings1.size())
916 break;
917 Changes.emplace_back(Insert, Id2, P2, Position);
918 Node PatchNode;
919 PatchNode.Parent = P1;
920 PatchNode.LeftMostDescendant = N2.LeftMostDescendant;
921 PatchNode.RightMostDescendant = N2.RightMostDescendant;
922 PatchNode.Depth = N2.Depth;
923 PatchNode.ASTNode = N2.ASTNode;
924 // TODO update Depth if needed
925 NodeId PatchNodeId = T1.getSize();
926 // TODO maybe choose a different data structure for Children.
927 Siblings1.insert(Siblings1.begin() + Position, PatchNodeId);
928 T1.addNode(PatchNode);
929 M.link(PatchNodeId, Id2);
930 }
931 for (NodeId Id1 = 0; Id1 < T1.getSize(); ++Id1) {
932 NodeId Id2 = M.getDst(Id1);
933 if (Id2.isInvalid())
934 Changes.emplace_back(Delete, Id1, Id2);
935 }
936 return Changes;
937}
938
939void ASTDiff::Impl::printChangeImpl(raw_ostream &OS, const Change &Chg) const {
940 switch (Chg.Kind) {
941 case Delete:
942 OS << "Delete ";
943 T1.printNode(OS, Chg.Src);
944 OS << "\n";
945 break;
946 case Update:
947 OS << "Update ";
948 T1.printNode(OS, Chg.Src);
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000949 OS << " to " << T2.getNodeValue(Chg.Dst) << "\n";
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000950 break;
951 case Insert:
952 OS << "Insert ";
953 T2.printNode(OS, Chg.Src);
954 OS << " into ";
955 T2.printNode(OS, Chg.Dst);
956 OS << " at " << Chg.Position << "\n";
957 break;
958 case Move:
959 llvm_unreachable("TODO");
960 break;
961 };
962}
963
964void ASTDiff::Impl::printMatchImpl(raw_ostream &OS, const Match &M) const {
965 OS << "Match ";
966 T1.printNode(OS, M.Src);
967 OS << " to ";
968 T2.printNode(OS, M.Dst);
969 OS << "\n";
970}
971
972ASTDiff::ASTDiff(SyntaxTree &T1, SyntaxTree &T2,
973 const ComparisonOptions &Options)
974 : DiffImpl(llvm::make_unique<Impl>(*T1.TreeImpl, *T2.TreeImpl, Options)) {}
975
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000976ASTDiff::~ASTDiff() = default;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000977
978SyntaxTree::SyntaxTree(const ASTContext &AST)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000979 : TreeImpl(llvm::make_unique<SyntaxTree::Impl>(
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000980 this, AST.getTranslationUnitDecl(), AST)) {}
981
982std::vector<Match> ASTDiff::getMatches() {
983 DiffImpl->computeMapping();
984 return DiffImpl->getMatches(DiffImpl->TheMapping);
985}
986
987std::vector<Change> ASTDiff::getChanges() {
988 DiffImpl->computeMapping();
989 return DiffImpl->computeChanges(DiffImpl->TheMapping);
990}
991
992void ASTDiff::printChange(raw_ostream &OS, const Change &Chg) const {
993 DiffImpl->printChangeImpl(OS, Chg);
994}
995
996void ASTDiff::printMatch(raw_ostream &OS, const Match &M) const {
997 DiffImpl->printMatchImpl(OS, M);
998}
999
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +00001000SyntaxTree::~SyntaxTree() = default;
1001
Alex Lorenza75b2ca2017-07-21 12:49:28 +00001002void SyntaxTree::printAsJson(raw_ostream &OS) { TreeImpl->printAsJsonImpl(OS); }
1003
1004std::string SyntaxTree::getNodeValue(const DynTypedNode &DTN) const {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +00001005 return TreeImpl->getNodeValue(DTN);
Alex Lorenza75b2ca2017-07-21 12:49:28 +00001006}
1007
1008} // end namespace diff
1009} // end namespace clang