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)) {
158 if (llvm::any_of(Driver,
159 [](
char C) {
return llvm::sys::path::is_separator(C); }))
163 (Driver ==
"clang" || Driver ==
"clang++" || Driver ==
"gcc" ||
164 Driver ==
"g++" || Driver ==
"cc" || Driver ==
"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);
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;
274 for (
unsigned I = DashDashIndex + 1; I < Cmd.size(); ++I)
276 Cmd.resize(DashDashIndex);
278 llvm::sort(IndicesToDrop);
279 for (
unsigned Idx : llvm::reverse(IndicesToDrop))
282 Cmd.erase(Cmd.begin() + Idx + 1);
286 Cmd.push_back(
File.str());
289 tooling::CompileCommand TransferCmd;
290 TransferCmd.Filename = std::move(*TransferFrom);
291 TransferCmd.CommandLine = std::move(Cmd);
292 TransferCmd = transferCompileCommand(std::move(TransferCmd),
File);
293 Cmd = std::move(TransferCmd.CommandLine);
294 assert(Cmd.size() >= 2 && Cmd.back() ==
File &&
295 Cmd[Cmd.size() - 2] ==
"--" &&
296 "TransferCommand should produce a command ending in -- filename");
315 tooling::addTargetAndModeForProgramName(Cmd, Cmd.front());
318 auto HasExact = [&](llvm::StringRef Flag) {
319 return llvm::is_contained(Cmd, Flag);
323 auto HasPrefix = [&](llvm::StringRef Flag) {
325 Cmd, [&](llvm::StringRef Arg) {
return Arg.starts_with(Flag); });
328 llvm::erase_if(Cmd, [](llvm::StringRef Elem) {
329 return Elem.starts_with(
"--save-temps") || Elem.starts_with(
"-save-temps");
332 std::vector<std::string> ToAppend;
333 if (
ResourceDir && !HasExact(
"-resource-dir") && !HasPrefix(
"-resource-dir="))
334 ToAppend.push_back((
"-resource-dir=" + *
ResourceDir));
338 if (
Sysroot && !HasPrefix(
"-isysroot") && !HasExact(
"--sysroot") &&
339 !HasPrefix(
"--sysroot=")) {
340 ToAppend.push_back(
"-isysroot");
344 if (!ToAppend.empty()) {
345 Cmd.insert(llvm::find(Cmd,
"--"), std::make_move_iterator(ToAppend.begin()),
346 std::make_move_iterator(ToAppend.end()));
350 bool FollowSymlink = !HasExact(
"-no-canonical-prefixes");
352 (FollowSymlink ? ResolvedDrivers : ResolvedDriversNoFollow)
353 .get(Cmd.front(), [&,
this] {
354 return resolveDriver(Cmd.front(), FollowSymlink, ClangPath);
364std::pair<unsigned, unsigned> getArgCount(
const llvm::opt::Option &Opt) {
365 constexpr static unsigned Rest = 10000;
367 using llvm::opt::Option;
368 switch (Opt.getKind()) {
369 case Option::FlagClass:
371 case Option::JoinedClass:
372 case Option::CommaJoinedClass:
374 case Option::GroupClass:
375 case Option::InputClass:
376 case Option::UnknownClass:
377 case Option::ValuesClass:
379 case Option::JoinedAndSeparateClass:
381 case Option::SeparateClass:
383 case Option::MultiArgClass:
384 return {1 + Opt.getNumArgs(), 0};
385 case Option::JoinedOrSeparateClass:
387 case Option::RemainingArgsClass:
389 case Option::RemainingArgsJoinedClass:
392 llvm_unreachable(
"Unhandled option kind");
396enum DriverMode :
unsigned char {
405DriverMode getDriverMode(
const std::vector<std::string> &Args) {
406 DriverMode Mode = DM_GCC;
407 llvm::StringRef
Argv0 = Args.front();
408 Argv0.consume_back_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];
465 const void *AliasArgs;
467#define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, \
468 FLAGS, VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, \
469 METAVAR, VALUES, SUBCOMMANDIDS_OFFSET) \
470 {DriverID::OPT_##ID, DriverID::OPT_##ALIAS, ALIASARGS},
471#include "clang/Driver/Options.inc"
474 for (
auto &E : AliasTable)
475 if (E.AliasID != DriverID::OPT_INVALID && E.AliasArgs ==
nullptr)
476 AddAlias(E.ID, E.AliasID);
478 auto Result = std::make_unique<TableTy>();
481 for (
unsigned ID = 1 ; ID < DriverID::LastOption; ++ID) {
482 if (PrevAlias[ID] || ID == DriverID::OPT_Xclang)
484 llvm::SmallVector<Rule> Rules;
486 for (
unsigned A = ID;
A != DriverID::OPT_INVALID;
A = NextAlias[
A]) {
487 llvm::SmallVector<llvm::StringRef, 4> Prefixes;
488 DriverTable.appendOptionPrefixes(A, Prefixes);
489 if (Prefixes.empty())
491 auto Opt = DriverTable.getOption(A);
493 if (Opt.getName().empty())
495 auto Modes = getModes(Opt);
496 std::pair<unsigned, unsigned> ArgCount = getArgCount(Opt);
498 for (StringRef Prefix : Prefixes) {
499 llvm::SmallString<64> Buf(Prefix);
500 Buf.append(Opt.getName());
501 llvm::StringRef Spelling = Result->try_emplace(Buf).first->getKey();
502 Rules.emplace_back();
503 Rule &R = Rules.back();
506 R.ExactArgs = ArgCount.first;
507 R.PrefixArgs = ArgCount.second;
510 assert(ID < std::numeric_limits<
decltype(R.Priority)>::max() &&
511 "Rules::Priority overflowed by options table");
516 for (
const auto &R : Rules)
517 Result->find(R.Text)->second.append(Rules.begin(), Rules.end());
521 unsigned RuleCount = 0;
522 dlog(
"ArgStripper Option spelling table");
523 for (
const auto &Entry : *Result) {
524 dlog(
"{0}", Entry.first());
525 RuleCount += Entry.second.size();
526 for (
const auto &R : Entry.second)
527 dlog(
" {0} #={1} *={2} Mode={3}", R.Text, R.ExactArgs, R.PrefixArgs,
530 dlog(
"Table spellings={0} rules={1} string-bytes={2}", Result->size(),
531 RuleCount, Result->getAllocator().getBytesAllocated());
534 return Result.release();
537 auto It = Table->find(Arg);
538 return (It == Table->end()) ? llvm::ArrayRef<Rule>() : It->second;
542 auto OptionRules = rulesFor(Arg);
543 if (OptionRules.empty()) {
545 Storage.emplace_back(Arg);
546 Rules.emplace_back();
547 Rules.back().Text = Storage.back();
548 Rules.back().ExactArgs = 1;
549 if (Rules.back().Text.consume_back(
"*"))
550 Rules.back().PrefixArgs = 1;
551 Rules.back().Modes = DM_All;
552 Rules.back().Priority = -1;
554 Rules.append(OptionRules.begin(), OptionRules.end());
558const ArgStripper::Rule *ArgStripper::matchingRule(llvm::StringRef Arg,
560 unsigned &ArgCount)
const {
561 const ArgStripper::Rule *BestRule =
nullptr;
562 for (
const Rule &R : Rules) {
564 if (!(R.Modes & Mode))
566 if (BestRule && BestRule->Priority < R.Priority)
568 if (!Arg.starts_with(R.Text))
570 bool PrefixMatch = Arg.size() > R.Text.size();
572 if (
unsigned Count = PrefixMatch ? R.PrefixArgs : R.ExactArgs) {
587 DriverMode MainMode = getDriverMode(Args);
588 DriverMode CurrentMode = MainMode;
592 bool WasXclang =
false;
593 while (
Read < Args.size()) {
594 unsigned ArgCount = 0;
595 if (matchingRule(Args[
Read], CurrentMode, ArgCount)) {
600 CurrentMode = MainMode;
604 for (
unsigned I = 1;
Read < Args.size() && I < ArgCount; ++I) {
606 if (
Read < Args.size() && Args[
Read] ==
"-Xclang")
611 WasXclang = Args[
Read] ==
"-Xclang";
612 CurrentMode = WasXclang ? DM_CC1 : MainMode;
622std::string
printArgv(llvm::ArrayRef<llvm::StringRef> Args) {
624 llvm::raw_string_ostream OS(Buf);
626 for (llvm::StringRef Arg : Args) {
630 if (llvm::all_of(Arg, llvm::isPrint) &&
631 Arg.find_first_of(
" \t\n\"\\") == llvm::StringRef::npos) {
636 OS.write_escaped(Arg,
true);
639 return std::move(OS.str());
642std::string
printArgv(llvm::ArrayRef<std::string> Args) {
643 std::vector<llvm::StringRef> Refs(Args.size());
644 llvm::copy(Args, Refs.begin());
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.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
void vlog(const char *Fmt, Ts &&... Vals)
void log(const char *Fmt, Ts &&... Vals)
std::string printArgv(llvm::ArrayRef< llvm::StringRef > Args)
std::string Path
A typedef to represent a file path.
===– 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.
A set of edits generated for a single file.