1 //===- ClangSrcLocDump.cpp ------------------------------------*- C++ -*---===// 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 #include "clang/Basic/Diagnostic.h" 10 #include "clang/Driver/Compilation.h" 11 #include "clang/Driver/Driver.h" 12 #include "clang/Driver/Job.h" 13 #include "clang/Driver/Options.h" 14 #include "clang/Driver/Tool.h" 15 #include "clang/Frontend/CompilerInstance.h" 16 #include "clang/Frontend/TextDiagnosticPrinter.h" 17 #include "clang/Tooling/Tooling.h" 18 #include "llvm/Option/ArgList.h" 19 #include "llvm/Support/CommandLine.h" 20 #include "llvm/Support/Host.h" 21 #include "llvm/Support/JSON.h" 22 23 #include "ASTSrcLocProcessor.h" 24 25 using namespace clang::tooling; 26 using namespace clang; 27 using namespace llvm; 28 29 static cl::list<std::string> IncludeDirectories( 30 "I", cl::desc("Include directories to use while compiling"), 31 cl::value_desc("directory"), cl::Required, cl::OneOrMore, cl::Prefix); 32 33 static cl::opt<std::string> 34 AstHeaderFile("astheader", cl::desc("AST header to parse API from"), 35 cl::Required, cl::value_desc("AST header file")); 36 37 static cl::opt<bool> 38 SkipProcessing("skip-processing", 39 cl::desc("Avoid processing the AST header file"), 40 cl::Required, cl::value_desc("bool")); 41 42 static cl::opt<std::string> JsonOutputPath("json-output-path", 43 cl::desc("json output path"), 44 cl::Required, 45 cl::value_desc("path")); 46 47 class ASTSrcLocGenerationAction : public clang::ASTFrontendAction { 48 public: 49 ASTSrcLocGenerationAction() : Processor(JsonOutputPath) {} 50 51 void ExecuteAction() override { 52 clang::ASTFrontendAction::ExecuteAction(); 53 if (getCompilerInstance().getDiagnostics().getNumErrors() > 0) 54 Processor.generateEmpty(); 55 else 56 Processor.generate(); 57 } 58 59 std::unique_ptr<clang::ASTConsumer> 60 CreateASTConsumer(clang::CompilerInstance &Compiler, 61 llvm::StringRef File) override { 62 return Processor.createASTConsumer(Compiler, File); 63 } 64 65 private: 66 ASTSrcLocProcessor Processor; 67 }; 68 69 int main(int argc, const char **argv) { 70 71 cl::ParseCommandLineOptions(argc, argv); 72 73 if (SkipProcessing) { 74 std::error_code EC; 75 llvm::raw_fd_ostream JsonOut(JsonOutputPath, EC, llvm::sys::fs::F_Text); 76 if (EC) 77 return 1; 78 JsonOut << formatv("{0:2}", llvm::json::Value(llvm::json::Object())); 79 return 0; 80 } 81 82 std::vector<std::string> Args; 83 Args.push_back("-cc1"); 84 85 llvm::transform(IncludeDirectories, std::back_inserter(Args), 86 [](const std::string &IncDir) { return "-I" + IncDir; }); 87 88 Args.push_back("-fsyntax-only"); 89 Args.push_back(AstHeaderFile); 90 91 std::vector<const char *> Argv(Args.size(), nullptr); 92 llvm::transform(Args, Argv.begin(), 93 [](const std::string &Arg) { return Arg.c_str(); }); 94 95 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); 96 unsigned MissingArgIndex, MissingArgCount; 97 auto Opts = driver::getDriverOptTable(); 98 auto ParsedArgs = Opts.ParseArgs(llvm::makeArrayRef(Argv).slice(1), 99 MissingArgIndex, MissingArgCount); 100 ParseDiagnosticArgs(*DiagOpts, ParsedArgs); 101 102 // Don't output diagnostics, because common scenarios such as 103 // cross-compiling fail with diagnostics. This is not fatal, but 104 // just causes attempts to use the introspection API to return no data. 105 std::string Str; 106 llvm::raw_string_ostream OS(Str); 107 TextDiagnosticPrinter DiagnosticPrinter(OS, &*DiagOpts); 108 DiagnosticsEngine Diagnostics( 109 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, 110 &DiagnosticPrinter, false); 111 112 FileManager Files(FileSystemOptions(), vfs::getRealFileSystem()); 113 114 auto Driver = std::make_unique<driver::Driver>( 115 "clang", llvm::sys::getDefaultTargetTriple(), Diagnostics, 116 "ast-api-dump-tool", &Files.getVirtualFileSystem()); 117 118 std::unique_ptr<clang::driver::Compilation> Comp( 119 Driver->BuildCompilation(llvm::makeArrayRef(Argv))); 120 if (!Comp) 121 return 1; 122 123 const auto &Jobs = Comp->getJobs(); 124 if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) { 125 SmallString<256> error_msg; 126 llvm::raw_svector_ostream error_stream(error_msg); 127 Jobs.Print(error_stream, "; ", true); 128 return 1; 129 } 130 131 const auto &Cmd = cast<driver::Command>(*Jobs.begin()); 132 const llvm::opt::ArgStringList &CC1Args = Cmd.getArguments(); 133 134 auto Invocation = std::make_unique<CompilerInvocation>(); 135 CompilerInvocation::CreateFromArgs(*Invocation, CC1Args, Diagnostics); 136 137 CompilerInstance Compiler(std::make_shared<clang::PCHContainerOperations>()); 138 Compiler.setInvocation(std::move(Invocation)); 139 140 Compiler.createDiagnostics(&DiagnosticPrinter, false); 141 if (!Compiler.hasDiagnostics()) 142 return 1; 143 144 // Suppress "2 errors generated" or similar messages 145 Compiler.getDiagnosticOpts().ShowCarets = false; 146 Compiler.createSourceManager(Files); 147 148 ASTSrcLocGenerationAction ScopedToolAction; 149 Compiler.ExecuteAction(ScopedToolAction); 150 151 Files.clearStatCache(); 152 153 return 0; 154 } 155