File: Function.h

package info (click to toggle)
llvm-toolchain-6.0 1%3A6.0.1-10
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 598,080 kB
  • sloc: cpp: 3,046,253; ansic: 595,057; asm: 271,965; python: 128,926; objc: 106,554; sh: 21,906; lisp: 10,191; pascal: 6,094; ml: 5,544; perl: 5,265; makefile: 2,227; cs: 2,027; xml: 686; php: 212; csh: 117
file content (177 lines) | stat: -rw-r--r-- 5,974 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
//===--- Function.h - Utility callable wrappers  -----------------*- C++-*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides an analogue to std::function that supports move semantics.
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_FUNCTION_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_FUNCTION_H

#include "llvm/ADT/STLExtras.h"
#include <cassert>
#include <memory>
#include <tuple>
#include <type_traits>
#include <utility>

namespace clang {
namespace clangd {

/// A move-only type-erasing function wrapper. Similar to `std::function`, but
/// allows to store move-only callables.
template <class> class UniqueFunction;

template <class Ret, class... Args> class UniqueFunction<Ret(Args...)> {
public:
  UniqueFunction() = default;
  UniqueFunction(std::nullptr_t) : UniqueFunction(){};

  UniqueFunction(UniqueFunction const &) = delete;
  UniqueFunction &operator=(UniqueFunction const &) = delete;

  UniqueFunction(UniqueFunction &&) noexcept = default;
  UniqueFunction &operator=(UniqueFunction &&) noexcept = default;

  template <class Callable,
            /// A sfinae-check that Callable can be called with Args... and
            class = typename std::enable_if<std::is_convertible<
                decltype(std::declval<Callable>()(std::declval<Args>()...)),
                Ret>::value>::type>
  UniqueFunction(Callable &&Func)
      : CallablePtr(llvm::make_unique<
                    FunctionCallImpl<typename std::decay<Callable>::type>>(
            std::forward<Callable>(Func))) {}

  explicit operator bool() { return bool(CallablePtr); }

  Ret operator()(Args... As) {
    assert(CallablePtr);
    return CallablePtr->Call(std::forward<Args>(As)...);
  }

private:
  class FunctionCallBase {
  public:
    virtual ~FunctionCallBase() = default;
    virtual Ret Call(Args... As) = 0;
  };

  template <class Callable>
  class FunctionCallImpl final : public FunctionCallBase {
    static_assert(
        std::is_same<Callable, typename std::decay<Callable>::type>::value,
        "FunctionCallImpl must be instanstiated with std::decay'ed types");

  public:
    FunctionCallImpl(Callable Func) : Func(std::move(Func)) {}

    Ret Call(Args... As) override { return Func(std::forward<Args>(As)...); }

  private:
    Callable Func;
  };

  std::unique_ptr<FunctionCallBase> CallablePtr;
};

/// Stores a callable object (Func) and arguments (Args) and allows to call the
/// callable with provided arguments later using `operator ()`. The arguments
/// are std::forward'ed into the callable in the body of `operator()`. Therefore
/// `operator()` can only be called once, as some of the arguments could be
/// std::move'ed into the callable on first call.
template <class Func, class... Args> struct ForwardBinder {
  using Tuple = std::tuple<typename std::decay<Func>::type,
                           typename std::decay<Args>::type...>;
  Tuple FuncWithArguments;
#ifndef NDEBUG
  bool WasCalled = false;
#endif

public:
  ForwardBinder(Tuple FuncWithArguments)
      : FuncWithArguments(std::move(FuncWithArguments)) {}

private:
  template <std::size_t... Indexes, class... RestArgs>
  auto CallImpl(llvm::integer_sequence<std::size_t, Indexes...> Seq,
                RestArgs &&... Rest)
      -> decltype(std::get<0>(this->FuncWithArguments)(
          std::forward<Args>(std::get<Indexes + 1>(this->FuncWithArguments))...,
          std::forward<RestArgs>(Rest)...)) {
    return std::get<0>(this->FuncWithArguments)(
        std::forward<Args>(std::get<Indexes + 1>(this->FuncWithArguments))...,
        std::forward<RestArgs>(Rest)...);
  }

public:
  template <class... RestArgs>
  auto operator()(RestArgs &&... Rest)
      -> decltype(this->CallImpl(llvm::index_sequence_for<Args...>(),
                                 std::forward<RestArgs>(Rest)...)) {

#ifndef NDEBUG
    assert(!WasCalled && "Can only call result of BindWithForward once.");
    WasCalled = true;
#endif
    return CallImpl(llvm::index_sequence_for<Args...>(),
                    std::forward<RestArgs>(Rest)...);
  }
};

/// Creates an object that stores a callable (\p F) and first arguments to the
/// callable (\p As) and allows to call \p F with \Args at a later point.
/// Similar to std::bind, but also works with move-only \p F and \p As.
///
/// The returned object must be called no more than once, as \p As are
/// std::forwarded'ed (therefore can be moved) into \p F during the call.
template <class Func, class... Args>
ForwardBinder<Func, Args...> BindWithForward(Func F, Args &&... As) {
  return ForwardBinder<Func, Args...>(
      std::make_tuple(std::forward<Func>(F), std::forward<Args>(As)...));
}

namespace detail {
/// Runs provided callback in destructor. Use onScopeExit helper function to
/// create this object.
template <class Func> struct ScopeExitGuard {
  static_assert(std::is_same<typename std::decay<Func>::type, Func>::value,
                "Func must be decayed");

  ScopeExitGuard(Func F) : F(std::move(F)) {}
  ~ScopeExitGuard() {
    if (!F)
      return;
    (*F)();
  }

  // Move-only.
  ScopeExitGuard(const ScopeExitGuard &) = delete;
  ScopeExitGuard &operator=(const ScopeExitGuard &) = delete;

  ScopeExitGuard(ScopeExitGuard &&Other) = default;
  ScopeExitGuard &operator=(ScopeExitGuard &&Other) = default;

private:
  llvm::Optional<Func> F;
};
} // namespace detail

/// Creates a RAII object that will run \p F in its destructor.
template <class Func>
auto onScopeExit(Func &&F)
    -> detail::ScopeExitGuard<typename std::decay<Func>::type> {
  return detail::ScopeExitGuard<typename std::decay<Func>::type>(
      std::forward<Func>(F));
}

} // namespace clangd
} // namespace clang

#endif