bind_internal.h 39 KB

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