blob: c7f4998332fce064f0c6ab5a530663993e66c683 [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
Ilya Biryukov38d79772017-05-16 09:38:59 +000010#include "ClangdLSPServer.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000011#include "JSONRPCDispatcher.h"
Ilya Biryukove6dbb582017-10-10 09:08:47 +000012#include "Path.h"
Sam McCall50f36312018-09-04 16:16:50 +000013#include "RIFF.h"
Sam McCall8567cb32017-11-02 09:21:51 +000014#include "Trace.h"
Haojian Wuba28e9a2018-01-10 14:44:34 +000015#include "index/SymbolYAML.h"
Kirill Bobyrev7a94c912018-08-21 10:32:27 +000016#include "index/dex/DexIndex.h"
Raoul Wols8f5e06f2018-07-29 19:12:42 +000017#include "clang/Basic/Version.h"
Benjamin Kramerf0af3e62017-03-01 16:16:29 +000018#include "llvm/Support/CommandLine.h"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000019#include "llvm/Support/FileSystem.h"
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +000020#include "llvm/Support/Path.h"
Benjamin Kramer6a3d74e2017-02-07 12:40:59 +000021#include "llvm/Support/Program.h"
Eric Liuc5105f92018-02-16 14:15:55 +000022#include "llvm/Support/Signals.h"
Ilya Biryukove6dbb582017-10-10 09:08:47 +000023#include "llvm/Support/raw_ostream.h"
Sam McCalled2717a2018-02-14 03:20:07 +000024#include <cstdlib>
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000025#include <iostream>
Ilya Biryukov38d79772017-05-16 09:38:59 +000026#include <memory>
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000027#include <string>
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000028#include <thread>
Ilya Biryukov38d79772017-05-16 09:38:59 +000029
30using namespace clang;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000031using namespace clang::clangd;
32
Kirill Bobyrev8212eae2018-08-28 14:55:05 +000033// FIXME: remove this option when Dex is stable enough.
Kirill Bobyrevdc41bef2018-08-21 10:40:19 +000034static llvm::cl::opt<bool>
35 UseDex("use-dex-index",
36 llvm::cl::desc("Use experimental Dex static index."),
Kirill Bobyrev8212eae2018-08-28 14:55:05 +000037 llvm::cl::init(true), llvm::cl::Hidden);
Kirill Bobyrevdc41bef2018-08-21 10:40:19 +000038
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000039namespace {
Kirill Bobyrev7a94c912018-08-21 10:32:27 +000040
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000041enum class PCHStorageFlag { Disk, Memory };
Haojian Wuba28e9a2018-01-10 14:44:34 +000042
Haojian Wuba28e9a2018-01-10 14:44:34 +000043} // namespace
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000044
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +000045static llvm::cl::opt<Path> CompileCommandsDir(
46 "compile-commands-dir",
47 llvm::cl::desc("Specify a path to look for compile_commands.json. If path "
48 "is invalid, clangd will look in the current directory and "
49 "parent paths of each source file."));
50
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000051static llvm::cl::opt<unsigned>
52 WorkerThreadsCount("j",
53 llvm::cl::desc("Number of async workers used by clangd"),
54 llvm::cl::init(getDefaultAsyncThreadsCount()));
55
Sam McCallc18c2802018-06-15 11:06:29 +000056// FIXME: also support "plain" style where signatures are always omitted.
57enum CompletionStyleFlag {
58 Detailed,
59 Bundled,
60};
61static llvm::cl::opt<CompletionStyleFlag> CompletionStyle(
62 "completion-style",
63 llvm::cl::desc("Granularity of code completion suggestions"),
64 llvm::cl::values(
65 clEnumValN(Detailed, "detailed",
66 "One completion item for each semantically distinct "
67 "completion, with full type information."),
68 clEnumValN(Bundled, "bundled",
69 "Similar completion items (e.g. function overloads) are "
70 "combined. Type information shown where possible.")),
71 llvm::cl::init(Detailed));
72
Sam McCalladccab62017-11-23 16:58:22 +000073// FIXME: Flags are the wrong mechanism for user preferences.
74// We should probably read a dotfile or similar.
75static llvm::cl::opt<bool> IncludeIneligibleResults(
76 "include-ineligible-results",
77 llvm::cl::desc(
78 "Include ineligible completion results (e.g. private members)"),
79 llvm::cl::init(clangd::CodeCompleteOptions().IncludeIneligibleResults),
80 llvm::cl::Hidden);
Ilya Biryukovb33c1572017-09-12 13:57:14 +000081
Sam McCall5ed599e2018-02-06 10:47:30 +000082static llvm::cl::opt<JSONStreamStyle> InputStyle(
83 "input-style", llvm::cl::desc("Input JSON stream encoding"),
84 llvm::cl::values(
85 clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
86 clEnumValN(JSONStreamStyle::Delimited, "delimited",
87 "messages delimited by --- lines, with # comment support")),
88 llvm::cl::init(JSONStreamStyle::Standard));
89
Sam McCalldd0566b2017-11-06 15:40:30 +000090static llvm::cl::opt<bool>
91 PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
92 llvm::cl::init(false));
93
Sam McCallbed58852018-07-11 10:35:11 +000094static llvm::cl::opt<Logger::Level> LogLevel(
95 "log", llvm::cl::desc("Verbosity of log messages written to stderr"),
96 llvm::cl::values(clEnumValN(Logger::Error, "error", "Error messages only"),
97 clEnumValN(Logger::Info, "info",
98 "High level execution tracing"),
99 clEnumValN(Logger::Debug, "verbose", "Low level details")),
100 llvm::cl::init(Logger::Info));
101
Sam McCall5ed599e2018-02-06 10:47:30 +0000102static llvm::cl::opt<bool> Test(
103 "lit-test",
104 llvm::cl::desc(
105 "Abbreviation for -input-style=delimited -pretty -run-synchronously. "
106 "Intended to simplify lit tests."),
107 llvm::cl::init(false), llvm::cl::Hidden);
108
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000109static llvm::cl::opt<PCHStorageFlag> PCHStorage(
110 "pch-storage",
111 llvm::cl::desc("Storing PCHs in memory increases memory usages, but may "
112 "improve performance"),
113 llvm::cl::values(
114 clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
115 clEnumValN(PCHStorageFlag::Memory, "memory", "store PCHs in memory")),
116 llvm::cl::init(PCHStorageFlag::Disk));
117
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000118static llvm::cl::opt<int> LimitResults(
119 "limit-results",
120 llvm::cl::desc("Limit the number of results returned by clangd. "
Haojian Wu48b48652018-01-25 09:20:09 +0000121 "0 means no limit."),
Sam McCallea283c72018-01-30 09:21:30 +0000122 llvm::cl::init(100));
Haojian Wu48b48652018-01-25 09:20:09 +0000123
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000124static llvm::cl::opt<bool> RunSynchronously(
125 "run-synchronously",
126 llvm::cl::desc("Parse on main thread. If set, -j is ignored"),
127 llvm::cl::init(false), llvm::cl::Hidden);
Benjamin Kramerf0af3e62017-03-01 16:16:29 +0000128
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000129static llvm::cl::opt<Path>
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000130 ResourceDir("resource-dir",
Ilya Biryukov4ca7d852017-08-02 08:53:48 +0000131 llvm::cl::desc("Directory for system clang headers"),
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000132 llvm::cl::init(""), llvm::cl::Hidden);
133
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000134static llvm::cl::opt<Path> InputMirrorFile(
135 "input-mirror-file",
136 llvm::cl::desc(
137 "Mirror all LSP input to the specified file. Useful for debugging."),
138 llvm::cl::init(""), llvm::cl::Hidden);
139
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000140static llvm::cl::opt<bool> EnableIndex(
141 "index",
142 llvm::cl::desc("Enable index-based features such as global code completion "
Kirill Bobyrev0ef813f2018-08-14 12:00:39 +0000143 "and searching for symbols. "
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000144 "Clang uses an index built from symbols in opened files"),
Sam McCallea283c72018-01-30 09:21:30 +0000145 llvm::cl::init(true));
Eric Liubfac8f72017-12-19 18:00:37 +0000146
Sam McCall2161ec72018-07-05 06:20:41 +0000147static llvm::cl::opt<bool>
148 ShowOrigins("debug-origin",
149 llvm::cl::desc("Show origins of completion items"),
150 llvm::cl::init(clangd::CodeCompleteOptions().ShowOrigins),
151 llvm::cl::Hidden);
152
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000153static llvm::cl::opt<bool> HeaderInsertionDecorators(
154 "header-insertion-decorators",
155 llvm::cl::desc("Prepend a circular dot or space before the completion "
Kirill Bobyrev0ef813f2018-08-14 12:00:39 +0000156 "label, depending on whether "
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000157 "an include line will be inserted or not."),
158 llvm::cl::init(true));
159
Haojian Wuba28e9a2018-01-10 14:44:34 +0000160static llvm::cl::opt<Path> YamlSymbolFile(
161 "yaml-symbol-file",
162 llvm::cl::desc(
163 "YAML-format global symbol file to build the static index. Clangd will "
164 "use the static index for global code completion.\n"
165 "WARNING: This option is experimental only, and will be removed "
166 "eventually. Don't rely on it."),
167 llvm::cl::init(""), llvm::cl::Hidden);
168
Alex Lorenzf8087862018-08-01 17:39:29 +0000169enum CompileArgsFrom { LSPCompileArgs, FilesystemCompileArgs };
170
171static llvm::cl::opt<CompileArgsFrom> CompileArgsFrom(
172 "compile_args_from", llvm::cl::desc("The source of compile commands"),
173 llvm::cl::values(clEnumValN(LSPCompileArgs, "lsp",
174 "All compile commands come from LSP and "
175 "'compile_commands.json' files are ignored"),
176 clEnumValN(FilesystemCompileArgs, "filesystem",
177 "All compile commands come from the "
178 "'compile_commands.json' files")),
179 llvm::cl::init(FilesystemCompileArgs), llvm::cl::Hidden);
180
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000181int main(int argc, char *argv[]) {
Sam McCall3ebf7602018-02-20 11:46:39 +0000182 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
Sam McCalle72d0972018-06-29 13:24:20 +0000183 llvm::cl::SetVersionPrinter([](llvm::raw_ostream &OS) {
184 OS << clang::getClangToolFullVersion("clangd") << "\n";
185 });
186 llvm::cl::ParseCommandLineOptions(
187 argc, argv,
188 "clangd is a language server that provides IDE-like features to editors. "
189 "\n\nIt should be used via an editor plugin rather than invoked directly."
190 "For more information, see:"
191 "\n\thttps://clang.llvm.org/extra/clangd.html"
192 "\n\thttps://microsoft.github.io/language-server-protocol/");
Sam McCall5ed599e2018-02-06 10:47:30 +0000193 if (Test) {
194 RunSynchronously = true;
195 InputStyle = JSONStreamStyle::Delimited;
196 PrettyPrint = true;
197 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000198
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000199 if (!RunSynchronously && WorkerThreadsCount == 0) {
200 llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
201 "specify -run-synchronously?";
202 return 1;
203 }
204
Kirill Bobyrevbcaf3802018-02-25 07:21:16 +0000205 if (RunSynchronously) {
206 if (WorkerThreadsCount.getNumOccurrences())
207 llvm::errs() << "Ignoring -j because -run-synchronously is set.\n";
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000208 WorkerThreadsCount = 0;
Kirill Bobyrevbcaf3802018-02-25 07:21:16 +0000209 }
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000210
Benjamin Kramer74a18952017-10-26 10:07:04 +0000211 // Validate command line arguments.
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000212 llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
213 if (!InputMirrorFile.empty()) {
214 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000215 InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC,
216 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000217 if (EC) {
218 InputMirrorStream.reset();
219 llvm::errs() << "Error while opening an input mirror file: "
220 << EC.message();
221 }
222 }
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000223
Sam McCalled2717a2018-02-14 03:20:07 +0000224 // Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a
225 // trace flag in your editor's config is annoying, launching with
226 // `CLANGD_TRACE=trace.json vim` is easier.
Sam McCall8567cb32017-11-02 09:21:51 +0000227 llvm::Optional<llvm::raw_fd_ostream> TraceStream;
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000228 std::unique_ptr<trace::EventTracer> Tracer;
Sam McCalled2717a2018-02-14 03:20:07 +0000229 if (auto *TraceFile = getenv("CLANGD_TRACE")) {
Sam McCall8567cb32017-11-02 09:21:51 +0000230 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000231 TraceStream.emplace(TraceFile, /*ref*/ EC,
232 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
Sam McCall8567cb32017-11-02 09:21:51 +0000233 if (EC) {
Sam McCalled2717a2018-02-14 03:20:07 +0000234 TraceStream.reset();
235 llvm::errs() << "Error while opening trace file " << TraceFile << ": "
236 << EC.message();
Sam McCall8567cb32017-11-02 09:21:51 +0000237 } else {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000238 Tracer = trace::createJSONTracer(*TraceStream, PrettyPrint);
Sam McCall8567cb32017-11-02 09:21:51 +0000239 }
240 }
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000241
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000242 llvm::Optional<trace::Session> TracingSession;
243 if (Tracer)
244 TracingSession.emplace(*Tracer);
245
Eric Liu4e4e5a42018-08-28 13:15:50 +0000246 // Use buffered stream to stderr (we still flush each log message). Unbuffered
247 // stream can cause significant (non-deterministic) latency for the logger.
248 llvm::errs().SetBuffered();
Sam McCallbed58852018-07-11 10:35:11 +0000249 JSONOutput Out(llvm::outs(), llvm::errs(), LogLevel,
Sam McCalldd0566b2017-11-06 15:40:30 +0000250 InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
251 PrettyPrint);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000252
Ilya Biryukov940901e2017-12-13 12:51:22 +0000253 clangd::LoggingSession LoggingSession(Out);
254
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000255 // If --compile-commands-dir arg was invoked, check value and override default
256 // path.
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000257 llvm::Optional<Path> CompileCommandsDirPath;
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000258 if (CompileCommandsDir.empty()) {
259 CompileCommandsDirPath = llvm::None;
260 } else if (!llvm::sys::path::is_absolute(CompileCommandsDir) ||
261 !llvm::sys::fs::exists(CompileCommandsDir)) {
262 llvm::errs() << "Path specified by --compile-commands-dir either does not "
263 "exist or is not an absolute "
264 "path. The argument will be ignored.\n";
265 CompileCommandsDirPath = llvm::None;
266 } else {
267 CompileCommandsDirPath = CompileCommandsDir;
268 }
Benjamin Kramer6a3d74e2017-02-07 12:40:59 +0000269
Sam McCall7363a2f2018-03-05 17:28:54 +0000270 ClangdServer::Options Opts;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000271 switch (PCHStorage) {
272 case PCHStorageFlag::Memory:
Sam McCall7363a2f2018-03-05 17:28:54 +0000273 Opts.StorePreamblesInMemory = true;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000274 break;
275 case PCHStorageFlag::Disk:
Sam McCall7363a2f2018-03-05 17:28:54 +0000276 Opts.StorePreamblesInMemory = false;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000277 break;
278 }
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000279 if (!ResourceDir.empty())
Sam McCall7363a2f2018-03-05 17:28:54 +0000280 Opts.ResourceDir = ResourceDir;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000281 Opts.BuildDynamicSymbolIndex = EnableIndex;
Haojian Wuba28e9a2018-01-10 14:44:34 +0000282 std::unique_ptr<SymbolIndex> StaticIdx;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000283 if (EnableIndex && !YamlSymbolFile.empty()) {
Sam McCall76c4c3a2018-09-04 16:19:40 +0000284 // Load the index asynchronously. Meanwhile SwapIndex returns no results.
285 SwapIndex *Placeholder;
286 StaticIdx.reset(Placeholder = new SwapIndex(llvm::make_unique<MemIndex>()));
287 runAsync<void>([Placeholder] {
288 if (auto Idx = loadIndex(YamlSymbolFile))
289 Placeholder->reset(std::move(Idx));
290 });
Sam McCall7363a2f2018-03-05 17:28:54 +0000291 }
Sam McCall76c4c3a2018-09-04 16:19:40 +0000292 Opts.StaticIndex = StaticIdx.get();
Sam McCall7363a2f2018-03-05 17:28:54 +0000293 Opts.AsyncThreadsCount = WorkerThreadsCount;
294
Sam McCalladccab62017-11-23 16:58:22 +0000295 clangd::CodeCompleteOptions CCOpts;
Sam McCalladccab62017-11-23 16:58:22 +0000296 CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000297 CCOpts.Limit = LimitResults;
Sam McCallc18c2802018-06-15 11:06:29 +0000298 CCOpts.BundleOverloads = CompletionStyle != Detailed;
Sam McCall2161ec72018-07-05 06:20:41 +0000299 CCOpts.ShowOrigins = ShowOrigins;
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000300 if (!HeaderInsertionDecorators) {
301 CCOpts.IncludeIndicator.Insert.clear();
302 CCOpts.IncludeIndicator.NoInsert.clear();
303 }
Eric Liu25d74e92018-08-24 11:23:56 +0000304 CCOpts.SpeculativeIndexRequest = Opts.StaticIndex;
Sam McCall7363a2f2018-03-05 17:28:54 +0000305
Benjamin Kramer74a18952017-10-26 10:07:04 +0000306 // Initialize and run ClangdLSPServer.
Alex Lorenzf8087862018-08-01 17:39:29 +0000307 ClangdLSPServer LSPServer(
308 Out, CCOpts, CompileCommandsDirPath,
309 /*ShouldUseInMemoryCDB=*/CompileArgsFrom == LSPCompileArgs, Opts);
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000310 constexpr int NoShutdownRequestErrorCode = 1;
Sam McCall8567cb32017-11-02 09:21:51 +0000311 llvm::set_thread_name("clangd.main");
Sam McCall7363a2f2018-03-05 17:28:54 +0000312 // Change stdin to binary to not lose \r\n on windows.
313 llvm::sys::ChangeStdinToBinary();
Sam McCall27a07cf2018-06-05 09:34:46 +0000314 return LSPServer.run(stdin, InputStyle) ? 0 : NoShutdownRequestErrorCode;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000315}