blob: 88b0664d737ffdc5dd12241927f1d842d37f917f [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
Ilya Biryukov22602992017-05-30 15:11:02 +000068Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000069RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000070 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000071}
72
Sam McCalladccab62017-11-23 16:58:22 +000073ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
74 DiagnosticsConsumer &DiagConsumer,
75 FileSystemProvider &FSProvider,
76 unsigned AsyncThreadsCount,
Ilya Biryukov940901e2017-12-13 12:51:22 +000077 bool StorePreamblesInMemory,
Haojian Wuba28e9a2018-01-10 14:44:34 +000078 bool BuildDynamicSymbolIndex, SymbolIndex *StaticIdx,
Sam McCalld1e0deb2018-03-02 08:56:37 +000079 llvm::Optional<StringRef> ResourceDir,
80 std::chrono::steady_clock::duration UpdateDebounce)
Ilya Biryukov929697b2018-01-25 14:19:21 +000081 : CompileArgs(CDB,
82 ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
83 DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Eric Liubfac8f72017-12-19 18:00:37 +000084 FileIdx(BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000085 PCHs(std::make_shared<PCHContainerOperations>()),
86 // Pass a callback into `WorkScheduler` to extract symbols from a newly
87 // parsed file and rebuild the file index synchronously each time an AST
88 // is parsed.
Eric Liubfac8f72017-12-19 18:00:37 +000089 // FIXME(ioeric): this can be slow and we may be able to index on less
90 // critical paths.
Sam McCalld1a7a372018-01-31 13:40:48 +000091 WorkScheduler(AsyncThreadsCount, StorePreamblesInMemory,
92 FileIdx
93 ? [this](PathRef Path,
94 ParsedAST *AST) { FileIdx->update(Path, AST); }
Sam McCalld1e0deb2018-03-02 08:56:37 +000095 : ASTParsedCallback(),
96 UpdateDebounce) {
Sam McCall0faecf02018-01-15 12:33:00 +000097 if (FileIdx && StaticIdx) {
98 MergedIndex = mergeIndex(FileIdx.get(), StaticIdx);
99 Index = MergedIndex.get();
100 } else if (FileIdx)
101 Index = FileIdx.get();
102 else if (StaticIdx)
103 Index = StaticIdx;
104 else
105 Index = nullptr;
106}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000107
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000108void ClangdServer::setRootPath(PathRef RootPath) {
109 std::string NewRootPath = llvm::sys::path::convert_to_slash(
110 RootPath, llvm::sys::path::Style::posix);
111 if (llvm::sys::fs::is_directory(NewRootPath))
112 this->RootPath = NewRootPath;
113}
114
Sam McCall568e17f2018-02-22 13:11:12 +0000115void ClangdServer::addDocument(PathRef File, StringRef Contents,
116 WantDiagnostics WantDiags) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000117 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000118 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Sam McCall0bb24cd2018-02-13 08:59:23 +0000119 scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
Sam McCall568e17f2018-02-22 13:11:12 +0000120 WantDiags, std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000121}
122
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000123void ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000124 DraftMgr.removeDraft(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000125 CompileArgs.invalidate(File);
Ilya Biryukov7e5ee262018-02-08 07:37:35 +0000126 WorkScheduler.remove(File);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000127}
128
Sam McCall0bb24cd2018-02-13 08:59:23 +0000129void ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000130 auto FileContents = DraftMgr.getDraft(File);
131 assert(FileContents.Draft &&
132 "forceReparse() was called for non-added document");
133
Ilya Biryukov929697b2018-01-25 14:19:21 +0000134 // forceReparse promises to request new compilation flags from CDB, so we
135 // remove any cahced flags.
136 CompileArgs.invalidate(File);
137
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000138 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Sam McCall568e17f2018-02-22 13:11:12 +0000139 scheduleReparseAndDiags(File, std::move(FileContents), WantDiagnostics::Yes,
140 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000141}
142
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000143void ClangdServer::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000144 PathRef File, Position Pos, const clangd::CodeCompleteOptions &Opts,
145 UniqueFunction<void(Tagged<CompletionList>)> Callback,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000146 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000147 using CallbackType = UniqueFunction<void(Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000148
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000149 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000150 if (UsedFS)
151 *UsedFS = TaggedFS.Value;
152
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000153 // Copy completion options for passing them to async task handler.
154 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000155 if (!CodeCompleteOpts.Index) // Respect overridden index.
156 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000157
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000158 VersionedDraft Latest = DraftMgr.getDraft(File);
159 // FIXME(sammccall): return error for consistency?
160 assert(Latest.Draft && "codeComplete called for non-added document");
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000161
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000162 // Copy PCHs to avoid accessing this->PCHs concurrently
163 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000164 auto Task = [PCHs, Pos, TaggedFS, CodeCompleteOpts](
Sam McCalld1a7a372018-01-31 13:40:48 +0000165 std::string Contents, Path File, CallbackType Callback,
166 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000167 assert(IP && "error when trying to read preamble for codeComplete");
168 auto PreambleData = IP->Preamble;
169 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000170
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000171 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
172 // both the old and the new version in case only one of them matches.
173 CompletionList Result = clangd::codeComplete(
Sam McCalld1a7a372018-01-31 13:40:48 +0000174 File, Command, PreambleData ? &PreambleData->Preamble : nullptr,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000175 Contents, Pos, TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000176
Sam McCalld1a7a372018-01-31 13:40:48 +0000177 Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000178 };
179
Sam McCall091557d2018-02-23 07:54:17 +0000180 WorkScheduler.runWithPreamble(
181 "CodeComplete", File,
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000182 Bind(Task, std::move(*Latest.Draft), File.str(), std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000183}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000184
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000185void ClangdServer::signatureHelp(
186 PathRef File, Position Pos,
187 UniqueFunction<void(llvm::Expected<Tagged<SignatureHelp>>)> Callback,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000188 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000189 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
190 if (UsedFS)
191 *UsedFS = TaggedFS.Value;
192
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000193 VersionedDraft Latest = DraftMgr.getDraft(File);
194 if (!Latest.Draft)
195 return Callback(llvm::make_error<llvm::StringError>(
196 "signatureHelp is called for non-added document",
197 llvm::errc::invalid_argument));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000198
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000199 auto PCHs = this->PCHs;
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000200 auto Action = [Pos, TaggedFS, PCHs](std::string Contents, Path File,
201 decltype(Callback) Callback,
202 llvm::Expected<InputsAndPreamble> IP) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000203 if (!IP)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000204 return Callback(IP.takeError());
205
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000206 auto PreambleData = IP->Preamble;
207 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000208 Callback(make_tagged(
Sam McCalld1a7a372018-01-31 13:40:48 +0000209 clangd::signatureHelp(File, Command,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000210 PreambleData ? &PreambleData->Preamble : nullptr,
211 Contents, Pos, TaggedFS.Value, PCHs),
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000212 TaggedFS.Tag));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000213 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000214
Sam McCalldb3ea4c2018-02-27 17:15:50 +0000215 WorkScheduler.runWithPreamble(
216 "SignatureHelp", File,
217 Bind(Action, std::move(*Latest.Draft), File.str(), std::move(Callback)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000218}
219
Raoul Wols212bcf82017-12-12 20:25:06 +0000220llvm::Expected<tooling::Replacements>
221ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000222 size_t Begin = positionToOffset(Code, Rng.start);
223 size_t Len = positionToOffset(Code, Rng.end) - Begin;
224 return formatCode(Code, File, {tooling::Range(Begin, Len)});
225}
226
Raoul Wols212bcf82017-12-12 20:25:06 +0000227llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
228 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000229 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000230 return formatCode(Code, File, {tooling::Range(0, Code.size())});
231}
232
Raoul Wols212bcf82017-12-12 20:25:06 +0000233llvm::Expected<tooling::Replacements>
234ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000235 // Look for the previous opening brace from the character position and
236 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000237 size_t CursorPos = positionToOffset(Code, Pos);
238 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
239 if (PreviousLBracePos == StringRef::npos)
240 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000241 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000242
243 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
244}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000245
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000246void ClangdServer::rename(
247 PathRef File, Position Pos, llvm::StringRef NewName,
248 UniqueFunction<void(Expected<std::vector<tooling::Replacement>>)>
249 Callback) {
250 auto Action = [Pos](Path File, std::string NewName,
251 decltype(Callback) Callback,
252 Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000253 if (!InpAST)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000254 return Callback(InpAST.takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000255 auto &AST = InpAST->AST;
256
257 RefactoringResultCollector ResultCollector;
258 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000259 const FileEntry *FE =
260 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
261 if (!FE)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000262 return Callback(llvm::make_error<llvm::StringError>(
263 "rename called for non-added document",
264 llvm::errc::invalid_argument));
Haojian Wu345099c2017-11-09 11:30:04 +0000265 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000266 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000267 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000268 AST.getASTContext().getSourceManager());
269 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000270 auto Rename = clang::tooling::RenameOccurrences::initiate(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000271 Context, SourceRange(SourceLocationBeg), NewName);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000272 if (!Rename)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000273 return Callback(Rename.takeError());
Haojian Wu345099c2017-11-09 11:30:04 +0000274
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000275 Rename->invoke(ResultCollector, Context);
276
277 assert(ResultCollector.Result.hasValue());
278 if (!ResultCollector.Result.getValue())
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000279 return Callback(ResultCollector.Result->takeError());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000280
281 std::vector<tooling::Replacement> Replacements;
282 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
283 tooling::Replacements ChangeReps = Change.getReplacements();
284 for (const auto &Rep : ChangeReps) {
285 // FIXME: Right now we only support renaming the main file, so we
286 // drop replacements not for the main file. In the future, we might
287 // consider to support:
288 // * rename in any included header
289 // * rename only in the "main" header
290 // * provide an error if there are symbols we won't rename (e.g.
291 // std::vector)
292 // * rename globally in project
293 // * rename in open files
294 if (Rep.getFilePath() == File)
295 Replacements.push_back(Rep);
296 }
Haojian Wu345099c2017-11-09 11:30:04 +0000297 }
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000298 return Callback(Replacements);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000299 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000300
301 WorkScheduler.runWithAST(
Sam McCallc901c5d2018-02-19 09:56:28 +0000302 "Rename", File,
Sam McCall091557d2018-02-23 07:54:17 +0000303 Bind(Action, File.str(), NewName.str(), std::move(Callback)));
Haojian Wu345099c2017-11-09 11:30:04 +0000304}
305
Eric Liu6c8e8582018-02-26 08:32:13 +0000306/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
307/// include.
308static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
309 llvm::StringRef HintPath) {
310 if (isLiteralInclude(Header))
311 return HeaderFile{Header.str(), /*Verbatim=*/true};
312 auto U = URI::parse(Header);
313 if (!U)
314 return U.takeError();
315 auto Resolved = URI::resolve(*U, HintPath);
316 if (!Resolved)
317 return Resolved.takeError();
318 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
319};
320
Eric Liuc5105f92018-02-16 14:15:55 +0000321Expected<tooling::Replacements>
322ClangdServer::insertInclude(PathRef File, StringRef Code,
Eric Liu6c8e8582018-02-26 08:32:13 +0000323 StringRef DeclaringHeader,
324 StringRef InsertedHeader) {
325 assert(!DeclaringHeader.empty() && !InsertedHeader.empty());
Eric Liuc5105f92018-02-16 14:15:55 +0000326 std::string ToInclude;
Eric Liu6c8e8582018-02-26 08:32:13 +0000327 auto ResolvedOrginal = toHeaderFile(DeclaringHeader, File);
328 if (!ResolvedOrginal)
329 return ResolvedOrginal.takeError();
330 auto ResolvedPreferred = toHeaderFile(InsertedHeader, File);
331 if (!ResolvedPreferred)
332 return ResolvedPreferred.takeError();
333 tooling::CompileCommand CompileCommand = CompileArgs.getCompileCommand(File);
334 auto Include = calculateIncludePath(
335 File, Code, *ResolvedOrginal, *ResolvedPreferred, CompileCommand,
336 FSProvider.getTaggedFileSystem(File).Value);
337 if (!Include)
338 return Include.takeError();
339 if (Include->empty())
340 return tooling::Replacements();
341 ToInclude = std::move(*Include);
Eric Liuc5105f92018-02-16 14:15:55 +0000342
343 auto Style = format::getStyle("file", File, "llvm");
344 if (!Style) {
345 llvm::consumeError(Style.takeError());
346 // FIXME(ioeric): needs more consistent style support in clangd server.
347 Style = format::getLLVMStyle();
348 }
349 // Replacement with offset UINT_MAX and length 0 will be treated as include
350 // insertion.
351 tooling::Replacement R(File, /*Offset=*/UINT_MAX, 0, "#include " + ToInclude);
352 return format::cleanupAroundReplacements(Code, tooling::Replacements(R),
353 *Style);
354}
355
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000356llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
357 auto Latest = DraftMgr.getDraft(File);
358 if (!Latest.Draft)
359 return llvm::None;
360 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000361}
362
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000363void ClangdServer::dumpAST(PathRef File,
364 UniqueFunction<void(std::string)> Callback) {
365 auto Action = [](decltype(Callback) Callback,
366 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000367 if (!InpAST) {
368 ignoreError(InpAST.takeError());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000369 return Callback("<no-ast>");
Ilya Biryukov02d58702017-08-01 15:51:38 +0000370 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000371 std::string Result;
372
373 llvm::raw_string_ostream ResultOS(Result);
374 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000375 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000376
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000377 Callback(Result);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000378 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000379
Sam McCall091557d2018-02-23 07:54:17 +0000380 WorkScheduler.runWithAST("DumpAST", File, Bind(Action, std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000381}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000382
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000383void ClangdServer::findDefinitions(
384 PathRef File, Position Pos,
385 UniqueFunction<void(llvm::Expected<Tagged<std::vector<Location>>>)>
386 Callback) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000387 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000388 auto Action = [Pos, TaggedFS](decltype(Callback) Callback,
389 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000390 if (!InpAST)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000391 return Callback(InpAST.takeError());
Sam McCalld1a7a372018-01-31 13:40:48 +0000392 auto Result = clangd::findDefinitions(InpAST->AST, Pos);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000393 Callback(make_tagged(std::move(Result), TaggedFS.Tag));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000394 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000395
Sam McCallc901c5d2018-02-19 09:56:28 +0000396 WorkScheduler.runWithAST("Definitions", File,
Sam McCall091557d2018-02-23 07:54:17 +0000397 Bind(Action, std::move(Callback)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000398}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000399
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000400llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
401
402 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
403 ".c++", ".m", ".mm"};
404 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
405
406 StringRef PathExt = llvm::sys::path::extension(Path);
407
408 // Lookup in a list of known extensions.
409 auto SourceIter =
410 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
411 [&PathExt](PathRef SourceExt) {
412 return SourceExt.equals_lower(PathExt);
413 });
414 bool IsSource = SourceIter != std::end(SourceExtensions);
415
416 auto HeaderIter =
417 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
418 [&PathExt](PathRef HeaderExt) {
419 return HeaderExt.equals_lower(PathExt);
420 });
421
422 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
423
424 // We can only switch between extensions known extensions.
425 if (!IsSource && !IsHeader)
426 return llvm::None;
427
428 // Array to lookup extensions for the switch. An opposite of where original
429 // extension was found.
430 ArrayRef<StringRef> NewExts;
431 if (IsSource)
432 NewExts = HeaderExtensions;
433 else
434 NewExts = SourceExtensions;
435
436 // Storage for the new path.
437 SmallString<128> NewPath = StringRef(Path);
438
439 // Instance of vfs::FileSystem, used for file existence checks.
440 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
441
442 // Loop through switched extension candidates.
443 for (StringRef NewExt : NewExts) {
444 llvm::sys::path::replace_extension(NewPath, NewExt);
445 if (FS->exists(NewPath))
446 return NewPath.str().str(); // First str() to convert from SmallString to
447 // StringRef, second to convert from StringRef
448 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000449
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000450 // Also check NewExt in upper-case, just in case.
451 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
452 if (FS->exists(NewPath))
453 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000454 }
455
456 return llvm::None;
457}
458
Raoul Wols212bcf82017-12-12 20:25:06 +0000459llvm::Expected<tooling::Replacements>
460ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
461 ArrayRef<tooling::Range> Ranges) {
462 // Call clang-format.
463 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
464 auto StyleOrError =
465 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
466 if (!StyleOrError) {
467 return StyleOrError.takeError();
468 } else {
469 return format::reformat(StyleOrError.get(), Code, Ranges, File);
470 }
471}
472
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000473void ClangdServer::findDocumentHighlights(
474 PathRef File, Position Pos,
475 UniqueFunction<void(llvm::Expected<Tagged<std::vector<DocumentHighlight>>>)>
476 Callback) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000477 auto FileContents = DraftMgr.getDraft(File);
478 if (!FileContents.Draft)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000479 return Callback(llvm::make_error<llvm::StringError>(
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000480 "findDocumentHighlights called on non-added file",
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000481 llvm::errc::invalid_argument));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000482
483 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
484
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000485 auto Action = [TaggedFS, Pos](decltype(Callback) Callback,
486 llvm::Expected<InputsAndAST> InpAST) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000487 if (!InpAST)
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000488 return Callback(InpAST.takeError());
Sam McCalld1a7a372018-01-31 13:40:48 +0000489 auto Result = clangd::findDocumentHighlights(InpAST->AST, Pos);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000490 Callback(make_tagged(std::move(Result), TaggedFS.Tag));
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000491 };
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000492
Sam McCallc901c5d2018-02-19 09:56:28 +0000493 WorkScheduler.runWithAST("Highlights", File,
Sam McCall091557d2018-02-23 07:54:17 +0000494 Bind(Action, std::move(Callback)));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000495}
496
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000497void ClangdServer::findHover(
498 PathRef File, Position Pos,
499 UniqueFunction<void(llvm::Expected<Tagged<Hover>>)> Callback) {
500 Hover FinalHover;
501 auto FileContents = DraftMgr.getDraft(File);
502 if (!FileContents.Draft)
503 return Callback(llvm::make_error<llvm::StringError>(
504 "findHover called on non-added file", llvm::errc::invalid_argument));
505
506 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
507
508 auto Action = [Pos, TaggedFS](decltype(Callback) Callback,
509 llvm::Expected<InputsAndAST> InpAST) {
510 if (!InpAST)
511 return Callback(InpAST.takeError());
512
513 Hover Result = clangd::getHover(InpAST->AST, Pos);
514 Callback(make_tagged(std::move(Result), TaggedFS.Tag));
515 };
516
Sam McCall091557d2018-02-23 07:54:17 +0000517 WorkScheduler.runWithAST("Hover", File, Bind(Action, std::move(Callback)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000518}
519
Sam McCall0bb24cd2018-02-13 08:59:23 +0000520void ClangdServer::scheduleReparseAndDiags(
Sam McCall568e17f2018-02-22 13:11:12 +0000521 PathRef File, VersionedDraft Contents, WantDiagnostics WantDiags,
Ilya Biryukov929697b2018-01-25 14:19:21 +0000522 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000523 tooling::CompileCommand Command = CompileArgs.getCompileCommand(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000524
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000525 DocVersion Version = Contents.Version;
526 Path FileStr = File.str();
527 VFSTag Tag = std::move(TaggedFS.Tag);
528
Sam McCall568e17f2018-02-22 13:11:12 +0000529 auto Callback = [this, Version, FileStr,
530 Tag](std::vector<DiagWithFixIts> Diags) {
Ilya Biryukov47f22022017-09-20 12:58:55 +0000531 // We need to serialize access to resulting diagnostics to avoid calling
532 // `onDiagnosticsReady` in the wrong order.
533 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
534 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
535 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
536 // implementation diagnostics will not be reported after version counters'
537 // overflow. This should not happen in practice, since DocVersion is a
538 // 64-bit unsigned integer.
539 if (Version < LastReportedDiagsVersion)
540 return;
541 LastReportedDiagsVersion = Version;
542
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000543 DiagConsumer.onDiagnosticsReady(
Sam McCall568e17f2018-02-22 13:11:12 +0000544 FileStr, make_tagged(std::move(Diags), std::move(Tag)));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000545 };
546
Sam McCalld1a7a372018-01-31 13:40:48 +0000547 WorkScheduler.update(File,
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000548 ParseInputs{std::move(Command),
549 std::move(TaggedFS.Value),
550 std::move(*Contents.Draft)},
Sam McCall568e17f2018-02-22 13:11:12 +0000551 WantDiags, std::move(Callback));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000552}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000553
Simon Marchi5178f922018-02-22 14:00:39 +0000554void ClangdServer::reparseOpenedFiles() {
555 for (const Path &FilePath : DraftMgr.getActiveFiles())
556 forceReparse(FilePath);
557}
558
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000559void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
560 // FIXME: Do nothing for now. This will be used for indexing and potentially
561 // invalidating other caches.
562}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000563
564std::vector<std::pair<Path, std::size_t>>
565ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000566 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000567}
Sam McCall0bb24cd2018-02-13 08:59:23 +0000568
569LLVM_NODISCARD bool
570ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
571 return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds));
572}