blob: c5b3c98ae59a0133815323bb356b115cc2211f84 [file] [log] [blame]
Krasimir Georgiev95ef1712017-04-12 17:13:08 +00001//===--- ClangdMain.cpp - clangd server loop ------------------------------===//
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Jan Korousdca9c7c2019-01-16 00:24:22 +000010#include "Features.inc"
Ilya Biryukov38d79772017-05-16 09:38:59 +000011#include "ClangdLSPServer.h"
Ilya Biryukove6dbb582017-10-10 09:08:47 +000012#include "Path.h"
Sam McCall8567cb32017-11-02 09:21:51 +000013#include "Trace.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000014#include "Transport.h"
Sam McCall02d600d2018-09-25 18:06:43 +000015#include "index/Serialization.h"
Raoul Wols8f5e06f2018-07-29 19:12:42 +000016#include "clang/Basic/Version.h"
Benjamin Kramerf0af3e62017-03-01 16:16:29 +000017#include "llvm/Support/CommandLine.h"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000018#include "llvm/Support/FileSystem.h"
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +000019#include "llvm/Support/Path.h"
Benjamin Kramer6a3d74e2017-02-07 12:40:59 +000020#include "llvm/Support/Program.h"
Eric Liuc5105f92018-02-16 14:15:55 +000021#include "llvm/Support/Signals.h"
Ilya Biryukove6dbb582017-10-10 09:08:47 +000022#include "llvm/Support/raw_ostream.h"
Sam McCalled2717a2018-02-14 03:20:07 +000023#include <cstdlib>
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000024#include <iostream>
Ilya Biryukov38d79772017-05-16 09:38:59 +000025#include <memory>
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000026#include <string>
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000027#include <thread>
Ilya Biryukov38d79772017-05-16 09:38:59 +000028
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000029namespace clang {
30namespace clangd {
Sam McCall96f24892018-10-16 08:53:52 +000031// FIXME: remove this option when Dex is cheap enough.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000032static llvm::cl::opt<bool>
33 UseDex("use-dex-index",
34 llvm::cl::desc("Use experimental Dex dynamic index."),
35 llvm::cl::init(false), llvm::cl::Hidden);
Kirill Bobyrevdc41bef2018-08-21 10:40:19 +000036
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000037static llvm::cl::opt<Path> CompileCommandsDir(
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +000038 "compile-commands-dir",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000039 llvm::cl::desc("Specify a path to look for compile_commands.json. If path "
40 "is invalid, clangd will look in the current directory and "
41 "parent paths of each source file."));
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +000042
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000043static llvm::cl::opt<unsigned>
44 WorkerThreadsCount("j",
45 llvm::cl::desc("Number of async workers used by clangd"),
46 llvm::cl::init(getDefaultAsyncThreadsCount()));
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000047
Sam McCallc18c2802018-06-15 11:06:29 +000048// FIXME: also support "plain" style where signatures are always omitted.
Sam McCall47feb572018-09-05 10:39:58 +000049enum CompletionStyleFlag { Detailed, Bundled };
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000050static llvm::cl::opt<CompletionStyleFlag> CompletionStyle(
51 "completion-style",
52 llvm::cl::desc("Granularity of code completion suggestions"),
53 llvm::cl::values(
Sam McCallc18c2802018-06-15 11:06:29 +000054 clEnumValN(Detailed, "detailed",
55 "One completion item for each semantically distinct "
56 "completion, with full type information."),
57 clEnumValN(Bundled, "bundled",
58 "Similar completion items (e.g. function overloads) are "
59 "combined. Type information shown where possible.")),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000060 llvm::cl::init(Detailed));
Sam McCallc18c2802018-06-15 11:06:29 +000061
Sam McCalladccab62017-11-23 16:58:22 +000062// FIXME: Flags are the wrong mechanism for user preferences.
63// We should probably read a dotfile or similar.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000064static llvm::cl::opt<bool> IncludeIneligibleResults(
Sam McCalladccab62017-11-23 16:58:22 +000065 "include-ineligible-results",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000066 llvm::cl::desc(
67 "Include ineligible completion results (e.g. private members)"),
68 llvm::cl::init(CodeCompleteOptions().IncludeIneligibleResults),
69 llvm::cl::Hidden);
Ilya Biryukovb33c1572017-09-12 13:57:14 +000070
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000071static llvm::cl::opt<JSONStreamStyle> InputStyle(
72 "input-style", llvm::cl::desc("Input JSON stream encoding"),
73 llvm::cl::values(
Sam McCall5ed599e2018-02-06 10:47:30 +000074 clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
75 clEnumValN(JSONStreamStyle::Delimited, "delimited",
76 "messages delimited by --- lines, with # comment support")),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000077 llvm::cl::init(JSONStreamStyle::Standard));
Sam McCall5ed599e2018-02-06 10:47:30 +000078
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000079static llvm::cl::opt<bool>
80 PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
81 llvm::cl::init(false));
Sam McCalldd0566b2017-11-06 15:40:30 +000082
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000083static llvm::cl::opt<Logger::Level> LogLevel(
84 "log", llvm::cl::desc("Verbosity of log messages written to stderr"),
85 llvm::cl::values(clEnumValN(Logger::Error, "error", "Error messages only"),
86 clEnumValN(Logger::Info, "info",
87 "High level execution tracing"),
88 clEnumValN(Logger::Debug, "verbose", "Low level details")),
89 llvm::cl::init(Logger::Info));
Sam McCallbed58852018-07-11 10:35:11 +000090
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000091static llvm::cl::opt<bool>
Eric Liuc0ac4bb2018-11-22 15:02:05 +000092 Test("lit-test",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000093 llvm::cl::desc("Abbreviation for -input-style=delimited -pretty "
94 "-run-synchronously -enable-test-scheme. "
95 "Intended to simplify lit tests."),
96 llvm::cl::init(false), llvm::cl::Hidden);
Eric Liuc0ac4bb2018-11-22 15:02:05 +000097
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000098static llvm::cl::opt<bool> EnableTestScheme(
Eric Liuc0ac4bb2018-11-22 15:02:05 +000099 "enable-test-uri-scheme",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000100 llvm::cl::desc("Enable 'test:' URI scheme. Only use in lit tests."),
101 llvm::cl::init(false), llvm::cl::Hidden);
Sam McCall5ed599e2018-02-06 10:47:30 +0000102
Sam McCall47feb572018-09-05 10:39:58 +0000103enum PCHStorageFlag { Disk, Memory };
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000104static llvm::cl::opt<PCHStorageFlag> PCHStorage(
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000105 "pch-storage",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000106 llvm::cl::desc("Storing PCHs in memory increases memory usages, but may "
107 "improve performance"),
108 llvm::cl::values(
109 clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
110 clEnumValN(PCHStorageFlag::Memory, "memory", "store PCHs in memory")),
111 llvm::cl::init(PCHStorageFlag::Disk));
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000112
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000113static llvm::cl::opt<int> LimitResults(
114 "limit-results",
115 llvm::cl::desc("Limit the number of results returned by clangd. "
116 "0 means no limit."),
117 llvm::cl::init(100));
Haojian Wu48b48652018-01-25 09:20:09 +0000118
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000119static llvm::cl::opt<bool> RunSynchronously(
120 "run-synchronously",
121 llvm::cl::desc("Parse on main thread. If set, -j is ignored"),
122 llvm::cl::init(false), llvm::cl::Hidden);
Benjamin Kramerf0af3e62017-03-01 16:16:29 +0000123
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000124static llvm::cl::opt<Path>
125 ResourceDir("resource-dir",
126 llvm::cl::desc("Directory for system clang headers"),
127 llvm::cl::init(""), llvm::cl::Hidden);
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000128
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000129static llvm::cl::opt<Path> InputMirrorFile(
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000130 "input-mirror-file",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000131 llvm::cl::desc(
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000132 "Mirror all LSP input to the specified file. Useful for debugging."),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000133 llvm::cl::init(""), llvm::cl::Hidden);
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000134
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000135static llvm::cl::opt<bool> EnableIndex(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000136 "index",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000137 llvm::cl::desc(
Eric Liu76b88d82018-09-13 12:53:23 +0000138 "Enable index-based features. By default, clangd maintains an index "
139 "built from symbols in opened files. Global index support needs to "
140 "enabled separatedly."),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000141 llvm::cl::init(true), llvm::cl::Hidden);
Eric Liubfac8f72017-12-19 18:00:37 +0000142
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000143static llvm::cl::opt<bool> AllScopesCompletion(
Eric Liu670c1472018-09-27 18:46:00 +0000144 "all-scopes-completion",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000145 llvm::cl::desc(
Eric Liu670c1472018-09-27 18:46:00 +0000146 "If set to true, code completion will include index symbols that are "
147 "not defined in the scopes (e.g. "
148 "namespaces) visible from the code completion point. Such completions "
149 "can insert scope qualifiers."),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000150 llvm::cl::init(true));
Eric Liu670c1472018-09-27 18:46:00 +0000151
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000152static llvm::cl::opt<bool> ShowOrigins(
153 "debug-origin", llvm::cl::desc("Show origins of completion items"),
154 llvm::cl::init(CodeCompleteOptions().ShowOrigins), llvm::cl::Hidden);
Sam McCall2161ec72018-07-05 06:20:41 +0000155
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000156static llvm::cl::opt<bool> HeaderInsertionDecorators(
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000157 "header-insertion-decorators",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000158 llvm::cl::desc("Prepend a circular dot or space before the completion "
159 "label, depending on whether "
160 "an include line will be inserted or not."),
161 llvm::cl::init(true));
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000162
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000163static llvm::cl::opt<Path> IndexFile(
Haojian Wu162510f2018-10-08 10:44:54 +0000164 "index-file",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000165 llvm::cl::desc(
Haojian Wu162510f2018-10-08 10:44:54 +0000166 "Index file to build the static index. The file must have been created "
167 "by a compatible clangd-index.\n"
Haojian Wuba28e9a2018-01-10 14:44:34 +0000168 "WARNING: This option is experimental only, and will be removed "
169 "eventually. Don't rely on it."),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000170 llvm::cl::init(""), llvm::cl::Hidden);
Haojian Wuba28e9a2018-01-10 14:44:34 +0000171
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000172static llvm::cl::opt<bool> EnableBackgroundIndex(
Sam McCall422c8282018-11-26 16:00:11 +0000173 "background-index",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000174 llvm::cl::desc(
175 "Index project code in the background and persist index on disk. "
176 "Experimental"),
177 llvm::cl::init(false), llvm::cl::Hidden);
Sam McCall422c8282018-11-26 16:00:11 +0000178
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000179static llvm::cl::opt<int> BackgroundIndexRebuildPeriod(
Eric Liu667e8ef2018-12-18 15:39:33 +0000180 "background-index-rebuild-period",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000181 llvm::cl::desc(
Eric Liu667e8ef2018-12-18 15:39:33 +0000182 "If set to non-zero, the background index rebuilds the symbol index "
183 "periodically every X milliseconds; otherwise, the "
184 "symbol index will be updated for each indexed file."),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000185 llvm::cl::init(5000), llvm::cl::Hidden);
Eric Liu667e8ef2018-12-18 15:39:33 +0000186
Alex Lorenzf8087862018-08-01 17:39:29 +0000187enum CompileArgsFrom { LSPCompileArgs, FilesystemCompileArgs };
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000188static llvm::cl::opt<CompileArgsFrom> CompileArgsFrom(
189 "compile_args_from", llvm::cl::desc("The source of compile commands"),
190 llvm::cl::values(clEnumValN(LSPCompileArgs, "lsp",
191 "All compile commands come from LSP and "
192 "'compile_commands.json' files are ignored"),
193 clEnumValN(FilesystemCompileArgs, "filesystem",
194 "All compile commands come from the "
195 "'compile_commands.json' files")),
196 llvm::cl::init(FilesystemCompileArgs), llvm::cl::Hidden);
Alex Lorenzf8087862018-08-01 17:39:29 +0000197
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000198static llvm::cl::opt<bool> EnableFunctionArgSnippets(
Kadir Cetinkayae8d8aee2018-09-19 10:16:44 +0000199 "function-arg-placeholders",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000200 llvm::cl::desc("When disabled, completions contain only parentheses for "
201 "function calls. When enabled, completions also contain "
202 "placeholders for method parameters."),
203 llvm::cl::init(CodeCompleteOptions().EnableFunctionArgSnippets));
Kadir Cetinkayae8d8aee2018-09-19 10:16:44 +0000204
Eric Liuc0ac4bb2018-11-22 15:02:05 +0000205namespace {
206
207/// \brief Supports a test URI scheme with relaxed constraints for lit tests.
208/// The path in a test URI will be combined with a platform-specific fake
209/// directory to form an absolute path. For example, test:///a.cpp is resolved
210/// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
211class TestScheme : public URIScheme {
212public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000213 llvm::Expected<std::string>
214 getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
215 llvm::StringRef /*HintPath*/) const override {
Eric Liuc0ac4bb2018-11-22 15:02:05 +0000216 using namespace llvm::sys;
217 // Still require "/" in body to mimic file scheme, as we want lengths of an
218 // equivalent URI in both schemes to be the same.
219 if (!Body.startswith("/"))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000220 return llvm::make_error<llvm::StringError>(
Eric Liuc0ac4bb2018-11-22 15:02:05 +0000221 "Expect URI body to be an absolute path starting with '/': " + Body,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000222 llvm::inconvertibleErrorCode());
Eric Liuc0ac4bb2018-11-22 15:02:05 +0000223 Body = Body.ltrim('/');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000224 llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
Eric Liuc0ac4bb2018-11-22 15:02:05 +0000225 path::native(Path);
226 auto Err = fs::make_absolute(TestScheme::TestDir, Path);
227 if (Err)
228 llvm_unreachable("Failed to make absolute path in test scheme.");
229 return std::string(Path.begin(), Path.end());
230 }
231
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000232 llvm::Expected<URI>
233 uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
234 llvm::StringRef Body = AbsolutePath;
Eric Liuc0ac4bb2018-11-22 15:02:05 +0000235 if (!Body.consume_front(TestScheme::TestDir)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000236 return llvm::make_error<llvm::StringError>(
237 "Path " + AbsolutePath + " doesn't start with root " + TestDir,
238 llvm::inconvertibleErrorCode());
Eric Liuc0ac4bb2018-11-22 15:02:05 +0000239 }
240
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000241 return URI("test", /*Authority=*/"",
242 llvm::sys::path::convert_to_slash(Body));
Eric Liuc0ac4bb2018-11-22 15:02:05 +0000243 }
244
245private:
246 const static char TestDir[];
247};
248
249#ifdef _WIN32
250const char TestScheme::TestDir[] = "C:\\clangd-test";
251#else
252const char TestScheme::TestDir[] = "/clangd-test";
253#endif
254
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000255} // namespace
256} // namespace clangd
257} // namespace clang
Eric Liuc0ac4bb2018-11-22 15:02:05 +0000258
Jan Korousdca9c7c2019-01-16 00:24:22 +0000259enum class ErrorResultCode : int {
260 NoShutdownRequest = 1,
261 CantRunAsXPCService = 2
262};
263
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000264int main(int argc, char *argv[]) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000265 using namespace clang;
266 using namespace clang::clangd;
267
268 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
269 llvm::cl::SetVersionPrinter([](llvm::raw_ostream &OS) {
Sam McCalle72d0972018-06-29 13:24:20 +0000270 OS << clang::getClangToolFullVersion("clangd") << "\n";
271 });
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000272 llvm::cl::ParseCommandLineOptions(
Sam McCalle72d0972018-06-29 13:24:20 +0000273 argc, argv,
274 "clangd is a language server that provides IDE-like features to editors. "
Sam McCallc008af62018-10-20 15:30:37 +0000275 "\n\nIt should be used via an editor plugin rather than invoked "
276 "directly. "
Sam McCalle72d0972018-06-29 13:24:20 +0000277 "For more information, see:"
278 "\n\thttps://clang.llvm.org/extra/clangd.html"
279 "\n\thttps://microsoft.github.io/language-server-protocol/");
Sam McCall5ed599e2018-02-06 10:47:30 +0000280 if (Test) {
281 RunSynchronously = true;
282 InputStyle = JSONStreamStyle::Delimited;
283 PrettyPrint = true;
Sam McCall032f3e72018-11-27 12:09:13 +0000284 preventThreadStarvationInTests(); // Ensure background index makes progress.
Sam McCall5ed599e2018-02-06 10:47:30 +0000285 }
Eric Liuc0ac4bb2018-11-22 15:02:05 +0000286 if (Test || EnableTestScheme) {
287 static URISchemeRegistry::Add<TestScheme> X(
288 "test", "Test scheme for clangd lit tests.");
289 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000290
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000291 if (!RunSynchronously && WorkerThreadsCount == 0) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000292 llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
293 "specify -run-synchronously?";
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000294 return 1;
295 }
296
Kirill Bobyrevbcaf3802018-02-25 07:21:16 +0000297 if (RunSynchronously) {
298 if (WorkerThreadsCount.getNumOccurrences())
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000299 llvm::errs() << "Ignoring -j because -run-synchronously is set.\n";
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000300 WorkerThreadsCount = 0;
Kirill Bobyrevbcaf3802018-02-25 07:21:16 +0000301 }
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000302
Benjamin Kramer74a18952017-10-26 10:07:04 +0000303 // Validate command line arguments.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000304 llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000305 if (!InputMirrorFile.empty()) {
306 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000307 InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000308 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000309 if (EC) {
310 InputMirrorStream.reset();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000311 llvm::errs() << "Error while opening an input mirror file: "
312 << EC.message();
Sam McCall0d946182018-11-02 23:47:55 +0000313 } else {
314 InputMirrorStream->SetUnbuffered();
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000315 }
316 }
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000317
Sam McCalled2717a2018-02-14 03:20:07 +0000318 // Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a
319 // trace flag in your editor's config is annoying, launching with
320 // `CLANGD_TRACE=trace.json vim` is easier.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000321 llvm::Optional<llvm::raw_fd_ostream> TraceStream;
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000322 std::unique_ptr<trace::EventTracer> Tracer;
Sam McCalled2717a2018-02-14 03:20:07 +0000323 if (auto *TraceFile = getenv("CLANGD_TRACE")) {
Sam McCall8567cb32017-11-02 09:21:51 +0000324 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000325 TraceStream.emplace(TraceFile, /*ref*/ EC,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000326 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
Sam McCall8567cb32017-11-02 09:21:51 +0000327 if (EC) {
Sam McCalled2717a2018-02-14 03:20:07 +0000328 TraceStream.reset();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000329 llvm::errs() << "Error while opening trace file " << TraceFile << ": "
330 << EC.message();
Sam McCall8567cb32017-11-02 09:21:51 +0000331 } else {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000332 Tracer = trace::createJSONTracer(*TraceStream, PrettyPrint);
Sam McCall8567cb32017-11-02 09:21:51 +0000333 }
334 }
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000335
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000336 llvm::Optional<trace::Session> TracingSession;
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000337 if (Tracer)
338 TracingSession.emplace(*Tracer);
339
Eric Liu4e4e5a42018-08-28 13:15:50 +0000340 // Use buffered stream to stderr (we still flush each log message). Unbuffered
341 // stream can cause significant (non-deterministic) latency for the logger.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000342 llvm::errs().SetBuffered();
343 StreamLogger Logger(llvm::errs(), LogLevel);
344 LoggingSession LoggingSession(Logger);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000345
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000346 // If --compile-commands-dir arg was invoked, check value and override default
347 // path.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000348 llvm::Optional<Path> CompileCommandsDirPath;
Sam McCallf01ad102018-10-23 11:54:36 +0000349 if (!CompileCommandsDir.empty()) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000350 if (llvm::sys::fs::exists(CompileCommandsDir)) {
Sam McCallf01ad102018-10-23 11:54:36 +0000351 // We support passing both relative and absolute paths to the
352 // --compile-commands-dir argument, but we assume the path is absolute in
353 // the rest of clangd so we make sure the path is absolute before
354 // continuing.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000355 llvm::SmallString<128> Path(CompileCommandsDir);
356 if (std::error_code EC = llvm::sys::fs::make_absolute(Path)) {
357 llvm::errs() << "Error while converting the relative path specified by "
358 "--compile-commands-dir to an absolute path: "
359 << EC.message() << ". The argument will be ignored.\n";
Sam McCallf01ad102018-10-23 11:54:36 +0000360 } else {
361 CompileCommandsDirPath = Path.str();
362 }
363 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000364 llvm::errs()
365 << "Path specified by --compile-commands-dir does not exist. The "
366 "argument will be ignored.\n";
Sam McCallf01ad102018-10-23 11:54:36 +0000367 }
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000368 }
Benjamin Kramer6a3d74e2017-02-07 12:40:59 +0000369
Sam McCall7363a2f2018-03-05 17:28:54 +0000370 ClangdServer::Options Opts;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000371 switch (PCHStorage) {
372 case PCHStorageFlag::Memory:
Sam McCall7363a2f2018-03-05 17:28:54 +0000373 Opts.StorePreamblesInMemory = true;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000374 break;
375 case PCHStorageFlag::Disk:
Sam McCall7363a2f2018-03-05 17:28:54 +0000376 Opts.StorePreamblesInMemory = false;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000377 break;
378 }
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000379 if (!ResourceDir.empty())
Sam McCall7363a2f2018-03-05 17:28:54 +0000380 Opts.ResourceDir = ResourceDir;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000381 Opts.BuildDynamicSymbolIndex = EnableIndex;
Sam McCall96f24892018-10-16 08:53:52 +0000382 Opts.HeavyweightDynamicSymbolIndex = UseDex;
Sam McCall422c8282018-11-26 16:00:11 +0000383 Opts.BackgroundIndex = EnableBackgroundIndex;
Eric Liu667e8ef2018-12-18 15:39:33 +0000384 Opts.BackgroundIndexRebuildPeriodMs = BackgroundIndexRebuildPeriod;
Haojian Wuba28e9a2018-01-10 14:44:34 +0000385 std::unique_ptr<SymbolIndex> StaticIdx;
Sam McCallf469c642018-09-10 10:00:47 +0000386 std::future<void> AsyncIndexLoad; // Block exit while loading the index.
Haojian Wu162510f2018-10-08 10:44:54 +0000387 if (EnableIndex && !IndexFile.empty()) {
Sam McCall76c4c3a2018-09-04 16:19:40 +0000388 // Load the index asynchronously. Meanwhile SwapIndex returns no results.
389 SwapIndex *Placeholder;
390 StaticIdx.reset(Placeholder = new SwapIndex(llvm::make_unique<MemIndex>()));
Eric Liuc0ac4bb2018-11-22 15:02:05 +0000391 AsyncIndexLoad = runAsync<void>([Placeholder] {
392 if (auto Idx = loadIndex(IndexFile, /*UseDex=*/true))
Sam McCall76c4c3a2018-09-04 16:19:40 +0000393 Placeholder->reset(std::move(Idx));
394 });
Sam McCallf469c642018-09-10 10:00:47 +0000395 if (RunSynchronously)
396 AsyncIndexLoad.wait();
Sam McCall7363a2f2018-03-05 17:28:54 +0000397 }
Sam McCall76c4c3a2018-09-04 16:19:40 +0000398 Opts.StaticIndex = StaticIdx.get();
Sam McCall7363a2f2018-03-05 17:28:54 +0000399 Opts.AsyncThreadsCount = WorkerThreadsCount;
400
Sam McCalladccab62017-11-23 16:58:22 +0000401 clangd::CodeCompleteOptions CCOpts;
Sam McCalladccab62017-11-23 16:58:22 +0000402 CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000403 CCOpts.Limit = LimitResults;
Sam McCallc18c2802018-06-15 11:06:29 +0000404 CCOpts.BundleOverloads = CompletionStyle != Detailed;
Sam McCall2161ec72018-07-05 06:20:41 +0000405 CCOpts.ShowOrigins = ShowOrigins;
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000406 if (!HeaderInsertionDecorators) {
407 CCOpts.IncludeIndicator.Insert.clear();
408 CCOpts.IncludeIndicator.NoInsert.clear();
409 }
Eric Liu25d74e92018-08-24 11:23:56 +0000410 CCOpts.SpeculativeIndexRequest = Opts.StaticIndex;
Kadir Cetinkayae8d8aee2018-09-19 10:16:44 +0000411 CCOpts.EnableFunctionArgSnippets = EnableFunctionArgSnippets;
Eric Liu670c1472018-09-27 18:46:00 +0000412 CCOpts.AllScopes = AllScopesCompletion;
Sam McCall7363a2f2018-03-05 17:28:54 +0000413
Benjamin Kramer74a18952017-10-26 10:07:04 +0000414 // Initialize and run ClangdLSPServer.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000415 // Change stdin to binary to not lose \r\n on windows.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000416 llvm::sys::ChangeStdinToBinary();
Jan Korousdca9c7c2019-01-16 00:24:22 +0000417
418 std::unique_ptr<Transport> TransportLayer;
419 if (getenv("CLANGD_AS_XPC_SERVICE")) {
Fangrui Song54762df2019-01-16 08:13:15 +0000420#if CLANGD_BUILD_XPC
Jan Korousdca9c7c2019-01-16 00:24:22 +0000421 TransportLayer = newXPCTransport();
422#else
Fangrui Song54762df2019-01-16 08:13:15 +0000423 llvm::errs() << "This clangd binary wasn't built with XPC support.\n";
424 return (int)ErrorResultCode::CantRunAsXPCService;
Jan Korousdca9c7c2019-01-16 00:24:22 +0000425#endif
426 } else {
427 TransportLayer = newJSONTransport(
428 stdin, llvm::outs(),
429 InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
430 PrettyPrint, InputStyle);
431 }
432
Alex Lorenzf8087862018-08-01 17:39:29 +0000433 ClangdLSPServer LSPServer(
Jan Korousdca9c7c2019-01-16 00:24:22 +0000434 *TransportLayer, CCOpts, CompileCommandsDirPath,
Sam McCallc55d09a2018-11-02 13:09:36 +0000435 /*UseDirBasedCDB=*/CompileArgsFrom == FilesystemCompileArgs, Opts);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000436 llvm::set_thread_name("clangd.main");
Jan Korousdca9c7c2019-01-16 00:24:22 +0000437 return LSPServer.run() ? 0
438 : static_cast<int>(ErrorResultCode::NoShutdownRequest);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000439}