blob: 4b59dd50d892173dabe2ee2afca7f1a418605517 [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 +000034void ignoreError(llvm::Error Err) {
35 handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
36}
37
Ilya Biryukova46f7a92017-06-28 10:34:50 +000038std::string getStandardResourceDir() {
39 static int Dummy; // Just an address in this process.
40 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
41}
42
Haojian Wu345099c2017-11-09 11:30:04 +000043class RefactoringResultCollector final
44 : public tooling::RefactoringResultConsumer {
45public:
46 void handleError(llvm::Error Err) override {
47 assert(!Result.hasValue());
48 // FIXME: figure out a way to return better message for DiagnosticError.
49 // clangd uses llvm::toString to convert the Err to string, however, for
50 // DiagnosticError, only "clang diagnostic" will be generated.
51 Result = std::move(Err);
52 }
53
54 // Using the handle(SymbolOccurrences) from parent class.
55 using tooling::RefactoringResultConsumer::handle;
56
57 void handle(tooling::AtomicChanges SourceReplacements) override {
58 assert(!Result.hasValue());
59 Result = std::move(SourceReplacements);
60 }
61
62 Optional<Expected<tooling::AtomicChanges>> Result;
63};
64
Ilya Biryukovafb55542017-05-16 14:40:30 +000065} // namespace
66
Ilya Biryukov22602992017-05-30 15:11:02 +000067Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000068RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000069 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000070}
71
Sam McCalladccab62017-11-23 16:58:22 +000072ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
73 DiagnosticsConsumer &DiagConsumer,
74 FileSystemProvider &FSProvider,
75 unsigned AsyncThreadsCount,
Ilya Biryukov940901e2017-12-13 12:51:22 +000076 bool StorePreamblesInMemory,
Haojian Wuba28e9a2018-01-10 14:44:34 +000077 bool BuildDynamicSymbolIndex, SymbolIndex *StaticIdx,
Sam McCalladccab62017-11-23 16:58:22 +000078 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukov929697b2018-01-25 14:19:21 +000079 : CompileArgs(CDB,
80 ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
81 DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Eric Liubfac8f72017-12-19 18:00:37 +000082 FileIdx(BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000083 PCHs(std::make_shared<PCHContainerOperations>()),
84 // Pass a callback into `WorkScheduler` to extract symbols from a newly
85 // parsed file and rebuild the file index synchronously each time an AST
86 // is parsed.
Eric Liubfac8f72017-12-19 18:00:37 +000087 // FIXME(ioeric): this can be slow and we may be able to index on less
88 // critical paths.
Sam McCalld1a7a372018-01-31 13:40:48 +000089 WorkScheduler(AsyncThreadsCount, StorePreamblesInMemory,
90 FileIdx
91 ? [this](PathRef Path,
92 ParsedAST *AST) { FileIdx->update(Path, AST); }
93 : ASTParsedCallback()) {
Sam McCall0faecf02018-01-15 12:33:00 +000094 if (FileIdx && StaticIdx) {
95 MergedIndex = mergeIndex(FileIdx.get(), StaticIdx);
96 Index = MergedIndex.get();
97 } else if (FileIdx)
98 Index = FileIdx.get();
99 else if (StaticIdx)
100 Index = StaticIdx;
101 else
102 Index = nullptr;
103}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000104
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000105void ClangdServer::setRootPath(PathRef RootPath) {
106 std::string NewRootPath = llvm::sys::path::convert_to_slash(
107 RootPath, llvm::sys::path::Style::posix);
108 if (llvm::sys::fs::is_directory(NewRootPath))
109 this->RootPath = NewRootPath;
110}
111
Sam McCall0bb24cd2018-02-13 08:59:23 +0000112void ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000113 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000114 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Sam McCall0bb24cd2018-02-13 08:59:23 +0000115 scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
116 std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000117}
118
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000119void ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000120 DraftMgr.removeDraft(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000121 CompileArgs.invalidate(File);
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000122 WorkScheduler.remove(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000123}
124
Sam McCall0bb24cd2018-02-13 08:59:23 +0000125void ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000126 auto FileContents = DraftMgr.getDraft(File);
127 assert(FileContents.Draft &&
128 "forceReparse() was called for non-added document");
129
Ilya Biryukov929697b2018-01-25 14:19:21 +0000130 // forceReparse promises to request new compilation flags from CDB, so we
131 // remove any cahced flags.
132 CompileArgs.invalidate(File);
133
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000134 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Sam McCall0bb24cd2018-02-13 08:59:23 +0000135 scheduleReparseAndDiags(File, std::move(FileContents), std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000136}
137
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000138void ClangdServer::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000139 PathRef File, Position Pos, const clangd::CodeCompleteOptions &Opts,
140 UniqueFunction<void(Tagged<CompletionList>)> Callback,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000141 llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000142 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000143 using CallbackType = UniqueFunction<void(Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000144
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000145 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000146 if (UsedFS)
147 *UsedFS = TaggedFS.Value;
148
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000149 // Copy completion options for passing them to async task handler.
150 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000151 if (!CodeCompleteOpts.Index) // Respect overridden index.
152 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000153
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000154 std::string Contents;
155 if (OverridenContents) {
156 Contents = OverridenContents->str();
157 } else {
158 VersionedDraft Latest = DraftMgr.getDraft(File);
159 assert(Latest.Draft && "codeComplete called for non-added document");
160 Contents = *Latest.Draft;
161 }
162
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000163 // Copy PCHs to avoid accessing this->PCHs concurrently
164 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000165 auto Task = [PCHs, Pos, TaggedFS, CodeCompleteOpts](
Sam McCalld1a7a372018-01-31 13:40:48 +0000166 std::string Contents, Path File, CallbackType Callback,
167 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000168 assert(IP && "error when trying to read preamble for codeComplete");
169 auto PreambleData = IP->Preamble;
170 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000171
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000172 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
173 // both the old and the new version in case only one of them matches.
174 CompletionList Result = clangd::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000175 File, Command, PreambleData ? &PreambleData->Preamble : nullptr,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000176 Contents, Pos, TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000177
Sam McCalld1a7a372018-01-31 13:40:48 +0000178 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000179 };
180
Sam McCalld1a7a372018-01-31 13:40:48 +0000181 WorkScheduler.runWithPreamble(File, BindWithForward(Task, std::move(Contents),
182 File.str(),
183 std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000184}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000185
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000186void ClangdServer::signatureHelp(
187 PathRef File, Position Pos,
188 UniqueFunction<void(llvm::Expected<Tagged<SignatureHelp>>)> Callback,
189 llvm::Optional<StringRef> OverridenContents,
190 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000191 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
192 if (UsedFS)
193 *UsedFS = TaggedFS.Value;
194
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000195 std::string Contents;
196 if (OverridenContents) {
197 Contents = OverridenContents->str();
198 } else {
199 VersionedDraft Latest = DraftMgr.getDraft(File);
200 if (!Latest.Draft)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000201 return Callback(llvm::make_error<llvm::StringError>(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000202 "signatureHelp is called for non-added document",
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000203 llvm::errc::invalid_argument));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000204 Contents = std::move(*Latest.Draft);
205 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000206
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000207 auto PCHs = this->PCHs;
208 auto Action = [Contents, Pos, TaggedFS,
209 PCHs](Path File, decltype(Callback) Callback,
210 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000211 if (!IP)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000212 return Callback(IP.takeError());
213
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000214 auto PreambleData = IP->Preamble;
215 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000216 Callback(make_tagged(
Sam McCalld1a7a372018-01-31 13:40:48 +0000217 clangd::signatureHelp(File, Command,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000218 PreambleData ? &PreambleData->Preamble : nullptr,
219 Contents, Pos, TaggedFS.Value, PCHs),
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000220 TaggedFS.Tag));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000221 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000222
223 WorkScheduler.runWithPreamble(
224 File, BindWithForward(Action, File.str(), std::move(Callback)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000225}
226
Raoul Wols212bcf82017-12-12 20:25:06 +0000227llvm::Expected<tooling::Replacements>
228ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000229 size_t Begin = positionToOffset(Code, Rng.start);
230 size_t Len = positionToOffset(Code, Rng.end) - Begin;
231 return formatCode(Code, File, {tooling::Range(Begin, Len)});
232}
233
Raoul Wols212bcf82017-12-12 20:25:06 +0000234llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
235 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000236 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000237 return formatCode(Code, File, {tooling::Range(0, Code.size())});
238}
239
Raoul Wols212bcf82017-12-12 20:25:06 +0000240llvm::Expected<tooling::Replacements>
241ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000242 // Look for the previous opening brace from the character position and
243 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000244 size_t CursorPos = positionToOffset(Code, Pos);
245 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
246 if (PreviousLBracePos == StringRef::npos)
247 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000248 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000249
250 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
251}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000252
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000253void ClangdServer::rename(
254 PathRef File, Position Pos, llvm::StringRef NewName,
255 UniqueFunction<void(Expected<std::vector<tooling::Replacement>>)>
256 Callback) {
257 auto Action = [Pos](Path File, std::string NewName,
258 decltype(Callback) Callback,
259 Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000260 if (!InpAST)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000261 return Callback(InpAST.takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000262 auto &AST = InpAST->AST;
263
264 RefactoringResultCollector ResultCollector;
265 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000266 const FileEntry *FE =
267 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
268 if (!FE)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000269 return Callback(llvm::make_error<llvm::StringError>(
270 "rename called for non-added document",
271 llvm::errc::invalid_argument));
Haojian Wu345099c2017-11-09 11:30:04 +0000272 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000273 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000274 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000275 AST.getASTContext().getSourceManager());
276 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000277 auto Rename = clang::tooling::RenameOccurrences::initiate(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000278 Context, SourceRange(SourceLocationBeg), NewName);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000279 if (!Rename)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000280 return Callback(Rename.takeError());
Haojian Wu345099c2017-11-09 11:30:04 +0000281
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000282 Rename->invoke(ResultCollector, Context);
283
284 assert(ResultCollector.Result.hasValue());
285 if (!ResultCollector.Result.getValue())
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000286 return Callback(ResultCollector.Result->takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000287
288 std::vector<tooling::Replacement> Replacements;
289 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
290 tooling::Replacements ChangeReps = Change.getReplacements();
291 for (const auto &Rep : ChangeReps) {
292 // FIXME: Right now we only support renaming the main file, so we
293 // drop replacements not for the main file. In the future, we might
294 // consider to support:
295 // * rename in any included header
296 // * rename only in the "main" header
297 // * provide an error if there are symbols we won't rename (e.g.
298 // std::vector)
299 // * rename globally in project
300 // * rename in open files
301 if (Rep.getFilePath() == File)
302 Replacements.push_back(Rep);
303 }
Haojian Wu345099c2017-11-09 11:30:04 +0000304 }
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000305 return Callback(Replacements);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000306 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000307
308 WorkScheduler.runWithAST(
309 File,
310 BindWithForward(Action, File.str(), NewName.str(), std::move(Callback)));
Haojian Wu345099c2017-11-09 11:30:04 +0000311}
312
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000313llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
314 auto Latest = DraftMgr.getDraft(File);
315 if (!Latest.Draft)
316 return llvm::None;
317 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000318}
319
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000320void ClangdServer::dumpAST(PathRef File,
321 UniqueFunction<void(std::string)> Callback) {
322 auto Action = [](decltype(Callback) Callback,
323 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000324 if (!InpAST) {
325 ignoreError(InpAST.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000326 return Callback("<no-ast>");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000327 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000328 std::string Result;
329
330 llvm::raw_string_ostream ResultOS(Result);
331 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000332 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000333
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000334 Callback(Result);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000335 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000336
337 WorkScheduler.runWithAST(File, BindWithForward(Action, std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000338}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000339
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000340void ClangdServer::findDefinitions(
341 PathRef File, Position Pos,
342 UniqueFunction<void(llvm::Expected<Tagged<std::vector<Location>>>)>
343 Callback) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000344 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000345 auto Action = [Pos, TaggedFS](decltype(Callback) Callback,
346 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000347 if (!InpAST)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000348 return Callback(InpAST.takeError());
Sam McCalld1a7a372018-01-31 13:40:48 +0000349 auto Result = clangd::findDefinitions(InpAST->AST, Pos);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000350 Callback(make_tagged(std::move(Result), TaggedFS.Tag));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000351 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000352
353 WorkScheduler.runWithAST(File, BindWithForward(Action, std::move(Callback)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000354}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000355
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000356llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
357
358 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
359 ".c++", ".m", ".mm"};
360 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
361
362 StringRef PathExt = llvm::sys::path::extension(Path);
363
364 // Lookup in a list of known extensions.
365 auto SourceIter =
366 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
367 [&PathExt](PathRef SourceExt) {
368 return SourceExt.equals_lower(PathExt);
369 });
370 bool IsSource = SourceIter != std::end(SourceExtensions);
371
372 auto HeaderIter =
373 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
374 [&PathExt](PathRef HeaderExt) {
375 return HeaderExt.equals_lower(PathExt);
376 });
377
378 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
379
380 // We can only switch between extensions known extensions.
381 if (!IsSource && !IsHeader)
382 return llvm::None;
383
384 // Array to lookup extensions for the switch. An opposite of where original
385 // extension was found.
386 ArrayRef<StringRef> NewExts;
387 if (IsSource)
388 NewExts = HeaderExtensions;
389 else
390 NewExts = SourceExtensions;
391
392 // Storage for the new path.
393 SmallString<128> NewPath = StringRef(Path);
394
395 // Instance of vfs::FileSystem, used for file existence checks.
396 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
397
398 // Loop through switched extension candidates.
399 for (StringRef NewExt : NewExts) {
400 llvm::sys::path::replace_extension(NewPath, NewExt);
401 if (FS->exists(NewPath))
402 return NewPath.str().str(); // First str() to convert from SmallString to
403 // StringRef, second to convert from StringRef
404 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000405
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000406 // Also check NewExt in upper-case, just in case.
407 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
408 if (FS->exists(NewPath))
409 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000410 }
411
412 return llvm::None;
413}
414
Raoul Wols212bcf82017-12-12 20:25:06 +0000415llvm::Expected<tooling::Replacements>
416ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
417 ArrayRef<tooling::Range> Ranges) {
418 // Call clang-format.
419 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
420 auto StyleOrError =
421 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
422 if (!StyleOrError) {
423 return StyleOrError.takeError();
424 } else {
425 return format::reformat(StyleOrError.get(), Code, Ranges, File);
426 }
427}
428
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000429void ClangdServer::findDocumentHighlights(
430 PathRef File, Position Pos,
431 UniqueFunction<void(llvm::Expected<Tagged<std::vector<DocumentHighlight>>>)>
432 Callback) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000433 auto FileContents = DraftMgr.getDraft(File);
434 if (!FileContents.Draft)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000435 return Callback(llvm::make_error<llvm::StringError>(
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000436 "findDocumentHighlights called on non-added file",
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000437 llvm::errc::invalid_argument));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000438
439 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
440
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000441 auto Action = [TaggedFS, Pos](decltype(Callback) Callback,
442 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000443 if (!InpAST)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000444 return Callback(InpAST.takeError());
Sam McCalld1a7a372018-01-31 13:40:48 +0000445 auto Result = clangd::findDocumentHighlights(InpAST->AST, Pos);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000446 Callback(make_tagged(std::move(Result), TaggedFS.Tag));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000447 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000448
449 WorkScheduler.runWithAST(File, BindWithForward(Action, std::move(Callback)));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000450}
451
Sam McCall0bb24cd2018-02-13 08:59:23 +0000452void ClangdServer::scheduleReparseAndDiags(
Sam McCalld1a7a372018-01-31 13:40:48 +0000453 PathRef File, VersionedDraft Contents,
Ilya Biryukov929697b2018-01-25 14:19:21 +0000454 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000455 tooling::CompileCommand Command = CompileArgs.getCompileCommand(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000456
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000457 using OptDiags = llvm::Optional<std::vector<DiagWithFixIts>>;
458
459 DocVersion Version = Contents.Version;
460 Path FileStr = File.str();
461 VFSTag Tag = std::move(TaggedFS.Tag);
462
Sam McCall0bb24cd2018-02-13 08:59:23 +0000463 auto Callback = [this, Version, FileStr, Tag](OptDiags Diags) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000464 if (!Diags)
465 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000466
467 // We need to serialize access to resulting diagnostics to avoid calling
468 // `onDiagnosticsReady` in the wrong order.
469 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
470 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
471 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
472 // implementation diagnostics will not be reported after version counters'
473 // overflow. This should not happen in practice, since DocVersion is a
474 // 64-bit unsigned integer.
475 if (Version < LastReportedDiagsVersion)
476 return;
477 LastReportedDiagsVersion = Version;
478
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000479 DiagConsumer.onDiagnosticsReady(
Sam McCalld1a7a372018-01-31 13:40:48 +0000480 FileStr, make_tagged(std::move(*Diags), std::move(Tag)));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000481 };
482
Sam McCalld1a7a372018-01-31 13:40:48 +0000483 WorkScheduler.update(File,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000484 ParseInputs{std::move(Command),
485 std::move(TaggedFS.Value),
486 std::move(*Contents.Draft)},
Sam McCall0bb24cd2018-02-13 08:59:23 +0000487 std::move(Callback));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000488}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000489
490void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
491 // FIXME: Do nothing for now. This will be used for indexing and potentially
492 // invalidating other caches.
493}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000494
495std::vector<std::pair<Path, std::size_t>>
496ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000497 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000498}
Sam McCall0bb24cd2018-02-13 08:59:23 +0000499
500LLVM_NODISCARD bool
501ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
502 return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds));
503}