blob: 4e0e9553b39adf67bb756d11a12535e68cba1ec1 [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
Sam McCalla7bb0cc2018-03-12 23:22:35 +000068IntrusiveRefCntPtr<vfs::FileSystem> RealFileSystemProvider::getFileSystem() {
69 return vfs::getRealFileSystem();
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000070}
71
Sam McCall7363a2f2018-03-05 17:28:54 +000072ClangdServer::Options ClangdServer::optsForTest() {
73 ClangdServer::Options Opts;
74 Opts.UpdateDebounce = std::chrono::steady_clock::duration::zero(); // Faster!
75 Opts.StorePreamblesInMemory = true;
76 Opts.AsyncThreadsCount = 4; // Consistent!
77 return Opts;
78}
79
Sam McCalladccab62017-11-23 16:58:22 +000080ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
Sam McCalladccab62017-11-23 16:58:22 +000081 FileSystemProvider &FSProvider,
Sam McCall7363a2f2018-03-05 17:28:54 +000082 DiagnosticsConsumer &DiagConsumer,
83 const Options &Opts)
84 : CompileArgs(CDB, Opts.ResourceDir ? Opts.ResourceDir->str()
85 : getStandardResourceDir()),
Ilya Biryukov929697b2018-01-25 14:19:21 +000086 DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Sam McCall7363a2f2018-03-05 17:28:54 +000087 FileIdx(Opts.BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000088 PCHs(std::make_shared<PCHContainerOperations>()),
89 // Pass a callback into `WorkScheduler` to extract symbols from a newly
90 // parsed file and rebuild the file index synchronously each time an AST
91 // is parsed.
Eric Liubfac8f72017-12-19 18:00:37 +000092 // FIXME(ioeric): this can be slow and we may be able to index on less
93 // critical paths.
Sam McCall7363a2f2018-03-05 17:28:54 +000094 WorkScheduler(Opts.AsyncThreadsCount, Opts.StorePreamblesInMemory,
Sam McCalld1a7a372018-01-31 13:40:48 +000095 FileIdx
96 ? [this](PathRef Path,
97 ParsedAST *AST) { FileIdx->update(Path, AST); }
Sam McCalld1e0deb2018-03-02 08:56:37 +000098 : ASTParsedCallback(),
Sam McCall7363a2f2018-03-05 17:28:54 +000099 Opts.UpdateDebounce) {
100 if (FileIdx && Opts.StaticIndex) {
101 MergedIndex = mergeIndex(FileIdx.get(), Opts.StaticIndex);
Sam McCall0faecf02018-01-15 12:33:00 +0000102 Index = MergedIndex.get();
103 } else if (FileIdx)
104 Index = FileIdx.get();
Sam McCall7363a2f2018-03-05 17:28:54 +0000105 else if (Opts.StaticIndex)
106 Index = Opts.StaticIndex;
Sam McCall0faecf02018-01-15 12:33:00 +0000107 else
108 Index = nullptr;
109}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000110
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000111void ClangdServer::setRootPath(PathRef RootPath) {
112 std::string NewRootPath = llvm::sys::path::convert_to_slash(
113 RootPath, llvm::sys::path::Style::posix);
114 if (llvm::sys::fs::is_directory(NewRootPath))
115 this->RootPath = NewRootPath;
116}
117
Sam McCall568e17f2018-02-22 13:11:12 +0000118void ClangdServer::addDocument(PathRef File, StringRef Contents,
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000119 WantDiagnostics WantDiags, bool SkipCache) {
120 if (SkipCache)
121 CompileArgs.invalidate(File);
122
Ilya Biryukovf01af682017-05-23 13:42:59 +0000123 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000124 ParseInputs Inputs = {CompileArgs.getCompileCommand(File),
125 FSProvider.getFileSystem(), Contents.str()};
126
127 Path FileStr = File.str();
128 WorkScheduler.update(File, std::move(Inputs), WantDiags,
129 [this, FileStr, Version](std::vector<Diag> Diags) {
130 consumeDiagnostics(FileStr, Version, std::move(Diags));
131 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000132}
133
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000134void ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000135 DraftMgr.removeDraft(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000136 CompileArgs.invalidate(File);
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000137 WorkScheduler.remove(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000138}
139
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000140void ClangdServer::codeComplete(PathRef File, Position Pos,
141 const clangd::CodeCompleteOptions &Opts,
142 Callback<CompletionList> CB) {
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000143 // Copy completion options for passing them to async task handler.
144 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000145 if (!CodeCompleteOpts.Index) // Respect overridden index.
146 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000147
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000148 VersionedDraft Latest = DraftMgr.getDraft(File);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000149 if (!Latest.Draft)
150 return CB(llvm::make_error<llvm::StringError>(
151 "codeComplete called for non-added document",
152 llvm::errc::invalid_argument));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000153
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000154 // Copy PCHs to avoid accessing this->PCHs concurrently
155 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000156 auto FS = FSProvider.getFileSystem();
Simon Marchi5a48cf82018-03-14 18:31:48 +0000157 auto Task = [PCHs, Pos, FS,
158 CodeCompleteOpts](Path File, Callback<CompletionList> CB,
159 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000160 assert(IP && "error when trying to read preamble for codeComplete");
161 auto PreambleData = IP->Preamble;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000162
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000163 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
164 // both the old and the new version in case only one of them matches.
165 CompletionList Result = clangd::codeComplete(
Ilya Biryukovf1f3d572018-03-14 17:46:52 +0000166 File, IP->Command, PreambleData ? &PreambleData->Preamble : nullptr,
Simon Marchi5a48cf82018-03-14 18:31:48 +0000167 IP->Contents, Pos, FS, PCHs, CodeCompleteOpts);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000168 CB(std::move(Result));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000169 };
170
Simon Marchi5a48cf82018-03-14 18:31:48 +0000171 WorkScheduler.runWithPreamble("CodeComplete", File,
172 Bind(Task, File.str(), std::move(CB)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000173}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000174
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000175void ClangdServer::signatureHelp(PathRef File, Position Pos,
176 Callback<SignatureHelp> CB) {
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000177 VersionedDraft Latest = DraftMgr.getDraft(File);
178 if (!Latest.Draft)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000179 return CB(llvm::make_error<llvm::StringError>(
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000180 "signatureHelp is called for non-added document",
181 llvm::errc::invalid_argument));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000182
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000183 auto PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000184 auto FS = FSProvider.getFileSystem();
Simon Marchi5a48cf82018-03-14 18:31:48 +0000185 auto Action = [Pos, FS, PCHs](Path File, Callback<SignatureHelp> CB,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000186 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000187 if (!IP)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000188 return CB(IP.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000189
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000190 auto PreambleData = IP->Preamble;
Ilya Biryukovf1f3d572018-03-14 17:46:52 +0000191 CB(clangd::signatureHelp(File, IP->Command,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000192 PreambleData ? &PreambleData->Preamble : nullptr,
Simon Marchi5a48cf82018-03-14 18:31:48 +0000193 IP->Contents, Pos, FS, PCHs));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000194 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000195
Simon Marchi5a48cf82018-03-14 18:31:48 +0000196 WorkScheduler.runWithPreamble("SignatureHelp", File,
197 Bind(Action, File.str(), std::move(CB)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000198}
199
Raoul Wols212bcf82017-12-12 20:25:06 +0000200llvm::Expected<tooling::Replacements>
201ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000202 size_t Begin = positionToOffset(Code, Rng.start);
203 size_t Len = positionToOffset(Code, Rng.end) - Begin;
204 return formatCode(Code, File, {tooling::Range(Begin, Len)});
205}
206
Raoul Wols212bcf82017-12-12 20:25:06 +0000207llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
208 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000209 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000210 return formatCode(Code, File, {tooling::Range(0, Code.size())});
211}
212
Raoul Wols212bcf82017-12-12 20:25:06 +0000213llvm::Expected<tooling::Replacements>
214ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000215 // Look for the previous opening brace from the character position and
216 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000217 size_t CursorPos = positionToOffset(Code, Pos);
218 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
219 if (PreviousLBracePos == StringRef::npos)
220 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000221 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000222
223 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
224}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000225
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000226void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
227 Callback<std::vector<tooling::Replacement>> CB) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000228 auto Action = [Pos](Path File, std::string NewName,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000229 Callback<std::vector<tooling::Replacement>> CB,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000230 Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000231 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000232 return CB(InpAST.takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000233 auto &AST = InpAST->AST;
234
235 RefactoringResultCollector ResultCollector;
236 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000237 const FileEntry *FE =
238 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
239 if (!FE)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000240 return CB(llvm::make_error<llvm::StringError>(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000241 "rename called for non-added document",
242 llvm::errc::invalid_argument));
Haojian Wu345099c2017-11-09 11:30:04 +0000243 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000244 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000245 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000246 AST.getASTContext().getSourceManager());
247 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000248 auto Rename = clang::tooling::RenameOccurrences::initiate(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000249 Context, SourceRange(SourceLocationBeg), NewName);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000250 if (!Rename)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000251 return CB(Rename.takeError());
Haojian Wu345099c2017-11-09 11:30:04 +0000252
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000253 Rename->invoke(ResultCollector, Context);
254
255 assert(ResultCollector.Result.hasValue());
256 if (!ResultCollector.Result.getValue())
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000257 return CB(ResultCollector.Result->takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000258
259 std::vector<tooling::Replacement> Replacements;
260 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
261 tooling::Replacements ChangeReps = Change.getReplacements();
262 for (const auto &Rep : ChangeReps) {
263 // FIXME: Right now we only support renaming the main file, so we
264 // drop replacements not for the main file. In the future, we might
265 // consider to support:
266 // * rename in any included header
267 // * rename only in the "main" header
268 // * provide an error if there are symbols we won't rename (e.g.
269 // std::vector)
270 // * rename globally in project
271 // * rename in open files
272 if (Rep.getFilePath() == File)
273 Replacements.push_back(Rep);
274 }
Haojian Wu345099c2017-11-09 11:30:04 +0000275 }
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000276 return CB(std::move(Replacements));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000277 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000278
279 WorkScheduler.runWithAST(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000280 "Rename", File, Bind(Action, File.str(), NewName.str(), std::move(CB)));
Haojian Wu345099c2017-11-09 11:30:04 +0000281}
282
Eric Liu6c8e8582018-02-26 08:32:13 +0000283/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
284/// include.
285static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
286 llvm::StringRef HintPath) {
287 if (isLiteralInclude(Header))
288 return HeaderFile{Header.str(), /*Verbatim=*/true};
289 auto U = URI::parse(Header);
290 if (!U)
291 return U.takeError();
292 auto Resolved = URI::resolve(*U, HintPath);
293 if (!Resolved)
294 return Resolved.takeError();
295 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
Haojian Wu33caf892018-03-06 12:56:18 +0000296}
Eric Liu6c8e8582018-02-26 08:32:13 +0000297
Eric Liuc5105f92018-02-16 14:15:55 +0000298Expected<tooling::Replacements>
299ClangdServer::insertInclude(PathRef File, StringRef Code,
Eric Liu6c8e8582018-02-26 08:32:13 +0000300 StringRef DeclaringHeader,
301 StringRef InsertedHeader) {
302 assert(!DeclaringHeader.empty() && !InsertedHeader.empty());
Eric Liuc5105f92018-02-16 14:15:55 +0000303 std::string ToInclude;
Eric Liu6c8e8582018-02-26 08:32:13 +0000304 auto ResolvedOrginal = toHeaderFile(DeclaringHeader, File);
305 if (!ResolvedOrginal)
306 return ResolvedOrginal.takeError();
307 auto ResolvedPreferred = toHeaderFile(InsertedHeader, File);
308 if (!ResolvedPreferred)
309 return ResolvedPreferred.takeError();
310 tooling::CompileCommand CompileCommand = CompileArgs.getCompileCommand(File);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000311 auto Include =
312 calculateIncludePath(File, Code, *ResolvedOrginal, *ResolvedPreferred,
313 CompileCommand, FSProvider.getFileSystem());
Eric Liu6c8e8582018-02-26 08:32:13 +0000314 if (!Include)
315 return Include.takeError();
316 if (Include->empty())
317 return tooling::Replacements();
318 ToInclude = std::move(*Include);
Eric Liuc5105f92018-02-16 14:15:55 +0000319
320 auto Style = format::getStyle("file", File, "llvm");
321 if (!Style) {
322 llvm::consumeError(Style.takeError());
323 // FIXME(ioeric): needs more consistent style support in clangd server.
324 Style = format::getLLVMStyle();
325 }
326 // Replacement with offset UINT_MAX and length 0 will be treated as include
327 // insertion.
328 tooling::Replacement R(File, /*Offset=*/UINT_MAX, 0, "#include " + ToInclude);
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000329 auto Replaces =
330 format::cleanupAroundReplacements(Code, tooling::Replacements(R), *Style);
Eric Liue3395b92018-03-06 10:42:50 +0000331 if (!Replaces)
332 return Replaces;
333 return formatReplacements(Code, *Replaces, *Style);
Eric Liuc5105f92018-02-16 14:15:55 +0000334}
335
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000336llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
337 auto Latest = DraftMgr.getDraft(File);
338 if (!Latest.Draft)
339 return llvm::None;
340 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000341}
342
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000343void ClangdServer::dumpAST(PathRef File,
344 UniqueFunction<void(std::string)> Callback) {
345 auto Action = [](decltype(Callback) Callback,
346 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000347 if (!InpAST) {
348 ignoreError(InpAST.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000349 return Callback("<no-ast>");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000350 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000351 std::string Result;
352
353 llvm::raw_string_ostream ResultOS(Result);
354 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000355 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000356
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000357 Callback(Result);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000358 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000359
Sam McCall091557d2018-02-23 07:54:17 +0000360 WorkScheduler.runWithAST("DumpAST", File, Bind(Action, std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000361}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000362
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000363void ClangdServer::findDefinitions(PathRef File, Position Pos,
364 Callback<std::vector<Location>> CB) {
365 auto FS = FSProvider.getFileSystem();
366 auto Action = [Pos, FS](Callback<std::vector<Location>> CB,
367 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000368 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000369 return CB(InpAST.takeError());
370 CB(clangd::findDefinitions(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000371 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000372
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000373 WorkScheduler.runWithAST("Definitions", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000374}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000375
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000376llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
377
378 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
379 ".c++", ".m", ".mm"};
380 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
381
382 StringRef PathExt = llvm::sys::path::extension(Path);
383
384 // Lookup in a list of known extensions.
385 auto SourceIter =
386 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
387 [&PathExt](PathRef SourceExt) {
388 return SourceExt.equals_lower(PathExt);
389 });
390 bool IsSource = SourceIter != std::end(SourceExtensions);
391
392 auto HeaderIter =
393 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
394 [&PathExt](PathRef HeaderExt) {
395 return HeaderExt.equals_lower(PathExt);
396 });
397
398 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
399
400 // We can only switch between extensions known extensions.
401 if (!IsSource && !IsHeader)
402 return llvm::None;
403
404 // Array to lookup extensions for the switch. An opposite of where original
405 // extension was found.
406 ArrayRef<StringRef> NewExts;
407 if (IsSource)
408 NewExts = HeaderExtensions;
409 else
410 NewExts = SourceExtensions;
411
412 // Storage for the new path.
413 SmallString<128> NewPath = StringRef(Path);
414
415 // Instance of vfs::FileSystem, used for file existence checks.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000416 auto FS = FSProvider.getFileSystem();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000417
418 // Loop through switched extension candidates.
419 for (StringRef NewExt : NewExts) {
420 llvm::sys::path::replace_extension(NewPath, NewExt);
421 if (FS->exists(NewPath))
422 return NewPath.str().str(); // First str() to convert from SmallString to
423 // StringRef, second to convert from StringRef
424 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000425
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000426 // Also check NewExt in upper-case, just in case.
427 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
428 if (FS->exists(NewPath))
429 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000430 }
431
432 return llvm::None;
433}
434
Raoul Wols212bcf82017-12-12 20:25:06 +0000435llvm::Expected<tooling::Replacements>
436ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
437 ArrayRef<tooling::Range> Ranges) {
438 // Call clang-format.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000439 auto FS = FSProvider.getFileSystem();
440 auto Style = format::getStyle("file", File, "LLVM", Code, FS.get());
Eric Liue3395b92018-03-06 10:42:50 +0000441 if (!Style)
442 return Style.takeError();
443
444 tooling::Replacements IncludeReplaces =
445 format::sortIncludes(*Style, Code, Ranges, File);
446 auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
447 if (!Changed)
448 return Changed.takeError();
449
450 return IncludeReplaces.merge(format::reformat(
451 Style.get(), *Changed,
452 tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
453 File));
Raoul Wols212bcf82017-12-12 20:25:06 +0000454}
455
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000456void ClangdServer::findDocumentHighlights(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000457 PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000458 auto FileContents = DraftMgr.getDraft(File);
459 if (!FileContents.Draft)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000460 return CB(llvm::make_error<llvm::StringError>(
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000461 "findDocumentHighlights called on non-added file",
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000462 llvm::errc::invalid_argument));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000463
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000464 auto FS = FSProvider.getFileSystem();
465 auto Action = [FS, Pos](Callback<std::vector<DocumentHighlight>> CB,
466 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000467 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000468 return CB(InpAST.takeError());
469 CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000470 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000471
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000472 WorkScheduler.runWithAST("Highlights", File, Bind(Action, std::move(CB)));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000473}
474
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000475void ClangdServer::findHover(PathRef File, Position Pos, Callback<Hover> CB) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000476 Hover FinalHover;
477 auto FileContents = DraftMgr.getDraft(File);
478 if (!FileContents.Draft)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000479 return CB(llvm::make_error<llvm::StringError>(
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000480 "findHover called on non-added file", llvm::errc::invalid_argument));
481
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000482 auto FS = FSProvider.getFileSystem();
483 auto Action = [Pos, FS](Callback<Hover> CB,
484 llvm::Expected<InputsAndAST> InpAST) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000485 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000486 return CB(InpAST.takeError());
487 CB(clangd::getHover(InpAST->AST, Pos));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000488 };
489
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000490 WorkScheduler.runWithAST("Hover", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000491}
492
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000493void ClangdServer::consumeDiagnostics(PathRef File, DocVersion Version,
494 std::vector<Diag> Diags) {
495 // We need to serialize access to resulting diagnostics to avoid calling
496 // `onDiagnosticsReady` in the wrong order.
497 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
498 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[File];
Ilya Biryukov929697b2018-01-25 14:19:21 +0000499
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000500 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
501 // implementation diagnostics will not be reported after version counters'
502 // overflow. This should not happen in practice, since DocVersion is a
503 // 64-bit unsigned integer.
504 if (Version < LastReportedDiagsVersion)
505 return;
506 LastReportedDiagsVersion = Version;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000507
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000508 DiagConsumer.onDiagnosticsReady(File, std::move(Diags));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000509}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000510
Simon Marchi5178f922018-02-22 14:00:39 +0000511void ClangdServer::reparseOpenedFiles() {
512 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000513 addDocument(FilePath, *DraftMgr.getDraft(FilePath).Draft,
514 WantDiagnostics::Auto, /*SkipCache=*/true);
Simon Marchi5178f922018-02-22 14:00:39 +0000515}
516
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000517void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
518 // FIXME: Do nothing for now. This will be used for indexing and potentially
519 // invalidating other caches.
520}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000521
522std::vector<std::pair<Path, std::size_t>>
523ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000524 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000525}
Sam McCall0bb24cd2018-02-13 08:59:23 +0000526
527LLVM_NODISCARD bool
528ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
529 return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds));
530}