// 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 "base/tuple.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 make_void { using type = void; }; // A clone of C++17 std::void_t. // Unlike the original version, we need |make_void| as a helper struct to avoid // a C++14 defect. // ref: http://en.cppreference.com/w/cpp/types/void_t // ref: http://open-std.org/JTC1/SC22/WG21/docs/cwg_defects.html#1558 template using void_t = typename make_void::type; 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::value, std::true_type, HasRefCountedTypeAsRawPtr>::type {}; // 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< Functor, typename std::enable_if::value>::type> { 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) { // Clang skips CV qualifier check on a method pointer invocation when the // receiver is a subclass. Store the receiver into a const reference to // T to ensure the CV check works. // https://llvm.org/bugs/show_bug.cgi?id=27037 Receiver& receiver = *receiver_ptr; return (receiver.*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) { // Clang skips CV qualifier check on a method pointer invocation when the // receiver is a subclass. Store the receiver into a const reference to // T to ensure the CV check works. // https://llvm.org/bugs/show_bug.cgi?id=27037 const Receiver& receiver = *receiver_ptr; return (receiver.*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 Callbacks. 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)...); } }; // 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 = FunctorTraits::type>; 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 = FunctorTraits::type>; 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_), MakeIndexSequence(), 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_, MakeIndexSequence(), std::forward(unbound_args)...); } private: template static inline R RunImpl(Functor&& functor, BoundArgsTuple&& bound, IndexSequence, UnboundArgs&&... unbound_args) { static constexpr bool is_method = FunctorTraits::type>::is_method; using DecayedArgsTuple = typename std::decay::type; static constexpr bool is_weak_call = IsWeakMethod::type...>::value; return InvokeHelper::MakeItSo( std::forward(functor), Unwrap(base::get(std::forward(bound)))..., std::forward(unbound_args)...); } }; // Used to implement MakeUnboundRunType. template struct MakeUnboundRunTypeImpl { using RunType = typename FunctorTraits::type>::RunType; using ReturnType = ExtractReturnType; using Args = ExtractArgs; using UnboundArgs = DropTypeListItem; using Type = MakeFunctionType; }; template typename std::enable_if::is_nullable, bool>::type IsNull(const Functor& functor) { return !functor; } template typename std::enable_if::is_nullable, bool>::type IsNull(const Functor&) { return false; } // Used by ApplyCancellationTraits below. template bool ApplyCancellationTraitsImpl(const Functor& functor, const BoundArgsTuple& bound_args, IndexSequence) { return CallbackCancellationTraits::IsCancelled( functor, base::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_, MakeIndexSequence()); }; // Template helpers to detect using Bind() on a base::Callback without any // additional arguments. In that case, the original base::Callback object should // just be directly used. template struct BindingCallbackWithNoArgs { static constexpr bool value = false; }; template struct BindingCallbackWithNoArgs, BoundArgs...> { static constexpr bool value = sizeof...(BoundArgs) == 0; }; // 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)...) { static_assert(!BindingCallbackWithNoArgs::value, "Attempting to bind a base::Callback with no additional " "arguments: save a heap allocation and use the original " "base::Callback object"); } 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::type, typename std::decay::type...>; }; template struct MakeBindStateTypeImpl { using Type = BindState::type>; }; template struct MakeBindStateTypeImpl { static_assert( !std::is_array::type>::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 = typename std::decay::type; public: using Type = BindState< typename std::decay::type, typename std::conditional< std::is_pointer::value, scoped_refptr::type>, DecayedReceiver>::type, typename std::decay::type...>; }; template using MakeBindStateType = typename MakeBindStateTypeImpl< FunctorTraits::type>::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::MakeUnboundRunTypeImpl::Type; } // namespace base #endif // BASE_BIND_INTERNAL_H_