• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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::list<std::string> Commands("c", cl::desc("Specify command to run"),
53                                       cl::value_desc("command"),
54                                       cl::cat(ClangQueryCategory));
55 
56 static cl::list<std::string> CommandFiles("f",
57                                           cl::desc("Read commands from file"),
58                                           cl::value_desc("file"),
59                                           cl::cat(ClangQueryCategory));
60 
61 static cl::opt<std::string> PreloadFile(
62     "preload",
63     cl::desc("Preload commands from file and start interactive mode"),
64     cl::value_desc("file"), cl::cat(ClangQueryCategory));
65 
runCommandsInFile(const char * ExeName,std::string const & FileName,QuerySession & QS)66 bool runCommandsInFile(const char *ExeName, std::string const &FileName,
67                        QuerySession &QS) {
68   std::ifstream Input(FileName.c_str());
69   if (!Input.is_open()) {
70     llvm::errs() << ExeName << ": cannot open " << FileName << "\n";
71     return 1;
72   }
73 
74   std::string FileContent((std::istreambuf_iterator<char>(Input)),
75                           std::istreambuf_iterator<char>());
76 
77   StringRef FileContentRef(FileContent);
78   while (!FileContentRef.empty()) {
79     QueryRef Q = QueryParser::parse(FileContentRef, QS);
80     if (!Q->run(llvm::outs(), QS))
81       return true;
82     FileContentRef = Q->RemainingContent;
83   }
84   return false;
85 }
86 
main(int argc,const char ** argv)87 int main(int argc, const char **argv) {
88   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
89 
90   llvm::Expected<CommonOptionsParser> OptionsParser =
91       CommonOptionsParser::create(argc, argv, ClangQueryCategory,
92                                   llvm::cl::OneOrMore);
93 
94   if (!OptionsParser) {
95     llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
96     return 1;
97   }
98 
99   if (!Commands.empty() && !CommandFiles.empty()) {
100     llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
101     return 1;
102   }
103 
104   if ((!Commands.empty() || !CommandFiles.empty()) && !PreloadFile.empty()) {
105     llvm::errs() << argv[0]
106                  << ": cannot specify both -c or -f with --preload\n";
107     return 1;
108   }
109 
110   ClangTool Tool(OptionsParser->getCompilations(),
111                  OptionsParser->getSourcePathList());
112   std::vector<std::unique_ptr<ASTUnit>> ASTs;
113   int ASTStatus = 0;
114   switch (Tool.buildASTs(ASTs)) {
115   case 0:
116     break;
117   case 1: // Building ASTs failed.
118     return 1;
119   case 2:
120     ASTStatus |= 1;
121     llvm::errs() << "Failed to build AST for some of the files, "
122                  << "results may be incomplete."
123                  << "\n";
124     break;
125   default:
126     llvm_unreachable("Unexpected status returned");
127   }
128 
129   QuerySession QS(ASTs);
130 
131   if (!Commands.empty()) {
132     for (auto &Command : Commands) {
133       QueryRef Q = QueryParser::parse(Command, QS);
134       if (!Q->run(llvm::outs(), QS))
135         return 1;
136     }
137   } else if (!CommandFiles.empty()) {
138     for (auto &CommandFile : CommandFiles) {
139       if (runCommandsInFile(argv[0], CommandFile, QS))
140         return 1;
141     }
142   } else {
143     if (!PreloadFile.empty()) {
144       if (runCommandsInFile(argv[0], PreloadFile, QS))
145         return 1;
146     }
147     LineEditor LE("clang-query");
148     LE.setListCompleter([&QS](StringRef Line, size_t Pos) {
149       return QueryParser::complete(Line, Pos, QS);
150     });
151     while (llvm::Optional<std::string> Line = LE.readLine()) {
152       QueryRef Q = QueryParser::parse(*Line, QS);
153       Q->run(llvm::outs(), QS);
154       llvm::outs().flush();
155       if (QS.Terminate)
156         break;
157     }
158   }
159 
160   return ASTStatus;
161 }
162