[MIParser] Set RegClassOrRegBank during instruction parsing
[llvm-complete.git] / utils / unittest / googlemock / include / gmock / gmock-actions.h
blob8e17468a2cf6a1957143fd4d01826afcf4a26c6c
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.
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.
30 // Author: wan@google.com (Zhanyong Wan)
32 // Google Mock - a framework for writing C++ mock classes.
34 // This file implements some commonly used actions.
36 // IWYU pragma: private, include "gmock/gmock.h"
38 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
39 #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
41 #ifndef _WIN32_WCE
42 # include <errno.h>
43 #endif
45 #include <algorithm>
46 #include <string>
48 #include "gmock/internal/gmock-internal-utils.h"
49 #include "gmock/internal/gmock-port.h"
51 #if GTEST_HAS_STD_TYPE_TRAITS_ // Defined by gtest-port.h via gmock-port.h.
52 #include <type_traits>
53 #endif
55 namespace testing {
57 // To implement an action Foo, define:
58 // 1. a class FooAction that implements the ActionInterface interface, and
59 // 2. a factory function that creates an Action object from a
60 // const FooAction*.
62 // The two-level delegation design follows that of Matcher, providing
63 // consistency for extension developers. It also eases ownership
64 // management as Action objects can now be copied like plain values.
66 namespace internal {
68 template <typename F1, typename F2>
69 class ActionAdaptor;
71 // BuiltInDefaultValueGetter<T, true>::Get() returns a
72 // default-constructed T value. BuiltInDefaultValueGetter<T,
73 // false>::Get() crashes with an error.
75 // This primary template is used when kDefaultConstructible is true.
76 template <typename T, bool kDefaultConstructible>
77 struct BuiltInDefaultValueGetter {
78 static T Get() { return T(); }
80 template <typename T>
81 struct BuiltInDefaultValueGetter<T, false> {
82 static T Get() {
83 Assert(false, __FILE__, __LINE__,
84 "Default action undefined for the function return type.");
85 return internal::Invalid<T>();
86 // The above statement will never be reached, but is required in
87 // order for this function to compile.
91 // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
92 // for type T, which is NULL when T is a raw pointer type, 0 when T is
93 // a numeric type, false when T is bool, or "" when T is string or
94 // std::string. In addition, in C++11 and above, it turns a
95 // default-constructed T value if T is default constructible. For any
96 // other type T, the built-in default T value is undefined, and the
97 // function will abort the process.
98 template <typename T>
99 class BuiltInDefaultValue {
100 public:
101 #if GTEST_HAS_STD_TYPE_TRAITS_
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;
107 static T Get() {
108 return BuiltInDefaultValueGetter<
109 T, ::std::is_default_constructible<T>::value>::Get();
112 #else // GTEST_HAS_STD_TYPE_TRAITS_
113 // This function returns true iff type T has a built-in default value.
114 static bool Exists() {
115 return false;
118 static T Get() {
119 return BuiltInDefaultValueGetter<T, false>::Get();
122 #endif // GTEST_HAS_STD_TYPE_TRAITS_
125 // This partial specialization says that we use the same built-in
126 // default value for T and const T.
127 template <typename T>
128 class BuiltInDefaultValue<const T> {
129 public:
130 static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
131 static T Get() { return BuiltInDefaultValue<T>::Get(); }
134 // This partial specialization defines the default values for pointer
135 // types.
136 template <typename T>
137 class BuiltInDefaultValue<T*> {
138 public:
139 static bool Exists() { return true; }
140 static T* Get() { return NULL; }
143 // The following specializations define the default values for
144 // specific types we care about.
145 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
146 template <> \
147 class BuiltInDefaultValue<type> { \
148 public: \
149 static bool Exists() { return true; } \
150 static type Get() { return value; } \
153 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
154 #if GTEST_HAS_GLOBAL_STRING
155 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
156 #endif // GTEST_HAS_GLOBAL_STRING
157 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
158 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
159 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
160 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
161 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
163 // There's no need for a default action for signed wchar_t, as that
164 // type is the same as wchar_t for gcc, and invalid for MSVC.
166 // There's also no need for a default action for unsigned wchar_t, as
167 // that type is the same as unsigned int for gcc, and invalid for
168 // MSVC.
169 #if GMOCK_WCHAR_T_IS_NATIVE_
170 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
171 #endif
173 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
174 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
175 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
176 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
177 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
178 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
179 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
180 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
181 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
182 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
184 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
186 } // namespace internal
188 // When an unexpected function call is encountered, Google Mock will
189 // let it return a default value if the user has specified one for its
190 // return type, or if the return type has a built-in default value;
191 // otherwise Google Mock won't know what value to return and will have
192 // to abort the process.
194 // The DefaultValue<T> class allows a user to specify the
195 // default value for a type T that is both copyable and publicly
196 // destructible (i.e. anything that can be used as a function return
197 // type). The usage is:
199 // // Sets the default value for type T to be foo.
200 // DefaultValue<T>::Set(foo);
201 template <typename T>
202 class DefaultValue {
203 public:
204 // Sets the default value for type T; requires T to be
205 // copy-constructable and have a public destructor.
206 static void Set(T x) {
207 delete producer_;
208 producer_ = new FixedValueProducer(x);
211 // Provides a factory function to be called to generate the default value.
212 // This method can be used even if T is only move-constructible, but it is not
213 // limited to that case.
214 typedef T (*FactoryFunction)();
215 static void SetFactory(FactoryFunction factory) {
216 delete producer_;
217 producer_ = new FactoryValueProducer(factory);
220 // Unsets the default value for type T.
221 static void Clear() {
222 delete producer_;
223 producer_ = NULL;
226 // Returns true iff the user has set the default value for type T.
227 static bool IsSet() { return producer_ != NULL; }
229 // Returns true if T has a default return value set by the user or there
230 // exists a built-in default value.
231 static bool Exists() {
232 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
235 // Returns the default value for type T if the user has set one;
236 // otherwise returns the built-in default value. Requires that Exists()
237 // is true, which ensures that the return value is well-defined.
238 static T Get() {
239 return producer_ == NULL ?
240 internal::BuiltInDefaultValue<T>::Get() : producer_->Produce();
243 private:
244 class ValueProducer {
245 public:
246 virtual ~ValueProducer() {}
247 virtual T Produce() = 0;
250 class FixedValueProducer : public ValueProducer {
251 public:
252 explicit FixedValueProducer(T value) : value_(value) {}
253 virtual T Produce() { return value_; }
255 private:
256 const T value_;
257 GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
260 class FactoryValueProducer : public ValueProducer {
261 public:
262 explicit FactoryValueProducer(FactoryFunction factory)
263 : factory_(factory) {}
264 virtual T Produce() { return factory_(); }
266 private:
267 const FactoryFunction factory_;
268 GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
271 static ValueProducer* producer_;
274 // This partial specialization allows a user to set default values for
275 // reference types.
276 template <typename T>
277 class DefaultValue<T&> {
278 public:
279 // Sets the default value for type T&.
280 static void Set(T& x) { // NOLINT
281 address_ = &x;
284 // Unsets the default value for type T&.
285 static void Clear() {
286 address_ = NULL;
289 // Returns true iff the user has set the default value for type T&.
290 static bool IsSet() { return address_ != NULL; }
292 // Returns true if T has a default return value set by the user or there
293 // exists a built-in default value.
294 static bool Exists() {
295 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
298 // Returns the default value for type T& if the user has set one;
299 // otherwise returns the built-in default value if there is one;
300 // otherwise aborts the process.
301 static T& Get() {
302 return address_ == NULL ?
303 internal::BuiltInDefaultValue<T&>::Get() : *address_;
306 private:
307 static T* address_;
310 // This specialization allows DefaultValue<void>::Get() to
311 // compile.
312 template <>
313 class DefaultValue<void> {
314 public:
315 static bool Exists() { return true; }
316 static void Get() {}
319 // Points to the user-set default value for type T.
320 template <typename T>
321 typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL;
323 // Points to the user-set default value for type T&.
324 template <typename T>
325 T* DefaultValue<T&>::address_ = NULL;
327 // Implement this interface to define an action for function type F.
328 template <typename F>
329 class ActionInterface {
330 public:
331 typedef typename internal::Function<F>::Result Result;
332 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
334 ActionInterface() {}
335 virtual ~ActionInterface() {}
337 // Performs the action. This method is not const, as in general an
338 // action can have side effects and be stateful. For example, a
339 // get-the-next-element-from-the-collection action will need to
340 // remember the current element.
341 virtual Result Perform(const ArgumentTuple& args) = 0;
343 private:
344 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
347 // An Action<F> is a copyable and IMMUTABLE (except by assignment)
348 // object that represents an action to be taken when a mock function
349 // of type F is called. The implementation of Action<T> is just a
350 // linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
351 // Don't inherit from Action!
353 // You can view an object implementing ActionInterface<F> as a
354 // concrete action (including its current state), and an Action<F>
355 // object as a handle to it.
356 template <typename F>
357 class Action {
358 public:
359 typedef typename internal::Function<F>::Result Result;
360 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
362 // Constructs a null Action. Needed for storing Action objects in
363 // STL containers.
364 Action() : impl_(NULL) {}
366 // Constructs an Action from its implementation. A NULL impl is
367 // used to represent the "do-default" action.
368 explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
370 // Copy constructor.
371 Action(const Action& action) : impl_(action.impl_) {}
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
376 // F's.
377 template <typename Func>
378 explicit Action(const Action<Func>& action);
380 // Returns true iff this is the DoDefault() action.
381 bool IsDoDefault() const { return impl_.get() == NULL; }
383 // Performs the action. Note that this method is const even though
384 // the corresponding method in ActionInterface is not. The reason
385 // is that a const Action<F> means that it cannot be re-bound to
386 // another concrete action, not that the concrete action it binds to
387 // cannot change state. (Think of the difference between a const
388 // pointer and a pointer to const.)
389 Result Perform(const ArgumentTuple& args) const {
390 internal::Assert(
391 !IsDoDefault(), __FILE__, __LINE__,
392 "You are using DoDefault() inside a composite action like "
393 "DoAll() or WithArgs(). This is not supported for technical "
394 "reasons. Please instead spell out the default action, or "
395 "assign the default action to an Action variable and use "
396 "the variable in various places.");
397 return impl_->Perform(args);
400 private:
401 template <typename F1, typename F2>
402 friend class internal::ActionAdaptor;
404 internal::linked_ptr<ActionInterface<F> > impl_;
407 // The PolymorphicAction class template makes it easy to implement a
408 // polymorphic action (i.e. an action that can be used in mock
409 // functions of than one type, e.g. Return()).
411 // To define a polymorphic action, a user first provides a COPYABLE
412 // implementation class that has a Perform() method template:
414 // class FooAction {
415 // public:
416 // template <typename Result, typename ArgumentTuple>
417 // Result Perform(const ArgumentTuple& args) const {
418 // // Processes the arguments and returns a result, using
419 // // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
420 // }
421 // ...
422 // };
424 // Then the user creates the polymorphic action using
425 // MakePolymorphicAction(object) where object has type FooAction. See
426 // the definition of Return(void) and SetArgumentPointee<N>(value) for
427 // complete examples.
428 template <typename Impl>
429 class PolymorphicAction {
430 public:
431 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
433 template <typename F>
434 operator Action<F>() const {
435 return Action<F>(new MonomorphicImpl<F>(impl_));
438 private:
439 template <typename F>
440 class MonomorphicImpl : public ActionInterface<F> {
441 public:
442 typedef typename internal::Function<F>::Result Result;
443 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
445 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
447 virtual Result Perform(const ArgumentTuple& args) {
448 return impl_.template Perform<Result>(args);
451 private:
452 Impl impl_;
454 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
457 Impl impl_;
459 GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
462 // Creates an Action from its implementation and returns it. The
463 // created Action object owns the implementation.
464 template <typename F>
465 Action<F> MakeAction(ActionInterface<F>* impl) {
466 return Action<F>(impl);
469 // Creates a polymorphic action from its implementation. This is
470 // easier to use than the PolymorphicAction<Impl> constructor as it
471 // doesn't require you to explicitly write the template argument, e.g.
473 // MakePolymorphicAction(foo);
474 // vs
475 // PolymorphicAction<TypeOfFoo>(foo);
476 template <typename Impl>
477 inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
478 return PolymorphicAction<Impl>(impl);
481 namespace internal {
483 // Allows an Action<F2> object to pose as an Action<F1>, as long as F2
484 // and F1 are compatible.
485 template <typename F1, typename F2>
486 class ActionAdaptor : public ActionInterface<F1> {
487 public:
488 typedef typename internal::Function<F1>::Result Result;
489 typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
491 explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
493 virtual Result Perform(const ArgumentTuple& args) {
494 return impl_->Perform(args);
497 private:
498 const internal::linked_ptr<ActionInterface<F2> > impl_;
500 GTEST_DISALLOW_ASSIGN_(ActionAdaptor);
503 // Helper struct to specialize ReturnAction to execute a move instead of a copy
504 // on return. Useful for move-only types, but could be used on any type.
505 template <typename T>
506 struct ByMoveWrapper {
507 explicit ByMoveWrapper(T value) : payload(internal::move(value)) {}
508 T payload;
511 // Implements the polymorphic Return(x) action, which can be used in
512 // any function that returns the type of x, regardless of the argument
513 // types.
515 // Note: The value passed into Return must be converted into
516 // Function<F>::Result when this action is cast to Action<F> rather than
517 // when that action is performed. This is important in scenarios like
519 // MOCK_METHOD1(Method, T(U));
520 // ...
521 // {
522 // Foo foo;
523 // X x(&foo);
524 // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
525 // }
527 // In the example above the variable x holds reference to foo which leaves
528 // scope and gets destroyed. If copying X just copies a reference to foo,
529 // that copy will be left with a hanging reference. If conversion to T
530 // makes a copy of foo, the above code is safe. To support that scenario, we
531 // need to make sure that the type conversion happens inside the EXPECT_CALL
532 // statement, and conversion of the result of Return to Action<T(U)> is a
533 // good place for that.
535 template <typename R>
536 class ReturnAction {
537 public:
538 // Constructs a ReturnAction object from the value to be returned.
539 // 'value' is passed by value instead of by const reference in order
540 // to allow Return("string literal") to compile.
541 explicit ReturnAction(R value) : value_(new R(internal::move(value))) {}
543 // This template type conversion operator allows Return(x) to be
544 // used in ANY function that returns x's type.
545 template <typename F>
546 operator Action<F>() const {
547 // Assert statement belongs here because this is the best place to verify
548 // conditions on F. It produces the clearest error messages
549 // in most compilers.
550 // Impl really belongs in this scope as a local class but can't
551 // because MSVC produces duplicate symbols in different translation units
552 // in this case. Until MS fixes that bug we put Impl into the class scope
553 // and put the typedef both here (for use in assert statement) and
554 // in the Impl class. But both definitions must be the same.
555 typedef typename Function<F>::Result Result;
556 GTEST_COMPILE_ASSERT_(
557 !is_reference<Result>::value,
558 use_ReturnRef_instead_of_Return_to_return_a_reference);
559 return Action<F>(new Impl<R, F>(value_));
562 private:
563 // Implements the Return(x) action for a particular function type F.
564 template <typename R_, typename F>
565 class Impl : public ActionInterface<F> {
566 public:
567 typedef typename Function<F>::Result Result;
568 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
570 // The implicit cast is necessary when Result has more than one
571 // single-argument constructor (e.g. Result is std::vector<int>) and R
572 // has a type conversion operator template. In that case, value_(value)
573 // won't compile as the compiler doesn't known which constructor of
574 // Result to call. ImplicitCast_ forces the compiler to convert R to
575 // Result without considering explicit constructors, thus resolving the
576 // ambiguity. value_ is then initialized using its copy constructor.
577 explicit Impl(const linked_ptr<R>& value)
578 : value_before_cast_(*value),
579 value_(ImplicitCast_<Result>(value_before_cast_)) {}
581 virtual Result Perform(const ArgumentTuple&) { return value_; }
583 private:
584 GTEST_COMPILE_ASSERT_(!is_reference<Result>::value,
585 Result_cannot_be_a_reference_type);
586 // We save the value before casting just in case it is being cast to a
587 // wrapper type.
588 R value_before_cast_;
589 Result value_;
591 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
594 // Partially specialize for ByMoveWrapper. This version of ReturnAction will
595 // move its contents instead.
596 template <typename R_, typename F>
597 class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
598 public:
599 typedef typename Function<F>::Result Result;
600 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
602 explicit Impl(const linked_ptr<R>& wrapper)
603 : performed_(false), wrapper_(wrapper) {}
605 virtual Result Perform(const ArgumentTuple&) {
606 GTEST_CHECK_(!performed_)
607 << "A ByMove() action should only be performed once.";
608 performed_ = true;
609 return internal::move(wrapper_->payload);
612 private:
613 bool performed_;
614 const linked_ptr<R> wrapper_;
616 GTEST_DISALLOW_ASSIGN_(Impl);
619 const linked_ptr<R> value_;
621 GTEST_DISALLOW_ASSIGN_(ReturnAction);
624 // Implements the ReturnNull() action.
625 class ReturnNullAction {
626 public:
627 // Allows ReturnNull() to be used in any pointer-returning function. In C++11
628 // this is enforced by returning nullptr, and in non-C++11 by asserting a
629 // pointer type on compile time.
630 template <typename Result, typename ArgumentTuple>
631 static Result Perform(const ArgumentTuple&) {
632 #if GTEST_LANG_CXX11
633 return nullptr;
634 #else
635 GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
636 ReturnNull_can_be_used_to_return_a_pointer_only);
637 return NULL;
638 #endif // GTEST_LANG_CXX11
642 // Implements the Return() action.
643 class ReturnVoidAction {
644 public:
645 // Allows Return() to be used in any void-returning function.
646 template <typename Result, typename ArgumentTuple>
647 static void Perform(const ArgumentTuple&) {
648 CompileAssertTypesEqual<void, Result>();
652 // Implements the polymorphic ReturnRef(x) action, which can be used
653 // in any function that returns a reference to the type of x,
654 // regardless of the argument types.
655 template <typename T>
656 class ReturnRefAction {
657 public:
658 // Constructs a ReturnRefAction object from the reference to be returned.
659 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
661 // This template type conversion operator allows ReturnRef(x) to be
662 // used in ANY function that returns a reference to x's type.
663 template <typename F>
664 operator Action<F>() const {
665 typedef typename Function<F>::Result Result;
666 // Asserts that the function return type is a reference. This
667 // catches the user error of using ReturnRef(x) when Return(x)
668 // should be used, and generates some helpful error message.
669 GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value,
670 use_Return_instead_of_ReturnRef_to_return_a_value);
671 return Action<F>(new Impl<F>(ref_));
674 private:
675 // Implements the ReturnRef(x) action for a particular function type F.
676 template <typename F>
677 class Impl : public ActionInterface<F> {
678 public:
679 typedef typename Function<F>::Result Result;
680 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
682 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
684 virtual Result Perform(const ArgumentTuple&) {
685 return ref_;
688 private:
689 T& ref_;
691 GTEST_DISALLOW_ASSIGN_(Impl);
694 T& ref_;
696 GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
699 // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
700 // used in any function that returns a reference to the type of x,
701 // regardless of the argument types.
702 template <typename T>
703 class ReturnRefOfCopyAction {
704 public:
705 // Constructs a ReturnRefOfCopyAction object from the reference to
706 // be returned.
707 explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
709 // This template type conversion operator allows ReturnRefOfCopy(x) to be
710 // used in ANY function that returns a reference to x's type.
711 template <typename F>
712 operator Action<F>() const {
713 typedef typename Function<F>::Result Result;
714 // Asserts that the function return type is a reference. This
715 // catches the user error of using ReturnRefOfCopy(x) when Return(x)
716 // should be used, and generates some helpful error message.
717 GTEST_COMPILE_ASSERT_(
718 internal::is_reference<Result>::value,
719 use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
720 return Action<F>(new Impl<F>(value_));
723 private:
724 // Implements the ReturnRefOfCopy(x) action for a particular function type F.
725 template <typename F>
726 class Impl : public ActionInterface<F> {
727 public:
728 typedef typename Function<F>::Result Result;
729 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
731 explicit Impl(const T& value) : value_(value) {} // NOLINT
733 virtual Result Perform(const ArgumentTuple&) {
734 return value_;
737 private:
738 T value_;
740 GTEST_DISALLOW_ASSIGN_(Impl);
743 const T value_;
745 GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
748 // Implements the polymorphic DoDefault() action.
749 class DoDefaultAction {
750 public:
751 // This template type conversion operator allows DoDefault() to be
752 // used in any function.
753 template <typename F>
754 operator Action<F>() const { return Action<F>(NULL); }
757 // Implements the Assign action to set a given pointer referent to a
758 // particular value.
759 template <typename T1, typename T2>
760 class AssignAction {
761 public:
762 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
764 template <typename Result, typename ArgumentTuple>
765 void Perform(const ArgumentTuple& /* args */) const {
766 *ptr_ = value_;
769 private:
770 T1* const ptr_;
771 const T2 value_;
773 GTEST_DISALLOW_ASSIGN_(AssignAction);
776 #if !GTEST_OS_WINDOWS_MOBILE
778 // Implements the SetErrnoAndReturn action to simulate return from
779 // various system calls and libc functions.
780 template <typename T>
781 class SetErrnoAndReturnAction {
782 public:
783 SetErrnoAndReturnAction(int errno_value, T result)
784 : errno_(errno_value),
785 result_(result) {}
786 template <typename Result, typename ArgumentTuple>
787 Result Perform(const ArgumentTuple& /* args */) const {
788 errno = errno_;
789 return result_;
792 private:
793 const int errno_;
794 const T result_;
796 GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
799 #endif // !GTEST_OS_WINDOWS_MOBILE
801 // Implements the SetArgumentPointee<N>(x) action for any function
802 // whose N-th argument (0-based) is a pointer to x's type. The
803 // template parameter kIsProto is true iff type A is ProtocolMessage,
804 // proto2::Message, or a sub-class of those.
805 template <size_t N, typename A, bool kIsProto>
806 class SetArgumentPointeeAction {
807 public:
808 // Constructs an action that sets the variable pointed to by the
809 // N-th function argument to 'value'.
810 explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
812 template <typename Result, typename ArgumentTuple>
813 void Perform(const ArgumentTuple& args) const {
814 CompileAssertTypesEqual<void, Result>();
815 *::testing::get<N>(args) = value_;
818 private:
819 const A value_;
821 GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
824 template <size_t N, typename Proto>
825 class SetArgumentPointeeAction<N, Proto, true> {
826 public:
827 // Constructs an action that sets the variable pointed to by the
828 // N-th function argument to 'proto'. Both ProtocolMessage and
829 // proto2::Message have the CopyFrom() method, so the same
830 // implementation works for both.
831 explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
832 proto_->CopyFrom(proto);
835 template <typename Result, typename ArgumentTuple>
836 void Perform(const ArgumentTuple& args) const {
837 CompileAssertTypesEqual<void, Result>();
838 ::testing::get<N>(args)->CopyFrom(*proto_);
841 private:
842 const internal::linked_ptr<Proto> proto_;
844 GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
847 // Implements the InvokeWithoutArgs(f) action. The template argument
848 // FunctionImpl is the implementation type of f, which can be either a
849 // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
850 // Action<F> as long as f's type is compatible with F (i.e. f can be
851 // assigned to a tr1::function<F>).
852 template <typename FunctionImpl>
853 class InvokeWithoutArgsAction {
854 public:
855 // The c'tor makes a copy of function_impl (either a function
856 // pointer or a functor).
857 explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
858 : function_impl_(function_impl) {}
860 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
861 // compatible with f.
862 template <typename Result, typename ArgumentTuple>
863 Result Perform(const ArgumentTuple&) { return function_impl_(); }
865 private:
866 FunctionImpl function_impl_;
868 GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction);
871 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
872 template <class Class, typename MethodPtr>
873 class InvokeMethodWithoutArgsAction {
874 public:
875 InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
876 : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
878 template <typename Result, typename ArgumentTuple>
879 Result Perform(const ArgumentTuple&) const {
880 return (obj_ptr_->*method_ptr_)();
883 private:
884 Class* const obj_ptr_;
885 const MethodPtr method_ptr_;
887 GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction);
890 // Implements the IgnoreResult(action) action.
891 template <typename A>
892 class IgnoreResultAction {
893 public:
894 explicit IgnoreResultAction(const A& action) : action_(action) {}
896 template <typename F>
897 operator Action<F>() const {
898 // Assert statement belongs here because this is the best place to verify
899 // conditions on F. It produces the clearest error messages
900 // in most compilers.
901 // Impl really belongs in this scope as a local class but can't
902 // because MSVC produces duplicate symbols in different translation units
903 // in this case. Until MS fixes that bug we put Impl into the class scope
904 // and put the typedef both here (for use in assert statement) and
905 // in the Impl class. But both definitions must be the same.
906 typedef typename internal::Function<F>::Result Result;
908 // Asserts at compile time that F returns void.
909 CompileAssertTypesEqual<void, Result>();
911 return Action<F>(new Impl<F>(action_));
914 private:
915 template <typename F>
916 class Impl : public ActionInterface<F> {
917 public:
918 typedef typename internal::Function<F>::Result Result;
919 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
921 explicit Impl(const A& action) : action_(action) {}
923 virtual void Perform(const ArgumentTuple& args) {
924 // Performs the action and ignores its result.
925 action_.Perform(args);
928 private:
929 // Type OriginalFunction is the same as F except that its return
930 // type is IgnoredValue.
931 typedef typename internal::Function<F>::MakeResultIgnoredValue
932 OriginalFunction;
934 const Action<OriginalFunction> action_;
936 GTEST_DISALLOW_ASSIGN_(Impl);
939 const A action_;
941 GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
944 // A ReferenceWrapper<T> object represents a reference to type T,
945 // which can be either const or not. It can be explicitly converted
946 // from, and implicitly converted to, a T&. Unlike a reference,
947 // ReferenceWrapper<T> can be copied and can survive template type
948 // inference. This is used to support by-reference arguments in the
949 // InvokeArgument<N>(...) action. The idea was from "reference
950 // wrappers" in tr1, which we don't have in our source tree yet.
951 template <typename T>
952 class ReferenceWrapper {
953 public:
954 // Constructs a ReferenceWrapper<T> object from a T&.
955 explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT
957 // Allows a ReferenceWrapper<T> object to be implicitly converted to
958 // a T&.
959 operator T&() const { return *pointer_; }
960 private:
961 T* pointer_;
964 // Allows the expression ByRef(x) to be printed as a reference to x.
965 template <typename T>
966 void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
967 T& value = ref;
968 UniversalPrinter<T&>::Print(value, os);
971 // Does two actions sequentially. Used for implementing the DoAll(a1,
972 // a2, ...) action.
973 template <typename Action1, typename Action2>
974 class DoBothAction {
975 public:
976 DoBothAction(Action1 action1, Action2 action2)
977 : action1_(action1), action2_(action2) {}
979 // This template type conversion operator allows DoAll(a1, ..., a_n)
980 // to be used in ANY function of compatible type.
981 template <typename F>
982 operator Action<F>() const {
983 return Action<F>(new Impl<F>(action1_, action2_));
986 private:
987 // Implements the DoAll(...) action for a particular function type F.
988 template <typename F>
989 class Impl : public ActionInterface<F> {
990 public:
991 typedef typename Function<F>::Result Result;
992 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
993 typedef typename Function<F>::MakeResultVoid VoidResult;
995 Impl(const Action<VoidResult>& action1, const Action<F>& action2)
996 : action1_(action1), action2_(action2) {}
998 virtual Result Perform(const ArgumentTuple& args) {
999 action1_.Perform(args);
1000 return action2_.Perform(args);
1003 private:
1004 const Action<VoidResult> action1_;
1005 const Action<F> action2_;
1007 GTEST_DISALLOW_ASSIGN_(Impl);
1010 Action1 action1_;
1011 Action2 action2_;
1013 GTEST_DISALLOW_ASSIGN_(DoBothAction);
1016 } // namespace internal
1018 // An Unused object can be implicitly constructed from ANY value.
1019 // This is handy when defining actions that ignore some or all of the
1020 // mock function arguments. For example, given
1022 // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
1023 // MOCK_METHOD3(Bar, double(int index, double x, double y));
1025 // instead of
1027 // double DistanceToOriginWithLabel(const string& label, double x, double y) {
1028 // return sqrt(x*x + y*y);
1029 // }
1030 // double DistanceToOriginWithIndex(int index, double x, double y) {
1031 // return sqrt(x*x + y*y);
1032 // }
1033 // ...
1034 // EXEPCT_CALL(mock, Foo("abc", _, _))
1035 // .WillOnce(Invoke(DistanceToOriginWithLabel));
1036 // EXEPCT_CALL(mock, Bar(5, _, _))
1037 // .WillOnce(Invoke(DistanceToOriginWithIndex));
1039 // you could write
1041 // // We can declare any uninteresting argument as Unused.
1042 // double DistanceToOrigin(Unused, double x, double y) {
1043 // return sqrt(x*x + y*y);
1044 // }
1045 // ...
1046 // EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
1047 // EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
1048 typedef internal::IgnoredValue Unused;
1050 // This constructor allows us to turn an Action<From> object into an
1051 // Action<To>, as long as To's arguments can be implicitly converted
1052 // to From's and From's return type cann be implicitly converted to
1053 // To's.
1054 template <typename To>
1055 template <typename From>
1056 Action<To>::Action(const Action<From>& from)
1057 : impl_(new internal::ActionAdaptor<To, From>(from)) {}
1059 // Creates an action that returns 'value'. 'value' is passed by value
1060 // instead of const reference - otherwise Return("string literal")
1061 // will trigger a compiler error about using array as initializer.
1062 template <typename R>
1063 internal::ReturnAction<R> Return(R value) {
1064 return internal::ReturnAction<R>(internal::move(value));
1067 // Creates an action that returns NULL.
1068 inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
1069 return MakePolymorphicAction(internal::ReturnNullAction());
1072 // Creates an action that returns from a void function.
1073 inline PolymorphicAction<internal::ReturnVoidAction> Return() {
1074 return MakePolymorphicAction(internal::ReturnVoidAction());
1077 // Creates an action that returns the reference to a variable.
1078 template <typename R>
1079 inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
1080 return internal::ReturnRefAction<R>(x);
1083 // Creates an action that returns the reference to a copy of the
1084 // argument. The copy is created when the action is constructed and
1085 // lives as long as the action.
1086 template <typename R>
1087 inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
1088 return internal::ReturnRefOfCopyAction<R>(x);
1091 // Modifies the parent action (a Return() action) to perform a move of the
1092 // argument instead of a copy.
1093 // Return(ByMove()) actions can only be executed once and will assert this
1094 // invariant.
1095 template <typename R>
1096 internal::ByMoveWrapper<R> ByMove(R x) {
1097 return internal::ByMoveWrapper<R>(internal::move(x));
1100 // Creates an action that does the default action for the give mock function.
1101 inline internal::DoDefaultAction DoDefault() {
1102 return internal::DoDefaultAction();
1105 // Creates an action that sets the variable pointed by the N-th
1106 // (0-based) function argument to 'value'.
1107 template <size_t N, typename T>
1108 PolymorphicAction<
1109 internal::SetArgumentPointeeAction<
1110 N, T, internal::IsAProtocolMessage<T>::value> >
1111 SetArgPointee(const T& x) {
1112 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1113 N, T, internal::IsAProtocolMessage<T>::value>(x));
1116 #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
1117 // This overload allows SetArgPointee() to accept a string literal.
1118 // GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish
1119 // this overload from the templated version and emit a compile error.
1120 template <size_t N>
1121 PolymorphicAction<
1122 internal::SetArgumentPointeeAction<N, const char*, false> >
1123 SetArgPointee(const char* p) {
1124 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1125 N, const char*, false>(p));
1128 template <size_t N>
1129 PolymorphicAction<
1130 internal::SetArgumentPointeeAction<N, const wchar_t*, false> >
1131 SetArgPointee(const wchar_t* p) {
1132 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1133 N, const wchar_t*, false>(p));
1135 #endif
1137 // The following version is DEPRECATED.
1138 template <size_t N, typename T>
1139 PolymorphicAction<
1140 internal::SetArgumentPointeeAction<
1141 N, T, internal::IsAProtocolMessage<T>::value> >
1142 SetArgumentPointee(const T& x) {
1143 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1144 N, T, internal::IsAProtocolMessage<T>::value>(x));
1147 // Creates an action that sets a pointer referent to a given value.
1148 template <typename T1, typename T2>
1149 PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
1150 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
1153 #if !GTEST_OS_WINDOWS_MOBILE
1155 // Creates an action that sets errno and returns the appropriate error.
1156 template <typename T>
1157 PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
1158 SetErrnoAndReturn(int errval, T result) {
1159 return MakePolymorphicAction(
1160 internal::SetErrnoAndReturnAction<T>(errval, result));
1163 #endif // !GTEST_OS_WINDOWS_MOBILE
1165 // Various overloads for InvokeWithoutArgs().
1167 // Creates an action that invokes 'function_impl' with no argument.
1168 template <typename FunctionImpl>
1169 PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
1170 InvokeWithoutArgs(FunctionImpl function_impl) {
1171 return MakePolymorphicAction(
1172 internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
1175 // Creates an action that invokes the given method on the given object
1176 // with no argument.
1177 template <class Class, typename MethodPtr>
1178 PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
1179 InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
1180 return MakePolymorphicAction(
1181 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
1182 obj_ptr, method_ptr));
1185 // Creates an action that performs an_action and throws away its
1186 // result. In other words, it changes the return type of an_action to
1187 // void. an_action MUST NOT return void, or the code won't compile.
1188 template <typename A>
1189 inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1190 return internal::IgnoreResultAction<A>(an_action);
1193 // Creates a reference wrapper for the given L-value. If necessary,
1194 // you can explicitly specify the type of the reference. For example,
1195 // suppose 'derived' is an object of type Derived, ByRef(derived)
1196 // would wrap a Derived&. If you want to wrap a const Base& instead,
1197 // where Base is a base class of Derived, just write:
1199 // ByRef<const Base>(derived)
1200 template <typename T>
1201 inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT
1202 return internal::ReferenceWrapper<T>(l_value);
1205 } // namespace testing
1207 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_