Path: blob/main/contrib/googletest/googlemock/include/gmock/gmock-actions.h
110743 views
// Copyright 2007, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// Google Mock - a framework for writing C++ mock classes.30//31// The ACTION* family of macros can be used in a namespace scope to32// define custom actions easily. The syntax:33//34// ACTION(name) { statements; }35//36// will define an action with the given name that executes the37// statements. The value returned by the statements will be used as38// the return value of the action. Inside the statements, you can39// refer to the K-th (0-based) argument of the mock function by40// 'argK', and refer to its type by 'argK_type'. For example:41//42// ACTION(IncrementArg1) {43// arg1_type temp = arg1;44// return ++(*temp);45// }46//47// allows you to write48//49// ...WillOnce(IncrementArg1());50//51// You can also refer to the entire argument tuple and its type by52// 'args' and 'args_type', and refer to the mock function type and its53// return type by 'function_type' and 'return_type'.54//55// Note that you don't need to specify the types of the mock function56// arguments. However rest assured that your code is still type-safe:57// you'll get a compiler error if *arg1 doesn't support the ++58// operator, or if the type of ++(*arg1) isn't compatible with the59// mock function's return type, for example.60//61// Sometimes you'll want to parameterize the action. For that you can use62// another macro:63//64// ACTION_P(name, param_name) { statements; }65//66// For example:67//68// ACTION_P(Add, n) { return arg0 + n; }69//70// will allow you to write:71//72// ...WillOnce(Add(5));73//74// Note that you don't need to provide the type of the parameter75// either. If you need to reference the type of a parameter named76// 'foo', you can write 'foo_type'. For example, in the body of77// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type78// of 'n'.79//80// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support81// multi-parameter actions.82//83// For the purpose of typing, you can view84//85// ACTION_Pk(Foo, p1, ..., pk) { ... }86//87// as shorthand for88//89// template <typename p1_type, ..., typename pk_type>90// FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }91//92// In particular, you can provide the template type arguments93// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);94// although usually you can rely on the compiler to infer the types95// for you automatically. You can assign the result of expression96// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,97// pk_type>. This can be useful when composing actions.98//99// You can also overload actions with different numbers of parameters:100//101// ACTION_P(Plus, a) { ... }102// ACTION_P2(Plus, a, b) { ... }103//104// While it's tempting to always use the ACTION* macros when defining105// a new action, you should also consider implementing ActionInterface106// or using MakePolymorphicAction() instead, especially if you need to107// use the action a lot. While these approaches require more work,108// they give you more control on the types of the mock function109// arguments and the action parameters, which in general leads to110// better compiler error messages that pay off in the long run. They111// also allow overloading actions based on parameter types (as opposed112// to just based on the number of parameters).113//114// CAVEAT:115//116// ACTION*() can only be used in a namespace scope as templates cannot be117// declared inside of a local class.118// Users can, however, define any local functors (e.g. a lambda) that119// can be used as actions.120//121// MORE INFORMATION:122//123// To learn more about using these macros, please search for 'ACTION' on124// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md125126// IWYU pragma: private, include "gmock/gmock.h"127// IWYU pragma: friend gmock/.*128129#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_130#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_131132#ifndef _WIN32_WCE133#include <errno.h>134#endif135136#include <algorithm>137#include <exception>138#include <functional>139#include <memory>140#include <string>141#include <tuple>142#include <type_traits>143#include <utility>144145#include "gmock/internal/gmock-internal-utils.h"146#include "gmock/internal/gmock-port.h"147#include "gmock/internal/gmock-pp.h"148149GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)150151namespace testing {152153// To implement an action Foo, define:154// 1. a class FooAction that implements the ActionInterface interface, and155// 2. a factory function that creates an Action object from a156// const FooAction*.157//158// The two-level delegation design follows that of Matcher, providing159// consistency for extension developers. It also eases ownership160// management as Action objects can now be copied like plain values.161162namespace internal {163164// BuiltInDefaultValueGetter<T, true>::Get() returns a165// default-constructed T value. BuiltInDefaultValueGetter<T,166// false>::Get() crashes with an error.167//168// This primary template is used when kDefaultConstructible is true.169template <typename T, bool kDefaultConstructible>170struct BuiltInDefaultValueGetter {171static T Get() { return T(); }172};173template <typename T>174struct BuiltInDefaultValueGetter<T, false> {175static T Get() {176Assert(false, __FILE__, __LINE__,177"Default action undefined for the function return type.");178#if defined(__GNUC__) || defined(__clang__)179__builtin_unreachable();180#elif defined(_MSC_VER)181__assume(0);182#else183return Invalid<T>();184// The above statement will never be reached, but is required in185// order for this function to compile.186#endif187}188};189190// BuiltInDefaultValue<T>::Get() returns the "built-in" default value191// for type T, which is NULL when T is a raw pointer type, 0 when T is192// a numeric type, false when T is bool, or "" when T is string or193// std::string. In addition, in C++11 and above, it turns a194// default-constructed T value if T is default constructible. For any195// other type T, the built-in default T value is undefined, and the196// function will abort the process.197template <typename T>198class BuiltInDefaultValue {199public:200// This function returns true if and only if type T has a built-in default201// value.202static bool Exists() { return ::std::is_default_constructible<T>::value; }203204static T Get() {205return BuiltInDefaultValueGetter<206T, ::std::is_default_constructible<T>::value>::Get();207}208};209210// This partial specialization says that we use the same built-in211// default value for T and const T.212template <typename T>213class BuiltInDefaultValue<const T> {214public:215static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }216static T Get() { return BuiltInDefaultValue<T>::Get(); }217};218219// This partial specialization defines the default values for pointer220// types.221template <typename T>222class BuiltInDefaultValue<T*> {223public:224static bool Exists() { return true; }225static T* Get() { return nullptr; }226};227228// The following specializations define the default values for229// specific types we care about.230#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \231template <> \232class BuiltInDefaultValue<type> { \233public: \234static bool Exists() { return true; } \235static type Get() { return value; } \236}237238GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT239GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");240GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);241GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');242GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');243GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');244245// There's no need for a default action for signed wchar_t, as that246// type is the same as wchar_t for gcc, and invalid for MSVC.247//248// There's also no need for a default action for unsigned wchar_t, as249// that type is the same as unsigned int for gcc, and invalid for250// MSVC.251#if GMOCK_WCHAR_T_IS_NATIVE_252GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT253#endif254255GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT256GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT257GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);258GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);259GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT260GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT261GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT262GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT263GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);264GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);265266#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_267268// Partial implementations of metaprogramming types from the standard library269// not available in C++11.270271template <typename P>272struct negation273// NOLINTNEXTLINE274: std::integral_constant<bool, bool(!P::value)> {};275276// Base case: with zero predicates the answer is always true.277template <typename...>278struct conjunction : std::true_type {};279280// With a single predicate, the answer is that predicate.281template <typename P1>282struct conjunction<P1> : P1 {};283284// With multiple predicates the answer is the first predicate if that is false,285// and we recurse otherwise.286template <typename P1, typename... Ps>287struct conjunction<P1, Ps...>288: std::conditional<bool(P1::value), conjunction<Ps...>, P1>::type {};289290template <typename...>291struct disjunction : std::false_type {};292293template <typename P1>294struct disjunction<P1> : P1 {};295296template <typename P1, typename... Ps>297struct disjunction<P1, Ps...>298// NOLINTNEXTLINE299: std::conditional<!bool(P1::value), disjunction<Ps...>, P1>::type {};300301template <typename...>302using void_t = void;303304// Detects whether an expression of type `From` can be implicitly converted to305// `To` according to [conv]. In C++17, [conv]/3 defines this as follows:306//307// An expression e can be implicitly converted to a type T if and only if308// the declaration T t=e; is well-formed, for some invented temporary309// variable t ([dcl.init]).310//311// [conv]/2 implies we can use function argument passing to detect whether this312// initialization is valid.313//314// Note that this is distinct from is_convertible, which requires this be valid:315//316// To test() {317// return declval<From>();318// }319//320// In particular, is_convertible doesn't give the correct answer when `To` and321// `From` are the same non-moveable type since `declval<From>` will be an rvalue322// reference, defeating the guaranteed copy elision that would otherwise make323// this function work.324//325// REQUIRES: `From` is not cv void.326template <typename From, typename To>327struct is_implicitly_convertible {328private:329// A function that accepts a parameter of type T. This can be called with type330// U successfully only if U is implicitly convertible to T.331template <typename T>332static void Accept(T);333334// A function that creates a value of type T.335template <typename T>336static T Make();337338// An overload be selected when implicit conversion from T to To is possible.339template <typename T, typename = decltype(Accept<To>(Make<T>()))>340static std::true_type TestImplicitConversion(int);341342// A fallback overload selected in all other cases.343template <typename T>344static std::false_type TestImplicitConversion(...);345346public:347using type = decltype(TestImplicitConversion<From>(0));348static constexpr bool value = type::value;349};350351// Like std::invoke_result_t from C++17, but works only for objects with call352// operators (not e.g. member function pointers, which we don't need specific353// support for in OnceAction because std::function deals with them).354template <typename F, typename... Args>355using call_result_t = decltype(std::declval<F>()(std::declval<Args>()...));356357template <typename Void, typename R, typename F, typename... Args>358struct is_callable_r_impl : std::false_type {};359360// Specialize the struct for those template arguments where call_result_t is361// well-formed. When it's not, the generic template above is chosen, resulting362// in std::false_type.363template <typename R, typename F, typename... Args>364struct is_callable_r_impl<void_t<call_result_t<F, Args...>>, R, F, Args...>365: std::conditional<366std::is_void<R>::value, //367std::true_type, //368is_implicitly_convertible<call_result_t<F, Args...>, R>>::type {};369370// Like std::is_invocable_r from C++17, but works only for objects with call371// operators. See the note on call_result_t.372template <typename R, typename F, typename... Args>373using is_callable_r = is_callable_r_impl<void, R, F, Args...>;374375// Like std::as_const from C++17.376template <typename T>377typename std::add_const<T>::type& as_const(T& t) {378return t;379}380381} // namespace internal382383// Specialized for function types below.384template <typename F>385class OnceAction;386387// An action that can only be used once.388//389// This is accepted by WillOnce, which doesn't require the underlying action to390// be copy-constructible (only move-constructible), and promises to invoke it as391// an rvalue reference. This allows the action to work with move-only types like392// std::move_only_function in a type-safe manner.393//394// For example:395//396// // Assume we have some API that needs to accept a unique pointer to some397// // non-copyable object Foo.398// void AcceptUniquePointer(std::unique_ptr<Foo> foo);399//400// // We can define an action that provides a Foo to that API. Because It401// // has to give away its unique pointer, it must not be called more than402// // once, so its call operator is &&-qualified.403// struct ProvideFoo {404// std::unique_ptr<Foo> foo;405//406// void operator()() && {407// AcceptUniquePointer(std::move(Foo));408// }409// };410//411// // This action can be used with WillOnce.412// EXPECT_CALL(mock, Call)413// .WillOnce(ProvideFoo{std::make_unique<Foo>(...)});414//415// // But a call to WillRepeatedly will fail to compile. This is correct,416// // since the action cannot correctly be used repeatedly.417// EXPECT_CALL(mock, Call)418// .WillRepeatedly(ProvideFoo{std::make_unique<Foo>(...)});419//420// A less-contrived example would be an action that returns an arbitrary type,421// whose &&-qualified call operator is capable of dealing with move-only types.422template <typename Result, typename... Args>423class OnceAction<Result(Args...)> final {424private:425// True iff we can use the given callable type (or lvalue reference) directly426// via StdFunctionAdaptor.427template <typename Callable>428using IsDirectlyCompatible = internal::conjunction<429// It must be possible to capture the callable in StdFunctionAdaptor.430std::is_constructible<typename std::decay<Callable>::type, Callable>,431// The callable must be compatible with our signature.432internal::is_callable_r<Result, typename std::decay<Callable>::type,433Args...>>;434435// True iff we can use the given callable type via StdFunctionAdaptor once we436// ignore incoming arguments.437template <typename Callable>438using IsCompatibleAfterIgnoringArguments = internal::conjunction<439// It must be possible to capture the callable in a lambda.440std::is_constructible<typename std::decay<Callable>::type, Callable>,441// The callable must be invocable with zero arguments, returning something442// convertible to Result.443internal::is_callable_r<Result, typename std::decay<Callable>::type>>;444445public:446// Construct from a callable that is directly compatible with our mocked447// signature: it accepts our function type's arguments and returns something448// convertible to our result type.449template <typename Callable,450typename std::enable_if<451internal::conjunction<452// Teach clang on macOS that we're not talking about a453// copy/move constructor here. Otherwise it gets confused454// when checking the is_constructible requirement of our455// traits above.456internal::negation<std::is_same<457OnceAction, typename std::decay<Callable>::type>>,458IsDirectlyCompatible<Callable>> //459::value,460int>::type = 0>461OnceAction(Callable&& callable) // NOLINT462: function_(StdFunctionAdaptor<typename std::decay<Callable>::type>(463{}, std::forward<Callable>(callable))) {}464465// As above, but for a callable that ignores the mocked function's arguments.466template <typename Callable,467typename std::enable_if<468internal::conjunction<469// Teach clang on macOS that we're not talking about a470// copy/move constructor here. Otherwise it gets confused471// when checking the is_constructible requirement of our472// traits above.473internal::negation<std::is_same<474OnceAction, typename std::decay<Callable>::type>>,475// Exclude callables for which the overload above works.476// We'd rather provide the arguments if possible.477internal::negation<IsDirectlyCompatible<Callable>>,478IsCompatibleAfterIgnoringArguments<Callable>>::value,479int>::type = 0>480OnceAction(Callable&& callable) // NOLINT481// Call the constructor above with a callable482// that ignores the input arguments.483: OnceAction(IgnoreIncomingArguments<typename std::decay<Callable>::type>{484std::forward<Callable>(callable)}) {}485486// We are naturally copyable because we store only an std::function, but487// semantically we should not be copyable.488OnceAction(const OnceAction&) = delete;489OnceAction& operator=(const OnceAction&) = delete;490OnceAction(OnceAction&&) = default;491492// Invoke the underlying action callable with which we were constructed,493// handing it the supplied arguments.494Result Call(Args... args) && {495return function_(std::forward<Args>(args)...);496}497498private:499// An adaptor that wraps a callable that is compatible with our signature and500// being invoked as an rvalue reference so that it can be used as an501// StdFunctionAdaptor. This throws away type safety, but that's fine because502// this is only used by WillOnce, which we know calls at most once.503//504// Once we have something like std::move_only_function from C++23, we can do505// away with this.506template <typename Callable>507class StdFunctionAdaptor final {508public:509// A tag indicating that the (otherwise universal) constructor is accepting510// the callable itself, instead of e.g. stealing calls for the move511// constructor.512struct CallableTag final {};513514template <typename F>515explicit StdFunctionAdaptor(CallableTag, F&& callable)516: callable_(std::make_shared<Callable>(std::forward<F>(callable))) {}517518// Rather than explicitly returning Result, we return whatever the wrapped519// callable returns. This allows for compatibility with existing uses like520// the following, when the mocked function returns void:521//522// EXPECT_CALL(mock_fn_, Call)523// .WillOnce([&] {524// [...]525// return 0;526// });527//528// Such a callable can be turned into std::function<void()>. If we use an529// explicit return type of Result here then it *doesn't* work with530// std::function, because we'll get a "void function should not return a531// value" error.532//533// We need not worry about incompatible result types because the SFINAE on534// OnceAction already checks this for us. std::is_invocable_r_v itself makes535// the same allowance for void result types.536template <typename... ArgRefs>537internal::call_result_t<Callable, ArgRefs...> operator()(538ArgRefs&&... args) const {539return std::move(*callable_)(std::forward<ArgRefs>(args)...);540}541542private:543// We must put the callable on the heap so that we are copyable, which544// std::function needs.545std::shared_ptr<Callable> callable_;546};547548// An adaptor that makes a callable that accepts zero arguments callable with549// our mocked arguments.550template <typename Callable>551struct IgnoreIncomingArguments {552internal::call_result_t<Callable> operator()(Args&&...) {553return std::move(callable)();554}555556Callable callable;557};558559std::function<Result(Args...)> function_;560};561562// When an unexpected function call is encountered, Google Mock will563// let it return a default value if the user has specified one for its564// return type, or if the return type has a built-in default value;565// otherwise Google Mock won't know what value to return and will have566// to abort the process.567//568// The DefaultValue<T> class allows a user to specify the569// default value for a type T that is both copyable and publicly570// destructible (i.e. anything that can be used as a function return571// type). The usage is:572//573// // Sets the default value for type T to be foo.574// DefaultValue<T>::Set(foo);575template <typename T>576class DefaultValue {577public:578// Sets the default value for type T; requires T to be579// copy-constructable and have a public destructor.580static void Set(T x) {581delete producer_;582producer_ = new FixedValueProducer(x);583}584585// Provides a factory function to be called to generate the default value.586// This method can be used even if T is only move-constructible, but it is not587// limited to that case.588typedef T (*FactoryFunction)();589static void SetFactory(FactoryFunction factory) {590delete producer_;591producer_ = new FactoryValueProducer(factory);592}593594// Unsets the default value for type T.595static void Clear() {596delete producer_;597producer_ = nullptr;598}599600// Returns true if and only if the user has set the default value for type T.601static bool IsSet() { return producer_ != nullptr; }602603// Returns true if T has a default return value set by the user or there604// exists a built-in default value.605static bool Exists() {606return IsSet() || internal::BuiltInDefaultValue<T>::Exists();607}608609// Returns the default value for type T if the user has set one;610// otherwise returns the built-in default value. Requires that Exists()611// is true, which ensures that the return value is well-defined.612static T Get() {613return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()614: producer_->Produce();615}616617private:618class ValueProducer {619public:620virtual ~ValueProducer() = default;621virtual T Produce() = 0;622};623624class FixedValueProducer : public ValueProducer {625public:626explicit FixedValueProducer(T value) : value_(value) {}627T Produce() override { return value_; }628629private:630const T value_;631FixedValueProducer(const FixedValueProducer&) = delete;632FixedValueProducer& operator=(const FixedValueProducer&) = delete;633};634635class FactoryValueProducer : public ValueProducer {636public:637explicit FactoryValueProducer(FactoryFunction factory)638: factory_(factory) {}639T Produce() override { return factory_(); }640641private:642const FactoryFunction factory_;643FactoryValueProducer(const FactoryValueProducer&) = delete;644FactoryValueProducer& operator=(const FactoryValueProducer&) = delete;645};646647static ValueProducer* producer_;648};649650// This partial specialization allows a user to set default values for651// reference types.652template <typename T>653class DefaultValue<T&> {654public:655// Sets the default value for type T&.656static void Set(T& x) { // NOLINT657address_ = &x;658}659660// Unsets the default value for type T&.661static void Clear() { address_ = nullptr; }662663// Returns true if and only if the user has set the default value for type T&.664static bool IsSet() { return address_ != nullptr; }665666// Returns true if T has a default return value set by the user or there667// exists a built-in default value.668static bool Exists() {669return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();670}671672// Returns the default value for type T& if the user has set one;673// otherwise returns the built-in default value if there is one;674// otherwise aborts the process.675static T& Get() {676return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()677: *address_;678}679680private:681static T* address_;682};683684// This specialization allows DefaultValue<void>::Get() to685// compile.686template <>687class DefaultValue<void> {688public:689static bool Exists() { return true; }690static void Get() {}691};692693// Points to the user-set default value for type T.694template <typename T>695typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;696697// Points to the user-set default value for type T&.698template <typename T>699T* DefaultValue<T&>::address_ = nullptr;700701// Implement this interface to define an action for function type F.702template <typename F>703class ActionInterface {704public:705typedef typename internal::Function<F>::Result Result;706typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;707708ActionInterface() = default;709virtual ~ActionInterface() = default;710711// Performs the action. This method is not const, as in general an712// action can have side effects and be stateful. For example, a713// get-the-next-element-from-the-collection action will need to714// remember the current element.715virtual Result Perform(const ArgumentTuple& args) = 0;716717private:718ActionInterface(const ActionInterface&) = delete;719ActionInterface& operator=(const ActionInterface&) = delete;720};721722template <typename F>723class Action;724725// An Action<R(Args...)> is a copyable and IMMUTABLE (except by assignment)726// object that represents an action to be taken when a mock function of type727// R(Args...) is called. The implementation of Action<T> is just a728// std::shared_ptr to const ActionInterface<T>. Don't inherit from Action! You729// can view an object implementing ActionInterface<F> as a concrete action730// (including its current state), and an Action<F> object as a handle to it.731template <typename R, typename... Args>732class Action<R(Args...)> {733private:734using F = R(Args...);735736// Adapter class to allow constructing Action from a legacy ActionInterface.737// New code should create Actions from functors instead.738struct ActionAdapter {739// Adapter must be copyable to satisfy std::function requirements.740::std::shared_ptr<ActionInterface<F>> impl_;741742template <typename... InArgs>743typename internal::Function<F>::Result operator()(InArgs&&... args) {744return impl_->Perform(745::std::forward_as_tuple(::std::forward<InArgs>(args)...));746}747};748749template <typename G>750using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;751752public:753typedef typename internal::Function<F>::Result Result;754typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;755756// Constructs a null Action. Needed for storing Action objects in757// STL containers.758Action() = default;759760// Construct an Action from a specified callable.761// This cannot take std::function directly, because then Action would not be762// directly constructible from lambda (it would require two conversions).763template <764typename G,765typename = typename std::enable_if<internal::disjunction<766IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,767G>>::value>::type>768Action(G&& fun) { // NOLINT769Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());770}771772// Constructs an Action from its implementation.773explicit Action(ActionInterface<F>* impl)774: fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}775776// This constructor allows us to turn an Action<Func> object into an777// Action<F>, as long as F's arguments can be implicitly converted778// to Func's and Func's return type can be implicitly converted to F's.779template <typename Func>780Action(const Action<Func>& action) // NOLINT781: fun_(action.fun_) {}782783// Returns true if and only if this is the DoDefault() action.784bool IsDoDefault() const { return fun_ == nullptr; }785786// Performs the action. Note that this method is const even though787// the corresponding method in ActionInterface is not. The reason788// is that a const Action<F> means that it cannot be re-bound to789// another concrete action, not that the concrete action it binds to790// cannot change state. (Think of the difference between a const791// pointer and a pointer to const.)792Result Perform(ArgumentTuple args) const {793if (IsDoDefault()) {794internal::IllegalDoDefault(__FILE__, __LINE__);795}796return internal::Apply(fun_, ::std::move(args));797}798799// An action can be used as a OnceAction, since it's obviously safe to call it800// once.801operator OnceAction<F>() const { // NOLINT802// Return a OnceAction-compatible callable that calls Perform with the803// arguments it is provided. We could instead just return fun_, but then804// we'd need to handle the IsDoDefault() case separately.805struct OA {806Action<F> action;807808R operator()(Args... args) && {809return action.Perform(810std::forward_as_tuple(std::forward<Args>(args)...));811}812};813814return OA{*this};815}816817private:818template <typename G>819friend class Action;820821template <typename G>822void Init(G&& g, ::std::true_type) {823fun_ = ::std::forward<G>(g);824}825826template <typename G>827void Init(G&& g, ::std::false_type) {828fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};829}830831template <typename FunctionImpl>832struct IgnoreArgs {833template <typename... InArgs>834Result operator()(const InArgs&...) const {835return function_impl();836}837template <typename... InArgs>838Result operator()(const InArgs&...) {839return function_impl();840}841842FunctionImpl function_impl;843};844845// fun_ is an empty function if and only if this is the DoDefault() action.846::std::function<F> fun_;847};848849// The PolymorphicAction class template makes it easy to implement a850// polymorphic action (i.e. an action that can be used in mock851// functions of than one type, e.g. Return()).852//853// To define a polymorphic action, a user first provides a COPYABLE854// implementation class that has a Perform() method template:855//856// class FooAction {857// public:858// template <typename Result, typename ArgumentTuple>859// Result Perform(const ArgumentTuple& args) const {860// // Processes the arguments and returns a result, using861// // std::get<N>(args) to get the N-th (0-based) argument in the tuple.862// }863// ...864// };865//866// Then the user creates the polymorphic action using867// MakePolymorphicAction(object) where object has type FooAction. See868// the definition of Return(void) and SetArgumentPointee<N>(value) for869// complete examples.870template <typename Impl>871class PolymorphicAction {872public:873explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}874875template <typename F>876operator Action<F>() const {877return Action<F>(new MonomorphicImpl<F>(impl_));878}879880private:881template <typename F>882class MonomorphicImpl : public ActionInterface<F> {883public:884typedef typename internal::Function<F>::Result Result;885typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;886887explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}888889Result Perform(const ArgumentTuple& args) override {890return impl_.template Perform<Result>(args);891}892893private:894Impl impl_;895};896897Impl impl_;898};899900// Creates an Action from its implementation and returns it. The901// created Action object owns the implementation.902template <typename F>903Action<F> MakeAction(ActionInterface<F>* impl) {904return Action<F>(impl);905}906907// Creates a polymorphic action from its implementation. This is908// easier to use than the PolymorphicAction<Impl> constructor as it909// doesn't require you to explicitly write the template argument, e.g.910//911// MakePolymorphicAction(foo);912// vs913// PolymorphicAction<TypeOfFoo>(foo);914template <typename Impl>915inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {916return PolymorphicAction<Impl>(impl);917}918919namespace internal {920921// Helper struct to specialize ReturnAction to execute a move instead of a copy922// on return. Useful for move-only types, but could be used on any type.923template <typename T>924struct ByMoveWrapper {925explicit ByMoveWrapper(T value) : payload(std::move(value)) {}926T payload;927};928929// The general implementation of Return(R). Specializations follow below.930template <typename R>931class ReturnAction final {932public:933explicit ReturnAction(R value) : value_(std::move(value)) {}934935template <typename U, typename... Args,936typename = typename std::enable_if<conjunction<937// See the requirements documented on Return.938negation<std::is_same<void, U>>, //939negation<std::is_reference<U>>, //940std::is_convertible<R, U>, //941std::is_move_constructible<U>>::value>::type>942operator OnceAction<U(Args...)>() && { // NOLINT943return Impl<U>(std::move(value_));944}945946template <typename U, typename... Args,947typename = typename std::enable_if<conjunction<948// See the requirements documented on Return.949negation<std::is_same<void, U>>, //950negation<std::is_reference<U>>, //951std::is_convertible<const R&, U>, //952std::is_copy_constructible<U>>::value>::type>953operator Action<U(Args...)>() const { // NOLINT954return Impl<U>(value_);955}956957private:958// Implements the Return(x) action for a mock function that returns type U.959template <typename U>960class Impl final {961public:962// The constructor used when the return value is allowed to move from the963// input value (i.e. we are converting to OnceAction).964explicit Impl(R&& input_value)965: state_(new State(std::move(input_value))) {}966967// The constructor used when the return value is not allowed to move from968// the input value (i.e. we are converting to Action).969explicit Impl(const R& input_value) : state_(new State(input_value)) {}970971U operator()() && { return std::move(state_->value); }972U operator()() const& { return state_->value; }973974private:975// We put our state on the heap so that the compiler-generated copy/move976// constructors work correctly even when U is a reference-like type. This is977// necessary only because we eagerly create State::value (see the note on978// that symbol for details). If we instead had only the input value as a979// member then the default constructors would work fine.980//981// For example, when R is std::string and U is std::string_view, value is a982// reference to the string backed by input_value. The copy constructor would983// copy both, so that we wind up with a new input_value object (with the984// same contents) and a reference to the *old* input_value object rather985// than the new one.986struct State {987explicit State(const R& input_value_in)988: input_value(input_value_in),989// Make an implicit conversion to Result before initializing the U990// object we store, avoiding calling any explicit constructor of U991// from R.992//993// This simulates the language rules: a function with return type U994// that does `return R()` requires R to be implicitly convertible to995// U, and uses that path for the conversion, even U Result has an996// explicit constructor from R.997value(ImplicitCast_<U>(internal::as_const(input_value))) {}998999// As above, but for the case where we're moving from the ReturnAction1000// object because it's being used as a OnceAction.1001explicit State(R&& input_value_in)1002: input_value(std::move(input_value_in)),1003// For the same reason as above we make an implicit conversion to U1004// before initializing the value.1005//1006// Unlike above we provide the input value as an rvalue to the1007// implicit conversion because this is a OnceAction: it's fine if it1008// wants to consume the input value.1009value(ImplicitCast_<U>(std::move(input_value))) {}10101011// A copy of the value originally provided by the user. We retain this in1012// addition to the value of the mock function's result type below in case1013// the latter is a reference-like type. See the std::string_view example1014// in the documentation on Return.1015R input_value;10161017// The value we actually return, as the type returned by the mock function1018// itself.1019//1020// We eagerly initialize this here, rather than lazily doing the implicit1021// conversion automatically each time Perform is called, for historical1022// reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126)1023// made the Action<U()> conversion operator eagerly convert the R value to1024// U, but without keeping the R alive. This broke the use case discussed1025// in the documentation for Return, making reference-like types such as1026// std::string_view not safe to use as U where the input type R is a1027// value-like type such as std::string.1028//1029// The example the commit gave was not very clear, nor was the issue1030// thread (https://github.com/google/googlemock/issues/86), but it seems1031// the worry was about reference-like input types R that flatten to a1032// value-like type U when being implicitly converted. An example of this1033// is std::vector<bool>::reference, which is often a proxy type with an1034// reference to the underlying vector:1035//1036// // Helper method: have the mock function return bools according1037// // to the supplied script.1038// void SetActions(MockFunction<bool(size_t)>& mock,1039// const std::vector<bool>& script) {1040// for (size_t i = 0; i < script.size(); ++i) {1041// EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i]));1042// }1043// }1044//1045// TEST(Foo, Bar) {1046// // Set actions using a temporary vector, whose operator[]1047// // returns proxy objects that references that will be1048// // dangling once the call to SetActions finishes and the1049// // vector is destroyed.1050// MockFunction<bool(size_t)> mock;1051// SetActions(mock, {false, true});1052//1053// EXPECT_FALSE(mock.AsStdFunction()(0));1054// EXPECT_TRUE(mock.AsStdFunction()(1));1055// }1056//1057// This eager conversion helps with a simple case like this, but doesn't1058// fully make these types work in general. For example the following still1059// uses a dangling reference:1060//1061// TEST(Foo, Baz) {1062// MockFunction<std::vector<std::string>()> mock;1063//1064// // Return the same vector twice, and then the empty vector1065// // thereafter.1066// auto action = Return(std::initializer_list<std::string>{1067// "taco", "burrito",1068// });1069//1070// EXPECT_CALL(mock, Call)1071// .WillOnce(action)1072// .WillOnce(action)1073// .WillRepeatedly(Return(std::vector<std::string>{}));1074//1075// EXPECT_THAT(mock.AsStdFunction()(),1076// ElementsAre("taco", "burrito"));1077// EXPECT_THAT(mock.AsStdFunction()(),1078// ElementsAre("taco", "burrito"));1079// EXPECT_THAT(mock.AsStdFunction()(), IsEmpty());1080// }1081//1082U value;1083};10841085const std::shared_ptr<State> state_;1086};10871088R value_;1089};10901091// A specialization of ReturnAction<R> when R is ByMoveWrapper<T> for some T.1092//1093// This version applies the type system-defeating hack of moving from T even in1094// the const call operator, checking at runtime that it isn't called more than1095// once, since the user has declared their intent to do so by using ByMove.1096template <typename T>1097class ReturnAction<ByMoveWrapper<T>> final {1098public:1099explicit ReturnAction(ByMoveWrapper<T> wrapper)1100: state_(new State(std::move(wrapper.payload))) {}11011102T operator()() const {1103GTEST_CHECK_(!state_->called)1104<< "A ByMove() action must be performed at most once.";11051106state_->called = true;1107return std::move(state_->value);1108}11091110private:1111// We store our state on the heap so that we are copyable as required by1112// Action, despite the fact that we are stateful and T may not be copyable.1113struct State {1114explicit State(T&& value_in) : value(std::move(value_in)) {}11151116T value;1117bool called = false;1118};11191120const std::shared_ptr<State> state_;1121};11221123// Implements the ReturnNull() action.1124class ReturnNullAction {1125public:1126// Allows ReturnNull() to be used in any pointer-returning function. In C++111127// this is enforced by returning nullptr, and in non-C++11 by asserting a1128// pointer type on compile time.1129template <typename Result, typename ArgumentTuple>1130static Result Perform(const ArgumentTuple&) {1131return nullptr;1132}1133};11341135// Implements the Return() action.1136class ReturnVoidAction {1137public:1138// Allows Return() to be used in any void-returning function.1139template <typename Result, typename ArgumentTuple>1140static void Perform(const ArgumentTuple&) {1141static_assert(std::is_void<Result>::value, "Result should be void.");1142}1143};11441145// Implements the polymorphic ReturnRef(x) action, which can be used1146// in any function that returns a reference to the type of x,1147// regardless of the argument types.1148template <typename T>1149class ReturnRefAction {1150public:1151// Constructs a ReturnRefAction object from the reference to be returned.1152explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT11531154// This template type conversion operator allows ReturnRef(x) to be1155// used in ANY function that returns a reference to x's type.1156template <typename F>1157operator Action<F>() const {1158typedef typename Function<F>::Result Result;1159// Asserts that the function return type is a reference. This1160// catches the user error of using ReturnRef(x) when Return(x)1161// should be used, and generates some helpful error message.1162static_assert(std::is_reference<Result>::value,1163"use Return instead of ReturnRef to return a value");1164return Action<F>(new Impl<F>(ref_));1165}11661167private:1168// Implements the ReturnRef(x) action for a particular function type F.1169template <typename F>1170class Impl : public ActionInterface<F> {1171public:1172typedef typename Function<F>::Result Result;1173typedef typename Function<F>::ArgumentTuple ArgumentTuple;11741175explicit Impl(T& ref) : ref_(ref) {} // NOLINT11761177Result Perform(const ArgumentTuple&) override { return ref_; }11781179private:1180T& ref_;1181};11821183T& ref_;1184};11851186// Implements the polymorphic ReturnRefOfCopy(x) action, which can be1187// used in any function that returns a reference to the type of x,1188// regardless of the argument types.1189template <typename T>1190class ReturnRefOfCopyAction {1191public:1192// Constructs a ReturnRefOfCopyAction object from the reference to1193// be returned.1194explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT11951196// This template type conversion operator allows ReturnRefOfCopy(x) to be1197// used in ANY function that returns a reference to x's type.1198template <typename F>1199operator Action<F>() const {1200typedef typename Function<F>::Result Result;1201// Asserts that the function return type is a reference. This1202// catches the user error of using ReturnRefOfCopy(x) when Return(x)1203// should be used, and generates some helpful error message.1204static_assert(std::is_reference<Result>::value,1205"use Return instead of ReturnRefOfCopy to return a value");1206return Action<F>(new Impl<F>(value_));1207}12081209private:1210// Implements the ReturnRefOfCopy(x) action for a particular function type F.1211template <typename F>1212class Impl : public ActionInterface<F> {1213public:1214typedef typename Function<F>::Result Result;1215typedef typename Function<F>::ArgumentTuple ArgumentTuple;12161217explicit Impl(const T& value) : value_(value) {} // NOLINT12181219Result Perform(const ArgumentTuple&) override { return value_; }12201221private:1222T value_;1223};12241225const T value_;1226};12271228// Implements the polymorphic ReturnRoundRobin(v) action, which can be1229// used in any function that returns the element_type of v.1230template <typename T>1231class ReturnRoundRobinAction {1232public:1233explicit ReturnRoundRobinAction(std::vector<T> values) {1234GTEST_CHECK_(!values.empty())1235<< "ReturnRoundRobin requires at least one element.";1236state_->values = std::move(values);1237}12381239template <typename... Args>1240T operator()(Args&&...) const {1241return state_->Next();1242}12431244private:1245struct State {1246T Next() {1247T ret_val = values[i++];1248if (i == values.size()) i = 0;1249return ret_val;1250}12511252std::vector<T> values;1253size_t i = 0;1254};1255std::shared_ptr<State> state_ = std::make_shared<State>();1256};12571258// Implements the polymorphic DoDefault() action.1259class DoDefaultAction {1260public:1261// This template type conversion operator allows DoDefault() to be1262// used in any function.1263template <typename F>1264operator Action<F>() const {1265return Action<F>();1266} // NOLINT1267};12681269// Implements the Assign action to set a given pointer referent to a1270// particular value.1271template <typename T1, typename T2>1272class AssignAction {1273public:1274AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}12751276template <typename Result, typename ArgumentTuple>1277void Perform(const ArgumentTuple& /* args */) const {1278*ptr_ = value_;1279}12801281private:1282T1* const ptr_;1283const T2 value_;1284};12851286#ifndef GTEST_OS_WINDOWS_MOBILE12871288// Implements the SetErrnoAndReturn action to simulate return from1289// various system calls and libc functions.1290template <typename T>1291class SetErrnoAndReturnAction {1292public:1293SetErrnoAndReturnAction(int errno_value, T result)1294: errno_(errno_value), result_(result) {}1295template <typename Result, typename ArgumentTuple>1296Result Perform(const ArgumentTuple& /* args */) const {1297errno = errno_;1298return result_;1299}13001301private:1302const int errno_;1303const T result_;1304};13051306#endif // !GTEST_OS_WINDOWS_MOBILE13071308// Implements the SetArgumentPointee<N>(x) action for any function1309// whose N-th argument (0-based) is a pointer to x's type.1310template <size_t N, typename A, typename = void>1311struct SetArgumentPointeeAction {1312A value;13131314template <typename... Args>1315void operator()(const Args&... args) const {1316*::std::get<N>(std::tie(args...)) = value;1317}1318};13191320// Implements the Invoke(object_ptr, &Class::Method) action.1321template <class Class, typename MethodPtr>1322struct InvokeMethodAction {1323Class* const obj_ptr;1324const MethodPtr method_ptr;13251326template <typename... Args>1327auto operator()(Args&&... args) const1328-> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {1329return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);1330}1331};13321333// Implements the InvokeWithoutArgs(f) action. The template argument1334// FunctionImpl is the implementation type of f, which can be either a1335// function pointer or a functor. InvokeWithoutArgs(f) can be used as an1336// Action<F> as long as f's type is compatible with F.1337template <typename FunctionImpl>1338struct InvokeWithoutArgsAction {1339FunctionImpl function_impl;13401341// Allows InvokeWithoutArgs(f) to be used as any action whose type is1342// compatible with f.1343template <typename... Args>1344auto operator()(const Args&...) -> decltype(function_impl()) {1345return function_impl();1346}1347};13481349// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.1350template <class Class, typename MethodPtr>1351struct InvokeMethodWithoutArgsAction {1352Class* const obj_ptr;1353const MethodPtr method_ptr;13541355using ReturnType =1356decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());13571358template <typename... Args>1359ReturnType operator()(const Args&...) const {1360return (obj_ptr->*method_ptr)();1361}1362};13631364// Implements the IgnoreResult(action) action.1365template <typename A>1366class IgnoreResultAction {1367public:1368explicit IgnoreResultAction(const A& action) : action_(action) {}13691370template <typename F>1371operator Action<F>() const {1372// Assert statement belongs here because this is the best place to verify1373// conditions on F. It produces the clearest error messages1374// in most compilers.1375// Impl really belongs in this scope as a local class but can't1376// because MSVC produces duplicate symbols in different translation units1377// in this case. Until MS fixes that bug we put Impl into the class scope1378// and put the typedef both here (for use in assert statement) and1379// in the Impl class. But both definitions must be the same.1380typedef typename internal::Function<F>::Result Result;13811382// Asserts at compile time that F returns void.1383static_assert(std::is_void<Result>::value, "Result type should be void.");13841385return Action<F>(new Impl<F>(action_));1386}13871388private:1389template <typename F>1390class Impl : public ActionInterface<F> {1391public:1392typedef typename internal::Function<F>::Result Result;1393typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;13941395explicit Impl(const A& action) : action_(action) {}13961397void Perform(const ArgumentTuple& args) override {1398// Performs the action and ignores its result.1399action_.Perform(args);1400}14011402private:1403// Type OriginalFunction is the same as F except that its return1404// type is IgnoredValue.1405typedef1406typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction;14071408const Action<OriginalFunction> action_;1409};14101411const A action_;1412};14131414template <typename InnerAction, size_t... I>1415struct WithArgsAction {1416InnerAction inner_action;14171418// The signature of the function as seen by the inner action, given an out1419// action with the given result and argument types.1420template <typename R, typename... Args>1421using InnerSignature =1422R(typename std::tuple_element<I, std::tuple<Args...>>::type...);14231424// Rather than a call operator, we must define conversion operators to1425// particular action types. This is necessary for embedded actions like1426// DoDefault(), which rely on an action conversion operators rather than1427// providing a call operator because even with a particular set of arguments1428// they don't have a fixed return type.14291430template <1431typename R, typename... Args,1432typename std::enable_if<1433std::is_convertible<InnerAction,1434// Unfortunately we can't use the InnerSignature1435// alias here; MSVC complains about the I1436// parameter pack not being expanded (error C3520)1437// despite it being expanded in the type alias.1438// TupleElement is also an MSVC workaround.1439// See its definition for details.1440OnceAction<R(internal::TupleElement<1441I, std::tuple<Args...>>...)>>::value,1442int>::type = 0>1443operator OnceAction<R(Args...)>() && { // NOLINT1444struct OA {1445OnceAction<InnerSignature<R, Args...>> inner_action;14461447R operator()(Args&&... args) && {1448return std::move(inner_action)1449.Call(std::get<I>(1450std::forward_as_tuple(std::forward<Args>(args)...))...);1451}1452};14531454return OA{std::move(inner_action)};1455}14561457// As above, but in the case where we want to create a OnceAction from a const1458// WithArgsAction. This is fine as long as the inner action doesn't need to1459// move any of its state to create a OnceAction.1460template <1461typename R, typename... Args,1462typename std::enable_if<1463std::is_convertible<const InnerAction&,1464OnceAction<R(internal::TupleElement<1465I, std::tuple<Args...>>...)>>::value,1466int>::type = 0>1467operator OnceAction<R(Args...)>() const& { // NOLINT1468struct OA {1469OnceAction<InnerSignature<R, Args...>> inner_action;14701471R operator()(Args&&... args) && {1472return std::move(inner_action)1473.Call(std::get<I>(1474std::forward_as_tuple(std::forward<Args>(args)...))...);1475}1476};14771478return OA{inner_action};1479}14801481template <1482typename R, typename... Args,1483typename std::enable_if<1484std::is_convertible<const InnerAction&,1485// Unfortunately we can't use the InnerSignature1486// alias here; MSVC complains about the I1487// parameter pack not being expanded (error C3520)1488// despite it being expanded in the type alias.1489// TupleElement is also an MSVC workaround.1490// See its definition for details.1491Action<R(internal::TupleElement<1492I, std::tuple<Args...>>...)>>::value,1493int>::type = 0>1494operator Action<R(Args...)>() const { // NOLINT1495Action<InnerSignature<R, Args...>> converted(inner_action);14961497return [converted](Args&&... args) -> R {1498return converted.Perform(std::forward_as_tuple(1499std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));1500};1501}1502};15031504template <typename... Actions>1505class DoAllAction;15061507// Base case: only a single action.1508template <typename FinalAction>1509class DoAllAction<FinalAction> {1510public:1511struct UserConstructorTag {};15121513template <typename T>1514explicit DoAllAction(UserConstructorTag, T&& action)1515: final_action_(std::forward<T>(action)) {}15161517// Rather than a call operator, we must define conversion operators to1518// particular action types. This is necessary for embedded actions like1519// DoDefault(), which rely on an action conversion operators rather than1520// providing a call operator because even with a particular set of arguments1521// they don't have a fixed return type.15221523// We support conversion to OnceAction whenever the sub-action does.1524template <typename R, typename... Args,1525typename std::enable_if<1526std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value,1527int>::type = 0>1528operator OnceAction<R(Args...)>() && { // NOLINT1529return std::move(final_action_);1530}15311532// We also support conversion to OnceAction whenever the sub-action supports1533// conversion to Action (since any Action can also be a OnceAction).1534template <1535typename R, typename... Args,1536typename std::enable_if<1537conjunction<1538negation<1539std::is_convertible<FinalAction, OnceAction<R(Args...)>>>,1540std::is_convertible<FinalAction, Action<R(Args...)>>>::value,1541int>::type = 0>1542operator OnceAction<R(Args...)>() && { // NOLINT1543return Action<R(Args...)>(std::move(final_action_));1544}15451546// We support conversion to Action whenever the sub-action does.1547template <1548typename R, typename... Args,1549typename std::enable_if<1550std::is_convertible<const FinalAction&, Action<R(Args...)>>::value,1551int>::type = 0>1552operator Action<R(Args...)>() const { // NOLINT1553return final_action_;1554}15551556private:1557FinalAction final_action_;1558};15591560// Recursive case: support N actions by calling the initial action and then1561// calling through to the base class containing N-1 actions.1562template <typename InitialAction, typename... OtherActions>1563class DoAllAction<InitialAction, OtherActions...>1564: private DoAllAction<OtherActions...> {1565private:1566using Base = DoAllAction<OtherActions...>;15671568// The type of reference that should be provided to an initial action for a1569// mocked function parameter of type T.1570//1571// There are two quirks here:1572//1573// * Unlike most forwarding functions, we pass scalars through by value.1574// This isn't strictly necessary because an lvalue reference would work1575// fine too and be consistent with other non-reference types, but it's1576// perhaps less surprising.1577//1578// For example if the mocked function has signature void(int), then it1579// might seem surprising for the user's initial action to need to be1580// convertible to Action<void(const int&)>. This is perhaps less1581// surprising for a non-scalar type where there may be a performance1582// impact, or it might even be impossible, to pass by value.1583//1584// * More surprisingly, `const T&` is often not a const reference type.1585// By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to1586// U& or U&& for some non-scalar type U, then InitialActionArgType<T> is1587// U&. In other words, we may hand over a non-const reference.1588//1589// So for example, given some non-scalar type Obj we have the following1590// mappings:1591//1592// T InitialActionArgType<T>1593// ------- -----------------------1594// Obj const Obj&1595// Obj& Obj&1596// Obj&& Obj&1597// const Obj const Obj&1598// const Obj& const Obj&1599// const Obj&& const Obj&1600//1601// In other words, the initial actions get a mutable view of an non-scalar1602// argument if and only if the mock function itself accepts a non-const1603// reference type. They are never given an rvalue reference to an1604// non-scalar type.1605//1606// This situation makes sense if you imagine use with a matcher that is1607// designed to write through a reference. For example, if the caller wants1608// to fill in a reference argument and then return a canned value:1609//1610// EXPECT_CALL(mock, Call)1611// .WillOnce(DoAll(SetArgReferee<0>(17), Return(19)));1612//1613template <typename T>1614using InitialActionArgType =1615typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;16161617public:1618struct UserConstructorTag {};16191620template <typename T, typename... U>1621explicit DoAllAction(UserConstructorTag, T&& initial_action,1622U&&... other_actions)1623: Base({}, std::forward<U>(other_actions)...),1624initial_action_(std::forward<T>(initial_action)) {}16251626// We support conversion to OnceAction whenever both the initial action and1627// the rest support conversion to OnceAction.1628template <1629typename R, typename... Args,1630typename std::enable_if<1631conjunction<std::is_convertible<1632InitialAction,1633OnceAction<void(InitialActionArgType<Args>...)>>,1634std::is_convertible<Base, OnceAction<R(Args...)>>>::value,1635int>::type = 0>1636operator OnceAction<R(Args...)>() && { // NOLINT1637// Return an action that first calls the initial action with arguments1638// filtered through InitialActionArgType, then forwards arguments directly1639// to the base class to deal with the remaining actions.1640struct OA {1641OnceAction<void(InitialActionArgType<Args>...)> initial_action;1642OnceAction<R(Args...)> remaining_actions;16431644R operator()(Args... args) && {1645std::move(initial_action)1646.Call(static_cast<InitialActionArgType<Args>>(args)...);16471648return std::move(remaining_actions).Call(std::forward<Args>(args)...);1649}1650};16511652return OA{1653std::move(initial_action_),1654std::move(static_cast<Base&>(*this)),1655};1656}16571658// We also support conversion to OnceAction whenever the initial action1659// supports conversion to Action (since any Action can also be a OnceAction).1660//1661// The remaining sub-actions must also be compatible, but we don't need to1662// special case them because the base class deals with them.1663template <1664typename R, typename... Args,1665typename std::enable_if<1666conjunction<1667negation<std::is_convertible<1668InitialAction,1669OnceAction<void(InitialActionArgType<Args>...)>>>,1670std::is_convertible<InitialAction,1671Action<void(InitialActionArgType<Args>...)>>,1672std::is_convertible<Base, OnceAction<R(Args...)>>>::value,1673int>::type = 0>1674operator OnceAction<R(Args...)>() && { // NOLINT1675return DoAll(1676Action<void(InitialActionArgType<Args>...)>(std::move(initial_action_)),1677std::move(static_cast<Base&>(*this)));1678}16791680// We support conversion to Action whenever both the initial action and the1681// rest support conversion to Action.1682template <1683typename R, typename... Args,1684typename std::enable_if<1685conjunction<1686std::is_convertible<const InitialAction&,1687Action<void(InitialActionArgType<Args>...)>>,1688std::is_convertible<const Base&, Action<R(Args...)>>>::value,1689int>::type = 0>1690operator Action<R(Args...)>() const { // NOLINT1691// Return an action that first calls the initial action with arguments1692// filtered through InitialActionArgType, then forwards arguments directly1693// to the base class to deal with the remaining actions.1694struct OA {1695Action<void(InitialActionArgType<Args>...)> initial_action;1696Action<R(Args...)> remaining_actions;16971698R operator()(Args... args) const {1699initial_action.Perform(std::forward_as_tuple(1700static_cast<InitialActionArgType<Args>>(args)...));17011702return remaining_actions.Perform(1703std::forward_as_tuple(std::forward<Args>(args)...));1704}1705};17061707return OA{1708initial_action_,1709static_cast<const Base&>(*this),1710};1711}17121713private:1714InitialAction initial_action_;1715};17161717template <typename T, typename... Params>1718struct ReturnNewAction {1719T* operator()() const {1720return internal::Apply(1721[](const Params&... unpacked_params) {1722return new T(unpacked_params...);1723},1724params);1725}1726std::tuple<Params...> params;1727};17281729template <size_t k>1730struct ReturnArgAction {1731template <typename... Args,1732typename = typename std::enable_if<(k < sizeof...(Args))>::type>1733auto operator()(Args&&... args) const -> decltype(std::get<k>(1734std::forward_as_tuple(std::forward<Args>(args)...))) {1735return std::get<k>(std::forward_as_tuple(std::forward<Args>(args)...));1736}1737};17381739template <size_t k, typename Ptr>1740struct SaveArgAction {1741Ptr pointer;17421743template <typename... Args>1744void operator()(const Args&... args) const {1745*pointer = std::get<k>(std::tie(args...));1746}1747};17481749template <size_t k, typename Ptr>1750struct SaveArgByMoveAction {1751Ptr pointer;17521753template <typename... Args>1754void operator()(Args&&... args) const {1755*pointer = std::move(std::get<k>(std::tie(args...)));1756}1757};17581759template <size_t k, typename Ptr>1760struct SaveArgPointeeAction {1761Ptr pointer;17621763template <typename... Args>1764void operator()(const Args&... args) const {1765*pointer = *std::get<k>(std::tie(args...));1766}1767};17681769template <size_t k, typename T>1770struct SetArgRefereeAction {1771T value;17721773template <typename... Args>1774void operator()(Args&&... args) const {1775using argk_type =1776typename ::std::tuple_element<k, std::tuple<Args...>>::type;1777static_assert(std::is_lvalue_reference<argk_type>::value,1778"Argument must be a reference type.");1779std::get<k>(std::tie(args...)) = value;1780}1781};17821783template <size_t k, typename I1, typename I2>1784struct SetArrayArgumentAction {1785I1 first;1786I2 last;17871788template <typename... Args>1789void operator()(const Args&... args) const {1790auto value = std::get<k>(std::tie(args...));1791for (auto it = first; it != last; ++it, (void)++value) {1792*value = *it;1793}1794}1795};17961797template <size_t k>1798struct DeleteArgAction {1799template <typename... Args>1800void operator()(const Args&... args) const {1801delete std::get<k>(std::tie(args...));1802}1803};18041805template <typename Ptr>1806struct ReturnPointeeAction {1807Ptr pointer;1808template <typename... Args>1809auto operator()(const Args&...) const -> decltype(*pointer) {1810return *pointer;1811}1812};18131814#if GTEST_HAS_EXCEPTIONS1815template <typename T>1816struct ThrowAction {1817T exception;1818// We use a conversion operator to adapt to any return type.1819template <typename R, typename... Args>1820operator Action<R(Args...)>() const { // NOLINT1821T copy = exception;1822return [copy](Args...) -> R { throw copy; };1823}1824};1825struct RethrowAction {1826std::exception_ptr exception;1827template <typename R, typename... Args>1828operator Action<R(Args...)>() const { // NOLINT1829return [ex = exception](Args...) -> R { std::rethrow_exception(ex); };1830}1831};1832#endif // GTEST_HAS_EXCEPTIONS18331834} // namespace internal18351836// An Unused object can be implicitly constructed from ANY value.1837// This is handy when defining actions that ignore some or all of the1838// mock function arguments. For example, given1839//1840// MOCK_METHOD3(Foo, double(const string& label, double x, double y));1841// MOCK_METHOD3(Bar, double(int index, double x, double y));1842//1843// instead of1844//1845// double DistanceToOriginWithLabel(const string& label, double x, double y) {1846// return sqrt(x*x + y*y);1847// }1848// double DistanceToOriginWithIndex(int index, double x, double y) {1849// return sqrt(x*x + y*y);1850// }1851// ...1852// EXPECT_CALL(mock, Foo("abc", _, _))1853// .WillOnce(Invoke(DistanceToOriginWithLabel));1854// EXPECT_CALL(mock, Bar(5, _, _))1855// .WillOnce(Invoke(DistanceToOriginWithIndex));1856//1857// you could write1858//1859// // We can declare any uninteresting argument as Unused.1860// double DistanceToOrigin(Unused, double x, double y) {1861// return sqrt(x*x + y*y);1862// }1863// ...1864// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));1865// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));1866typedef internal::IgnoredValue Unused;18671868// Creates an action that does actions a1, a2, ..., sequentially in1869// each invocation. All but the last action will have a readonly view of the1870// arguments.1871template <typename... Action>1872internal::DoAllAction<typename std::decay<Action>::type...> DoAll(1873Action&&... action) {1874return internal::DoAllAction<typename std::decay<Action>::type...>(1875{}, std::forward<Action>(action)...);1876}18771878// WithArg<k>(an_action) creates an action that passes the k-th1879// (0-based) argument of the mock function to an_action and performs1880// it. It adapts an action accepting one argument to one that accepts1881// multiple arguments. For convenience, we also provide1882// WithArgs<k>(an_action) (defined below) as a synonym.1883template <size_t k, typename InnerAction>1884internal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg(1885InnerAction&& action) {1886return {std::forward<InnerAction>(action)};1887}18881889// WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes1890// the selected arguments of the mock function to an_action and1891// performs it. It serves as an adaptor between actions with1892// different argument lists.1893template <size_t k, size_t... ks, typename InnerAction>1894internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>1895WithArgs(InnerAction&& action) {1896return {std::forward<InnerAction>(action)};1897}18981899// WithoutArgs(inner_action) can be used in a mock function with a1900// non-empty argument list to perform inner_action, which takes no1901// argument. In other words, it adapts an action accepting no1902// argument to one that accepts (and ignores) arguments.1903template <typename InnerAction>1904internal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs(1905InnerAction&& action) {1906return {std::forward<InnerAction>(action)};1907}19081909// Creates an action that returns a value.1910//1911// The returned type can be used with a mock function returning a non-void,1912// non-reference type U as follows:1913//1914// * If R is convertible to U and U is move-constructible, then the action can1915// be used with WillOnce.1916//1917// * If const R& is convertible to U and U is copy-constructible, then the1918// action can be used with both WillOnce and WillRepeatedly.1919//1920// The mock expectation contains the R value from which the U return value is1921// constructed (a move/copy of the argument to Return). This means that the R1922// value will survive at least until the mock object's expectations are cleared1923// or the mock object is destroyed, meaning that U can safely be a1924// reference-like type such as std::string_view:1925//1926// // The mock function returns a view of a copy of the string fed to1927// // Return. The view is valid even after the action is performed.1928// MockFunction<std::string_view()> mock;1929// EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco")));1930// const std::string_view result = mock.AsStdFunction()();1931// EXPECT_EQ("taco", result);1932//1933template <typename R>1934internal::ReturnAction<R> Return(R value) {1935return internal::ReturnAction<R>(std::move(value));1936}19371938// Creates an action that returns NULL.1939inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {1940return MakePolymorphicAction(internal::ReturnNullAction());1941}19421943// Creates an action that returns from a void function.1944inline PolymorphicAction<internal::ReturnVoidAction> Return() {1945return MakePolymorphicAction(internal::ReturnVoidAction());1946}19471948// Creates an action that returns the reference to a variable.1949template <typename R>1950inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT1951return internal::ReturnRefAction<R>(x);1952}19531954// Prevent using ReturnRef on reference to temporary.1955template <typename R, R* = nullptr>1956internal::ReturnRefAction<R> ReturnRef(R&&) = delete;19571958// Creates an action that returns the reference to a copy of the1959// argument. The copy is created when the action is constructed and1960// lives as long as the action.1961template <typename R>1962inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {1963return internal::ReturnRefOfCopyAction<R>(x);1964}19651966// DEPRECATED: use Return(x) directly with WillOnce.1967//1968// Modifies the parent action (a Return() action) to perform a move of the1969// argument instead of a copy.1970// Return(ByMove()) actions can only be executed once and will assert this1971// invariant.1972template <typename R>1973internal::ByMoveWrapper<R> ByMove(R x) {1974return internal::ByMoveWrapper<R>(std::move(x));1975}19761977// Creates an action that returns an element of `vals`. Calling this action will1978// repeatedly return the next value from `vals` until it reaches the end and1979// will restart from the beginning.1980template <typename T>1981internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {1982return internal::ReturnRoundRobinAction<T>(std::move(vals));1983}19841985// Creates an action that returns an element of `vals`. Calling this action will1986// repeatedly return the next value from `vals` until it reaches the end and1987// will restart from the beginning.1988template <typename T>1989internal::ReturnRoundRobinAction<T> ReturnRoundRobin(1990std::initializer_list<T> vals) {1991return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));1992}19931994// Creates an action that does the default action for the give mock function.1995inline internal::DoDefaultAction DoDefault() {1996return internal::DoDefaultAction();1997}19981999// Creates an action that sets the variable pointed by the N-th2000// (0-based) function argument to 'value'.2001template <size_t N, typename T>2002internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {2003return {std::move(value)};2004}20052006// The following version is DEPRECATED.2007template <size_t N, typename T>2008internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {2009return {std::move(value)};2010}20112012// Creates an action that sets a pointer referent to a given value.2013template <typename T1, typename T2>2014PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) {2015return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));2016}20172018#ifndef GTEST_OS_WINDOWS_MOBILE20192020// Creates an action that sets errno and returns the appropriate error.2021template <typename T>2022PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn(2023int errval, T result) {2024return MakePolymorphicAction(2025internal::SetErrnoAndReturnAction<T>(errval, result));2026}20272028#endif // !GTEST_OS_WINDOWS_MOBILE20292030// Various overloads for Invoke().20312032// Legacy function.2033// Actions can now be implicitly constructed from callables. No need to create2034// wrapper objects.2035// This function exists for backwards compatibility.2036template <typename FunctionImpl>2037typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {2038return std::forward<FunctionImpl>(function_impl);2039}20402041// Creates an action that invokes the given method on the given object2042// with the mock function's arguments.2043template <class Class, typename MethodPtr>2044internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,2045MethodPtr method_ptr) {2046return {obj_ptr, method_ptr};2047}20482049// Creates an action that invokes 'function_impl' with no argument.2050template <typename FunctionImpl>2051internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>2052InvokeWithoutArgs(FunctionImpl function_impl) {2053return {std::move(function_impl)};2054}20552056// Creates an action that invokes the given method on the given object2057// with no argument.2058template <class Class, typename MethodPtr>2059internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(2060Class* obj_ptr, MethodPtr method_ptr) {2061return {obj_ptr, method_ptr};2062}20632064// Creates an action that performs an_action and throws away its2065// result. In other words, it changes the return type of an_action to2066// void. an_action MUST NOT return void, or the code won't compile.2067template <typename A>2068inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {2069return internal::IgnoreResultAction<A>(an_action);2070}20712072// Creates a reference wrapper for the given L-value. If necessary,2073// you can explicitly specify the type of the reference. For example,2074// suppose 'derived' is an object of type Derived, ByRef(derived)2075// would wrap a Derived&. If you want to wrap a const Base& instead,2076// where Base is a base class of Derived, just write:2077//2078// ByRef<const Base>(derived)2079//2080// N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.2081// However, it may still be used for consistency with ByMove().2082template <typename T>2083inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT2084return ::std::reference_wrapper<T>(l_value);2085}20862087// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new2088// instance of type T, constructed on the heap with constructor arguments2089// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.2090template <typename T, typename... Params>2091internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(2092Params&&... params) {2093return {std::forward_as_tuple(std::forward<Params>(params)...)};2094}20952096// Action ReturnArg<k>() returns the k-th argument of the mock function.2097template <size_t k>2098internal::ReturnArgAction<k> ReturnArg() {2099return {};2100}21012102// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the2103// mock function to *pointer.2104template <size_t k, typename Ptr>2105internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {2106return {pointer};2107}21082109// Action SaveArgByMove<k>(pointer) moves the k-th (0-based) argument of the2110// mock function into *pointer.2111template <size_t k, typename Ptr>2112internal::SaveArgByMoveAction<k, Ptr> SaveArgByMove(Ptr pointer) {2113return {pointer};2114}21152116// Action SaveArgPointee<k>(pointer) saves the value pointed to2117// by the k-th (0-based) argument of the mock function to *pointer.2118template <size_t k, typename Ptr>2119internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {2120return {pointer};2121}21222123// Action SetArgReferee<k>(value) assigns 'value' to the variable2124// referenced by the k-th (0-based) argument of the mock function.2125template <size_t k, typename T>2126internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(2127T&& value) {2128return {std::forward<T>(value)};2129}21302131// Action SetArrayArgument<k>(first, last) copies the elements in2132// source range [first, last) to the array pointed to by the k-th2133// (0-based) argument, which can be either a pointer or an2134// iterator. The action does not take ownership of the elements in the2135// source range.2136template <size_t k, typename I1, typename I2>2137internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,2138I2 last) {2139return {first, last};2140}21412142// Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock2143// function.2144template <size_t k>2145internal::DeleteArgAction<k> DeleteArg() {2146return {};2147}21482149// This action returns the value pointed to by 'pointer'.2150template <typename Ptr>2151internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {2152return {pointer};2153}21542155#if GTEST_HAS_EXCEPTIONS2156// Action Throw(exception) can be used in a mock function of any type2157// to throw the given exception. Any copyable value can be thrown,2158// except for std::exception_ptr, which is likely a mistake if2159// thrown directly.2160template <typename T>2161typename std::enable_if<2162!std::is_base_of<std::exception_ptr, typename std::decay<T>::type>::value,2163internal::ThrowAction<typename std::decay<T>::type>>::type2164Throw(T&& exception) {2165return {std::forward<T>(exception)};2166}2167// Action Rethrow(exception_ptr) can be used in a mock function of any type2168// to rethrow any exception_ptr. Note that the same object is thrown each time.2169inline internal::RethrowAction Rethrow(std::exception_ptr exception) {2170return {std::move(exception)};2171}2172#endif // GTEST_HAS_EXCEPTIONS21732174namespace internal {21752176// A macro from the ACTION* family (defined later in gmock-generated-actions.h)2177// defines an action that can be used in a mock function. Typically,2178// these actions only care about a subset of the arguments of the mock2179// function. For example, if such an action only uses the second2180// argument, it can be used in any mock function that takes >= 22181// arguments where the type of the second argument is compatible.2182//2183// Therefore, the action implementation must be prepared to take more2184// arguments than it needs. The ExcessiveArg type is used to2185// represent those excessive arguments. In order to keep the compiler2186// error messages tractable, we define it in the testing namespace2187// instead of testing::internal. However, this is an INTERNAL TYPE2188// and subject to change without notice, so a user MUST NOT USE THIS2189// TYPE DIRECTLY.2190struct ExcessiveArg {};21912192// Builds an implementation of an Action<> for some particular signature, using2193// a class defined by an ACTION* macro.2194template <typename F, typename Impl>2195struct ActionImpl;21962197template <typename Impl>2198struct ImplBase {2199struct Holder {2200// Allows each copy of the Action<> to get to the Impl.2201explicit operator const Impl&() const { return *ptr; }2202std::shared_ptr<Impl> ptr;2203};2204using type = typename std::conditional<std::is_constructible<Impl>::value,2205Impl, Holder>::type;2206};22072208template <typename R, typename... Args, typename Impl>2209struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {2210using Base = typename ImplBase<Impl>::type;2211using function_type = R(Args...);2212using args_type = std::tuple<Args...>;22132214ActionImpl() = default; // Only defined if appropriate for Base.2215explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} {}22162217R operator()(Args&&... arg) const {2218static constexpr size_t kMaxArgs =2219sizeof...(Args) <= 10 ? sizeof...(Args) : 10;2220return Apply(std::make_index_sequence<kMaxArgs>{},2221std::make_index_sequence<10 - kMaxArgs>{},2222args_type{std::forward<Args>(arg)...});2223}22242225template <std::size_t... arg_id, std::size_t... excess_id>2226R Apply(std::index_sequence<arg_id...>, std::index_sequence<excess_id...>,2227const args_type& args) const {2228// Impl need not be specific to the signature of action being implemented;2229// only the implementing function body needs to have all of the specific2230// types instantiated. Up to 10 of the args that are provided by the2231// args_type get passed, followed by a dummy of unspecified type for the2232// remainder up to 10 explicit args.2233static constexpr ExcessiveArg kExcessArg{};2234return static_cast<const Impl&>(*this)2235.template gmock_PerformImpl<2236/*function_type=*/function_type, /*return_type=*/R,2237/*args_type=*/args_type,2238/*argN_type=*/2239typename std::tuple_element<arg_id, args_type>::type...>(2240/*args=*/args, std::get<arg_id>(args)...,2241((void)excess_id, kExcessArg)...);2242}2243};22442245// Stores a default-constructed Impl as part of the Action<>'s2246// std::function<>. The Impl should be trivial to copy.2247template <typename F, typename Impl>2248::testing::Action<F> MakeAction() {2249return ::testing::Action<F>(ActionImpl<F, Impl>());2250}22512252// Stores just the one given instance of Impl.2253template <typename F, typename Impl>2254::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {2255return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl)));2256}22572258#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \2259, [[maybe_unused]] const arg##i##_type& arg##i2260#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \2261[[maybe_unused]] const args_type& args GMOCK_PP_REPEAT( \2262GMOCK_INTERNAL_ARG_UNUSED, , 10)22632264#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i2265#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \2266const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)22672268#define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type2269#define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \2270GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))22712272#define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type2273#define GMOCK_ACTION_TYPENAME_PARAMS_(params) \2274GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))22752276#define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type2277#define GMOCK_ACTION_TYPE_PARAMS_(params) \2278GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))22792280#define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \2281, param##_type gmock_p##i2282#define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \2283GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))22842285#define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \2286, std::forward<param##_type>(gmock_p##i)2287#define GMOCK_ACTION_GVALUE_PARAMS_(params) \2288GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))22892290#define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \2291, param(::std::forward<param##_type>(gmock_p##i))2292#define GMOCK_ACTION_INIT_PARAMS_(params) \2293GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))22942295#define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;2296#define GMOCK_ACTION_FIELD_PARAMS_(params) \2297GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)22982299#define GMOCK_INTERNAL_ACTION(name, full_name, params) \2300template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \2301class full_name { \2302public: \2303explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \2304: impl_(std::make_shared<gmock_Impl>( \2305GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \2306full_name(const full_name&) = default; \2307full_name(full_name&&) noexcept = default; \2308template <typename F> \2309operator ::testing::Action<F>() const { \2310return ::testing::internal::MakeAction<F>(impl_); \2311} \2312\2313private: \2314class gmock_Impl { \2315public: \2316explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \2317: GMOCK_ACTION_INIT_PARAMS_(params) {} \2318template <typename function_type, typename return_type, \2319typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \2320return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \2321GMOCK_ACTION_FIELD_PARAMS_(params) \2322}; \2323std::shared_ptr<const gmock_Impl> impl_; \2324}; \2325template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \2326[[nodiscard]] inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \2327GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)); \2328template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \2329inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \2330GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \2331return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \2332GMOCK_ACTION_GVALUE_PARAMS_(params)); \2333} \2334template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \2335template <typename function_type, typename return_type, typename args_type, \2336GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \2337return_type \2338full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \2339GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const23402341} // namespace internal23422343// Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.2344#define ACTION(name) \2345class name##Action { \2346public: \2347explicit name##Action() noexcept {} \2348name##Action(const name##Action&) noexcept {} \2349template <typename F> \2350operator ::testing::Action<F>() const { \2351return ::testing::internal::MakeAction<F, gmock_Impl>(); \2352} \2353\2354private: \2355class gmock_Impl { \2356public: \2357template <typename function_type, typename return_type, \2358typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \2359return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \2360}; \2361}; \2362[[nodiscard]] inline name##Action name(); \2363inline name##Action name() { return name##Action(); } \2364template <typename function_type, typename return_type, typename args_type, \2365GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \2366return_type name##Action::gmock_Impl::gmock_PerformImpl( \2367GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const23682369#define ACTION_P(name, ...) \2370GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))23712372#define ACTION_P2(name, ...) \2373GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))23742375#define ACTION_P3(name, ...) \2376GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))23772378#define ACTION_P4(name, ...) \2379GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))23802381#define ACTION_P5(name, ...) \2382GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))23832384#define ACTION_P6(name, ...) \2385GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))23862387#define ACTION_P7(name, ...) \2388GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))23892390#define ACTION_P8(name, ...) \2391GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))23922393#define ACTION_P9(name, ...) \2394GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))23952396#define ACTION_P10(name, ...) \2397GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))23982399} // namespace testing24002401GTEST_DISABLE_MSC_WARNINGS_POP_() // 410024022403#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_240424052406