1 //===---- ClangQuery.cpp - clang-query tool -------------------------------===//
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 //
9 // This tool is for interactive exploration of the Clang AST using AST matchers.
10 // It currently allows the user to enter a matcher at an interactive prompt and
11 // view the resulting bindings as diagnostics, AST pretty prints or AST dumps.
12 // Example session:
13 //
14 // $ cat foo.c
15 // void foo(void) {}
16 // $ clang-query foo.c --
17 // clang-query> match functionDecl()
18 //
19 // Match #1:
20 //
21 // foo.c:1:1: note: "root" binds here
22 // void foo(void) {}
23 // ^~~~~~~~~~~~~~~~~
24 // 1 match.
25 //
26 //===----------------------------------------------------------------------===//
27
28 #include "Query.h"
29 #include "QueryParser.h"
30 #include "QuerySession.h"
31 #include "clang/Frontend/ASTUnit.h"
32 #include "clang/Tooling/CommonOptionsParser.h"
33 #include "clang/Tooling/Tooling.h"
34 #include "llvm/LineEditor/LineEditor.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/WithColor.h"
39 #include <fstream>
40 #include <string>
41
42 using namespace clang;
43 using namespace clang::ast_matchers;
44 using namespace clang::ast_matchers::dynamic;
45 using namespace clang::query;
46 using namespace clang::tooling;
47 using namespace llvm;
48
49 static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
50 static cl::OptionCategory ClangQueryCategory("clang-query options");
51
52 static cl::opt<bool>
53 UseColor("use-color",
54 cl::desc(
55 R"(Use colors in detailed AST output. If not set, colors
56 will be used if the terminal connected to
57 standard output supports colors.)"),
58 cl::init(false), cl::cat(ClangQueryCategory));
59
60 static cl::list<std::string> Commands("c", cl::desc("Specify command to run"),
61 cl::value_desc("command"),
62 cl::cat(ClangQueryCategory));
63
64 static cl::list<std::string> CommandFiles("f",
65 cl::desc("Read commands from file"),
66 cl::value_desc("file"),
67 cl::cat(ClangQueryCategory));
68
69 static cl::opt<std::string> PreloadFile(
70 "preload",
71 cl::desc("Preload commands from file and start interactive mode"),
72 cl::value_desc("file"), cl::cat(ClangQueryCategory));
73
runCommandsInFile(const char * ExeName,std::string const & FileName,QuerySession & QS)74 bool runCommandsInFile(const char *ExeName, std::string const &FileName,
75 QuerySession &QS) {
76 std::ifstream Input(FileName.c_str());
77 if (!Input.is_open()) {
78 llvm::errs() << ExeName << ": cannot open " << FileName << "\n";
79 return 1;
80 }
81
82 std::string FileContent((std::istreambuf_iterator<char>(Input)),
83 std::istreambuf_iterator<char>());
84
85 StringRef FileContentRef(FileContent);
86 while (!FileContentRef.empty()) {
87 QueryRef Q = QueryParser::parse(FileContentRef, QS);
88 if (!Q->run(llvm::outs(), QS))
89 return true;
90 FileContentRef = Q->RemainingContent;
91 }
92 return false;
93 }
94
main(int argc,const char ** argv)95 int main(int argc, const char **argv) {
96 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
97
98 llvm::Expected<CommonOptionsParser> OptionsParser =
99 CommonOptionsParser::create(argc, argv, ClangQueryCategory,
100 llvm::cl::OneOrMore);
101
102 if (!OptionsParser) {
103 llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
104 return 1;
105 }
106
107 if (!Commands.empty() && !CommandFiles.empty()) {
108 llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
109 return 1;
110 }
111
112 if ((!Commands.empty() || !CommandFiles.empty()) && !PreloadFile.empty()) {
113 llvm::errs() << argv[0]
114 << ": cannot specify both -c or -f with --preload\n";
115 return 1;
116 }
117
118 ClangTool Tool(OptionsParser->getCompilations(),
119 OptionsParser->getSourcePathList());
120
121 if (UseColor.getNumOccurrences() > 0) {
122 ArgumentsAdjuster colorAdjustor = [](const CommandLineArguments &Args, StringRef /*unused*/) {
123 CommandLineArguments AdjustedArgs = Args;
124 if (UseColor)
125 AdjustedArgs.push_back("-fdiagnostics-color");
126 else
127 AdjustedArgs.push_back("-fno-diagnostics-color");
128 return AdjustedArgs;
129 };
130 Tool.appendArgumentsAdjuster(colorAdjustor);
131 }
132
133 std::vector<std::unique_ptr<ASTUnit>> ASTs;
134 int ASTStatus = 0;
135 switch (Tool.buildASTs(ASTs)) {
136 case 0:
137 break;
138 case 1: // Building ASTs failed.
139 return 1;
140 case 2:
141 ASTStatus |= 1;
142 llvm::errs() << "Failed to build AST for some of the files, "
143 << "results may be incomplete."
144 << "\n";
145 break;
146 default:
147 llvm_unreachable("Unexpected status returned");
148 }
149
150 QuerySession QS(ASTs);
151
152 if (!Commands.empty()) {
153 for (auto &Command : Commands) {
154 QueryRef Q = QueryParser::parse(Command, QS);
155 if (!Q->run(llvm::outs(), QS))
156 return 1;
157 }
158 } else if (!CommandFiles.empty()) {
159 for (auto &CommandFile : CommandFiles) {
160 if (runCommandsInFile(argv[0], CommandFile, QS))
161 return 1;
162 }
163 } else {
164 if (!PreloadFile.empty()) {
165 if (runCommandsInFile(argv[0], PreloadFile, QS))
166 return 1;
167 }
168 LineEditor LE("clang-query");
169 LE.setListCompleter([&QS](StringRef Line, size_t Pos) {
170 return QueryParser::complete(Line, Pos, QS);
171 });
172 while (llvm::Optional<std::string> Line = LE.readLine()) {
173 QueryRef Q = QueryParser::parse(*Line, QS);
174 Q->run(llvm::outs(), QS);
175 llvm::outs().flush();
176 if (QS.Terminate)
177 break;
178 }
179 }
180
181 return ASTStatus;
182 }
183