// Copyright (c) 2011 Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the name Chromium Embedded // Framework nor the names of its contributors may be used to endorse // or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Do not include this header file directly. Use base/cef_bind.h instead. // See base/cef_callback.h for user documentation. // // // CONCEPTS: // Functor -- A movable type representing something that should be called. // All function pointers and Callback<> are functors even if the // invocation syntax differs. // RunType -- A function type (as opposed to function _pointer_ type) for // a Callback<>::Run(). Usually just a convenience typedef. // (Bound)Args -- A set of types that stores the arguments. // // Types: // ForceVoidReturn<> -- Helper class for translating function signatures to // equivalent forms with a "void" return type. // FunctorTraits<> -- Type traits used to determine the correct RunType and // invocation manner for a Functor. This is where function // signature adapters are applied. // InvokeHelper<> -- Take a Functor + arguments and actully invokes it. // Handle the differing syntaxes needed for WeakPtr<> // support. This is separate from Invoker to avoid creating // multiple version of Invoker<>. // Invoker<> -- Unwraps the curried parameters and executes the Functor. // BindState<> -- Stores the curried parameters, and is the main entry point // into the Bind() system. #ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_H_ #define CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_H_ #include #include #include #include #include #include #include "include/base/cef_build.h" #include "include/base/cef_compiler_specific.h" #include "include/base/cef_logging.h" #include "include/base/cef_template_util.h" #include "include/base/cef_weak_ptr.h" #include "include/base/internal/cef_callback_internal.h" #include "include/base/internal/cef_raw_scoped_refptr_mismatch_checker.h" #if defined(OS_APPLE) && !HAS_FEATURE(objc_arc) #include "include/base/internal/cef_scoped_block_mac.h" #endif #if defined(OS_WIN) namespace Microsoft { namespace WRL { template class ComPtr; } // namespace WRL } // namespace Microsoft #endif namespace base { template struct IsWeakReceiver; template struct BindUnwrapTraits; template struct CallbackCancellationTraits; namespace internal { template struct FunctorTraits; template class UnretainedWrapper { public: explicit UnretainedWrapper(T* o) : ptr_(o) {} T* get() const { return ptr_; } private: T* ptr_; }; template class RetainedRefWrapper { public: explicit RetainedRefWrapper(T* o) : ptr_(o) {} explicit RetainedRefWrapper(scoped_refptr o) : ptr_(std::move(o)) {} T* get() const { return ptr_.get(); } private: scoped_refptr ptr_; }; template struct IgnoreResultHelper { explicit IgnoreResultHelper(T functor) : functor_(std::move(functor)) {} explicit operator bool() const { return !!functor_; } T functor_; }; template > class OwnedWrapper { public: explicit OwnedWrapper(T* o) : ptr_(o) {} explicit OwnedWrapper(std::unique_ptr&& ptr) : ptr_(std::move(ptr)) {} T* get() const { return ptr_.get(); } private: std::unique_ptr ptr_; }; template class OwnedRefWrapper { public: explicit OwnedRefWrapper(const T& t) : t_(t) {} explicit OwnedRefWrapper(T&& t) : t_(std::move(t)) {} T& get() const { return t_; } private: mutable T t_; }; // PassedWrapper is a copyable adapter for a scoper that ignores const. // // It is needed to get around the fact that Bind() takes a const reference to // all its arguments. Because Bind() takes a const reference to avoid // unnecessary copies, it is incompatible with movable-but-not-copyable // types; doing a destructive "move" of the type into Bind() would violate // the const correctness. // // This conundrum cannot be solved without either C++11 rvalue references or // a O(2^n) blowup of Bind() templates to handle each combination of regular // types and movable-but-not-copyable types. Thus we introduce a wrapper type // that is copyable to transmit the correct type information down into // BindState<>. Ignoring const in this type makes sense because it is only // created when we are explicitly trying to do a destructive move. // // Two notes: // 1) PassedWrapper supports any type that has a move constructor, however // the type will need to be specifically allowed in order for it to be // bound to a Callback. We guard this explicitly at the call of Passed() // to make for clear errors. Things not given to Passed() will be forwarded // and stored by value which will not work for general move-only types. // 2) is_valid_ is distinct from NULL because it is valid to bind a "NULL" // scoper to a Callback and allow the Callback to execute once. template class PassedWrapper { public: explicit PassedWrapper(T&& scoper) : is_valid_(true), scoper_(std::move(scoper)) {} PassedWrapper(PassedWrapper&& other) : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {} T Take() const { CHECK(is_valid_); is_valid_ = false; return std::move(scoper_); } private: mutable bool is_valid_; mutable T scoper_; }; template using Unwrapper = BindUnwrapTraits>; template decltype(auto) Unwrap(T&& o) { return Unwrapper::Unwrap(std::forward(o)); } // IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a // method. It is used internally by Bind() to select the correct // InvokeHelper that will no-op itself in the event the WeakPtr<> for // the target object is invalidated. // // The first argument should be the type of the object that will be received by // the method. template struct IsWeakMethod : std::false_type {}; template struct IsWeakMethod : IsWeakReceiver {}; // Packs a list of types to hold them in a single type. template struct TypeList {}; // Used for DropTypeListItem implementation. template struct DropTypeListItemImpl; // Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure. template struct DropTypeListItemImpl> : DropTypeListItemImpl> {}; template struct DropTypeListItemImpl<0, TypeList> { using Type = TypeList; }; template <> struct DropTypeListItemImpl<0, TypeList<>> { using Type = TypeList<>; }; // A type-level function that drops |n| list item from given TypeList. template using DropTypeListItem = typename DropTypeListItemImpl::Type; // Used for TakeTypeListItem implementation. template struct TakeTypeListItemImpl; // Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure. template struct TakeTypeListItemImpl, Accum...> : TakeTypeListItemImpl, Accum..., T> {}; template struct TakeTypeListItemImpl<0, TypeList, Accum...> { using Type = TypeList; }; template struct TakeTypeListItemImpl<0, TypeList<>, Accum...> { using Type = TypeList; }; // A type-level function that takes first |n| list item from given TypeList. // E.g. TakeTypeListItem<3, TypeList> is evaluated to // TypeList. template using TakeTypeListItem = typename TakeTypeListItemImpl::Type; // Used for ConcatTypeLists implementation. template struct ConcatTypeListsImpl; template struct ConcatTypeListsImpl, TypeList> { using Type = TypeList; }; // A type-level function that concats two TypeLists. template using ConcatTypeLists = typename ConcatTypeListsImpl::Type; // Used for MakeFunctionType implementation. template struct MakeFunctionTypeImpl; template struct MakeFunctionTypeImpl> { // MSVC 2013 doesn't support Type Alias of function types. // Revisit this after we update it to newer version. typedef R Type(Args...); }; // A type-level function that constructs a function type that has |R| as its // return type and has TypeLists items as its arguments. template using MakeFunctionType = typename MakeFunctionTypeImpl::Type; // Used for ExtractArgs and ExtractReturnType. template struct ExtractArgsImpl; template struct ExtractArgsImpl { using ReturnType = R; using ArgsList = TypeList; }; // A type-level function that extracts function arguments into a TypeList. // E.g. ExtractArgs is evaluated to TypeList. template using ExtractArgs = typename ExtractArgsImpl::ArgsList; // A type-level function that extracts the return type of a function. // E.g. ExtractReturnType is evaluated to R. template using ExtractReturnType = typename ExtractArgsImpl::ReturnType; template struct ExtractCallableRunTypeImpl; template struct ExtractCallableRunTypeImpl { using Type = R(Args...); }; template struct ExtractCallableRunTypeImpl { using Type = R(Args...); }; // Evaluated to RunType of the given callable type. // Example: // auto f = [](int, char*) { return 0.1; }; // ExtractCallableRunType // is evaluated to // double(int, char*); template using ExtractCallableRunType = typename ExtractCallableRunTypeImpl::Type; // IsCallableObject is std::true_type if |Functor| has operator(). // Otherwise, it's std::false_type. // Example: // IsCallableObject::value is false. // // struct Foo {}; // IsCallableObject::value is false. // // int i = 0; // auto f = [i]() {}; // IsCallableObject::value is false. template struct IsCallableObject : std::false_type {}; template struct IsCallableObject> : std::true_type {}; // HasRefCountedTypeAsRawPtr inherits from true_type when any of the |Args| is a // raw pointer to a RefCounted type. template struct HasRefCountedTypeAsRawPtr : disjunction...> {}; // ForceVoidReturn<> // // Set of templates that support forcing the function return type to void. template struct ForceVoidReturn; template struct ForceVoidReturn { using RunType = void(Args...); }; // FunctorTraits<> // // See description at top of file. template struct FunctorTraits; // For empty callable types. // This specialization is intended to allow binding captureless lambdas, based // on the fact that captureless lambdas are empty while capturing lambdas are // not. This also allows any functors as far as it's an empty class. // Example: // // // Captureless lambdas are allowed. // []() {return 42;}; // // // Capturing lambdas are *not* allowed. // int x; // [x]() {return x;}; // // // Any empty class with operator() is allowed. // struct Foo { // void operator()() const {} // // No non-static member variable and no virtual functions. // }; template struct FunctorTraits::value && std::is_empty::value>> { using RunType = ExtractCallableRunType; static constexpr bool is_method = false; static constexpr bool is_nullable = false; static constexpr bool is_callback = false; template static ExtractReturnType Invoke(RunFunctor&& functor, RunArgs&&... args) { return std::forward(functor)(std::forward(args)...); } }; // For functions. template struct FunctorTraits { using RunType = R(Args...); static constexpr bool is_method = false; static constexpr bool is_nullable = true; static constexpr bool is_callback = false; template static R Invoke(Function&& function, RunArgs&&... args) { return std::forward(function)(std::forward(args)...); } }; #if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS) // For functions. template struct FunctorTraits { using RunType = R(Args...); static constexpr bool is_method = false; static constexpr bool is_nullable = true; static constexpr bool is_callback = false; template static R Invoke(R(__stdcall* function)(Args...), RunArgs&&... args) { return function(std::forward(args)...); } }; // For functions. template struct FunctorTraits { using RunType = R(Args...); static constexpr bool is_method = false; static constexpr bool is_nullable = true; static constexpr bool is_callback = false; template static R Invoke(R(__fastcall* function)(Args...), RunArgs&&... args) { return function(std::forward(args)...); } }; #endif // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS) #if defined(OS_APPLE) // Support for Objective-C blocks. There are two implementation depending // on whether Automated Reference Counting (ARC) is enabled. When ARC is // enabled, then the block itself can be bound as the compiler will ensure // its lifetime will be correctly managed. Otherwise, require the block to // be wrapped in a base::mac::ScopedBlock (via base::RetainBlock) that will // correctly manage the block lifetime. // // The two implementation ensure that the One Definition Rule (ODR) is not // broken (it is not possible to write a template base::RetainBlock that would // work correctly both with ARC enabled and disabled). #if HAS_FEATURE(objc_arc) template struct FunctorTraits { using RunType = R(Args...); static constexpr bool is_method = false; static constexpr bool is_nullable = true; static constexpr bool is_callback = false; template static R Invoke(BlockType&& block, RunArgs&&... args) { // According to LLVM documentation (6.3), "local variables of automatic // storage duration do not have precise lifetime." Use objc_precise_lifetime // to ensure that the Objective-C block is not deallocated until it has // finished executing even if the Callback<> is destroyed during the block // execution. // https://clang.llvm.org/docs/AutomaticReferenceCounting.html#precise-lifetime-semantics __attribute__((objc_precise_lifetime)) R (^scoped_block)(Args...) = block; return scoped_block(std::forward(args)...); } }; #else // HAS_FEATURE(objc_arc) template struct FunctorTraits> { using RunType = R(Args...); static constexpr bool is_method = false; static constexpr bool is_nullable = true; static constexpr bool is_callback = false; template static R Invoke(BlockType&& block, RunArgs&&... args) { // Copy the block to ensure that the Objective-C block is not deallocated // until it has finished executing even if the Callback<> is destroyed // during the block execution. base::mac::ScopedBlock scoped_block(block); return scoped_block.get()(std::forward(args)...); } }; #endif // HAS_FEATURE(objc_arc) #endif // defined(OS_APPLE) // For methods. template struct FunctorTraits { using RunType = R(Receiver*, Args...); static constexpr bool is_method = true; static constexpr bool is_nullable = true; static constexpr bool is_callback = false; template static R Invoke(Method method, ReceiverPtr&& receiver_ptr, RunArgs&&... args) { return ((*receiver_ptr).*method)(std::forward(args)...); } }; // For const methods. template struct FunctorTraits { using RunType = R(const Receiver*, Args...); static constexpr bool is_method = true; static constexpr bool is_nullable = true; static constexpr bool is_callback = false; template static R Invoke(Method method, ReceiverPtr&& receiver_ptr, RunArgs&&... args) { return ((*receiver_ptr).*method)(std::forward(args)...); } }; #if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS) // For __stdcall methods. template struct FunctorTraits { using RunType = R(Receiver*, Args...); static constexpr bool is_method = true; static constexpr bool is_nullable = true; static constexpr bool is_callback = false; template static R Invoke(Method method, ReceiverPtr&& receiver_ptr, RunArgs&&... args) { return ((*receiver_ptr).*method)(std::forward(args)...); } }; // For __stdcall const methods. template struct FunctorTraits { using RunType = R(const Receiver*, Args...); static constexpr bool is_method = true; static constexpr bool is_nullable = true; static constexpr bool is_callback = false; template static R Invoke(Method method, ReceiverPtr&& receiver_ptr, RunArgs&&... args) { return ((*receiver_ptr).*method)(std::forward(args)...); } }; #endif // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS) #ifdef __cpp_noexcept_function_type // noexcept makes a distinct function type in C++17. // I.e. `void(*)()` and `void(*)() noexcept` are same in pre-C++17, and // different in C++17. template struct FunctorTraits : FunctorTraits { }; template struct FunctorTraits : FunctorTraits {}; template struct FunctorTraits : FunctorTraits {}; #endif // For IgnoreResults. template struct FunctorTraits> : FunctorTraits { using RunType = typename ForceVoidReturn::RunType>::RunType; template static void Invoke(IgnoreResultType&& ignore_result_helper, RunArgs&&... args) { FunctorTraits::Invoke( std::forward(ignore_result_helper).functor_, std::forward(args)...); } }; // For OnceCallbacks. template struct FunctorTraits> { using RunType = R(Args...); static constexpr bool is_method = false; static constexpr bool is_nullable = true; static constexpr bool is_callback = true; template static R Invoke(CallbackType&& callback, RunArgs&&... args) { DCHECK(!callback.is_null()); return std::forward(callback).Run( std::forward(args)...); } }; // For RepeatingCallbacks. template struct FunctorTraits> { using RunType = R(Args...); static constexpr bool is_method = false; static constexpr bool is_nullable = true; static constexpr bool is_callback = true; template static R Invoke(CallbackType&& callback, RunArgs&&... args) { DCHECK(!callback.is_null()); return std::forward(callback).Run( std::forward(args)...); } }; template using MakeFunctorTraits = FunctorTraits>; // InvokeHelper<> // // There are 2 logical InvokeHelper<> specializations: normal, WeakCalls. // // The normal type just calls the underlying runnable. // // WeakCalls need special syntax that is applied to the first argument to check // if they should no-op themselves. template struct InvokeHelper; template struct InvokeHelper { template static inline ReturnType MakeItSo(Functor&& functor, RunArgs&&... args) { using Traits = MakeFunctorTraits; return Traits::Invoke(std::forward(functor), std::forward(args)...); } }; template struct InvokeHelper { // WeakCalls are only supported for functions with a void return type. // Otherwise, the function result would be undefined if the WeakPtr<> // is invalidated. static_assert(std::is_void::value, "weak_ptrs can only bind to methods without return values"); template static inline void MakeItSo(Functor&& functor, BoundWeakPtr&& weak_ptr, RunArgs&&... args) { if (!weak_ptr) return; using Traits = MakeFunctorTraits; Traits::Invoke(std::forward(functor), std::forward(weak_ptr), std::forward(args)...); } }; // Invoker<> // // See description at the top of the file. template struct Invoker; template struct Invoker { static R RunOnce(BindStateBase* base, PassingType... unbound_args) { // Local references to make debugger stepping easier. If in a debugger, // you really want to warp ahead and step through the // InvokeHelper<>::MakeItSo() call below. StorageType* storage = static_cast(base); static constexpr size_t num_bound_args = std::tuple_sizebound_args_)>::value; return RunImpl(std::move(storage->functor_), std::move(storage->bound_args_), std::make_index_sequence(), std::forward(unbound_args)...); } static R Run(BindStateBase* base, PassingType... unbound_args) { // Local references to make debugger stepping easier. If in a debugger, // you really want to warp ahead and step through the // InvokeHelper<>::MakeItSo() call below. const StorageType* storage = static_cast(base); static constexpr size_t num_bound_args = std::tuple_sizebound_args_)>::value; return RunImpl(storage->functor_, storage->bound_args_, std::make_index_sequence(), std::forward(unbound_args)...); } private: template static inline R RunImpl(Functor&& functor, BoundArgsTuple&& bound, std::index_sequence, UnboundArgs&&... unbound_args) { static constexpr bool is_method = MakeFunctorTraits::is_method; using DecayedArgsTuple = std::decay_t; static constexpr bool is_weak_call = IsWeakMethod...>(); return InvokeHelper::MakeItSo( std::forward(functor), Unwrap(std::get(std::forward(bound)))..., std::forward(unbound_args)...); } }; // Extracts necessary type info from Functor and BoundArgs. // Used to implement MakeUnboundRunType, BindOnce and BindRepeating. template struct BindTypeHelper { static constexpr size_t num_bounds = sizeof...(BoundArgs); using FunctorTraits = MakeFunctorTraits; // Example: // When Functor is `double (Foo::*)(int, const std::string&)`, and BoundArgs // is a template pack of `Foo*` and `int16_t`: // - RunType is `double(Foo*, int, const std::string&)`, // - ReturnType is `double`, // - RunParamsList is `TypeList`, // - BoundParamsList is `TypeList`, // - UnboundParamsList is `TypeList`, // - BoundArgsList is `TypeList`, // - UnboundRunType is `double(const std::string&)`. using RunType = typename FunctorTraits::RunType; using ReturnType = ExtractReturnType; using RunParamsList = ExtractArgs; using BoundParamsList = TakeTypeListItem; using UnboundParamsList = DropTypeListItem; using BoundArgsList = TypeList; using UnboundRunType = MakeFunctionType; }; template std::enable_if_t::is_nullable, bool> IsNull( const Functor& functor) { return !functor; } template std::enable_if_t::is_nullable, bool> IsNull( const Functor&) { return false; } // Used by QueryCancellationTraits below. template bool QueryCancellationTraitsImpl(BindStateBase::CancellationQueryMode mode, const Functor& functor, const BoundArgsTuple& bound_args, std::index_sequence) { switch (mode) { case BindStateBase::IS_CANCELLED: return CallbackCancellationTraits::IsCancelled( functor, std::get(bound_args)...); case BindStateBase::MAYBE_VALID: return CallbackCancellationTraits::MaybeValid( functor, std::get(bound_args)...); } NOTREACHED(); return false; } // Relays |base| to corresponding CallbackCancellationTraits<>::Run(). Returns // true if the callback |base| represents is canceled. template bool QueryCancellationTraits(const BindStateBase* base, BindStateBase::CancellationQueryMode mode) { const BindStateType* storage = static_cast(base); static constexpr size_t num_bound_args = std::tuple_sizebound_args_)>::value; return QueryCancellationTraitsImpl( mode, storage->functor_, storage->bound_args_, std::make_index_sequence()); } // The base case of BanUnconstructedRefCountedReceiver that checks nothing. template std::enable_if_t< !(MakeFunctorTraits::is_method && std::is_pointer>::value && IsRefCountedType>>::value)> BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {} template void BanUnconstructedRefCountedReceiver() {} // Asserts that Callback is not the first owner of a ref-counted receiver. template std::enable_if_t< MakeFunctorTraits::is_method && std::is_pointer>::value && IsRefCountedType>>::value> BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) { DCHECK(receiver); // It's error prone to make the implicit first reference to ref-counted types. // In the example below, base::BindOnce() makes the implicit first reference // to the ref-counted Foo. If PostTask() failed or the posted task ran fast // enough, the newly created instance can be destroyed before |oo| makes // another reference. // Foo::Foo() { // base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, this)); // } // // scoped_refptr oo = new Foo(); // // Instead of doing like above, please consider adding a static constructor, // and keep the first reference alive explicitly. // // static // scoped_refptr Foo::Create() { // auto foo = base::WrapRefCounted(new Foo()); // base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, foo)); // return foo; // } // // Foo::Foo() {} // // scoped_refptr oo = Foo::Create(); DCHECK(receiver->HasAtLeastOneRef()) << "base::Bind{Once,Repeating}() refuses to create the first reference " "to ref-counted objects. That typically happens around PostTask() in " "their constructor, and such objects can be destroyed before `new` " "returns if the task resolves fast enough."; } // BindState<> // // This stores all the state passed into Bind(). template struct BindState final : BindStateBase { using IsCancellable = bool_constant< CallbackCancellationTraits>::is_cancellable>; template static BindState* Create(BindStateBase::InvokeFuncStorage invoke_func, ForwardFunctor&& functor, ForwardBoundArgs&&... bound_args) { // Ban ref counted receivers that were not yet fully constructed to avoid // a common pattern of racy situation. BanUnconstructedRefCountedReceiver(bound_args...); // IsCancellable is std::false_type if // CallbackCancellationTraits<>::IsCancelled returns always false. // Otherwise, it's std::true_type. return new BindState(IsCancellable{}, invoke_func, std::forward(functor), std::forward(bound_args)...); } Functor functor_; std::tuple bound_args_; private: static constexpr bool is_nested_callback = MakeFunctorTraits::is_callback; template explicit BindState(std::true_type, BindStateBase::InvokeFuncStorage invoke_func, ForwardFunctor&& functor, ForwardBoundArgs&&... bound_args) : BindStateBase(invoke_func, &Destroy, &QueryCancellationTraits), functor_(std::forward(functor)), bound_args_(std::forward(bound_args)...) { // We check the validity of nested callbacks (e.g., Bind(callback, ...)) in // release builds to avoid null pointers from ending up in posted tasks, // causing hard-to-diagnose crashes. Ideally we'd do this for all functors // here, but that would have a large binary size impact. if (is_nested_callback) { CHECK(!IsNull(functor_)); } else { DCHECK(!IsNull(functor_)); } } template explicit BindState(std::false_type, BindStateBase::InvokeFuncStorage invoke_func, ForwardFunctor&& functor, ForwardBoundArgs&&... bound_args) : BindStateBase(invoke_func, &Destroy), functor_(std::forward(functor)), bound_args_(std::forward(bound_args)...) { // See above for CHECK/DCHECK rationale. if (is_nested_callback) { CHECK(!IsNull(functor_)); } else { DCHECK(!IsNull(functor_)); } } ~BindState() = default; static void Destroy(const BindStateBase* self) { delete static_cast(self); } }; // Used to implement MakeBindStateType. template struct MakeBindStateTypeImpl; template struct MakeBindStateTypeImpl { static_assert(!HasRefCountedTypeAsRawPtr...>::value, "A parameter is a refcounted type and needs scoped_refptr."); using Type = BindState, std::decay_t...>; }; template struct MakeBindStateTypeImpl { using Type = BindState>; }; template struct MakeBindStateTypeImpl { private: using DecayedReceiver = std::decay_t; static_assert(!std::is_array>::value, "First bound argument to a method cannot be an array."); static_assert( !std::is_pointer::value || IsRefCountedType>::value, "Receivers may not be raw pointers. If using a raw pointer here is safe" " and has no lifetime concerns, use base::Unretained() and document why" " it's safe."); static_assert(!HasRefCountedTypeAsRawPtr...>::value, "A parameter is a refcounted type and needs scoped_refptr."); public: using Type = BindState< std::decay_t, std::conditional_t::value, scoped_refptr>, DecayedReceiver>, std::decay_t...>; }; template using MakeBindStateType = typename MakeBindStateTypeImpl::is_method, Functor, BoundArgs...>::Type; // Returns a RunType of bound functor. // E.g. MakeUnboundRunType is evaluated to R(C). template using MakeUnboundRunType = typename BindTypeHelper::UnboundRunType; // The implementation of TransformToUnwrappedType below. template struct TransformToUnwrappedTypeImpl; template struct TransformToUnwrappedTypeImpl { using StoredType = std::decay_t; using ForwardType = StoredType&&; using Unwrapped = decltype(Unwrap(std::declval())); }; template struct TransformToUnwrappedTypeImpl { using StoredType = std::decay_t; using ForwardType = const StoredType&; using Unwrapped = decltype(Unwrap(std::declval())); }; // Transform |T| into `Unwrapped` type, which is passed to the target function. // Example: // In is_once == true case, // `int&&` -> `int&&`, // `const int&` -> `int&&`, // `OwnedWrapper&` -> `int*&&`. // In is_once == false case, // `int&&` -> `const int&`, // `const int&` -> `const int&`, // `OwnedWrapper&` -> `int* const &`. template using TransformToUnwrappedType = typename TransformToUnwrappedTypeImpl::Unwrapped; // Transforms |Args| into `Unwrapped` types, and packs them into a TypeList. // If |is_method| is true, tries to dereference the first argument to support // smart pointers. template struct MakeUnwrappedTypeListImpl { using Type = TypeList...>; }; // Performs special handling for this pointers. // Example: // int* -> int*, // std::unique_ptr -> int*. template struct MakeUnwrappedTypeListImpl { using UnwrappedReceiver = TransformToUnwrappedType; using Type = TypeList()), TransformToUnwrappedType...>; }; template using MakeUnwrappedTypeList = typename MakeUnwrappedTypeListImpl::Type; // IsOnceCallback is a std::true_type if |T| is a OnceCallback. template struct IsOnceCallback : std::false_type {}; template struct IsOnceCallback> : std::true_type {}; // Helpers to make error messages slightly more readable. template struct BindArgument { template struct ForwardedAs { template struct ToParamWithType { static constexpr bool kCanBeForwardedToBoundFunctor = std::is_constructible::value; // If the bound type can't be forwarded then test if `FunctorParamType` is // a non-const lvalue reference and a reference to the unwrapped type // *could* have been successfully forwarded. static constexpr bool kNonConstRefParamMustBeWrapped = kCanBeForwardedToBoundFunctor || !(std::is_lvalue_reference::value && !std::is_const>::value && std::is_convertible&, FunctorParamType>::value); // Note that this intentionally drops the const qualifier from // `ForwardingType`, to test if it *could* have been successfully // forwarded if `Passed()` had been used. static constexpr bool kMoveOnlyTypeMustUseBasePassed = kCanBeForwardedToBoundFunctor || !std::is_constructible&&>::value; }; }; template struct BoundAs { template struct StoredAs { static constexpr bool kBindArgumentCanBeCaptured = std::is_constructible::value; // Note that this intentionally drops the const qualifier from // `BoundAsType`, to test if it *could* have been successfully bound if // `std::move()` had been used. static constexpr bool kMoveOnlyTypeMustUseStdMove = kBindArgumentCanBeCaptured || !std::is_constructible&&>::value; }; }; }; // Helper to assert that parameter |i| of type |Arg| can be bound, which means: // - |Arg| can be retained internally as |Storage|. // - |Arg| can be forwarded as |Unwrapped| to |Param|. template struct AssertConstructible { private: // With `BindRepeating`, there are two decision points for how to handle a // move-only type: // // 1. Whether the move-only argument should be moved into the internal // `BindState`. Either `std::move()` or `Passed` is sufficient to trigger // move-only semantics. // 2. Whether or not the bound, move-only argument should be moved to the // bound functor when invoked. When the argument is bound with `Passed`, // invoking the callback will destructively move the bound, move-only // argument to the bound functor. In contrast, if the argument is bound // with `std::move()`, `RepeatingCallback` will attempt to call the bound // functor with a constant reference to the bound, move-only argument. This // will fail if the bound functor accepts that argument by value, since the // argument cannot be copied. It is this latter case that this // static_assert aims to catch. // // In contrast, `BindOnce()` only has one decision point. Once a move-only // type is captured by value into the internal `BindState`, the bound, // move-only argument will always be moved to the functor when invoked. // Failure to use std::move will simply fail the `kMoveOnlyTypeMustUseStdMove` // assert below instead. // // Note: `Passed()` is a legacy of supporting move-only types when repeating // callbacks were the only callback type. A `RepeatingCallback` with a // `Passed()` argument is really a `OnceCallback` and should eventually be // migrated. static_assert( BindArgument::template ForwardedAs:: template ToParamWithType::kMoveOnlyTypeMustUseBasePassed, "base::BindRepeating() argument is a move-only type. Use base::Passed() " "instead of std::move() to transfer ownership from the callback to the " "bound functor."); static_assert( BindArgument::template ForwardedAs:: template ToParamWithType::kNonConstRefParamMustBeWrapped, "Bound argument for non-const reference parameter must be wrapped in " "std::ref() or base::OwnedRef()."); static_assert( BindArgument::template ForwardedAs:: template ToParamWithType::kCanBeForwardedToBoundFunctor, "Type mismatch between bound argument and bound functor's parameter."); static_assert(BindArgument::template BoundAs::template StoredAs< Storage>::kMoveOnlyTypeMustUseStdMove, "Attempting to bind a move-only type. Use std::move() to " "transfer ownership to the created callback."); // In practice, this static_assert should be quite rare as the storage type // is deduced from the arguments passed to `BindOnce()`/`BindRepeating()`. static_assert( BindArgument::template BoundAs::template StoredAs< Storage>::kBindArgumentCanBeCaptured, "Cannot capture argument: is the argument copyable or movable?"); }; // Takes three same-length TypeLists, and applies AssertConstructible for each // triples. template struct AssertBindArgsValidity; template struct AssertBindArgsValidity, TypeList, TypeList, TypeList> : AssertConstructible, Unwrapped, Params>... { static constexpr bool ok = true; }; template struct AssertBindArgIsNotBasePassed : public std::true_type {}; template struct AssertBindArgIsNotBasePassed> : public std::false_type { }; // Used below in BindImpl to determine whether to use Invoker::Run or // Invoker::RunOnce. // Note: Simply using `kIsOnce ? &Invoker::RunOnce : &Invoker::Run` does not // work, since the compiler needs to check whether both expressions are // well-formed. Using `Invoker::Run` with a OnceCallback triggers a // static_assert, which is why the ternary expression does not compile. // TODO(crbug.com/752720): Remove this indirection once we have `if constexpr`. template constexpr auto GetInvokeFunc(std::true_type) { return Invoker::RunOnce; } template constexpr auto GetInvokeFunc(std::false_type) { return Invoker::Run; } template