[Syntax] Add syntax-tree-dump in clang-check.

This is useful to experiment/develop syntax trees.

Reviewed By: sammccall

Differential Revision: https://reviews.llvm.org/D95526
This commit is contained in:
Haojian Wu 2021-01-29 09:08:02 +01:00
parent 42a21778f6
commit e90e455d2a
3 changed files with 41 additions and 0 deletions

View File

@ -0,0 +1,9 @@
// RUN: clang-check -syntax-tree-dump "%s" -- 2>&1 | FileCheck %s
int abc;
// CHECK: TranslationUnit Detached
// CHECK-NEXT: `-SimpleDeclaration
// CHECK-NEXT: |-'int'
// CHECK-NEXT: |-DeclaratorList Declarators
// CHECK-NEXT: | `-SimpleDeclarator ListElement
// CHECK-NEXT: | `-'abc'
// CHECK-NEXT: `-';'

View File

@ -18,4 +18,5 @@ clang_target_link_libraries(clang-check
clangSerialization
clangStaticAnalyzerFrontend
clangTooling
clangToolingSyntax
)

View File

@ -24,6 +24,9 @@
#include "clang/Rewrite/Frontend/FrontendActions.h"
#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Syntax/BuildTree.h"
#include "clang/Tooling/Syntax/Tokens.h"
#include "clang/Tooling/Syntax/Tree.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/OptTable.h"
@ -82,6 +85,10 @@ static cl::opt<bool> FixWhatYouCan(
cl::desc(Options.getOptionHelpText(options::OPT_fix_what_you_can)),
cl::cat(ClangCheckCategory));
static cl::opt<bool> SyntaxTreeDump("syntax-tree-dump",
cl::desc("dump the syntax tree"),
cl::cat(ClangCheckCategory));
namespace {
// FIXME: Move FixItRewriteInPlace from lib/Rewrite/Frontend/FrontendActions.cpp
@ -131,6 +138,28 @@ public:
}
};
class DumpSyntaxTree : public clang::ASTFrontendAction {
public:
std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(clang::CompilerInstance &CI, StringRef InFile) override {
class Consumer : public clang::ASTConsumer {
public:
Consumer(clang::CompilerInstance &CI) : Collector(CI.getPreprocessor()) {}
void HandleTranslationUnit(clang::ASTContext &AST) override {
clang::syntax::TokenBuffer TB = std::move(Collector).consume();
clang::syntax::Arena A(AST.getSourceManager(), AST.getLangOpts(), TB);
llvm::outs() << clang::syntax::buildSyntaxTree(A, AST)->dump(
AST.getSourceManager());
}
private:
clang::syntax::TokenCollector Collector;
};
return std::make_unique<Consumer>(CI);
}
};
class ClangCheckActionFactory {
public:
std::unique_ptr<clang::ASTConsumer> newASTConsumer() {
@ -188,6 +217,8 @@ int main(int argc, const char **argv) {
FrontendFactory = newFrontendActionFactory<clang::ento::AnalysisAction>();
else if (Fixit)
FrontendFactory = newFrontendActionFactory<ClangCheckFixItAction>();
else if (SyntaxTreeDump)
FrontendFactory = newFrontendActionFactory<DumpSyntaxTree>();
else
FrontendFactory = newFrontendActionFactory(&CheckFactory);