blob: 0441dbc78dab92747b38d787857e4838d45a1419 [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;
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +000085 bool IsMappingDone = false;
Alex Lorenza75b2ca2017-07-21 12:49:28 +000086 Mapping TheMapping;
87
Johannes Altmanninger31b52d62017-08-01 20:17:46 +000088 Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +000089 const ComparisonOptions &Options)
90 : T1(T1), T2(T2), Options(Options) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +000091
92 /// Matches nodes one-by-one based on their similarity.
93 void computeMapping();
94
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +000095 std::vector<Match> getMatches(Mapping &M);
Alex Lorenza75b2ca2017-07-21 12:49:28 +000096
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +000097 /// Finds an edit script that converts T1 to T2.
98 std::vector<Change> computeChanges(Mapping &M);
99
100 void printChangeImpl(raw_ostream &OS, const Change &Chg) const;
101 void printMatchImpl(raw_ostream &OS, const Match &M) const;
102
103 // Returns a mapping of identical subtrees.
104 Mapping matchTopDown() const;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000105
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;
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000170 std::string getNodeValue(const DynTypedNode &DTN) const;
171 /// Prints the node as "<type>[: <value>](<postorder-id)"
172 void printNode(NodeId Id) const { printNode(llvm::outs(), Id); }
173 void printNode(raw_ostream &OS, NodeId Id) const;
174
175 void printTree() const;
176 void printTree(NodeId Root) const;
177 void printTree(raw_ostream &OS, NodeId Root) const;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000178
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000179private:
180 /// Nodes in preorder.
181 std::vector<Node> Nodes;
182
183 void initTree();
184 void setLeftMostDescendants();
185};
186
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000187template <class T>
188static bool isNodeExcluded(const SourceManager &SrcMgr, T *N) {
189 if (!N)
190 return true;
191 SourceLocation SLoc = N->getLocStart();
192 return SLoc.isValid() && SrcMgr.isInSystemHeader(SLoc);
193}
194
195namespace {
196/// Counts the number of nodes that will be compared.
197struct NodeCountVisitor : public RecursiveASTVisitor<NodeCountVisitor> {
198 int Count = 0;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000199 const SyntaxTree::Impl &Tree;
200 NodeCountVisitor(const SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000201 bool TraverseDecl(Decl *D) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000202 if (isNodeExcluded(Tree.AST.getSourceManager(), D))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000203 return true;
204 ++Count;
205 RecursiveASTVisitor<NodeCountVisitor>::TraverseDecl(D);
206 return true;
207 }
208 bool TraverseStmt(Stmt *S) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000209 if (isNodeExcluded(Tree.AST.getSourceManager(), S))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000210 return true;
211 ++Count;
212 RecursiveASTVisitor<NodeCountVisitor>::TraverseStmt(S);
213 return true;
214 }
215 bool TraverseType(QualType T) { return true; }
216};
217} // end anonymous namespace
218
219namespace {
220// Sets Height, Parent and Children for each node.
221struct PreorderVisitor : public RecursiveASTVisitor<PreorderVisitor> {
222 int Id = 0, Depth = 0;
223 NodeId Parent;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000224 SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000225
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000226 PreorderVisitor(SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000227
228 template <class T> std::tuple<NodeId, NodeId> PreTraverse(T *ASTNode) {
229 NodeId MyId = Id;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000230 Node &N = Tree.getMutableNode(MyId);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000231 N.Parent = Parent;
232 N.Depth = Depth;
233 N.ASTNode = DynTypedNode::create(*ASTNode);
234 assert(!N.ASTNode.getNodeKind().isNone() &&
235 "Expected nodes to have a valid kind.");
236 if (Parent.isValid()) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000237 Node &P = Tree.getMutableNode(Parent);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000238 P.Children.push_back(MyId);
239 }
240 Parent = MyId;
241 ++Id;
242 ++Depth;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000243 return std::make_tuple(MyId, Tree.getNode(MyId).Parent);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000244 }
245 void PostTraverse(std::tuple<NodeId, NodeId> State) {
246 NodeId MyId, PreviousParent;
247 std::tie(MyId, PreviousParent) = State;
248 assert(MyId.isValid() && "Expecting to only traverse valid nodes.");
249 Parent = PreviousParent;
250 --Depth;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000251 Node &N = Tree.getMutableNode(MyId);
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000252 N.RightMostDescendant = Id - 1;
253 assert(N.RightMostDescendant >= 0 &&
254 N.RightMostDescendant < Tree.getSize() &&
255 "Rightmost descendant must be a valid tree node.");
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000256 if (N.isLeaf())
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000257 Tree.Leaves.push_back(MyId);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000258 N.Height = 1;
259 for (NodeId Child : N.Children)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000260 N.Height = std::max(N.Height, 1 + Tree.getNode(Child).Height);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000261 }
262 bool TraverseDecl(Decl *D) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000263 if (isNodeExcluded(Tree.AST.getSourceManager(), D))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000264 return true;
265 auto SavedState = PreTraverse(D);
266 RecursiveASTVisitor<PreorderVisitor>::TraverseDecl(D);
267 PostTraverse(SavedState);
268 return true;
269 }
270 bool TraverseStmt(Stmt *S) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000271 if (isNodeExcluded(Tree.AST.getSourceManager(), S))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000272 return true;
273 auto SavedState = PreTraverse(S);
274 RecursiveASTVisitor<PreorderVisitor>::TraverseStmt(S);
275 PostTraverse(SavedState);
276 return true;
277 }
278 bool TraverseType(QualType T) { return true; }
279};
280} // end anonymous namespace
281
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000282SyntaxTree::Impl::Impl(SyntaxTree *Parent, const ASTContext &AST)
283 : Impl(Parent, AST.getTranslationUnitDecl(), AST) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000284
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000285SyntaxTree::Impl::Impl(SyntaxTree *Parent, Decl *N, const ASTContext &AST)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000286 : Parent(Parent), AST(AST) {
287 NodeCountVisitor NodeCounter(*this);
288 NodeCounter.TraverseDecl(N);
289 Nodes.resize(NodeCounter.Count);
290 PreorderVisitor PreorderWalker(*this);
291 PreorderWalker.TraverseDecl(N);
292 initTree();
293}
294
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000295SyntaxTree::Impl::Impl(SyntaxTree *Parent, Stmt *N, const ASTContext &AST)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000296 : Parent(Parent), AST(AST) {
297 NodeCountVisitor NodeCounter(*this);
298 NodeCounter.TraverseStmt(N);
299 Nodes.resize(NodeCounter.Count);
300 PreorderVisitor PreorderWalker(*this);
301 PreorderWalker.TraverseStmt(N);
302 initTree();
303}
304
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000305void SyntaxTree::Impl::initTree() {
306 setLeftMostDescendants();
307 int PostorderId = 0;
308 PostorderIds.resize(getSize());
309 std::function<void(NodeId)> PostorderTraverse = [&](NodeId Id) {
310 for (NodeId Child : getNode(Id).Children)
311 PostorderTraverse(Child);
312 PostorderIds[Id] = PostorderId;
313 ++PostorderId;
314 };
315 PostorderTraverse(getRootId());
316}
317
318void SyntaxTree::Impl::setLeftMostDescendants() {
319 for (NodeId Leaf : Leaves) {
320 getMutableNode(Leaf).LeftMostDescendant = Leaf;
321 NodeId Parent, Cur = Leaf;
322 while ((Parent = getNode(Cur).Parent).isValid() &&
323 getNode(Parent).Children[0] == Cur) {
324 Cur = Parent;
325 getMutableNode(Cur).LeftMostDescendant = Leaf;
326 }
327 }
328}
329
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000330static std::vector<NodeId> getSubtreePostorder(const SyntaxTree::Impl &Tree,
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000331 NodeId Root) {
332 std::vector<NodeId> Postorder;
333 std::function<void(NodeId)> Traverse = [&](NodeId Id) {
334 const Node &N = Tree.getNode(Id);
335 for (NodeId Child : N.Children)
336 Traverse(Child);
337 Postorder.push_back(Id);
338 };
339 Traverse(Root);
340 return Postorder;
341}
342
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000343static std::vector<NodeId> getSubtreeBfs(const SyntaxTree::Impl &Tree,
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000344 NodeId Root) {
345 std::vector<NodeId> Ids;
346 size_t Expanded = 0;
347 Ids.push_back(Root);
348 while (Expanded < Ids.size())
349 for (NodeId Child : Tree.getNode(Ids[Expanded++]).Children)
350 Ids.push_back(Child);
351 return Ids;
352}
353
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000354int SyntaxTree::Impl::getNumberOfDescendants(NodeId Id) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000355 return getNode(Id).RightMostDescendant - Id + 1;
356}
357
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000358bool SyntaxTree::Impl::isInSubtree(NodeId Id, NodeId SubtreeRoot) const {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000359 return Id >= SubtreeRoot && Id <= getNode(SubtreeRoot).RightMostDescendant;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000360}
361
Johannes Altmanninger69774d62017-08-18 21:26:34 +0000362std::string SyntaxTree::Impl::getNodeValue(NodeId Id) const {
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000363 return getNodeValue(getNode(Id).ASTNode);
Johannes Altmanninger69774d62017-08-18 21:26:34 +0000364}
365
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000366std::string SyntaxTree::Impl::getNodeValue(const DynTypedNode &DTN) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000367 if (auto *X = DTN.get<BinaryOperator>())
368 return X->getOpcodeStr();
369 if (auto *X = DTN.get<AccessSpecDecl>()) {
370 CharSourceRange Range(X->getSourceRange(), false);
371 return Lexer::getSourceText(Range, AST.getSourceManager(),
372 AST.getLangOpts());
373 }
374 if (auto *X = DTN.get<IntegerLiteral>()) {
375 SmallString<256> Str;
376 X->getValue().toString(Str, /*Radix=*/10, /*Signed=*/false);
377 return Str.str();
378 }
379 if (auto *X = DTN.get<StringLiteral>())
380 return X->getString();
381 if (auto *X = DTN.get<ValueDecl>())
382 return X->getNameAsString() + "(" + X->getType().getAsString() + ")";
Alex Lorenz04184a62017-07-21 13:18:51 +0000383 if (DTN.get<DeclStmt>() || DTN.get<TranslationUnitDecl>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000384 return "";
385 std::string Value;
386 if (auto *X = DTN.get<DeclRefExpr>()) {
387 if (X->hasQualifier()) {
388 llvm::raw_string_ostream OS(Value);
389 PrintingPolicy PP(AST.getLangOpts());
390 X->getQualifier()->print(OS, PP);
391 }
392 Value += X->getDecl()->getNameAsString();
393 return Value;
394 }
395 if (auto *X = DTN.get<NamedDecl>())
396 Value += X->getNameAsString() + ";";
397 if (auto *X = DTN.get<TypedefNameDecl>())
398 return Value + X->getUnderlyingType().getAsString() + ";";
Alex Lorenz04184a62017-07-21 13:18:51 +0000399 if (DTN.get<NamespaceDecl>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000400 return Value;
401 if (auto *X = DTN.get<TypeDecl>())
402 if (X->getTypeForDecl())
403 Value +=
404 X->getTypeForDecl()->getCanonicalTypeInternal().getAsString() + ";";
Alex Lorenz04184a62017-07-21 13:18:51 +0000405 if (DTN.get<Decl>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000406 return Value;
Alex Lorenz04184a62017-07-21 13:18:51 +0000407 if (DTN.get<Stmt>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000408 return "";
409 llvm_unreachable("Fatal: unhandled AST node.\n");
410}
411
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000412void SyntaxTree::Impl::printTree() const { printTree(getRootId()); }
413void SyntaxTree::Impl::printTree(NodeId Root) const {
414 printTree(llvm::outs(), Root);
415}
416
417void SyntaxTree::Impl::printTree(raw_ostream &OS, NodeId Root) const {
418 const Node &N = getNode(Root);
419 for (int I = 0; I < N.Depth; ++I)
420 OS << " ";
421 printNode(OS, Root);
422 OS << "\n";
423 for (NodeId Child : N.Children)
424 printTree(OS, Child);
425}
426
427void SyntaxTree::Impl::printNode(raw_ostream &OS, NodeId Id) const {
428 if (Id.isInvalid()) {
429 OS << "None";
430 return;
431 }
432 OS << getNode(Id).getTypeLabel();
433 if (getNodeValue(Id) != "")
434 OS << ": " << getNodeValue(Id);
435 OS << "(" << PostorderIds[Id] << ")";
436}
437
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000438/// Identifies a node in a subtree by its postorder offset, starting at 1.
439struct SNodeId {
440 int Id = 0;
441
442 explicit SNodeId(int Id) : Id(Id) {}
443 explicit SNodeId() = default;
444
445 operator int() const { return Id; }
446 SNodeId &operator++() { return ++Id, *this; }
447 SNodeId &operator--() { return --Id, *this; }
448 SNodeId operator+(int Other) const { return SNodeId(Id + Other); }
449};
450
451class Subtree {
452private:
453 /// The parent tree.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000454 const SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000455 /// Maps SNodeIds to original ids.
456 std::vector<NodeId> RootIds;
457 /// Maps subtree nodes to their leftmost descendants wtihin the subtree.
458 std::vector<SNodeId> LeftMostDescendants;
459
460public:
461 std::vector<SNodeId> KeyRoots;
462
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000463 Subtree(const SyntaxTree::Impl &Tree, NodeId SubtreeRoot) : Tree(Tree) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000464 RootIds = getSubtreePostorder(Tree, SubtreeRoot);
465 int NumLeaves = setLeftMostDescendants();
466 computeKeyRoots(NumLeaves);
467 }
468 int getSize() const { return RootIds.size(); }
469 NodeId getIdInRoot(SNodeId Id) const {
470 assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
471 return RootIds[Id - 1];
472 }
473 const Node &getNode(SNodeId Id) const {
474 return Tree.getNode(getIdInRoot(Id));
475 }
476 SNodeId getLeftMostDescendant(SNodeId Id) const {
477 assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
478 return LeftMostDescendants[Id - 1];
479 }
480 /// Returns the postorder index of the leftmost descendant in the subtree.
481 NodeId getPostorderOffset() const {
482 return Tree.PostorderIds[getIdInRoot(SNodeId(1))];
483 }
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000484 std::string getNodeValue(SNodeId Id) const {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000485 return Tree.getNodeValue(getIdInRoot(Id));
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000486 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000487
488private:
489 /// Returns the number of leafs in the subtree.
490 int setLeftMostDescendants() {
491 int NumLeaves = 0;
492 LeftMostDescendants.resize(getSize());
493 for (int I = 0; I < getSize(); ++I) {
494 SNodeId SI(I + 1);
495 const Node &N = getNode(SI);
496 NumLeaves += N.isLeaf();
497 assert(I == Tree.PostorderIds[getIdInRoot(SI)] - getPostorderOffset() &&
498 "Postorder traversal in subtree should correspond to traversal in "
499 "the root tree by a constant offset.");
500 LeftMostDescendants[I] = SNodeId(Tree.PostorderIds[N.LeftMostDescendant] -
501 getPostorderOffset());
502 }
503 return NumLeaves;
504 }
505 void computeKeyRoots(int Leaves) {
506 KeyRoots.resize(Leaves);
507 std::unordered_set<int> Visited;
508 int K = Leaves - 1;
509 for (SNodeId I(getSize()); I > 0; --I) {
510 SNodeId LeftDesc = getLeftMostDescendant(I);
511 if (Visited.count(LeftDesc))
512 continue;
513 assert(K >= 0 && "K should be non-negative");
514 KeyRoots[K] = I;
515 Visited.insert(LeftDesc);
516 --K;
517 }
518 }
519};
520
521/// Implementation of Zhang and Shasha's Algorithm for tree edit distance.
522/// Computes an optimal mapping between two trees using only insertion,
523/// deletion and update as edit actions (similar to the Levenshtein distance).
524class ZhangShashaMatcher {
525 const ASTDiff::Impl &DiffImpl;
526 Subtree S1;
527 Subtree S2;
528 std::unique_ptr<std::unique_ptr<double[]>[]> TreeDist, ForestDist;
529
530public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000531 ZhangShashaMatcher(const ASTDiff::Impl &DiffImpl, const SyntaxTree::Impl &T1,
532 const SyntaxTree::Impl &T2, NodeId Id1, NodeId Id2)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000533 : DiffImpl(DiffImpl), S1(T1, Id1), S2(T2, Id2) {
534 TreeDist = llvm::make_unique<std::unique_ptr<double[]>[]>(
535 size_t(S1.getSize()) + 1);
536 ForestDist = llvm::make_unique<std::unique_ptr<double[]>[]>(
537 size_t(S1.getSize()) + 1);
538 for (int I = 0, E = S1.getSize() + 1; I < E; ++I) {
539 TreeDist[I] = llvm::make_unique<double[]>(size_t(S2.getSize()) + 1);
540 ForestDist[I] = llvm::make_unique<double[]>(size_t(S2.getSize()) + 1);
541 }
542 }
543
544 std::vector<std::pair<NodeId, NodeId>> getMatchingNodes() {
545 std::vector<std::pair<NodeId, NodeId>> Matches;
546 std::vector<std::pair<SNodeId, SNodeId>> TreePairs;
547
548 computeTreeDist();
549
550 bool RootNodePair = true;
551
Alex Lorenz4c0a8662017-07-21 13:04:57 +0000552 TreePairs.emplace_back(SNodeId(S1.getSize()), SNodeId(S2.getSize()));
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000553
554 while (!TreePairs.empty()) {
555 SNodeId LastRow, LastCol, FirstRow, FirstCol, Row, Col;
556 std::tie(LastRow, LastCol) = TreePairs.back();
557 TreePairs.pop_back();
558
559 if (!RootNodePair) {
560 computeForestDist(LastRow, LastCol);
561 }
562
563 RootNodePair = false;
564
565 FirstRow = S1.getLeftMostDescendant(LastRow);
566 FirstCol = S2.getLeftMostDescendant(LastCol);
567
568 Row = LastRow;
569 Col = LastCol;
570
571 while (Row > FirstRow || Col > FirstCol) {
572 if (Row > FirstRow &&
573 ForestDist[Row - 1][Col] + 1 == ForestDist[Row][Col]) {
574 --Row;
575 } else if (Col > FirstCol &&
576 ForestDist[Row][Col - 1] + 1 == ForestDist[Row][Col]) {
577 --Col;
578 } else {
579 SNodeId LMD1 = S1.getLeftMostDescendant(Row);
580 SNodeId LMD2 = S2.getLeftMostDescendant(Col);
581 if (LMD1 == S1.getLeftMostDescendant(LastRow) &&
582 LMD2 == S2.getLeftMostDescendant(LastCol)) {
583 NodeId Id1 = S1.getIdInRoot(Row);
584 NodeId Id2 = S2.getIdInRoot(Col);
585 assert(DiffImpl.isMatchingPossible(Id1, Id2) &&
586 "These nodes must not be matched.");
587 Matches.emplace_back(Id1, Id2);
588 --Row;
589 --Col;
590 } else {
591 TreePairs.emplace_back(Row, Col);
592 Row = LMD1;
593 Col = LMD2;
594 }
595 }
596 }
597 }
598 return Matches;
599 }
600
601private:
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000602 /// We use a simple cost model for edit actions, which seems good enough.
603 /// Simple cost model for edit actions. This seems to make the matching
604 /// algorithm perform reasonably well.
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000605 /// The values range between 0 and 1, or infinity if this edit action should
606 /// always be avoided.
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000607 static constexpr double DeletionCost = 1;
608 static constexpr double InsertionCost = 1;
609
610 double getUpdateCost(SNodeId Id1, SNodeId Id2) {
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000611 if (!DiffImpl.isMatchingPossible(S1.getIdInRoot(Id1), S2.getIdInRoot(Id2)))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000612 return std::numeric_limits<double>::max();
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000613 return S1.getNodeValue(Id1) != S2.getNodeValue(Id2);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000614 }
615
616 void computeTreeDist() {
617 for (SNodeId Id1 : S1.KeyRoots)
618 for (SNodeId Id2 : S2.KeyRoots)
619 computeForestDist(Id1, Id2);
620 }
621
622 void computeForestDist(SNodeId Id1, SNodeId Id2) {
623 assert(Id1 > 0 && Id2 > 0 && "Expecting offsets greater than 0.");
624 SNodeId LMD1 = S1.getLeftMostDescendant(Id1);
625 SNodeId LMD2 = S2.getLeftMostDescendant(Id2);
626
627 ForestDist[LMD1][LMD2] = 0;
628 for (SNodeId D1 = LMD1 + 1; D1 <= Id1; ++D1) {
629 ForestDist[D1][LMD2] = ForestDist[D1 - 1][LMD2] + DeletionCost;
630 for (SNodeId D2 = LMD2 + 1; D2 <= Id2; ++D2) {
631 ForestDist[LMD1][D2] = ForestDist[LMD1][D2 - 1] + InsertionCost;
632 SNodeId DLMD1 = S1.getLeftMostDescendant(D1);
633 SNodeId DLMD2 = S2.getLeftMostDescendant(D2);
634 if (DLMD1 == LMD1 && DLMD2 == LMD2) {
635 double UpdateCost = getUpdateCost(D1, D2);
636 ForestDist[D1][D2] =
637 std::min({ForestDist[D1 - 1][D2] + DeletionCost,
638 ForestDist[D1][D2 - 1] + InsertionCost,
639 ForestDist[D1 - 1][D2 - 1] + UpdateCost});
640 TreeDist[D1][D2] = ForestDist[D1][D2];
641 } else {
642 ForestDist[D1][D2] =
643 std::min({ForestDist[D1 - 1][D2] + DeletionCost,
644 ForestDist[D1][D2 - 1] + InsertionCost,
645 ForestDist[DLMD1][DLMD2] + TreeDist[D1][D2]});
646 }
647 }
648 }
649 }
650};
651
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000652ast_type_traits::ASTNodeKind Node::getType() const {
653 return ASTNode.getNodeKind();
654}
655
656StringRef Node::getTypeLabel() const { return getType().asStringRef(); }
657
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000658namespace {
659// Compares nodes by their depth.
660struct HeightLess {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000661 const SyntaxTree::Impl &Tree;
662 HeightLess(const SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000663 bool operator()(NodeId Id1, NodeId Id2) const {
664 return Tree.getNode(Id1).Height < Tree.getNode(Id2).Height;
665 }
666};
667} // end anonymous namespace
668
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000669namespace {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000670// Priority queue for nodes, sorted descendingly by their height.
671class PriorityList {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000672 const SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000673 HeightLess Cmp;
674 std::vector<NodeId> Container;
675 PriorityQueue<NodeId, std::vector<NodeId>, HeightLess> List;
676
677public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000678 PriorityList(const SyntaxTree::Impl &Tree)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000679 : Tree(Tree), Cmp(Tree), List(Cmp, Container) {}
680
681 void push(NodeId id) { List.push(id); }
682
683 std::vector<NodeId> pop() {
684 int Max = peekMax();
685 std::vector<NodeId> Result;
686 if (Max == 0)
687 return Result;
688 while (peekMax() == Max) {
689 Result.push_back(List.top());
690 List.pop();
691 }
692 // TODO this is here to get a stable output, not a good heuristic
693 std::sort(Result.begin(), Result.end());
694 return Result;
695 }
696 int peekMax() const {
697 if (List.empty())
698 return 0;
699 return Tree.getNode(List.top()).Height;
700 }
701 void open(NodeId Id) {
702 for (NodeId Child : Tree.getNode(Id).Children)
703 push(Child);
704 }
705};
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000706} // end anonymous namespace
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000707
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000708bool ASTDiff::Impl::identical(NodeId Id1, NodeId Id2) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000709 const Node &N1 = T1.getNode(Id1);
710 const Node &N2 = T2.getNode(Id2);
711 if (N1.Children.size() != N2.Children.size() ||
712 !isMatchingPossible(Id1, Id2) ||
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000713 T1.getNodeValue(Id1) != T2.getNodeValue(Id2))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000714 return false;
715 for (size_t Id = 0, E = N1.Children.size(); Id < E; ++Id)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000716 if (!identical(N1.Children[Id], N2.Children[Id]))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000717 return false;
718 return true;
719}
720
721bool ASTDiff::Impl::canBeAddedToMapping(const Mapping &M, NodeId Id1,
722 NodeId Id2) const {
723 assert(isMatchingPossible(Id1, Id2) &&
724 "Matching must be possible in the first place.");
725 if (M.hasSrcDst(Id1, Id2))
726 return false;
727 if (Options.EnableMatchingWithUnmatchableParents)
728 return true;
729 const Node &N1 = T1.getNode(Id1);
730 const Node &N2 = T2.getNode(Id2);
731 NodeId P1 = N1.Parent;
732 NodeId P2 = N2.Parent;
733 // Only allow matching if parents can be matched.
734 return (P1.isInvalid() && P2.isInvalid()) ||
735 (P1.isValid() && P2.isValid() && isMatchingPossible(P1, P2));
736}
737
738bool ASTDiff::Impl::isMatchingPossible(NodeId Id1, NodeId Id2) const {
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000739 return Options.isMatchingAllowed(T1.getNode(Id1).ASTNode,
740 T2.getNode(Id2).ASTNode);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000741}
742
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000743void ASTDiff::Impl::addOptimalMapping(Mapping &M, NodeId Id1,
744 NodeId Id2) const {
745 if (std::max(T1.getNumberOfDescendants(Id1),
746 T2.getNumberOfDescendants(Id2)) >= Options.MaxSize)
747 return;
748 ZhangShashaMatcher Matcher(*this, T1, T2, Id1, Id2);
749 std::vector<std::pair<NodeId, NodeId>> R = Matcher.getMatchingNodes();
750 for (const auto Tuple : R) {
751 NodeId Src = Tuple.first;
752 NodeId Dst = Tuple.second;
753 if (canBeAddedToMapping(M, Src, Dst))
754 M.link(Src, Dst);
755 }
756}
757
758double ASTDiff::Impl::getSimilarity(const Mapping &M, NodeId Id1,
759 NodeId Id2) const {
760 if (Id1.isInvalid() || Id2.isInvalid())
761 return 0.0;
762 int CommonDescendants = 0;
763 const Node &N1 = T1.getNode(Id1);
764 for (NodeId Id = Id1 + 1; Id <= N1.RightMostDescendant; ++Id)
765 CommonDescendants += int(T2.isInSubtree(M.getDst(Id), Id2));
766 return 2.0 * CommonDescendants /
767 (T1.getNumberOfDescendants(Id1) + T2.getNumberOfDescendants(Id2));
768}
769
770NodeId ASTDiff::Impl::findCandidate(const Mapping &M, NodeId Id1) const {
771 NodeId Candidate;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000772 double HighestSimilarity = 0.0;
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000773 for (NodeId Id2 = 0, E = T2.getSize(); Id2 < E; ++Id2) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000774 if (!isMatchingPossible(Id1, Id2))
775 continue;
776 if (M.hasDst(Id2))
777 continue;
778 double Similarity = getSimilarity(M, Id1, Id2);
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000779 if (Similarity >= Options.MinSimilarity && Similarity > HighestSimilarity) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000780 HighestSimilarity = Similarity;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000781 Candidate = Id2;
782 }
783 }
784 return Candidate;
785}
786
787void ASTDiff::Impl::matchBottomUp(Mapping &M) const {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000788 std::vector<NodeId> Postorder = getSubtreePostorder(T1, T1.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000789 for (NodeId Id1 : Postorder) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000790 if (Id1 == T1.getRootId() && !M.hasSrc(T1.getRootId()) &&
791 !M.hasDst(T2.getRootId())) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000792 if (isMatchingPossible(T1.getRootId(), T2.getRootId())) {
793 M.link(T1.getRootId(), T2.getRootId());
794 addOptimalMapping(M, T1.getRootId(), T2.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000795 }
796 break;
797 }
798 const Node &N1 = T1.getNode(Id1);
799 bool Matched = M.hasSrc(Id1);
800 bool MatchedChildren =
801 std::any_of(N1.Children.begin(), N1.Children.end(),
802 [&](NodeId Child) { return M.hasSrc(Child); });
803 if (Matched || !MatchedChildren)
804 continue;
805 NodeId Id2 = findCandidate(M, Id1);
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000806 if (Id2.isValid() && canBeAddedToMapping(M, Id1, Id2)) {
807 M.link(Id1, Id2);
808 addOptimalMapping(M, Id1, Id2);
809 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000810 }
811}
812
813Mapping ASTDiff::Impl::matchTopDown() const {
814 PriorityList L1(T1);
815 PriorityList L2(T2);
816
817 Mapping M(T1.getSize(), T2.getSize());
818
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000819 L1.push(T1.getRootId());
820 L2.push(T2.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000821
822 int Max1, Max2;
823 while (std::min(Max1 = L1.peekMax(), Max2 = L2.peekMax()) >
824 Options.MinHeight) {
825 if (Max1 > Max2) {
826 for (NodeId Id : L1.pop())
827 L1.open(Id);
828 continue;
829 }
830 if (Max2 > Max1) {
831 for (NodeId Id : L2.pop())
832 L2.open(Id);
833 continue;
834 }
835 std::vector<NodeId> H1, H2;
836 H1 = L1.pop();
837 H2 = L2.pop();
838 for (NodeId Id1 : H1) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000839 for (NodeId Id2 : H2) {
840 if (identical(Id1, Id2) && canBeAddedToMapping(M, Id1, Id2)) {
841 for (int I = 0, E = T1.getNumberOfDescendants(Id1); I < E; ++I)
842 M.link(Id1 + I, Id2 + I);
843 }
844 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000845 }
846 for (NodeId Id1 : H1) {
847 if (!M.hasSrc(Id1))
848 L1.open(Id1);
849 }
850 for (NodeId Id2 : H2) {
851 if (!M.hasDst(Id2))
852 L2.open(Id2);
853 }
854 }
855 return M;
856}
857
858void ASTDiff::Impl::computeMapping() {
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000859 if (IsMappingDone)
860 return;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000861 TheMapping = matchTopDown();
862 matchBottomUp(TheMapping);
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000863 IsMappingDone = true;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000864}
865
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000866std::vector<Match> ASTDiff::Impl::getMatches(Mapping &M) {
867 std::vector<Match> Matches;
868 for (NodeId Id1 = 0, Id2, E = T1.getSize(); Id1 < E; ++Id1)
869 if ((Id2 = M.getDst(Id1)).isValid())
870 Matches.push_back({Id1, Id2});
871 return Matches;
872}
873
874std::vector<Change> ASTDiff::Impl::computeChanges(Mapping &M) {
875 std::vector<Change> Changes;
876 for (NodeId Id2 : getSubtreeBfs(T2, T2.getRootId())) {
877 const Node &N2 = T2.getNode(Id2);
878 NodeId Id1 = M.getSrc(Id2);
879 if (Id1.isValid()) {
880 assert(isMatchingPossible(Id1, Id2) && "Invalid matching.");
881 if (T1.getNodeValue(Id1) != T2.getNodeValue(Id2)) {
882 Changes.emplace_back(Update, Id1, Id2);
883 }
884 continue;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000885 }
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000886 NodeId P2 = N2.Parent;
887 NodeId P1 = M.getSrc(P2);
888 assert(P1.isValid() &&
889 "Parents must be matched for determining the change type.");
890 Node &Parent1 = T1.getMutableNode(P1);
891 const Node &Parent2 = T2.getNode(P2);
892 auto &Siblings1 = Parent1.Children;
893 const auto &Siblings2 = Parent2.Children;
894 size_t Position;
895 for (Position = 0; Position < Siblings2.size(); ++Position)
896 if (Siblings2[Position] == Id2 || Position >= Siblings1.size())
897 break;
898 Changes.emplace_back(Insert, Id2, P2, Position);
899 Node PatchNode;
900 PatchNode.Parent = P1;
901 PatchNode.LeftMostDescendant = N2.LeftMostDescendant;
902 PatchNode.RightMostDescendant = N2.RightMostDescendant;
903 PatchNode.Depth = N2.Depth;
904 PatchNode.ASTNode = N2.ASTNode;
905 // TODO update Depth if needed
906 NodeId PatchNodeId = T1.getSize();
907 // TODO maybe choose a different data structure for Children.
908 Siblings1.insert(Siblings1.begin() + Position, PatchNodeId);
909 T1.addNode(PatchNode);
910 M.link(PatchNodeId, Id2);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000911 }
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000912 for (NodeId Id1 = 0; Id1 < T1.getSize(); ++Id1) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000913 NodeId Id2 = M.getDst(Id1);
914 if (Id2.isInvalid())
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000915 Changes.emplace_back(Delete, Id1, Id2);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000916 }
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000917 return Changes;
918}
919
920void ASTDiff::Impl::printChangeImpl(raw_ostream &OS, const Change &Chg) const {
921 switch (Chg.Kind) {
922 case Delete:
923 OS << "Delete ";
924 T1.printNode(OS, Chg.Src);
925 OS << "\n";
926 break;
927 case Update:
928 OS << "Update ";
929 T1.printNode(OS, Chg.Src);
930 OS << " to " << T2.getNodeValue(Chg.Dst) << "\n";
931 break;
932 case Insert:
933 OS << "Insert ";
934 T2.printNode(OS, Chg.Src);
935 OS << " into ";
936 T2.printNode(OS, Chg.Dst);
937 OS << " at " << Chg.Position << "\n";
938 break;
939 case Move:
940 llvm_unreachable("TODO");
941 break;
942 };
943}
944
945void ASTDiff::Impl::printMatchImpl(raw_ostream &OS, const Match &M) const {
946 OS << "Match ";
947 T1.printNode(OS, M.Src);
948 OS << " to ";
949 T2.printNode(OS, M.Dst);
950 OS << "\n";
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000951}
952
953ASTDiff::ASTDiff(SyntaxTree &T1, SyntaxTree &T2,
954 const ComparisonOptions &Options)
955 : DiffImpl(llvm::make_unique<Impl>(*T1.TreeImpl, *T2.TreeImpl, Options)) {}
956
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000957ASTDiff::~ASTDiff() = default;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000958
959SyntaxTree::SyntaxTree(const ASTContext &AST)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000960 : TreeImpl(llvm::make_unique<SyntaxTree::Impl>(
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000961 this, AST.getTranslationUnitDecl(), AST)) {}
962
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +0000963std::vector<Match> ASTDiff::getMatches() {
964 DiffImpl->computeMapping();
965 return DiffImpl->getMatches(DiffImpl->TheMapping);
966}
967
968std::vector<Change> ASTDiff::getChanges() {
969 DiffImpl->computeMapping();
970 return DiffImpl->computeChanges(DiffImpl->TheMapping);
971}
972
973void ASTDiff::printChange(raw_ostream &OS, const Change &Chg) const {
974 DiffImpl->printChangeImpl(OS, Chg);
975}
976
977void ASTDiff::printMatch(raw_ostream &OS, const Match &M) const {
978 DiffImpl->printMatchImpl(OS, M);
979}
980
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000981SyntaxTree::~SyntaxTree() = default;
982
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000983const ASTContext &SyntaxTree::getASTContext() const { return TreeImpl->AST; }
984
985const Node &SyntaxTree::getNode(NodeId Id) const {
986 return TreeImpl->getNode(Id);
987}
988
989NodeId SyntaxTree::getRootId() const { return TreeImpl->getRootId(); }
990
991std::pair<unsigned, unsigned> SyntaxTree::getSourceRangeOffsets(const Node &N) const {
992 const SourceManager &SrcMgr = TreeImpl->AST.getSourceManager();
993 SourceRange Range = N.ASTNode.getSourceRange();
994 SourceLocation BeginLoc = Range.getBegin();
995 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
996 Range.getEnd(), /*Offset=*/0, SrcMgr, TreeImpl->AST.getLangOpts());
997 if (auto *ThisExpr = N.ASTNode.get<CXXThisExpr>()) {
998 if (ThisExpr->isImplicit())
999 EndLoc = BeginLoc;
1000 }
1001 unsigned Begin = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(BeginLoc));
1002 unsigned End = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(EndLoc));
1003 return {Begin, End};
1004}
Alex Lorenza75b2ca2017-07-21 12:49:28 +00001005
Vlad Tsyrklevichebcb7732017-08-18 23:21:10 +00001006std::string SyntaxTree::getNodeValue(const DynTypedNode &DTN) const {
1007 return TreeImpl->getNodeValue(DTN);
Alex Lorenza75b2ca2017-07-21 12:49:28 +00001008}
1009
1010} // end namespace diff
1011} // end namespace clang