xref: /llvm-project/clang-tools-extra/clang-query/tool/ClangQuery.cpp (revision 2946cd701067404b99c39fb29dc9c74bd7193eb3)
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 <fstream>
39 #include <string>
40 
41 using namespace clang;
42 using namespace clang::ast_matchers;
43 using namespace clang::ast_matchers::dynamic;
44 using namespace clang::query;
45 using namespace clang::tooling;
46 using namespace llvm;
47 
48 static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
49 static cl::OptionCategory ClangQueryCategory("clang-query options");
50 
51 static cl::list<std::string> Commands("c", cl::desc("Specify command to run"),
52                                       cl::value_desc("command"),
53                                       cl::cat(ClangQueryCategory));
54 
55 static cl::list<std::string> CommandFiles("f",
56                                           cl::desc("Read commands from file"),
57                                           cl::value_desc("file"),
58                                           cl::cat(ClangQueryCategory));
59 
60 static cl::opt<std::string> PreloadFile(
61     "preload",
62     cl::desc("Preload commands from file and start interactive mode"),
63     cl::value_desc("file"), cl::cat(ClangQueryCategory));
64 
65 bool runCommandsInFile(const char *ExeName, std::string const &FileName,
66                        QuerySession &QS) {
67   std::ifstream Input(FileName.c_str());
68   if (!Input.is_open()) {
69     llvm::errs() << ExeName << ": cannot open " << FileName << "\n";
70     return 1;
71   }
72   while (Input.good()) {
73     std::string Line;
74     std::getline(Input, Line);
75 
76     QueryRef Q = QueryParser::parse(Line, QS);
77     if (!Q->run(llvm::outs(), QS))
78       return true;
79   }
80   return false;
81 }
82 
83 int main(int argc, const char **argv) {
84   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
85 
86   CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
87 
88   if (!Commands.empty() && !CommandFiles.empty()) {
89     llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
90     return 1;
91   }
92 
93   if ((!Commands.empty() || !CommandFiles.empty()) && !PreloadFile.empty()) {
94     llvm::errs() << argv[0]
95                  << ": cannot specify both -c or -f with --preload\n";
96     return 1;
97   }
98 
99   ClangTool Tool(OptionsParser.getCompilations(),
100                  OptionsParser.getSourcePathList());
101   std::vector<std::unique_ptr<ASTUnit>> ASTs;
102   int Status = Tool.buildASTs(ASTs);
103   int ASTStatus = 0;
104   if (Status == 1) {
105     // Building ASTs failed.
106     return 1;
107   } else if (Status == 2) {
108     ASTStatus |= 1;
109     llvm::errs() << "Failed to build AST for some of the files, "
110                  << "results may be incomplete."
111                  << "\n";
112   } else {
113     assert(Status == 0 && "Unexpected status returned");
114   }
115 
116   QuerySession QS(ASTs);
117 
118   if (!Commands.empty()) {
119     for (auto I = Commands.begin(), E = Commands.end(); I != E; ++I) {
120       QueryRef Q = QueryParser::parse(*I, QS);
121       if (!Q->run(llvm::outs(), QS))
122         return 1;
123     }
124   } else if (!CommandFiles.empty()) {
125     for (auto I = CommandFiles.begin(), E = CommandFiles.end(); I != E; ++I) {
126       if (runCommandsInFile(argv[0], *I, QS))
127         return 1;
128     }
129   } else {
130     if (!PreloadFile.empty()) {
131       if (runCommandsInFile(argv[0], PreloadFile, QS))
132         return 1;
133     }
134     LineEditor LE("clang-query");
135     LE.setListCompleter([&QS](StringRef Line, size_t Pos) {
136       return QueryParser::complete(Line, Pos, QS);
137     });
138     while (llvm::Optional<std::string> Line = LE.readLine()) {
139       QueryRef Q = QueryParser::parse(*Line, QS);
140       Q->run(llvm::outs(), QS);
141       llvm::outs().flush();
142       if (QS.Terminate)
143         break;
144     }
145   }
146 
147   return ASTStatus;
148 }
149