blob: 4e0405999c6f2750093d0ceb573057c064c7df84 [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"
Eric Liuc5105f92018-02-16 14:15:55 +000012#include "Headers.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000013#include "SourceCode.h"
Sam McCalla66d2cb2017-12-19 17:06:07 +000014#include "XRefs.h"
Sam McCall0faecf02018-01-15 12:33:00 +000015#include "index/Merge.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000016#include "clang/Format/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000017#include "clang/Frontend/CompilerInstance.h"
18#include "clang/Frontend/CompilerInvocation.h"
19#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +000020#include "clang/Tooling/Refactoring/RefactoringResultConsumer.h"
21#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000022#include "llvm/ADT/ArrayRef.h"
Sam McCallb5f5eb62018-01-25 17:01:39 +000023#include "llvm/ADT/ScopeExit.h"
Benjamin Krameree19f162017-10-26 12:28:13 +000024#include "llvm/Support/Errc.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000025#include "llvm/Support/FileSystem.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000026#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000027#include "llvm/Support/raw_ostream.h"
28#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000029
Ilya Biryukov2f314102017-05-16 10:06:20 +000030using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000031using namespace clang::clangd;
32
Ilya Biryukovafb55542017-05-16 14:40:30 +000033namespace {
34
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000035void ignoreError(llvm::Error Err) {
36 handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
37}
38
Ilya Biryukova46f7a92017-06-28 10:34:50 +000039std::string getStandardResourceDir() {
40 static int Dummy; // Just an address in this process.
41 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
42}
43
Haojian Wu345099c2017-11-09 11:30:04 +000044class RefactoringResultCollector final
45 : public tooling::RefactoringResultConsumer {
46public:
47 void handleError(llvm::Error Err) override {
48 assert(!Result.hasValue());
49 // FIXME: figure out a way to return better message for DiagnosticError.
50 // clangd uses llvm::toString to convert the Err to string, however, for
51 // DiagnosticError, only "clang diagnostic" will be generated.
52 Result = std::move(Err);
53 }
54
55 // Using the handle(SymbolOccurrences) from parent class.
56 using tooling::RefactoringResultConsumer::handle;
57
58 void handle(tooling::AtomicChanges SourceReplacements) override {
59 assert(!Result.hasValue());
60 Result = std::move(SourceReplacements);
61 }
62
63 Optional<Expected<tooling::AtomicChanges>> Result;
64};
65
Ilya Biryukovafb55542017-05-16 14:40:30 +000066} // namespace
67
Ilya Biryukov22602992017-05-30 15:11:02 +000068Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000069RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000070 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000071}
72
Sam McCalladccab62017-11-23 16:58:22 +000073ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
74 DiagnosticsConsumer &DiagConsumer,
75 FileSystemProvider &FSProvider,
76 unsigned AsyncThreadsCount,
Ilya Biryukov940901e2017-12-13 12:51:22 +000077 bool StorePreamblesInMemory,
Haojian Wuba28e9a2018-01-10 14:44:34 +000078 bool BuildDynamicSymbolIndex, SymbolIndex *StaticIdx,
Sam McCalladccab62017-11-23 16:58:22 +000079 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukov929697b2018-01-25 14:19:21 +000080 : CompileArgs(CDB,
81 ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
82 DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Eric Liubfac8f72017-12-19 18:00:37 +000083 FileIdx(BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000084 PCHs(std::make_shared<PCHContainerOperations>()),
85 // Pass a callback into `WorkScheduler` to extract symbols from a newly
86 // parsed file and rebuild the file index synchronously each time an AST
87 // is parsed.
Eric Liubfac8f72017-12-19 18:00:37 +000088 // FIXME(ioeric): this can be slow and we may be able to index on less
89 // critical paths.
Sam McCalld1a7a372018-01-31 13:40:48 +000090 WorkScheduler(AsyncThreadsCount, StorePreamblesInMemory,
91 FileIdx
92 ? [this](PathRef Path,
93 ParsedAST *AST) { FileIdx->update(Path, AST); }
94 : ASTParsedCallback()) {
Sam McCall0faecf02018-01-15 12:33:00 +000095 if (FileIdx && StaticIdx) {
96 MergedIndex = mergeIndex(FileIdx.get(), StaticIdx);
97 Index = MergedIndex.get();
98 } else if (FileIdx)
99 Index = FileIdx.get();
100 else if (StaticIdx)
101 Index = StaticIdx;
102 else
103 Index = nullptr;
104}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000105
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000106void ClangdServer::setRootPath(PathRef RootPath) {
107 std::string NewRootPath = llvm::sys::path::convert_to_slash(
108 RootPath, llvm::sys::path::Style::posix);
109 if (llvm::sys::fs::is_directory(NewRootPath))
110 this->RootPath = NewRootPath;
111}
112
Sam McCall568e17f2018-02-22 13:11:12 +0000113void ClangdServer::addDocument(PathRef File, StringRef Contents,
114 WantDiagnostics WantDiags) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000115 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000116 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Sam McCall0bb24cd2018-02-13 08:59:23 +0000117 scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
Sam McCall568e17f2018-02-22 13:11:12 +0000118 WantDiags, std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000119}
120
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000121void ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000122 DraftMgr.removeDraft(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000123 CompileArgs.invalidate(File);
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000124 WorkScheduler.remove(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000125}
126
Sam McCall0bb24cd2018-02-13 08:59:23 +0000127void ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000128 auto FileContents = DraftMgr.getDraft(File);
129 assert(FileContents.Draft &&
130 "forceReparse() was called for non-added document");
131
Ilya Biryukov929697b2018-01-25 14:19:21 +0000132 // forceReparse promises to request new compilation flags from CDB, so we
133 // remove any cahced flags.
134 CompileArgs.invalidate(File);
135
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000136 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Sam McCall568e17f2018-02-22 13:11:12 +0000137 scheduleReparseAndDiags(File, std::move(FileContents), WantDiagnostics::Yes,
138 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000139}
140
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000141void ClangdServer::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000142 PathRef File, Position Pos, const clangd::CodeCompleteOptions &Opts,
143 UniqueFunction<void(Tagged<CompletionList>)> Callback,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000144 llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000145 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000146 using CallbackType = UniqueFunction<void(Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000147
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000148 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000149 if (UsedFS)
150 *UsedFS = TaggedFS.Value;
151
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000152 // Copy completion options for passing them to async task handler.
153 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000154 if (!CodeCompleteOpts.Index) // Respect overridden index.
155 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000156
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000157 std::string Contents;
158 if (OverridenContents) {
159 Contents = OverridenContents->str();
160 } else {
161 VersionedDraft Latest = DraftMgr.getDraft(File);
162 assert(Latest.Draft && "codeComplete called for non-added document");
163 Contents = *Latest.Draft;
164 }
165
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000166 // Copy PCHs to avoid accessing this->PCHs concurrently
167 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000168 auto Task = [PCHs, Pos, TaggedFS, CodeCompleteOpts](
Sam McCalld1a7a372018-01-31 13:40:48 +0000169 std::string Contents, Path File, CallbackType Callback,
170 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000171 assert(IP && "error when trying to read preamble for codeComplete");
172 auto PreambleData = IP->Preamble;
173 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000174
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000175 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
176 // both the old and the new version in case only one of them matches.
177 CompletionList Result = clangd::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000178 File, Command, PreambleData ? &PreambleData->Preamble : nullptr,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000179 Contents, Pos, TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000180
Sam McCalld1a7a372018-01-31 13:40:48 +0000181 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000182 };
183
Sam McCallc901c5d2018-02-19 09:56:28 +0000184 WorkScheduler.runWithPreamble("CodeComplete", File,
185 BindWithForward(Task, std::move(Contents),
186 File.str(),
187 std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000188}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000189
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000190void ClangdServer::signatureHelp(
191 PathRef File, Position Pos,
192 UniqueFunction<void(llvm::Expected<Tagged<SignatureHelp>>)> Callback,
193 llvm::Optional<StringRef> OverridenContents,
194 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000195 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
196 if (UsedFS)
197 *UsedFS = TaggedFS.Value;
198
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000199 std::string Contents;
200 if (OverridenContents) {
201 Contents = OverridenContents->str();
202 } else {
203 VersionedDraft Latest = DraftMgr.getDraft(File);
204 if (!Latest.Draft)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000205 return Callback(llvm::make_error<llvm::StringError>(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000206 "signatureHelp is called for non-added document",
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000207 llvm::errc::invalid_argument));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000208 Contents = std::move(*Latest.Draft);
209 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000210
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000211 auto PCHs = this->PCHs;
212 auto Action = [Contents, Pos, TaggedFS,
213 PCHs](Path File, decltype(Callback) Callback,
214 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000215 if (!IP)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000216 return Callback(IP.takeError());
217
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000218 auto PreambleData = IP->Preamble;
219 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000220 Callback(make_tagged(
Sam McCalld1a7a372018-01-31 13:40:48 +0000221 clangd::signatureHelp(File, Command,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000222 PreambleData ? &PreambleData->Preamble : nullptr,
223 Contents, Pos, TaggedFS.Value, PCHs),
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000224 TaggedFS.Tag));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000225 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000226
227 WorkScheduler.runWithPreamble(
Sam McCallc901c5d2018-02-19 09:56:28 +0000228 "SignatureHelp", File,
229 BindWithForward(Action, File.str(), std::move(Callback)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000230}
231
Raoul Wols212bcf82017-12-12 20:25:06 +0000232llvm::Expected<tooling::Replacements>
233ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000234 size_t Begin = positionToOffset(Code, Rng.start);
235 size_t Len = positionToOffset(Code, Rng.end) - Begin;
236 return formatCode(Code, File, {tooling::Range(Begin, Len)});
237}
238
Raoul Wols212bcf82017-12-12 20:25:06 +0000239llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
240 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000241 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000242 return formatCode(Code, File, {tooling::Range(0, Code.size())});
243}
244
Raoul Wols212bcf82017-12-12 20:25:06 +0000245llvm::Expected<tooling::Replacements>
246ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000247 // Look for the previous opening brace from the character position and
248 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000249 size_t CursorPos = positionToOffset(Code, Pos);
250 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
251 if (PreviousLBracePos == StringRef::npos)
252 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000253 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000254
255 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
256}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000257
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000258void ClangdServer::rename(
259 PathRef File, Position Pos, llvm::StringRef NewName,
260 UniqueFunction<void(Expected<std::vector<tooling::Replacement>>)>
261 Callback) {
262 auto Action = [Pos](Path File, std::string NewName,
263 decltype(Callback) Callback,
264 Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000265 if (!InpAST)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000266 return Callback(InpAST.takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000267 auto &AST = InpAST->AST;
268
269 RefactoringResultCollector ResultCollector;
270 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000271 const FileEntry *FE =
272 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
273 if (!FE)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000274 return Callback(llvm::make_error<llvm::StringError>(
275 "rename called for non-added document",
276 llvm::errc::invalid_argument));
Haojian Wu345099c2017-11-09 11:30:04 +0000277 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000278 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000279 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000280 AST.getASTContext().getSourceManager());
281 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000282 auto Rename = clang::tooling::RenameOccurrences::initiate(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000283 Context, SourceRange(SourceLocationBeg), NewName);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000284 if (!Rename)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000285 return Callback(Rename.takeError());
Haojian Wu345099c2017-11-09 11:30:04 +0000286
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000287 Rename->invoke(ResultCollector, Context);
288
289 assert(ResultCollector.Result.hasValue());
290 if (!ResultCollector.Result.getValue())
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000291 return Callback(ResultCollector.Result->takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000292
293 std::vector<tooling::Replacement> Replacements;
294 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
295 tooling::Replacements ChangeReps = Change.getReplacements();
296 for (const auto &Rep : ChangeReps) {
297 // FIXME: Right now we only support renaming the main file, so we
298 // drop replacements not for the main file. In the future, we might
299 // consider to support:
300 // * rename in any included header
301 // * rename only in the "main" header
302 // * provide an error if there are symbols we won't rename (e.g.
303 // std::vector)
304 // * rename globally in project
305 // * rename in open files
306 if (Rep.getFilePath() == File)
307 Replacements.push_back(Rep);
308 }
Haojian Wu345099c2017-11-09 11:30:04 +0000309 }
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000310 return Callback(Replacements);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000311 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000312
313 WorkScheduler.runWithAST(
Sam McCallc901c5d2018-02-19 09:56:28 +0000314 "Rename", File,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000315 BindWithForward(Action, File.str(), NewName.str(), std::move(Callback)));
Haojian Wu345099c2017-11-09 11:30:04 +0000316}
317
Eric Liuc5105f92018-02-16 14:15:55 +0000318Expected<tooling::Replacements>
319ClangdServer::insertInclude(PathRef File, StringRef Code,
320 llvm::StringRef Header) {
321 std::string ToInclude;
322 if (Header.startswith("<") || Header.startswith("\"")) {
323 ToInclude = Header;
324 } else {
325 auto U = URI::parse(Header);
326 if (!U)
327 return U.takeError();
328 auto Resolved = URI::resolve(*U, /*HintPath=*/File);
329 if (!Resolved)
330 return Resolved.takeError();
331
Eric Liuc5105f92018-02-16 14:15:55 +0000332 tooling::CompileCommand CompileCommand =
333 CompileArgs.getCompileCommand(File);
Eric Liuc5105f92018-02-16 14:15:55 +0000334 auto Include =
Eric Liu709bde82018-02-19 18:48:44 +0000335 calculateIncludePath(File, Code, *Resolved, CompileCommand,
336 FSProvider.getTaggedFileSystem(File).Value);
Eric Liuc5105f92018-02-16 14:15:55 +0000337 if (!Include)
338 return Include.takeError();
339 if (Include->empty())
340 return tooling::Replacements();
341 ToInclude = std::move(*Include);
342 }
343
344 auto Style = format::getStyle("file", File, "llvm");
345 if (!Style) {
346 llvm::consumeError(Style.takeError());
347 // FIXME(ioeric): needs more consistent style support in clangd server.
348 Style = format::getLLVMStyle();
349 }
350 // Replacement with offset UINT_MAX and length 0 will be treated as include
351 // insertion.
352 tooling::Replacement R(File, /*Offset=*/UINT_MAX, 0, "#include " + ToInclude);
353 return format::cleanupAroundReplacements(Code, tooling::Replacements(R),
354 *Style);
355}
356
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000357llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
358 auto Latest = DraftMgr.getDraft(File);
359 if (!Latest.Draft)
360 return llvm::None;
361 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000362}
363
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000364void ClangdServer::dumpAST(PathRef File,
365 UniqueFunction<void(std::string)> Callback) {
366 auto Action = [](decltype(Callback) Callback,
367 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000368 if (!InpAST) {
369 ignoreError(InpAST.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000370 return Callback("<no-ast>");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000371 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000372 std::string Result;
373
374 llvm::raw_string_ostream ResultOS(Result);
375 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000376 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000377
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000378 Callback(Result);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000379 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000380
Sam McCallc901c5d2018-02-19 09:56:28 +0000381 WorkScheduler.runWithAST("DumpAST", File,
382 BindWithForward(Action, std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000383}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000384
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000385void ClangdServer::findDefinitions(
386 PathRef File, Position Pos,
387 UniqueFunction<void(llvm::Expected<Tagged<std::vector<Location>>>)>
388 Callback) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000389 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000390 auto Action = [Pos, TaggedFS](decltype(Callback) Callback,
391 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000392 if (!InpAST)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000393 return Callback(InpAST.takeError());
Sam McCalld1a7a372018-01-31 13:40:48 +0000394 auto Result = clangd::findDefinitions(InpAST->AST, Pos);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000395 Callback(make_tagged(std::move(Result), TaggedFS.Tag));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000396 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000397
Sam McCallc901c5d2018-02-19 09:56:28 +0000398 WorkScheduler.runWithAST("Definitions", File,
399 BindWithForward(Action, std::move(Callback)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000400}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000401
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000402llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
403
404 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
405 ".c++", ".m", ".mm"};
406 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
407
408 StringRef PathExt = llvm::sys::path::extension(Path);
409
410 // Lookup in a list of known extensions.
411 auto SourceIter =
412 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
413 [&PathExt](PathRef SourceExt) {
414 return SourceExt.equals_lower(PathExt);
415 });
416 bool IsSource = SourceIter != std::end(SourceExtensions);
417
418 auto HeaderIter =
419 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
420 [&PathExt](PathRef HeaderExt) {
421 return HeaderExt.equals_lower(PathExt);
422 });
423
424 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
425
426 // We can only switch between extensions known extensions.
427 if (!IsSource && !IsHeader)
428 return llvm::None;
429
430 // Array to lookup extensions for the switch. An opposite of where original
431 // extension was found.
432 ArrayRef<StringRef> NewExts;
433 if (IsSource)
434 NewExts = HeaderExtensions;
435 else
436 NewExts = SourceExtensions;
437
438 // Storage for the new path.
439 SmallString<128> NewPath = StringRef(Path);
440
441 // Instance of vfs::FileSystem, used for file existence checks.
442 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
443
444 // Loop through switched extension candidates.
445 for (StringRef NewExt : NewExts) {
446 llvm::sys::path::replace_extension(NewPath, NewExt);
447 if (FS->exists(NewPath))
448 return NewPath.str().str(); // First str() to convert from SmallString to
449 // StringRef, second to convert from StringRef
450 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000451
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000452 // Also check NewExt in upper-case, just in case.
453 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
454 if (FS->exists(NewPath))
455 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000456 }
457
458 return llvm::None;
459}
460
Raoul Wols212bcf82017-12-12 20:25:06 +0000461llvm::Expected<tooling::Replacements>
462ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
463 ArrayRef<tooling::Range> Ranges) {
464 // Call clang-format.
465 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
466 auto StyleOrError =
467 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
468 if (!StyleOrError) {
469 return StyleOrError.takeError();
470 } else {
471 return format::reformat(StyleOrError.get(), Code, Ranges, File);
472 }
473}
474
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000475void ClangdServer::findDocumentHighlights(
476 PathRef File, Position Pos,
477 UniqueFunction<void(llvm::Expected<Tagged<std::vector<DocumentHighlight>>>)>
478 Callback) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000479 auto FileContents = DraftMgr.getDraft(File);
480 if (!FileContents.Draft)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000481 return Callback(llvm::make_error<llvm::StringError>(
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000482 "findDocumentHighlights called on non-added file",
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000483 llvm::errc::invalid_argument));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000484
485 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
486
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000487 auto Action = [TaggedFS, Pos](decltype(Callback) Callback,
488 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000489 if (!InpAST)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000490 return Callback(InpAST.takeError());
Sam McCalld1a7a372018-01-31 13:40:48 +0000491 auto Result = clangd::findDocumentHighlights(InpAST->AST, Pos);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000492 Callback(make_tagged(std::move(Result), TaggedFS.Tag));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000493 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000494
Sam McCallc901c5d2018-02-19 09:56:28 +0000495 WorkScheduler.runWithAST("Highlights", File,
496 BindWithForward(Action, std::move(Callback)));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000497}
498
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000499void ClangdServer::findHover(
500 PathRef File, Position Pos,
501 UniqueFunction<void(llvm::Expected<Tagged<Hover>>)> Callback) {
502 Hover FinalHover;
503 auto FileContents = DraftMgr.getDraft(File);
504 if (!FileContents.Draft)
505 return Callback(llvm::make_error<llvm::StringError>(
506 "findHover called on non-added file", llvm::errc::invalid_argument));
507
508 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
509
510 auto Action = [Pos, TaggedFS](decltype(Callback) Callback,
511 llvm::Expected<InputsAndAST> InpAST) {
512 if (!InpAST)
513 return Callback(InpAST.takeError());
514
515 Hover Result = clangd::getHover(InpAST->AST, Pos);
516 Callback(make_tagged(std::move(Result), TaggedFS.Tag));
517 };
518
Sam McCallc901c5d2018-02-19 09:56:28 +0000519 WorkScheduler.runWithAST("Hover", File,
520 BindWithForward(Action, std::move(Callback)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000521}
522
Sam McCall0bb24cd2018-02-13 08:59:23 +0000523void ClangdServer::scheduleReparseAndDiags(
Sam McCall568e17f2018-02-22 13:11:12 +0000524 PathRef File, VersionedDraft Contents, WantDiagnostics WantDiags,
Ilya Biryukov929697b2018-01-25 14:19:21 +0000525 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000526 tooling::CompileCommand Command = CompileArgs.getCompileCommand(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000527
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000528 DocVersion Version = Contents.Version;
529 Path FileStr = File.str();
530 VFSTag Tag = std::move(TaggedFS.Tag);
531
Sam McCall568e17f2018-02-22 13:11:12 +0000532 auto Callback = [this, Version, FileStr,
533 Tag](std::vector<DiagWithFixIts> Diags) {
Ilya Biryukov47f22022017-09-20 12:58:55 +0000534 // We need to serialize access to resulting diagnostics to avoid calling
535 // `onDiagnosticsReady` in the wrong order.
536 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
537 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
538 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
539 // implementation diagnostics will not be reported after version counters'
540 // overflow. This should not happen in practice, since DocVersion is a
541 // 64-bit unsigned integer.
542 if (Version < LastReportedDiagsVersion)
543 return;
544 LastReportedDiagsVersion = Version;
545
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000546 DiagConsumer.onDiagnosticsReady(
Sam McCall568e17f2018-02-22 13:11:12 +0000547 FileStr, make_tagged(std::move(Diags), std::move(Tag)));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000548 };
549
Sam McCalld1a7a372018-01-31 13:40:48 +0000550 WorkScheduler.update(File,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000551 ParseInputs{std::move(Command),
552 std::move(TaggedFS.Value),
553 std::move(*Contents.Draft)},
Sam McCall568e17f2018-02-22 13:11:12 +0000554 WantDiags, std::move(Callback));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000555}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000556
557void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
558 // FIXME: Do nothing for now. This will be used for indexing and potentially
559 // invalidating other caches.
560}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000561
562std::vector<std::pair<Path, std::size_t>>
563ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000564 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000565}
Sam McCall0bb24cd2018-02-13 08:59:23 +0000566
567LLVM_NODISCARD bool
568ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
569 return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds));
570}