blob: 96b75b189d64aa4da510cdba9134c141af5bd483 [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
Sam McCalld1a7a372018-01-31 13:40:48 +0000169std::future<Tagged<CompletionList>>
170ClangdServer::codeComplete(PathRef File, Position Pos,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000171 const clangd::CodeCompleteOptions &Opts,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000172 llvm::Optional<StringRef> OverridenContents,
173 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000174 std::promise<Tagged<CompletionList>> ResultPromise;
175 auto Callback = [](std::promise<Tagged<CompletionList>> ResultPromise,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000176 Tagged<CompletionList> Result) -> void {
Sam McCalld1a7a372018-01-31 13:40:48 +0000177 ResultPromise.set_value(std::move(Result));
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000178 };
179
Sam McCalld1a7a372018-01-31 13:40:48 +0000180 auto ResultFuture = ResultPromise.get_future();
181 codeComplete(File, Pos, Opts,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000182 BindWithForward(Callback, std::move(ResultPromise)),
183 OverridenContents, UsedFS);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000184 return ResultFuture;
185}
186
187void ClangdServer::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000188 PathRef File, Position Pos, const clangd::CodeCompleteOptions &Opts,
189 UniqueFunction<void(Tagged<CompletionList>)> Callback,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000190 llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000191 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000192 using CallbackType = UniqueFunction<void(Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000193
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000194 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000195 if (UsedFS)
196 *UsedFS = TaggedFS.Value;
197
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000198 // Copy completion options for passing them to async task handler.
199 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000200 if (!CodeCompleteOpts.Index) // Respect overridden index.
201 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000202
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000203 std::string Contents;
204 if (OverridenContents) {
205 Contents = OverridenContents->str();
206 } else {
207 VersionedDraft Latest = DraftMgr.getDraft(File);
208 assert(Latest.Draft && "codeComplete called for non-added document");
209 Contents = *Latest.Draft;
210 }
211
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000212 // Copy PCHs to avoid accessing this->PCHs concurrently
213 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000214 auto Task = [PCHs, Pos, TaggedFS, CodeCompleteOpts](
Sam McCalld1a7a372018-01-31 13:40:48 +0000215 std::string Contents, Path File, CallbackType Callback,
216 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000217 assert(IP && "error when trying to read preamble for codeComplete");
218 auto PreambleData = IP->Preamble;
219 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000220
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000221 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
222 // both the old and the new version in case only one of them matches.
223 CompletionList Result = clangd::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000224 File, Command, PreambleData ? &PreambleData->Preamble : nullptr,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000225 Contents, Pos, TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000226
Sam McCalld1a7a372018-01-31 13:40:48 +0000227 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000228 };
229
Sam McCalld1a7a372018-01-31 13:40:48 +0000230 WorkScheduler.runWithPreamble(File, BindWithForward(Task, std::move(Contents),
231 File.str(),
232 std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000233}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000234
Benjamin Krameree19f162017-10-26 12:28:13 +0000235llvm::Expected<Tagged<SignatureHelp>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000236ClangdServer::signatureHelp(PathRef File, Position Pos,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000237 llvm::Optional<StringRef> OverridenContents,
238 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000239 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
240 if (UsedFS)
241 *UsedFS = TaggedFS.Value;
242
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000243 std::string Contents;
244 if (OverridenContents) {
245 Contents = OverridenContents->str();
246 } else {
247 VersionedDraft Latest = DraftMgr.getDraft(File);
248 if (!Latest.Draft)
249 return llvm::make_error<llvm::StringError>(
250 "signatureHelp is called for non-added document",
251 llvm::errc::invalid_argument);
252 Contents = std::move(*Latest.Draft);
253 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000254
Sam McCalld1a7a372018-01-31 13:40:48 +0000255 auto Action = [=](llvm::Expected<InputsAndPreamble> IP)
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000256 -> Expected<Tagged<SignatureHelp>> {
257 if (!IP)
258 return IP.takeError();
259 auto PreambleData = IP->Preamble;
260 auto &Command = IP->Inputs.CompileCommand;
261
262 return make_tagged(
Sam McCalld1a7a372018-01-31 13:40:48 +0000263 clangd::signatureHelp(File, Command,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000264 PreambleData ? &PreambleData->Preamble : nullptr,
265 Contents, Pos, TaggedFS.Value, PCHs),
266 TaggedFS.Tag);
267 };
268 return blockingRunWithPreamble<Expected<Tagged<SignatureHelp>>>(WorkScheduler,
269 File, Action);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000270}
271
Raoul Wols212bcf82017-12-12 20:25:06 +0000272llvm::Expected<tooling::Replacements>
273ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000274 size_t Begin = positionToOffset(Code, Rng.start);
275 size_t Len = positionToOffset(Code, Rng.end) - Begin;
276 return formatCode(Code, File, {tooling::Range(Begin, Len)});
277}
278
Raoul Wols212bcf82017-12-12 20:25:06 +0000279llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
280 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000281 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000282 return formatCode(Code, File, {tooling::Range(0, Code.size())});
283}
284
Raoul Wols212bcf82017-12-12 20:25:06 +0000285llvm::Expected<tooling::Replacements>
286ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000287 // Look for the previous opening brace from the character position and
288 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000289 size_t CursorPos = positionToOffset(Code, Pos);
290 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
291 if (PreviousLBracePos == StringRef::npos)
292 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000293 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000294
295 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
296}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000297
Haojian Wu345099c2017-11-09 11:30:04 +0000298Expected<std::vector<tooling::Replacement>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000299ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000300 using RetType = Expected<std::vector<tooling::Replacement>>;
301 auto Action = [=](Expected<InputsAndAST> InpAST) -> RetType {
302 if (!InpAST)
303 return InpAST.takeError();
304 auto &AST = InpAST->AST;
305
306 RefactoringResultCollector ResultCollector;
307 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000308 const FileEntry *FE =
309 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
310 if (!FE)
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000311 return llvm::make_error<llvm::StringError>(
312 "rename called for non-added document", llvm::errc::invalid_argument);
Haojian Wu345099c2017-11-09 11:30:04 +0000313 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000314 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000315 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000316 AST.getASTContext().getSourceManager());
317 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000318 auto Rename = clang::tooling::RenameOccurrences::initiate(
319 Context, SourceRange(SourceLocationBeg), NewName.str());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000320 if (!Rename)
321 return Rename.takeError();
Haojian Wu345099c2017-11-09 11:30:04 +0000322
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000323 Rename->invoke(ResultCollector, Context);
324
325 assert(ResultCollector.Result.hasValue());
326 if (!ResultCollector.Result.getValue())
327 return ResultCollector.Result->takeError();
328
329 std::vector<tooling::Replacement> Replacements;
330 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
331 tooling::Replacements ChangeReps = Change.getReplacements();
332 for (const auto &Rep : ChangeReps) {
333 // FIXME: Right now we only support renaming the main file, so we
334 // drop replacements not for the main file. In the future, we might
335 // consider to support:
336 // * rename in any included header
337 // * rename only in the "main" header
338 // * provide an error if there are symbols we won't rename (e.g.
339 // std::vector)
340 // * rename globally in project
341 // * rename in open files
342 if (Rep.getFilePath() == File)
343 Replacements.push_back(Rep);
344 }
Haojian Wu345099c2017-11-09 11:30:04 +0000345 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000346 return Replacements;
347 };
348 return blockingRunWithAST<RetType>(WorkScheduler, File, std::move(Action));
Haojian Wu345099c2017-11-09 11:30:04 +0000349}
350
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000351llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
352 auto Latest = DraftMgr.getDraft(File);
353 if (!Latest.Draft)
354 return llvm::None;
355 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000356}
357
Ilya Biryukovf01af682017-05-23 13:42:59 +0000358std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000359 auto Action = [](llvm::Expected<InputsAndAST> InpAST) -> std::string {
360 if (!InpAST) {
361 ignoreError(InpAST.takeError());
362 return "<no-ast>";
Ilya Biryukov02d58702017-08-01 15:51:38 +0000363 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000364
365 std::string Result;
366
367 llvm::raw_string_ostream ResultOS(Result);
368 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000369 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000370
371 return Result;
372 };
373 return blockingRunWithAST<std::string>(WorkScheduler, File,
374 std::move(Action));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000375}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000376
Benjamin Krameree19f162017-10-26 12:28:13 +0000377llvm::Expected<Tagged<std::vector<Location>>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000378ClangdServer::findDefinitions(PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000379 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
380
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000381 using RetType = llvm::Expected<Tagged<std::vector<Location>>>;
Sam McCalld1a7a372018-01-31 13:40:48 +0000382 auto Action = [=](llvm::Expected<InputsAndAST> InpAST) -> RetType {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000383 if (!InpAST)
384 return InpAST.takeError();
Sam McCalld1a7a372018-01-31 13:40:48 +0000385 auto Result = clangd::findDefinitions(InpAST->AST, Pos);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000386 return make_tagged(std::move(Result), TaggedFS.Tag);
387 };
388 return blockingRunWithAST<RetType>(WorkScheduler, File, Action);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000389}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000390
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000391llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
392
393 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
394 ".c++", ".m", ".mm"};
395 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
396
397 StringRef PathExt = llvm::sys::path::extension(Path);
398
399 // Lookup in a list of known extensions.
400 auto SourceIter =
401 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
402 [&PathExt](PathRef SourceExt) {
403 return SourceExt.equals_lower(PathExt);
404 });
405 bool IsSource = SourceIter != std::end(SourceExtensions);
406
407 auto HeaderIter =
408 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
409 [&PathExt](PathRef HeaderExt) {
410 return HeaderExt.equals_lower(PathExt);
411 });
412
413 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
414
415 // We can only switch between extensions known extensions.
416 if (!IsSource && !IsHeader)
417 return llvm::None;
418
419 // Array to lookup extensions for the switch. An opposite of where original
420 // extension was found.
421 ArrayRef<StringRef> NewExts;
422 if (IsSource)
423 NewExts = HeaderExtensions;
424 else
425 NewExts = SourceExtensions;
426
427 // Storage for the new path.
428 SmallString<128> NewPath = StringRef(Path);
429
430 // Instance of vfs::FileSystem, used for file existence checks.
431 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
432
433 // Loop through switched extension candidates.
434 for (StringRef NewExt : NewExts) {
435 llvm::sys::path::replace_extension(NewPath, NewExt);
436 if (FS->exists(NewPath))
437 return NewPath.str().str(); // First str() to convert from SmallString to
438 // StringRef, second to convert from StringRef
439 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000440
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000441 // Also check NewExt in upper-case, just in case.
442 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
443 if (FS->exists(NewPath))
444 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000445 }
446
447 return llvm::None;
448}
449
Raoul Wols212bcf82017-12-12 20:25:06 +0000450llvm::Expected<tooling::Replacements>
451ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
452 ArrayRef<tooling::Range> Ranges) {
453 // Call clang-format.
454 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
455 auto StyleOrError =
456 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
457 if (!StyleOrError) {
458 return StyleOrError.takeError();
459 } else {
460 return format::reformat(StyleOrError.get(), Code, Ranges, File);
461 }
462}
463
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000464llvm::Expected<Tagged<std::vector<DocumentHighlight>>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000465ClangdServer::findDocumentHighlights(PathRef File, Position Pos) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000466 auto FileContents = DraftMgr.getDraft(File);
467 if (!FileContents.Draft)
468 return llvm::make_error<llvm::StringError>(
469 "findDocumentHighlights called on non-added file",
470 llvm::errc::invalid_argument);
471
472 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
473
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000474 using RetType = llvm::Expected<Tagged<std::vector<DocumentHighlight>>>;
Sam McCalld1a7a372018-01-31 13:40:48 +0000475 auto Action = [=](llvm::Expected<InputsAndAST> InpAST) -> RetType {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000476 if (!InpAST)
477 return InpAST.takeError();
Sam McCalld1a7a372018-01-31 13:40:48 +0000478 auto Result = clangd::findDocumentHighlights(InpAST->AST, Pos);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000479 return make_tagged(std::move(Result), TaggedFS.Tag);
480 };
481 return blockingRunWithAST<RetType>(WorkScheduler, File, Action);
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000482}
483
Sam McCalld1a7a372018-01-31 13:40:48 +0000484std::future<void> ClangdServer::scheduleReparseAndDiags(
485 PathRef File, VersionedDraft Contents,
Ilya Biryukov929697b2018-01-25 14:19:21 +0000486 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000487 tooling::CompileCommand Command = CompileArgs.getCompileCommand(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000488
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000489 using OptDiags = llvm::Optional<std::vector<DiagWithFixIts>>;
490
491 DocVersion Version = Contents.Version;
492 Path FileStr = File.str();
493 VFSTag Tag = std::move(TaggedFS.Tag);
494
Sam McCalld1a7a372018-01-31 13:40:48 +0000495 std::promise<void> DonePromise;
496 std::future<void> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000497
Sam McCalld1a7a372018-01-31 13:40:48 +0000498 auto Callback = [this, Version, FileStr, Tag](std::promise<void> DonePromise,
499 OptDiags Diags) {
500 auto Guard = llvm::make_scope_exit([&]() { DonePromise.set_value(); });
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000501 if (!Diags)
502 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000503
504 // We need to serialize access to resulting diagnostics to avoid calling
505 // `onDiagnosticsReady` in the wrong order.
506 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
507 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
508 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
509 // implementation diagnostics will not be reported after version counters'
510 // overflow. This should not happen in practice, since DocVersion is a
511 // 64-bit unsigned integer.
512 if (Version < LastReportedDiagsVersion)
513 return;
514 LastReportedDiagsVersion = Version;
515
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000516 DiagConsumer.onDiagnosticsReady(
Sam McCalld1a7a372018-01-31 13:40:48 +0000517 FileStr, make_tagged(std::move(*Diags), std::move(Tag)));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000518 };
519
Sam McCalld1a7a372018-01-31 13:40:48 +0000520 WorkScheduler.update(File,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000521 ParseInputs{std::move(Command),
522 std::move(TaggedFS.Value),
523 std::move(*Contents.Draft)},
524 BindWithForward(Callback, std::move(DonePromise)));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000525 return DoneFuture;
526}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000527
528void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
529 // FIXME: Do nothing for now. This will be used for indexing and potentially
530 // invalidating other caches.
531}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000532
533std::vector<std::pair<Path, std::size_t>>
534ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000535 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000536}