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