bind_internal.h 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  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. #ifndef BASE_BIND_INTERNAL_H_
  5. #define BASE_BIND_INTERNAL_H_
  6. #include <stddef.h>
  7. #include <functional>
  8. #include <memory>
  9. #include <tuple>
  10. #include <type_traits>
  11. #include <utility>
  12. #include "base/bind.h"
  13. #include "base/callback_internal.h"
  14. #include "base/check.h"
  15. #include "base/compiler_specific.h"
  16. #include "base/memory/raw_scoped_refptr_mismatch_checker.h"
  17. #include "base/memory/weak_ptr.h"
  18. #include "base/notreached.h"
  19. #include "base/template_util.h"
  20. #include "build/build_config.h"
  21. #if defined(OS_APPLE) && !HAS_FEATURE(objc_arc)
  22. #include "base/mac/scoped_block.h"
  23. #endif
  24. // See base/callback.h for user documentation.
  25. //
  26. //
  27. // CONCEPTS:
  28. // Functor -- A movable type representing something that should be called.
  29. // All function pointers and Callback<> are functors even if the
  30. // invocation syntax differs.
  31. // RunType -- A function type (as opposed to function _pointer_ type) for
  32. // a Callback<>::Run(). Usually just a convenience typedef.
  33. // (Bound)Args -- A set of types that stores the arguments.
  34. //
  35. // Types:
  36. // ForceVoidReturn<> -- Helper class for translating function signatures to
  37. // equivalent forms with a "void" return type.
  38. // FunctorTraits<> -- Type traits used to determine the correct RunType and
  39. // invocation manner for a Functor. This is where function
  40. // signature adapters are applied.
  41. // InvokeHelper<> -- Take a Functor + arguments and actully invokes it.
  42. // Handle the differing syntaxes needed for WeakPtr<>
  43. // support. This is separate from Invoker to avoid creating
  44. // multiple version of Invoker<>.
  45. // Invoker<> -- Unwraps the curried parameters and executes the Functor.
  46. // BindState<> -- Stores the curried parameters, and is the main entry point
  47. // into the Bind() system.
  48. #if defined(OS_WIN)
  49. namespace Microsoft {
  50. namespace WRL {
  51. template <typename>
  52. class ComPtr;
  53. } // namespace WRL
  54. } // namespace Microsoft
  55. #endif
  56. namespace base {
  57. template <typename T>
  58. struct IsWeakReceiver;
  59. template <typename>
  60. struct BindUnwrapTraits;
  61. template <typename Functor, typename BoundArgsTuple, typename SFINAE = void>
  62. struct CallbackCancellationTraits;
  63. namespace internal {
  64. template <typename Functor, typename SFINAE = void>
  65. struct FunctorTraits;
  66. template <typename T>
  67. class UnretainedWrapper {
  68. public:
  69. explicit UnretainedWrapper(T* o) : ptr_(o) {}
  70. T* get() const { return ptr_; }
  71. private:
  72. T* ptr_;
  73. };
  74. template <typename T>
  75. class RetainedRefWrapper {
  76. public:
  77. explicit RetainedRefWrapper(T* o) : ptr_(o) {}
  78. explicit RetainedRefWrapper(scoped_refptr<T> o) : ptr_(std::move(o)) {}
  79. T* get() const { return ptr_.get(); }
  80. private:
  81. scoped_refptr<T> ptr_;
  82. };
  83. template <typename T>
  84. struct IgnoreResultHelper {
  85. explicit IgnoreResultHelper(T functor) : functor_(std::move(functor)) {}
  86. explicit operator bool() const { return !!functor_; }
  87. T functor_;
  88. };
  89. template <typename T, typename Deleter = std::default_delete<T>>
  90. class OwnedWrapper {
  91. public:
  92. explicit OwnedWrapper(T* o) : ptr_(o) {}
  93. explicit OwnedWrapper(std::unique_ptr<T, Deleter>&& ptr)
  94. : ptr_(std::move(ptr)) {}
  95. T* get() const { return ptr_.get(); }
  96. private:
  97. std::unique_ptr<T, Deleter> ptr_;
  98. };
  99. // PassedWrapper is a copyable adapter for a scoper that ignores const.
  100. //
  101. // It is needed to get around the fact that Bind() takes a const reference to
  102. // all its arguments. Because Bind() takes a const reference to avoid
  103. // unnecessary copies, it is incompatible with movable-but-not-copyable
  104. // types; doing a destructive "move" of the type into Bind() would violate
  105. // the const correctness.
  106. //
  107. // This conundrum cannot be solved without either C++11 rvalue references or
  108. // a O(2^n) blowup of Bind() templates to handle each combination of regular
  109. // types and movable-but-not-copyable types. Thus we introduce a wrapper type
  110. // that is copyable to transmit the correct type information down into
  111. // BindState<>. Ignoring const in this type makes sense because it is only
  112. // created when we are explicitly trying to do a destructive move.
  113. //
  114. // Two notes:
  115. // 1) PassedWrapper supports any type that has a move constructor, however
  116. // the type will need to be specifically whitelisted in order for it to be
  117. // bound to a Callback. We guard this explicitly at the call of Passed()
  118. // to make for clear errors. Things not given to Passed() will be forwarded
  119. // and stored by value which will not work for general move-only types.
  120. // 2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
  121. // scoper to a Callback and allow the Callback to execute once.
  122. template <typename T>
  123. class PassedWrapper {
  124. public:
  125. explicit PassedWrapper(T&& scoper)
  126. : is_valid_(true), scoper_(std::move(scoper)) {}
  127. PassedWrapper(PassedWrapper&& other)
  128. : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {}
  129. T Take() const {
  130. CHECK(is_valid_);
  131. is_valid_ = false;
  132. return std::move(scoper_);
  133. }
  134. private:
  135. mutable bool is_valid_;
  136. mutable T scoper_;
  137. };
  138. template <typename T>
  139. using Unwrapper = BindUnwrapTraits<std::decay_t<T>>;
  140. template <typename T>
  141. decltype(auto) Unwrap(T&& o) {
  142. return Unwrapper<T>::Unwrap(std::forward<T>(o));
  143. }
  144. // IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a
  145. // method. It is used internally by Bind() to select the correct
  146. // InvokeHelper that will no-op itself in the event the WeakPtr<> for
  147. // the target object is invalidated.
  148. //
  149. // The first argument should be the type of the object that will be received by
  150. // the method.
  151. template <bool is_method, typename... Args>
  152. struct IsWeakMethod : std::false_type {};
  153. template <typename T, typename... Args>
  154. struct IsWeakMethod<true, T, Args...> : IsWeakReceiver<T> {};
  155. // Packs a list of types to hold them in a single type.
  156. template <typename... Types>
  157. struct TypeList {};
  158. // Used for DropTypeListItem implementation.
  159. template <size_t n, typename List>
  160. struct DropTypeListItemImpl;
  161. // Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
  162. template <size_t n, typename T, typename... List>
  163. struct DropTypeListItemImpl<n, TypeList<T, List...>>
  164. : DropTypeListItemImpl<n - 1, TypeList<List...>> {};
  165. template <typename T, typename... List>
  166. struct DropTypeListItemImpl<0, TypeList<T, List...>> {
  167. using Type = TypeList<T, List...>;
  168. };
  169. template <>
  170. struct DropTypeListItemImpl<0, TypeList<>> {
  171. using Type = TypeList<>;
  172. };
  173. // A type-level function that drops |n| list item from given TypeList.
  174. template <size_t n, typename List>
  175. using DropTypeListItem = typename DropTypeListItemImpl<n, List>::Type;
  176. // Used for TakeTypeListItem implementation.
  177. template <size_t n, typename List, typename... Accum>
  178. struct TakeTypeListItemImpl;
  179. // Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
  180. template <size_t n, typename T, typename... List, typename... Accum>
  181. struct TakeTypeListItemImpl<n, TypeList<T, List...>, Accum...>
  182. : TakeTypeListItemImpl<n - 1, TypeList<List...>, Accum..., T> {};
  183. template <typename T, typename... List, typename... Accum>
  184. struct TakeTypeListItemImpl<0, TypeList<T, List...>, Accum...> {
  185. using Type = TypeList<Accum...>;
  186. };
  187. template <typename... Accum>
  188. struct TakeTypeListItemImpl<0, TypeList<>, Accum...> {
  189. using Type = TypeList<Accum...>;
  190. };
  191. // A type-level function that takes first |n| list item from given TypeList.
  192. // E.g. TakeTypeListItem<3, TypeList<A, B, C, D>> is evaluated to
  193. // TypeList<A, B, C>.
  194. template <size_t n, typename List>
  195. using TakeTypeListItem = typename TakeTypeListItemImpl<n, List>::Type;
  196. // Used for ConcatTypeLists implementation.
  197. template <typename List1, typename List2>
  198. struct ConcatTypeListsImpl;
  199. template <typename... Types1, typename... Types2>
  200. struct ConcatTypeListsImpl<TypeList<Types1...>, TypeList<Types2...>> {
  201. using Type = TypeList<Types1..., Types2...>;
  202. };
  203. // A type-level function that concats two TypeLists.
  204. template <typename List1, typename List2>
  205. using ConcatTypeLists = typename ConcatTypeListsImpl<List1, List2>::Type;
  206. // Used for MakeFunctionType implementation.
  207. template <typename R, typename ArgList>
  208. struct MakeFunctionTypeImpl;
  209. template <typename R, typename... Args>
  210. struct MakeFunctionTypeImpl<R, TypeList<Args...>> {
  211. // MSVC 2013 doesn't support Type Alias of function types.
  212. // Revisit this after we update it to newer version.
  213. typedef R Type(Args...);
  214. };
  215. // A type-level function that constructs a function type that has |R| as its
  216. // return type and has TypeLists items as its arguments.
  217. template <typename R, typename ArgList>
  218. using MakeFunctionType = typename MakeFunctionTypeImpl<R, ArgList>::Type;
  219. // Used for ExtractArgs and ExtractReturnType.
  220. template <typename Signature>
  221. struct ExtractArgsImpl;
  222. template <typename R, typename... Args>
  223. struct ExtractArgsImpl<R(Args...)> {
  224. using ReturnType = R;
  225. using ArgsList = TypeList<Args...>;
  226. };
  227. // A type-level function that extracts function arguments into a TypeList.
  228. // E.g. ExtractArgs<R(A, B, C)> is evaluated to TypeList<A, B, C>.
  229. template <typename Signature>
  230. using ExtractArgs = typename ExtractArgsImpl<Signature>::ArgsList;
  231. // A type-level function that extracts the return type of a function.
  232. // E.g. ExtractReturnType<R(A, B, C)> is evaluated to R.
  233. template <typename Signature>
  234. using ExtractReturnType = typename ExtractArgsImpl<Signature>::ReturnType;
  235. template <typename Callable,
  236. typename Signature = decltype(&Callable::operator())>
  237. struct ExtractCallableRunTypeImpl;
  238. template <typename Callable, typename R, typename... Args>
  239. struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...)> {
  240. using Type = R(Args...);
  241. };
  242. template <typename Callable, typename R, typename... Args>
  243. struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...) const> {
  244. using Type = R(Args...);
  245. };
  246. // Evaluated to RunType of the given callable type.
  247. // Example:
  248. // auto f = [](int, char*) { return 0.1; };
  249. // ExtractCallableRunType<decltype(f)>
  250. // is evaluated to
  251. // double(int, char*);
  252. template <typename Callable>
  253. using ExtractCallableRunType =
  254. typename ExtractCallableRunTypeImpl<Callable>::Type;
  255. // IsCallableObject<Functor> is std::true_type if |Functor| has operator().
  256. // Otherwise, it's std::false_type.
  257. // Example:
  258. // IsCallableObject<void(*)()>::value is false.
  259. //
  260. // struct Foo {};
  261. // IsCallableObject<void(Foo::*)()>::value is false.
  262. //
  263. // int i = 0;
  264. // auto f = [i]() {};
  265. // IsCallableObject<decltype(f)>::value is false.
  266. template <typename Functor, typename SFINAE = void>
  267. struct IsCallableObject : std::false_type {};
  268. template <typename Callable>
  269. struct IsCallableObject<Callable, void_t<decltype(&Callable::operator())>>
  270. : std::true_type {};
  271. // HasRefCountedTypeAsRawPtr inherits from true_type when any of the |Args| is a
  272. // raw pointer to a RefCounted type.
  273. template <typename... Ts>
  274. struct HasRefCountedTypeAsRawPtr
  275. : disjunction<NeedsScopedRefptrButGetsRawPtr<Ts>...> {};
  276. // ForceVoidReturn<>
  277. //
  278. // Set of templates that support forcing the function return type to void.
  279. template <typename Sig>
  280. struct ForceVoidReturn;
  281. template <typename R, typename... Args>
  282. struct ForceVoidReturn<R(Args...)> {
  283. using RunType = void(Args...);
  284. };
  285. // FunctorTraits<>
  286. //
  287. // See description at top of file.
  288. template <typename Functor, typename SFINAE>
  289. struct FunctorTraits;
  290. // For empty callable types.
  291. // This specialization is intended to allow binding captureless lambdas, based
  292. // on the fact that captureless lambdas are empty while capturing lambdas are
  293. // not. This also allows any functors as far as it's an empty class.
  294. // Example:
  295. //
  296. // // Captureless lambdas are allowed.
  297. // []() {return 42;};
  298. //
  299. // // Capturing lambdas are *not* allowed.
  300. // int x;
  301. // [x]() {return x;};
  302. //
  303. // // Any empty class with operator() is allowed.
  304. // struct Foo {
  305. // void operator()() const {}
  306. // // No non-static member variable and no virtual functions.
  307. // };
  308. template <typename Functor>
  309. struct FunctorTraits<Functor,
  310. std::enable_if_t<IsCallableObject<Functor>::value &&
  311. std::is_empty<Functor>::value>> {
  312. using RunType = ExtractCallableRunType<Functor>;
  313. static constexpr bool is_method = false;
  314. static constexpr bool is_nullable = false;
  315. static constexpr bool is_callback = false;
  316. template <typename RunFunctor, typename... RunArgs>
  317. static ExtractReturnType<RunType> Invoke(RunFunctor&& functor,
  318. RunArgs&&... args) {
  319. return std::forward<RunFunctor>(functor)(std::forward<RunArgs>(args)...);
  320. }
  321. };
  322. // For functions.
  323. template <typename R, typename... Args>
  324. struct FunctorTraits<R (*)(Args...)> {
  325. using RunType = R(Args...);
  326. static constexpr bool is_method = false;
  327. static constexpr bool is_nullable = true;
  328. static constexpr bool is_callback = false;
  329. template <typename Function, typename... RunArgs>
  330. static R Invoke(Function&& function, RunArgs&&... args) {
  331. return std::forward<Function>(function)(std::forward<RunArgs>(args)...);
  332. }
  333. };
  334. #if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
  335. // For functions.
  336. template <typename R, typename... Args>
  337. struct FunctorTraits<R(__stdcall*)(Args...)> {
  338. using RunType = R(Args...);
  339. static constexpr bool is_method = false;
  340. static constexpr bool is_nullable = true;
  341. static constexpr bool is_callback = false;
  342. template <typename... RunArgs>
  343. static R Invoke(R(__stdcall* function)(Args...), RunArgs&&... args) {
  344. return function(std::forward<RunArgs>(args)...);
  345. }
  346. };
  347. // For functions.
  348. template <typename R, typename... Args>
  349. struct FunctorTraits<R(__fastcall*)(Args...)> {
  350. using RunType = R(Args...);
  351. static constexpr bool is_method = false;
  352. static constexpr bool is_nullable = true;
  353. static constexpr bool is_callback = false;
  354. template <typename... RunArgs>
  355. static R Invoke(R(__fastcall* function)(Args...), RunArgs&&... args) {
  356. return function(std::forward<RunArgs>(args)...);
  357. }
  358. };
  359. #endif // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
  360. #if defined(OS_APPLE)
  361. // Support for Objective-C blocks. There are two implementation depending
  362. // on whether Automated Reference Counting (ARC) is enabled. When ARC is
  363. // enabled, then the block itself can be bound as the compiler will ensure
  364. // its lifetime will be correctly managed. Otherwise, require the block to
  365. // be wrapped in a base::mac::ScopedBlock (via base::RetainBlock) that will
  366. // correctly manage the block lifetime.
  367. //
  368. // The two implementation ensure that the One Definition Rule (ODR) is not
  369. // broken (it is not possible to write a template base::RetainBlock that would
  370. // work correctly both with ARC enabled and disabled).
  371. #if HAS_FEATURE(objc_arc)
  372. template <typename R, typename... Args>
  373. struct FunctorTraits<R (^)(Args...)> {
  374. using RunType = R(Args...);
  375. static constexpr bool is_method = false;
  376. static constexpr bool is_nullable = true;
  377. static constexpr bool is_callback = false;
  378. template <typename BlockType, typename... RunArgs>
  379. static R Invoke(BlockType&& block, RunArgs&&... args) {
  380. // According to LLVM documentation (§ 6.3), "local variables of automatic
  381. // storage duration do not have precise lifetime." Use objc_precise_lifetime
  382. // to ensure that the Objective-C block is not deallocated until it has
  383. // finished executing even if the Callback<> is destroyed during the block
  384. // execution.
  385. // https://clang.llvm.org/docs/AutomaticReferenceCounting.html#precise-lifetime-semantics
  386. __attribute__((objc_precise_lifetime)) R (^scoped_block)(Args...) = block;
  387. return scoped_block(std::forward<RunArgs>(args)...);
  388. }
  389. };
  390. #else // HAS_FEATURE(objc_arc)
  391. template <typename R, typename... Args>
  392. struct FunctorTraits<base::mac::ScopedBlock<R (^)(Args...)>> {
  393. using RunType = R(Args...);
  394. static constexpr bool is_method = false;
  395. static constexpr bool is_nullable = true;
  396. static constexpr bool is_callback = false;
  397. template <typename BlockType, typename... RunArgs>
  398. static R Invoke(BlockType&& block, RunArgs&&... args) {
  399. // Copy the block to ensure that the Objective-C block is not deallocated
  400. // until it has finished executing even if the Callback<> is destroyed
  401. // during the block execution.
  402. base::mac::ScopedBlock<R (^)(Args...)> scoped_block(block);
  403. return scoped_block.get()(std::forward<RunArgs>(args)...);
  404. }
  405. };
  406. #endif // HAS_FEATURE(objc_arc)
  407. #endif // defined(OS_APPLE)
  408. // For methods.
  409. template <typename R, typename Receiver, typename... Args>
  410. struct FunctorTraits<R (Receiver::*)(Args...)> {
  411. using RunType = R(Receiver*, Args...);
  412. static constexpr bool is_method = true;
  413. static constexpr bool is_nullable = true;
  414. static constexpr bool is_callback = false;
  415. template <typename Method, typename ReceiverPtr, typename... RunArgs>
  416. static R Invoke(Method method,
  417. ReceiverPtr&& receiver_ptr,
  418. RunArgs&&... args) {
  419. return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
  420. }
  421. };
  422. // For const methods.
  423. template <typename R, typename Receiver, typename... Args>
  424. struct FunctorTraits<R (Receiver::*)(Args...) const> {
  425. using RunType = R(const Receiver*, Args...);
  426. static constexpr bool is_method = true;
  427. static constexpr bool is_nullable = true;
  428. static constexpr bool is_callback = false;
  429. template <typename Method, typename ReceiverPtr, typename... RunArgs>
  430. static R Invoke(Method method,
  431. ReceiverPtr&& receiver_ptr,
  432. RunArgs&&... args) {
  433. return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
  434. }
  435. };
  436. #if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
  437. // For __stdcall methods.
  438. template <typename R, typename Receiver, typename... Args>
  439. struct FunctorTraits<R (__stdcall Receiver::*)(Args...)> {
  440. using RunType = R(Receiver*, Args...);
  441. static constexpr bool is_method = true;
  442. static constexpr bool is_nullable = true;
  443. static constexpr bool is_callback = false;
  444. template <typename Method, typename ReceiverPtr, typename... RunArgs>
  445. static R Invoke(Method method,
  446. ReceiverPtr&& receiver_ptr,
  447. RunArgs&&... args) {
  448. return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
  449. }
  450. };
  451. // For __stdcall const methods.
  452. template <typename R, typename Receiver, typename... Args>
  453. struct FunctorTraits<R (__stdcall Receiver::*)(Args...) const> {
  454. using RunType = R(const Receiver*, Args...);
  455. static constexpr bool is_method = true;
  456. static constexpr bool is_nullable = true;
  457. static constexpr bool is_callback = false;
  458. template <typename Method, typename ReceiverPtr, typename... RunArgs>
  459. static R Invoke(Method method,
  460. ReceiverPtr&& receiver_ptr,
  461. RunArgs&&... args) {
  462. return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
  463. }
  464. };
  465. #endif // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
  466. #ifdef __cpp_noexcept_function_type
  467. // noexcept makes a distinct function type in C++17.
  468. // I.e. `void(*)()` and `void(*)() noexcept` are same in pre-C++17, and
  469. // different in C++17.
  470. template <typename R, typename... Args>
  471. struct FunctorTraits<R (*)(Args...) noexcept> : FunctorTraits<R (*)(Args...)> {
  472. };
  473. template <typename R, typename Receiver, typename... Args>
  474. struct FunctorTraits<R (Receiver::*)(Args...) noexcept>
  475. : FunctorTraits<R (Receiver::*)(Args...)> {};
  476. template <typename R, typename Receiver, typename... Args>
  477. struct FunctorTraits<R (Receiver::*)(Args...) const noexcept>
  478. : FunctorTraits<R (Receiver::*)(Args...) const> {};
  479. #endif
  480. // For IgnoreResults.
  481. template <typename T>
  482. struct FunctorTraits<IgnoreResultHelper<T>> : FunctorTraits<T> {
  483. using RunType =
  484. typename ForceVoidReturn<typename FunctorTraits<T>::RunType>::RunType;
  485. template <typename IgnoreResultType, typename... RunArgs>
  486. static void Invoke(IgnoreResultType&& ignore_result_helper,
  487. RunArgs&&... args) {
  488. FunctorTraits<T>::Invoke(
  489. std::forward<IgnoreResultType>(ignore_result_helper).functor_,
  490. std::forward<RunArgs>(args)...);
  491. }
  492. };
  493. // For OnceCallbacks.
  494. template <typename R, typename... Args>
  495. struct FunctorTraits<OnceCallback<R(Args...)>> {
  496. using RunType = R(Args...);
  497. static constexpr bool is_method = false;
  498. static constexpr bool is_nullable = true;
  499. static constexpr bool is_callback = true;
  500. template <typename CallbackType, typename... RunArgs>
  501. static R Invoke(CallbackType&& callback, RunArgs&&... args) {
  502. DCHECK(!callback.is_null());
  503. return std::forward<CallbackType>(callback).Run(
  504. std::forward<RunArgs>(args)...);
  505. }
  506. };
  507. // For RepeatingCallbacks.
  508. template <typename R, typename... Args>
  509. struct FunctorTraits<RepeatingCallback<R(Args...)>> {
  510. using RunType = R(Args...);
  511. static constexpr bool is_method = false;
  512. static constexpr bool is_nullable = true;
  513. static constexpr bool is_callback = true;
  514. template <typename CallbackType, typename... RunArgs>
  515. static R Invoke(CallbackType&& callback, RunArgs&&... args) {
  516. DCHECK(!callback.is_null());
  517. return std::forward<CallbackType>(callback).Run(
  518. std::forward<RunArgs>(args)...);
  519. }
  520. };
  521. template <typename Functor>
  522. using MakeFunctorTraits = FunctorTraits<std::decay_t<Functor>>;
  523. // InvokeHelper<>
  524. //
  525. // There are 2 logical InvokeHelper<> specializations: normal, WeakCalls.
  526. //
  527. // The normal type just calls the underlying runnable.
  528. //
  529. // WeakCalls need special syntax that is applied to the first argument to check
  530. // if they should no-op themselves.
  531. template <bool is_weak_call, typename ReturnType>
  532. struct InvokeHelper;
  533. template <typename ReturnType>
  534. struct InvokeHelper<false, ReturnType> {
  535. template <typename Functor, typename... RunArgs>
  536. static inline ReturnType MakeItSo(Functor&& functor, RunArgs&&... args) {
  537. using Traits = MakeFunctorTraits<Functor>;
  538. return Traits::Invoke(std::forward<Functor>(functor),
  539. std::forward<RunArgs>(args)...);
  540. }
  541. };
  542. template <typename ReturnType>
  543. struct InvokeHelper<true, ReturnType> {
  544. // WeakCalls are only supported for functions with a void return type.
  545. // Otherwise, the function result would be undefined if the WeakPtr<>
  546. // is invalidated.
  547. static_assert(std::is_void<ReturnType>::value,
  548. "weak_ptrs can only bind to methods without return values");
  549. template <typename Functor, typename BoundWeakPtr, typename... RunArgs>
  550. static inline void MakeItSo(Functor&& functor,
  551. BoundWeakPtr&& weak_ptr,
  552. RunArgs&&... args) {
  553. if (!weak_ptr)
  554. return;
  555. using Traits = MakeFunctorTraits<Functor>;
  556. Traits::Invoke(std::forward<Functor>(functor),
  557. std::forward<BoundWeakPtr>(weak_ptr),
  558. std::forward<RunArgs>(args)...);
  559. }
  560. };
  561. // Invoker<>
  562. //
  563. // See description at the top of the file.
  564. template <typename StorageType, typename UnboundRunType>
  565. struct Invoker;
  566. template <typename StorageType, typename R, typename... UnboundArgs>
  567. struct Invoker<StorageType, R(UnboundArgs...)> {
  568. static R RunOnce(BindStateBase* base,
  569. PassingType<UnboundArgs>... unbound_args) {
  570. // Local references to make debugger stepping easier. If in a debugger,
  571. // you really want to warp ahead and step through the
  572. // InvokeHelper<>::MakeItSo() call below.
  573. StorageType* storage = static_cast<StorageType*>(base);
  574. static constexpr size_t num_bound_args =
  575. std::tuple_size<decltype(storage->bound_args_)>::value;
  576. return RunImpl(std::move(storage->functor_),
  577. std::move(storage->bound_args_),
  578. std::make_index_sequence<num_bound_args>(),
  579. std::forward<UnboundArgs>(unbound_args)...);
  580. }
  581. static R Run(BindStateBase* base, PassingType<UnboundArgs>... unbound_args) {
  582. // Local references to make debugger stepping easier. If in a debugger,
  583. // you really want to warp ahead and step through the
  584. // InvokeHelper<>::MakeItSo() call below.
  585. const StorageType* storage = static_cast<StorageType*>(base);
  586. static constexpr size_t num_bound_args =
  587. std::tuple_size<decltype(storage->bound_args_)>::value;
  588. return RunImpl(storage->functor_, storage->bound_args_,
  589. std::make_index_sequence<num_bound_args>(),
  590. std::forward<UnboundArgs>(unbound_args)...);
  591. }
  592. private:
  593. template <typename Functor, typename BoundArgsTuple, size_t... indices>
  594. static inline R RunImpl(Functor&& functor,
  595. BoundArgsTuple&& bound,
  596. std::index_sequence<indices...>,
  597. UnboundArgs&&... unbound_args) {
  598. static constexpr bool is_method = MakeFunctorTraits<Functor>::is_method;
  599. using DecayedArgsTuple = std::decay_t<BoundArgsTuple>;
  600. static constexpr bool is_weak_call =
  601. IsWeakMethod<is_method,
  602. std::tuple_element_t<indices, DecayedArgsTuple>...>();
  603. return InvokeHelper<is_weak_call, R>::MakeItSo(
  604. std::forward<Functor>(functor),
  605. Unwrap(std::get<indices>(std::forward<BoundArgsTuple>(bound)))...,
  606. std::forward<UnboundArgs>(unbound_args)...);
  607. }
  608. };
  609. // Extracts necessary type info from Functor and BoundArgs.
  610. // Used to implement MakeUnboundRunType, BindOnce and BindRepeating.
  611. template <typename Functor, typename... BoundArgs>
  612. struct BindTypeHelper {
  613. static constexpr size_t num_bounds = sizeof...(BoundArgs);
  614. using FunctorTraits = MakeFunctorTraits<Functor>;
  615. // Example:
  616. // When Functor is `double (Foo::*)(int, const std::string&)`, and BoundArgs
  617. // is a template pack of `Foo*` and `int16_t`:
  618. // - RunType is `double(Foo*, int, const std::string&)`,
  619. // - ReturnType is `double`,
  620. // - RunParamsList is `TypeList<Foo*, int, const std::string&>`,
  621. // - BoundParamsList is `TypeList<Foo*, int>`,
  622. // - UnboundParamsList is `TypeList<const std::string&>`,
  623. // - BoundArgsList is `TypeList<Foo*, int16_t>`,
  624. // - UnboundRunType is `double(const std::string&)`.
  625. using RunType = typename FunctorTraits::RunType;
  626. using ReturnType = ExtractReturnType<RunType>;
  627. using RunParamsList = ExtractArgs<RunType>;
  628. using BoundParamsList = TakeTypeListItem<num_bounds, RunParamsList>;
  629. using UnboundParamsList = DropTypeListItem<num_bounds, RunParamsList>;
  630. using BoundArgsList = TypeList<BoundArgs...>;
  631. using UnboundRunType = MakeFunctionType<ReturnType, UnboundParamsList>;
  632. };
  633. template <typename Functor>
  634. std::enable_if_t<FunctorTraits<Functor>::is_nullable, bool> IsNull(
  635. const Functor& functor) {
  636. return !functor;
  637. }
  638. template <typename Functor>
  639. std::enable_if_t<!FunctorTraits<Functor>::is_nullable, bool> IsNull(
  640. const Functor&) {
  641. return false;
  642. }
  643. // Used by QueryCancellationTraits below.
  644. template <typename Functor, typename BoundArgsTuple, size_t... indices>
  645. bool QueryCancellationTraitsImpl(BindStateBase::CancellationQueryMode mode,
  646. const Functor& functor,
  647. const BoundArgsTuple& bound_args,
  648. std::index_sequence<indices...>) {
  649. switch (mode) {
  650. case BindStateBase::IS_CANCELLED:
  651. return CallbackCancellationTraits<Functor, BoundArgsTuple>::IsCancelled(
  652. functor, std::get<indices>(bound_args)...);
  653. case BindStateBase::MAYBE_VALID:
  654. return CallbackCancellationTraits<Functor, BoundArgsTuple>::MaybeValid(
  655. functor, std::get<indices>(bound_args)...);
  656. }
  657. NOTREACHED();
  658. }
  659. // Relays |base| to corresponding CallbackCancellationTraits<>::Run(). Returns
  660. // true if the callback |base| represents is canceled.
  661. template <typename BindStateType>
  662. bool QueryCancellationTraits(const BindStateBase* base,
  663. BindStateBase::CancellationQueryMode mode) {
  664. const BindStateType* storage = static_cast<const BindStateType*>(base);
  665. static constexpr size_t num_bound_args =
  666. std::tuple_size<decltype(storage->bound_args_)>::value;
  667. return QueryCancellationTraitsImpl(
  668. mode, storage->functor_, storage->bound_args_,
  669. std::make_index_sequence<num_bound_args>());
  670. }
  671. // The base case of BanUnconstructedRefCountedReceiver that checks nothing.
  672. template <typename Functor, typename Receiver, typename... Unused>
  673. std::enable_if_t<
  674. !(MakeFunctorTraits<Functor>::is_method &&
  675. std::is_pointer<std::decay_t<Receiver>>::value &&
  676. IsRefCountedType<std::remove_pointer_t<std::decay_t<Receiver>>>::value)>
  677. BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {}
  678. template <typename Functor>
  679. void BanUnconstructedRefCountedReceiver() {}
  680. // Asserts that Callback is not the first owner of a ref-counted receiver.
  681. template <typename Functor, typename Receiver, typename... Unused>
  682. std::enable_if_t<
  683. MakeFunctorTraits<Functor>::is_method &&
  684. std::is_pointer<std::decay_t<Receiver>>::value &&
  685. IsRefCountedType<std::remove_pointer_t<std::decay_t<Receiver>>>::value>
  686. BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {
  687. DCHECK(receiver);
  688. // It's error prone to make the implicit first reference to ref-counted types.
  689. // In the example below, base::BindOnce() makes the implicit first reference
  690. // to the ref-counted Foo. If PostTask() failed or the posted task ran fast
  691. // enough, the newly created instance can be destroyed before |oo| makes
  692. // another reference.
  693. // Foo::Foo() {
  694. // base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, this));
  695. // }
  696. //
  697. // scoped_refptr<Foo> oo = new Foo();
  698. //
  699. // Instead of doing like above, please consider adding a static constructor,
  700. // and keep the first reference alive explicitly.
  701. // // static
  702. // scoped_refptr<Foo> Foo::Create() {
  703. // auto foo = base::WrapRefCounted(new Foo());
  704. // base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, foo));
  705. // return foo;
  706. // }
  707. //
  708. // Foo::Foo() {}
  709. //
  710. // scoped_refptr<Foo> oo = Foo::Create();
  711. DCHECK(receiver->HasAtLeastOneRef())
  712. << "base::Bind{Once,Repeating}() refuses to create the first reference "
  713. "to ref-counted objects. That typically happens around PostTask() in "
  714. "their constructor, and such objects can be destroyed before `new` "
  715. "returns if the task resolves fast enough.";
  716. }
  717. // BindState<>
  718. //
  719. // This stores all the state passed into Bind().
  720. template <typename Functor, typename... BoundArgs>
  721. struct BindState final : BindStateBase {
  722. using IsCancellable = bool_constant<
  723. CallbackCancellationTraits<Functor,
  724. std::tuple<BoundArgs...>>::is_cancellable>;
  725. template <typename ForwardFunctor, typename... ForwardBoundArgs>
  726. static BindState* Create(BindStateBase::InvokeFuncStorage invoke_func,
  727. ForwardFunctor&& functor,
  728. ForwardBoundArgs&&... bound_args) {
  729. // Ban ref counted receivers that were not yet fully constructed to avoid
  730. // a common pattern of racy situation.
  731. BanUnconstructedRefCountedReceiver<ForwardFunctor>(bound_args...);
  732. // IsCancellable is std::false_type if
  733. // CallbackCancellationTraits<>::IsCancelled returns always false.
  734. // Otherwise, it's std::true_type.
  735. return new BindState(IsCancellable{}, invoke_func,
  736. std::forward<ForwardFunctor>(functor),
  737. std::forward<ForwardBoundArgs>(bound_args)...);
  738. }
  739. Functor functor_;
  740. std::tuple<BoundArgs...> bound_args_;
  741. private:
  742. static constexpr bool is_nested_callback =
  743. internal::MakeFunctorTraits<Functor>::is_callback;
  744. template <typename ForwardFunctor, typename... ForwardBoundArgs>
  745. explicit BindState(std::true_type,
  746. BindStateBase::InvokeFuncStorage invoke_func,
  747. ForwardFunctor&& functor,
  748. ForwardBoundArgs&&... bound_args)
  749. : BindStateBase(invoke_func,
  750. &Destroy,
  751. &QueryCancellationTraits<BindState>),
  752. functor_(std::forward<ForwardFunctor>(functor)),
  753. bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
  754. // We check the validity of nested callbacks (e.g., Bind(callback, ...)) in
  755. // release builds to avoid null pointers from ending up in posted tasks,
  756. // causing hard-to-diagnose crashes. Ideally we'd do this for all functors
  757. // here, but that would have a large binary size impact.
  758. if (is_nested_callback) {
  759. CHECK(!IsNull(functor_));
  760. } else {
  761. DCHECK(!IsNull(functor_));
  762. }
  763. }
  764. template <typename ForwardFunctor, typename... ForwardBoundArgs>
  765. explicit BindState(std::false_type,
  766. BindStateBase::InvokeFuncStorage invoke_func,
  767. ForwardFunctor&& functor,
  768. ForwardBoundArgs&&... bound_args)
  769. : BindStateBase(invoke_func, &Destroy),
  770. functor_(std::forward<ForwardFunctor>(functor)),
  771. bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
  772. // See above for CHECK/DCHECK rationale.
  773. if (is_nested_callback) {
  774. CHECK(!IsNull(functor_));
  775. } else {
  776. DCHECK(!IsNull(functor_));
  777. }
  778. }
  779. ~BindState() = default;
  780. static void Destroy(const BindStateBase* self) {
  781. delete static_cast<const BindState*>(self);
  782. }
  783. };
  784. // Used to implement MakeBindStateType.
  785. template <bool is_method, typename Functor, typename... BoundArgs>
  786. struct MakeBindStateTypeImpl;
  787. template <typename Functor, typename... BoundArgs>
  788. struct MakeBindStateTypeImpl<false, Functor, BoundArgs...> {
  789. static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
  790. "A parameter is a refcounted type and needs scoped_refptr.");
  791. using Type = BindState<std::decay_t<Functor>, std::decay_t<BoundArgs>...>;
  792. };
  793. template <typename Functor>
  794. struct MakeBindStateTypeImpl<true, Functor> {
  795. using Type = BindState<std::decay_t<Functor>>;
  796. };
  797. template <typename Functor, typename Receiver, typename... BoundArgs>
  798. struct MakeBindStateTypeImpl<true, Functor, Receiver, BoundArgs...> {
  799. private:
  800. using DecayedReceiver = std::decay_t<Receiver>;
  801. static_assert(!std::is_array<std::remove_reference_t<Receiver>>::value,
  802. "First bound argument to a method cannot be an array.");
  803. static_assert(
  804. !std::is_pointer<DecayedReceiver>::value ||
  805. IsRefCountedType<std::remove_pointer_t<DecayedReceiver>>::value,
  806. "Receivers may not be raw pointers. If using a raw pointer here is safe"
  807. " and has no lifetime concerns, use base::Unretained() and document why"
  808. " it's safe.");
  809. static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
  810. "A parameter is a refcounted type and needs scoped_refptr.");
  811. public:
  812. using Type = BindState<
  813. std::decay_t<Functor>,
  814. std::conditional_t<std::is_pointer<DecayedReceiver>::value,
  815. scoped_refptr<std::remove_pointer_t<DecayedReceiver>>,
  816. DecayedReceiver>,
  817. std::decay_t<BoundArgs>...>;
  818. };
  819. template <typename Functor, typename... BoundArgs>
  820. using MakeBindStateType =
  821. typename MakeBindStateTypeImpl<MakeFunctorTraits<Functor>::is_method,
  822. Functor,
  823. BoundArgs...>::Type;
  824. } // namespace internal
  825. // An injection point to control |this| pointer behavior on a method invocation.
  826. // If IsWeakReceiver<> is true_type for |T| and |T| is used for a receiver of a
  827. // method, base::Bind cancels the method invocation if the receiver is tested as
  828. // false.
  829. // E.g. Foo::bar() is not called:
  830. // struct Foo : base::SupportsWeakPtr<Foo> {
  831. // void bar() {}
  832. // };
  833. //
  834. // WeakPtr<Foo> oo = nullptr;
  835. // base::BindOnce(&Foo::bar, oo).Run();
  836. template <typename T>
  837. struct IsWeakReceiver : std::false_type {};
  838. template <typename T>
  839. struct IsWeakReceiver<std::reference_wrapper<T>> : IsWeakReceiver<T> {};
  840. template <typename T>
  841. struct IsWeakReceiver<WeakPtr<T>> : std::true_type {};
  842. // An injection point to control how bound objects passed to the target
  843. // function. BindUnwrapTraits<>::Unwrap() is called for each bound objects right
  844. // before the target function is invoked.
  845. template <typename>
  846. struct BindUnwrapTraits {
  847. template <typename T>
  848. static T&& Unwrap(T&& o) {
  849. return std::forward<T>(o);
  850. }
  851. };
  852. template <typename T>
  853. struct BindUnwrapTraits<internal::UnretainedWrapper<T>> {
  854. static T* Unwrap(const internal::UnretainedWrapper<T>& o) { return o.get(); }
  855. };
  856. template <typename T>
  857. struct BindUnwrapTraits<std::reference_wrapper<T>> {
  858. static T& Unwrap(std::reference_wrapper<T> o) { return o.get(); }
  859. };
  860. template <typename T>
  861. struct BindUnwrapTraits<internal::RetainedRefWrapper<T>> {
  862. static T* Unwrap(const internal::RetainedRefWrapper<T>& o) { return o.get(); }
  863. };
  864. template <typename T, typename Deleter>
  865. struct BindUnwrapTraits<internal::OwnedWrapper<T, Deleter>> {
  866. static T* Unwrap(const internal::OwnedWrapper<T, Deleter>& o) {
  867. return o.get();
  868. }
  869. };
  870. template <typename T>
  871. struct BindUnwrapTraits<internal::PassedWrapper<T>> {
  872. static T Unwrap(const internal::PassedWrapper<T>& o) { return o.Take(); }
  873. };
  874. #if defined(OS_WIN)
  875. template <typename T>
  876. struct BindUnwrapTraits<Microsoft::WRL::ComPtr<T>> {
  877. static T* Unwrap(const Microsoft::WRL::ComPtr<T>& ptr) { return ptr.Get(); }
  878. };
  879. #endif
  880. // CallbackCancellationTraits allows customization of Callback's cancellation
  881. // semantics. By default, callbacks are not cancellable. A specialization should
  882. // set is_cancellable = true and implement an IsCancelled() that returns if the
  883. // callback should be cancelled.
  884. template <typename Functor, typename BoundArgsTuple, typename SFINAE>
  885. struct CallbackCancellationTraits {
  886. static constexpr bool is_cancellable = false;
  887. };
  888. // Specialization for method bound to weak pointer receiver.
  889. template <typename Functor, typename... BoundArgs>
  890. struct CallbackCancellationTraits<
  891. Functor,
  892. std::tuple<BoundArgs...>,
  893. std::enable_if_t<
  894. internal::IsWeakMethod<internal::FunctorTraits<Functor>::is_method,
  895. BoundArgs...>::value>> {
  896. static constexpr bool is_cancellable = true;
  897. template <typename Receiver, typename... Args>
  898. static bool IsCancelled(const Functor&,
  899. const Receiver& receiver,
  900. const Args&...) {
  901. return !receiver;
  902. }
  903. template <typename Receiver, typename... Args>
  904. static bool MaybeValid(const Functor&,
  905. const Receiver& receiver,
  906. const Args&...) {
  907. return receiver.MaybeValid();
  908. }
  909. };
  910. // Specialization for a nested bind.
  911. template <typename Signature, typename... BoundArgs>
  912. struct CallbackCancellationTraits<OnceCallback<Signature>,
  913. std::tuple<BoundArgs...>> {
  914. static constexpr bool is_cancellable = true;
  915. template <typename Functor>
  916. static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
  917. return functor.IsCancelled();
  918. }
  919. template <typename Functor>
  920. static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
  921. return functor.MaybeValid();
  922. }
  923. };
  924. template <typename Signature, typename... BoundArgs>
  925. struct CallbackCancellationTraits<RepeatingCallback<Signature>,
  926. std::tuple<BoundArgs...>> {
  927. static constexpr bool is_cancellable = true;
  928. template <typename Functor>
  929. static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
  930. return functor.IsCancelled();
  931. }
  932. template <typename Functor>
  933. static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
  934. return functor.MaybeValid();
  935. }
  936. };
  937. // Returns a RunType of bound functor.
  938. // E.g. MakeUnboundRunType<R(A, B, C), A, B> is evaluated to R(C).
  939. template <typename Functor, typename... BoundArgs>
  940. using MakeUnboundRunType =
  941. typename internal::BindTypeHelper<Functor, BoundArgs...>::UnboundRunType;
  942. } // namespace base
  943. #endif // BASE_BIND_INTERNAL_H_