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/Error.h"
37#include "llvm/Support/MemoryBuffer.h"
38#include "llvm/Support/Signals.h"
39#include "llvm/Support/WithColor.h"
40#include <optional>
41#include <string>
42
43using namespace clang;
44using namespace clang::ast_matchers;
45using namespace clang::ast_matchers::dynamic;
46using namespace clang::query;
47using namespace clang::tooling;
48using namespace llvm;
49
50static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
51static cl::OptionCategory ClangQueryCategory("clang-query options");
52
53static cl::opt<bool>
54 UseColor("use-color",
55 cl::desc(
56 R"(Use colors in detailed AST output. If not set, colors
57will be used if the terminal connected to
58standard output supports colors.)"),
59 cl::init(Val: false), cl::cat(ClangQueryCategory));
60
61static cl::list<std::string> Commands("c", cl::desc("Specify command to run"),
62 cl::value_desc("command"),
63 cl::cat(ClangQueryCategory));
64
65static cl::list<std::string> CommandFiles("f",
66 cl::desc("Read commands from file"),
67 cl::value_desc("file"),
68 cl::cat(ClangQueryCategory));
69
70static cl::opt<std::string> PreloadFile(
71 "preload",
72 cl::desc("Preload commands from file and start interactive mode"),
73 cl::value_desc("file"), cl::cat(ClangQueryCategory));
74
75bool runCommandsInFile(const char *ExeName, std::string const &FileName,
76 QuerySession &QS) {
77 auto Buffer = llvm::MemoryBuffer::getFile(Filename: FileName);
78 if (!Buffer) {
79 llvm::errs() << ExeName << ": cannot open " << FileName << ": "
80 << Buffer.getError().message() << "\n";
81 return true;
82 }
83
84 StringRef FileContentRef(Buffer.get()->getBuffer());
85
86 while (!FileContentRef.empty()) {
87 QueryRef Q = QueryParser::parse(Line: FileContentRef, QS);
88 if (!Q->run(OS&: llvm::outs(), QS))
89 return true;
90 FileContentRef = Q->RemainingContent;
91 }
92 return false;
93}
94
95int main(int argc, const char **argv) {
96 llvm::sys::PrintStackTraceOnErrorSignal(Argv0: argv[0]);
97
98 llvm::Expected<CommonOptionsParser> OptionsParser =
99 CommonOptionsParser::create(argc, argv, Category&: ClangQueryCategory,
100 OccurrencesFlag: llvm::cl::OneOrMore);
101
102 if (!OptionsParser) {
103 llvm::WithColor::error() << llvm::toString(E: 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(x: "-fdiagnostics-color");
126 else
127 AdjustedArgs.push_back(x: "-fno-diagnostics-color");
128 return AdjustedArgs;
129 };
130 Tool.appendArgumentsAdjuster(Adjuster: 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(Line: Command, QS);
155 if (!Q->run(OS&: llvm::outs(), QS))
156 return 1;
157 }
158 } else if (!CommandFiles.empty()) {
159 for (auto &CommandFile : CommandFiles) {
160 if (runCommandsInFile(ExeName: argv[0], FileName: CommandFile, QS))
161 return 1;
162 }
163 } else {
164 if (!PreloadFile.empty()) {
165 if (runCommandsInFile(ExeName: argv[0], FileName: 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 (std::optional<std::string> Line = LE.readLine()) {
173 QueryRef Q = QueryParser::parse(Line: *Line, QS);
174 Q->run(OS&: llvm::outs(), QS);
175 llvm::outs().flush();
176 if (QS.Terminate)
177 break;
178 }
179 }
180
181 return ASTStatus;
182}
183

source code of clang-tools-extra/clang-query/tool/ClangQuery.cpp