blob: 39f2185359ad1b7f37b8fb8fe3c4a2a2e7bfbf86 [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 McCall8567cb32017-11-02 09:21:51 +000013#include "Trace.h"
Haojian Wuba28e9a2018-01-10 14:44:34 +000014#include "index/SymbolYAML.h"
Kirill Bobyrev7a94c912018-08-21 10:32:27 +000015#include "index/dex/DexIndex.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
29using namespace clang;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000030using namespace clang::clangd;
31
Kirill Bobyrevdc41bef2018-08-21 10:40:19 +000032static llvm::cl::opt<bool>
33 UseDex("use-dex-index",
34 llvm::cl::desc("Use experimental Dex static index."),
35 llvm::cl::init(false), llvm::cl::Hidden);
36
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000037namespace {
Kirill Bobyrev7a94c912018-08-21 10:32:27 +000038
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000039enum class PCHStorageFlag { Disk, Memory };
Haojian Wuba28e9a2018-01-10 14:44:34 +000040
41// Build an in-memory static index for global symbols from a YAML-format file.
42// The size of global symbols should be relatively small, so that all symbols
43// can be managed in memory.
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +000044std::unique_ptr<SymbolIndex> buildStaticIndex(llvm::StringRef YamlSymbolFile) {
Haojian Wuba28e9a2018-01-10 14:44:34 +000045 auto Buffer = llvm::MemoryBuffer::getFile(YamlSymbolFile);
46 if (!Buffer) {
47 llvm::errs() << "Can't open " << YamlSymbolFile << "\n";
48 return nullptr;
49 }
Ilya Biryukov74f26552018-07-26 12:05:31 +000050 auto Slab = symbolsFromYAML(Buffer.get()->getBuffer());
Haojian Wuba28e9a2018-01-10 14:44:34 +000051 SymbolSlab::Builder SymsBuilder;
52 for (auto Sym : Slab)
53 SymsBuilder.insert(Sym);
54
Kirill Bobyrevdc41bef2018-08-21 10:40:19 +000055 return UseDex ? dex::DexIndex::build(std::move(SymsBuilder).build())
Kirill Bobyrev7a94c912018-08-21 10:32:27 +000056 : MemIndex::build(std::move(SymsBuilder).build());
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000057}
Kirill Bobyrev7a94c912018-08-21 10:32:27 +000058
Haojian Wuba28e9a2018-01-10 14:44:34 +000059} // namespace
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000060
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +000061static llvm::cl::opt<Path> CompileCommandsDir(
62 "compile-commands-dir",
63 llvm::cl::desc("Specify a path to look for compile_commands.json. If path "
64 "is invalid, clangd will look in the current directory and "
65 "parent paths of each source file."));
66
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000067static llvm::cl::opt<unsigned>
68 WorkerThreadsCount("j",
69 llvm::cl::desc("Number of async workers used by clangd"),
70 llvm::cl::init(getDefaultAsyncThreadsCount()));
71
Sam McCallc18c2802018-06-15 11:06:29 +000072// FIXME: also support "plain" style where signatures are always omitted.
73enum CompletionStyleFlag {
74 Detailed,
75 Bundled,
76};
77static llvm::cl::opt<CompletionStyleFlag> CompletionStyle(
78 "completion-style",
79 llvm::cl::desc("Granularity of code completion suggestions"),
80 llvm::cl::values(
81 clEnumValN(Detailed, "detailed",
82 "One completion item for each semantically distinct "
83 "completion, with full type information."),
84 clEnumValN(Bundled, "bundled",
85 "Similar completion items (e.g. function overloads) are "
86 "combined. Type information shown where possible.")),
87 llvm::cl::init(Detailed));
88
Sam McCalladccab62017-11-23 16:58:22 +000089// FIXME: Flags are the wrong mechanism for user preferences.
90// We should probably read a dotfile or similar.
91static llvm::cl::opt<bool> IncludeIneligibleResults(
92 "include-ineligible-results",
93 llvm::cl::desc(
94 "Include ineligible completion results (e.g. private members)"),
95 llvm::cl::init(clangd::CodeCompleteOptions().IncludeIneligibleResults),
96 llvm::cl::Hidden);
Ilya Biryukovb33c1572017-09-12 13:57:14 +000097
Sam McCall5ed599e2018-02-06 10:47:30 +000098static llvm::cl::opt<JSONStreamStyle> InputStyle(
99 "input-style", llvm::cl::desc("Input JSON stream encoding"),
100 llvm::cl::values(
101 clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
102 clEnumValN(JSONStreamStyle::Delimited, "delimited",
103 "messages delimited by --- lines, with # comment support")),
104 llvm::cl::init(JSONStreamStyle::Standard));
105
Sam McCalldd0566b2017-11-06 15:40:30 +0000106static llvm::cl::opt<bool>
107 PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
108 llvm::cl::init(false));
109
Sam McCallbed58852018-07-11 10:35:11 +0000110static llvm::cl::opt<Logger::Level> LogLevel(
111 "log", llvm::cl::desc("Verbosity of log messages written to stderr"),
112 llvm::cl::values(clEnumValN(Logger::Error, "error", "Error messages only"),
113 clEnumValN(Logger::Info, "info",
114 "High level execution tracing"),
115 clEnumValN(Logger::Debug, "verbose", "Low level details")),
116 llvm::cl::init(Logger::Info));
117
Sam McCall5ed599e2018-02-06 10:47:30 +0000118static llvm::cl::opt<bool> Test(
119 "lit-test",
120 llvm::cl::desc(
121 "Abbreviation for -input-style=delimited -pretty -run-synchronously. "
122 "Intended to simplify lit tests."),
123 llvm::cl::init(false), llvm::cl::Hidden);
124
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000125static llvm::cl::opt<PCHStorageFlag> PCHStorage(
126 "pch-storage",
127 llvm::cl::desc("Storing PCHs in memory increases memory usages, but may "
128 "improve performance"),
129 llvm::cl::values(
130 clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
131 clEnumValN(PCHStorageFlag::Memory, "memory", "store PCHs in memory")),
132 llvm::cl::init(PCHStorageFlag::Disk));
133
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000134static llvm::cl::opt<int> LimitResults(
135 "limit-results",
136 llvm::cl::desc("Limit the number of results returned by clangd. "
Haojian Wu48b48652018-01-25 09:20:09 +0000137 "0 means no limit."),
Sam McCallea283c72018-01-30 09:21:30 +0000138 llvm::cl::init(100));
Haojian Wu48b48652018-01-25 09:20:09 +0000139
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000140static llvm::cl::opt<bool> RunSynchronously(
141 "run-synchronously",
142 llvm::cl::desc("Parse on main thread. If set, -j is ignored"),
143 llvm::cl::init(false), llvm::cl::Hidden);
Benjamin Kramerf0af3e62017-03-01 16:16:29 +0000144
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000145static llvm::cl::opt<Path>
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000146 ResourceDir("resource-dir",
Ilya Biryukov4ca7d852017-08-02 08:53:48 +0000147 llvm::cl::desc("Directory for system clang headers"),
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000148 llvm::cl::init(""), llvm::cl::Hidden);
149
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000150static llvm::cl::opt<Path> InputMirrorFile(
151 "input-mirror-file",
152 llvm::cl::desc(
153 "Mirror all LSP input to the specified file. Useful for debugging."),
154 llvm::cl::init(""), llvm::cl::Hidden);
155
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000156static llvm::cl::opt<bool> EnableIndex(
157 "index",
158 llvm::cl::desc("Enable index-based features such as global code completion "
Kirill Bobyrev0ef813f2018-08-14 12:00:39 +0000159 "and searching for symbols. "
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000160 "Clang uses an index built from symbols in opened files"),
Sam McCallea283c72018-01-30 09:21:30 +0000161 llvm::cl::init(true));
Eric Liubfac8f72017-12-19 18:00:37 +0000162
Sam McCall2161ec72018-07-05 06:20:41 +0000163static llvm::cl::opt<bool>
164 ShowOrigins("debug-origin",
165 llvm::cl::desc("Show origins of completion items"),
166 llvm::cl::init(clangd::CodeCompleteOptions().ShowOrigins),
167 llvm::cl::Hidden);
168
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000169static llvm::cl::opt<bool> HeaderInsertionDecorators(
170 "header-insertion-decorators",
171 llvm::cl::desc("Prepend a circular dot or space before the completion "
Kirill Bobyrev0ef813f2018-08-14 12:00:39 +0000172 "label, depending on whether "
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000173 "an include line will be inserted or not."),
174 llvm::cl::init(true));
175
Haojian Wuba28e9a2018-01-10 14:44:34 +0000176static llvm::cl::opt<Path> YamlSymbolFile(
177 "yaml-symbol-file",
178 llvm::cl::desc(
179 "YAML-format global symbol file to build the static index. Clangd will "
180 "use the static index for global code completion.\n"
181 "WARNING: This option is experimental only, and will be removed "
182 "eventually. Don't rely on it."),
183 llvm::cl::init(""), llvm::cl::Hidden);
184
Alex Lorenzf8087862018-08-01 17:39:29 +0000185enum CompileArgsFrom { LSPCompileArgs, FilesystemCompileArgs };
186
187static llvm::cl::opt<CompileArgsFrom> CompileArgsFrom(
188 "compile_args_from", llvm::cl::desc("The source of compile commands"),
189 llvm::cl::values(clEnumValN(LSPCompileArgs, "lsp",
190 "All compile commands come from LSP and "
191 "'compile_commands.json' files are ignored"),
192 clEnumValN(FilesystemCompileArgs, "filesystem",
193 "All compile commands come from the "
194 "'compile_commands.json' files")),
195 llvm::cl::init(FilesystemCompileArgs), llvm::cl::Hidden);
196
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000197int main(int argc, char *argv[]) {
Sam McCall3ebf7602018-02-20 11:46:39 +0000198 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
Sam McCalle72d0972018-06-29 13:24:20 +0000199 llvm::cl::SetVersionPrinter([](llvm::raw_ostream &OS) {
200 OS << clang::getClangToolFullVersion("clangd") << "\n";
201 });
202 llvm::cl::ParseCommandLineOptions(
203 argc, argv,
204 "clangd is a language server that provides IDE-like features to editors. "
205 "\n\nIt should be used via an editor plugin rather than invoked directly."
206 "For more information, see:"
207 "\n\thttps://clang.llvm.org/extra/clangd.html"
208 "\n\thttps://microsoft.github.io/language-server-protocol/");
Sam McCall5ed599e2018-02-06 10:47:30 +0000209 if (Test) {
210 RunSynchronously = true;
211 InputStyle = JSONStreamStyle::Delimited;
212 PrettyPrint = true;
213 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000214
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000215 if (!RunSynchronously && WorkerThreadsCount == 0) {
216 llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
217 "specify -run-synchronously?";
218 return 1;
219 }
220
Kirill Bobyrevbcaf3802018-02-25 07:21:16 +0000221 if (RunSynchronously) {
222 if (WorkerThreadsCount.getNumOccurrences())
223 llvm::errs() << "Ignoring -j because -run-synchronously is set.\n";
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000224 WorkerThreadsCount = 0;
Kirill Bobyrevbcaf3802018-02-25 07:21:16 +0000225 }
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000226
Benjamin Kramer74a18952017-10-26 10:07:04 +0000227 // Validate command line arguments.
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000228 llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
229 if (!InputMirrorFile.empty()) {
230 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000231 InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC,
232 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000233 if (EC) {
234 InputMirrorStream.reset();
235 llvm::errs() << "Error while opening an input mirror file: "
236 << EC.message();
237 }
238 }
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000239
Sam McCalled2717a2018-02-14 03:20:07 +0000240 // Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a
241 // trace flag in your editor's config is annoying, launching with
242 // `CLANGD_TRACE=trace.json vim` is easier.
Sam McCall8567cb32017-11-02 09:21:51 +0000243 llvm::Optional<llvm::raw_fd_ostream> TraceStream;
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000244 std::unique_ptr<trace::EventTracer> Tracer;
Sam McCalled2717a2018-02-14 03:20:07 +0000245 if (auto *TraceFile = getenv("CLANGD_TRACE")) {
Sam McCall8567cb32017-11-02 09:21:51 +0000246 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000247 TraceStream.emplace(TraceFile, /*ref*/ EC,
248 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
Sam McCall8567cb32017-11-02 09:21:51 +0000249 if (EC) {
Sam McCalled2717a2018-02-14 03:20:07 +0000250 TraceStream.reset();
251 llvm::errs() << "Error while opening trace file " << TraceFile << ": "
252 << EC.message();
Sam McCall8567cb32017-11-02 09:21:51 +0000253 } else {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000254 Tracer = trace::createJSONTracer(*TraceStream, PrettyPrint);
Sam McCall8567cb32017-11-02 09:21:51 +0000255 }
256 }
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000257
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000258 llvm::Optional<trace::Session> TracingSession;
259 if (Tracer)
260 TracingSession.emplace(*Tracer);
261
Sam McCallbed58852018-07-11 10:35:11 +0000262 JSONOutput Out(llvm::outs(), llvm::errs(), LogLevel,
Sam McCalldd0566b2017-11-06 15:40:30 +0000263 InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
264 PrettyPrint);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000265
Ilya Biryukov940901e2017-12-13 12:51:22 +0000266 clangd::LoggingSession LoggingSession(Out);
267
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000268 // If --compile-commands-dir arg was invoked, check value and override default
269 // path.
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000270 llvm::Optional<Path> CompileCommandsDirPath;
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000271 if (CompileCommandsDir.empty()) {
272 CompileCommandsDirPath = llvm::None;
273 } else if (!llvm::sys::path::is_absolute(CompileCommandsDir) ||
274 !llvm::sys::fs::exists(CompileCommandsDir)) {
275 llvm::errs() << "Path specified by --compile-commands-dir either does not "
276 "exist or is not an absolute "
277 "path. The argument will be ignored.\n";
278 CompileCommandsDirPath = llvm::None;
279 } else {
280 CompileCommandsDirPath = CompileCommandsDir;
281 }
Benjamin Kramer6a3d74e2017-02-07 12:40:59 +0000282
Sam McCall7363a2f2018-03-05 17:28:54 +0000283 ClangdServer::Options Opts;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000284 switch (PCHStorage) {
285 case PCHStorageFlag::Memory:
Sam McCall7363a2f2018-03-05 17:28:54 +0000286 Opts.StorePreamblesInMemory = true;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000287 break;
288 case PCHStorageFlag::Disk:
Sam McCall7363a2f2018-03-05 17:28:54 +0000289 Opts.StorePreamblesInMemory = false;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000290 break;
291 }
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000292 if (!ResourceDir.empty())
Sam McCall7363a2f2018-03-05 17:28:54 +0000293 Opts.ResourceDir = ResourceDir;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000294 Opts.BuildDynamicSymbolIndex = EnableIndex;
Haojian Wuba28e9a2018-01-10 14:44:34 +0000295 std::unique_ptr<SymbolIndex> StaticIdx;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000296 if (EnableIndex && !YamlSymbolFile.empty()) {
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000297 StaticIdx = buildStaticIndex(YamlSymbolFile);
Sam McCall7363a2f2018-03-05 17:28:54 +0000298 Opts.StaticIndex = StaticIdx.get();
299 }
300 Opts.AsyncThreadsCount = WorkerThreadsCount;
301
Sam McCalladccab62017-11-23 16:58:22 +0000302 clangd::CodeCompleteOptions CCOpts;
Sam McCalladccab62017-11-23 16:58:22 +0000303 CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000304 CCOpts.Limit = LimitResults;
Sam McCallc18c2802018-06-15 11:06:29 +0000305 CCOpts.BundleOverloads = CompletionStyle != Detailed;
Sam McCall2161ec72018-07-05 06:20:41 +0000306 CCOpts.ShowOrigins = ShowOrigins;
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000307 if (!HeaderInsertionDecorators) {
308 CCOpts.IncludeIndicator.Insert.clear();
309 CCOpts.IncludeIndicator.NoInsert.clear();
310 }
Eric Liu25d74e92018-08-24 11:23:56 +0000311 CCOpts.SpeculativeIndexRequest = Opts.StaticIndex;
Sam McCall7363a2f2018-03-05 17:28:54 +0000312
Benjamin Kramer74a18952017-10-26 10:07:04 +0000313 // Initialize and run ClangdLSPServer.
Alex Lorenzf8087862018-08-01 17:39:29 +0000314 ClangdLSPServer LSPServer(
315 Out, CCOpts, CompileCommandsDirPath,
316 /*ShouldUseInMemoryCDB=*/CompileArgsFrom == LSPCompileArgs, Opts);
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000317 constexpr int NoShutdownRequestErrorCode = 1;
Sam McCall8567cb32017-11-02 09:21:51 +0000318 llvm::set_thread_name("clangd.main");
Sam McCall7363a2f2018-03-05 17:28:54 +0000319 // Change stdin to binary to not lose \r\n on windows.
320 llvm::sys::ChangeStdinToBinary();
Sam McCall27a07cf2018-06-05 09:34:46 +0000321 return LSPServer.run(stdin, InputStyle) ? 0 : NoShutdownRequestErrorCode;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000322}