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);
277 llvm::SmallVector<const char *, 16> UnknownArgs;
279 for (
auto *UnknownArg : ArgList.filtered(options::OPT_UNKNOWN)) {
280 UnknownArgs.push_back(UnknownArg->getValue());
281 IndicesToDrop.push_back(UnknownArg->getIndex());
284 if (!UnknownArgs.empty()) {
285 log(
"Warning: detected unsupported options '{0}'",
286 llvm::join(UnknownArgs,
", "));
289 llvm::sort(IndicesToDrop);
290 for (
unsigned Idx : llvm::reverse(IndicesToDrop))
293 Cmd.erase(Cmd.begin() + Idx + 1);
297 Cmd.push_back(
File.str());
300 tooling::CompileCommand TransferCmd;
301 TransferCmd.Filename = std::move(*TransferFrom);
302 TransferCmd.CommandLine = std::move(Cmd);
303 TransferCmd = transferCompileCommand(std::move(TransferCmd),
File);
304 Cmd = std::move(TransferCmd.CommandLine);
305 assert(Cmd.size() >= 2 && Cmd.back() ==
File &&
306 Cmd[Cmd.size() - 2] ==
"--" &&
307 "TransferCommand should produce a command ending in -- filename");
326 tooling::addTargetAndModeForProgramName(Cmd, Cmd.front());
329 auto HasExact = [&](llvm::StringRef Flag) {
330 return llvm::is_contained(Cmd, Flag);
334 auto HasPrefix = [&](llvm::StringRef Flag) {
336 Cmd, [&](llvm::StringRef Arg) {
return Arg.starts_with(Flag); });
339 llvm::erase_if(Cmd, [](llvm::StringRef Elem) {
340 return Elem.starts_with(
"--save-temps") || Elem.starts_with(
"-save-temps");
343 std::vector<std::string> ToAppend;
344 if (
ResourceDir && !HasExact(
"-resource-dir") && !HasPrefix(
"-resource-dir="))
345 ToAppend.push_back((
"-resource-dir=" + *
ResourceDir));
349 if (
Sysroot && !HasPrefix(
"-isysroot") && !HasExact(
"--sysroot") &&
350 !HasPrefix(
"--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 = !HasExact(
"-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;
418 llvm::StringRef
Argv0 = Args.front();
419 Argv0.consume_back_insensitive(
".exe");
420 if (
Argv0.ends_with_insensitive(
"cl"))
422 for (
const llvm::StringRef Arg : Args) {
423 if (Arg ==
"--driver-mode=cl") {
436unsigned char getModes(
const llvm::opt::Option &Opt) {
437 unsigned char Result = DM_None;
438 if (Opt.hasVisibilityFlag(options::ClangOption))
440 if (Opt.hasVisibilityFlag(options::CC1Option))
442 if (Opt.hasVisibilityFlag(options::CLOption))
449llvm::ArrayRef<ArgStripper::Rule> ArgStripper::rulesFor(llvm::StringRef Arg) {
454 llvm::StringMap<llvm::SmallVector<Rule, 4>, llvm::BumpPtrAllocator>;
455 static TableTy *Table = [] {
456 auto &DriverTable = getDriverOptTable();
457 using DriverID = clang::options::ID;
462 DriverID PrevAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
463 DriverID NextAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
464 auto AddAlias = [&](DriverID Self, DriverID
T) {
466 PrevAlias[NextAlias[
T]] = Self;
467 NextAlias[Self] = NextAlias[
T];
476 const void *AliasArgs;
478#define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, \
479 FLAGS, VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, \
480 METAVAR, VALUES, SUBCOMMANDIDS_OFFSET) \
481 {DriverID::OPT_##ID, DriverID::OPT_##ALIAS, ALIASARGS},
482#include "clang/Options/Options.inc"
485 for (
auto &E : AliasTable)
486 if (E.AliasID != DriverID::OPT_INVALID && E.AliasArgs ==
nullptr)
487 AddAlias(E.ID, E.AliasID);
489 auto Result = std::make_unique<TableTy>();
492 for (
unsigned ID = 1 ; ID < DriverID::LastOption; ++ID) {
493 if (PrevAlias[ID] || ID == DriverID::OPT_Xclang)
495 llvm::SmallVector<Rule> Rules;
497 for (
unsigned A = ID;
A != DriverID::OPT_INVALID;
A = NextAlias[
A]) {
498 llvm::SmallVector<llvm::StringRef, 4> Prefixes;
499 DriverTable.appendOptionPrefixes(A, Prefixes);
500 if (Prefixes.empty())
502 auto Opt = DriverTable.getOption(A);
504 if (Opt.getName().empty())
506 auto Modes = getModes(Opt);
507 std::pair<unsigned, unsigned> ArgCount = getArgCount(Opt);
509 for (StringRef Prefix : Prefixes) {
510 llvm::SmallString<64> Buf(Prefix);
511 Buf.append(Opt.getName());
512 llvm::StringRef Spelling = Result->try_emplace(Buf).first->getKey();
513 Rules.emplace_back();
514 Rule &R = Rules.back();
517 R.ExactArgs = ArgCount.first;
518 R.PrefixArgs = ArgCount.second;
521 assert(ID < std::numeric_limits<
decltype(R.Priority)>::max() &&
522 "Rules::Priority overflowed by options table");
527 for (
const auto &R : Rules)
528 Result->find(R.Text)->second.append(Rules.begin(), Rules.end());
532 unsigned RuleCount = 0;
533 dlog(
"ArgStripper Option spelling table");
534 for (
const auto &Entry : *Result) {
535 dlog(
"{0}", Entry.first());
536 RuleCount += Entry.second.size();
537 for (
const auto &R : Entry.second)
538 dlog(
" {0} #={1} *={2} Mode={3}", R.Text, R.ExactArgs, R.PrefixArgs,
541 dlog(
"Table spellings={0} rules={1} string-bytes={2}", Result->size(),
542 RuleCount, Result->getAllocator().getBytesAllocated());
545 return Result.release();
548 auto It = Table->find(Arg);
549 return (It == Table->end()) ? llvm::ArrayRef<Rule>() : It->second;
553 auto OptionRules = rulesFor(Arg);
554 if (OptionRules.empty()) {
556 Storage.emplace_back(Arg);
557 Rules.emplace_back();
558 Rules.back().Text = Storage.back();
559 Rules.back().ExactArgs = 1;
560 if (Rules.back().Text.consume_back(
"*"))
561 Rules.back().PrefixArgs = 1;
562 Rules.back().Modes = DM_All;
563 Rules.back().Priority = -1;
565 Rules.append(OptionRules.begin(), OptionRules.end());
569const ArgStripper::Rule *ArgStripper::matchingRule(llvm::StringRef Arg,
571 unsigned &ArgCount)
const {
572 const ArgStripper::Rule *BestRule =
nullptr;
573 for (
const Rule &R : Rules) {
575 if (!(R.Modes & Mode))
577 if (BestRule && BestRule->Priority < R.Priority)
579 if (!Arg.starts_with(R.Text))
581 bool PrefixMatch = Arg.size() > R.Text.size();
583 if (
unsigned Count = PrefixMatch ? R.PrefixArgs : R.ExactArgs) {
598 DriverMode MainMode = getDriverMode(Args);
599 DriverMode CurrentMode = MainMode;
603 bool WasXclang =
false;
604 while (
Read < Args.size()) {
605 unsigned ArgCount = 0;
606 if (matchingRule(Args[
Read], CurrentMode, ArgCount)) {
611 CurrentMode = MainMode;
615 for (
unsigned I = 1;
Read < Args.size() && I < ArgCount; ++I) {
617 if (
Read < Args.size() && Args[
Read] ==
"-Xclang")
622 WasXclang = Args[
Read] ==
"-Xclang";
623 CurrentMode = WasXclang ? DM_CC1 : MainMode;
633std::string
printArgv(llvm::ArrayRef<llvm::StringRef> Args) {
635 llvm::raw_string_ostream OS(Buf);
637 for (llvm::StringRef Arg : Args) {
641 if (llvm::all_of(Arg, llvm::isPrint) &&
642 Arg.find_first_of(
" \t\n\"\\") == llvm::StringRef::npos) {
647 OS.write_escaped(Arg,
true);
650 return std::move(OS.str());
653std::string
printArgv(llvm::ArrayRef<std::string> Args) {
654 std::vector<llvm::StringRef> Refs(Args.size());
655 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.