blob: d09aec2426e71a1268bd6fd10d7618af416b71ea [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
Sam McCalld1a7a372018-01-31 13:40:48 +0000149std::future<void> 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);
152
Sam McCalld1a7a372018-01-31 13:40:48 +0000153 std::promise<void> DonePromise;
154 std::future<void> DoneFuture = DonePromise.get_future();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000155
156 auto Callback = BindWithForward(
Sam McCalld1a7a372018-01-31 13:40:48 +0000157 [](std::promise<void> DonePromise, llvm::Error Err) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000158 if (Err)
159 ignoreError(std::move(Err));
Sam McCalld1a7a372018-01-31 13:40:48 +0000160 DonePromise.set_value();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000161 },
Sam McCalld1a7a372018-01-31 13:40:48 +0000162 std::move(DonePromise));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000163
164 WorkScheduler.remove(File, std::move(Callback));
165 return DoneFuture;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000166}
167
Sam McCalld1a7a372018-01-31 13:40:48 +0000168std::future<void> ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000169 auto FileContents = DraftMgr.getDraft(File);
170 assert(FileContents.Draft &&
171 "forceReparse() was called for non-added document");
172
Ilya Biryukov929697b2018-01-25 14:19:21 +0000173 // forceReparse promises to request new compilation flags from CDB, so we
174 // remove any cahced flags.
175 CompileArgs.invalidate(File);
176
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000177 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Sam McCalld1a7a372018-01-31 13:40:48 +0000178 return scheduleReparseAndDiags(File, std::move(FileContents),
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000179 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000180}
181
Sam McCalld1a7a372018-01-31 13:40:48 +0000182std::future<Tagged<CompletionList>>
183ClangdServer::codeComplete(PathRef File, Position Pos,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000184 const clangd::CodeCompleteOptions &Opts,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000185 llvm::Optional<StringRef> OverridenContents,
186 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000187 std::promise<Tagged<CompletionList>> ResultPromise;
188 auto Callback = [](std::promise<Tagged<CompletionList>> ResultPromise,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000189 Tagged<CompletionList> Result) -> void {
Sam McCalld1a7a372018-01-31 13:40:48 +0000190 ResultPromise.set_value(std::move(Result));
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000191 };
192
Sam McCalld1a7a372018-01-31 13:40:48 +0000193 auto ResultFuture = ResultPromise.get_future();
194 codeComplete(File, Pos, Opts,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000195 BindWithForward(Callback, std::move(ResultPromise)),
196 OverridenContents, UsedFS);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000197 return ResultFuture;
198}
199
200void ClangdServer::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000201 PathRef File, Position Pos, const clangd::CodeCompleteOptions &Opts,
202 UniqueFunction<void(Tagged<CompletionList>)> Callback,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000203 llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000204 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000205 using CallbackType = UniqueFunction<void(Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000206
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000207 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000208 if (UsedFS)
209 *UsedFS = TaggedFS.Value;
210
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000211 // Copy completion options for passing them to async task handler.
212 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000213 if (!CodeCompleteOpts.Index) // Respect overridden index.
214 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000215
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000216 std::string Contents;
217 if (OverridenContents) {
218 Contents = OverridenContents->str();
219 } else {
220 VersionedDraft Latest = DraftMgr.getDraft(File);
221 assert(Latest.Draft && "codeComplete called for non-added document");
222 Contents = *Latest.Draft;
223 }
224
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000225 // Copy PCHs to avoid accessing this->PCHs concurrently
226 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000227 auto Task = [PCHs, Pos, TaggedFS, CodeCompleteOpts](
Sam McCalld1a7a372018-01-31 13:40:48 +0000228 std::string Contents, Path File, CallbackType Callback,
229 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000230 assert(IP && "error when trying to read preamble for codeComplete");
231 auto PreambleData = IP->Preamble;
232 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000233
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000234 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
235 // both the old and the new version in case only one of them matches.
236 CompletionList Result = clangd::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000237 File, Command, PreambleData ? &PreambleData->Preamble : nullptr,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000238 Contents, Pos, TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000239
Sam McCalld1a7a372018-01-31 13:40:48 +0000240 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000241 };
242
Sam McCalld1a7a372018-01-31 13:40:48 +0000243 WorkScheduler.runWithPreamble(File, BindWithForward(Task, std::move(Contents),
244 File.str(),
245 std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000246}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000247
Benjamin Krameree19f162017-10-26 12:28:13 +0000248llvm::Expected<Tagged<SignatureHelp>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000249ClangdServer::signatureHelp(PathRef File, Position Pos,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000250 llvm::Optional<StringRef> OverridenContents,
251 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000252 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
253 if (UsedFS)
254 *UsedFS = TaggedFS.Value;
255
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000256 std::string Contents;
257 if (OverridenContents) {
258 Contents = OverridenContents->str();
259 } else {
260 VersionedDraft Latest = DraftMgr.getDraft(File);
261 if (!Latest.Draft)
262 return llvm::make_error<llvm::StringError>(
263 "signatureHelp is called for non-added document",
264 llvm::errc::invalid_argument);
265 Contents = std::move(*Latest.Draft);
266 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000267
Sam McCalld1a7a372018-01-31 13:40:48 +0000268 auto Action = [=](llvm::Expected<InputsAndPreamble> IP)
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000269 -> Expected<Tagged<SignatureHelp>> {
270 if (!IP)
271 return IP.takeError();
272 auto PreambleData = IP->Preamble;
273 auto &Command = IP->Inputs.CompileCommand;
274
275 return make_tagged(
Sam McCalld1a7a372018-01-31 13:40:48 +0000276 clangd::signatureHelp(File, Command,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000277 PreambleData ? &PreambleData->Preamble : nullptr,
278 Contents, Pos, TaggedFS.Value, PCHs),
279 TaggedFS.Tag);
280 };
281 return blockingRunWithPreamble<Expected<Tagged<SignatureHelp>>>(WorkScheduler,
282 File, Action);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000283}
284
Raoul Wols212bcf82017-12-12 20:25:06 +0000285llvm::Expected<tooling::Replacements>
286ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000287 size_t Begin = positionToOffset(Code, Rng.start);
288 size_t Len = positionToOffset(Code, Rng.end) - Begin;
289 return formatCode(Code, File, {tooling::Range(Begin, Len)});
290}
291
Raoul Wols212bcf82017-12-12 20:25:06 +0000292llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
293 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000294 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000295 return formatCode(Code, File, {tooling::Range(0, Code.size())});
296}
297
Raoul Wols212bcf82017-12-12 20:25:06 +0000298llvm::Expected<tooling::Replacements>
299ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000300 // Look for the previous opening brace from the character position and
301 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000302 size_t CursorPos = positionToOffset(Code, Pos);
303 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
304 if (PreviousLBracePos == StringRef::npos)
305 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000306 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000307
308 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
309}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000310
Haojian Wu345099c2017-11-09 11:30:04 +0000311Expected<std::vector<tooling::Replacement>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000312ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000313 using RetType = Expected<std::vector<tooling::Replacement>>;
314 auto Action = [=](Expected<InputsAndAST> InpAST) -> RetType {
315 if (!InpAST)
316 return InpAST.takeError();
317 auto &AST = InpAST->AST;
318
319 RefactoringResultCollector ResultCollector;
320 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000321 const FileEntry *FE =
322 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
323 if (!FE)
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000324 return llvm::make_error<llvm::StringError>(
325 "rename called for non-added document", llvm::errc::invalid_argument);
Haojian Wu345099c2017-11-09 11:30:04 +0000326 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000327 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000328 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000329 AST.getASTContext().getSourceManager());
330 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000331 auto Rename = clang::tooling::RenameOccurrences::initiate(
332 Context, SourceRange(SourceLocationBeg), NewName.str());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000333 if (!Rename)
334 return Rename.takeError();
Haojian Wu345099c2017-11-09 11:30:04 +0000335
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000336 Rename->invoke(ResultCollector, Context);
337
338 assert(ResultCollector.Result.hasValue());
339 if (!ResultCollector.Result.getValue())
340 return ResultCollector.Result->takeError();
341
342 std::vector<tooling::Replacement> Replacements;
343 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
344 tooling::Replacements ChangeReps = Change.getReplacements();
345 for (const auto &Rep : ChangeReps) {
346 // FIXME: Right now we only support renaming the main file, so we
347 // drop replacements not for the main file. In the future, we might
348 // consider to support:
349 // * rename in any included header
350 // * rename only in the "main" header
351 // * provide an error if there are symbols we won't rename (e.g.
352 // std::vector)
353 // * rename globally in project
354 // * rename in open files
355 if (Rep.getFilePath() == File)
356 Replacements.push_back(Rep);
357 }
Haojian Wu345099c2017-11-09 11:30:04 +0000358 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000359 return Replacements;
360 };
361 return blockingRunWithAST<RetType>(WorkScheduler, File, std::move(Action));
Haojian Wu345099c2017-11-09 11:30:04 +0000362}
363
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000364llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
365 auto Latest = DraftMgr.getDraft(File);
366 if (!Latest.Draft)
367 return llvm::None;
368 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000369}
370
Ilya Biryukovf01af682017-05-23 13:42:59 +0000371std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000372 auto Action = [](llvm::Expected<InputsAndAST> InpAST) -> std::string {
373 if (!InpAST) {
374 ignoreError(InpAST.takeError());
375 return "<no-ast>";
Ilya Biryukov02d58702017-08-01 15:51:38 +0000376 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000377
378 std::string Result;
379
380 llvm::raw_string_ostream ResultOS(Result);
381 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000382 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000383
384 return Result;
385 };
386 return blockingRunWithAST<std::string>(WorkScheduler, File,
387 std::move(Action));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000388}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000389
Benjamin Krameree19f162017-10-26 12:28:13 +0000390llvm::Expected<Tagged<std::vector<Location>>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000391ClangdServer::findDefinitions(PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000392 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
393
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000394 using RetType = llvm::Expected<Tagged<std::vector<Location>>>;
Sam McCalld1a7a372018-01-31 13:40:48 +0000395 auto Action = [=](llvm::Expected<InputsAndAST> InpAST) -> RetType {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000396 if (!InpAST)
397 return InpAST.takeError();
Sam McCalld1a7a372018-01-31 13:40:48 +0000398 auto Result = clangd::findDefinitions(InpAST->AST, Pos);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000399 return make_tagged(std::move(Result), TaggedFS.Tag);
400 };
401 return blockingRunWithAST<RetType>(WorkScheduler, File, Action);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000402}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000403
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000404llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
405
406 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
407 ".c++", ".m", ".mm"};
408 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
409
410 StringRef PathExt = llvm::sys::path::extension(Path);
411
412 // Lookup in a list of known extensions.
413 auto SourceIter =
414 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
415 [&PathExt](PathRef SourceExt) {
416 return SourceExt.equals_lower(PathExt);
417 });
418 bool IsSource = SourceIter != std::end(SourceExtensions);
419
420 auto HeaderIter =
421 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
422 [&PathExt](PathRef HeaderExt) {
423 return HeaderExt.equals_lower(PathExt);
424 });
425
426 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
427
428 // We can only switch between extensions known extensions.
429 if (!IsSource && !IsHeader)
430 return llvm::None;
431
432 // Array to lookup extensions for the switch. An opposite of where original
433 // extension was found.
434 ArrayRef<StringRef> NewExts;
435 if (IsSource)
436 NewExts = HeaderExtensions;
437 else
438 NewExts = SourceExtensions;
439
440 // Storage for the new path.
441 SmallString<128> NewPath = StringRef(Path);
442
443 // Instance of vfs::FileSystem, used for file existence checks.
444 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
445
446 // Loop through switched extension candidates.
447 for (StringRef NewExt : NewExts) {
448 llvm::sys::path::replace_extension(NewPath, NewExt);
449 if (FS->exists(NewPath))
450 return NewPath.str().str(); // First str() to convert from SmallString to
451 // StringRef, second to convert from StringRef
452 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000453
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000454 // Also check NewExt in upper-case, just in case.
455 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
456 if (FS->exists(NewPath))
457 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000458 }
459
460 return llvm::None;
461}
462
Raoul Wols212bcf82017-12-12 20:25:06 +0000463llvm::Expected<tooling::Replacements>
464ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
465 ArrayRef<tooling::Range> Ranges) {
466 // Call clang-format.
467 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
468 auto StyleOrError =
469 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
470 if (!StyleOrError) {
471 return StyleOrError.takeError();
472 } else {
473 return format::reformat(StyleOrError.get(), Code, Ranges, File);
474 }
475}
476
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000477llvm::Expected<Tagged<std::vector<DocumentHighlight>>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000478ClangdServer::findDocumentHighlights(PathRef File, Position Pos) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000479 auto FileContents = DraftMgr.getDraft(File);
480 if (!FileContents.Draft)
481 return llvm::make_error<llvm::StringError>(
482 "findDocumentHighlights called on non-added file",
483 llvm::errc::invalid_argument);
484
485 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
486
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000487 using RetType = llvm::Expected<Tagged<std::vector<DocumentHighlight>>>;
Sam McCalld1a7a372018-01-31 13:40:48 +0000488 auto Action = [=](llvm::Expected<InputsAndAST> InpAST) -> RetType {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000489 if (!InpAST)
490 return InpAST.takeError();
Sam McCalld1a7a372018-01-31 13:40:48 +0000491 auto Result = clangd::findDocumentHighlights(InpAST->AST, Pos);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000492 return make_tagged(std::move(Result), TaggedFS.Tag);
493 };
494 return blockingRunWithAST<RetType>(WorkScheduler, File, Action);
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000495}
496
Sam McCalld1a7a372018-01-31 13:40:48 +0000497std::future<void> ClangdServer::scheduleReparseAndDiags(
498 PathRef File, VersionedDraft Contents,
Ilya Biryukov929697b2018-01-25 14:19:21 +0000499 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000500 tooling::CompileCommand Command = CompileArgs.getCompileCommand(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000501
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000502 using OptDiags = llvm::Optional<std::vector<DiagWithFixIts>>;
503
504 DocVersion Version = Contents.Version;
505 Path FileStr = File.str();
506 VFSTag Tag = std::move(TaggedFS.Tag);
507
Sam McCalld1a7a372018-01-31 13:40:48 +0000508 std::promise<void> DonePromise;
509 std::future<void> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000510
Sam McCalld1a7a372018-01-31 13:40:48 +0000511 auto Callback = [this, Version, FileStr, Tag](std::promise<void> DonePromise,
512 OptDiags Diags) {
513 auto Guard = llvm::make_scope_exit([&]() { DonePromise.set_value(); });
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000514 if (!Diags)
515 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000516
517 // We need to serialize access to resulting diagnostics to avoid calling
518 // `onDiagnosticsReady` in the wrong order.
519 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
520 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
521 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
522 // implementation diagnostics will not be reported after version counters'
523 // overflow. This should not happen in practice, since DocVersion is a
524 // 64-bit unsigned integer.
525 if (Version < LastReportedDiagsVersion)
526 return;
527 LastReportedDiagsVersion = Version;
528
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000529 DiagConsumer.onDiagnosticsReady(
Sam McCalld1a7a372018-01-31 13:40:48 +0000530 FileStr, make_tagged(std::move(*Diags), std::move(Tag)));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000531 };
532
Sam McCalld1a7a372018-01-31 13:40:48 +0000533 WorkScheduler.update(File,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000534 ParseInputs{std::move(Command),
535 std::move(TaggedFS.Value),
536 std::move(*Contents.Draft)},
537 BindWithForward(Callback, std::move(DonePromise)));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000538 return DoneFuture;
539}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000540
541void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
542 // FIXME: Do nothing for now. This will be used for indexing and potentially
543 // invalidating other caches.
544}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000545
546std::vector<std::pair<Path, std::size_t>>
547ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000548 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000549}