blob: 310ddbcd7f21c4d5c9b8badefbd2280ba516afce [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"
Benjamin Kramerf0af3e62017-03-01 16:16:29 +000015#include "llvm/Support/CommandLine.h"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000016#include "llvm/Support/FileSystem.h"
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +000017#include "llvm/Support/Path.h"
Benjamin Kramer6a3d74e2017-02-07 12:40:59 +000018#include "llvm/Support/Program.h"
Ilya Biryukove6dbb582017-10-10 09:08:47 +000019#include "llvm/Support/raw_ostream.h"
Sam McCalled2717a2018-02-14 03:20:07 +000020#include <cstdlib>
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000021#include <iostream>
Ilya Biryukov38d79772017-05-16 09:38:59 +000022#include <memory>
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000023#include <string>
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000024#include <thread>
Ilya Biryukov38d79772017-05-16 09:38:59 +000025
26using namespace clang;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000027using namespace clang::clangd;
28
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000029namespace {
30enum class PCHStorageFlag { Disk, Memory };
Haojian Wuba28e9a2018-01-10 14:44:34 +000031
32// Build an in-memory static index for global symbols from a YAML-format file.
33// The size of global symbols should be relatively small, so that all symbols
34// can be managed in memory.
35std::unique_ptr<SymbolIndex> BuildStaticIndex(llvm::StringRef YamlSymbolFile) {
36 auto Buffer = llvm::MemoryBuffer::getFile(YamlSymbolFile);
37 if (!Buffer) {
38 llvm::errs() << "Can't open " << YamlSymbolFile << "\n";
39 return nullptr;
40 }
Sam McCall60039512018-02-09 14:42:01 +000041 auto Slab = SymbolsFromYAML(Buffer.get()->getBuffer());
Haojian Wuba28e9a2018-01-10 14:44:34 +000042 SymbolSlab::Builder SymsBuilder;
43 for (auto Sym : Slab)
44 SymsBuilder.insert(Sym);
45
46 return MemIndex::build(std::move(SymsBuilder).build());
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000047}
Haojian Wuba28e9a2018-01-10 14:44:34 +000048} // namespace
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000049
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +000050static llvm::cl::opt<Path> CompileCommandsDir(
51 "compile-commands-dir",
52 llvm::cl::desc("Specify a path to look for compile_commands.json. If path "
53 "is invalid, clangd will look in the current directory and "
54 "parent paths of each source file."));
55
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000056static llvm::cl::opt<unsigned>
57 WorkerThreadsCount("j",
58 llvm::cl::desc("Number of async workers used by clangd"),
59 llvm::cl::init(getDefaultAsyncThreadsCount()));
60
Ilya Biryukovb33c1572017-09-12 13:57:14 +000061static llvm::cl::opt<bool> EnableSnippets(
62 "enable-snippets",
63 llvm::cl::desc(
Sam McCalladccab62017-11-23 16:58:22 +000064 "Present snippet completions instead of plaintext completions. "
65 "This also enables code pattern results." /* FIXME: should it? */),
66 llvm::cl::init(clangd::CodeCompleteOptions().EnableSnippets));
67
68// FIXME: Flags are the wrong mechanism for user preferences.
69// We should probably read a dotfile or similar.
70static llvm::cl::opt<bool> IncludeIneligibleResults(
71 "include-ineligible-results",
72 llvm::cl::desc(
73 "Include ineligible completion results (e.g. private members)"),
74 llvm::cl::init(clangd::CodeCompleteOptions().IncludeIneligibleResults),
75 llvm::cl::Hidden);
Ilya Biryukovb33c1572017-09-12 13:57:14 +000076
Sam McCall5ed599e2018-02-06 10:47:30 +000077static llvm::cl::opt<JSONStreamStyle> InputStyle(
78 "input-style", llvm::cl::desc("Input JSON stream encoding"),
79 llvm::cl::values(
80 clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
81 clEnumValN(JSONStreamStyle::Delimited, "delimited",
82 "messages delimited by --- lines, with # comment support")),
83 llvm::cl::init(JSONStreamStyle::Standard));
84
Sam McCalldd0566b2017-11-06 15:40:30 +000085static llvm::cl::opt<bool>
86 PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
87 llvm::cl::init(false));
88
Sam McCall5ed599e2018-02-06 10:47:30 +000089static llvm::cl::opt<bool> Test(
90 "lit-test",
91 llvm::cl::desc(
92 "Abbreviation for -input-style=delimited -pretty -run-synchronously. "
93 "Intended to simplify lit tests."),
94 llvm::cl::init(false), llvm::cl::Hidden);
95
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000096static llvm::cl::opt<PCHStorageFlag> PCHStorage(
97 "pch-storage",
98 llvm::cl::desc("Storing PCHs in memory increases memory usages, but may "
99 "improve performance"),
100 llvm::cl::values(
101 clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
102 clEnumValN(PCHStorageFlag::Memory, "memory", "store PCHs in memory")),
103 llvm::cl::init(PCHStorageFlag::Disk));
104
Haojian Wu48b48652018-01-25 09:20:09 +0000105static llvm::cl::opt<int> LimitCompletionResult(
Sam McCallea283c72018-01-30 09:21:30 +0000106 "completion-limit",
Haojian Wu48b48652018-01-25 09:20:09 +0000107 llvm::cl::desc("Limit the number of completion results returned by clangd. "
108 "0 means no limit."),
Sam McCallea283c72018-01-30 09:21:30 +0000109 llvm::cl::init(100));
Haojian Wu48b48652018-01-25 09:20:09 +0000110
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000111static llvm::cl::opt<bool> RunSynchronously(
112 "run-synchronously",
113 llvm::cl::desc("Parse on main thread. If set, -j is ignored"),
114 llvm::cl::init(false), llvm::cl::Hidden);
Benjamin Kramerf0af3e62017-03-01 16:16:29 +0000115
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000116static llvm::cl::opt<Path>
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000117 ResourceDir("resource-dir",
Ilya Biryukov4ca7d852017-08-02 08:53:48 +0000118 llvm::cl::desc("Directory for system clang headers"),
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000119 llvm::cl::init(""), llvm::cl::Hidden);
120
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000121static llvm::cl::opt<Path> InputMirrorFile(
122 "input-mirror-file",
123 llvm::cl::desc(
124 "Mirror all LSP input to the specified file. Useful for debugging."),
125 llvm::cl::init(""), llvm::cl::Hidden);
126
Eric Liubfac8f72017-12-19 18:00:37 +0000127static llvm::cl::opt<bool> EnableIndexBasedCompletion(
128 "enable-index-based-completion",
129 llvm::cl::desc(
Sam McCallea283c72018-01-30 09:21:30 +0000130 "Enable index-based global code completion. "
131 "Clang uses an index built from symbols in opened files"),
132 llvm::cl::init(true));
Eric Liubfac8f72017-12-19 18:00:37 +0000133
Haojian Wuba28e9a2018-01-10 14:44:34 +0000134static llvm::cl::opt<Path> YamlSymbolFile(
135 "yaml-symbol-file",
136 llvm::cl::desc(
137 "YAML-format global symbol file to build the static index. Clangd will "
138 "use the static index for global code completion.\n"
139 "WARNING: This option is experimental only, and will be removed "
140 "eventually. Don't rely on it."),
141 llvm::cl::init(""), llvm::cl::Hidden);
142
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000143int main(int argc, char *argv[]) {
Benjamin Kramerf0af3e62017-03-01 16:16:29 +0000144 llvm::cl::ParseCommandLineOptions(argc, argv, "clangd");
Sam McCall5ed599e2018-02-06 10:47:30 +0000145 if (Test) {
146 RunSynchronously = true;
147 InputStyle = JSONStreamStyle::Delimited;
148 PrettyPrint = true;
149 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000150
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000151 if (!RunSynchronously && WorkerThreadsCount == 0) {
152 llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
153 "specify -run-synchronously?";
154 return 1;
155 }
156
157 // Ignore -j option if -run-synchonously is used.
158 // FIXME: a warning should be shown here.
159 if (RunSynchronously)
160 WorkerThreadsCount = 0;
161
Benjamin Kramer74a18952017-10-26 10:07:04 +0000162 // Validate command line arguments.
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000163 llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
164 if (!InputMirrorFile.empty()) {
165 std::error_code EC;
166 InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC, llvm::sys::fs::F_RW);
167 if (EC) {
168 InputMirrorStream.reset();
169 llvm::errs() << "Error while opening an input mirror file: "
170 << EC.message();
171 }
172 }
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000173
Sam McCalled2717a2018-02-14 03:20:07 +0000174 // Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a
175 // trace flag in your editor's config is annoying, launching with
176 // `CLANGD_TRACE=trace.json vim` is easier.
Sam McCall8567cb32017-11-02 09:21:51 +0000177 llvm::Optional<llvm::raw_fd_ostream> TraceStream;
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000178 std::unique_ptr<trace::EventTracer> Tracer;
Sam McCalled2717a2018-02-14 03:20:07 +0000179 if (auto *TraceFile = getenv("CLANGD_TRACE")) {
Sam McCall8567cb32017-11-02 09:21:51 +0000180 std::error_code EC;
181 TraceStream.emplace(TraceFile, /*ref*/ EC, llvm::sys::fs::F_RW);
182 if (EC) {
Sam McCalled2717a2018-02-14 03:20:07 +0000183 TraceStream.reset();
184 llvm::errs() << "Error while opening trace file " << TraceFile << ": "
185 << EC.message();
Sam McCall8567cb32017-11-02 09:21:51 +0000186 } else {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000187 Tracer = trace::createJSONTracer(*TraceStream, PrettyPrint);
Sam McCall8567cb32017-11-02 09:21:51 +0000188 }
189 }
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000190
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000191 llvm::Optional<trace::Session> TracingSession;
192 if (Tracer)
193 TracingSession.emplace(*Tracer);
194
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000195 llvm::raw_ostream &Outs = llvm::outs();
196 llvm::raw_ostream &Logs = llvm::errs();
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000197 JSONOutput Out(Outs, Logs,
Sam McCalldd0566b2017-11-06 15:40:30 +0000198 InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
199 PrettyPrint);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000200
Ilya Biryukov940901e2017-12-13 12:51:22 +0000201 clangd::LoggingSession LoggingSession(Out);
202
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000203 // If --compile-commands-dir arg was invoked, check value and override default
204 // path.
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000205 llvm::Optional<Path> CompileCommandsDirPath;
206
207 if (CompileCommandsDir.empty()) {
208 CompileCommandsDirPath = llvm::None;
209 } else if (!llvm::sys::path::is_absolute(CompileCommandsDir) ||
210 !llvm::sys::fs::exists(CompileCommandsDir)) {
211 llvm::errs() << "Path specified by --compile-commands-dir either does not "
212 "exist or is not an absolute "
213 "path. The argument will be ignored.\n";
214 CompileCommandsDirPath = llvm::None;
215 } else {
216 CompileCommandsDirPath = CompileCommandsDir;
217 }
Benjamin Kramer6a3d74e2017-02-07 12:40:59 +0000218
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000219 bool StorePreamblesInMemory;
220 switch (PCHStorage) {
221 case PCHStorageFlag::Memory:
222 StorePreamblesInMemory = true;
223 break;
224 case PCHStorageFlag::Disk:
225 StorePreamblesInMemory = false;
226 break;
227 }
228
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000229 llvm::Optional<StringRef> ResourceDirRef = None;
230 if (!ResourceDir.empty())
231 ResourceDirRef = ResourceDir;
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000232
Benjamin Kramer74a18952017-10-26 10:07:04 +0000233 // Change stdin to binary to not lose \r\n on windows.
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000234 llvm::sys::ChangeStdinToBinary();
235
Haojian Wuba28e9a2018-01-10 14:44:34 +0000236 std::unique_ptr<SymbolIndex> StaticIdx;
237 if (EnableIndexBasedCompletion && !YamlSymbolFile.empty())
238 StaticIdx = BuildStaticIndex(YamlSymbolFile);
Sam McCalladccab62017-11-23 16:58:22 +0000239 clangd::CodeCompleteOptions CCOpts;
240 CCOpts.EnableSnippets = EnableSnippets;
241 CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
Haojian Wu48b48652018-01-25 09:20:09 +0000242 CCOpts.Limit = LimitCompletionResult;
Benjamin Kramer74a18952017-10-26 10:07:04 +0000243 // Initialize and run ClangdLSPServer.
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000244 ClangdLSPServer LSPServer(Out, WorkerThreadsCount, StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000245 CCOpts, ResourceDirRef, CompileCommandsDirPath,
Haojian Wuba28e9a2018-01-10 14:44:34 +0000246 EnableIndexBasedCompletion, StaticIdx.get());
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000247 constexpr int NoShutdownRequestErrorCode = 1;
Sam McCall8567cb32017-11-02 09:21:51 +0000248 llvm::set_thread_name("clangd.main");
Sam McCall5ed599e2018-02-06 10:47:30 +0000249 return LSPServer.run(std::cin, InputStyle) ? 0 : NoShutdownRequestErrorCode;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000250}