Path: blob/main/contrib/llvm-project/clang/lib/Tooling/JSONCompilationDatabase.cpp
35232 views
//===- JSONCompilationDatabase.cpp ----------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains the implementation of the JSONCompilationDatabase.9//10//===----------------------------------------------------------------------===//1112#include "clang/Tooling/JSONCompilationDatabase.h"13#include "clang/Basic/LLVM.h"14#include "clang/Tooling/CompilationDatabase.h"15#include "clang/Tooling/CompilationDatabasePluginRegistry.h"16#include "clang/Tooling/Tooling.h"17#include "llvm/ADT/STLExtras.h"18#include "llvm/ADT/SmallString.h"19#include "llvm/ADT/SmallVector.h"20#include "llvm/ADT/StringRef.h"21#include "llvm/Support/Allocator.h"22#include "llvm/Support/Casting.h"23#include "llvm/Support/CommandLine.h"24#include "llvm/Support/ErrorOr.h"25#include "llvm/Support/MemoryBuffer.h"26#include "llvm/Support/Path.h"27#include "llvm/Support/StringSaver.h"28#include "llvm/Support/VirtualFileSystem.h"29#include "llvm/Support/YAMLParser.h"30#include "llvm/Support/raw_ostream.h"31#include "llvm/TargetParser/Host.h"32#include "llvm/TargetParser/Triple.h"33#include <cassert>34#include <memory>35#include <optional>36#include <string>37#include <system_error>38#include <tuple>39#include <utility>40#include <vector>4142using namespace clang;43using namespace tooling;4445namespace {4647/// A parser for escaped strings of command line arguments.48///49/// Assumes \-escaping for quoted arguments (see the documentation of50/// unescapeCommandLine(...)).51class CommandLineArgumentParser {52public:53CommandLineArgumentParser(StringRef CommandLine)54: Input(CommandLine), Position(Input.begin()-1) {}5556std::vector<std::string> parse() {57bool HasMoreInput = true;58while (HasMoreInput && nextNonWhitespace()) {59std::string Argument;60HasMoreInput = parseStringInto(Argument);61CommandLine.push_back(Argument);62}63return CommandLine;64}6566private:67// All private methods return true if there is more input available.6869bool parseStringInto(std::string &String) {70do {71if (*Position == '"') {72if (!parseDoubleQuotedStringInto(String)) return false;73} else if (*Position == '\'') {74if (!parseSingleQuotedStringInto(String)) return false;75} else {76if (!parseFreeStringInto(String)) return false;77}78} while (*Position != ' ');79return true;80}8182bool parseDoubleQuotedStringInto(std::string &String) {83if (!next()) return false;84while (*Position != '"') {85if (!skipEscapeCharacter()) return false;86String.push_back(*Position);87if (!next()) return false;88}89return next();90}9192bool parseSingleQuotedStringInto(std::string &String) {93if (!next()) return false;94while (*Position != '\'') {95String.push_back(*Position);96if (!next()) return false;97}98return next();99}100101bool parseFreeStringInto(std::string &String) {102do {103if (!skipEscapeCharacter()) return false;104String.push_back(*Position);105if (!next()) return false;106} while (*Position != ' ' && *Position != '"' && *Position != '\'');107return true;108}109110bool skipEscapeCharacter() {111if (*Position == '\\') {112return next();113}114return true;115}116117bool nextNonWhitespace() {118do {119if (!next()) return false;120} while (*Position == ' ');121return true;122}123124bool next() {125++Position;126return Position != Input.end();127}128129const StringRef Input;130StringRef::iterator Position;131std::vector<std::string> CommandLine;132};133134std::vector<std::string> unescapeCommandLine(JSONCommandLineSyntax Syntax,135StringRef EscapedCommandLine) {136if (Syntax == JSONCommandLineSyntax::AutoDetect) {137#ifdef _WIN32138// Assume Windows command line parsing on Win32139Syntax = JSONCommandLineSyntax::Windows;140#else141Syntax = JSONCommandLineSyntax::Gnu;142#endif143}144145if (Syntax == JSONCommandLineSyntax::Windows) {146llvm::BumpPtrAllocator Alloc;147llvm::StringSaver Saver(Alloc);148llvm::SmallVector<const char *, 64> T;149llvm::cl::TokenizeWindowsCommandLine(EscapedCommandLine, Saver, T);150std::vector<std::string> Result(T.begin(), T.end());151return Result;152}153assert(Syntax == JSONCommandLineSyntax::Gnu);154CommandLineArgumentParser parser(EscapedCommandLine);155return parser.parse();156}157158// This plugin locates a nearby compile_command.json file, and also infers159// compile commands for files not present in the database.160class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin {161std::unique_ptr<CompilationDatabase>162loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {163SmallString<1024> JSONDatabasePath(Directory);164llvm::sys::path::append(JSONDatabasePath, "compile_commands.json");165auto Base = JSONCompilationDatabase::loadFromFile(166JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);167return Base ? inferTargetAndDriverMode(168inferMissingCompileCommands(expandResponseFiles(169std::move(Base), llvm::vfs::getRealFileSystem())))170: nullptr;171}172};173174} // namespace175176// Register the JSONCompilationDatabasePlugin with the177// CompilationDatabasePluginRegistry using this statically initialized variable.178static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin>179X("json-compilation-database", "Reads JSON formatted compilation databases");180181namespace clang {182namespace tooling {183184// This anchor is used to force the linker to link in the generated object file185// and thus register the JSONCompilationDatabasePlugin.186volatile int JSONAnchorSource = 0;187188} // namespace tooling189} // namespace clang190191std::unique_ptr<JSONCompilationDatabase>192JSONCompilationDatabase::loadFromFile(StringRef FilePath,193std::string &ErrorMessage,194JSONCommandLineSyntax Syntax) {195// Don't mmap: if we're a long-lived process, the build system may overwrite.196llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =197llvm::MemoryBuffer::getFile(FilePath, /*IsText=*/false,198/*RequiresNullTerminator=*/true,199/*IsVolatile=*/true);200if (std::error_code Result = DatabaseBuffer.getError()) {201ErrorMessage = "Error while opening JSON database: " + Result.message();202return nullptr;203}204std::unique_ptr<JSONCompilationDatabase> Database(205new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));206if (!Database->parse(ErrorMessage))207return nullptr;208return Database;209}210211std::unique_ptr<JSONCompilationDatabase>212JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,213std::string &ErrorMessage,214JSONCommandLineSyntax Syntax) {215std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(216llvm::MemoryBuffer::getMemBufferCopy(DatabaseString));217std::unique_ptr<JSONCompilationDatabase> Database(218new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax));219if (!Database->parse(ErrorMessage))220return nullptr;221return Database;222}223224std::vector<CompileCommand>225JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const {226SmallString<128> NativeFilePath;227llvm::sys::path::native(FilePath, NativeFilePath);228229std::string Error;230llvm::raw_string_ostream ES(Error);231StringRef Match = MatchTrie.findEquivalent(NativeFilePath, ES);232if (Match.empty())233return {};234const auto CommandsRefI = IndexByFile.find(Match);235if (CommandsRefI == IndexByFile.end())236return {};237std::vector<CompileCommand> Commands;238getCommands(CommandsRefI->getValue(), Commands);239return Commands;240}241242std::vector<std::string>243JSONCompilationDatabase::getAllFiles() const {244std::vector<std::string> Result;245for (const auto &CommandRef : IndexByFile)246Result.push_back(CommandRef.first().str());247return Result;248}249250std::vector<CompileCommand>251JSONCompilationDatabase::getAllCompileCommands() const {252std::vector<CompileCommand> Commands;253getCommands(AllCommands, Commands);254return Commands;255}256257static llvm::StringRef stripExecutableExtension(llvm::StringRef Name) {258Name.consume_back(".exe");259return Name;260}261262// There are compiler-wrappers (ccache, distcc) that take the "real"263// compiler as an argument, e.g. distcc gcc -O3 foo.c.264// These end up in compile_commands.json when people set CC="distcc gcc".265// Clang's driver doesn't understand this, so we need to unwrap.266static bool unwrapCommand(std::vector<std::string> &Args) {267if (Args.size() < 2)268return false;269StringRef Wrapper =270stripExecutableExtension(llvm::sys::path::filename(Args.front()));271if (Wrapper == "distcc" || Wrapper == "ccache" || Wrapper == "sccache") {272// Most of these wrappers support being invoked 3 ways:273// `distcc g++ file.c` This is the mode we're trying to match.274// We need to drop `distcc`.275// `distcc file.c` This acts like compiler is cc or similar.276// Clang's driver can handle this, no change needed.277// `g++ file.c` g++ is a symlink to distcc.278// We don't even notice this case, and all is well.279//280// We need to distinguish between the first and second case.281// The wrappers themselves don't take flags, so Args[1] is a compiler flag,282// an input file, or a compiler. Inputs have extensions, compilers don't.283bool HasCompiler =284(Args[1][0] != '-') &&285!llvm::sys::path::has_extension(stripExecutableExtension(Args[1]));286if (HasCompiler) {287Args.erase(Args.begin());288return true;289}290// If !HasCompiler, wrappers act like GCC. Fine: so do we.291}292return false;293}294295static std::vector<std::string>296nodeToCommandLine(JSONCommandLineSyntax Syntax,297const std::vector<llvm::yaml::ScalarNode *> &Nodes) {298SmallString<1024> Storage;299std::vector<std::string> Arguments;300if (Nodes.size() == 1)301Arguments = unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));302else303for (const auto *Node : Nodes)304Arguments.push_back(std::string(Node->getValue(Storage)));305// There may be multiple wrappers: using distcc and ccache together is common.306while (unwrapCommand(Arguments))307;308return Arguments;309}310311void JSONCompilationDatabase::getCommands(312ArrayRef<CompileCommandRef> CommandsRef,313std::vector<CompileCommand> &Commands) const {314for (const auto &CommandRef : CommandsRef) {315SmallString<8> DirectoryStorage;316SmallString<32> FilenameStorage;317SmallString<32> OutputStorage;318auto Output = std::get<3>(CommandRef);319Commands.emplace_back(320std::get<0>(CommandRef)->getValue(DirectoryStorage),321std::get<1>(CommandRef)->getValue(FilenameStorage),322nodeToCommandLine(Syntax, std::get<2>(CommandRef)),323Output ? Output->getValue(OutputStorage) : "");324}325}326327bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {328llvm::yaml::document_iterator I = YAMLStream.begin();329if (I == YAMLStream.end()) {330ErrorMessage = "Error while parsing YAML.";331return false;332}333llvm::yaml::Node *Root = I->getRoot();334if (!Root) {335ErrorMessage = "Error while parsing YAML.";336return false;337}338auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);339if (!Array) {340ErrorMessage = "Expected array.";341return false;342}343for (auto &NextObject : *Array) {344auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);345if (!Object) {346ErrorMessage = "Expected object.";347return false;348}349llvm::yaml::ScalarNode *Directory = nullptr;350std::optional<std::vector<llvm::yaml::ScalarNode *>> Command;351llvm::yaml::ScalarNode *File = nullptr;352llvm::yaml::ScalarNode *Output = nullptr;353for (auto& NextKeyValue : *Object) {354auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());355if (!KeyString) {356ErrorMessage = "Expected strings as key.";357return false;358}359SmallString<10> KeyStorage;360StringRef KeyValue = KeyString->getValue(KeyStorage);361llvm::yaml::Node *Value = NextKeyValue.getValue();362if (!Value) {363ErrorMessage = "Expected value.";364return false;365}366auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value);367auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value);368if (KeyValue == "arguments") {369if (!SequenceString) {370ErrorMessage = "Expected sequence as value.";371return false;372}373Command = std::vector<llvm::yaml::ScalarNode *>();374for (auto &Argument : *SequenceString) {375auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);376if (!Scalar) {377ErrorMessage = "Only strings are allowed in 'arguments'.";378return false;379}380Command->push_back(Scalar);381}382} else {383if (!ValueString) {384ErrorMessage = "Expected string as value.";385return false;386}387if (KeyValue == "directory") {388Directory = ValueString;389} else if (KeyValue == "command") {390if (!Command)391Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);392} else if (KeyValue == "file") {393File = ValueString;394} else if (KeyValue == "output") {395Output = ValueString;396} else {397ErrorMessage =398("Unknown key: \"" + KeyString->getRawValue() + "\"").str();399return false;400}401}402}403if (!File) {404ErrorMessage = "Missing key: \"file\".";405return false;406}407if (!Command) {408ErrorMessage = "Missing key: \"command\" or \"arguments\".";409return false;410}411if (!Directory) {412ErrorMessage = "Missing key: \"directory\".";413return false;414}415SmallString<8> FileStorage;416StringRef FileName = File->getValue(FileStorage);417SmallString<128> NativeFilePath;418if (llvm::sys::path::is_relative(FileName)) {419SmallString<8> DirectoryStorage;420SmallString<128> AbsolutePath(Directory->getValue(DirectoryStorage));421llvm::sys::path::append(AbsolutePath, FileName);422llvm::sys::path::native(AbsolutePath, NativeFilePath);423} else {424llvm::sys::path::native(FileName, NativeFilePath);425}426llvm::sys::path::remove_dots(NativeFilePath, /*remove_dot_dot=*/true);427auto Cmd = CompileCommandRef(Directory, File, *Command, Output);428IndexByFile[NativeFilePath].push_back(Cmd);429AllCommands.push_back(Cmd);430MatchTrie.insert(NativeFilePath);431}432return true;433}434435436