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 ~ASTSrcLocGenerationAction() { Processor.generate(); } 52 53 std::unique_ptr<clang::ASTConsumer> 54 CreateASTConsumer(clang::CompilerInstance &Compiler, 55 llvm::StringRef File) override { 56 return Processor.createASTConsumer(Compiler, File); 57 } 58 59 private: 60 ASTSrcLocProcessor Processor; 61 }; 62 63 int main(int argc, const char **argv) { 64 65 cl::ParseCommandLineOptions(argc, argv); 66 67 if (SkipProcessing) { 68 std::error_code EC; 69 llvm::raw_fd_ostream JsonOut(JsonOutputPath, EC, llvm::sys::fs::F_Text); 70 if (EC) 71 return 1; 72 JsonOut << formatv("{0:2}", llvm::json::Value(llvm::json::Object())); 73 return 0; 74 } 75 76 std::vector<std::string> Args; 77 Args.push_back("-cc1"); 78 79 llvm::transform(IncludeDirectories, std::back_inserter(Args), 80 [](const std::string &IncDir) { return "-I" + IncDir; }); 81 82 Args.push_back("-fsyntax-only"); 83 Args.push_back(AstHeaderFile); 84 85 std::vector<const char *> Argv(Args.size(), nullptr); 86 llvm::transform(Args, Argv.begin(), 87 [](const std::string &Arg) { return Arg.c_str(); }); 88 89 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); 90 unsigned MissingArgIndex, MissingArgCount; 91 auto Opts = driver::getDriverOptTable(); 92 auto ParsedArgs = Opts.ParseArgs(llvm::makeArrayRef(Argv).slice(1), 93 MissingArgIndex, MissingArgCount); 94 ParseDiagnosticArgs(*DiagOpts, ParsedArgs); 95 96 // Don't output diagnostics, because common scenarios such as 97 // cross-compiling fail with diagnostics. This is not fatal, but 98 // just causes attempts to use the introspection API to return no data. 99 std::string Str; 100 llvm::raw_string_ostream OS(Str); 101 TextDiagnosticPrinter DiagnosticPrinter(OS, &*DiagOpts); 102 DiagnosticsEngine Diagnostics( 103 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, 104 &DiagnosticPrinter, false); 105 106 FileManager Files(FileSystemOptions(), vfs::getRealFileSystem()); 107 108 auto Driver = std::make_unique<driver::Driver>( 109 "clang", llvm::sys::getDefaultTargetTriple(), Diagnostics, 110 "ast-api-dump-tool", &Files.getVirtualFileSystem()); 111 112 std::unique_ptr<clang::driver::Compilation> Comp( 113 Driver->BuildCompilation(llvm::makeArrayRef(Argv))); 114 if (!Comp) 115 return 1; 116 117 const auto &Jobs = Comp->getJobs(); 118 if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) { 119 SmallString<256> error_msg; 120 llvm::raw_svector_ostream error_stream(error_msg); 121 Jobs.Print(error_stream, "; ", true); 122 return 1; 123 } 124 125 const auto &Cmd = cast<driver::Command>(*Jobs.begin()); 126 const llvm::opt::ArgStringList &CC1Args = Cmd.getArguments(); 127 128 auto Invocation = std::make_unique<CompilerInvocation>(); 129 CompilerInvocation::CreateFromArgs(*Invocation, CC1Args, Diagnostics); 130 131 CompilerInstance Compiler(std::make_shared<clang::PCHContainerOperations>()); 132 Compiler.setInvocation(std::move(Invocation)); 133 134 Compiler.createDiagnostics(&DiagnosticPrinter, false); 135 if (!Compiler.hasDiagnostics()) 136 return 1; 137 138 // Suppress "2 errors generated" or similar messages 139 Compiler.getDiagnosticOpts().ShowCarets = false; 140 Compiler.createSourceManager(Files); 141 142 ASTSrcLocGenerationAction ScopedToolAction; 143 Compiler.ExecuteAction(ScopedToolAction); 144 145 Files.clearStatCache(); 146 147 return 0; 148 } 149