blob: b3b34def0977dff6efe07a11ee17e734680edebf [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"
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 Bobyrev8212eae2018-08-28 14:55:05 +000032// FIXME: remove this option when Dex is stable enough.
Kirill Bobyrevdc41bef2018-08-21 10:40:19 +000033static llvm::cl::opt<bool>
34 UseDex("use-dex-index",
35 llvm::cl::desc("Use experimental Dex static index."),
Kirill Bobyrev8212eae2018-08-28 14:55:05 +000036 llvm::cl::init(true), llvm::cl::Hidden);
Kirill Bobyrevdc41bef2018-08-21 10:40:19 +000037
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +000038static llvm::cl::opt<Path> CompileCommandsDir(
39 "compile-commands-dir",
40 llvm::cl::desc("Specify a path to look for compile_commands.json. If path "
41 "is invalid, clangd will look in the current directory and "
42 "parent paths of each source file."));
43
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000044static llvm::cl::opt<unsigned>
45 WorkerThreadsCount("j",
46 llvm::cl::desc("Number of async workers used by clangd"),
47 llvm::cl::init(getDefaultAsyncThreadsCount()));
48
Sam McCallc18c2802018-06-15 11:06:29 +000049// FIXME: also support "plain" style where signatures are always omitted.
Sam McCall47feb572018-09-05 10:39:58 +000050enum CompletionStyleFlag { Detailed, Bundled };
Sam McCallc18c2802018-06-15 11:06:29 +000051static llvm::cl::opt<CompletionStyleFlag> CompletionStyle(
52 "completion-style",
53 llvm::cl::desc("Granularity of code completion suggestions"),
54 llvm::cl::values(
55 clEnumValN(Detailed, "detailed",
56 "One completion item for each semantically distinct "
57 "completion, with full type information."),
58 clEnumValN(Bundled, "bundled",
59 "Similar completion items (e.g. function overloads) are "
60 "combined. Type information shown where possible.")),
61 llvm::cl::init(Detailed));
62
Sam McCalladccab62017-11-23 16:58:22 +000063// FIXME: Flags are the wrong mechanism for user preferences.
64// We should probably read a dotfile or similar.
65static llvm::cl::opt<bool> IncludeIneligibleResults(
66 "include-ineligible-results",
67 llvm::cl::desc(
68 "Include ineligible completion results (e.g. private members)"),
69 llvm::cl::init(clangd::CodeCompleteOptions().IncludeIneligibleResults),
70 llvm::cl::Hidden);
Ilya Biryukovb33c1572017-09-12 13:57:14 +000071
Sam McCall5ed599e2018-02-06 10:47:30 +000072static llvm::cl::opt<JSONStreamStyle> InputStyle(
73 "input-style", llvm::cl::desc("Input JSON stream encoding"),
74 llvm::cl::values(
75 clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
76 clEnumValN(JSONStreamStyle::Delimited, "delimited",
77 "messages delimited by --- lines, with # comment support")),
78 llvm::cl::init(JSONStreamStyle::Standard));
79
Sam McCalldd0566b2017-11-06 15:40:30 +000080static llvm::cl::opt<bool>
81 PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
82 llvm::cl::init(false));
83
Sam McCallbed58852018-07-11 10:35:11 +000084static llvm::cl::opt<Logger::Level> LogLevel(
85 "log", llvm::cl::desc("Verbosity of log messages written to stderr"),
86 llvm::cl::values(clEnumValN(Logger::Error, "error", "Error messages only"),
87 clEnumValN(Logger::Info, "info",
88 "High level execution tracing"),
89 clEnumValN(Logger::Debug, "verbose", "Low level details")),
90 llvm::cl::init(Logger::Info));
91
Sam McCall5ed599e2018-02-06 10:47:30 +000092static llvm::cl::opt<bool> Test(
93 "lit-test",
94 llvm::cl::desc(
95 "Abbreviation for -input-style=delimited -pretty -run-synchronously. "
96 "Intended to simplify lit tests."),
97 llvm::cl::init(false), llvm::cl::Hidden);
98
Sam McCall47feb572018-09-05 10:39:58 +000099enum PCHStorageFlag { Disk, Memory };
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000100static llvm::cl::opt<PCHStorageFlag> PCHStorage(
101 "pch-storage",
102 llvm::cl::desc("Storing PCHs in memory increases memory usages, but may "
103 "improve performance"),
104 llvm::cl::values(
105 clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
106 clEnumValN(PCHStorageFlag::Memory, "memory", "store PCHs in memory")),
107 llvm::cl::init(PCHStorageFlag::Disk));
108
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000109static llvm::cl::opt<int> LimitResults(
110 "limit-results",
111 llvm::cl::desc("Limit the number of results returned by clangd. "
Haojian Wu48b48652018-01-25 09:20:09 +0000112 "0 means no limit."),
Sam McCallea283c72018-01-30 09:21:30 +0000113 llvm::cl::init(100));
Haojian Wu48b48652018-01-25 09:20:09 +0000114
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000115static llvm::cl::opt<bool> RunSynchronously(
116 "run-synchronously",
117 llvm::cl::desc("Parse on main thread. If set, -j is ignored"),
118 llvm::cl::init(false), llvm::cl::Hidden);
Benjamin Kramerf0af3e62017-03-01 16:16:29 +0000119
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000120static llvm::cl::opt<Path>
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000121 ResourceDir("resource-dir",
Ilya Biryukov4ca7d852017-08-02 08:53:48 +0000122 llvm::cl::desc("Directory for system clang headers"),
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000123 llvm::cl::init(""), llvm::cl::Hidden);
124
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000125static llvm::cl::opt<Path> InputMirrorFile(
126 "input-mirror-file",
127 llvm::cl::desc(
128 "Mirror all LSP input to the specified file. Useful for debugging."),
129 llvm::cl::init(""), llvm::cl::Hidden);
130
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000131static llvm::cl::opt<bool> EnableIndex(
132 "index",
Eric Liu76b88d82018-09-13 12:53:23 +0000133 llvm::cl::desc(
134 "Enable index-based features. By default, clangd maintains an index "
135 "built from symbols in opened files. Global index support needs to "
136 "enabled separatedly."),
137 llvm::cl::init(true), llvm::cl::Hidden);
Eric Liubfac8f72017-12-19 18:00:37 +0000138
Sam McCall2161ec72018-07-05 06:20:41 +0000139static llvm::cl::opt<bool>
140 ShowOrigins("debug-origin",
141 llvm::cl::desc("Show origins of completion items"),
142 llvm::cl::init(clangd::CodeCompleteOptions().ShowOrigins),
143 llvm::cl::Hidden);
144
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000145static llvm::cl::opt<bool> HeaderInsertionDecorators(
146 "header-insertion-decorators",
147 llvm::cl::desc("Prepend a circular dot or space before the completion "
Kirill Bobyrev0ef813f2018-08-14 12:00:39 +0000148 "label, depending on whether "
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000149 "an include line will be inserted or not."),
150 llvm::cl::init(true));
151
Haojian Wuba28e9a2018-01-10 14:44:34 +0000152static llvm::cl::opt<Path> YamlSymbolFile(
153 "yaml-symbol-file",
154 llvm::cl::desc(
155 "YAML-format global symbol file to build the static index. Clangd will "
156 "use the static index for global code completion.\n"
157 "WARNING: This option is experimental only, and will be removed "
158 "eventually. Don't rely on it."),
159 llvm::cl::init(""), llvm::cl::Hidden);
160
Alex Lorenzf8087862018-08-01 17:39:29 +0000161enum CompileArgsFrom { LSPCompileArgs, FilesystemCompileArgs };
Alex Lorenzf8087862018-08-01 17:39:29 +0000162static llvm::cl::opt<CompileArgsFrom> CompileArgsFrom(
163 "compile_args_from", llvm::cl::desc("The source of compile commands"),
164 llvm::cl::values(clEnumValN(LSPCompileArgs, "lsp",
165 "All compile commands come from LSP and "
166 "'compile_commands.json' files are ignored"),
167 clEnumValN(FilesystemCompileArgs, "filesystem",
168 "All compile commands come from the "
169 "'compile_commands.json' files")),
170 llvm::cl::init(FilesystemCompileArgs), llvm::cl::Hidden);
171
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000172int main(int argc, char *argv[]) {
Sam McCall3ebf7602018-02-20 11:46:39 +0000173 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
Sam McCalle72d0972018-06-29 13:24:20 +0000174 llvm::cl::SetVersionPrinter([](llvm::raw_ostream &OS) {
175 OS << clang::getClangToolFullVersion("clangd") << "\n";
176 });
177 llvm::cl::ParseCommandLineOptions(
178 argc, argv,
179 "clangd is a language server that provides IDE-like features to editors. "
180 "\n\nIt should be used via an editor plugin rather than invoked directly."
181 "For more information, see:"
182 "\n\thttps://clang.llvm.org/extra/clangd.html"
183 "\n\thttps://microsoft.github.io/language-server-protocol/");
Sam McCall5ed599e2018-02-06 10:47:30 +0000184 if (Test) {
185 RunSynchronously = true;
186 InputStyle = JSONStreamStyle::Delimited;
187 PrettyPrint = true;
188 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000189
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000190 if (!RunSynchronously && WorkerThreadsCount == 0) {
191 llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
192 "specify -run-synchronously?";
193 return 1;
194 }
195
Kirill Bobyrevbcaf3802018-02-25 07:21:16 +0000196 if (RunSynchronously) {
197 if (WorkerThreadsCount.getNumOccurrences())
198 llvm::errs() << "Ignoring -j because -run-synchronously is set.\n";
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000199 WorkerThreadsCount = 0;
Kirill Bobyrevbcaf3802018-02-25 07:21:16 +0000200 }
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000201
Benjamin Kramer74a18952017-10-26 10:07:04 +0000202 // Validate command line arguments.
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000203 llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
204 if (!InputMirrorFile.empty()) {
205 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000206 InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC,
207 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000208 if (EC) {
209 InputMirrorStream.reset();
210 llvm::errs() << "Error while opening an input mirror file: "
211 << EC.message();
212 }
213 }
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000214
Sam McCalled2717a2018-02-14 03:20:07 +0000215 // Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a
216 // trace flag in your editor's config is annoying, launching with
217 // `CLANGD_TRACE=trace.json vim` is easier.
Sam McCall8567cb32017-11-02 09:21:51 +0000218 llvm::Optional<llvm::raw_fd_ostream> TraceStream;
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000219 std::unique_ptr<trace::EventTracer> Tracer;
Sam McCalled2717a2018-02-14 03:20:07 +0000220 if (auto *TraceFile = getenv("CLANGD_TRACE")) {
Sam McCall8567cb32017-11-02 09:21:51 +0000221 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000222 TraceStream.emplace(TraceFile, /*ref*/ EC,
223 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
Sam McCall8567cb32017-11-02 09:21:51 +0000224 if (EC) {
Sam McCalled2717a2018-02-14 03:20:07 +0000225 TraceStream.reset();
226 llvm::errs() << "Error while opening trace file " << TraceFile << ": "
227 << EC.message();
Sam McCall8567cb32017-11-02 09:21:51 +0000228 } else {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000229 Tracer = trace::createJSONTracer(*TraceStream, PrettyPrint);
Sam McCall8567cb32017-11-02 09:21:51 +0000230 }
231 }
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000232
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000233 llvm::Optional<trace::Session> TracingSession;
234 if (Tracer)
235 TracingSession.emplace(*Tracer);
236
Eric Liu4e4e5a42018-08-28 13:15:50 +0000237 // Use buffered stream to stderr (we still flush each log message). Unbuffered
238 // stream can cause significant (non-deterministic) latency for the logger.
239 llvm::errs().SetBuffered();
Sam McCallbed58852018-07-11 10:35:11 +0000240 JSONOutput Out(llvm::outs(), llvm::errs(), LogLevel,
Sam McCalldd0566b2017-11-06 15:40:30 +0000241 InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
242 PrettyPrint);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000243
Ilya Biryukov940901e2017-12-13 12:51:22 +0000244 clangd::LoggingSession LoggingSession(Out);
245
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000246 // If --compile-commands-dir arg was invoked, check value and override default
247 // path.
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000248 llvm::Optional<Path> CompileCommandsDirPath;
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000249 if (CompileCommandsDir.empty()) {
250 CompileCommandsDirPath = llvm::None;
251 } else if (!llvm::sys::path::is_absolute(CompileCommandsDir) ||
252 !llvm::sys::fs::exists(CompileCommandsDir)) {
253 llvm::errs() << "Path specified by --compile-commands-dir either does not "
254 "exist or is not an absolute "
255 "path. The argument will be ignored.\n";
256 CompileCommandsDirPath = llvm::None;
257 } else {
258 CompileCommandsDirPath = CompileCommandsDir;
259 }
Benjamin Kramer6a3d74e2017-02-07 12:40:59 +0000260
Sam McCall7363a2f2018-03-05 17:28:54 +0000261 ClangdServer::Options Opts;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000262 switch (PCHStorage) {
263 case PCHStorageFlag::Memory:
Sam McCall7363a2f2018-03-05 17:28:54 +0000264 Opts.StorePreamblesInMemory = true;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000265 break;
266 case PCHStorageFlag::Disk:
Sam McCall7363a2f2018-03-05 17:28:54 +0000267 Opts.StorePreamblesInMemory = false;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000268 break;
269 }
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000270 if (!ResourceDir.empty())
Sam McCall7363a2f2018-03-05 17:28:54 +0000271 Opts.ResourceDir = ResourceDir;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000272 Opts.BuildDynamicSymbolIndex = EnableIndex;
Haojian Wuba28e9a2018-01-10 14:44:34 +0000273 std::unique_ptr<SymbolIndex> StaticIdx;
Sam McCallf469c642018-09-10 10:00:47 +0000274 std::future<void> AsyncIndexLoad; // Block exit while loading the index.
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000275 if (EnableIndex && !YamlSymbolFile.empty()) {
Sam McCall76c4c3a2018-09-04 16:19:40 +0000276 // Load the index asynchronously. Meanwhile SwapIndex returns no results.
277 SwapIndex *Placeholder;
278 StaticIdx.reset(Placeholder = new SwapIndex(llvm::make_unique<MemIndex>()));
Sam McCallf469c642018-09-10 10:00:47 +0000279 AsyncIndexLoad = runAsync<void>([Placeholder, &Opts] {
Kirill Bobyrev19a94612018-09-06 12:54:43 +0000280 if (auto Idx = loadIndex(YamlSymbolFile, Opts.URISchemes, UseDex))
Sam McCall76c4c3a2018-09-04 16:19:40 +0000281 Placeholder->reset(std::move(Idx));
282 });
Sam McCallf469c642018-09-10 10:00:47 +0000283 if (RunSynchronously)
284 AsyncIndexLoad.wait();
Sam McCall7363a2f2018-03-05 17:28:54 +0000285 }
Sam McCall76c4c3a2018-09-04 16:19:40 +0000286 Opts.StaticIndex = StaticIdx.get();
Sam McCall7363a2f2018-03-05 17:28:54 +0000287 Opts.AsyncThreadsCount = WorkerThreadsCount;
288
Sam McCalladccab62017-11-23 16:58:22 +0000289 clangd::CodeCompleteOptions CCOpts;
Sam McCalladccab62017-11-23 16:58:22 +0000290 CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000291 CCOpts.Limit = LimitResults;
Sam McCallc18c2802018-06-15 11:06:29 +0000292 CCOpts.BundleOverloads = CompletionStyle != Detailed;
Sam McCall2161ec72018-07-05 06:20:41 +0000293 CCOpts.ShowOrigins = ShowOrigins;
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000294 if (!HeaderInsertionDecorators) {
295 CCOpts.IncludeIndicator.Insert.clear();
296 CCOpts.IncludeIndicator.NoInsert.clear();
297 }
Eric Liu25d74e92018-08-24 11:23:56 +0000298 CCOpts.SpeculativeIndexRequest = Opts.StaticIndex;
Sam McCall7363a2f2018-03-05 17:28:54 +0000299
Benjamin Kramer74a18952017-10-26 10:07:04 +0000300 // Initialize and run ClangdLSPServer.
Alex Lorenzf8087862018-08-01 17:39:29 +0000301 ClangdLSPServer LSPServer(
302 Out, CCOpts, CompileCommandsDirPath,
303 /*ShouldUseInMemoryCDB=*/CompileArgsFrom == LSPCompileArgs, Opts);
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000304 constexpr int NoShutdownRequestErrorCode = 1;
Sam McCall8567cb32017-11-02 09:21:51 +0000305 llvm::set_thread_name("clangd.main");
Sam McCall7363a2f2018-03-05 17:28:54 +0000306 // Change stdin to binary to not lose \r\n on windows.
307 llvm::sys::ChangeStdinToBinary();
Sam McCall27a07cf2018-06-05 09:34:46 +0000308 return LSPServer.run(stdin, InputStyle) ? 0 : NoShutdownRequestErrorCode;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000309}