Debian Codegraph @

clang-tools-extra/clangd/tool/ClangdMain.cpp

raw
1 //===--- ClangdMain.cpp - clangd server loop ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "ClangdMain.h"
10 #include "ClangdLSPServer.h"
11 #include "CodeComplete.h"
12 #include "Compiler.h"
13 #include "Config.h"
14 #include "ConfigProvider.h"
15 #include "Feature.h"
16 #include "FeatureModule.h"
17 #include "IncludeCleaner.h"
18 #include "PathMapping.h"
19 #include "Protocol.h"
20 #include "TidyProvider.h"
21 #include "Transport.h"
22 #include "index/Background.h"
23 #include "index/Index.h"
24 #include "index/MemIndex.h"
25 #include "index/Merge.h"
26 #include "index/ProjectAware.h"
27 #include "index/remote/Client.h"
28 #include "support/Path.h"
29 #include "support/Shutdown.h"
30 #include "support/ThreadCrashReporter.h"
31 #include "support/ThreadsafeFS.h"
32 #include "support/Trace.h"
33 #include "clang/Basic/Stack.h"
34 #include "clang/Format/Format.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/InitLLVM.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include <chrono>
47 #include <cstdlib>
48 #include <memory>
49 #include <mutex>
50 #include <optional>
51 #include <string>
52 #include <thread>
53 #include <utility>
54 #include <vector>
55
56 #ifndef _WIN32
57 #include <unistd.h>
58 #endif
59
60 #ifdef __GLIBC__
61 #include <malloc.h>
62 #endif
63
64 namespace clang {
65 namespace clangd {
66
67 // Implemented in Check.cpp.
68 bool check(const llvm::StringRef File, const ThreadsafeFS &TFS,
69 const ClangdLSPServer::Options &Opts);
70
71 namespace {
72
73 using llvm::cl::cat;
74 using llvm::cl::CommaSeparated;
75 using llvm::cl::desc;
76 using llvm::cl::Hidden;
77 using llvm::cl::init;
78 using llvm::cl::list;
79 using llvm::cl::opt;
80 using llvm::cl::OptionCategory;
81 using llvm::cl::ValueOptional;
82 using llvm::cl::values;
83
84 // All flags must be placed in a category, or they will be shown neither in
85 // --help, nor --help-hidden!
86 OptionCategory CompileCommands("clangd compilation flags options");
87 OptionCategory Features("clangd feature options");
88 OptionCategory Misc("clangd miscellaneous options");
89 OptionCategory Protocol("clangd protocol and logging options");
90 OptionCategory Retired("clangd flags no longer in use");
91 const OptionCategory *ClangdCategories[] = {&Features, &Protocol,
92 &CompileCommands, &Misc, &Retired};
93
94 template <typename T> class RetiredFlag {
95 opt<T> Option;
96
97 public:
98 RetiredFlag(llvm::StringRef Name)
99 : Option(Name, cat(Retired), desc("Obsolete flag, ignored"), Hidden,
100 llvm::cl::callback([Name](const T &) {
101 llvm::errs()
102 << "The flag `-" << Name << "` is obsolete and ignored.\n";
103 })) {}
104 };
105
106 enum CompileArgsFrom { LSPCompileArgs, FilesystemCompileArgs };
107 opt<CompileArgsFrom> CompileArgsFrom{
108 "compile_args_from",
109 cat(CompileCommands),
110 desc("The source of compile commands"),
111 values(clEnumValN(LSPCompileArgs, "lsp",
112 "All compile commands come from LSP and "
113 "'compile_commands.json' files are ignored"),
114 clEnumValN(FilesystemCompileArgs, "filesystem",
115 "All compile commands come from the "
116 "'compile_commands.json' files")),
117 init(FilesystemCompileArgs),
118 Hidden,
119 };
120
121 opt<Path> CompileCommandsDir{
122 "compile-commands-dir",
123 cat(CompileCommands),
124 desc("Specify a path to look for compile_commands.json. If path "
125 "is invalid, clangd will look in the current directory and "
126 "parent paths of each source file"),
127 };
128
129 opt<Path> ResourceDir{
130 "resource-dir",
131 cat(CompileCommands),
132 desc("Directory for system clang headers"),
133 init(""),
134 Hidden,
135 };
136
137 list<std::string> QueryDriverGlobs{
138 "query-driver",
139 cat(CompileCommands),
140 desc(
141 "Comma separated list of globs for white-listing gcc-compatible "
142 "drivers that are safe to execute. Drivers matching any of these globs "
143 "will be used to extract system includes. e.g. "
144 "/usr/bin/**/clang-*,/path/to/repo/**/g++-*"),
145 CommaSeparated,
146 };
147
148 // FIXME: Flags are the wrong mechanism for user preferences.
149 // We should probably read a dotfile or similar.
150 opt<bool> AllScopesCompletion{
151 "all-scopes-completion",
152 cat(Features),
153 desc("If set to true, code completion will include index symbols that are "
154 "not defined in the scopes (e.g. "
155 "namespaces) visible from the code completion point. Such completions "
156 "can insert scope qualifiers"),
157 init(true),
158 };
159
160 opt<bool> ShowOrigins{
161 "debug-origin",
162 cat(Features),
163 desc("Show origins of completion items"),
164 init(CodeCompleteOptions().ShowOrigins),
165 Hidden,
166 };
167
168 opt<bool> EnableBackgroundIndex{
169 "background-index",
170 cat(Features),
171 desc("Index project code in the background and persist index on disk."),
172 init(true),
173 };
174
175 opt<llvm::ThreadPriority> BackgroundIndexPriority{
176 "background-index-priority",
177 cat(Features),
178 desc("Thread priority for building the background index. "
179 "The effect of this flag is OS-specific."),
180 values(clEnumValN(llvm::ThreadPriority::Background, "background",
181 "Minimum priority, runs on idle CPUs. "
182 "May leave 'performance' cores unused."),
183 clEnumValN(llvm::ThreadPriority::Low, "low",
184 "Reduced priority compared to interactive work."),
185 clEnumValN(llvm::ThreadPriority::Default, "normal",
186 "Same priority as other clangd work.")),
187 init(llvm::ThreadPriority::Low),
188 };
189
190 opt<bool> EnableClangTidy{
191 "clang-tidy",
192 cat(Features),
193 desc("Enable clang-tidy diagnostics"),
194 init(true),
195 };
196
197 opt<CodeCompleteOptions::CodeCompletionParse> CodeCompletionParse{
198 "completion-parse",
199 cat(Features),
200 desc("Whether the clang-parser is used for code-completion"),
201 values(clEnumValN(CodeCompleteOptions::AlwaysParse, "always",
202 "Block until the parser can be used"),
203 clEnumValN(CodeCompleteOptions::ParseIfReady, "auto",
204 "Use text-based completion if the parser "
205 "is not ready"),
206 clEnumValN(CodeCompleteOptions::NeverParse, "never",
207 "Always used text-based completion")),
208 init(CodeCompleteOptions().RunParser),
209 Hidden,
210 };
211
212 opt<CodeCompleteOptions::CodeCompletionRankingModel> RankingModel{
213 "ranking-model",
214 cat(Features),
215 desc("Model to use to rank code-completion items"),
216 values(clEnumValN(CodeCompleteOptions::Heuristics, "heuristics",
217 "Use heuristics to rank code completion items"),
218 clEnumValN(CodeCompleteOptions::DecisionForest, "decision_forest",
219 "Use Decision Forest model to rank completion items")),
220 init(CodeCompleteOptions().RankingModel),
221 Hidden,
222 };
223
224 // FIXME: also support "plain" style where signatures are always omitted.
225 enum CompletionStyleFlag { Detailed, Bundled };
226 opt<CompletionStyleFlag> CompletionStyle{
227 "completion-style",
228 cat(Features),
229 desc("Granularity of code completion suggestions"),
230 values(clEnumValN(Detailed, "detailed",
231 "One completion item for each semantically distinct "
232 "completion, with full type information"),
233 clEnumValN(Bundled, "bundled",
234 "Similar completion items (e.g. function overloads) are "
235 "combined. Type information shown where possible")),
236 };
237
238 opt<std::string> FallbackStyle{
239 "fallback-style",
240 cat(Features),
241 desc("clang-format style to apply by default when "
242 "no .clang-format file is found"),
243 init(clang::format::DefaultFallbackStyle),
244 };
245
246 opt<std::string> EnableFunctionArgSnippets{
247 "function-arg-placeholders",
248 cat(Features),
249 desc("When disabled (0), completions contain only parentheses for "
250 "function calls. When enabled (1), completions also contain "
251 "placeholders for method parameters"),
252 init("-1"),
253 };
254
255 opt<Config::HeaderInsertionPolicy> HeaderInsertion{
256 "header-insertion",
257 cat(Features),
258 desc("Add #include directives when accepting code completions"),
259 init(CodeCompleteOptions().InsertIncludes),
260 values(
261 clEnumValN(Config::HeaderInsertionPolicy::IWYU, "iwyu",
262 "Include what you use. "
263 "Insert the owning header for top-level symbols, unless the "
264 "header is already directly included or the symbol is "
265 "forward-declared"),
266 clEnumValN(
267 Config::HeaderInsertionPolicy::NeverInsert, "never",
268 "Never insert #include directives as part of code completion")),
269 };
270
271 opt<bool> ImportInsertions{
272 "import-insertions",
273 cat(Features),
274 desc("If header insertion is enabled, add #import directives when "
275 "accepting code completions or fixing includes in Objective-C code"),
276 init(CodeCompleteOptions().ImportInsertions),
277 };
278
279 opt<bool> HeaderInsertionDecorators{
280 "header-insertion-decorators",
281 cat(Features),
282 desc("Prepend a circular dot or space before the completion "
283 "label, depending on whether "
284 "an include line will be inserted or not"),
285 init(true),
286 };
287
288 opt<bool> HiddenFeatures{
289 "hidden-features",
290 cat(Features),
291 desc("Enable hidden features mostly useful to clangd developers"),
292 init(false),
293 Hidden,
294 };
295
296 opt<bool> IncludeIneligibleResults{
297 "include-ineligible-results",
298 cat(Features),
299 desc("Include ineligible completion results (e.g. private members)"),
300 init(CodeCompleteOptions().IncludeIneligibleResults),
301 Hidden,
302 };
303
304 RetiredFlag<bool> EnableIndex("index");
305 RetiredFlag<bool> SuggestMissingIncludes("suggest-missing-includes");
306 RetiredFlag<bool> RecoveryAST("recovery-ast");
307 RetiredFlag<bool> RecoveryASTType("recovery-ast-type");
308 RetiredFlag<bool> AsyncPreamble("async-preamble");
309 RetiredFlag<bool> CollectMainFileRefs("collect-main-file-refs");
310 RetiredFlag<bool> CrossFileRename("cross-file-rename");
311 RetiredFlag<std::string> ClangTidyChecks("clang-tidy-checks");
312 RetiredFlag<bool> InlayHints("inlay-hints");
313 RetiredFlag<bool> FoldingRanges("folding-ranges");
314 RetiredFlag<bool> IncludeCleanerStdlib("include-cleaner-stdlib");
315
316 opt<int> LimitResults{
317 "limit-results",
318 cat(Features),
319 desc("Limit the number of results returned by clangd. "
320 "0 means no limit (default=100)"),
321 init(100),
322 };
323
324 opt<int> ReferencesLimit{
325 "limit-references",
326 cat(Features),
327 desc("Limit the number of references returned by clangd. "
328 "0 means no limit (default=1000)"),
329 init(1000),
330 };
331
332 opt<int> RenameFileLimit{
333 "rename-file-limit",
334 cat(Features),
335 desc("Limit the number of files to be affected by symbol renaming. "
336 "0 means no limit (default=50)"),
337 init(50),
338 };
339
340 list<std::string> TweakList{
341 "tweaks",
342 cat(Features),
343 desc("Specify a list of Tweaks to enable (only for clangd developers)."),
344 Hidden,
345 CommaSeparated,
346 };
347
348 opt<unsigned> WorkerThreadsCount{
349 "j",
350 cat(Misc),
351 desc("Number of async workers used by clangd. Background index also "
352 "uses this many workers."),
353 init(getDefaultAsyncThreadsCount()),
354 };
355
356 opt<Path> IndexFile{
357 "index-file",
358 cat(Misc),
359 desc(
360 "Index file to build the static index. The file must have been created "
361 "by a compatible clangd-indexer\n"
362 "WARNING: This option is experimental only, and will be removed "
363 "eventually. Don't rely on it"),
364 init(""),
365 Hidden,
366 };
367
368 opt<bool> Test{
369 "lit-test",
370 cat(Misc),
371 desc("Abbreviation for -input-style=delimited -pretty -sync "
372 "-enable-test-scheme -enable-config=0 -log=verbose -crash-pragmas. "
373 "Also sets config options: Index.StandardLibrary=false. "
374 "Intended to simplify lit tests"),
375 init(false),
376 Hidden,
377 };
378
379 opt<bool> CrashPragmas{
380 "crash-pragmas",
381 cat(Misc),
382 desc("Respect `#pragma clang __debug crash` and friends."),
383 init(false),
384 Hidden,
385 };
386
387 opt<Path> CheckFile{
388 "check",
389 cat(Misc),
390 desc("Parse one file in isolation instead of acting as a language server. "
391 "Useful to investigate/reproduce crashes or configuration problems. "
392 "With --check=<filename>, attempts to parse a particular file."),
393 init(""),
394 ValueOptional,
395 };
396
397 enum PCHStorageFlag { Disk, Memory };
398 opt<PCHStorageFlag> PCHStorage{
399 "pch-storage",
400 cat(Misc),
401 desc("Storing PCHs in memory increases memory usages, but may "
402 "improve performance"),
403 values(
404 clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
405 clEnumValN(PCHStorageFlag::Memory, "memory", "store PCHs in memory")),
406 init(PCHStorageFlag::Disk),
407 };
408
409 opt<bool> Sync{
410 "sync",
411 cat(Misc),
412 desc("Handle client requests on main thread. Background index still uses "
413 "its own thread."),
414 init(false),
415 Hidden,
416 };
417
418 opt<JSONStreamStyle> InputStyle{
419 "input-style",
420 cat(Protocol),
421 desc("Input JSON stream encoding"),
422 values(
423 clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
424 clEnumValN(JSONStreamStyle::Delimited, "delimited",
425 "messages delimited by --- lines, with # comment support")),
426 init(JSONStreamStyle::Standard),
427 Hidden,
428 };
429
430 opt<bool> EnableTestScheme{
431 "enable-test-uri-scheme",
432 cat(Protocol),
433 desc("Enable 'test:' URI scheme. Only use in lit tests"),
434 init(false),
435 Hidden,
436 };
437
438 opt<std::string> PathMappingsArg{
439 "path-mappings",
440 cat(Protocol),
441 desc(
442 "Translates between client paths (as seen by a remote editor) and "
443 "server paths (where clangd sees files on disk). "
444 "Comma separated list of '<client_path>=<server_path>' pairs, the "
445 "first entry matching a given path is used. "
446 "e.g. /home/project/incl=/opt/include,/home/project=/workarea/project"),
447 init(""),
448 };
449
450 opt<Path> InputMirrorFile{
451 "input-mirror-file",
452 cat(Protocol),
453 desc("Mirror all LSP input to the specified file. Useful for debugging"),
454 init(""),
455 Hidden,
456 };
457
458 opt<Logger::Level> LogLevel{
459 "log",
460 cat(Protocol),
461 desc("Verbosity of log messages written to stderr"),
462 values(clEnumValN(Logger::Error, "error", "Error messages only"),
463 clEnumValN(Logger::Info, "info", "High level execution tracing"),
464 clEnumValN(Logger::Debug, "verbose", "Low level details")),
465 init(Logger::Info),
466 };
467
468 opt<OffsetEncoding> ForceOffsetEncoding{
469 "offset-encoding",
470 cat(Protocol),
471 desc("Force the offsetEncoding used for character positions. "
472 "This bypasses negotiation via client capabilities"),
473 values(
474 clEnumValN(OffsetEncoding::UTF8, "utf-8", "Offsets are in UTF-8 bytes"),
475 clEnumValN(OffsetEncoding::UTF16, "utf-16",
476 "Offsets are in UTF-16 code units"),
477 clEnumValN(OffsetEncoding::UTF32, "utf-32",
478 "Offsets are in unicode codepoints")),
479 init(OffsetEncoding::UnsupportedEncoding),
480 };
481
482 opt<bool> PrettyPrint{
483 "pretty",
484 cat(Protocol),
485 desc("Pretty-print JSON output"),
486 init(false),
487 };
488
489 opt<bool> EnableConfig{
490 "enable-config",
491 cat(Misc),
492 desc(
493 "Read user and project configuration from YAML files.\n"
494 "Project config is from a .clangd file in the project directory.\n"
495 "User config is from clangd/config.yaml in the following directories:\n"
496 "\tWindows: %USERPROFILE%\\AppData\\Local\n"
497 "\tMac OS: ~/Library/Preferences/\n"
498 "\tOthers: $XDG_CONFIG_HOME, usually ~/.config\n"
499 "Configuration is documented at https://clangd.llvm.org/config.html"),
500 init(true),
501 };
502
503 opt<bool> StrongWorkspaceMode{
504 "strong-workspace-mode",
505 cat(Features),
506 desc("An alternate mode of operation for clangd, where the clangd instance "
507 "is used to edit a single workspace.\n"
508 "When enabled, fallback commands use the workspace directory as their "
509 "working directory instead of the parent folder."),
510 init(false),
511 Hidden,
512 };
513
514 opt<bool> UseDirtyHeaders{"use-dirty-headers", cat(Misc),
515 desc("Use files open in the editor when parsing "
516 "headers instead of reading from the disk"),
517 Hidden,
518 init(ClangdServer::Options().UseDirtyHeaders)};
519
520 opt<bool> PreambleParseForwardingFunctions{
521 "parse-forwarding-functions",
522 cat(Misc),
523 desc("Parse all emplace-like functions in included headers"),
524 Hidden,
525 init(ParseOptions().PreambleParseForwardingFunctions),
526 };
527
528 #if defined(__GLIBC__) && CLANGD_MALLOC_TRIM
529 opt<bool> EnableMallocTrim{
530 "malloc-trim",
531 cat(Misc),
532 desc("Release memory periodically via malloc_trim(3)."),
533 init(true),
534 };
535
536 std::function<void()> getMemoryCleanupFunction() {
537 if (!EnableMallocTrim)
538 return nullptr;
539 // Leave a few MB at the top of the heap: it is insignificant
540 // and will most likely be needed by the main thread
541 constexpr size_t MallocTrimPad = 20'000'000;
542 return []() {
543 if (malloc_trim(MallocTrimPad))
544 vlog("Released memory via malloc_trim");
545 };
546 }
547 #else
548 std::function<void()> getMemoryCleanupFunction() { return nullptr; }
549 #endif
550
551 #if CLANGD_ENABLE_REMOTE
552 opt<std::string> RemoteIndexAddress{
553 "remote-index-address",
554 cat(Features),
555 desc("Address of the remote index server"),
556 };
557
558 // FIXME(kirillbobyrev): Should this be the location of compile_commands.json?
559 opt<std::string> ProjectRoot{
560 "project-root",
561 cat(Features),
562 desc("Path to the project root. Requires remote-index-address to be set."),
563 };
564 #endif
565
566 opt<bool> ExperimentalModulesSupport{
567 "experimental-modules-support",
568 cat(Features),
569 desc("Experimental support for standard c++ modules"),
570 init(false),
571 };
572
573 /// Supports a test URI scheme with relaxed constraints for lit tests.
574 /// The path in a test URI will be combined with a platform-specific fake
575 /// directory to form an absolute path. For example, test:///a.cpp is resolved
576 /// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
577 class TestScheme : public URIScheme {
578 public:
579 llvm::Expected<std::string>
580 getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
581 llvm::StringRef /*HintPath*/) const override {
582 using namespace llvm::sys;
583 // Still require "/" in body to mimic file scheme, as we want lengths of an
584 // equivalent URI in both schemes to be the same.
585 if (!Body.starts_with("/"))
586 return error(
587 "Expect URI body to be an absolute path starting with '/': {0}",
588 Body);
589 Body = Body.ltrim('/');
590 llvm::SmallString<16> Path(Body);
591 path::native(Path);
592 path::make_absolute(TestScheme::TestDir, Path);
593 return std::string(Path);
594 }
595
596 llvm::Expected<URI>
597 uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
598 llvm::StringRef Body = AbsolutePath;
599 if (!Body.consume_front(TestScheme::TestDir))
600 return error("Path {0} doesn't start with root {1}", AbsolutePath,
601 TestDir);
602
603 return URI("test", /*Authority=*/"",
604 llvm::sys::path::convert_to_slash(Body));
605 }
606
607 private:
608 const static char TestDir[];
609 };
610
611 #ifdef _WIN32
612 const char TestScheme::TestDir[] = "C:\\clangd-test";
613 #else
614 const char TestScheme::TestDir[] = "/clangd-test";
615 #endif
616
617 std::unique_ptr<SymbolIndex>
618 loadExternalIndex(const Config::ExternalIndexSpec &External,
619 AsyncTaskRunner *Tasks, bool SupportContainedRefs) {
620 static const trace::Metric RemoteIndexUsed("used_remote_index",
621 trace::Metric::Value, "address");
622 switch (External.Kind) {
623 case Config::ExternalIndexSpec::None:
624 break;
625 case Config::ExternalIndexSpec::Server:
626 RemoteIndexUsed.record(1, External.Location);
627 log("Associating {0} with remote index at {1}.", External.MountPoint,
628 External.Location);
629 return remote::getClient(External.Location, External.MountPoint);
630 case Config::ExternalIndexSpec::File:
631 log("Associating {0} with monolithic index at {1}.", External.MountPoint,
632 External.Location);
633 auto NewIndex = std::make_unique<SwapIndex>(std::make_unique<MemIndex>());
634 auto IndexLoadTask = [File = External.Location,
635 PlaceHolder = NewIndex.get(), SupportContainedRefs] {
636 if (auto Idx = loadIndex(File, SymbolOrigin::Static, /*UseDex=*/true,
637 SupportContainedRefs))
638 PlaceHolder->reset(std::move(Idx));
639 };
640 if (Tasks) {
641 Tasks->runAsync("Load-index:" + External.Location,
642 std::move(IndexLoadTask));
643 } else {
644 IndexLoadTask();
645 }
646 return std::move(NewIndex);
647 }
648 llvm_unreachable("Invalid ExternalIndexKind.");
649 }
650
651 std::optional<bool> shouldEnableFunctionArgSnippets() {
652 std::string Val = EnableFunctionArgSnippets;
653 // Accept the same values that a bool option parser would, but also accept
654 // -1 to indicate "unspecified", in which case the ArgumentListsPolicy
655 // config option will be respected.
656 if (Val == "1" || Val == "true" || Val == "True" || Val == "TRUE")
657 return true;
658 if (Val == "0" || Val == "false" || Val == "False" || Val == "FALSE")
659 return false;
660 if (Val != "-1")
661 elog("Value specified by --function-arg-placeholders is invalid. Provide a "
662 "boolean value or leave unspecified to use ArgumentListsPolicy from "
663 "config instead.");
664 return std::nullopt;
665 }
666
667 class FlagsConfigProvider : public config::Provider {
668 private:
669 config::CompiledFragment Frag;
670
671 std::vector<config::CompiledFragment>
672 getFragments(const config::Params &,
673 config::DiagnosticCallback) const override {
674 return {Frag};
675 }
676
677 public:
678 FlagsConfigProvider() {
679 std::optional<Config::CDBSearchSpec> CDBSearch;
680 std::optional<Config::ExternalIndexSpec> IndexSpec;
681 std::optional<Config::BackgroundPolicy> BGPolicy;
682 std::optional<Config::ArgumentListsPolicy> ArgumentLists;
683
684 // If --compile-commands-dir arg was invoked, check value and override
685 // default path.
686 if (!CompileCommandsDir.empty()) {
687 if (llvm::sys::fs::exists(CompileCommandsDir)) {
688 // We support passing both relative and absolute paths to the
689 // --compile-commands-dir argument, but we assume the path is absolute
690 // in the rest of clangd so we make sure the path is absolute before
691 // continuing.
692 llvm::SmallString<128> Path(CompileCommandsDir);
693 if (std::error_code EC = llvm::sys::fs::make_absolute(Path)) {
694 elog("Error while converting the relative path specified by "
695 "--compile-commands-dir to an absolute path: {0}. The argument "
696 "will be ignored.",
697 EC.message());
698 } else {
699 CDBSearch = {Config::CDBSearchSpec::FixedDir, Path.str().str()};
700 }
701 } else {
702 elog("Path specified by --compile-commands-dir does not exist. The "
703 "argument will be ignored.");
704 }
705 }
706 if (!IndexFile.empty()) {
707 Config::ExternalIndexSpec Spec;
708 Spec.Kind = Spec.File;
709 Spec.Location = IndexFile;
710 IndexSpec = std::move(Spec);
711 }
712 #if CLANGD_ENABLE_REMOTE
713 if (!RemoteIndexAddress.empty()) {
714 assert(!ProjectRoot.empty() && IndexFile.empty());
715 Config::ExternalIndexSpec Spec;
716 Spec.Kind = Spec.Server;
717 Spec.Location = RemoteIndexAddress;
718 Spec.MountPoint = ProjectRoot;
719 IndexSpec = std::move(Spec);
720 BGPolicy = Config::BackgroundPolicy::Skip;
721 }
722 #endif
723 if (!EnableBackgroundIndex) {
724 BGPolicy = Config::BackgroundPolicy::Skip;
725 }
726
727 if (std::optional<bool> Enable = shouldEnableFunctionArgSnippets()) {
728 ArgumentLists = *Enable ? Config::ArgumentListsPolicy::FullPlaceholders
729 : Config::ArgumentListsPolicy::Delimiters;
730 }
731
732 Frag = [=](const config::Params &, Config &C) {
733 if (CDBSearch)
734 C.CompileFlags.CDBSearch = *CDBSearch;
735 if (IndexSpec)
736 C.Index.External = *IndexSpec;
737 if (BGPolicy)
738 C.Index.Background = *BGPolicy;
739 if (ArgumentLists)
740 C.Completion.ArgumentLists = *ArgumentLists;
741 if (HeaderInsertion.getNumOccurrences())
742 C.Completion.HeaderInsertion = HeaderInsertion;
743 if (AllScopesCompletion.getNumOccurrences())
744 C.Completion.AllScopes = AllScopesCompletion;
745
746 if (Test)
747 C.Index.StandardLibrary = false;
748 return true;
749 };
750 }
751 };
752 } // namespace
753
754 enum class ErrorResultCode : int {
755 NoShutdownRequest = 1,
756 CantRunAsXPCService = 2,
757 CheckFailed = 3
758 };
759
760 int clangdMain(int argc, char *argv[]) {
761 // Clang could run on the main thread. e.g., when the flag '-check' or '-sync'
762 // is enabled.
763 clang::noteBottomOfStack();
764 llvm::InitLLVM X(argc, argv);
765 llvm::InitializeAllTargetInfos();
766 llvm::sys::AddSignalHandler(
767 [](void *) {
768 ThreadCrashReporter::runCrashHandlers();
769 // Ensure ThreadCrashReporter and PrintStackTrace output is visible.
770 llvm::errs().flush();
771 },
772 nullptr);
773 llvm::sys::SetInterruptFunction(&requestShutdown);
774 llvm::cl::SetVersionPrinter([](llvm::raw_ostream &OS) {
775 OS << versionString() << "\n"
776 << "Features: " << featureString() << "\n"
777 << "Platform: " << platformString() << "\n";
778 });
779 const char *FlagsEnvVar = "CLANGD_FLAGS";
780 const char *Overview =
781 R"(clangd is a language server that provides IDE-like features to editors.
782
783 It should be used via an editor plugin rather than invoked directly. For more information, see:
784 https://clangd.llvm.org/
785 https://microsoft.github.io/language-server-protocol/
786
787 clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment variable.
788 )";
789 llvm::cl::HideUnrelatedOptions(ClangdCategories);
790 llvm::cl::ParseCommandLineOptions(argc, argv, Overview, /*Errs=*/nullptr,
791 /*VFS=*/nullptr, FlagsEnvVar);
792 if (Test) {
793 if (!Sync.getNumOccurrences())
794 Sync = true;
795 if (!CrashPragmas.getNumOccurrences())
796 CrashPragmas = true;
797 InputStyle = JSONStreamStyle::Delimited;
798 LogLevel = Logger::Verbose;
799 PrettyPrint = true;
800 // Disable config system by default to avoid external reads.
801 if (!EnableConfig.getNumOccurrences())
802 EnableConfig = false;
803 // Disable background index on lit tests by default to prevent disk writes.
804 if (!EnableBackgroundIndex.getNumOccurrences())
805 EnableBackgroundIndex = false;
806 // Ensure background index makes progress.
807 else if (EnableBackgroundIndex)
808 BackgroundQueue::preventThreadStarvationInTests();
809 }
810 if (Test || EnableTestScheme) {
811 static URISchemeRegistry::Add<TestScheme> X(
812 "test", "Test scheme for clangd lit tests.");
813 }
814 if (CrashPragmas)
815 allowCrashPragmasForTest();
816
817 if (!Sync && WorkerThreadsCount == 0) {
818 llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
819 "specify -sync?";
820 return 1;
821 }
822
823 if (Sync) {
824 if (WorkerThreadsCount.getNumOccurrences())
825 llvm::errs() << "Ignoring -j because -sync is set.\n";
826 WorkerThreadsCount = 0;
827 }
828 if (FallbackStyle.getNumOccurrences())
829 clang::format::DefaultFallbackStyle = FallbackStyle.c_str();
830
831 // Validate command line arguments.
832 std::optional<llvm::raw_fd_ostream> InputMirrorStream;
833 if (!InputMirrorFile.empty()) {
834 std::error_code EC;
835 InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC,
836 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
837 if (EC) {
838 InputMirrorStream.reset();
839 llvm::errs() << "Error while opening an input mirror file: "
840 << EC.message();
841 } else {
842 InputMirrorStream->SetUnbuffered();
843 }
844 }
845
846 #if !CLANGD_DECISION_FOREST
847 if (RankingModel == clangd::CodeCompleteOptions::DecisionForest) {
848 llvm::errs() << "Clangd was compiled without decision forest support.\n";
849 return 1;
850 }
851 #endif
852
853 // Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a
854 // trace flag in your editor's config is annoying, launching with
855 // `CLANGD_TRACE=trace.json vim` is easier.
856 std::optional<llvm::raw_fd_ostream> TracerStream;
857 std::unique_ptr<trace::EventTracer> Tracer;
858 const char *JSONTraceFile = getenv("CLANGD_TRACE");
859 const char *MetricsCSVFile = getenv("CLANGD_METRICS");
860 const char *TracerFile = JSONTraceFile ? JSONTraceFile : MetricsCSVFile;
861 if (TracerFile) {
862 std::error_code EC;
863 TracerStream.emplace(TracerFile, /*ref*/ EC,
864 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
865 if (EC) {
866 TracerStream.reset();
867 llvm::errs() << "Error while opening trace file " << TracerFile << ": "
868 << EC.message();
869 } else {
870 Tracer = (TracerFile == JSONTraceFile)
871 ? trace::createJSONTracer(*TracerStream, PrettyPrint)
872 : trace::createCSVMetricTracer(*TracerStream);
873 }
874 }
875
876 std::optional<trace::Session> TracingSession;
877 if (Tracer)
878 TracingSession.emplace(*Tracer);
879
880 // If a user ran `clangd` in a terminal without redirecting anything,
881 // it's somewhat likely they're confused about how to use clangd.
882 // Show them the help overview, which explains.
883 if (llvm::outs().is_displayed() && llvm::errs().is_displayed() &&
884 !CheckFile.getNumOccurrences())
885 llvm::errs() << Overview << "\n";
886 // Use buffered stream to stderr (we still flush each log message). Unbuffered
887 // stream can cause significant (non-deterministic) latency for the logger.
888 llvm::errs().SetBuffered();
889 StreamLogger Logger(llvm::errs(), LogLevel);
890 LoggingSession LoggingSession(Logger);
891 // Write some initial logs before we start doing any real work.
892 log("{0}", versionString());
893 log("Features: {0}", featureString());
894 log("PID: {0}", llvm::sys::Process::getProcessId());
895 {
896 SmallString<128> CWD;
897 if (auto Err = llvm::sys::fs::current_path(CWD))
898 log("Working directory unknown: {0}", Err.message());
899 else
900 log("Working directory: {0}", CWD);
901 }
902 for (int I = 0; I < argc; ++I)
903 log("argv[{0}]: {1}", I, argv[I]);
904 if (auto EnvFlags = llvm::sys::Process::GetEnv(FlagsEnvVar))
905 log("{0}: {1}", FlagsEnvVar, *EnvFlags);
906
907 ClangdLSPServer::Options Opts;
908 Opts.UseDirBasedCDB = (CompileArgsFrom == FilesystemCompileArgs);
909 Opts.EnableExperimentalModulesSupport = ExperimentalModulesSupport;
910
911 switch (PCHStorage) {
912 case PCHStorageFlag::Memory:
913 Opts.StorePreamblesInMemory = true;
914 break;
915 case PCHStorageFlag::Disk:
916 Opts.StorePreamblesInMemory = false;
917 break;
918 }
919 if (!ResourceDir.empty())
920 Opts.ResourceDir = ResourceDir;
921 Opts.StrongWorkspaceMode = StrongWorkspaceMode;
922 Opts.BuildDynamicSymbolIndex = true;
923 #if CLANGD_ENABLE_REMOTE
924 if (RemoteIndexAddress.empty() != ProjectRoot.empty()) {
925 llvm::errs() << "remote-index-address and project-path have to be "
926 "specified at the same time.";
927 return 1;
928 }
929 if (!RemoteIndexAddress.empty()) {
930 if (IndexFile.empty()) {
931 log("Connecting to remote index at {0}", RemoteIndexAddress);
932 } else {
933 elog("When enabling remote index, IndexFile should not be specified. "
934 "Only one can be used at time. Remote index will ignored.");
935 }
936 }
937 #endif
938 Opts.BackgroundIndex = EnableBackgroundIndex;
939 Opts.BackgroundIndexPriority = BackgroundIndexPriority;
940 Opts.ReferencesLimit = ReferencesLimit;
941 Opts.Rename.LimitFiles = RenameFileLimit;
942 auto PAI = createProjectAwareIndex(
943 [SupportContainedRefs = Opts.EnableOutgoingCalls](
944 const Config::ExternalIndexSpec &External, AsyncTaskRunner *Tasks) {
945 return loadExternalIndex(External, Tasks, SupportContainedRefs);
946 },
947 Sync);
948 Opts.StaticIndex = PAI.get();
949 Opts.AsyncThreadsCount = WorkerThreadsCount;
950 Opts.MemoryCleanup = getMemoryCleanupFunction();
951
952 Opts.CodeComplete.IncludeIneligibleResults = IncludeIneligibleResults;
953 Opts.CodeComplete.Limit = LimitResults;
954 if (CompletionStyle.getNumOccurrences())
955 Opts.CodeComplete.BundleOverloads = CompletionStyle != Detailed;
956 Opts.CodeComplete.ShowOrigins = ShowOrigins;
957 Opts.CodeComplete.InsertIncludes = HeaderInsertion;
958 Opts.CodeComplete.ImportInsertions = ImportInsertions;
959 if (!HeaderInsertionDecorators) {
960 Opts.CodeComplete.IncludeIndicator.Insert.clear();
961 Opts.CodeComplete.IncludeIndicator.NoInsert.clear();
962 }
963 Opts.CodeComplete.RunParser = CodeCompletionParse;
964 Opts.CodeComplete.RankingModel = RankingModel;
965 // FIXME: If we're using C++20 modules, force the lookup process to load
966 // external decls, since currently the index doesn't support C++20 modules.
967 Opts.CodeComplete.ForceLoadPreamble = ExperimentalModulesSupport;
968
969 RealThreadsafeFS TFS;
970 std::vector<std::unique_ptr<config::Provider>> ProviderStack;
971 std::unique_ptr<config::Provider> Config;
972 if (EnableConfig) {
973 ProviderStack.push_back(
974 config::Provider::fromAncestorRelativeYAMLFiles(".clangd", TFS));
975 llvm::SmallString<256> UserConfig;
976 if (llvm::sys::path::user_config_directory(UserConfig)) {
977 llvm::sys::path::append(UserConfig, "clangd", "config.yaml");
978 vlog("User config file is {0}", UserConfig);
979 ProviderStack.push_back(config::Provider::fromYAMLFile(
980 UserConfig, /*Directory=*/"", TFS, /*Trusted=*/true));
981 } else {
982 elog("Couldn't determine user config file, not loading");
983 }
984 }
985 ProviderStack.push_back(std::make_unique<FlagsConfigProvider>());
986 std::vector<const config::Provider *> ProviderPointers;
987 for (const auto &P : ProviderStack)
988 ProviderPointers.push_back(P.get());
989 Config = config::Provider::combine(std::move(ProviderPointers));
990 Opts.ConfigProvider = Config.get();
991
992 // Create an empty clang-tidy option.
993 TidyProvider ClangTidyOptProvider;
994 if (EnableClangTidy) {
995 std::vector<TidyProvider> Providers;
996 Providers.reserve(4 + EnableConfig);
997 Providers.push_back(provideEnvironment());
998 Providers.push_back(provideClangTidyFiles(TFS));
999 if (EnableConfig)
1000 Providers.push_back(provideClangdConfig());
1001 Providers.push_back(provideDefaultChecks());
1002 Providers.push_back(disableUnusableChecks());
1003 ClangTidyOptProvider = combine(std::move(Providers));
1004 Opts.ClangTidyProvider = ClangTidyOptProvider;
1005 }
1006 Opts.UseDirtyHeaders = UseDirtyHeaders;
1007 Opts.PreambleParseForwardingFunctions = PreambleParseForwardingFunctions;
1008 Opts.ImportInsertions = ImportInsertions;
1009 Opts.QueryDriverGlobs = std::move(QueryDriverGlobs);
1010 Opts.TweakFilter = [&](const Tweak &T) {
1011 if (T.hidden() && !HiddenFeatures)
1012 return false;
1013 if (TweakList.getNumOccurrences())
1014 return llvm::is_contained(TweakList, T.id());
1015 return true;
1016 };
1017 if (ForceOffsetEncoding != OffsetEncoding::UnsupportedEncoding)
1018 Opts.Encoding = ForceOffsetEncoding;
1019
1020 if (CheckFile.getNumOccurrences()) {
1021 llvm::SmallString<256> Path;
1022 if (auto Error =
1023 llvm::sys::fs::real_path(CheckFile, Path, /*expand_tilde=*/true)) {
1024 elog("Failed to resolve path {0}: {1}", CheckFile, Error.message());
1025 return 1;
1026 }
1027 log("Entering check mode (no LSP server)");
1028 return check(Path, TFS, Opts)
1029 ? 0
1030 : static_cast<int>(ErrorResultCode::CheckFailed);
1031 }
1032
1033 FeatureModuleSet ModuleSet = FeatureModuleSet::fromRegistry();
1034 if (ModuleSet.begin() != ModuleSet.end())
1035 Opts.FeatureModules = &ModuleSet;
1036
1037 // Initialize and run ClangdLSPServer.
1038 // Change stdin to binary to not lose \r\n on windows.
1039 llvm::sys::ChangeStdinToBinary();
1040 std::unique_ptr<Transport> TransportLayer;
1041 if (getenv("CLANGD_AS_XPC_SERVICE")) {
1042 #if CLANGD_BUILD_XPC
1043 log("Starting LSP over XPC service");
1044 TransportLayer = newXPCTransport();
1045 #else
1046 llvm::errs() << "This clangd binary wasn't built with XPC support.\n";
1047 return static_cast<int>(ErrorResultCode::CantRunAsXPCService);
1048 #endif
1049 } else {
1050 log("Starting LSP over stdin/stdout");
1051 TransportLayer = newJSONTransport(
1052 stdin, llvm::outs(), InputMirrorStream ? &*InputMirrorStream : nullptr,
1053 PrettyPrint, InputStyle);
1054 }
1055 if (!PathMappingsArg.empty()) {
1056 auto Mappings = parsePathMappings(PathMappingsArg);
1057 if (!Mappings) {
1058 elog("Invalid -path-mappings: {0}", Mappings.takeError());
1059 return 1;
1060 }
1061 TransportLayer = createPathMappingTransport(std::move(TransportLayer),
1062 std::move(*Mappings));
1063 }
1064
1065 ClangdLSPServer LSPServer(*TransportLayer, TFS, Opts);
1066 llvm::set_thread_name("clangd.main");
1067 int ExitCode = LSPServer.run()
1068 ? 0
1069 : static_cast<int>(ErrorResultCode::NoShutdownRequest);
1070 log("LSP finished, exiting with status {0}", ExitCode);
1071
1072 // There may still be lingering background threads (e.g. slow requests
1073 // whose results will be dropped, background index shutting down).
1074 //
1075 // These should terminate quickly, and ~ClangdLSPServer blocks on them.
1076 // However if a bug causes them to run forever, we want to ensure the process
1077 // eventually exits. As clangd isn't directly user-facing, an editor can
1078 // "leak" clangd processes. Crashing in this case contains the damage.
1079 abortAfterTimeout(std::chrono::minutes(5));
1080
1081 return ExitCode;
1082 }
1083
1084 } // namespace clangd
1085 } // namespace clang