• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 Google Inc. All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 //    * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 //    * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 //    * Neither the name of Google Inc. nor the name Chromium Embedded
14 // Framework nor the names of its contributors may be used to endorse
15 // or promote products derived from this software without specific prior
16 // written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 // Do not include this header file directly. Use base/cef_bind.h instead.
31 
32 // See base/cef_callback.h for user documentation.
33 //
34 //
35 // CONCEPTS:
36 //  Functor -- A movable type representing something that should be called.
37 //             All function pointers and Callback<> are functors even if the
38 //             invocation syntax differs.
39 //  RunType -- A function type (as opposed to function _pointer_ type) for
40 //             a Callback<>::Run().  Usually just a convenience typedef.
41 //  (Bound)Args -- A set of types that stores the arguments.
42 //
43 // Types:
44 //  ForceVoidReturn<> -- Helper class for translating function signatures to
45 //                       equivalent forms with a "void" return type.
46 //  FunctorTraits<> -- Type traits used to determine the correct RunType and
47 //                     invocation manner for a Functor.  This is where function
48 //                     signature adapters are applied.
49 //  InvokeHelper<> -- Take a Functor + arguments and actully invokes it.
50 //                    Handle the differing syntaxes needed for WeakPtr<>
51 //                    support.  This is separate from Invoker to avoid creating
52 //                    multiple version of Invoker<>.
53 //  Invoker<> -- Unwraps the curried parameters and executes the Functor.
54 //  BindState<> -- Stores the curried parameters, and is the main entry point
55 //                 into the Bind() system.
56 
57 #ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_H_
58 #define CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_H_
59 
60 #include <stddef.h>
61 
62 #include <functional>
63 #include <memory>
64 #include <tuple>
65 #include <type_traits>
66 #include <utility>
67 
68 #include "include/base/cef_build.h"
69 #include "include/base/cef_compiler_specific.h"
70 #include "include/base/cef_logging.h"
71 #include "include/base/cef_template_util.h"
72 #include "include/base/cef_weak_ptr.h"
73 #include "include/base/internal/cef_callback_internal.h"
74 #include "include/base/internal/cef_raw_scoped_refptr_mismatch_checker.h"
75 
76 #if defined(OS_APPLE) && !HAS_FEATURE(objc_arc)
77 #include "include/base/internal/cef_scoped_block_mac.h"
78 #endif
79 
80 #if defined(OS_WIN)
81 namespace Microsoft {
82 namespace WRL {
83 template <typename>
84 class ComPtr;
85 }  // namespace WRL
86 }  // namespace Microsoft
87 #endif
88 
89 namespace base {
90 
91 template <typename T>
92 struct IsWeakReceiver;
93 
94 template <typename>
95 struct BindUnwrapTraits;
96 
97 template <typename Functor, typename BoundArgsTuple, typename SFINAE = void>
98 struct CallbackCancellationTraits;
99 
100 namespace internal {
101 
102 template <typename Functor, typename SFINAE = void>
103 struct FunctorTraits;
104 
105 template <typename T>
106 class UnretainedWrapper {
107  public:
UnretainedWrapper(T * o)108   explicit UnretainedWrapper(T* o) : ptr_(o) {}
get()109   T* get() const { return ptr_; }
110 
111  private:
112   T* ptr_;
113 };
114 
115 template <typename T>
116 class RetainedRefWrapper {
117  public:
RetainedRefWrapper(T * o)118   explicit RetainedRefWrapper(T* o) : ptr_(o) {}
RetainedRefWrapper(scoped_refptr<T> o)119   explicit RetainedRefWrapper(scoped_refptr<T> o) : ptr_(std::move(o)) {}
get()120   T* get() const { return ptr_.get(); }
121 
122  private:
123   scoped_refptr<T> ptr_;
124 };
125 
126 template <typename T>
127 struct IgnoreResultHelper {
IgnoreResultHelperIgnoreResultHelper128   explicit IgnoreResultHelper(T functor) : functor_(std::move(functor)) {}
129   explicit operator bool() const { return !!functor_; }
130 
131   T functor_;
132 };
133 
134 template <typename T, typename Deleter = std::default_delete<T>>
135 class OwnedWrapper {
136  public:
OwnedWrapper(T * o)137   explicit OwnedWrapper(T* o) : ptr_(o) {}
OwnedWrapper(std::unique_ptr<T,Deleter> && ptr)138   explicit OwnedWrapper(std::unique_ptr<T, Deleter>&& ptr)
139       : ptr_(std::move(ptr)) {}
get()140   T* get() const { return ptr_.get(); }
141 
142  private:
143   std::unique_ptr<T, Deleter> ptr_;
144 };
145 
146 template <typename T>
147 class OwnedRefWrapper {
148  public:
OwnedRefWrapper(const T & t)149   explicit OwnedRefWrapper(const T& t) : t_(t) {}
OwnedRefWrapper(T && t)150   explicit OwnedRefWrapper(T&& t) : t_(std::move(t)) {}
get()151   T& get() const { return t_; }
152 
153  private:
154   mutable T t_;
155 };
156 
157 // PassedWrapper is a copyable adapter for a scoper that ignores const.
158 //
159 // It is needed to get around the fact that Bind() takes a const reference to
160 // all its arguments.  Because Bind() takes a const reference to avoid
161 // unnecessary copies, it is incompatible with movable-but-not-copyable
162 // types; doing a destructive "move" of the type into Bind() would violate
163 // the const correctness.
164 //
165 // This conundrum cannot be solved without either C++11 rvalue references or
166 // a O(2^n) blowup of Bind() templates to handle each combination of regular
167 // types and movable-but-not-copyable types.  Thus we introduce a wrapper type
168 // that is copyable to transmit the correct type information down into
169 // BindState<>. Ignoring const in this type makes sense because it is only
170 // created when we are explicitly trying to do a destructive move.
171 //
172 // Two notes:
173 //  1) PassedWrapper supports any type that has a move constructor, however
174 //     the type will need to be specifically allowed in order for it to be
175 //     bound to a Callback. We guard this explicitly at the call of Passed()
176 //     to make for clear errors. Things not given to Passed() will be forwarded
177 //     and stored by value which will not work for general move-only types.
178 //  2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
179 //     scoper to a Callback and allow the Callback to execute once.
180 template <typename T>
181 class PassedWrapper {
182  public:
PassedWrapper(T && scoper)183   explicit PassedWrapper(T&& scoper)
184       : is_valid_(true), scoper_(std::move(scoper)) {}
PassedWrapper(PassedWrapper && other)185   PassedWrapper(PassedWrapper&& other)
186       : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {}
Take()187   T Take() const {
188     CHECK(is_valid_);
189     is_valid_ = false;
190     return std::move(scoper_);
191   }
192 
193  private:
194   mutable bool is_valid_;
195   mutable T scoper_;
196 };
197 
198 template <typename T>
199 using Unwrapper = BindUnwrapTraits<std::decay_t<T>>;
200 
201 template <typename T>
decltype(auto)202 decltype(auto) Unwrap(T&& o) {
203   return Unwrapper<T>::Unwrap(std::forward<T>(o));
204 }
205 
206 // IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a
207 // method.  It is used internally by Bind() to select the correct
208 // InvokeHelper that will no-op itself in the event the WeakPtr<> for
209 // the target object is invalidated.
210 //
211 // The first argument should be the type of the object that will be received by
212 // the method.
213 template <bool is_method, typename... Args>
214 struct IsWeakMethod : std::false_type {};
215 
216 template <typename T, typename... Args>
217 struct IsWeakMethod<true, T, Args...> : IsWeakReceiver<T> {};
218 
219 // Packs a list of types to hold them in a single type.
220 template <typename... Types>
221 struct TypeList {};
222 
223 // Used for DropTypeListItem implementation.
224 template <size_t n, typename List>
225 struct DropTypeListItemImpl;
226 
227 // Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
228 template <size_t n, typename T, typename... List>
229 struct DropTypeListItemImpl<n, TypeList<T, List...>>
230     : DropTypeListItemImpl<n - 1, TypeList<List...>> {};
231 
232 template <typename T, typename... List>
233 struct DropTypeListItemImpl<0, TypeList<T, List...>> {
234   using Type = TypeList<T, List...>;
235 };
236 
237 template <>
238 struct DropTypeListItemImpl<0, TypeList<>> {
239   using Type = TypeList<>;
240 };
241 
242 // A type-level function that drops |n| list item from given TypeList.
243 template <size_t n, typename List>
244 using DropTypeListItem = typename DropTypeListItemImpl<n, List>::Type;
245 
246 // Used for TakeTypeListItem implementation.
247 template <size_t n, typename List, typename... Accum>
248 struct TakeTypeListItemImpl;
249 
250 // Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
251 template <size_t n, typename T, typename... List, typename... Accum>
252 struct TakeTypeListItemImpl<n, TypeList<T, List...>, Accum...>
253     : TakeTypeListItemImpl<n - 1, TypeList<List...>, Accum..., T> {};
254 
255 template <typename T, typename... List, typename... Accum>
256 struct TakeTypeListItemImpl<0, TypeList<T, List...>, Accum...> {
257   using Type = TypeList<Accum...>;
258 };
259 
260 template <typename... Accum>
261 struct TakeTypeListItemImpl<0, TypeList<>, Accum...> {
262   using Type = TypeList<Accum...>;
263 };
264 
265 // A type-level function that takes first |n| list item from given TypeList.
266 // E.g. TakeTypeListItem<3, TypeList<A, B, C, D>> is evaluated to
267 // TypeList<A, B, C>.
268 template <size_t n, typename List>
269 using TakeTypeListItem = typename TakeTypeListItemImpl<n, List>::Type;
270 
271 // Used for ConcatTypeLists implementation.
272 template <typename List1, typename List2>
273 struct ConcatTypeListsImpl;
274 
275 template <typename... Types1, typename... Types2>
276 struct ConcatTypeListsImpl<TypeList<Types1...>, TypeList<Types2...>> {
277   using Type = TypeList<Types1..., Types2...>;
278 };
279 
280 // A type-level function that concats two TypeLists.
281 template <typename List1, typename List2>
282 using ConcatTypeLists = typename ConcatTypeListsImpl<List1, List2>::Type;
283 
284 // Used for MakeFunctionType implementation.
285 template <typename R, typename ArgList>
286 struct MakeFunctionTypeImpl;
287 
288 template <typename R, typename... Args>
289 struct MakeFunctionTypeImpl<R, TypeList<Args...>> {
290   // MSVC 2013 doesn't support Type Alias of function types.
291   // Revisit this after we update it to newer version.
292   typedef R Type(Args...);
293 };
294 
295 // A type-level function that constructs a function type that has |R| as its
296 // return type and has TypeLists items as its arguments.
297 template <typename R, typename ArgList>
298 using MakeFunctionType = typename MakeFunctionTypeImpl<R, ArgList>::Type;
299 
300 // Used for ExtractArgs and ExtractReturnType.
301 template <typename Signature>
302 struct ExtractArgsImpl;
303 
304 template <typename R, typename... Args>
305 struct ExtractArgsImpl<R(Args...)> {
306   using ReturnType = R;
307   using ArgsList = TypeList<Args...>;
308 };
309 
310 // A type-level function that extracts function arguments into a TypeList.
311 // E.g. ExtractArgs<R(A, B, C)> is evaluated to TypeList<A, B, C>.
312 template <typename Signature>
313 using ExtractArgs = typename ExtractArgsImpl<Signature>::ArgsList;
314 
315 // A type-level function that extracts the return type of a function.
316 // E.g. ExtractReturnType<R(A, B, C)> is evaluated to R.
317 template <typename Signature>
318 using ExtractReturnType = typename ExtractArgsImpl<Signature>::ReturnType;
319 
320 template <typename Callable,
321           typename Signature = decltype(&Callable::operator())>
322 struct ExtractCallableRunTypeImpl;
323 
324 template <typename Callable, typename R, typename... Args>
325 struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...)> {
326   using Type = R(Args...);
327 };
328 
329 template <typename Callable, typename R, typename... Args>
330 struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...) const> {
331   using Type = R(Args...);
332 };
333 
334 // Evaluated to RunType of the given callable type.
335 // Example:
336 //   auto f = [](int, char*) { return 0.1; };
337 //   ExtractCallableRunType<decltype(f)>
338 //   is evaluated to
339 //   double(int, char*);
340 template <typename Callable>
341 using ExtractCallableRunType =
342     typename ExtractCallableRunTypeImpl<Callable>::Type;
343 
344 // IsCallableObject<Functor> is std::true_type if |Functor| has operator().
345 // Otherwise, it's std::false_type.
346 // Example:
347 //   IsCallableObject<void(*)()>::value is false.
348 //
349 //   struct Foo {};
350 //   IsCallableObject<void(Foo::*)()>::value is false.
351 //
352 //   int i = 0;
353 //   auto f = [i]() {};
354 //   IsCallableObject<decltype(f)>::value is false.
355 template <typename Functor, typename SFINAE = void>
356 struct IsCallableObject : std::false_type {};
357 
358 template <typename Callable>
359 struct IsCallableObject<Callable, void_t<decltype(&Callable::operator())>>
360     : std::true_type {};
361 
362 // HasRefCountedTypeAsRawPtr inherits from true_type when any of the |Args| is a
363 // raw pointer to a RefCounted type.
364 template <typename... Ts>
365 struct HasRefCountedTypeAsRawPtr
366     : disjunction<NeedsScopedRefptrButGetsRawPtr<Ts>...> {};
367 
368 // ForceVoidReturn<>
369 //
370 // Set of templates that support forcing the function return type to void.
371 template <typename Sig>
372 struct ForceVoidReturn;
373 
374 template <typename R, typename... Args>
375 struct ForceVoidReturn<R(Args...)> {
376   using RunType = void(Args...);
377 };
378 
379 // FunctorTraits<>
380 //
381 // See description at top of file.
382 template <typename Functor, typename SFINAE>
383 struct FunctorTraits;
384 
385 // For empty callable types.
386 // This specialization is intended to allow binding captureless lambdas, based
387 // on the fact that captureless lambdas are empty while capturing lambdas are
388 // not. This also allows any functors as far as it's an empty class.
389 // Example:
390 //
391 //   // Captureless lambdas are allowed.
392 //   []() {return 42;};
393 //
394 //   // Capturing lambdas are *not* allowed.
395 //   int x;
396 //   [x]() {return x;};
397 //
398 //   // Any empty class with operator() is allowed.
399 //   struct Foo {
400 //     void operator()() const {}
401 //     // No non-static member variable and no virtual functions.
402 //   };
403 template <typename Functor>
404 struct FunctorTraits<Functor,
405                      std::enable_if_t<IsCallableObject<Functor>::value &&
406                                       std::is_empty<Functor>::value>> {
407   using RunType = ExtractCallableRunType<Functor>;
408   static constexpr bool is_method = false;
409   static constexpr bool is_nullable = false;
410   static constexpr bool is_callback = false;
411 
412   template <typename RunFunctor, typename... RunArgs>
413   static ExtractReturnType<RunType> Invoke(RunFunctor&& functor,
414                                            RunArgs&&... args) {
415     return std::forward<RunFunctor>(functor)(std::forward<RunArgs>(args)...);
416   }
417 };
418 
419 // For functions.
420 template <typename R, typename... Args>
421 struct FunctorTraits<R (*)(Args...)> {
422   using RunType = R(Args...);
423   static constexpr bool is_method = false;
424   static constexpr bool is_nullable = true;
425   static constexpr bool is_callback = false;
426 
427   template <typename Function, typename... RunArgs>
428   static R Invoke(Function&& function, RunArgs&&... args) {
429     return std::forward<Function>(function)(std::forward<RunArgs>(args)...);
430   }
431 };
432 
433 #if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
434 
435 // For functions.
436 template <typename R, typename... Args>
437 struct FunctorTraits<R(__stdcall*)(Args...)> {
438   using RunType = R(Args...);
439   static constexpr bool is_method = false;
440   static constexpr bool is_nullable = true;
441   static constexpr bool is_callback = false;
442 
443   template <typename... RunArgs>
444   static R Invoke(R(__stdcall* function)(Args...), RunArgs&&... args) {
445     return function(std::forward<RunArgs>(args)...);
446   }
447 };
448 
449 // For functions.
450 template <typename R, typename... Args>
451 struct FunctorTraits<R(__fastcall*)(Args...)> {
452   using RunType = R(Args...);
453   static constexpr bool is_method = false;
454   static constexpr bool is_nullable = true;
455   static constexpr bool is_callback = false;
456 
457   template <typename... RunArgs>
458   static R Invoke(R(__fastcall* function)(Args...), RunArgs&&... args) {
459     return function(std::forward<RunArgs>(args)...);
460   }
461 };
462 
463 #endif  // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
464 
465 #if defined(OS_APPLE)
466 
467 // Support for Objective-C blocks. There are two implementation depending
468 // on whether Automated Reference Counting (ARC) is enabled. When ARC is
469 // enabled, then the block itself can be bound as the compiler will ensure
470 // its lifetime will be correctly managed. Otherwise, require the block to
471 // be wrapped in a base::mac::ScopedBlock (via base::RetainBlock) that will
472 // correctly manage the block lifetime.
473 //
474 // The two implementation ensure that the One Definition Rule (ODR) is not
475 // broken (it is not possible to write a template base::RetainBlock that would
476 // work correctly both with ARC enabled and disabled).
477 
478 #if HAS_FEATURE(objc_arc)
479 
480 template <typename R, typename... Args>
481 struct FunctorTraits<R (^)(Args...)> {
482   using RunType = R(Args...);
483   static constexpr bool is_method = false;
484   static constexpr bool is_nullable = true;
485   static constexpr bool is_callback = false;
486 
487   template <typename BlockType, typename... RunArgs>
488   static R Invoke(BlockType&& block, RunArgs&&... args) {
489     // According to LLVM documentation (6.3), "local variables of automatic
490     // storage duration do not have precise lifetime." Use objc_precise_lifetime
491     // to ensure that the Objective-C block is not deallocated until it has
492     // finished executing even if the Callback<> is destroyed during the block
493     // execution.
494     // https://clang.llvm.org/docs/AutomaticReferenceCounting.html#precise-lifetime-semantics
495     __attribute__((objc_precise_lifetime)) R (^scoped_block)(Args...) = block;
496     return scoped_block(std::forward<RunArgs>(args)...);
497   }
498 };
499 
500 #else  // HAS_FEATURE(objc_arc)
501 
502 template <typename R, typename... Args>
503 struct FunctorTraits<base::mac::ScopedBlock<R (^)(Args...)>> {
504   using RunType = R(Args...);
505   static constexpr bool is_method = false;
506   static constexpr bool is_nullable = true;
507   static constexpr bool is_callback = false;
508 
509   template <typename BlockType, typename... RunArgs>
510   static R Invoke(BlockType&& block, RunArgs&&... args) {
511     // Copy the block to ensure that the Objective-C block is not deallocated
512     // until it has finished executing even if the Callback<> is destroyed
513     // during the block execution.
514     base::mac::ScopedBlock<R (^)(Args...)> scoped_block(block);
515     return scoped_block.get()(std::forward<RunArgs>(args)...);
516   }
517 };
518 
519 #endif  // HAS_FEATURE(objc_arc)
520 #endif  // defined(OS_APPLE)
521 
522 // For methods.
523 template <typename R, typename Receiver, typename... Args>
524 struct FunctorTraits<R (Receiver::*)(Args...)> {
525   using RunType = R(Receiver*, Args...);
526   static constexpr bool is_method = true;
527   static constexpr bool is_nullable = true;
528   static constexpr bool is_callback = false;
529 
530   template <typename Method, typename ReceiverPtr, typename... RunArgs>
531   static R Invoke(Method method,
532                   ReceiverPtr&& receiver_ptr,
533                   RunArgs&&... args) {
534     return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
535   }
536 };
537 
538 // For const methods.
539 template <typename R, typename Receiver, typename... Args>
540 struct FunctorTraits<R (Receiver::*)(Args...) const> {
541   using RunType = R(const Receiver*, Args...);
542   static constexpr bool is_method = true;
543   static constexpr bool is_nullable = true;
544   static constexpr bool is_callback = false;
545 
546   template <typename Method, typename ReceiverPtr, typename... RunArgs>
547   static R Invoke(Method method,
548                   ReceiverPtr&& receiver_ptr,
549                   RunArgs&&... args) {
550     return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
551   }
552 };
553 
554 #if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
555 
556 // For __stdcall methods.
557 template <typename R, typename Receiver, typename... Args>
558 struct FunctorTraits<R (__stdcall Receiver::*)(Args...)> {
559   using RunType = R(Receiver*, Args...);
560   static constexpr bool is_method = true;
561   static constexpr bool is_nullable = true;
562   static constexpr bool is_callback = false;
563 
564   template <typename Method, typename ReceiverPtr, typename... RunArgs>
565   static R Invoke(Method method,
566                   ReceiverPtr&& receiver_ptr,
567                   RunArgs&&... args) {
568     return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
569   }
570 };
571 
572 // For __stdcall const methods.
573 template <typename R, typename Receiver, typename... Args>
574 struct FunctorTraits<R (__stdcall Receiver::*)(Args...) const> {
575   using RunType = R(const Receiver*, Args...);
576   static constexpr bool is_method = true;
577   static constexpr bool is_nullable = true;
578   static constexpr bool is_callback = false;
579 
580   template <typename Method, typename ReceiverPtr, typename... RunArgs>
581   static R Invoke(Method method,
582                   ReceiverPtr&& receiver_ptr,
583                   RunArgs&&... args) {
584     return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
585   }
586 };
587 
588 #endif  // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
589 
590 #ifdef __cpp_noexcept_function_type
591 // noexcept makes a distinct function type in C++17.
592 // I.e. `void(*)()` and `void(*)() noexcept` are same in pre-C++17, and
593 // different in C++17.
594 template <typename R, typename... Args>
595 struct FunctorTraits<R (*)(Args...) noexcept> : FunctorTraits<R (*)(Args...)> {
596 };
597 
598 template <typename R, typename Receiver, typename... Args>
599 struct FunctorTraits<R (Receiver::*)(Args...) noexcept>
600     : FunctorTraits<R (Receiver::*)(Args...)> {};
601 
602 template <typename R, typename Receiver, typename... Args>
603 struct FunctorTraits<R (Receiver::*)(Args...) const noexcept>
604     : FunctorTraits<R (Receiver::*)(Args...) const> {};
605 #endif
606 
607 // For IgnoreResults.
608 template <typename T>
609 struct FunctorTraits<IgnoreResultHelper<T>> : FunctorTraits<T> {
610   using RunType =
611       typename ForceVoidReturn<typename FunctorTraits<T>::RunType>::RunType;
612 
613   template <typename IgnoreResultType, typename... RunArgs>
614   static void Invoke(IgnoreResultType&& ignore_result_helper,
615                      RunArgs&&... args) {
616     FunctorTraits<T>::Invoke(
617         std::forward<IgnoreResultType>(ignore_result_helper).functor_,
618         std::forward<RunArgs>(args)...);
619   }
620 };
621 
622 // For OnceCallbacks.
623 template <typename R, typename... Args>
624 struct FunctorTraits<OnceCallback<R(Args...)>> {
625   using RunType = R(Args...);
626   static constexpr bool is_method = false;
627   static constexpr bool is_nullable = true;
628   static constexpr bool is_callback = true;
629 
630   template <typename CallbackType, typename... RunArgs>
631   static R Invoke(CallbackType&& callback, RunArgs&&... args) {
632     DCHECK(!callback.is_null());
633     return std::forward<CallbackType>(callback).Run(
634         std::forward<RunArgs>(args)...);
635   }
636 };
637 
638 // For RepeatingCallbacks.
639 template <typename R, typename... Args>
640 struct FunctorTraits<RepeatingCallback<R(Args...)>> {
641   using RunType = R(Args...);
642   static constexpr bool is_method = false;
643   static constexpr bool is_nullable = true;
644   static constexpr bool is_callback = true;
645 
646   template <typename CallbackType, typename... RunArgs>
647   static R Invoke(CallbackType&& callback, RunArgs&&... args) {
648     DCHECK(!callback.is_null());
649     return std::forward<CallbackType>(callback).Run(
650         std::forward<RunArgs>(args)...);
651   }
652 };
653 
654 template <typename Functor>
655 using MakeFunctorTraits = FunctorTraits<std::decay_t<Functor>>;
656 
657 // InvokeHelper<>
658 //
659 // There are 2 logical InvokeHelper<> specializations: normal, WeakCalls.
660 //
661 // The normal type just calls the underlying runnable.
662 //
663 // WeakCalls need special syntax that is applied to the first argument to check
664 // if they should no-op themselves.
665 template <bool is_weak_call, typename ReturnType>
666 struct InvokeHelper;
667 
668 template <typename ReturnType>
669 struct InvokeHelper<false, ReturnType> {
670   template <typename Functor, typename... RunArgs>
671   static inline ReturnType MakeItSo(Functor&& functor, RunArgs&&... args) {
672     using Traits = MakeFunctorTraits<Functor>;
673     return Traits::Invoke(std::forward<Functor>(functor),
674                           std::forward<RunArgs>(args)...);
675   }
676 };
677 
678 template <typename ReturnType>
679 struct InvokeHelper<true, ReturnType> {
680   // WeakCalls are only supported for functions with a void return type.
681   // Otherwise, the function result would be undefined if the WeakPtr<>
682   // is invalidated.
683   static_assert(std::is_void<ReturnType>::value,
684                 "weak_ptrs can only bind to methods without return values");
685 
686   template <typename Functor, typename BoundWeakPtr, typename... RunArgs>
687   static inline void MakeItSo(Functor&& functor,
688                               BoundWeakPtr&& weak_ptr,
689                               RunArgs&&... args) {
690     if (!weak_ptr)
691       return;
692     using Traits = MakeFunctorTraits<Functor>;
693     Traits::Invoke(std::forward<Functor>(functor),
694                    std::forward<BoundWeakPtr>(weak_ptr),
695                    std::forward<RunArgs>(args)...);
696   }
697 };
698 
699 // Invoker<>
700 //
701 // See description at the top of the file.
702 template <typename StorageType, typename UnboundRunType>
703 struct Invoker;
704 
705 template <typename StorageType, typename R, typename... UnboundArgs>
706 struct Invoker<StorageType, R(UnboundArgs...)> {
707   static R RunOnce(BindStateBase* base,
708                    PassingType<UnboundArgs>... unbound_args) {
709     // Local references to make debugger stepping easier. If in a debugger,
710     // you really want to warp ahead and step through the
711     // InvokeHelper<>::MakeItSo() call below.
712     StorageType* storage = static_cast<StorageType*>(base);
713     static constexpr size_t num_bound_args =
714         std::tuple_size<decltype(storage->bound_args_)>::value;
715     return RunImpl(std::move(storage->functor_),
716                    std::move(storage->bound_args_),
717                    std::make_index_sequence<num_bound_args>(),
718                    std::forward<UnboundArgs>(unbound_args)...);
719   }
720 
721   static R Run(BindStateBase* base, PassingType<UnboundArgs>... unbound_args) {
722     // Local references to make debugger stepping easier. If in a debugger,
723     // you really want to warp ahead and step through the
724     // InvokeHelper<>::MakeItSo() call below.
725     const StorageType* storage = static_cast<StorageType*>(base);
726     static constexpr size_t num_bound_args =
727         std::tuple_size<decltype(storage->bound_args_)>::value;
728     return RunImpl(storage->functor_, storage->bound_args_,
729                    std::make_index_sequence<num_bound_args>(),
730                    std::forward<UnboundArgs>(unbound_args)...);
731   }
732 
733  private:
734   template <typename Functor, typename BoundArgsTuple, size_t... indices>
735   static inline R RunImpl(Functor&& functor,
736                           BoundArgsTuple&& bound,
737                           std::index_sequence<indices...>,
738                           UnboundArgs&&... unbound_args) {
739     static constexpr bool is_method = MakeFunctorTraits<Functor>::is_method;
740 
741     using DecayedArgsTuple = std::decay_t<BoundArgsTuple>;
742     static constexpr bool is_weak_call =
743         IsWeakMethod<is_method,
744                      std::tuple_element_t<indices, DecayedArgsTuple>...>();
745 
746     return InvokeHelper<is_weak_call, R>::MakeItSo(
747         std::forward<Functor>(functor),
748         Unwrap(std::get<indices>(std::forward<BoundArgsTuple>(bound)))...,
749         std::forward<UnboundArgs>(unbound_args)...);
750   }
751 };
752 
753 // Extracts necessary type info from Functor and BoundArgs.
754 // Used to implement MakeUnboundRunType, BindOnce and BindRepeating.
755 template <typename Functor, typename... BoundArgs>
756 struct BindTypeHelper {
757   static constexpr size_t num_bounds = sizeof...(BoundArgs);
758   using FunctorTraits = MakeFunctorTraits<Functor>;
759 
760   // Example:
761   //   When Functor is `double (Foo::*)(int, const std::string&)`, and BoundArgs
762   //   is a template pack of `Foo*` and `int16_t`:
763   //    - RunType is `double(Foo*, int, const std::string&)`,
764   //    - ReturnType is `double`,
765   //    - RunParamsList is `TypeList<Foo*, int, const std::string&>`,
766   //    - BoundParamsList is `TypeList<Foo*, int>`,
767   //    - UnboundParamsList is `TypeList<const std::string&>`,
768   //    - BoundArgsList is `TypeList<Foo*, int16_t>`,
769   //    - UnboundRunType is `double(const std::string&)`.
770   using RunType = typename FunctorTraits::RunType;
771   using ReturnType = ExtractReturnType<RunType>;
772 
773   using RunParamsList = ExtractArgs<RunType>;
774   using BoundParamsList = TakeTypeListItem<num_bounds, RunParamsList>;
775   using UnboundParamsList = DropTypeListItem<num_bounds, RunParamsList>;
776 
777   using BoundArgsList = TypeList<BoundArgs...>;
778 
779   using UnboundRunType = MakeFunctionType<ReturnType, UnboundParamsList>;
780 };
781 
782 template <typename Functor>
783 std::enable_if_t<FunctorTraits<Functor>::is_nullable, bool> IsNull(
784     const Functor& functor) {
785   return !functor;
786 }
787 
788 template <typename Functor>
789 std::enable_if_t<!FunctorTraits<Functor>::is_nullable, bool> IsNull(
790     const Functor&) {
791   return false;
792 }
793 
794 // Used by QueryCancellationTraits below.
795 template <typename Functor, typename BoundArgsTuple, size_t... indices>
796 bool QueryCancellationTraitsImpl(BindStateBase::CancellationQueryMode mode,
797                                  const Functor& functor,
798                                  const BoundArgsTuple& bound_args,
799                                  std::index_sequence<indices...>) {
800   switch (mode) {
801     case BindStateBase::IS_CANCELLED:
802       return CallbackCancellationTraits<Functor, BoundArgsTuple>::IsCancelled(
803           functor, std::get<indices>(bound_args)...);
804     case BindStateBase::MAYBE_VALID:
805       return CallbackCancellationTraits<Functor, BoundArgsTuple>::MaybeValid(
806           functor, std::get<indices>(bound_args)...);
807   }
808   NOTREACHED();
809   return false;
810 }
811 
812 // Relays |base| to corresponding CallbackCancellationTraits<>::Run(). Returns
813 // true if the callback |base| represents is canceled.
814 template <typename BindStateType>
815 bool QueryCancellationTraits(const BindStateBase* base,
816                              BindStateBase::CancellationQueryMode mode) {
817   const BindStateType* storage = static_cast<const BindStateType*>(base);
818   static constexpr size_t num_bound_args =
819       std::tuple_size<decltype(storage->bound_args_)>::value;
820   return QueryCancellationTraitsImpl(
821       mode, storage->functor_, storage->bound_args_,
822       std::make_index_sequence<num_bound_args>());
823 }
824 
825 // The base case of BanUnconstructedRefCountedReceiver that checks nothing.
826 template <typename Functor, typename Receiver, typename... Unused>
827 std::enable_if_t<
828     !(MakeFunctorTraits<Functor>::is_method &&
829       std::is_pointer<std::decay_t<Receiver>>::value &&
830       IsRefCountedType<std::remove_pointer_t<std::decay_t<Receiver>>>::value)>
831 BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {}
832 
833 template <typename Functor>
834 void BanUnconstructedRefCountedReceiver() {}
835 
836 // Asserts that Callback is not the first owner of a ref-counted receiver.
837 template <typename Functor, typename Receiver, typename... Unused>
838 std::enable_if_t<
839     MakeFunctorTraits<Functor>::is_method &&
840     std::is_pointer<std::decay_t<Receiver>>::value &&
841     IsRefCountedType<std::remove_pointer_t<std::decay_t<Receiver>>>::value>
842 BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {
843   DCHECK(receiver);
844 
845   // It's error prone to make the implicit first reference to ref-counted types.
846   // In the example below, base::BindOnce() makes the implicit first reference
847   // to the ref-counted Foo. If PostTask() failed or the posted task ran fast
848   // enough, the newly created instance can be destroyed before |oo| makes
849   // another reference.
850   //   Foo::Foo() {
851   //     base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, this));
852   //   }
853   //
854   //   scoped_refptr<Foo> oo = new Foo();
855   //
856   // Instead of doing like above, please consider adding a static constructor,
857   // and keep the first reference alive explicitly.
858   //   // static
859   //   scoped_refptr<Foo> Foo::Create() {
860   //     auto foo = base::WrapRefCounted(new Foo());
861   //     base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, foo));
862   //     return foo;
863   //   }
864   //
865   //   Foo::Foo() {}
866   //
867   //   scoped_refptr<Foo> oo = Foo::Create();
868   DCHECK(receiver->HasAtLeastOneRef())
869       << "base::Bind{Once,Repeating}() refuses to create the first reference "
870          "to ref-counted objects. That typically happens around PostTask() in "
871          "their constructor, and such objects can be destroyed before `new` "
872          "returns if the task resolves fast enough.";
873 }
874 
875 // BindState<>
876 //
877 // This stores all the state passed into Bind().
878 template <typename Functor, typename... BoundArgs>
879 struct BindState final : BindStateBase {
880   using IsCancellable = bool_constant<
881       CallbackCancellationTraits<Functor,
882                                  std::tuple<BoundArgs...>>::is_cancellable>;
883   template <typename ForwardFunctor, typename... ForwardBoundArgs>
884   static BindState* Create(BindStateBase::InvokeFuncStorage invoke_func,
885                            ForwardFunctor&& functor,
886                            ForwardBoundArgs&&... bound_args) {
887     // Ban ref counted receivers that were not yet fully constructed to avoid
888     // a common pattern of racy situation.
889     BanUnconstructedRefCountedReceiver<ForwardFunctor>(bound_args...);
890 
891     // IsCancellable is std::false_type if
892     // CallbackCancellationTraits<>::IsCancelled returns always false.
893     // Otherwise, it's std::true_type.
894     return new BindState(IsCancellable{}, invoke_func,
895                          std::forward<ForwardFunctor>(functor),
896                          std::forward<ForwardBoundArgs>(bound_args)...);
897   }
898 
899   Functor functor_;
900   std::tuple<BoundArgs...> bound_args_;
901 
902  private:
903   static constexpr bool is_nested_callback =
904       MakeFunctorTraits<Functor>::is_callback;
905 
906   template <typename ForwardFunctor, typename... ForwardBoundArgs>
907   explicit BindState(std::true_type,
908                      BindStateBase::InvokeFuncStorage invoke_func,
909                      ForwardFunctor&& functor,
910                      ForwardBoundArgs&&... bound_args)
911       : BindStateBase(invoke_func,
912                       &Destroy,
913                       &QueryCancellationTraits<BindState>),
914         functor_(std::forward<ForwardFunctor>(functor)),
915         bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
916     // We check the validity of nested callbacks (e.g., Bind(callback, ...)) in
917     // release builds to avoid null pointers from ending up in posted tasks,
918     // causing hard-to-diagnose crashes. Ideally we'd do this for all functors
919     // here, but that would have a large binary size impact.
920     if (is_nested_callback) {
921       CHECK(!IsNull(functor_));
922     } else {
923       DCHECK(!IsNull(functor_));
924     }
925   }
926 
927   template <typename ForwardFunctor, typename... ForwardBoundArgs>
928   explicit BindState(std::false_type,
929                      BindStateBase::InvokeFuncStorage invoke_func,
930                      ForwardFunctor&& functor,
931                      ForwardBoundArgs&&... bound_args)
932       : BindStateBase(invoke_func, &Destroy),
933         functor_(std::forward<ForwardFunctor>(functor)),
934         bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
935     // See above for CHECK/DCHECK rationale.
936     if (is_nested_callback) {
937       CHECK(!IsNull(functor_));
938     } else {
939       DCHECK(!IsNull(functor_));
940     }
941   }
942 
943   ~BindState() = default;
944 
945   static void Destroy(const BindStateBase* self) {
946     delete static_cast<const BindState*>(self);
947   }
948 };
949 
950 // Used to implement MakeBindStateType.
951 template <bool is_method, typename Functor, typename... BoundArgs>
952 struct MakeBindStateTypeImpl;
953 
954 template <typename Functor, typename... BoundArgs>
955 struct MakeBindStateTypeImpl<false, Functor, BoundArgs...> {
956   static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
957                 "A parameter is a refcounted type and needs scoped_refptr.");
958   using Type = BindState<std::decay_t<Functor>, std::decay_t<BoundArgs>...>;
959 };
960 
961 template <typename Functor>
962 struct MakeBindStateTypeImpl<true, Functor> {
963   using Type = BindState<std::decay_t<Functor>>;
964 };
965 
966 template <typename Functor, typename Receiver, typename... BoundArgs>
967 struct MakeBindStateTypeImpl<true, Functor, Receiver, BoundArgs...> {
968  private:
969   using DecayedReceiver = std::decay_t<Receiver>;
970 
971   static_assert(!std::is_array<std::remove_reference_t<Receiver>>::value,
972                 "First bound argument to a method cannot be an array.");
973   static_assert(
974       !std::is_pointer<DecayedReceiver>::value ||
975           IsRefCountedType<std::remove_pointer_t<DecayedReceiver>>::value,
976       "Receivers may not be raw pointers. If using a raw pointer here is safe"
977       " and has no lifetime concerns, use base::Unretained() and document why"
978       " it's safe.");
979   static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
980                 "A parameter is a refcounted type and needs scoped_refptr.");
981 
982  public:
983   using Type = BindState<
984       std::decay_t<Functor>,
985       std::conditional_t<std::is_pointer<DecayedReceiver>::value,
986                          scoped_refptr<std::remove_pointer_t<DecayedReceiver>>,
987                          DecayedReceiver>,
988       std::decay_t<BoundArgs>...>;
989 };
990 
991 template <typename Functor, typename... BoundArgs>
992 using MakeBindStateType =
993     typename MakeBindStateTypeImpl<MakeFunctorTraits<Functor>::is_method,
994                                    Functor,
995                                    BoundArgs...>::Type;
996 
997 // Returns a RunType of bound functor.
998 // E.g. MakeUnboundRunType<R(A, B, C), A, B> is evaluated to R(C).
999 template <typename Functor, typename... BoundArgs>
1000 using MakeUnboundRunType =
1001     typename BindTypeHelper<Functor, BoundArgs...>::UnboundRunType;
1002 
1003 // The implementation of TransformToUnwrappedType below.
1004 template <bool is_once, typename T>
1005 struct TransformToUnwrappedTypeImpl;
1006 
1007 template <typename T>
1008 struct TransformToUnwrappedTypeImpl<true, T> {
1009   using StoredType = std::decay_t<T>;
1010   using ForwardType = StoredType&&;
1011   using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
1012 };
1013 
1014 template <typename T>
1015 struct TransformToUnwrappedTypeImpl<false, T> {
1016   using StoredType = std::decay_t<T>;
1017   using ForwardType = const StoredType&;
1018   using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
1019 };
1020 
1021 // Transform |T| into `Unwrapped` type, which is passed to the target function.
1022 // Example:
1023 //   In is_once == true case,
1024 //     `int&&` -> `int&&`,
1025 //     `const int&` -> `int&&`,
1026 //     `OwnedWrapper<int>&` -> `int*&&`.
1027 //   In is_once == false case,
1028 //     `int&&` -> `const int&`,
1029 //     `const int&` -> `const int&`,
1030 //     `OwnedWrapper<int>&` -> `int* const &`.
1031 template <bool is_once, typename T>
1032 using TransformToUnwrappedType =
1033     typename TransformToUnwrappedTypeImpl<is_once, T>::Unwrapped;
1034 
1035 // Transforms |Args| into `Unwrapped` types, and packs them into a TypeList.
1036 // If |is_method| is true, tries to dereference the first argument to support
1037 // smart pointers.
1038 template <bool is_once, bool is_method, typename... Args>
1039 struct MakeUnwrappedTypeListImpl {
1040   using Type = TypeList<TransformToUnwrappedType<is_once, Args>...>;
1041 };
1042 
1043 // Performs special handling for this pointers.
1044 // Example:
1045 //   int* -> int*,
1046 //   std::unique_ptr<int> -> int*.
1047 template <bool is_once, typename Receiver, typename... Args>
1048 struct MakeUnwrappedTypeListImpl<is_once, true, Receiver, Args...> {
1049   using UnwrappedReceiver = TransformToUnwrappedType<is_once, Receiver>;
1050   using Type = TypeList<decltype(&*std::declval<UnwrappedReceiver>()),
1051                         TransformToUnwrappedType<is_once, Args>...>;
1052 };
1053 
1054 template <bool is_once, bool is_method, typename... Args>
1055 using MakeUnwrappedTypeList =
1056     typename MakeUnwrappedTypeListImpl<is_once, is_method, Args...>::Type;
1057 
1058 // IsOnceCallback<T> is a std::true_type if |T| is a OnceCallback.
1059 template <typename T>
1060 struct IsOnceCallback : std::false_type {};
1061 
1062 template <typename Signature>
1063 struct IsOnceCallback<OnceCallback<Signature>> : std::true_type {};
1064 
1065 // Helpers to make error messages slightly more readable.
1066 template <int i>
1067 struct BindArgument {
1068   template <typename ForwardingType>
1069   struct ForwardedAs {
1070     template <typename FunctorParamType>
1071     struct ToParamWithType {
1072       static constexpr bool kCanBeForwardedToBoundFunctor =
1073           std::is_constructible<FunctorParamType, ForwardingType>::value;
1074 
1075       // If the bound type can't be forwarded then test if `FunctorParamType` is
1076       // a non-const lvalue reference and a reference to the unwrapped type
1077       // *could* have been successfully forwarded.
1078       static constexpr bool kNonConstRefParamMustBeWrapped =
1079           kCanBeForwardedToBoundFunctor ||
1080           !(std::is_lvalue_reference<FunctorParamType>::value &&
1081             !std::is_const<std::remove_reference_t<FunctorParamType>>::value &&
1082             std::is_convertible<std::decay_t<ForwardingType>&,
1083                                 FunctorParamType>::value);
1084 
1085       // Note that this intentionally drops the const qualifier from
1086       // `ForwardingType`, to test if it *could* have been successfully
1087       // forwarded if `Passed()` had been used.
1088       static constexpr bool kMoveOnlyTypeMustUseBasePassed =
1089           kCanBeForwardedToBoundFunctor ||
1090           !std::is_constructible<FunctorParamType,
1091                                  std::decay_t<ForwardingType>&&>::value;
1092     };
1093   };
1094 
1095   template <typename BoundAsType>
1096   struct BoundAs {
1097     template <typename StorageType>
1098     struct StoredAs {
1099       static constexpr bool kBindArgumentCanBeCaptured =
1100           std::is_constructible<StorageType, BoundAsType>::value;
1101       // Note that this intentionally drops the const qualifier from
1102       // `BoundAsType`, to test if it *could* have been successfully bound if
1103       // `std::move()` had been used.
1104       static constexpr bool kMoveOnlyTypeMustUseStdMove =
1105           kBindArgumentCanBeCaptured ||
1106           !std::is_constructible<StorageType,
1107                                  std::decay_t<BoundAsType>&&>::value;
1108     };
1109   };
1110 };
1111 
1112 // Helper to assert that parameter |i| of type |Arg| can be bound, which means:
1113 // - |Arg| can be retained internally as |Storage|.
1114 // - |Arg| can be forwarded as |Unwrapped| to |Param|.
1115 template <int i,
1116           typename Arg,
1117           typename Storage,
1118           typename Unwrapped,
1119           typename Param>
1120 struct AssertConstructible {
1121  private:
1122   // With `BindRepeating`, there are two decision points for how to handle a
1123   // move-only type:
1124   //
1125   // 1. Whether the move-only argument should be moved into the internal
1126   //    `BindState`. Either `std::move()` or `Passed` is sufficient to trigger
1127   //    move-only semantics.
1128   // 2. Whether or not the bound, move-only argument should be moved to the
1129   //    bound functor when invoked. When the argument is bound with `Passed`,
1130   //    invoking the callback will destructively move the bound, move-only
1131   //    argument to the bound functor. In contrast, if the argument is bound
1132   //    with `std::move()`, `RepeatingCallback` will attempt to call the bound
1133   //    functor with a constant reference to the bound, move-only argument. This
1134   //    will fail if the bound functor accepts that argument by value, since the
1135   //    argument cannot be copied. It is this latter case that this
1136   //    static_assert aims to catch.
1137   //
1138   // In contrast, `BindOnce()` only has one decision point. Once a move-only
1139   // type is captured by value into the internal `BindState`, the bound,
1140   // move-only argument will always be moved to the functor when invoked.
1141   // Failure to use std::move will simply fail the `kMoveOnlyTypeMustUseStdMove`
1142   // assert below instead.
1143   //
1144   // Note: `Passed()` is a legacy of supporting move-only types when repeating
1145   // callbacks were the only callback type. A `RepeatingCallback` with a
1146   // `Passed()` argument is really a `OnceCallback` and should eventually be
1147   // migrated.
1148   static_assert(
1149       BindArgument<i>::template ForwardedAs<Unwrapped>::
1150           template ToParamWithType<Param>::kMoveOnlyTypeMustUseBasePassed,
1151       "base::BindRepeating() argument is a move-only type. Use base::Passed() "
1152       "instead of std::move() to transfer ownership from the callback to the "
1153       "bound functor.");
1154   static_assert(
1155       BindArgument<i>::template ForwardedAs<Unwrapped>::
1156           template ToParamWithType<Param>::kNonConstRefParamMustBeWrapped,
1157       "Bound argument for non-const reference parameter must be wrapped in "
1158       "std::ref() or base::OwnedRef().");
1159   static_assert(
1160       BindArgument<i>::template ForwardedAs<Unwrapped>::
1161           template ToParamWithType<Param>::kCanBeForwardedToBoundFunctor,
1162       "Type mismatch between bound argument and bound functor's parameter.");
1163 
1164   static_assert(BindArgument<i>::template BoundAs<Arg>::template StoredAs<
1165                     Storage>::kMoveOnlyTypeMustUseStdMove,
1166                 "Attempting to bind a move-only type. Use std::move() to "
1167                 "transfer ownership to the created callback.");
1168   // In practice, this static_assert should be quite rare as the storage type
1169   // is deduced from the arguments passed to `BindOnce()`/`BindRepeating()`.
1170   static_assert(
1171       BindArgument<i>::template BoundAs<Arg>::template StoredAs<
1172           Storage>::kBindArgumentCanBeCaptured,
1173       "Cannot capture argument: is the argument copyable or movable?");
1174 };
1175 
1176 // Takes three same-length TypeLists, and applies AssertConstructible for each
1177 // triples.
1178 template <typename Index,
1179           typename Args,
1180           typename UnwrappedTypeList,
1181           typename ParamsList>
1182 struct AssertBindArgsValidity;
1183 
1184 template <size_t... Ns,
1185           typename... Args,
1186           typename... Unwrapped,
1187           typename... Params>
1188 struct AssertBindArgsValidity<std::index_sequence<Ns...>,
1189                               TypeList<Args...>,
1190                               TypeList<Unwrapped...>,
1191                               TypeList<Params...>>
1192     : AssertConstructible<Ns, Args, std::decay_t<Args>, Unwrapped, Params>... {
1193   static constexpr bool ok = true;
1194 };
1195 
1196 template <typename T>
1197 struct AssertBindArgIsNotBasePassed : public std::true_type {};
1198 
1199 template <typename T>
1200 struct AssertBindArgIsNotBasePassed<PassedWrapper<T>> : public std::false_type {
1201 };
1202 
1203 // Used below in BindImpl to determine whether to use Invoker::Run or
1204 // Invoker::RunOnce.
1205 // Note: Simply using `kIsOnce ? &Invoker::RunOnce : &Invoker::Run` does not
1206 // work, since the compiler needs to check whether both expressions are
1207 // well-formed. Using `Invoker::Run` with a OnceCallback triggers a
1208 // static_assert, which is why the ternary expression does not compile.
1209 // TODO(crbug.com/752720): Remove this indirection once we have `if constexpr`.
1210 template <typename Invoker>
1211 constexpr auto GetInvokeFunc(std::true_type) {
1212   return Invoker::RunOnce;
1213 }
1214 
1215 template <typename Invoker>
1216 constexpr auto GetInvokeFunc(std::false_type) {
1217   return Invoker::Run;
1218 }
1219 
1220 template <template <typename> class CallbackT,
1221           typename Functor,
1222           typename... Args>
1223 decltype(auto) BindImpl(Functor&& functor, Args&&... args) {
1224   // This block checks if each |args| matches to the corresponding params of the
1225   // target function. This check does not affect the behavior of Bind, but its
1226   // error message should be more readable.
1227   static constexpr bool kIsOnce = IsOnceCallback<CallbackT<void()>>::value;
1228   using Helper = BindTypeHelper<Functor, Args...>;
1229   using FunctorTraits = typename Helper::FunctorTraits;
1230   using BoundArgsList = typename Helper::BoundArgsList;
1231   using UnwrappedArgsList =
1232       MakeUnwrappedTypeList<kIsOnce, FunctorTraits::is_method, Args&&...>;
1233   using BoundParamsList = typename Helper::BoundParamsList;
1234   static_assert(
1235       AssertBindArgsValidity<std::make_index_sequence<Helper::num_bounds>,
1236                              BoundArgsList, UnwrappedArgsList,
1237                              BoundParamsList>::ok,
1238       "The bound args need to be convertible to the target params.");
1239 
1240   using BindState = MakeBindStateType<Functor, Args...>;
1241   using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
1242   using Invoker = Invoker<BindState, UnboundRunType>;
1243   using CallbackType = CallbackT<UnboundRunType>;
1244 
1245   // Store the invoke func into PolymorphicInvoke before casting it to
1246   // InvokeFuncStorage, so that we can ensure its type matches to
1247   // PolymorphicInvoke, to which CallbackType will cast back.
1248   using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
1249   PolymorphicInvoke invoke_func =
1250       GetInvokeFunc<Invoker>(bool_constant<kIsOnce>());
1251 
1252   using InvokeFuncStorage = BindStateBase::InvokeFuncStorage;
1253   return CallbackType(BindState::Create(
1254       reinterpret_cast<InvokeFuncStorage>(invoke_func),
1255       std::forward<Functor>(functor), std::forward<Args>(args)...));
1256 }
1257 
1258 }  // namespace internal
1259 
1260 // An injection point to control |this| pointer behavior on a method invocation.
1261 // If IsWeakReceiver<> is true_type for |T| and |T| is used for a receiver of a
1262 // method, base::Bind cancels the method invocation if the receiver is tested as
1263 // false.
1264 // E.g. Foo::bar() is not called:
1265 //   struct Foo : base::SupportsWeakPtr<Foo> {
1266 //     void bar() {}
1267 //   };
1268 //
1269 //   WeakPtr<Foo> oo = nullptr;
1270 //   base::BindOnce(&Foo::bar, oo).Run();
1271 template <typename T>
1272 struct IsWeakReceiver : std::false_type {};
1273 
1274 template <typename T>
1275 struct IsWeakReceiver<std::reference_wrapper<T>> : IsWeakReceiver<T> {};
1276 
1277 template <typename T>
1278 struct IsWeakReceiver<WeakPtr<T>> : std::true_type {};
1279 
1280 // An injection point to control how objects are checked for maybe validity,
1281 // which is an optimistic thread-safe check for full validity.
1282 template <typename>
1283 struct MaybeValidTraits {
1284   template <typename T>
1285   static bool MaybeValid(const T& o) {
1286     return o.MaybeValid();
1287   }
1288 };
1289 
1290 // An injection point to control how bound objects passed to the target
1291 // function. BindUnwrapTraits<>::Unwrap() is called for each bound objects right
1292 // before the target function is invoked.
1293 template <typename>
1294 struct BindUnwrapTraits {
1295   template <typename T>
1296   static T&& Unwrap(T&& o) {
1297     return std::forward<T>(o);
1298   }
1299 };
1300 
1301 template <typename T>
1302 struct BindUnwrapTraits<internal::UnretainedWrapper<T>> {
1303   static T* Unwrap(const internal::UnretainedWrapper<T>& o) { return o.get(); }
1304 };
1305 
1306 template <typename T>
1307 struct BindUnwrapTraits<internal::RetainedRefWrapper<T>> {
1308   static T* Unwrap(const internal::RetainedRefWrapper<T>& o) { return o.get(); }
1309 };
1310 
1311 template <typename T, typename Deleter>
1312 struct BindUnwrapTraits<internal::OwnedWrapper<T, Deleter>> {
1313   static T* Unwrap(const internal::OwnedWrapper<T, Deleter>& o) {
1314     return o.get();
1315   }
1316 };
1317 
1318 template <typename T>
1319 struct BindUnwrapTraits<internal::OwnedRefWrapper<T>> {
1320   static T& Unwrap(const internal::OwnedRefWrapper<T>& o) { return o.get(); }
1321 };
1322 
1323 template <typename T>
1324 struct BindUnwrapTraits<internal::PassedWrapper<T>> {
1325   static T Unwrap(const internal::PassedWrapper<T>& o) { return o.Take(); }
1326 };
1327 
1328 #if defined(OS_WIN)
1329 template <typename T>
1330 struct BindUnwrapTraits<Microsoft::WRL::ComPtr<T>> {
1331   static T* Unwrap(const Microsoft::WRL::ComPtr<T>& ptr) { return ptr.Get(); }
1332 };
1333 #endif
1334 
1335 // CallbackCancellationTraits allows customization of Callback's cancellation
1336 // semantics. By default, callbacks are not cancellable. A specialization should
1337 // set is_cancellable = true and implement an IsCancelled() that returns if the
1338 // callback should be cancelled.
1339 template <typename Functor, typename BoundArgsTuple, typename SFINAE>
1340 struct CallbackCancellationTraits {
1341   static constexpr bool is_cancellable = false;
1342 };
1343 
1344 // Specialization for method bound to weak pointer receiver.
1345 template <typename Functor, typename... BoundArgs>
1346 struct CallbackCancellationTraits<
1347     Functor,
1348     std::tuple<BoundArgs...>,
1349     std::enable_if_t<
1350         internal::IsWeakMethod<internal::FunctorTraits<Functor>::is_method,
1351                                BoundArgs...>::value>> {
1352   static constexpr bool is_cancellable = true;
1353 
1354   template <typename Receiver, typename... Args>
1355   static bool IsCancelled(const Functor&,
1356                           const Receiver& receiver,
1357                           const Args&...) {
1358     return !receiver;
1359   }
1360 
1361   template <typename Receiver, typename... Args>
1362   static bool MaybeValid(const Functor&,
1363                          const Receiver& receiver,
1364                          const Args&...) {
1365     return MaybeValidTraits<Receiver>::MaybeValid(receiver);
1366   }
1367 };
1368 
1369 // Specialization for a nested bind.
1370 template <typename Signature, typename... BoundArgs>
1371 struct CallbackCancellationTraits<OnceCallback<Signature>,
1372                                   std::tuple<BoundArgs...>> {
1373   static constexpr bool is_cancellable = true;
1374 
1375   template <typename Functor>
1376   static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
1377     return functor.IsCancelled();
1378   }
1379 
1380   template <typename Functor>
1381   static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
1382     return MaybeValidTraits<Functor>::MaybeValid(functor);
1383   }
1384 };
1385 
1386 template <typename Signature, typename... BoundArgs>
1387 struct CallbackCancellationTraits<RepeatingCallback<Signature>,
1388                                   std::tuple<BoundArgs...>> {
1389   static constexpr bool is_cancellable = true;
1390 
1391   template <typename Functor>
1392   static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
1393     return functor.IsCancelled();
1394   }
1395 
1396   template <typename Functor>
1397   static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
1398     return MaybeValidTraits<Functor>::MaybeValid(functor);
1399   }
1400 };
1401 
1402 }  // namespace base
1403 
1404 #endif  // CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_H_
1405