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];
465 const void *AliasArgs;
467#define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, \
468 FLAGS, VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, \
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) {
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;
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) {
611 WasXclang =
Args[
Read] ==
"-Xclang";
612 CurrentMode = WasXclang ? DM_CC1 : MainMode;
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());
643 std::vector<llvm::StringRef> Refs(
Args.size());
644 llvm::copy(
Args, Refs.begin());
llvm::SmallString< 256U > Name
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.