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