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.
10 #include "base/bind_internal.h"
11 #include "base/compiler_specific.h"
12 #include "build/build_config.h"
14 #if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
15 #include "base/mac/scoped_block.h"
18 // -----------------------------------------------------------------------------
19 // Usage documentation
20 // -----------------------------------------------------------------------------
23 // base::BindOnce() and base::BindRepeating() are helpers for creating
24 // base::OnceCallback and base::RepeatingCallback objects respectively.
26 // For a runnable object of n-arity, the base::Bind*() family allows partial
27 // application of the first m arguments. The remaining n - m arguments must be
28 // passed when invoking the callback with Run().
30 // // The first argument is bound at callback creation; the remaining
31 // // two must be passed when calling Run() on the callback object.
32 // base::OnceCallback<long(int, long)> cb = base::BindOnce(
33 // [](short x, int y, long z) { return x * y * z; }, 42);
35 // When binding to a method, the receiver object must also be specified at
36 // callback creation time. When Run() is invoked, the method will be invoked on
37 // the specified receiver object.
39 // class C : public base::RefCounted<C> { void F(); };
40 // auto instance = base::MakeRefCounted<C>();
41 // auto cb = base::BindOnce(&C::F, instance);
42 // cb.Run(); // Identical to instance->F()
44 // base::Bind is currently a type alias for base::BindRepeating(). In the
45 // future, we expect to flip this to default to base::BindOnce().
47 // See //docs/callback.md for the full documentation.
49 // -----------------------------------------------------------------------------
50 // Implementation notes
51 // -----------------------------------------------------------------------------
53 // If you're reading the implementation, before proceeding further, you should
54 // read the top comment of base/bind_internal.h for a definition of common
55 // terms and concepts.
61 // IsOnceCallback<T> is a std::true_type if |T| is a OnceCallback.
63 struct IsOnceCallback : std::false_type {};
65 template <typename Signature>
66 struct IsOnceCallback<OnceCallback<Signature>> : std::true_type {};
68 // Helper to assert that parameter |i| of type |Arg| can be bound, which means:
69 // - |Arg| can be retained internally as |Storage|.
70 // - |Arg| can be forwarded as |Unwrapped| to |Param|.
76 struct AssertConstructible {
78 static constexpr bool param_is_forwardable =
79 std::is_constructible<Param, Unwrapped>::value;
80 // Unlike the check for binding into storage below, the check for
81 // forwardability drops the const qualifier for repeating callbacks. This is
82 // to try to catch instances where std::move()--which forwards as a const
83 // reference with repeating callbacks--is used instead of base::Passed().
85 param_is_forwardable ||
86 !std::is_constructible<Param, std::decay_t<Unwrapped>&&>::value,
87 "Bound argument |i| is move-only but will be forwarded by copy. "
88 "Ensure |Arg| is bound using base::Passed(), not std::move().");
91 "Bound argument |i| of type |Arg| cannot be forwarded as "
92 "|Unwrapped| to the bound functor, which declares it as |Param|.");
94 static constexpr bool arg_is_storable =
95 std::is_constructible<Storage, Arg>::value;
96 static_assert(arg_is_storable ||
97 !std::is_constructible<Storage, std::decay_t<Arg>&&>::value,
98 "Bound argument |i| is move-only but will be bound by copy. "
99 "Ensure |Arg| is mutable and bound using std::move().");
100 static_assert(arg_is_storable,
101 "Bound argument |i| of type |Arg| cannot be converted and "
102 "bound as |Storage|.");
105 // Takes three same-length TypeLists, and applies AssertConstructible for each
107 template <typename Index,
109 typename UnwrappedTypeList,
111 struct AssertBindArgsValidity;
113 template <size_t... Ns,
115 typename... Unwrapped,
117 struct AssertBindArgsValidity<std::index_sequence<Ns...>,
119 TypeList<Unwrapped...>,
121 : AssertConstructible<Ns, Args, std::decay_t<Args>, Unwrapped, Params>... {
122 static constexpr bool ok = true;
125 // The implementation of TransformToUnwrappedType below.
126 template <bool is_once, typename T>
127 struct TransformToUnwrappedTypeImpl;
129 template <typename T>
130 struct TransformToUnwrappedTypeImpl<true, T> {
131 using StoredType = std::decay_t<T>;
132 using ForwardType = StoredType&&;
133 using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
136 template <typename T>
137 struct TransformToUnwrappedTypeImpl<false, T> {
138 using StoredType = std::decay_t<T>;
139 using ForwardType = const StoredType&;
140 using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
143 // Transform |T| into `Unwrapped` type, which is passed to the target function.
145 // In is_once == true case,
146 // `int&&` -> `int&&`,
147 // `const int&` -> `int&&`,
148 // `OwnedWrapper<int>&` -> `int*&&`.
149 // In is_once == false case,
150 // `int&&` -> `const int&`,
151 // `const int&` -> `const int&`,
152 // `OwnedWrapper<int>&` -> `int* const &`.
153 template <bool is_once, typename T>
154 using TransformToUnwrappedType =
155 typename TransformToUnwrappedTypeImpl<is_once, T>::Unwrapped;
157 // Transforms |Args| into `Unwrapped` types, and packs them into a TypeList.
158 // If |is_method| is true, tries to dereference the first argument to support
160 template <bool is_once, bool is_method, typename... Args>
161 struct MakeUnwrappedTypeListImpl {
162 using Type = TypeList<TransformToUnwrappedType<is_once, Args>...>;
165 // Performs special handling for this pointers.
168 // std::unique_ptr<int> -> int*.
169 template <bool is_once, typename Receiver, typename... Args>
170 struct MakeUnwrappedTypeListImpl<is_once, true, Receiver, Args...> {
171 using UnwrappedReceiver = TransformToUnwrappedType<is_once, Receiver>;
172 using Type = TypeList<decltype(&*std::declval<UnwrappedReceiver>()),
173 TransformToUnwrappedType<is_once, Args>...>;
176 template <bool is_once, bool is_method, typename... Args>
177 using MakeUnwrappedTypeList =
178 typename MakeUnwrappedTypeListImpl<is_once, is_method, Args...>::Type;
180 } // namespace internal
182 // Bind as OnceCallback.
183 template <typename Functor, typename... Args>
184 inline OnceCallback<MakeUnboundRunType<Functor, Args...>>
185 BindOnce(Functor&& functor, Args&&... args) {
186 static_assert(!internal::IsOnceCallback<std::decay_t<Functor>>() ||
187 (std::is_rvalue_reference<Functor&&>() &&
188 !std::is_const<std::remove_reference_t<Functor>>()),
189 "BindOnce requires non-const rvalue for OnceCallback binding."
190 " I.e.: base::BindOnce(std::move(callback)).");
192 // This block checks if each |args| matches to the corresponding params of the
193 // target function. This check does not affect the behavior of Bind, but its
194 // error message should be more readable.
195 using Helper = internal::BindTypeHelper<Functor, Args...>;
196 using FunctorTraits = typename Helper::FunctorTraits;
197 using BoundArgsList = typename Helper::BoundArgsList;
198 using UnwrappedArgsList =
199 internal::MakeUnwrappedTypeList<true, FunctorTraits::is_method,
201 using BoundParamsList = typename Helper::BoundParamsList;
202 static_assert(internal::AssertBindArgsValidity<
203 std::make_index_sequence<Helper::num_bounds>, BoundArgsList,
204 UnwrappedArgsList, BoundParamsList>::ok,
205 "The bound args need to be convertible to the target params.");
207 using BindState = internal::MakeBindStateType<Functor, Args...>;
208 using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
209 using Invoker = internal::Invoker<BindState, UnboundRunType>;
210 using CallbackType = OnceCallback<UnboundRunType>;
212 // Store the invoke func into PolymorphicInvoke before casting it to
213 // InvokeFuncStorage, so that we can ensure its type matches to
214 // PolymorphicInvoke, to which CallbackType will cast back.
215 using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
216 PolymorphicInvoke invoke_func = &Invoker::RunOnce;
218 using InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage;
219 return CallbackType(BindState::Create(
220 reinterpret_cast<InvokeFuncStorage>(invoke_func),
221 std::forward<Functor>(functor), std::forward<Args>(args)...));
224 // Bind as RepeatingCallback.
225 template <typename Functor, typename... Args>
226 inline RepeatingCallback<MakeUnboundRunType<Functor, Args...>>
227 BindRepeating(Functor&& functor, Args&&... args) {
229 !internal::IsOnceCallback<std::decay_t<Functor>>(),
230 "BindRepeating cannot bind OnceCallback. Use BindOnce with std::move().");
232 // This block checks if each |args| matches to the corresponding params of the
233 // target function. This check does not affect the behavior of Bind, but its
234 // error message should be more readable.
235 using Helper = internal::BindTypeHelper<Functor, Args...>;
236 using FunctorTraits = typename Helper::FunctorTraits;
237 using BoundArgsList = typename Helper::BoundArgsList;
238 using UnwrappedArgsList =
239 internal::MakeUnwrappedTypeList<false, FunctorTraits::is_method,
241 using BoundParamsList = typename Helper::BoundParamsList;
242 static_assert(internal::AssertBindArgsValidity<
243 std::make_index_sequence<Helper::num_bounds>, BoundArgsList,
244 UnwrappedArgsList, BoundParamsList>::ok,
245 "The bound args need to be convertible to the target params.");
247 using BindState = internal::MakeBindStateType<Functor, Args...>;
248 using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
249 using Invoker = internal::Invoker<BindState, UnboundRunType>;
250 using CallbackType = RepeatingCallback<UnboundRunType>;
252 // Store the invoke func into PolymorphicInvoke before casting it to
253 // InvokeFuncStorage, so that we can ensure its type matches to
254 // PolymorphicInvoke, to which CallbackType will cast back.
255 using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
256 PolymorphicInvoke invoke_func = &Invoker::Run;
258 using InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage;
259 return CallbackType(BindState::Create(
260 reinterpret_cast<InvokeFuncStorage>(invoke_func),
261 std::forward<Functor>(functor), std::forward<Args>(args)...));
265 // TODO(tzik): Deprecate this and migrate to OnceCallback and
266 // RepeatingCallback, once they get ready.
267 template <typename Functor, typename... Args>
268 inline Callback<MakeUnboundRunType<Functor, Args...>>
269 Bind(Functor&& functor, Args&&... args) {
270 return base::BindRepeating(std::forward<Functor>(functor),
271 std::forward<Args>(args)...);
274 // Special cases for binding to a base::Callback without extra bound arguments.
275 template <typename Signature>
276 OnceCallback<Signature> BindOnce(OnceCallback<Signature> closure) {
280 template <typename Signature>
281 RepeatingCallback<Signature> BindRepeating(
282 RepeatingCallback<Signature> closure) {
286 template <typename Signature>
287 Callback<Signature> Bind(Callback<Signature> closure) {
291 // Unretained() allows Bind() to bind a non-refcounted class, and to disable
292 // refcounting on arguments that are refcounted objects.
294 // EXAMPLE OF Unretained():
298 // void func() { cout << "Foo:f" << endl; }
301 // // In some function somewhere.
303 // Closure foo_callback =
304 // Bind(&Foo::func, Unretained(&foo));
305 // foo_callback.Run(); // Prints "Foo:f".
307 // Without the Unretained() wrapper on |&foo|, the above call would fail
308 // to compile because Foo does not support the AddRef() and Release() methods.
309 template <typename T>
310 static inline internal::UnretainedWrapper<T> Unretained(T* o) {
311 return internal::UnretainedWrapper<T>(o);
314 // RetainedRef() accepts a ref counted object and retains a reference to it.
315 // When the callback is called, the object is passed as a raw pointer.
317 // EXAMPLE OF RetainedRef():
319 // void foo(RefCountedBytes* bytes) {}
321 // scoped_refptr<RefCountedBytes> bytes = ...;
322 // Closure callback = Bind(&foo, base::RetainedRef(bytes));
325 // Without RetainedRef, the scoped_refptr would try to implicitly convert to
326 // a raw pointer and fail compilation:
328 // Closure callback = Bind(&foo, bytes); // ERROR!
329 template <typename T>
330 static inline internal::RetainedRefWrapper<T> RetainedRef(T* o) {
331 return internal::RetainedRefWrapper<T>(o);
333 template <typename T>
334 static inline internal::RetainedRefWrapper<T> RetainedRef(scoped_refptr<T> o) {
335 return internal::RetainedRefWrapper<T>(std::move(o));
338 // ConstRef() allows binding a constant reference to an argument rather
341 // EXAMPLE OF ConstRef():
343 // void foo(int arg) { cout << arg << endl }
346 // Closure no_ref = Bind(&foo, n);
347 // Closure has_ref = Bind(&foo, ConstRef(n));
349 // no_ref.Run(); // Prints "1"
350 // has_ref.Run(); // Prints "1"
353 // no_ref.Run(); // Prints "1"
354 // has_ref.Run(); // Prints "2"
356 // Note that because ConstRef() takes a reference on |n|, |n| must outlive all
357 // its bound callbacks.
358 template <typename T>
359 static inline internal::ConstRefWrapper<T> ConstRef(const T& o) {
360 return internal::ConstRefWrapper<T>(o);
363 // Owned() transfers ownership of an object to the Callback resulting from
364 // bind; the object will be deleted when the Callback is deleted.
366 // EXAMPLE OF Owned():
368 // void foo(int* arg) { cout << *arg << endl }
370 // int* pn = new int(1);
371 // Closure foo_callback = Bind(&foo, Owned(pn));
373 // foo_callback.Run(); // Prints "1"
374 // foo_callback.Run(); // Prints "1"
376 // foo_callback.Run(); // Prints "2"
378 // foo_callback.Reset(); // |pn| is deleted. Also will happen when
379 // // |foo_callback| goes out of scope.
381 // Without Owned(), someone would have to know to delete |pn| when the last
382 // reference to the Callback is deleted.
383 template <typename T>
384 static inline internal::OwnedWrapper<T> Owned(T* o) {
385 return internal::OwnedWrapper<T>(o);
388 // Passed() is for transferring movable-but-not-copyable types (eg. unique_ptr)
389 // through a Callback. Logically, this signifies a destructive transfer of
390 // the state of the argument into the target function. Invoking
391 // Callback::Run() twice on a Callback that was created with a Passed()
392 // argument will CHECK() because the first invocation would have already
393 // transferred ownership to the target function.
395 // Note that Passed() is not necessary with BindOnce(), as std::move() does the
396 // same thing. Avoid Passed() in favor of std::move() with BindOnce().
398 // EXAMPLE OF Passed():
400 // void TakesOwnership(std::unique_ptr<Foo> arg) { }
401 // std::unique_ptr<Foo> CreateFoo() { return std::make_unique<Foo>();
404 // auto f = std::make_unique<Foo>();
406 // // |cb| is given ownership of Foo(). |f| is now NULL.
407 // // You can use std::move(f) in place of &f, but it's more verbose.
408 // Closure cb = Bind(&TakesOwnership, Passed(&f));
410 // // Run was never called so |cb| still owns Foo() and deletes
414 // // |cb| is given a new Foo created by CreateFoo().
415 // cb = Bind(&TakesOwnership, Passed(CreateFoo()));
417 // // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
418 // // no longer owns Foo() and, if reset, would not delete Foo().
419 // cb.Run(); // Foo() is now transferred to |arg| and deleted.
420 // cb.Run(); // This CHECK()s since Foo() already been used once.
422 // We offer 2 syntaxes for calling Passed(). The first takes an rvalue and
423 // is best suited for use with the return value of a function or other temporary
424 // rvalues. The second takes a pointer to the scoper and is just syntactic sugar
425 // to avoid having to write Passed(std::move(scoper)).
427 // Both versions of Passed() prevent T from being an lvalue reference. The first
428 // via use of enable_if, and the second takes a T* which will not bind to T&.
429 template <typename T,
430 std::enable_if_t<!std::is_lvalue_reference<T>::value>* = nullptr>
431 static inline internal::PassedWrapper<T> Passed(T&& scoper) {
432 return internal::PassedWrapper<T>(std::move(scoper));
434 template <typename T>
435 static inline internal::PassedWrapper<T> Passed(T* scoper) {
436 return internal::PassedWrapper<T>(std::move(*scoper));
439 // IgnoreResult() is used to adapt a function or Callback with a return type to
440 // one with a void return. This is most useful if you have a function with,
441 // say, a pesky ignorable bool return that you want to use with PostTask or
442 // something else that expect a Callback with a void return.
444 // EXAMPLE OF IgnoreResult():
446 // int DoSomething(int arg) { cout << arg << endl; }
448 // // Assign to a Callback with a void return type.
449 // Callback<void(int)> cb = Bind(IgnoreResult(&DoSomething));
450 // cb->Run(1); // Prints "1".
452 // // Prints "1" on |ml|.
453 // ml->PostTask(FROM_HERE, Bind(IgnoreResult(&DoSomething), 1);
454 template <typename T>
455 static inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
456 return internal::IgnoreResultHelper<T>(std::move(data));
459 #if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
461 // RetainBlock() is used to adapt an Objective-C block when Automated Reference
462 // Counting (ARC) is disabled. This is unnecessary when ARC is enabled, as the
463 // BindOnce and BindRepeating already support blocks then.
465 // EXAMPLE OF RetainBlock():
467 // // Wrap the block and bind it to a callback.
468 // Callback<void(int)> cb = Bind(RetainBlock(^(int n) { NSLog(@"%d", n); }));
469 // cb.Run(1); // Logs "1".
470 template <typename R, typename... Args>
471 base::mac::ScopedBlock<R (^)(Args...)> RetainBlock(R (^block)(Args...)) {
472 return base::mac::ScopedBlock<R (^)(Args...)>(block,
473 base::scoped_policy::RETAIN);
476 #endif // defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
480 #endif // BASE_BIND_H_