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