34#include "clang/Basic/Stack.h"
35#include "clang/Format/Format.h"
36#include "llvm/ADT/SmallString.h"
37#include "llvm/ADT/StringRef.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/FileSystem.h"
40#include "llvm/Support/InitLLVM.h"
41#include "llvm/Support/Path.h"
42#include "llvm/Support/PluginLoader.h"
43#include "llvm/Support/Process.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/TargetSelect.h"
47#include "llvm/Support/raw_ostream.h"
76using llvm::cl::CommaSeparated;
78using llvm::cl::Hidden;
82using llvm::cl::OptionCategory;
83using llvm::cl::ValueOptional;
84using llvm::cl::values;
88OptionCategory CompileCommands(
"clangd compilation flags options");
89OptionCategory Features(
"clangd feature options");
90OptionCategory Misc(
"clangd miscellaneous options");
91OptionCategory Protocol(
"clangd protocol and logging options");
92OptionCategory Retired(
"clangd flags no longer in use");
93const OptionCategory *ClangdCategories[] = {&Features, &Protocol,
94 &CompileCommands, &Misc, &Retired};
96std::vector<const llvm::cl::Option *> RetiredOptions;
98template <
typename T>
class RetiredFlag {
102 RetiredFlag(llvm::StringRef Name)
103 : Option(Name, cat(Retired),
desc(
"Obsolete flag, ignored"), Hidden) {
104 RetiredOptions.push_back(&Option);
108enum CompileArgsFrom { LSPCompileArgs, FilesystemCompileArgs };
109opt<CompileArgsFrom> CompileArgsFrom{
111 cat(CompileCommands),
112 desc(
"The source of compile commands"),
113 values(clEnumValN(LSPCompileArgs,
"lsp",
114 "All compile commands come from LSP and "
115 "'compile_commands.json' files are ignored"),
116 clEnumValN(FilesystemCompileArgs,
"filesystem",
117 "All compile commands come from the "
118 "'compile_commands.json' files")),
119 init(FilesystemCompileArgs),
123opt<Path> CompileCommandsDir{
124 "compile-commands-dir",
125 cat(CompileCommands),
126 desc(
"Specify a path to look for compile_commands.json. If path "
127 "is invalid, clangd will look in the current directory and "
128 "parent paths of each source file"),
131opt<Path> ResourceDir{
133 cat(CompileCommands),
134 desc(
"Directory for system clang headers"),
139list<std::string> QueryDriverGlobs{
141 cat(CompileCommands),
143 "Comma separated list of globs for white-listing gcc-compatible "
144 "drivers that are safe to execute. Drivers matching any of these globs "
145 "will be used to extract system includes. e.g. "
146 "/usr/bin/**/clang-*,/path/to/repo/**/g++-*"),
152opt<bool> AllScopesCompletion{
153 "all-scopes-completion",
155 desc(
"If set to true, code completion will include index symbols that are "
156 "not defined in the scopes (e.g. "
157 "namespaces) visible from the code completion point. Such completions "
158 "can insert scope qualifiers"),
162opt<bool> ShowOrigins{
165 desc(
"Show origins of completion items"),
170opt<bool> EnableBackgroundIndex{
173 desc(
"Index project code in the background and persist index on disk."),
177opt<llvm::ThreadPriority> BackgroundIndexPriority{
178 "background-index-priority",
180 desc(
"Thread priority for building the background index. "
181 "The effect of this flag is OS-specific."),
182 values(clEnumValN(llvm::ThreadPriority::Background,
"background",
183 "Minimum priority, runs on idle CPUs. "
184 "May leave 'performance' cores unused."),
185 clEnumValN(llvm::ThreadPriority::Low,
"low",
186 "Reduced priority compared to interactive work."),
187 clEnumValN(llvm::ThreadPriority::Default,
"normal",
188 "Same priority as other clangd work.")),
189 init(llvm::ThreadPriority::Low),
192opt<bool> EnableClangTidy{
195 desc(
"Enable clang-tidy diagnostics"),
199opt<CodeCompleteOptions::CodeCompletionParse> CodeCompletionParse{
202 desc(
"Whether the clang-parser is used for code-completion"),
203 values(clEnumValN(CodeCompleteOptions::AlwaysParse,
"always",
204 "Block until the parser can be used"),
205 clEnumValN(CodeCompleteOptions::ParseIfReady,
"auto",
206 "Use text-based completion if the parser "
208 clEnumValN(CodeCompleteOptions::NeverParse,
"never",
209 "Always used text-based completion")),
214opt<CodeCompleteOptions::CodeCompletionRankingModel> RankingModel{
217 desc(
"Model to use to rank code-completion items"),
218 values(clEnumValN(CodeCompleteOptions::Heuristics,
"heuristics",
219 "Use heuristics to rank code completion items"),
220 clEnumValN(CodeCompleteOptions::DecisionForest,
"decision_forest",
221 "Use Decision Forest model to rank completion items")),
227enum CompletionStyleFlag { Detailed, Bundled };
228opt<CompletionStyleFlag> CompletionStyle{
231 desc(
"Granularity of code completion suggestions"),
232 values(clEnumValN(Detailed,
"detailed",
233 "One completion item for each semantically distinct "
234 "completion, with full type information"),
235 clEnumValN(Bundled,
"bundled",
236 "Similar completion items (e.g. function overloads) are "
237 "combined. Type information shown where possible")),
240opt<std::string> FallbackStyle{
243 desc(
"clang-format style to apply by default when "
244 "no .clang-format file is found"),
245 init(clang::format::DefaultFallbackStyle),
248opt<std::string> EnableFunctionArgSnippets{
249 "function-arg-placeholders",
251 desc(
"When disabled (0), completions contain only parentheses for "
252 "function calls. When enabled (1), completions also contain "
253 "placeholders for method parameters"),
257opt<Config::HeaderInsertionPolicy> HeaderInsertion{
260 desc(
"Add #include directives when accepting code completions"),
264 "Include what you use. "
265 "Insert the owning header for top-level symbols, unless the "
266 "header is already directly included or the symbol is "
270 "Never insert #include directives as part of code completion")),
273opt<bool> ImportInsertions{
276 desc(
"If header insertion is enabled, add #import directives when "
277 "accepting code completions or fixing includes in Objective-C code"),
281opt<bool> HeaderInsertionDecorators{
282 "header-insertion-decorators",
284 desc(
"Prepend a circular dot or space before the completion "
285 "label, depending on whether "
286 "an include line will be inserted or not"),
290opt<bool> HiddenFeatures{
293 desc(
"Enable hidden features mostly useful to clangd developers"),
298opt<bool> IncludeIneligibleResults{
299 "include-ineligible-results",
301 desc(
"Include ineligible completion results (e.g. private members)"),
306RetiredFlag<bool> EnableIndex(
"index");
307RetiredFlag<bool> SuggestMissingIncludes(
"suggest-missing-includes");
308RetiredFlag<bool> RecoveryAST(
"recovery-ast");
309RetiredFlag<bool> RecoveryASTType(
"recovery-ast-type");
310RetiredFlag<bool> AsyncPreamble(
"async-preamble");
311RetiredFlag<bool> CollectMainFileRefs(
"collect-main-file-refs");
312RetiredFlag<bool> CrossFileRename(
"cross-file-rename");
313RetiredFlag<std::string> ClangTidyChecks(
"clang-tidy-checks");
314RetiredFlag<bool> InlayHints(
"inlay-hints");
315RetiredFlag<bool> FoldingRanges(
"folding-ranges");
316RetiredFlag<bool> IncludeCleanerStdlib(
"include-cleaner-stdlib");
318opt<int> LimitResults{
321 desc(
"Limit the number of results returned by clangd. "
322 "0 means no limit (default=100)"),
326opt<int> ReferencesLimit{
329 desc(
"Limit the number of references returned by clangd. "
330 "0 means no limit (default=1000)"),
334opt<int> RenameFileLimit{
337 desc(
"Limit the number of files to be affected by symbol renaming. "
338 "0 means no limit (default=50)"),
342list<std::string> TweakList{
345 desc(
"Specify a list of Tweaks to enable (only for clangd developers)."),
350opt<unsigned> WorkerThreadsCount{
353 desc(
"Number of async workers used by clangd. Background index also "
354 "uses this many workers."),
362 "Index file to build the static index. The file must have been created "
363 "by a compatible clangd-indexer\n"
364 "WARNING: This option is experimental only, and will be removed "
365 "eventually. Don't rely on it"),
373 desc(
"Abbreviation for -input-style=delimited -pretty -sync "
374 "-enable-test-scheme -enable-config=0 -log=verbose -crash-pragmas. "
375 "Also sets config options: Index.StandardLibrary=false. "
376 "Intended to simplify lit tests"),
381opt<bool> CrashPragmas{
384 desc(
"Respect `#pragma clang __debug crash` and friends."),
392 desc(
"Parse one file in isolation instead of acting as a language server. "
393 "Useful to investigate/reproduce crashes or configuration problems. "
394 "With --check=<filename>, attempts to parse a particular file."),
399enum PCHStorageFlag { Disk, Memory };
400opt<PCHStorageFlag> PCHStorage{
403 desc(
"Storing PCHs in memory increases memory usages, but may "
404 "improve performance"),
406 clEnumValN(PCHStorageFlag::Disk,
"disk",
"store PCHs on disk"),
407 clEnumValN(PCHStorageFlag::Memory,
"memory",
"store PCHs in memory")),
408 init(PCHStorageFlag::Disk),
414 desc(
"Handle client requests on main thread. Background index still uses "
420opt<JSONStreamStyle> InputStyle{
423 desc(
"Input JSON stream encoding"),
427 "messages delimited by --- lines, with # comment support")),
432opt<bool> EnableTestScheme{
433 "enable-test-uri-scheme",
435 desc(
"Enable 'test:' URI scheme. Only use in lit tests"),
440opt<std::string> PathMappingsArg{
444 "Translates between client paths (as seen by a remote editor) and "
445 "server paths (where clangd sees files on disk). "
446 "Comma separated list of '<client_path>=<server_path>' pairs, the "
447 "first entry matching a given path is used. "
448 "e.g. /home/project/incl=/opt/include,/home/project=/workarea/project"),
452opt<Path> InputMirrorFile{
455 desc(
"Mirror all LSP input to the specified file. Useful for debugging"),
460opt<Logger::Level> LogLevel{
463 desc(
"Verbosity of log messages written to stderr"),
464 values(clEnumValN(
Logger::Error,
"error",
"Error messages only"),
465 clEnumValN(
Logger::Info,
"info",
"High level execution tracing"),
470opt<OffsetEncoding> ForceOffsetEncoding{
473 desc(
"Force the offsetEncoding used for character positions. "
474 "This bypasses negotiation via client capabilities"),
478 "Offsets are in UTF-16 code units"),
480 "Offsets are in unicode codepoints")),
484opt<bool> PrettyPrint{
487 desc(
"Pretty-print JSON output"),
491opt<bool> EnableConfig{
498opt<bool> StrongWorkspaceMode{
499 "strong-workspace-mode",
501 desc(
"An alternate mode of operation for clangd, where the clangd instance "
502 "is used to edit a single workspace.\n"
503 "When enabled, fallback commands use the workspace directory as their "
504 "working directory instead of the parent folder."),
509opt<bool> UseDirtyHeaders{
"use-dirty-headers", cat(Misc),
510 desc(
"Use files open in the editor when parsing "
511 "headers instead of reading from the disk"),
515opt<bool> PreambleParseForwardingFunctions{
516 "parse-forwarding-functions",
518 desc(
"Parse all emplace-like functions in included headers"),
523opt<ClangdServer::SkipPreambleBuildPolicy> SkipPreambleBuild{
524 "skip-preamble-build",
526 desc(
"Skip building the preamble"),
531 "only if module use is encountered (default)"),
537#if defined(__GLIBC__) && CLANGD_MALLOC_TRIM
538opt<bool> EnableMallocTrim{
541 desc(
"Release memory periodically via malloc_trim(3)."),
545std::function<void()> getMemoryCleanupFunction() {
546 if (!EnableMallocTrim)
550 constexpr size_t MallocTrimPad = 20'000'000;
552 if (malloc_trim(MallocTrimPad))
553 vlog(
"Released memory via malloc_trim");
557std::function<void()> getMemoryCleanupFunction() {
return nullptr; }
560#if CLANGD_ENABLE_REMOTE
561opt<std::string> RemoteIndexAddress{
562 "remote-index-address",
564 desc(
"Address of the remote index server"),
568opt<std::string> ProjectRoot{
571 desc(
"Path to the project root. Requires remote-index-address to be set."),
575opt<bool> ExperimentalModulesSupport{
576 "experimental-modules-support",
578 desc(
"Experimental support for standard c++ modules"),
588 llvm::Expected<std::string>
590 llvm::StringRef )
const override {
591 using namespace llvm::sys;
594 if (!Body.starts_with(
"/"))
596 "Expect URI body to be an absolute path starting with '/': {0}",
598 Body = Body.ltrim(
'/');
599 llvm::SmallString<16>
Path(Body);
601 path::make_absolute(testDir(),
Path);
602 return std::string(
Path);
607 llvm::StringRef Body = AbsolutePath;
608 if (!Body.consume_front(testDir()))
609 return error(
"Path {0} doesn't start with root {1}", AbsolutePath,
612 return URI(
"test",
"",
613 llvm::sys::path::convert_to_slash(Body));
617 static llvm::StringRef testDir() {
619 static const std::string TestDir = llvm::sys::path::native(
"C:/clangd-test");
622 return "/clangd-test";
627std::unique_ptr<SymbolIndex>
630 static const trace::Metric RemoteIndexUsed(
"used_remote_index",
632 switch (External.Kind) {
636 RemoteIndexUsed.record(1, External.Location);
637 log(
"Associating {0} with remote index at {1}.", External.MountPoint,
641 log(
"Associating {0} with monolithic index at {1}.", External.MountPoint,
643 auto NewIndex = std::make_unique<SwapIndex>(std::make_unique<MemIndex>());
644 auto IndexLoadTask = [
File = External.Location,
645 PlaceHolder = NewIndex.get(), SupportContainedRefs] {
647 SupportContainedRefs))
648 PlaceHolder->reset(std::move(Idx));
651 Tasks->runAsync(
"Load-index:" + External.Location,
652 std::move(IndexLoadTask));
656 return std::move(NewIndex);
658 llvm_unreachable(
"Invalid ExternalIndexKind.");
661std::optional<bool> shouldEnableFunctionArgSnippets() {
662 std::string Val = EnableFunctionArgSnippets;
666 if (Val ==
"1" || Val ==
"true" || Val ==
"True" || Val ==
"TRUE")
668 if (Val ==
"0" || Val ==
"false" || Val ==
"False" || Val ==
"FALSE")
671 elog(
"Value specified by --function-arg-placeholders is invalid. Provide a "
672 "boolean value or leave unspecified to use ArgumentListsPolicy from "
681 std::vector<config::CompiledFragment>
682 getFragments(
const config::Params &,
688 FlagsConfigProvider() {
689 std::optional<Config::CDBSearchSpec> CDBSearch;
690 std::optional<Config::ExternalIndexSpec> IndexSpec;
691 std::optional<Config::BackgroundPolicy> BGPolicy;
692 std::optional<Config::ArgumentListsPolicy> ArgumentLists;
696 if (!CompileCommandsDir.empty()) {
697 if (llvm::sys::fs::exists(CompileCommandsDir)) {
702 llvm::SmallString<128>
Path(CompileCommandsDir);
703 if (std::error_code EC = llvm::sys::fs::make_absolute(
Path)) {
704 elog(
"Error while converting the relative path specified by "
705 "--compile-commands-dir to an absolute path: {0}. The argument "
712 elog(
"Path specified by --compile-commands-dir does not exist. The "
713 "argument will be ignored.");
716 if (!IndexFile.empty()) {
717 Config::ExternalIndexSpec Spec;
718 Spec.Kind = Spec.File;
719 Spec.Location = IndexFile;
720 IndexSpec = std::move(Spec);
722#if CLANGD_ENABLE_REMOTE
723 if (!RemoteIndexAddress.empty()) {
724 assert(!ProjectRoot.empty() && IndexFile.empty());
725 Config::ExternalIndexSpec Spec;
726 Spec.Kind = Spec.Server;
727 Spec.Location = RemoteIndexAddress;
728 Spec.MountPoint = ProjectRoot;
729 IndexSpec = std::move(Spec);
733 if (!EnableBackgroundIndex) {
737 if (std::optional<bool> Enable = shouldEnableFunctionArgSnippets()) {
742 Frag = [=](
const config::Params &,
Config &
C) {
744 C.CompileFlags.CDBSearch = *CDBSearch;
746 C.Index.External = *IndexSpec;
748 C.Index.Background = *BGPolicy;
750 C.Completion.ArgumentLists = *ArgumentLists;
751 if (HeaderInsertion.getNumOccurrences())
752 C.Completion.HeaderInsertion = HeaderInsertion;
753 if (AllScopesCompletion.getNumOccurrences())
754 C.Completion.AllScopes = AllScopesCompletion;
757 C.Index.StandardLibrary =
false;
773 clang::noteBottomOfStack();
774 llvm::InitLLVM
X(argc, argv);
775 llvm::InitializeAllTargetInfos();
776 llvm::sys::AddSignalHandler(
780 llvm::errs().flush();
784 llvm::cl::SetVersionPrinter([](llvm::raw_ostream &OS) {
789 const char *FlagsEnvVar =
"CLANGD_FLAGS";
790 const char *Overview =
791 R
"(clangd is a language server that provides IDE-like features to editors.
793It should be used via an editor plugin rather than invoked directly. For more information, see:
794 https://clangd.llvm.org/
795 https://microsoft.github.io/language-server-protocol/
797clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment variable.
800 if (llvm::cl::Option *LoadOpt =
801 llvm::cl::getRegisteredOptions().
lookup(
"load"))
802 LoadOpt->addCategory(Features);
804 llvm::cl::HideUnrelatedOptions(ClangdCategories);
805 llvm::cl::ParseCommandLineOptions(argc, argv, Overview,
nullptr,
806 nullptr, FlagsEnvVar);
807 for (
const llvm::cl::Option *O : RetiredOptions)
808 if (O->getNumOccurrences())
809 llvm::errs() <<
"The flag `-" << O->ArgStr
810 <<
"` is obsolete and ignored.\n";
812 if (!Sync.getNumOccurrences())
814 if (!CrashPragmas.getNumOccurrences())
820 if (!EnableConfig.getNumOccurrences())
821 EnableConfig =
false;
823 if (!EnableBackgroundIndex.getNumOccurrences())
824 EnableBackgroundIndex =
false;
826 else if (EnableBackgroundIndex)
829 if (Test || EnableTestScheme) {
830 static URISchemeRegistry::Add<TestScheme>
X(
831 "test",
"Test scheme for clangd lit tests.");
836 if (!Sync && WorkerThreadsCount == 0) {
837 llvm::errs() <<
"A number of worker threads cannot be 0. Did you mean to "
843 if (WorkerThreadsCount.getNumOccurrences())
844 llvm::errs() <<
"Ignoring -j because -sync is set.\n";
845 WorkerThreadsCount = 0;
847 if (FallbackStyle.getNumOccurrences())
848 clang::format::DefaultFallbackStyle = FallbackStyle.c_str();
851 std::optional<llvm::raw_fd_ostream> InputMirrorStream;
852 if (!InputMirrorFile.empty()) {
854 InputMirrorStream.emplace(InputMirrorFile, EC,
855 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
857 InputMirrorStream.reset();
858 llvm::errs() <<
"Error while opening an input mirror file: "
861 InputMirrorStream->SetUnbuffered();
865#if !CLANGD_DECISION_FOREST
866 if (RankingModel == clangd::CodeCompleteOptions::DecisionForest) {
867 llvm::errs() <<
"Clangd was compiled without decision forest support.\n";
875 std::optional<llvm::raw_fd_ostream> TracerStream;
876 std::unique_ptr<trace::EventTracer> Tracer;
877 const char *JSONTraceFile = getenv(
"CLANGD_TRACE");
878 const char *MetricsCSVFile = getenv(
"CLANGD_METRICS");
879 const char *TracerFile = JSONTraceFile ? JSONTraceFile : MetricsCSVFile;
882 TracerStream.emplace(TracerFile, EC,
883 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
885 TracerStream.reset();
886 llvm::errs() <<
"Error while opening trace file " << TracerFile <<
": "
889 Tracer = (TracerFile == JSONTraceFile)
895 std::optional<trace::Session> TracingSession;
897 TracingSession.emplace(*Tracer);
902 if (llvm::outs().is_displayed() && llvm::errs().is_displayed() &&
903 !CheckFile.getNumOccurrences())
904 llvm::errs() << Overview <<
"\n";
907 llvm::errs().SetBuffered();
913 log(
"PID: {0}", llvm::sys::Process::getProcessId());
915 SmallString<128> CWD;
916 if (
auto Err = llvm::sys::fs::current_path(CWD))
917 log(
"Working directory unknown: {0}", Err.message());
919 log(
"Working directory: {0}", CWD);
921 for (
int I = 0; I < argc; ++I)
922 log(
"argv[{0}]: {1}", I, argv[I]);
923 for (
unsigned I = 0, E = llvm::PluginLoader::getNumPlugins(); I < E; ++I)
924 log(
"Loaded plugin: {0}", llvm::PluginLoader::getPlugin(I));
925 if (
auto EnvFlags = llvm::sys::Process::GetEnv(FlagsEnvVar))
926 log(
"{0}: {1}", FlagsEnvVar, *EnvFlags);
929 for (
const char *EnvVar : {
939 "CPLUS_INCLUDE_PATH",
944 if (
auto Val = llvm::sys::Process::GetEnv(EnvVar))
945 log(
"Env {0}: {1}", EnvVar, *Val);
953 switch (PCHStorage) {
954 case PCHStorageFlag::Memory:
957 case PCHStorageFlag::Disk:
961 if (!ResourceDir.empty())
965#if CLANGD_ENABLE_REMOTE
966 if (RemoteIndexAddress.empty() != ProjectRoot.empty()) {
967 llvm::errs() <<
"remote-index-address and project-path have to be "
968 "specified at the same time.";
971 if (!RemoteIndexAddress.empty()) {
972 if (IndexFile.empty()) {
973 log(
"Connecting to remote index at {0}", RemoteIndexAddress);
975 elog(
"When enabling remote index, IndexFile should not be specified. "
976 "Only one can be used at time. Remote index will ignored.");
987 return loadExternalIndex(External, Tasks, SupportContainedRefs);
994 Opts.
CodeComplete.IncludeIneligibleResults = IncludeIneligibleResults;
996 if (CompletionStyle.getNumOccurrences())
997 Opts.
CodeComplete.BundleOverloads = CompletionStyle != Detailed;
1001 if (!HeaderInsertionDecorators) {
1009 Opts.
CodeComplete.ForceLoadPreamble = ExperimentalModulesSupport;
1011 std::vector<std::unique_ptr<config::Provider>> ProviderStack;
1014 ProviderStack.push_back(std::make_unique<FlagsConfigProvider>());
1019 if (EnableClangTidy) {
1020 std::vector<TidyProvider> Providers;
1021 Providers.reserve(4 + EnableConfig);
1028 ClangTidyOptProvider =
combine(std::move(Providers));
1036 if (T.hidden() && !HiddenFeatures)
1038 if (TweakList.getNumOccurrences())
1039 return llvm::is_contained(TweakList, T.id());
1043 Opts.
Encoding = ForceOffsetEncoding;
1046 if (EnableClangTidy)
1047 ModuleSet.
add(std::make_unique<ClangTidyFeatureModule>(
1048 std::move(ClangTidyOptProvider)));
1049 if (ModuleSet.
begin() != ModuleSet.
end())
1052 if (CheckFile.getNumOccurrences()) {
1053 llvm::SmallString<256>
Path;
1055 llvm::sys::fs::real_path(CheckFile,
Path,
true)) {
1056 elog(
"Failed to resolve path {0}: {1}", CheckFile,
Error.message());
1059 log(
"Entering check mode (no LSP server)");
1060 return check(
Path, TFS, std::move(Opts))
1067 llvm::sys::ChangeStdinToBinary();
1068 std::unique_ptr<Transport> TransportLayer;
1069 if (getenv(
"CLANGD_AS_XPC_SERVICE")) {
1071 log(
"Starting LSP over XPC service");
1074 llvm::errs() <<
"This clangd binary wasn't built with XPC support.\n";
1078 log(
"Starting LSP over stdin/stdout");
1080 stdin, llvm::outs(), InputMirrorStream ? &*InputMirrorStream :
nullptr,
1081 PrettyPrint, InputStyle);
1083 if (!PathMappingsArg.empty()) {
1086 elog(
"Invalid -path-mappings: {0}", Mappings.takeError());
1090 std::move(*Mappings));
1094 llvm::set_thread_name(
"clangd.main");
1095 int ExitCode = LSPServer.
run()
1098 log(
"LSP finished, exiting with status {0}", ExitCode);
static cl::opt< std::string > Config("config", desc(R"(
Specifies a configuration in YAML/JSON format:
-config="{Checks:' *', CheckOptions:{x:y}}"
When the value is empty, clang-tidy will
attempt to find a file named .clang-tidy for
each source file in its parent directories.
)"), cl::init(""), cl::cat(ClangTidyCategory))
static cl::desc desc(StringRef Description)
Include Cleaner is clangd functionality for providing diagnostics for misuse of transitive headers an...
Runs tasks on separate (detached) threads and wait for all tasks to finish.
static void preventThreadStarvationInTests()
This class exposes ClangdServer's capabilities via Language Server Protocol.
bool run()
Run LSP server loop, communicating with the Transport provided in the constructor.
A FeatureModuleSet is a collection of feature modules installed in clangd.
static FeatureModuleSet fromRegistry()
void add(std::unique_ptr< FeatureModule > M)
Interface to allow custom logging in clangd.
Only one LoggingSession can be active at a time.
llvm::Expected< std::string > getAbsolutePath(llvm::StringRef, llvm::StringRef Body, llvm::StringRef HintPath) const override
Returns the absolute path of the file corresponding to the URI authority+body in the file system.
llvm::Expected< URI > uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override
static void runCrashHandlers()
Calls all currently-active ThreadCrashReporters for the current thread.
Wrapper for vfs::FileSystem for use in multithreaded programs like clangd.
An interface base for small context-sensitive refactoring actions.
URIScheme is an extension point for teaching clangd to recognize a custom URI scheme.
A source of configuration fragments.
static const char *const EnableConfigFlagDesc
Help text for the –enable-config flag, shared by clangd tools that expose createDefaultProviders() on...
static std::vector< std::unique_ptr< Provider > > createDefaultProviders(const ThreadsafeFS &)
Returns providers for the configuration files that clangd tools read by default: project config (ance...
static std::unique_ptr< Provider > combine(std::vector< std::unique_ptr< Provider > >)
A provider that includes fragments from all the supplied providers.
std::function< bool(const Params &, Config &)> CompiledFragment
A chunk of configuration that has been fully analyzed and is ready to apply.
llvm::function_ref< void(const llvm::SMDiagnostic &)> DiagnosticCallback
Used to report problems in parsing or interpreting a config.
std::unique_ptr< clangd::SymbolIndex > getClient(llvm::StringRef Address, llvm::StringRef ProjectRoot)
Returns an SymbolIndex client that passes requests to remote index located at Address.
std::unique_ptr< EventTracer > createJSONTracer(llvm::raw_ostream &OS, bool Pretty)
Create an instance of EventTracer that produces an output in the Trace Event format supported by Chro...
std::unique_ptr< EventTracer > createCSVMetricTracer(llvm::raw_ostream &OS)
Create an instance of EventTracer that outputs metric measurements as CSV.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
llvm::unique_function< void(tidy::ClangTidyOptions &, llvm::StringRef) const > TidyProvider
A factory to modify a tidy::ClangTidyOptions.
TidyProvider combine(std::vector< TidyProvider > Providers)
bool check(llvm::StringRef File, const ThreadsafeFS &TFS, ClangdLSPServer::Options &&Opts)
unsigned getDefaultAsyncThreadsCount()
Returns a number of a default async threads to use for TUScheduler.
void vlog(const char *Fmt, Ts &&... Vals)
std::string platformString()
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
llvm::Expected< PathMappings > parsePathMappings(llvm::StringRef RawPathMappings)
Parse the command line RawPathMappings (e.g.
std::string featureString()
static URISchemeRegistry::Add< TestScheme > X(TestScheme::Scheme, "Test schema")
std::unique_ptr< Transport > createPathMappingTransport(std::unique_ptr< Transport > Transp, PathMappings Mappings)
Creates a wrapping transport over Transp that applies the Mappings to all inbound and outbound LSP me...
std::unique_ptr< Transport > newXPCTransport()
void log(const char *Fmt, Ts &&... Vals)
TidyProvider provideClangTidyFiles(ThreadsafeFS &TFS)
Provider that searches for .clang-tidy configuration files in the directory tree.
void allowCrashPragmasForTest()
Respect #pragma clang __debug crash etc, which are usually disabled.
std::unique_ptr< SymbolIndex > createProjectAwareIndex(IndexFactory Gen, bool Sync)
Returns an index that answers queries using external indices.
int clangdMain(int argc, char *argv[])
std::vector< std::string > lookup(const SymbolIndex &I, llvm::ArrayRef< SymbolID > IDs)
void requestShutdown()
Sets a flag to indicate that clangd was sent a shutdown signal, and the transport loop should exit at...
TidyProvider disableUnusableChecks(llvm::ArrayRef< std::string > ExtraBadChecks)
Provider that will disable checks known to not work with clangd.
std::string Path
A typedef to represent a file path.
std::unique_ptr< Transport > newJSONTransport(std::FILE *In, llvm::raw_ostream &Out, llvm::raw_ostream *InMirror, bool Pretty, JSONStreamStyle Style)
TidyProvider provideDefaultChecks()
Provider that will enable a nice set of default checks if none are specified.
TidyProvider provideClangdConfig()
void abortAfterTimeout(std::chrono::seconds Timeout)
Causes this process to crash if still running after Timeout.
void elog(const char *Fmt, Ts &&... Vals)
std::string versionString()
std::unique_ptr< SymbolIndex > loadIndex(llvm::StringRef SymbolFilename, SymbolOrigin Origin, bool UseDex, bool SupportContainedRefs)
TidyProvider provideEnvironment()
Provider that just sets the defaults.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
bool EnableExperimentalModulesSupport
Flag to hint the experimental modules support is enabled.
size_t ReferencesLimit
Limit the number of references returned (0 means no limit).
bool UseDirBasedCDB
Look for compilation databases, rather than using compile commands set via LSP (extensions) only.
clangd::RenameOptions Rename
std::function< void()> MemoryCleanup
If set, periodically called to release memory.
std::unique_ptr< config::Provider > ConfigProvider
Supplies configuration (overrides ClangdServer::ContextProvider).
clangd::CodeCompleteOptions CodeComplete
Per-feature options.
std::function< bool(const Tweak &)> TweakFilter
Returns true if the tweak should be enabled.
std::optional< OffsetEncoding > Encoding
The offset-encoding to use, or std::nullopt to negotiate it over LSP.
bool BuildDynamicSymbolIndex
If true, ClangdServer builds a dynamic in-memory index for symbols in opened files and uses the index...
std::vector< std::string > QueryDriverGlobs
Clangd will execute compiler drivers matching one of these globs to fetch system include path.
bool UseDirtyHeaders
If true, use the dirty buffer contents when building Preambles.
bool StorePreamblesInMemory
Cached preambles are potentially large. If false, store them on disk.
bool PreambleParseForwardingFunctions
SymbolIndex * StaticIndex
If set, use this index to augment code completion results.
llvm::ThreadPriority BackgroundIndexPriority
bool BackgroundIndex
If true, ClangdServer automatically indexes files in the current project on background threads.
unsigned AsyncThreadsCount
To process requests asynchronously, ClangdServer spawns worker threads.
SkipPreambleBuildPolicy SkipPreambleBuild
bool ImportInsertions
Whether include fixer insertions for Objective-C code should use import instead of include.
bool StrongWorkspaceMode
Sets an alternate mode of operation.
std::optional< std::string > ResourceDir
The resource directory is used to find internal headers, overriding defaults and -resource-dir compil...
FeatureModuleSet * FeatureModules
bool EnableOutgoingCalls
Call hierarchy's outgoing calls feature requires additional index serving structures which increase m...
Describes an external index configuration.
@ Delimiters
empty pair of delimiters "()" or "<>".
@ FullPlaceholders
full name of both type and variable.
size_t LimitFiles
The maximum number of affected files (0 means no limit), only meaningful when AllowCrossFile = true.
Represents measurements of clangd events, e.g.
@ Value
A number whose value is meaningful, and may vary over time.