1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_BIND_H_
6 #define BASE_BIND_H_
7 
8 #include <functional>
9 #include <memory>
10 #include <type_traits>
11 #include <utility>
12 
13 #include "base/bind_internal.h"
14 #include "base/compiler_specific.h"
15 #include "base/template_util.h"
16 #include "build/build_config.h"
17 
18 #if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
19 #include "base/mac/scoped_block.h"
20 #endif
21 
22 // -----------------------------------------------------------------------------
23 // Usage documentation
24 // -----------------------------------------------------------------------------
25 //
26 // Overview:
27 // base::BindOnce() and base::BindRepeating() are helpers for creating
28 // base::OnceCallback and base::RepeatingCallback objects respectively.
29 //
30 // For a runnable object of n-arity, the base::Bind*() family allows partial
31 // application of the first m arguments. The remaining n - m arguments must be
32 // passed when invoking the callback with Run().
33 //
34 //   // The first argument is bound at callback creation; the remaining
35 //   // two must be passed when calling Run() on the callback object.
36 //   base::OnceCallback<long(int, long)> cb = base::BindOnce(
37 //       [](short x, int y, long z) { return x * y * z; }, 42);
38 //
39 // When binding to a method, the receiver object must also be specified at
40 // callback creation time. When Run() is invoked, the method will be invoked on
41 // the specified receiver object.
42 //
43 //   class C : public base::RefCounted<C> { void F(); };
44 //   auto instance = base::MakeRefCounted<C>();
45 //   auto cb = base::BindOnce(&C::F, instance);
46 //   std::move(cb).Run();  // Identical to instance->F()
47 //
48 // base::Bind is currently a type alias for base::BindRepeating(). In the
49 // future, we expect to flip this to default to base::BindOnce().
50 //
51 // See //docs/callback.md for the full documentation.
52 //
53 // -----------------------------------------------------------------------------
54 // Implementation notes
55 // -----------------------------------------------------------------------------
56 //
57 // If you're reading the implementation, before proceeding further, you should
58 // read the top comment of base/bind_internal.h for a definition of common
59 // terms and concepts.
60 
61 namespace base {
62 
63 namespace internal {
64 
65 // IsOnceCallback<T> is a std::true_type if |T| is a OnceCallback.
66 template <typename T>
67 struct IsOnceCallback : std::false_type {};
68 
69 template <typename Signature>
70 struct IsOnceCallback<OnceCallback<Signature>> : std::true_type {};
71 
72 // Helper to assert that parameter |i| of type |Arg| can be bound, which means:
73 // - |Arg| can be retained internally as |Storage|.
74 // - |Arg| can be forwarded as |Unwrapped| to |Param|.
75 template <size_t i,
76           typename Arg,
77           typename Storage,
78           typename Unwrapped,
79           typename Param>
80 struct AssertConstructible {
81  private:
82   static constexpr bool param_is_forwardable =
83       std::is_constructible<Param, Unwrapped>::value;
84   // Unlike the check for binding into storage below, the check for
85   // forwardability drops the const qualifier for repeating callbacks. This is
86   // to try to catch instances where std::move()--which forwards as a const
87   // reference with repeating callbacks--is used instead of base::Passed().
88   static_assert(
89       param_is_forwardable ||
90           !std::is_constructible<Param, std::decay_t<Unwrapped>&&>::value,
91       "Bound argument |i| is move-only but will be forwarded by copy. "
92       "Ensure |Arg| is bound using base::Passed(), not std::move().");
93   static_assert(
94       param_is_forwardable,
95       "Bound argument |i| of type |Arg| cannot be forwarded as "
96       "|Unwrapped| to the bound functor, which declares it as |Param|.");
97 
98   static constexpr bool arg_is_storable =
99       std::is_constructible<Storage, Arg>::value;
100   static_assert(arg_is_storable ||
101                     !std::is_constructible<Storage, std::decay_t<Arg>&&>::value,
102                 "Bound argument |i| is move-only but will be bound by copy. "
103                 "Ensure |Arg| is mutable and bound using std::move().");
104   static_assert(arg_is_storable,
105                 "Bound argument |i| of type |Arg| cannot be converted and "
106                 "bound as |Storage|.");
107 };
108 
109 // Takes three same-length TypeLists, and applies AssertConstructible for each
110 // triples.
111 template <typename Index,
112           typename Args,
113           typename UnwrappedTypeList,
114           typename ParamsList>
115 struct AssertBindArgsValidity;
116 
117 template <size_t... Ns,
118           typename... Args,
119           typename... Unwrapped,
120           typename... Params>
121 struct AssertBindArgsValidity<std::index_sequence<Ns...>,
122                               TypeList<Args...>,
123                               TypeList<Unwrapped...>,
124                               TypeList<Params...>>
125     : AssertConstructible<Ns, Args, std::decay_t<Args>, Unwrapped, Params>... {
126   static constexpr bool ok = true;
127 };
128 
129 // The implementation of TransformToUnwrappedType below.
130 template <bool is_once, typename T>
131 struct TransformToUnwrappedTypeImpl;
132 
133 template <typename T>
134 struct TransformToUnwrappedTypeImpl<true, T> {
135   using StoredType = std::decay_t<T>;
136   using ForwardType = StoredType&&;
137   using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
138 };
139 
140 template <typename T>
141 struct TransformToUnwrappedTypeImpl<false, T> {
142   using StoredType = std::decay_t<T>;
143   using ForwardType = const StoredType&;
144   using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
145 };
146 
147 // Transform |T| into `Unwrapped` type, which is passed to the target function.
148 // Example:
149 //   In is_once == true case,
150 //     `int&&` -> `int&&`,
151 //     `const int&` -> `int&&`,
152 //     `OwnedWrapper<int>&` -> `int*&&`.
153 //   In is_once == false case,
154 //     `int&&` -> `const int&`,
155 //     `const int&` -> `const int&`,
156 //     `OwnedWrapper<int>&` -> `int* const &`.
157 template <bool is_once, typename T>
158 using TransformToUnwrappedType =
159     typename TransformToUnwrappedTypeImpl<is_once, T>::Unwrapped;
160 
161 // Transforms |Args| into `Unwrapped` types, and packs them into a TypeList.
162 // If |is_method| is true, tries to dereference the first argument to support
163 // smart pointers.
164 template <bool is_once, bool is_method, typename... Args>
165 struct MakeUnwrappedTypeListImpl {
166   using Type = TypeList<TransformToUnwrappedType<is_once, Args>...>;
167 };
168 
169 // Performs special handling for this pointers.
170 // Example:
171 //   int* -> int*,
172 //   std::unique_ptr<int> -> int*.
173 template <bool is_once, typename Receiver, typename... Args>
174 struct MakeUnwrappedTypeListImpl<is_once, true, Receiver, Args...> {
175   using UnwrappedReceiver = TransformToUnwrappedType<is_once, Receiver>;
176   using Type = TypeList<decltype(&*std::declval<UnwrappedReceiver>()),
177                         TransformToUnwrappedType<is_once, Args>...>;
178 };
179 
180 template <bool is_once, bool is_method, typename... Args>
181 using MakeUnwrappedTypeList =
182     typename MakeUnwrappedTypeListImpl<is_once, is_method, Args...>::Type;
183 
184 // Used below in BindImpl to determine whether to use Invoker::Run or
185 // Invoker::RunOnce.
186 // Note: Simply using `kIsOnce ? &Invoker::RunOnce : &Invoker::Run` does not
187 // work, since the compiler needs to check whether both expressions are
188 // well-formed. Using `Invoker::Run` with a OnceCallback triggers a
189 // static_assert, which is why the ternary expression does not compile.
190 // TODO(crbug.com/752720): Remove this indirection once we have `if constexpr`.
191 template <typename Invoker>
192 constexpr auto GetInvokeFunc(std::true_type) {
193   return Invoker::RunOnce;
194 }
195 
196 template <typename Invoker>
197 constexpr auto GetInvokeFunc(std::false_type) {
198   return Invoker::Run;
199 }
200 
201 template <template <typename> class CallbackT,
202           typename Functor,
203           typename... Args>
204 decltype(auto) BindImpl(Functor&& functor, Args&&... args) {
205   // This block checks if each |args| matches to the corresponding params of the
206   // target function. This check does not affect the behavior of Bind, but its
207   // error message should be more readable.
208   static constexpr bool kIsOnce = IsOnceCallback<CallbackT<void()>>::value;
209   using Helper = internal::BindTypeHelper<Functor, Args...>;
210   using FunctorTraits = typename Helper::FunctorTraits;
211   using BoundArgsList = typename Helper::BoundArgsList;
212   using UnwrappedArgsList =
213       internal::MakeUnwrappedTypeList<kIsOnce, FunctorTraits::is_method,
214                                       Args&&...>;
215   using BoundParamsList = typename Helper::BoundParamsList;
216   static_assert(internal::AssertBindArgsValidity<
217                     std::make_index_sequence<Helper::num_bounds>, BoundArgsList,
218                     UnwrappedArgsList, BoundParamsList>::ok,
219                 "The bound args need to be convertible to the target params.");
220 
221   using BindState = internal::MakeBindStateType<Functor, Args...>;
222   using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
223   using Invoker = internal::Invoker<BindState, UnboundRunType>;
224   using CallbackType = CallbackT<UnboundRunType>;
225 
226   // Store the invoke func into PolymorphicInvoke before casting it to
227   // InvokeFuncStorage, so that we can ensure its type matches to
228   // PolymorphicInvoke, to which CallbackType will cast back.
229   using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
230   PolymorphicInvoke invoke_func =
231       GetInvokeFunc<Invoker>(bool_constant<kIsOnce>());
232 
233   using InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage;
234   return CallbackType(BindState::Create(
235       reinterpret_cast<InvokeFuncStorage>(invoke_func),
236       std::forward<Functor>(functor), std::forward<Args>(args)...));
237 }
238 
239 }  // namespace internal
240 
241 // Bind as OnceCallback.
242 template <typename Functor, typename... Args>
243 inline OnceCallback<MakeUnboundRunType<Functor, Args...>> BindOnce(
244     Functor&& functor,
245     Args&&... args) {
246   static_assert(!internal::IsOnceCallback<std::decay_t<Functor>>() ||
247                     (std::is_rvalue_reference<Functor&&>() &&
248                      !std::is_const<std::remove_reference_t<Functor>>()),
249                 "BindOnce requires non-const rvalue for OnceCallback binding."
250                 " I.e.: base::BindOnce(std::move(callback)).");
251 
252   return internal::BindImpl<OnceCallback>(std::forward<Functor>(functor),
253                                           std::forward<Args>(args)...);
254 }
255 
256 // Bind as RepeatingCallback.
257 template <typename Functor, typename... Args>
258 inline RepeatingCallback<MakeUnboundRunType<Functor, Args...>>
259 BindRepeating(Functor&& functor, Args&&... args) {
260   static_assert(
261       !internal::IsOnceCallback<std::decay_t<Functor>>(),
262       "BindRepeating cannot bind OnceCallback. Use BindOnce with std::move().");
263 
264   return internal::BindImpl<RepeatingCallback>(std::forward<Functor>(functor),
265                                                std::forward<Args>(args)...);
266 }
267 
268 // Unannotated Bind.
269 // TODO(tzik): Deprecate this and migrate to OnceCallback and
270 // RepeatingCallback, once they get ready.
271 template <typename Functor, typename... Args>
272 inline Callback<MakeUnboundRunType<Functor, Args...>>
273 Bind(Functor&& functor, Args&&... args) {
274   return base::BindRepeating(std::forward<Functor>(functor),
275                              std::forward<Args>(args)...);
276 }
277 
278 // Special cases for binding to a base::Callback without extra bound arguments.
279 template <typename Signature>
280 OnceCallback<Signature> BindOnce(OnceCallback<Signature> callback) {
281   return callback;
282 }
283 
284 template <typename Signature>
285 OnceCallback<Signature> BindOnce(RepeatingCallback<Signature> callback) {
286   return callback;
287 }
288 
289 template <typename Signature>
290 RepeatingCallback<Signature> BindRepeating(
291     RepeatingCallback<Signature> callback) {
292   return callback;
293 }
294 
295 template <typename Signature>
296 Callback<Signature> Bind(Callback<Signature> callback) {
297   return callback;
298 }
299 
300 // Unretained() allows binding a non-refcounted class, and to disable
301 // refcounting on arguments that are refcounted objects.
302 //
303 // EXAMPLE OF Unretained():
304 //
305 //   class Foo {
306 //    public:
307 //     void func() { cout << "Foo:f" << endl; }
308 //   };
309 //
310 //   // In some function somewhere.
311 //   Foo foo;
312 //   OnceClosure foo_callback =
313 //       BindOnce(&Foo::func, Unretained(&foo));
314 //   std::move(foo_callback).Run();  // Prints "Foo:f".
315 //
316 // Without the Unretained() wrapper on |&foo|, the above call would fail
317 // to compile because Foo does not support the AddRef() and Release() methods.
318 template <typename T>
319 static inline internal::UnretainedWrapper<T> Unretained(T* o) {
320   return internal::UnretainedWrapper<T>(o);
321 }
322 
323 // RetainedRef() accepts a ref counted object and retains a reference to it.
324 // When the callback is called, the object is passed as a raw pointer.
325 //
326 // EXAMPLE OF RetainedRef():
327 //
328 //    void foo(RefCountedBytes* bytes) {}
329 //
330 //    scoped_refptr<RefCountedBytes> bytes = ...;
331 //    OnceClosure callback = BindOnce(&foo, base::RetainedRef(bytes));
332 //    std::move(callback).Run();
333 //
334 // Without RetainedRef, the scoped_refptr would try to implicitly convert to
335 // a raw pointer and fail compilation:
336 //
337 //    OnceClosure callback = BindOnce(&foo, bytes); // ERROR!
338 template <typename T>
339 static inline internal::RetainedRefWrapper<T> RetainedRef(T* o) {
340   return internal::RetainedRefWrapper<T>(o);
341 }
342 template <typename T>
343 static inline internal::RetainedRefWrapper<T> RetainedRef(scoped_refptr<T> o) {
344   return internal::RetainedRefWrapper<T>(std::move(o));
345 }
346 
347 // Owned() transfers ownership of an object to the callback resulting from
348 // bind; the object will be deleted when the callback is deleted.
349 //
350 // EXAMPLE OF Owned():
351 //
352 //   void foo(int* arg) { cout << *arg << endl }
353 //
354 //   int* pn = new int(1);
355 //   RepeatingClosure foo_callback = BindRepeating(&foo, Owned(pn));
356 //
357 //   foo_callback.Run();  // Prints "1"
358 //   foo_callback.Run();  // Prints "1"
359 //   *pn = 2;
360 //   foo_callback.Run();  // Prints "2"
361 //
362 //   foo_callback.Reset();  // |pn| is deleted.  Also will happen when
363 //                          // |foo_callback| goes out of scope.
364 //
365 // Without Owned(), someone would have to know to delete |pn| when the last
366 // reference to the callback is deleted.
367 template <typename T>
368 static inline internal::OwnedWrapper<T> Owned(T* o) {
369   return internal::OwnedWrapper<T>(o);
370 }
371 
372 template <typename T, typename Deleter>
373 static inline internal::OwnedWrapper<T, Deleter> Owned(
374     std::unique_ptr<T, Deleter>&& ptr) {
375   return internal::OwnedWrapper<T, Deleter>(std::move(ptr));
376 }
377 
378 // Passed() is for transferring movable-but-not-copyable types (eg. unique_ptr)
379 // through a RepeatingCallback. Logically, this signifies a destructive transfer
380 // of the state of the argument into the target function. Invoking
381 // RepeatingCallback::Run() twice on a callback that was created with a Passed()
382 // argument will CHECK() because the first invocation would have already
383 // transferred ownership to the target function.
384 //
385 // Note that Passed() is not necessary with BindOnce(), as std::move() does the
386 // same thing. Avoid Passed() in favor of std::move() with BindOnce().
387 //
388 // EXAMPLE OF Passed():
389 //
390 //   void TakesOwnership(std::unique_ptr<Foo> arg) { }
391 //   std::unique_ptr<Foo> CreateFoo() { return std::make_unique<Foo>();
392 //   }
393 //
394 //   auto f = std::make_unique<Foo>();
395 //
396 //   // |cb| is given ownership of Foo(). |f| is now NULL.
397 //   // You can use std::move(f) in place of &f, but it's more verbose.
398 //   RepeatingClosure cb = BindRepeating(&TakesOwnership, Passed(&f));
399 //
400 //   // Run was never called so |cb| still owns Foo() and deletes
401 //   // it on Reset().
402 //   cb.Reset();
403 //
404 //   // |cb| is given a new Foo created by CreateFoo().
405 //   cb = BindRepeating(&TakesOwnership, Passed(CreateFoo()));
406 //
407 //   // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
408 //   // no longer owns Foo() and, if reset, would not delete Foo().
409 //   cb.Run();  // Foo() is now transferred to |arg| and deleted.
410 //   cb.Run();  // This CHECK()s since Foo() already been used once.
411 //
412 // We offer 2 syntaxes for calling Passed(). The first takes an rvalue and is
413 // best suited for use with the return value of a function or other temporary
414 // rvalues. The second takes a pointer to the scoper and is just syntactic sugar
415 // to avoid having to write Passed(std::move(scoper)).
416 //
417 // Both versions of Passed() prevent T from being an lvalue reference. The first
418 // via use of enable_if, and the second takes a T* which will not bind to T&.
419 template <typename T,
420           std::enable_if_t<!std::is_lvalue_reference<T>::value>* = nullptr>
421 static inline internal::PassedWrapper<T> Passed(T&& scoper) {
422   return internal::PassedWrapper<T>(std::move(scoper));
423 }
424 template <typename T>
425 static inline internal::PassedWrapper<T> Passed(T* scoper) {
426   return internal::PassedWrapper<T>(std::move(*scoper));
427 }
428 
429 // IgnoreResult() is used to adapt a function or callback with a return type to
430 // one with a void return. This is most useful if you have a function with,
431 // say, a pesky ignorable bool return that you want to use with PostTask or
432 // something else that expect a callback with a void return.
433 //
434 // EXAMPLE OF IgnoreResult():
435 //
436 //   int DoSomething(int arg) { cout << arg << endl; }
437 //
438 //   // Assign to a callback with a void return type.
439 //   OnceCallback<void(int)> cb = BindOnce(IgnoreResult(&DoSomething));
440 //   std::move(cb).Run(1);  // Prints "1".
441 //
442 //   // Prints "2" on |ml|.
443 //   ml->PostTask(FROM_HERE, BindOnce(IgnoreResult(&DoSomething), 2);
444 template <typename T>
445 static inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
446   return internal::IgnoreResultHelper<T>(std::move(data));
447 }
448 
449 #if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
450 
451 // RetainBlock() is used to adapt an Objective-C block when Automated Reference
452 // Counting (ARC) is disabled. This is unnecessary when ARC is enabled, as the
453 // BindOnce and BindRepeating already support blocks then.
454 //
455 // EXAMPLE OF RetainBlock():
456 //
457 //   // Wrap the block and bind it to a callback.
458 //   OnceCallback<void(int)> cb =
459 //       BindOnce(RetainBlock(^(int n) { NSLog(@"%d", n); }));
460 //   std::move(cb).Run(1);  // Logs "1".
461 template <typename R, typename... Args>
462 base::mac::ScopedBlock<R (^)(Args...)> RetainBlock(R (^block)(Args...)) {
463   return base::mac::ScopedBlock<R (^)(Args...)>(block,
464                                                 base::scoped_policy::RETAIN);
465 }
466 
467 #endif  // defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
468 
469 }  // namespace base
470 
471 #endif  // BASE_BIND_H_
472