BuildTree.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. //===- BuildTree.cpp ------------------------------------------*- C++ -*-=====//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Tooling/Syntax/BuildTree.h"
  9. #include "clang/AST/RecursiveASTVisitor.h"
  10. #include "clang/AST/Stmt.h"
  11. #include "clang/Basic/LLVM.h"
  12. #include "clang/Basic/SourceLocation.h"
  13. #include "clang/Basic/SourceManager.h"
  14. #include "clang/Basic/TokenKinds.h"
  15. #include "clang/Lex/Lexer.h"
  16. #include "clang/Tooling/Syntax/Nodes.h"
  17. #include "clang/Tooling/Syntax/Tokens.h"
  18. #include "clang/Tooling/Syntax/Tree.h"
  19. #include "llvm/ADT/ArrayRef.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/Support/Allocator.h"
  23. #include "llvm/Support/Casting.h"
  24. #include "llvm/Support/FormatVariadic.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include <map>
  27. using namespace clang;
  28. /// A helper class for constructing the syntax tree while traversing a clang
  29. /// AST.
  30. ///
  31. /// At each point of the traversal we maintain a list of pending nodes.
  32. /// Initially all tokens are added as pending nodes. When processing a clang AST
  33. /// node, the clients need to:
  34. /// - create a corresponding syntax node,
  35. /// - assign roles to all pending child nodes with 'markChild' and
  36. /// 'markChildToken',
  37. /// - replace the child nodes with the new syntax node in the pending list
  38. /// with 'foldNode'.
  39. ///
  40. /// Note that all children are expected to be processed when building a node.
  41. ///
  42. /// Call finalize() to finish building the tree and consume the root node.
  43. class syntax::TreeBuilder {
  44. public:
  45. TreeBuilder(syntax::Arena &Arena) : Arena(Arena), Pending(Arena) {}
  46. llvm::BumpPtrAllocator &allocator() { return Arena.allocator(); }
  47. /// Populate children for \p New node, assuming it covers tokens from \p
  48. /// Range.
  49. void foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New);
  50. /// Set role for a token starting at \p Loc.
  51. void markChildToken(SourceLocation Loc, tok::TokenKind Kind, NodeRole R);
  52. /// Finish building the tree and consume the root node.
  53. syntax::TranslationUnit *finalize() && {
  54. auto Tokens = Arena.tokenBuffer().expandedTokens();
  55. // Build the root of the tree, consuming all the children.
  56. Pending.foldChildren(Tokens,
  57. new (Arena.allocator()) syntax::TranslationUnit);
  58. return cast<syntax::TranslationUnit>(std::move(Pending).finalize());
  59. }
  60. /// getRange() finds the syntax tokens corresponding to the passed source
  61. /// locations.
  62. /// \p First is the start position of the first token and \p Last is the start
  63. /// position of the last token.
  64. llvm::ArrayRef<syntax::Token> getRange(SourceLocation First,
  65. SourceLocation Last) const {
  66. assert(First.isValid());
  67. assert(Last.isValid());
  68. assert(First == Last ||
  69. Arena.sourceManager().isBeforeInTranslationUnit(First, Last));
  70. return llvm::makeArrayRef(findToken(First), std::next(findToken(Last)));
  71. }
  72. llvm::ArrayRef<syntax::Token> getRange(const Decl *D) const {
  73. return getRange(D->getBeginLoc(), D->getEndLoc());
  74. }
  75. llvm::ArrayRef<syntax::Token> getRange(const Stmt *S) const {
  76. return getRange(S->getBeginLoc(), S->getEndLoc());
  77. }
  78. private:
  79. /// Finds a token starting at \p L. The token must exist.
  80. const syntax::Token *findToken(SourceLocation L) const;
  81. /// A collection of trees covering the input tokens.
  82. /// When created, each tree corresponds to a single token in the file.
  83. /// Clients call 'foldChildren' to attach one or more subtrees to a parent
  84. /// node and update the list of trees accordingly.
  85. ///
  86. /// Ensures that added nodes properly nest and cover the whole token stream.
  87. struct Forest {
  88. Forest(syntax::Arena &A) {
  89. // FIXME: do not add 'eof' to the tree.
  90. // Create all leaf nodes.
  91. for (auto &T : A.tokenBuffer().expandedTokens())
  92. Trees.insert(Trees.end(),
  93. {&T, NodeAndRole{new (A.allocator()) syntax::Leaf(&T)}});
  94. }
  95. void assignRole(llvm::ArrayRef<syntax::Token> Range,
  96. syntax::NodeRole Role) {
  97. assert(!Range.empty());
  98. auto It = Trees.lower_bound(Range.begin());
  99. assert(It != Trees.end() && "no node found");
  100. assert(It->first == Range.begin() && "no child with the specified range");
  101. assert((std::next(It) == Trees.end() ||
  102. std::next(It)->first == Range.end()) &&
  103. "no child with the specified range");
  104. It->second.Role = Role;
  105. }
  106. /// Add \p Node to the forest and fill its children nodes based on the \p
  107. /// NodeRange.
  108. void foldChildren(llvm::ArrayRef<syntax::Token> NodeTokens,
  109. syntax::Tree *Node) {
  110. assert(!NodeTokens.empty());
  111. assert(Node->firstChild() == nullptr && "node already has children");
  112. auto *FirstToken = NodeTokens.begin();
  113. auto BeginChildren = Trees.lower_bound(FirstToken);
  114. assert(BeginChildren != Trees.end() &&
  115. BeginChildren->first == FirstToken &&
  116. "fold crosses boundaries of existing subtrees");
  117. auto EndChildren = Trees.lower_bound(NodeTokens.end());
  118. assert((EndChildren == Trees.end() ||
  119. EndChildren->first == NodeTokens.end()) &&
  120. "fold crosses boundaries of existing subtrees");
  121. // (!) we need to go in reverse order, because we can only prepend.
  122. for (auto It = EndChildren; It != BeginChildren; --It)
  123. Node->prependChildLowLevel(std::prev(It)->second.Node,
  124. std::prev(It)->second.Role);
  125. Trees.erase(BeginChildren, EndChildren);
  126. Trees.insert({FirstToken, NodeAndRole(Node)});
  127. }
  128. // EXPECTS: all tokens were consumed and are owned by a single root node.
  129. syntax::Node *finalize() && {
  130. assert(Trees.size() == 1);
  131. auto *Root = Trees.begin()->second.Node;
  132. Trees = {};
  133. return Root;
  134. }
  135. std::string str(const syntax::Arena &A) const {
  136. std::string R;
  137. for (auto It = Trees.begin(); It != Trees.end(); ++It) {
  138. unsigned CoveredTokens =
  139. It != Trees.end()
  140. ? (std::next(It)->first - It->first)
  141. : A.tokenBuffer().expandedTokens().end() - It->first;
  142. R += llvm::formatv("- '{0}' covers '{1}'+{2} tokens\n",
  143. It->second.Node->kind(),
  144. It->first->text(A.sourceManager()), CoveredTokens);
  145. R += It->second.Node->dump(A);
  146. }
  147. return R;
  148. }
  149. private:
  150. /// A with a role that should be assigned to it when adding to a parent.
  151. struct NodeAndRole {
  152. explicit NodeAndRole(syntax::Node *Node)
  153. : Node(Node), Role(NodeRole::Unknown) {}
  154. syntax::Node *Node;
  155. NodeRole Role;
  156. };
  157. /// Maps from the start token to a subtree starting at that token.
  158. /// FIXME: storing the end tokens is redundant.
  159. /// FIXME: the key of a map is redundant, it is also stored in NodeForRange.
  160. std::map<const syntax::Token *, NodeAndRole> Trees;
  161. };
  162. /// For debugging purposes.
  163. std::string str() { return Pending.str(Arena); }
  164. syntax::Arena &Arena;
  165. Forest Pending;
  166. };
  167. namespace {
  168. class BuildTreeVisitor : public RecursiveASTVisitor<BuildTreeVisitor> {
  169. public:
  170. explicit BuildTreeVisitor(ASTContext &Ctx, syntax::TreeBuilder &Builder)
  171. : Builder(Builder), LangOpts(Ctx.getLangOpts()) {}
  172. bool shouldTraversePostOrder() const { return true; }
  173. bool TraverseDecl(Decl *D) {
  174. if (!D || isa<TranslationUnitDecl>(D))
  175. return RecursiveASTVisitor::TraverseDecl(D);
  176. if (!llvm::isa<TranslationUnitDecl>(D->getDeclContext()))
  177. return true; // Only build top-level decls for now, do not recurse.
  178. return RecursiveASTVisitor::TraverseDecl(D);
  179. }
  180. bool VisitDecl(Decl *D) {
  181. assert(llvm::isa<TranslationUnitDecl>(D->getDeclContext()) &&
  182. "expected a top-level decl");
  183. assert(!D->isImplicit());
  184. Builder.foldNode(Builder.getRange(D),
  185. new (allocator()) syntax::TopLevelDeclaration());
  186. return true;
  187. }
  188. bool WalkUpFromTranslationUnitDecl(TranslationUnitDecl *TU) {
  189. // (!) we do not want to call VisitDecl(), the declaration for translation
  190. // unit is built by finalize().
  191. return true;
  192. }
  193. bool WalkUpFromCompoundStmt(CompoundStmt *S) {
  194. using NodeRole = syntax::NodeRole;
  195. Builder.markChildToken(S->getLBracLoc(), tok::l_brace,
  196. NodeRole::CompoundStatement_lbrace);
  197. Builder.markChildToken(S->getRBracLoc(), tok::r_brace,
  198. NodeRole::CompoundStatement_rbrace);
  199. Builder.foldNode(Builder.getRange(S),
  200. new (allocator()) syntax::CompoundStatement);
  201. return true;
  202. }
  203. private:
  204. /// A small helper to save some typing.
  205. llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); }
  206. syntax::TreeBuilder &Builder;
  207. const LangOptions &LangOpts;
  208. };
  209. } // namespace
  210. void syntax::TreeBuilder::foldNode(llvm::ArrayRef<syntax::Token> Range,
  211. syntax::Tree *New) {
  212. Pending.foldChildren(Range, New);
  213. }
  214. void syntax::TreeBuilder::markChildToken(SourceLocation Loc,
  215. tok::TokenKind Kind, NodeRole Role) {
  216. if (Loc.isInvalid())
  217. return;
  218. Pending.assignRole(*findToken(Loc), Role);
  219. }
  220. const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const {
  221. auto Tokens = Arena.tokenBuffer().expandedTokens();
  222. auto &SM = Arena.sourceManager();
  223. auto It = llvm::partition_point(Tokens, [&](const syntax::Token &T) {
  224. return SM.isBeforeInTranslationUnit(T.location(), L);
  225. });
  226. assert(It != Tokens.end());
  227. assert(It->location() == L);
  228. return &*It;
  229. }
  230. syntax::TranslationUnit *
  231. syntax::buildSyntaxTree(Arena &A, const TranslationUnitDecl &TU) {
  232. TreeBuilder Builder(A);
  233. BuildTreeVisitor(TU.getASTContext(), Builder).TraverseAST(TU.getASTContext());
  234. return std::move(Builder).finalize();
  235. }