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