xref: /llvm-project/clang-tools-extra/clang-query/tool/ClangQuery.cpp (revision f0722333dd167245eb3c2b4263529a1ce3679b5c)
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 
73   std::string FileContent((std::istreambuf_iterator<char>(Input)),
74                           std::istreambuf_iterator<char>());
75 
76   StringRef FileContentRef(FileContent);
77   while (!FileContentRef.empty()) {
78     QueryRef Q = QueryParser::parse(FileContentRef, QS);
79     if (!Q->run(llvm::outs(), QS))
80       return true;
81     FileContentRef = Q->RemainingContent;
82   }
83   return false;
84 }
85 
86 int main(int argc, const char **argv) {
87   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
88 
89   CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
90 
91   if (!Commands.empty() && !CommandFiles.empty()) {
92     llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
93     return 1;
94   }
95 
96   if ((!Commands.empty() || !CommandFiles.empty()) && !PreloadFile.empty()) {
97     llvm::errs() << argv[0]
98                  << ": cannot specify both -c or -f with --preload\n";
99     return 1;
100   }
101 
102   ClangTool Tool(OptionsParser.getCompilations(),
103                  OptionsParser.getSourcePathList());
104   std::vector<std::unique_ptr<ASTUnit>> ASTs;
105   int Status = Tool.buildASTs(ASTs);
106   int ASTStatus = 0;
107   if (Status == 1) {
108     // Building ASTs failed.
109     return 1;
110   } else if (Status == 2) {
111     ASTStatus |= 1;
112     llvm::errs() << "Failed to build AST for some of the files, "
113                  << "results may be incomplete."
114                  << "\n";
115   } else {
116     assert(Status == 0 && "Unexpected status returned");
117   }
118 
119   QuerySession QS(ASTs);
120 
121   if (!Commands.empty()) {
122     for (auto I = Commands.begin(), E = Commands.end(); I != E; ++I) {
123       QueryRef Q = QueryParser::parse(*I, QS);
124       if (!Q->run(llvm::outs(), QS))
125         return 1;
126     }
127   } else if (!CommandFiles.empty()) {
128     for (auto I = CommandFiles.begin(), E = CommandFiles.end(); I != E; ++I) {
129       if (runCommandsInFile(argv[0], *I, QS))
130         return 1;
131     }
132   } else {
133     if (!PreloadFile.empty()) {
134       if (runCommandsInFile(argv[0], PreloadFile, QS))
135         return 1;
136     }
137     LineEditor LE("clang-query");
138     LE.setListCompleter([&QS](StringRef Line, size_t Pos) {
139       return QueryParser::complete(Line, Pos, QS);
140     });
141     while (llvm::Optional<std::string> Line = LE.readLine()) {
142       QueryRef Q = QueryParser::parse(*Line, QS);
143       Q->run(llvm::outs(), QS);
144       llvm::outs().flush();
145       if (QS.Terminate)
146         break;
147     }
148   }
149 
150   return ASTStatus;
151 }
152