Ilya Biryukov | cd5eb00 | 2018-02-12 11:37:28 +0000 | [diff] [blame] | 1 | //===--- SyncAPI.cpp - Sync version of ClangdServer's API --------*- 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 | #include "SyncAPI.h" |
| 10 | |
| 11 | namespace clang { |
| 12 | namespace clangd { |
| 13 | |
| 14 | namespace { |
| 15 | /// A helper that waits for async callbacks to fire and exposes their result in |
| 16 | /// the output variable. Intended to be used in the following way: |
| 17 | /// T Result; |
| 18 | /// someAsyncFunc(Param1, Param2, /*Callback=*/capture(Result)); |
| 19 | template <typename T> struct CaptureProxy { |
| 20 | CaptureProxy(T &Target) : Target(&Target) {} |
| 21 | |
| 22 | CaptureProxy(const CaptureProxy &) = delete; |
| 23 | CaptureProxy &operator=(const CaptureProxy &) = delete; |
| 24 | // We need move ctor to return a value from the 'capture' helper. |
| 25 | CaptureProxy(CaptureProxy &&Other) : Target(Other.Target) { |
| 26 | Other.Target = nullptr; |
| 27 | } |
| 28 | CaptureProxy &operator=(CaptureProxy &&) = delete; |
| 29 | |
| 30 | operator UniqueFunction<void(T)>() && { |
| 31 | assert(!Future.valid() && "conversion to callback called multiple times"); |
| 32 | Future = Promise.get_future(); |
| 33 | return BindWithForward([](std::promise<T> Promise, |
| 34 | T Value) { Promise.set_value(std::move(Value)); }, |
| 35 | std::move(Promise)); |
| 36 | } |
| 37 | |
| 38 | ~CaptureProxy() { |
| 39 | if (!Target) |
| 40 | return; |
| 41 | assert(Future.valid() && "conversion to callback was not called"); |
| 42 | *Target = Future.get(); |
| 43 | } |
| 44 | |
| 45 | private: |
| 46 | T *Target; |
| 47 | std::promise<T> Promise; |
| 48 | std::future<T> Future; |
| 49 | }; |
| 50 | |
| 51 | template <typename T> CaptureProxy<T> capture(T &Target) { |
| 52 | return CaptureProxy<T>(Target); |
| 53 | } |
| 54 | } // namespace |
| 55 | |
| 56 | Tagged<CompletionList> |
| 57 | runCodeComplete(ClangdServer &Server, PathRef File, Position Pos, |
| 58 | clangd::CodeCompleteOptions Opts, |
| 59 | llvm::Optional<StringRef> OverridenContents) { |
| 60 | Tagged<CompletionList> Result; |
| 61 | Server.codeComplete(File, Pos, Opts, capture(Result), OverridenContents); |
| 62 | return Result; |
| 63 | } |
| 64 | |
| 65 | } // namespace clangd |
| 66 | } // namespace clang |