gmock-matchers.h revision c6a412397bc98f120d5e79d4a64e3972854b5af3
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// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements some commonly used argument matchers.  More
35// matchers can be defined by the user implementing the
36// MatcherInterface<T> interface if necessary.
37
38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
40
41#include <algorithm>
42#include <ostream>  // NOLINT
43#include <sstream>
44#include <string>
45#include <vector>
46
47#include <gmock/gmock-printers.h>
48#include <gmock/internal/gmock-internal-utils.h>
49#include <gmock/internal/gmock-port.h>
50#include <gtest/gtest.h>
51
52namespace testing {
53
54// To implement a matcher Foo for type T, define:
55//   1. a class FooMatcherImpl that implements the
56//      MatcherInterface<T> interface, and
57//   2. a factory function that creates a Matcher<T> object from a
58//      FooMatcherImpl*.
59//
60// The two-level delegation design makes it possible to allow a user
61// to write "v" instead of "Eq(v)" where a Matcher is expected, which
62// is impossible if we pass matchers by pointers.  It also eases
63// ownership management as Matcher objects can now be copied like
64// plain values.
65
66// The implementation of a matcher.
67template <typename T>
68class MatcherInterface {
69 public:
70  virtual ~MatcherInterface() {}
71
72  // Returns true iff the matcher matches x.
73  virtual bool Matches(T x) const = 0;
74
75  // Describes this matcher to an ostream.
76  virtual void DescribeTo(::std::ostream* os) const = 0;
77
78  // Describes the negation of this matcher to an ostream.  For
79  // example, if the description of this matcher is "is greater than
80  // 7", the negated description could be "is not greater than 7".
81  // You are not required to override this when implementing
82  // MatcherInterface, but it is highly advised so that your matcher
83  // can produce good error messages.
84  virtual void DescribeNegationTo(::std::ostream* os) const {
85    *os << "not (";
86    DescribeTo(os);
87    *os << ")";
88  }
89
90  // Explains why x matches, or doesn't match, the matcher.  Override
91  // this to provide any additional information that helps a user
92  // understand the match result.
93  virtual void ExplainMatchResultTo(T /* x */, ::std::ostream* /* os */) const {
94    // By default, nothing more needs to be explained, as Google Mock
95    // has already printed the value of x when this function is
96    // called.
97  }
98};
99
100namespace internal {
101
102// An internal class for implementing Matcher<T>, which will derive
103// from it.  We put functionalities common to all Matcher<T>
104// specializations here to avoid code duplication.
105template <typename T>
106class MatcherBase {
107 public:
108  // Returns true iff this matcher matches x.
109  bool Matches(T x) const { return impl_->Matches(x); }
110
111  // Describes this matcher to an ostream.
112  void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
113
114  // Describes the negation of this matcher to an ostream.
115  void DescribeNegationTo(::std::ostream* os) const {
116    impl_->DescribeNegationTo(os);
117  }
118
119  // Explains why x matches, or doesn't match, the matcher.
120  void ExplainMatchResultTo(T x, ::std::ostream* os) const {
121    impl_->ExplainMatchResultTo(x, os);
122  }
123 protected:
124  MatcherBase() {}
125
126  // Constructs a matcher from its implementation.
127  explicit MatcherBase(const MatcherInterface<T>* impl)
128      : impl_(impl) {}
129
130  virtual ~MatcherBase() {}
131 private:
132  // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
133  // interfaces.  The former dynamically allocates a chunk of memory
134  // to hold the reference count, while the latter tracks all
135  // references using a circular linked list without allocating
136  // memory.  It has been observed that linked_ptr performs better in
137  // typical scenarios.  However, shared_ptr can out-perform
138  // linked_ptr when there are many more uses of the copy constructor
139  // than the default constructor.
140  //
141  // If performance becomes a problem, we should see if using
142  // shared_ptr helps.
143  ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
144};
145
146// The default implementation of ExplainMatchResultTo() for
147// polymorphic matchers.
148template <typename PolymorphicMatcherImpl, typename T>
149inline void ExplainMatchResultTo(const PolymorphicMatcherImpl& /* impl */,
150                                 const T& /* x */,
151                                 ::std::ostream* /* os */) {
152  // By default, nothing more needs to be said, as Google Mock already
153  // prints the value of x elsewhere.
154}
155
156}  // namespace internal
157
158// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
159// object that can check whether a value of type T matches.  The
160// implementation of Matcher<T> is just a linked_ptr to const
161// MatcherInterface<T>, so copying is fairly cheap.  Don't inherit
162// from Matcher!
163template <typename T>
164class Matcher : public internal::MatcherBase<T> {
165 public:
166  // Constructs a null matcher.  Needed for storing Matcher objects in
167  // STL containers.
168  Matcher() {}
169
170  // Constructs a matcher from its implementation.
171  explicit Matcher(const MatcherInterface<T>* impl)
172      : internal::MatcherBase<T>(impl) {}
173
174  // Implicit constructor here allows people to write
175  // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
176  Matcher(T value);  // NOLINT
177};
178
179// The following two specializations allow the user to write str
180// instead of Eq(str) and "foo" instead of Eq("foo") when a string
181// matcher is expected.
182template <>
183class Matcher<const internal::string&>
184    : public internal::MatcherBase<const internal::string&> {
185 public:
186  Matcher() {}
187
188  explicit Matcher(const MatcherInterface<const internal::string&>* impl)
189      : internal::MatcherBase<const internal::string&>(impl) {}
190
191  // Allows the user to write str instead of Eq(str) sometimes, where
192  // str is a string object.
193  Matcher(const internal::string& s);  // NOLINT
194
195  // Allows the user to write "foo" instead of Eq("foo") sometimes.
196  Matcher(const char* s);  // NOLINT
197};
198
199template <>
200class Matcher<internal::string>
201    : public internal::MatcherBase<internal::string> {
202 public:
203  Matcher() {}
204
205  explicit Matcher(const MatcherInterface<internal::string>* impl)
206      : internal::MatcherBase<internal::string>(impl) {}
207
208  // Allows the user to write str instead of Eq(str) sometimes, where
209  // str is a string object.
210  Matcher(const internal::string& s);  // NOLINT
211
212  // Allows the user to write "foo" instead of Eq("foo") sometimes.
213  Matcher(const char* s);  // NOLINT
214};
215
216// The PolymorphicMatcher class template makes it easy to implement a
217// polymorphic matcher (i.e. a matcher that can match values of more
218// than one type, e.g. Eq(n) and NotNull()).
219//
220// To define a polymorphic matcher, a user first provides a Impl class
221// that has a Matches() method, a DescribeTo() method, and a
222// DescribeNegationTo() method.  The Matches() method is usually a
223// method template (such that it works with multiple types).  Then the
224// user creates the polymorphic matcher using
225// MakePolymorphicMatcher().  To provide additional explanation to the
226// match result, define a FREE function (or function template)
227//
228//   void ExplainMatchResultTo(const Impl& matcher, const Value& value,
229//                             ::std::ostream* os);
230//
231// in the SAME NAME SPACE where Impl is defined.  See the definition
232// of NotNull() for a complete example.
233template <class Impl>
234class PolymorphicMatcher {
235 public:
236  explicit PolymorphicMatcher(const Impl& impl) : impl_(impl) {}
237
238  template <typename T>
239  operator Matcher<T>() const {
240    return Matcher<T>(new MonomorphicImpl<T>(impl_));
241  }
242 private:
243  template <typename T>
244  class MonomorphicImpl : public MatcherInterface<T> {
245   public:
246    explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
247
248    virtual bool Matches(T x) const { return impl_.Matches(x); }
249
250    virtual void DescribeTo(::std::ostream* os) const {
251      impl_.DescribeTo(os);
252    }
253
254    virtual void DescribeNegationTo(::std::ostream* os) const {
255      impl_.DescribeNegationTo(os);
256    }
257
258    virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
259      using ::testing::internal::ExplainMatchResultTo;
260
261      // C++ uses Argument-Dependent Look-up (aka Koenig Look-up) to
262      // resolve the call to ExplainMatchResultTo() here.  This
263      // means that if there's a ExplainMatchResultTo() function
264      // defined in the name space where class Impl is defined, it
265      // will be picked by the compiler as the better match.
266      // Otherwise the default implementation of it in
267      // ::testing::internal will be picked.
268      //
269      // This look-up rule lets a writer of a polymorphic matcher
270      // customize the behavior of ExplainMatchResultTo() when he
271      // cares to.  Nothing needs to be done by the writer if he
272      // doesn't need to customize it.
273      ExplainMatchResultTo(impl_, x, os);
274    }
275   private:
276    const Impl impl_;
277  };
278
279  const Impl impl_;
280};
281
282// Creates a matcher from its implementation.  This is easier to use
283// than the Matcher<T> constructor as it doesn't require you to
284// explicitly write the template argument, e.g.
285//
286//   MakeMatcher(foo);
287// vs
288//   Matcher<const string&>(foo);
289template <typename T>
290inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
291  return Matcher<T>(impl);
292};
293
294// Creates a polymorphic matcher from its implementation.  This is
295// easier to use than the PolymorphicMatcher<Impl> constructor as it
296// doesn't require you to explicitly write the template argument, e.g.
297//
298//   MakePolymorphicMatcher(foo);
299// vs
300//   PolymorphicMatcher<TypeOfFoo>(foo);
301template <class Impl>
302inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
303  return PolymorphicMatcher<Impl>(impl);
304}
305
306// In order to be safe and clear, casting between different matcher
307// types is done explicitly via MatcherCast<T>(m), which takes a
308// matcher m and returns a Matcher<T>.  It compiles only when T can be
309// statically converted to the argument type of m.
310template <typename T, typename M>
311Matcher<T> MatcherCast(M m);
312
313// TODO(vladl@google.com): Modify the implementation to reject casting
314// Matcher<int> to Matcher<double>.
315// Implements SafeMatcherCast().
316//
317// This overload handles polymorphic matchers only since monomorphic
318// matchers are handled by the next one.
319template <typename T, typename M>
320inline Matcher<T> SafeMatcherCast(M polymorphic_matcher) {
321  return Matcher<T>(polymorphic_matcher);
322}
323
324// This overload handles monomorphic matchers.
325//
326// In general, if type T can be implicitly converted to type U, we can
327// safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
328// contravariant): just keep a copy of the original Matcher<U>, convert the
329// argument from type T to U, and then pass it to the underlying Matcher<U>.
330// The only exception is when U is a reference and T is not, as the
331// underlying Matcher<U> may be interested in the argument's address, which
332// is not preserved in the conversion from T to U.
333template <typename T, typename U>
334Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
335  // Enforce that T can be implicitly converted to U.
336  GMOCK_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
337                        T_must_be_implicitly_convertible_to_U);
338  // Enforce that we are not converting a non-reference type T to a reference
339  // type U.
340  GMOCK_COMPILE_ASSERT_(
341      internal::is_reference<T>::value || !internal::is_reference<U>::value,
342      cannot_convert_non_referentce_arg_to_reference);
343  return MatcherCast<T>(matcher);
344}
345
346// A<T>() returns a matcher that matches any value of type T.
347template <typename T>
348Matcher<T> A();
349
350// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
351// and MUST NOT BE USED IN USER CODE!!!
352namespace internal {
353
354// Appends the explanation on the result of matcher.Matches(value) to
355// os iff the explanation is not empty.
356template <typename T>
357void ExplainMatchResultAsNeededTo(const Matcher<T>& matcher, T value,
358                                  ::std::ostream* os) {
359  ::std::stringstream reason;
360  matcher.ExplainMatchResultTo(value, &reason);
361  const internal::string s = reason.str();
362  if (s != "") {
363    *os << " (" << s << ")";
364  }
365}
366
367// An internal helper class for doing compile-time loop on a tuple's
368// fields.
369template <size_t N>
370class TuplePrefix {
371 public:
372  // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
373  // iff the first N fields of matcher_tuple matches the first N
374  // fields of value_tuple, respectively.
375  template <typename MatcherTuple, typename ValueTuple>
376  static bool Matches(const MatcherTuple& matcher_tuple,
377                      const ValueTuple& value_tuple) {
378    using ::std::tr1::get;
379    return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
380        && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
381  }
382
383  // TuplePrefix<N>::DescribeMatchFailuresTo(matchers, values, os)
384  // describes failures in matching the first N fields of matchers
385  // against the first N fields of values.  If there is no failure,
386  // nothing will be streamed to os.
387  template <typename MatcherTuple, typename ValueTuple>
388  static void DescribeMatchFailuresTo(const MatcherTuple& matchers,
389                                      const ValueTuple& values,
390                                      ::std::ostream* os) {
391    using ::std::tr1::tuple_element;
392    using ::std::tr1::get;
393
394    // First, describes failures in the first N - 1 fields.
395    TuplePrefix<N - 1>::DescribeMatchFailuresTo(matchers, values, os);
396
397    // Then describes the failure (if any) in the (N - 1)-th (0-based)
398    // field.
399    typename tuple_element<N - 1, MatcherTuple>::type matcher =
400        get<N - 1>(matchers);
401    typedef typename tuple_element<N - 1, ValueTuple>::type Value;
402    Value value = get<N - 1>(values);
403    if (!matcher.Matches(value)) {
404      // TODO(wan): include in the message the name of the parameter
405      // as used in MOCK_METHOD*() when possible.
406      *os << "  Expected arg #" << N - 1 << ": ";
407      get<N - 1>(matchers).DescribeTo(os);
408      *os << "\n           Actual: ";
409      // We remove the reference in type Value to prevent the
410      // universal printer from printing the address of value, which
411      // isn't interesting to the user most of the time.  The
412      // matcher's ExplainMatchResultTo() method handles the case when
413      // the address is interesting.
414      internal::UniversalPrinter<GMOCK_REMOVE_REFERENCE_(Value)>::
415          Print(value, os);
416      ExplainMatchResultAsNeededTo<Value>(matcher, value, os);
417      *os << "\n";
418    }
419  }
420};
421
422// The base case.
423template <>
424class TuplePrefix<0> {
425 public:
426  template <typename MatcherTuple, typename ValueTuple>
427  static bool Matches(const MatcherTuple& /* matcher_tuple */,
428                      const ValueTuple& /* value_tuple */) {
429    return true;
430  }
431
432  template <typename MatcherTuple, typename ValueTuple>
433  static void DescribeMatchFailuresTo(const MatcherTuple& /* matchers */,
434                                      const ValueTuple& /* values */,
435                                      ::std::ostream* /* os */) {}
436};
437
438// TupleMatches(matcher_tuple, value_tuple) returns true iff all
439// matchers in matcher_tuple match the corresponding fields in
440// value_tuple.  It is a compiler error if matcher_tuple and
441// value_tuple have different number of fields or incompatible field
442// types.
443template <typename MatcherTuple, typename ValueTuple>
444bool TupleMatches(const MatcherTuple& matcher_tuple,
445                  const ValueTuple& value_tuple) {
446  using ::std::tr1::tuple_size;
447  // Makes sure that matcher_tuple and value_tuple have the same
448  // number of fields.
449  GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
450                        tuple_size<ValueTuple>::value,
451                        matcher_and_value_have_different_numbers_of_fields);
452  return TuplePrefix<tuple_size<ValueTuple>::value>::
453      Matches(matcher_tuple, value_tuple);
454}
455
456// Describes failures in matching matchers against values.  If there
457// is no failure, nothing will be streamed to os.
458template <typename MatcherTuple, typename ValueTuple>
459void DescribeMatchFailureTupleTo(const MatcherTuple& matchers,
460                                 const ValueTuple& values,
461                                 ::std::ostream* os) {
462  using ::std::tr1::tuple_size;
463  TuplePrefix<tuple_size<MatcherTuple>::value>::DescribeMatchFailuresTo(
464      matchers, values, os);
465}
466
467// The MatcherCastImpl class template is a helper for implementing
468// MatcherCast().  We need this helper in order to partially
469// specialize the implementation of MatcherCast() (C++ allows
470// class/struct templates to be partially specialized, but not
471// function templates.).
472
473// This general version is used when MatcherCast()'s argument is a
474// polymorphic matcher (i.e. something that can be converted to a
475// Matcher but is not one yet; for example, Eq(value)).
476template <typename T, typename M>
477class MatcherCastImpl {
478 public:
479  static Matcher<T> Cast(M polymorphic_matcher) {
480    return Matcher<T>(polymorphic_matcher);
481  }
482};
483
484// This more specialized version is used when MatcherCast()'s argument
485// is already a Matcher.  This only compiles when type T can be
486// statically converted to type U.
487template <typename T, typename U>
488class MatcherCastImpl<T, Matcher<U> > {
489 public:
490  static Matcher<T> Cast(const Matcher<U>& source_matcher) {
491    return Matcher<T>(new Impl(source_matcher));
492  }
493 private:
494  class Impl : public MatcherInterface<T> {
495   public:
496    explicit Impl(const Matcher<U>& source_matcher)
497        : source_matcher_(source_matcher) {}
498
499    // We delegate the matching logic to the source matcher.
500    virtual bool Matches(T x) const {
501      return source_matcher_.Matches(static_cast<U>(x));
502    }
503
504    virtual void DescribeTo(::std::ostream* os) const {
505      source_matcher_.DescribeTo(os);
506    }
507
508    virtual void DescribeNegationTo(::std::ostream* os) const {
509      source_matcher_.DescribeNegationTo(os);
510    }
511
512    virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
513      source_matcher_.ExplainMatchResultTo(static_cast<U>(x), os);
514    }
515   private:
516    const Matcher<U> source_matcher_;
517  };
518};
519
520// This even more specialized version is used for efficiently casting
521// a matcher to its own type.
522template <typename T>
523class MatcherCastImpl<T, Matcher<T> > {
524 public:
525  static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
526};
527
528// Implements A<T>().
529template <typename T>
530class AnyMatcherImpl : public MatcherInterface<T> {
531 public:
532  virtual bool Matches(T /* x */) const { return true; }
533  virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
534  virtual void DescribeNegationTo(::std::ostream* os) const {
535    // This is mostly for completeness' safe, as it's not very useful
536    // to write Not(A<bool>()).  However we cannot completely rule out
537    // such a possibility, and it doesn't hurt to be prepared.
538    *os << "never matches";
539  }
540};
541
542// Implements _, a matcher that matches any value of any
543// type.  This is a polymorphic matcher, so we need a template type
544// conversion operator to make it appearing as a Matcher<T> for any
545// type T.
546class AnythingMatcher {
547 public:
548  template <typename T>
549  operator Matcher<T>() const { return A<T>(); }
550};
551
552// Implements a matcher that compares a given value with a
553// pre-supplied value using one of the ==, <=, <, etc, operators.  The
554// two values being compared don't have to have the same type.
555//
556// The matcher defined here is polymorphic (for example, Eq(5) can be
557// used to match an int, a short, a double, etc).  Therefore we use
558// a template type conversion operator in the implementation.
559//
560// We define this as a macro in order to eliminate duplicated source
561// code.
562//
563// The following template definition assumes that the Rhs parameter is
564// a "bare" type (i.e. neither 'const T' nor 'T&').
565#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_(name, op, relation) \
566  template <typename Rhs> class name##Matcher { \
567   public: \
568    explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
569    template <typename Lhs> \
570    operator Matcher<Lhs>() const { \
571      return MakeMatcher(new Impl<Lhs>(rhs_)); \
572    } \
573   private: \
574    template <typename Lhs> \
575    class Impl : public MatcherInterface<Lhs> { \
576     public: \
577      explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
578      virtual bool Matches(Lhs lhs) const { return lhs op rhs_; } \
579      virtual void DescribeTo(::std::ostream* os) const { \
580        *os << "is " relation  " "; \
581        UniversalPrinter<Rhs>::Print(rhs_, os); \
582      } \
583      virtual void DescribeNegationTo(::std::ostream* os) const { \
584        *os << "is not " relation  " "; \
585        UniversalPrinter<Rhs>::Print(rhs_, os); \
586      } \
587     private: \
588      Rhs rhs_; \
589    }; \
590    Rhs rhs_; \
591  }
592
593// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
594// respectively.
595GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "equal to");
596GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "greater than or equal to");
597GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "greater than");
598GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "less than or equal to");
599GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "less than");
600GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "not equal to");
601
602#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
603
604// Implements the polymorphic NotNull() matcher, which matches any
605// pointer that is not NULL.
606class NotNullMatcher {
607 public:
608  template <typename T>
609  bool Matches(T* p) const { return p != NULL; }
610
611  void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
612  void DescribeNegationTo(::std::ostream* os) const {
613    *os << "is NULL";
614  }
615};
616
617// Ref(variable) matches any argument that is a reference to
618// 'variable'.  This matcher is polymorphic as it can match any
619// super type of the type of 'variable'.
620//
621// The RefMatcher template class implements Ref(variable).  It can
622// only be instantiated with a reference type.  This prevents a user
623// from mistakenly using Ref(x) to match a non-reference function
624// argument.  For example, the following will righteously cause a
625// compiler error:
626//
627//   int n;
628//   Matcher<int> m1 = Ref(n);   // This won't compile.
629//   Matcher<int&> m2 = Ref(n);  // This will compile.
630template <typename T>
631class RefMatcher;
632
633template <typename T>
634class RefMatcher<T&> {
635  // Google Mock is a generic framework and thus needs to support
636  // mocking any function types, including those that take non-const
637  // reference arguments.  Therefore the template parameter T (and
638  // Super below) can be instantiated to either a const type or a
639  // non-const type.
640 public:
641  // RefMatcher() takes a T& instead of const T&, as we want the
642  // compiler to catch using Ref(const_value) as a matcher for a
643  // non-const reference.
644  explicit RefMatcher(T& x) : object_(x) {}  // NOLINT
645
646  template <typename Super>
647  operator Matcher<Super&>() const {
648    // By passing object_ (type T&) to Impl(), which expects a Super&,
649    // we make sure that Super is a super type of T.  In particular,
650    // this catches using Ref(const_value) as a matcher for a
651    // non-const reference, as you cannot implicitly convert a const
652    // reference to a non-const reference.
653    return MakeMatcher(new Impl<Super>(object_));
654  }
655 private:
656  template <typename Super>
657  class Impl : public MatcherInterface<Super&> {
658   public:
659    explicit Impl(Super& x) : object_(x) {}  // NOLINT
660
661    // Matches() takes a Super& (as opposed to const Super&) in
662    // order to match the interface MatcherInterface<Super&>.
663    virtual bool Matches(Super& x) const { return &x == &object_; }  // NOLINT
664
665    virtual void DescribeTo(::std::ostream* os) const {
666      *os << "references the variable ";
667      UniversalPrinter<Super&>::Print(object_, os);
668    }
669
670    virtual void DescribeNegationTo(::std::ostream* os) const {
671      *os << "does not reference the variable ";
672      UniversalPrinter<Super&>::Print(object_, os);
673    }
674
675    virtual void ExplainMatchResultTo(Super& x,  // NOLINT
676                                      ::std::ostream* os) const {
677      *os << "is located @" << static_cast<const void*>(&x);
678    }
679   private:
680    const Super& object_;
681  };
682
683  T& object_;
684};
685
686// Polymorphic helper functions for narrow and wide string matchers.
687inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
688  return String::CaseInsensitiveCStringEquals(lhs, rhs);
689}
690
691inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
692                                         const wchar_t* rhs) {
693  return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
694}
695
696// String comparison for narrow or wide strings that can have embedded NUL
697// characters.
698template <typename StringType>
699bool CaseInsensitiveStringEquals(const StringType& s1,
700                                 const StringType& s2) {
701  // Are the heads equal?
702  if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
703    return false;
704  }
705
706  // Skip the equal heads.
707  const typename StringType::value_type nul = 0;
708  const size_t i1 = s1.find(nul), i2 = s2.find(nul);
709
710  // Are we at the end of either s1 or s2?
711  if (i1 == StringType::npos || i2 == StringType::npos) {
712    return i1 == i2;
713  }
714
715  // Are the tails equal?
716  return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
717}
718
719// String matchers.
720
721// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
722template <typename StringType>
723class StrEqualityMatcher {
724 public:
725  typedef typename StringType::const_pointer ConstCharPointer;
726
727  StrEqualityMatcher(const StringType& str, bool expect_eq,
728                     bool case_sensitive)
729      : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
730
731  // When expect_eq_ is true, returns true iff s is equal to string_;
732  // otherwise returns true iff s is not equal to string_.
733  bool Matches(ConstCharPointer s) const {
734    if (s == NULL) {
735      return !expect_eq_;
736    }
737    return Matches(StringType(s));
738  }
739
740  bool Matches(const StringType& s) const {
741    const bool eq = case_sensitive_ ? s == string_ :
742        CaseInsensitiveStringEquals(s, string_);
743    return expect_eq_ == eq;
744  }
745
746  void DescribeTo(::std::ostream* os) const {
747    DescribeToHelper(expect_eq_, os);
748  }
749
750  void DescribeNegationTo(::std::ostream* os) const {
751    DescribeToHelper(!expect_eq_, os);
752  }
753 private:
754  void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
755    *os << "is ";
756    if (!expect_eq) {
757      *os << "not ";
758    }
759    *os << "equal to ";
760    if (!case_sensitive_) {
761      *os << "(ignoring case) ";
762    }
763    UniversalPrinter<StringType>::Print(string_, os);
764  }
765
766  const StringType string_;
767  const bool expect_eq_;
768  const bool case_sensitive_;
769};
770
771// Implements the polymorphic HasSubstr(substring) matcher, which
772// can be used as a Matcher<T> as long as T can be converted to a
773// string.
774template <typename StringType>
775class HasSubstrMatcher {
776 public:
777  typedef typename StringType::const_pointer ConstCharPointer;
778
779  explicit HasSubstrMatcher(const StringType& substring)
780      : substring_(substring) {}
781
782  // These overloaded methods allow HasSubstr(substring) to be used as a
783  // Matcher<T> as long as T can be converted to string.  Returns true
784  // iff s contains substring_ as a substring.
785  bool Matches(ConstCharPointer s) const {
786    return s != NULL && Matches(StringType(s));
787  }
788
789  bool Matches(const StringType& s) const {
790    return s.find(substring_) != StringType::npos;
791  }
792
793  // Describes what this matcher matches.
794  void DescribeTo(::std::ostream* os) const {
795    *os << "has substring ";
796    UniversalPrinter<StringType>::Print(substring_, os);
797  }
798
799  void DescribeNegationTo(::std::ostream* os) const {
800    *os << "has no substring ";
801    UniversalPrinter<StringType>::Print(substring_, os);
802  }
803 private:
804  const StringType substring_;
805};
806
807// Implements the polymorphic StartsWith(substring) matcher, which
808// can be used as a Matcher<T> as long as T can be converted to a
809// string.
810template <typename StringType>
811class StartsWithMatcher {
812 public:
813  typedef typename StringType::const_pointer ConstCharPointer;
814
815  explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
816  }
817
818  // These overloaded methods allow StartsWith(prefix) to be used as a
819  // Matcher<T> as long as T can be converted to string.  Returns true
820  // iff s starts with prefix_.
821  bool Matches(ConstCharPointer s) const {
822    return s != NULL && Matches(StringType(s));
823  }
824
825  bool Matches(const StringType& s) const {
826    return s.length() >= prefix_.length() &&
827        s.substr(0, prefix_.length()) == prefix_;
828  }
829
830  void DescribeTo(::std::ostream* os) const {
831    *os << "starts with ";
832    UniversalPrinter<StringType>::Print(prefix_, os);
833  }
834
835  void DescribeNegationTo(::std::ostream* os) const {
836    *os << "doesn't start with ";
837    UniversalPrinter<StringType>::Print(prefix_, os);
838  }
839 private:
840  const StringType prefix_;
841};
842
843// Implements the polymorphic EndsWith(substring) matcher, which
844// can be used as a Matcher<T> as long as T can be converted to a
845// string.
846template <typename StringType>
847class EndsWithMatcher {
848 public:
849  typedef typename StringType::const_pointer ConstCharPointer;
850
851  explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
852
853  // These overloaded methods allow EndsWith(suffix) to be used as a
854  // Matcher<T> as long as T can be converted to string.  Returns true
855  // iff s ends with suffix_.
856  bool Matches(ConstCharPointer s) const {
857    return s != NULL && Matches(StringType(s));
858  }
859
860  bool Matches(const StringType& s) const {
861    return s.length() >= suffix_.length() &&
862        s.substr(s.length() - suffix_.length()) == suffix_;
863  }
864
865  void DescribeTo(::std::ostream* os) const {
866    *os << "ends with ";
867    UniversalPrinter<StringType>::Print(suffix_, os);
868  }
869
870  void DescribeNegationTo(::std::ostream* os) const {
871    *os << "doesn't end with ";
872    UniversalPrinter<StringType>::Print(suffix_, os);
873  }
874 private:
875  const StringType suffix_;
876};
877
878#if GMOCK_HAS_REGEX
879
880// Implements polymorphic matchers MatchesRegex(regex) and
881// ContainsRegex(regex), which can be used as a Matcher<T> as long as
882// T can be converted to a string.
883class MatchesRegexMatcher {
884 public:
885  MatchesRegexMatcher(const RE* regex, bool full_match)
886      : regex_(regex), full_match_(full_match) {}
887
888  // These overloaded methods allow MatchesRegex(regex) to be used as
889  // a Matcher<T> as long as T can be converted to string.  Returns
890  // true iff s matches regular expression regex.  When full_match_ is
891  // true, a full match is done; otherwise a partial match is done.
892  bool Matches(const char* s) const {
893    return s != NULL && Matches(internal::string(s));
894  }
895
896  bool Matches(const internal::string& s) const {
897    return full_match_ ? RE::FullMatch(s, *regex_) :
898        RE::PartialMatch(s, *regex_);
899  }
900
901  void DescribeTo(::std::ostream* os) const {
902    *os << (full_match_ ? "matches" : "contains")
903        << " regular expression ";
904    UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
905  }
906
907  void DescribeNegationTo(::std::ostream* os) const {
908    *os << "doesn't " << (full_match_ ? "match" : "contain")
909        << " regular expression ";
910    UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
911  }
912 private:
913  const internal::linked_ptr<const RE> regex_;
914  const bool full_match_;
915};
916
917#endif  // GMOCK_HAS_REGEX
918
919// Implements a matcher that compares the two fields of a 2-tuple
920// using one of the ==, <=, <, etc, operators.  The two fields being
921// compared don't have to have the same type.
922//
923// The matcher defined here is polymorphic (for example, Eq() can be
924// used to match a tuple<int, short>, a tuple<const long&, double>,
925// etc).  Therefore we use a template type conversion operator in the
926// implementation.
927//
928// We define this as a macro in order to eliminate duplicated source
929// code.
930#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
931  class name##2Matcher { \
932   public: \
933    template <typename T1, typename T2> \
934    operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
935      return MakeMatcher(new Impl<T1, T2>); \
936    } \
937   private: \
938    template <typename T1, typename T2> \
939    class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
940     public: \
941      virtual bool Matches(const ::std::tr1::tuple<T1, T2>& args) const { \
942        return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
943      } \
944      virtual void DescribeTo(::std::ostream* os) const { \
945        *os << "argument #0 is " relation " argument #1"; \
946      } \
947      virtual void DescribeNegationTo(::std::ostream* os) const { \
948        *os << "argument #0 is not " relation " argument #1"; \
949      } \
950    }; \
951  }
952
953// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
954GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "equal to");
955GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=, "greater than or equal to");
956GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >, "greater than");
957GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=, "less than or equal to");
958GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <, "less than");
959GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "not equal to");
960
961#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
962
963// Implements the Not(...) matcher for a particular argument type T.
964// We do not nest it inside the NotMatcher class template, as that
965// will prevent different instantiations of NotMatcher from sharing
966// the same NotMatcherImpl<T> class.
967template <typename T>
968class NotMatcherImpl : public MatcherInterface<T> {
969 public:
970  explicit NotMatcherImpl(const Matcher<T>& matcher)
971      : matcher_(matcher) {}
972
973  virtual bool Matches(T x) const {
974    return !matcher_.Matches(x);
975  }
976
977  virtual void DescribeTo(::std::ostream* os) const {
978    matcher_.DescribeNegationTo(os);
979  }
980
981  virtual void DescribeNegationTo(::std::ostream* os) const {
982    matcher_.DescribeTo(os);
983  }
984
985  virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
986    matcher_.ExplainMatchResultTo(x, os);
987  }
988 private:
989  const Matcher<T> matcher_;
990};
991
992// Implements the Not(m) matcher, which matches a value that doesn't
993// match matcher m.
994template <typename InnerMatcher>
995class NotMatcher {
996 public:
997  explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
998
999  // This template type conversion operator allows Not(m) to be used
1000  // to match any type m can match.
1001  template <typename T>
1002  operator Matcher<T>() const {
1003    return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
1004  }
1005 private:
1006  InnerMatcher matcher_;
1007};
1008
1009// Implements the AllOf(m1, m2) matcher for a particular argument type
1010// T. We do not nest it inside the BothOfMatcher class template, as
1011// that will prevent different instantiations of BothOfMatcher from
1012// sharing the same BothOfMatcherImpl<T> class.
1013template <typename T>
1014class BothOfMatcherImpl : public MatcherInterface<T> {
1015 public:
1016  BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1017      : matcher1_(matcher1), matcher2_(matcher2) {}
1018
1019  virtual bool Matches(T x) const {
1020    return matcher1_.Matches(x) && matcher2_.Matches(x);
1021  }
1022
1023  virtual void DescribeTo(::std::ostream* os) const {
1024    *os << "(";
1025    matcher1_.DescribeTo(os);
1026    *os << ") and (";
1027    matcher2_.DescribeTo(os);
1028    *os << ")";
1029  }
1030
1031  virtual void DescribeNegationTo(::std::ostream* os) const {
1032    *os << "not ";
1033    DescribeTo(os);
1034  }
1035
1036  virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1037    if (Matches(x)) {
1038      // When both matcher1_ and matcher2_ match x, we need to
1039      // explain why *both* of them match.
1040      ::std::stringstream ss1;
1041      matcher1_.ExplainMatchResultTo(x, &ss1);
1042      const internal::string s1 = ss1.str();
1043
1044      ::std::stringstream ss2;
1045      matcher2_.ExplainMatchResultTo(x, &ss2);
1046      const internal::string s2 = ss2.str();
1047
1048      if (s1 == "") {
1049        *os << s2;
1050      } else {
1051        *os << s1;
1052        if (s2 != "") {
1053          *os << "; " << s2;
1054        }
1055      }
1056    } else {
1057      // Otherwise we only need to explain why *one* of them fails
1058      // to match.
1059      if (!matcher1_.Matches(x)) {
1060        matcher1_.ExplainMatchResultTo(x, os);
1061      } else {
1062        matcher2_.ExplainMatchResultTo(x, os);
1063      }
1064    }
1065  }
1066 private:
1067  const Matcher<T> matcher1_;
1068  const Matcher<T> matcher2_;
1069};
1070
1071// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1072// matches a value that matches all of the matchers m_1, ..., and m_n.
1073template <typename Matcher1, typename Matcher2>
1074class BothOfMatcher {
1075 public:
1076  BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1077      : matcher1_(matcher1), matcher2_(matcher2) {}
1078
1079  // This template type conversion operator allows a
1080  // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1081  // both Matcher1 and Matcher2 can match.
1082  template <typename T>
1083  operator Matcher<T>() const {
1084    return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1085                                               SafeMatcherCast<T>(matcher2_)));
1086  }
1087 private:
1088  Matcher1 matcher1_;
1089  Matcher2 matcher2_;
1090};
1091
1092// Implements the AnyOf(m1, m2) matcher for a particular argument type
1093// T.  We do not nest it inside the AnyOfMatcher class template, as
1094// that will prevent different instantiations of AnyOfMatcher from
1095// sharing the same EitherOfMatcherImpl<T> class.
1096template <typename T>
1097class EitherOfMatcherImpl : public MatcherInterface<T> {
1098 public:
1099  EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1100      : matcher1_(matcher1), matcher2_(matcher2) {}
1101
1102  virtual bool Matches(T x) const {
1103    return matcher1_.Matches(x) || matcher2_.Matches(x);
1104  }
1105
1106  virtual void DescribeTo(::std::ostream* os) const {
1107    *os << "(";
1108    matcher1_.DescribeTo(os);
1109    *os << ") or (";
1110    matcher2_.DescribeTo(os);
1111    *os << ")";
1112  }
1113
1114  virtual void DescribeNegationTo(::std::ostream* os) const {
1115    *os << "not ";
1116    DescribeTo(os);
1117  }
1118
1119  virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1120    if (Matches(x)) {
1121      // If either matcher1_ or matcher2_ matches x, we just need
1122      // to explain why *one* of them matches.
1123      if (matcher1_.Matches(x)) {
1124        matcher1_.ExplainMatchResultTo(x, os);
1125      } else {
1126        matcher2_.ExplainMatchResultTo(x, os);
1127      }
1128    } else {
1129      // Otherwise we need to explain why *neither* matches.
1130      ::std::stringstream ss1;
1131      matcher1_.ExplainMatchResultTo(x, &ss1);
1132      const internal::string s1 = ss1.str();
1133
1134      ::std::stringstream ss2;
1135      matcher2_.ExplainMatchResultTo(x, &ss2);
1136      const internal::string s2 = ss2.str();
1137
1138      if (s1 == "") {
1139        *os << s2;
1140      } else {
1141        *os << s1;
1142        if (s2 != "") {
1143          *os << "; " << s2;
1144        }
1145      }
1146    }
1147  }
1148 private:
1149  const Matcher<T> matcher1_;
1150  const Matcher<T> matcher2_;
1151};
1152
1153// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1154// matches a value that matches at least one of the matchers m_1, ...,
1155// and m_n.
1156template <typename Matcher1, typename Matcher2>
1157class EitherOfMatcher {
1158 public:
1159  EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1160      : matcher1_(matcher1), matcher2_(matcher2) {}
1161
1162  // This template type conversion operator allows a
1163  // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1164  // both Matcher1 and Matcher2 can match.
1165  template <typename T>
1166  operator Matcher<T>() const {
1167    return Matcher<T>(new EitherOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1168                                                 SafeMatcherCast<T>(matcher2_)));
1169  }
1170 private:
1171  Matcher1 matcher1_;
1172  Matcher2 matcher2_;
1173};
1174
1175// Used for implementing Truly(pred), which turns a predicate into a
1176// matcher.
1177template <typename Predicate>
1178class TrulyMatcher {
1179 public:
1180  explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1181
1182  // This method template allows Truly(pred) to be used as a matcher
1183  // for type T where T is the argument type of predicate 'pred'.  The
1184  // argument is passed by reference as the predicate may be
1185  // interested in the address of the argument.
1186  template <typename T>
1187  bool Matches(T& x) const {
1188#if GTEST_OS_WINDOWS
1189    // MSVC warns about converting a value into bool (warning 4800).
1190#pragma warning(push)          // Saves the current warning state.
1191#pragma warning(disable:4800)  // Temporarily disables warning 4800.
1192#endif  // GTEST_OS_WINDOWS
1193    return predicate_(x);
1194#if GTEST_OS_WINDOWS
1195#pragma warning(pop)           // Restores the warning state.
1196#endif  // GTEST_OS_WINDOWS
1197  }
1198
1199  void DescribeTo(::std::ostream* os) const {
1200    *os << "satisfies the given predicate";
1201  }
1202
1203  void DescribeNegationTo(::std::ostream* os) const {
1204    *os << "doesn't satisfy the given predicate";
1205  }
1206 private:
1207  Predicate predicate_;
1208};
1209
1210// Used for implementing Matches(matcher), which turns a matcher into
1211// a predicate.
1212template <typename M>
1213class MatcherAsPredicate {
1214 public:
1215  explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1216
1217  // This template operator() allows Matches(m) to be used as a
1218  // predicate on type T where m is a matcher on type T.
1219  //
1220  // The argument x is passed by reference instead of by value, as
1221  // some matcher may be interested in its address (e.g. as in
1222  // Matches(Ref(n))(x)).
1223  template <typename T>
1224  bool operator()(const T& x) const {
1225    // We let matcher_ commit to a particular type here instead of
1226    // when the MatcherAsPredicate object was constructed.  This
1227    // allows us to write Matches(m) where m is a polymorphic matcher
1228    // (e.g. Eq(5)).
1229    //
1230    // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1231    // compile when matcher_ has type Matcher<const T&>; if we write
1232    // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1233    // when matcher_ has type Matcher<T>; if we just write
1234    // matcher_.Matches(x), it won't compile when matcher_ is
1235    // polymorphic, e.g. Eq(5).
1236    //
1237    // MatcherCast<const T&>() is necessary for making the code work
1238    // in all of the above situations.
1239    return MatcherCast<const T&>(matcher_).Matches(x);
1240  }
1241 private:
1242  M matcher_;
1243};
1244
1245// For implementing ASSERT_THAT() and EXPECT_THAT().  The template
1246// argument M must be a type that can be converted to a matcher.
1247template <typename M>
1248class PredicateFormatterFromMatcher {
1249 public:
1250  explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1251
1252  // This template () operator allows a PredicateFormatterFromMatcher
1253  // object to act as a predicate-formatter suitable for using with
1254  // Google Test's EXPECT_PRED_FORMAT1() macro.
1255  template <typename T>
1256  AssertionResult operator()(const char* value_text, const T& x) const {
1257    // We convert matcher_ to a Matcher<const T&> *now* instead of
1258    // when the PredicateFormatterFromMatcher object was constructed,
1259    // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1260    // know which type to instantiate it to until we actually see the
1261    // type of x here.
1262    //
1263    // We write MatcherCast<const T&>(matcher_) instead of
1264    // Matcher<const T&>(matcher_), as the latter won't compile when
1265    // matcher_ has type Matcher<T> (e.g. An<int>()).
1266    const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
1267    if (matcher.Matches(x)) {
1268      return AssertionSuccess();
1269    } else {
1270      ::std::stringstream ss;
1271      ss << "Value of: " << value_text << "\n"
1272         << "Expected: ";
1273      matcher.DescribeTo(&ss);
1274      ss << "\n  Actual: ";
1275      UniversalPrinter<T>::Print(x, &ss);
1276      ExplainMatchResultAsNeededTo<const T&>(matcher, x, &ss);
1277      return AssertionFailure(Message() << ss.str());
1278    }
1279  }
1280 private:
1281  const M matcher_;
1282};
1283
1284// A helper function for converting a matcher to a predicate-formatter
1285// without the user needing to explicitly write the type.  This is
1286// used for implementing ASSERT_THAT() and EXPECT_THAT().
1287template <typename M>
1288inline PredicateFormatterFromMatcher<M>
1289MakePredicateFormatterFromMatcher(const M& matcher) {
1290  return PredicateFormatterFromMatcher<M>(matcher);
1291}
1292
1293// Implements the polymorphic floating point equality matcher, which
1294// matches two float values using ULP-based approximation.  The
1295// template is meant to be instantiated with FloatType being either
1296// float or double.
1297template <typename FloatType>
1298class FloatingEqMatcher {
1299 public:
1300  // Constructor for FloatingEqMatcher.
1301  // The matcher's input will be compared with rhs.  The matcher treats two
1302  // NANs as equal if nan_eq_nan is true.  Otherwise, under IEEE standards,
1303  // equality comparisons between NANs will always return false.
1304  FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1305    rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1306
1307  // Implements floating point equality matcher as a Matcher<T>.
1308  template <typename T>
1309  class Impl : public MatcherInterface<T> {
1310   public:
1311    Impl(FloatType rhs, bool nan_eq_nan) :
1312      rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1313
1314    virtual bool Matches(T value) const {
1315      const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1316
1317      // Compares NaNs first, if nan_eq_nan_ is true.
1318      if (nan_eq_nan_ && lhs.is_nan()) {
1319        return rhs.is_nan();
1320      }
1321
1322      return lhs.AlmostEquals(rhs);
1323    }
1324
1325    virtual void DescribeTo(::std::ostream* os) const {
1326      // os->precision() returns the previously set precision, which we
1327      // store to restore the ostream to its original configuration
1328      // after outputting.
1329      const ::std::streamsize old_precision = os->precision(
1330          ::std::numeric_limits<FloatType>::digits10 + 2);
1331      if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1332        if (nan_eq_nan_) {
1333          *os << "is NaN";
1334        } else {
1335          *os << "never matches";
1336        }
1337      } else {
1338        *os << "is approximately " << rhs_;
1339      }
1340      os->precision(old_precision);
1341    }
1342
1343    virtual void DescribeNegationTo(::std::ostream* os) const {
1344      // As before, get original precision.
1345      const ::std::streamsize old_precision = os->precision(
1346          ::std::numeric_limits<FloatType>::digits10 + 2);
1347      if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1348        if (nan_eq_nan_) {
1349          *os << "is not NaN";
1350        } else {
1351          *os << "is anything";
1352        }
1353      } else {
1354        *os << "is not approximately " << rhs_;
1355      }
1356      // Restore original precision.
1357      os->precision(old_precision);
1358    }
1359
1360   private:
1361    const FloatType rhs_;
1362    const bool nan_eq_nan_;
1363  };
1364
1365  // The following 3 type conversion operators allow FloatEq(rhs) and
1366  // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1367  // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1368  // (While Google's C++ coding style doesn't allow arguments passed
1369  // by non-const reference, we may see them in code not conforming to
1370  // the style.  Therefore Google Mock needs to support them.)
1371  operator Matcher<FloatType>() const {
1372    return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1373  }
1374
1375  operator Matcher<const FloatType&>() const {
1376    return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1377  }
1378
1379  operator Matcher<FloatType&>() const {
1380    return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1381  }
1382 private:
1383  const FloatType rhs_;
1384  const bool nan_eq_nan_;
1385};
1386
1387// Implements the Pointee(m) matcher for matching a pointer whose
1388// pointee matches matcher m.  The pointer can be either raw or smart.
1389template <typename InnerMatcher>
1390class PointeeMatcher {
1391 public:
1392  explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1393
1394  // This type conversion operator template allows Pointee(m) to be
1395  // used as a matcher for any pointer type whose pointee type is
1396  // compatible with the inner matcher, where type Pointer can be
1397  // either a raw pointer or a smart pointer.
1398  //
1399  // The reason we do this instead of relying on
1400  // MakePolymorphicMatcher() is that the latter is not flexible
1401  // enough for implementing the DescribeTo() method of Pointee().
1402  template <typename Pointer>
1403  operator Matcher<Pointer>() const {
1404    return MakeMatcher(new Impl<Pointer>(matcher_));
1405  }
1406 private:
1407  // The monomorphic implementation that works for a particular pointer type.
1408  template <typename Pointer>
1409  class Impl : public MatcherInterface<Pointer> {
1410   public:
1411    typedef typename PointeeOf<GMOCK_REMOVE_CONST_(  // NOLINT
1412        GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
1413
1414    explicit Impl(const InnerMatcher& matcher)
1415        : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1416
1417    virtual bool Matches(Pointer p) const {
1418      return GetRawPointer(p) != NULL && matcher_.Matches(*p);
1419    }
1420
1421    virtual void DescribeTo(::std::ostream* os) const {
1422      *os << "points to a value that ";
1423      matcher_.DescribeTo(os);
1424    }
1425
1426    virtual void DescribeNegationTo(::std::ostream* os) const {
1427      *os << "does not point to a value that ";
1428      matcher_.DescribeTo(os);
1429    }
1430
1431    virtual void ExplainMatchResultTo(Pointer pointer,
1432                                      ::std::ostream* os) const {
1433      if (GetRawPointer(pointer) == NULL)
1434        return;
1435
1436      ::std::stringstream ss;
1437      matcher_.ExplainMatchResultTo(*pointer, &ss);
1438      const internal::string s = ss.str();
1439      if (s != "") {
1440        *os << "points to a value that " << s;
1441      }
1442    }
1443   private:
1444    const Matcher<const Pointee&> matcher_;
1445  };
1446
1447  const InnerMatcher matcher_;
1448};
1449
1450// Implements the Field() matcher for matching a field (i.e. member
1451// variable) of an object.
1452template <typename Class, typename FieldType>
1453class FieldMatcher {
1454 public:
1455  FieldMatcher(FieldType Class::*field,
1456               const Matcher<const FieldType&>& matcher)
1457      : field_(field), matcher_(matcher) {}
1458
1459  // Returns true iff the inner matcher matches obj.field.
1460  bool Matches(const Class& obj) const {
1461    return matcher_.Matches(obj.*field_);
1462  }
1463
1464  // Returns true iff the inner matcher matches obj->field.
1465  bool Matches(const Class* p) const {
1466    return (p != NULL) && matcher_.Matches(p->*field_);
1467  }
1468
1469  void DescribeTo(::std::ostream* os) const {
1470    *os << "the given field ";
1471    matcher_.DescribeTo(os);
1472  }
1473
1474  void DescribeNegationTo(::std::ostream* os) const {
1475    *os << "the given field ";
1476    matcher_.DescribeNegationTo(os);
1477  }
1478
1479  // The first argument of ExplainMatchResultTo() is needed to help
1480  // Symbian's C++ compiler choose which overload to use.  Its type is
1481  // true_type iff the Field() matcher is used to match a pointer.
1482  void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1483                            ::std::ostream* os) const {
1484    ::std::stringstream ss;
1485    matcher_.ExplainMatchResultTo(obj.*field_, &ss);
1486    const internal::string s = ss.str();
1487    if (s != "") {
1488      *os << "the given field " << s;
1489    }
1490  }
1491
1492  void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1493                            ::std::ostream* os) const {
1494    if (p != NULL) {
1495      // Since *p has a field, it must be a class/struct/union type
1496      // and thus cannot be a pointer.  Therefore we pass false_type()
1497      // as the first argument.
1498      ExplainMatchResultTo(false_type(), *p, os);
1499    }
1500  }
1501 private:
1502  const FieldType Class::*field_;
1503  const Matcher<const FieldType&> matcher_;
1504};
1505
1506// Explains the result of matching an object or pointer against a field matcher.
1507template <typename Class, typename FieldType, typename T>
1508void ExplainMatchResultTo(const FieldMatcher<Class, FieldType>& matcher,
1509                          const T& value, ::std::ostream* os) {
1510  matcher.ExplainMatchResultTo(
1511      typename ::testing::internal::is_pointer<T>::type(), value, os);
1512}
1513
1514// Implements the Property() matcher for matching a property
1515// (i.e. return value of a getter method) of an object.
1516template <typename Class, typename PropertyType>
1517class PropertyMatcher {
1518 public:
1519  // The property may have a reference type, so 'const PropertyType&'
1520  // may cause double references and fail to compile.  That's why we
1521  // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1522  // PropertyType being a reference or not.
1523  typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
1524
1525  PropertyMatcher(PropertyType (Class::*property)() const,
1526                  const Matcher<RefToConstProperty>& matcher)
1527      : property_(property), matcher_(matcher) {}
1528
1529  // Returns true iff obj.property() matches the inner matcher.
1530  bool Matches(const Class& obj) const {
1531    return matcher_.Matches((obj.*property_)());
1532  }
1533
1534  // Returns true iff p->property() matches the inner matcher.
1535  bool Matches(const Class* p) const {
1536    return (p != NULL) && matcher_.Matches((p->*property_)());
1537  }
1538
1539  void DescribeTo(::std::ostream* os) const {
1540    *os << "the given property ";
1541    matcher_.DescribeTo(os);
1542  }
1543
1544  void DescribeNegationTo(::std::ostream* os) const {
1545    *os << "the given property ";
1546    matcher_.DescribeNegationTo(os);
1547  }
1548
1549  // The first argument of ExplainMatchResultTo() is needed to help
1550  // Symbian's C++ compiler choose which overload to use.  Its type is
1551  // true_type iff the Property() matcher is used to match a pointer.
1552  void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1553                            ::std::ostream* os) const {
1554    ::std::stringstream ss;
1555    matcher_.ExplainMatchResultTo((obj.*property_)(), &ss);
1556    const internal::string s = ss.str();
1557    if (s != "") {
1558      *os << "the given property " << s;
1559    }
1560  }
1561
1562  void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1563                            ::std::ostream* os) const {
1564    if (p != NULL) {
1565      // Since *p has a property method, it must be a
1566      // class/struct/union type and thus cannot be a pointer.
1567      // Therefore we pass false_type() as the first argument.
1568      ExplainMatchResultTo(false_type(), *p, os);
1569    }
1570  }
1571 private:
1572  PropertyType (Class::*property_)() const;
1573  const Matcher<RefToConstProperty> matcher_;
1574};
1575
1576// Explains the result of matching an object or pointer against a
1577// property matcher.
1578template <typename Class, typename PropertyType, typename T>
1579void ExplainMatchResultTo(const PropertyMatcher<Class, PropertyType>& matcher,
1580                          const T& value, ::std::ostream* os) {
1581  matcher.ExplainMatchResultTo(
1582      typename ::testing::internal::is_pointer<T>::type(), value, os);
1583}
1584
1585// Type traits specifying various features of different functors for ResultOf.
1586// The default template specifies features for functor objects.
1587// Functor classes have to typedef argument_type and result_type
1588// to be compatible with ResultOf.
1589template <typename Functor>
1590struct CallableTraits {
1591  typedef typename Functor::result_type ResultType;
1592  typedef Functor StorageType;
1593
1594  static void CheckIsValid(Functor functor) {}
1595  template <typename T>
1596  static ResultType Invoke(Functor f, T arg) { return f(arg); }
1597};
1598
1599// Specialization for function pointers.
1600template <typename ArgType, typename ResType>
1601struct CallableTraits<ResType(*)(ArgType)> {
1602  typedef ResType ResultType;
1603  typedef ResType(*StorageType)(ArgType);
1604
1605  static void CheckIsValid(ResType(*f)(ArgType)) {
1606    GMOCK_CHECK_(f != NULL)
1607        << "NULL function pointer is passed into ResultOf().";
1608  }
1609  template <typename T>
1610  static ResType Invoke(ResType(*f)(ArgType), T arg) {
1611    return (*f)(arg);
1612  }
1613};
1614
1615// Implements the ResultOf() matcher for matching a return value of a
1616// unary function of an object.
1617template <typename Callable>
1618class ResultOfMatcher {
1619 public:
1620  typedef typename CallableTraits<Callable>::ResultType ResultType;
1621
1622  ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1623      : callable_(callable), matcher_(matcher) {
1624    CallableTraits<Callable>::CheckIsValid(callable_);
1625  }
1626
1627  template <typename T>
1628  operator Matcher<T>() const {
1629    return Matcher<T>(new Impl<T>(callable_, matcher_));
1630  }
1631
1632 private:
1633  typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1634
1635  template <typename T>
1636  class Impl : public MatcherInterface<T> {
1637   public:
1638    Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1639        : callable_(callable), matcher_(matcher) {}
1640    // Returns true iff callable_(obj) matches the inner matcher.
1641    // The calling syntax is different for different types of callables
1642    // so we abstract it in CallableTraits<Callable>::Invoke().
1643    virtual bool Matches(T obj) const {
1644      return matcher_.Matches(
1645          CallableTraits<Callable>::template Invoke<T>(callable_, obj));
1646    }
1647
1648    virtual void DescribeTo(::std::ostream* os) const {
1649      *os << "result of the given callable ";
1650      matcher_.DescribeTo(os);
1651    }
1652
1653    virtual void DescribeNegationTo(::std::ostream* os) const {
1654      *os << "result of the given callable ";
1655      matcher_.DescribeNegationTo(os);
1656    }
1657
1658    virtual void ExplainMatchResultTo(T obj, ::std::ostream* os) const {
1659      ::std::stringstream ss;
1660      matcher_.ExplainMatchResultTo(
1661          CallableTraits<Callable>::template Invoke<T>(callable_, obj),
1662          &ss);
1663      const internal::string s = ss.str();
1664      if (s != "")
1665        *os << "result of the given callable " << s;
1666    }
1667   private:
1668    // Functors often define operator() as non-const method even though
1669    // they are actualy stateless. But we need to use them even when
1670    // 'this' is a const pointer. It's the user's responsibility not to
1671    // use stateful callables with ResultOf(), which does't guarantee
1672    // how many times the callable will be invoked.
1673    mutable CallableStorageType callable_;
1674    const Matcher<ResultType> matcher_;
1675  };  // class Impl
1676
1677  const CallableStorageType callable_;
1678  const Matcher<ResultType> matcher_;
1679};
1680
1681// Explains the result of matching a value against a functor matcher.
1682template <typename T, typename Callable>
1683void ExplainMatchResultTo(const ResultOfMatcher<Callable>& matcher,
1684                          T obj, ::std::ostream* os) {
1685  matcher.ExplainMatchResultTo(obj, os);
1686}
1687
1688// Implements an equality matcher for any STL-style container whose elements
1689// support ==. This matcher is like Eq(), but its failure explanations provide
1690// more detailed information that is useful when the container is used as a set.
1691// The failure message reports elements that are in one of the operands but not
1692// the other. The failure messages do not report duplicate or out-of-order
1693// elements in the containers (which don't properly matter to sets, but can
1694// occur if the containers are vectors or lists, for example).
1695//
1696// Uses the container's const_iterator, value_type, operator ==,
1697// begin(), and end().
1698template <typename Container>
1699class ContainerEqMatcher {
1700 public:
1701  explicit ContainerEqMatcher(const Container& rhs) : rhs_(rhs) {}
1702  bool Matches(const Container& lhs) const { return lhs == rhs_; }
1703  void DescribeTo(::std::ostream* os) const {
1704    *os << "equals ";
1705    UniversalPrinter<Container>::Print(rhs_, os);
1706  }
1707  void DescribeNegationTo(::std::ostream* os) const {
1708    *os << "does not equal ";
1709    UniversalPrinter<Container>::Print(rhs_, os);
1710  }
1711
1712  void ExplainMatchResultTo(const Container& lhs,
1713                            ::std::ostream* os) const {
1714    // Something is different. Check for missing values first.
1715    bool printed_header = false;
1716    for (typename Container::const_iterator it = lhs.begin();
1717         it != lhs.end(); ++it) {
1718      if (std::find(rhs_.begin(), rhs_.end(), *it) == rhs_.end()) {
1719        if (printed_header) {
1720          *os << ", ";
1721        } else {
1722          *os << "Only in actual: ";
1723          printed_header = true;
1724        }
1725        UniversalPrinter<typename Container::value_type>::Print(*it, os);
1726      }
1727    }
1728
1729    // Now check for extra values.
1730    bool printed_header2 = false;
1731    for (typename Container::const_iterator it = rhs_.begin();
1732         it != rhs_.end(); ++it) {
1733      if (std::find(lhs.begin(), lhs.end(), *it) == lhs.end()) {
1734        if (printed_header2) {
1735          *os << ", ";
1736        } else {
1737          *os << (printed_header ? "; not" : "Not") << " in actual: ";
1738          printed_header2 = true;
1739        }
1740        UniversalPrinter<typename Container::value_type>::Print(*it, os);
1741      }
1742    }
1743  }
1744 private:
1745  const Container rhs_;
1746};
1747
1748template <typename Container>
1749void ExplainMatchResultTo(const ContainerEqMatcher<Container>& matcher,
1750                          const Container& lhs,
1751                          ::std::ostream* os) {
1752  matcher.ExplainMatchResultTo(lhs, os);
1753}
1754
1755}  // namespace internal
1756
1757// Implements MatcherCast().
1758template <typename T, typename M>
1759inline Matcher<T> MatcherCast(M matcher) {
1760  return internal::MatcherCastImpl<T, M>::Cast(matcher);
1761}
1762
1763// _ is a matcher that matches anything of any type.
1764//
1765// This definition is fine as:
1766//
1767//   1. The C++ standard permits using the name _ in a namespace that
1768//      is not the global namespace or ::std.
1769//   2. The AnythingMatcher class has no data member or constructor,
1770//      so it's OK to create global variables of this type.
1771//   3. c-style has approved of using _ in this case.
1772const internal::AnythingMatcher _ = {};
1773// Creates a matcher that matches any value of the given type T.
1774template <typename T>
1775inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
1776
1777// Creates a matcher that matches any value of the given type T.
1778template <typename T>
1779inline Matcher<T> An() { return A<T>(); }
1780
1781// Creates a polymorphic matcher that matches anything equal to x.
1782// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
1783// wouldn't compile.
1784template <typename T>
1785inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
1786
1787// Constructs a Matcher<T> from a 'value' of type T.  The constructed
1788// matcher matches any value that's equal to 'value'.
1789template <typename T>
1790Matcher<T>::Matcher(T value) { *this = Eq(value); }
1791
1792// Creates a monomorphic matcher that matches anything with type Lhs
1793// and equal to rhs.  A user may need to use this instead of Eq(...)
1794// in order to resolve an overloading ambiguity.
1795//
1796// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
1797// or Matcher<T>(x), but more readable than the latter.
1798//
1799// We could define similar monomorphic matchers for other comparison
1800// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
1801// it yet as those are used much less than Eq() in practice.  A user
1802// can always write Matcher<T>(Lt(5)) to be explicit about the type,
1803// for example.
1804template <typename Lhs, typename Rhs>
1805inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
1806
1807// Creates a polymorphic matcher that matches anything >= x.
1808template <typename Rhs>
1809inline internal::GeMatcher<Rhs> Ge(Rhs x) {
1810  return internal::GeMatcher<Rhs>(x);
1811}
1812
1813// Creates a polymorphic matcher that matches anything > x.
1814template <typename Rhs>
1815inline internal::GtMatcher<Rhs> Gt(Rhs x) {
1816  return internal::GtMatcher<Rhs>(x);
1817}
1818
1819// Creates a polymorphic matcher that matches anything <= x.
1820template <typename Rhs>
1821inline internal::LeMatcher<Rhs> Le(Rhs x) {
1822  return internal::LeMatcher<Rhs>(x);
1823}
1824
1825// Creates a polymorphic matcher that matches anything < x.
1826template <typename Rhs>
1827inline internal::LtMatcher<Rhs> Lt(Rhs x) {
1828  return internal::LtMatcher<Rhs>(x);
1829}
1830
1831// Creates a polymorphic matcher that matches anything != x.
1832template <typename Rhs>
1833inline internal::NeMatcher<Rhs> Ne(Rhs x) {
1834  return internal::NeMatcher<Rhs>(x);
1835}
1836
1837// Creates a polymorphic matcher that matches any non-NULL pointer.
1838// This is convenient as Not(NULL) doesn't compile (the compiler
1839// thinks that that expression is comparing a pointer with an integer).
1840inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
1841  return MakePolymorphicMatcher(internal::NotNullMatcher());
1842}
1843
1844// Creates a polymorphic matcher that matches any argument that
1845// references variable x.
1846template <typename T>
1847inline internal::RefMatcher<T&> Ref(T& x) {  // NOLINT
1848  return internal::RefMatcher<T&>(x);
1849}
1850
1851// Creates a matcher that matches any double argument approximately
1852// equal to rhs, where two NANs are considered unequal.
1853inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
1854  return internal::FloatingEqMatcher<double>(rhs, false);
1855}
1856
1857// Creates a matcher that matches any double argument approximately
1858// equal to rhs, including NaN values when rhs is NaN.
1859inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
1860  return internal::FloatingEqMatcher<double>(rhs, true);
1861}
1862
1863// Creates a matcher that matches any float argument approximately
1864// equal to rhs, where two NANs are considered unequal.
1865inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
1866  return internal::FloatingEqMatcher<float>(rhs, false);
1867}
1868
1869// Creates a matcher that matches any double argument approximately
1870// equal to rhs, including NaN values when rhs is NaN.
1871inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
1872  return internal::FloatingEqMatcher<float>(rhs, true);
1873}
1874
1875// Creates a matcher that matches a pointer (raw or smart) that points
1876// to a value that matches inner_matcher.
1877template <typename InnerMatcher>
1878inline internal::PointeeMatcher<InnerMatcher> Pointee(
1879    const InnerMatcher& inner_matcher) {
1880  return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
1881}
1882
1883// Creates a matcher that matches an object whose given field matches
1884// 'matcher'.  For example,
1885//   Field(&Foo::number, Ge(5))
1886// matches a Foo object x iff x.number >= 5.
1887template <typename Class, typename FieldType, typename FieldMatcher>
1888inline PolymorphicMatcher<
1889  internal::FieldMatcher<Class, FieldType> > Field(
1890    FieldType Class::*field, const FieldMatcher& matcher) {
1891  return MakePolymorphicMatcher(
1892      internal::FieldMatcher<Class, FieldType>(
1893          field, MatcherCast<const FieldType&>(matcher)));
1894  // The call to MatcherCast() is required for supporting inner
1895  // matchers of compatible types.  For example, it allows
1896  //   Field(&Foo::bar, m)
1897  // to compile where bar is an int32 and m is a matcher for int64.
1898}
1899
1900// Creates a matcher that matches an object whose given property
1901// matches 'matcher'.  For example,
1902//   Property(&Foo::str, StartsWith("hi"))
1903// matches a Foo object x iff x.str() starts with "hi".
1904template <typename Class, typename PropertyType, typename PropertyMatcher>
1905inline PolymorphicMatcher<
1906  internal::PropertyMatcher<Class, PropertyType> > Property(
1907    PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
1908  return MakePolymorphicMatcher(
1909      internal::PropertyMatcher<Class, PropertyType>(
1910          property,
1911          MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
1912  // The call to MatcherCast() is required for supporting inner
1913  // matchers of compatible types.  For example, it allows
1914  //   Property(&Foo::bar, m)
1915  // to compile where bar() returns an int32 and m is a matcher for int64.
1916}
1917
1918// Creates a matcher that matches an object iff the result of applying
1919// a callable to x matches 'matcher'.
1920// For example,
1921//   ResultOf(f, StartsWith("hi"))
1922// matches a Foo object x iff f(x) starts with "hi".
1923// callable parameter can be a function, function pointer, or a functor.
1924// Callable has to satisfy the following conditions:
1925//   * It is required to keep no state affecting the results of
1926//     the calls on it and make no assumptions about how many calls
1927//     will be made. Any state it keeps must be protected from the
1928//     concurrent access.
1929//   * If it is a function object, it has to define type result_type.
1930//     We recommend deriving your functor classes from std::unary_function.
1931template <typename Callable, typename ResultOfMatcher>
1932internal::ResultOfMatcher<Callable> ResultOf(
1933    Callable callable, const ResultOfMatcher& matcher) {
1934  return internal::ResultOfMatcher<Callable>(
1935          callable,
1936          MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
1937              matcher));
1938  // The call to MatcherCast() is required for supporting inner
1939  // matchers of compatible types.  For example, it allows
1940  //   ResultOf(Function, m)
1941  // to compile where Function() returns an int32 and m is a matcher for int64.
1942}
1943
1944// String matchers.
1945
1946// Matches a string equal to str.
1947inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
1948    StrEq(const internal::string& str) {
1949  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
1950      str, true, true));
1951}
1952
1953// Matches a string not equal to str.
1954inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
1955    StrNe(const internal::string& str) {
1956  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
1957      str, false, true));
1958}
1959
1960// Matches a string equal to str, ignoring case.
1961inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
1962    StrCaseEq(const internal::string& str) {
1963  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
1964      str, true, false));
1965}
1966
1967// Matches a string not equal to str, ignoring case.
1968inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
1969    StrCaseNe(const internal::string& str) {
1970  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
1971      str, false, false));
1972}
1973
1974// Creates a matcher that matches any string, std::string, or C string
1975// that contains the given substring.
1976inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
1977    HasSubstr(const internal::string& substring) {
1978  return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
1979      substring));
1980}
1981
1982// Matches a string that starts with 'prefix' (case-sensitive).
1983inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
1984    StartsWith(const internal::string& prefix) {
1985  return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
1986      prefix));
1987}
1988
1989// Matches a string that ends with 'suffix' (case-sensitive).
1990inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
1991    EndsWith(const internal::string& suffix) {
1992  return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
1993      suffix));
1994}
1995
1996#ifdef GMOCK_HAS_REGEX
1997
1998// Matches a string that fully matches regular expression 'regex'.
1999// The matcher takes ownership of 'regex'.
2000inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2001    const internal::RE* regex) {
2002  return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2003}
2004inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2005    const internal::string& regex) {
2006  return MatchesRegex(new internal::RE(regex));
2007}
2008
2009// Matches a string that contains regular expression 'regex'.
2010// The matcher takes ownership of 'regex'.
2011inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2012    const internal::RE* regex) {
2013  return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2014}
2015inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2016    const internal::string& regex) {
2017  return ContainsRegex(new internal::RE(regex));
2018}
2019
2020#endif  // GMOCK_HAS_REGEX
2021
2022#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2023// Wide string matchers.
2024
2025// Matches a string equal to str.
2026inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2027    StrEq(const internal::wstring& str) {
2028  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2029      str, true, true));
2030}
2031
2032// Matches a string not equal to str.
2033inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2034    StrNe(const internal::wstring& str) {
2035  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2036      str, false, true));
2037}
2038
2039// Matches a string equal to str, ignoring case.
2040inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2041    StrCaseEq(const internal::wstring& str) {
2042  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2043      str, true, false));
2044}
2045
2046// Matches a string not equal to str, ignoring case.
2047inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2048    StrCaseNe(const internal::wstring& str) {
2049  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2050      str, false, false));
2051}
2052
2053// Creates a matcher that matches any wstring, std::wstring, or C wide string
2054// that contains the given substring.
2055inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2056    HasSubstr(const internal::wstring& substring) {
2057  return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2058      substring));
2059}
2060
2061// Matches a string that starts with 'prefix' (case-sensitive).
2062inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2063    StartsWith(const internal::wstring& prefix) {
2064  return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2065      prefix));
2066}
2067
2068// Matches a string that ends with 'suffix' (case-sensitive).
2069inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2070    EndsWith(const internal::wstring& suffix) {
2071  return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2072      suffix));
2073}
2074
2075#endif  // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2076
2077// Creates a polymorphic matcher that matches a 2-tuple where the
2078// first field == the second field.
2079inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2080
2081// Creates a polymorphic matcher that matches a 2-tuple where the
2082// first field >= the second field.
2083inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2084
2085// Creates a polymorphic matcher that matches a 2-tuple where the
2086// first field > the second field.
2087inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2088
2089// Creates a polymorphic matcher that matches a 2-tuple where the
2090// first field <= the second field.
2091inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2092
2093// Creates a polymorphic matcher that matches a 2-tuple where the
2094// first field < the second field.
2095inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2096
2097// Creates a polymorphic matcher that matches a 2-tuple where the
2098// first field != the second field.
2099inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2100
2101// Creates a matcher that matches any value of type T that m doesn't
2102// match.
2103template <typename InnerMatcher>
2104inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2105  return internal::NotMatcher<InnerMatcher>(m);
2106}
2107
2108// Creates a matcher that matches any value that matches all of the
2109// given matchers.
2110//
2111// For now we only support up to 5 matchers.  Support for more
2112// matchers can be added as needed, or the user can use nested
2113// AllOf()s.
2114template <typename Matcher1, typename Matcher2>
2115inline internal::BothOfMatcher<Matcher1, Matcher2>
2116AllOf(Matcher1 m1, Matcher2 m2) {
2117  return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2118}
2119
2120template <typename Matcher1, typename Matcher2, typename Matcher3>
2121inline internal::BothOfMatcher<Matcher1,
2122           internal::BothOfMatcher<Matcher2, Matcher3> >
2123AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2124  return AllOf(m1, AllOf(m2, m3));
2125}
2126
2127template <typename Matcher1, typename Matcher2, typename Matcher3,
2128          typename Matcher4>
2129inline internal::BothOfMatcher<Matcher1,
2130           internal::BothOfMatcher<Matcher2,
2131               internal::BothOfMatcher<Matcher3, Matcher4> > >
2132AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2133  return AllOf(m1, AllOf(m2, m3, m4));
2134}
2135
2136template <typename Matcher1, typename Matcher2, typename Matcher3,
2137          typename Matcher4, typename Matcher5>
2138inline internal::BothOfMatcher<Matcher1,
2139           internal::BothOfMatcher<Matcher2,
2140               internal::BothOfMatcher<Matcher3,
2141                   internal::BothOfMatcher<Matcher4, Matcher5> > > >
2142AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2143  return AllOf(m1, AllOf(m2, m3, m4, m5));
2144}
2145
2146// Creates a matcher that matches any value that matches at least one
2147// of the given matchers.
2148//
2149// For now we only support up to 5 matchers.  Support for more
2150// matchers can be added as needed, or the user can use nested
2151// AnyOf()s.
2152template <typename Matcher1, typename Matcher2>
2153inline internal::EitherOfMatcher<Matcher1, Matcher2>
2154AnyOf(Matcher1 m1, Matcher2 m2) {
2155  return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2156}
2157
2158template <typename Matcher1, typename Matcher2, typename Matcher3>
2159inline internal::EitherOfMatcher<Matcher1,
2160           internal::EitherOfMatcher<Matcher2, Matcher3> >
2161AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2162  return AnyOf(m1, AnyOf(m2, m3));
2163}
2164
2165template <typename Matcher1, typename Matcher2, typename Matcher3,
2166          typename Matcher4>
2167inline internal::EitherOfMatcher<Matcher1,
2168           internal::EitherOfMatcher<Matcher2,
2169               internal::EitherOfMatcher<Matcher3, Matcher4> > >
2170AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2171  return AnyOf(m1, AnyOf(m2, m3, m4));
2172}
2173
2174template <typename Matcher1, typename Matcher2, typename Matcher3,
2175          typename Matcher4, typename Matcher5>
2176inline internal::EitherOfMatcher<Matcher1,
2177           internal::EitherOfMatcher<Matcher2,
2178               internal::EitherOfMatcher<Matcher3,
2179                   internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2180AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2181  return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2182}
2183
2184// Returns a matcher that matches anything that satisfies the given
2185// predicate.  The predicate can be any unary function or functor
2186// whose return type can be implicitly converted to bool.
2187template <typename Predicate>
2188inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2189Truly(Predicate pred) {
2190  return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2191}
2192
2193// Returns a matcher that matches an equal container.
2194// This matcher behaves like Eq(), but in the event of mismatch lists the
2195// values that are included in one container but not the other. (Duplicate
2196// values and order differences are not explained.)
2197template <typename Container>
2198inline PolymorphicMatcher<internal::ContainerEqMatcher<Container> >
2199    ContainerEq(const Container& rhs) {
2200  return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));
2201}
2202
2203// Returns a predicate that is satisfied by anything that matches the
2204// given matcher.
2205template <typename M>
2206inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2207  return internal::MatcherAsPredicate<M>(matcher);
2208}
2209
2210// These macros allow using matchers to check values in Google Test
2211// tests.  ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2212// succeed iff the value matches the matcher.  If the assertion fails,
2213// the value and the description of the matcher will be printed.
2214#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2215    ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2216#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2217    ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2218
2219}  // namespace testing
2220
2221#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
2222