blob: 2bf4b36d68ea0863690f53a74548df0068898950 [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdServer.cpp - Main clangd server code --------------*- C++-*-===//
2//
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
10#include "ClangdServer.h"
Sam McCalla66d2cb2017-12-19 17:06:07 +000011#include "CodeComplete.h"
Eric Liuc5105f92018-02-16 14:15:55 +000012#include "Headers.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000013#include "SourceCode.h"
Sam McCalla66d2cb2017-12-19 17:06:07 +000014#include "XRefs.h"
Sam McCall0faecf02018-01-15 12:33:00 +000015#include "index/Merge.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000016#include "clang/Format/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000017#include "clang/Frontend/CompilerInstance.h"
18#include "clang/Frontend/CompilerInvocation.h"
19#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +000020#include "clang/Tooling/Refactoring/RefactoringResultConsumer.h"
21#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000022#include "llvm/ADT/ArrayRef.h"
Sam McCallb5f5eb62018-01-25 17:01:39 +000023#include "llvm/ADT/ScopeExit.h"
Benjamin Krameree19f162017-10-26 12:28:13 +000024#include "llvm/Support/Errc.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000025#include "llvm/Support/FileSystem.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000026#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000027#include "llvm/Support/raw_ostream.h"
28#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000029
Ilya Biryukov2f314102017-05-16 10:06:20 +000030using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000031using namespace clang::clangd;
32
Ilya Biryukovafb55542017-05-16 14:40:30 +000033namespace {
34
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000035void ignoreError(llvm::Error Err) {
36 handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
37}
38
Ilya Biryukova46f7a92017-06-28 10:34:50 +000039std::string getStandardResourceDir() {
40 static int Dummy; // Just an address in this process.
41 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
42}
43
Haojian Wu345099c2017-11-09 11:30:04 +000044class RefactoringResultCollector final
45 : public tooling::RefactoringResultConsumer {
46public:
47 void handleError(llvm::Error Err) override {
48 assert(!Result.hasValue());
49 // FIXME: figure out a way to return better message for DiagnosticError.
50 // clangd uses llvm::toString to convert the Err to string, however, for
51 // DiagnosticError, only "clang diagnostic" will be generated.
52 Result = std::move(Err);
53 }
54
55 // Using the handle(SymbolOccurrences) from parent class.
56 using tooling::RefactoringResultConsumer::handle;
57
58 void handle(tooling::AtomicChanges SourceReplacements) override {
59 assert(!Result.hasValue());
60 Result = std::move(SourceReplacements);
61 }
62
63 Optional<Expected<tooling::AtomicChanges>> Result;
64};
65
Ilya Biryukovafb55542017-05-16 14:40:30 +000066} // namespace
67
Sam McCalla7bb0cc2018-03-12 23:22:35 +000068IntrusiveRefCntPtr<vfs::FileSystem> RealFileSystemProvider::getFileSystem() {
69 return vfs::getRealFileSystem();
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000070}
71
Sam McCall7363a2f2018-03-05 17:28:54 +000072ClangdServer::Options ClangdServer::optsForTest() {
73 ClangdServer::Options Opts;
74 Opts.UpdateDebounce = std::chrono::steady_clock::duration::zero(); // Faster!
75 Opts.StorePreamblesInMemory = true;
76 Opts.AsyncThreadsCount = 4; // Consistent!
77 return Opts;
78}
79
Sam McCalladccab62017-11-23 16:58:22 +000080ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
Sam McCalladccab62017-11-23 16:58:22 +000081 FileSystemProvider &FSProvider,
Sam McCall7363a2f2018-03-05 17:28:54 +000082 DiagnosticsConsumer &DiagConsumer,
83 const Options &Opts)
84 : CompileArgs(CDB, Opts.ResourceDir ? Opts.ResourceDir->str()
85 : getStandardResourceDir()),
Ilya Biryukov929697b2018-01-25 14:19:21 +000086 DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Sam McCall7363a2f2018-03-05 17:28:54 +000087 FileIdx(Opts.BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000088 PCHs(std::make_shared<PCHContainerOperations>()),
89 // Pass a callback into `WorkScheduler` to extract symbols from a newly
90 // parsed file and rebuild the file index synchronously each time an AST
91 // is parsed.
Eric Liubfac8f72017-12-19 18:00:37 +000092 // FIXME(ioeric): this can be slow and we may be able to index on less
93 // critical paths.
Sam McCall7363a2f2018-03-05 17:28:54 +000094 WorkScheduler(Opts.AsyncThreadsCount, Opts.StorePreamblesInMemory,
Sam McCalld1a7a372018-01-31 13:40:48 +000095 FileIdx
96 ? [this](PathRef Path,
97 ParsedAST *AST) { FileIdx->update(Path, AST); }
Sam McCalld1e0deb2018-03-02 08:56:37 +000098 : ASTParsedCallback(),
Sam McCall7363a2f2018-03-05 17:28:54 +000099 Opts.UpdateDebounce) {
100 if (FileIdx && Opts.StaticIndex) {
101 MergedIndex = mergeIndex(FileIdx.get(), Opts.StaticIndex);
Sam McCall0faecf02018-01-15 12:33:00 +0000102 Index = MergedIndex.get();
103 } else if (FileIdx)
104 Index = FileIdx.get();
Sam McCall7363a2f2018-03-05 17:28:54 +0000105 else if (Opts.StaticIndex)
106 Index = Opts.StaticIndex;
Sam McCall0faecf02018-01-15 12:33:00 +0000107 else
108 Index = nullptr;
109}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000110
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000111void ClangdServer::setRootPath(PathRef RootPath) {
112 std::string NewRootPath = llvm::sys::path::convert_to_slash(
113 RootPath, llvm::sys::path::Style::posix);
114 if (llvm::sys::fs::is_directory(NewRootPath))
115 this->RootPath = NewRootPath;
116}
117
Sam McCall568e17f2018-02-22 13:11:12 +0000118void ClangdServer::addDocument(PathRef File, StringRef Contents,
119 WantDiagnostics WantDiags) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000120 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Sam McCall0bb24cd2018-02-13 08:59:23 +0000121 scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000122 WantDiags, FSProvider.getFileSystem());
Ilya Biryukov38d79772017-05-16 09:38:59 +0000123}
124
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000125void ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000126 DraftMgr.removeDraft(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000127 CompileArgs.invalidate(File);
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000128 WorkScheduler.remove(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000129}
130
Sam McCall0bb24cd2018-02-13 08:59:23 +0000131void ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000132 auto FileContents = DraftMgr.getDraft(File);
133 assert(FileContents.Draft &&
134 "forceReparse() was called for non-added document");
135
Ilya Biryukov929697b2018-01-25 14:19:21 +0000136 // forceReparse promises to request new compilation flags from CDB, so we
137 // remove any cahced flags.
138 CompileArgs.invalidate(File);
139
Sam McCall568e17f2018-02-22 13:11:12 +0000140 scheduleReparseAndDiags(File, std::move(FileContents), WantDiagnostics::Yes,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000141 FSProvider.getFileSystem());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000142}
143
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000144void ClangdServer::codeComplete(PathRef File, Position Pos,
145 const clangd::CodeCompleteOptions &Opts,
146 Callback<CompletionList> CB) {
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000147 // Copy completion options for passing them to async task handler.
148 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000149 if (!CodeCompleteOpts.Index) // Respect overridden index.
150 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000151
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000152 VersionedDraft Latest = DraftMgr.getDraft(File);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000153 if (!Latest.Draft)
154 return CB(llvm::make_error<llvm::StringError>(
155 "codeComplete called for non-added document",
156 llvm::errc::invalid_argument));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000157
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000158 // Copy PCHs to avoid accessing this->PCHs concurrently
159 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000160 auto FS = FSProvider.getFileSystem();
161 auto Task = [PCHs, Pos, FS, CodeCompleteOpts](
162 std::string Contents, Path File, Callback<CompletionList> CB,
Sam McCalld1a7a372018-01-31 13:40:48 +0000163 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000164 assert(IP && "error when trying to read preamble for codeComplete");
165 auto PreambleData = IP->Preamble;
166 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000167
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000168 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
169 // both the old and the new version in case only one of them matches.
170 CompletionList Result = clangd::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000171 File, Command, PreambleData ? &PreambleData->Preamble : nullptr,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000172 Contents, Pos, FS, PCHs, CodeCompleteOpts);
173 CB(std::move(Result));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000174 };
175
Sam McCall091557d2018-02-23 07:54:17 +0000176 WorkScheduler.runWithPreamble(
177 "CodeComplete", File,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000178 Bind(Task, std::move(*Latest.Draft), File.str(), std::move(CB)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000179}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000180
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000181void ClangdServer::signatureHelp(PathRef File, Position Pos,
182 Callback<SignatureHelp> CB) {
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000183 VersionedDraft Latest = DraftMgr.getDraft(File);
184 if (!Latest.Draft)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000185 return CB(llvm::make_error<llvm::StringError>(
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000186 "signatureHelp is called for non-added document",
187 llvm::errc::invalid_argument));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000188
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000189 auto PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000190 auto FS = FSProvider.getFileSystem();
191 auto Action = [Pos, FS, PCHs](std::string Contents, Path File,
192 Callback<SignatureHelp> CB,
193 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000194 if (!IP)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000195 return CB(IP.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000196
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000197 auto PreambleData = IP->Preamble;
198 auto &Command = IP->Inputs.CompileCommand;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000199 CB(clangd::signatureHelp(File, Command,
200 PreambleData ? &PreambleData->Preamble : nullptr,
201 Contents, Pos, FS, PCHs));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000202 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000203
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000204 WorkScheduler.runWithPreamble(
205 "SignatureHelp", File,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000206 Bind(Action, std::move(*Latest.Draft), File.str(), std::move(CB)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000207}
208
Raoul Wols212bcf82017-12-12 20:25:06 +0000209llvm::Expected<tooling::Replacements>
210ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000211 size_t Begin = positionToOffset(Code, Rng.start);
212 size_t Len = positionToOffset(Code, Rng.end) - Begin;
213 return formatCode(Code, File, {tooling::Range(Begin, Len)});
214}
215
Raoul Wols212bcf82017-12-12 20:25:06 +0000216llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
217 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000218 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000219 return formatCode(Code, File, {tooling::Range(0, Code.size())});
220}
221
Raoul Wols212bcf82017-12-12 20:25:06 +0000222llvm::Expected<tooling::Replacements>
223ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000224 // Look for the previous opening brace from the character position and
225 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000226 size_t CursorPos = positionToOffset(Code, Pos);
227 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
228 if (PreviousLBracePos == StringRef::npos)
229 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000230 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000231
232 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
233}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000234
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000235void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
236 Callback<std::vector<tooling::Replacement>> CB) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000237 auto Action = [Pos](Path File, std::string NewName,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000238 Callback<std::vector<tooling::Replacement>> CB,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000239 Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000240 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000241 return CB(InpAST.takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000242 auto &AST = InpAST->AST;
243
244 RefactoringResultCollector ResultCollector;
245 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000246 const FileEntry *FE =
247 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
248 if (!FE)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000249 return CB(llvm::make_error<llvm::StringError>(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000250 "rename called for non-added document",
251 llvm::errc::invalid_argument));
Haojian Wu345099c2017-11-09 11:30:04 +0000252 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000253 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000254 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000255 AST.getASTContext().getSourceManager());
256 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000257 auto Rename = clang::tooling::RenameOccurrences::initiate(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000258 Context, SourceRange(SourceLocationBeg), NewName);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000259 if (!Rename)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000260 return CB(Rename.takeError());
Haojian Wu345099c2017-11-09 11:30:04 +0000261
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000262 Rename->invoke(ResultCollector, Context);
263
264 assert(ResultCollector.Result.hasValue());
265 if (!ResultCollector.Result.getValue())
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000266 return CB(ResultCollector.Result->takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000267
268 std::vector<tooling::Replacement> Replacements;
269 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
270 tooling::Replacements ChangeReps = Change.getReplacements();
271 for (const auto &Rep : ChangeReps) {
272 // FIXME: Right now we only support renaming the main file, so we
273 // drop replacements not for the main file. In the future, we might
274 // consider to support:
275 // * rename in any included header
276 // * rename only in the "main" header
277 // * provide an error if there are symbols we won't rename (e.g.
278 // std::vector)
279 // * rename globally in project
280 // * rename in open files
281 if (Rep.getFilePath() == File)
282 Replacements.push_back(Rep);
283 }
Haojian Wu345099c2017-11-09 11:30:04 +0000284 }
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000285 return CB(std::move(Replacements));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000286 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000287
288 WorkScheduler.runWithAST(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000289 "Rename", File, Bind(Action, File.str(), NewName.str(), std::move(CB)));
Haojian Wu345099c2017-11-09 11:30:04 +0000290}
291
Eric Liu6c8e8582018-02-26 08:32:13 +0000292/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
293/// include.
294static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
295 llvm::StringRef HintPath) {
296 if (isLiteralInclude(Header))
297 return HeaderFile{Header.str(), /*Verbatim=*/true};
298 auto U = URI::parse(Header);
299 if (!U)
300 return U.takeError();
301 auto Resolved = URI::resolve(*U, HintPath);
302 if (!Resolved)
303 return Resolved.takeError();
304 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
Haojian Wu33caf892018-03-06 12:56:18 +0000305}
Eric Liu6c8e8582018-02-26 08:32:13 +0000306
Eric Liuc5105f92018-02-16 14:15:55 +0000307Expected<tooling::Replacements>
308ClangdServer::insertInclude(PathRef File, StringRef Code,
Eric Liu6c8e8582018-02-26 08:32:13 +0000309 StringRef DeclaringHeader,
310 StringRef InsertedHeader) {
311 assert(!DeclaringHeader.empty() && !InsertedHeader.empty());
Eric Liuc5105f92018-02-16 14:15:55 +0000312 std::string ToInclude;
Eric Liu6c8e8582018-02-26 08:32:13 +0000313 auto ResolvedOrginal = toHeaderFile(DeclaringHeader, File);
314 if (!ResolvedOrginal)
315 return ResolvedOrginal.takeError();
316 auto ResolvedPreferred = toHeaderFile(InsertedHeader, File);
317 if (!ResolvedPreferred)
318 return ResolvedPreferred.takeError();
319 tooling::CompileCommand CompileCommand = CompileArgs.getCompileCommand(File);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000320 auto Include =
321 calculateIncludePath(File, Code, *ResolvedOrginal, *ResolvedPreferred,
322 CompileCommand, FSProvider.getFileSystem());
Eric Liu6c8e8582018-02-26 08:32:13 +0000323 if (!Include)
324 return Include.takeError();
325 if (Include->empty())
326 return tooling::Replacements();
327 ToInclude = std::move(*Include);
Eric Liuc5105f92018-02-16 14:15:55 +0000328
329 auto Style = format::getStyle("file", File, "llvm");
330 if (!Style) {
331 llvm::consumeError(Style.takeError());
332 // FIXME(ioeric): needs more consistent style support in clangd server.
333 Style = format::getLLVMStyle();
334 }
335 // Replacement with offset UINT_MAX and length 0 will be treated as include
336 // insertion.
337 tooling::Replacement R(File, /*Offset=*/UINT_MAX, 0, "#include " + ToInclude);
Eric Liue3395b92018-03-06 10:42:50 +0000338 auto Replaces = format::cleanupAroundReplacements(
339 Code, tooling::Replacements(R), *Style);
340 if (!Replaces)
341 return Replaces;
342 return formatReplacements(Code, *Replaces, *Style);
Eric Liuc5105f92018-02-16 14:15:55 +0000343}
344
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000345llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
346 auto Latest = DraftMgr.getDraft(File);
347 if (!Latest.Draft)
348 return llvm::None;
349 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000350}
351
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000352void ClangdServer::dumpAST(PathRef File,
353 UniqueFunction<void(std::string)> Callback) {
354 auto Action = [](decltype(Callback) Callback,
355 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000356 if (!InpAST) {
357 ignoreError(InpAST.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000358 return Callback("<no-ast>");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000359 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000360 std::string Result;
361
362 llvm::raw_string_ostream ResultOS(Result);
363 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000364 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000365
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000366 Callback(Result);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000367 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000368
Sam McCall091557d2018-02-23 07:54:17 +0000369 WorkScheduler.runWithAST("DumpAST", File, Bind(Action, std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000370}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000371
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000372void ClangdServer::findDefinitions(PathRef File, Position Pos,
373 Callback<std::vector<Location>> CB) {
374 auto FS = FSProvider.getFileSystem();
375 auto Action = [Pos, FS](Callback<std::vector<Location>> CB,
376 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000377 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000378 return CB(InpAST.takeError());
379 CB(clangd::findDefinitions(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000380 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000381
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000382 WorkScheduler.runWithAST("Definitions", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000383}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000384
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000385llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
386
387 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
388 ".c++", ".m", ".mm"};
389 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
390
391 StringRef PathExt = llvm::sys::path::extension(Path);
392
393 // Lookup in a list of known extensions.
394 auto SourceIter =
395 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
396 [&PathExt](PathRef SourceExt) {
397 return SourceExt.equals_lower(PathExt);
398 });
399 bool IsSource = SourceIter != std::end(SourceExtensions);
400
401 auto HeaderIter =
402 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
403 [&PathExt](PathRef HeaderExt) {
404 return HeaderExt.equals_lower(PathExt);
405 });
406
407 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
408
409 // We can only switch between extensions known extensions.
410 if (!IsSource && !IsHeader)
411 return llvm::None;
412
413 // Array to lookup extensions for the switch. An opposite of where original
414 // extension was found.
415 ArrayRef<StringRef> NewExts;
416 if (IsSource)
417 NewExts = HeaderExtensions;
418 else
419 NewExts = SourceExtensions;
420
421 // Storage for the new path.
422 SmallString<128> NewPath = StringRef(Path);
423
424 // Instance of vfs::FileSystem, used for file existence checks.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000425 auto FS = FSProvider.getFileSystem();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000426
427 // Loop through switched extension candidates.
428 for (StringRef NewExt : NewExts) {
429 llvm::sys::path::replace_extension(NewPath, NewExt);
430 if (FS->exists(NewPath))
431 return NewPath.str().str(); // First str() to convert from SmallString to
432 // StringRef, second to convert from StringRef
433 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000434
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000435 // Also check NewExt in upper-case, just in case.
436 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
437 if (FS->exists(NewPath))
438 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000439 }
440
441 return llvm::None;
442}
443
Raoul Wols212bcf82017-12-12 20:25:06 +0000444llvm::Expected<tooling::Replacements>
445ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
446 ArrayRef<tooling::Range> Ranges) {
447 // Call clang-format.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000448 auto FS = FSProvider.getFileSystem();
449 auto Style = format::getStyle("file", File, "LLVM", Code, FS.get());
Eric Liue3395b92018-03-06 10:42:50 +0000450 if (!Style)
451 return Style.takeError();
452
453 tooling::Replacements IncludeReplaces =
454 format::sortIncludes(*Style, Code, Ranges, File);
455 auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
456 if (!Changed)
457 return Changed.takeError();
458
459 return IncludeReplaces.merge(format::reformat(
460 Style.get(), *Changed,
461 tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
462 File));
Raoul Wols212bcf82017-12-12 20:25:06 +0000463}
464
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000465void ClangdServer::findDocumentHighlights(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000466 PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000467 auto FileContents = DraftMgr.getDraft(File);
468 if (!FileContents.Draft)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000469 return CB(llvm::make_error<llvm::StringError>(
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000470 "findDocumentHighlights called on non-added file",
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000471 llvm::errc::invalid_argument));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000472
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000473 auto FS = FSProvider.getFileSystem();
474 auto Action = [FS, Pos](Callback<std::vector<DocumentHighlight>> CB,
475 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000476 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000477 return CB(InpAST.takeError());
478 CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000479 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000480
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000481 WorkScheduler.runWithAST("Highlights", File, Bind(Action, std::move(CB)));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000482}
483
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000484void ClangdServer::findHover(PathRef File, Position Pos, Callback<Hover> CB) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000485 Hover FinalHover;
486 auto FileContents = DraftMgr.getDraft(File);
487 if (!FileContents.Draft)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000488 return CB(llvm::make_error<llvm::StringError>(
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000489 "findHover called on non-added file", llvm::errc::invalid_argument));
490
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000491 auto FS = FSProvider.getFileSystem();
492 auto Action = [Pos, FS](Callback<Hover> CB,
493 llvm::Expected<InputsAndAST> InpAST) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000494 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000495 return CB(InpAST.takeError());
496 CB(clangd::getHover(InpAST->AST, Pos));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000497 };
498
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000499 WorkScheduler.runWithAST("Hover", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000500}
501
Sam McCall0bb24cd2018-02-13 08:59:23 +0000502void ClangdServer::scheduleReparseAndDiags(
Sam McCall568e17f2018-02-22 13:11:12 +0000503 PathRef File, VersionedDraft Contents, WantDiagnostics WantDiags,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000504 IntrusiveRefCntPtr<vfs::FileSystem> FS) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000505 tooling::CompileCommand Command = CompileArgs.getCompileCommand(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000506
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000507 DocVersion Version = Contents.Version;
508 Path FileStr = File.str();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000509
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000510 auto Callback = [this, Version, FileStr](std::vector<Diag> Diags) {
Ilya Biryukov47f22022017-09-20 12:58:55 +0000511 // We need to serialize access to resulting diagnostics to avoid calling
512 // `onDiagnosticsReady` in the wrong order.
513 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
514 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
515 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
516 // implementation diagnostics will not be reported after version counters'
517 // overflow. This should not happen in practice, since DocVersion is a
518 // 64-bit unsigned integer.
519 if (Version < LastReportedDiagsVersion)
520 return;
521 LastReportedDiagsVersion = Version;
522
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000523 DiagConsumer.onDiagnosticsReady(FileStr, std::move(Diags));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000524 };
525
Sam McCalld1a7a372018-01-31 13:40:48 +0000526 WorkScheduler.update(File,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000527 ParseInputs{std::move(Command), std::move(FS),
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000528 std::move(*Contents.Draft)},
Sam McCall568e17f2018-02-22 13:11:12 +0000529 WantDiags, std::move(Callback));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000530}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000531
Simon Marchi5178f922018-02-22 14:00:39 +0000532void ClangdServer::reparseOpenedFiles() {
533 for (const Path &FilePath : DraftMgr.getActiveFiles())
534 forceReparse(FilePath);
535}
536
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000537void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
538 // FIXME: Do nothing for now. This will be used for indexing and potentially
539 // invalidating other caches.
540}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000541
542std::vector<std::pair<Path, std::size_t>>
543ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000544 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000545}
Sam McCall0bb24cd2018-02-13 08:59:23 +0000546
547LLVM_NODISCARD bool
548ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
549 return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds));
550}