13#include "clang/Driver/Driver.h"
14#include "clang/Driver/Options.h"
15#include "clang/Frontend/CompilerInvocation.h"
16#include "clang/Tooling/CompilationDatabase.h"
17#include "clang/Tooling/Tooling.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Option/ArgList.h"
23#include "llvm/Option/Option.h"
24#include "llvm/Support/Allocator.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/FileUtilities.h"
28#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/Path.h"
30#include "llvm/Support/Program.h"
31#include "llvm/TargetParser/Host.h"
43std::optional<std::string> queryXcrun(llvm::ArrayRef<llvm::StringRef> Argv) {
44 auto Xcrun = llvm::sys::findProgramByName(
"xcrun");
46 log(
"Couldn't find xcrun. Hopefully you have a non-apple toolchain...");
49 llvm::SmallString<64> OutFile;
50 llvm::sys::fs::createTemporaryFile(
"clangd-xcrun",
"", OutFile);
51 llvm::FileRemover OutRemover(OutFile);
52 std::optional<llvm::StringRef> Redirects[3] = {
53 {
""}, {OutFile.str()}, {
""}};
54 vlog(
"Invoking {0} to find clang installation", *Xcrun);
55 int Ret = llvm::sys::ExecuteAndWait(*Xcrun, Argv,
56 std::nullopt, Redirects,
59 log(
"xcrun exists but failed with code {0}. "
60 "If you have a non-apple toolchain, this is OK. "
61 "Otherwise, try xcode-select --install.",
66 auto Buf = llvm::MemoryBuffer::getFile(OutFile);
68 log(
"Can't read xcrun output: {0}", Buf.getError().message());
71 StringRef
Path = Buf->get()->getBuffer().trim();
73 log(
"xcrun produced no output");
80std::string resolve(std::string
Path) {
81 llvm::SmallString<128> Resolved;
82 if (llvm::sys::fs::real_path(
Path, Resolved)) {
83 log(
"Failed to resolve possible symlink {0}",
Path);
86 return std::string(Resolved.str());
92std::string detectClangPath() {
104 if (
auto MacClang = queryXcrun({
"xcrun",
"--find",
"clang"}))
105 return resolve(std::move(*MacClang));
108 for (
const char *
Name : {
"clang",
"gcc",
"cc"})
109 if (
auto PathCC = llvm::sys::findProgramByName(
Name))
110 return resolve(std::move(*PathCC));
112 static int StaticForMainAddr;
113 std::string ClangdExecutable =
114 llvm::sys::fs::getMainExecutable(
"clangd", (
void *)&StaticForMainAddr);
115 SmallString<128> ClangPath;
116 ClangPath = llvm::sys::path::parent_path(ClangdExecutable);
117 llvm::sys::path::append(ClangPath,
"clang");
118 return std::string(ClangPath.str());
123std::optional<std::string> detectSysroot() {
129 if (::getenv(
"SDKROOT"))
131 return queryXcrun({
"xcrun",
"--show-sdk-path"});
134std::string detectStandardResourceDir() {
135 static int StaticForMainAddr;
136 return CompilerInvocation::GetResourcesPath(
"clangd",
137 (
void *)&StaticForMainAddr);
145static std::string resolveDriver(llvm::StringRef
Driver,
bool FollowSymlink,
146 std::optional<std::string> ClangPath) {
147 auto SiblingOf = [&](llvm::StringRef AbsPath) {
148 llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath);
149 llvm::sys::path::append(Result, llvm::sys::path::filename(
Driver));
150 return Result.str().str();
155 if (!llvm::sys::path::is_absolute(
Driver)) {
160 [](
char C) {
return llvm::sys::path::is_separator(
C); }))
166 return SiblingOf(*ClangPath);
169 auto Absolute = llvm::sys::findProgramByName(
Driver);
170 if (Absolute && llvm::sys::path::is_absolute(*Absolute))
171 Driver = Storage = std::move(*Absolute);
173 return SiblingOf(*ClangPath);
179 assert(llvm::sys::path::is_absolute(
Driver));
181 llvm::SmallString<256> Resolved;
182 if (!llvm::sys::fs::real_path(
Driver, Resolved))
183 return SiblingOf(Resolved);
190CommandMangler::CommandMangler() {
191 Tokenizer = llvm::Triple(llvm::sys::getProcessTriple()).isOSWindows()
192 ? llvm::cl::TokenizeWindowsCommandLine
193 : llvm::cl::TokenizeGNUCommandLine;
198 Result.ClangPath = detectClangPath();
199 Result.ResourceDir = detectStandardResourceDir();
200 Result.Sysroot = detectSysroot();
207 llvm::StringRef
File)
const {
208 std::vector<std::string> &Cmd = Command.CommandLine;
221 auto FS = llvm::vfs::getRealFileSystem();
222 tooling::addExpandedResponseFiles(Cmd, Command.Directory, Tokenizer, *FS);
224 auto &OptTable = clang::driver::getDriverOptTable();
226 llvm::SmallVector<const char *, 16> OriginalArgs;
227 OriginalArgs.reserve(Cmd.size());
228 for (
const auto &S : Cmd)
229 OriginalArgs.push_back(S.c_str());
230 bool IsCLMode = driver::IsClangCL(driver::getDriverMode(
231 OriginalArgs[0], llvm::ArrayRef(OriginalArgs).slice(1)));
234 unsigned IgnoredCount;
237 llvm::opt::InputArgList ArgList;
238 ArgList = OptTable.ParseArgs(
239 llvm::ArrayRef(OriginalArgs).drop_front(), IgnoredCount, IgnoredCount,
240 llvm::opt::Visibility(IsCLMode ? driver::options::CLOption
241 : driver::options::ClangOption));
243 llvm::SmallVector<unsigned, 1> IndicesToDrop;
249 unsigned ArchOptCount = 0;
250 for (
auto *Input : ArgList.filtered(driver::options::OPT_arch)) {
252 for (
auto I = 0U; I <= Input->getNumValues(); ++I)
253 IndicesToDrop.push_back(Input->getIndex() + I);
256 if (ArchOptCount < 2)
257 IndicesToDrop.clear();
269 llvm::StringRef FileExtension = llvm::sys::path::extension(
File);
270 std::optional<std::string> TransferFrom;
271 auto SawInput = [&](llvm::StringRef Input) {
272 if (llvm::sys::path::extension(Input) != FileExtension)
273 TransferFrom.emplace(Input);
280 for (
auto *Input : ArgList.filtered(driver::options::OPT_INPUT)) {
281 SawInput(Input->getValue(0));
282 IndicesToDrop.push_back(Input->getIndex());
286 ArgList.getLastArgNoClaim(driver::options::OPT__DASH_DASH)) {
287 auto DashDashIndex = DashDash->getIndex() + 1;
288 for (
unsigned I = DashDashIndex; I < Cmd.size(); ++I)
290 Cmd.resize(DashDashIndex);
292 llvm::sort(IndicesToDrop);
293 for (
unsigned Idx : llvm::reverse(IndicesToDrop))
296 Cmd.erase(Cmd.begin() + Idx + 1);
300 Cmd.push_back(
File.str());
303 tooling::CompileCommand TransferCmd;
304 TransferCmd.Filename = std::move(*TransferFrom);
305 TransferCmd.CommandLine = std::move(Cmd);
306 TransferCmd = transferCompileCommand(std::move(TransferCmd),
File);
307 Cmd = std::move(TransferCmd.CommandLine);
308 assert(Cmd.size() >= 2 && Cmd.back() ==
File &&
309 Cmd[Cmd.size() - 2] ==
"--" &&
310 "TransferCommand should produce a command ending in -- filename");
329 tooling::addTargetAndModeForProgramName(Cmd, Cmd.front());
332 auto Has = [&](llvm::StringRef Flag) {
333 for (llvm::StringRef Arg : Cmd) {
334 if (Arg.consume_front(Flag) && (Arg.empty() || Arg[0] ==
'='))
340 llvm::erase_if(Cmd, [](llvm::StringRef Elem) {
341 return Elem.startswith(
"--save-temps") || Elem.startswith(
"-save-temps");
344 std::vector<std::string> ToAppend;
346 ToAppend.push_back((
"-resource-dir=" + *
ResourceDir));
350 if (
Sysroot && !Has(
"-isysroot") && !Has(
"--sysroot")) {
351 ToAppend.push_back(
"-isysroot");
355 if (!ToAppend.empty()) {
356 Cmd.insert(llvm::find(Cmd,
"--"), std::make_move_iterator(ToAppend.begin()),
357 std::make_move_iterator(ToAppend.end()));
361 bool FollowSymlink = !Has(
"-no-canonical-prefixes");
363 (FollowSymlink ? ResolvedDrivers : ResolvedDriversNoFollow)
364 .get(Cmd.front(), [&,
this] {
365 return resolveDriver(Cmd.front(), FollowSymlink,
ClangPath);
375std::pair<unsigned, unsigned> getArgCount(
const llvm::opt::Option &Opt) {
376 constexpr static unsigned Rest = 10000;
378 using llvm::opt::Option;
379 switch (Opt.getKind()) {
380 case Option::FlagClass:
382 case Option::JoinedClass:
383 case Option::CommaJoinedClass:
385 case Option::GroupClass:
386 case Option::InputClass:
387 case Option::UnknownClass:
388 case Option::ValuesClass:
390 case Option::JoinedAndSeparateClass:
392 case Option::SeparateClass:
394 case Option::MultiArgClass:
395 return {1 + Opt.getNumArgs(), 0};
396 case Option::JoinedOrSeparateClass:
398 case Option::RemainingArgsClass:
400 case Option::RemainingArgsJoinedClass:
403 llvm_unreachable(
"Unhandled option kind");
407enum DriverMode :
unsigned char {
416DriverMode getDriverMode(
const std::vector<std::string> &
Args) {
417 DriverMode Mode = DM_GCC;
419 if (
Argv0.ends_with_insensitive(
".exe"))
421 if (
Argv0.ends_with_insensitive(
"cl"))
423 for (
const llvm::StringRef Arg :
Args) {
424 if (Arg ==
"--driver-mode=cl") {
437unsigned char getModes(
const llvm::opt::Option &Opt) {
438 unsigned char Result = DM_None;
439 if (Opt.hasVisibilityFlag(driver::options::ClangOption))
441 if (Opt.hasVisibilityFlag(driver::options::CC1Option))
443 if (Opt.hasVisibilityFlag(driver::options::CLOption))
450llvm::ArrayRef<ArgStripper::Rule> ArgStripper::rulesFor(llvm::StringRef Arg) {
455 llvm::StringMap<llvm::SmallVector<Rule, 4>, llvm::BumpPtrAllocator>;
456 static TableTy *Table = [] {
457 auto &DriverTable = driver::getDriverOptTable();
458 using DriverID = clang::driver::options::ID;
463 DriverID PrevAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
464 DriverID NextAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
465 auto AddAlias = [&](DriverID Self, DriverID T) {
467 PrevAlias[NextAlias[T]] = Self;
468 NextAlias[Self] = NextAlias[T];
474 llvm::ArrayRef<llvm::StringLiteral> Prefixes[DriverID::LastOption];
476#define PREFIX(NAME, VALUE) \
477 static constexpr llvm::StringLiteral NAME##_init[] = VALUE; \
478 static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME( \
479 NAME##_init, std::size(NAME##_init) - 1);
480#define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, \
481 FLAGS, VISIBILITY, PARAM, HELP, METAVAR, VALUES) \
482 Prefixes[DriverID::OPT_##ID] = PREFIX;
483#include "clang/Driver/Options.inc"
490 const void *AliasArgs;
492#define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, \
493 FLAGS, VISIBILITY, PARAM, HELP, METAVAR, VALUES) \
494 {DriverID::OPT_##ID, DriverID::OPT_##ALIAS, ALIASARGS},
495#include "clang/Driver/Options.inc"
498 for (
auto &
E : AliasTable)
499 if (
E.AliasID != DriverID::OPT_INVALID &&
E.AliasArgs ==
nullptr)
500 AddAlias(
E.ID,
E.AliasID);
502 auto Result = std::make_unique<TableTy>();
505 for (
unsigned ID = 1 ;
ID < DriverID::LastOption; ++
ID) {
506 if (PrevAlias[
ID] ||
ID == DriverID::OPT_Xclang)
508 llvm::SmallVector<Rule> Rules;
510 for (
unsigned A =
ID;
A != DriverID::OPT_INVALID;
A = NextAlias[
A]) {
511 if (!Prefixes[A].size())
513 auto Opt = DriverTable.getOption(A);
515 if (Opt.getName().empty())
517 auto Modes = getModes(Opt);
518 std::pair<unsigned, unsigned> ArgCount = getArgCount(Opt);
520 for (StringRef Prefix : Prefixes[A]) {
521 llvm::SmallString<64> Buf(Prefix);
522 Buf.append(Opt.getName());
523 llvm::StringRef Spelling = Result->try_emplace(Buf).first->getKey();
524 Rules.emplace_back();
525 Rule &R = Rules.back();
528 R.ExactArgs = ArgCount.first;
529 R.PrefixArgs = ArgCount.second;
532 assert(
ID < std::numeric_limits<
decltype(R.Priority)>::max() &&
533 "Rules::Priority overflowed by options table");
538 for (
const auto &R : Rules)
539 Result->find(R.Text)->second.append(Rules.begin(), Rules.end());
543 unsigned RuleCount = 0;
544 dlog(
"ArgStripper Option spelling table");
545 for (
const auto &
Entry : *Result) {
547 RuleCount +=
Entry.second.size();
548 for (
const auto &R :
Entry.second)
549 dlog(
" {0} #={1} *={2} Mode={3}", R.Text, R.ExactArgs, R.PrefixArgs,
552 dlog(
"Table spellings={0} rules={1} string-bytes={2}", Result->size(),
553 RuleCount, Result->getAllocator().getBytesAllocated());
556 return Result.release();
559 auto It = Table->find(Arg);
560 return (It == Table->end()) ? llvm::ArrayRef<Rule>() : It->second;
564 auto OptionRules = rulesFor(Arg);
565 if (OptionRules.empty()) {
567 Storage.emplace_back(Arg);
568 Rules.emplace_back();
569 Rules.back().Text = Storage.back();
570 Rules.back().ExactArgs = 1;
571 if (Rules.back().Text.consume_back(
"*"))
572 Rules.back().PrefixArgs = 1;
573 Rules.back().Modes = DM_All;
574 Rules.back().Priority = -1;
576 Rules.append(OptionRules.begin(), OptionRules.end());
580const ArgStripper::Rule *ArgStripper::matchingRule(llvm::StringRef Arg,
582 unsigned &ArgCount)
const {
583 const ArgStripper::Rule *BestRule =
nullptr;
584 for (
const Rule &R : Rules) {
586 if (!(R.Modes & Mode))
588 if (BestRule && BestRule->Priority < R.Priority)
590 if (!Arg.startswith(R.Text))
592 bool PrefixMatch = Arg.size() > R.Text.size();
594 if (
unsigned Count = PrefixMatch ? R.PrefixArgs : R.ExactArgs) {
609 DriverMode MainMode = getDriverMode(
Args);
610 DriverMode CurrentMode = MainMode;
614 bool WasXclang =
false;
616 unsigned ArgCount = 0;
617 if (matchingRule(
Args[
Read], CurrentMode, ArgCount)) {
622 CurrentMode = MainMode;
626 for (
unsigned I = 1;
Read <
Args.size() && I < ArgCount; ++I) {
633 WasXclang =
Args[
Read] ==
"-Xclang";
634 CurrentMode = WasXclang ? DM_CC1 : MainMode;
646 llvm::raw_string_ostream
OS(Buf);
648 for (llvm::StringRef Arg :
Args) {
652 if (llvm::all_of(Arg, llvm::isPrint) &&
653 Arg.find_first_of(
" \t\n\"\\") == llvm::StringRef::npos) {
658 OS.write_escaped(Arg,
true);
661 return std::move(
OS.str());
665 std::vector<llvm::StringRef> Refs(
Args.size());
666 llvm::copy(
Args, Refs.begin());
llvm::raw_string_ostream OS
void process(std::vector< std::string > &Args) const
void strip(llvm::StringRef Arg)
Records an event whose duration is the lifetime of the Span object.
std::string Path
A typedef to represent a file path.
void vlog(const char *Fmt, Ts &&... Vals)
void log(const char *Fmt, Ts &&... Vals)
std::string printArgv(llvm::ArrayRef< llvm::StringRef > Args)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
std::optional< std::string > ResourceDir
static CommandMangler detect()
SystemIncludeExtractorFn SystemIncludeExtractor
std::optional< std::string > ClangPath
std::optional< std::string > Sysroot
static CommandMangler forTests()
void operator()(tooling::CompileCommand &Cmd, llvm::StringRef TargetFile) const
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
std::vector< llvm::unique_function< void(std::vector< std::string > &) const > > Edits
Edits to apply to the compile command, in sequence.
A set of edits generated for a single file.