blob: 80737706704d38c1200c32842f2b5e1bff168bb7 [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"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000020#include <iostream>
Ilya Biryukov38d79772017-05-16 09:38:59 +000021#include <memory>
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000022#include <string>
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000023#include <thread>
Ilya Biryukov38d79772017-05-16 09:38:59 +000024
25using namespace clang;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000026using namespace clang::clangd;
27
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000028namespace {
29enum class PCHStorageFlag { Disk, Memory };
Haojian Wuba28e9a2018-01-10 14:44:34 +000030
31// Build an in-memory static index for global symbols from a YAML-format file.
32// The size of global symbols should be relatively small, so that all symbols
33// can be managed in memory.
34std::unique_ptr<SymbolIndex> BuildStaticIndex(llvm::StringRef YamlSymbolFile) {
35 auto Buffer = llvm::MemoryBuffer::getFile(YamlSymbolFile);
36 if (!Buffer) {
37 llvm::errs() << "Can't open " << YamlSymbolFile << "\n";
38 return nullptr;
39 }
Sam McCall60039512018-02-09 14:42:01 +000040 auto Slab = SymbolsFromYAML(Buffer.get()->getBuffer());
Haojian Wuba28e9a2018-01-10 14:44:34 +000041 SymbolSlab::Builder SymsBuilder;
42 for (auto Sym : Slab)
43 SymsBuilder.insert(Sym);
44
45 return MemIndex::build(std::move(SymsBuilder).build());
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000046}
Haojian Wuba28e9a2018-01-10 14:44:34 +000047} // namespace
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000048
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +000049static llvm::cl::opt<Path> CompileCommandsDir(
50 "compile-commands-dir",
51 llvm::cl::desc("Specify a path to look for compile_commands.json. If path "
52 "is invalid, clangd will look in the current directory and "
53 "parent paths of each source file."));
54
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000055static llvm::cl::opt<unsigned>
56 WorkerThreadsCount("j",
57 llvm::cl::desc("Number of async workers used by clangd"),
58 llvm::cl::init(getDefaultAsyncThreadsCount()));
59
Ilya Biryukovb33c1572017-09-12 13:57:14 +000060static llvm::cl::opt<bool> EnableSnippets(
61 "enable-snippets",
62 llvm::cl::desc(
Sam McCalladccab62017-11-23 16:58:22 +000063 "Present snippet completions instead of plaintext completions. "
64 "This also enables code pattern results." /* FIXME: should it? */),
65 llvm::cl::init(clangd::CodeCompleteOptions().EnableSnippets));
66
67// FIXME: Flags are the wrong mechanism for user preferences.
68// We should probably read a dotfile or similar.
69static llvm::cl::opt<bool> IncludeIneligibleResults(
70 "include-ineligible-results",
71 llvm::cl::desc(
72 "Include ineligible completion results (e.g. private members)"),
73 llvm::cl::init(clangd::CodeCompleteOptions().IncludeIneligibleResults),
74 llvm::cl::Hidden);
Ilya Biryukovb33c1572017-09-12 13:57:14 +000075
Sam McCall5ed599e2018-02-06 10:47:30 +000076static llvm::cl::opt<JSONStreamStyle> InputStyle(
77 "input-style", llvm::cl::desc("Input JSON stream encoding"),
78 llvm::cl::values(
79 clEnumValN(JSONStreamStyle::Standard, "standard", "usual LSP protocol"),
80 clEnumValN(JSONStreamStyle::Delimited, "delimited",
81 "messages delimited by --- lines, with # comment support")),
82 llvm::cl::init(JSONStreamStyle::Standard));
83
Sam McCalldd0566b2017-11-06 15:40:30 +000084static llvm::cl::opt<bool>
85 PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
86 llvm::cl::init(false));
87
Sam McCall5ed599e2018-02-06 10:47:30 +000088static llvm::cl::opt<bool> Test(
89 "lit-test",
90 llvm::cl::desc(
91 "Abbreviation for -input-style=delimited -pretty -run-synchronously. "
92 "Intended to simplify lit tests."),
93 llvm::cl::init(false), llvm::cl::Hidden);
94
Ilya Biryukove9eb7f02017-11-16 16:25:18 +000095static llvm::cl::opt<PCHStorageFlag> PCHStorage(
96 "pch-storage",
97 llvm::cl::desc("Storing PCHs in memory increases memory usages, but may "
98 "improve performance"),
99 llvm::cl::values(
100 clEnumValN(PCHStorageFlag::Disk, "disk", "store PCHs on disk"),
101 clEnumValN(PCHStorageFlag::Memory, "memory", "store PCHs in memory")),
102 llvm::cl::init(PCHStorageFlag::Disk));
103
Haojian Wu48b48652018-01-25 09:20:09 +0000104static llvm::cl::opt<int> LimitCompletionResult(
Sam McCallea283c72018-01-30 09:21:30 +0000105 "completion-limit",
Haojian Wu48b48652018-01-25 09:20:09 +0000106 llvm::cl::desc("Limit the number of completion results returned by clangd. "
107 "0 means no limit."),
Sam McCallea283c72018-01-30 09:21:30 +0000108 llvm::cl::init(100));
Haojian Wu48b48652018-01-25 09:20:09 +0000109
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000110static llvm::cl::opt<bool> RunSynchronously(
111 "run-synchronously",
112 llvm::cl::desc("Parse on main thread. If set, -j is ignored"),
113 llvm::cl::init(false), llvm::cl::Hidden);
Benjamin Kramerf0af3e62017-03-01 16:16:29 +0000114
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000115static llvm::cl::opt<Path>
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000116 ResourceDir("resource-dir",
Ilya Biryukov4ca7d852017-08-02 08:53:48 +0000117 llvm::cl::desc("Directory for system clang headers"),
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000118 llvm::cl::init(""), llvm::cl::Hidden);
119
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000120static llvm::cl::opt<Path> InputMirrorFile(
121 "input-mirror-file",
122 llvm::cl::desc(
123 "Mirror all LSP input to the specified file. Useful for debugging."),
124 llvm::cl::init(""), llvm::cl::Hidden);
125
Sam McCall8567cb32017-11-02 09:21:51 +0000126static llvm::cl::opt<Path> TraceFile(
127 "trace",
128 llvm::cl::desc(
129 "Trace internal events and timestamps in chrome://tracing JSON format"),
130 llvm::cl::init(""), llvm::cl::Hidden);
131
Eric Liubfac8f72017-12-19 18:00:37 +0000132static llvm::cl::opt<bool> EnableIndexBasedCompletion(
133 "enable-index-based-completion",
134 llvm::cl::desc(
Sam McCallea283c72018-01-30 09:21:30 +0000135 "Enable index-based global code completion. "
136 "Clang uses an index built from symbols in opened files"),
137 llvm::cl::init(true));
Eric Liubfac8f72017-12-19 18:00:37 +0000138
Haojian Wuba28e9a2018-01-10 14:44:34 +0000139static llvm::cl::opt<Path> YamlSymbolFile(
140 "yaml-symbol-file",
141 llvm::cl::desc(
142 "YAML-format global symbol file to build the static index. Clangd will "
143 "use the static index for global code completion.\n"
144 "WARNING: This option is experimental only, and will be removed "
145 "eventually. Don't rely on it."),
146 llvm::cl::init(""), llvm::cl::Hidden);
147
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000148int main(int argc, char *argv[]) {
Benjamin Kramerf0af3e62017-03-01 16:16:29 +0000149 llvm::cl::ParseCommandLineOptions(argc, argv, "clangd");
Sam McCall5ed599e2018-02-06 10:47:30 +0000150 if (Test) {
151 RunSynchronously = true;
152 InputStyle = JSONStreamStyle::Delimited;
153 PrettyPrint = true;
154 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000155
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000156 if (!RunSynchronously && WorkerThreadsCount == 0) {
157 llvm::errs() << "A number of worker threads cannot be 0. Did you mean to "
158 "specify -run-synchronously?";
159 return 1;
160 }
161
162 // Ignore -j option if -run-synchonously is used.
163 // FIXME: a warning should be shown here.
164 if (RunSynchronously)
165 WorkerThreadsCount = 0;
166
Benjamin Kramer74a18952017-10-26 10:07:04 +0000167 // Validate command line arguments.
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000168 llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
169 if (!InputMirrorFile.empty()) {
170 std::error_code EC;
171 InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC, llvm::sys::fs::F_RW);
172 if (EC) {
173 InputMirrorStream.reset();
174 llvm::errs() << "Error while opening an input mirror file: "
175 << EC.message();
176 }
177 }
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000178
179 // Setup tracing facilities.
Sam McCall8567cb32017-11-02 09:21:51 +0000180 llvm::Optional<llvm::raw_fd_ostream> TraceStream;
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000181 std::unique_ptr<trace::EventTracer> Tracer;
Sam McCall8567cb32017-11-02 09:21:51 +0000182 if (!TraceFile.empty()) {
183 std::error_code EC;
184 TraceStream.emplace(TraceFile, /*ref*/ EC, llvm::sys::fs::F_RW);
185 if (EC) {
186 TraceFile.reset();
187 llvm::errs() << "Error while opening trace file: " << EC.message();
188 } else {
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000189 Tracer = trace::createJSONTracer(*TraceStream, PrettyPrint);
Sam McCall8567cb32017-11-02 09:21:51 +0000190 }
191 }
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000192
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000193 llvm::Optional<trace::Session> TracingSession;
194 if (Tracer)
195 TracingSession.emplace(*Tracer);
196
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000197 llvm::raw_ostream &Outs = llvm::outs();
198 llvm::raw_ostream &Logs = llvm::errs();
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000199 JSONOutput Out(Outs, Logs,
Sam McCalldd0566b2017-11-06 15:40:30 +0000200 InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
201 PrettyPrint);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000202
Ilya Biryukov940901e2017-12-13 12:51:22 +0000203 clangd::LoggingSession LoggingSession(Out);
204
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000205 // If --compile-commands-dir arg was invoked, check value and override default
206 // path.
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000207 llvm::Optional<Path> CompileCommandsDirPath;
208
209 if (CompileCommandsDir.empty()) {
210 CompileCommandsDirPath = llvm::None;
211 } else if (!llvm::sys::path::is_absolute(CompileCommandsDir) ||
212 !llvm::sys::fs::exists(CompileCommandsDir)) {
213 llvm::errs() << "Path specified by --compile-commands-dir either does not "
214 "exist or is not an absolute "
215 "path. The argument will be ignored.\n";
216 CompileCommandsDirPath = llvm::None;
217 } else {
218 CompileCommandsDirPath = CompileCommandsDir;
219 }
Benjamin Kramer6a3d74e2017-02-07 12:40:59 +0000220
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000221 bool StorePreamblesInMemory;
222 switch (PCHStorage) {
223 case PCHStorageFlag::Memory:
224 StorePreamblesInMemory = true;
225 break;
226 case PCHStorageFlag::Disk:
227 StorePreamblesInMemory = false;
228 break;
229 }
230
Krasimir Georgiev0dcb48e2017-07-19 15:43:35 +0000231 llvm::Optional<StringRef> ResourceDirRef = None;
232 if (!ResourceDir.empty())
233 ResourceDirRef = ResourceDir;
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000234
Benjamin Kramer74a18952017-10-26 10:07:04 +0000235 // Change stdin to binary to not lose \r\n on windows.
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000236 llvm::sys::ChangeStdinToBinary();
237
Haojian Wuba28e9a2018-01-10 14:44:34 +0000238 std::unique_ptr<SymbolIndex> StaticIdx;
239 if (EnableIndexBasedCompletion && !YamlSymbolFile.empty())
240 StaticIdx = BuildStaticIndex(YamlSymbolFile);
Sam McCalladccab62017-11-23 16:58:22 +0000241 clangd::CodeCompleteOptions CCOpts;
242 CCOpts.EnableSnippets = EnableSnippets;
243 CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
Haojian Wu48b48652018-01-25 09:20:09 +0000244 CCOpts.Limit = LimitCompletionResult;
Benjamin Kramer74a18952017-10-26 10:07:04 +0000245 // Initialize and run ClangdLSPServer.
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000246 ClangdLSPServer LSPServer(Out, WorkerThreadsCount, StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000247 CCOpts, ResourceDirRef, CompileCommandsDirPath,
Haojian Wuba28e9a2018-01-10 14:44:34 +0000248 EnableIndexBasedCompletion, StaticIdx.get());
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000249 constexpr int NoShutdownRequestErrorCode = 1;
Sam McCall8567cb32017-11-02 09:21:51 +0000250 llvm::set_thread_name("clangd.main");
Sam McCall5ed599e2018-02-06 10:47:30 +0000251 return LSPServer.run(std::cin, InputStyle) ? 0 : NoShutdownRequestErrorCode;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000252}