Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 1 | //===- ASTDiff.cpp - AST differencing implementation-----------*- C++ -*- -===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file contains definitons for the AST differencing interface. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "clang/Tooling/ASTDiff/ASTDiff.h" |
| 15 | |
| 16 | #include "clang/AST/RecursiveASTVisitor.h" |
| 17 | #include "clang/Lex/Lexer.h" |
| 18 | #include "llvm/ADT/PriorityQueue.h" |
| 19 | |
| 20 | #include <limits> |
| 21 | #include <memory> |
| 22 | #include <unordered_set> |
| 23 | |
| 24 | using namespace llvm; |
| 25 | using namespace clang; |
| 26 | |
| 27 | namespace clang { |
| 28 | namespace diff { |
| 29 | |
Johannes Altmanninger | fa524d7 | 2017-08-18 16:34:15 +0000 | [diff] [blame] | 30 | namespace { |
Johannes Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 31 | /// Maps nodes of the left tree to ones on the right, and vice versa. |
| 32 | class Mapping { |
| 33 | public: |
| 34 | Mapping() = default; |
| 35 | Mapping(Mapping &&Other) = default; |
| 36 | Mapping &operator=(Mapping &&Other) = default; |
| 37 | 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 | |
| 77 | private: |
| 78 | std::unique_ptr<SmallVector<NodeId, 2>[]> SrcToDst, DstToSrc; |
| 79 | }; |
Johannes Altmanninger | fa524d7 | 2017-08-18 16:34:15 +0000 | [diff] [blame] | 80 | } // end anonymous namespace |
Johannes Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 81 | |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 82 | class ASTDiff::Impl { |
| 83 | public: |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 84 | SyntaxTree::Impl &T1, &T2; |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 85 | bool IsMappingDone = false; |
| 86 | Mapping TheMapping; |
| 87 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 88 | Impl(SyntaxTree::Impl &T1, SyntaxTree::Impl &T2, |
| 89 | const ComparisonOptions &Options) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 90 | : 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 103 | // Returns a mapping of identical subtrees. |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 104 | Mapping matchTopDown() const; |
| 105 | |
| 106 | private: |
| 107 | // Returns true if the two subtrees are identical. |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 108 | bool identical(NodeId Id1, NodeId Id2) const; |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 109 | |
| 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 Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 115 | // 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 Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 134 | /// Represents the AST of a TranslationUnit. |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 135 | class SyntaxTree::Impl { |
Johannes Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 136 | public: |
| 137 | /// Constructs a tree from the entire translation unit. |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 138 | Impl(SyntaxTree *Parent, const ASTContext &AST); |
Johannes Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 139 | /// Constructs a tree from an AST node. |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 140 | Impl(SyntaxTree *Parent, Decl *N, const ASTContext &AST); |
| 141 | Impl(SyntaxTree *Parent, Stmt *N, const ASTContext &AST); |
Johannes Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 142 | template <class T> |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 143 | 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 Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 147 | template <class T> |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 148 | 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 Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 152 | |
| 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 160 | NodeId getRootId() const { return 0; } |
Johannes Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 161 | |
| 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 169 | std::string getNodeValue(NodeId Id) const; |
| 170 | std::string getNodeValue(const DynTypedNode &DTN) const; |
Johannes Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 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; |
| 178 | |
| 179 | void printAsJsonImpl(raw_ostream &OS) const; |
| 180 | void printNodeAsJson(raw_ostream &OS, NodeId Id) const; |
| 181 | |
| 182 | private: |
| 183 | /// Nodes in preorder. |
| 184 | std::vector<Node> Nodes; |
| 185 | |
| 186 | void initTree(); |
| 187 | void setLeftMostDescendants(); |
| 188 | }; |
| 189 | |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 190 | template <class T> |
| 191 | static 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 | |
| 198 | namespace { |
| 199 | /// Counts the number of nodes that will be compared. |
| 200 | struct NodeCountVisitor : public RecursiveASTVisitor<NodeCountVisitor> { |
| 201 | int Count = 0; |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 202 | const SyntaxTree::Impl &Tree; |
| 203 | NodeCountVisitor(const SyntaxTree::Impl &Tree) : Tree(Tree) {} |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 204 | bool TraverseDecl(Decl *D) { |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 205 | if (isNodeExcluded(Tree.AST.getSourceManager(), D)) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 206 | return true; |
| 207 | ++Count; |
| 208 | RecursiveASTVisitor<NodeCountVisitor>::TraverseDecl(D); |
| 209 | return true; |
| 210 | } |
| 211 | bool TraverseStmt(Stmt *S) { |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 212 | if (isNodeExcluded(Tree.AST.getSourceManager(), S)) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 213 | 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 | |
| 222 | namespace { |
| 223 | // Sets Height, Parent and Children for each node. |
| 224 | struct PreorderVisitor : public RecursiveASTVisitor<PreorderVisitor> { |
| 225 | int Id = 0, Depth = 0; |
| 226 | NodeId Parent; |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 227 | SyntaxTree::Impl &Tree; |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 228 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 229 | PreorderVisitor(SyntaxTree::Impl &Tree) : Tree(Tree) {} |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 230 | |
| 231 | template <class T> std::tuple<NodeId, NodeId> PreTraverse(T *ASTNode) { |
| 232 | NodeId MyId = Id; |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 233 | Node &N = Tree.getMutableNode(MyId); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 234 | 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 240 | Node &P = Tree.getMutableNode(Parent); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 241 | P.Children.push_back(MyId); |
| 242 | } |
| 243 | Parent = MyId; |
| 244 | ++Id; |
| 245 | ++Depth; |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 246 | return std::make_tuple(MyId, Tree.getNode(MyId).Parent); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 247 | } |
| 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 254 | Node &N = Tree.getMutableNode(MyId); |
Johannes Altmanninger | fa524d7 | 2017-08-18 16:34:15 +0000 | [diff] [blame] | 255 | N.RightMostDescendant = Id - 1; |
| 256 | assert(N.RightMostDescendant >= 0 && |
| 257 | N.RightMostDescendant < Tree.getSize() && |
| 258 | "Rightmost descendant must be a valid tree node."); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 259 | if (N.isLeaf()) |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 260 | Tree.Leaves.push_back(MyId); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 261 | N.Height = 1; |
| 262 | for (NodeId Child : N.Children) |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 263 | N.Height = std::max(N.Height, 1 + Tree.getNode(Child).Height); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 264 | } |
| 265 | bool TraverseDecl(Decl *D) { |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 266 | if (isNodeExcluded(Tree.AST.getSourceManager(), D)) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 267 | 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 274 | if (isNodeExcluded(Tree.AST.getSourceManager(), S)) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 275 | 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 285 | SyntaxTree::Impl::Impl(SyntaxTree *Parent, const ASTContext &AST) |
| 286 | : Impl(Parent, AST.getTranslationUnitDecl(), AST) {} |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 287 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 288 | SyntaxTree::Impl::Impl(SyntaxTree *Parent, Decl *N, const ASTContext &AST) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 289 | : 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 298 | SyntaxTree::Impl::Impl(SyntaxTree *Parent, Stmt *N, const ASTContext &AST) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 299 | : 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 308 | void SyntaxTree::Impl::initTree() { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 309 | 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 318 | PostorderTraverse(getRootId()); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 319 | } |
| 320 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 321 | void SyntaxTree::Impl::setLeftMostDescendants() { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 322 | 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 333 | static std::vector<NodeId> getSubtreePostorder(const SyntaxTree::Impl &Tree, |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 334 | 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 346 | static std::vector<NodeId> getSubtreeBfs(const SyntaxTree::Impl &Tree, |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 347 | 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 357 | int SyntaxTree::Impl::getNumberOfDescendants(NodeId Id) const { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 358 | return getNode(Id).RightMostDescendant - Id + 1; |
| 359 | } |
| 360 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 361 | bool SyntaxTree::Impl::isInSubtree(NodeId Id, NodeId SubtreeRoot) const { |
Johannes Altmanninger | fa524d7 | 2017-08-18 16:34:15 +0000 | [diff] [blame] | 362 | return Id >= SubtreeRoot && Id <= getNode(SubtreeRoot).RightMostDescendant; |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 363 | } |
| 364 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 365 | std::string SyntaxTree::Impl::getNodeValue(NodeId Id) const { |
| 366 | return getNodeValue(getNode(Id).ASTNode); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 367 | } |
| 368 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 369 | std::string SyntaxTree::Impl::getNodeValue(const DynTypedNode &DTN) const { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 370 | 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 Lorenz | 04184a6 | 2017-07-21 13:18:51 +0000 | [diff] [blame] | 386 | if (DTN.get<DeclStmt>() || DTN.get<TranslationUnitDecl>()) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 387 | 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 Lorenz | 04184a6 | 2017-07-21 13:18:51 +0000 | [diff] [blame] | 402 | if (DTN.get<NamespaceDecl>()) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 403 | return Value; |
| 404 | if (auto *X = DTN.get<TypeDecl>()) |
| 405 | if (X->getTypeForDecl()) |
| 406 | Value += |
| 407 | X->getTypeForDecl()->getCanonicalTypeInternal().getAsString() + ";"; |
Alex Lorenz | 04184a6 | 2017-07-21 13:18:51 +0000 | [diff] [blame] | 408 | if (DTN.get<Decl>()) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 409 | return Value; |
Alex Lorenz | 04184a6 | 2017-07-21 13:18:51 +0000 | [diff] [blame] | 410 | if (DTN.get<Stmt>()) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 411 | return ""; |
| 412 | llvm_unreachable("Fatal: unhandled AST node.\n"); |
| 413 | } |
| 414 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 415 | void SyntaxTree::Impl::printTree() const { printTree(getRootId()); } |
| 416 | void SyntaxTree::Impl::printTree(NodeId Root) const { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 417 | printTree(llvm::outs(), Root); |
| 418 | } |
| 419 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 420 | void SyntaxTree::Impl::printTree(raw_ostream &OS, NodeId Root) const { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 421 | 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 430 | void SyntaxTree::Impl::printNode(raw_ostream &OS, NodeId Id) const { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 431 | if (Id.isInvalid()) { |
| 432 | OS << "None"; |
| 433 | return; |
| 434 | } |
| 435 | OS << getNode(Id).getTypeLabel(); |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 436 | if (getNodeValue(Id) != "") |
| 437 | OS << ": " << getNodeValue(Id); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 438 | OS << "(" << PostorderIds[Id] << ")"; |
| 439 | } |
| 440 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 441 | void SyntaxTree::Impl::printNodeAsJson(raw_ostream &OS, NodeId Id) const { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 442 | auto N = getNode(Id); |
| 443 | OS << R"({"type":")" << N.getTypeLabel() << R"(")"; |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 444 | if (getNodeValue(Id) != "") |
| 445 | OS << R"(,"value":")" << getNodeValue(Id) << R"(")"; |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 446 | 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 457 | void SyntaxTree::Impl::printAsJsonImpl(raw_ostream &OS) const { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 458 | OS << R"({"root":)"; |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 459 | printNodeAsJson(OS, getRootId()); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 460 | OS << "}\n"; |
| 461 | } |
| 462 | |
| 463 | /// Identifies a node in a subtree by its postorder offset, starting at 1. |
| 464 | struct SNodeId { |
| 465 | int Id = 0; |
| 466 | |
| 467 | explicit SNodeId(int Id) : Id(Id) {} |
| 468 | explicit SNodeId() = default; |
| 469 | |
| 470 | operator int() const { return Id; } |
| 471 | SNodeId &operator++() { return ++Id, *this; } |
| 472 | SNodeId &operator--() { return --Id, *this; } |
| 473 | SNodeId operator+(int Other) const { return SNodeId(Id + Other); } |
| 474 | }; |
| 475 | |
| 476 | class Subtree { |
| 477 | private: |
| 478 | /// The parent tree. |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 479 | const SyntaxTree::Impl &Tree; |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 480 | /// Maps SNodeIds to original ids. |
| 481 | std::vector<NodeId> RootIds; |
| 482 | /// Maps subtree nodes to their leftmost descendants wtihin the subtree. |
| 483 | std::vector<SNodeId> LeftMostDescendants; |
| 484 | |
| 485 | public: |
| 486 | std::vector<SNodeId> KeyRoots; |
| 487 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 488 | Subtree(const SyntaxTree::Impl &Tree, NodeId SubtreeRoot) : Tree(Tree) { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 489 | RootIds = getSubtreePostorder(Tree, SubtreeRoot); |
| 490 | int NumLeaves = setLeftMostDescendants(); |
| 491 | computeKeyRoots(NumLeaves); |
| 492 | } |
| 493 | int getSize() const { return RootIds.size(); } |
| 494 | NodeId getIdInRoot(SNodeId Id) const { |
| 495 | assert(Id > 0 && Id <= getSize() && "Invalid subtree node index."); |
| 496 | return RootIds[Id - 1]; |
| 497 | } |
| 498 | const Node &getNode(SNodeId Id) const { |
| 499 | return Tree.getNode(getIdInRoot(Id)); |
| 500 | } |
| 501 | SNodeId getLeftMostDescendant(SNodeId Id) const { |
| 502 | assert(Id > 0 && Id <= getSize() && "Invalid subtree node index."); |
| 503 | return LeftMostDescendants[Id - 1]; |
| 504 | } |
| 505 | /// Returns the postorder index of the leftmost descendant in the subtree. |
| 506 | NodeId getPostorderOffset() const { |
| 507 | return Tree.PostorderIds[getIdInRoot(SNodeId(1))]; |
| 508 | } |
Johannes Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 509 | std::string getNodeValue(SNodeId Id) const { |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 510 | return Tree.getNodeValue(getIdInRoot(Id)); |
Johannes Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 511 | } |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 512 | |
| 513 | private: |
| 514 | /// Returns the number of leafs in the subtree. |
| 515 | int setLeftMostDescendants() { |
| 516 | int NumLeaves = 0; |
| 517 | LeftMostDescendants.resize(getSize()); |
| 518 | for (int I = 0; I < getSize(); ++I) { |
| 519 | SNodeId SI(I + 1); |
| 520 | const Node &N = getNode(SI); |
| 521 | NumLeaves += N.isLeaf(); |
| 522 | assert(I == Tree.PostorderIds[getIdInRoot(SI)] - getPostorderOffset() && |
| 523 | "Postorder traversal in subtree should correspond to traversal in " |
| 524 | "the root tree by a constant offset."); |
| 525 | LeftMostDescendants[I] = SNodeId(Tree.PostorderIds[N.LeftMostDescendant] - |
| 526 | getPostorderOffset()); |
| 527 | } |
| 528 | return NumLeaves; |
| 529 | } |
| 530 | void computeKeyRoots(int Leaves) { |
| 531 | KeyRoots.resize(Leaves); |
| 532 | std::unordered_set<int> Visited; |
| 533 | int K = Leaves - 1; |
| 534 | for (SNodeId I(getSize()); I > 0; --I) { |
| 535 | SNodeId LeftDesc = getLeftMostDescendant(I); |
| 536 | if (Visited.count(LeftDesc)) |
| 537 | continue; |
| 538 | assert(K >= 0 && "K should be non-negative"); |
| 539 | KeyRoots[K] = I; |
| 540 | Visited.insert(LeftDesc); |
| 541 | --K; |
| 542 | } |
| 543 | } |
| 544 | }; |
| 545 | |
| 546 | /// Implementation of Zhang and Shasha's Algorithm for tree edit distance. |
| 547 | /// Computes an optimal mapping between two trees using only insertion, |
| 548 | /// deletion and update as edit actions (similar to the Levenshtein distance). |
| 549 | class ZhangShashaMatcher { |
| 550 | const ASTDiff::Impl &DiffImpl; |
| 551 | Subtree S1; |
| 552 | Subtree S2; |
| 553 | std::unique_ptr<std::unique_ptr<double[]>[]> TreeDist, ForestDist; |
| 554 | |
| 555 | public: |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 556 | ZhangShashaMatcher(const ASTDiff::Impl &DiffImpl, const SyntaxTree::Impl &T1, |
| 557 | const SyntaxTree::Impl &T2, NodeId Id1, NodeId Id2) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 558 | : DiffImpl(DiffImpl), S1(T1, Id1), S2(T2, Id2) { |
| 559 | TreeDist = llvm::make_unique<std::unique_ptr<double[]>[]>( |
| 560 | size_t(S1.getSize()) + 1); |
| 561 | ForestDist = llvm::make_unique<std::unique_ptr<double[]>[]>( |
| 562 | size_t(S1.getSize()) + 1); |
| 563 | for (int I = 0, E = S1.getSize() + 1; I < E; ++I) { |
| 564 | TreeDist[I] = llvm::make_unique<double[]>(size_t(S2.getSize()) + 1); |
| 565 | ForestDist[I] = llvm::make_unique<double[]>(size_t(S2.getSize()) + 1); |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | std::vector<std::pair<NodeId, NodeId>> getMatchingNodes() { |
| 570 | std::vector<std::pair<NodeId, NodeId>> Matches; |
| 571 | std::vector<std::pair<SNodeId, SNodeId>> TreePairs; |
| 572 | |
| 573 | computeTreeDist(); |
| 574 | |
| 575 | bool RootNodePair = true; |
| 576 | |
Alex Lorenz | 4c0a866 | 2017-07-21 13:04:57 +0000 | [diff] [blame] | 577 | TreePairs.emplace_back(SNodeId(S1.getSize()), SNodeId(S2.getSize())); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 578 | |
| 579 | while (!TreePairs.empty()) { |
| 580 | SNodeId LastRow, LastCol, FirstRow, FirstCol, Row, Col; |
| 581 | std::tie(LastRow, LastCol) = TreePairs.back(); |
| 582 | TreePairs.pop_back(); |
| 583 | |
| 584 | if (!RootNodePair) { |
| 585 | computeForestDist(LastRow, LastCol); |
| 586 | } |
| 587 | |
| 588 | RootNodePair = false; |
| 589 | |
| 590 | FirstRow = S1.getLeftMostDescendant(LastRow); |
| 591 | FirstCol = S2.getLeftMostDescendant(LastCol); |
| 592 | |
| 593 | Row = LastRow; |
| 594 | Col = LastCol; |
| 595 | |
| 596 | while (Row > FirstRow || Col > FirstCol) { |
| 597 | if (Row > FirstRow && |
| 598 | ForestDist[Row - 1][Col] + 1 == ForestDist[Row][Col]) { |
| 599 | --Row; |
| 600 | } else if (Col > FirstCol && |
| 601 | ForestDist[Row][Col - 1] + 1 == ForestDist[Row][Col]) { |
| 602 | --Col; |
| 603 | } else { |
| 604 | SNodeId LMD1 = S1.getLeftMostDescendant(Row); |
| 605 | SNodeId LMD2 = S2.getLeftMostDescendant(Col); |
| 606 | if (LMD1 == S1.getLeftMostDescendant(LastRow) && |
| 607 | LMD2 == S2.getLeftMostDescendant(LastCol)) { |
| 608 | NodeId Id1 = S1.getIdInRoot(Row); |
| 609 | NodeId Id2 = S2.getIdInRoot(Col); |
| 610 | assert(DiffImpl.isMatchingPossible(Id1, Id2) && |
| 611 | "These nodes must not be matched."); |
| 612 | Matches.emplace_back(Id1, Id2); |
| 613 | --Row; |
| 614 | --Col; |
| 615 | } else { |
| 616 | TreePairs.emplace_back(Row, Col); |
| 617 | Row = LMD1; |
| 618 | Col = LMD2; |
| 619 | } |
| 620 | } |
| 621 | } |
| 622 | } |
| 623 | return Matches; |
| 624 | } |
| 625 | |
| 626 | private: |
Johannes Altmanninger | fa524d7 | 2017-08-18 16:34:15 +0000 | [diff] [blame] | 627 | /// We use a simple cost model for edit actions, which seems good enough. |
| 628 | /// Simple cost model for edit actions. This seems to make the matching |
| 629 | /// algorithm perform reasonably well. |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 630 | /// The values range between 0 and 1, or infinity if this edit action should |
| 631 | /// always be avoided. |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 632 | static constexpr double DeletionCost = 1; |
| 633 | static constexpr double InsertionCost = 1; |
| 634 | |
| 635 | double getUpdateCost(SNodeId Id1, SNodeId Id2) { |
Johannes Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 636 | if (!DiffImpl.isMatchingPossible(S1.getIdInRoot(Id1), S2.getIdInRoot(Id2))) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 637 | return std::numeric_limits<double>::max(); |
Johannes Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 638 | return S1.getNodeValue(Id1) != S2.getNodeValue(Id2); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 639 | } |
| 640 | |
| 641 | void computeTreeDist() { |
| 642 | for (SNodeId Id1 : S1.KeyRoots) |
| 643 | for (SNodeId Id2 : S2.KeyRoots) |
| 644 | computeForestDist(Id1, Id2); |
| 645 | } |
| 646 | |
| 647 | void computeForestDist(SNodeId Id1, SNodeId Id2) { |
| 648 | assert(Id1 > 0 && Id2 > 0 && "Expecting offsets greater than 0."); |
| 649 | SNodeId LMD1 = S1.getLeftMostDescendant(Id1); |
| 650 | SNodeId LMD2 = S2.getLeftMostDescendant(Id2); |
| 651 | |
| 652 | ForestDist[LMD1][LMD2] = 0; |
| 653 | for (SNodeId D1 = LMD1 + 1; D1 <= Id1; ++D1) { |
| 654 | ForestDist[D1][LMD2] = ForestDist[D1 - 1][LMD2] + DeletionCost; |
| 655 | for (SNodeId D2 = LMD2 + 1; D2 <= Id2; ++D2) { |
| 656 | ForestDist[LMD1][D2] = ForestDist[LMD1][D2 - 1] + InsertionCost; |
| 657 | SNodeId DLMD1 = S1.getLeftMostDescendant(D1); |
| 658 | SNodeId DLMD2 = S2.getLeftMostDescendant(D2); |
| 659 | if (DLMD1 == LMD1 && DLMD2 == LMD2) { |
| 660 | double UpdateCost = getUpdateCost(D1, D2); |
| 661 | ForestDist[D1][D2] = |
| 662 | std::min({ForestDist[D1 - 1][D2] + DeletionCost, |
| 663 | ForestDist[D1][D2 - 1] + InsertionCost, |
| 664 | ForestDist[D1 - 1][D2 - 1] + UpdateCost}); |
| 665 | TreeDist[D1][D2] = ForestDist[D1][D2]; |
| 666 | } else { |
| 667 | ForestDist[D1][D2] = |
| 668 | std::min({ForestDist[D1 - 1][D2] + DeletionCost, |
| 669 | ForestDist[D1][D2 - 1] + InsertionCost, |
| 670 | ForestDist[DLMD1][DLMD2] + TreeDist[D1][D2]}); |
| 671 | } |
| 672 | } |
| 673 | } |
| 674 | } |
| 675 | }; |
| 676 | |
| 677 | namespace { |
| 678 | // Compares nodes by their depth. |
| 679 | struct HeightLess { |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 680 | const SyntaxTree::Impl &Tree; |
| 681 | HeightLess(const SyntaxTree::Impl &Tree) : Tree(Tree) {} |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 682 | 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 Altmanninger | fa524d7 | 2017-08-18 16:34:15 +0000 | [diff] [blame] | 688 | namespace { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 689 | // Priority queue for nodes, sorted descendingly by their height. |
| 690 | class PriorityList { |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 691 | const SyntaxTree::Impl &Tree; |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 692 | HeightLess Cmp; |
| 693 | std::vector<NodeId> Container; |
| 694 | PriorityQueue<NodeId, std::vector<NodeId>, HeightLess> List; |
| 695 | |
| 696 | public: |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 697 | PriorityList(const SyntaxTree::Impl &Tree) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 698 | : 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 Altmanninger | fa524d7 | 2017-08-18 16:34:15 +0000 | [diff] [blame] | 725 | } // end anonymous namespace |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 726 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 727 | bool ASTDiff::Impl::identical(NodeId Id1, NodeId Id2) const { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 728 | 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 732 | T1.getNodeValue(Id1) != T2.getNodeValue(Id2)) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 733 | return false; |
| 734 | for (size_t Id = 0, E = N1.Children.size(); Id < E; ++Id) |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 735 | if (!identical(N1.Children[Id], N2.Children[Id])) |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 736 | return false; |
| 737 | return true; |
| 738 | } |
| 739 | |
| 740 | bool 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 | |
| 757 | bool ASTDiff::Impl::isMatchingPossible(NodeId Id1, NodeId Id2) const { |
| 758 | return Options.isMatchingAllowed(T1.getNode(Id1).ASTNode, |
| 759 | T2.getNode(Id2).ASTNode); |
| 760 | } |
| 761 | |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 762 | void 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 | |
| 777 | double 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 | |
| 789 | NodeId ASTDiff::Impl::findCandidate(const Mapping &M, NodeId Id1) const { |
| 790 | NodeId Candidate; |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 791 | double HighestSimilarity = 0.0; |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 792 | 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 Altmanninger | fa524d7 | 2017-08-18 16:34:15 +0000 | [diff] [blame] | 798 | if (Similarity >= Options.MinSimilarity && Similarity > HighestSimilarity) { |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 799 | HighestSimilarity = Similarity; |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 800 | Candidate = Id2; |
| 801 | } |
| 802 | } |
| 803 | return Candidate; |
| 804 | } |
| 805 | |
| 806 | void ASTDiff::Impl::matchBottomUp(Mapping &M) const { |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 807 | std::vector<NodeId> Postorder = getSubtreePostorder(T1, T1.getRootId()); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 808 | for (NodeId Id1 : Postorder) { |
Johannes Altmanninger | fa524d7 | 2017-08-18 16:34:15 +0000 | [diff] [blame] | 809 | if (Id1 == T1.getRootId() && !M.hasSrc(T1.getRootId()) && |
| 810 | !M.hasDst(T2.getRootId())) { |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 811 | if (isMatchingPossible(T1.getRootId(), T2.getRootId())) { |
| 812 | M.link(T1.getRootId(), T2.getRootId()); |
| 813 | addOptimalMapping(M, T1.getRootId(), T2.getRootId()); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 814 | } |
| 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 Altmanninger | fa524d7 | 2017-08-18 16:34:15 +0000 | [diff] [blame] | 825 | if (Id2.isValid() && canBeAddedToMapping(M, Id1, Id2)) { |
| 826 | M.link(Id1, Id2); |
| 827 | addOptimalMapping(M, Id1, Id2); |
| 828 | } |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 829 | } |
| 830 | } |
| 831 | |
| 832 | Mapping ASTDiff::Impl::matchTopDown() const { |
| 833 | PriorityList L1(T1); |
| 834 | PriorityList L2(T2); |
| 835 | |
| 836 | Mapping M(T1.getSize(), T2.getSize()); |
| 837 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 838 | L1.push(T1.getRootId()); |
| 839 | L2.push(T2.getRootId()); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 840 | |
| 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 Altmanninger | fa524d7 | 2017-08-18 16:34:15 +0000 | [diff] [blame] | 858 | 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 Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 864 | } |
| 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 | |
| 877 | void ASTDiff::Impl::computeMapping() { |
| 878 | if (IsMappingDone) |
| 879 | return; |
| 880 | TheMapping = matchTopDown(); |
| 881 | matchBottomUp(TheMapping); |
| 882 | IsMappingDone = true; |
| 883 | } |
| 884 | |
| 885 | std::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 | |
| 893 | std::vector<Change> ASTDiff::Impl::computeChanges(Mapping &M) { |
| 894 | std::vector<Change> Changes; |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 895 | for (NodeId Id2 : getSubtreeBfs(T2, T2.getRootId())) { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 896 | const Node &N2 = T2.getNode(Id2); |
| 897 | NodeId Id1 = M.getSrc(Id2); |
| 898 | if (Id1.isValid()) { |
| 899 | assert(isMatchingPossible(Id1, Id2) && "Invalid matching."); |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 900 | if (T1.getNodeValue(Id1) != T2.getNodeValue(Id2)) { |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 901 | 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 | |
| 939 | void 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 Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 949 | OS << " to " << T2.getNodeValue(Chg.Dst) << "\n"; |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 950 | 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 | |
| 964 | void 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 | |
| 972 | ASTDiff::ASTDiff(SyntaxTree &T1, SyntaxTree &T2, |
| 973 | const ComparisonOptions &Options) |
| 974 | : DiffImpl(llvm::make_unique<Impl>(*T1.TreeImpl, *T2.TreeImpl, Options)) {} |
| 975 | |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 976 | ASTDiff::~ASTDiff() = default; |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 977 | |
| 978 | SyntaxTree::SyntaxTree(const ASTContext &AST) |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 979 | : TreeImpl(llvm::make_unique<SyntaxTree::Impl>( |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 980 | this, AST.getTranslationUnitDecl(), AST)) {} |
| 981 | |
| 982 | std::vector<Match> ASTDiff::getMatches() { |
| 983 | DiffImpl->computeMapping(); |
| 984 | return DiffImpl->getMatches(DiffImpl->TheMapping); |
| 985 | } |
| 986 | |
| 987 | std::vector<Change> ASTDiff::getChanges() { |
| 988 | DiffImpl->computeMapping(); |
| 989 | return DiffImpl->computeChanges(DiffImpl->TheMapping); |
| 990 | } |
| 991 | |
| 992 | void ASTDiff::printChange(raw_ostream &OS, const Change &Chg) const { |
| 993 | DiffImpl->printChangeImpl(OS, Chg); |
| 994 | } |
| 995 | |
| 996 | void ASTDiff::printMatch(raw_ostream &OS, const Match &M) const { |
| 997 | DiffImpl->printMatchImpl(OS, M); |
| 998 | } |
| 999 | |
Johannes Altmanninger | 8b0e066 | 2017-08-01 20:17:40 +0000 | [diff] [blame] | 1000 | SyntaxTree::~SyntaxTree() = default; |
| 1001 | |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 1002 | void SyntaxTree::printAsJson(raw_ostream &OS) { TreeImpl->printAsJsonImpl(OS); } |
| 1003 | |
| 1004 | std::string SyntaxTree::getNodeValue(const DynTypedNode &DTN) const { |
Johannes Altmanninger | 31b52d6 | 2017-08-01 20:17:46 +0000 | [diff] [blame] | 1005 | return TreeImpl->getNodeValue(DTN); |
Alex Lorenz | a75b2ca | 2017-07-21 12:49:28 +0000 | [diff] [blame] | 1006 | } |
| 1007 | |
| 1008 | } // end namespace diff |
| 1009 | } // end namespace clang |