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 <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 74 bool runCommandsInFile(const char *ExeName, std::string const &FileName, 75 QuerySession &QS) { 76 auto Buffer = llvm::MemoryBuffer::getFile(FileName); 77 if (!Buffer) { 78 llvm::errs() << ExeName << ": cannot open " << FileName << ": " 79 << Buffer.getError().message() << "\n"; 80 return true; 81 } 82 83 StringRef FileContentRef(Buffer.get()->getBuffer()); 84 85 while (!FileContentRef.empty()) { 86 QueryRef Q = QueryParser::parse(FileContentRef, QS); 87 if (!Q->run(llvm::outs(), QS)) 88 return true; 89 FileContentRef = Q->RemainingContent; 90 } 91 return false; 92 } 93 94 int main(int argc, const char **argv) { 95 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); 96 97 llvm::Expected<CommonOptionsParser> OptionsParser = 98 CommonOptionsParser::create(argc, argv, ClangQueryCategory, 99 llvm::cl::OneOrMore); 100 101 if (!OptionsParser) { 102 llvm::WithColor::error() << llvm::toString(OptionsParser.takeError()); 103 return 1; 104 } 105 106 if (!Commands.empty() && !CommandFiles.empty()) { 107 llvm::errs() << argv[0] << ": cannot specify both -c and -f\n"; 108 return 1; 109 } 110 111 if ((!Commands.empty() || !CommandFiles.empty()) && !PreloadFile.empty()) { 112 llvm::errs() << argv[0] 113 << ": cannot specify both -c or -f with --preload\n"; 114 return 1; 115 } 116 117 ClangTool Tool(OptionsParser->getCompilations(), 118 OptionsParser->getSourcePathList()); 119 120 if (UseColor.getNumOccurrences() > 0) { 121 ArgumentsAdjuster colorAdjustor = [](const CommandLineArguments &Args, StringRef /*unused*/) { 122 CommandLineArguments AdjustedArgs = Args; 123 if (UseColor) 124 AdjustedArgs.push_back("-fdiagnostics-color"); 125 else 126 AdjustedArgs.push_back("-fno-diagnostics-color"); 127 return AdjustedArgs; 128 }; 129 Tool.appendArgumentsAdjuster(colorAdjustor); 130 } 131 132 std::vector<std::unique_ptr<ASTUnit>> ASTs; 133 int ASTStatus = 0; 134 switch (Tool.buildASTs(ASTs)) { 135 case 0: 136 break; 137 case 1: // Building ASTs failed. 138 return 1; 139 case 2: 140 ASTStatus |= 1; 141 llvm::errs() << "Failed to build AST for some of the files, " 142 << "results may be incomplete." 143 << "\n"; 144 break; 145 default: 146 llvm_unreachable("Unexpected status returned"); 147 } 148 149 QuerySession QS(ASTs); 150 151 if (!Commands.empty()) { 152 for (auto &Command : Commands) { 153 QueryRef Q = QueryParser::parse(Command, QS); 154 if (!Q->run(llvm::outs(), QS)) 155 return 1; 156 } 157 } else if (!CommandFiles.empty()) { 158 for (auto &CommandFile : CommandFiles) { 159 if (runCommandsInFile(argv[0], CommandFile, QS)) 160 return 1; 161 } 162 } else { 163 if (!PreloadFile.empty()) { 164 if (runCommandsInFile(argv[0], PreloadFile, QS)) 165 return 1; 166 } 167 LineEditor LE("clang-query"); 168 LE.setListCompleter([&QS](StringRef Line, size_t Pos) { 169 return QueryParser::complete(Line, Pos, QS); 170 }); 171 while (llvm::Optional<std::string> Line = LE.readLine()) { 172 QueryRef Q = QueryParser::parse(*Line, QS); 173 Q->run(llvm::outs(), QS); 174 llvm::outs().flush(); 175 if (QS.Terminate) 176 break; 177 } 178 } 179 180 return ASTStatus; 181 } 182