blob: e73834be32daf5dab97ab672f56f3a1ea7205f23 [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,
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000119 WantDiagnostics WantDiags, bool SkipCache) {
120 if (SkipCache)
121 CompileArgs.invalidate(File);
122
Simon Marchi9569fd52018-03-16 14:30:42 +0000123 DocVersion Version = ++InternalVersion[File];
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000124 ParseInputs Inputs = {CompileArgs.getCompileCommand(File),
125 FSProvider.getFileSystem(), Contents.str()};
126
127 Path FileStr = File.str();
128 WorkScheduler.update(File, std::move(Inputs), WantDiags,
129 [this, FileStr, Version](std::vector<Diag> Diags) {
130 consumeDiagnostics(FileStr, Version, std::move(Diags));
131 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000132}
133
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000134void ClangdServer::removeDocument(PathRef File) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000135 ++InternalVersion[File];
Ilya Biryukov929697b2018-01-25 14:19:21 +0000136 CompileArgs.invalidate(File);
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000137 WorkScheduler.remove(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000138}
139
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000140void ClangdServer::codeComplete(PathRef File, Position Pos,
141 const clangd::CodeCompleteOptions &Opts,
142 Callback<CompletionList> CB) {
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000143 // Copy completion options for passing them to async task handler.
144 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000145 if (!CodeCompleteOpts.Index) // Respect overridden index.
146 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000147
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000148 // Copy PCHs to avoid accessing this->PCHs concurrently
149 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000150 auto FS = FSProvider.getFileSystem();
Simon Marchi5a48cf82018-03-14 18:31:48 +0000151 auto Task = [PCHs, Pos, FS,
152 CodeCompleteOpts](Path File, Callback<CompletionList> CB,
153 llvm::Expected<InputsAndPreamble> IP) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000154 if (!IP)
155 return CB(IP.takeError());
156
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000157 auto PreambleData = IP->Preamble;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000158
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000159 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
160 // both the old and the new version in case only one of them matches.
161 CompletionList Result = clangd::codeComplete(
Ilya Biryukovf1f3d572018-03-14 17:46:52 +0000162 File, IP->Command, PreambleData ? &PreambleData->Preamble : nullptr,
Simon Marchi5a48cf82018-03-14 18:31:48 +0000163 IP->Contents, Pos, FS, PCHs, CodeCompleteOpts);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000164 CB(std::move(Result));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000165 };
166
Simon Marchi5a48cf82018-03-14 18:31:48 +0000167 WorkScheduler.runWithPreamble("CodeComplete", File,
168 Bind(Task, File.str(), std::move(CB)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000169}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000170
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000171void ClangdServer::signatureHelp(PathRef File, Position Pos,
172 Callback<SignatureHelp> CB) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000173
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000174 auto PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000175 auto FS = FSProvider.getFileSystem();
Simon Marchi5a48cf82018-03-14 18:31:48 +0000176 auto Action = [Pos, FS, PCHs](Path File, Callback<SignatureHelp> CB,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000177 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000178 if (!IP)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000179 return CB(IP.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000180
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000181 auto PreambleData = IP->Preamble;
Ilya Biryukovf1f3d572018-03-14 17:46:52 +0000182 CB(clangd::signatureHelp(File, IP->Command,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000183 PreambleData ? &PreambleData->Preamble : nullptr,
Simon Marchi5a48cf82018-03-14 18:31:48 +0000184 IP->Contents, Pos, FS, PCHs));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000185 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000186
Simon Marchi5a48cf82018-03-14 18:31:48 +0000187 WorkScheduler.runWithPreamble("SignatureHelp", File,
188 Bind(Action, File.str(), std::move(CB)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000189}
190
Raoul Wols212bcf82017-12-12 20:25:06 +0000191llvm::Expected<tooling::Replacements>
192ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Simon Marchi766338a2018-03-21 14:36:46 +0000193 llvm::Expected<size_t> Begin = positionToOffset(Code, Rng.start);
194 if (!Begin)
195 return Begin.takeError();
196 llvm::Expected<size_t> End = positionToOffset(Code, Rng.end);
197 if (!End)
198 return End.takeError();
199 return formatCode(Code, File, {tooling::Range(*Begin, *End - *Begin)});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000200}
201
Raoul Wols212bcf82017-12-12 20:25:06 +0000202llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
203 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000204 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000205 return formatCode(Code, File, {tooling::Range(0, Code.size())});
206}
207
Raoul Wols212bcf82017-12-12 20:25:06 +0000208llvm::Expected<tooling::Replacements>
209ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000210 // Look for the previous opening brace from the character position and
211 // format starting from there.
Simon Marchi766338a2018-03-21 14:36:46 +0000212 llvm::Expected<size_t> CursorPos = positionToOffset(Code, Pos);
213 if (!CursorPos)
214 return CursorPos.takeError();
215 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', *CursorPos);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000216 if (PreviousLBracePos == StringRef::npos)
Simon Marchi766338a2018-03-21 14:36:46 +0000217 PreviousLBracePos = *CursorPos;
218 size_t Len = *CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000219
220 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
221}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000222
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000223void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
224 Callback<std::vector<tooling::Replacement>> CB) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000225 auto Action = [Pos](Path File, std::string NewName,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000226 Callback<std::vector<tooling::Replacement>> CB,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000227 Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000228 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000229 return CB(InpAST.takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000230 auto &AST = InpAST->AST;
231
232 RefactoringResultCollector ResultCollector;
233 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000234 const FileEntry *FE =
235 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
236 if (!FE)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000237 return CB(llvm::make_error<llvm::StringError>(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000238 "rename called for non-added document",
239 llvm::errc::invalid_argument));
Haojian Wu345099c2017-11-09 11:30:04 +0000240 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000241 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000242 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000243 AST.getASTContext().getSourceManager());
244 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000245 auto Rename = clang::tooling::RenameOccurrences::initiate(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000246 Context, SourceRange(SourceLocationBeg), NewName);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000247 if (!Rename)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000248 return CB(Rename.takeError());
Haojian Wu345099c2017-11-09 11:30:04 +0000249
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000250 Rename->invoke(ResultCollector, Context);
251
252 assert(ResultCollector.Result.hasValue());
253 if (!ResultCollector.Result.getValue())
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000254 return CB(ResultCollector.Result->takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000255
256 std::vector<tooling::Replacement> Replacements;
257 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
258 tooling::Replacements ChangeReps = Change.getReplacements();
259 for (const auto &Rep : ChangeReps) {
260 // FIXME: Right now we only support renaming the main file, so we
261 // drop replacements not for the main file. In the future, we might
262 // consider to support:
263 // * rename in any included header
264 // * rename only in the "main" header
265 // * provide an error if there are symbols we won't rename (e.g.
266 // std::vector)
267 // * rename globally in project
268 // * rename in open files
269 if (Rep.getFilePath() == File)
270 Replacements.push_back(Rep);
271 }
Haojian Wu345099c2017-11-09 11:30:04 +0000272 }
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000273 return CB(std::move(Replacements));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000274 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000275
276 WorkScheduler.runWithAST(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000277 "Rename", File, Bind(Action, File.str(), NewName.str(), std::move(CB)));
Haojian Wu345099c2017-11-09 11:30:04 +0000278}
279
Eric Liu6c8e8582018-02-26 08:32:13 +0000280/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
281/// include.
282static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
283 llvm::StringRef HintPath) {
284 if (isLiteralInclude(Header))
285 return HeaderFile{Header.str(), /*Verbatim=*/true};
286 auto U = URI::parse(Header);
287 if (!U)
288 return U.takeError();
Haojian Wue9a5a2f2018-04-09 15:09:44 +0000289
290 auto IncludePath = URI::includeSpelling(*U);
291 if (!IncludePath)
292 return IncludePath.takeError();
293 if (!IncludePath->empty())
294 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
295
Eric Liu6c8e8582018-02-26 08:32:13 +0000296 auto Resolved = URI::resolve(*U, HintPath);
297 if (!Resolved)
298 return Resolved.takeError();
299 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
Haojian Wu33caf892018-03-06 12:56:18 +0000300}
Eric Liu6c8e8582018-02-26 08:32:13 +0000301
Eric Liuc5105f92018-02-16 14:15:55 +0000302Expected<tooling::Replacements>
303ClangdServer::insertInclude(PathRef File, StringRef Code,
Eric Liu6c8e8582018-02-26 08:32:13 +0000304 StringRef DeclaringHeader,
305 StringRef InsertedHeader) {
306 assert(!DeclaringHeader.empty() && !InsertedHeader.empty());
Eric Liuc5105f92018-02-16 14:15:55 +0000307 std::string ToInclude;
Eric Liu6c8e8582018-02-26 08:32:13 +0000308 auto ResolvedOrginal = toHeaderFile(DeclaringHeader, File);
309 if (!ResolvedOrginal)
310 return ResolvedOrginal.takeError();
311 auto ResolvedPreferred = toHeaderFile(InsertedHeader, File);
312 if (!ResolvedPreferred)
313 return ResolvedPreferred.takeError();
314 tooling::CompileCommand CompileCommand = CompileArgs.getCompileCommand(File);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000315 auto Include =
316 calculateIncludePath(File, Code, *ResolvedOrginal, *ResolvedPreferred,
317 CompileCommand, FSProvider.getFileSystem());
Eric Liu6c8e8582018-02-26 08:32:13 +0000318 if (!Include)
319 return Include.takeError();
320 if (Include->empty())
321 return tooling::Replacements();
322 ToInclude = std::move(*Include);
Eric Liuc5105f92018-02-16 14:15:55 +0000323
324 auto Style = format::getStyle("file", File, "llvm");
325 if (!Style) {
326 llvm::consumeError(Style.takeError());
327 // FIXME(ioeric): needs more consistent style support in clangd server.
328 Style = format::getLLVMStyle();
329 }
330 // Replacement with offset UINT_MAX and length 0 will be treated as include
331 // insertion.
332 tooling::Replacement R(File, /*Offset=*/UINT_MAX, 0, "#include " + ToInclude);
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000333 auto Replaces =
334 format::cleanupAroundReplacements(Code, tooling::Replacements(R), *Style);
Eric Liue3395b92018-03-06 10:42:50 +0000335 if (!Replaces)
336 return Replaces;
337 return formatReplacements(Code, *Replaces, *Style);
Eric Liuc5105f92018-02-16 14:15:55 +0000338}
339
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000340void ClangdServer::dumpAST(PathRef File,
341 UniqueFunction<void(std::string)> Callback) {
342 auto Action = [](decltype(Callback) Callback,
343 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000344 if (!InpAST) {
345 ignoreError(InpAST.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000346 return Callback("<no-ast>");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000347 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000348 std::string Result;
349
350 llvm::raw_string_ostream ResultOS(Result);
351 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000352 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000353
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000354 Callback(Result);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000355 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000356
Sam McCall091557d2018-02-23 07:54:17 +0000357 WorkScheduler.runWithAST("DumpAST", File, Bind(Action, std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000358}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000359
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000360void ClangdServer::findDefinitions(PathRef File, Position Pos,
361 Callback<std::vector<Location>> CB) {
362 auto FS = FSProvider.getFileSystem();
363 auto Action = [Pos, FS](Callback<std::vector<Location>> CB,
364 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000365 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000366 return CB(InpAST.takeError());
367 CB(clangd::findDefinitions(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000368 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000369
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000370 WorkScheduler.runWithAST("Definitions", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000371}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000372
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000373llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
374
375 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
376 ".c++", ".m", ".mm"};
377 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
378
379 StringRef PathExt = llvm::sys::path::extension(Path);
380
381 // Lookup in a list of known extensions.
382 auto SourceIter =
383 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
384 [&PathExt](PathRef SourceExt) {
385 return SourceExt.equals_lower(PathExt);
386 });
387 bool IsSource = SourceIter != std::end(SourceExtensions);
388
389 auto HeaderIter =
390 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
391 [&PathExt](PathRef HeaderExt) {
392 return HeaderExt.equals_lower(PathExt);
393 });
394
395 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
396
397 // We can only switch between extensions known extensions.
398 if (!IsSource && !IsHeader)
399 return llvm::None;
400
401 // Array to lookup extensions for the switch. An opposite of where original
402 // extension was found.
403 ArrayRef<StringRef> NewExts;
404 if (IsSource)
405 NewExts = HeaderExtensions;
406 else
407 NewExts = SourceExtensions;
408
409 // Storage for the new path.
410 SmallString<128> NewPath = StringRef(Path);
411
412 // Instance of vfs::FileSystem, used for file existence checks.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000413 auto FS = FSProvider.getFileSystem();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000414
415 // Loop through switched extension candidates.
416 for (StringRef NewExt : NewExts) {
417 llvm::sys::path::replace_extension(NewPath, NewExt);
418 if (FS->exists(NewPath))
419 return NewPath.str().str(); // First str() to convert from SmallString to
420 // StringRef, second to convert from StringRef
421 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000422
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000423 // Also check NewExt in upper-case, just in case.
424 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
425 if (FS->exists(NewPath))
426 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000427 }
428
429 return llvm::None;
430}
431
Raoul Wols212bcf82017-12-12 20:25:06 +0000432llvm::Expected<tooling::Replacements>
433ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
434 ArrayRef<tooling::Range> Ranges) {
435 // Call clang-format.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000436 auto FS = FSProvider.getFileSystem();
437 auto Style = format::getStyle("file", File, "LLVM", Code, FS.get());
Eric Liue3395b92018-03-06 10:42:50 +0000438 if (!Style)
439 return Style.takeError();
440
441 tooling::Replacements IncludeReplaces =
442 format::sortIncludes(*Style, Code, Ranges, File);
443 auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
444 if (!Changed)
445 return Changed.takeError();
446
447 return IncludeReplaces.merge(format::reformat(
448 Style.get(), *Changed,
449 tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
450 File));
Raoul Wols212bcf82017-12-12 20:25:06 +0000451}
452
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000453void ClangdServer::findDocumentHighlights(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000454 PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000455
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000456 auto FS = FSProvider.getFileSystem();
457 auto Action = [FS, Pos](Callback<std::vector<DocumentHighlight>> CB,
458 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000459 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000460 return CB(InpAST.takeError());
461 CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000462 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000463
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000464 WorkScheduler.runWithAST("Highlights", File, Bind(Action, std::move(CB)));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000465}
466
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000467void ClangdServer::findHover(PathRef File, Position Pos, Callback<Hover> CB) {
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000468 auto FS = FSProvider.getFileSystem();
469 auto Action = [Pos, FS](Callback<Hover> CB,
470 llvm::Expected<InputsAndAST> InpAST) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000471 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000472 return CB(InpAST.takeError());
473 CB(clangd::getHover(InpAST->AST, Pos));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000474 };
475
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000476 WorkScheduler.runWithAST("Hover", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000477}
478
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000479void ClangdServer::consumeDiagnostics(PathRef File, DocVersion Version,
480 std::vector<Diag> Diags) {
481 // We need to serialize access to resulting diagnostics to avoid calling
482 // `onDiagnosticsReady` in the wrong order.
483 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
484 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[File];
Ilya Biryukov929697b2018-01-25 14:19:21 +0000485
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000486 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
487 // implementation diagnostics will not be reported after version counters'
488 // overflow. This should not happen in practice, since DocVersion is a
489 // 64-bit unsigned integer.
490 if (Version < LastReportedDiagsVersion)
491 return;
492 LastReportedDiagsVersion = Version;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000493
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000494 DiagConsumer.onDiagnosticsReady(File, std::move(Diags));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000495}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000496
497void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
498 // FIXME: Do nothing for now. This will be used for indexing and potentially
499 // invalidating other caches.
500}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000501
502std::vector<std::pair<Path, std::size_t>>
503ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000504 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000505}
Sam McCall0bb24cd2018-02-13 08:59:23 +0000506
507LLVM_NODISCARD bool
508ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
509 return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds));
510}