blob: 4d49072986aaf0f4de2674149e1b7a970c4a548d [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
Simon Marchi9569fd52018-03-16 14:30:42 +0000123 DocVersion Version = ++InternalVersion[File];
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) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000135 ++InternalVersion[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
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000148 // Copy PCHs to avoid accessing this->PCHs concurrently
149 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000150 auto FS = FSProvider.getFileSystem();
Simon Marchi5a48cf82018-03-14 18:31:48 +0000151 auto Task = [PCHs, Pos, FS,
152 CodeCompleteOpts](Path File, Callback<CompletionList> CB,
153 llvm::Expected<InputsAndPreamble> IP) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000154 if (!IP)
155 return CB(IP.takeError());
156
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000157 auto PreambleData = IP->Preamble;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000158
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000159 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
160 // both the old and the new version in case only one of them matches.
161 CompletionList Result = clangd::codeComplete(
Ilya Biryukovf1f3d572018-03-14 17:46:52 +0000162 File, IP->Command, PreambleData ? &PreambleData->Preamble : nullptr,
Simon Marchi5a48cf82018-03-14 18:31:48 +0000163 IP->Contents, Pos, FS, PCHs, CodeCompleteOpts);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000164 CB(std::move(Result));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000165 };
166
Simon Marchi5a48cf82018-03-14 18:31:48 +0000167 WorkScheduler.runWithPreamble("CodeComplete", File,
168 Bind(Task, File.str(), std::move(CB)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000169}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000170
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000171void ClangdServer::signatureHelp(PathRef File, Position Pos,
172 Callback<SignatureHelp> CB) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000173
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000174 auto PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000175 auto FS = FSProvider.getFileSystem();
Simon Marchi5a48cf82018-03-14 18:31:48 +0000176 auto Action = [Pos, FS, PCHs](Path File, Callback<SignatureHelp> CB,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000177 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000178 if (!IP)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000179 return CB(IP.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000180
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000181 auto PreambleData = IP->Preamble;
Ilya Biryukovf1f3d572018-03-14 17:46:52 +0000182 CB(clangd::signatureHelp(File, IP->Command,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000183 PreambleData ? &PreambleData->Preamble : nullptr,
Simon Marchi5a48cf82018-03-14 18:31:48 +0000184 IP->Contents, Pos, FS, PCHs));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000185 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000186
Simon Marchi5a48cf82018-03-14 18:31:48 +0000187 WorkScheduler.runWithPreamble("SignatureHelp", File,
188 Bind(Action, File.str(), std::move(CB)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000189}
190
Raoul Wols212bcf82017-12-12 20:25:06 +0000191llvm::Expected<tooling::Replacements>
192ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000193 size_t Begin = positionToOffset(Code, Rng.start);
194 size_t Len = positionToOffset(Code, Rng.end) - Begin;
195 return formatCode(Code, File, {tooling::Range(Begin, Len)});
196}
197
Raoul Wols212bcf82017-12-12 20:25:06 +0000198llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
199 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000200 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000201 return formatCode(Code, File, {tooling::Range(0, Code.size())});
202}
203
Raoul Wols212bcf82017-12-12 20:25:06 +0000204llvm::Expected<tooling::Replacements>
205ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000206 // Look for the previous opening brace from the character position and
207 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000208 size_t CursorPos = positionToOffset(Code, Pos);
209 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
210 if (PreviousLBracePos == StringRef::npos)
211 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000212 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000213
214 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
215}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000216
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000217void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
218 Callback<std::vector<tooling::Replacement>> CB) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000219 auto Action = [Pos](Path File, std::string NewName,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000220 Callback<std::vector<tooling::Replacement>> CB,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000221 Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000222 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000223 return CB(InpAST.takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000224 auto &AST = InpAST->AST;
225
226 RefactoringResultCollector ResultCollector;
227 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000228 const FileEntry *FE =
229 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
230 if (!FE)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000231 return CB(llvm::make_error<llvm::StringError>(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000232 "rename called for non-added document",
233 llvm::errc::invalid_argument));
Haojian Wu345099c2017-11-09 11:30:04 +0000234 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000235 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000236 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000237 AST.getASTContext().getSourceManager());
238 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000239 auto Rename = clang::tooling::RenameOccurrences::initiate(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000240 Context, SourceRange(SourceLocationBeg), NewName);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000241 if (!Rename)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000242 return CB(Rename.takeError());
Haojian Wu345099c2017-11-09 11:30:04 +0000243
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000244 Rename->invoke(ResultCollector, Context);
245
246 assert(ResultCollector.Result.hasValue());
247 if (!ResultCollector.Result.getValue())
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000248 return CB(ResultCollector.Result->takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000249
250 std::vector<tooling::Replacement> Replacements;
251 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
252 tooling::Replacements ChangeReps = Change.getReplacements();
253 for (const auto &Rep : ChangeReps) {
254 // FIXME: Right now we only support renaming the main file, so we
255 // drop replacements not for the main file. In the future, we might
256 // consider to support:
257 // * rename in any included header
258 // * rename only in the "main" header
259 // * provide an error if there are symbols we won't rename (e.g.
260 // std::vector)
261 // * rename globally in project
262 // * rename in open files
263 if (Rep.getFilePath() == File)
264 Replacements.push_back(Rep);
265 }
Haojian Wu345099c2017-11-09 11:30:04 +0000266 }
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000267 return CB(std::move(Replacements));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000268 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000269
270 WorkScheduler.runWithAST(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000271 "Rename", File, Bind(Action, File.str(), NewName.str(), std::move(CB)));
Haojian Wu345099c2017-11-09 11:30:04 +0000272}
273
Eric Liu6c8e8582018-02-26 08:32:13 +0000274/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
275/// include.
276static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
277 llvm::StringRef HintPath) {
278 if (isLiteralInclude(Header))
279 return HeaderFile{Header.str(), /*Verbatim=*/true};
280 auto U = URI::parse(Header);
281 if (!U)
282 return U.takeError();
283 auto Resolved = URI::resolve(*U, HintPath);
284 if (!Resolved)
285 return Resolved.takeError();
286 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
Haojian Wu33caf892018-03-06 12:56:18 +0000287}
Eric Liu6c8e8582018-02-26 08:32:13 +0000288
Eric Liuc5105f92018-02-16 14:15:55 +0000289Expected<tooling::Replacements>
290ClangdServer::insertInclude(PathRef File, StringRef Code,
Eric Liu6c8e8582018-02-26 08:32:13 +0000291 StringRef DeclaringHeader,
292 StringRef InsertedHeader) {
293 assert(!DeclaringHeader.empty() && !InsertedHeader.empty());
Eric Liuc5105f92018-02-16 14:15:55 +0000294 std::string ToInclude;
Eric Liu6c8e8582018-02-26 08:32:13 +0000295 auto ResolvedOrginal = toHeaderFile(DeclaringHeader, File);
296 if (!ResolvedOrginal)
297 return ResolvedOrginal.takeError();
298 auto ResolvedPreferred = toHeaderFile(InsertedHeader, File);
299 if (!ResolvedPreferred)
300 return ResolvedPreferred.takeError();
301 tooling::CompileCommand CompileCommand = CompileArgs.getCompileCommand(File);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000302 auto Include =
303 calculateIncludePath(File, Code, *ResolvedOrginal, *ResolvedPreferred,
304 CompileCommand, FSProvider.getFileSystem());
Eric Liu6c8e8582018-02-26 08:32:13 +0000305 if (!Include)
306 return Include.takeError();
307 if (Include->empty())
308 return tooling::Replacements();
309 ToInclude = std::move(*Include);
Eric Liuc5105f92018-02-16 14:15:55 +0000310
311 auto Style = format::getStyle("file", File, "llvm");
312 if (!Style) {
313 llvm::consumeError(Style.takeError());
314 // FIXME(ioeric): needs more consistent style support in clangd server.
315 Style = format::getLLVMStyle();
316 }
317 // Replacement with offset UINT_MAX and length 0 will be treated as include
318 // insertion.
319 tooling::Replacement R(File, /*Offset=*/UINT_MAX, 0, "#include " + ToInclude);
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000320 auto Replaces =
321 format::cleanupAroundReplacements(Code, tooling::Replacements(R), *Style);
Eric Liue3395b92018-03-06 10:42:50 +0000322 if (!Replaces)
323 return Replaces;
324 return formatReplacements(Code, *Replaces, *Style);
Eric Liuc5105f92018-02-16 14:15:55 +0000325}
326
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000327void ClangdServer::dumpAST(PathRef File,
328 UniqueFunction<void(std::string)> Callback) {
329 auto Action = [](decltype(Callback) Callback,
330 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000331 if (!InpAST) {
332 ignoreError(InpAST.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000333 return Callback("<no-ast>");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000334 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000335 std::string Result;
336
337 llvm::raw_string_ostream ResultOS(Result);
338 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000339 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000340
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000341 Callback(Result);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000342 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000343
Sam McCall091557d2018-02-23 07:54:17 +0000344 WorkScheduler.runWithAST("DumpAST", File, Bind(Action, std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000345}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000346
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000347void ClangdServer::findDefinitions(PathRef File, Position Pos,
348 Callback<std::vector<Location>> CB) {
349 auto FS = FSProvider.getFileSystem();
350 auto Action = [Pos, FS](Callback<std::vector<Location>> CB,
351 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000352 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000353 return CB(InpAST.takeError());
354 CB(clangd::findDefinitions(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000355 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000356
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000357 WorkScheduler.runWithAST("Definitions", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000358}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000359
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000360llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
361
362 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
363 ".c++", ".m", ".mm"};
364 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
365
366 StringRef PathExt = llvm::sys::path::extension(Path);
367
368 // Lookup in a list of known extensions.
369 auto SourceIter =
370 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
371 [&PathExt](PathRef SourceExt) {
372 return SourceExt.equals_lower(PathExt);
373 });
374 bool IsSource = SourceIter != std::end(SourceExtensions);
375
376 auto HeaderIter =
377 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
378 [&PathExt](PathRef HeaderExt) {
379 return HeaderExt.equals_lower(PathExt);
380 });
381
382 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
383
384 // We can only switch between extensions known extensions.
385 if (!IsSource && !IsHeader)
386 return llvm::None;
387
388 // Array to lookup extensions for the switch. An opposite of where original
389 // extension was found.
390 ArrayRef<StringRef> NewExts;
391 if (IsSource)
392 NewExts = HeaderExtensions;
393 else
394 NewExts = SourceExtensions;
395
396 // Storage for the new path.
397 SmallString<128> NewPath = StringRef(Path);
398
399 // Instance of vfs::FileSystem, used for file existence checks.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000400 auto FS = FSProvider.getFileSystem();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000401
402 // Loop through switched extension candidates.
403 for (StringRef NewExt : NewExts) {
404 llvm::sys::path::replace_extension(NewPath, NewExt);
405 if (FS->exists(NewPath))
406 return NewPath.str().str(); // First str() to convert from SmallString to
407 // StringRef, second to convert from StringRef
408 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000409
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000410 // Also check NewExt in upper-case, just in case.
411 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
412 if (FS->exists(NewPath))
413 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000414 }
415
416 return llvm::None;
417}
418
Raoul Wols212bcf82017-12-12 20:25:06 +0000419llvm::Expected<tooling::Replacements>
420ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
421 ArrayRef<tooling::Range> Ranges) {
422 // Call clang-format.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000423 auto FS = FSProvider.getFileSystem();
424 auto Style = format::getStyle("file", File, "LLVM", Code, FS.get());
Eric Liue3395b92018-03-06 10:42:50 +0000425 if (!Style)
426 return Style.takeError();
427
428 tooling::Replacements IncludeReplaces =
429 format::sortIncludes(*Style, Code, Ranges, File);
430 auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
431 if (!Changed)
432 return Changed.takeError();
433
434 return IncludeReplaces.merge(format::reformat(
435 Style.get(), *Changed,
436 tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
437 File));
Raoul Wols212bcf82017-12-12 20:25:06 +0000438}
439
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000440void ClangdServer::findDocumentHighlights(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000441 PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000442
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000443 auto FS = FSProvider.getFileSystem();
444 auto Action = [FS, Pos](Callback<std::vector<DocumentHighlight>> CB,
445 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000446 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000447 return CB(InpAST.takeError());
448 CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000449 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000450
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000451 WorkScheduler.runWithAST("Highlights", File, Bind(Action, std::move(CB)));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000452}
453
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000454void ClangdServer::findHover(PathRef File, Position Pos, Callback<Hover> CB) {
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000455 auto FS = FSProvider.getFileSystem();
456 auto Action = [Pos, FS](Callback<Hover> CB,
457 llvm::Expected<InputsAndAST> InpAST) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000458 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000459 return CB(InpAST.takeError());
460 CB(clangd::getHover(InpAST->AST, Pos));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000461 };
462
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000463 WorkScheduler.runWithAST("Hover", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000464}
465
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000466void ClangdServer::consumeDiagnostics(PathRef File, DocVersion Version,
467 std::vector<Diag> Diags) {
468 // We need to serialize access to resulting diagnostics to avoid calling
469 // `onDiagnosticsReady` in the wrong order.
470 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
471 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[File];
Ilya Biryukov929697b2018-01-25 14:19:21 +0000472
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000473 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
474 // implementation diagnostics will not be reported after version counters'
475 // overflow. This should not happen in practice, since DocVersion is a
476 // 64-bit unsigned integer.
477 if (Version < LastReportedDiagsVersion)
478 return;
479 LastReportedDiagsVersion = Version;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000480
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000481 DiagConsumer.onDiagnosticsReady(File, std::move(Diags));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000482}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000483
484void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
485 // FIXME: Do nothing for now. This will be used for indexing and potentially
486 // invalidating other caches.
487}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000488
489std::vector<std::pair<Path, std::size_t>>
490ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000491 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000492}
Sam McCall0bb24cd2018-02-13 08:59:23 +0000493
494LLVM_NODISCARD bool
495ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
496 return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds));
497}