blob: e72cf40159c9df80edb38d7ea95f4560c7a05892 [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"
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000012#include "FindSymbols.h"
Eric Liuc5105f92018-02-16 14:15:55 +000013#include "Headers.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000014#include "SourceCode.h"
Sam McCalla66d2cb2017-12-19 17:06:07 +000015#include "XRefs.h"
Sam McCall0faecf02018-01-15 12:33:00 +000016#include "index/Merge.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000017#include "clang/Format/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000018#include "clang/Frontend/CompilerInstance.h"
19#include "clang/Frontend/CompilerInvocation.h"
20#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +000021#include "clang/Tooling/Refactoring/RefactoringResultConsumer.h"
22#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000023#include "llvm/ADT/ArrayRef.h"
Sam McCallb5f5eb62018-01-25 17:01:39 +000024#include "llvm/ADT/ScopeExit.h"
Benjamin Krameree19f162017-10-26 12:28:13 +000025#include "llvm/Support/Errc.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000026#include "llvm/Support/FileSystem.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000027#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000028#include "llvm/Support/raw_ostream.h"
29#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000030
Ilya Biryukov2f314102017-05-16 10:06:20 +000031using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000032using namespace clang::clangd;
33
Ilya Biryukovafb55542017-05-16 14:40:30 +000034namespace {
35
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000036void ignoreError(llvm::Error Err) {
37 handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
38}
39
Ilya Biryukova46f7a92017-06-28 10:34:50 +000040std::string getStandardResourceDir() {
41 static int Dummy; // Just an address in this process.
42 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
43}
44
Haojian Wu345099c2017-11-09 11:30:04 +000045class RefactoringResultCollector final
46 : public tooling::RefactoringResultConsumer {
47public:
48 void handleError(llvm::Error Err) override {
49 assert(!Result.hasValue());
50 // FIXME: figure out a way to return better message for DiagnosticError.
51 // clangd uses llvm::toString to convert the Err to string, however, for
52 // DiagnosticError, only "clang diagnostic" will be generated.
53 Result = std::move(Err);
54 }
55
56 // Using the handle(SymbolOccurrences) from parent class.
57 using tooling::RefactoringResultConsumer::handle;
58
59 void handle(tooling::AtomicChanges SourceReplacements) override {
60 assert(!Result.hasValue());
61 Result = std::move(SourceReplacements);
62 }
63
64 Optional<Expected<tooling::AtomicChanges>> Result;
65};
66
Ilya Biryukovafb55542017-05-16 14:40:30 +000067} // namespace
68
Sam McCalla7bb0cc2018-03-12 23:22:35 +000069IntrusiveRefCntPtr<vfs::FileSystem> RealFileSystemProvider::getFileSystem() {
70 return vfs::getRealFileSystem();
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000071}
72
Sam McCall7363a2f2018-03-05 17:28:54 +000073ClangdServer::Options ClangdServer::optsForTest() {
74 ClangdServer::Options Opts;
75 Opts.UpdateDebounce = std::chrono::steady_clock::duration::zero(); // Faster!
76 Opts.StorePreamblesInMemory = true;
77 Opts.AsyncThreadsCount = 4; // Consistent!
78 return Opts;
79}
80
Sam McCalladccab62017-11-23 16:58:22 +000081ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
Sam McCalladccab62017-11-23 16:58:22 +000082 FileSystemProvider &FSProvider,
Sam McCall7363a2f2018-03-05 17:28:54 +000083 DiagnosticsConsumer &DiagConsumer,
84 const Options &Opts)
85 : CompileArgs(CDB, Opts.ResourceDir ? Opts.ResourceDir->str()
86 : getStandardResourceDir()),
Ilya Biryukov929697b2018-01-25 14:19:21 +000087 DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Sam McCall7363a2f2018-03-05 17:28:54 +000088 FileIdx(Opts.BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000089 PCHs(std::make_shared<PCHContainerOperations>()),
90 // Pass a callback into `WorkScheduler` to extract symbols from a newly
91 // parsed file and rebuild the file index synchronously each time an AST
92 // is parsed.
Eric Liubfac8f72017-12-19 18:00:37 +000093 // FIXME(ioeric): this can be slow and we may be able to index on less
94 // critical paths.
Sam McCall7363a2f2018-03-05 17:28:54 +000095 WorkScheduler(Opts.AsyncThreadsCount, Opts.StorePreamblesInMemory,
Sam McCalld1a7a372018-01-31 13:40:48 +000096 FileIdx
97 ? [this](PathRef Path,
98 ParsedAST *AST) { FileIdx->update(Path, AST); }
Sam McCalld1e0deb2018-03-02 08:56:37 +000099 : ASTParsedCallback(),
Sam McCall7363a2f2018-03-05 17:28:54 +0000100 Opts.UpdateDebounce) {
101 if (FileIdx && Opts.StaticIndex) {
102 MergedIndex = mergeIndex(FileIdx.get(), Opts.StaticIndex);
Sam McCall0faecf02018-01-15 12:33:00 +0000103 Index = MergedIndex.get();
104 } else if (FileIdx)
105 Index = FileIdx.get();
Sam McCall7363a2f2018-03-05 17:28:54 +0000106 else if (Opts.StaticIndex)
107 Index = Opts.StaticIndex;
Sam McCall0faecf02018-01-15 12:33:00 +0000108 else
109 Index = nullptr;
110}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000111
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000112void ClangdServer::setRootPath(PathRef RootPath) {
113 std::string NewRootPath = llvm::sys::path::convert_to_slash(
114 RootPath, llvm::sys::path::Style::posix);
115 if (llvm::sys::fs::is_directory(NewRootPath))
116 this->RootPath = NewRootPath;
117}
118
Sam McCall568e17f2018-02-22 13:11:12 +0000119void ClangdServer::addDocument(PathRef File, StringRef Contents,
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000120 WantDiagnostics WantDiags, bool SkipCache) {
121 if (SkipCache)
122 CompileArgs.invalidate(File);
123
Simon Marchi9569fd52018-03-16 14:30:42 +0000124 DocVersion Version = ++InternalVersion[File];
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000125 ParseInputs Inputs = {CompileArgs.getCompileCommand(File),
126 FSProvider.getFileSystem(), Contents.str()};
127
128 Path FileStr = File.str();
129 WorkScheduler.update(File, std::move(Inputs), WantDiags,
130 [this, FileStr, Version](std::vector<Diag> Diags) {
131 consumeDiagnostics(FileStr, Version, std::move(Diags));
132 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000133}
134
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000135void ClangdServer::removeDocument(PathRef File) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000136 ++InternalVersion[File];
Ilya Biryukov929697b2018-01-25 14:19:21 +0000137 CompileArgs.invalidate(File);
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000138 WorkScheduler.remove(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000139}
140
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000141void ClangdServer::codeComplete(PathRef File, Position Pos,
142 const clangd::CodeCompleteOptions &Opts,
143 Callback<CompletionList> CB) {
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000144 // Copy completion options for passing them to async task handler.
145 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000146 if (!CodeCompleteOpts.Index) // Respect overridden index.
147 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000148
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000149 // Copy PCHs to avoid accessing this->PCHs concurrently
150 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000151 auto FS = FSProvider.getFileSystem();
Simon Marchi5a48cf82018-03-14 18:31:48 +0000152 auto Task = [PCHs, Pos, FS,
153 CodeCompleteOpts](Path File, Callback<CompletionList> CB,
154 llvm::Expected<InputsAndPreamble> IP) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000155 if (!IP)
156 return CB(IP.takeError());
157
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000158 auto PreambleData = IP->Preamble;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000159
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000160 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
161 // both the old and the new version in case only one of them matches.
162 CompletionList Result = clangd::codeComplete(
Ilya Biryukovf1f3d572018-03-14 17:46:52 +0000163 File, IP->Command, PreambleData ? &PreambleData->Preamble : nullptr,
Simon Marchi5a48cf82018-03-14 18:31:48 +0000164 IP->Contents, Pos, FS, PCHs, CodeCompleteOpts);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000165 CB(std::move(Result));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000166 };
167
Simon Marchi5a48cf82018-03-14 18:31:48 +0000168 WorkScheduler.runWithPreamble("CodeComplete", File,
169 Bind(Task, File.str(), std::move(CB)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000170}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000171
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000172void ClangdServer::signatureHelp(PathRef File, Position Pos,
173 Callback<SignatureHelp> CB) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000174
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000175 auto PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000176 auto FS = FSProvider.getFileSystem();
Simon Marchi5a48cf82018-03-14 18:31:48 +0000177 auto Action = [Pos, FS, PCHs](Path File, Callback<SignatureHelp> CB,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000178 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000179 if (!IP)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000180 return CB(IP.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000181
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000182 auto PreambleData = IP->Preamble;
Ilya Biryukovf1f3d572018-03-14 17:46:52 +0000183 CB(clangd::signatureHelp(File, IP->Command,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000184 PreambleData ? &PreambleData->Preamble : nullptr,
Simon Marchi5a48cf82018-03-14 18:31:48 +0000185 IP->Contents, Pos, FS, PCHs));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000186 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000187
Simon Marchi5a48cf82018-03-14 18:31:48 +0000188 WorkScheduler.runWithPreamble("SignatureHelp", File,
189 Bind(Action, File.str(), std::move(CB)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000190}
191
Raoul Wols212bcf82017-12-12 20:25:06 +0000192llvm::Expected<tooling::Replacements>
193ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Simon Marchi766338a2018-03-21 14:36:46 +0000194 llvm::Expected<size_t> Begin = positionToOffset(Code, Rng.start);
195 if (!Begin)
196 return Begin.takeError();
197 llvm::Expected<size_t> End = positionToOffset(Code, Rng.end);
198 if (!End)
199 return End.takeError();
200 return formatCode(Code, File, {tooling::Range(*Begin, *End - *Begin)});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000201}
202
Raoul Wols212bcf82017-12-12 20:25:06 +0000203llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
204 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000205 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000206 return formatCode(Code, File, {tooling::Range(0, Code.size())});
207}
208
Raoul Wols212bcf82017-12-12 20:25:06 +0000209llvm::Expected<tooling::Replacements>
210ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000211 // Look for the previous opening brace from the character position and
212 // format starting from there.
Simon Marchi766338a2018-03-21 14:36:46 +0000213 llvm::Expected<size_t> CursorPos = positionToOffset(Code, Pos);
214 if (!CursorPos)
215 return CursorPos.takeError();
216 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', *CursorPos);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000217 if (PreviousLBracePos == StringRef::npos)
Simon Marchi766338a2018-03-21 14:36:46 +0000218 PreviousLBracePos = *CursorPos;
219 size_t Len = *CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000220
221 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
222}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000223
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000224void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
225 Callback<std::vector<tooling::Replacement>> CB) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000226 auto Action = [Pos](Path File, std::string NewName,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000227 Callback<std::vector<tooling::Replacement>> CB,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000228 Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000229 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000230 return CB(InpAST.takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000231 auto &AST = InpAST->AST;
232
233 RefactoringResultCollector ResultCollector;
234 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000235 const FileEntry *FE =
236 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
237 if (!FE)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000238 return CB(llvm::make_error<llvm::StringError>(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000239 "rename called for non-added document",
240 llvm::errc::invalid_argument));
Haojian Wu345099c2017-11-09 11:30:04 +0000241 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000242 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000243 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000244 AST.getASTContext().getSourceManager());
245 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000246 auto Rename = clang::tooling::RenameOccurrences::initiate(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000247 Context, SourceRange(SourceLocationBeg), NewName);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000248 if (!Rename)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000249 return CB(Rename.takeError());
Haojian Wu345099c2017-11-09 11:30:04 +0000250
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000251 Rename->invoke(ResultCollector, Context);
252
253 assert(ResultCollector.Result.hasValue());
254 if (!ResultCollector.Result.getValue())
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000255 return CB(ResultCollector.Result->takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000256
257 std::vector<tooling::Replacement> Replacements;
258 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
259 tooling::Replacements ChangeReps = Change.getReplacements();
260 for (const auto &Rep : ChangeReps) {
261 // FIXME: Right now we only support renaming the main file, so we
262 // drop replacements not for the main file. In the future, we might
263 // consider to support:
264 // * rename in any included header
265 // * rename only in the "main" header
266 // * provide an error if there are symbols we won't rename (e.g.
267 // std::vector)
268 // * rename globally in project
269 // * rename in open files
270 if (Rep.getFilePath() == File)
271 Replacements.push_back(Rep);
272 }
Haojian Wu345099c2017-11-09 11:30:04 +0000273 }
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000274 return CB(std::move(Replacements));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000275 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000276
277 WorkScheduler.runWithAST(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000278 "Rename", File, Bind(Action, File.str(), NewName.str(), std::move(CB)));
Haojian Wu345099c2017-11-09 11:30:04 +0000279}
280
Eric Liu6c8e8582018-02-26 08:32:13 +0000281/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
282/// include.
283static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
284 llvm::StringRef HintPath) {
285 if (isLiteralInclude(Header))
286 return HeaderFile{Header.str(), /*Verbatim=*/true};
287 auto U = URI::parse(Header);
288 if (!U)
289 return U.takeError();
Haojian Wue9a5a2f2018-04-09 15:09:44 +0000290
291 auto IncludePath = URI::includeSpelling(*U);
292 if (!IncludePath)
293 return IncludePath.takeError();
294 if (!IncludePath->empty())
295 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
296
Eric Liu6c8e8582018-02-26 08:32:13 +0000297 auto Resolved = URI::resolve(*U, HintPath);
298 if (!Resolved)
299 return Resolved.takeError();
300 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
Haojian Wu33caf892018-03-06 12:56:18 +0000301}
Eric Liu6c8e8582018-02-26 08:32:13 +0000302
Eric Liuc5105f92018-02-16 14:15:55 +0000303Expected<tooling::Replacements>
304ClangdServer::insertInclude(PathRef File, StringRef Code,
Eric Liu6c8e8582018-02-26 08:32:13 +0000305 StringRef DeclaringHeader,
306 StringRef InsertedHeader) {
307 assert(!DeclaringHeader.empty() && !InsertedHeader.empty());
Eric Liuc5105f92018-02-16 14:15:55 +0000308 std::string ToInclude;
Eric Liu6c8e8582018-02-26 08:32:13 +0000309 auto ResolvedOrginal = toHeaderFile(DeclaringHeader, File);
310 if (!ResolvedOrginal)
311 return ResolvedOrginal.takeError();
312 auto ResolvedPreferred = toHeaderFile(InsertedHeader, File);
313 if (!ResolvedPreferred)
314 return ResolvedPreferred.takeError();
315 tooling::CompileCommand CompileCommand = CompileArgs.getCompileCommand(File);
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000316 auto Include =
317 calculateIncludePath(File, Code, *ResolvedOrginal, *ResolvedPreferred,
318 CompileCommand, FSProvider.getFileSystem());
Eric Liu6c8e8582018-02-26 08:32:13 +0000319 if (!Include)
320 return Include.takeError();
321 if (Include->empty())
322 return tooling::Replacements();
323 ToInclude = std::move(*Include);
Eric Liuc5105f92018-02-16 14:15:55 +0000324
325 auto Style = format::getStyle("file", File, "llvm");
326 if (!Style) {
327 llvm::consumeError(Style.takeError());
328 // FIXME(ioeric): needs more consistent style support in clangd server.
329 Style = format::getLLVMStyle();
330 }
331 // Replacement with offset UINT_MAX and length 0 will be treated as include
332 // insertion.
333 tooling::Replacement R(File, /*Offset=*/UINT_MAX, 0, "#include " + ToInclude);
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000334 auto Replaces =
335 format::cleanupAroundReplacements(Code, tooling::Replacements(R), *Style);
Eric Liue3395b92018-03-06 10:42:50 +0000336 if (!Replaces)
337 return Replaces;
338 return formatReplacements(Code, *Replaces, *Style);
Eric Liuc5105f92018-02-16 14:15:55 +0000339}
340
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000341void ClangdServer::dumpAST(PathRef File,
342 UniqueFunction<void(std::string)> Callback) {
343 auto Action = [](decltype(Callback) Callback,
344 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000345 if (!InpAST) {
346 ignoreError(InpAST.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000347 return Callback("<no-ast>");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000348 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000349 std::string Result;
350
351 llvm::raw_string_ostream ResultOS(Result);
352 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000353 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000354
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000355 Callback(Result);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000356 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000357
Sam McCall091557d2018-02-23 07:54:17 +0000358 WorkScheduler.runWithAST("DumpAST", File, Bind(Action, std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000359}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000360
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000361void ClangdServer::findDefinitions(PathRef File, Position Pos,
362 Callback<std::vector<Location>> CB) {
363 auto FS = FSProvider.getFileSystem();
364 auto Action = [Pos, FS](Callback<std::vector<Location>> CB,
365 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000366 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000367 return CB(InpAST.takeError());
368 CB(clangd::findDefinitions(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000369 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000370
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000371 WorkScheduler.runWithAST("Definitions", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000372}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000373
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000374llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
375
376 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
377 ".c++", ".m", ".mm"};
378 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
379
380 StringRef PathExt = llvm::sys::path::extension(Path);
381
382 // Lookup in a list of known extensions.
383 auto SourceIter =
384 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
385 [&PathExt](PathRef SourceExt) {
386 return SourceExt.equals_lower(PathExt);
387 });
388 bool IsSource = SourceIter != std::end(SourceExtensions);
389
390 auto HeaderIter =
391 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
392 [&PathExt](PathRef HeaderExt) {
393 return HeaderExt.equals_lower(PathExt);
394 });
395
396 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
397
398 // We can only switch between extensions known extensions.
399 if (!IsSource && !IsHeader)
400 return llvm::None;
401
402 // Array to lookup extensions for the switch. An opposite of where original
403 // extension was found.
404 ArrayRef<StringRef> NewExts;
405 if (IsSource)
406 NewExts = HeaderExtensions;
407 else
408 NewExts = SourceExtensions;
409
410 // Storage for the new path.
411 SmallString<128> NewPath = StringRef(Path);
412
413 // Instance of vfs::FileSystem, used for file existence checks.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000414 auto FS = FSProvider.getFileSystem();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000415
416 // Loop through switched extension candidates.
417 for (StringRef NewExt : NewExts) {
418 llvm::sys::path::replace_extension(NewPath, NewExt);
419 if (FS->exists(NewPath))
420 return NewPath.str().str(); // First str() to convert from SmallString to
421 // StringRef, second to convert from StringRef
422 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000423
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000424 // Also check NewExt in upper-case, just in case.
425 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
426 if (FS->exists(NewPath))
427 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000428 }
429
430 return llvm::None;
431}
432
Raoul Wols212bcf82017-12-12 20:25:06 +0000433llvm::Expected<tooling::Replacements>
434ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
435 ArrayRef<tooling::Range> Ranges) {
436 // Call clang-format.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000437 auto FS = FSProvider.getFileSystem();
438 auto Style = format::getStyle("file", File, "LLVM", Code, FS.get());
Eric Liue3395b92018-03-06 10:42:50 +0000439 if (!Style)
440 return Style.takeError();
441
442 tooling::Replacements IncludeReplaces =
443 format::sortIncludes(*Style, Code, Ranges, File);
444 auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
445 if (!Changed)
446 return Changed.takeError();
447
448 return IncludeReplaces.merge(format::reformat(
449 Style.get(), *Changed,
450 tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
451 File));
Raoul Wols212bcf82017-12-12 20:25:06 +0000452}
453
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000454void ClangdServer::findDocumentHighlights(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000455 PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000456
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000457 auto FS = FSProvider.getFileSystem();
458 auto Action = [FS, Pos](Callback<std::vector<DocumentHighlight>> CB,
459 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000460 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000461 return CB(InpAST.takeError());
462 CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000463 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000464
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000465 WorkScheduler.runWithAST("Highlights", File, Bind(Action, std::move(CB)));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000466}
467
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000468void ClangdServer::findHover(PathRef File, Position Pos, Callback<Hover> CB) {
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000469 auto FS = FSProvider.getFileSystem();
470 auto Action = [Pos, FS](Callback<Hover> CB,
471 llvm::Expected<InputsAndAST> InpAST) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000472 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000473 return CB(InpAST.takeError());
474 CB(clangd::getHover(InpAST->AST, Pos));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000475 };
476
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000477 WorkScheduler.runWithAST("Hover", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000478}
479
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000480void ClangdServer::consumeDiagnostics(PathRef File, DocVersion Version,
481 std::vector<Diag> Diags) {
482 // We need to serialize access to resulting diagnostics to avoid calling
483 // `onDiagnosticsReady` in the wrong order.
484 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
485 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[File];
Ilya Biryukov929697b2018-01-25 14:19:21 +0000486
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000487 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
488 // implementation diagnostics will not be reported after version counters'
489 // overflow. This should not happen in practice, since DocVersion is a
490 // 64-bit unsigned integer.
491 if (Version < LastReportedDiagsVersion)
492 return;
493 LastReportedDiagsVersion = Version;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000494
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000495 DiagConsumer.onDiagnosticsReady(File, std::move(Diags));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000496}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000497
498void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
499 // FIXME: Do nothing for now. This will be used for indexing and potentially
500 // invalidating other caches.
501}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000502
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000503void ClangdServer::workspaceSymbols(
504 StringRef Query, int Limit, Callback<std::vector<SymbolInformation>> CB) {
505 CB(clangd::getWorkspaceSymbols(Query, Limit, Index));
506}
507
Ilya Biryukovdf842342018-01-25 14:32:21 +0000508std::vector<std::pair<Path, std::size_t>>
509ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000510 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000511}
Sam McCall0bb24cd2018-02-13 08:59:23 +0000512
513LLVM_NODISCARD bool
514ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
515 return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds));
516}