blob: f8e07f9a761f4bc6423fce2d7c684422c7e8236f [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 McCall0bb24cd2018-02-13 08:59:23 +0000142void 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 McCall0bb24cd2018-02-13 08:59:23 +0000145 scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
146 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 McCall0bb24cd2018-02-13 08:59:23 +0000155void 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 McCall0bb24cd2018-02-13 08:59:23 +0000165 scheduleReparseAndDiags(File, std::move(FileContents), std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000166}
167
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000168void ClangdServer::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000169 PathRef File, Position Pos, const clangd::CodeCompleteOptions &Opts,
170 UniqueFunction<void(Tagged<CompletionList>)> Callback,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000171 llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000172 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000173 using CallbackType = UniqueFunction<void(Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000174
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000175 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000176 if (UsedFS)
177 *UsedFS = TaggedFS.Value;
178
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000179 // Copy completion options for passing them to async task handler.
180 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000181 if (!CodeCompleteOpts.Index) // Respect overridden index.
182 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000183
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000184 std::string Contents;
185 if (OverridenContents) {
186 Contents = OverridenContents->str();
187 } else {
188 VersionedDraft Latest = DraftMgr.getDraft(File);
189 assert(Latest.Draft && "codeComplete called for non-added document");
190 Contents = *Latest.Draft;
191 }
192
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000193 // Copy PCHs to avoid accessing this->PCHs concurrently
194 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000195 auto Task = [PCHs, Pos, TaggedFS, CodeCompleteOpts](
Sam McCalld1a7a372018-01-31 13:40:48 +0000196 std::string Contents, Path File, CallbackType Callback,
197 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000198 assert(IP && "error when trying to read preamble for codeComplete");
199 auto PreambleData = IP->Preamble;
200 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000201
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000202 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
203 // both the old and the new version in case only one of them matches.
204 CompletionList Result = clangd::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000205 File, Command, PreambleData ? &PreambleData->Preamble : nullptr,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000206 Contents, Pos, TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000207
Sam McCalld1a7a372018-01-31 13:40:48 +0000208 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000209 };
210
Sam McCalld1a7a372018-01-31 13:40:48 +0000211 WorkScheduler.runWithPreamble(File, BindWithForward(Task, std::move(Contents),
212 File.str(),
213 std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000214}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000215
Benjamin Krameree19f162017-10-26 12:28:13 +0000216llvm::Expected<Tagged<SignatureHelp>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000217ClangdServer::signatureHelp(PathRef File, Position Pos,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000218 llvm::Optional<StringRef> OverridenContents,
219 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000220 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
221 if (UsedFS)
222 *UsedFS = TaggedFS.Value;
223
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000224 std::string Contents;
225 if (OverridenContents) {
226 Contents = OverridenContents->str();
227 } else {
228 VersionedDraft Latest = DraftMgr.getDraft(File);
229 if (!Latest.Draft)
230 return llvm::make_error<llvm::StringError>(
231 "signatureHelp is called for non-added document",
232 llvm::errc::invalid_argument);
233 Contents = std::move(*Latest.Draft);
234 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000235
Sam McCalld1a7a372018-01-31 13:40:48 +0000236 auto Action = [=](llvm::Expected<InputsAndPreamble> IP)
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000237 -> Expected<Tagged<SignatureHelp>> {
238 if (!IP)
239 return IP.takeError();
240 auto PreambleData = IP->Preamble;
241 auto &Command = IP->Inputs.CompileCommand;
242
243 return make_tagged(
Sam McCalld1a7a372018-01-31 13:40:48 +0000244 clangd::signatureHelp(File, Command,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000245 PreambleData ? &PreambleData->Preamble : nullptr,
246 Contents, Pos, TaggedFS.Value, PCHs),
247 TaggedFS.Tag);
248 };
249 return blockingRunWithPreamble<Expected<Tagged<SignatureHelp>>>(WorkScheduler,
250 File, Action);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000251}
252
Raoul Wols212bcf82017-12-12 20:25:06 +0000253llvm::Expected<tooling::Replacements>
254ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000255 size_t Begin = positionToOffset(Code, Rng.start);
256 size_t Len = positionToOffset(Code, Rng.end) - Begin;
257 return formatCode(Code, File, {tooling::Range(Begin, Len)});
258}
259
Raoul Wols212bcf82017-12-12 20:25:06 +0000260llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
261 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000262 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000263 return formatCode(Code, File, {tooling::Range(0, Code.size())});
264}
265
Raoul Wols212bcf82017-12-12 20:25:06 +0000266llvm::Expected<tooling::Replacements>
267ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000268 // Look for the previous opening brace from the character position and
269 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000270 size_t CursorPos = positionToOffset(Code, Pos);
271 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
272 if (PreviousLBracePos == StringRef::npos)
273 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000274 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000275
276 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
277}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000278
Haojian Wu345099c2017-11-09 11:30:04 +0000279Expected<std::vector<tooling::Replacement>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000280ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000281 using RetType = Expected<std::vector<tooling::Replacement>>;
282 auto Action = [=](Expected<InputsAndAST> InpAST) -> RetType {
283 if (!InpAST)
284 return InpAST.takeError();
285 auto &AST = InpAST->AST;
286
287 RefactoringResultCollector ResultCollector;
288 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000289 const FileEntry *FE =
290 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
291 if (!FE)
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000292 return llvm::make_error<llvm::StringError>(
293 "rename called for non-added document", llvm::errc::invalid_argument);
Haojian Wu345099c2017-11-09 11:30:04 +0000294 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000295 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000296 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000297 AST.getASTContext().getSourceManager());
298 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000299 auto Rename = clang::tooling::RenameOccurrences::initiate(
300 Context, SourceRange(SourceLocationBeg), NewName.str());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000301 if (!Rename)
302 return Rename.takeError();
Haojian Wu345099c2017-11-09 11:30:04 +0000303
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000304 Rename->invoke(ResultCollector, Context);
305
306 assert(ResultCollector.Result.hasValue());
307 if (!ResultCollector.Result.getValue())
308 return ResultCollector.Result->takeError();
309
310 std::vector<tooling::Replacement> Replacements;
311 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
312 tooling::Replacements ChangeReps = Change.getReplacements();
313 for (const auto &Rep : ChangeReps) {
314 // FIXME: Right now we only support renaming the main file, so we
315 // drop replacements not for the main file. In the future, we might
316 // consider to support:
317 // * rename in any included header
318 // * rename only in the "main" header
319 // * provide an error if there are symbols we won't rename (e.g.
320 // std::vector)
321 // * rename globally in project
322 // * rename in open files
323 if (Rep.getFilePath() == File)
324 Replacements.push_back(Rep);
325 }
Haojian Wu345099c2017-11-09 11:30:04 +0000326 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000327 return Replacements;
328 };
329 return blockingRunWithAST<RetType>(WorkScheduler, File, std::move(Action));
Haojian Wu345099c2017-11-09 11:30:04 +0000330}
331
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000332llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
333 auto Latest = DraftMgr.getDraft(File);
334 if (!Latest.Draft)
335 return llvm::None;
336 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000337}
338
Ilya Biryukovf01af682017-05-23 13:42:59 +0000339std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000340 auto Action = [](llvm::Expected<InputsAndAST> InpAST) -> std::string {
341 if (!InpAST) {
342 ignoreError(InpAST.takeError());
343 return "<no-ast>";
Ilya Biryukov02d58702017-08-01 15:51:38 +0000344 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000345
346 std::string Result;
347
348 llvm::raw_string_ostream ResultOS(Result);
349 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000350 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000351
352 return Result;
353 };
354 return blockingRunWithAST<std::string>(WorkScheduler, File,
355 std::move(Action));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000356}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000357
Benjamin Krameree19f162017-10-26 12:28:13 +0000358llvm::Expected<Tagged<std::vector<Location>>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000359ClangdServer::findDefinitions(PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000360 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
361
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000362 using RetType = llvm::Expected<Tagged<std::vector<Location>>>;
Sam McCalld1a7a372018-01-31 13:40:48 +0000363 auto Action = [=](llvm::Expected<InputsAndAST> InpAST) -> RetType {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000364 if (!InpAST)
365 return InpAST.takeError();
Sam McCalld1a7a372018-01-31 13:40:48 +0000366 auto Result = clangd::findDefinitions(InpAST->AST, Pos);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000367 return make_tagged(std::move(Result), TaggedFS.Tag);
368 };
369 return blockingRunWithAST<RetType>(WorkScheduler, File, Action);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000370}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000371
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000372llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
373
374 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
375 ".c++", ".m", ".mm"};
376 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
377
378 StringRef PathExt = llvm::sys::path::extension(Path);
379
380 // Lookup in a list of known extensions.
381 auto SourceIter =
382 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
383 [&PathExt](PathRef SourceExt) {
384 return SourceExt.equals_lower(PathExt);
385 });
386 bool IsSource = SourceIter != std::end(SourceExtensions);
387
388 auto HeaderIter =
389 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
390 [&PathExt](PathRef HeaderExt) {
391 return HeaderExt.equals_lower(PathExt);
392 });
393
394 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
395
396 // We can only switch between extensions known extensions.
397 if (!IsSource && !IsHeader)
398 return llvm::None;
399
400 // Array to lookup extensions for the switch. An opposite of where original
401 // extension was found.
402 ArrayRef<StringRef> NewExts;
403 if (IsSource)
404 NewExts = HeaderExtensions;
405 else
406 NewExts = SourceExtensions;
407
408 // Storage for the new path.
409 SmallString<128> NewPath = StringRef(Path);
410
411 // Instance of vfs::FileSystem, used for file existence checks.
412 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
413
414 // Loop through switched extension candidates.
415 for (StringRef NewExt : NewExts) {
416 llvm::sys::path::replace_extension(NewPath, NewExt);
417 if (FS->exists(NewPath))
418 return NewPath.str().str(); // First str() to convert from SmallString to
419 // StringRef, second to convert from StringRef
420 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000421
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000422 // Also check NewExt in upper-case, just in case.
423 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
424 if (FS->exists(NewPath))
425 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000426 }
427
428 return llvm::None;
429}
430
Raoul Wols212bcf82017-12-12 20:25:06 +0000431llvm::Expected<tooling::Replacements>
432ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
433 ArrayRef<tooling::Range> Ranges) {
434 // Call clang-format.
435 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
436 auto StyleOrError =
437 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
438 if (!StyleOrError) {
439 return StyleOrError.takeError();
440 } else {
441 return format::reformat(StyleOrError.get(), Code, Ranges, File);
442 }
443}
444
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000445llvm::Expected<Tagged<std::vector<DocumentHighlight>>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000446ClangdServer::findDocumentHighlights(PathRef File, Position Pos) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000447 auto FileContents = DraftMgr.getDraft(File);
448 if (!FileContents.Draft)
449 return llvm::make_error<llvm::StringError>(
450 "findDocumentHighlights called on non-added file",
451 llvm::errc::invalid_argument);
452
453 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
454
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000455 using RetType = llvm::Expected<Tagged<std::vector<DocumentHighlight>>>;
Sam McCalld1a7a372018-01-31 13:40:48 +0000456 auto Action = [=](llvm::Expected<InputsAndAST> InpAST) -> RetType {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000457 if (!InpAST)
458 return InpAST.takeError();
Sam McCalld1a7a372018-01-31 13:40:48 +0000459 auto Result = clangd::findDocumentHighlights(InpAST->AST, Pos);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000460 return make_tagged(std::move(Result), TaggedFS.Tag);
461 };
462 return blockingRunWithAST<RetType>(WorkScheduler, File, Action);
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000463}
464
Sam McCall0bb24cd2018-02-13 08:59:23 +0000465void ClangdServer::scheduleReparseAndDiags(
Sam McCalld1a7a372018-01-31 13:40:48 +0000466 PathRef File, VersionedDraft Contents,
Ilya Biryukov929697b2018-01-25 14:19:21 +0000467 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000468 tooling::CompileCommand Command = CompileArgs.getCompileCommand(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000469
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000470 using OptDiags = llvm::Optional<std::vector<DiagWithFixIts>>;
471
472 DocVersion Version = Contents.Version;
473 Path FileStr = File.str();
474 VFSTag Tag = std::move(TaggedFS.Tag);
475
Sam McCall0bb24cd2018-02-13 08:59:23 +0000476 auto Callback = [this, Version, FileStr, Tag](OptDiags Diags) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000477 if (!Diags)
478 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000479
480 // We need to serialize access to resulting diagnostics to avoid calling
481 // `onDiagnosticsReady` in the wrong order.
482 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
483 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
484 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
485 // implementation diagnostics will not be reported after version counters'
486 // overflow. This should not happen in practice, since DocVersion is a
487 // 64-bit unsigned integer.
488 if (Version < LastReportedDiagsVersion)
489 return;
490 LastReportedDiagsVersion = Version;
491
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000492 DiagConsumer.onDiagnosticsReady(
Sam McCalld1a7a372018-01-31 13:40:48 +0000493 FileStr, make_tagged(std::move(*Diags), std::move(Tag)));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000494 };
495
Sam McCalld1a7a372018-01-31 13:40:48 +0000496 WorkScheduler.update(File,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000497 ParseInputs{std::move(Command),
498 std::move(TaggedFS.Value),
499 std::move(*Contents.Draft)},
Sam McCall0bb24cd2018-02-13 08:59:23 +0000500 std::move(Callback));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000501}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000502
503void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
504 // FIXME: Do nothing for now. This will be used for indexing and potentially
505 // invalidating other caches.
506}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000507
508std::vector<std::pair<Path, std::size_t>>
509ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000510 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000511}
Sam McCall0bb24cd2018-02-13 08:59:23 +0000512
513LLVM_NODISCARD bool
514ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
515 return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds));
516}