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 
31 // Google Mock - a framework for writing C++ mock classes.
32 //
33 // This file implements some commonly used actions.
34 
35 // GOOGLETEST_CM0002 DO NOT DELETE
36 
37 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
38 #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
39 
40 #ifndef _WIN32_WCE
41 # include <errno.h>
42 #endif
43 
44 #include <algorithm>
45 #include <functional>
46 #include <memory>
47 #include <string>
48 #include <type_traits>
49 #include <utility>
50 
51 #include "gmock/internal/gmock-internal-utils.h"
52 #include "gmock/internal/gmock-port.h"
53 
54 #ifdef _MSC_VER
55 # pragma warning(push)
56 # pragma warning(disable:4100)
57 #endif
58 
59 namespace testing {
60 
61 // To implement an action Foo, define:
62 //   1. a class FooAction that implements the ActionInterface interface, and
63 //   2. a factory function that creates an Action object from a
64 //      const FooAction*.
65 //
66 // The two-level delegation design follows that of Matcher, providing
67 // consistency for extension developers.  It also eases ownership
68 // management as Action objects can now be copied like plain values.
69 
70 namespace internal {
71 
72 // BuiltInDefaultValueGetter<T, true>::Get() returns a
73 // default-constructed T value.  BuiltInDefaultValueGetter<T,
74 // false>::Get() crashes with an error.
75 //
76 // This primary template is used when kDefaultConstructible is true.
77 template <typename T, bool kDefaultConstructible>
78 struct BuiltInDefaultValueGetter {
GetBuiltInDefaultValueGetter79   static T Get() { return T(); }
80 };
81 template <typename T>
82 struct BuiltInDefaultValueGetter<T, false> {
83   static T Get() {
84     Assert(false, __FILE__, __LINE__,
85            "Default action undefined for the function return type.");
86     return internal::Invalid<T>();
87     // The above statement will never be reached, but is required in
88     // order for this function to compile.
89   }
90 };
91 
92 // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
93 // for type T, which is NULL when T is a raw pointer type, 0 when T is
94 // a numeric type, false when T is bool, or "" when T is string or
95 // std::string.  In addition, in C++11 and above, it turns a
96 // default-constructed T value if T is default constructible.  For any
97 // other type T, the built-in default T value is undefined, and the
98 // function will abort the process.
99 template <typename T>
100 class BuiltInDefaultValue {
101  public:
102   // This function returns true iff type T has a built-in default value.
103   static bool Exists() {
104     return ::std::is_default_constructible<T>::value;
105   }
106 
107   static T Get() {
108     return BuiltInDefaultValueGetter<
109         T, ::std::is_default_constructible<T>::value>::Get();
110   }
111 };
112 
113 // This partial specialization says that we use the same built-in
114 // default value for T and const T.
115 template <typename T>
116 class BuiltInDefaultValue<const T> {
117  public:
118   static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
119   static T Get() { return BuiltInDefaultValue<T>::Get(); }
120 };
121 
122 // This partial specialization defines the default values for pointer
123 // types.
124 template <typename T>
125 class BuiltInDefaultValue<T*> {
126  public:
127   static bool Exists() { return true; }
128   static T* Get() { return nullptr; }
129 };
130 
131 // The following specializations define the default values for
132 // specific types we care about.
133 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
134   template <> \
135   class BuiltInDefaultValue<type> { \
136    public: \
137     static bool Exists() { return true; } \
138     static type Get() { return value; } \
139   }
140 
141 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, );  // NOLINT
142 #if GTEST_HAS_GLOBAL_STRING
143 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
144 #endif  // GTEST_HAS_GLOBAL_STRING
145 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
146 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
147 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
148 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
149 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
150 
151 // There's no need for a default action for signed wchar_t, as that
152 // type is the same as wchar_t for gcc, and invalid for MSVC.
153 //
154 // There's also no need for a default action for unsigned wchar_t, as
155 // that type is the same as unsigned int for gcc, and invalid for
156 // MSVC.
157 #if GMOCK_WCHAR_T_IS_NATIVE_
158 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U);  // NOLINT
159 #endif
160 
161 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U);  // NOLINT
162 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0);     // NOLINT
163 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
164 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
165 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL);  // NOLINT
166 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L);     // NOLINT
167 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
168 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
169 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
170 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
171 
172 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
173 
174 }  // namespace internal
175 
176 // When an unexpected function call is encountered, Google Mock will
177 // let it return a default value if the user has specified one for its
178 // return type, or if the return type has a built-in default value;
179 // otherwise Google Mock won't know what value to return and will have
180 // to abort the process.
181 //
182 // The DefaultValue<T> class allows a user to specify the
183 // default value for a type T that is both copyable and publicly
184 // destructible (i.e. anything that can be used as a function return
185 // type).  The usage is:
186 //
187 //   // Sets the default value for type T to be foo.
188 //   DefaultValue<T>::Set(foo);
189 template <typename T>
190 class DefaultValue {
191  public:
192   // Sets the default value for type T; requires T to be
193   // copy-constructable and have a public destructor.
194   static void Set(T x) {
195     delete producer_;
196     producer_ = new FixedValueProducer(x);
197   }
198 
199   // Provides a factory function to be called to generate the default value.
200   // This method can be used even if T is only move-constructible, but it is not
201   // limited to that case.
202   typedef T (*FactoryFunction)();
203   static void SetFactory(FactoryFunction factory) {
204     delete producer_;
205     producer_ = new FactoryValueProducer(factory);
206   }
207 
208   // Unsets the default value for type T.
209   static void Clear() {
210     delete producer_;
211     producer_ = nullptr;
212   }
213 
214   // Returns true iff the user has set the default value for type T.
215   static bool IsSet() { return producer_ != nullptr; }
216 
217   // Returns true if T has a default return value set by the user or there
218   // exists a built-in default value.
219   static bool Exists() {
220     return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
221   }
222 
223   // Returns the default value for type T if the user has set one;
224   // otherwise returns the built-in default value. Requires that Exists()
225   // is true, which ensures that the return value is well-defined.
226   static T Get() {
227     return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
228                                 : producer_->Produce();
229   }
230 
231  private:
232   class ValueProducer {
233    public:
234     virtual ~ValueProducer() {}
235     virtual T Produce() = 0;
236   };
237 
238   class FixedValueProducer : public ValueProducer {
239    public:
240     explicit FixedValueProducer(T value) : value_(value) {}
241     T Produce() override { return value_; }
242 
243    private:
244     const T value_;
245     GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
246   };
247 
248   class FactoryValueProducer : public ValueProducer {
249    public:
250     explicit FactoryValueProducer(FactoryFunction factory)
251         : factory_(factory) {}
252     T Produce() override { return factory_(); }
253 
254    private:
255     const FactoryFunction factory_;
256     GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
257   };
258 
259   static ValueProducer* producer_;
260 };
261 
262 // This partial specialization allows a user to set default values for
263 // reference types.
264 template <typename T>
265 class DefaultValue<T&> {
266  public:
267   // Sets the default value for type T&.
268   static void Set(T& x) {  // NOLINT
269     address_ = &x;
270   }
271 
272   // Unsets the default value for type T&.
273   static void Clear() { address_ = nullptr; }
274 
275   // Returns true iff the user has set the default value for type T&.
276   static bool IsSet() { return address_ != nullptr; }
277 
278   // Returns true if T has a default return value set by the user or there
279   // exists a built-in default value.
280   static bool Exists() {
281     return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
282   }
283 
284   // Returns the default value for type T& if the user has set one;
285   // otherwise returns the built-in default value if there is one;
286   // otherwise aborts the process.
287   static T& Get() {
288     return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
289                                : *address_;
290   }
291 
292  private:
293   static T* address_;
294 };
295 
296 // This specialization allows DefaultValue<void>::Get() to
297 // compile.
298 template <>
299 class DefaultValue<void> {
300  public:
301   static bool Exists() { return true; }
302   static void Get() {}
303 };
304 
305 // Points to the user-set default value for type T.
306 template <typename T>
307 typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
308 
309 // Points to the user-set default value for type T&.
310 template <typename T>
311 T* DefaultValue<T&>::address_ = nullptr;
312 
313 // Implement this interface to define an action for function type F.
314 template <typename F>
315 class ActionInterface {
316  public:
317   typedef typename internal::Function<F>::Result Result;
318   typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
319 
320   ActionInterface() {}
321   virtual ~ActionInterface() {}
322 
323   // Performs the action.  This method is not const, as in general an
324   // action can have side effects and be stateful.  For example, a
325   // get-the-next-element-from-the-collection action will need to
326   // remember the current element.
327   virtual Result Perform(const ArgumentTuple& args) = 0;
328 
329  private:
330   GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
331 };
332 
333 // An Action<F> is a copyable and IMMUTABLE (except by assignment)
334 // object that represents an action to be taken when a mock function
335 // of type F is called.  The implementation of Action<T> is just a
336 // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
337 // You can view an object implementing ActionInterface<F> as a
338 // concrete action (including its current state), and an Action<F>
339 // object as a handle to it.
340 template <typename F>
341 class Action {
342   // Adapter class to allow constructing Action from a legacy ActionInterface.
343   // New code should create Actions from functors instead.
344   struct ActionAdapter {
345     // Adapter must be copyable to satisfy std::function requirements.
346     ::std::shared_ptr<ActionInterface<F>> impl_;
347 
348     template <typename... Args>
349     typename internal::Function<F>::Result operator()(Args&&... args) {
350       return impl_->Perform(
351           ::std::forward_as_tuple(::std::forward<Args>(args)...));
352     }
353   };
354 
355  public:
356   typedef typename internal::Function<F>::Result Result;
357   typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
358 
359   // Constructs a null Action.  Needed for storing Action objects in
360   // STL containers.
361   Action() {}
362 
363   // Construct an Action from a specified callable.
364   // This cannot take std::function directly, because then Action would not be
365   // directly constructible from lambda (it would require two conversions).
366   template <typename G,
367             typename = typename ::std::enable_if<
368                 ::std::is_constructible<::std::function<F>, G>::value>::type>
369   Action(G&& fun) : fun_(::std::forward<G>(fun)) {}  // NOLINT
370 
371   // Constructs an Action from its implementation.
372   explicit Action(ActionInterface<F>* impl)
373       : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
374 
375   // This constructor allows us to turn an Action<Func> object into an
376   // Action<F>, as long as F's arguments can be implicitly converted
377   // to Func's and Func's return type can be implicitly converted to F's.
378   template <typename Func>
379   explicit Action(const Action<Func>& action) : fun_(action.fun_) {}
380 
381   // Returns true iff this is the DoDefault() action.
382   bool IsDoDefault() const { return fun_ == nullptr; }
383 
384   // Performs the action.  Note that this method is const even though
385   // the corresponding method in ActionInterface is not.  The reason
386   // is that a const Action<F> means that it cannot be re-bound to
387   // another concrete action, not that the concrete action it binds to
388   // cannot change state.  (Think of the difference between a const
389   // pointer and a pointer to const.)
390   Result Perform(ArgumentTuple args) const {
391     if (IsDoDefault()) {
392       internal::IllegalDoDefault(__FILE__, __LINE__);
393     }
394     return internal::Apply(fun_, ::std::move(args));
395   }
396 
397  private:
398   template <typename G>
399   friend class Action;
400 
401   // fun_ is an empty function iff this is the DoDefault() action.
402   ::std::function<F> fun_;
403 };
404 
405 // The PolymorphicAction class template makes it easy to implement a
406 // polymorphic action (i.e. an action that can be used in mock
407 // functions of than one type, e.g. Return()).
408 //
409 // To define a polymorphic action, a user first provides a COPYABLE
410 // implementation class that has a Perform() method template:
411 //
412 //   class FooAction {
413 //    public:
414 //     template <typename Result, typename ArgumentTuple>
415 //     Result Perform(const ArgumentTuple& args) const {
416 //       // Processes the arguments and returns a result, using
417 //       // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
418 //     }
419 //     ...
420 //   };
421 //
422 // Then the user creates the polymorphic action using
423 // MakePolymorphicAction(object) where object has type FooAction.  See
424 // the definition of Return(void) and SetArgumentPointee<N>(value) for
425 // complete examples.
426 template <typename Impl>
427 class PolymorphicAction {
428  public:
429   explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
430 
431   template <typename F>
432   operator Action<F>() const {
433     return Action<F>(new MonomorphicImpl<F>(impl_));
434   }
435 
436  private:
437   template <typename F>
438   class MonomorphicImpl : public ActionInterface<F> {
439    public:
440     typedef typename internal::Function<F>::Result Result;
441     typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
442 
443     explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
444 
445     Result Perform(const ArgumentTuple& args) override {
446       return impl_.template Perform<Result>(args);
447     }
448 
449    private:
450     Impl impl_;
451 
452     GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
453   };
454 
455   Impl impl_;
456 
457   GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
458 };
459 
460 // Creates an Action from its implementation and returns it.  The
461 // created Action object owns the implementation.
462 template <typename F>
463 Action<F> MakeAction(ActionInterface<F>* impl) {
464   return Action<F>(impl);
465 }
466 
467 // Creates a polymorphic action from its implementation.  This is
468 // easier to use than the PolymorphicAction<Impl> constructor as it
469 // doesn't require you to explicitly write the template argument, e.g.
470 //
471 //   MakePolymorphicAction(foo);
472 // vs
473 //   PolymorphicAction<TypeOfFoo>(foo);
474 template <typename Impl>
475 inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
476   return PolymorphicAction<Impl>(impl);
477 }
478 
479 namespace internal {
480 
481 // Helper struct to specialize ReturnAction to execute a move instead of a copy
482 // on return. Useful for move-only types, but could be used on any type.
483 template <typename T>
484 struct ByMoveWrapper {
485   explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
486   T payload;
487 };
488 
489 // Implements the polymorphic Return(x) action, which can be used in
490 // any function that returns the type of x, regardless of the argument
491 // types.
492 //
493 // Note: The value passed into Return must be converted into
494 // Function<F>::Result when this action is cast to Action<F> rather than
495 // when that action is performed. This is important in scenarios like
496 //
497 // MOCK_METHOD1(Method, T(U));
498 // ...
499 // {
500 //   Foo foo;
501 //   X x(&foo);
502 //   EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
503 // }
504 //
505 // In the example above the variable x holds reference to foo which leaves
506 // scope and gets destroyed.  If copying X just copies a reference to foo,
507 // that copy will be left with a hanging reference.  If conversion to T
508 // makes a copy of foo, the above code is safe. To support that scenario, we
509 // need to make sure that the type conversion happens inside the EXPECT_CALL
510 // statement, and conversion of the result of Return to Action<T(U)> is a
511 // good place for that.
512 //
513 // The real life example of the above scenario happens when an invocation
514 // of gtl::Container() is passed into Return.
515 //
516 template <typename R>
517 class ReturnAction {
518  public:
519   // Constructs a ReturnAction object from the value to be returned.
520   // 'value' is passed by value instead of by const reference in order
521   // to allow Return("string literal") to compile.
522   explicit ReturnAction(R value) : value_(new R(std::move(value))) {}
523 
524   // This template type conversion operator allows Return(x) to be
525   // used in ANY function that returns x's type.
526   template <typename F>
527   operator Action<F>() const {  // NOLINT
528     // Assert statement belongs here because this is the best place to verify
529     // conditions on F. It produces the clearest error messages
530     // in most compilers.
531     // Impl really belongs in this scope as a local class but can't
532     // because MSVC produces duplicate symbols in different translation units
533     // in this case. Until MS fixes that bug we put Impl into the class scope
534     // and put the typedef both here (for use in assert statement) and
535     // in the Impl class. But both definitions must be the same.
536     typedef typename Function<F>::Result Result;
537     GTEST_COMPILE_ASSERT_(
538         !is_reference<Result>::value,
539         use_ReturnRef_instead_of_Return_to_return_a_reference);
540     static_assert(!std::is_void<Result>::value,
541                   "Can't use Return() on an action expected to return `void`.");
542     return Action<F>(new Impl<R, F>(value_));
543   }
544 
545  private:
546   // Implements the Return(x) action for a particular function type F.
547   template <typename R_, typename F>
548   class Impl : public ActionInterface<F> {
549    public:
550     typedef typename Function<F>::Result Result;
551     typedef typename Function<F>::ArgumentTuple ArgumentTuple;
552 
553     // The implicit cast is necessary when Result has more than one
554     // single-argument constructor (e.g. Result is std::vector<int>) and R
555     // has a type conversion operator template.  In that case, value_(value)
556     // won't compile as the compiler doesn't known which constructor of
557     // Result to call.  ImplicitCast_ forces the compiler to convert R to
558     // Result without considering explicit constructors, thus resolving the
559     // ambiguity. value_ is then initialized using its copy constructor.
560     explicit Impl(const std::shared_ptr<R>& value)
561         : value_before_cast_(*value),
562           value_(ImplicitCast_<Result>(value_before_cast_)) {}
563 
564     Result Perform(const ArgumentTuple&) override { return value_; }
565 
566    private:
567     GTEST_COMPILE_ASSERT_(!is_reference<Result>::value,
568                           Result_cannot_be_a_reference_type);
569     // We save the value before casting just in case it is being cast to a
570     // wrapper type.
571     R value_before_cast_;
572     Result value_;
573 
574     GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
575   };
576 
577   // Partially specialize for ByMoveWrapper. This version of ReturnAction will
578   // move its contents instead.
579   template <typename R_, typename F>
580   class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
581    public:
582     typedef typename Function<F>::Result Result;
583     typedef typename Function<F>::ArgumentTuple ArgumentTuple;
584 
585     explicit Impl(const std::shared_ptr<R>& wrapper)
586         : performed_(false), wrapper_(wrapper) {}
587 
588     Result Perform(const ArgumentTuple&) override {
589       GTEST_CHECK_(!performed_)
590           << "A ByMove() action should only be performed once.";
591       performed_ = true;
592       return std::move(wrapper_->payload);
593     }
594 
595    private:
596     bool performed_;
597     const std::shared_ptr<R> wrapper_;
598 
599     GTEST_DISALLOW_ASSIGN_(Impl);
600   };
601 
602   const std::shared_ptr<R> value_;
603 
604   GTEST_DISALLOW_ASSIGN_(ReturnAction);
605 };
606 
607 // Implements the ReturnNull() action.
608 class ReturnNullAction {
609  public:
610   // Allows ReturnNull() to be used in any pointer-returning function. In C++11
611   // this is enforced by returning nullptr, and in non-C++11 by asserting a
612   // pointer type on compile time.
613   template <typename Result, typename ArgumentTuple>
614   static Result Perform(const ArgumentTuple&) {
615     return nullptr;
616   }
617 };
618 
619 // Implements the Return() action.
620 class ReturnVoidAction {
621  public:
622   // Allows Return() to be used in any void-returning function.
623   template <typename Result, typename ArgumentTuple>
624   static void Perform(const ArgumentTuple&) {
625     CompileAssertTypesEqual<void, Result>();
626   }
627 };
628 
629 // Implements the polymorphic ReturnRef(x) action, which can be used
630 // in any function that returns a reference to the type of x,
631 // regardless of the argument types.
632 template <typename T>
633 class ReturnRefAction {
634  public:
635   // Constructs a ReturnRefAction object from the reference to be returned.
636   explicit ReturnRefAction(T& ref) : ref_(ref) {}  // NOLINT
637 
638   // This template type conversion operator allows ReturnRef(x) to be
639   // used in ANY function that returns a reference to x's type.
640   template <typename F>
641   operator Action<F>() const {
642     typedef typename Function<F>::Result Result;
643     // Asserts that the function return type is a reference.  This
644     // catches the user error of using ReturnRef(x) when Return(x)
645     // should be used, and generates some helpful error message.
646     GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value,
647                           use_Return_instead_of_ReturnRef_to_return_a_value);
648     return Action<F>(new Impl<F>(ref_));
649   }
650 
651  private:
652   // Implements the ReturnRef(x) action for a particular function type F.
653   template <typename F>
654   class Impl : public ActionInterface<F> {
655    public:
656     typedef typename Function<F>::Result Result;
657     typedef typename Function<F>::ArgumentTuple ArgumentTuple;
658 
659     explicit Impl(T& ref) : ref_(ref) {}  // NOLINT
660 
661     Result Perform(const ArgumentTuple&) override { return ref_; }
662 
663    private:
664     T& ref_;
665 
666     GTEST_DISALLOW_ASSIGN_(Impl);
667   };
668 
669   T& ref_;
670 
671   GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
672 };
673 
674 // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
675 // used in any function that returns a reference to the type of x,
676 // regardless of the argument types.
677 template <typename T>
678 class ReturnRefOfCopyAction {
679  public:
680   // Constructs a ReturnRefOfCopyAction object from the reference to
681   // be returned.
682   explicit ReturnRefOfCopyAction(const T& value) : value_(value) {}  // NOLINT
683 
684   // This template type conversion operator allows ReturnRefOfCopy(x) to be
685   // used in ANY function that returns a reference to x's type.
686   template <typename F>
687   operator Action<F>() const {
688     typedef typename Function<F>::Result Result;
689     // Asserts that the function return type is a reference.  This
690     // catches the user error of using ReturnRefOfCopy(x) when Return(x)
691     // should be used, and generates some helpful error message.
692     GTEST_COMPILE_ASSERT_(
693         internal::is_reference<Result>::value,
694         use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
695     return Action<F>(new Impl<F>(value_));
696   }
697 
698  private:
699   // Implements the ReturnRefOfCopy(x) action for a particular function type F.
700   template <typename F>
701   class Impl : public ActionInterface<F> {
702    public:
703     typedef typename Function<F>::Result Result;
704     typedef typename Function<F>::ArgumentTuple ArgumentTuple;
705 
706     explicit Impl(const T& value) : value_(value) {}  // NOLINT
707 
708     Result Perform(const ArgumentTuple&) override { return value_; }
709 
710    private:
711     T value_;
712 
713     GTEST_DISALLOW_ASSIGN_(Impl);
714   };
715 
716   const T value_;
717 
718   GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
719 };
720 
721 // Implements the polymorphic DoDefault() action.
722 class DoDefaultAction {
723  public:
724   // This template type conversion operator allows DoDefault() to be
725   // used in any function.
726   template <typename F>
727   operator Action<F>() const { return Action<F>(); }  // NOLINT
728 };
729 
730 // Implements the Assign action to set a given pointer referent to a
731 // particular value.
732 template <typename T1, typename T2>
733 class AssignAction {
734  public:
735   AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
736 
737   template <typename Result, typename ArgumentTuple>
738   void Perform(const ArgumentTuple& /* args */) const {
739     *ptr_ = value_;
740   }
741 
742  private:
743   T1* const ptr_;
744   const T2 value_;
745 
746   GTEST_DISALLOW_ASSIGN_(AssignAction);
747 };
748 
749 #if !GTEST_OS_WINDOWS_MOBILE
750 
751 // Implements the SetErrnoAndReturn action to simulate return from
752 // various system calls and libc functions.
753 template <typename T>
754 class SetErrnoAndReturnAction {
755  public:
756   SetErrnoAndReturnAction(int errno_value, T result)
757       : errno_(errno_value),
758         result_(result) {}
759   template <typename Result, typename ArgumentTuple>
760   Result Perform(const ArgumentTuple& /* args */) const {
761     errno = errno_;
762     return result_;
763   }
764 
765  private:
766   const int errno_;
767   const T result_;
768 
769   GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
770 };
771 
772 #endif  // !GTEST_OS_WINDOWS_MOBILE
773 
774 // Implements the SetArgumentPointee<N>(x) action for any function
775 // whose N-th argument (0-based) is a pointer to x's type.  The
776 // template parameter kIsProto is true iff type A is ProtocolMessage,
777 // proto2::Message, or a sub-class of those.
778 template <size_t N, typename A, bool kIsProto>
779 class SetArgumentPointeeAction {
780  public:
781   // Constructs an action that sets the variable pointed to by the
782   // N-th function argument to 'value'.
783   explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
784 
785   template <typename Result, typename ArgumentTuple>
786   void Perform(const ArgumentTuple& args) const {
787     CompileAssertTypesEqual<void, Result>();
788     *::std::get<N>(args) = value_;
789   }
790 
791  private:
792   const A value_;
793 
794   GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
795 };
796 
797 template <size_t N, typename Proto>
798 class SetArgumentPointeeAction<N, Proto, true> {
799  public:
800   // Constructs an action that sets the variable pointed to by the
801   // N-th function argument to 'proto'.  Both ProtocolMessage and
802   // proto2::Message have the CopyFrom() method, so the same
803   // implementation works for both.
804   explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
805     proto_->CopyFrom(proto);
806   }
807 
808   template <typename Result, typename ArgumentTuple>
809   void Perform(const ArgumentTuple& args) const {
810     CompileAssertTypesEqual<void, Result>();
811     ::std::get<N>(args)->CopyFrom(*proto_);
812   }
813 
814  private:
815   const std::shared_ptr<Proto> proto_;
816 
817   GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
818 };
819 
820 // Implements the Invoke(object_ptr, &Class::Method) action.
821 template <class Class, typename MethodPtr>
822 struct InvokeMethodAction {
823   Class* const obj_ptr;
824   const MethodPtr method_ptr;
825 
826   template <typename... Args>
827   auto operator()(Args&&... args) const
828       -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
829     return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
830   }
831 };
832 
833 // Implements the InvokeWithoutArgs(f) action.  The template argument
834 // FunctionImpl is the implementation type of f, which can be either a
835 // function pointer or a functor.  InvokeWithoutArgs(f) can be used as an
836 // Action<F> as long as f's type is compatible with F.
837 template <typename FunctionImpl>
838 struct InvokeWithoutArgsAction {
839   FunctionImpl function_impl;
840 
841   // Allows InvokeWithoutArgs(f) to be used as any action whose type is
842   // compatible with f.
843   template <typename... Args>
844   auto operator()(const Args&...) -> decltype(function_impl()) {
845     return function_impl();
846   }
847 };
848 
849 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
850 template <class Class, typename MethodPtr>
851 struct InvokeMethodWithoutArgsAction {
852   Class* const obj_ptr;
853   const MethodPtr method_ptr;
854 
855   using ReturnType = typename std::result_of<MethodPtr(Class*)>::type;
856 
857   template <typename... Args>
858   ReturnType operator()(const Args&...) const {
859     return (obj_ptr->*method_ptr)();
860   }
861 };
862 
863 // Implements the IgnoreResult(action) action.
864 template <typename A>
865 class IgnoreResultAction {
866  public:
867   explicit IgnoreResultAction(const A& action) : action_(action) {}
868 
869   template <typename F>
870   operator Action<F>() const {
871     // Assert statement belongs here because this is the best place to verify
872     // conditions on F. It produces the clearest error messages
873     // in most compilers.
874     // Impl really belongs in this scope as a local class but can't
875     // because MSVC produces duplicate symbols in different translation units
876     // in this case. Until MS fixes that bug we put Impl into the class scope
877     // and put the typedef both here (for use in assert statement) and
878     // in the Impl class. But both definitions must be the same.
879     typedef typename internal::Function<F>::Result Result;
880 
881     // Asserts at compile time that F returns void.
882     CompileAssertTypesEqual<void, Result>();
883 
884     return Action<F>(new Impl<F>(action_));
885   }
886 
887  private:
888   template <typename F>
889   class Impl : public ActionInterface<F> {
890    public:
891     typedef typename internal::Function<F>::Result Result;
892     typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
893 
894     explicit Impl(const A& action) : action_(action) {}
895 
896     void Perform(const ArgumentTuple& args) override {
897       // Performs the action and ignores its result.
898       action_.Perform(args);
899     }
900 
901    private:
902     // Type OriginalFunction is the same as F except that its return
903     // type is IgnoredValue.
904     typedef typename internal::Function<F>::MakeResultIgnoredValue
905         OriginalFunction;
906 
907     const Action<OriginalFunction> action_;
908 
909     GTEST_DISALLOW_ASSIGN_(Impl);
910   };
911 
912   const A action_;
913 
914   GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
915 };
916 
917 template <typename InnerAction, size_t... I>
918 struct WithArgsAction {
919   InnerAction action;
920 
921   // The inner action could be anything convertible to Action<X>.
922   // We use the conversion operator to detect the signature of the inner Action.
923   template <typename R, typename... Args>
924   operator Action<R(Args...)>() const {  // NOLINT
925     Action<R(typename std::tuple_element<I, std::tuple<Args...>>::type...)>
926         converted(action);
927 
928     return [converted](Args... args) -> R {
929       return converted.Perform(std::forward_as_tuple(
930         std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
931     };
932   }
933 };
934 
935 template <typename... Actions>
936 struct DoAllAction {
937  private:
938   template <typename... Args, size_t... I>
939   std::vector<Action<void(Args...)>> Convert(IndexSequence<I...>) const {
940     return {std::get<I>(actions)...};
941   }
942 
943  public:
944   std::tuple<Actions...> actions;
945 
946   template <typename R, typename... Args>
947   operator Action<R(Args...)>() const {  // NOLINT
948     struct Op {
949       std::vector<Action<void(Args...)>> converted;
950       Action<R(Args...)> last;
951       R operator()(Args... args) const {
952         auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
953         for (auto& a : converted) {
954           a.Perform(tuple_args);
955         }
956         return last.Perform(tuple_args);
957       }
958     };
959     return Op{Convert<Args...>(MakeIndexSequence<sizeof...(Actions) - 1>()),
960               std::get<sizeof...(Actions) - 1>(actions)};
961   }
962 };
963 
964 }  // namespace internal
965 
966 // An Unused object can be implicitly constructed from ANY value.
967 // This is handy when defining actions that ignore some or all of the
968 // mock function arguments.  For example, given
969 //
970 //   MOCK_METHOD3(Foo, double(const string& label, double x, double y));
971 //   MOCK_METHOD3(Bar, double(int index, double x, double y));
972 //
973 // instead of
974 //
975 //   double DistanceToOriginWithLabel(const string& label, double x, double y) {
976 //     return sqrt(x*x + y*y);
977 //   }
978 //   double DistanceToOriginWithIndex(int index, double x, double y) {
979 //     return sqrt(x*x + y*y);
980 //   }
981 //   ...
982 //   EXPECT_CALL(mock, Foo("abc", _, _))
983 //       .WillOnce(Invoke(DistanceToOriginWithLabel));
984 //   EXPECT_CALL(mock, Bar(5, _, _))
985 //       .WillOnce(Invoke(DistanceToOriginWithIndex));
986 //
987 // you could write
988 //
989 //   // We can declare any uninteresting argument as Unused.
990 //   double DistanceToOrigin(Unused, double x, double y) {
991 //     return sqrt(x*x + y*y);
992 //   }
993 //   ...
994 //   EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
995 //   EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
996 typedef internal::IgnoredValue Unused;
997 
998 // Creates an action that does actions a1, a2, ..., sequentially in
999 // each invocation.
1000 template <typename... Action>
1001 internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
1002     Action&&... action) {
1003   return {std::forward_as_tuple(std::forward<Action>(action)...)};
1004 }
1005 
1006 // WithArg<k>(an_action) creates an action that passes the k-th
1007 // (0-based) argument of the mock function to an_action and performs
1008 // it.  It adapts an action accepting one argument to one that accepts
1009 // multiple arguments.  For convenience, we also provide
1010 // WithArgs<k>(an_action) (defined below) as a synonym.
1011 template <size_t k, typename InnerAction>
1012 internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
1013 WithArg(InnerAction&& action) {
1014   return {std::forward<InnerAction>(action)};
1015 }
1016 
1017 // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
1018 // the selected arguments of the mock function to an_action and
1019 // performs it.  It serves as an adaptor between actions with
1020 // different argument lists.
1021 template <size_t k, size_t... ks, typename InnerAction>
1022 internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
1023 WithArgs(InnerAction&& action) {
1024   return {std::forward<InnerAction>(action)};
1025 }
1026 
1027 // WithoutArgs(inner_action) can be used in a mock function with a
1028 // non-empty argument list to perform inner_action, which takes no
1029 // argument.  In other words, it adapts an action accepting no
1030 // argument to one that accepts (and ignores) arguments.
1031 template <typename InnerAction>
1032 internal::WithArgsAction<typename std::decay<InnerAction>::type>
1033 WithoutArgs(InnerAction&& action) {
1034   return {std::forward<InnerAction>(action)};
1035 }
1036 
1037 // Creates an action that returns 'value'.  'value' is passed by value
1038 // instead of const reference - otherwise Return("string literal")
1039 // will trigger a compiler error about using array as initializer.
1040 template <typename R>
1041 internal::ReturnAction<R> Return(R value) {
1042   return internal::ReturnAction<R>(std::move(value));
1043 }
1044 
1045 // Creates an action that returns NULL.
1046 inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
1047   return MakePolymorphicAction(internal::ReturnNullAction());
1048 }
1049 
1050 // Creates an action that returns from a void function.
1051 inline PolymorphicAction<internal::ReturnVoidAction> Return() {
1052   return MakePolymorphicAction(internal::ReturnVoidAction());
1053 }
1054 
1055 // Creates an action that returns the reference to a variable.
1056 template <typename R>
1057 inline internal::ReturnRefAction<R> ReturnRef(R& x) {  // NOLINT
1058   return internal::ReturnRefAction<R>(x);
1059 }
1060 
1061 // Creates an action that returns the reference to a copy of the
1062 // argument.  The copy is created when the action is constructed and
1063 // lives as long as the action.
1064 template <typename R>
1065 inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
1066   return internal::ReturnRefOfCopyAction<R>(x);
1067 }
1068 
1069 // Modifies the parent action (a Return() action) to perform a move of the
1070 // argument instead of a copy.
1071 // Return(ByMove()) actions can only be executed once and will assert this
1072 // invariant.
1073 template <typename R>
1074 internal::ByMoveWrapper<R> ByMove(R x) {
1075   return internal::ByMoveWrapper<R>(std::move(x));
1076 }
1077 
1078 // Creates an action that does the default action for the give mock function.
1079 inline internal::DoDefaultAction DoDefault() {
1080   return internal::DoDefaultAction();
1081 }
1082 
1083 // Creates an action that sets the variable pointed by the N-th
1084 // (0-based) function argument to 'value'.
1085 template <size_t N, typename T>
1086 PolymorphicAction<
1087   internal::SetArgumentPointeeAction<
1088     N, T, internal::IsAProtocolMessage<T>::value> >
1089 SetArgPointee(const T& x) {
1090   return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1091       N, T, internal::IsAProtocolMessage<T>::value>(x));
1092 }
1093 
1094 template <size_t N>
1095 PolymorphicAction<
1096   internal::SetArgumentPointeeAction<N, const char*, false> >
1097 SetArgPointee(const char* p) {
1098   return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1099       N, const char*, false>(p));
1100 }
1101 
1102 template <size_t N>
1103 PolymorphicAction<
1104   internal::SetArgumentPointeeAction<N, const wchar_t*, false> >
1105 SetArgPointee(const wchar_t* p) {
1106   return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1107       N, const wchar_t*, false>(p));
1108 }
1109 
1110 // The following version is DEPRECATED.
1111 template <size_t N, typename T>
1112 PolymorphicAction<
1113   internal::SetArgumentPointeeAction<
1114     N, T, internal::IsAProtocolMessage<T>::value> >
1115 SetArgumentPointee(const T& x) {
1116   return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1117       N, T, internal::IsAProtocolMessage<T>::value>(x));
1118 }
1119 
1120 // Creates an action that sets a pointer referent to a given value.
1121 template <typename T1, typename T2>
1122 PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
1123   return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
1124 }
1125 
1126 #if !GTEST_OS_WINDOWS_MOBILE
1127 
1128 // Creates an action that sets errno and returns the appropriate error.
1129 template <typename T>
1130 PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
1131 SetErrnoAndReturn(int errval, T result) {
1132   return MakePolymorphicAction(
1133       internal::SetErrnoAndReturnAction<T>(errval, result));
1134 }
1135 
1136 #endif  // !GTEST_OS_WINDOWS_MOBILE
1137 
1138 // Various overloads for Invoke().
1139 
1140 // Legacy function.
1141 // Actions can now be implicitly constructed from callables. No need to create
1142 // wrapper objects.
1143 // This function exists for backwards compatibility.
1144 template <typename FunctionImpl>
1145 typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
1146   return std::forward<FunctionImpl>(function_impl);
1147 }
1148 
1149 // Creates an action that invokes the given method on the given object
1150 // with the mock function's arguments.
1151 template <class Class, typename MethodPtr>
1152 internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
1153                                                       MethodPtr method_ptr) {
1154   return {obj_ptr, method_ptr};
1155 }
1156 
1157 // Creates an action that invokes 'function_impl' with no argument.
1158 template <typename FunctionImpl>
1159 internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
1160 InvokeWithoutArgs(FunctionImpl function_impl) {
1161   return {std::move(function_impl)};
1162 }
1163 
1164 // Creates an action that invokes the given method on the given object
1165 // with no argument.
1166 template <class Class, typename MethodPtr>
1167 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
1168     Class* obj_ptr, MethodPtr method_ptr) {
1169   return {obj_ptr, method_ptr};
1170 }
1171 
1172 // Creates an action that performs an_action and throws away its
1173 // result.  In other words, it changes the return type of an_action to
1174 // void.  an_action MUST NOT return void, or the code won't compile.
1175 template <typename A>
1176 inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1177   return internal::IgnoreResultAction<A>(an_action);
1178 }
1179 
1180 // Creates a reference wrapper for the given L-value.  If necessary,
1181 // you can explicitly specify the type of the reference.  For example,
1182 // suppose 'derived' is an object of type Derived, ByRef(derived)
1183 // would wrap a Derived&.  If you want to wrap a const Base& instead,
1184 // where Base is a base class of Derived, just write:
1185 //
1186 //   ByRef<const Base>(derived)
1187 //
1188 // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
1189 // However, it may still be used for consistency with ByMove().
1190 template <typename T>
1191 inline ::std::reference_wrapper<T> ByRef(T& l_value) {  // NOLINT
1192   return ::std::reference_wrapper<T>(l_value);
1193 }
1194 
1195 }  // namespace testing
1196 
1197 #ifdef _MSC_VER
1198 # pragma warning(pop)
1199 #endif
1200 
1201 
1202 #endif  // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
1203