// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_BIND_INTERNAL_H_ #define BASE_BIND_INTERNAL_H_ #include #include #include #include "base/bind_helpers.h" #include "base/callback_internal.h" #include "base/memory/raw_scoped_refptr_mismatch_checker.h" #include "base/memory/weak_ptr.h" #include "base/template_util.h" #include "build/build_config.h" namespace base { namespace internal { // See base/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. template struct ExtractCallableRunTypeImpl; 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; // IsConvertibleToRunType is std::true_type if |Functor| has operator() // and convertible to the corresponding function pointer. Otherwise, it's // std::false_type. // Example: // IsConvertibleToRunType::value is false. // // struct Foo {}; // IsConvertibleToRunType::value is false. // // auto f = []() {}; // IsConvertibleToRunType::value is true. // // int i = 0; // auto g = [i]() {}; // IsConvertibleToRunType::value is false. template struct IsConvertibleToRunType : std::false_type {}; template struct IsConvertibleToRunType> : std::is_convertible*> {}; // HasRefCountedTypeAsRawPtr selects true_type when any of the |Args| is a raw // pointer to a RefCounted type. // Implementation note: This non-specialized case handles zero-arity case only. // Non-zero-arity cases should be handled by the specialization below. template struct HasRefCountedTypeAsRawPtr : std::false_type {}; // Implementation note: Select true_type if the first parameter is a raw pointer // to a RefCounted type. Otherwise, skip the first parameter and check rest of // parameters recursively. template struct HasRefCountedTypeAsRawPtr : std::conditional_t::value, std::true_type, HasRefCountedTypeAsRawPtr> {}; // 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 a callable type that is convertible to the corresponding function type. // This specialization is intended to allow binding captureless lambdas by // base::Bind(), based on the fact that captureless lambdas can be convertible // to the function type while capturing lambdas can't. template struct FunctorTraits::value>> { using RunType = ExtractCallableRunType; static constexpr bool is_method = false; static constexpr bool is_nullable = false; template static ExtractReturnType Invoke(const Functor& functor, RunArgs&&... args) { return 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; template static R Invoke(R (*function)(Args...), RunArgs&&... args) { return function(std::forward(args)...); } }; #if defined(OS_WIN) && !defined(ARCH_CPU_X86_64) // For functions. template struct FunctorTraits { using RunType = R(Args...); static constexpr bool is_method = false; static constexpr bool is_nullable = true; 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; template static R Invoke(R(__fastcall* function)(Args...), RunArgs&&... args) { return function(std::forward(args)...); } }; #endif // defined(OS_WIN) && !defined(ARCH_CPU_X86_64) // For methods. template struct FunctorTraits { using RunType = R(Receiver*, Args...); static constexpr bool is_method = true; static constexpr bool is_nullable = true; template static R Invoke(R (Receiver::*method)(Args...), 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; template static R Invoke(R (Receiver::*method)(Args...) const, ReceiverPtr&& receiver_ptr, RunArgs&&... args) { return ((*receiver_ptr).*method)(std::forward(args)...); } }; // 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; 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; 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 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, UnboundArgs&&... 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, UnboundArgs&&... 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 ApplyCancellationTraits below. template bool ApplyCancellationTraitsImpl(const Functor& functor, const BoundArgsTuple& bound_args, std::index_sequence) { return CallbackCancellationTraits::IsCancelled( functor, std::get(bound_args)...); } // Relays |base| to corresponding CallbackCancellationTraits<>::Run(). Returns // true if the callback |base| represents is canceled. template bool ApplyCancellationTraits(const BindStateBase* base) { const BindStateType* storage = static_cast(base); static constexpr size_t num_bound_args = std::tuple_sizebound_args_)>::value; return ApplyCancellationTraitsImpl( storage->functor_, storage->bound_args_, std::make_index_sequence()); }; // BindState<> // // This stores all the state passed into Bind(). template struct BindState final : BindStateBase { using IsCancellable = std::integral_constant< bool, CallbackCancellationTraits>::is_cancellable>; template explicit BindState(BindStateBase::InvokeFuncStorage invoke_func, ForwardFunctor&& functor, ForwardBoundArgs&&... bound_args) // IsCancellable is std::false_type if // CallbackCancellationTraits<>::IsCancelled returns always false. // Otherwise, it's std::true_type. : BindState(IsCancellable{}, invoke_func, std::forward(functor), std::forward(bound_args)...) { } Functor functor_; std::tuple bound_args_; private: template explicit BindState(std::true_type, BindStateBase::InvokeFuncStorage invoke_func, ForwardFunctor&& functor, ForwardBoundArgs&&... bound_args) : BindStateBase(invoke_func, &Destroy, &ApplyCancellationTraits), functor_(std::forward(functor)), bound_args_(std::forward(bound_args)...) { 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)...) { DCHECK(!IsNull(functor_)); } ~BindState() {} 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 { static_assert(!std::is_array>::value, "First bound argument to a method cannot be an array."); static_assert(!HasRefCountedTypeAsRawPtr...>::value, "A parameter is a refcounted type and needs scoped_refptr."); private: using DecayedReceiver = std::decay_t; 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; } // namespace internal // Returns a RunType of bound functor. // E.g. MakeUnboundRunType is evaluated to R(C). template using MakeUnboundRunType = typename internal::BindTypeHelper::UnboundRunType; } // namespace base #endif // BASE_BIND_INTERNAL_H_