13#include "clang/Driver/Driver.h"
14#include "clang/Frontend/CompilerInvocation.h"
15#include "clang/Options/Options.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 GetResourcesPath(
"clangd", (
void *)&StaticForMainAddr);
143static std::string resolveDriver(llvm::StringRef Driver,
bool FollowSymlink,
144 std::optional<std::string> ClangPath) {
145 auto SiblingOf = [&](llvm::StringRef AbsPath) {
146 llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath);
147 llvm::sys::path::append(Result, llvm::sys::path::filename(Driver));
148 return Result.str().str();
153 if (!llvm::sys::path::is_absolute(Driver)) {
157 if (llvm::any_of(Driver,
158 [](
char C) {
return llvm::sys::path::is_separator(C); }))
162 (Driver ==
"clang" || Driver ==
"clang++" || Driver ==
"gcc" ||
163 Driver ==
"g++" || Driver ==
"cc" || Driver ==
"c++")) {
164 return SiblingOf(*ClangPath);
167 auto Absolute = llvm::sys::findProgramByName(Driver);
168 if (Absolute && llvm::sys::path::is_absolute(*Absolute))
169 Driver = Storage = std::move(*Absolute);
171 return SiblingOf(*ClangPath);
177 assert(llvm::sys::path::is_absolute(Driver));
179 llvm::SmallString<256> Resolved;
180 if (!llvm::sys::fs::real_path(Driver, Resolved))
181 return SiblingOf(Resolved);
192 Result.
Sysroot = detectSysroot();
199 llvm::StringRef
File)
const {
200 std::vector<std::string> &Cmd = Command.CommandLine;
208 auto &OptTable = getDriverOptTable();
210 llvm::SmallVector<const char *, 16> OriginalArgs;
211 OriginalArgs.reserve(Cmd.size());
212 for (
const auto &S : Cmd)
213 OriginalArgs.push_back(S.c_str());
214 bool IsCLMode = driver::IsClangCL(driver::getDriverMode(
215 OriginalArgs[0], llvm::ArrayRef(OriginalArgs).slice(1)));
218 unsigned IgnoredCount;
221 llvm::opt::InputArgList ArgList;
222 ArgList = OptTable.ParseArgs(
223 llvm::ArrayRef(OriginalArgs).drop_front(), IgnoredCount, IgnoredCount,
224 llvm::opt::Visibility(IsCLMode ? options::CLOption
225 : options::ClangOption));
227 llvm::SmallVector<unsigned, 1> IndicesToDrop;
233 unsigned ArchOptCount = 0;
234 for (
auto *Input : ArgList.filtered(options::OPT_arch)) {
236 for (
auto I = 0U; I <= Input->getNumValues(); ++I)
237 IndicesToDrop.push_back(Input->getIndex() + I);
240 if (ArchOptCount < 2)
241 IndicesToDrop.clear();
253 llvm::StringRef FileExtension = llvm::sys::path::extension(
File);
254 std::optional<std::string> TransferFrom;
255 auto SawInput = [&](llvm::StringRef Input) {
256 if (llvm::sys::path::extension(Input) != FileExtension)
257 TransferFrom.emplace(Input);
264 for (
auto *Input : ArgList.filtered(options::OPT_INPUT)) {
265 SawInput(Input->getValue(0));
266 IndicesToDrop.push_back(Input->getIndex());
269 if (
auto *DashDash = ArgList.getLastArgNoClaim(options::OPT__DASH_DASH)) {
270 auto DashDashIndex = DashDash->getIndex() + 1;
272 for (
unsigned I = DashDashIndex + 1; I < Cmd.size(); ++I)
274 Cmd.resize(DashDashIndex);
276 llvm::sort(IndicesToDrop);
277 for (
unsigned Idx : llvm::reverse(IndicesToDrop))
280 Cmd.erase(Cmd.begin() + Idx + 1);
284 Cmd.push_back(
File.str());
287 tooling::CompileCommand TransferCmd;
288 TransferCmd.Filename = std::move(*TransferFrom);
289 TransferCmd.CommandLine = std::move(Cmd);
290 TransferCmd = transferCompileCommand(std::move(TransferCmd),
File);
291 Cmd = std::move(TransferCmd.CommandLine);
292 assert(Cmd.size() >= 2 && Cmd.back() ==
File &&
293 Cmd[Cmd.size() - 2] ==
"--" &&
294 "TransferCommand should produce a command ending in -- filename");
313 tooling::addTargetAndModeForProgramName(Cmd, Cmd.front());
316 auto HasExact = [&](llvm::StringRef Flag) {
317 return llvm::is_contained(Cmd, Flag);
321 auto HasPrefix = [&](llvm::StringRef Flag) {
323 Cmd, [&](llvm::StringRef Arg) {
return Arg.starts_with(Flag); });
326 llvm::erase_if(Cmd, [](llvm::StringRef Elem) {
327 return Elem.starts_with(
"--save-temps") || Elem.starts_with(
"-save-temps");
330 std::vector<std::string> ToAppend;
331 if (
ResourceDir && !HasExact(
"-resource-dir") && !HasPrefix(
"-resource-dir="))
332 ToAppend.push_back((
"-resource-dir=" + *
ResourceDir));
336 if (
Sysroot && !HasPrefix(
"-isysroot") && !HasExact(
"--sysroot") &&
337 !HasPrefix(
"--sysroot=")) {
338 ToAppend.push_back(
"-isysroot");
342 if (!ToAppend.empty()) {
343 Cmd.insert(llvm::find(Cmd,
"--"), std::make_move_iterator(ToAppend.begin()),
344 std::make_move_iterator(ToAppend.end()));
348 bool FollowSymlink = !HasExact(
"-no-canonical-prefixes");
350 (FollowSymlink ? ResolvedDrivers : ResolvedDriversNoFollow)
351 .get(Cmd.front(), [&,
this] {
352 return resolveDriver(Cmd.front(), FollowSymlink, ClangPath);
362std::pair<unsigned, unsigned> getArgCount(
const llvm::opt::Option &Opt) {
363 constexpr static unsigned Rest = 10000;
365 using llvm::opt::Option;
366 switch (Opt.getKind()) {
367 case Option::FlagClass:
369 case Option::JoinedClass:
370 case Option::CommaJoinedClass:
372 case Option::GroupClass:
373 case Option::InputClass:
374 case Option::UnknownClass:
375 case Option::ValuesClass:
377 case Option::JoinedAndSeparateClass:
379 case Option::SeparateClass:
381 case Option::MultiArgClass:
382 return {1 + Opt.getNumArgs(), 0};
383 case Option::JoinedOrSeparateClass:
385 case Option::RemainingArgsClass:
387 case Option::RemainingArgsJoinedClass:
390 llvm_unreachable(
"Unhandled option kind");
394enum DriverMode :
unsigned char {
403DriverMode getDriverMode(
const std::vector<std::string> &Args) {
404 DriverMode Mode = DM_GCC;
405 llvm::StringRef
Argv0 = Args.front();
406 Argv0.consume_back_insensitive(
".exe");
407 if (
Argv0.ends_with_insensitive(
"cl"))
409 for (
const llvm::StringRef Arg : Args) {
410 if (Arg ==
"--driver-mode=cl") {
423unsigned char getModes(
const llvm::opt::Option &Opt) {
424 unsigned char Result = DM_None;
425 if (Opt.hasVisibilityFlag(options::ClangOption))
427 if (Opt.hasVisibilityFlag(options::CC1Option))
429 if (Opt.hasVisibilityFlag(options::CLOption))
436llvm::ArrayRef<ArgStripper::Rule> ArgStripper::rulesFor(llvm::StringRef Arg) {
441 llvm::StringMap<llvm::SmallVector<Rule, 4>, llvm::BumpPtrAllocator>;
442 static TableTy *Table = [] {
443 auto &DriverTable = getDriverOptTable();
444 using DriverID = clang::options::ID;
449 DriverID PrevAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
450 DriverID NextAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
451 auto AddAlias = [&](DriverID Self, DriverID
T) {
453 PrevAlias[NextAlias[
T]] = Self;
454 NextAlias[Self] = NextAlias[
T];
463 const void *AliasArgs;
465#define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, \
466 FLAGS, VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, \
467 METAVAR, VALUES, SUBCOMMANDIDS_OFFSET) \
468 {DriverID::OPT_##ID, DriverID::OPT_##ALIAS, ALIASARGS},
469#include "clang/Options/Options.inc"
472 for (
auto &E : AliasTable)
473 if (E.AliasID != DriverID::OPT_INVALID && E.AliasArgs ==
nullptr)
474 AddAlias(E.ID, E.AliasID);
476 auto Result = std::make_unique<TableTy>();
479 for (
unsigned ID = 1 ; ID < DriverID::LastOption; ++ID) {
480 if (PrevAlias[ID] || ID == DriverID::OPT_Xclang)
482 llvm::SmallVector<Rule> Rules;
484 for (
unsigned A = ID;
A != DriverID::OPT_INVALID;
A = NextAlias[
A]) {
485 llvm::SmallVector<llvm::StringRef, 4> Prefixes;
486 DriverTable.appendOptionPrefixes(A, Prefixes);
487 if (Prefixes.empty())
489 auto Opt = DriverTable.getOption(A);
491 if (Opt.getName().empty())
493 auto Modes = getModes(Opt);
494 std::pair<unsigned, unsigned> ArgCount = getArgCount(Opt);
496 for (StringRef Prefix : Prefixes) {
497 llvm::SmallString<64> Buf(Prefix);
498 Buf.append(Opt.getName());
499 llvm::StringRef Spelling = Result->try_emplace(Buf).first->getKey();
500 Rules.emplace_back();
501 Rule &R = Rules.back();
504 R.ExactArgs = ArgCount.first;
505 R.PrefixArgs = ArgCount.second;
508 assert(ID < std::numeric_limits<
decltype(R.Priority)>::max() &&
509 "Rules::Priority overflowed by options table");
514 for (
const auto &R : Rules)
515 Result->find(R.Text)->second.append(Rules.begin(), Rules.end());
519 unsigned RuleCount = 0;
520 dlog(
"ArgStripper Option spelling table");
521 for (
const auto &Entry : *Result) {
522 dlog(
"{0}", Entry.first());
523 RuleCount += Entry.second.size();
524 for (
const auto &R : Entry.second)
525 dlog(
" {0} #={1} *={2} Mode={3}", R.Text, R.ExactArgs, R.PrefixArgs,
528 dlog(
"Table spellings={0} rules={1} string-bytes={2}", Result->size(),
529 RuleCount, Result->getAllocator().getBytesAllocated());
532 return Result.release();
535 auto It = Table->find(Arg);
536 return (It == Table->end()) ? llvm::ArrayRef<Rule>() : It->second;
540 auto OptionRules = rulesFor(Arg);
541 if (OptionRules.empty()) {
543 Storage.emplace_back(Arg);
544 Rules.emplace_back();
545 Rules.back().Text = Storage.back();
546 Rules.back().ExactArgs = 1;
547 if (Rules.back().Text.consume_back(
"*"))
548 Rules.back().PrefixArgs = 1;
549 Rules.back().Modes = DM_All;
550 Rules.back().Priority = -1;
552 Rules.append(OptionRules.begin(), OptionRules.end());
556const ArgStripper::Rule *ArgStripper::matchingRule(llvm::StringRef Arg,
558 unsigned &ArgCount)
const {
559 const ArgStripper::Rule *BestRule =
nullptr;
560 for (
const Rule &R : Rules) {
562 if (!(R.Modes & Mode))
564 if (BestRule && BestRule->Priority < R.Priority)
566 if (!Arg.starts_with(R.Text))
568 bool PrefixMatch = Arg.size() > R.Text.size();
570 if (
unsigned Count = PrefixMatch ? R.PrefixArgs : R.ExactArgs) {
585 DriverMode MainMode = getDriverMode(Args);
586 DriverMode CurrentMode = MainMode;
590 bool WasXclang =
false;
591 while (
Read < Args.size()) {
592 unsigned ArgCount = 0;
593 if (matchingRule(Args[
Read], CurrentMode, ArgCount)) {
598 CurrentMode = MainMode;
602 for (
unsigned I = 1;
Read < Args.size() && I < ArgCount; ++I) {
604 if (
Read < Args.size() && Args[
Read] ==
"-Xclang")
609 WasXclang = Args[
Read] ==
"-Xclang";
610 CurrentMode = WasXclang ? DM_CC1 : MainMode;
620std::string
printArgv(llvm::ArrayRef<llvm::StringRef> Args) {
622 llvm::raw_string_ostream OS(Buf);
624 for (llvm::StringRef Arg : Args) {
628 if (llvm::all_of(Arg, llvm::isPrint) &&
629 Arg.find_first_of(
" \t\n\"\\") == llvm::StringRef::npos) {
634 OS.write_escaped(Arg,
true);
637 return std::move(OS.str());
640std::string
printArgv(llvm::ArrayRef<std::string> Args) {
641 std::vector<llvm::StringRef> Refs(Args.size());
642 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.