blob: cd8b3f4a8598809cab6dcb4368be03f17d7c0787 [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"
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000012#include "FindSymbols.h"
Eric Liuc5105f92018-02-16 14:15:55 +000013#include "Headers.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000014#include "SourceCode.h"
Sam McCalla66d2cb2017-12-19 17:06:07 +000015#include "XRefs.h"
Sam McCall0faecf02018-01-15 12:33:00 +000016#include "index/Merge.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000017#include "clang/Format/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000018#include "clang/Frontend/CompilerInstance.h"
19#include "clang/Frontend/CompilerInvocation.h"
20#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +000021#include "clang/Tooling/Refactoring/RefactoringResultConsumer.h"
22#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000023#include "llvm/ADT/ArrayRef.h"
Sam McCallb5f5eb62018-01-25 17:01:39 +000024#include "llvm/ADT/ScopeExit.h"
Benjamin Krameree19f162017-10-26 12:28:13 +000025#include "llvm/Support/Errc.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000026#include "llvm/Support/FileSystem.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000027#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000028#include "llvm/Support/raw_ostream.h"
29#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000030
Ilya Biryukov2f314102017-05-16 10:06:20 +000031using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000032using namespace clang::clangd;
33
Ilya Biryukovafb55542017-05-16 14:40:30 +000034namespace {
35
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000036void ignoreError(llvm::Error Err) {
37 handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
38}
39
Ilya Biryukova46f7a92017-06-28 10:34:50 +000040std::string getStandardResourceDir() {
41 static int Dummy; // Just an address in this process.
42 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
43}
44
Haojian Wu345099c2017-11-09 11:30:04 +000045class RefactoringResultCollector final
46 : public tooling::RefactoringResultConsumer {
47public:
48 void handleError(llvm::Error Err) override {
49 assert(!Result.hasValue());
50 // FIXME: figure out a way to return better message for DiagnosticError.
51 // clangd uses llvm::toString to convert the Err to string, however, for
52 // DiagnosticError, only "clang diagnostic" will be generated.
53 Result = std::move(Err);
54 }
55
56 // Using the handle(SymbolOccurrences) from parent class.
57 using tooling::RefactoringResultConsumer::handle;
58
59 void handle(tooling::AtomicChanges SourceReplacements) override {
60 assert(!Result.hasValue());
61 Result = std::move(SourceReplacements);
62 }
63
64 Optional<Expected<tooling::AtomicChanges>> Result;
65};
66
Ilya Biryukovafb55542017-05-16 14:40:30 +000067} // namespace
68
Sam McCalla7bb0cc2018-03-12 23:22:35 +000069IntrusiveRefCntPtr<vfs::FileSystem> RealFileSystemProvider::getFileSystem() {
70 return vfs::getRealFileSystem();
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000071}
72
Sam McCall7363a2f2018-03-05 17:28:54 +000073ClangdServer::Options ClangdServer::optsForTest() {
74 ClangdServer::Options Opts;
75 Opts.UpdateDebounce = std::chrono::steady_clock::duration::zero(); // Faster!
76 Opts.StorePreamblesInMemory = true;
77 Opts.AsyncThreadsCount = 4; // Consistent!
78 return Opts;
79}
80
Sam McCalladccab62017-11-23 16:58:22 +000081ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
Sam McCalladccab62017-11-23 16:58:22 +000082 FileSystemProvider &FSProvider,
Sam McCall7363a2f2018-03-05 17:28:54 +000083 DiagnosticsConsumer &DiagConsumer,
84 const Options &Opts)
85 : CompileArgs(CDB, Opts.ResourceDir ? Opts.ResourceDir->str()
86 : getStandardResourceDir()),
Ilya Biryukov929697b2018-01-25 14:19:21 +000087 DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Sam McCall7363a2f2018-03-05 17:28:54 +000088 FileIdx(Opts.BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000089 PCHs(std::make_shared<PCHContainerOperations>()),
90 // Pass a callback into `WorkScheduler` to extract symbols from a newly
91 // parsed file and rebuild the file index synchronously each time an AST
92 // is parsed.
Eric Liubfac8f72017-12-19 18:00:37 +000093 // FIXME(ioeric): this can be slow and we may be able to index on less
94 // critical paths.
Sam McCall7363a2f2018-03-05 17:28:54 +000095 WorkScheduler(Opts.AsyncThreadsCount, Opts.StorePreamblesInMemory,
Sam McCalld1a7a372018-01-31 13:40:48 +000096 FileIdx
97 ? [this](PathRef Path,
98 ParsedAST *AST) { FileIdx->update(Path, AST); }
Sam McCalld1e0deb2018-03-02 08:56:37 +000099 : ASTParsedCallback(),
Sam McCall7363a2f2018-03-05 17:28:54 +0000100 Opts.UpdateDebounce) {
101 if (FileIdx && Opts.StaticIndex) {
102 MergedIndex = mergeIndex(FileIdx.get(), Opts.StaticIndex);
Sam McCall0faecf02018-01-15 12:33:00 +0000103 Index = MergedIndex.get();
104 } else if (FileIdx)
105 Index = FileIdx.get();
Sam McCall7363a2f2018-03-05 17:28:54 +0000106 else if (Opts.StaticIndex)
107 Index = Opts.StaticIndex;
Sam McCall0faecf02018-01-15 12:33:00 +0000108 else
109 Index = nullptr;
110}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000111
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000112void ClangdServer::setRootPath(PathRef RootPath) {
113 std::string NewRootPath = llvm::sys::path::convert_to_slash(
114 RootPath, llvm::sys::path::Style::posix);
115 if (llvm::sys::fs::is_directory(NewRootPath))
116 this->RootPath = NewRootPath;
117}
118
Sam McCall568e17f2018-02-22 13:11:12 +0000119void ClangdServer::addDocument(PathRef File, StringRef Contents,
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000120 WantDiagnostics WantDiags, bool SkipCache) {
121 if (SkipCache)
122 CompileArgs.invalidate(File);
123
Simon Marchi9569fd52018-03-16 14:30:42 +0000124 DocVersion Version = ++InternalVersion[File];
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000125 ParseInputs Inputs = {CompileArgs.getCompileCommand(File),
126 FSProvider.getFileSystem(), Contents.str()};
127
128 Path FileStr = File.str();
129 WorkScheduler.update(File, std::move(Inputs), WantDiags,
130 [this, FileStr, Version](std::vector<Diag> Diags) {
131 consumeDiagnostics(FileStr, Version, std::move(Diags));
132 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000133}
134
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000135void ClangdServer::removeDocument(PathRef File) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000136 ++InternalVersion[File];
Ilya Biryukov929697b2018-01-25 14:19:21 +0000137 CompileArgs.invalidate(File);
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000138 WorkScheduler.remove(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000139}
140
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000141void ClangdServer::codeComplete(PathRef File, Position Pos,
142 const clangd::CodeCompleteOptions &Opts,
143 Callback<CompletionList> CB) {
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000144 // Copy completion options for passing them to async task handler.
145 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000146 if (!CodeCompleteOpts.Index) // Respect overridden index.
147 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000148
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000149 // Copy PCHs to avoid accessing this->PCHs concurrently
150 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000151 auto FS = FSProvider.getFileSystem();
Simon Marchi5a48cf82018-03-14 18:31:48 +0000152 auto Task = [PCHs, Pos, FS,
153 CodeCompleteOpts](Path File, Callback<CompletionList> CB,
154 llvm::Expected<InputsAndPreamble> IP) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000155 if (!IP)
156 return CB(IP.takeError());
157
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000158 auto PreambleData = IP->Preamble;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000159
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000160 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
161 // both the old and the new version in case only one of them matches.
162 CompletionList Result = clangd::codeComplete(
Ilya Biryukovf1f3d572018-03-14 17:46:52 +0000163 File, IP->Command, PreambleData ? &PreambleData->Preamble : nullptr,
Simon Marchi5a48cf82018-03-14 18:31:48 +0000164 IP->Contents, Pos, FS, PCHs, CodeCompleteOpts);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000165 CB(std::move(Result));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000166 };
167
Simon Marchi5a48cf82018-03-14 18:31:48 +0000168 WorkScheduler.runWithPreamble("CodeComplete", File,
169 Bind(Task, File.str(), std::move(CB)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000170}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000171
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000172void ClangdServer::signatureHelp(PathRef File, Position Pos,
173 Callback<SignatureHelp> CB) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000174
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000175 auto PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000176 auto FS = FSProvider.getFileSystem();
Simon Marchi5a48cf82018-03-14 18:31:48 +0000177 auto Action = [Pos, FS, PCHs](Path File, Callback<SignatureHelp> CB,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000178 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000179 if (!IP)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000180 return CB(IP.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000181
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000182 auto PreambleData = IP->Preamble;
Ilya Biryukovf1f3d572018-03-14 17:46:52 +0000183 CB(clangd::signatureHelp(File, IP->Command,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000184 PreambleData ? &PreambleData->Preamble : nullptr,
Simon Marchi5a48cf82018-03-14 18:31:48 +0000185 IP->Contents, Pos, FS, PCHs));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000186 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000187
Simon Marchi5a48cf82018-03-14 18:31:48 +0000188 WorkScheduler.runWithPreamble("SignatureHelp", File,
189 Bind(Action, File.str(), std::move(CB)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000190}
191
Raoul Wols212bcf82017-12-12 20:25:06 +0000192llvm::Expected<tooling::Replacements>
193ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Simon Marchi766338a2018-03-21 14:36:46 +0000194 llvm::Expected<size_t> Begin = positionToOffset(Code, Rng.start);
195 if (!Begin)
196 return Begin.takeError();
197 llvm::Expected<size_t> End = positionToOffset(Code, Rng.end);
198 if (!End)
199 return End.takeError();
200 return formatCode(Code, File, {tooling::Range(*Begin, *End - *Begin)});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000201}
202
Raoul Wols212bcf82017-12-12 20:25:06 +0000203llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
204 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000205 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000206 return formatCode(Code, File, {tooling::Range(0, Code.size())});
207}
208
Raoul Wols212bcf82017-12-12 20:25:06 +0000209llvm::Expected<tooling::Replacements>
210ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000211 // Look for the previous opening brace from the character position and
212 // format starting from there.
Simon Marchi766338a2018-03-21 14:36:46 +0000213 llvm::Expected<size_t> CursorPos = positionToOffset(Code, Pos);
214 if (!CursorPos)
215 return CursorPos.takeError();
216 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', *CursorPos);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000217 if (PreviousLBracePos == StringRef::npos)
Simon Marchi766338a2018-03-21 14:36:46 +0000218 PreviousLBracePos = *CursorPos;
219 size_t Len = *CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000220
221 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
222}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000223
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000224void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
225 Callback<std::vector<tooling::Replacement>> CB) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000226 auto Action = [Pos](Path File, std::string NewName,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000227 Callback<std::vector<tooling::Replacement>> CB,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000228 Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000229 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000230 return CB(InpAST.takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000231 auto &AST = InpAST->AST;
232
233 RefactoringResultCollector ResultCollector;
234 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000235 SourceLocation SourceLocationBeg =
Sam McCalla4962cc2018-04-27 11:59:28 +0000236 clangd::getBeginningOfIdentifier(AST, Pos, SourceMgr.getMainFileID());
Haojian Wu345099c2017-11-09 11:30:04 +0000237 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000238 AST.getASTContext().getSourceManager());
239 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000240 auto Rename = clang::tooling::RenameOccurrences::initiate(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000241 Context, SourceRange(SourceLocationBeg), NewName);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000242 if (!Rename)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000243 return CB(Rename.takeError());
Haojian Wu345099c2017-11-09 11:30:04 +0000244
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000245 Rename->invoke(ResultCollector, Context);
246
247 assert(ResultCollector.Result.hasValue());
248 if (!ResultCollector.Result.getValue())
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000249 return CB(ResultCollector.Result->takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000250
251 std::vector<tooling::Replacement> Replacements;
252 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
253 tooling::Replacements ChangeReps = Change.getReplacements();
254 for (const auto &Rep : ChangeReps) {
255 // FIXME: Right now we only support renaming the main file, so we
256 // drop replacements not for the main file. In the future, we might
257 // consider to support:
258 // * rename in any included header
259 // * rename only in the "main" header
260 // * provide an error if there are symbols we won't rename (e.g.
261 // std::vector)
262 // * rename globally in project
263 // * rename in open files
264 if (Rep.getFilePath() == File)
265 Replacements.push_back(Rep);
266 }
Haojian Wu345099c2017-11-09 11:30:04 +0000267 }
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000268 return CB(std::move(Replacements));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000269 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000270
271 WorkScheduler.runWithAST(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000272 "Rename", File, Bind(Action, File.str(), NewName.str(), std::move(CB)));
Haojian Wu345099c2017-11-09 11:30:04 +0000273}
274
Eric Liu6c8e8582018-02-26 08:32:13 +0000275/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
276/// include.
277static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
278 llvm::StringRef HintPath) {
279 if (isLiteralInclude(Header))
280 return HeaderFile{Header.str(), /*Verbatim=*/true};
281 auto U = URI::parse(Header);
282 if (!U)
283 return U.takeError();
Haojian Wue9a5a2f2018-04-09 15:09:44 +0000284
285 auto IncludePath = URI::includeSpelling(*U);
286 if (!IncludePath)
287 return IncludePath.takeError();
288 if (!IncludePath->empty())
289 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
290
Eric Liu6c8e8582018-02-26 08:32:13 +0000291 auto Resolved = URI::resolve(*U, HintPath);
292 if (!Resolved)
293 return Resolved.takeError();
294 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
Haojian Wu33caf892018-03-06 12:56:18 +0000295}
Eric Liu6c8e8582018-02-26 08:32:13 +0000296
Eric Liuc5105f92018-02-16 14:15:55 +0000297Expected<tooling::Replacements>
298ClangdServer::insertInclude(PathRef File, StringRef Code,
Eric Liu6c8e8582018-02-26 08:32:13 +0000299 StringRef DeclaringHeader,
300 StringRef InsertedHeader) {
301 assert(!DeclaringHeader.empty() && !InsertedHeader.empty());
Eric Liuc5105f92018-02-16 14:15:55 +0000302 std::string ToInclude;
Eric Liu6c8e8582018-02-26 08:32:13 +0000303 auto ResolvedOrginal = toHeaderFile(DeclaringHeader, File);
304 if (!ResolvedOrginal)
305 return ResolvedOrginal.takeError();
306 auto ResolvedPreferred = toHeaderFile(InsertedHeader, File);
307 if (!ResolvedPreferred)
308 return ResolvedPreferred.takeError();
309 tooling::CompileCommand CompileCommand = CompileArgs.getCompileCommand(File);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000310 auto Include =
311 calculateIncludePath(File, Code, *ResolvedOrginal, *ResolvedPreferred,
312 CompileCommand, FSProvider.getFileSystem());
Eric Liu6c8e8582018-02-26 08:32:13 +0000313 if (!Include)
314 return Include.takeError();
315 if (Include->empty())
316 return tooling::Replacements();
317 ToInclude = std::move(*Include);
Eric Liuc5105f92018-02-16 14:15:55 +0000318
319 auto Style = format::getStyle("file", File, "llvm");
320 if (!Style) {
321 llvm::consumeError(Style.takeError());
322 // FIXME(ioeric): needs more consistent style support in clangd server.
323 Style = format::getLLVMStyle();
324 }
325 // Replacement with offset UINT_MAX and length 0 will be treated as include
326 // insertion.
327 tooling::Replacement R(File, /*Offset=*/UINT_MAX, 0, "#include " + ToInclude);
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000328 auto Replaces =
329 format::cleanupAroundReplacements(Code, tooling::Replacements(R), *Style);
Eric Liue3395b92018-03-06 10:42:50 +0000330 if (!Replaces)
331 return Replaces;
332 return formatReplacements(Code, *Replaces, *Style);
Eric Liuc5105f92018-02-16 14:15:55 +0000333}
334
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000335void ClangdServer::dumpAST(PathRef File,
336 UniqueFunction<void(std::string)> Callback) {
337 auto Action = [](decltype(Callback) Callback,
338 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000339 if (!InpAST) {
340 ignoreError(InpAST.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000341 return Callback("<no-ast>");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000342 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000343 std::string Result;
344
345 llvm::raw_string_ostream ResultOS(Result);
346 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000347 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000348
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000349 Callback(Result);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000350 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000351
Sam McCall091557d2018-02-23 07:54:17 +0000352 WorkScheduler.runWithAST("DumpAST", File, Bind(Action, std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000353}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000354
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000355void ClangdServer::findDefinitions(PathRef File, Position Pos,
356 Callback<std::vector<Location>> CB) {
357 auto FS = FSProvider.getFileSystem();
358 auto Action = [Pos, FS](Callback<std::vector<Location>> CB,
359 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000360 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000361 return CB(InpAST.takeError());
362 CB(clangd::findDefinitions(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000363 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000364
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000365 WorkScheduler.runWithAST("Definitions", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000366}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000367
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000368llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
369
370 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
371 ".c++", ".m", ".mm"};
372 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
373
374 StringRef PathExt = llvm::sys::path::extension(Path);
375
376 // Lookup in a list of known extensions.
377 auto SourceIter =
378 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
379 [&PathExt](PathRef SourceExt) {
380 return SourceExt.equals_lower(PathExt);
381 });
382 bool IsSource = SourceIter != std::end(SourceExtensions);
383
384 auto HeaderIter =
385 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
386 [&PathExt](PathRef HeaderExt) {
387 return HeaderExt.equals_lower(PathExt);
388 });
389
390 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
391
392 // We can only switch between extensions known extensions.
393 if (!IsSource && !IsHeader)
394 return llvm::None;
395
396 // Array to lookup extensions for the switch. An opposite of where original
397 // extension was found.
398 ArrayRef<StringRef> NewExts;
399 if (IsSource)
400 NewExts = HeaderExtensions;
401 else
402 NewExts = SourceExtensions;
403
404 // Storage for the new path.
405 SmallString<128> NewPath = StringRef(Path);
406
407 // Instance of vfs::FileSystem, used for file existence checks.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000408 auto FS = FSProvider.getFileSystem();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000409
410 // Loop through switched extension candidates.
411 for (StringRef NewExt : NewExts) {
412 llvm::sys::path::replace_extension(NewPath, NewExt);
413 if (FS->exists(NewPath))
414 return NewPath.str().str(); // First str() to convert from SmallString to
415 // StringRef, second to convert from StringRef
416 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000417
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000418 // Also check NewExt in upper-case, just in case.
419 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
420 if (FS->exists(NewPath))
421 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000422 }
423
424 return llvm::None;
425}
426
Raoul Wols212bcf82017-12-12 20:25:06 +0000427llvm::Expected<tooling::Replacements>
428ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
429 ArrayRef<tooling::Range> Ranges) {
430 // Call clang-format.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000431 auto FS = FSProvider.getFileSystem();
432 auto Style = format::getStyle("file", File, "LLVM", Code, FS.get());
Eric Liue3395b92018-03-06 10:42:50 +0000433 if (!Style)
434 return Style.takeError();
435
436 tooling::Replacements IncludeReplaces =
437 format::sortIncludes(*Style, Code, Ranges, File);
438 auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
439 if (!Changed)
440 return Changed.takeError();
441
442 return IncludeReplaces.merge(format::reformat(
443 Style.get(), *Changed,
444 tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
445 File));
Raoul Wols212bcf82017-12-12 20:25:06 +0000446}
447
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000448void ClangdServer::findDocumentHighlights(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000449 PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000450
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000451 auto FS = FSProvider.getFileSystem();
452 auto Action = [FS, Pos](Callback<std::vector<DocumentHighlight>> CB,
453 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000454 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000455 return CB(InpAST.takeError());
456 CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000457 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000458
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000459 WorkScheduler.runWithAST("Highlights", File, Bind(Action, std::move(CB)));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000460}
461
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000462void ClangdServer::findHover(PathRef File, Position Pos, Callback<Hover> CB) {
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000463 auto FS = FSProvider.getFileSystem();
464 auto Action = [Pos, FS](Callback<Hover> CB,
465 llvm::Expected<InputsAndAST> InpAST) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000466 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000467 return CB(InpAST.takeError());
468 CB(clangd::getHover(InpAST->AST, Pos));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000469 };
470
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000471 WorkScheduler.runWithAST("Hover", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000472}
473
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000474void ClangdServer::consumeDiagnostics(PathRef File, DocVersion Version,
475 std::vector<Diag> Diags) {
476 // We need to serialize access to resulting diagnostics to avoid calling
477 // `onDiagnosticsReady` in the wrong order.
478 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
479 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[File];
Ilya Biryukov929697b2018-01-25 14:19:21 +0000480
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000481 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
482 // implementation diagnostics will not be reported after version counters'
483 // overflow. This should not happen in practice, since DocVersion is a
484 // 64-bit unsigned integer.
485 if (Version < LastReportedDiagsVersion)
486 return;
487 LastReportedDiagsVersion = Version;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000488
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000489 DiagConsumer.onDiagnosticsReady(File, std::move(Diags));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000490}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000491
492void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
493 // FIXME: Do nothing for now. This will be used for indexing and potentially
494 // invalidating other caches.
495}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000496
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000497void ClangdServer::workspaceSymbols(
498 StringRef Query, int Limit, Callback<std::vector<SymbolInformation>> CB) {
499 CB(clangd::getWorkspaceSymbols(Query, Limit, Index));
500}
501
Ilya Biryukovdf842342018-01-25 14:32:21 +0000502std::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}