Path: blob/main/contrib/llvm-project/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
35233 views
//===- InterpolatingCompilationDatabase.cpp ---------------------*- C++ -*-===//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// InterpolatingCompilationDatabase wraps another CompilationDatabase and9// attempts to heuristically determine appropriate compile commands for files10// that are not included, such as headers or newly created files.11//12// Motivating cases include:13// Header files that live next to their implementation files. These typically14// share a base filename. (libclang/CXString.h, libclang/CXString.cpp).15// Some projects separate headers from includes. Filenames still typically16// match, maybe other path segments too. (include/llvm/IR/Use.h, lib/IR/Use.cc).17// Matches are sometimes only approximate (Sema.h, SemaDecl.cpp). This goes18// for directories too (Support/Unix/Process.inc, lib/Support/Process.cpp).19// Even if we can't find a "right" compile command, even a random one from20// the project will tend to get important flags like -I and -x right.21//22// We "borrow" the compile command for the closest available file:23// - points are awarded if the filename matches (ignoring extension)24// - points are awarded if the directory structure matches25// - ties are broken by length of path prefix match26//27// The compile command is adjusted, replacing the filename and removing output28// file arguments. The -x and -std flags may be affected too.29//30// Source language is a tricky issue: is it OK to use a .c file's command31// for building a .cc file? What language is a .h file in?32// - We only consider compile commands for c-family languages as candidates.33// - For files whose language is implied by the filename (e.g. .m, .hpp)34// we prefer candidates from the same language.35// If we must cross languages, we drop any -x and -std flags.36// - For .h files, candidates from any c-family language are acceptable.37// We use the candidate's language, inserting e.g. -x c++-header.38//39// This class is only useful when wrapping databases that can enumerate all40// their compile commands. If getAllFilenames() is empty, no inference occurs.41//42//===----------------------------------------------------------------------===//4344#include "clang/Basic/LangStandard.h"45#include "clang/Driver/Driver.h"46#include "clang/Driver/Options.h"47#include "clang/Driver/Types.h"48#include "clang/Tooling/CompilationDatabase.h"49#include "llvm/ADT/ArrayRef.h"50#include "llvm/ADT/DenseMap.h"51#include "llvm/ADT/StringExtras.h"52#include "llvm/Option/ArgList.h"53#include "llvm/Option/OptTable.h"54#include "llvm/Support/Debug.h"55#include "llvm/Support/Path.h"56#include "llvm/Support/StringSaver.h"57#include "llvm/Support/raw_ostream.h"58#include <memory>59#include <optional>6061namespace clang {62namespace tooling {63namespace {64using namespace llvm;65namespace types = clang::driver::types;66namespace path = llvm::sys::path;6768// The length of the prefix these two strings have in common.69size_t matchingPrefix(StringRef L, StringRef R) {70size_t Limit = std::min(L.size(), R.size());71for (size_t I = 0; I < Limit; ++I)72if (L[I] != R[I])73return I;74return Limit;75}7677// A comparator for searching SubstringWithIndexes with std::equal_range etc.78// Optionaly prefix semantics: compares equal if the key is a prefix.79template <bool Prefix> struct Less {80bool operator()(StringRef Key, std::pair<StringRef, size_t> Value) const {81StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;82return Key < V;83}84bool operator()(std::pair<StringRef, size_t> Value, StringRef Key) const {85StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;86return V < Key;87}88};8990// Infer type from filename. If we might have gotten it wrong, set *Certain.91// *.h will be inferred as a C header, but not certain.92types::ID guessType(StringRef Filename, bool *Certain = nullptr) {93// path::extension is ".cpp", lookupTypeForExtension wants "cpp".94auto Lang =95types::lookupTypeForExtension(path::extension(Filename).substr(1));96if (Certain)97*Certain = Lang != types::TY_CHeader && Lang != types::TY_INVALID;98return Lang;99}100101// Return Lang as one of the canonical supported types.102// e.g. c-header --> c; fortran --> TY_INVALID103static types::ID foldType(types::ID Lang) {104switch (Lang) {105case types::TY_C:106case types::TY_CHeader:107return types::TY_C;108case types::TY_ObjC:109case types::TY_ObjCHeader:110return types::TY_ObjC;111case types::TY_CXX:112case types::TY_CXXHeader:113return types::TY_CXX;114case types::TY_ObjCXX:115case types::TY_ObjCXXHeader:116return types::TY_ObjCXX;117case types::TY_CUDA:118case types::TY_CUDA_DEVICE:119return types::TY_CUDA;120default:121return types::TY_INVALID;122}123}124125// A CompileCommand that can be applied to another file.126struct TransferableCommand {127// Flags that should not apply to all files are stripped from CommandLine.128CompileCommand Cmd;129// Language detected from -x or the filename. Never TY_INVALID.130std::optional<types::ID> Type;131// Standard specified by -std.132LangStandard::Kind Std = LangStandard::lang_unspecified;133// Whether the command line is for the cl-compatible driver.134bool ClangCLMode;135136TransferableCommand(CompileCommand C)137: Cmd(std::move(C)), Type(guessType(Cmd.Filename)) {138std::vector<std::string> OldArgs = std::move(Cmd.CommandLine);139Cmd.CommandLine.clear();140141// Wrap the old arguments in an InputArgList.142llvm::opt::InputArgList ArgList;143{144SmallVector<const char *, 16> TmpArgv;145for (const std::string &S : OldArgs)146TmpArgv.push_back(S.c_str());147ClangCLMode = !TmpArgv.empty() &&148driver::IsClangCL(driver::getDriverMode(149TmpArgv.front(), llvm::ArrayRef(TmpArgv).slice(1)));150ArgList = {TmpArgv.begin(), TmpArgv.end()};151}152153// Parse the old args in order to strip out and record unwanted flags.154// We parse each argument individually so that we can retain the exact155// spelling of each argument; re-rendering is lossy for aliased flags.156// E.g. in CL mode, /W4 maps to -Wall.157auto &OptTable = clang::driver::getDriverOptTable();158if (!OldArgs.empty())159Cmd.CommandLine.emplace_back(OldArgs.front());160for (unsigned Pos = 1; Pos < OldArgs.size();) {161using namespace driver::options;162163const unsigned OldPos = Pos;164std::unique_ptr<llvm::opt::Arg> Arg(OptTable.ParseOneArg(165ArgList, Pos,166llvm::opt::Visibility(ClangCLMode ? CLOption : ClangOption)));167168if (!Arg)169continue;170171const llvm::opt::Option &Opt = Arg->getOption();172173// Strip input and output files.174if (Opt.matches(OPT_INPUT) || Opt.matches(OPT_o) ||175(ClangCLMode && (Opt.matches(OPT__SLASH_Fa) ||176Opt.matches(OPT__SLASH_Fe) ||177Opt.matches(OPT__SLASH_Fi) ||178Opt.matches(OPT__SLASH_Fo))))179continue;180181// ...including when the inputs are passed after --.182if (Opt.matches(OPT__DASH_DASH))183break;184185// Strip -x, but record the overridden language.186if (const auto GivenType = tryParseTypeArg(*Arg)) {187Type = *GivenType;188continue;189}190191// Strip -std, but record the value.192if (const auto GivenStd = tryParseStdArg(*Arg)) {193if (*GivenStd != LangStandard::lang_unspecified)194Std = *GivenStd;195continue;196}197198Cmd.CommandLine.insert(Cmd.CommandLine.end(),199OldArgs.data() + OldPos, OldArgs.data() + Pos);200}201202// Make use of -std iff -x was missing.203if (Type == types::TY_INVALID && Std != LangStandard::lang_unspecified)204Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage());205Type = foldType(*Type);206// The contract is to store None instead of TY_INVALID.207if (Type == types::TY_INVALID)208Type = std::nullopt;209}210211// Produce a CompileCommand for \p filename, based on this one.212// (This consumes the TransferableCommand just to avoid copying Cmd).213CompileCommand transferTo(StringRef Filename) && {214CompileCommand Result = std::move(Cmd);215Result.Heuristic = "inferred from " + Result.Filename;216Result.Filename = std::string(Filename);217bool TypeCertain;218auto TargetType = guessType(Filename, &TypeCertain);219// If the filename doesn't determine the language (.h), transfer with -x.220if ((!TargetType || !TypeCertain) && Type) {221// Use *Type, or its header variant if the file is a header.222// Treat no/invalid extension as header (e.g. C++ standard library).223TargetType =224(!TargetType || types::onlyPrecompileType(TargetType)) // header?225? types::lookupHeaderTypeForSourceType(*Type)226: *Type;227if (ClangCLMode) {228const StringRef Flag = toCLFlag(TargetType);229if (!Flag.empty())230Result.CommandLine.push_back(std::string(Flag));231} else {232Result.CommandLine.push_back("-x");233Result.CommandLine.push_back(types::getTypeName(TargetType));234}235}236// --std flag may only be transferred if the language is the same.237// We may consider "translating" these, e.g. c++11 -> c11.238if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) {239Result.CommandLine.emplace_back((240llvm::Twine(ClangCLMode ? "/std:" : "-std=") +241LangStandard::getLangStandardForKind(Std).getName()).str());242}243Result.CommandLine.push_back("--");244Result.CommandLine.push_back(std::string(Filename));245return Result;246}247248private:249// Map the language from the --std flag to that of the -x flag.250static types::ID toType(Language Lang) {251switch (Lang) {252case Language::C:253return types::TY_C;254case Language::CXX:255return types::TY_CXX;256case Language::ObjC:257return types::TY_ObjC;258case Language::ObjCXX:259return types::TY_ObjCXX;260default:261return types::TY_INVALID;262}263}264265// Convert a file type to the matching CL-style type flag.266static StringRef toCLFlag(types::ID Type) {267switch (Type) {268case types::TY_C:269case types::TY_CHeader:270return "/TC";271case types::TY_CXX:272case types::TY_CXXHeader:273return "/TP";274default:275return StringRef();276}277}278279// Try to interpret the argument as a type specifier, e.g. '-x'.280std::optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) {281const llvm::opt::Option &Opt = Arg.getOption();282using namespace driver::options;283if (ClangCLMode) {284if (Opt.matches(OPT__SLASH_TC) || Opt.matches(OPT__SLASH_Tc))285return types::TY_C;286if (Opt.matches(OPT__SLASH_TP) || Opt.matches(OPT__SLASH_Tp))287return types::TY_CXX;288} else {289if (Opt.matches(driver::options::OPT_x))290return types::lookupTypeForTypeSpecifier(Arg.getValue());291}292return std::nullopt;293}294295// Try to interpret the argument as '-std='.296std::optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) {297using namespace driver::options;298if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ))299return LangStandard::getLangKind(Arg.getValue());300return std::nullopt;301}302};303304// Given a filename, FileIndex picks the best matching file from the underlying305// DB. This is the proxy file whose CompileCommand will be reused. The306// heuristics incorporate file name, extension, and directory structure.307// Strategy:308// - Build indexes of each of the substrings we want to look up by.309// These indexes are just sorted lists of the substrings.310// - Each criterion corresponds to a range lookup into the index, so we only311// need O(log N) string comparisons to determine scores.312//313// Apart from path proximity signals, also takes file extensions into account314// when scoring the candidates.315class FileIndex {316public:317FileIndex(std::vector<std::string> Files)318: OriginalPaths(std::move(Files)), Strings(Arena) {319// Sort commands by filename for determinism (index is a tiebreaker later).320llvm::sort(OriginalPaths);321Paths.reserve(OriginalPaths.size());322Types.reserve(OriginalPaths.size());323Stems.reserve(OriginalPaths.size());324for (size_t I = 0; I < OriginalPaths.size(); ++I) {325StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower());326327Paths.emplace_back(Path, I);328Types.push_back(foldType(guessType(OriginalPaths[I])));329Stems.emplace_back(sys::path::stem(Path), I);330auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path);331for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir)332if (Dir->size() > ShortDirectorySegment) // not trivial ones333Components.emplace_back(*Dir, I);334}335llvm::sort(Paths);336llvm::sort(Stems);337llvm::sort(Components);338}339340bool empty() const { return Paths.empty(); }341342// Returns the path for the file that best fits OriginalFilename.343// Candidates with extensions matching PreferLanguage will be chosen over344// others (unless it's TY_INVALID, or all candidates are bad).345StringRef chooseProxy(StringRef OriginalFilename,346types::ID PreferLanguage) const {347assert(!empty() && "need at least one candidate!");348std::string Filename = OriginalFilename.lower();349auto Candidates = scoreCandidates(Filename);350std::pair<size_t, int> Best =351pickWinner(Candidates, Filename, PreferLanguage);352353DEBUG_WITH_TYPE(354"interpolate",355llvm::dbgs() << "interpolate: chose " << OriginalPaths[Best.first]356<< " as proxy for " << OriginalFilename << " preferring "357<< (PreferLanguage == types::TY_INVALID358? "none"359: types::getTypeName(PreferLanguage))360<< " score=" << Best.second << "\n");361return OriginalPaths[Best.first];362}363364private:365using SubstringAndIndex = std::pair<StringRef, size_t>;366// Directory matching parameters: we look at the last two segments of the367// parent directory (usually the semantically significant ones in practice).368// We search only the last four of each candidate (for efficiency).369constexpr static int DirectorySegmentsIndexed = 4;370constexpr static int DirectorySegmentsQueried = 2;371constexpr static int ShortDirectorySegment = 1; // Only look at longer names.372373// Award points to candidate entries that should be considered for the file.374// Returned keys are indexes into paths, and the values are (nonzero) scores.375DenseMap<size_t, int> scoreCandidates(StringRef Filename) const {376// Decompose Filename into the parts we care about.377// /some/path/complicated/project/Interesting.h378// [-prefix--][---dir---] [-dir-] [--stem---]379StringRef Stem = sys::path::stem(Filename);380llvm::SmallVector<StringRef, DirectorySegmentsQueried> Dirs;381llvm::StringRef Prefix;382auto Dir = ++sys::path::rbegin(Filename),383DirEnd = sys::path::rend(Filename);384for (int I = 0; I < DirectorySegmentsQueried && Dir != DirEnd; ++I, ++Dir) {385if (Dir->size() > ShortDirectorySegment)386Dirs.push_back(*Dir);387Prefix = Filename.substr(0, Dir - DirEnd);388}389390// Now award points based on lookups into our various indexes.391DenseMap<size_t, int> Candidates; // Index -> score.392auto Award = [&](int Points, ArrayRef<SubstringAndIndex> Range) {393for (const auto &Entry : Range)394Candidates[Entry.second] += Points;395};396// Award one point if the file's basename is a prefix of the candidate,397// and another if it's an exact match (so exact matches get two points).398Award(1, indexLookup</*Prefix=*/true>(Stem, Stems));399Award(1, indexLookup</*Prefix=*/false>(Stem, Stems));400// For each of the last few directories in the Filename, award a point401// if it's present in the candidate.402for (StringRef Dir : Dirs)403Award(1, indexLookup</*Prefix=*/false>(Dir, Components));404// Award one more point if the whole rest of the path matches.405if (sys::path::root_directory(Prefix) != Prefix)406Award(1, indexLookup</*Prefix=*/true>(Prefix, Paths));407return Candidates;408}409410// Pick a single winner from the set of scored candidates.411// Returns (index, score).412std::pair<size_t, int> pickWinner(const DenseMap<size_t, int> &Candidates,413StringRef Filename,414types::ID PreferredLanguage) const {415struct ScoredCandidate {416size_t Index;417bool Preferred;418int Points;419size_t PrefixLength;420};421// Choose the best candidate by (preferred, points, prefix length, alpha).422ScoredCandidate Best = {size_t(-1), false, 0, 0};423for (const auto &Candidate : Candidates) {424ScoredCandidate S;425S.Index = Candidate.first;426S.Preferred = PreferredLanguage == types::TY_INVALID ||427PreferredLanguage == Types[S.Index];428S.Points = Candidate.second;429if (!S.Preferred && Best.Preferred)430continue;431if (S.Preferred == Best.Preferred) {432if (S.Points < Best.Points)433continue;434if (S.Points == Best.Points) {435S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);436if (S.PrefixLength < Best.PrefixLength)437continue;438// hidden heuristics should at least be deterministic!439if (S.PrefixLength == Best.PrefixLength)440if (S.Index > Best.Index)441continue;442}443}444// PrefixLength was only set above if actually needed for a tiebreak.445// But it definitely needs to be set to break ties in the future.446S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);447Best = S;448}449// Edge case: no candidate got any points.450// We ignore PreferredLanguage at this point (not ideal).451if (Best.Index == size_t(-1))452return {longestMatch(Filename, Paths).second, 0};453return {Best.Index, Best.Points};454}455456// Returns the range within a sorted index that compares equal to Key.457// If Prefix is true, it's instead the range starting with Key.458template <bool Prefix>459ArrayRef<SubstringAndIndex>460indexLookup(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const {461// Use pointers as iteratiors to ease conversion of result to ArrayRef.462auto Range = std::equal_range(Idx.data(), Idx.data() + Idx.size(), Key,463Less<Prefix>());464return {Range.first, Range.second};465}466467// Performs a point lookup into a nonempty index, returning a longest match.468SubstringAndIndex longestMatch(StringRef Key,469ArrayRef<SubstringAndIndex> Idx) const {470assert(!Idx.empty());471// Longest substring match will be adjacent to a direct lookup.472auto It = llvm::lower_bound(Idx, SubstringAndIndex{Key, 0});473if (It == Idx.begin())474return *It;475if (It == Idx.end())476return *--It;477// Have to choose between It and It-1478size_t Prefix = matchingPrefix(Key, It->first);479size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first);480return Prefix > PrevPrefix ? *It : *--It;481}482483// Original paths, everything else is in lowercase.484std::vector<std::string> OriginalPaths;485BumpPtrAllocator Arena;486StringSaver Strings;487// Indexes of candidates by certain substrings.488// String is lowercase and sorted, index points into OriginalPaths.489std::vector<SubstringAndIndex> Paths; // Full path.490// Lang types obtained by guessing on the corresponding path. I-th element is491// a type for the I-th path.492std::vector<types::ID> Types;493std::vector<SubstringAndIndex> Stems; // Basename, without extension.494std::vector<SubstringAndIndex> Components; // Last path components.495};496497// The actual CompilationDatabase wrapper delegates to its inner database.498// If no match, looks up a proxy file in FileIndex and transfers its499// command to the requested file.500class InterpolatingCompilationDatabase : public CompilationDatabase {501public:502InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)503: Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {}504505std::vector<CompileCommand>506getCompileCommands(StringRef Filename) const override {507auto Known = Inner->getCompileCommands(Filename);508if (Index.empty() || !Known.empty())509return Known;510bool TypeCertain;511auto Lang = guessType(Filename, &TypeCertain);512if (!TypeCertain)513Lang = types::TY_INVALID;514auto ProxyCommands =515Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang)));516if (ProxyCommands.empty())517return {};518return {transferCompileCommand(std::move(ProxyCommands.front()), Filename)};519}520521std::vector<std::string> getAllFiles() const override {522return Inner->getAllFiles();523}524525std::vector<CompileCommand> getAllCompileCommands() const override {526return Inner->getAllCompileCommands();527}528529private:530std::unique_ptr<CompilationDatabase> Inner;531FileIndex Index;532};533534} // namespace535536std::unique_ptr<CompilationDatabase>537inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) {538return std::make_unique<InterpolatingCompilationDatabase>(std::move(Inner));539}540541tooling::CompileCommand transferCompileCommand(CompileCommand Cmd,542StringRef Filename) {543return TransferableCommand(std::move(Cmd)).transferTo(Filename);544}545546} // namespace tooling547} // namespace clang548549550