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);
138std::optional<std::string>
139detectResourceDirWithClangPath(std::optional<std::string> ClangPath) {
140 std::string ResourceDir = detectStandardResourceDir();
141 if (llvm::sys::fs::exists(ResourceDir))
143 vlog(
"Auto-detected standard resource directory '{0}' doesn't exist",
147 ResourceDir = GetResourcesPath(*ClangPath);
148 if (llvm::sys::fs::exists(ResourceDir))
150 vlog(
"Auto-detected using clang path '{0}' "
151 "resource directory '{1}' doesn't exist",
152 *ClangPath, ResourceDir);
155 elog(
"Failed to auto-detect resource directory, "
156 "specify it manually via --resource-dir command line argument");
165static std::string resolveDriver(llvm::StringRef Driver,
bool FollowSymlink,
166 std::optional<std::string> ClangPath) {
167 auto SiblingOf = [&](llvm::StringRef AbsPath) {
168 llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath);
169 llvm::sys::path::append(Result, llvm::sys::path::filename(Driver));
170 return Result.str().str();
175 if (!llvm::sys::path::is_absolute(Driver)) {
179 if (llvm::any_of(Driver,
180 [](
char C) {
return llvm::sys::path::is_separator(C); }))
184 (Driver ==
"clang" || Driver ==
"clang++" || Driver ==
"gcc" ||
185 Driver ==
"g++" || Driver ==
"cc" || Driver ==
"c++")) {
186 return SiblingOf(*ClangPath);
189 auto Absolute = llvm::sys::findProgramByName(Driver);
190 if (Absolute && llvm::sys::path::is_absolute(*Absolute))
191 Driver = Storage = std::move(*Absolute);
193 return SiblingOf(*ClangPath);
199 assert(llvm::sys::path::is_absolute(Driver));
201 llvm::SmallString<256> Resolved;
202 if (!llvm::sys::fs::real_path(Driver, Resolved))
203 return SiblingOf(Resolved);
214 Result.
Sysroot = detectSysroot();
221 llvm::StringRef
File)
const {
222 std::vector<std::string> &Cmd = Command.CommandLine;
230 auto &OptTable = getDriverOptTable();
232 llvm::SmallVector<const char *, 16> OriginalArgs;
233 OriginalArgs.reserve(Cmd.size());
234 for (
const auto &S : Cmd)
235 OriginalArgs.push_back(S.c_str());
236 bool IsCLMode = driver::IsClangCL(driver::getDriverMode(
237 OriginalArgs[0], llvm::ArrayRef(OriginalArgs).slice(1)));
240 unsigned IgnoredCount;
243 llvm::opt::InputArgList ArgList;
244 ArgList = OptTable.ParseArgs(
245 llvm::ArrayRef(OriginalArgs).drop_front(), IgnoredCount, IgnoredCount,
246 llvm::opt::Visibility(IsCLMode ? options::CLOption
247 : options::ClangOption));
249 llvm::SmallVector<unsigned, 1> IndicesToDrop;
255 unsigned ArchOptCount = 0;
256 for (
auto *Input : ArgList.filtered(options::OPT_arch)) {
258 for (
auto I = 0U; I <= Input->getNumValues(); ++I)
259 IndicesToDrop.push_back(Input->getIndex() + I);
262 if (ArchOptCount < 2)
263 IndicesToDrop.clear();
275 llvm::StringRef FileExtension = llvm::sys::path::extension(
File);
276 std::optional<std::string> TransferFrom;
277 auto SawInput = [&](llvm::StringRef Input) {
278 if (llvm::sys::path::extension(Input) != FileExtension)
279 TransferFrom.emplace(Input);
286 for (
auto *Input : ArgList.filtered(options::OPT_INPUT)) {
287 SawInput(Input->getValue(0));
288 IndicesToDrop.push_back(Input->getIndex());
291 if (
auto *DashDash = ArgList.getLastArgNoClaim(options::OPT__DASH_DASH)) {
292 auto DashDashIndex = DashDash->getIndex() + 1;
294 for (
unsigned I = DashDashIndex + 1; I < Cmd.size(); ++I)
296 Cmd.resize(DashDashIndex);
299 llvm::SmallVector<const char *, 16> UnknownArgs;
301 for (
auto *UnknownArg : ArgList.filtered(options::OPT_UNKNOWN)) {
302 UnknownArgs.push_back(UnknownArg->getValue());
303 IndicesToDrop.push_back(UnknownArg->getIndex());
306 if (!UnknownArgs.empty()) {
307 log(
"Warning: detected unsupported options '{0}'",
308 llvm::join(UnknownArgs,
", "));
311 llvm::sort(IndicesToDrop);
312 for (
unsigned Idx : llvm::reverse(IndicesToDrop))
315 Cmd.erase(Cmd.begin() + Idx + 1);
319 Cmd.push_back(
File.str());
322 tooling::CompileCommand TransferCmd;
323 TransferCmd.Filename = std::move(*TransferFrom);
324 TransferCmd.CommandLine = std::move(Cmd);
325 TransferCmd = transferCompileCommand(std::move(TransferCmd),
File);
326 Cmd = std::move(TransferCmd.CommandLine);
327 assert(Cmd.size() >= 2 && Cmd.back() ==
File &&
328 Cmd[Cmd.size() - 2] ==
"--" &&
329 "TransferCommand should produce a command ending in -- filename");
348 tooling::addTargetAndModeForProgramName(Cmd, Cmd.front());
351 auto HasExact = [&](llvm::StringRef Flag) {
352 return llvm::is_contained(Cmd, Flag);
356 auto HasPrefix = [&](llvm::StringRef Flag) {
358 Cmd, [&](llvm::StringRef Arg) {
return Arg.starts_with(Flag); });
361 llvm::erase_if(Cmd, [](llvm::StringRef Elem) {
362 return Elem.starts_with(
"--save-temps") || Elem.starts_with(
"-save-temps");
365 std::vector<std::string> ToAppend;
366 if (
ResourceDir && !HasExact(
"-resource-dir") && !HasPrefix(
"-resource-dir="))
367 ToAppend.push_back((
"-resource-dir=" + *
ResourceDir));
371 if (
Sysroot && !HasPrefix(
"-isysroot") && !HasExact(
"--sysroot") &&
372 !HasPrefix(
"--sysroot=")) {
373 ToAppend.push_back(
"-isysroot");
377 if (!ToAppend.empty()) {
378 Cmd.insert(llvm::find(Cmd,
"--"), std::make_move_iterator(ToAppend.begin()),
379 std::make_move_iterator(ToAppend.end()));
383 bool FollowSymlink = !HasExact(
"-no-canonical-prefixes");
385 (FollowSymlink ? ResolvedDrivers : ResolvedDriversNoFollow)
386 .get(Cmd.front(), [&,
this] {
387 return resolveDriver(Cmd.front(), FollowSymlink, ClangPath);
397std::pair<unsigned, unsigned> getArgCount(
const llvm::opt::Option &Opt) {
398 constexpr static unsigned Rest = 10000;
400 using llvm::opt::Option;
401 switch (Opt.getKind()) {
402 case Option::FlagClass:
404 case Option::JoinedClass:
405 case Option::CommaJoinedClass:
407 case Option::GroupClass:
408 case Option::InputClass:
409 case Option::UnknownClass:
410 case Option::ValuesClass:
412 case Option::JoinedAndSeparateClass:
414 case Option::SeparateClass:
416 case Option::MultiArgClass:
417 return {1 + Opt.getNumArgs(), 0};
418 case Option::JoinedOrSeparateClass:
420 case Option::RemainingArgsClass:
422 case Option::RemainingArgsJoinedClass:
425 llvm_unreachable(
"Unhandled option kind");
429enum DriverMode :
unsigned char {
438DriverMode getDriverMode(
const std::vector<std::string> &Args) {
439 DriverMode Mode = DM_GCC;
440 llvm::StringRef
Argv0 = Args.front();
441 Argv0.consume_back_insensitive(
".exe");
442 if (
Argv0.ends_with_insensitive(
"cl"))
444 for (
const llvm::StringRef Arg : Args) {
445 if (Arg ==
"--driver-mode=cl") {
458unsigned char getModes(
const llvm::opt::Option &Opt) {
459 unsigned char Result = DM_None;
460 if (Opt.hasVisibilityFlag(options::ClangOption))
462 if (Opt.hasVisibilityFlag(options::CC1Option))
464 if (Opt.hasVisibilityFlag(options::CLOption))
471llvm::ArrayRef<ArgStripper::Rule> ArgStripper::rulesFor(llvm::StringRef Arg) {
476 llvm::StringMap<llvm::SmallVector<Rule, 4>, llvm::BumpPtrAllocator>;
477 static TableTy *Table = [] {
478 auto &DriverTable = getDriverOptTable();
479 using DriverID = clang::options::ID;
484 DriverID PrevAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
485 DriverID NextAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
486 auto AddAlias = [&](DriverID Self, DriverID
T) {
488 PrevAlias[NextAlias[
T]] = Self;
489 NextAlias[Self] = NextAlias[
T];
498 const void *AliasArgs;
500#define OPTION(PREFIX, PREFIXED_NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, \
501 FLAGS, VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, \
502 METAVAR, VALUES, SUBCOMMANDIDS_OFFSET) \
503 {DriverID::OPT_##ID, DriverID::OPT_##ALIAS, ALIASARGS},
504#include "clang/Options/Options.inc"
507 for (
auto &E : AliasTable)
508 if (E.AliasID != DriverID::OPT_INVALID && E.AliasArgs ==
nullptr)
509 AddAlias(E.ID, E.AliasID);
511 auto Result = std::make_unique<TableTy>();
514 for (
unsigned ID = 1 ; ID < DriverID::LastOption; ++ID) {
515 if (PrevAlias[ID] || ID == DriverID::OPT_Xclang)
517 llvm::SmallVector<Rule> Rules;
519 for (
unsigned A = ID;
A != DriverID::OPT_INVALID;
A = NextAlias[
A]) {
520 llvm::SmallVector<llvm::StringRef, 4> Prefixes;
521 DriverTable.appendOptionPrefixes(A, Prefixes);
522 if (Prefixes.empty())
524 auto Opt = DriverTable.getOption(A);
526 if (Opt.getName().empty())
528 auto Modes = getModes(Opt);
529 std::pair<unsigned, unsigned> ArgCount = getArgCount(Opt);
531 for (StringRef Prefix : Prefixes) {
532 llvm::SmallString<64> Buf(Prefix);
533 Buf.append(Opt.getName());
534 llvm::StringRef Spelling = Result->try_emplace(Buf).first->getKey();
535 Rules.emplace_back();
536 Rule &R = Rules.back();
539 R.ExactArgs = ArgCount.first;
540 R.PrefixArgs = ArgCount.second;
543 assert(ID < std::numeric_limits<
decltype(R.Priority)>::max() &&
544 "Rules::Priority overflowed by options table");
549 for (
const auto &R : Rules)
550 Result->find(R.Text)->second.append(Rules.begin(), Rules.end());
554 unsigned RuleCount = 0;
555 dlog(
"ArgStripper Option spelling table");
556 for (
const auto &Entry : *Result) {
557 dlog(
"{0}", Entry.first());
558 RuleCount += Entry.second.size();
559 for (
const auto &R : Entry.second)
560 dlog(
" {0} #={1} *={2} Mode={3}", R.Text, R.ExactArgs, R.PrefixArgs,
563 dlog(
"Table spellings={0} rules={1} string-bytes={2}", Result->size(),
564 RuleCount, Result->getAllocator().getBytesAllocated());
567 return Result.release();
570 auto It = Table->find(Arg);
571 return (It == Table->end()) ? llvm::ArrayRef<Rule>() : It->second;
575 auto OptionRules = rulesFor(Arg);
576 if (OptionRules.empty()) {
578 Storage.emplace_back(Arg);
579 Rules.emplace_back();
580 Rules.back().Text = Storage.back();
581 Rules.back().ExactArgs = 1;
582 if (Rules.back().Text.consume_back(
"*"))
583 Rules.back().PrefixArgs = 1;
584 Rules.back().Modes = DM_All;
585 Rules.back().Priority = -1;
587 Rules.append(OptionRules.begin(), OptionRules.end());
591const ArgStripper::Rule *ArgStripper::matchingRule(llvm::StringRef Arg,
593 unsigned &ArgCount)
const {
594 const ArgStripper::Rule *BestRule =
nullptr;
595 for (
const Rule &R : Rules) {
597 if (!(R.Modes & Mode))
599 if (BestRule && BestRule->Priority < R.Priority)
601 if (!Arg.starts_with(R.Text))
603 bool PrefixMatch = Arg.size() > R.Text.size();
605 if (
unsigned Count = PrefixMatch ? R.PrefixArgs : R.ExactArgs) {
620 DriverMode MainMode = getDriverMode(Args);
621 DriverMode CurrentMode = MainMode;
625 bool WasXclang =
false;
626 while (
Read < Args.size()) {
627 unsigned ArgCount = 0;
628 if (matchingRule(Args[
Read], CurrentMode, ArgCount)) {
633 CurrentMode = MainMode;
637 for (
unsigned I = 1;
Read < Args.size() && I < ArgCount; ++I) {
639 if (
Read < Args.size() && Args[
Read] ==
"-Xclang")
644 WasXclang = Args[
Read] ==
"-Xclang";
645 CurrentMode = WasXclang ? DM_CC1 : MainMode;
655std::string
printArgv(llvm::ArrayRef<llvm::StringRef> Args) {
657 llvm::raw_string_ostream OS(Buf);
659 for (llvm::StringRef Arg : Args) {
663 if (llvm::all_of(Arg, llvm::isPrint) &&
664 Arg.find_first_of(
" \t\n\"\\") == llvm::StringRef::npos) {
669 OS.write_escaped(Arg,
true);
672 return std::move(OS.str());
675std::string
printArgv(llvm::ArrayRef<std::string> Args) {
676 std::vector<llvm::StringRef> Refs(Args.size());
677 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.
void elog(const char *Fmt, Ts &&... Vals)
===– 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.