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