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"
42std::optional<std::string> queryXcrun(llvm::ArrayRef<llvm::StringRef> Argv) {
43 auto Xcrun = llvm::sys::findProgramByName(
"xcrun");
45 log(
"Couldn't find xcrun. Hopefully you have a non-apple toolchain...");
48 llvm::SmallString<64> OutFile;
49 llvm::sys::fs::createTemporaryFile(
"clangd-xcrun",
"", OutFile);
50 llvm::FileRemover OutRemover(OutFile);
51 std::optional<llvm::StringRef> Redirects[3] = {
52 {
""}, {OutFile.str()}, {
""}};
53 vlog(
"Invoking {0} to find clang installation", *Xcrun);
54 int Ret = llvm::sys::ExecuteAndWait(*Xcrun, Argv,
55 std::nullopt, Redirects,
58 log(
"xcrun exists but failed with code {0}. "
59 "If you have a non-apple toolchain, this is OK. "
60 "Otherwise, try xcode-select --install.",
65 auto Buf = llvm::MemoryBuffer::getFile(OutFile);
67 log(
"Can't read xcrun output: {0}", Buf.getError().message());
70 StringRef
Path = Buf->get()->getBuffer().trim();
72 log(
"xcrun produced no output");
79std::string resolve(std::string
Path) {
80 llvm::SmallString<128> Resolved;
81 if (llvm::sys::fs::real_path(
Path, Resolved)) {
82 log(
"Failed to resolve possible symlink {0}",
Path);
85 return std::string(Resolved);
91std::string detectClangPath() {
103 if (
auto MacClang = queryXcrun({
"xcrun",
"--find",
"clang"}))
104 return resolve(std::move(*MacClang));
107 for (
const char *
Name : {
"clang",
"gcc",
"cc"})
108 if (
auto PathCC = llvm::sys::findProgramByName(
Name))
109 return resolve(std::move(*PathCC));
111 static int StaticForMainAddr;
112 std::string ClangdExecutable =
113 llvm::sys::fs::getMainExecutable(
"clangd", (
void *)&StaticForMainAddr);
114 SmallString<128> ClangPath;
115 ClangPath = llvm::sys::path::parent_path(ClangdExecutable);
116 llvm::sys::path::append(ClangPath,
"clang");
117 return std::string(ClangPath);
122std::optional<std::string> detectSysroot() {
128 if (::getenv(
"SDKROOT"))
130 return queryXcrun({
"xcrun",
"--show-sdk-path"});
133std::string detectStandardResourceDir() {
134 static int StaticForMainAddr;
135 return CompilerInvocation::GetResourcesPath(
"clangd",
136 (
void *)&StaticForMainAddr);
144static std::string resolveDriver(llvm::StringRef
Driver,
bool FollowSymlink,
145 std::optional<std::string> ClangPath) {
146 auto SiblingOf = [&](llvm::StringRef AbsPath) {
147 llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath);
148 llvm::sys::path::append(Result, llvm::sys::path::filename(
Driver));
149 return Result.str().str();
154 if (!llvm::sys::path::is_absolute(
Driver)) {
159 [](
char C) {
return llvm::sys::path::is_separator(
C); }))
165 return SiblingOf(*ClangPath);
168 auto Absolute = llvm::sys::findProgramByName(
Driver);
169 if (Absolute && llvm::sys::path::is_absolute(*Absolute))
170 Driver = Storage = std::move(*Absolute);
172 return SiblingOf(*ClangPath);
178 assert(llvm::sys::path::is_absolute(
Driver));
180 llvm::SmallString<256> Resolved;
181 if (!llvm::sys::fs::real_path(
Driver, Resolved))
182 return SiblingOf(Resolved);
191 Result.ClangPath = detectClangPath();
192 Result.ResourceDir = detectStandardResourceDir();
193 Result.Sysroot = detectSysroot();
200 llvm::StringRef
File)
const {
201 std::vector<std::string> &Cmd = Command.CommandLine;
209 auto &OptTable = clang::driver::getDriverOptTable();
211 llvm::SmallVector<const char *, 16> OriginalArgs;
212 OriginalArgs.reserve(Cmd.size());
213 for (
const auto &S : Cmd)
214 OriginalArgs.push_back(S.c_str());
215 bool IsCLMode = driver::IsClangCL(driver::getDriverMode(
216 OriginalArgs[0], llvm::ArrayRef(OriginalArgs).slice(1)));
219 unsigned IgnoredCount;
222 llvm::opt::InputArgList ArgList;
223 ArgList = OptTable.ParseArgs(
224 llvm::ArrayRef(OriginalArgs).drop_front(), IgnoredCount, IgnoredCount,
225 llvm::opt::Visibility(IsCLMode ? driver::options::CLOption
226 : driver::options::ClangOption));
228 llvm::SmallVector<unsigned, 1> IndicesToDrop;
234 unsigned ArchOptCount = 0;
235 for (
auto *Input : ArgList.filtered(driver::options::OPT_arch)) {
237 for (
auto I = 0U; I <= Input->getNumValues(); ++I)
238 IndicesToDrop.push_back(Input->getIndex() + I);
241 if (ArchOptCount < 2)
242 IndicesToDrop.clear();
254 llvm::StringRef FileExtension = llvm::sys::path::extension(
File);
255 std::optional<std::string> TransferFrom;
256 auto SawInput = [&](llvm::StringRef Input) {
257 if (llvm::sys::path::extension(Input) != FileExtension)
258 TransferFrom.emplace(Input);
265 for (
auto *Input : ArgList.filtered(driver::options::OPT_INPUT)) {
266 SawInput(Input->getValue(0));
267 IndicesToDrop.push_back(Input->getIndex());
271 ArgList.getLastArgNoClaim(driver::options::OPT__DASH_DASH)) {
272 auto DashDashIndex = DashDash->getIndex() + 1;
273 for (
unsigned I = DashDashIndex; I < Cmd.size(); ++I)
275 Cmd.resize(DashDashIndex);
277 llvm::sort(IndicesToDrop);
278 for (
unsigned Idx : llvm::reverse(IndicesToDrop))
281 Cmd.erase(Cmd.begin() + Idx + 1);
285 Cmd.push_back(
File.str());
288 tooling::CompileCommand TransferCmd;
289 TransferCmd.Filename = std::move(*TransferFrom);
290 TransferCmd.CommandLine = std::move(Cmd);
291 TransferCmd = transferCompileCommand(std::move(TransferCmd),
File);
292 Cmd = std::move(TransferCmd.CommandLine);
293 assert(Cmd.size() >= 2 && Cmd.back() ==
File &&
294 Cmd[Cmd.size() - 2] ==
"--" &&
295 "TransferCommand should produce a command ending in -- filename");
314 tooling::addTargetAndModeForProgramName(Cmd, Cmd.front());
317 auto HasExact = [&](llvm::StringRef Flag) {
318 return llvm::any_of(Cmd, [&](llvm::StringRef Arg) {
return Arg == Flag; });
322 auto HasPrefix = [&](llvm::StringRef Flag) {
324 Cmd, [&](llvm::StringRef Arg) {
return Arg.starts_with(Flag); });
327 llvm::erase_if(Cmd, [](llvm::StringRef Elem) {
328 return Elem.starts_with(
"--save-temps") || Elem.starts_with(
"-save-temps");
331 std::vector<std::string> ToAppend;
332 if (
ResourceDir && !HasExact(
"-resource-dir") && !HasPrefix(
"-resource-dir="))
333 ToAppend.push_back((
"-resource-dir=" + *
ResourceDir));
337 if (
Sysroot && !HasPrefix(
"-isysroot") && !HasExact(
"--sysroot") &&
338 !HasPrefix(
"--sysroot=")) {
339 ToAppend.push_back(
"-isysroot");
343 if (!ToAppend.empty()) {
344 Cmd.insert(llvm::find(Cmd,
"--"), std::make_move_iterator(ToAppend.begin()),
345 std::make_move_iterator(ToAppend.end()));
349 bool FollowSymlink = !HasExact(
"-no-canonical-prefixes");
351 (FollowSymlink ? ResolvedDrivers : ResolvedDriversNoFollow)
352 .get(Cmd.front(), [&,
this] {
353 return resolveDriver(Cmd.front(), FollowSymlink,
ClangPath);
363std::pair<unsigned, unsigned> getArgCount(
const llvm::opt::Option &Opt) {
364 constexpr static unsigned Rest = 10000;
366 using llvm::opt::Option;
367 switch (Opt.getKind()) {
368 case Option::FlagClass:
370 case Option::JoinedClass:
371 case Option::CommaJoinedClass:
373 case Option::GroupClass:
374 case Option::InputClass:
375 case Option::UnknownClass:
376 case Option::ValuesClass:
378 case Option::JoinedAndSeparateClass:
380 case Option::SeparateClass:
382 case Option::MultiArgClass:
383 return {1 + Opt.getNumArgs(), 0};
384 case Option::JoinedOrSeparateClass:
386 case Option::RemainingArgsClass:
388 case Option::RemainingArgsJoinedClass:
391 llvm_unreachable(
"Unhandled option kind");
395enum DriverMode :
unsigned char {
404DriverMode getDriverMode(
const std::vector<std::string> &
Args) {
405 DriverMode Mode = DM_GCC;
407 if (
Argv0.ends_with_insensitive(
".exe"))
409 if (
Argv0.ends_with_insensitive(
"cl"))
411 for (
const llvm::StringRef Arg :
Args) {
412 if (Arg ==
"--driver-mode=cl") {
425unsigned char getModes(
const llvm::opt::Option &Opt) {
426 unsigned char Result = DM_None;
427 if (Opt.hasVisibilityFlag(driver::options::ClangOption))
429 if (Opt.hasVisibilityFlag(driver::options::CC1Option))
431 if (Opt.hasVisibilityFlag(driver::options::CLOption))
438llvm::ArrayRef<ArgStripper::Rule> ArgStripper::rulesFor(llvm::StringRef Arg) {
443 llvm::StringMap<llvm::SmallVector<Rule, 4>, llvm::BumpPtrAllocator>;
444 static TableTy *Table = [] {
445 auto &DriverTable = driver::getDriverOptTable();
446 using DriverID = clang::driver::options::ID;
451 DriverID PrevAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
452 DriverID NextAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
453 auto AddAlias = [&](DriverID Self, DriverID
T) {
455 PrevAlias[NextAlias[
T]] = Self;
456 NextAlias[Self] = NextAlias[
T];
462 llvm::ArrayRef<llvm::StringLiteral> Prefixes[DriverID::LastOption];
464#define PREFIX(NAME, VALUE) \
465 static constexpr llvm::StringLiteral NAME##_init[] = VALUE; \
466 static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME( \
467 NAME##_init, std::size(NAME##_init) - 1);
468#define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, \
469 FLAGS, VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, \
471 Prefixes[DriverID::OPT_##ID] = PREFIX;
472#include "clang/Driver/Options.inc"
479 const void *AliasArgs;
481#define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, \
482 FLAGS, VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, \
484 {DriverID::OPT_##ID, DriverID::OPT_##ALIAS, ALIASARGS},
485#include "clang/Driver/Options.inc"
488 for (
auto &
E : AliasTable)
489 if (
E.AliasID != DriverID::OPT_INVALID &&
E.AliasArgs ==
nullptr)
490 AddAlias(
E.ID,
E.AliasID);
492 auto Result = std::make_unique<TableTy>();
495 for (
unsigned ID = 1 ;
ID < DriverID::LastOption; ++
ID) {
496 if (PrevAlias[
ID] ||
ID == DriverID::OPT_Xclang)
498 llvm::SmallVector<Rule> Rules;
500 for (
unsigned A =
ID;
A != DriverID::OPT_INVALID;
A = NextAlias[
A]) {
501 if (!Prefixes[A].size())
503 auto Opt = DriverTable.getOption(A);
505 if (Opt.getName().empty())
507 auto Modes = getModes(Opt);
508 std::pair<unsigned, unsigned> ArgCount = getArgCount(Opt);
510 for (StringRef Prefix : Prefixes[A]) {
511 llvm::SmallString<64> Buf(Prefix);
512 Buf.append(Opt.getName());
513 llvm::StringRef Spelling = Result->try_emplace(Buf).first->getKey();
514 Rules.emplace_back();
515 Rule &R = Rules.back();
518 R.ExactArgs = ArgCount.first;
519 R.PrefixArgs = ArgCount.second;
522 assert(
ID < std::numeric_limits<
decltype(R.Priority)>::max() &&
523 "Rules::Priority overflowed by options table");
528 for (
const auto &R : Rules)
529 Result->find(R.Text)->second.append(Rules.begin(), Rules.end());
533 unsigned RuleCount = 0;
534 dlog(
"ArgStripper Option spelling table");
535 for (
const auto &
Entry : *Result) {
537 RuleCount +=
Entry.second.size();
538 for (
const auto &R :
Entry.second)
539 dlog(
" {0} #={1} *={2} Mode={3}", R.Text, R.ExactArgs, R.PrefixArgs,
542 dlog(
"Table spellings={0} rules={1} string-bytes={2}", Result->size(),
543 RuleCount, Result->getAllocator().getBytesAllocated());
546 return Result.release();
549 auto It = Table->find(Arg);
550 return (It == Table->end()) ? llvm::ArrayRef<Rule>() : It->second;
554 auto OptionRules = rulesFor(Arg);
555 if (OptionRules.empty()) {
557 Storage.emplace_back(Arg);
558 Rules.emplace_back();
559 Rules.back().Text = Storage.back();
560 Rules.back().ExactArgs = 1;
561 if (Rules.back().Text.consume_back(
"*"))
562 Rules.back().PrefixArgs = 1;
563 Rules.back().Modes = DM_All;
564 Rules.back().Priority = -1;
566 Rules.append(OptionRules.begin(), OptionRules.end());
570const ArgStripper::Rule *ArgStripper::matchingRule(llvm::StringRef Arg,
572 unsigned &ArgCount)
const {
573 const ArgStripper::Rule *BestRule =
nullptr;
574 for (
const Rule &R : Rules) {
576 if (!(R.Modes & Mode))
578 if (BestRule && BestRule->Priority < R.Priority)
580 if (!Arg.starts_with(R.Text))
582 bool PrefixMatch = Arg.size() > R.Text.size();
584 if (
unsigned Count = PrefixMatch ? R.PrefixArgs : R.ExactArgs) {
599 DriverMode MainMode = getDriverMode(
Args);
600 DriverMode CurrentMode = MainMode;
604 bool WasXclang =
false;
606 unsigned ArgCount = 0;
607 if (matchingRule(
Args[
Read], CurrentMode, ArgCount)) {
612 CurrentMode = MainMode;
616 for (
unsigned I = 1;
Read <
Args.size() && I < ArgCount; ++I) {
623 WasXclang =
Args[
Read] ==
"-Xclang";
624 CurrentMode = WasXclang ? DM_CC1 : MainMode;
636 llvm::raw_string_ostream
OS(Buf);
638 for (llvm::StringRef Arg :
Args) {
642 if (llvm::all_of(Arg, llvm::isPrint) &&
643 Arg.find_first_of(
" \t\n\"\\") == llvm::StringRef::npos) {
648 OS.write_escaped(Arg,
true);
651 return std::move(
OS.str());
655 std::vector<llvm::StringRef> Refs(
Args.size());
656 llvm::copy(
Args, Refs.begin());
llvm::SmallString< 256U > Name
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.