blob: 2c5c544c9854907ed349b640fb6efd3c1de04df4 [file] [log] [blame]
Ilya Biryukovcd5eb002018-02-12 11:37:28 +00001//===--- 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
11namespace clang {
12namespace clangd {
13
14namespace {
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));
19template <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
45private:
46 T *Target;
47 std::promise<T> Promise;
48 std::future<T> Future;
49};
50
51template <typename T> CaptureProxy<T> capture(T &Target) {
52 return CaptureProxy<T>(Target);
53}
54} // namespace
55
56Tagged<CompletionList>
57runCodeComplete(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