xref: /llvm-project/third-party/unittest/googlemock/include/gmock/gmock-actions.h (revision a866ce789eb99da4d7a486eeb60a53be6c75f4fd)
1a11cd0d9STom Stellard // Copyright 2007, Google Inc.
2a11cd0d9STom Stellard // All rights reserved.
3a11cd0d9STom Stellard //
4a11cd0d9STom Stellard // Redistribution and use in source and binary forms, with or without
5a11cd0d9STom Stellard // modification, are permitted provided that the following conditions are
6a11cd0d9STom Stellard // met:
7a11cd0d9STom Stellard //
8a11cd0d9STom Stellard //     * Redistributions of source code must retain the above copyright
9a11cd0d9STom Stellard // notice, this list of conditions and the following disclaimer.
10a11cd0d9STom Stellard //     * Redistributions in binary form must reproduce the above
11a11cd0d9STom Stellard // copyright notice, this list of conditions and the following disclaimer
12a11cd0d9STom Stellard // in the documentation and/or other materials provided with the
13a11cd0d9STom Stellard // distribution.
14a11cd0d9STom Stellard //     * Neither the name of Google Inc. nor the names of its
15a11cd0d9STom Stellard // contributors may be used to endorse or promote products derived from
16a11cd0d9STom Stellard // this software without specific prior written permission.
17a11cd0d9STom Stellard //
18a11cd0d9STom Stellard // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19a11cd0d9STom Stellard // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20a11cd0d9STom Stellard // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21a11cd0d9STom Stellard // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22a11cd0d9STom Stellard // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23a11cd0d9STom Stellard // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24a11cd0d9STom Stellard // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25a11cd0d9STom Stellard // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26a11cd0d9STom Stellard // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27a11cd0d9STom Stellard // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28a11cd0d9STom Stellard // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29a11cd0d9STom Stellard 
30a11cd0d9STom Stellard // Google Mock - a framework for writing C++ mock classes.
31a11cd0d9STom Stellard //
32*a866ce78SHaowei Wu // The ACTION* family of macros can be used in a namespace scope to
33*a866ce78SHaowei Wu // define custom actions easily.  The syntax:
34*a866ce78SHaowei Wu //
35*a866ce78SHaowei Wu //   ACTION(name) { statements; }
36*a866ce78SHaowei Wu //
37*a866ce78SHaowei Wu // will define an action with the given name that executes the
38*a866ce78SHaowei Wu // statements.  The value returned by the statements will be used as
39*a866ce78SHaowei Wu // the return value of the action.  Inside the statements, you can
40*a866ce78SHaowei Wu // refer to the K-th (0-based) argument of the mock function by
41*a866ce78SHaowei Wu // 'argK', and refer to its type by 'argK_type'.  For example:
42*a866ce78SHaowei Wu //
43*a866ce78SHaowei Wu //   ACTION(IncrementArg1) {
44*a866ce78SHaowei Wu //     arg1_type temp = arg1;
45*a866ce78SHaowei Wu //     return ++(*temp);
46*a866ce78SHaowei Wu //   }
47*a866ce78SHaowei Wu //
48*a866ce78SHaowei Wu // allows you to write
49*a866ce78SHaowei Wu //
50*a866ce78SHaowei Wu //   ...WillOnce(IncrementArg1());
51*a866ce78SHaowei Wu //
52*a866ce78SHaowei Wu // You can also refer to the entire argument tuple and its type by
53*a866ce78SHaowei Wu // 'args' and 'args_type', and refer to the mock function type and its
54*a866ce78SHaowei Wu // return type by 'function_type' and 'return_type'.
55*a866ce78SHaowei Wu //
56*a866ce78SHaowei Wu // Note that you don't need to specify the types of the mock function
57*a866ce78SHaowei Wu // arguments.  However rest assured that your code is still type-safe:
58*a866ce78SHaowei Wu // you'll get a compiler error if *arg1 doesn't support the ++
59*a866ce78SHaowei Wu // operator, or if the type of ++(*arg1) isn't compatible with the
60*a866ce78SHaowei Wu // mock function's return type, for example.
61*a866ce78SHaowei Wu //
62*a866ce78SHaowei Wu // Sometimes you'll want to parameterize the action.   For that you can use
63*a866ce78SHaowei Wu // another macro:
64*a866ce78SHaowei Wu //
65*a866ce78SHaowei Wu //   ACTION_P(name, param_name) { statements; }
66*a866ce78SHaowei Wu //
67*a866ce78SHaowei Wu // For example:
68*a866ce78SHaowei Wu //
69*a866ce78SHaowei Wu //   ACTION_P(Add, n) { return arg0 + n; }
70*a866ce78SHaowei Wu //
71*a866ce78SHaowei Wu // will allow you to write:
72*a866ce78SHaowei Wu //
73*a866ce78SHaowei Wu //   ...WillOnce(Add(5));
74*a866ce78SHaowei Wu //
75*a866ce78SHaowei Wu // Note that you don't need to provide the type of the parameter
76*a866ce78SHaowei Wu // either.  If you need to reference the type of a parameter named
77*a866ce78SHaowei Wu // 'foo', you can write 'foo_type'.  For example, in the body of
78*a866ce78SHaowei Wu // ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
79*a866ce78SHaowei Wu // of 'n'.
80*a866ce78SHaowei Wu //
81*a866ce78SHaowei Wu // We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
82*a866ce78SHaowei Wu // multi-parameter actions.
83*a866ce78SHaowei Wu //
84*a866ce78SHaowei Wu // For the purpose of typing, you can view
85*a866ce78SHaowei Wu //
86*a866ce78SHaowei Wu //   ACTION_Pk(Foo, p1, ..., pk) { ... }
87*a866ce78SHaowei Wu //
88*a866ce78SHaowei Wu // as shorthand for
89*a866ce78SHaowei Wu //
90*a866ce78SHaowei Wu //   template <typename p1_type, ..., typename pk_type>
91*a866ce78SHaowei Wu //   FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
92*a866ce78SHaowei Wu //
93*a866ce78SHaowei Wu // In particular, you can provide the template type arguments
94*a866ce78SHaowei Wu // explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
95*a866ce78SHaowei Wu // although usually you can rely on the compiler to infer the types
96*a866ce78SHaowei Wu // for you automatically.  You can assign the result of expression
97*a866ce78SHaowei Wu // Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
98*a866ce78SHaowei Wu // pk_type>.  This can be useful when composing actions.
99*a866ce78SHaowei Wu //
100*a866ce78SHaowei Wu // You can also overload actions with different numbers of parameters:
101*a866ce78SHaowei Wu //
102*a866ce78SHaowei Wu //   ACTION_P(Plus, a) { ... }
103*a866ce78SHaowei Wu //   ACTION_P2(Plus, a, b) { ... }
104*a866ce78SHaowei Wu //
105*a866ce78SHaowei Wu // While it's tempting to always use the ACTION* macros when defining
106*a866ce78SHaowei Wu // a new action, you should also consider implementing ActionInterface
107*a866ce78SHaowei Wu // or using MakePolymorphicAction() instead, especially if you need to
108*a866ce78SHaowei Wu // use the action a lot.  While these approaches require more work,
109*a866ce78SHaowei Wu // they give you more control on the types of the mock function
110*a866ce78SHaowei Wu // arguments and the action parameters, which in general leads to
111*a866ce78SHaowei Wu // better compiler error messages that pay off in the long run.  They
112*a866ce78SHaowei Wu // also allow overloading actions based on parameter types (as opposed
113*a866ce78SHaowei Wu // to just based on the number of parameters).
114*a866ce78SHaowei Wu //
115*a866ce78SHaowei Wu // CAVEAT:
116*a866ce78SHaowei Wu //
117*a866ce78SHaowei Wu // ACTION*() can only be used in a namespace scope as templates cannot be
118*a866ce78SHaowei Wu // declared inside of a local class.
119*a866ce78SHaowei Wu // Users can, however, define any local functors (e.g. a lambda) that
120*a866ce78SHaowei Wu // can be used as actions.
121*a866ce78SHaowei Wu //
122*a866ce78SHaowei Wu // MORE INFORMATION:
123*a866ce78SHaowei Wu //
124*a866ce78SHaowei Wu // To learn more about using these macros, please search for 'ACTION' on
125*a866ce78SHaowei Wu // https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md
126a11cd0d9STom Stellard 
127a11cd0d9STom Stellard // IWYU pragma: private, include "gmock/gmock.h"
128a11cd0d9STom Stellard // IWYU pragma: friend gmock/.*
129a11cd0d9STom Stellard 
130*a866ce78SHaowei Wu #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
131*a866ce78SHaowei Wu #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
132a11cd0d9STom Stellard 
133a11cd0d9STom Stellard #ifndef _WIN32_WCE
134a11cd0d9STom Stellard #include <errno.h>
135a11cd0d9STom Stellard #endif
136a11cd0d9STom Stellard 
137a11cd0d9STom Stellard #include <algorithm>
138a11cd0d9STom Stellard #include <functional>
139a11cd0d9STom Stellard #include <memory>
140a11cd0d9STom Stellard #include <string>
141*a866ce78SHaowei Wu #include <tuple>
142a11cd0d9STom Stellard #include <type_traits>
143a11cd0d9STom Stellard #include <utility>
144a11cd0d9STom Stellard 
145a11cd0d9STom Stellard #include "gmock/internal/gmock-internal-utils.h"
146a11cd0d9STom Stellard #include "gmock/internal/gmock-port.h"
147*a866ce78SHaowei Wu #include "gmock/internal/gmock-pp.h"
148a11cd0d9STom Stellard 
149*a866ce78SHaowei Wu GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
150a11cd0d9STom Stellard 
151a11cd0d9STom Stellard namespace testing {
152a11cd0d9STom Stellard 
153a11cd0d9STom Stellard // To implement an action Foo, define:
154a11cd0d9STom Stellard //   1. a class FooAction that implements the ActionInterface interface, and
155a11cd0d9STom Stellard //   2. a factory function that creates an Action object from a
156a11cd0d9STom Stellard //      const FooAction*.
157a11cd0d9STom Stellard //
158a11cd0d9STom Stellard // The two-level delegation design follows that of Matcher, providing
159a11cd0d9STom Stellard // consistency for extension developers.  It also eases ownership
160a11cd0d9STom Stellard // management as Action objects can now be copied like plain values.
161a11cd0d9STom Stellard 
162a11cd0d9STom Stellard namespace internal {
163a11cd0d9STom Stellard 
164a11cd0d9STom Stellard // BuiltInDefaultValueGetter<T, true>::Get() returns a
165a11cd0d9STom Stellard // default-constructed T value.  BuiltInDefaultValueGetter<T,
166a11cd0d9STom Stellard // false>::Get() crashes with an error.
167a11cd0d9STom Stellard //
168a11cd0d9STom Stellard // This primary template is used when kDefaultConstructible is true.
169a11cd0d9STom Stellard template <typename T, bool kDefaultConstructible>
170a11cd0d9STom Stellard struct BuiltInDefaultValueGetter {
GetBuiltInDefaultValueGetter171a11cd0d9STom Stellard   static T Get() { return T(); }
172a11cd0d9STom Stellard };
173a11cd0d9STom Stellard template <typename T>
174a11cd0d9STom Stellard struct BuiltInDefaultValueGetter<T, false> {
175a11cd0d9STom Stellard   static T Get() {
176a11cd0d9STom Stellard     Assert(false, __FILE__, __LINE__,
177a11cd0d9STom Stellard            "Default action undefined for the function return type.");
178a11cd0d9STom Stellard     return internal::Invalid<T>();
179a11cd0d9STom Stellard     // The above statement will never be reached, but is required in
180a11cd0d9STom Stellard     // order for this function to compile.
181a11cd0d9STom Stellard   }
182a11cd0d9STom Stellard };
183a11cd0d9STom Stellard 
184a11cd0d9STom Stellard // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
185a11cd0d9STom Stellard // for type T, which is NULL when T is a raw pointer type, 0 when T is
186a11cd0d9STom Stellard // a numeric type, false when T is bool, or "" when T is string or
187a11cd0d9STom Stellard // std::string.  In addition, in C++11 and above, it turns a
188a11cd0d9STom Stellard // default-constructed T value if T is default constructible.  For any
189a11cd0d9STom Stellard // other type T, the built-in default T value is undefined, and the
190a11cd0d9STom Stellard // function will abort the process.
191a11cd0d9STom Stellard template <typename T>
192a11cd0d9STom Stellard class BuiltInDefaultValue {
193a11cd0d9STom Stellard  public:
194a11cd0d9STom Stellard   // This function returns true if and only if type T has a built-in default
195a11cd0d9STom Stellard   // value.
196*a866ce78SHaowei Wu   static bool Exists() { return ::std::is_default_constructible<T>::value; }
197a11cd0d9STom Stellard 
198a11cd0d9STom Stellard   static T Get() {
199a11cd0d9STom Stellard     return BuiltInDefaultValueGetter<
200a11cd0d9STom Stellard         T, ::std::is_default_constructible<T>::value>::Get();
201a11cd0d9STom Stellard   }
202a11cd0d9STom Stellard };
203a11cd0d9STom Stellard 
204a11cd0d9STom Stellard // This partial specialization says that we use the same built-in
205a11cd0d9STom Stellard // default value for T and const T.
206a11cd0d9STom Stellard template <typename T>
207a11cd0d9STom Stellard class BuiltInDefaultValue<const T> {
208a11cd0d9STom Stellard  public:
209a11cd0d9STom Stellard   static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
210a11cd0d9STom Stellard   static T Get() { return BuiltInDefaultValue<T>::Get(); }
211a11cd0d9STom Stellard };
212a11cd0d9STom Stellard 
213a11cd0d9STom Stellard // This partial specialization defines the default values for pointer
214a11cd0d9STom Stellard // types.
215a11cd0d9STom Stellard template <typename T>
216a11cd0d9STom Stellard class BuiltInDefaultValue<T*> {
217a11cd0d9STom Stellard  public:
218a11cd0d9STom Stellard   static bool Exists() { return true; }
219a11cd0d9STom Stellard   static T* Get() { return nullptr; }
220a11cd0d9STom Stellard };
221a11cd0d9STom Stellard 
222a11cd0d9STom Stellard // The following specializations define the default values for
223a11cd0d9STom Stellard // specific types we care about.
224a11cd0d9STom Stellard #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
225a11cd0d9STom Stellard   template <>                                                     \
226a11cd0d9STom Stellard   class BuiltInDefaultValue<type> {                               \
227a11cd0d9STom Stellard    public:                                                        \
228a11cd0d9STom Stellard     static bool Exists() { return true; }                         \
229a11cd0d9STom Stellard     static type Get() { return value; }                           \
230a11cd0d9STom Stellard   }
231a11cd0d9STom Stellard 
232a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, );  // NOLINT
233a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
234a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
235a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
236a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
237a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
238a11cd0d9STom Stellard 
239a11cd0d9STom Stellard // There's no need for a default action for signed wchar_t, as that
240a11cd0d9STom Stellard // type is the same as wchar_t for gcc, and invalid for MSVC.
241a11cd0d9STom Stellard //
242a11cd0d9STom Stellard // There's also no need for a default action for unsigned wchar_t, as
243a11cd0d9STom Stellard // that type is the same as unsigned int for gcc, and invalid for
244a11cd0d9STom Stellard // MSVC.
245a11cd0d9STom Stellard #if GMOCK_WCHAR_T_IS_NATIVE_
246a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U);  // NOLINT
247a11cd0d9STom Stellard #endif
248a11cd0d9STom Stellard 
249a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U);  // NOLINT
250a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0);     // NOLINT
251a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
252a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
253a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL);     // NOLINT
254a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L);        // NOLINT
255*a866ce78SHaowei Wu GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0);  // NOLINT
256*a866ce78SHaowei Wu GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0);    // NOLINT
257a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
258a11cd0d9STom Stellard GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
259a11cd0d9STom Stellard 
260a11cd0d9STom Stellard #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
261a11cd0d9STom Stellard 
262*a866ce78SHaowei Wu // Partial implementations of metaprogramming types from the standard library
263*a866ce78SHaowei Wu // not available in C++11.
264*a866ce78SHaowei Wu 
265*a866ce78SHaowei Wu template <typename P>
266*a866ce78SHaowei Wu struct negation
267*a866ce78SHaowei Wu     // NOLINTNEXTLINE
268*a866ce78SHaowei Wu     : std::integral_constant<bool, bool(!P::value)> {};
269*a866ce78SHaowei Wu 
270*a866ce78SHaowei Wu // Base case: with zero predicates the answer is always true.
271*a866ce78SHaowei Wu template <typename...>
272*a866ce78SHaowei Wu struct conjunction : std::true_type {};
273*a866ce78SHaowei Wu 
274*a866ce78SHaowei Wu // With a single predicate, the answer is that predicate.
275*a866ce78SHaowei Wu template <typename P1>
276*a866ce78SHaowei Wu struct conjunction<P1> : P1 {};
277*a866ce78SHaowei Wu 
278*a866ce78SHaowei Wu // With multiple predicates the answer is the first predicate if that is false,
279*a866ce78SHaowei Wu // and we recurse otherwise.
280*a866ce78SHaowei Wu template <typename P1, typename... Ps>
281*a866ce78SHaowei Wu struct conjunction<P1, Ps...>
282*a866ce78SHaowei Wu     : std::conditional<bool(P1::value), conjunction<Ps...>, P1>::type {};
283*a866ce78SHaowei Wu 
284*a866ce78SHaowei Wu template <typename...>
285*a866ce78SHaowei Wu struct disjunction : std::false_type {};
286*a866ce78SHaowei Wu 
287*a866ce78SHaowei Wu template <typename P1>
288*a866ce78SHaowei Wu struct disjunction<P1> : P1 {};
289*a866ce78SHaowei Wu 
290*a866ce78SHaowei Wu template <typename P1, typename... Ps>
291*a866ce78SHaowei Wu struct disjunction<P1, Ps...>
292*a866ce78SHaowei Wu     // NOLINTNEXTLINE
293*a866ce78SHaowei Wu     : std::conditional<!bool(P1::value), disjunction<Ps...>, P1>::type {};
294*a866ce78SHaowei Wu 
295*a866ce78SHaowei Wu template <typename...>
296*a866ce78SHaowei Wu using void_t = void;
297*a866ce78SHaowei Wu 
298*a866ce78SHaowei Wu // Detects whether an expression of type `From` can be implicitly converted to
299*a866ce78SHaowei Wu // `To` according to [conv]. In C++17, [conv]/3 defines this as follows:
300*a866ce78SHaowei Wu //
301*a866ce78SHaowei Wu //     An expression e can be implicitly converted to a type T if and only if
302*a866ce78SHaowei Wu //     the declaration T t=e; is well-formed, for some invented temporary
303*a866ce78SHaowei Wu //     variable t ([dcl.init]).
304*a866ce78SHaowei Wu //
305*a866ce78SHaowei Wu // [conv]/2 implies we can use function argument passing to detect whether this
306*a866ce78SHaowei Wu // initialization is valid.
307*a866ce78SHaowei Wu //
308*a866ce78SHaowei Wu // Note that this is distinct from is_convertible, which requires this be valid:
309*a866ce78SHaowei Wu //
310*a866ce78SHaowei Wu //     To test() {
311*a866ce78SHaowei Wu //       return declval<From>();
312*a866ce78SHaowei Wu //     }
313*a866ce78SHaowei Wu //
314*a866ce78SHaowei Wu // In particular, is_convertible doesn't give the correct answer when `To` and
315*a866ce78SHaowei Wu // `From` are the same non-moveable type since `declval<From>` will be an rvalue
316*a866ce78SHaowei Wu // reference, defeating the guaranteed copy elision that would otherwise make
317*a866ce78SHaowei Wu // this function work.
318*a866ce78SHaowei Wu //
319*a866ce78SHaowei Wu // REQUIRES: `From` is not cv void.
320*a866ce78SHaowei Wu template <typename From, typename To>
321*a866ce78SHaowei Wu struct is_implicitly_convertible {
322*a866ce78SHaowei Wu  private:
323*a866ce78SHaowei Wu   // A function that accepts a parameter of type T. This can be called with type
324*a866ce78SHaowei Wu   // U successfully only if U is implicitly convertible to T.
325*a866ce78SHaowei Wu   template <typename T>
326*a866ce78SHaowei Wu   static void Accept(T);
327*a866ce78SHaowei Wu 
328*a866ce78SHaowei Wu   // A function that creates a value of type T.
329*a866ce78SHaowei Wu   template <typename T>
330*a866ce78SHaowei Wu   static T Make();
331*a866ce78SHaowei Wu 
332*a866ce78SHaowei Wu   // An overload be selected when implicit conversion from T to To is possible.
333*a866ce78SHaowei Wu   template <typename T, typename = decltype(Accept<To>(Make<T>()))>
334*a866ce78SHaowei Wu   static std::true_type TestImplicitConversion(int);
335*a866ce78SHaowei Wu 
336*a866ce78SHaowei Wu   // A fallback overload selected in all other cases.
337*a866ce78SHaowei Wu   template <typename T>
338*a866ce78SHaowei Wu   static std::false_type TestImplicitConversion(...);
339*a866ce78SHaowei Wu 
340*a866ce78SHaowei Wu  public:
341*a866ce78SHaowei Wu   using type = decltype(TestImplicitConversion<From>(0));
342*a866ce78SHaowei Wu   static constexpr bool value = type::value;
343*a866ce78SHaowei Wu };
344*a866ce78SHaowei Wu 
345*a866ce78SHaowei Wu // Like std::invoke_result_t from C++17, but works only for objects with call
346*a866ce78SHaowei Wu // operators (not e.g. member function pointers, which we don't need specific
347*a866ce78SHaowei Wu // support for in OnceAction because std::function deals with them).
348*a866ce78SHaowei Wu template <typename F, typename... Args>
349*a866ce78SHaowei Wu using call_result_t = decltype(std::declval<F>()(std::declval<Args>()...));
350*a866ce78SHaowei Wu 
351*a866ce78SHaowei Wu template <typename Void, typename R, typename F, typename... Args>
352*a866ce78SHaowei Wu struct is_callable_r_impl : std::false_type {};
353*a866ce78SHaowei Wu 
354*a866ce78SHaowei Wu // Specialize the struct for those template arguments where call_result_t is
355*a866ce78SHaowei Wu // well-formed. When it's not, the generic template above is chosen, resulting
356*a866ce78SHaowei Wu // in std::false_type.
357*a866ce78SHaowei Wu template <typename R, typename F, typename... Args>
358*a866ce78SHaowei Wu struct is_callable_r_impl<void_t<call_result_t<F, Args...>>, R, F, Args...>
359*a866ce78SHaowei Wu     : std::conditional<
360*a866ce78SHaowei Wu           std::is_void<R>::value,  //
361*a866ce78SHaowei Wu           std::true_type,          //
362*a866ce78SHaowei Wu           is_implicitly_convertible<call_result_t<F, Args...>, R>>::type {};
363*a866ce78SHaowei Wu 
364*a866ce78SHaowei Wu // Like std::is_invocable_r from C++17, but works only for objects with call
365*a866ce78SHaowei Wu // operators. See the note on call_result_t.
366*a866ce78SHaowei Wu template <typename R, typename F, typename... Args>
367*a866ce78SHaowei Wu using is_callable_r = is_callable_r_impl<void, R, F, Args...>;
368*a866ce78SHaowei Wu 
369*a866ce78SHaowei Wu // Like std::as_const from C++17.
370*a866ce78SHaowei Wu template <typename T>
371*a866ce78SHaowei Wu typename std::add_const<T>::type& as_const(T& t) {
372*a866ce78SHaowei Wu   return t;
373*a866ce78SHaowei Wu }
374*a866ce78SHaowei Wu 
375a11cd0d9STom Stellard }  // namespace internal
376a11cd0d9STom Stellard 
377*a866ce78SHaowei Wu // Specialized for function types below.
378*a866ce78SHaowei Wu template <typename F>
379*a866ce78SHaowei Wu class OnceAction;
380*a866ce78SHaowei Wu 
381*a866ce78SHaowei Wu // An action that can only be used once.
382*a866ce78SHaowei Wu //
383*a866ce78SHaowei Wu // This is accepted by WillOnce, which doesn't require the underlying action to
384*a866ce78SHaowei Wu // be copy-constructible (only move-constructible), and promises to invoke it as
385*a866ce78SHaowei Wu // an rvalue reference. This allows the action to work with move-only types like
386*a866ce78SHaowei Wu // std::move_only_function in a type-safe manner.
387*a866ce78SHaowei Wu //
388*a866ce78SHaowei Wu // For example:
389*a866ce78SHaowei Wu //
390*a866ce78SHaowei Wu //     // Assume we have some API that needs to accept a unique pointer to some
391*a866ce78SHaowei Wu //     // non-copyable object Foo.
392*a866ce78SHaowei Wu //     void AcceptUniquePointer(std::unique_ptr<Foo> foo);
393*a866ce78SHaowei Wu //
394*a866ce78SHaowei Wu //     // We can define an action that provides a Foo to that API. Because It
395*a866ce78SHaowei Wu //     // has to give away its unique pointer, it must not be called more than
396*a866ce78SHaowei Wu //     // once, so its call operator is &&-qualified.
397*a866ce78SHaowei Wu //     struct ProvideFoo {
398*a866ce78SHaowei Wu //       std::unique_ptr<Foo> foo;
399*a866ce78SHaowei Wu //
400*a866ce78SHaowei Wu //       void operator()() && {
401*a866ce78SHaowei Wu //         AcceptUniquePointer(std::move(Foo));
402*a866ce78SHaowei Wu //       }
403*a866ce78SHaowei Wu //     };
404*a866ce78SHaowei Wu //
405*a866ce78SHaowei Wu //     // This action can be used with WillOnce.
406*a866ce78SHaowei Wu //     EXPECT_CALL(mock, Call)
407*a866ce78SHaowei Wu //         .WillOnce(ProvideFoo{std::make_unique<Foo>(...)});
408*a866ce78SHaowei Wu //
409*a866ce78SHaowei Wu //     // But a call to WillRepeatedly will fail to compile. This is correct,
410*a866ce78SHaowei Wu //     // since the action cannot correctly be used repeatedly.
411*a866ce78SHaowei Wu //     EXPECT_CALL(mock, Call)
412*a866ce78SHaowei Wu //         .WillRepeatedly(ProvideFoo{std::make_unique<Foo>(...)});
413*a866ce78SHaowei Wu //
414*a866ce78SHaowei Wu // A less-contrived example would be an action that returns an arbitrary type,
415*a866ce78SHaowei Wu // whose &&-qualified call operator is capable of dealing with move-only types.
416*a866ce78SHaowei Wu template <typename Result, typename... Args>
417*a866ce78SHaowei Wu class OnceAction<Result(Args...)> final {
418*a866ce78SHaowei Wu  private:
419*a866ce78SHaowei Wu   // True iff we can use the given callable type (or lvalue reference) directly
420*a866ce78SHaowei Wu   // via StdFunctionAdaptor.
421*a866ce78SHaowei Wu   template <typename Callable>
422*a866ce78SHaowei Wu   using IsDirectlyCompatible = internal::conjunction<
423*a866ce78SHaowei Wu       // It must be possible to capture the callable in StdFunctionAdaptor.
424*a866ce78SHaowei Wu       std::is_constructible<typename std::decay<Callable>::type, Callable>,
425*a866ce78SHaowei Wu       // The callable must be compatible with our signature.
426*a866ce78SHaowei Wu       internal::is_callable_r<Result, typename std::decay<Callable>::type,
427*a866ce78SHaowei Wu                               Args...>>;
428*a866ce78SHaowei Wu 
429*a866ce78SHaowei Wu   // True iff we can use the given callable type via StdFunctionAdaptor once we
430*a866ce78SHaowei Wu   // ignore incoming arguments.
431*a866ce78SHaowei Wu   template <typename Callable>
432*a866ce78SHaowei Wu   using IsCompatibleAfterIgnoringArguments = internal::conjunction<
433*a866ce78SHaowei Wu       // It must be possible to capture the callable in a lambda.
434*a866ce78SHaowei Wu       std::is_constructible<typename std::decay<Callable>::type, Callable>,
435*a866ce78SHaowei Wu       // The callable must be invocable with zero arguments, returning something
436*a866ce78SHaowei Wu       // convertible to Result.
437*a866ce78SHaowei Wu       internal::is_callable_r<Result, typename std::decay<Callable>::type>>;
438*a866ce78SHaowei Wu 
439*a866ce78SHaowei Wu  public:
440*a866ce78SHaowei Wu   // Construct from a callable that is directly compatible with our mocked
441*a866ce78SHaowei Wu   // signature: it accepts our function type's arguments and returns something
442*a866ce78SHaowei Wu   // convertible to our result type.
443*a866ce78SHaowei Wu   template <typename Callable,
444*a866ce78SHaowei Wu             typename std::enable_if<
445*a866ce78SHaowei Wu                 internal::conjunction<
446*a866ce78SHaowei Wu                     // Teach clang on macOS that we're not talking about a
447*a866ce78SHaowei Wu                     // copy/move constructor here. Otherwise it gets confused
448*a866ce78SHaowei Wu                     // when checking the is_constructible requirement of our
449*a866ce78SHaowei Wu                     // traits above.
450*a866ce78SHaowei Wu                     internal::negation<std::is_same<
451*a866ce78SHaowei Wu                         OnceAction, typename std::decay<Callable>::type>>,
452*a866ce78SHaowei Wu                     IsDirectlyCompatible<Callable>>  //
453*a866ce78SHaowei Wu                 ::value,
454*a866ce78SHaowei Wu                 int>::type = 0>
455*a866ce78SHaowei Wu   OnceAction(Callable&& callable)  // NOLINT
456*a866ce78SHaowei Wu       : function_(StdFunctionAdaptor<typename std::decay<Callable>::type>(
457*a866ce78SHaowei Wu             {}, std::forward<Callable>(callable))) {}
458*a866ce78SHaowei Wu 
459*a866ce78SHaowei Wu   // As above, but for a callable that ignores the mocked function's arguments.
460*a866ce78SHaowei Wu   template <typename Callable,
461*a866ce78SHaowei Wu             typename std::enable_if<
462*a866ce78SHaowei Wu                 internal::conjunction<
463*a866ce78SHaowei Wu                     // Teach clang on macOS that we're not talking about a
464*a866ce78SHaowei Wu                     // copy/move constructor here. Otherwise it gets confused
465*a866ce78SHaowei Wu                     // when checking the is_constructible requirement of our
466*a866ce78SHaowei Wu                     // traits above.
467*a866ce78SHaowei Wu                     internal::negation<std::is_same<
468*a866ce78SHaowei Wu                         OnceAction, typename std::decay<Callable>::type>>,
469*a866ce78SHaowei Wu                     // Exclude callables for which the overload above works.
470*a866ce78SHaowei Wu                     // We'd rather provide the arguments if possible.
471*a866ce78SHaowei Wu                     internal::negation<IsDirectlyCompatible<Callable>>,
472*a866ce78SHaowei Wu                     IsCompatibleAfterIgnoringArguments<Callable>>::value,
473*a866ce78SHaowei Wu                 int>::type = 0>
474*a866ce78SHaowei Wu   OnceAction(Callable&& callable)  // NOLINT
475*a866ce78SHaowei Wu                                    // Call the constructor above with a callable
476*a866ce78SHaowei Wu                                    // that ignores the input arguments.
477*a866ce78SHaowei Wu       : OnceAction(IgnoreIncomingArguments<typename std::decay<Callable>::type>{
478*a866ce78SHaowei Wu             std::forward<Callable>(callable)}) {}
479*a866ce78SHaowei Wu 
480*a866ce78SHaowei Wu   // We are naturally copyable because we store only an std::function, but
481*a866ce78SHaowei Wu   // semantically we should not be copyable.
482*a866ce78SHaowei Wu   OnceAction(const OnceAction&) = delete;
483*a866ce78SHaowei Wu   OnceAction& operator=(const OnceAction&) = delete;
484*a866ce78SHaowei Wu   OnceAction(OnceAction&&) = default;
485*a866ce78SHaowei Wu 
486*a866ce78SHaowei Wu   // Invoke the underlying action callable with which we were constructed,
487*a866ce78SHaowei Wu   // handing it the supplied arguments.
488*a866ce78SHaowei Wu   Result Call(Args... args) && {
489*a866ce78SHaowei Wu     return function_(std::forward<Args>(args)...);
490*a866ce78SHaowei Wu   }
491*a866ce78SHaowei Wu 
492*a866ce78SHaowei Wu  private:
493*a866ce78SHaowei Wu   // An adaptor that wraps a callable that is compatible with our signature and
494*a866ce78SHaowei Wu   // being invoked as an rvalue reference so that it can be used as an
495*a866ce78SHaowei Wu   // StdFunctionAdaptor. This throws away type safety, but that's fine because
496*a866ce78SHaowei Wu   // this is only used by WillOnce, which we know calls at most once.
497*a866ce78SHaowei Wu   //
498*a866ce78SHaowei Wu   // Once we have something like std::move_only_function from C++23, we can do
499*a866ce78SHaowei Wu   // away with this.
500*a866ce78SHaowei Wu   template <typename Callable>
501*a866ce78SHaowei Wu   class StdFunctionAdaptor final {
502*a866ce78SHaowei Wu    public:
503*a866ce78SHaowei Wu     // A tag indicating that the (otherwise universal) constructor is accepting
504*a866ce78SHaowei Wu     // the callable itself, instead of e.g. stealing calls for the move
505*a866ce78SHaowei Wu     // constructor.
506*a866ce78SHaowei Wu     struct CallableTag final {};
507*a866ce78SHaowei Wu 
508*a866ce78SHaowei Wu     template <typename F>
509*a866ce78SHaowei Wu     explicit StdFunctionAdaptor(CallableTag, F&& callable)
510*a866ce78SHaowei Wu         : callable_(std::make_shared<Callable>(std::forward<F>(callable))) {}
511*a866ce78SHaowei Wu 
512*a866ce78SHaowei Wu     // Rather than explicitly returning Result, we return whatever the wrapped
513*a866ce78SHaowei Wu     // callable returns. This allows for compatibility with existing uses like
514*a866ce78SHaowei Wu     // the following, when the mocked function returns void:
515*a866ce78SHaowei Wu     //
516*a866ce78SHaowei Wu     //     EXPECT_CALL(mock_fn_, Call)
517*a866ce78SHaowei Wu     //         .WillOnce([&] {
518*a866ce78SHaowei Wu     //            [...]
519*a866ce78SHaowei Wu     //            return 0;
520*a866ce78SHaowei Wu     //         });
521*a866ce78SHaowei Wu     //
522*a866ce78SHaowei Wu     // Such a callable can be turned into std::function<void()>. If we use an
523*a866ce78SHaowei Wu     // explicit return type of Result here then it *doesn't* work with
524*a866ce78SHaowei Wu     // std::function, because we'll get a "void function should not return a
525*a866ce78SHaowei Wu     // value" error.
526*a866ce78SHaowei Wu     //
527*a866ce78SHaowei Wu     // We need not worry about incompatible result types because the SFINAE on
528*a866ce78SHaowei Wu     // OnceAction already checks this for us. std::is_invocable_r_v itself makes
529*a866ce78SHaowei Wu     // the same allowance for void result types.
530*a866ce78SHaowei Wu     template <typename... ArgRefs>
531*a866ce78SHaowei Wu     internal::call_result_t<Callable, ArgRefs...> operator()(
532*a866ce78SHaowei Wu         ArgRefs&&... args) const {
533*a866ce78SHaowei Wu       return std::move(*callable_)(std::forward<ArgRefs>(args)...);
534*a866ce78SHaowei Wu     }
535*a866ce78SHaowei Wu 
536*a866ce78SHaowei Wu    private:
537*a866ce78SHaowei Wu     // We must put the callable on the heap so that we are copyable, which
538*a866ce78SHaowei Wu     // std::function needs.
539*a866ce78SHaowei Wu     std::shared_ptr<Callable> callable_;
540*a866ce78SHaowei Wu   };
541*a866ce78SHaowei Wu 
542*a866ce78SHaowei Wu   // An adaptor that makes a callable that accepts zero arguments callable with
543*a866ce78SHaowei Wu   // our mocked arguments.
544*a866ce78SHaowei Wu   template <typename Callable>
545*a866ce78SHaowei Wu   struct IgnoreIncomingArguments {
546*a866ce78SHaowei Wu     internal::call_result_t<Callable> operator()(Args&&...) {
547*a866ce78SHaowei Wu       return std::move(callable)();
548*a866ce78SHaowei Wu     }
549*a866ce78SHaowei Wu 
550*a866ce78SHaowei Wu     Callable callable;
551*a866ce78SHaowei Wu   };
552*a866ce78SHaowei Wu 
553*a866ce78SHaowei Wu   std::function<Result(Args...)> function_;
554*a866ce78SHaowei Wu };
555*a866ce78SHaowei Wu 
556a11cd0d9STom Stellard // When an unexpected function call is encountered, Google Mock will
557a11cd0d9STom Stellard // let it return a default value if the user has specified one for its
558a11cd0d9STom Stellard // return type, or if the return type has a built-in default value;
559a11cd0d9STom Stellard // otherwise Google Mock won't know what value to return and will have
560a11cd0d9STom Stellard // to abort the process.
561a11cd0d9STom Stellard //
562a11cd0d9STom Stellard // The DefaultValue<T> class allows a user to specify the
563a11cd0d9STom Stellard // default value for a type T that is both copyable and publicly
564a11cd0d9STom Stellard // destructible (i.e. anything that can be used as a function return
565a11cd0d9STom Stellard // type).  The usage is:
566a11cd0d9STom Stellard //
567a11cd0d9STom Stellard //   // Sets the default value for type T to be foo.
568a11cd0d9STom Stellard //   DefaultValue<T>::Set(foo);
569a11cd0d9STom Stellard template <typename T>
570a11cd0d9STom Stellard class DefaultValue {
571a11cd0d9STom Stellard  public:
572a11cd0d9STom Stellard   // Sets the default value for type T; requires T to be
573a11cd0d9STom Stellard   // copy-constructable and have a public destructor.
574a11cd0d9STom Stellard   static void Set(T x) {
575a11cd0d9STom Stellard     delete producer_;
576a11cd0d9STom Stellard     producer_ = new FixedValueProducer(x);
577a11cd0d9STom Stellard   }
578a11cd0d9STom Stellard 
579a11cd0d9STom Stellard   // Provides a factory function to be called to generate the default value.
580a11cd0d9STom Stellard   // This method can be used even if T is only move-constructible, but it is not
581a11cd0d9STom Stellard   // limited to that case.
582a11cd0d9STom Stellard   typedef T (*FactoryFunction)();
583a11cd0d9STom Stellard   static void SetFactory(FactoryFunction factory) {
584a11cd0d9STom Stellard     delete producer_;
585a11cd0d9STom Stellard     producer_ = new FactoryValueProducer(factory);
586a11cd0d9STom Stellard   }
587a11cd0d9STom Stellard 
588a11cd0d9STom Stellard   // Unsets the default value for type T.
589a11cd0d9STom Stellard   static void Clear() {
590a11cd0d9STom Stellard     delete producer_;
591a11cd0d9STom Stellard     producer_ = nullptr;
592a11cd0d9STom Stellard   }
593a11cd0d9STom Stellard 
594a11cd0d9STom Stellard   // Returns true if and only if the user has set the default value for type T.
595a11cd0d9STom Stellard   static bool IsSet() { return producer_ != nullptr; }
596a11cd0d9STom Stellard 
597a11cd0d9STom Stellard   // Returns true if T has a default return value set by the user or there
598a11cd0d9STom Stellard   // exists a built-in default value.
599a11cd0d9STom Stellard   static bool Exists() {
600a11cd0d9STom Stellard     return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
601a11cd0d9STom Stellard   }
602a11cd0d9STom Stellard 
603a11cd0d9STom Stellard   // Returns the default value for type T if the user has set one;
604a11cd0d9STom Stellard   // otherwise returns the built-in default value. Requires that Exists()
605a11cd0d9STom Stellard   // is true, which ensures that the return value is well-defined.
606a11cd0d9STom Stellard   static T Get() {
607a11cd0d9STom Stellard     return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
608a11cd0d9STom Stellard                                 : producer_->Produce();
609a11cd0d9STom Stellard   }
610a11cd0d9STom Stellard 
611a11cd0d9STom Stellard  private:
612a11cd0d9STom Stellard   class ValueProducer {
613a11cd0d9STom Stellard    public:
614*a866ce78SHaowei Wu     virtual ~ValueProducer() = default;
615a11cd0d9STom Stellard     virtual T Produce() = 0;
616a11cd0d9STom Stellard   };
617a11cd0d9STom Stellard 
618a11cd0d9STom Stellard   class FixedValueProducer : public ValueProducer {
619a11cd0d9STom Stellard    public:
620a11cd0d9STom Stellard     explicit FixedValueProducer(T value) : value_(value) {}
621a11cd0d9STom Stellard     T Produce() override { return value_; }
622a11cd0d9STom Stellard 
623a11cd0d9STom Stellard    private:
624a11cd0d9STom Stellard     const T value_;
625*a866ce78SHaowei Wu     FixedValueProducer(const FixedValueProducer&) = delete;
626*a866ce78SHaowei Wu     FixedValueProducer& operator=(const FixedValueProducer&) = delete;
627a11cd0d9STom Stellard   };
628a11cd0d9STom Stellard 
629a11cd0d9STom Stellard   class FactoryValueProducer : public ValueProducer {
630a11cd0d9STom Stellard    public:
631a11cd0d9STom Stellard     explicit FactoryValueProducer(FactoryFunction factory)
632a11cd0d9STom Stellard         : factory_(factory) {}
633a11cd0d9STom Stellard     T Produce() override { return factory_(); }
634a11cd0d9STom Stellard 
635a11cd0d9STom Stellard    private:
636a11cd0d9STom Stellard     const FactoryFunction factory_;
637*a866ce78SHaowei Wu     FactoryValueProducer(const FactoryValueProducer&) = delete;
638*a866ce78SHaowei Wu     FactoryValueProducer& operator=(const FactoryValueProducer&) = delete;
639a11cd0d9STom Stellard   };
640a11cd0d9STom Stellard 
641a11cd0d9STom Stellard   static ValueProducer* producer_;
642a11cd0d9STom Stellard };
643a11cd0d9STom Stellard 
644a11cd0d9STom Stellard // This partial specialization allows a user to set default values for
645a11cd0d9STom Stellard // reference types.
646a11cd0d9STom Stellard template <typename T>
647a11cd0d9STom Stellard class DefaultValue<T&> {
648a11cd0d9STom Stellard  public:
649a11cd0d9STom Stellard   // Sets the default value for type T&.
650a11cd0d9STom Stellard   static void Set(T& x) {  // NOLINT
651a11cd0d9STom Stellard     address_ = &x;
652a11cd0d9STom Stellard   }
653a11cd0d9STom Stellard 
654a11cd0d9STom Stellard   // Unsets the default value for type T&.
655a11cd0d9STom Stellard   static void Clear() { address_ = nullptr; }
656a11cd0d9STom Stellard 
657a11cd0d9STom Stellard   // Returns true if and only if the user has set the default value for type T&.
658a11cd0d9STom Stellard   static bool IsSet() { return address_ != nullptr; }
659a11cd0d9STom Stellard 
660a11cd0d9STom Stellard   // Returns true if T has a default return value set by the user or there
661a11cd0d9STom Stellard   // exists a built-in default value.
662a11cd0d9STom Stellard   static bool Exists() {
663a11cd0d9STom Stellard     return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
664a11cd0d9STom Stellard   }
665a11cd0d9STom Stellard 
666a11cd0d9STom Stellard   // Returns the default value for type T& if the user has set one;
667a11cd0d9STom Stellard   // otherwise returns the built-in default value if there is one;
668a11cd0d9STom Stellard   // otherwise aborts the process.
669a11cd0d9STom Stellard   static T& Get() {
670a11cd0d9STom Stellard     return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
671a11cd0d9STom Stellard                                : *address_;
672a11cd0d9STom Stellard   }
673a11cd0d9STom Stellard 
674a11cd0d9STom Stellard  private:
675a11cd0d9STom Stellard   static T* address_;
676a11cd0d9STom Stellard };
677a11cd0d9STom Stellard 
678a11cd0d9STom Stellard // This specialization allows DefaultValue<void>::Get() to
679a11cd0d9STom Stellard // compile.
680a11cd0d9STom Stellard template <>
681a11cd0d9STom Stellard class DefaultValue<void> {
682a11cd0d9STom Stellard  public:
683a11cd0d9STom Stellard   static bool Exists() { return true; }
684a11cd0d9STom Stellard   static void Get() {}
685a11cd0d9STom Stellard };
686a11cd0d9STom Stellard 
687a11cd0d9STom Stellard // Points to the user-set default value for type T.
688a11cd0d9STom Stellard template <typename T>
689a11cd0d9STom Stellard typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
690a11cd0d9STom Stellard 
691a11cd0d9STom Stellard // Points to the user-set default value for type T&.
692a11cd0d9STom Stellard template <typename T>
693a11cd0d9STom Stellard T* DefaultValue<T&>::address_ = nullptr;
694a11cd0d9STom Stellard 
695a11cd0d9STom Stellard // Implement this interface to define an action for function type F.
696a11cd0d9STom Stellard template <typename F>
697a11cd0d9STom Stellard class ActionInterface {
698a11cd0d9STom Stellard  public:
699a11cd0d9STom Stellard   typedef typename internal::Function<F>::Result Result;
700a11cd0d9STom Stellard   typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
701a11cd0d9STom Stellard 
702*a866ce78SHaowei Wu   ActionInterface() = default;
703*a866ce78SHaowei Wu   virtual ~ActionInterface() = default;
704a11cd0d9STom Stellard 
705a11cd0d9STom Stellard   // Performs the action.  This method is not const, as in general an
706a11cd0d9STom Stellard   // action can have side effects and be stateful.  For example, a
707a11cd0d9STom Stellard   // get-the-next-element-from-the-collection action will need to
708a11cd0d9STom Stellard   // remember the current element.
709a11cd0d9STom Stellard   virtual Result Perform(const ArgumentTuple& args) = 0;
710a11cd0d9STom Stellard 
711a11cd0d9STom Stellard  private:
712*a866ce78SHaowei Wu   ActionInterface(const ActionInterface&) = delete;
713*a866ce78SHaowei Wu   ActionInterface& operator=(const ActionInterface&) = delete;
714a11cd0d9STom Stellard };
715a11cd0d9STom Stellard 
716a11cd0d9STom Stellard template <typename F>
717*a866ce78SHaowei Wu class Action;
718*a866ce78SHaowei Wu 
719*a866ce78SHaowei Wu // An Action<R(Args...)> is a copyable and IMMUTABLE (except by assignment)
720*a866ce78SHaowei Wu // object that represents an action to be taken when a mock function of type
721*a866ce78SHaowei Wu // R(Args...) is called. The implementation of Action<T> is just a
722*a866ce78SHaowei Wu // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action! You
723*a866ce78SHaowei Wu // can view an object implementing ActionInterface<F> as a concrete action
724*a866ce78SHaowei Wu // (including its current state), and an Action<F> object as a handle to it.
725*a866ce78SHaowei Wu template <typename R, typename... Args>
726*a866ce78SHaowei Wu class Action<R(Args...)> {
727*a866ce78SHaowei Wu  private:
728*a866ce78SHaowei Wu   using F = R(Args...);
729*a866ce78SHaowei Wu 
730a11cd0d9STom Stellard   // Adapter class to allow constructing Action from a legacy ActionInterface.
731a11cd0d9STom Stellard   // New code should create Actions from functors instead.
732a11cd0d9STom Stellard   struct ActionAdapter {
733a11cd0d9STom Stellard     // Adapter must be copyable to satisfy std::function requirements.
734a11cd0d9STom Stellard     ::std::shared_ptr<ActionInterface<F>> impl_;
735a11cd0d9STom Stellard 
736*a866ce78SHaowei Wu     template <typename... InArgs>
737*a866ce78SHaowei Wu     typename internal::Function<F>::Result operator()(InArgs&&... args) {
738a11cd0d9STom Stellard       return impl_->Perform(
739*a866ce78SHaowei Wu           ::std::forward_as_tuple(::std::forward<InArgs>(args)...));
740a11cd0d9STom Stellard     }
741a11cd0d9STom Stellard   };
742a11cd0d9STom Stellard 
743*a866ce78SHaowei Wu   template <typename G>
744*a866ce78SHaowei Wu   using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;
745*a866ce78SHaowei Wu 
746a11cd0d9STom Stellard  public:
747a11cd0d9STom Stellard   typedef typename internal::Function<F>::Result Result;
748a11cd0d9STom Stellard   typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
749a11cd0d9STom Stellard 
750a11cd0d9STom Stellard   // Constructs a null Action.  Needed for storing Action objects in
751a11cd0d9STom Stellard   // STL containers.
752*a866ce78SHaowei Wu   Action() = default;
753a11cd0d9STom Stellard 
754a11cd0d9STom Stellard   // Construct an Action from a specified callable.
755a11cd0d9STom Stellard   // This cannot take std::function directly, because then Action would not be
756a11cd0d9STom Stellard   // directly constructible from lambda (it would require two conversions).
757*a866ce78SHaowei Wu   template <
758*a866ce78SHaowei Wu       typename G,
759*a866ce78SHaowei Wu       typename = typename std::enable_if<internal::disjunction<
760*a866ce78SHaowei Wu           IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,
761*a866ce78SHaowei Wu                                                         G>>::value>::type>
762*a866ce78SHaowei Wu   Action(G&& fun) {  // NOLINT
763*a866ce78SHaowei Wu     Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());
764*a866ce78SHaowei Wu   }
765a11cd0d9STom Stellard 
766a11cd0d9STom Stellard   // Constructs an Action from its implementation.
767a11cd0d9STom Stellard   explicit Action(ActionInterface<F>* impl)
768a11cd0d9STom Stellard       : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
769a11cd0d9STom Stellard 
770a11cd0d9STom Stellard   // This constructor allows us to turn an Action<Func> object into an
771a11cd0d9STom Stellard   // Action<F>, as long as F's arguments can be implicitly converted
772a11cd0d9STom Stellard   // to Func's and Func's return type can be implicitly converted to F's.
773a11cd0d9STom Stellard   template <typename Func>
774*a866ce78SHaowei Wu   Action(const Action<Func>& action)  // NOLINT
775*a866ce78SHaowei Wu       : fun_(action.fun_) {}
776a11cd0d9STom Stellard 
777a11cd0d9STom Stellard   // Returns true if and only if this is the DoDefault() action.
778a11cd0d9STom Stellard   bool IsDoDefault() const { return fun_ == nullptr; }
779a11cd0d9STom Stellard 
780a11cd0d9STom Stellard   // Performs the action.  Note that this method is const even though
781a11cd0d9STom Stellard   // the corresponding method in ActionInterface is not.  The reason
782a11cd0d9STom Stellard   // is that a const Action<F> means that it cannot be re-bound to
783a11cd0d9STom Stellard   // another concrete action, not that the concrete action it binds to
784a11cd0d9STom Stellard   // cannot change state.  (Think of the difference between a const
785a11cd0d9STom Stellard   // pointer and a pointer to const.)
786a11cd0d9STom Stellard   Result Perform(ArgumentTuple args) const {
787a11cd0d9STom Stellard     if (IsDoDefault()) {
788a11cd0d9STom Stellard       internal::IllegalDoDefault(__FILE__, __LINE__);
789a11cd0d9STom Stellard     }
790a11cd0d9STom Stellard     return internal::Apply(fun_, ::std::move(args));
791a11cd0d9STom Stellard   }
792a11cd0d9STom Stellard 
793*a866ce78SHaowei Wu   // An action can be used as a OnceAction, since it's obviously safe to call it
794*a866ce78SHaowei Wu   // once.
795*a866ce78SHaowei Wu   operator OnceAction<F>() const {  // NOLINT
796*a866ce78SHaowei Wu     // Return a OnceAction-compatible callable that calls Perform with the
797*a866ce78SHaowei Wu     // arguments it is provided. We could instead just return fun_, but then
798*a866ce78SHaowei Wu     // we'd need to handle the IsDoDefault() case separately.
799*a866ce78SHaowei Wu     struct OA {
800*a866ce78SHaowei Wu       Action<F> action;
801*a866ce78SHaowei Wu 
802*a866ce78SHaowei Wu       R operator()(Args... args) && {
803*a866ce78SHaowei Wu         return action.Perform(
804*a866ce78SHaowei Wu             std::forward_as_tuple(std::forward<Args>(args)...));
805*a866ce78SHaowei Wu       }
806*a866ce78SHaowei Wu     };
807*a866ce78SHaowei Wu 
808*a866ce78SHaowei Wu     return OA{*this};
809*a866ce78SHaowei Wu   }
810*a866ce78SHaowei Wu 
811a11cd0d9STom Stellard  private:
812a11cd0d9STom Stellard   template <typename G>
813a11cd0d9STom Stellard   friend class Action;
814a11cd0d9STom Stellard 
815*a866ce78SHaowei Wu   template <typename G>
816*a866ce78SHaowei Wu   void Init(G&& g, ::std::true_type) {
817*a866ce78SHaowei Wu     fun_ = ::std::forward<G>(g);
818*a866ce78SHaowei Wu   }
819*a866ce78SHaowei Wu 
820*a866ce78SHaowei Wu   template <typename G>
821*a866ce78SHaowei Wu   void Init(G&& g, ::std::false_type) {
822*a866ce78SHaowei Wu     fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};
823*a866ce78SHaowei Wu   }
824*a866ce78SHaowei Wu 
825*a866ce78SHaowei Wu   template <typename FunctionImpl>
826*a866ce78SHaowei Wu   struct IgnoreArgs {
827*a866ce78SHaowei Wu     template <typename... InArgs>
828*a866ce78SHaowei Wu     Result operator()(const InArgs&...) const {
829*a866ce78SHaowei Wu       return function_impl();
830*a866ce78SHaowei Wu     }
831*a866ce78SHaowei Wu 
832*a866ce78SHaowei Wu     FunctionImpl function_impl;
833*a866ce78SHaowei Wu   };
834*a866ce78SHaowei Wu 
835a11cd0d9STom Stellard   // fun_ is an empty function if and only if this is the DoDefault() action.
836a11cd0d9STom Stellard   ::std::function<F> fun_;
837a11cd0d9STom Stellard };
838a11cd0d9STom Stellard 
839a11cd0d9STom Stellard // The PolymorphicAction class template makes it easy to implement a
840a11cd0d9STom Stellard // polymorphic action (i.e. an action that can be used in mock
841a11cd0d9STom Stellard // functions of than one type, e.g. Return()).
842a11cd0d9STom Stellard //
843a11cd0d9STom Stellard // To define a polymorphic action, a user first provides a COPYABLE
844a11cd0d9STom Stellard // implementation class that has a Perform() method template:
845a11cd0d9STom Stellard //
846a11cd0d9STom Stellard //   class FooAction {
847a11cd0d9STom Stellard //    public:
848a11cd0d9STom Stellard //     template <typename Result, typename ArgumentTuple>
849a11cd0d9STom Stellard //     Result Perform(const ArgumentTuple& args) const {
850a11cd0d9STom Stellard //       // Processes the arguments and returns a result, using
851a11cd0d9STom Stellard //       // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
852a11cd0d9STom Stellard //     }
853a11cd0d9STom Stellard //     ...
854a11cd0d9STom Stellard //   };
855a11cd0d9STom Stellard //
856a11cd0d9STom Stellard // Then the user creates the polymorphic action using
857a11cd0d9STom Stellard // MakePolymorphicAction(object) where object has type FooAction.  See
858a11cd0d9STom Stellard // the definition of Return(void) and SetArgumentPointee<N>(value) for
859a11cd0d9STom Stellard // complete examples.
860a11cd0d9STom Stellard template <typename Impl>
861a11cd0d9STom Stellard class PolymorphicAction {
862a11cd0d9STom Stellard  public:
863a11cd0d9STom Stellard   explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
864a11cd0d9STom Stellard 
865a11cd0d9STom Stellard   template <typename F>
866a11cd0d9STom Stellard   operator Action<F>() const {
867a11cd0d9STom Stellard     return Action<F>(new MonomorphicImpl<F>(impl_));
868a11cd0d9STom Stellard   }
869a11cd0d9STom Stellard 
870a11cd0d9STom Stellard  private:
871a11cd0d9STom Stellard   template <typename F>
872a11cd0d9STom Stellard   class MonomorphicImpl : public ActionInterface<F> {
873a11cd0d9STom Stellard    public:
874a11cd0d9STom Stellard     typedef typename internal::Function<F>::Result Result;
875a11cd0d9STom Stellard     typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
876a11cd0d9STom Stellard 
877a11cd0d9STom Stellard     explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
878a11cd0d9STom Stellard 
879a11cd0d9STom Stellard     Result Perform(const ArgumentTuple& args) override {
880a11cd0d9STom Stellard       return impl_.template Perform<Result>(args);
881a11cd0d9STom Stellard     }
882a11cd0d9STom Stellard 
883a11cd0d9STom Stellard    private:
884a11cd0d9STom Stellard     Impl impl_;
885a11cd0d9STom Stellard   };
886a11cd0d9STom Stellard 
887a11cd0d9STom Stellard   Impl impl_;
888a11cd0d9STom Stellard };
889a11cd0d9STom Stellard 
890a11cd0d9STom Stellard // Creates an Action from its implementation and returns it.  The
891a11cd0d9STom Stellard // created Action object owns the implementation.
892a11cd0d9STom Stellard template <typename F>
893a11cd0d9STom Stellard Action<F> MakeAction(ActionInterface<F>* impl) {
894a11cd0d9STom Stellard   return Action<F>(impl);
895a11cd0d9STom Stellard }
896a11cd0d9STom Stellard 
897a11cd0d9STom Stellard // Creates a polymorphic action from its implementation.  This is
898a11cd0d9STom Stellard // easier to use than the PolymorphicAction<Impl> constructor as it
899a11cd0d9STom Stellard // doesn't require you to explicitly write the template argument, e.g.
900a11cd0d9STom Stellard //
901a11cd0d9STom Stellard //   MakePolymorphicAction(foo);
902a11cd0d9STom Stellard // vs
903a11cd0d9STom Stellard //   PolymorphicAction<TypeOfFoo>(foo);
904a11cd0d9STom Stellard template <typename Impl>
905a11cd0d9STom Stellard inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
906a11cd0d9STom Stellard   return PolymorphicAction<Impl>(impl);
907a11cd0d9STom Stellard }
908a11cd0d9STom Stellard 
909a11cd0d9STom Stellard namespace internal {
910a11cd0d9STom Stellard 
911a11cd0d9STom Stellard // Helper struct to specialize ReturnAction to execute a move instead of a copy
912a11cd0d9STom Stellard // on return. Useful for move-only types, but could be used on any type.
913a11cd0d9STom Stellard template <typename T>
914a11cd0d9STom Stellard struct ByMoveWrapper {
915a11cd0d9STom Stellard   explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
916a11cd0d9STom Stellard   T payload;
917a11cd0d9STom Stellard };
918a11cd0d9STom Stellard 
919*a866ce78SHaowei Wu // The general implementation of Return(R). Specializations follow below.
920*a866ce78SHaowei Wu template <typename R>
921*a866ce78SHaowei Wu class ReturnAction final {
922*a866ce78SHaowei Wu  public:
923*a866ce78SHaowei Wu   explicit ReturnAction(R value) : value_(std::move(value)) {}
924*a866ce78SHaowei Wu 
925*a866ce78SHaowei Wu   template <typename U, typename... Args,
926*a866ce78SHaowei Wu             typename = typename std::enable_if<conjunction<
927*a866ce78SHaowei Wu                 // See the requirements documented on Return.
928*a866ce78SHaowei Wu                 negation<std::is_same<void, U>>,  //
929*a866ce78SHaowei Wu                 negation<std::is_reference<U>>,   //
930*a866ce78SHaowei Wu                 std::is_convertible<R, U>,        //
931*a866ce78SHaowei Wu                 std::is_move_constructible<U>>::value>::type>
932*a866ce78SHaowei Wu   operator OnceAction<U(Args...)>() && {  // NOLINT
933*a866ce78SHaowei Wu     return Impl<U>(std::move(value_));
934*a866ce78SHaowei Wu   }
935*a866ce78SHaowei Wu 
936*a866ce78SHaowei Wu   template <typename U, typename... Args,
937*a866ce78SHaowei Wu             typename = typename std::enable_if<conjunction<
938*a866ce78SHaowei Wu                 // See the requirements documented on Return.
939*a866ce78SHaowei Wu                 negation<std::is_same<void, U>>,   //
940*a866ce78SHaowei Wu                 negation<std::is_reference<U>>,    //
941*a866ce78SHaowei Wu                 std::is_convertible<const R&, U>,  //
942*a866ce78SHaowei Wu                 std::is_copy_constructible<U>>::value>::type>
943*a866ce78SHaowei Wu   operator Action<U(Args...)>() const {  // NOLINT
944*a866ce78SHaowei Wu     return Impl<U>(value_);
945*a866ce78SHaowei Wu   }
946*a866ce78SHaowei Wu 
947*a866ce78SHaowei Wu  private:
948*a866ce78SHaowei Wu   // Implements the Return(x) action for a mock function that returns type U.
949*a866ce78SHaowei Wu   template <typename U>
950*a866ce78SHaowei Wu   class Impl final {
951*a866ce78SHaowei Wu    public:
952*a866ce78SHaowei Wu     // The constructor used when the return value is allowed to move from the
953*a866ce78SHaowei Wu     // input value (i.e. we are converting to OnceAction).
954*a866ce78SHaowei Wu     explicit Impl(R&& input_value)
955*a866ce78SHaowei Wu         : state_(new State(std::move(input_value))) {}
956*a866ce78SHaowei Wu 
957*a866ce78SHaowei Wu     // The constructor used when the return value is not allowed to move from
958*a866ce78SHaowei Wu     // the input value (i.e. we are converting to Action).
959*a866ce78SHaowei Wu     explicit Impl(const R& input_value) : state_(new State(input_value)) {}
960*a866ce78SHaowei Wu 
961*a866ce78SHaowei Wu     U operator()() && { return std::move(state_->value); }
962*a866ce78SHaowei Wu     U operator()() const& { return state_->value; }
963*a866ce78SHaowei Wu 
964*a866ce78SHaowei Wu    private:
965*a866ce78SHaowei Wu     // We put our state on the heap so that the compiler-generated copy/move
966*a866ce78SHaowei Wu     // constructors work correctly even when U is a reference-like type. This is
967*a866ce78SHaowei Wu     // necessary only because we eagerly create State::value (see the note on
968*a866ce78SHaowei Wu     // that symbol for details). If we instead had only the input value as a
969*a866ce78SHaowei Wu     // member then the default constructors would work fine.
970499d713bSHaowei Wu     //
971*a866ce78SHaowei Wu     // For example, when R is std::string and U is std::string_view, value is a
972*a866ce78SHaowei Wu     // reference to the string backed by input_value. The copy constructor would
973*a866ce78SHaowei Wu     // copy both, so that we wind up with a new input_value object (with the
974*a866ce78SHaowei Wu     // same contents) and a reference to the *old* input_value object rather
975*a866ce78SHaowei Wu     // than the new one.
976*a866ce78SHaowei Wu     struct State {
977*a866ce78SHaowei Wu       explicit State(const R& input_value_in)
978*a866ce78SHaowei Wu           : input_value(input_value_in),
979*a866ce78SHaowei Wu             // Make an implicit conversion to Result before initializing the U
980*a866ce78SHaowei Wu             // object we store, avoiding calling any explicit constructor of U
981*a866ce78SHaowei Wu             // from R.
982499d713bSHaowei Wu             //
983*a866ce78SHaowei Wu             // This simulates the language rules: a function with return type U
984*a866ce78SHaowei Wu             // that does `return R()` requires R to be implicitly convertible to
985*a866ce78SHaowei Wu             // U, and uses that path for the conversion, even U Result has an
986*a866ce78SHaowei Wu             // explicit constructor from R.
987*a866ce78SHaowei Wu             value(ImplicitCast_<U>(internal::as_const(input_value))) {}
988*a866ce78SHaowei Wu 
989*a866ce78SHaowei Wu       // As above, but for the case where we're moving from the ReturnAction
990*a866ce78SHaowei Wu       // object because it's being used as a OnceAction.
991*a866ce78SHaowei Wu       explicit State(R&& input_value_in)
992*a866ce78SHaowei Wu           : input_value(std::move(input_value_in)),
993*a866ce78SHaowei Wu             // For the same reason as above we make an implicit conversion to U
994*a866ce78SHaowei Wu             // before initializing the value.
995*a866ce78SHaowei Wu             //
996*a866ce78SHaowei Wu             // Unlike above we provide the input value as an rvalue to the
997*a866ce78SHaowei Wu             // implicit conversion because this is a OnceAction: it's fine if it
998*a866ce78SHaowei Wu             // wants to consume the input value.
999*a866ce78SHaowei Wu             value(ImplicitCast_<U>(std::move(input_value))) {}
1000*a866ce78SHaowei Wu 
1001*a866ce78SHaowei Wu       // A copy of the value originally provided by the user. We retain this in
1002*a866ce78SHaowei Wu       // addition to the value of the mock function's result type below in case
1003*a866ce78SHaowei Wu       // the latter is a reference-like type. See the std::string_view example
1004*a866ce78SHaowei Wu       // in the documentation on Return.
1005*a866ce78SHaowei Wu       R input_value;
1006*a866ce78SHaowei Wu 
1007*a866ce78SHaowei Wu       // The value we actually return, as the type returned by the mock function
1008*a866ce78SHaowei Wu       // itself.
1009*a866ce78SHaowei Wu       //
1010*a866ce78SHaowei Wu       // We eagerly initialize this here, rather than lazily doing the implicit
1011*a866ce78SHaowei Wu       // conversion automatically each time Perform is called, for historical
1012*a866ce78SHaowei Wu       // reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126)
1013*a866ce78SHaowei Wu       // made the Action<U()> conversion operator eagerly convert the R value to
1014*a866ce78SHaowei Wu       // U, but without keeping the R alive. This broke the use case discussed
1015*a866ce78SHaowei Wu       // in the documentation for Return, making reference-like types such as
1016*a866ce78SHaowei Wu       // std::string_view not safe to use as U where the input type R is a
1017*a866ce78SHaowei Wu       // value-like type such as std::string.
1018*a866ce78SHaowei Wu       //
1019*a866ce78SHaowei Wu       // The example the commit gave was not very clear, nor was the issue
1020*a866ce78SHaowei Wu       // thread (https://github.com/google/googlemock/issues/86), but it seems
1021*a866ce78SHaowei Wu       // the worry was about reference-like input types R that flatten to a
1022*a866ce78SHaowei Wu       // value-like type U when being implicitly converted. An example of this
1023*a866ce78SHaowei Wu       // is std::vector<bool>::reference, which is often a proxy type with an
1024*a866ce78SHaowei Wu       // reference to the underlying vector:
1025*a866ce78SHaowei Wu       //
1026*a866ce78SHaowei Wu       //     // Helper method: have the mock function return bools according
1027*a866ce78SHaowei Wu       //     // to the supplied script.
1028*a866ce78SHaowei Wu       //     void SetActions(MockFunction<bool(size_t)>& mock,
1029*a866ce78SHaowei Wu       //                     const std::vector<bool>& script) {
1030*a866ce78SHaowei Wu       //       for (size_t i = 0; i < script.size(); ++i) {
1031*a866ce78SHaowei Wu       //         EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i]));
1032*a866ce78SHaowei Wu       //       }
1033499d713bSHaowei Wu       //     }
1034499d713bSHaowei Wu       //
1035*a866ce78SHaowei Wu       //     TEST(Foo, Bar) {
1036*a866ce78SHaowei Wu       //       // Set actions using a temporary vector, whose operator[]
1037*a866ce78SHaowei Wu       //       // returns proxy objects that references that will be
1038*a866ce78SHaowei Wu       //       // dangling once the call to SetActions finishes and the
1039*a866ce78SHaowei Wu       //       // vector is destroyed.
1040*a866ce78SHaowei Wu       //       MockFunction<bool(size_t)> mock;
1041*a866ce78SHaowei Wu       //       SetActions(mock, {false, true});
1042499d713bSHaowei Wu       //
1043*a866ce78SHaowei Wu       //       EXPECT_FALSE(mock.AsStdFunction()(0));
1044*a866ce78SHaowei Wu       //       EXPECT_TRUE(mock.AsStdFunction()(1));
1045*a866ce78SHaowei Wu       //     }
1046499d713bSHaowei Wu       //
1047*a866ce78SHaowei Wu       // This eager conversion helps with a simple case like this, but doesn't
1048*a866ce78SHaowei Wu       // fully make these types work in general. For example the following still
1049*a866ce78SHaowei Wu       // uses a dangling reference:
1050*a866ce78SHaowei Wu       //
1051*a866ce78SHaowei Wu       //     TEST(Foo, Baz) {
1052*a866ce78SHaowei Wu       //       MockFunction<std::vector<std::string>()> mock;
1053*a866ce78SHaowei Wu       //
1054*a866ce78SHaowei Wu       //       // Return the same vector twice, and then the empty vector
1055*a866ce78SHaowei Wu       //       // thereafter.
1056*a866ce78SHaowei Wu       //       auto action = Return(std::initializer_list<std::string>{
1057*a866ce78SHaowei Wu       //           "taco", "burrito",
1058*a866ce78SHaowei Wu       //       });
1059*a866ce78SHaowei Wu       //
1060*a866ce78SHaowei Wu       //       EXPECT_CALL(mock, Call)
1061*a866ce78SHaowei Wu       //           .WillOnce(action)
1062*a866ce78SHaowei Wu       //           .WillOnce(action)
1063*a866ce78SHaowei Wu       //           .WillRepeatedly(Return(std::vector<std::string>{}));
1064*a866ce78SHaowei Wu       //
1065*a866ce78SHaowei Wu       //       EXPECT_THAT(mock.AsStdFunction()(),
1066*a866ce78SHaowei Wu       //                   ElementsAre("taco", "burrito"));
1067*a866ce78SHaowei Wu       //       EXPECT_THAT(mock.AsStdFunction()(),
1068*a866ce78SHaowei Wu       //                   ElementsAre("taco", "burrito"));
1069*a866ce78SHaowei Wu       //       EXPECT_THAT(mock.AsStdFunction()(), IsEmpty());
1070*a866ce78SHaowei Wu       //     }
1071*a866ce78SHaowei Wu       //
1072*a866ce78SHaowei Wu       U value;
1073*a866ce78SHaowei Wu     };
107454c1a9b2SZero Omega 
1075*a866ce78SHaowei Wu     const std::shared_ptr<State> state_;
1076*a866ce78SHaowei Wu   };
1077*a866ce78SHaowei Wu 
1078*a866ce78SHaowei Wu   R value_;
1079*a866ce78SHaowei Wu };
1080*a866ce78SHaowei Wu 
1081*a866ce78SHaowei Wu // A specialization of ReturnAction<R> when R is ByMoveWrapper<T> for some T.
1082*a866ce78SHaowei Wu //
1083*a866ce78SHaowei Wu // This version applies the type system-defeating hack of moving from T even in
1084*a866ce78SHaowei Wu // the const call operator, checking at runtime that it isn't called more than
1085*a866ce78SHaowei Wu // once, since the user has declared their intent to do so by using ByMove.
1086*a866ce78SHaowei Wu template <typename T>
1087*a866ce78SHaowei Wu class ReturnAction<ByMoveWrapper<T>> final {
1088*a866ce78SHaowei Wu  public:
1089*a866ce78SHaowei Wu   explicit ReturnAction(ByMoveWrapper<T> wrapper)
1090*a866ce78SHaowei Wu       : state_(new State(std::move(wrapper.payload))) {}
1091*a866ce78SHaowei Wu 
1092*a866ce78SHaowei Wu   T operator()() const {
1093*a866ce78SHaowei Wu     GTEST_CHECK_(!state_->called)
1094*a866ce78SHaowei Wu         << "A ByMove() action must be performed at most once.";
1095*a866ce78SHaowei Wu 
1096*a866ce78SHaowei Wu     state_->called = true;
1097*a866ce78SHaowei Wu     return std::move(state_->value);
109854c1a9b2SZero Omega   }
109954c1a9b2SZero Omega 
110054c1a9b2SZero Omega  private:
1101*a866ce78SHaowei Wu   // We store our state on the heap so that we are copyable as required by
1102*a866ce78SHaowei Wu   // Action, despite the fact that we are stateful and T may not be copyable.
1103*a866ce78SHaowei Wu   struct State {
1104*a866ce78SHaowei Wu     explicit State(T&& value_in) : value(std::move(value_in)) {}
110554c1a9b2SZero Omega 
1106*a866ce78SHaowei Wu     T value;
1107*a866ce78SHaowei Wu     bool called = false;
110854c1a9b2SZero Omega   };
1109a11cd0d9STom Stellard 
1110*a866ce78SHaowei Wu   const std::shared_ptr<State> state_;
1111a11cd0d9STom Stellard };
1112a11cd0d9STom Stellard 
1113a11cd0d9STom Stellard // Implements the ReturnNull() action.
1114a11cd0d9STom Stellard class ReturnNullAction {
1115a11cd0d9STom Stellard  public:
1116a11cd0d9STom Stellard   // Allows ReturnNull() to be used in any pointer-returning function. In C++11
1117a11cd0d9STom Stellard   // this is enforced by returning nullptr, and in non-C++11 by asserting a
1118a11cd0d9STom Stellard   // pointer type on compile time.
1119a11cd0d9STom Stellard   template <typename Result, typename ArgumentTuple>
1120a11cd0d9STom Stellard   static Result Perform(const ArgumentTuple&) {
1121a11cd0d9STom Stellard     return nullptr;
1122a11cd0d9STom Stellard   }
1123a11cd0d9STom Stellard };
1124a11cd0d9STom Stellard 
1125a11cd0d9STom Stellard // Implements the Return() action.
1126a11cd0d9STom Stellard class ReturnVoidAction {
1127a11cd0d9STom Stellard  public:
1128a11cd0d9STom Stellard   // Allows Return() to be used in any void-returning function.
1129a11cd0d9STom Stellard   template <typename Result, typename ArgumentTuple>
1130a11cd0d9STom Stellard   static void Perform(const ArgumentTuple&) {
1131a11cd0d9STom Stellard     static_assert(std::is_void<Result>::value, "Result should be void.");
1132a11cd0d9STom Stellard   }
1133a11cd0d9STom Stellard };
1134a11cd0d9STom Stellard 
1135a11cd0d9STom Stellard // Implements the polymorphic ReturnRef(x) action, which can be used
1136a11cd0d9STom Stellard // in any function that returns a reference to the type of x,
1137a11cd0d9STom Stellard // regardless of the argument types.
1138a11cd0d9STom Stellard template <typename T>
1139a11cd0d9STom Stellard class ReturnRefAction {
1140a11cd0d9STom Stellard  public:
1141a11cd0d9STom Stellard   // Constructs a ReturnRefAction object from the reference to be returned.
1142a11cd0d9STom Stellard   explicit ReturnRefAction(T& ref) : ref_(ref) {}  // NOLINT
1143a11cd0d9STom Stellard 
1144a11cd0d9STom Stellard   // This template type conversion operator allows ReturnRef(x) to be
1145a11cd0d9STom Stellard   // used in ANY function that returns a reference to x's type.
1146a11cd0d9STom Stellard   template <typename F>
1147a11cd0d9STom Stellard   operator Action<F>() const {
1148a11cd0d9STom Stellard     typedef typename Function<F>::Result Result;
1149a11cd0d9STom Stellard     // Asserts that the function return type is a reference.  This
1150a11cd0d9STom Stellard     // catches the user error of using ReturnRef(x) when Return(x)
1151a11cd0d9STom Stellard     // should be used, and generates some helpful error message.
1152*a866ce78SHaowei Wu     static_assert(std::is_reference<Result>::value,
1153*a866ce78SHaowei Wu                   "use Return instead of ReturnRef to return a value");
1154a11cd0d9STom Stellard     return Action<F>(new Impl<F>(ref_));
1155a11cd0d9STom Stellard   }
1156a11cd0d9STom Stellard 
1157a11cd0d9STom Stellard  private:
1158a11cd0d9STom Stellard   // Implements the ReturnRef(x) action for a particular function type F.
1159a11cd0d9STom Stellard   template <typename F>
1160a11cd0d9STom Stellard   class Impl : public ActionInterface<F> {
1161a11cd0d9STom Stellard    public:
1162a11cd0d9STom Stellard     typedef typename Function<F>::Result Result;
1163a11cd0d9STom Stellard     typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1164a11cd0d9STom Stellard 
1165a11cd0d9STom Stellard     explicit Impl(T& ref) : ref_(ref) {}  // NOLINT
1166a11cd0d9STom Stellard 
1167a11cd0d9STom Stellard     Result Perform(const ArgumentTuple&) override { return ref_; }
1168a11cd0d9STom Stellard 
1169a11cd0d9STom Stellard    private:
1170a11cd0d9STom Stellard     T& ref_;
1171a11cd0d9STom Stellard   };
1172a11cd0d9STom Stellard 
1173a11cd0d9STom Stellard   T& ref_;
1174a11cd0d9STom Stellard };
1175a11cd0d9STom Stellard 
1176a11cd0d9STom Stellard // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
1177a11cd0d9STom Stellard // used in any function that returns a reference to the type of x,
1178a11cd0d9STom Stellard // regardless of the argument types.
1179a11cd0d9STom Stellard template <typename T>
1180a11cd0d9STom Stellard class ReturnRefOfCopyAction {
1181a11cd0d9STom Stellard  public:
1182a11cd0d9STom Stellard   // Constructs a ReturnRefOfCopyAction object from the reference to
1183a11cd0d9STom Stellard   // be returned.
1184a11cd0d9STom Stellard   explicit ReturnRefOfCopyAction(const T& value) : value_(value) {}  // NOLINT
1185a11cd0d9STom Stellard 
1186a11cd0d9STom Stellard   // This template type conversion operator allows ReturnRefOfCopy(x) to be
1187a11cd0d9STom Stellard   // used in ANY function that returns a reference to x's type.
1188a11cd0d9STom Stellard   template <typename F>
1189a11cd0d9STom Stellard   operator Action<F>() const {
1190a11cd0d9STom Stellard     typedef typename Function<F>::Result Result;
1191a11cd0d9STom Stellard     // Asserts that the function return type is a reference.  This
1192a11cd0d9STom Stellard     // catches the user error of using ReturnRefOfCopy(x) when Return(x)
1193a11cd0d9STom Stellard     // should be used, and generates some helpful error message.
1194*a866ce78SHaowei Wu     static_assert(std::is_reference<Result>::value,
1195*a866ce78SHaowei Wu                   "use Return instead of ReturnRefOfCopy to return a value");
1196a11cd0d9STom Stellard     return Action<F>(new Impl<F>(value_));
1197a11cd0d9STom Stellard   }
1198a11cd0d9STom Stellard 
1199a11cd0d9STom Stellard  private:
1200a11cd0d9STom Stellard   // Implements the ReturnRefOfCopy(x) action for a particular function type F.
1201a11cd0d9STom Stellard   template <typename F>
1202a11cd0d9STom Stellard   class Impl : public ActionInterface<F> {
1203a11cd0d9STom Stellard    public:
1204a11cd0d9STom Stellard     typedef typename Function<F>::Result Result;
1205a11cd0d9STom Stellard     typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1206a11cd0d9STom Stellard 
1207a11cd0d9STom Stellard     explicit Impl(const T& value) : value_(value) {}  // NOLINT
1208a11cd0d9STom Stellard 
1209a11cd0d9STom Stellard     Result Perform(const ArgumentTuple&) override { return value_; }
1210a11cd0d9STom Stellard 
1211a11cd0d9STom Stellard    private:
1212a11cd0d9STom Stellard     T value_;
1213a11cd0d9STom Stellard   };
1214a11cd0d9STom Stellard 
1215a11cd0d9STom Stellard   const T value_;
1216*a866ce78SHaowei Wu };
1217a11cd0d9STom Stellard 
1218*a866ce78SHaowei Wu // Implements the polymorphic ReturnRoundRobin(v) action, which can be
1219*a866ce78SHaowei Wu // used in any function that returns the element_type of v.
1220*a866ce78SHaowei Wu template <typename T>
1221*a866ce78SHaowei Wu class ReturnRoundRobinAction {
1222*a866ce78SHaowei Wu  public:
1223*a866ce78SHaowei Wu   explicit ReturnRoundRobinAction(std::vector<T> values) {
1224*a866ce78SHaowei Wu     GTEST_CHECK_(!values.empty())
1225*a866ce78SHaowei Wu         << "ReturnRoundRobin requires at least one element.";
1226*a866ce78SHaowei Wu     state_->values = std::move(values);
1227*a866ce78SHaowei Wu   }
1228*a866ce78SHaowei Wu 
1229*a866ce78SHaowei Wu   template <typename... Args>
1230*a866ce78SHaowei Wu   T operator()(Args&&...) const {
1231*a866ce78SHaowei Wu     return state_->Next();
1232*a866ce78SHaowei Wu   }
1233*a866ce78SHaowei Wu 
1234*a866ce78SHaowei Wu  private:
1235*a866ce78SHaowei Wu   struct State {
1236*a866ce78SHaowei Wu     T Next() {
1237*a866ce78SHaowei Wu       T ret_val = values[i++];
1238*a866ce78SHaowei Wu       if (i == values.size()) i = 0;
1239*a866ce78SHaowei Wu       return ret_val;
1240*a866ce78SHaowei Wu     }
1241*a866ce78SHaowei Wu 
1242*a866ce78SHaowei Wu     std::vector<T> values;
1243*a866ce78SHaowei Wu     size_t i = 0;
1244*a866ce78SHaowei Wu   };
1245*a866ce78SHaowei Wu   std::shared_ptr<State> state_ = std::make_shared<State>();
1246a11cd0d9STom Stellard };
1247a11cd0d9STom Stellard 
1248a11cd0d9STom Stellard // Implements the polymorphic DoDefault() action.
1249a11cd0d9STom Stellard class DoDefaultAction {
1250a11cd0d9STom Stellard  public:
1251a11cd0d9STom Stellard   // This template type conversion operator allows DoDefault() to be
1252a11cd0d9STom Stellard   // used in any function.
1253a11cd0d9STom Stellard   template <typename F>
1254*a866ce78SHaowei Wu   operator Action<F>() const {
1255*a866ce78SHaowei Wu     return Action<F>();
1256*a866ce78SHaowei Wu   }  // NOLINT
1257a11cd0d9STom Stellard };
1258a11cd0d9STom Stellard 
1259a11cd0d9STom Stellard // Implements the Assign action to set a given pointer referent to a
1260a11cd0d9STom Stellard // particular value.
1261a11cd0d9STom Stellard template <typename T1, typename T2>
1262a11cd0d9STom Stellard class AssignAction {
1263a11cd0d9STom Stellard  public:
1264a11cd0d9STom Stellard   AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
1265a11cd0d9STom Stellard 
1266a11cd0d9STom Stellard   template <typename Result, typename ArgumentTuple>
1267a11cd0d9STom Stellard   void Perform(const ArgumentTuple& /* args */) const {
1268a11cd0d9STom Stellard     *ptr_ = value_;
1269a11cd0d9STom Stellard   }
1270a11cd0d9STom Stellard 
1271a11cd0d9STom Stellard  private:
1272a11cd0d9STom Stellard   T1* const ptr_;
1273a11cd0d9STom Stellard   const T2 value_;
1274a11cd0d9STom Stellard };
1275a11cd0d9STom Stellard 
1276*a866ce78SHaowei Wu #ifndef GTEST_OS_WINDOWS_MOBILE
1277a11cd0d9STom Stellard 
1278a11cd0d9STom Stellard // Implements the SetErrnoAndReturn action to simulate return from
1279a11cd0d9STom Stellard // various system calls and libc functions.
1280a11cd0d9STom Stellard template <typename T>
1281a11cd0d9STom Stellard class SetErrnoAndReturnAction {
1282a11cd0d9STom Stellard  public:
1283a11cd0d9STom Stellard   SetErrnoAndReturnAction(int errno_value, T result)
1284*a866ce78SHaowei Wu       : errno_(errno_value), result_(result) {}
1285a11cd0d9STom Stellard   template <typename Result, typename ArgumentTuple>
1286a11cd0d9STom Stellard   Result Perform(const ArgumentTuple& /* args */) const {
1287a11cd0d9STom Stellard     errno = errno_;
1288a11cd0d9STom Stellard     return result_;
1289a11cd0d9STom Stellard   }
1290a11cd0d9STom Stellard 
1291a11cd0d9STom Stellard  private:
1292a11cd0d9STom Stellard   const int errno_;
1293a11cd0d9STom Stellard   const T result_;
1294a11cd0d9STom Stellard };
1295a11cd0d9STom Stellard 
1296a11cd0d9STom Stellard #endif  // !GTEST_OS_WINDOWS_MOBILE
1297a11cd0d9STom Stellard 
1298a11cd0d9STom Stellard // Implements the SetArgumentPointee<N>(x) action for any function
1299a11cd0d9STom Stellard // whose N-th argument (0-based) is a pointer to x's type.
1300a11cd0d9STom Stellard template <size_t N, typename A, typename = void>
1301a11cd0d9STom Stellard struct SetArgumentPointeeAction {
1302a11cd0d9STom Stellard   A value;
1303a11cd0d9STom Stellard 
1304a11cd0d9STom Stellard   template <typename... Args>
1305a11cd0d9STom Stellard   void operator()(const Args&... args) const {
1306a11cd0d9STom Stellard     *::std::get<N>(std::tie(args...)) = value;
1307a11cd0d9STom Stellard   }
1308a11cd0d9STom Stellard };
1309a11cd0d9STom Stellard 
1310a11cd0d9STom Stellard // Implements the Invoke(object_ptr, &Class::Method) action.
1311a11cd0d9STom Stellard template <class Class, typename MethodPtr>
1312a11cd0d9STom Stellard struct InvokeMethodAction {
1313a11cd0d9STom Stellard   Class* const obj_ptr;
1314a11cd0d9STom Stellard   const MethodPtr method_ptr;
1315a11cd0d9STom Stellard 
1316a11cd0d9STom Stellard   template <typename... Args>
1317a11cd0d9STom Stellard   auto operator()(Args&&... args) const
1318a11cd0d9STom Stellard       -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
1319a11cd0d9STom Stellard     return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
1320a11cd0d9STom Stellard   }
1321a11cd0d9STom Stellard };
1322a11cd0d9STom Stellard 
1323a11cd0d9STom Stellard // Implements the InvokeWithoutArgs(f) action.  The template argument
1324a11cd0d9STom Stellard // FunctionImpl is the implementation type of f, which can be either a
1325a11cd0d9STom Stellard // function pointer or a functor.  InvokeWithoutArgs(f) can be used as an
1326a11cd0d9STom Stellard // Action<F> as long as f's type is compatible with F.
1327a11cd0d9STom Stellard template <typename FunctionImpl>
1328a11cd0d9STom Stellard struct InvokeWithoutArgsAction {
1329a11cd0d9STom Stellard   FunctionImpl function_impl;
1330a11cd0d9STom Stellard 
1331a11cd0d9STom Stellard   // Allows InvokeWithoutArgs(f) to be used as any action whose type is
1332a11cd0d9STom Stellard   // compatible with f.
1333a11cd0d9STom Stellard   template <typename... Args>
1334a11cd0d9STom Stellard   auto operator()(const Args&...) -> decltype(function_impl()) {
1335a11cd0d9STom Stellard     return function_impl();
1336a11cd0d9STom Stellard   }
1337a11cd0d9STom Stellard };
1338a11cd0d9STom Stellard 
1339a11cd0d9STom Stellard // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
1340a11cd0d9STom Stellard template <class Class, typename MethodPtr>
1341a11cd0d9STom Stellard struct InvokeMethodWithoutArgsAction {
1342a11cd0d9STom Stellard   Class* const obj_ptr;
1343a11cd0d9STom Stellard   const MethodPtr method_ptr;
1344a11cd0d9STom Stellard 
1345a11cd0d9STom Stellard   using ReturnType =
1346a11cd0d9STom Stellard       decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());
1347a11cd0d9STom Stellard 
1348a11cd0d9STom Stellard   template <typename... Args>
1349a11cd0d9STom Stellard   ReturnType operator()(const Args&...) const {
1350a11cd0d9STom Stellard     return (obj_ptr->*method_ptr)();
1351a11cd0d9STom Stellard   }
1352a11cd0d9STom Stellard };
1353a11cd0d9STom Stellard 
1354a11cd0d9STom Stellard // Implements the IgnoreResult(action) action.
1355a11cd0d9STom Stellard template <typename A>
1356a11cd0d9STom Stellard class IgnoreResultAction {
1357a11cd0d9STom Stellard  public:
1358a11cd0d9STom Stellard   explicit IgnoreResultAction(const A& action) : action_(action) {}
1359a11cd0d9STom Stellard 
1360a11cd0d9STom Stellard   template <typename F>
1361a11cd0d9STom Stellard   operator Action<F>() const {
1362a11cd0d9STom Stellard     // Assert statement belongs here because this is the best place to verify
1363a11cd0d9STom Stellard     // conditions on F. It produces the clearest error messages
1364a11cd0d9STom Stellard     // in most compilers.
1365a11cd0d9STom Stellard     // Impl really belongs in this scope as a local class but can't
1366a11cd0d9STom Stellard     // because MSVC produces duplicate symbols in different translation units
1367a11cd0d9STom Stellard     // in this case. Until MS fixes that bug we put Impl into the class scope
1368a11cd0d9STom Stellard     // and put the typedef both here (for use in assert statement) and
1369a11cd0d9STom Stellard     // in the Impl class. But both definitions must be the same.
1370a11cd0d9STom Stellard     typedef typename internal::Function<F>::Result Result;
1371a11cd0d9STom Stellard 
1372a11cd0d9STom Stellard     // Asserts at compile time that F returns void.
1373a11cd0d9STom Stellard     static_assert(std::is_void<Result>::value, "Result type should be void.");
1374a11cd0d9STom Stellard 
1375a11cd0d9STom Stellard     return Action<F>(new Impl<F>(action_));
1376a11cd0d9STom Stellard   }
1377a11cd0d9STom Stellard 
1378a11cd0d9STom Stellard  private:
1379a11cd0d9STom Stellard   template <typename F>
1380a11cd0d9STom Stellard   class Impl : public ActionInterface<F> {
1381a11cd0d9STom Stellard    public:
1382a11cd0d9STom Stellard     typedef typename internal::Function<F>::Result Result;
1383a11cd0d9STom Stellard     typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1384a11cd0d9STom Stellard 
1385a11cd0d9STom Stellard     explicit Impl(const A& action) : action_(action) {}
1386a11cd0d9STom Stellard 
1387a11cd0d9STom Stellard     void Perform(const ArgumentTuple& args) override {
1388a11cd0d9STom Stellard       // Performs the action and ignores its result.
1389a11cd0d9STom Stellard       action_.Perform(args);
1390a11cd0d9STom Stellard     }
1391a11cd0d9STom Stellard 
1392a11cd0d9STom Stellard    private:
1393a11cd0d9STom Stellard     // Type OriginalFunction is the same as F except that its return
1394a11cd0d9STom Stellard     // type is IgnoredValue.
1395*a866ce78SHaowei Wu     typedef
1396*a866ce78SHaowei Wu         typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction;
1397a11cd0d9STom Stellard 
1398a11cd0d9STom Stellard     const Action<OriginalFunction> action_;
1399a11cd0d9STom Stellard   };
1400a11cd0d9STom Stellard 
1401a11cd0d9STom Stellard   const A action_;
1402a11cd0d9STom Stellard };
1403a11cd0d9STom Stellard 
1404a11cd0d9STom Stellard template <typename InnerAction, size_t... I>
1405a11cd0d9STom Stellard struct WithArgsAction {
1406*a866ce78SHaowei Wu   InnerAction inner_action;
1407a11cd0d9STom Stellard 
1408*a866ce78SHaowei Wu   // The signature of the function as seen by the inner action, given an out
1409*a866ce78SHaowei Wu   // action with the given result and argument types.
1410a11cd0d9STom Stellard   template <typename R, typename... Args>
1411*a866ce78SHaowei Wu   using InnerSignature =
1412*a866ce78SHaowei Wu       R(typename std::tuple_element<I, std::tuple<Args...>>::type...);
141354c1a9b2SZero Omega 
1414*a866ce78SHaowei Wu   // Rather than a call operator, we must define conversion operators to
1415*a866ce78SHaowei Wu   // particular action types. This is necessary for embedded actions like
1416*a866ce78SHaowei Wu   // DoDefault(), which rely on an action conversion operators rather than
1417*a866ce78SHaowei Wu   // providing a call operator because even with a particular set of arguments
1418*a866ce78SHaowei Wu   // they don't have a fixed return type.
1419*a866ce78SHaowei Wu 
1420*a866ce78SHaowei Wu   template <
1421*a866ce78SHaowei Wu       typename R, typename... Args,
1422*a866ce78SHaowei Wu       typename std::enable_if<
1423*a866ce78SHaowei Wu           std::is_convertible<InnerAction,
1424*a866ce78SHaowei Wu                               // Unfortunately we can't use the InnerSignature
1425*a866ce78SHaowei Wu                               // alias here; MSVC complains about the I
1426*a866ce78SHaowei Wu                               // parameter pack not being expanded (error C3520)
1427*a866ce78SHaowei Wu                               // despite it being expanded in the type alias.
1428*a866ce78SHaowei Wu                               // TupleElement is also an MSVC workaround.
1429*a866ce78SHaowei Wu                               // See its definition for details.
1430*a866ce78SHaowei Wu                               OnceAction<R(internal::TupleElement<
1431*a866ce78SHaowei Wu                                            I, std::tuple<Args...>>...)>>::value,
1432*a866ce78SHaowei Wu           int>::type = 0>
1433*a866ce78SHaowei Wu   operator OnceAction<R(Args...)>() && {  // NOLINT
1434*a866ce78SHaowei Wu     struct OA {
1435*a866ce78SHaowei Wu       OnceAction<InnerSignature<R, Args...>> inner_action;
1436*a866ce78SHaowei Wu 
1437*a866ce78SHaowei Wu       R operator()(Args&&... args) && {
1438*a866ce78SHaowei Wu         return std::move(inner_action)
1439*a866ce78SHaowei Wu             .Call(std::get<I>(
1440*a866ce78SHaowei Wu                 std::forward_as_tuple(std::forward<Args>(args)...))...);
1441*a866ce78SHaowei Wu       }
1442*a866ce78SHaowei Wu     };
1443*a866ce78SHaowei Wu 
1444*a866ce78SHaowei Wu     return OA{std::move(inner_action)};
1445*a866ce78SHaowei Wu   }
1446*a866ce78SHaowei Wu 
1447*a866ce78SHaowei Wu   template <
1448*a866ce78SHaowei Wu       typename R, typename... Args,
1449*a866ce78SHaowei Wu       typename std::enable_if<
1450*a866ce78SHaowei Wu           std::is_convertible<const InnerAction&,
1451*a866ce78SHaowei Wu                               // Unfortunately we can't use the InnerSignature
1452*a866ce78SHaowei Wu                               // alias here; MSVC complains about the I
1453*a866ce78SHaowei Wu                               // parameter pack not being expanded (error C3520)
1454*a866ce78SHaowei Wu                               // despite it being expanded in the type alias.
1455*a866ce78SHaowei Wu                               // TupleElement is also an MSVC workaround.
1456*a866ce78SHaowei Wu                               // See its definition for details.
1457*a866ce78SHaowei Wu                               Action<R(internal::TupleElement<
1458*a866ce78SHaowei Wu                                        I, std::tuple<Args...>>...)>>::value,
1459*a866ce78SHaowei Wu           int>::type = 0>
1460*a866ce78SHaowei Wu   operator Action<R(Args...)>() const {  // NOLINT
1461*a866ce78SHaowei Wu     Action<InnerSignature<R, Args...>> converted(inner_action);
1462*a866ce78SHaowei Wu 
1463*a866ce78SHaowei Wu     return [converted](Args&&... args) -> R {
1464a11cd0d9STom Stellard       return converted.Perform(std::forward_as_tuple(
1465a11cd0d9STom Stellard           std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
1466a11cd0d9STom Stellard     };
1467a11cd0d9STom Stellard   }
1468a11cd0d9STom Stellard };
1469a11cd0d9STom Stellard 
1470a11cd0d9STom Stellard template <typename... Actions>
1471*a866ce78SHaowei Wu class DoAllAction;
1472*a866ce78SHaowei Wu 
1473*a866ce78SHaowei Wu // Base case: only a single action.
1474*a866ce78SHaowei Wu template <typename FinalAction>
1475*a866ce78SHaowei Wu class DoAllAction<FinalAction> {
1476*a866ce78SHaowei Wu  public:
1477*a866ce78SHaowei Wu   struct UserConstructorTag {};
1478*a866ce78SHaowei Wu 
1479*a866ce78SHaowei Wu   template <typename T>
1480*a866ce78SHaowei Wu   explicit DoAllAction(UserConstructorTag, T&& action)
1481*a866ce78SHaowei Wu       : final_action_(std::forward<T>(action)) {}
1482*a866ce78SHaowei Wu 
1483*a866ce78SHaowei Wu   // Rather than a call operator, we must define conversion operators to
1484*a866ce78SHaowei Wu   // particular action types. This is necessary for embedded actions like
1485*a866ce78SHaowei Wu   // DoDefault(), which rely on an action conversion operators rather than
1486*a866ce78SHaowei Wu   // providing a call operator because even with a particular set of arguments
1487*a866ce78SHaowei Wu   // they don't have a fixed return type.
1488*a866ce78SHaowei Wu 
1489*a866ce78SHaowei Wu   template <typename R, typename... Args,
1490*a866ce78SHaowei Wu             typename std::enable_if<
1491*a866ce78SHaowei Wu                 std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value,
1492*a866ce78SHaowei Wu                 int>::type = 0>
1493*a866ce78SHaowei Wu   operator OnceAction<R(Args...)>() && {  // NOLINT
1494*a866ce78SHaowei Wu     return std::move(final_action_);
1495499d713bSHaowei Wu   }
149654c1a9b2SZero Omega 
1497*a866ce78SHaowei Wu   template <
1498*a866ce78SHaowei Wu       typename R, typename... Args,
1499*a866ce78SHaowei Wu       typename std::enable_if<
1500*a866ce78SHaowei Wu           std::is_convertible<const FinalAction&, Action<R(Args...)>>::value,
1501*a866ce78SHaowei Wu           int>::type = 0>
1502*a866ce78SHaowei Wu   operator Action<R(Args...)>() const {  // NOLINT
1503*a866ce78SHaowei Wu     return final_action_;
1504*a866ce78SHaowei Wu   }
1505*a866ce78SHaowei Wu 
1506*a866ce78SHaowei Wu  private:
1507*a866ce78SHaowei Wu   FinalAction final_action_;
1508*a866ce78SHaowei Wu };
1509*a866ce78SHaowei Wu 
1510*a866ce78SHaowei Wu // Recursive case: support N actions by calling the initial action and then
1511*a866ce78SHaowei Wu // calling through to the base class containing N-1 actions.
1512*a866ce78SHaowei Wu template <typename InitialAction, typename... OtherActions>
1513*a866ce78SHaowei Wu class DoAllAction<InitialAction, OtherActions...>
1514*a866ce78SHaowei Wu     : private DoAllAction<OtherActions...> {
1515*a866ce78SHaowei Wu  private:
1516*a866ce78SHaowei Wu   using Base = DoAllAction<OtherActions...>;
1517*a866ce78SHaowei Wu 
1518*a866ce78SHaowei Wu   // The type of reference that should be provided to an initial action for a
1519*a866ce78SHaowei Wu   // mocked function parameter of type T.
1520*a866ce78SHaowei Wu   //
1521*a866ce78SHaowei Wu   // There are two quirks here:
1522*a866ce78SHaowei Wu   //
1523*a866ce78SHaowei Wu   //  *  Unlike most forwarding functions, we pass scalars through by value.
1524*a866ce78SHaowei Wu   //     This isn't strictly necessary because an lvalue reference would work
1525*a866ce78SHaowei Wu   //     fine too and be consistent with other non-reference types, but it's
1526*a866ce78SHaowei Wu   //     perhaps less surprising.
1527*a866ce78SHaowei Wu   //
1528*a866ce78SHaowei Wu   //     For example if the mocked function has signature void(int), then it
1529*a866ce78SHaowei Wu   //     might seem surprising for the user's initial action to need to be
1530*a866ce78SHaowei Wu   //     convertible to Action<void(const int&)>. This is perhaps less
1531*a866ce78SHaowei Wu   //     surprising for a non-scalar type where there may be a performance
1532*a866ce78SHaowei Wu   //     impact, or it might even be impossible, to pass by value.
1533*a866ce78SHaowei Wu   //
1534*a866ce78SHaowei Wu   //  *  More surprisingly, `const T&` is often not a const reference type.
1535*a866ce78SHaowei Wu   //     By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to
1536*a866ce78SHaowei Wu   //     U& or U&& for some non-scalar type U, then InitialActionArgType<T> is
1537*a866ce78SHaowei Wu   //     U&. In other words, we may hand over a non-const reference.
1538*a866ce78SHaowei Wu   //
1539*a866ce78SHaowei Wu   //     So for example, given some non-scalar type Obj we have the following
1540*a866ce78SHaowei Wu   //     mappings:
1541*a866ce78SHaowei Wu   //
1542*a866ce78SHaowei Wu   //            T               InitialActionArgType<T>
1543*a866ce78SHaowei Wu   //         -------            -----------------------
1544*a866ce78SHaowei Wu   //         Obj                const Obj&
1545*a866ce78SHaowei Wu   //         Obj&               Obj&
1546*a866ce78SHaowei Wu   //         Obj&&              Obj&
1547*a866ce78SHaowei Wu   //         const Obj          const Obj&
1548*a866ce78SHaowei Wu   //         const Obj&         const Obj&
1549*a866ce78SHaowei Wu   //         const Obj&&        const Obj&
1550*a866ce78SHaowei Wu   //
1551*a866ce78SHaowei Wu   //     In other words, the initial actions get a mutable view of an non-scalar
1552*a866ce78SHaowei Wu   //     argument if and only if the mock function itself accepts a non-const
1553*a866ce78SHaowei Wu   //     reference type. They are never given an rvalue reference to an
1554*a866ce78SHaowei Wu   //     non-scalar type.
1555*a866ce78SHaowei Wu   //
1556*a866ce78SHaowei Wu   //     This situation makes sense if you imagine use with a matcher that is
1557*a866ce78SHaowei Wu   //     designed to write through a reference. For example, if the caller wants
1558*a866ce78SHaowei Wu   //     to fill in a reference argument and then return a canned value:
1559*a866ce78SHaowei Wu   //
1560*a866ce78SHaowei Wu   //         EXPECT_CALL(mock, Call)
1561*a866ce78SHaowei Wu   //             .WillOnce(DoAll(SetArgReferee<0>(17), Return(19)));
1562*a866ce78SHaowei Wu   //
1563*a866ce78SHaowei Wu   template <typename T>
1564*a866ce78SHaowei Wu   using InitialActionArgType =
1565*a866ce78SHaowei Wu       typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;
1566*a866ce78SHaowei Wu 
1567a11cd0d9STom Stellard  public:
1568*a866ce78SHaowei Wu   struct UserConstructorTag {};
1569a11cd0d9STom Stellard 
1570*a866ce78SHaowei Wu   template <typename T, typename... U>
1571*a866ce78SHaowei Wu   explicit DoAllAction(UserConstructorTag, T&& initial_action,
1572*a866ce78SHaowei Wu                        U&&... other_actions)
1573*a866ce78SHaowei Wu       : Base({}, std::forward<U>(other_actions)...),
1574*a866ce78SHaowei Wu         initial_action_(std::forward<T>(initial_action)) {}
1575*a866ce78SHaowei Wu 
1576*a866ce78SHaowei Wu   template <typename R, typename... Args,
1577*a866ce78SHaowei Wu             typename std::enable_if<
1578*a866ce78SHaowei Wu                 conjunction<
1579*a866ce78SHaowei Wu                     // Both the initial action and the rest must support
1580*a866ce78SHaowei Wu                     // conversion to OnceAction.
1581*a866ce78SHaowei Wu                     std::is_convertible<
1582*a866ce78SHaowei Wu                         InitialAction,
1583*a866ce78SHaowei Wu                         OnceAction<void(InitialActionArgType<Args>...)>>,
1584*a866ce78SHaowei Wu                     std::is_convertible<Base, OnceAction<R(Args...)>>>::value,
1585*a866ce78SHaowei Wu                 int>::type = 0>
1586*a866ce78SHaowei Wu   operator OnceAction<R(Args...)>() && {  // NOLINT
1587*a866ce78SHaowei Wu     // Return an action that first calls the initial action with arguments
1588*a866ce78SHaowei Wu     // filtered through InitialActionArgType, then forwards arguments directly
1589*a866ce78SHaowei Wu     // to the base class to deal with the remaining actions.
1590*a866ce78SHaowei Wu     struct OA {
1591*a866ce78SHaowei Wu       OnceAction<void(InitialActionArgType<Args>...)> initial_action;
1592*a866ce78SHaowei Wu       OnceAction<R(Args...)> remaining_actions;
1593*a866ce78SHaowei Wu 
1594*a866ce78SHaowei Wu       R operator()(Args... args) && {
1595*a866ce78SHaowei Wu         std::move(initial_action)
1596*a866ce78SHaowei Wu             .Call(static_cast<InitialActionArgType<Args>>(args)...);
1597*a866ce78SHaowei Wu 
1598*a866ce78SHaowei Wu         return std::move(remaining_actions).Call(std::forward<Args>(args)...);
1599*a866ce78SHaowei Wu       }
1600*a866ce78SHaowei Wu     };
1601*a866ce78SHaowei Wu 
1602*a866ce78SHaowei Wu     return OA{
1603*a866ce78SHaowei Wu         std::move(initial_action_),
1604*a866ce78SHaowei Wu         std::move(static_cast<Base&>(*this)),
1605*a866ce78SHaowei Wu     };
1606*a866ce78SHaowei Wu   }
1607*a866ce78SHaowei Wu 
1608*a866ce78SHaowei Wu   template <
1609*a866ce78SHaowei Wu       typename R, typename... Args,
1610*a866ce78SHaowei Wu       typename std::enable_if<
1611*a866ce78SHaowei Wu           conjunction<
1612*a866ce78SHaowei Wu               // Both the initial action and the rest must support conversion to
1613*a866ce78SHaowei Wu               // Action.
1614*a866ce78SHaowei Wu               std::is_convertible<const InitialAction&,
1615*a866ce78SHaowei Wu                                   Action<void(InitialActionArgType<Args>...)>>,
1616*a866ce78SHaowei Wu               std::is_convertible<const Base&, Action<R(Args...)>>>::value,
1617*a866ce78SHaowei Wu           int>::type = 0>
1618*a866ce78SHaowei Wu   operator Action<R(Args...)>() const {  // NOLINT
1619*a866ce78SHaowei Wu     // Return an action that first calls the initial action with arguments
1620*a866ce78SHaowei Wu     // filtered through InitialActionArgType, then forwards arguments directly
1621*a866ce78SHaowei Wu     // to the base class to deal with the remaining actions.
1622*a866ce78SHaowei Wu     struct OA {
1623*a866ce78SHaowei Wu       Action<void(InitialActionArgType<Args>...)> initial_action;
1624*a866ce78SHaowei Wu       Action<R(Args...)> remaining_actions;
1625*a866ce78SHaowei Wu 
1626*a866ce78SHaowei Wu       R operator()(Args... args) const {
1627*a866ce78SHaowei Wu         initial_action.Perform(std::forward_as_tuple(
1628*a866ce78SHaowei Wu             static_cast<InitialActionArgType<Args>>(args)...));
1629*a866ce78SHaowei Wu 
1630*a866ce78SHaowei Wu         return remaining_actions.Perform(
1631*a866ce78SHaowei Wu             std::forward_as_tuple(std::forward<Args>(args)...));
1632*a866ce78SHaowei Wu       }
1633*a866ce78SHaowei Wu     };
1634*a866ce78SHaowei Wu 
1635*a866ce78SHaowei Wu     return OA{
1636*a866ce78SHaowei Wu         initial_action_,
1637*a866ce78SHaowei Wu         static_cast<const Base&>(*this),
1638*a866ce78SHaowei Wu     };
1639*a866ce78SHaowei Wu   }
1640*a866ce78SHaowei Wu 
1641*a866ce78SHaowei Wu  private:
1642*a866ce78SHaowei Wu   InitialAction initial_action_;
1643*a866ce78SHaowei Wu };
1644*a866ce78SHaowei Wu 
1645*a866ce78SHaowei Wu template <typename T, typename... Params>
1646*a866ce78SHaowei Wu struct ReturnNewAction {
1647*a866ce78SHaowei Wu   T* operator()() const {
1648*a866ce78SHaowei Wu     return internal::Apply(
1649*a866ce78SHaowei Wu         [](const Params&... unpacked_params) {
1650*a866ce78SHaowei Wu           return new T(unpacked_params...);
1651*a866ce78SHaowei Wu         },
1652*a866ce78SHaowei Wu         params);
1653*a866ce78SHaowei Wu   }
1654*a866ce78SHaowei Wu   std::tuple<Params...> params;
1655*a866ce78SHaowei Wu };
1656*a866ce78SHaowei Wu 
1657*a866ce78SHaowei Wu template <size_t k>
1658*a866ce78SHaowei Wu struct ReturnArgAction {
1659*a866ce78SHaowei Wu   template <typename... Args,
1660*a866ce78SHaowei Wu             typename = typename std::enable_if<(k < sizeof...(Args))>::type>
1661*a866ce78SHaowei Wu   auto operator()(Args&&... args) const -> decltype(std::get<k>(
1662*a866ce78SHaowei Wu       std::forward_as_tuple(std::forward<Args>(args)...))) {
1663*a866ce78SHaowei Wu     return std::get<k>(std::forward_as_tuple(std::forward<Args>(args)...));
1664*a866ce78SHaowei Wu   }
1665*a866ce78SHaowei Wu };
1666*a866ce78SHaowei Wu 
1667*a866ce78SHaowei Wu template <size_t k, typename Ptr>
1668*a866ce78SHaowei Wu struct SaveArgAction {
1669*a866ce78SHaowei Wu   Ptr pointer;
1670*a866ce78SHaowei Wu 
1671*a866ce78SHaowei Wu   template <typename... Args>
1672*a866ce78SHaowei Wu   void operator()(const Args&... args) const {
1673*a866ce78SHaowei Wu     *pointer = std::get<k>(std::tie(args...));
1674*a866ce78SHaowei Wu   }
1675*a866ce78SHaowei Wu };
1676*a866ce78SHaowei Wu 
1677*a866ce78SHaowei Wu template <size_t k, typename Ptr>
1678*a866ce78SHaowei Wu struct SaveArgPointeeAction {
1679*a866ce78SHaowei Wu   Ptr pointer;
1680*a866ce78SHaowei Wu 
1681*a866ce78SHaowei Wu   template <typename... Args>
1682*a866ce78SHaowei Wu   void operator()(const Args&... args) const {
1683*a866ce78SHaowei Wu     *pointer = *std::get<k>(std::tie(args...));
1684*a866ce78SHaowei Wu   }
1685*a866ce78SHaowei Wu };
1686*a866ce78SHaowei Wu 
1687*a866ce78SHaowei Wu template <size_t k, typename T>
1688*a866ce78SHaowei Wu struct SetArgRefereeAction {
1689*a866ce78SHaowei Wu   T value;
1690*a866ce78SHaowei Wu 
1691*a866ce78SHaowei Wu   template <typename... Args>
1692*a866ce78SHaowei Wu   void operator()(Args&&... args) const {
1693*a866ce78SHaowei Wu     using argk_type =
1694*a866ce78SHaowei Wu         typename ::std::tuple_element<k, std::tuple<Args...>>::type;
1695*a866ce78SHaowei Wu     static_assert(std::is_lvalue_reference<argk_type>::value,
1696*a866ce78SHaowei Wu                   "Argument must be a reference type.");
1697*a866ce78SHaowei Wu     std::get<k>(std::tie(args...)) = value;
1698*a866ce78SHaowei Wu   }
1699*a866ce78SHaowei Wu };
1700*a866ce78SHaowei Wu 
1701*a866ce78SHaowei Wu template <size_t k, typename I1, typename I2>
1702*a866ce78SHaowei Wu struct SetArrayArgumentAction {
1703*a866ce78SHaowei Wu   I1 first;
1704*a866ce78SHaowei Wu   I2 last;
1705*a866ce78SHaowei Wu 
1706*a866ce78SHaowei Wu   template <typename... Args>
1707*a866ce78SHaowei Wu   void operator()(const Args&... args) const {
1708*a866ce78SHaowei Wu     auto value = std::get<k>(std::tie(args...));
1709*a866ce78SHaowei Wu     for (auto it = first; it != last; ++it, (void)++value) {
1710*a866ce78SHaowei Wu       *value = *it;
1711*a866ce78SHaowei Wu     }
1712*a866ce78SHaowei Wu   }
1713*a866ce78SHaowei Wu };
1714*a866ce78SHaowei Wu 
1715*a866ce78SHaowei Wu template <size_t k>
1716*a866ce78SHaowei Wu struct DeleteArgAction {
1717*a866ce78SHaowei Wu   template <typename... Args>
1718*a866ce78SHaowei Wu   void operator()(const Args&... args) const {
1719*a866ce78SHaowei Wu     delete std::get<k>(std::tie(args...));
1720*a866ce78SHaowei Wu   }
1721*a866ce78SHaowei Wu };
1722*a866ce78SHaowei Wu 
1723*a866ce78SHaowei Wu template <typename Ptr>
1724*a866ce78SHaowei Wu struct ReturnPointeeAction {
1725*a866ce78SHaowei Wu   Ptr pointer;
1726*a866ce78SHaowei Wu   template <typename... Args>
1727*a866ce78SHaowei Wu   auto operator()(const Args&...) const -> decltype(*pointer) {
1728*a866ce78SHaowei Wu     return *pointer;
1729*a866ce78SHaowei Wu   }
1730*a866ce78SHaowei Wu };
1731*a866ce78SHaowei Wu 
1732*a866ce78SHaowei Wu #if GTEST_HAS_EXCEPTIONS
1733*a866ce78SHaowei Wu template <typename T>
1734*a866ce78SHaowei Wu struct ThrowAction {
1735*a866ce78SHaowei Wu   T exception;
1736*a866ce78SHaowei Wu   // We use a conversion operator to adapt to any return type.
1737a11cd0d9STom Stellard   template <typename R, typename... Args>
1738a11cd0d9STom Stellard   operator Action<R(Args...)>() const {  // NOLINT
1739*a866ce78SHaowei Wu     T copy = exception;
1740*a866ce78SHaowei Wu     return [copy](Args...) -> R { throw copy; };
1741a11cd0d9STom Stellard   }
1742a11cd0d9STom Stellard };
1743*a866ce78SHaowei Wu #endif  // GTEST_HAS_EXCEPTIONS
1744a11cd0d9STom Stellard 
1745a11cd0d9STom Stellard }  // namespace internal
1746a11cd0d9STom Stellard 
1747a11cd0d9STom Stellard // An Unused object can be implicitly constructed from ANY value.
1748a11cd0d9STom Stellard // This is handy when defining actions that ignore some or all of the
1749a11cd0d9STom Stellard // mock function arguments.  For example, given
1750a11cd0d9STom Stellard //
1751a11cd0d9STom Stellard //   MOCK_METHOD3(Foo, double(const string& label, double x, double y));
1752a11cd0d9STom Stellard //   MOCK_METHOD3(Bar, double(int index, double x, double y));
1753a11cd0d9STom Stellard //
1754a11cd0d9STom Stellard // instead of
1755a11cd0d9STom Stellard //
1756a11cd0d9STom Stellard //   double DistanceToOriginWithLabel(const string& label, double x, double y) {
1757a11cd0d9STom Stellard //     return sqrt(x*x + y*y);
1758a11cd0d9STom Stellard //   }
1759a11cd0d9STom Stellard //   double DistanceToOriginWithIndex(int index, double x, double y) {
1760a11cd0d9STom Stellard //     return sqrt(x*x + y*y);
1761a11cd0d9STom Stellard //   }
1762a11cd0d9STom Stellard //   ...
1763a11cd0d9STom Stellard //   EXPECT_CALL(mock, Foo("abc", _, _))
1764a11cd0d9STom Stellard //       .WillOnce(Invoke(DistanceToOriginWithLabel));
1765a11cd0d9STom Stellard //   EXPECT_CALL(mock, Bar(5, _, _))
1766a11cd0d9STom Stellard //       .WillOnce(Invoke(DistanceToOriginWithIndex));
1767a11cd0d9STom Stellard //
1768a11cd0d9STom Stellard // you could write
1769a11cd0d9STom Stellard //
1770a11cd0d9STom Stellard //   // We can declare any uninteresting argument as Unused.
1771a11cd0d9STom Stellard //   double DistanceToOrigin(Unused, double x, double y) {
1772a11cd0d9STom Stellard //     return sqrt(x*x + y*y);
1773a11cd0d9STom Stellard //   }
1774a11cd0d9STom Stellard //   ...
1775a11cd0d9STom Stellard //   EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
1776a11cd0d9STom Stellard //   EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
1777a11cd0d9STom Stellard typedef internal::IgnoredValue Unused;
1778a11cd0d9STom Stellard 
1779a11cd0d9STom Stellard // Creates an action that does actions a1, a2, ..., sequentially in
1780*a866ce78SHaowei Wu // each invocation. All but the last action will have a readonly view of the
1781*a866ce78SHaowei Wu // arguments.
1782a11cd0d9STom Stellard template <typename... Action>
1783a11cd0d9STom Stellard internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
1784a11cd0d9STom Stellard     Action&&... action) {
1785*a866ce78SHaowei Wu   return internal::DoAllAction<typename std::decay<Action>::type...>(
1786*a866ce78SHaowei Wu       {}, std::forward<Action>(action)...);
1787a11cd0d9STom Stellard }
1788a11cd0d9STom Stellard 
1789a11cd0d9STom Stellard // WithArg<k>(an_action) creates an action that passes the k-th
1790a11cd0d9STom Stellard // (0-based) argument of the mock function to an_action and performs
1791a11cd0d9STom Stellard // it.  It adapts an action accepting one argument to one that accepts
1792a11cd0d9STom Stellard // multiple arguments.  For convenience, we also provide
1793a11cd0d9STom Stellard // WithArgs<k>(an_action) (defined below) as a synonym.
1794a11cd0d9STom Stellard template <size_t k, typename InnerAction>
1795*a866ce78SHaowei Wu internal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg(
1796*a866ce78SHaowei Wu     InnerAction&& action) {
1797a11cd0d9STom Stellard   return {std::forward<InnerAction>(action)};
1798a11cd0d9STom Stellard }
1799a11cd0d9STom Stellard 
1800a11cd0d9STom Stellard // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
1801a11cd0d9STom Stellard // the selected arguments of the mock function to an_action and
1802a11cd0d9STom Stellard // performs it.  It serves as an adaptor between actions with
1803a11cd0d9STom Stellard // different argument lists.
1804a11cd0d9STom Stellard template <size_t k, size_t... ks, typename InnerAction>
1805a11cd0d9STom Stellard internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
1806a11cd0d9STom Stellard WithArgs(InnerAction&& action) {
1807a11cd0d9STom Stellard   return {std::forward<InnerAction>(action)};
1808a11cd0d9STom Stellard }
1809a11cd0d9STom Stellard 
1810a11cd0d9STom Stellard // WithoutArgs(inner_action) can be used in a mock function with a
1811a11cd0d9STom Stellard // non-empty argument list to perform inner_action, which takes no
1812a11cd0d9STom Stellard // argument.  In other words, it adapts an action accepting no
1813a11cd0d9STom Stellard // argument to one that accepts (and ignores) arguments.
1814a11cd0d9STom Stellard template <typename InnerAction>
1815*a866ce78SHaowei Wu internal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs(
1816*a866ce78SHaowei Wu     InnerAction&& action) {
1817a11cd0d9STom Stellard   return {std::forward<InnerAction>(action)};
1818a11cd0d9STom Stellard }
1819a11cd0d9STom Stellard 
1820*a866ce78SHaowei Wu // Creates an action that returns a value.
1821*a866ce78SHaowei Wu //
1822*a866ce78SHaowei Wu // The returned type can be used with a mock function returning a non-void,
1823*a866ce78SHaowei Wu // non-reference type U as follows:
1824*a866ce78SHaowei Wu //
1825*a866ce78SHaowei Wu //  *  If R is convertible to U and U is move-constructible, then the action can
1826*a866ce78SHaowei Wu //     be used with WillOnce.
1827*a866ce78SHaowei Wu //
1828*a866ce78SHaowei Wu //  *  If const R& is convertible to U and U is copy-constructible, then the
1829*a866ce78SHaowei Wu //     action can be used with both WillOnce and WillRepeatedly.
1830*a866ce78SHaowei Wu //
1831*a866ce78SHaowei Wu // The mock expectation contains the R value from which the U return value is
1832*a866ce78SHaowei Wu // constructed (a move/copy of the argument to Return). This means that the R
1833*a866ce78SHaowei Wu // value will survive at least until the mock object's expectations are cleared
1834*a866ce78SHaowei Wu // or the mock object is destroyed, meaning that U can safely be a
1835*a866ce78SHaowei Wu // reference-like type such as std::string_view:
1836*a866ce78SHaowei Wu //
1837*a866ce78SHaowei Wu //     // The mock function returns a view of a copy of the string fed to
1838*a866ce78SHaowei Wu //     // Return. The view is valid even after the action is performed.
1839*a866ce78SHaowei Wu //     MockFunction<std::string_view()> mock;
1840*a866ce78SHaowei Wu //     EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco")));
1841*a866ce78SHaowei Wu //     const std::string_view result = mock.AsStdFunction()();
1842*a866ce78SHaowei Wu //     EXPECT_EQ("taco", result);
1843*a866ce78SHaowei Wu //
1844a11cd0d9STom Stellard template <typename R>
1845a11cd0d9STom Stellard internal::ReturnAction<R> Return(R value) {
1846a11cd0d9STom Stellard   return internal::ReturnAction<R>(std::move(value));
1847a11cd0d9STom Stellard }
1848a11cd0d9STom Stellard 
1849a11cd0d9STom Stellard // Creates an action that returns NULL.
1850a11cd0d9STom Stellard inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
1851a11cd0d9STom Stellard   return MakePolymorphicAction(internal::ReturnNullAction());
1852a11cd0d9STom Stellard }
1853a11cd0d9STom Stellard 
1854a11cd0d9STom Stellard // Creates an action that returns from a void function.
1855a11cd0d9STom Stellard inline PolymorphicAction<internal::ReturnVoidAction> Return() {
1856a11cd0d9STom Stellard   return MakePolymorphicAction(internal::ReturnVoidAction());
1857a11cd0d9STom Stellard }
1858a11cd0d9STom Stellard 
1859a11cd0d9STom Stellard // Creates an action that returns the reference to a variable.
1860a11cd0d9STom Stellard template <typename R>
1861a11cd0d9STom Stellard inline internal::ReturnRefAction<R> ReturnRef(R& x) {  // NOLINT
1862a11cd0d9STom Stellard   return internal::ReturnRefAction<R>(x);
1863a11cd0d9STom Stellard }
1864a11cd0d9STom Stellard 
1865*a866ce78SHaowei Wu // Prevent using ReturnRef on reference to temporary.
1866*a866ce78SHaowei Wu template <typename R, R* = nullptr>
1867*a866ce78SHaowei Wu internal::ReturnRefAction<R> ReturnRef(R&&) = delete;
1868*a866ce78SHaowei Wu 
1869a11cd0d9STom Stellard // Creates an action that returns the reference to a copy of the
1870a11cd0d9STom Stellard // argument.  The copy is created when the action is constructed and
1871a11cd0d9STom Stellard // lives as long as the action.
1872a11cd0d9STom Stellard template <typename R>
1873a11cd0d9STom Stellard inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
1874a11cd0d9STom Stellard   return internal::ReturnRefOfCopyAction<R>(x);
1875a11cd0d9STom Stellard }
1876a11cd0d9STom Stellard 
1877*a866ce78SHaowei Wu // DEPRECATED: use Return(x) directly with WillOnce.
1878*a866ce78SHaowei Wu //
1879a11cd0d9STom Stellard // Modifies the parent action (a Return() action) to perform a move of the
1880a11cd0d9STom Stellard // argument instead of a copy.
1881a11cd0d9STom Stellard // Return(ByMove()) actions can only be executed once and will assert this
1882a11cd0d9STom Stellard // invariant.
1883a11cd0d9STom Stellard template <typename R>
1884a11cd0d9STom Stellard internal::ByMoveWrapper<R> ByMove(R x) {
1885a11cd0d9STom Stellard   return internal::ByMoveWrapper<R>(std::move(x));
1886a11cd0d9STom Stellard }
1887a11cd0d9STom Stellard 
1888*a866ce78SHaowei Wu // Creates an action that returns an element of `vals`. Calling this action will
1889*a866ce78SHaowei Wu // repeatedly return the next value from `vals` until it reaches the end and
1890*a866ce78SHaowei Wu // will restart from the beginning.
1891*a866ce78SHaowei Wu template <typename T>
1892*a866ce78SHaowei Wu internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {
1893*a866ce78SHaowei Wu   return internal::ReturnRoundRobinAction<T>(std::move(vals));
1894*a866ce78SHaowei Wu }
1895*a866ce78SHaowei Wu 
1896*a866ce78SHaowei Wu // Creates an action that returns an element of `vals`. Calling this action will
1897*a866ce78SHaowei Wu // repeatedly return the next value from `vals` until it reaches the end and
1898*a866ce78SHaowei Wu // will restart from the beginning.
1899*a866ce78SHaowei Wu template <typename T>
1900*a866ce78SHaowei Wu internal::ReturnRoundRobinAction<T> ReturnRoundRobin(
1901*a866ce78SHaowei Wu     std::initializer_list<T> vals) {
1902*a866ce78SHaowei Wu   return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));
1903*a866ce78SHaowei Wu }
1904*a866ce78SHaowei Wu 
1905a11cd0d9STom Stellard // Creates an action that does the default action for the give mock function.
1906a11cd0d9STom Stellard inline internal::DoDefaultAction DoDefault() {
1907a11cd0d9STom Stellard   return internal::DoDefaultAction();
1908a11cd0d9STom Stellard }
1909a11cd0d9STom Stellard 
1910a11cd0d9STom Stellard // Creates an action that sets the variable pointed by the N-th
1911a11cd0d9STom Stellard // (0-based) function argument to 'value'.
1912a11cd0d9STom Stellard template <size_t N, typename T>
1913*a866ce78SHaowei Wu internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {
1914*a866ce78SHaowei Wu   return {std::move(value)};
1915a11cd0d9STom Stellard }
1916a11cd0d9STom Stellard 
1917a11cd0d9STom Stellard // The following version is DEPRECATED.
1918a11cd0d9STom Stellard template <size_t N, typename T>
1919*a866ce78SHaowei Wu internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {
1920*a866ce78SHaowei Wu   return {std::move(value)};
1921a11cd0d9STom Stellard }
1922a11cd0d9STom Stellard 
1923a11cd0d9STom Stellard // Creates an action that sets a pointer referent to a given value.
1924a11cd0d9STom Stellard template <typename T1, typename T2>
1925a11cd0d9STom Stellard PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) {
1926a11cd0d9STom Stellard   return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
1927a11cd0d9STom Stellard }
1928a11cd0d9STom Stellard 
1929*a866ce78SHaowei Wu #ifndef GTEST_OS_WINDOWS_MOBILE
1930a11cd0d9STom Stellard 
1931a11cd0d9STom Stellard // Creates an action that sets errno and returns the appropriate error.
1932a11cd0d9STom Stellard template <typename T>
1933*a866ce78SHaowei Wu PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn(
1934*a866ce78SHaowei Wu     int errval, T result) {
1935a11cd0d9STom Stellard   return MakePolymorphicAction(
1936a11cd0d9STom Stellard       internal::SetErrnoAndReturnAction<T>(errval, result));
1937a11cd0d9STom Stellard }
1938a11cd0d9STom Stellard 
1939a11cd0d9STom Stellard #endif  // !GTEST_OS_WINDOWS_MOBILE
1940a11cd0d9STom Stellard 
1941a11cd0d9STom Stellard // Various overloads for Invoke().
1942a11cd0d9STom Stellard 
1943a11cd0d9STom Stellard // Legacy function.
1944a11cd0d9STom Stellard // Actions can now be implicitly constructed from callables. No need to create
1945a11cd0d9STom Stellard // wrapper objects.
1946a11cd0d9STom Stellard // This function exists for backwards compatibility.
1947a11cd0d9STom Stellard template <typename FunctionImpl>
1948a11cd0d9STom Stellard typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
1949a11cd0d9STom Stellard   return std::forward<FunctionImpl>(function_impl);
1950a11cd0d9STom Stellard }
1951a11cd0d9STom Stellard 
1952a11cd0d9STom Stellard // Creates an action that invokes the given method on the given object
1953a11cd0d9STom Stellard // with the mock function's arguments.
1954a11cd0d9STom Stellard template <class Class, typename MethodPtr>
1955a11cd0d9STom Stellard internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
1956a11cd0d9STom Stellard                                                       MethodPtr method_ptr) {
1957a11cd0d9STom Stellard   return {obj_ptr, method_ptr};
1958a11cd0d9STom Stellard }
1959a11cd0d9STom Stellard 
1960a11cd0d9STom Stellard // Creates an action that invokes 'function_impl' with no argument.
1961a11cd0d9STom Stellard template <typename FunctionImpl>
1962a11cd0d9STom Stellard internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
1963a11cd0d9STom Stellard InvokeWithoutArgs(FunctionImpl function_impl) {
1964a11cd0d9STom Stellard   return {std::move(function_impl)};
1965a11cd0d9STom Stellard }
1966a11cd0d9STom Stellard 
1967a11cd0d9STom Stellard // Creates an action that invokes the given method on the given object
1968a11cd0d9STom Stellard // with no argument.
1969a11cd0d9STom Stellard template <class Class, typename MethodPtr>
1970a11cd0d9STom Stellard internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
1971a11cd0d9STom Stellard     Class* obj_ptr, MethodPtr method_ptr) {
1972a11cd0d9STom Stellard   return {obj_ptr, method_ptr};
1973a11cd0d9STom Stellard }
1974a11cd0d9STom Stellard 
1975a11cd0d9STom Stellard // Creates an action that performs an_action and throws away its
1976a11cd0d9STom Stellard // result.  In other words, it changes the return type of an_action to
1977a11cd0d9STom Stellard // void.  an_action MUST NOT return void, or the code won't compile.
1978a11cd0d9STom Stellard template <typename A>
1979a11cd0d9STom Stellard inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1980a11cd0d9STom Stellard   return internal::IgnoreResultAction<A>(an_action);
1981a11cd0d9STom Stellard }
1982a11cd0d9STom Stellard 
1983a11cd0d9STom Stellard // Creates a reference wrapper for the given L-value.  If necessary,
1984a11cd0d9STom Stellard // you can explicitly specify the type of the reference.  For example,
1985a11cd0d9STom Stellard // suppose 'derived' is an object of type Derived, ByRef(derived)
1986a11cd0d9STom Stellard // would wrap a Derived&.  If you want to wrap a const Base& instead,
1987a11cd0d9STom Stellard // where Base is a base class of Derived, just write:
1988a11cd0d9STom Stellard //
1989a11cd0d9STom Stellard //   ByRef<const Base>(derived)
1990a11cd0d9STom Stellard //
1991a11cd0d9STom Stellard // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
1992a11cd0d9STom Stellard // However, it may still be used for consistency with ByMove().
1993a11cd0d9STom Stellard template <typename T>
1994a11cd0d9STom Stellard inline ::std::reference_wrapper<T> ByRef(T& l_value) {  // NOLINT
1995a11cd0d9STom Stellard   return ::std::reference_wrapper<T>(l_value);
1996a11cd0d9STom Stellard }
1997a11cd0d9STom Stellard 
1998*a866ce78SHaowei Wu // The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
1999*a866ce78SHaowei Wu // instance of type T, constructed on the heap with constructor arguments
2000*a866ce78SHaowei Wu // a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
2001*a866ce78SHaowei Wu template <typename T, typename... Params>
2002*a866ce78SHaowei Wu internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(
2003*a866ce78SHaowei Wu     Params&&... params) {
2004*a866ce78SHaowei Wu   return {std::forward_as_tuple(std::forward<Params>(params)...)};
2005*a866ce78SHaowei Wu }
2006*a866ce78SHaowei Wu 
2007*a866ce78SHaowei Wu // Action ReturnArg<k>() returns the k-th argument of the mock function.
2008*a866ce78SHaowei Wu template <size_t k>
2009*a866ce78SHaowei Wu internal::ReturnArgAction<k> ReturnArg() {
2010*a866ce78SHaowei Wu   return {};
2011*a866ce78SHaowei Wu }
2012*a866ce78SHaowei Wu 
2013*a866ce78SHaowei Wu // Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
2014*a866ce78SHaowei Wu // mock function to *pointer.
2015*a866ce78SHaowei Wu template <size_t k, typename Ptr>
2016*a866ce78SHaowei Wu internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {
2017*a866ce78SHaowei Wu   return {pointer};
2018*a866ce78SHaowei Wu }
2019*a866ce78SHaowei Wu 
2020*a866ce78SHaowei Wu // Action SaveArgPointee<k>(pointer) saves the value pointed to
2021*a866ce78SHaowei Wu // by the k-th (0-based) argument of the mock function to *pointer.
2022*a866ce78SHaowei Wu template <size_t k, typename Ptr>
2023*a866ce78SHaowei Wu internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {
2024*a866ce78SHaowei Wu   return {pointer};
2025*a866ce78SHaowei Wu }
2026*a866ce78SHaowei Wu 
2027*a866ce78SHaowei Wu // Action SetArgReferee<k>(value) assigns 'value' to the variable
2028*a866ce78SHaowei Wu // referenced by the k-th (0-based) argument of the mock function.
2029*a866ce78SHaowei Wu template <size_t k, typename T>
2030*a866ce78SHaowei Wu internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(
2031*a866ce78SHaowei Wu     T&& value) {
2032*a866ce78SHaowei Wu   return {std::forward<T>(value)};
2033*a866ce78SHaowei Wu }
2034*a866ce78SHaowei Wu 
2035*a866ce78SHaowei Wu // Action SetArrayArgument<k>(first, last) copies the elements in
2036*a866ce78SHaowei Wu // source range [first, last) to the array pointed to by the k-th
2037*a866ce78SHaowei Wu // (0-based) argument, which can be either a pointer or an
2038*a866ce78SHaowei Wu // iterator. The action does not take ownership of the elements in the
2039*a866ce78SHaowei Wu // source range.
2040*a866ce78SHaowei Wu template <size_t k, typename I1, typename I2>
2041*a866ce78SHaowei Wu internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,
2042*a866ce78SHaowei Wu                                                              I2 last) {
2043*a866ce78SHaowei Wu   return {first, last};
2044*a866ce78SHaowei Wu }
2045*a866ce78SHaowei Wu 
2046*a866ce78SHaowei Wu // Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
2047*a866ce78SHaowei Wu // function.
2048*a866ce78SHaowei Wu template <size_t k>
2049*a866ce78SHaowei Wu internal::DeleteArgAction<k> DeleteArg() {
2050*a866ce78SHaowei Wu   return {};
2051*a866ce78SHaowei Wu }
2052*a866ce78SHaowei Wu 
2053*a866ce78SHaowei Wu // This action returns the value pointed to by 'pointer'.
2054*a866ce78SHaowei Wu template <typename Ptr>
2055*a866ce78SHaowei Wu internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {
2056*a866ce78SHaowei Wu   return {pointer};
2057*a866ce78SHaowei Wu }
2058*a866ce78SHaowei Wu 
2059*a866ce78SHaowei Wu // Action Throw(exception) can be used in a mock function of any type
2060*a866ce78SHaowei Wu // to throw the given exception.  Any copyable value can be thrown.
2061*a866ce78SHaowei Wu #if GTEST_HAS_EXCEPTIONS
2062*a866ce78SHaowei Wu template <typename T>
2063*a866ce78SHaowei Wu internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) {
2064*a866ce78SHaowei Wu   return {std::forward<T>(exception)};
2065*a866ce78SHaowei Wu }
2066*a866ce78SHaowei Wu #endif  // GTEST_HAS_EXCEPTIONS
2067*a866ce78SHaowei Wu 
2068*a866ce78SHaowei Wu namespace internal {
2069*a866ce78SHaowei Wu 
2070*a866ce78SHaowei Wu // A macro from the ACTION* family (defined later in gmock-generated-actions.h)
2071*a866ce78SHaowei Wu // defines an action that can be used in a mock function.  Typically,
2072*a866ce78SHaowei Wu // these actions only care about a subset of the arguments of the mock
2073*a866ce78SHaowei Wu // function.  For example, if such an action only uses the second
2074*a866ce78SHaowei Wu // argument, it can be used in any mock function that takes >= 2
2075*a866ce78SHaowei Wu // arguments where the type of the second argument is compatible.
2076*a866ce78SHaowei Wu //
2077*a866ce78SHaowei Wu // Therefore, the action implementation must be prepared to take more
2078*a866ce78SHaowei Wu // arguments than it needs.  The ExcessiveArg type is used to
2079*a866ce78SHaowei Wu // represent those excessive arguments.  In order to keep the compiler
2080*a866ce78SHaowei Wu // error messages tractable, we define it in the testing namespace
2081*a866ce78SHaowei Wu // instead of testing::internal.  However, this is an INTERNAL TYPE
2082*a866ce78SHaowei Wu // and subject to change without notice, so a user MUST NOT USE THIS
2083*a866ce78SHaowei Wu // TYPE DIRECTLY.
2084*a866ce78SHaowei Wu struct ExcessiveArg {};
2085*a866ce78SHaowei Wu 
2086*a866ce78SHaowei Wu // Builds an implementation of an Action<> for some particular signature, using
2087*a866ce78SHaowei Wu // a class defined by an ACTION* macro.
2088*a866ce78SHaowei Wu template <typename F, typename Impl>
2089*a866ce78SHaowei Wu struct ActionImpl;
2090*a866ce78SHaowei Wu 
2091*a866ce78SHaowei Wu template <typename Impl>
2092*a866ce78SHaowei Wu struct ImplBase {
2093*a866ce78SHaowei Wu   struct Holder {
2094*a866ce78SHaowei Wu     // Allows each copy of the Action<> to get to the Impl.
2095*a866ce78SHaowei Wu     explicit operator const Impl&() const { return *ptr; }
2096*a866ce78SHaowei Wu     std::shared_ptr<Impl> ptr;
2097*a866ce78SHaowei Wu   };
2098*a866ce78SHaowei Wu   using type = typename std::conditional<std::is_constructible<Impl>::value,
2099*a866ce78SHaowei Wu                                          Impl, Holder>::type;
2100*a866ce78SHaowei Wu };
2101*a866ce78SHaowei Wu 
2102*a866ce78SHaowei Wu template <typename R, typename... Args, typename Impl>
2103*a866ce78SHaowei Wu struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
2104*a866ce78SHaowei Wu   using Base = typename ImplBase<Impl>::type;
2105*a866ce78SHaowei Wu   using function_type = R(Args...);
2106*a866ce78SHaowei Wu   using args_type = std::tuple<Args...>;
2107*a866ce78SHaowei Wu 
2108*a866ce78SHaowei Wu   ActionImpl() = default;  // Only defined if appropriate for Base.
2109*a866ce78SHaowei Wu   explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} {}
2110*a866ce78SHaowei Wu 
2111*a866ce78SHaowei Wu   R operator()(Args&&... arg) const {
2112*a866ce78SHaowei Wu     static constexpr size_t kMaxArgs =
2113*a866ce78SHaowei Wu         sizeof...(Args) <= 10 ? sizeof...(Args) : 10;
2114*a866ce78SHaowei Wu     return Apply(MakeIndexSequence<kMaxArgs>{},
2115*a866ce78SHaowei Wu                  MakeIndexSequence<10 - kMaxArgs>{},
2116*a866ce78SHaowei Wu                  args_type{std::forward<Args>(arg)...});
2117*a866ce78SHaowei Wu   }
2118*a866ce78SHaowei Wu 
2119*a866ce78SHaowei Wu   template <std::size_t... arg_id, std::size_t... excess_id>
2120*a866ce78SHaowei Wu   R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>,
2121*a866ce78SHaowei Wu           const args_type& args) const {
2122*a866ce78SHaowei Wu     // Impl need not be specific to the signature of action being implemented;
2123*a866ce78SHaowei Wu     // only the implementing function body needs to have all of the specific
2124*a866ce78SHaowei Wu     // types instantiated.  Up to 10 of the args that are provided by the
2125*a866ce78SHaowei Wu     // args_type get passed, followed by a dummy of unspecified type for the
2126*a866ce78SHaowei Wu     // remainder up to 10 explicit args.
2127*a866ce78SHaowei Wu     static constexpr ExcessiveArg kExcessArg{};
2128*a866ce78SHaowei Wu     return static_cast<const Impl&>(*this)
2129*a866ce78SHaowei Wu         .template gmock_PerformImpl<
2130*a866ce78SHaowei Wu             /*function_type=*/function_type, /*return_type=*/R,
2131*a866ce78SHaowei Wu             /*args_type=*/args_type,
2132*a866ce78SHaowei Wu             /*argN_type=*/
2133*a866ce78SHaowei Wu             typename std::tuple_element<arg_id, args_type>::type...>(
2134*a866ce78SHaowei Wu             /*args=*/args, std::get<arg_id>(args)...,
2135*a866ce78SHaowei Wu             ((void)excess_id, kExcessArg)...);
2136*a866ce78SHaowei Wu   }
2137*a866ce78SHaowei Wu };
2138*a866ce78SHaowei Wu 
2139*a866ce78SHaowei Wu // Stores a default-constructed Impl as part of the Action<>'s
2140*a866ce78SHaowei Wu // std::function<>. The Impl should be trivial to copy.
2141*a866ce78SHaowei Wu template <typename F, typename Impl>
2142*a866ce78SHaowei Wu ::testing::Action<F> MakeAction() {
2143*a866ce78SHaowei Wu   return ::testing::Action<F>(ActionImpl<F, Impl>());
2144*a866ce78SHaowei Wu }
2145*a866ce78SHaowei Wu 
2146*a866ce78SHaowei Wu // Stores just the one given instance of Impl.
2147*a866ce78SHaowei Wu template <typename F, typename Impl>
2148*a866ce78SHaowei Wu ::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {
2149*a866ce78SHaowei Wu   return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl)));
2150*a866ce78SHaowei Wu }
2151*a866ce78SHaowei Wu 
2152*a866ce78SHaowei Wu #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
2153*a866ce78SHaowei Wu   , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
2154*a866ce78SHaowei Wu #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_                 \
2155*a866ce78SHaowei Wu   const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
2156*a866ce78SHaowei Wu       GMOCK_INTERNAL_ARG_UNUSED, , 10)
2157*a866ce78SHaowei Wu 
2158*a866ce78SHaowei Wu #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
2159*a866ce78SHaowei Wu #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \
2160*a866ce78SHaowei Wu   const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)
2161*a866ce78SHaowei Wu 
2162*a866ce78SHaowei Wu #define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type
2163*a866ce78SHaowei Wu #define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \
2164*a866ce78SHaowei Wu   GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))
2165*a866ce78SHaowei Wu 
2166*a866ce78SHaowei Wu #define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type
2167*a866ce78SHaowei Wu #define GMOCK_ACTION_TYPENAME_PARAMS_(params) \
2168*a866ce78SHaowei Wu   GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))
2169*a866ce78SHaowei Wu 
2170*a866ce78SHaowei Wu #define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type
2171*a866ce78SHaowei Wu #define GMOCK_ACTION_TYPE_PARAMS_(params) \
2172*a866ce78SHaowei Wu   GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))
2173*a866ce78SHaowei Wu 
2174*a866ce78SHaowei Wu #define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \
2175*a866ce78SHaowei Wu   , param##_type gmock_p##i
2176*a866ce78SHaowei Wu #define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \
2177*a866ce78SHaowei Wu   GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))
2178*a866ce78SHaowei Wu 
2179*a866ce78SHaowei Wu #define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \
2180*a866ce78SHaowei Wu   , std::forward<param##_type>(gmock_p##i)
2181*a866ce78SHaowei Wu #define GMOCK_ACTION_GVALUE_PARAMS_(params) \
2182*a866ce78SHaowei Wu   GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))
2183*a866ce78SHaowei Wu 
2184*a866ce78SHaowei Wu #define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \
2185*a866ce78SHaowei Wu   , param(::std::forward<param##_type>(gmock_p##i))
2186*a866ce78SHaowei Wu #define GMOCK_ACTION_INIT_PARAMS_(params) \
2187*a866ce78SHaowei Wu   GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))
2188*a866ce78SHaowei Wu 
2189*a866ce78SHaowei Wu #define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;
2190*a866ce78SHaowei Wu #define GMOCK_ACTION_FIELD_PARAMS_(params) \
2191*a866ce78SHaowei Wu   GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
2192*a866ce78SHaowei Wu 
2193*a866ce78SHaowei Wu #define GMOCK_INTERNAL_ACTION(name, full_name, params)                         \
2194*a866ce78SHaowei Wu   template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                             \
2195*a866ce78SHaowei Wu   class full_name {                                                            \
2196*a866ce78SHaowei Wu    public:                                                                     \
2197*a866ce78SHaowei Wu     explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params))               \
2198*a866ce78SHaowei Wu         : impl_(std::make_shared<gmock_Impl>(                                  \
2199*a866ce78SHaowei Wu               GMOCK_ACTION_GVALUE_PARAMS_(params))) {}                         \
2200*a866ce78SHaowei Wu     full_name(const full_name&) = default;                                     \
2201*a866ce78SHaowei Wu     full_name(full_name&&) noexcept = default;                                 \
2202*a866ce78SHaowei Wu     template <typename F>                                                      \
2203*a866ce78SHaowei Wu     operator ::testing::Action<F>() const {                                    \
2204*a866ce78SHaowei Wu       return ::testing::internal::MakeAction<F>(impl_);                        \
2205*a866ce78SHaowei Wu     }                                                                          \
2206*a866ce78SHaowei Wu                                                                                \
2207*a866ce78SHaowei Wu    private:                                                                    \
2208*a866ce78SHaowei Wu     class gmock_Impl {                                                         \
2209*a866ce78SHaowei Wu      public:                                                                   \
2210*a866ce78SHaowei Wu       explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params))            \
2211*a866ce78SHaowei Wu           : GMOCK_ACTION_INIT_PARAMS_(params) {}                               \
2212*a866ce78SHaowei Wu       template <typename function_type, typename return_type,                  \
2213*a866ce78SHaowei Wu                 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>         \
2214*a866ce78SHaowei Wu       return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const;  \
2215*a866ce78SHaowei Wu       GMOCK_ACTION_FIELD_PARAMS_(params)                                       \
2216*a866ce78SHaowei Wu     };                                                                         \
2217*a866ce78SHaowei Wu     std::shared_ptr<const gmock_Impl> impl_;                                   \
2218*a866ce78SHaowei Wu   };                                                                           \
2219*a866ce78SHaowei Wu   template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                             \
2220*a866ce78SHaowei Wu   inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name(                    \
2221*a866ce78SHaowei Wu       GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_;        \
2222*a866ce78SHaowei Wu   template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                             \
2223*a866ce78SHaowei Wu   inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name(                    \
2224*a866ce78SHaowei Wu       GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) {                              \
2225*a866ce78SHaowei Wu     return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>(                       \
2226*a866ce78SHaowei Wu         GMOCK_ACTION_GVALUE_PARAMS_(params));                                  \
2227*a866ce78SHaowei Wu   }                                                                            \
2228*a866ce78SHaowei Wu   template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                             \
2229*a866ce78SHaowei Wu   template <typename function_type, typename return_type, typename args_type,  \
2230*a866ce78SHaowei Wu             GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>                                 \
2231*a866ce78SHaowei Wu   return_type                                                                  \
2232*a866ce78SHaowei Wu   full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \
2233*a866ce78SHaowei Wu       GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
2234*a866ce78SHaowei Wu 
2235*a866ce78SHaowei Wu }  // namespace internal
2236*a866ce78SHaowei Wu 
2237*a866ce78SHaowei Wu // Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.
2238*a866ce78SHaowei Wu #define ACTION(name)                                                          \
2239*a866ce78SHaowei Wu   class name##Action {                                                        \
2240*a866ce78SHaowei Wu    public:                                                                    \
2241*a866ce78SHaowei Wu     explicit name##Action() noexcept {}                                       \
2242*a866ce78SHaowei Wu     name##Action(const name##Action&) noexcept {}                             \
2243*a866ce78SHaowei Wu     template <typename F>                                                     \
2244*a866ce78SHaowei Wu     operator ::testing::Action<F>() const {                                   \
2245*a866ce78SHaowei Wu       return ::testing::internal::MakeAction<F, gmock_Impl>();                \
2246*a866ce78SHaowei Wu     }                                                                         \
2247*a866ce78SHaowei Wu                                                                               \
2248*a866ce78SHaowei Wu    private:                                                                   \
2249*a866ce78SHaowei Wu     class gmock_Impl {                                                        \
2250*a866ce78SHaowei Wu      public:                                                                  \
2251*a866ce78SHaowei Wu       template <typename function_type, typename return_type,                 \
2252*a866ce78SHaowei Wu                 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>        \
2253*a866ce78SHaowei Wu       return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
2254*a866ce78SHaowei Wu     };                                                                        \
2255*a866ce78SHaowei Wu   };                                                                          \
2256*a866ce78SHaowei Wu   inline name##Action name() GTEST_MUST_USE_RESULT_;                          \
2257*a866ce78SHaowei Wu   inline name##Action name() { return name##Action(); }                       \
2258*a866ce78SHaowei Wu   template <typename function_type, typename return_type, typename args_type, \
2259*a866ce78SHaowei Wu             GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>                                \
2260*a866ce78SHaowei Wu   return_type name##Action::gmock_Impl::gmock_PerformImpl(                    \
2261*a866ce78SHaowei Wu       GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
2262*a866ce78SHaowei Wu 
2263*a866ce78SHaowei Wu #define ACTION_P(name, ...) \
2264*a866ce78SHaowei Wu   GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))
2265*a866ce78SHaowei Wu 
2266*a866ce78SHaowei Wu #define ACTION_P2(name, ...) \
2267*a866ce78SHaowei Wu   GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))
2268*a866ce78SHaowei Wu 
2269*a866ce78SHaowei Wu #define ACTION_P3(name, ...) \
2270*a866ce78SHaowei Wu   GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))
2271*a866ce78SHaowei Wu 
2272*a866ce78SHaowei Wu #define ACTION_P4(name, ...) \
2273*a866ce78SHaowei Wu   GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))
2274*a866ce78SHaowei Wu 
2275*a866ce78SHaowei Wu #define ACTION_P5(name, ...) \
2276*a866ce78SHaowei Wu   GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))
2277*a866ce78SHaowei Wu 
2278*a866ce78SHaowei Wu #define ACTION_P6(name, ...) \
2279*a866ce78SHaowei Wu   GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))
2280*a866ce78SHaowei Wu 
2281*a866ce78SHaowei Wu #define ACTION_P7(name, ...) \
2282*a866ce78SHaowei Wu   GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))
2283*a866ce78SHaowei Wu 
2284*a866ce78SHaowei Wu #define ACTION_P8(name, ...) \
2285*a866ce78SHaowei Wu   GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))
2286*a866ce78SHaowei Wu 
2287*a866ce78SHaowei Wu #define ACTION_P9(name, ...) \
2288*a866ce78SHaowei Wu   GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))
2289*a866ce78SHaowei Wu 
2290*a866ce78SHaowei Wu #define ACTION_P10(name, ...) \
2291*a866ce78SHaowei Wu   GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))
2292*a866ce78SHaowei Wu 
2293a11cd0d9STom Stellard }  // namespace testing
2294a11cd0d9STom Stellard 
2295*a866ce78SHaowei Wu GTEST_DISABLE_MSC_WARNINGS_POP_()  // 4100
2296a11cd0d9STom Stellard 
2297*a866ce78SHaowei Wu #endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
2298