Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1 | //===--- 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" |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 11 | #include "clang/Format/Format.h" |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 12 | #include "clang/Frontend/CompilerInstance.h" |
| 13 | #include "clang/Frontend/CompilerInvocation.h" |
| 14 | #include "clang/Tooling/CompilationDatabase.h" |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/ArrayRef.h" |
Benjamin Kramer | ee19f16 | 2017-10-26 12:28:13 +0000 | [diff] [blame^] | 16 | #include "llvm/Support/Errc.h" |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 17 | #include "llvm/Support/FileSystem.h" |
Marc-Andre Laperle | 37de971 | 2017-09-27 15:31:17 +0000 | [diff] [blame] | 18 | #include "llvm/Support/Path.h" |
Ilya Biryukov | f01af68 | 2017-05-23 13:42:59 +0000 | [diff] [blame] | 19 | #include "llvm/Support/raw_ostream.h" |
| 20 | #include <future> |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 21 | |
Ilya Biryukov | 2f31410 | 2017-05-16 10:06:20 +0000 | [diff] [blame] | 22 | using namespace clang; |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 23 | using namespace clang::clangd; |
| 24 | |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 25 | namespace { |
| 26 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 27 | class FulfillPromiseGuard { |
| 28 | public: |
| 29 | FulfillPromiseGuard(std::promise<void> &Promise) : Promise(Promise) {} |
| 30 | |
| 31 | ~FulfillPromiseGuard() { Promise.set_value(); } |
| 32 | |
| 33 | private: |
| 34 | std::promise<void> &Promise; |
| 35 | }; |
| 36 | |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 37 | std::vector<tooling::Replacement> formatCode(StringRef Code, StringRef Filename, |
| 38 | ArrayRef<tooling::Range> Ranges) { |
| 39 | // Call clang-format. |
| 40 | // FIXME: Don't ignore style. |
| 41 | format::FormatStyle Style = format::getLLVMStyle(); |
| 42 | auto Result = format::reformat(Style, Code, Ranges, Filename); |
| 43 | |
| 44 | return std::vector<tooling::Replacement>(Result.begin(), Result.end()); |
| 45 | } |
| 46 | |
Ilya Biryukov | a46f7a9 | 2017-06-28 10:34:50 +0000 | [diff] [blame] | 47 | std::string getStandardResourceDir() { |
| 48 | static int Dummy; // Just an address in this process. |
| 49 | return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy); |
| 50 | } |
| 51 | |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 52 | } // namespace |
| 53 | |
| 54 | size_t clangd::positionToOffset(StringRef Code, Position P) { |
| 55 | size_t Offset = 0; |
| 56 | for (int I = 0; I != P.line; ++I) { |
| 57 | // FIXME: \r\n |
| 58 | // FIXME: UTF-8 |
| 59 | size_t F = Code.find('\n', Offset); |
| 60 | if (F == StringRef::npos) |
| 61 | return 0; // FIXME: Is this reasonable? |
| 62 | Offset = F + 1; |
| 63 | } |
| 64 | return (Offset == 0 ? 0 : (Offset - 1)) + P.character; |
| 65 | } |
| 66 | |
| 67 | /// Turn an offset in Code into a [line, column] pair. |
| 68 | Position clangd::offsetToPosition(StringRef Code, size_t Offset) { |
| 69 | StringRef JustBefore = Code.substr(0, Offset); |
| 70 | // FIXME: \r\n |
| 71 | // FIXME: UTF-8 |
| 72 | int Lines = JustBefore.count('\n'); |
| 73 | int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1; |
| 74 | return {Lines, Cols}; |
| 75 | } |
| 76 | |
Ilya Biryukov | 2260299 | 2017-05-30 15:11:02 +0000 | [diff] [blame] | 77 | Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> |
Ilya Biryukov | af0c04b | 2017-06-14 09:46:44 +0000 | [diff] [blame] | 78 | RealFileSystemProvider::getTaggedFileSystem(PathRef File) { |
Ilya Biryukov | 2260299 | 2017-05-30 15:11:02 +0000 | [diff] [blame] | 79 | return make_tagged(vfs::getRealFileSystem(), VFSTag()); |
Ilya Biryukov | 0f62ed2 | 2017-05-26 12:26:51 +0000 | [diff] [blame] | 80 | } |
| 81 | |
Ilya Biryukov | db8b2d7 | 2017-08-14 08:45:47 +0000 | [diff] [blame] | 82 | unsigned clangd::getDefaultAsyncThreadsCount() { |
| 83 | unsigned HardwareConcurrency = std::thread::hardware_concurrency(); |
| 84 | // C++ standard says that hardware_concurrency() |
| 85 | // may return 0, fallback to 1 worker thread in |
| 86 | // that case. |
| 87 | if (HardwareConcurrency == 0) |
| 88 | return 1; |
| 89 | return HardwareConcurrency; |
| 90 | } |
| 91 | |
| 92 | ClangdScheduler::ClangdScheduler(unsigned AsyncThreadsCount) |
| 93 | : RunSynchronously(AsyncThreadsCount == 0) { |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 94 | if (RunSynchronously) { |
| 95 | // Don't start the worker thread if we're running synchronously |
| 96 | return; |
| 97 | } |
| 98 | |
Ilya Biryukov | db8b2d7 | 2017-08-14 08:45:47 +0000 | [diff] [blame] | 99 | Workers.reserve(AsyncThreadsCount); |
| 100 | for (unsigned I = 0; I < AsyncThreadsCount; ++I) { |
| 101 | Workers.push_back(std::thread([this]() { |
| 102 | while (true) { |
Ilya Biryukov | 08e6ccb | 2017-10-09 16:26:26 +0000 | [diff] [blame] | 103 | UniqueFunction<void()> Request; |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 104 | |
Ilya Biryukov | db8b2d7 | 2017-08-14 08:45:47 +0000 | [diff] [blame] | 105 | // Pick request from the queue |
| 106 | { |
| 107 | std::unique_lock<std::mutex> Lock(Mutex); |
| 108 | // Wait for more requests. |
| 109 | RequestCV.wait(Lock, |
| 110 | [this] { return !RequestQueue.empty() || Done; }); |
| 111 | if (Done) |
| 112 | return; |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 113 | |
Ilya Biryukov | db8b2d7 | 2017-08-14 08:45:47 +0000 | [diff] [blame] | 114 | assert(!RequestQueue.empty() && "RequestQueue was empty"); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 115 | |
Ilya Biryukov | db8b2d7 | 2017-08-14 08:45:47 +0000 | [diff] [blame] | 116 | // We process requests starting from the front of the queue. Users of |
| 117 | // ClangdScheduler have a way to prioritise their requests by putting |
| 118 | // them to the either side of the queue (using either addToEnd or |
| 119 | // addToFront). |
| 120 | Request = std::move(RequestQueue.front()); |
| 121 | RequestQueue.pop_front(); |
| 122 | } // unlock Mutex |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 123 | |
Ilya Biryukov | 08e6ccb | 2017-10-09 16:26:26 +0000 | [diff] [blame] | 124 | Request(); |
Ilya Biryukov | db8b2d7 | 2017-08-14 08:45:47 +0000 | [diff] [blame] | 125 | } |
| 126 | })); |
| 127 | } |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 128 | } |
| 129 | |
| 130 | ClangdScheduler::~ClangdScheduler() { |
| 131 | if (RunSynchronously) |
| 132 | return; // no worker thread is running in that case |
| 133 | |
| 134 | { |
| 135 | std::lock_guard<std::mutex> Lock(Mutex); |
| 136 | // Wake up the worker thread |
| 137 | Done = true; |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 138 | } // unlock Mutex |
Ilya Biryukov | db8b2d7 | 2017-08-14 08:45:47 +0000 | [diff] [blame] | 139 | RequestCV.notify_all(); |
| 140 | |
| 141 | for (auto &Worker : Workers) |
| 142 | Worker.join(); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 143 | } |
| 144 | |
Ilya Biryukov | 103c951 | 2017-06-13 15:59:43 +0000 | [diff] [blame] | 145 | ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB, |
| 146 | DiagnosticsConsumer &DiagConsumer, |
| 147 | FileSystemProvider &FSProvider, |
Ilya Biryukov | b080cb1 | 2017-10-23 14:46:48 +0000 | [diff] [blame] | 148 | unsigned AsyncThreadsCount, |
| 149 | clangd::CodeCompleteOptions CodeCompleteOpts, |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 150 | clangd::Logger &Logger, |
Ilya Biryukov | a46f7a9 | 2017-06-28 10:34:50 +0000 | [diff] [blame] | 151 | llvm::Optional<StringRef> ResourceDir) |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 152 | : Logger(Logger), CDB(CDB), DiagConsumer(DiagConsumer), |
| 153 | FSProvider(FSProvider), |
Ilya Biryukov | a46f7a9 | 2017-06-28 10:34:50 +0000 | [diff] [blame] | 154 | ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()), |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 155 | PCHs(std::make_shared<PCHContainerOperations>()), |
Ilya Biryukov | b080cb1 | 2017-10-23 14:46:48 +0000 | [diff] [blame] | 156 | CodeCompleteOpts(CodeCompleteOpts), WorkScheduler(AsyncThreadsCount) {} |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 157 | |
Marc-Andre Laperle | 37de971 | 2017-09-27 15:31:17 +0000 | [diff] [blame] | 158 | void ClangdServer::setRootPath(PathRef RootPath) { |
| 159 | std::string NewRootPath = llvm::sys::path::convert_to_slash( |
| 160 | RootPath, llvm::sys::path::Style::posix); |
| 161 | if (llvm::sys::fs::is_directory(NewRootPath)) |
| 162 | this->RootPath = NewRootPath; |
| 163 | } |
| 164 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 165 | std::future<void> ClangdServer::addDocument(PathRef File, StringRef Contents) { |
Ilya Biryukov | f01af68 | 2017-05-23 13:42:59 +0000 | [diff] [blame] | 166 | DocVersion Version = DraftMgr.updateDraft(File, Contents); |
Ilya Biryukov | f01af68 | 2017-05-23 13:42:59 +0000 | [diff] [blame] | 167 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 168 | auto TaggedFS = FSProvider.getTaggedFileSystem(File); |
Marc-Andre Laperle | 37de971 | 2017-09-27 15:31:17 +0000 | [diff] [blame] | 169 | std::shared_ptr<CppFile> Resources = Units.getOrCreateFile( |
| 170 | File, ResourceDir, CDB, PCHs, TaggedFS.Value, Logger); |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 171 | return scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()}, |
| 172 | std::move(Resources), std::move(TaggedFS)); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 173 | } |
| 174 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 175 | std::future<void> ClangdServer::removeDocument(PathRef File) { |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 176 | DraftMgr.removeDraft(File); |
| 177 | std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File); |
| 178 | return scheduleCancelRebuild(std::move(Resources)); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 179 | } |
| 180 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 181 | std::future<void> ClangdServer::forceReparse(PathRef File) { |
Ilya Biryukov | 91dbf5b | 2017-08-14 08:37:32 +0000 | [diff] [blame] | 182 | auto FileContents = DraftMgr.getDraft(File); |
| 183 | assert(FileContents.Draft && |
| 184 | "forceReparse() was called for non-added document"); |
| 185 | |
| 186 | auto TaggedFS = FSProvider.getTaggedFileSystem(File); |
| 187 | auto Recreated = Units.recreateFileIfCompileCommandChanged( |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 188 | File, ResourceDir, CDB, PCHs, TaggedFS.Value, Logger); |
Ilya Biryukov | 91dbf5b | 2017-08-14 08:37:32 +0000 | [diff] [blame] | 189 | |
| 190 | // Note that std::future from this cleanup action is ignored. |
| 191 | scheduleCancelRebuild(std::move(Recreated.RemovedFile)); |
| 192 | // Schedule a reparse. |
| 193 | return scheduleReparseAndDiags(File, std::move(FileContents), |
| 194 | std::move(Recreated.FileInCollection), |
| 195 | std::move(TaggedFS)); |
Ilya Biryukov | 0f62ed2 | 2017-05-26 12:26:51 +0000 | [diff] [blame] | 196 | } |
| 197 | |
Ilya Biryukov | dcd2169 | 2017-10-05 17:04:13 +0000 | [diff] [blame] | 198 | std::future<Tagged<std::vector<CompletionItem>>> |
Ilya Biryukov | 0e27ce4 | 2017-06-13 14:15:56 +0000 | [diff] [blame] | 199 | ClangdServer::codeComplete(PathRef File, Position Pos, |
Ilya Biryukov | ed99e4c | 2017-07-31 17:09:29 +0000 | [diff] [blame] | 200 | llvm::Optional<StringRef> OverridenContents, |
| 201 | IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) { |
Ilya Biryukov | 90bbcfd | 2017-10-25 09:35:10 +0000 | [diff] [blame] | 202 | using ResultType = Tagged<std::vector<CompletionItem>>; |
| 203 | |
| 204 | std::promise<ResultType> ResultPromise; |
| 205 | |
| 206 | auto Callback = [](std::promise<ResultType> ResultPromise, |
| 207 | ResultType Result) -> void { |
| 208 | ResultPromise.set_value(std::move(Result)); |
| 209 | }; |
| 210 | |
| 211 | std::future<ResultType> ResultFuture = ResultPromise.get_future(); |
| 212 | codeComplete(BindWithForward(Callback, std::move(ResultPromise)), File, Pos, |
| 213 | OverridenContents, UsedFS); |
| 214 | return ResultFuture; |
| 215 | } |
| 216 | |
| 217 | void ClangdServer::codeComplete( |
| 218 | UniqueFunction<void(Tagged<std::vector<CompletionItem>>)> Callback, |
| 219 | PathRef File, Position Pos, llvm::Optional<StringRef> OverridenContents, |
| 220 | IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) { |
| 221 | using CallbackType = |
| 222 | UniqueFunction<void(Tagged<std::vector<CompletionItem>>)>; |
| 223 | |
Ilya Biryukov | dcd2169 | 2017-10-05 17:04:13 +0000 | [diff] [blame] | 224 | std::string Contents; |
| 225 | if (OverridenContents) { |
| 226 | Contents = *OverridenContents; |
| 227 | } else { |
Ilya Biryukov | 0e27ce4 | 2017-06-13 14:15:56 +0000 | [diff] [blame] | 228 | auto FileContents = DraftMgr.getDraft(File); |
| 229 | assert(FileContents.Draft && |
| 230 | "codeComplete is called for non-added document"); |
| 231 | |
Ilya Biryukov | dcd2169 | 2017-10-05 17:04:13 +0000 | [diff] [blame] | 232 | Contents = std::move(*FileContents.Draft); |
Ilya Biryukov | 0e27ce4 | 2017-06-13 14:15:56 +0000 | [diff] [blame] | 233 | } |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 234 | |
Ilya Biryukov | af0c04b | 2017-06-14 09:46:44 +0000 | [diff] [blame] | 235 | auto TaggedFS = FSProvider.getTaggedFileSystem(File); |
Ilya Biryukov | ed99e4c | 2017-07-31 17:09:29 +0000 | [diff] [blame] | 236 | if (UsedFS) |
| 237 | *UsedFS = TaggedFS.Value; |
| 238 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 239 | std::shared_ptr<CppFile> Resources = Units.getFile(File); |
| 240 | assert(Resources && "Calling completion on non-added file"); |
| 241 | |
Ilya Biryukov | dcd2169 | 2017-10-05 17:04:13 +0000 | [diff] [blame] | 242 | // Remember the current Preamble and use it when async task starts executing. |
| 243 | // At the point when async task starts executing, we may have a different |
| 244 | // Preamble in Resources. However, we assume the Preamble that we obtain here |
| 245 | // is reusable in completion more often. |
| 246 | std::shared_ptr<const PreambleData> Preamble = |
| 247 | Resources->getPossiblyStalePreamble(); |
| 248 | // A task that will be run asynchronously. |
Ilya Biryukov | 90bbcfd | 2017-10-25 09:35:10 +0000 | [diff] [blame] | 249 | auto Task = |
| 250 | // 'mutable' to reassign Preamble variable. |
| 251 | [=](CallbackType Callback) mutable { |
| 252 | if (!Preamble) { |
| 253 | // Maybe we built some preamble before processing this request. |
| 254 | Preamble = Resources->getPossiblyStalePreamble(); |
| 255 | } |
| 256 | // FIXME(ibiryukov): even if Preamble is non-null, we may want to check |
| 257 | // both the old and the new version in case only one of them matches. |
Ilya Biryukov | dcd2169 | 2017-10-05 17:04:13 +0000 | [diff] [blame] | 258 | |
Ilya Biryukov | 90bbcfd | 2017-10-25 09:35:10 +0000 | [diff] [blame] | 259 | std::vector<CompletionItem> Result = clangd::codeComplete( |
| 260 | File, Resources->getCompileCommand(), |
| 261 | Preamble ? &Preamble->Preamble : nullptr, Contents, Pos, |
| 262 | TaggedFS.Value, PCHs, CodeCompleteOpts, Logger); |
Ilya Biryukov | dcd2169 | 2017-10-05 17:04:13 +0000 | [diff] [blame] | 263 | |
Ilya Biryukov | 90bbcfd | 2017-10-25 09:35:10 +0000 | [diff] [blame] | 264 | Callback(make_tagged(std::move(Result), std::move(TaggedFS.Tag))); |
| 265 | }; |
| 266 | |
| 267 | WorkScheduler.addToFront(std::move(Task), std::move(Callback)); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 268 | } |
Ilya Biryukov | f01af68 | 2017-05-23 13:42:59 +0000 | [diff] [blame] | 269 | |
Benjamin Kramer | ee19f16 | 2017-10-26 12:28:13 +0000 | [diff] [blame^] | 270 | llvm::Expected<Tagged<SignatureHelp>> |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 271 | ClangdServer::signatureHelp(PathRef File, Position Pos, |
| 272 | llvm::Optional<StringRef> OverridenContents, |
| 273 | IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) { |
| 274 | std::string DraftStorage; |
| 275 | if (!OverridenContents) { |
| 276 | auto FileContents = DraftMgr.getDraft(File); |
Benjamin Kramer | ee19f16 | 2017-10-26 12:28:13 +0000 | [diff] [blame^] | 277 | if (!FileContents.Draft) |
| 278 | return llvm::make_error<llvm::StringError>( |
| 279 | "signatureHelp is called for non-added document", |
| 280 | llvm::errc::invalid_argument); |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 281 | |
| 282 | DraftStorage = std::move(*FileContents.Draft); |
| 283 | OverridenContents = DraftStorage; |
| 284 | } |
| 285 | |
| 286 | auto TaggedFS = FSProvider.getTaggedFileSystem(File); |
| 287 | if (UsedFS) |
| 288 | *UsedFS = TaggedFS.Value; |
| 289 | |
| 290 | std::shared_ptr<CppFile> Resources = Units.getFile(File); |
Benjamin Kramer | ee19f16 | 2017-10-26 12:28:13 +0000 | [diff] [blame^] | 291 | if (!Resources) |
| 292 | return llvm::make_error<llvm::StringError>( |
| 293 | "signatureHelp is called for non-added document", |
| 294 | llvm::errc::invalid_argument); |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 295 | |
| 296 | auto Preamble = Resources->getPossiblyStalePreamble(); |
| 297 | auto Result = clangd::signatureHelp(File, Resources->getCompileCommand(), |
| 298 | Preamble ? &Preamble->Preamble : nullptr, |
| 299 | *OverridenContents, Pos, TaggedFS.Value, |
| 300 | PCHs, Logger); |
| 301 | return make_tagged(std::move(Result), TaggedFS.Tag); |
| 302 | } |
| 303 | |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 304 | std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File, |
| 305 | Range Rng) { |
| 306 | std::string Code = getDocument(File); |
| 307 | |
| 308 | size_t Begin = positionToOffset(Code, Rng.start); |
| 309 | size_t Len = positionToOffset(Code, Rng.end) - Begin; |
| 310 | return formatCode(Code, File, {tooling::Range(Begin, Len)}); |
| 311 | } |
| 312 | |
| 313 | std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) { |
| 314 | // Format everything. |
| 315 | std::string Code = getDocument(File); |
| 316 | return formatCode(Code, File, {tooling::Range(0, Code.size())}); |
| 317 | } |
| 318 | |
| 319 | std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File, |
| 320 | Position Pos) { |
| 321 | // Look for the previous opening brace from the character position and |
| 322 | // format starting from there. |
| 323 | std::string Code = getDocument(File); |
| 324 | size_t CursorPos = positionToOffset(Code, Pos); |
| 325 | size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos); |
| 326 | if (PreviousLBracePos == StringRef::npos) |
| 327 | PreviousLBracePos = CursorPos; |
| 328 | size_t Len = 1 + CursorPos - PreviousLBracePos; |
| 329 | |
| 330 | return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)}); |
| 331 | } |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 332 | |
| 333 | std::string ClangdServer::getDocument(PathRef File) { |
| 334 | auto draft = DraftMgr.getDraft(File); |
| 335 | assert(draft.Draft && "File is not tracked, cannot get contents"); |
| 336 | return *draft.Draft; |
| 337 | } |
| 338 | |
Ilya Biryukov | f01af68 | 2017-05-23 13:42:59 +0000 | [diff] [blame] | 339 | std::string ClangdServer::dumpAST(PathRef File) { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 340 | std::shared_ptr<CppFile> Resources = Units.getFile(File); |
| 341 | assert(Resources && "dumpAST is called for non-added document"); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 342 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 343 | std::string Result; |
Ilya Biryukov | 6e1f3b1 | 2017-08-01 18:27:58 +0000 | [diff] [blame] | 344 | Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 345 | llvm::raw_string_ostream ResultOS(Result); |
| 346 | if (AST) { |
| 347 | clangd::dumpAST(*AST, ResultOS); |
| 348 | } else { |
| 349 | ResultOS << "<no-ast>"; |
| 350 | } |
| 351 | ResultOS.flush(); |
Ilya Biryukov | f01af68 | 2017-05-23 13:42:59 +0000 | [diff] [blame] | 352 | }); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 353 | return Result; |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 354 | } |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 355 | |
Benjamin Kramer | ee19f16 | 2017-10-26 12:28:13 +0000 | [diff] [blame^] | 356 | llvm::Expected<Tagged<std::vector<Location>>> |
| 357 | ClangdServer::findDefinitions(PathRef File, Position Pos) { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 358 | auto TaggedFS = FSProvider.getTaggedFileSystem(File); |
| 359 | |
| 360 | std::shared_ptr<CppFile> Resources = Units.getFile(File); |
Benjamin Kramer | ee19f16 | 2017-10-26 12:28:13 +0000 | [diff] [blame^] | 361 | if (!Resources) |
| 362 | return llvm::make_error<llvm::StringError>( |
| 363 | "findDefinitions called on non-added file", |
| 364 | llvm::errc::invalid_argument); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 365 | |
| 366 | std::vector<Location> Result; |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 367 | Resources->getAST().get()->runUnderLock([Pos, &Result, this](ParsedAST *AST) { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 368 | if (!AST) |
| 369 | return; |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 370 | Result = clangd::findDefinitions(*AST, Pos, Logger); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 371 | }); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 372 | return make_tagged(std::move(Result), TaggedFS.Tag); |
| 373 | } |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 374 | |
Marc-Andre Laperle | 6571b3e | 2017-09-28 03:14:40 +0000 | [diff] [blame] | 375 | llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) { |
| 376 | |
| 377 | StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx", |
| 378 | ".c++", ".m", ".mm"}; |
| 379 | StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"}; |
| 380 | |
| 381 | StringRef PathExt = llvm::sys::path::extension(Path); |
| 382 | |
| 383 | // Lookup in a list of known extensions. |
| 384 | auto SourceIter = |
| 385 | std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions), |
| 386 | [&PathExt](PathRef SourceExt) { |
| 387 | return SourceExt.equals_lower(PathExt); |
| 388 | }); |
| 389 | bool IsSource = SourceIter != std::end(SourceExtensions); |
| 390 | |
| 391 | auto HeaderIter = |
| 392 | std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions), |
| 393 | [&PathExt](PathRef HeaderExt) { |
| 394 | return HeaderExt.equals_lower(PathExt); |
| 395 | }); |
| 396 | |
| 397 | bool IsHeader = HeaderIter != std::end(HeaderExtensions); |
| 398 | |
| 399 | // We can only switch between extensions known extensions. |
| 400 | if (!IsSource && !IsHeader) |
| 401 | return llvm::None; |
| 402 | |
| 403 | // Array to lookup extensions for the switch. An opposite of where original |
| 404 | // extension was found. |
| 405 | ArrayRef<StringRef> NewExts; |
| 406 | if (IsSource) |
| 407 | NewExts = HeaderExtensions; |
| 408 | else |
| 409 | NewExts = SourceExtensions; |
| 410 | |
| 411 | // Storage for the new path. |
| 412 | SmallString<128> NewPath = StringRef(Path); |
| 413 | |
| 414 | // Instance of vfs::FileSystem, used for file existence checks. |
| 415 | auto FS = FSProvider.getTaggedFileSystem(Path).Value; |
| 416 | |
| 417 | // Loop through switched extension candidates. |
| 418 | for (StringRef NewExt : NewExts) { |
| 419 | llvm::sys::path::replace_extension(NewPath, NewExt); |
| 420 | if (FS->exists(NewPath)) |
| 421 | return NewPath.str().str(); // First str() to convert from SmallString to |
| 422 | // StringRef, second to convert from StringRef |
| 423 | // to std::string |
Ilya Biryukov | 3333494 | 2017-10-06 14:39:39 +0000 | [diff] [blame] | 424 | |
Marc-Andre Laperle | 6571b3e | 2017-09-28 03:14:40 +0000 | [diff] [blame] | 425 | // Also check NewExt in upper-case, just in case. |
| 426 | llvm::sys::path::replace_extension(NewPath, NewExt.upper()); |
| 427 | if (FS->exists(NewPath)) |
| 428 | return NewPath.str().str(); |
Marc-Andre Laperle | 6571b3e | 2017-09-28 03:14:40 +0000 | [diff] [blame] | 429 | } |
| 430 | |
| 431 | return llvm::None; |
| 432 | } |
| 433 | |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 434 | std::future<void> ClangdServer::scheduleReparseAndDiags( |
| 435 | PathRef File, VersionedDraft Contents, std::shared_ptr<CppFile> Resources, |
| 436 | Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) { |
| 437 | |
| 438 | assert(Contents.Draft && "Draft must have contents"); |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 439 | UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()> |
| 440 | DeferredRebuild = |
| 441 | Resources->deferRebuild(*Contents.Draft, TaggedFS.Value); |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 442 | std::promise<void> DonePromise; |
| 443 | std::future<void> DoneFuture = DonePromise.get_future(); |
| 444 | |
| 445 | DocVersion Version = Contents.Version; |
| 446 | Path FileStr = File; |
| 447 | VFSTag Tag = TaggedFS.Tag; |
| 448 | auto ReparseAndPublishDiags = |
| 449 | [this, FileStr, Version, |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 450 | Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()> |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 451 | DeferredRebuild, |
| 452 | std::promise<void> DonePromise) -> void { |
| 453 | FulfillPromiseGuard Guard(DonePromise); |
| 454 | |
| 455 | auto CurrentVersion = DraftMgr.getVersion(FileStr); |
| 456 | if (CurrentVersion != Version) |
| 457 | return; // This request is outdated |
| 458 | |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 459 | auto Diags = DeferredRebuild(); |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 460 | if (!Diags) |
| 461 | return; // A new reparse was requested before this one completed. |
Ilya Biryukov | 47f2202 | 2017-09-20 12:58:55 +0000 | [diff] [blame] | 462 | |
| 463 | // We need to serialize access to resulting diagnostics to avoid calling |
| 464 | // `onDiagnosticsReady` in the wrong order. |
| 465 | std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex); |
| 466 | DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr]; |
| 467 | // FIXME(ibiryukov): get rid of '<' comparison here. In the current |
| 468 | // implementation diagnostics will not be reported after version counters' |
| 469 | // overflow. This should not happen in practice, since DocVersion is a |
| 470 | // 64-bit unsigned integer. |
| 471 | if (Version < LastReportedDiagsVersion) |
| 472 | return; |
| 473 | LastReportedDiagsVersion = Version; |
| 474 | |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 475 | DiagConsumer.onDiagnosticsReady(FileStr, |
| 476 | make_tagged(std::move(*Diags), Tag)); |
| 477 | }; |
| 478 | |
| 479 | WorkScheduler.addToFront(std::move(ReparseAndPublishDiags), |
| 480 | std::move(DeferredRebuild), std::move(DonePromise)); |
| 481 | return DoneFuture; |
| 482 | } |
| 483 | |
| 484 | std::future<void> |
| 485 | ClangdServer::scheduleCancelRebuild(std::shared_ptr<CppFile> Resources) { |
| 486 | std::promise<void> DonePromise; |
| 487 | std::future<void> DoneFuture = DonePromise.get_future(); |
| 488 | if (!Resources) { |
| 489 | // No need to schedule any cleanup. |
| 490 | DonePromise.set_value(); |
| 491 | return DoneFuture; |
| 492 | } |
| 493 | |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 494 | UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild(); |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 495 | auto CancelReparses = [Resources](std::promise<void> DonePromise, |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 496 | UniqueFunction<void()> DeferredCancel) { |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 497 | FulfillPromiseGuard Guard(DonePromise); |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 498 | DeferredCancel(); |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 499 | }; |
| 500 | WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise), |
| 501 | std::move(DeferredCancel)); |
| 502 | return DoneFuture; |
| 503 | } |
Marc-Andre Laperle | bf11424 | 2017-10-02 18:00:37 +0000 | [diff] [blame] | 504 | |
| 505 | void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) { |
| 506 | // FIXME: Do nothing for now. This will be used for indexing and potentially |
| 507 | // invalidating other caches. |
| 508 | } |