blob: 2f7d5a2f35175a7b3d332025edcf861542e60a1a [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;
162 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000163
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000164 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
165 // both the old and the new version in case only one of them matches.
166 CompletionList Result = clangd::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000167 File, Command, PreambleData ? &PreambleData->Preamble : nullptr,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000168 Contents, Pos, FS, PCHs, CodeCompleteOpts);
169 CB(std::move(Result));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000170 };
171
Sam McCall091557d2018-02-23 07:54:17 +0000172 WorkScheduler.runWithPreamble(
173 "CodeComplete", File,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000174 Bind(Task, std::move(*Latest.Draft), File.str(), std::move(CB)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000175}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000176
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000177void ClangdServer::signatureHelp(PathRef File, Position Pos,
178 Callback<SignatureHelp> CB) {
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000179 VersionedDraft Latest = DraftMgr.getDraft(File);
180 if (!Latest.Draft)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000181 return CB(llvm::make_error<llvm::StringError>(
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000182 "signatureHelp is called for non-added document",
183 llvm::errc::invalid_argument));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000184
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000185 auto PCHs = this->PCHs;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000186 auto FS = FSProvider.getFileSystem();
187 auto Action = [Pos, FS, PCHs](std::string Contents, Path File,
188 Callback<SignatureHelp> CB,
189 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000190 if (!IP)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000191 return CB(IP.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000192
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000193 auto PreambleData = IP->Preamble;
194 auto &Command = IP->Inputs.CompileCommand;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000195 CB(clangd::signatureHelp(File, Command,
196 PreambleData ? &PreambleData->Preamble : nullptr,
197 Contents, Pos, FS, PCHs));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000198 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000199
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000200 WorkScheduler.runWithPreamble(
201 "SignatureHelp", File,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000202 Bind(Action, std::move(*Latest.Draft), File.str(), std::move(CB)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000203}
204
Raoul Wols212bcf82017-12-12 20:25:06 +0000205llvm::Expected<tooling::Replacements>
206ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000207 size_t Begin = positionToOffset(Code, Rng.start);
208 size_t Len = positionToOffset(Code, Rng.end) - Begin;
209 return formatCode(Code, File, {tooling::Range(Begin, Len)});
210}
211
Raoul Wols212bcf82017-12-12 20:25:06 +0000212llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
213 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000214 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000215 return formatCode(Code, File, {tooling::Range(0, Code.size())});
216}
217
Raoul Wols212bcf82017-12-12 20:25:06 +0000218llvm::Expected<tooling::Replacements>
219ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000220 // Look for the previous opening brace from the character position and
221 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000222 size_t CursorPos = positionToOffset(Code, Pos);
223 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
224 if (PreviousLBracePos == StringRef::npos)
225 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000226 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000227
228 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
229}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000230
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000231void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
232 Callback<std::vector<tooling::Replacement>> CB) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000233 auto Action = [Pos](Path File, std::string NewName,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000234 Callback<std::vector<tooling::Replacement>> CB,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000235 Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000236 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000237 return CB(InpAST.takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000238 auto &AST = InpAST->AST;
239
240 RefactoringResultCollector ResultCollector;
241 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000242 const FileEntry *FE =
243 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
244 if (!FE)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000245 return CB(llvm::make_error<llvm::StringError>(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000246 "rename called for non-added document",
247 llvm::errc::invalid_argument));
Haojian Wu345099c2017-11-09 11:30:04 +0000248 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000249 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000250 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000251 AST.getASTContext().getSourceManager());
252 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000253 auto Rename = clang::tooling::RenameOccurrences::initiate(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000254 Context, SourceRange(SourceLocationBeg), NewName);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000255 if (!Rename)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000256 return CB(Rename.takeError());
Haojian Wu345099c2017-11-09 11:30:04 +0000257
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000258 Rename->invoke(ResultCollector, Context);
259
260 assert(ResultCollector.Result.hasValue());
261 if (!ResultCollector.Result.getValue())
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000262 return CB(ResultCollector.Result->takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000263
264 std::vector<tooling::Replacement> Replacements;
265 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
266 tooling::Replacements ChangeReps = Change.getReplacements();
267 for (const auto &Rep : ChangeReps) {
268 // FIXME: Right now we only support renaming the main file, so we
269 // drop replacements not for the main file. In the future, we might
270 // consider to support:
271 // * rename in any included header
272 // * rename only in the "main" header
273 // * provide an error if there are symbols we won't rename (e.g.
274 // std::vector)
275 // * rename globally in project
276 // * rename in open files
277 if (Rep.getFilePath() == File)
278 Replacements.push_back(Rep);
279 }
Haojian Wu345099c2017-11-09 11:30:04 +0000280 }
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000281 return CB(std::move(Replacements));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000282 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000283
284 WorkScheduler.runWithAST(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000285 "Rename", File, Bind(Action, File.str(), NewName.str(), std::move(CB)));
Haojian Wu345099c2017-11-09 11:30:04 +0000286}
287
Eric Liu6c8e8582018-02-26 08:32:13 +0000288/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
289/// include.
290static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
291 llvm::StringRef HintPath) {
292 if (isLiteralInclude(Header))
293 return HeaderFile{Header.str(), /*Verbatim=*/true};
294 auto U = URI::parse(Header);
295 if (!U)
296 return U.takeError();
297 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 Biryukov261c72e2018-01-17 12:30:24 +0000341llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
342 auto Latest = DraftMgr.getDraft(File);
343 if (!Latest.Draft)
344 return llvm::None;
345 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000346}
347
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000348void ClangdServer::dumpAST(PathRef File,
349 UniqueFunction<void(std::string)> Callback) {
350 auto Action = [](decltype(Callback) Callback,
351 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000352 if (!InpAST) {
353 ignoreError(InpAST.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000354 return Callback("<no-ast>");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000355 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000356 std::string Result;
357
358 llvm::raw_string_ostream ResultOS(Result);
359 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000360 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000361
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000362 Callback(Result);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000363 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000364
Sam McCall091557d2018-02-23 07:54:17 +0000365 WorkScheduler.runWithAST("DumpAST", File, Bind(Action, std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000366}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000367
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000368void ClangdServer::findDefinitions(PathRef File, Position Pos,
369 Callback<std::vector<Location>> CB) {
370 auto FS = FSProvider.getFileSystem();
371 auto Action = [Pos, FS](Callback<std::vector<Location>> CB,
372 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000373 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000374 return CB(InpAST.takeError());
375 CB(clangd::findDefinitions(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000376 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000377
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000378 WorkScheduler.runWithAST("Definitions", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000379}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000380
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000381llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
382
383 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
384 ".c++", ".m", ".mm"};
385 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
386
387 StringRef PathExt = llvm::sys::path::extension(Path);
388
389 // Lookup in a list of known extensions.
390 auto SourceIter =
391 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
392 [&PathExt](PathRef SourceExt) {
393 return SourceExt.equals_lower(PathExt);
394 });
395 bool IsSource = SourceIter != std::end(SourceExtensions);
396
397 auto HeaderIter =
398 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
399 [&PathExt](PathRef HeaderExt) {
400 return HeaderExt.equals_lower(PathExt);
401 });
402
403 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
404
405 // We can only switch between extensions known extensions.
406 if (!IsSource && !IsHeader)
407 return llvm::None;
408
409 // Array to lookup extensions for the switch. An opposite of where original
410 // extension was found.
411 ArrayRef<StringRef> NewExts;
412 if (IsSource)
413 NewExts = HeaderExtensions;
414 else
415 NewExts = SourceExtensions;
416
417 // Storage for the new path.
418 SmallString<128> NewPath = StringRef(Path);
419
420 // Instance of vfs::FileSystem, used for file existence checks.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000421 auto FS = FSProvider.getFileSystem();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000422
423 // Loop through switched extension candidates.
424 for (StringRef NewExt : NewExts) {
425 llvm::sys::path::replace_extension(NewPath, NewExt);
426 if (FS->exists(NewPath))
427 return NewPath.str().str(); // First str() to convert from SmallString to
428 // StringRef, second to convert from StringRef
429 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000430
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000431 // Also check NewExt in upper-case, just in case.
432 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
433 if (FS->exists(NewPath))
434 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000435 }
436
437 return llvm::None;
438}
439
Raoul Wols212bcf82017-12-12 20:25:06 +0000440llvm::Expected<tooling::Replacements>
441ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
442 ArrayRef<tooling::Range> Ranges) {
443 // Call clang-format.
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000444 auto FS = FSProvider.getFileSystem();
445 auto Style = format::getStyle("file", File, "LLVM", Code, FS.get());
Eric Liue3395b92018-03-06 10:42:50 +0000446 if (!Style)
447 return Style.takeError();
448
449 tooling::Replacements IncludeReplaces =
450 format::sortIncludes(*Style, Code, Ranges, File);
451 auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
452 if (!Changed)
453 return Changed.takeError();
454
455 return IncludeReplaces.merge(format::reformat(
456 Style.get(), *Changed,
457 tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
458 File));
Raoul Wols212bcf82017-12-12 20:25:06 +0000459}
460
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000461void ClangdServer::findDocumentHighlights(
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000462 PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000463 auto FileContents = DraftMgr.getDraft(File);
464 if (!FileContents.Draft)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000465 return CB(llvm::make_error<llvm::StringError>(
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000466 "findDocumentHighlights called on non-added file",
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000467 llvm::errc::invalid_argument));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000468
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000469 auto FS = FSProvider.getFileSystem();
470 auto Action = [FS, Pos](Callback<std::vector<DocumentHighlight>> CB,
471 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000472 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000473 return CB(InpAST.takeError());
474 CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000475 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000476
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000477 WorkScheduler.runWithAST("Highlights", File, Bind(Action, std::move(CB)));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000478}
479
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000480void ClangdServer::findHover(PathRef File, Position Pos, Callback<Hover> CB) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000481 Hover FinalHover;
482 auto FileContents = DraftMgr.getDraft(File);
483 if (!FileContents.Draft)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000484 return CB(llvm::make_error<llvm::StringError>(
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000485 "findHover called on non-added file", llvm::errc::invalid_argument));
486
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000487 auto FS = FSProvider.getFileSystem();
488 auto Action = [Pos, FS](Callback<Hover> CB,
489 llvm::Expected<InputsAndAST> InpAST) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000490 if (!InpAST)
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000491 return CB(InpAST.takeError());
492 CB(clangd::getHover(InpAST->AST, Pos));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000493 };
494
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000495 WorkScheduler.runWithAST("Hover", File, Bind(Action, std::move(CB)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000496}
497
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000498void ClangdServer::consumeDiagnostics(PathRef File, DocVersion Version,
499 std::vector<Diag> Diags) {
500 // We need to serialize access to resulting diagnostics to avoid calling
501 // `onDiagnosticsReady` in the wrong order.
502 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
503 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[File];
Ilya Biryukov929697b2018-01-25 14:19:21 +0000504
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000505 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
506 // implementation diagnostics will not be reported after version counters'
507 // overflow. This should not happen in practice, since DocVersion is a
508 // 64-bit unsigned integer.
509 if (Version < LastReportedDiagsVersion)
510 return;
511 LastReportedDiagsVersion = Version;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000512
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000513 DiagConsumer.onDiagnosticsReady(File, std::move(Diags));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000514}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000515
Simon Marchi5178f922018-02-22 14:00:39 +0000516void ClangdServer::reparseOpenedFiles() {
517 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukovbec5df22018-03-14 17:08:41 +0000518 addDocument(FilePath, *DraftMgr.getDraft(FilePath).Draft,
519 WantDiagnostics::Auto, /*SkipCache=*/true);
Simon Marchi5178f922018-02-22 14:00:39 +0000520}
521
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000522void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
523 // FIXME: Do nothing for now. This will be used for indexing and potentially
524 // invalidating other caches.
525}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000526
527std::vector<std::pair<Path, std::size_t>>
528ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000529 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000530}
Sam McCall0bb24cd2018-02-13 08:59:23 +0000531
532LLVM_NODISCARD bool
533ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
534 return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds));
535}