blob: 7090bc16507e996c67227cb4e13cede2f807be14 [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"
Sam McCallb536a2a2017-12-19 12:23:48 +000012#include "SourceCode.h"
Sam McCalla66d2cb2017-12-19 17:06:07 +000013#include "XRefs.h"
Sam McCall0faecf02018-01-15 12:33:00 +000014#include "index/Merge.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000015#include "clang/Format/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000016#include "clang/Frontend/CompilerInstance.h"
17#include "clang/Frontend/CompilerInvocation.h"
18#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +000019#include "clang/Tooling/Refactoring/RefactoringResultConsumer.h"
20#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000021#include "llvm/ADT/ArrayRef.h"
Sam McCallb5f5eb62018-01-25 17:01:39 +000022#include "llvm/ADT/ScopeExit.h"
Benjamin Krameree19f162017-10-26 12:28:13 +000023#include "llvm/Support/Errc.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000024#include "llvm/Support/FileSystem.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000025#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000026#include "llvm/Support/raw_ostream.h"
27#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000028
Ilya Biryukov2f314102017-05-16 10:06:20 +000029using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000030using namespace clang::clangd;
31
Ilya Biryukovafb55542017-05-16 14:40:30 +000032namespace {
33
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000034// Issues an async read of AST and waits for results.
35template <class Ret, class Func>
36Ret blockingRunWithAST(TUScheduler &S, PathRef File, Func &&F) {
Ilya Biryukov25258702018-01-31 11:26:43 +000037 // Using shared_ptr to workaround MSVC bug. It requires future<> arguments to
38 // have default and copy ctor.
39 auto SharedPtrFunc = [&](llvm::Expected<InputsAndAST> Arg) {
40 return std::make_shared<Ret>(F(std::move(Arg)));
41 };
42 std::packaged_task<std::shared_ptr<Ret>(llvm::Expected<InputsAndAST>)> Task(
43 SharedPtrFunc);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000044 auto Future = Task.get_future();
45 S.runWithAST(File, std::move(Task));
Ilya Biryukov25258702018-01-31 11:26:43 +000046 return std::move(*Future.get());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000047}
48
49// Issues an async read of preamble and waits for results.
50template <class Ret, class Func>
51Ret blockingRunWithPreamble(TUScheduler &S, PathRef File, Func &&F) {
Ilya Biryukov25258702018-01-31 11:26:43 +000052 // Using shared_ptr to workaround MSVC bug. It requires future<> arguments to
53 // have default and copy ctor.
54 auto SharedPtrFunc = [&](llvm::Expected<InputsAndPreamble> Arg) {
55 return std::make_shared<Ret>(F(std::move(Arg)));
56 };
57 std::packaged_task<std::shared_ptr<Ret>(llvm::Expected<InputsAndPreamble>)>
58 Task(SharedPtrFunc);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000059 auto Future = Task.get_future();
60 S.runWithPreamble(File, std::move(Task));
Ilya Biryukov25258702018-01-31 11:26:43 +000061 return std::move(*Future.get());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000062}
63
64void ignoreError(llvm::Error Err) {
65 handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
66}
67
Ilya Biryukova46f7a92017-06-28 10:34:50 +000068std::string getStandardResourceDir() {
69 static int Dummy; // Just an address in this process.
70 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
71}
72
Haojian Wu345099c2017-11-09 11:30:04 +000073class RefactoringResultCollector final
74 : public tooling::RefactoringResultConsumer {
75public:
76 void handleError(llvm::Error Err) override {
77 assert(!Result.hasValue());
78 // FIXME: figure out a way to return better message for DiagnosticError.
79 // clangd uses llvm::toString to convert the Err to string, however, for
80 // DiagnosticError, only "clang diagnostic" will be generated.
81 Result = std::move(Err);
82 }
83
84 // Using the handle(SymbolOccurrences) from parent class.
85 using tooling::RefactoringResultConsumer::handle;
86
87 void handle(tooling::AtomicChanges SourceReplacements) override {
88 assert(!Result.hasValue());
89 Result = std::move(SourceReplacements);
90 }
91
92 Optional<Expected<tooling::AtomicChanges>> Result;
93};
94
Ilya Biryukovafb55542017-05-16 14:40:30 +000095} // namespace
96
Ilya Biryukov22602992017-05-30 15:11:02 +000097Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000098RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000099 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000100}
101
Sam McCalladccab62017-11-23 16:58:22 +0000102ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
103 DiagnosticsConsumer &DiagConsumer,
104 FileSystemProvider &FSProvider,
105 unsigned AsyncThreadsCount,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000106 bool StorePreamblesInMemory,
Haojian Wuba28e9a2018-01-10 14:44:34 +0000107 bool BuildDynamicSymbolIndex, SymbolIndex *StaticIdx,
Sam McCalladccab62017-11-23 16:58:22 +0000108 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukov929697b2018-01-25 14:19:21 +0000109 : CompileArgs(CDB,
110 ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
111 DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Eric Liubfac8f72017-12-19 18:00:37 +0000112 FileIdx(BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000113 PCHs(std::make_shared<PCHContainerOperations>()),
114 // Pass a callback into `WorkScheduler` to extract symbols from a newly
115 // parsed file and rebuild the file index synchronously each time an AST
116 // is parsed.
Eric Liubfac8f72017-12-19 18:00:37 +0000117 // FIXME(ioeric): this can be slow and we may be able to index on less
118 // critical paths.
Sam McCalld1a7a372018-01-31 13:40:48 +0000119 WorkScheduler(AsyncThreadsCount, StorePreamblesInMemory,
120 FileIdx
121 ? [this](PathRef Path,
122 ParsedAST *AST) { FileIdx->update(Path, AST); }
123 : ASTParsedCallback()) {
Sam McCall0faecf02018-01-15 12:33:00 +0000124 if (FileIdx && StaticIdx) {
125 MergedIndex = mergeIndex(FileIdx.get(), StaticIdx);
126 Index = MergedIndex.get();
127 } else if (FileIdx)
128 Index = FileIdx.get();
129 else if (StaticIdx)
130 Index = StaticIdx;
131 else
132 Index = nullptr;
133}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000134
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000135void ClangdServer::setRootPath(PathRef RootPath) {
136 std::string NewRootPath = llvm::sys::path::convert_to_slash(
137 RootPath, llvm::sys::path::Style::posix);
138 if (llvm::sys::fs::is_directory(NewRootPath))
139 this->RootPath = NewRootPath;
140}
141
Sam McCalld1a7a372018-01-31 13:40:48 +0000142std::future<void> ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000143 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000144 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Sam McCalld1a7a372018-01-31 13:40:48 +0000145 return scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000146 std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000147}
148
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000149void ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000150 DraftMgr.removeDraft(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000151 CompileArgs.invalidate(File);
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000152 WorkScheduler.remove(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000153}
154
Sam McCalld1a7a372018-01-31 13:40:48 +0000155std::future<void> ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000156 auto FileContents = DraftMgr.getDraft(File);
157 assert(FileContents.Draft &&
158 "forceReparse() was called for non-added document");
159
Ilya Biryukov929697b2018-01-25 14:19:21 +0000160 // forceReparse promises to request new compilation flags from CDB, so we
161 // remove any cahced flags.
162 CompileArgs.invalidate(File);
163
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000164 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Sam McCalld1a7a372018-01-31 13:40:48 +0000165 return scheduleReparseAndDiags(File, std::move(FileContents),
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000166 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000167}
168
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000169void ClangdServer::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000170 PathRef File, Position Pos, const clangd::CodeCompleteOptions &Opts,
171 UniqueFunction<void(Tagged<CompletionList>)> Callback,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000172 llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000173 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000174 using CallbackType = UniqueFunction<void(Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000175
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000176 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000177 if (UsedFS)
178 *UsedFS = TaggedFS.Value;
179
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000180 // Copy completion options for passing them to async task handler.
181 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000182 if (!CodeCompleteOpts.Index) // Respect overridden index.
183 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000184
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000185 std::string Contents;
186 if (OverridenContents) {
187 Contents = OverridenContents->str();
188 } else {
189 VersionedDraft Latest = DraftMgr.getDraft(File);
190 assert(Latest.Draft && "codeComplete called for non-added document");
191 Contents = *Latest.Draft;
192 }
193
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000194 // Copy PCHs to avoid accessing this->PCHs concurrently
195 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000196 auto Task = [PCHs, Pos, TaggedFS, CodeCompleteOpts](
Sam McCalld1a7a372018-01-31 13:40:48 +0000197 std::string Contents, Path File, CallbackType Callback,
198 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000199 assert(IP && "error when trying to read preamble for codeComplete");
200 auto PreambleData = IP->Preamble;
201 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000202
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000203 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
204 // both the old and the new version in case only one of them matches.
205 CompletionList Result = clangd::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000206 File, Command, PreambleData ? &PreambleData->Preamble : nullptr,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000207 Contents, Pos, TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000208
Sam McCalld1a7a372018-01-31 13:40:48 +0000209 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000210 };
211
Sam McCalld1a7a372018-01-31 13:40:48 +0000212 WorkScheduler.runWithPreamble(File, BindWithForward(Task, std::move(Contents),
213 File.str(),
214 std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000215}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000216
Benjamin Krameree19f162017-10-26 12:28:13 +0000217llvm::Expected<Tagged<SignatureHelp>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000218ClangdServer::signatureHelp(PathRef File, Position Pos,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000219 llvm::Optional<StringRef> OverridenContents,
220 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000221 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
222 if (UsedFS)
223 *UsedFS = TaggedFS.Value;
224
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000225 std::string Contents;
226 if (OverridenContents) {
227 Contents = OverridenContents->str();
228 } else {
229 VersionedDraft Latest = DraftMgr.getDraft(File);
230 if (!Latest.Draft)
231 return llvm::make_error<llvm::StringError>(
232 "signatureHelp is called for non-added document",
233 llvm::errc::invalid_argument);
234 Contents = std::move(*Latest.Draft);
235 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000236
Sam McCalld1a7a372018-01-31 13:40:48 +0000237 auto Action = [=](llvm::Expected<InputsAndPreamble> IP)
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000238 -> Expected<Tagged<SignatureHelp>> {
239 if (!IP)
240 return IP.takeError();
241 auto PreambleData = IP->Preamble;
242 auto &Command = IP->Inputs.CompileCommand;
243
244 return make_tagged(
Sam McCalld1a7a372018-01-31 13:40:48 +0000245 clangd::signatureHelp(File, Command,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000246 PreambleData ? &PreambleData->Preamble : nullptr,
247 Contents, Pos, TaggedFS.Value, PCHs),
248 TaggedFS.Tag);
249 };
250 return blockingRunWithPreamble<Expected<Tagged<SignatureHelp>>>(WorkScheduler,
251 File, Action);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000252}
253
Raoul Wols212bcf82017-12-12 20:25:06 +0000254llvm::Expected<tooling::Replacements>
255ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000256 size_t Begin = positionToOffset(Code, Rng.start);
257 size_t Len = positionToOffset(Code, Rng.end) - Begin;
258 return formatCode(Code, File, {tooling::Range(Begin, Len)});
259}
260
Raoul Wols212bcf82017-12-12 20:25:06 +0000261llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
262 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000263 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000264 return formatCode(Code, File, {tooling::Range(0, Code.size())});
265}
266
Raoul Wols212bcf82017-12-12 20:25:06 +0000267llvm::Expected<tooling::Replacements>
268ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000269 // Look for the previous opening brace from the character position and
270 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000271 size_t CursorPos = positionToOffset(Code, Pos);
272 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
273 if (PreviousLBracePos == StringRef::npos)
274 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000275 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000276
277 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
278}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000279
Haojian Wu345099c2017-11-09 11:30:04 +0000280Expected<std::vector<tooling::Replacement>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000281ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000282 using RetType = Expected<std::vector<tooling::Replacement>>;
283 auto Action = [=](Expected<InputsAndAST> InpAST) -> RetType {
284 if (!InpAST)
285 return InpAST.takeError();
286 auto &AST = InpAST->AST;
287
288 RefactoringResultCollector ResultCollector;
289 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000290 const FileEntry *FE =
291 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
292 if (!FE)
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000293 return llvm::make_error<llvm::StringError>(
294 "rename called for non-added document", llvm::errc::invalid_argument);
Haojian Wu345099c2017-11-09 11:30:04 +0000295 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000296 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000297 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000298 AST.getASTContext().getSourceManager());
299 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000300 auto Rename = clang::tooling::RenameOccurrences::initiate(
301 Context, SourceRange(SourceLocationBeg), NewName.str());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000302 if (!Rename)
303 return Rename.takeError();
Haojian Wu345099c2017-11-09 11:30:04 +0000304
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000305 Rename->invoke(ResultCollector, Context);
306
307 assert(ResultCollector.Result.hasValue());
308 if (!ResultCollector.Result.getValue())
309 return ResultCollector.Result->takeError();
310
311 std::vector<tooling::Replacement> Replacements;
312 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
313 tooling::Replacements ChangeReps = Change.getReplacements();
314 for (const auto &Rep : ChangeReps) {
315 // FIXME: Right now we only support renaming the main file, so we
316 // drop replacements not for the main file. In the future, we might
317 // consider to support:
318 // * rename in any included header
319 // * rename only in the "main" header
320 // * provide an error if there are symbols we won't rename (e.g.
321 // std::vector)
322 // * rename globally in project
323 // * rename in open files
324 if (Rep.getFilePath() == File)
325 Replacements.push_back(Rep);
326 }
Haojian Wu345099c2017-11-09 11:30:04 +0000327 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000328 return Replacements;
329 };
330 return blockingRunWithAST<RetType>(WorkScheduler, File, std::move(Action));
Haojian Wu345099c2017-11-09 11:30:04 +0000331}
332
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000333llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
334 auto Latest = DraftMgr.getDraft(File);
335 if (!Latest.Draft)
336 return llvm::None;
337 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000338}
339
Ilya Biryukovf01af682017-05-23 13:42:59 +0000340std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000341 auto Action = [](llvm::Expected<InputsAndAST> InpAST) -> std::string {
342 if (!InpAST) {
343 ignoreError(InpAST.takeError());
344 return "<no-ast>";
Ilya Biryukov02d58702017-08-01 15:51:38 +0000345 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000346
347 std::string Result;
348
349 llvm::raw_string_ostream ResultOS(Result);
350 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000351 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000352
353 return Result;
354 };
355 return blockingRunWithAST<std::string>(WorkScheduler, File,
356 std::move(Action));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000357}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000358
Benjamin Krameree19f162017-10-26 12:28:13 +0000359llvm::Expected<Tagged<std::vector<Location>>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000360ClangdServer::findDefinitions(PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000361 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
362
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000363 using RetType = llvm::Expected<Tagged<std::vector<Location>>>;
Sam McCalld1a7a372018-01-31 13:40:48 +0000364 auto Action = [=](llvm::Expected<InputsAndAST> InpAST) -> RetType {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000365 if (!InpAST)
366 return InpAST.takeError();
Sam McCalld1a7a372018-01-31 13:40:48 +0000367 auto Result = clangd::findDefinitions(InpAST->AST, Pos);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000368 return make_tagged(std::move(Result), TaggedFS.Tag);
369 };
370 return blockingRunWithAST<RetType>(WorkScheduler, File, Action);
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.
413 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
414
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.
436 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
437 auto StyleOrError =
438 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
439 if (!StyleOrError) {
440 return StyleOrError.takeError();
441 } else {
442 return format::reformat(StyleOrError.get(), Code, Ranges, File);
443 }
444}
445
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000446llvm::Expected<Tagged<std::vector<DocumentHighlight>>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000447ClangdServer::findDocumentHighlights(PathRef File, Position Pos) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000448 auto FileContents = DraftMgr.getDraft(File);
449 if (!FileContents.Draft)
450 return llvm::make_error<llvm::StringError>(
451 "findDocumentHighlights called on non-added file",
452 llvm::errc::invalid_argument);
453
454 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
455
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000456 using RetType = llvm::Expected<Tagged<std::vector<DocumentHighlight>>>;
Sam McCalld1a7a372018-01-31 13:40:48 +0000457 auto Action = [=](llvm::Expected<InputsAndAST> InpAST) -> RetType {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000458 if (!InpAST)
459 return InpAST.takeError();
Sam McCalld1a7a372018-01-31 13:40:48 +0000460 auto Result = clangd::findDocumentHighlights(InpAST->AST, Pos);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000461 return make_tagged(std::move(Result), TaggedFS.Tag);
462 };
463 return blockingRunWithAST<RetType>(WorkScheduler, File, Action);
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000464}
465
Sam McCalld1a7a372018-01-31 13:40:48 +0000466std::future<void> ClangdServer::scheduleReparseAndDiags(
467 PathRef File, VersionedDraft Contents,
Ilya Biryukov929697b2018-01-25 14:19:21 +0000468 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000469 tooling::CompileCommand Command = CompileArgs.getCompileCommand(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000470
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000471 using OptDiags = llvm::Optional<std::vector<DiagWithFixIts>>;
472
473 DocVersion Version = Contents.Version;
474 Path FileStr = File.str();
475 VFSTag Tag = std::move(TaggedFS.Tag);
476
Sam McCalld1a7a372018-01-31 13:40:48 +0000477 std::promise<void> DonePromise;
478 std::future<void> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000479
Sam McCalld1a7a372018-01-31 13:40:48 +0000480 auto Callback = [this, Version, FileStr, Tag](std::promise<void> DonePromise,
481 OptDiags Diags) {
482 auto Guard = llvm::make_scope_exit([&]() { DonePromise.set_value(); });
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000483 if (!Diags)
484 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000485
486 // We need to serialize access to resulting diagnostics to avoid calling
487 // `onDiagnosticsReady` in the wrong order.
488 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
489 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
490 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
491 // implementation diagnostics will not be reported after version counters'
492 // overflow. This should not happen in practice, since DocVersion is a
493 // 64-bit unsigned integer.
494 if (Version < LastReportedDiagsVersion)
495 return;
496 LastReportedDiagsVersion = Version;
497
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000498 DiagConsumer.onDiagnosticsReady(
Sam McCalld1a7a372018-01-31 13:40:48 +0000499 FileStr, make_tagged(std::move(*Diags), std::move(Tag)));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000500 };
501
Sam McCalld1a7a372018-01-31 13:40:48 +0000502 WorkScheduler.update(File,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000503 ParseInputs{std::move(Command),
504 std::move(TaggedFS.Value),
505 std::move(*Contents.Draft)},
506 BindWithForward(Callback, std::move(DonePromise)));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000507 return DoneFuture;
508}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000509
510void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
511 // FIXME: Do nothing for now. This will be used for indexing and potentially
512 // invalidating other caches.
513}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000514
515std::vector<std::pair<Path, std::size_t>>
516ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000517 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000518}