blob: 43c19a72260e9d03bb438f1f1ec88a0feecb79f0 [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;
Johannes Altmanninger51321ae2017-08-19 17:53:01 +000037
38 Mapping(size_t Size) {
39 SrcToDst = llvm::make_unique<NodeId[]>(Size);
40 DstToSrc = llvm::make_unique<NodeId[]>(Size);
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000041 }
42
43 void link(NodeId Src, NodeId Dst) {
Johannes Altmanninger51321ae2017-08-19 17:53:01 +000044 SrcToDst[Src] = Dst, DstToSrc[Dst] = Src;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000045 }
46
Johannes Altmanninger51321ae2017-08-19 17:53:01 +000047 NodeId getDst(NodeId Src) const { return SrcToDst[Src]; }
48 NodeId getSrc(NodeId Dst) const { return DstToSrc[Dst]; }
49 bool hasSrc(NodeId Src) const { return getDst(Src).isValid(); }
50 bool hasDst(NodeId Dst) const { return getSrc(Dst).isValid(); }
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000051
52private:
Johannes Altmanninger51321ae2017-08-19 17:53:01 +000053 std::unique_ptr<NodeId[]> SrcToDst, DstToSrc;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000054};
Johannes Altmanningerfa524d72017-08-18 16:34:15 +000055} // end anonymous namespace
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +000056
Alex Lorenza75b2ca2017-07-21 12:49:28 +000057class ASTDiff::Impl {
58public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +000059 SyntaxTree::Impl &T1, &T2;
Alex Lorenza75b2ca2017-07-21 12:49:28 +000060 Mapping TheMapping;
61
Johannes Altmanninger31b52d62017-08-01 20:17:46 +000062 Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +000063 const ComparisonOptions &Options);
Alex Lorenza75b2ca2017-07-21 12:49:28 +000064
65 /// Matches nodes one-by-one based on their similarity.
66 void computeMapping();
67
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +000068 // Compute Change for each node based on similarity.
69 void computeChangeKinds(Mapping &M);
Alex Lorenza75b2ca2017-07-21 12:49:28 +000070
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +000071 NodeId getMapped(const std::unique_ptr<SyntaxTree::Impl> &Tree,
72 NodeId Id) const {
73 if (&*Tree == &T1)
74 return TheMapping.getDst(Id);
75 assert(&*Tree == &T2 && "Invalid tree.");
76 return TheMapping.getSrc(Id);
77 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +000078
79private:
80 // Returns true if the two subtrees are identical.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +000081 bool identical(NodeId Id1, NodeId Id2) const;
Alex Lorenza75b2ca2017-07-21 12:49:28 +000082
Alex Lorenza75b2ca2017-07-21 12:49:28 +000083 // Returns false if the nodes must not be mached.
84 bool isMatchingPossible(NodeId Id1, NodeId Id2) const;
85
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +000086 // Returns true if the nodes' parents are matched.
87 bool haveSameParents(const Mapping &M, NodeId Id1, NodeId Id2) const;
88
Alex Lorenza75b2ca2017-07-21 12:49:28 +000089 // Uses an optimal albeit slow algorithm to compute a mapping between two
90 // subtrees, but only if both have fewer nodes than MaxSize.
91 void addOptimalMapping(Mapping &M, NodeId Id1, NodeId Id2) const;
92
93 // Computes the ratio of common descendants between the two nodes.
94 // Descendants are only considered to be equal when they are mapped in M.
95 double getSimilarity(const Mapping &M, NodeId Id1, NodeId Id2) const;
96
97 // Returns the node that has the highest degree of similarity.
98 NodeId findCandidate(const Mapping &M, NodeId Id1) const;
99
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000100 // Returns a mapping of identical subtrees.
101 Mapping matchTopDown() const;
102
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000103 // Tries to match any yet unmapped nodes, in a bottom-up fashion.
104 void matchBottomUp(Mapping &M) const;
105
106 const ComparisonOptions &Options;
107
108 friend class ZhangShashaMatcher;
109};
110
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000111/// Represents the AST of a TranslationUnit.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000112class SyntaxTree::Impl {
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000113public:
114 /// Constructs a tree from the entire translation unit.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000115 Impl(SyntaxTree *Parent, const ASTContext &AST);
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000116 /// Constructs a tree from an AST node.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000117 Impl(SyntaxTree *Parent, Decl *N, const ASTContext &AST);
118 Impl(SyntaxTree *Parent, Stmt *N, const ASTContext &AST);
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000119 template <class T>
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000120 Impl(SyntaxTree *Parent,
121 typename std::enable_if<std::is_base_of<Stmt, T>::value, T>::type *Node,
122 const ASTContext &AST)
123 : Impl(Parent, dyn_cast<Stmt>(Node), AST) {}
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000124 template <class T>
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000125 Impl(SyntaxTree *Parent,
126 typename std::enable_if<std::is_base_of<Decl, T>::value, T>::type *Node,
127 const ASTContext &AST)
128 : Impl(Parent, dyn_cast<Decl>(Node), AST) {}
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000129
130 SyntaxTree *Parent;
131 const ASTContext &AST;
132 std::vector<NodeId> Leaves;
133 // Maps preorder indices to postorder ones.
134 std::vector<int> PostorderIds;
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000135 std::vector<NodeId> NodesBfs;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000136
137 int getSize() const { return Nodes.size(); }
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000138 NodeId getRootId() const { return 0; }
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000139 PreorderIterator begin() const { return getRootId(); }
140 PreorderIterator end() const { return getSize(); }
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000141
142 const Node &getNode(NodeId Id) const { return Nodes[Id]; }
143 Node &getMutableNode(NodeId Id) { return Nodes[Id]; }
144 bool isValidNodeId(NodeId Id) const { return Id >= 0 && Id < getSize(); }
145 void addNode(Node &N) { Nodes.push_back(N); }
146 int getNumberOfDescendants(NodeId Id) const;
147 bool isInSubtree(NodeId Id, NodeId SubtreeRoot) const;
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000148 int findPositionInParent(NodeId Id, bool Shifted = false) const;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000149
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000150 std::string getNodeValue(NodeId Id) const;
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000151 std::string getNodeValue(const Node &Node) const;
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000152
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000153private:
154 /// Nodes in preorder.
155 std::vector<Node> Nodes;
156
157 void initTree();
158 void setLeftMostDescendants();
159};
160
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000161template <class T>
162static bool isNodeExcluded(const SourceManager &SrcMgr, T *N) {
163 if (!N)
164 return true;
165 SourceLocation SLoc = N->getLocStart();
166 return SLoc.isValid() && SrcMgr.isInSystemHeader(SLoc);
167}
168
169namespace {
170/// Counts the number of nodes that will be compared.
171struct NodeCountVisitor : public RecursiveASTVisitor<NodeCountVisitor> {
172 int Count = 0;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000173 const SyntaxTree::Impl &Tree;
174 NodeCountVisitor(const SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000175 bool TraverseDecl(Decl *D) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000176 if (isNodeExcluded(Tree.AST.getSourceManager(), D))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000177 return true;
178 ++Count;
179 RecursiveASTVisitor<NodeCountVisitor>::TraverseDecl(D);
180 return true;
181 }
182 bool TraverseStmt(Stmt *S) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000183 if (isNodeExcluded(Tree.AST.getSourceManager(), S))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000184 return true;
185 ++Count;
186 RecursiveASTVisitor<NodeCountVisitor>::TraverseStmt(S);
187 return true;
188 }
189 bool TraverseType(QualType T) { return true; }
190};
191} // end anonymous namespace
192
193namespace {
194// Sets Height, Parent and Children for each node.
195struct PreorderVisitor : public RecursiveASTVisitor<PreorderVisitor> {
196 int Id = 0, Depth = 0;
197 NodeId Parent;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000198 SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000199
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000200 PreorderVisitor(SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000201
202 template <class T> std::tuple<NodeId, NodeId> PreTraverse(T *ASTNode) {
203 NodeId MyId = Id;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000204 Node &N = Tree.getMutableNode(MyId);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000205 N.Parent = Parent;
206 N.Depth = Depth;
207 N.ASTNode = DynTypedNode::create(*ASTNode);
208 assert(!N.ASTNode.getNodeKind().isNone() &&
209 "Expected nodes to have a valid kind.");
210 if (Parent.isValid()) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000211 Node &P = Tree.getMutableNode(Parent);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000212 P.Children.push_back(MyId);
213 }
214 Parent = MyId;
215 ++Id;
216 ++Depth;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000217 return std::make_tuple(MyId, Tree.getNode(MyId).Parent);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000218 }
219 void PostTraverse(std::tuple<NodeId, NodeId> State) {
220 NodeId MyId, PreviousParent;
221 std::tie(MyId, PreviousParent) = State;
222 assert(MyId.isValid() && "Expecting to only traverse valid nodes.");
223 Parent = PreviousParent;
224 --Depth;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000225 Node &N = Tree.getMutableNode(MyId);
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000226 N.RightMostDescendant = Id - 1;
227 assert(N.RightMostDescendant >= 0 &&
228 N.RightMostDescendant < Tree.getSize() &&
229 "Rightmost descendant must be a valid tree node.");
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000230 if (N.isLeaf())
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000231 Tree.Leaves.push_back(MyId);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000232 N.Height = 1;
233 for (NodeId Child : N.Children)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000234 N.Height = std::max(N.Height, 1 + Tree.getNode(Child).Height);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000235 }
236 bool TraverseDecl(Decl *D) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000237 if (isNodeExcluded(Tree.AST.getSourceManager(), D))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000238 return true;
239 auto SavedState = PreTraverse(D);
240 RecursiveASTVisitor<PreorderVisitor>::TraverseDecl(D);
241 PostTraverse(SavedState);
242 return true;
243 }
244 bool TraverseStmt(Stmt *S) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000245 if (isNodeExcluded(Tree.AST.getSourceManager(), S))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000246 return true;
247 auto SavedState = PreTraverse(S);
248 RecursiveASTVisitor<PreorderVisitor>::TraverseStmt(S);
249 PostTraverse(SavedState);
250 return true;
251 }
252 bool TraverseType(QualType T) { return true; }
253};
254} // end anonymous namespace
255
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000256SyntaxTree::Impl::Impl(SyntaxTree *Parent, const ASTContext &AST)
257 : Impl(Parent, AST.getTranslationUnitDecl(), AST) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000258
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000259SyntaxTree::Impl::Impl(SyntaxTree *Parent, Decl *N, const ASTContext &AST)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000260 : Parent(Parent), AST(AST) {
261 NodeCountVisitor NodeCounter(*this);
262 NodeCounter.TraverseDecl(N);
263 Nodes.resize(NodeCounter.Count);
264 PreorderVisitor PreorderWalker(*this);
265 PreorderWalker.TraverseDecl(N);
266 initTree();
267}
268
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000269SyntaxTree::Impl::Impl(SyntaxTree *Parent, Stmt *N, const ASTContext &AST)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000270 : Parent(Parent), AST(AST) {
271 NodeCountVisitor NodeCounter(*this);
272 NodeCounter.TraverseStmt(N);
273 Nodes.resize(NodeCounter.Count);
274 PreorderVisitor PreorderWalker(*this);
275 PreorderWalker.TraverseStmt(N);
276 initTree();
277}
278
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000279static std::vector<NodeId> getSubtreePostorder(const SyntaxTree::Impl &Tree,
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000280 NodeId Root) {
281 std::vector<NodeId> Postorder;
282 std::function<void(NodeId)> Traverse = [&](NodeId Id) {
283 const Node &N = Tree.getNode(Id);
284 for (NodeId Child : N.Children)
285 Traverse(Child);
286 Postorder.push_back(Id);
287 };
288 Traverse(Root);
289 return Postorder;
290}
291
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000292static std::vector<NodeId> getSubtreeBfs(const SyntaxTree::Impl &Tree,
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000293 NodeId Root) {
294 std::vector<NodeId> Ids;
295 size_t Expanded = 0;
296 Ids.push_back(Root);
297 while (Expanded < Ids.size())
298 for (NodeId Child : Tree.getNode(Ids[Expanded++]).Children)
299 Ids.push_back(Child);
300 return Ids;
301}
302
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000303void SyntaxTree::Impl::initTree() {
304 setLeftMostDescendants();
305 int PostorderId = 0;
306 PostorderIds.resize(getSize());
307 std::function<void(NodeId)> PostorderTraverse = [&](NodeId Id) {
308 for (NodeId Child : getNode(Id).Children)
309 PostorderTraverse(Child);
310 PostorderIds[Id] = PostorderId;
311 ++PostorderId;
312 };
313 PostorderTraverse(getRootId());
314 NodesBfs = getSubtreeBfs(*this, getRootId());
315}
316
317void SyntaxTree::Impl::setLeftMostDescendants() {
318 for (NodeId Leaf : Leaves) {
319 getMutableNode(Leaf).LeftMostDescendant = Leaf;
320 NodeId Parent, Cur = Leaf;
321 while ((Parent = getNode(Cur).Parent).isValid() &&
322 getNode(Parent).Children[0] == Cur) {
323 Cur = Parent;
324 getMutableNode(Cur).LeftMostDescendant = Leaf;
325 }
326 }
327}
328
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000329int SyntaxTree::Impl::getNumberOfDescendants(NodeId Id) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000330 return getNode(Id).RightMostDescendant - Id + 1;
331}
332
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000333bool SyntaxTree::Impl::isInSubtree(NodeId Id, NodeId SubtreeRoot) const {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000334 return Id >= SubtreeRoot && Id <= getNode(SubtreeRoot).RightMostDescendant;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000335}
336
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000337int SyntaxTree::Impl::findPositionInParent(NodeId Id, bool Shifted) const {
338 NodeId Parent = getNode(Id).Parent;
339 if (Parent.isInvalid())
340 return 0;
341 const auto &Siblings = getNode(Parent).Children;
342 int Position = 0;
343 for (size_t I = 0, E = Siblings.size(); I < E; ++I) {
344 if (Shifted)
345 Position += getNode(Siblings[I]).Shift;
346 if (Siblings[I] == Id) {
347 Position += I;
348 return Position;
349 }
350 }
351 llvm_unreachable("Node not found in parent's children.");
Johannes Altmanninger69774d62017-08-18 21:26:34 +0000352}
353
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000354std::string SyntaxTree::Impl::getNodeValue(NodeId Id) const {
355 return getNodeValue(getNode(Id));
356}
357
358std::string SyntaxTree::Impl::getNodeValue(const Node &N) const {
359 const DynTypedNode &DTN = N.ASTNode;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000360 if (auto *X = DTN.get<BinaryOperator>())
361 return X->getOpcodeStr();
362 if (auto *X = DTN.get<AccessSpecDecl>()) {
363 CharSourceRange Range(X->getSourceRange(), false);
364 return Lexer::getSourceText(Range, AST.getSourceManager(),
365 AST.getLangOpts());
366 }
367 if (auto *X = DTN.get<IntegerLiteral>()) {
368 SmallString<256> Str;
369 X->getValue().toString(Str, /*Radix=*/10, /*Signed=*/false);
370 return Str.str();
371 }
372 if (auto *X = DTN.get<StringLiteral>())
373 return X->getString();
374 if (auto *X = DTN.get<ValueDecl>())
375 return X->getNameAsString() + "(" + X->getType().getAsString() + ")";
Alex Lorenz04184a62017-07-21 13:18:51 +0000376 if (DTN.get<DeclStmt>() || DTN.get<TranslationUnitDecl>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000377 return "";
378 std::string Value;
379 if (auto *X = DTN.get<DeclRefExpr>()) {
380 if (X->hasQualifier()) {
381 llvm::raw_string_ostream OS(Value);
382 PrintingPolicy PP(AST.getLangOpts());
383 X->getQualifier()->print(OS, PP);
384 }
385 Value += X->getDecl()->getNameAsString();
386 return Value;
387 }
388 if (auto *X = DTN.get<NamedDecl>())
389 Value += X->getNameAsString() + ";";
390 if (auto *X = DTN.get<TypedefNameDecl>())
391 return Value + X->getUnderlyingType().getAsString() + ";";
Alex Lorenz04184a62017-07-21 13:18:51 +0000392 if (DTN.get<NamespaceDecl>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000393 return Value;
394 if (auto *X = DTN.get<TypeDecl>())
395 if (X->getTypeForDecl())
396 Value +=
397 X->getTypeForDecl()->getCanonicalTypeInternal().getAsString() + ";";
Alex Lorenz04184a62017-07-21 13:18:51 +0000398 if (DTN.get<Decl>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000399 return Value;
Alex Lorenz04184a62017-07-21 13:18:51 +0000400 if (DTN.get<Stmt>())
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000401 return "";
402 llvm_unreachable("Fatal: unhandled AST node.\n");
403}
404
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000405/// Identifies a node in a subtree by its postorder offset, starting at 1.
406struct SNodeId {
407 int Id = 0;
408
409 explicit SNodeId(int Id) : Id(Id) {}
410 explicit SNodeId() = default;
411
412 operator int() const { return Id; }
413 SNodeId &operator++() { return ++Id, *this; }
414 SNodeId &operator--() { return --Id, *this; }
415 SNodeId operator+(int Other) const { return SNodeId(Id + Other); }
416};
417
418class Subtree {
419private:
420 /// The parent tree.
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000421 const SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000422 /// Maps SNodeIds to original ids.
423 std::vector<NodeId> RootIds;
424 /// Maps subtree nodes to their leftmost descendants wtihin the subtree.
425 std::vector<SNodeId> LeftMostDescendants;
426
427public:
428 std::vector<SNodeId> KeyRoots;
429
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000430 Subtree(const SyntaxTree::Impl &Tree, NodeId SubtreeRoot) : Tree(Tree) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000431 RootIds = getSubtreePostorder(Tree, SubtreeRoot);
432 int NumLeaves = setLeftMostDescendants();
433 computeKeyRoots(NumLeaves);
434 }
435 int getSize() const { return RootIds.size(); }
436 NodeId getIdInRoot(SNodeId Id) const {
437 assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
438 return RootIds[Id - 1];
439 }
440 const Node &getNode(SNodeId Id) const {
441 return Tree.getNode(getIdInRoot(Id));
442 }
443 SNodeId getLeftMostDescendant(SNodeId Id) const {
444 assert(Id > 0 && Id <= getSize() && "Invalid subtree node index.");
445 return LeftMostDescendants[Id - 1];
446 }
447 /// Returns the postorder index of the leftmost descendant in the subtree.
448 NodeId getPostorderOffset() const {
449 return Tree.PostorderIds[getIdInRoot(SNodeId(1))];
450 }
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000451 std::string getNodeValue(SNodeId Id) const {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000452 return Tree.getNodeValue(getIdInRoot(Id));
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000453 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000454
455private:
456 /// Returns the number of leafs in the subtree.
457 int setLeftMostDescendants() {
458 int NumLeaves = 0;
459 LeftMostDescendants.resize(getSize());
460 for (int I = 0; I < getSize(); ++I) {
461 SNodeId SI(I + 1);
462 const Node &N = getNode(SI);
463 NumLeaves += N.isLeaf();
464 assert(I == Tree.PostorderIds[getIdInRoot(SI)] - getPostorderOffset() &&
465 "Postorder traversal in subtree should correspond to traversal in "
466 "the root tree by a constant offset.");
467 LeftMostDescendants[I] = SNodeId(Tree.PostorderIds[N.LeftMostDescendant] -
468 getPostorderOffset());
469 }
470 return NumLeaves;
471 }
472 void computeKeyRoots(int Leaves) {
473 KeyRoots.resize(Leaves);
474 std::unordered_set<int> Visited;
475 int K = Leaves - 1;
476 for (SNodeId I(getSize()); I > 0; --I) {
477 SNodeId LeftDesc = getLeftMostDescendant(I);
478 if (Visited.count(LeftDesc))
479 continue;
480 assert(K >= 0 && "K should be non-negative");
481 KeyRoots[K] = I;
482 Visited.insert(LeftDesc);
483 --K;
484 }
485 }
486};
487
488/// Implementation of Zhang and Shasha's Algorithm for tree edit distance.
489/// Computes an optimal mapping between two trees using only insertion,
490/// deletion and update as edit actions (similar to the Levenshtein distance).
491class ZhangShashaMatcher {
492 const ASTDiff::Impl &DiffImpl;
493 Subtree S1;
494 Subtree S2;
495 std::unique_ptr<std::unique_ptr<double[]>[]> TreeDist, ForestDist;
496
497public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000498 ZhangShashaMatcher(const ASTDiff::Impl &DiffImpl, const SyntaxTree::Impl &T1,
499 const SyntaxTree::Impl &T2, NodeId Id1, NodeId Id2)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000500 : DiffImpl(DiffImpl), S1(T1, Id1), S2(T2, Id2) {
501 TreeDist = llvm::make_unique<std::unique_ptr<double[]>[]>(
502 size_t(S1.getSize()) + 1);
503 ForestDist = llvm::make_unique<std::unique_ptr<double[]>[]>(
504 size_t(S1.getSize()) + 1);
505 for (int I = 0, E = S1.getSize() + 1; I < E; ++I) {
506 TreeDist[I] = llvm::make_unique<double[]>(size_t(S2.getSize()) + 1);
507 ForestDist[I] = llvm::make_unique<double[]>(size_t(S2.getSize()) + 1);
508 }
509 }
510
511 std::vector<std::pair<NodeId, NodeId>> getMatchingNodes() {
512 std::vector<std::pair<NodeId, NodeId>> Matches;
513 std::vector<std::pair<SNodeId, SNodeId>> TreePairs;
514
515 computeTreeDist();
516
517 bool RootNodePair = true;
518
Alex Lorenz4c0a8662017-07-21 13:04:57 +0000519 TreePairs.emplace_back(SNodeId(S1.getSize()), SNodeId(S2.getSize()));
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000520
521 while (!TreePairs.empty()) {
522 SNodeId LastRow, LastCol, FirstRow, FirstCol, Row, Col;
523 std::tie(LastRow, LastCol) = TreePairs.back();
524 TreePairs.pop_back();
525
526 if (!RootNodePair) {
527 computeForestDist(LastRow, LastCol);
528 }
529
530 RootNodePair = false;
531
532 FirstRow = S1.getLeftMostDescendant(LastRow);
533 FirstCol = S2.getLeftMostDescendant(LastCol);
534
535 Row = LastRow;
536 Col = LastCol;
537
538 while (Row > FirstRow || Col > FirstCol) {
539 if (Row > FirstRow &&
540 ForestDist[Row - 1][Col] + 1 == ForestDist[Row][Col]) {
541 --Row;
542 } else if (Col > FirstCol &&
543 ForestDist[Row][Col - 1] + 1 == ForestDist[Row][Col]) {
544 --Col;
545 } else {
546 SNodeId LMD1 = S1.getLeftMostDescendant(Row);
547 SNodeId LMD2 = S2.getLeftMostDescendant(Col);
548 if (LMD1 == S1.getLeftMostDescendant(LastRow) &&
549 LMD2 == S2.getLeftMostDescendant(LastCol)) {
550 NodeId Id1 = S1.getIdInRoot(Row);
551 NodeId Id2 = S2.getIdInRoot(Col);
552 assert(DiffImpl.isMatchingPossible(Id1, Id2) &&
553 "These nodes must not be matched.");
554 Matches.emplace_back(Id1, Id2);
555 --Row;
556 --Col;
557 } else {
558 TreePairs.emplace_back(Row, Col);
559 Row = LMD1;
560 Col = LMD2;
561 }
562 }
563 }
564 }
565 return Matches;
566 }
567
568private:
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000569 /// We use a simple cost model for edit actions, which seems good enough.
570 /// Simple cost model for edit actions. This seems to make the matching
571 /// algorithm perform reasonably well.
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000572 /// The values range between 0 and 1, or infinity if this edit action should
573 /// always be avoided.
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000574 static constexpr double DeletionCost = 1;
575 static constexpr double InsertionCost = 1;
576
577 double getUpdateCost(SNodeId Id1, SNodeId Id2) {
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000578 if (!DiffImpl.isMatchingPossible(S1.getIdInRoot(Id1), S2.getIdInRoot(Id2)))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000579 return std::numeric_limits<double>::max();
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000580 return S1.getNodeValue(Id1) != S2.getNodeValue(Id2);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000581 }
582
583 void computeTreeDist() {
584 for (SNodeId Id1 : S1.KeyRoots)
585 for (SNodeId Id2 : S2.KeyRoots)
586 computeForestDist(Id1, Id2);
587 }
588
589 void computeForestDist(SNodeId Id1, SNodeId Id2) {
590 assert(Id1 > 0 && Id2 > 0 && "Expecting offsets greater than 0.");
591 SNodeId LMD1 = S1.getLeftMostDescendant(Id1);
592 SNodeId LMD2 = S2.getLeftMostDescendant(Id2);
593
594 ForestDist[LMD1][LMD2] = 0;
595 for (SNodeId D1 = LMD1 + 1; D1 <= Id1; ++D1) {
596 ForestDist[D1][LMD2] = ForestDist[D1 - 1][LMD2] + DeletionCost;
597 for (SNodeId D2 = LMD2 + 1; D2 <= Id2; ++D2) {
598 ForestDist[LMD1][D2] = ForestDist[LMD1][D2 - 1] + InsertionCost;
599 SNodeId DLMD1 = S1.getLeftMostDescendant(D1);
600 SNodeId DLMD2 = S2.getLeftMostDescendant(D2);
601 if (DLMD1 == LMD1 && DLMD2 == LMD2) {
602 double UpdateCost = getUpdateCost(D1, D2);
603 ForestDist[D1][D2] =
604 std::min({ForestDist[D1 - 1][D2] + DeletionCost,
605 ForestDist[D1][D2 - 1] + InsertionCost,
606 ForestDist[D1 - 1][D2 - 1] + UpdateCost});
607 TreeDist[D1][D2] = ForestDist[D1][D2];
608 } else {
609 ForestDist[D1][D2] =
610 std::min({ForestDist[D1 - 1][D2] + DeletionCost,
611 ForestDist[D1][D2 - 1] + InsertionCost,
612 ForestDist[DLMD1][DLMD2] + TreeDist[D1][D2]});
613 }
614 }
615 }
616 }
617};
618
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000619ast_type_traits::ASTNodeKind Node::getType() const {
620 return ASTNode.getNodeKind();
621}
622
623StringRef Node::getTypeLabel() const { return getType().asStringRef(); }
624
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000625namespace {
626// Compares nodes by their depth.
627struct HeightLess {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000628 const SyntaxTree::Impl &Tree;
629 HeightLess(const SyntaxTree::Impl &Tree) : Tree(Tree) {}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000630 bool operator()(NodeId Id1, NodeId Id2) const {
631 return Tree.getNode(Id1).Height < Tree.getNode(Id2).Height;
632 }
633};
634} // end anonymous namespace
635
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000636namespace {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000637// Priority queue for nodes, sorted descendingly by their height.
638class PriorityList {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000639 const SyntaxTree::Impl &Tree;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000640 HeightLess Cmp;
641 std::vector<NodeId> Container;
642 PriorityQueue<NodeId, std::vector<NodeId>, HeightLess> List;
643
644public:
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000645 PriorityList(const SyntaxTree::Impl &Tree)
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000646 : Tree(Tree), Cmp(Tree), List(Cmp, Container) {}
647
648 void push(NodeId id) { List.push(id); }
649
650 std::vector<NodeId> pop() {
651 int Max = peekMax();
652 std::vector<NodeId> Result;
653 if (Max == 0)
654 return Result;
655 while (peekMax() == Max) {
656 Result.push_back(List.top());
657 List.pop();
658 }
659 // TODO this is here to get a stable output, not a good heuristic
660 std::sort(Result.begin(), Result.end());
661 return Result;
662 }
663 int peekMax() const {
664 if (List.empty())
665 return 0;
666 return Tree.getNode(List.top()).Height;
667 }
668 void open(NodeId Id) {
669 for (NodeId Child : Tree.getNode(Id).Children)
670 push(Child);
671 }
672};
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000673} // end anonymous namespace
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000674
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000675bool ASTDiff::Impl::identical(NodeId Id1, NodeId Id2) const {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000676 const Node &N1 = T1.getNode(Id1);
677 const Node &N2 = T2.getNode(Id2);
678 if (N1.Children.size() != N2.Children.size() ||
679 !isMatchingPossible(Id1, Id2) ||
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000680 T1.getNodeValue(Id1) != T2.getNodeValue(Id2))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000681 return false;
682 for (size_t Id = 0, E = N1.Children.size(); Id < E; ++Id)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000683 if (!identical(N1.Children[Id], N2.Children[Id]))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000684 return false;
685 return true;
686}
687
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000688bool ASTDiff::Impl::isMatchingPossible(NodeId Id1, NodeId Id2) const {
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000689 return Options.isMatchingAllowed(T1.getNode(Id1), T2.getNode(Id2));
690}
691
692bool ASTDiff::Impl::haveSameParents(const Mapping &M, NodeId Id1,
693 NodeId Id2) const {
694 NodeId P1 = T1.getNode(Id1).Parent;
695 NodeId P2 = T2.getNode(Id2).Parent;
696 return (P1.isInvalid() && P2.isInvalid()) ||
697 (P1.isValid() && P2.isValid() && M.getDst(P1) == P2);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000698}
699
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000700void ASTDiff::Impl::addOptimalMapping(Mapping &M, NodeId Id1,
701 NodeId Id2) const {
702 if (std::max(T1.getNumberOfDescendants(Id1),
703 T2.getNumberOfDescendants(Id2)) >= Options.MaxSize)
704 return;
705 ZhangShashaMatcher Matcher(*this, T1, T2, Id1, Id2);
706 std::vector<std::pair<NodeId, NodeId>> R = Matcher.getMatchingNodes();
707 for (const auto Tuple : R) {
708 NodeId Src = Tuple.first;
709 NodeId Dst = Tuple.second;
Johannes Altmanninger51321ae2017-08-19 17:53:01 +0000710 if (!M.hasSrc(Src) && !M.hasDst(Dst))
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000711 M.link(Src, Dst);
712 }
713}
714
715double ASTDiff::Impl::getSimilarity(const Mapping &M, NodeId Id1,
716 NodeId Id2) const {
717 if (Id1.isInvalid() || Id2.isInvalid())
718 return 0.0;
719 int CommonDescendants = 0;
720 const Node &N1 = T1.getNode(Id1);
721 for (NodeId Id = Id1 + 1; Id <= N1.RightMostDescendant; ++Id)
722 CommonDescendants += int(T2.isInSubtree(M.getDst(Id), Id2));
723 return 2.0 * CommonDescendants /
724 (T1.getNumberOfDescendants(Id1) + T2.getNumberOfDescendants(Id2));
725}
726
727NodeId ASTDiff::Impl::findCandidate(const Mapping &M, NodeId Id1) const {
728 NodeId Candidate;
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000729 double HighestSimilarity = 0.0;
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000730 for (NodeId Id2 : T2) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000731 if (!isMatchingPossible(Id1, Id2))
732 continue;
733 if (M.hasDst(Id2))
734 continue;
735 double Similarity = getSimilarity(M, Id1, Id2);
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000736 if (Similarity >= Options.MinSimilarity && Similarity > HighestSimilarity) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000737 HighestSimilarity = Similarity;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000738 Candidate = Id2;
739 }
740 }
741 return Candidate;
742}
743
744void ASTDiff::Impl::matchBottomUp(Mapping &M) const {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000745 std::vector<NodeId> Postorder = getSubtreePostorder(T1, T1.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000746 for (NodeId Id1 : Postorder) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000747 if (Id1 == T1.getRootId() && !M.hasSrc(T1.getRootId()) &&
748 !M.hasDst(T2.getRootId())) {
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000749 if (isMatchingPossible(T1.getRootId(), T2.getRootId())) {
750 M.link(T1.getRootId(), T2.getRootId());
751 addOptimalMapping(M, T1.getRootId(), T2.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000752 }
753 break;
754 }
755 const Node &N1 = T1.getNode(Id1);
756 bool Matched = M.hasSrc(Id1);
757 bool MatchedChildren =
758 std::any_of(N1.Children.begin(), N1.Children.end(),
759 [&](NodeId Child) { return M.hasSrc(Child); });
760 if (Matched || !MatchedChildren)
761 continue;
762 NodeId Id2 = findCandidate(M, Id1);
Johannes Altmanninger51321ae2017-08-19 17:53:01 +0000763 if (Id2.isValid()) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000764 M.link(Id1, Id2);
765 addOptimalMapping(M, Id1, Id2);
766 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000767 }
768}
769
770Mapping ASTDiff::Impl::matchTopDown() const {
771 PriorityList L1(T1);
772 PriorityList L2(T2);
773
Johannes Altmanninger51321ae2017-08-19 17:53:01 +0000774 Mapping M(T1.getSize() + T2.getSize());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000775
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000776 L1.push(T1.getRootId());
777 L2.push(T2.getRootId());
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000778
779 int Max1, Max2;
780 while (std::min(Max1 = L1.peekMax(), Max2 = L2.peekMax()) >
781 Options.MinHeight) {
782 if (Max1 > Max2) {
783 for (NodeId Id : L1.pop())
784 L1.open(Id);
785 continue;
786 }
787 if (Max2 > Max1) {
788 for (NodeId Id : L2.pop())
789 L2.open(Id);
790 continue;
791 }
792 std::vector<NodeId> H1, H2;
793 H1 = L1.pop();
794 H2 = L2.pop();
795 for (NodeId Id1 : H1) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000796 for (NodeId Id2 : H2) {
Johannes Altmanninger51321ae2017-08-19 17:53:01 +0000797 if (identical(Id1, Id2) && !M.hasSrc(Id1) && !M.hasDst(Id2)) {
Johannes Altmanningerfa524d72017-08-18 16:34:15 +0000798 for (int I = 0, E = T1.getNumberOfDescendants(Id1); I < E; ++I)
799 M.link(Id1 + I, Id2 + I);
800 }
801 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000802 }
803 for (NodeId Id1 : H1) {
804 if (!M.hasSrc(Id1))
805 L1.open(Id1);
806 }
807 for (NodeId Id2 : H2) {
808 if (!M.hasDst(Id2))
809 L2.open(Id2);
810 }
811 }
812 return M;
813}
814
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000815ASTDiff::Impl::Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2,
816 const ComparisonOptions &Options)
817 : T1(T1), T2(T2), Options(Options) {
818 computeMapping();
819 computeChangeKinds(TheMapping);
820}
821
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000822void ASTDiff::Impl::computeMapping() {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000823 TheMapping = matchTopDown();
824 matchBottomUp(TheMapping);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000825}
826
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000827void ASTDiff::Impl::computeChangeKinds(Mapping &M) {
828 for (NodeId Id1 : T1) {
829 if (!M.hasSrc(Id1)) {
830 T1.getMutableNode(Id1).Change = Delete;
831 T1.getMutableNode(Id1).Shift -= 1;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000832 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000833 }
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000834 for (NodeId Id2 : T2) {
835 if (!M.hasDst(Id2)) {
836 T2.getMutableNode(Id2).Change = Insert;
837 T2.getMutableNode(Id2).Shift -= 1;
838 }
839 }
840 for (NodeId Id1 : T1.NodesBfs) {
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000841 NodeId Id2 = M.getDst(Id1);
842 if (Id2.isInvalid())
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000843 continue;
844 if (!haveSameParents(M, Id1, Id2) ||
845 T1.findPositionInParent(Id1, true) !=
846 T2.findPositionInParent(Id2, true)) {
847 T1.getMutableNode(Id1).Shift -= 1;
848 T2.getMutableNode(Id2).Shift -= 1;
849 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000850 }
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000851 for (NodeId Id2 : T2.NodesBfs) {
852 NodeId Id1 = M.getSrc(Id2);
853 if (Id1.isInvalid())
854 continue;
855 Node &N1 = T1.getMutableNode(Id1);
856 Node &N2 = T2.getMutableNode(Id2);
857 if (Id1.isInvalid())
858 continue;
859 if (!haveSameParents(M, Id1, Id2) ||
860 T1.findPositionInParent(Id1, true) !=
861 T2.findPositionInParent(Id2, true)) {
862 N1.Change = N2.Change = Move;
863 }
864 if (T1.getNodeValue(Id1) != T2.getNodeValue(Id2)) {
865 N1.Change = N2.Change = (N1.Change == Move ? UpdateMove : Update);
866 }
867 }
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000868}
869
870ASTDiff::ASTDiff(SyntaxTree &T1, SyntaxTree &T2,
871 const ComparisonOptions &Options)
872 : DiffImpl(llvm::make_unique<Impl>(*T1.TreeImpl, *T2.TreeImpl, Options)) {}
873
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000874ASTDiff::~ASTDiff() = default;
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000875
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000876NodeId ASTDiff::getMapped(const SyntaxTree &SourceTree, NodeId Id) const {
877 return DiffImpl->getMapped(SourceTree.TreeImpl, Id);
878}
879
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000880SyntaxTree::SyntaxTree(const ASTContext &AST)
Johannes Altmanninger31b52d62017-08-01 20:17:46 +0000881 : TreeImpl(llvm::make_unique<SyntaxTree::Impl>(
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000882 this, AST.getTranslationUnitDecl(), AST)) {}
883
Johannes Altmanninger8b0e0662017-08-01 20:17:40 +0000884SyntaxTree::~SyntaxTree() = default;
885
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000886const ASTContext &SyntaxTree::getASTContext() const { return TreeImpl->AST; }
887
888const Node &SyntaxTree::getNode(NodeId Id) const {
889 return TreeImpl->getNode(Id);
890}
891
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000892int SyntaxTree::getSize() const { return TreeImpl->getSize(); }
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000893NodeId SyntaxTree::getRootId() const { return TreeImpl->getRootId(); }
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000894SyntaxTree::PreorderIterator SyntaxTree::begin() const {
895 return TreeImpl->begin();
896}
897SyntaxTree::PreorderIterator SyntaxTree::end() const { return TreeImpl->end(); }
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000898
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000899int SyntaxTree::findPositionInParent(NodeId Id) const {
900 return TreeImpl->findPositionInParent(Id);
901}
902
903std::pair<unsigned, unsigned>
904SyntaxTree::getSourceRangeOffsets(const Node &N) const {
Johannes Altmanninger0da12c82017-08-19 00:57:38 +0000905 const SourceManager &SrcMgr = TreeImpl->AST.getSourceManager();
906 SourceRange Range = N.ASTNode.getSourceRange();
907 SourceLocation BeginLoc = Range.getBegin();
908 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
909 Range.getEnd(), /*Offset=*/0, SrcMgr, TreeImpl->AST.getLangOpts());
910 if (auto *ThisExpr = N.ASTNode.get<CXXThisExpr>()) {
911 if (ThisExpr->isImplicit())
912 EndLoc = BeginLoc;
913 }
914 unsigned Begin = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(BeginLoc));
915 unsigned End = SrcMgr.getFileOffset(SrcMgr.getExpansionLoc(EndLoc));
916 return {Begin, End};
917}
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000918
Johannes Altmanningere0fe5cd2017-08-19 02:56:35 +0000919std::string SyntaxTree::getNodeValue(NodeId Id) const {
920 return TreeImpl->getNodeValue(Id);
921}
922
923std::string SyntaxTree::getNodeValue(const Node &N) const {
924 return TreeImpl->getNodeValue(N);
Alex Lorenza75b2ca2017-07-21 12:49:28 +0000925}
926
927} // end namespace diff
928} // end namespace clang