blob: 789382db2b4a45ee78d335ccff9640ba6fcf36e3 [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();
157 auto Task = [PCHs, Pos, FS, CodeCompleteOpts](
158 std::string Contents, Path File, Callback<CompletionList> CB,
Sam McCalld1a7a372018-01-31 13:40:48 +0000159 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,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000167 Contents, Pos, FS, PCHs, CodeCompleteOpts);
168 CB(std::move(Result));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000169 };
170
Sam McCall091557d2018-02-23 07:54:17 +0000171 WorkScheduler.runWithPreamble(
172 "CodeComplete", File,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000173 Bind(Task, std::move(*Latest.Draft), File.str(), std::move(CB)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000174}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000175
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000176void ClangdServer::signatureHelp(PathRef File, Position Pos,
177 Callback<SignatureHelp> CB) {
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000178 VersionedDraft Latest = DraftMgr.getDraft(File);
179 if (!Latest.Draft)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000180 return CB(llvm::make_error<llvm::StringError>(
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000181 "signatureHelp is called for non-added document",
182 llvm::errc::invalid_argument));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000183
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000184 auto PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000185 auto FS = FSProvider.getFileSystem();
186 auto Action = [Pos, FS, PCHs](std::string Contents, Path File,
187 Callback<SignatureHelp> CB,
188 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000189 if (!IP)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000190 return CB(IP.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000191
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000192 auto PreambleData = IP->Preamble;
Ilya Biryukovf1f3d572018-03-14 17:46:52 +0000193 CB(clangd::signatureHelp(File, IP->Command,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000194 PreambleData ? &PreambleData->Preamble : nullptr,
195 Contents, Pos, FS, PCHs));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000196 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000197
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000198 WorkScheduler.runWithPreamble(
199 "SignatureHelp", File,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000200 Bind(Action, std::move(*Latest.Draft), File.str(), std::move(CB)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000201}
202
Raoul Wols212bcf82017-12-12 20:25:06 +0000203llvm::Expected<tooling::Replacements>
204ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000205 size_t Begin = positionToOffset(Code, Rng.start);
206 size_t Len = positionToOffset(Code, Rng.end) - Begin;
207 return formatCode(Code, File, {tooling::Range(Begin, Len)});
208}
209
Raoul Wols212bcf82017-12-12 20:25:06 +0000210llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
211 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000212 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000213 return formatCode(Code, File, {tooling::Range(0, Code.size())});
214}
215
Raoul Wols212bcf82017-12-12 20:25:06 +0000216llvm::Expected<tooling::Replacements>
217ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000218 // Look for the previous opening brace from the character position and
219 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000220 size_t CursorPos = positionToOffset(Code, Pos);
221 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
222 if (PreviousLBracePos == StringRef::npos)
223 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000224 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000225
226 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
227}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000228
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000229void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
230 Callback<std::vector<tooling::Replacement>> CB) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000231 auto Action = [Pos](Path File, std::string NewName,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000232 Callback<std::vector<tooling::Replacement>> CB,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000233 Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000234 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000235 return CB(InpAST.takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000236 auto &AST = InpAST->AST;
237
238 RefactoringResultCollector ResultCollector;
239 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000240 const FileEntry *FE =
241 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
242 if (!FE)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000243 return CB(llvm::make_error<llvm::StringError>(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000244 "rename called for non-added document",
245 llvm::errc::invalid_argument));
Haojian Wu345099c2017-11-09 11:30:04 +0000246 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000247 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000248 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000249 AST.getASTContext().getSourceManager());
250 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000251 auto Rename = clang::tooling::RenameOccurrences::initiate(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000252 Context, SourceRange(SourceLocationBeg), NewName);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000253 if (!Rename)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000254 return CB(Rename.takeError());
Haojian Wu345099c2017-11-09 11:30:04 +0000255
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000256 Rename->invoke(ResultCollector, Context);
257
258 assert(ResultCollector.Result.hasValue());
259 if (!ResultCollector.Result.getValue())
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000260 return CB(ResultCollector.Result->takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000261
262 std::vector<tooling::Replacement> Replacements;
263 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
264 tooling::Replacements ChangeReps = Change.getReplacements();
265 for (const auto &Rep : ChangeReps) {
266 // FIXME: Right now we only support renaming the main file, so we
267 // drop replacements not for the main file. In the future, we might
268 // consider to support:
269 // * rename in any included header
270 // * rename only in the "main" header
271 // * provide an error if there are symbols we won't rename (e.g.
272 // std::vector)
273 // * rename globally in project
274 // * rename in open files
275 if (Rep.getFilePath() == File)
276 Replacements.push_back(Rep);
277 }
Haojian Wu345099c2017-11-09 11:30:04 +0000278 }
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000279 return CB(std::move(Replacements));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000280 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000281
282 WorkScheduler.runWithAST(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000283 "Rename", File, Bind(Action, File.str(), NewName.str(), std::move(CB)));
Haojian Wu345099c2017-11-09 11:30:04 +0000284}
285
Eric Liu6c8e8582018-02-26 08:32:13 +0000286/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
287/// include.
288static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
289 llvm::StringRef HintPath) {
290 if (isLiteralInclude(Header))
291 return HeaderFile{Header.str(), /*Verbatim=*/true};
292 auto U = URI::parse(Header);
293 if (!U)
294 return U.takeError();
295 auto Resolved = URI::resolve(*U, HintPath);
296 if (!Resolved)
297 return Resolved.takeError();
298 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
Haojian Wu33caf892018-03-06 12:56:18 +0000299}
Eric Liu6c8e8582018-02-26 08:32:13 +0000300
Eric Liuc5105f92018-02-16 14:15:55 +0000301Expected<tooling::Replacements>
302ClangdServer::insertInclude(PathRef File, StringRef Code,
Eric Liu6c8e8582018-02-26 08:32:13 +0000303 StringRef DeclaringHeader,
304 StringRef InsertedHeader) {
305 assert(!DeclaringHeader.empty() && !InsertedHeader.empty());
Eric Liuc5105f92018-02-16 14:15:55 +0000306 std::string ToInclude;
Eric Liu6c8e8582018-02-26 08:32:13 +0000307 auto ResolvedOrginal = toHeaderFile(DeclaringHeader, File);
308 if (!ResolvedOrginal)
309 return ResolvedOrginal.takeError();
310 auto ResolvedPreferred = toHeaderFile(InsertedHeader, File);
311 if (!ResolvedPreferred)
312 return ResolvedPreferred.takeError();
313 tooling::CompileCommand CompileCommand = CompileArgs.getCompileCommand(File);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000314 auto Include =
315 calculateIncludePath(File, Code, *ResolvedOrginal, *ResolvedPreferred,
316 CompileCommand, FSProvider.getFileSystem());
Eric Liu6c8e8582018-02-26 08:32:13 +0000317 if (!Include)
318 return Include.takeError();
319 if (Include->empty())
320 return tooling::Replacements();
321 ToInclude = std::move(*Include);
Eric Liuc5105f92018-02-16 14:15:55 +0000322
323 auto Style = format::getStyle("file", File, "llvm");
324 if (!Style) {
325 llvm::consumeError(Style.takeError());
326 // FIXME(ioeric): needs more consistent style support in clangd server.
327 Style = format::getLLVMStyle();
328 }
329 // Replacement with offset UINT_MAX and length 0 will be treated as include
330 // insertion.
331 tooling::Replacement R(File, /*Offset=*/UINT_MAX, 0, "#include " + ToInclude);
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000332 auto Replaces =
333 format::cleanupAroundReplacements(Code, tooling::Replacements(R), *Style);
Eric Liue3395b92018-03-06 10:42:50 +0000334 if (!Replaces)
335 return Replaces;
336 return formatReplacements(Code, *Replaces, *Style);
Eric Liuc5105f92018-02-16 14:15:55 +0000337}
338
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000339llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
340 auto Latest = DraftMgr.getDraft(File);
341 if (!Latest.Draft)
342 return llvm::None;
343 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000344}
345
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000346void ClangdServer::dumpAST(PathRef File,
347 UniqueFunction<void(std::string)> Callback) {
348 auto Action = [](decltype(Callback) Callback,
349 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000350 if (!InpAST) {
351 ignoreError(InpAST.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000352 return Callback("<no-ast>");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000353 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000354 std::string Result;
355
356 llvm::raw_string_ostream ResultOS(Result);
357 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000358 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000359
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000360 Callback(Result);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000361 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000362
Sam McCall091557d2018-02-23 07:54:17 +0000363 WorkScheduler.runWithAST("DumpAST", File, Bind(Action, std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000364}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000365
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000366void ClangdServer::findDefinitions(PathRef File, Position Pos,
367 Callback<std::vector<Location>> CB) {
368 auto FS = FSProvider.getFileSystem();
369 auto Action = [Pos, FS](Callback<std::vector<Location>> CB,
370 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000371 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000372 return CB(InpAST.takeError());
373 CB(clangd::findDefinitions(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000374 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000375
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000376 WorkScheduler.runWithAST("Definitions", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000377}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000378
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000379llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
380
381 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
382 ".c++", ".m", ".mm"};
383 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
384
385 StringRef PathExt = llvm::sys::path::extension(Path);
386
387 // Lookup in a list of known extensions.
388 auto SourceIter =
389 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
390 [&PathExt](PathRef SourceExt) {
391 return SourceExt.equals_lower(PathExt);
392 });
393 bool IsSource = SourceIter != std::end(SourceExtensions);
394
395 auto HeaderIter =
396 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
397 [&PathExt](PathRef HeaderExt) {
398 return HeaderExt.equals_lower(PathExt);
399 });
400
401 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
402
403 // We can only switch between extensions known extensions.
404 if (!IsSource && !IsHeader)
405 return llvm::None;
406
407 // Array to lookup extensions for the switch. An opposite of where original
408 // extension was found.
409 ArrayRef<StringRef> NewExts;
410 if (IsSource)
411 NewExts = HeaderExtensions;
412 else
413 NewExts = SourceExtensions;
414
415 // Storage for the new path.
416 SmallString<128> NewPath = StringRef(Path);
417
418 // Instance of vfs::FileSystem, used for file existence checks.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000419 auto FS = FSProvider.getFileSystem();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000420
421 // Loop through switched extension candidates.
422 for (StringRef NewExt : NewExts) {
423 llvm::sys::path::replace_extension(NewPath, NewExt);
424 if (FS->exists(NewPath))
425 return NewPath.str().str(); // First str() to convert from SmallString to
426 // StringRef, second to convert from StringRef
427 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000428
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000429 // Also check NewExt in upper-case, just in case.
430 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
431 if (FS->exists(NewPath))
432 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000433 }
434
435 return llvm::None;
436}
437
Raoul Wols212bcf82017-12-12 20:25:06 +0000438llvm::Expected<tooling::Replacements>
439ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
440 ArrayRef<tooling::Range> Ranges) {
441 // Call clang-format.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000442 auto FS = FSProvider.getFileSystem();
443 auto Style = format::getStyle("file", File, "LLVM", Code, FS.get());
Eric Liue3395b92018-03-06 10:42:50 +0000444 if (!Style)
445 return Style.takeError();
446
447 tooling::Replacements IncludeReplaces =
448 format::sortIncludes(*Style, Code, Ranges, File);
449 auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
450 if (!Changed)
451 return Changed.takeError();
452
453 return IncludeReplaces.merge(format::reformat(
454 Style.get(), *Changed,
455 tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
456 File));
Raoul Wols212bcf82017-12-12 20:25:06 +0000457}
458
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000459void ClangdServer::findDocumentHighlights(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000460 PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000461 auto FileContents = DraftMgr.getDraft(File);
462 if (!FileContents.Draft)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000463 return CB(llvm::make_error<llvm::StringError>(
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000464 "findDocumentHighlights called on non-added file",
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000465 llvm::errc::invalid_argument));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000466
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000467 auto FS = FSProvider.getFileSystem();
468 auto Action = [FS, Pos](Callback<std::vector<DocumentHighlight>> CB,
469 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000470 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000471 return CB(InpAST.takeError());
472 CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000473 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000474
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000475 WorkScheduler.runWithAST("Highlights", File, Bind(Action, std::move(CB)));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000476}
477
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000478void ClangdServer::findHover(PathRef File, Position Pos, Callback<Hover> CB) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000479 Hover FinalHover;
480 auto FileContents = DraftMgr.getDraft(File);
481 if (!FileContents.Draft)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000482 return CB(llvm::make_error<llvm::StringError>(
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000483 "findHover called on non-added file", llvm::errc::invalid_argument));
484
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000485 auto FS = FSProvider.getFileSystem();
486 auto Action = [Pos, FS](Callback<Hover> CB,
487 llvm::Expected<InputsAndAST> InpAST) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000488 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000489 return CB(InpAST.takeError());
490 CB(clangd::getHover(InpAST->AST, Pos));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000491 };
492
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000493 WorkScheduler.runWithAST("Hover", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000494}
495
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000496void ClangdServer::consumeDiagnostics(PathRef File, DocVersion Version,
497 std::vector<Diag> Diags) {
498 // We need to serialize access to resulting diagnostics to avoid calling
499 // `onDiagnosticsReady` in the wrong order.
500 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
501 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[File];
Ilya Biryukov929697b2018-01-25 14:19:21 +0000502
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000503 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
504 // implementation diagnostics will not be reported after version counters'
505 // overflow. This should not happen in practice, since DocVersion is a
506 // 64-bit unsigned integer.
507 if (Version < LastReportedDiagsVersion)
508 return;
509 LastReportedDiagsVersion = Version;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000510
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000511 DiagConsumer.onDiagnosticsReady(File, std::move(Diags));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000512}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000513
Simon Marchi5178f922018-02-22 14:00:39 +0000514void ClangdServer::reparseOpenedFiles() {
515 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000516 addDocument(FilePath, *DraftMgr.getDraft(FilePath).Draft,
517 WantDiagnostics::Auto, /*SkipCache=*/true);
Simon Marchi5178f922018-02-22 14:00:39 +0000518}
519
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000520void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
521 // FIXME: Do nothing for now. This will be used for indexing and potentially
522 // invalidating other caches.
523}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000524
525std::vector<std::pair<Path, std::size_t>>
526ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000527 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000528}
Sam McCall0bb24cd2018-02-13 08:59:23 +0000529
530LLVM_NODISCARD bool
531ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
532 return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds));
533}