blob: 95ffdfad52ea93d439479e2dc9f9ed8ba6907bea [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"
Raoul Wols8f5e06f2018-07-29 19:12:42 +000015#include "clang/Basic/Version.h"
Benjamin Kramerf0af3e62017-03-01 16:16:29 +000016#include "llvm/Support/CommandLine.h"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000017#include "llvm/Support/FileSystem.h"
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +000018#include "llvm/Support/Path.h"
Benjamin Kramer6a3d74e2017-02-07 12:40:59 +000019#include "llvm/Support/Program.h"
Eric Liuc5105f92018-02-16 14:15:55 +000020#include "llvm/Support/Signals.h"
Ilya Biryukove6dbb582017-10-10 09:08:47 +000021#include "llvm/Support/raw_ostream.h"
Sam McCalled2717a2018-02-14 03:20:07 +000022#include <cstdlib>
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000023#include <iostream>
Ilya Biryukov38d79772017-05-16 09:38:59 +000024#include <memory>
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000025#include <string>
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000026#include <thread>
Ilya Biryukov38d79772017-05-16 09:38:59 +000027
28using namespace clang;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000029using namespace clang::clangd;
30
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000031namespace {
32enum class PCHStorageFlag { Disk, Memory };
Haojian Wuba28e9a2018-01-10 14:44:34 +000033
34// Build an in-memory static index for global symbols from a YAML-format file.
35// The size of global symbols should be relatively small, so that all symbols
36// can be managed in memory.
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +000037std::unique_ptr<SymbolIndex> buildStaticIndex(llvm::StringRef YamlSymbolFile) {
Haojian Wuba28e9a2018-01-10 14:44:34 +000038 auto Buffer = llvm::MemoryBuffer::getFile(YamlSymbolFile);
39 if (!Buffer) {
40 llvm::errs() << "Can't open " << YamlSymbolFile << "\n";
41 return nullptr;
42 }
Ilya Biryukov74f26552018-07-26 12:05:31 +000043 auto Slab = symbolsFromYAML(Buffer.get()->getBuffer());
Haojian Wuba28e9a2018-01-10 14:44:34 +000044 SymbolSlab::Builder SymsBuilder;
45 for (auto Sym : Slab)
46 SymsBuilder.insert(Sym);
47
48 return MemIndex::build(std::move(SymsBuilder).build());
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000049}
Haojian Wuba28e9a2018-01-10 14:44:34 +000050} // namespace
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000051
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +000052static llvm::cl::opt<Path> CompileCommandsDir(
53 "compile-commands-dir",
54 llvm::cl::desc("Specify a path to look for compile_commands.json. If path "
55 "is invalid, clangd will look in the current directory and "
56 "parent paths of each source file."));
57
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000058static llvm::cl::opt<unsigned>
59 WorkerThreadsCount("j",
60 llvm::cl::desc("Number of async workers used by clangd"),
61 llvm::cl::init(getDefaultAsyncThreadsCount()));
62
Sam McCallc18c2802018-06-15 11:06:29 +000063// FIXME: also support "plain" style where signatures are always omitted.
64enum CompletionStyleFlag {
65 Detailed,
66 Bundled,
67};
68static llvm::cl::opt<CompletionStyleFlag> CompletionStyle(
69 "completion-style",
70 llvm::cl::desc("Granularity of code completion suggestions"),
71 llvm::cl::values(
72 clEnumValN(Detailed, "detailed",
73 "One completion item for each semantically distinct "
74 "completion, with full type information."),
75 clEnumValN(Bundled, "bundled",
76 "Similar completion items (e.g. function overloads) are "
77 "combined. Type information shown where possible.")),
78 llvm::cl::init(Detailed));
79
Sam McCalladccab62017-11-23 16:58:22 +000080// FIXME: Flags are the wrong mechanism for user preferences.
81// We should probably read a dotfile or similar.
82static llvm::cl::opt<bool> IncludeIneligibleResults(
83 "include-ineligible-results",
84 llvm::cl::desc(
85 "Include ineligible completion results (e.g. private members)"),
86 llvm::cl::init(clangd::CodeCompleteOptions().IncludeIneligibleResults),
87 llvm::cl::Hidden);
Ilya Biryukovb33c1572017-09-12 13:57:14 +000088
Sam McCall5ed599e2018-02-06 10:47:30 +000089static llvm::cl::opt<JSONStreamStyle> InputStyle(
90 "input-style", llvm::cl::desc("Input JSON stream encoding"),
91 llvm::cl::values(
92 clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
93 clEnumValN(JSONStreamStyle::Delimited, "delimited",
94 "messages delimited by --- lines, with # comment support")),
95 llvm::cl::init(JSONStreamStyle::Standard));
96
Sam McCalldd0566b2017-11-06 15:40:30 +000097static llvm::cl::opt<bool>
98 PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
99 llvm::cl::init(false));
100
Sam McCallbed58852018-07-11 10:35:11 +0000101static llvm::cl::opt<Logger::Level> LogLevel(
102 "log", llvm::cl::desc("Verbosity of log messages written to stderr"),
103 llvm::cl::values(clEnumValN(Logger::Error, "error", "Error messages only"),
104 clEnumValN(Logger::Info, "info",
105 "High level execution tracing"),
106 clEnumValN(Logger::Debug, "verbose", "Low level details")),
107 llvm::cl::init(Logger::Info));
108
Sam McCall5ed599e2018-02-06 10:47:30 +0000109static llvm::cl::opt<bool> Test(
110 "lit-test",
111 llvm::cl::desc(
112 "Abbreviation for -input-style=delimited -pretty -run-synchronously. "
113 "Intended to simplify lit tests."),
114 llvm::cl::init(false), llvm::cl::Hidden);
115
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000116static llvm::cl::opt<PCHStorageFlag> PCHStorage(
117 "pch-storage",
118 llvm::cl::desc("Storing PCHs in memory increases memory usages, but may "
119 "improve performance"),
120 llvm::cl::values(
121 clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
122 clEnumValN(PCHStorageFlag::Memory, "memory", "store PCHs in memory")),
123 llvm::cl::init(PCHStorageFlag::Disk));
124
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000125static llvm::cl::opt<int> LimitResults(
126 "limit-results",
127 llvm::cl::desc("Limit the number of results returned by clangd. "
Haojian Wu48b48652018-01-25 09:20:09 +0000128 "0 means no limit."),
Sam McCallea283c72018-01-30 09:21:30 +0000129 llvm::cl::init(100));
Haojian Wu48b48652018-01-25 09:20:09 +0000130
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000131static llvm::cl::opt<bool> RunSynchronously(
132 "run-synchronously",
133 llvm::cl::desc("Parse on main thread. If set, -j is ignored"),
134 llvm::cl::init(false), llvm::cl::Hidden);
Benjamin Kramerf0af3e62017-03-01 16:16:29 +0000135
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000136static llvm::cl::opt<Path>
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000137 ResourceDir("resource-dir",
Ilya Biryukov4ca7d852017-08-02 08:53:48 +0000138 llvm::cl::desc("Directory for system clang headers"),
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000139 llvm::cl::init(""), llvm::cl::Hidden);
140
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000141static llvm::cl::opt<Path> InputMirrorFile(
142 "input-mirror-file",
143 llvm::cl::desc(
144 "Mirror all LSP input to the specified file. Useful for debugging."),
145 llvm::cl::init(""), llvm::cl::Hidden);
146
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000147static llvm::cl::opt<bool> EnableIndex(
148 "index",
149 llvm::cl::desc("Enable index-based features such as global code completion "
150 "and searching for symbols."
151 "Clang uses an index built from symbols in opened files"),
Sam McCallea283c72018-01-30 09:21:30 +0000152 llvm::cl::init(true));
Eric Liubfac8f72017-12-19 18:00:37 +0000153
Sam McCall2161ec72018-07-05 06:20:41 +0000154static llvm::cl::opt<bool>
155 ShowOrigins("debug-origin",
156 llvm::cl::desc("Show origins of completion items"),
157 llvm::cl::init(clangd::CodeCompleteOptions().ShowOrigins),
158 llvm::cl::Hidden);
159
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000160static llvm::cl::opt<bool> HeaderInsertionDecorators(
161 "header-insertion-decorators",
162 llvm::cl::desc("Prepend a circular dot or space before the completion "
163 "label, depending on wether "
164 "an include line will be inserted or not."),
165 llvm::cl::init(true));
166
Haojian Wuba28e9a2018-01-10 14:44:34 +0000167static llvm::cl::opt<Path> YamlSymbolFile(
168 "yaml-symbol-file",
169 llvm::cl::desc(
170 "YAML-format global symbol file to build the static index. Clangd will "
171 "use the static index for global code completion.\n"
172 "WARNING: This option is experimental only, and will be removed "
173 "eventually. Don't rely on it."),
174 llvm::cl::init(""), llvm::cl::Hidden);
175
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000176int main(int argc, char *argv[]) {
Sam McCall3ebf7602018-02-20 11:46:39 +0000177 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
Sam McCalle72d0972018-06-29 13:24:20 +0000178 llvm::cl::SetVersionPrinter([](llvm::raw_ostream &OS) {
179 OS << clang::getClangToolFullVersion("clangd") << "\n";
180 });
181 llvm::cl::ParseCommandLineOptions(
182 argc, argv,
183 "clangd is a language server that provides IDE-like features to editors. "
184 "\n\nIt should be used via an editor plugin rather than invoked directly."
185 "For more information, see:"
186 "\n\thttps://clang.llvm.org/extra/clangd.html"
187 "\n\thttps://microsoft.github.io/language-server-protocol/");
Sam McCall5ed599e2018-02-06 10:47:30 +0000188 if (Test) {
189 RunSynchronously = true;
190 InputStyle = JSONStreamStyle::Delimited;
191 PrettyPrint = true;
192 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000193
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000194 if (!RunSynchronously && WorkerThreadsCount == 0) {
195 llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
196 "specify -run-synchronously?";
197 return 1;
198 }
199
Kirill Bobyrevbcaf3802018-02-25 07:21:16 +0000200 if (RunSynchronously) {
201 if (WorkerThreadsCount.getNumOccurrences())
202 llvm::errs() << "Ignoring -j because -run-synchronously is set.\n";
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000203 WorkerThreadsCount = 0;
Kirill Bobyrevbcaf3802018-02-25 07:21:16 +0000204 }
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000205
Benjamin Kramer74a18952017-10-26 10:07:04 +0000206 // Validate command line arguments.
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000207 llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
208 if (!InputMirrorFile.empty()) {
209 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000210 InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC,
211 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000212 if (EC) {
213 InputMirrorStream.reset();
214 llvm::errs() << "Error while opening an input mirror file: "
215 << EC.message();
216 }
217 }
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000218
Sam McCalled2717a2018-02-14 03:20:07 +0000219 // Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a
220 // trace flag in your editor's config is annoying, launching with
221 // `CLANGD_TRACE=trace.json vim` is easier.
Sam McCall8567cb32017-11-02 09:21:51 +0000222 llvm::Optional<llvm::raw_fd_ostream> TraceStream;
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000223 std::unique_ptr<trace::EventTracer> Tracer;
Sam McCalled2717a2018-02-14 03:20:07 +0000224 if (auto *TraceFile = getenv("CLANGD_TRACE")) {
Sam McCall8567cb32017-11-02 09:21:51 +0000225 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000226 TraceStream.emplace(TraceFile, /*ref*/ EC,
227 llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
Sam McCall8567cb32017-11-02 09:21:51 +0000228 if (EC) {
Sam McCalled2717a2018-02-14 03:20:07 +0000229 TraceStream.reset();
230 llvm::errs() << "Error while opening trace file " << TraceFile << ": "
231 << EC.message();
Sam McCall8567cb32017-11-02 09:21:51 +0000232 } else {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000233 Tracer = trace::createJSONTracer(*TraceStream, PrettyPrint);
Sam McCall8567cb32017-11-02 09:21:51 +0000234 }
235 }
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000236
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000237 llvm::Optional<trace::Session> TracingSession;
238 if (Tracer)
239 TracingSession.emplace(*Tracer);
240
Sam McCallbed58852018-07-11 10:35:11 +0000241 JSONOutput Out(llvm::outs(), llvm::errs(), LogLevel,
Sam McCalldd0566b2017-11-06 15:40:30 +0000242 InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
243 PrettyPrint);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000244
Ilya Biryukov940901e2017-12-13 12:51:22 +0000245 clangd::LoggingSession LoggingSession(Out);
246
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000247 // If --compile-commands-dir arg was invoked, check value and override default
248 // path.
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000249 llvm::Optional<Path> CompileCommandsDirPath;
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000250 if (CompileCommandsDir.empty()) {
251 CompileCommandsDirPath = llvm::None;
252 } else if (!llvm::sys::path::is_absolute(CompileCommandsDir) ||
253 !llvm::sys::fs::exists(CompileCommandsDir)) {
254 llvm::errs() << "Path specified by --compile-commands-dir either does not "
255 "exist or is not an absolute "
256 "path. The argument will be ignored.\n";
257 CompileCommandsDirPath = llvm::None;
258 } else {
259 CompileCommandsDirPath = CompileCommandsDir;
260 }
Benjamin Kramer6a3d74e2017-02-07 12:40:59 +0000261
Sam McCall7363a2f2018-03-05 17:28:54 +0000262 ClangdServer::Options Opts;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000263 switch (PCHStorage) {
264 case PCHStorageFlag::Memory:
Sam McCall7363a2f2018-03-05 17:28:54 +0000265 Opts.StorePreamblesInMemory = true;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000266 break;
267 case PCHStorageFlag::Disk:
Sam McCall7363a2f2018-03-05 17:28:54 +0000268 Opts.StorePreamblesInMemory = false;
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000269 break;
270 }
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000271 if (!ResourceDir.empty())
Sam McCall7363a2f2018-03-05 17:28:54 +0000272 Opts.ResourceDir = ResourceDir;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000273 Opts.BuildDynamicSymbolIndex = EnableIndex;
Haojian Wuba28e9a2018-01-10 14:44:34 +0000274 std::unique_ptr<SymbolIndex> StaticIdx;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000275 if (EnableIndex && !YamlSymbolFile.empty()) {
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000276 StaticIdx = buildStaticIndex(YamlSymbolFile);
Sam McCall7363a2f2018-03-05 17:28:54 +0000277 Opts.StaticIndex = StaticIdx.get();
278 }
279 Opts.AsyncThreadsCount = WorkerThreadsCount;
280
Sam McCalladccab62017-11-23 16:58:22 +0000281 clangd::CodeCompleteOptions CCOpts;
Sam McCalladccab62017-11-23 16:58:22 +0000282 CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000283 CCOpts.Limit = LimitResults;
Sam McCallc18c2802018-06-15 11:06:29 +0000284 CCOpts.BundleOverloads = CompletionStyle != Detailed;
Sam McCall2161ec72018-07-05 06:20:41 +0000285 CCOpts.ShowOrigins = ShowOrigins;
Raoul Wols8f5e06f2018-07-29 19:12:42 +0000286 if (!HeaderInsertionDecorators) {
287 CCOpts.IncludeIndicator.Insert.clear();
288 CCOpts.IncludeIndicator.NoInsert.clear();
289 }
Sam McCall7363a2f2018-03-05 17:28:54 +0000290
Benjamin Kramer74a18952017-10-26 10:07:04 +0000291 // Initialize and run ClangdLSPServer.
Sam McCall7363a2f2018-03-05 17:28:54 +0000292 ClangdLSPServer LSPServer(Out, CCOpts, CompileCommandsDirPath, Opts);
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000293 constexpr int NoShutdownRequestErrorCode = 1;
Sam McCall8567cb32017-11-02 09:21:51 +0000294 llvm::set_thread_name("clangd.main");
Sam McCall7363a2f2018-03-05 17:28:54 +0000295 // Change stdin to binary to not lose \r\n on windows.
296 llvm::sys::ChangeStdinToBinary();
Sam McCall27a07cf2018-06-05 09:34:46 +0000297 return LSPServer.run(stdin, InputStyle) ? 0 : NoShutdownRequestErrorCode;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000298}