Home | History | Annotate | Download | only in gmock
      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 (at) 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 <limits>
     43 #include <ostream>  // NOLINT
     44 #include <sstream>
     45 #include <string>
     46 #include <utility>
     47 #include <vector>
     48 
     49 #include "gmock/internal/gmock-internal-utils.h"
     50 #include "gmock/internal/gmock-port.h"
     51 #include "gtest/gtest.h"
     52 
     53 namespace testing {
     54 
     55 // To implement a matcher Foo for type T, define:
     56 //   1. a class FooMatcherImpl that implements the
     57 //      MatcherInterface<T> interface, and
     58 //   2. a factory function that creates a Matcher<T> object from a
     59 //      FooMatcherImpl*.
     60 //
     61 // The two-level delegation design makes it possible to allow a user
     62 // to write "v" instead of "Eq(v)" where a Matcher is expected, which
     63 // is impossible if we pass matchers by pointers.  It also eases
     64 // ownership management as Matcher objects can now be copied like
     65 // plain values.
     66 
     67 // MatchResultListener is an abstract class.  Its << operator can be
     68 // used by a matcher to explain why a value matches or doesn't match.
     69 //
     70 // TODO(wan (at) google.com): add method
     71 //   bool InterestedInWhy(bool result) const;
     72 // to indicate whether the listener is interested in why the match
     73 // result is 'result'.
     74 class MatchResultListener {
     75  public:
     76   // Creates a listener object with the given underlying ostream.  The
     77   // listener does not own the ostream.
     78   explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
     79   virtual ~MatchResultListener() = 0;  // Makes this class abstract.
     80 
     81   // Streams x to the underlying ostream; does nothing if the ostream
     82   // is NULL.
     83   template <typename T>
     84   MatchResultListener& operator<<(const T& x) {
     85     if (stream_ != NULL)
     86       *stream_ << x;
     87     return *this;
     88   }
     89 
     90   // Returns the underlying ostream.
     91   ::std::ostream* stream() { return stream_; }
     92 
     93   // Returns true iff the listener is interested in an explanation of
     94   // the match result.  A matcher's MatchAndExplain() method can use
     95   // this information to avoid generating the explanation when no one
     96   // intends to hear it.
     97   bool IsInterested() const { return stream_ != NULL; }
     98 
     99  private:
    100   ::std::ostream* const stream_;
    101 
    102   GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
    103 };
    104 
    105 inline MatchResultListener::~MatchResultListener() {
    106 }
    107 
    108 // The implementation of a matcher.
    109 template <typename T>
    110 class MatcherInterface {
    111  public:
    112   virtual ~MatcherInterface() {}
    113 
    114   // Returns true iff the matcher matches x; also explains the match
    115   // result to 'listener', in the form of a non-restrictive relative
    116   // clause ("which ...", "whose ...", etc) that describes x.  For
    117   // example, the MatchAndExplain() method of the Pointee(...) matcher
    118   // should generate an explanation like "which points to ...".
    119   //
    120   // You should override this method when defining a new matcher.
    121   //
    122   // It's the responsibility of the caller (Google Mock) to guarantee
    123   // that 'listener' is not NULL.  This helps to simplify a matcher's
    124   // implementation when it doesn't care about the performance, as it
    125   // can talk to 'listener' without checking its validity first.
    126   // However, in order to implement dummy listeners efficiently,
    127   // listener->stream() may be NULL.
    128   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
    129 
    130   // Describes this matcher to an ostream.  The function should print
    131   // a verb phrase that describes the property a value matching this
    132   // matcher should have.  The subject of the verb phrase is the value
    133   // being matched.  For example, the DescribeTo() method of the Gt(7)
    134   // matcher prints "is greater than 7".
    135   virtual void DescribeTo(::std::ostream* os) const = 0;
    136 
    137   // Describes the negation of this matcher to an ostream.  For
    138   // example, if the description of this matcher is "is greater than
    139   // 7", the negated description could be "is not greater than 7".
    140   // You are not required to override this when implementing
    141   // MatcherInterface, but it is highly advised so that your matcher
    142   // can produce good error messages.
    143   virtual void DescribeNegationTo(::std::ostream* os) const {
    144     *os << "not (";
    145     DescribeTo(os);
    146     *os << ")";
    147   }
    148 };
    149 
    150 namespace internal {
    151 
    152 // A match result listener that ignores the explanation.
    153 class DummyMatchResultListener : public MatchResultListener {
    154  public:
    155   DummyMatchResultListener() : MatchResultListener(NULL) {}
    156 
    157  private:
    158   GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
    159 };
    160 
    161 // A match result listener that forwards the explanation to a given
    162 // ostream.  The difference between this and MatchResultListener is
    163 // that the former is concrete.
    164 class StreamMatchResultListener : public MatchResultListener {
    165  public:
    166   explicit StreamMatchResultListener(::std::ostream* os)
    167       : MatchResultListener(os) {}
    168 
    169  private:
    170   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
    171 };
    172 
    173 // A match result listener that stores the explanation in a string.
    174 class StringMatchResultListener : public MatchResultListener {
    175  public:
    176   StringMatchResultListener() : MatchResultListener(&ss_) {}
    177 
    178   // Returns the explanation heard so far.
    179   internal::string str() const { return ss_.str(); }
    180 
    181  private:
    182   ::std::stringstream ss_;
    183 
    184   GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
    185 };
    186 
    187 // An internal class for implementing Matcher<T>, which will derive
    188 // from it.  We put functionalities common to all Matcher<T>
    189 // specializations here to avoid code duplication.
    190 template <typename T>
    191 class MatcherBase {
    192  public:
    193   // Returns true iff the matcher matches x; also explains the match
    194   // result to 'listener'.
    195   bool MatchAndExplain(T x, MatchResultListener* listener) const {
    196     return impl_->MatchAndExplain(x, listener);
    197   }
    198 
    199   // Returns true iff this matcher matches x.
    200   bool Matches(T x) const {
    201     DummyMatchResultListener dummy;
    202     return MatchAndExplain(x, &dummy);
    203   }
    204 
    205   // Describes this matcher to an ostream.
    206   void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
    207 
    208   // Describes the negation of this matcher to an ostream.
    209   void DescribeNegationTo(::std::ostream* os) const {
    210     impl_->DescribeNegationTo(os);
    211   }
    212 
    213   // Explains why x matches, or doesn't match, the matcher.
    214   void ExplainMatchResultTo(T x, ::std::ostream* os) const {
    215     StreamMatchResultListener listener(os);
    216     MatchAndExplain(x, &listener);
    217   }
    218 
    219  protected:
    220   MatcherBase() {}
    221 
    222   // Constructs a matcher from its implementation.
    223   explicit MatcherBase(const MatcherInterface<T>* impl)
    224       : impl_(impl) {}
    225 
    226   virtual ~MatcherBase() {}
    227 
    228  private:
    229   // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
    230   // interfaces.  The former dynamically allocates a chunk of memory
    231   // to hold the reference count, while the latter tracks all
    232   // references using a circular linked list without allocating
    233   // memory.  It has been observed that linked_ptr performs better in
    234   // typical scenarios.  However, shared_ptr can out-perform
    235   // linked_ptr when there are many more uses of the copy constructor
    236   // than the default constructor.
    237   //
    238   // If performance becomes a problem, we should see if using
    239   // shared_ptr helps.
    240   ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
    241 };
    242 
    243 }  // namespace internal
    244 
    245 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
    246 // object that can check whether a value of type T matches.  The
    247 // implementation of Matcher<T> is just a linked_ptr to const
    248 // MatcherInterface<T>, so copying is fairly cheap.  Don't inherit
    249 // from Matcher!
    250 template <typename T>
    251 class Matcher : public internal::MatcherBase<T> {
    252  public:
    253   // Constructs a null matcher.  Needed for storing Matcher objects in STL
    254   // containers.  A default-constructed matcher is not yet initialized.  You
    255   // cannot use it until a valid value has been assigned to it.
    256   Matcher() {}
    257 
    258   // Constructs a matcher from its implementation.
    259   explicit Matcher(const MatcherInterface<T>* impl)
    260       : internal::MatcherBase<T>(impl) {}
    261 
    262   // Implicit constructor here allows people to write
    263   // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
    264   Matcher(T value);  // NOLINT
    265 };
    266 
    267 // The following two specializations allow the user to write str
    268 // instead of Eq(str) and "foo" instead of Eq("foo") when a string
    269 // matcher is expected.
    270 template <>
    271 class Matcher<const internal::string&>
    272     : public internal::MatcherBase<const internal::string&> {
    273  public:
    274   Matcher() {}
    275 
    276   explicit Matcher(const MatcherInterface<const internal::string&>* impl)
    277       : internal::MatcherBase<const internal::string&>(impl) {}
    278 
    279   // Allows the user to write str instead of Eq(str) sometimes, where
    280   // str is a string object.
    281   Matcher(const internal::string& s);  // NOLINT
    282 
    283   // Allows the user to write "foo" instead of Eq("foo") sometimes.
    284   Matcher(const char* s);  // NOLINT
    285 };
    286 
    287 template <>
    288 class Matcher<internal::string>
    289     : public internal::MatcherBase<internal::string> {
    290  public:
    291   Matcher() {}
    292 
    293   explicit Matcher(const MatcherInterface<internal::string>* impl)
    294       : internal::MatcherBase<internal::string>(impl) {}
    295 
    296   // Allows the user to write str instead of Eq(str) sometimes, where
    297   // str is a string object.
    298   Matcher(const internal::string& s);  // NOLINT
    299 
    300   // Allows the user to write "foo" instead of Eq("foo") sometimes.
    301   Matcher(const char* s);  // NOLINT
    302 };
    303 
    304 // The PolymorphicMatcher class template makes it easy to implement a
    305 // polymorphic matcher (i.e. a matcher that can match values of more
    306 // than one type, e.g. Eq(n) and NotNull()).
    307 //
    308 // To define a polymorphic matcher, a user should provide an Impl
    309 // class that has a DescribeTo() method and a DescribeNegationTo()
    310 // method, and define a member function (or member function template)
    311 //
    312 //   bool MatchAndExplain(const Value& value,
    313 //                        MatchResultListener* listener) const;
    314 //
    315 // See the definition of NotNull() for a complete example.
    316 template <class Impl>
    317 class PolymorphicMatcher {
    318  public:
    319   explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
    320 
    321   // Returns a mutable reference to the underlying matcher
    322   // implementation object.
    323   Impl& mutable_impl() { return impl_; }
    324 
    325   // Returns an immutable reference to the underlying matcher
    326   // implementation object.
    327   const Impl& impl() const { return impl_; }
    328 
    329   template <typename T>
    330   operator Matcher<T>() const {
    331     return Matcher<T>(new MonomorphicImpl<T>(impl_));
    332   }
    333 
    334  private:
    335   template <typename T>
    336   class MonomorphicImpl : public MatcherInterface<T> {
    337    public:
    338     explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
    339 
    340     virtual void DescribeTo(::std::ostream* os) const {
    341       impl_.DescribeTo(os);
    342     }
    343 
    344     virtual void DescribeNegationTo(::std::ostream* os) const {
    345       impl_.DescribeNegationTo(os);
    346     }
    347 
    348     virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
    349       return impl_.MatchAndExplain(x, listener);
    350     }
    351 
    352    private:
    353     const Impl impl_;
    354 
    355     GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
    356   };
    357 
    358   Impl impl_;
    359 
    360   GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
    361 };
    362 
    363 // Creates a matcher from its implementation.  This is easier to use
    364 // than the Matcher<T> constructor as it doesn't require you to
    365 // explicitly write the template argument, e.g.
    366 //
    367 //   MakeMatcher(foo);
    368 // vs
    369 //   Matcher<const string&>(foo);
    370 template <typename T>
    371 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
    372   return Matcher<T>(impl);
    373 };
    374 
    375 // Creates a polymorphic matcher from its implementation.  This is
    376 // easier to use than the PolymorphicMatcher<Impl> constructor as it
    377 // doesn't require you to explicitly write the template argument, e.g.
    378 //
    379 //   MakePolymorphicMatcher(foo);
    380 // vs
    381 //   PolymorphicMatcher<TypeOfFoo>(foo);
    382 template <class Impl>
    383 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
    384   return PolymorphicMatcher<Impl>(impl);
    385 }
    386 
    387 // In order to be safe and clear, casting between different matcher
    388 // types is done explicitly via MatcherCast<T>(m), which takes a
    389 // matcher m and returns a Matcher<T>.  It compiles only when T can be
    390 // statically converted to the argument type of m.
    391 template <typename T, typename M>
    392 Matcher<T> MatcherCast(M m);
    393 
    394 // Implements SafeMatcherCast().
    395 //
    396 // We use an intermediate class to do the actual safe casting as Nokia's
    397 // Symbian compiler cannot decide between
    398 // template <T, M> ... (M) and
    399 // template <T, U> ... (const Matcher<U>&)
    400 // for function templates but can for member function templates.
    401 template <typename T>
    402 class SafeMatcherCastImpl {
    403  public:
    404   // This overload handles polymorphic matchers only since monomorphic
    405   // matchers are handled by the next one.
    406   template <typename M>
    407   static inline Matcher<T> Cast(M polymorphic_matcher) {
    408     return Matcher<T>(polymorphic_matcher);
    409   }
    410 
    411   // This overload handles monomorphic matchers.
    412   //
    413   // In general, if type T can be implicitly converted to type U, we can
    414   // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
    415   // contravariant): just keep a copy of the original Matcher<U>, convert the
    416   // argument from type T to U, and then pass it to the underlying Matcher<U>.
    417   // The only exception is when U is a reference and T is not, as the
    418   // underlying Matcher<U> may be interested in the argument's address, which
    419   // is not preserved in the conversion from T to U.
    420   template <typename U>
    421   static inline Matcher<T> Cast(const Matcher<U>& matcher) {
    422     // Enforce that T can be implicitly converted to U.
    423     GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
    424                           T_must_be_implicitly_convertible_to_U);
    425     // Enforce that we are not converting a non-reference type T to a reference
    426     // type U.
    427     GTEST_COMPILE_ASSERT_(
    428         internal::is_reference<T>::value || !internal::is_reference<U>::value,
    429         cannot_convert_non_referentce_arg_to_reference);
    430     // In case both T and U are arithmetic types, enforce that the
    431     // conversion is not lossy.
    432     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
    433     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
    434     const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
    435     const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
    436     GTEST_COMPILE_ASSERT_(
    437         kTIsOther || kUIsOther ||
    438         (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
    439         conversion_of_arithmetic_types_must_be_lossless);
    440     return MatcherCast<T>(matcher);
    441   }
    442 };
    443 
    444 template <typename T, typename M>
    445 inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
    446   return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
    447 }
    448 
    449 // A<T>() returns a matcher that matches any value of type T.
    450 template <typename T>
    451 Matcher<T> A();
    452 
    453 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
    454 // and MUST NOT BE USED IN USER CODE!!!
    455 namespace internal {
    456 
    457 // If the explanation is not empty, prints it to the ostream.
    458 inline void PrintIfNotEmpty(const internal::string& explanation,
    459                             std::ostream* os) {
    460   if (explanation != "" && os != NULL) {
    461     *os << ", " << explanation;
    462   }
    463 }
    464 
    465 // Returns true if the given type name is easy to read by a human.
    466 // This is used to decide whether printing the type of a value might
    467 // be helpful.
    468 inline bool IsReadableTypeName(const string& type_name) {
    469   // We consider a type name readable if it's short or doesn't contain
    470   // a template or function type.
    471   return (type_name.length() <= 20 ||
    472           type_name.find_first_of("<(") == string::npos);
    473 }
    474 
    475 // Matches the value against the given matcher, prints the value and explains
    476 // the match result to the listener. Returns the match result.
    477 // 'listener' must not be NULL.
    478 // Value cannot be passed by const reference, because some matchers take a
    479 // non-const argument.
    480 template <typename Value, typename T>
    481 bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
    482                           MatchResultListener* listener) {
    483   if (!listener->IsInterested()) {
    484     // If the listener is not interested, we do not need to construct the
    485     // inner explanation.
    486     return matcher.Matches(value);
    487   }
    488 
    489   StringMatchResultListener inner_listener;
    490   const bool match = matcher.MatchAndExplain(value, &inner_listener);
    491 
    492   UniversalPrint(value, listener->stream());
    493 #if GTEST_HAS_RTTI
    494   const string& type_name = GetTypeName<Value>();
    495   if (IsReadableTypeName(type_name))
    496     *listener->stream() << " (of type " << type_name << ")";
    497 #endif
    498   PrintIfNotEmpty(inner_listener.str(), listener->stream());
    499 
    500   return match;
    501 }
    502 
    503 // An internal helper class for doing compile-time loop on a tuple's
    504 // fields.
    505 template <size_t N>
    506 class TuplePrefix {
    507  public:
    508   // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
    509   // iff the first N fields of matcher_tuple matches the first N
    510   // fields of value_tuple, respectively.
    511   template <typename MatcherTuple, typename ValueTuple>
    512   static bool Matches(const MatcherTuple& matcher_tuple,
    513                       const ValueTuple& value_tuple) {
    514     using ::std::tr1::get;
    515     return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
    516         && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
    517   }
    518 
    519   // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
    520   // describes failures in matching the first N fields of matchers
    521   // against the first N fields of values.  If there is no failure,
    522   // nothing will be streamed to os.
    523   template <typename MatcherTuple, typename ValueTuple>
    524   static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
    525                                      const ValueTuple& values,
    526                                      ::std::ostream* os) {
    527     using ::std::tr1::tuple_element;
    528     using ::std::tr1::get;
    529 
    530     // First, describes failures in the first N - 1 fields.
    531     TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
    532 
    533     // Then describes the failure (if any) in the (N - 1)-th (0-based)
    534     // field.
    535     typename tuple_element<N - 1, MatcherTuple>::type matcher =
    536         get<N - 1>(matchers);
    537     typedef typename tuple_element<N - 1, ValueTuple>::type Value;
    538     Value value = get<N - 1>(values);
    539     StringMatchResultListener listener;
    540     if (!matcher.MatchAndExplain(value, &listener)) {
    541       // TODO(wan): include in the message the name of the parameter
    542       // as used in MOCK_METHOD*() when possible.
    543       *os << "  Expected arg #" << N - 1 << ": ";
    544       get<N - 1>(matchers).DescribeTo(os);
    545       *os << "\n           Actual: ";
    546       // We remove the reference in type Value to prevent the
    547       // universal printer from printing the address of value, which
    548       // isn't interesting to the user most of the time.  The
    549       // matcher's MatchAndExplain() method handles the case when
    550       // the address is interesting.
    551       internal::UniversalPrint(value, os);
    552       PrintIfNotEmpty(listener.str(), os);
    553       *os << "\n";
    554     }
    555   }
    556 };
    557 
    558 // The base case.
    559 template <>
    560 class TuplePrefix<0> {
    561  public:
    562   template <typename MatcherTuple, typename ValueTuple>
    563   static bool Matches(const MatcherTuple& /* matcher_tuple */,
    564                       const ValueTuple& /* value_tuple */) {
    565     return true;
    566   }
    567 
    568   template <typename MatcherTuple, typename ValueTuple>
    569   static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
    570                                      const ValueTuple& /* values */,
    571                                      ::std::ostream* /* os */) {}
    572 };
    573 
    574 // TupleMatches(matcher_tuple, value_tuple) returns true iff all
    575 // matchers in matcher_tuple match the corresponding fields in
    576 // value_tuple.  It is a compiler error if matcher_tuple and
    577 // value_tuple have different number of fields or incompatible field
    578 // types.
    579 template <typename MatcherTuple, typename ValueTuple>
    580 bool TupleMatches(const MatcherTuple& matcher_tuple,
    581                   const ValueTuple& value_tuple) {
    582   using ::std::tr1::tuple_size;
    583   // Makes sure that matcher_tuple and value_tuple have the same
    584   // number of fields.
    585   GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
    586                         tuple_size<ValueTuple>::value,
    587                         matcher_and_value_have_different_numbers_of_fields);
    588   return TuplePrefix<tuple_size<ValueTuple>::value>::
    589       Matches(matcher_tuple, value_tuple);
    590 }
    591 
    592 // Describes failures in matching matchers against values.  If there
    593 // is no failure, nothing will be streamed to os.
    594 template <typename MatcherTuple, typename ValueTuple>
    595 void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
    596                                 const ValueTuple& values,
    597                                 ::std::ostream* os) {
    598   using ::std::tr1::tuple_size;
    599   TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
    600       matchers, values, os);
    601 }
    602 
    603 // The MatcherCastImpl class template is a helper for implementing
    604 // MatcherCast().  We need this helper in order to partially
    605 // specialize the implementation of MatcherCast() (C++ allows
    606 // class/struct templates to be partially specialized, but not
    607 // function templates.).
    608 
    609 // This general version is used when MatcherCast()'s argument is a
    610 // polymorphic matcher (i.e. something that can be converted to a
    611 // Matcher but is not one yet; for example, Eq(value)).
    612 template <typename T, typename M>
    613 class MatcherCastImpl {
    614  public:
    615   static Matcher<T> Cast(M polymorphic_matcher) {
    616     return Matcher<T>(polymorphic_matcher);
    617   }
    618 };
    619 
    620 // This more specialized version is used when MatcherCast()'s argument
    621 // is already a Matcher.  This only compiles when type T can be
    622 // statically converted to type U.
    623 template <typename T, typename U>
    624 class MatcherCastImpl<T, Matcher<U> > {
    625  public:
    626   static Matcher<T> Cast(const Matcher<U>& source_matcher) {
    627     return Matcher<T>(new Impl(source_matcher));
    628   }
    629 
    630  private:
    631   class Impl : public MatcherInterface<T> {
    632    public:
    633     explicit Impl(const Matcher<U>& source_matcher)
    634         : source_matcher_(source_matcher) {}
    635 
    636     // We delegate the matching logic to the source matcher.
    637     virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
    638       return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
    639     }
    640 
    641     virtual void DescribeTo(::std::ostream* os) const {
    642       source_matcher_.DescribeTo(os);
    643     }
    644 
    645     virtual void DescribeNegationTo(::std::ostream* os) const {
    646       source_matcher_.DescribeNegationTo(os);
    647     }
    648 
    649    private:
    650     const Matcher<U> source_matcher_;
    651 
    652     GTEST_DISALLOW_ASSIGN_(Impl);
    653   };
    654 };
    655 
    656 // This even more specialized version is used for efficiently casting
    657 // a matcher to its own type.
    658 template <typename T>
    659 class MatcherCastImpl<T, Matcher<T> > {
    660  public:
    661   static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
    662 };
    663 
    664 // Implements A<T>().
    665 template <typename T>
    666 class AnyMatcherImpl : public MatcherInterface<T> {
    667  public:
    668   virtual bool MatchAndExplain(
    669       T /* x */, MatchResultListener* /* listener */) const { return true; }
    670   virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
    671   virtual void DescribeNegationTo(::std::ostream* os) const {
    672     // This is mostly for completeness' safe, as it's not very useful
    673     // to write Not(A<bool>()).  However we cannot completely rule out
    674     // such a possibility, and it doesn't hurt to be prepared.
    675     *os << "never matches";
    676   }
    677 };
    678 
    679 // Implements _, a matcher that matches any value of any
    680 // type.  This is a polymorphic matcher, so we need a template type
    681 // conversion operator to make it appearing as a Matcher<T> for any
    682 // type T.
    683 class AnythingMatcher {
    684  public:
    685   template <typename T>
    686   operator Matcher<T>() const { return A<T>(); }
    687 };
    688 
    689 // Implements a matcher that compares a given value with a
    690 // pre-supplied value using one of the ==, <=, <, etc, operators.  The
    691 // two values being compared don't have to have the same type.
    692 //
    693 // The matcher defined here is polymorphic (for example, Eq(5) can be
    694 // used to match an int, a short, a double, etc).  Therefore we use
    695 // a template type conversion operator in the implementation.
    696 //
    697 // We define this as a macro in order to eliminate duplicated source
    698 // code.
    699 //
    700 // The following template definition assumes that the Rhs parameter is
    701 // a "bare" type (i.e. neither 'const T' nor 'T&').
    702 #define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
    703     name, op, relation, negated_relation) \
    704   template <typename Rhs> class name##Matcher { \
    705    public: \
    706     explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
    707     template <typename Lhs> \
    708     operator Matcher<Lhs>() const { \
    709       return MakeMatcher(new Impl<Lhs>(rhs_)); \
    710     } \
    711    private: \
    712     template <typename Lhs> \
    713     class Impl : public MatcherInterface<Lhs> { \
    714      public: \
    715       explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
    716       virtual bool MatchAndExplain(\
    717           Lhs lhs, MatchResultListener* /* listener */) const { \
    718         return lhs op rhs_; \
    719       } \
    720       virtual void DescribeTo(::std::ostream* os) const { \
    721         *os << relation  " "; \
    722         UniversalPrint(rhs_, os); \
    723       } \
    724       virtual void DescribeNegationTo(::std::ostream* os) const { \
    725         *os << negated_relation  " "; \
    726         UniversalPrint(rhs_, os); \
    727       } \
    728      private: \
    729       Rhs rhs_; \
    730       GTEST_DISALLOW_ASSIGN_(Impl); \
    731     }; \
    732     Rhs rhs_; \
    733     GTEST_DISALLOW_ASSIGN_(name##Matcher); \
    734   }
    735 
    736 // Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
    737 // respectively.
    738 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
    739 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
    740 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
    741 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
    742 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
    743 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
    744 
    745 #undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
    746 
    747 // Implements the polymorphic IsNull() matcher, which matches any raw or smart
    748 // pointer that is NULL.
    749 class IsNullMatcher {
    750  public:
    751   template <typename Pointer>
    752   bool MatchAndExplain(const Pointer& p,
    753                        MatchResultListener* /* listener */) const {
    754     return GetRawPointer(p) == NULL;
    755   }
    756 
    757   void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
    758   void DescribeNegationTo(::std::ostream* os) const {
    759     *os << "isn't NULL";
    760   }
    761 };
    762 
    763 // Implements the polymorphic NotNull() matcher, which matches any raw or smart
    764 // pointer that is not NULL.
    765 class NotNullMatcher {
    766  public:
    767   template <typename Pointer>
    768   bool MatchAndExplain(const Pointer& p,
    769                        MatchResultListener* /* listener */) const {
    770     return GetRawPointer(p) != NULL;
    771   }
    772 
    773   void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
    774   void DescribeNegationTo(::std::ostream* os) const {
    775     *os << "is NULL";
    776   }
    777 };
    778 
    779 // Ref(variable) matches any argument that is a reference to
    780 // 'variable'.  This matcher is polymorphic as it can match any
    781 // super type of the type of 'variable'.
    782 //
    783 // The RefMatcher template class implements Ref(variable).  It can
    784 // only be instantiated with a reference type.  This prevents a user
    785 // from mistakenly using Ref(x) to match a non-reference function
    786 // argument.  For example, the following will righteously cause a
    787 // compiler error:
    788 //
    789 //   int n;
    790 //   Matcher<int> m1 = Ref(n);   // This won't compile.
    791 //   Matcher<int&> m2 = Ref(n);  // This will compile.
    792 template <typename T>
    793 class RefMatcher;
    794 
    795 template <typename T>
    796 class RefMatcher<T&> {
    797   // Google Mock is a generic framework and thus needs to support
    798   // mocking any function types, including those that take non-const
    799   // reference arguments.  Therefore the template parameter T (and
    800   // Super below) can be instantiated to either a const type or a
    801   // non-const type.
    802  public:
    803   // RefMatcher() takes a T& instead of const T&, as we want the
    804   // compiler to catch using Ref(const_value) as a matcher for a
    805   // non-const reference.
    806   explicit RefMatcher(T& x) : object_(x) {}  // NOLINT
    807 
    808   template <typename Super>
    809   operator Matcher<Super&>() const {
    810     // By passing object_ (type T&) to Impl(), which expects a Super&,
    811     // we make sure that Super is a super type of T.  In particular,
    812     // this catches using Ref(const_value) as a matcher for a
    813     // non-const reference, as you cannot implicitly convert a const
    814     // reference to a non-const reference.
    815     return MakeMatcher(new Impl<Super>(object_));
    816   }
    817 
    818  private:
    819   template <typename Super>
    820   class Impl : public MatcherInterface<Super&> {
    821    public:
    822     explicit Impl(Super& x) : object_(x) {}  // NOLINT
    823 
    824     // MatchAndExplain() takes a Super& (as opposed to const Super&)
    825     // in order to match the interface MatcherInterface<Super&>.
    826     virtual bool MatchAndExplain(
    827         Super& x, MatchResultListener* listener) const {
    828       *listener << "which is located @" << static_cast<const void*>(&x);
    829       return &x == &object_;
    830     }
    831 
    832     virtual void DescribeTo(::std::ostream* os) const {
    833       *os << "references the variable ";
    834       UniversalPrinter<Super&>::Print(object_, os);
    835     }
    836 
    837     virtual void DescribeNegationTo(::std::ostream* os) const {
    838       *os << "does not reference the variable ";
    839       UniversalPrinter<Super&>::Print(object_, os);
    840     }
    841 
    842    private:
    843     const Super& object_;
    844 
    845     GTEST_DISALLOW_ASSIGN_(Impl);
    846   };
    847 
    848   T& object_;
    849 
    850   GTEST_DISALLOW_ASSIGN_(RefMatcher);
    851 };
    852 
    853 // Polymorphic helper functions for narrow and wide string matchers.
    854 inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
    855   return String::CaseInsensitiveCStringEquals(lhs, rhs);
    856 }
    857 
    858 inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
    859                                          const wchar_t* rhs) {
    860   return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
    861 }
    862 
    863 // String comparison for narrow or wide strings that can have embedded NUL
    864 // characters.
    865 template <typename StringType>
    866 bool CaseInsensitiveStringEquals(const StringType& s1,
    867                                  const StringType& s2) {
    868   // Are the heads equal?
    869   if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
    870     return false;
    871   }
    872 
    873   // Skip the equal heads.
    874   const typename StringType::value_type nul = 0;
    875   const size_t i1 = s1.find(nul), i2 = s2.find(nul);
    876 
    877   // Are we at the end of either s1 or s2?
    878   if (i1 == StringType::npos || i2 == StringType::npos) {
    879     return i1 == i2;
    880   }
    881 
    882   // Are the tails equal?
    883   return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
    884 }
    885 
    886 // String matchers.
    887 
    888 // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
    889 template <typename StringType>
    890 class StrEqualityMatcher {
    891  public:
    892   typedef typename StringType::const_pointer ConstCharPointer;
    893 
    894   StrEqualityMatcher(const StringType& str, bool expect_eq,
    895                      bool case_sensitive)
    896       : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
    897 
    898   // When expect_eq_ is true, returns true iff s is equal to string_;
    899   // otherwise returns true iff s is not equal to string_.
    900   bool MatchAndExplain(ConstCharPointer s,
    901                        MatchResultListener* listener) const {
    902     if (s == NULL) {
    903       return !expect_eq_;
    904     }
    905     return MatchAndExplain(StringType(s), listener);
    906   }
    907 
    908   bool MatchAndExplain(const StringType& s,
    909                        MatchResultListener* /* listener */) const {
    910     const bool eq = case_sensitive_ ? s == string_ :
    911         CaseInsensitiveStringEquals(s, string_);
    912     return expect_eq_ == eq;
    913   }
    914 
    915   void DescribeTo(::std::ostream* os) const {
    916     DescribeToHelper(expect_eq_, os);
    917   }
    918 
    919   void DescribeNegationTo(::std::ostream* os) const {
    920     DescribeToHelper(!expect_eq_, os);
    921   }
    922 
    923  private:
    924   void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
    925     *os << (expect_eq ? "is " : "isn't ");
    926     *os << "equal to ";
    927     if (!case_sensitive_) {
    928       *os << "(ignoring case) ";
    929     }
    930     UniversalPrint(string_, os);
    931   }
    932 
    933   const StringType string_;
    934   const bool expect_eq_;
    935   const bool case_sensitive_;
    936 
    937   GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
    938 };
    939 
    940 // Implements the polymorphic HasSubstr(substring) matcher, which
    941 // can be used as a Matcher<T> as long as T can be converted to a
    942 // string.
    943 template <typename StringType>
    944 class HasSubstrMatcher {
    945  public:
    946   typedef typename StringType::const_pointer ConstCharPointer;
    947 
    948   explicit HasSubstrMatcher(const StringType& substring)
    949       : substring_(substring) {}
    950 
    951   // These overloaded methods allow HasSubstr(substring) to be used as a
    952   // Matcher<T> as long as T can be converted to string.  Returns true
    953   // iff s contains substring_ as a substring.
    954   bool MatchAndExplain(ConstCharPointer s,
    955                        MatchResultListener* listener) const {
    956     return s != NULL && MatchAndExplain(StringType(s), listener);
    957   }
    958 
    959   bool MatchAndExplain(const StringType& s,
    960                        MatchResultListener* /* listener */) const {
    961     return s.find(substring_) != StringType::npos;
    962   }
    963 
    964   // Describes what this matcher matches.
    965   void DescribeTo(::std::ostream* os) const {
    966     *os << "has substring ";
    967     UniversalPrint(substring_, os);
    968   }
    969 
    970   void DescribeNegationTo(::std::ostream* os) const {
    971     *os << "has no substring ";
    972     UniversalPrint(substring_, os);
    973   }
    974 
    975  private:
    976   const StringType substring_;
    977 
    978   GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
    979 };
    980 
    981 // Implements the polymorphic StartsWith(substring) matcher, which
    982 // can be used as a Matcher<T> as long as T can be converted to a
    983 // string.
    984 template <typename StringType>
    985 class StartsWithMatcher {
    986  public:
    987   typedef typename StringType::const_pointer ConstCharPointer;
    988 
    989   explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
    990   }
    991 
    992   // These overloaded methods allow StartsWith(prefix) to be used as a
    993   // Matcher<T> as long as T can be converted to string.  Returns true
    994   // iff s starts with prefix_.
    995   bool MatchAndExplain(ConstCharPointer s,
    996                        MatchResultListener* listener) const {
    997     return s != NULL && MatchAndExplain(StringType(s), listener);
    998   }
    999 
   1000   bool MatchAndExplain(const StringType& s,
   1001                        MatchResultListener* /* listener */) const {
   1002     return s.length() >= prefix_.length() &&
   1003         s.substr(0, prefix_.length()) == prefix_;
   1004   }
   1005 
   1006   void DescribeTo(::std::ostream* os) const {
   1007     *os << "starts with ";
   1008     UniversalPrint(prefix_, os);
   1009   }
   1010 
   1011   void DescribeNegationTo(::std::ostream* os) const {
   1012     *os << "doesn't start with ";
   1013     UniversalPrint(prefix_, os);
   1014   }
   1015 
   1016  private:
   1017   const StringType prefix_;
   1018 
   1019   GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
   1020 };
   1021 
   1022 // Implements the polymorphic EndsWith(substring) matcher, which
   1023 // can be used as a Matcher<T> as long as T can be converted to a
   1024 // string.
   1025 template <typename StringType>
   1026 class EndsWithMatcher {
   1027  public:
   1028   typedef typename StringType::const_pointer ConstCharPointer;
   1029 
   1030   explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
   1031 
   1032   // These overloaded methods allow EndsWith(suffix) to be used as a
   1033   // Matcher<T> as long as T can be converted to string.  Returns true
   1034   // iff s ends with suffix_.
   1035   bool MatchAndExplain(ConstCharPointer s,
   1036                        MatchResultListener* listener) const {
   1037     return s != NULL && MatchAndExplain(StringType(s), listener);
   1038   }
   1039 
   1040   bool MatchAndExplain(const StringType& s,
   1041                        MatchResultListener* /* listener */) const {
   1042     return s.length() >= suffix_.length() &&
   1043         s.substr(s.length() - suffix_.length()) == suffix_;
   1044   }
   1045 
   1046   void DescribeTo(::std::ostream* os) const {
   1047     *os << "ends with ";
   1048     UniversalPrint(suffix_, os);
   1049   }
   1050 
   1051   void DescribeNegationTo(::std::ostream* os) const {
   1052     *os << "doesn't end with ";
   1053     UniversalPrint(suffix_, os);
   1054   }
   1055 
   1056  private:
   1057   const StringType suffix_;
   1058 
   1059   GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
   1060 };
   1061 
   1062 // Implements polymorphic matchers MatchesRegex(regex) and
   1063 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
   1064 // T can be converted to a string.
   1065 class MatchesRegexMatcher {
   1066  public:
   1067   MatchesRegexMatcher(const RE* regex, bool full_match)
   1068       : regex_(regex), full_match_(full_match) {}
   1069 
   1070   // These overloaded methods allow MatchesRegex(regex) to be used as
   1071   // a Matcher<T> as long as T can be converted to string.  Returns
   1072   // true iff s matches regular expression regex.  When full_match_ is
   1073   // true, a full match is done; otherwise a partial match is done.
   1074   bool MatchAndExplain(const char* s,
   1075                        MatchResultListener* listener) const {
   1076     return s != NULL && MatchAndExplain(internal::string(s), listener);
   1077   }
   1078 
   1079   bool MatchAndExplain(const internal::string& s,
   1080                        MatchResultListener* /* listener */) const {
   1081     return full_match_ ? RE::FullMatch(s, *regex_) :
   1082         RE::PartialMatch(s, *regex_);
   1083   }
   1084 
   1085   void DescribeTo(::std::ostream* os) const {
   1086     *os << (full_match_ ? "matches" : "contains")
   1087         << " regular expression ";
   1088     UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
   1089   }
   1090 
   1091   void DescribeNegationTo(::std::ostream* os) const {
   1092     *os << "doesn't " << (full_match_ ? "match" : "contain")
   1093         << " regular expression ";
   1094     UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
   1095   }
   1096 
   1097  private:
   1098   const internal::linked_ptr<const RE> regex_;
   1099   const bool full_match_;
   1100 
   1101   GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
   1102 };
   1103 
   1104 // Implements a matcher that compares the two fields of a 2-tuple
   1105 // using one of the ==, <=, <, etc, operators.  The two fields being
   1106 // compared don't have to have the same type.
   1107 //
   1108 // The matcher defined here is polymorphic (for example, Eq() can be
   1109 // used to match a tuple<int, short>, a tuple<const long&, double>,
   1110 // etc).  Therefore we use a template type conversion operator in the
   1111 // implementation.
   1112 //
   1113 // We define this as a macro in order to eliminate duplicated source
   1114 // code.
   1115 #define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
   1116   class name##2Matcher { \
   1117    public: \
   1118     template <typename T1, typename T2> \
   1119     operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
   1120       return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
   1121     } \
   1122     template <typename T1, typename T2> \
   1123     operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
   1124       return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
   1125     } \
   1126    private: \
   1127     template <typename Tuple> \
   1128     class Impl : public MatcherInterface<Tuple> { \
   1129      public: \
   1130       virtual bool MatchAndExplain( \
   1131           Tuple args, \
   1132           MatchResultListener* /* listener */) const { \
   1133         return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
   1134       } \
   1135       virtual void DescribeTo(::std::ostream* os) const { \
   1136         *os << "are " relation;                                 \
   1137       } \
   1138       virtual void DescribeNegationTo(::std::ostream* os) const { \
   1139         *os << "aren't " relation; \
   1140       } \
   1141     }; \
   1142   }
   1143 
   1144 // Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
   1145 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
   1146 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
   1147     Ge, >=, "a pair where the first >= the second");
   1148 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
   1149     Gt, >, "a pair where the first > the second");
   1150 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
   1151     Le, <=, "a pair where the first <= the second");
   1152 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
   1153     Lt, <, "a pair where the first < the second");
   1154 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
   1155 
   1156 #undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
   1157 
   1158 // Implements the Not(...) matcher for a particular argument type T.
   1159 // We do not nest it inside the NotMatcher class template, as that
   1160 // will prevent different instantiations of NotMatcher from sharing
   1161 // the same NotMatcherImpl<T> class.
   1162 template <typename T>
   1163 class NotMatcherImpl : public MatcherInterface<T> {
   1164  public:
   1165   explicit NotMatcherImpl(const Matcher<T>& matcher)
   1166       : matcher_(matcher) {}
   1167 
   1168   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
   1169     return !matcher_.MatchAndExplain(x, listener);
   1170   }
   1171 
   1172   virtual void DescribeTo(::std::ostream* os) const {
   1173     matcher_.DescribeNegationTo(os);
   1174   }
   1175 
   1176   virtual void DescribeNegationTo(::std::ostream* os) const {
   1177     matcher_.DescribeTo(os);
   1178   }
   1179 
   1180  private:
   1181   const Matcher<T> matcher_;
   1182 
   1183   GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
   1184 };
   1185 
   1186 // Implements the Not(m) matcher, which matches a value that doesn't
   1187 // match matcher m.
   1188 template <typename InnerMatcher>
   1189 class NotMatcher {
   1190  public:
   1191   explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
   1192 
   1193   // This template type conversion operator allows Not(m) to be used
   1194   // to match any type m can match.
   1195   template <typename T>
   1196   operator Matcher<T>() const {
   1197     return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
   1198   }
   1199 
   1200  private:
   1201   InnerMatcher matcher_;
   1202 
   1203   GTEST_DISALLOW_ASSIGN_(NotMatcher);
   1204 };
   1205 
   1206 // Implements the AllOf(m1, m2) matcher for a particular argument type
   1207 // T. We do not nest it inside the BothOfMatcher class template, as
   1208 // that will prevent different instantiations of BothOfMatcher from
   1209 // sharing the same BothOfMatcherImpl<T> class.
   1210 template <typename T>
   1211 class BothOfMatcherImpl : public MatcherInterface<T> {
   1212  public:
   1213   BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
   1214       : matcher1_(matcher1), matcher2_(matcher2) {}
   1215 
   1216   virtual void DescribeTo(::std::ostream* os) const {
   1217     *os << "(";
   1218     matcher1_.DescribeTo(os);
   1219     *os << ") and (";
   1220     matcher2_.DescribeTo(os);
   1221     *os << ")";
   1222   }
   1223 
   1224   virtual void DescribeNegationTo(::std::ostream* os) const {
   1225     *os << "(";
   1226     matcher1_.DescribeNegationTo(os);
   1227     *os << ") or (";
   1228     matcher2_.DescribeNegationTo(os);
   1229     *os << ")";
   1230   }
   1231 
   1232   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
   1233     // If either matcher1_ or matcher2_ doesn't match x, we only need
   1234     // to explain why one of them fails.
   1235     StringMatchResultListener listener1;
   1236     if (!matcher1_.MatchAndExplain(x, &listener1)) {
   1237       *listener << listener1.str();
   1238       return false;
   1239     }
   1240 
   1241     StringMatchResultListener listener2;
   1242     if (!matcher2_.MatchAndExplain(x, &listener2)) {
   1243       *listener << listener2.str();
   1244       return false;
   1245     }
   1246 
   1247     // Otherwise we need to explain why *both* of them match.
   1248     const internal::string s1 = listener1.str();
   1249     const internal::string s2 = listener2.str();
   1250 
   1251     if (s1 == "") {
   1252       *listener << s2;
   1253     } else {
   1254       *listener << s1;
   1255       if (s2 != "") {
   1256         *listener << ", and " << s2;
   1257       }
   1258     }
   1259     return true;
   1260   }
   1261 
   1262  private:
   1263   const Matcher<T> matcher1_;
   1264   const Matcher<T> matcher2_;
   1265 
   1266   GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
   1267 };
   1268 
   1269 // Used for implementing the AllOf(m_1, ..., m_n) matcher, which
   1270 // matches a value that matches all of the matchers m_1, ..., and m_n.
   1271 template <typename Matcher1, typename Matcher2>
   1272 class BothOfMatcher {
   1273  public:
   1274   BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
   1275       : matcher1_(matcher1), matcher2_(matcher2) {}
   1276 
   1277   // This template type conversion operator allows a
   1278   // BothOfMatcher<Matcher1, Matcher2> object to match any type that
   1279   // both Matcher1 and Matcher2 can match.
   1280   template <typename T>
   1281   operator Matcher<T>() const {
   1282     return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
   1283                                                SafeMatcherCast<T>(matcher2_)));
   1284   }
   1285 
   1286  private:
   1287   Matcher1 matcher1_;
   1288   Matcher2 matcher2_;
   1289 
   1290   GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
   1291 };
   1292 
   1293 // Implements the AnyOf(m1, m2) matcher for a particular argument type
   1294 // T.  We do not nest it inside the AnyOfMatcher class template, as
   1295 // that will prevent different instantiations of AnyOfMatcher from
   1296 // sharing the same EitherOfMatcherImpl<T> class.
   1297 template <typename T>
   1298 class EitherOfMatcherImpl : public MatcherInterface<T> {
   1299  public:
   1300   EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
   1301       : matcher1_(matcher1), matcher2_(matcher2) {}
   1302 
   1303   virtual void DescribeTo(::std::ostream* os) const {
   1304     *os << "(";
   1305     matcher1_.DescribeTo(os);
   1306     *os << ") or (";
   1307     matcher2_.DescribeTo(os);
   1308     *os << ")";
   1309   }
   1310 
   1311   virtual void DescribeNegationTo(::std::ostream* os) const {
   1312     *os << "(";
   1313     matcher1_.DescribeNegationTo(os);
   1314     *os << ") and (";
   1315     matcher2_.DescribeNegationTo(os);
   1316     *os << ")";
   1317   }
   1318 
   1319   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
   1320     // If either matcher1_ or matcher2_ matches x, we just need to
   1321     // explain why *one* of them matches.
   1322     StringMatchResultListener listener1;
   1323     if (matcher1_.MatchAndExplain(x, &listener1)) {
   1324       *listener << listener1.str();
   1325       return true;
   1326     }
   1327 
   1328     StringMatchResultListener listener2;
   1329     if (matcher2_.MatchAndExplain(x, &listener2)) {
   1330       *listener << listener2.str();
   1331       return true;
   1332     }
   1333 
   1334     // Otherwise we need to explain why *both* of them fail.
   1335     const internal::string s1 = listener1.str();
   1336     const internal::string s2 = listener2.str();
   1337 
   1338     if (s1 == "") {
   1339       *listener << s2;
   1340     } else {
   1341       *listener << s1;
   1342       if (s2 != "") {
   1343         *listener << ", and " << s2;
   1344       }
   1345     }
   1346     return false;
   1347   }
   1348 
   1349  private:
   1350   const Matcher<T> matcher1_;
   1351   const Matcher<T> matcher2_;
   1352 
   1353   GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
   1354 };
   1355 
   1356 // Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
   1357 // matches a value that matches at least one of the matchers m_1, ...,
   1358 // and m_n.
   1359 template <typename Matcher1, typename Matcher2>
   1360 class EitherOfMatcher {
   1361  public:
   1362   EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
   1363       : matcher1_(matcher1), matcher2_(matcher2) {}
   1364 
   1365   // This template type conversion operator allows a
   1366   // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
   1367   // both Matcher1 and Matcher2 can match.
   1368   template <typename T>
   1369   operator Matcher<T>() const {
   1370     return Matcher<T>(new EitherOfMatcherImpl<T>(
   1371         SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
   1372   }
   1373 
   1374  private:
   1375   Matcher1 matcher1_;
   1376   Matcher2 matcher2_;
   1377 
   1378   GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
   1379 };
   1380 
   1381 // Used for implementing Truly(pred), which turns a predicate into a
   1382 // matcher.
   1383 template <typename Predicate>
   1384 class TrulyMatcher {
   1385  public:
   1386   explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
   1387 
   1388   // This method template allows Truly(pred) to be used as a matcher
   1389   // for type T where T is the argument type of predicate 'pred'.  The
   1390   // argument is passed by reference as the predicate may be
   1391   // interested in the address of the argument.
   1392   template <typename T>
   1393   bool MatchAndExplain(T& x,  // NOLINT
   1394                        MatchResultListener* /* listener */) const {
   1395 #if GTEST_OS_WINDOWS
   1396     // MSVC warns about converting a value into bool (warning 4800).
   1397 # pragma warning(push)          // Saves the current warning state.
   1398 # pragma warning(disable:4800)  // Temporarily disables warning 4800.
   1399 #endif  // GTEST_OS_WINDOWS
   1400     return predicate_(x);
   1401 #if GTEST_OS_WINDOWS
   1402 # pragma warning(pop)           // Restores the warning state.
   1403 #endif  // GTEST_OS_WINDOWS
   1404   }
   1405 
   1406   void DescribeTo(::std::ostream* os) const {
   1407     *os << "satisfies the given predicate";
   1408   }
   1409 
   1410   void DescribeNegationTo(::std::ostream* os) const {
   1411     *os << "doesn't satisfy the given predicate";
   1412   }
   1413 
   1414  private:
   1415   Predicate predicate_;
   1416 
   1417   GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
   1418 };
   1419 
   1420 // Used for implementing Matches(matcher), which turns a matcher into
   1421 // a predicate.
   1422 template <typename M>
   1423 class MatcherAsPredicate {
   1424  public:
   1425   explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
   1426 
   1427   // This template operator() allows Matches(m) to be used as a
   1428   // predicate on type T where m is a matcher on type T.
   1429   //
   1430   // The argument x is passed by reference instead of by value, as
   1431   // some matcher may be interested in its address (e.g. as in
   1432   // Matches(Ref(n))(x)).
   1433   template <typename T>
   1434   bool operator()(const T& x) const {
   1435     // We let matcher_ commit to a particular type here instead of
   1436     // when the MatcherAsPredicate object was constructed.  This
   1437     // allows us to write Matches(m) where m is a polymorphic matcher
   1438     // (e.g. Eq(5)).
   1439     //
   1440     // If we write Matcher<T>(matcher_).Matches(x) here, it won't
   1441     // compile when matcher_ has type Matcher<const T&>; if we write
   1442     // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
   1443     // when matcher_ has type Matcher<T>; if we just write
   1444     // matcher_.Matches(x), it won't compile when matcher_ is
   1445     // polymorphic, e.g. Eq(5).
   1446     //
   1447     // MatcherCast<const T&>() is necessary for making the code work
   1448     // in all of the above situations.
   1449     return MatcherCast<const T&>(matcher_).Matches(x);
   1450   }
   1451 
   1452  private:
   1453   M matcher_;
   1454 
   1455   GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
   1456 };
   1457 
   1458 // For implementing ASSERT_THAT() and EXPECT_THAT().  The template
   1459 // argument M must be a type that can be converted to a matcher.
   1460 template <typename M>
   1461 class PredicateFormatterFromMatcher {
   1462  public:
   1463   explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
   1464 
   1465   // This template () operator allows a PredicateFormatterFromMatcher
   1466   // object to act as a predicate-formatter suitable for using with
   1467   // Google Test's EXPECT_PRED_FORMAT1() macro.
   1468   template <typename T>
   1469   AssertionResult operator()(const char* value_text, const T& x) const {
   1470     // We convert matcher_ to a Matcher<const T&> *now* instead of
   1471     // when the PredicateFormatterFromMatcher object was constructed,
   1472     // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
   1473     // know which type to instantiate it to until we actually see the
   1474     // type of x here.
   1475     //
   1476     // We write MatcherCast<const T&>(matcher_) instead of
   1477     // Matcher<const T&>(matcher_), as the latter won't compile when
   1478     // matcher_ has type Matcher<T> (e.g. An<int>()).
   1479     const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
   1480     StringMatchResultListener listener;
   1481     if (MatchPrintAndExplain(x, matcher, &listener))
   1482       return AssertionSuccess();
   1483 
   1484     ::std::stringstream ss;
   1485     ss << "Value of: " << value_text << "\n"
   1486        << "Expected: ";
   1487     matcher.DescribeTo(&ss);
   1488     ss << "\n  Actual: " << listener.str();
   1489     return AssertionFailure() << ss.str();
   1490   }
   1491 
   1492  private:
   1493   const M matcher_;
   1494 
   1495   GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
   1496 };
   1497 
   1498 // A helper function for converting a matcher to a predicate-formatter
   1499 // without the user needing to explicitly write the type.  This is
   1500 // used for implementing ASSERT_THAT() and EXPECT_THAT().
   1501 template <typename M>
   1502 inline PredicateFormatterFromMatcher<M>
   1503 MakePredicateFormatterFromMatcher(const M& matcher) {
   1504   return PredicateFormatterFromMatcher<M>(matcher);
   1505 }
   1506 
   1507 // Implements the polymorphic floating point equality matcher, which
   1508 // matches two float values using ULP-based approximation.  The
   1509 // template is meant to be instantiated with FloatType being either
   1510 // float or double.
   1511 template <typename FloatType>
   1512 class FloatingEqMatcher {
   1513  public:
   1514   // Constructor for FloatingEqMatcher.
   1515   // The matcher's input will be compared with rhs.  The matcher treats two
   1516   // NANs as equal if nan_eq_nan is true.  Otherwise, under IEEE standards,
   1517   // equality comparisons between NANs will always return false.
   1518   FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
   1519     rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
   1520 
   1521   // Implements floating point equality matcher as a Matcher<T>.
   1522   template <typename T>
   1523   class Impl : public MatcherInterface<T> {
   1524    public:
   1525     Impl(FloatType rhs, bool nan_eq_nan) :
   1526       rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
   1527 
   1528     virtual bool MatchAndExplain(T value,
   1529                                  MatchResultListener* /* listener */) const {
   1530       const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
   1531 
   1532       // Compares NaNs first, if nan_eq_nan_ is true.
   1533       if (nan_eq_nan_ && lhs.is_nan()) {
   1534         return rhs.is_nan();
   1535       }
   1536 
   1537       return lhs.AlmostEquals(rhs);
   1538     }
   1539 
   1540     virtual void DescribeTo(::std::ostream* os) const {
   1541       // os->precision() returns the previously set precision, which we
   1542       // store to restore the ostream to its original configuration
   1543       // after outputting.
   1544       const ::std::streamsize old_precision = os->precision(
   1545           ::std::numeric_limits<FloatType>::digits10 + 2);
   1546       if (FloatingPoint<FloatType>(rhs_).is_nan()) {
   1547         if (nan_eq_nan_) {
   1548           *os << "is NaN";
   1549         } else {
   1550           *os << "never matches";
   1551         }
   1552       } else {
   1553         *os << "is approximately " << rhs_;
   1554       }
   1555       os->precision(old_precision);
   1556     }
   1557 
   1558     virtual void DescribeNegationTo(::std::ostream* os) const {
   1559       // As before, get original precision.
   1560       const ::std::streamsize old_precision = os->precision(
   1561           ::std::numeric_limits<FloatType>::digits10 + 2);
   1562       if (FloatingPoint<FloatType>(rhs_).is_nan()) {
   1563         if (nan_eq_nan_) {
   1564           *os << "isn't NaN";
   1565         } else {
   1566           *os << "is anything";
   1567         }
   1568       } else {
   1569         *os << "isn't approximately " << rhs_;
   1570       }
   1571       // Restore original precision.
   1572       os->precision(old_precision);
   1573     }
   1574 
   1575    private:
   1576     const FloatType rhs_;
   1577     const bool nan_eq_nan_;
   1578 
   1579     GTEST_DISALLOW_ASSIGN_(Impl);
   1580   };
   1581 
   1582   // The following 3 type conversion operators allow FloatEq(rhs) and
   1583   // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
   1584   // Matcher<const float&>, or a Matcher<float&>, but nothing else.
   1585   // (While Google's C++ coding style doesn't allow arguments passed
   1586   // by non-const reference, we may see them in code not conforming to
   1587   // the style.  Therefore Google Mock needs to support them.)
   1588   operator Matcher<FloatType>() const {
   1589     return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
   1590   }
   1591 
   1592   operator Matcher<const FloatType&>() const {
   1593     return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
   1594   }
   1595 
   1596   operator Matcher<FloatType&>() const {
   1597     return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
   1598   }
   1599  private:
   1600   const FloatType rhs_;
   1601   const bool nan_eq_nan_;
   1602 
   1603   GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
   1604 };
   1605 
   1606 // Implements the Pointee(m) matcher for matching a pointer whose
   1607 // pointee matches matcher m.  The pointer can be either raw or smart.
   1608 template <typename InnerMatcher>
   1609 class PointeeMatcher {
   1610  public:
   1611   explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
   1612 
   1613   // This type conversion operator template allows Pointee(m) to be
   1614   // used as a matcher for any pointer type whose pointee type is
   1615   // compatible with the inner matcher, where type Pointer can be
   1616   // either a raw pointer or a smart pointer.
   1617   //
   1618   // The reason we do this instead of relying on
   1619   // MakePolymorphicMatcher() is that the latter is not flexible
   1620   // enough for implementing the DescribeTo() method of Pointee().
   1621   template <typename Pointer>
   1622   operator Matcher<Pointer>() const {
   1623     return MakeMatcher(new Impl<Pointer>(matcher_));
   1624   }
   1625 
   1626  private:
   1627   // The monomorphic implementation that works for a particular pointer type.
   1628   template <typename Pointer>
   1629   class Impl : public MatcherInterface<Pointer> {
   1630    public:
   1631     typedef typename PointeeOf<GTEST_REMOVE_CONST_(  // NOLINT
   1632         GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
   1633 
   1634     explicit Impl(const InnerMatcher& matcher)
   1635         : matcher_(MatcherCast<const Pointee&>(matcher)) {}
   1636 
   1637     virtual void DescribeTo(::std::ostream* os) const {
   1638       *os << "points to a value that ";
   1639       matcher_.DescribeTo(os);
   1640     }
   1641 
   1642     virtual void DescribeNegationTo(::std::ostream* os) const {
   1643       *os << "does not point to a value that ";
   1644       matcher_.DescribeTo(os);
   1645     }
   1646 
   1647     virtual bool MatchAndExplain(Pointer pointer,
   1648                                  MatchResultListener* listener) const {
   1649       if (GetRawPointer(pointer) == NULL)
   1650         return false;
   1651 
   1652       *listener << "which points to ";
   1653       return MatchPrintAndExplain(*pointer, matcher_, listener);
   1654     }
   1655 
   1656    private:
   1657     const Matcher<const Pointee&> matcher_;
   1658 
   1659     GTEST_DISALLOW_ASSIGN_(Impl);
   1660   };
   1661 
   1662   const InnerMatcher matcher_;
   1663 
   1664   GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
   1665 };
   1666 
   1667 // Implements the Field() matcher for matching a field (i.e. member
   1668 // variable) of an object.
   1669 template <typename Class, typename FieldType>
   1670 class FieldMatcher {
   1671  public:
   1672   FieldMatcher(FieldType Class::*field,
   1673                const Matcher<const FieldType&>& matcher)
   1674       : field_(field), matcher_(matcher) {}
   1675 
   1676   void DescribeTo(::std::ostream* os) const {
   1677     *os << "is an object whose given field ";
   1678     matcher_.DescribeTo(os);
   1679   }
   1680 
   1681   void DescribeNegationTo(::std::ostream* os) const {
   1682     *os << "is an object whose given field ";
   1683     matcher_.DescribeNegationTo(os);
   1684   }
   1685 
   1686   template <typename T>
   1687   bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
   1688     return MatchAndExplainImpl(
   1689         typename ::testing::internal::
   1690             is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
   1691         value, listener);
   1692   }
   1693 
   1694  private:
   1695   // The first argument of MatchAndExplainImpl() is needed to help
   1696   // Symbian's C++ compiler choose which overload to use.  Its type is
   1697   // true_type iff the Field() matcher is used to match a pointer.
   1698   bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
   1699                            MatchResultListener* listener) const {
   1700     *listener << "whose given field is ";
   1701     return MatchPrintAndExplain(obj.*field_, matcher_, listener);
   1702   }
   1703 
   1704   bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
   1705                            MatchResultListener* listener) const {
   1706     if (p == NULL)
   1707       return false;
   1708 
   1709     *listener << "which points to an object ";
   1710     // Since *p has a field, it must be a class/struct/union type and
   1711     // thus cannot be a pointer.  Therefore we pass false_type() as
   1712     // the first argument.
   1713     return MatchAndExplainImpl(false_type(), *p, listener);
   1714   }
   1715 
   1716   const FieldType Class::*field_;
   1717   const Matcher<const FieldType&> matcher_;
   1718 
   1719   GTEST_DISALLOW_ASSIGN_(FieldMatcher);
   1720 };
   1721 
   1722 // Implements the Property() matcher for matching a property
   1723 // (i.e. return value of a getter method) of an object.
   1724 template <typename Class, typename PropertyType>
   1725 class PropertyMatcher {
   1726  public:
   1727   // The property may have a reference type, so 'const PropertyType&'
   1728   // may cause double references and fail to compile.  That's why we
   1729   // need GTEST_REFERENCE_TO_CONST, which works regardless of
   1730   // PropertyType being a reference or not.
   1731   typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
   1732 
   1733   PropertyMatcher(PropertyType (Class::*property)() const,
   1734                   const Matcher<RefToConstProperty>& matcher)
   1735       : property_(property), matcher_(matcher) {}
   1736 
   1737   void DescribeTo(::std::ostream* os) const {
   1738     *os << "is an object whose given property ";
   1739     matcher_.DescribeTo(os);
   1740   }
   1741 
   1742   void DescribeNegationTo(::std::ostream* os) const {
   1743     *os << "is an object whose given property ";
   1744     matcher_.DescribeNegationTo(os);
   1745   }
   1746 
   1747   template <typename T>
   1748   bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
   1749     return MatchAndExplainImpl(
   1750         typename ::testing::internal::
   1751             is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
   1752         value, listener);
   1753   }
   1754 
   1755  private:
   1756   // The first argument of MatchAndExplainImpl() is needed to help
   1757   // Symbian's C++ compiler choose which overload to use.  Its type is
   1758   // true_type iff the Property() matcher is used to match a pointer.
   1759   bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
   1760                            MatchResultListener* listener) const {
   1761     *listener << "whose given property is ";
   1762     // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
   1763     // which takes a non-const reference as argument.
   1764     RefToConstProperty result = (obj.*property_)();
   1765     return MatchPrintAndExplain(result, matcher_, listener);
   1766   }
   1767 
   1768   bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
   1769                            MatchResultListener* listener) const {
   1770     if (p == NULL)
   1771       return false;
   1772 
   1773     *listener << "which points to an object ";
   1774     // Since *p has a property method, it must be a class/struct/union
   1775     // type and thus cannot be a pointer.  Therefore we pass
   1776     // false_type() as the first argument.
   1777     return MatchAndExplainImpl(false_type(), *p, listener);
   1778   }
   1779 
   1780   PropertyType (Class::*property_)() const;
   1781   const Matcher<RefToConstProperty> matcher_;
   1782 
   1783   GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
   1784 };
   1785 
   1786 // Type traits specifying various features of different functors for ResultOf.
   1787 // The default template specifies features for functor objects.
   1788 // Functor classes have to typedef argument_type and result_type
   1789 // to be compatible with ResultOf.
   1790 template <typename Functor>
   1791 struct CallableTraits {
   1792   typedef typename Functor::result_type ResultType;
   1793   typedef Functor StorageType;
   1794 
   1795   static void CheckIsValid(Functor /* functor */) {}
   1796   template <typename T>
   1797   static ResultType Invoke(Functor f, T arg) { return f(arg); }
   1798 };
   1799 
   1800 // Specialization for function pointers.
   1801 template <typename ArgType, typename ResType>
   1802 struct CallableTraits<ResType(*)(ArgType)> {
   1803   typedef ResType ResultType;
   1804   typedef ResType(*StorageType)(ArgType);
   1805 
   1806   static void CheckIsValid(ResType(*f)(ArgType)) {
   1807     GTEST_CHECK_(f != NULL)
   1808         << "NULL function pointer is passed into ResultOf().";
   1809   }
   1810   template <typename T>
   1811   static ResType Invoke(ResType(*f)(ArgType), T arg) {
   1812     return (*f)(arg);
   1813   }
   1814 };
   1815 
   1816 // Implements the ResultOf() matcher for matching a return value of a
   1817 // unary function of an object.
   1818 template <typename Callable>
   1819 class ResultOfMatcher {
   1820  public:
   1821   typedef typename CallableTraits<Callable>::ResultType ResultType;
   1822 
   1823   ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
   1824       : callable_(callable), matcher_(matcher) {
   1825     CallableTraits<Callable>::CheckIsValid(callable_);
   1826   }
   1827 
   1828   template <typename T>
   1829   operator Matcher<T>() const {
   1830     return Matcher<T>(new Impl<T>(callable_, matcher_));
   1831   }
   1832 
   1833  private:
   1834   typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
   1835 
   1836   template <typename T>
   1837   class Impl : public MatcherInterface<T> {
   1838    public:
   1839     Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
   1840         : callable_(callable), matcher_(matcher) {}
   1841 
   1842     virtual void DescribeTo(::std::ostream* os) const {
   1843       *os << "is mapped by the given callable to a value that ";
   1844       matcher_.DescribeTo(os);
   1845     }
   1846 
   1847     virtual void DescribeNegationTo(::std::ostream* os) const {
   1848       *os << "is mapped by the given callable to a value that ";
   1849       matcher_.DescribeNegationTo(os);
   1850     }
   1851 
   1852     virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
   1853       *listener << "which is mapped by the given callable to ";
   1854       // Cannot pass the return value (for example, int) to
   1855       // MatchPrintAndExplain, which takes a non-const reference as argument.
   1856       ResultType result =
   1857           CallableTraits<Callable>::template Invoke<T>(callable_, obj);
   1858       return MatchPrintAndExplain(result, matcher_, listener);
   1859     }
   1860 
   1861    private:
   1862     // Functors often define operator() as non-const method even though
   1863     // they are actualy stateless. But we need to use them even when
   1864     // 'this' is a const pointer. It's the user's responsibility not to
   1865     // use stateful callables with ResultOf(), which does't guarantee
   1866     // how many times the callable will be invoked.
   1867     mutable CallableStorageType callable_;
   1868     const Matcher<ResultType> matcher_;
   1869 
   1870     GTEST_DISALLOW_ASSIGN_(Impl);
   1871   };  // class Impl
   1872 
   1873   const CallableStorageType callable_;
   1874   const Matcher<ResultType> matcher_;
   1875 
   1876   GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
   1877 };
   1878 
   1879 // Implements an equality matcher for any STL-style container whose elements
   1880 // support ==. This matcher is like Eq(), but its failure explanations provide
   1881 // more detailed information that is useful when the container is used as a set.
   1882 // The failure message reports elements that are in one of the operands but not
   1883 // the other. The failure messages do not report duplicate or out-of-order
   1884 // elements in the containers (which don't properly matter to sets, but can
   1885 // occur if the containers are vectors or lists, for example).
   1886 //
   1887 // Uses the container's const_iterator, value_type, operator ==,
   1888 // begin(), and end().
   1889 template <typename Container>
   1890 class ContainerEqMatcher {
   1891  public:
   1892   typedef internal::StlContainerView<Container> View;
   1893   typedef typename View::type StlContainer;
   1894   typedef typename View::const_reference StlContainerReference;
   1895 
   1896   // We make a copy of rhs in case the elements in it are modified
   1897   // after this matcher is created.
   1898   explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
   1899     // Makes sure the user doesn't instantiate this class template
   1900     // with a const or reference type.
   1901     (void)testing::StaticAssertTypeEq<Container,
   1902         GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
   1903   }
   1904 
   1905   void DescribeTo(::std::ostream* os) const {
   1906     *os << "equals ";
   1907     UniversalPrint(rhs_, os);
   1908   }
   1909   void DescribeNegationTo(::std::ostream* os) const {
   1910     *os << "does not equal ";
   1911     UniversalPrint(rhs_, os);
   1912   }
   1913 
   1914   template <typename LhsContainer>
   1915   bool MatchAndExplain(const LhsContainer& lhs,
   1916                        MatchResultListener* listener) const {
   1917     // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
   1918     // that causes LhsContainer to be a const type sometimes.
   1919     typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
   1920         LhsView;
   1921     typedef typename LhsView::type LhsStlContainer;
   1922     StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
   1923     if (lhs_stl_container == rhs_)
   1924       return true;
   1925 
   1926     ::std::ostream* const os = listener->stream();
   1927     if (os != NULL) {
   1928       // Something is different. Check for extra values first.
   1929       bool printed_header = false;
   1930       for (typename LhsStlContainer::const_iterator it =
   1931                lhs_stl_container.begin();
   1932            it != lhs_stl_container.end(); ++it) {
   1933         if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
   1934             rhs_.end()) {
   1935           if (printed_header) {
   1936             *os << ", ";
   1937           } else {
   1938             *os << "which has these unexpected elements: ";
   1939             printed_header = true;
   1940           }
   1941           UniversalPrint(*it, os);
   1942         }
   1943       }
   1944 
   1945       // Now check for missing values.
   1946       bool printed_header2 = false;
   1947       for (typename StlContainer::const_iterator it = rhs_.begin();
   1948            it != rhs_.end(); ++it) {
   1949         if (internal::ArrayAwareFind(
   1950                 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
   1951             lhs_stl_container.end()) {
   1952           if (printed_header2) {
   1953             *os << ", ";
   1954           } else {
   1955             *os << (printed_header ? ",\nand" : "which")
   1956                 << " doesn't have these expected elements: ";
   1957             printed_header2 = true;
   1958           }
   1959           UniversalPrint(*it, os);
   1960         }
   1961       }
   1962     }
   1963 
   1964     return false;
   1965   }
   1966 
   1967  private:
   1968   const StlContainer rhs_;
   1969 
   1970   GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
   1971 };
   1972 
   1973 // Implements Pointwise(tuple_matcher, rhs_container).  tuple_matcher
   1974 // must be able to be safely cast to Matcher<tuple<const T1&, const
   1975 // T2&> >, where T1 and T2 are the types of elements in the LHS
   1976 // container and the RHS container respectively.
   1977 template <typename TupleMatcher, typename RhsContainer>
   1978 class PointwiseMatcher {
   1979  public:
   1980   typedef internal::StlContainerView<RhsContainer> RhsView;
   1981   typedef typename RhsView::type RhsStlContainer;
   1982   typedef typename RhsStlContainer::value_type RhsValue;
   1983 
   1984   // Like ContainerEq, we make a copy of rhs in case the elements in
   1985   // it are modified after this matcher is created.
   1986   PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
   1987       : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
   1988     // Makes sure the user doesn't instantiate this class template
   1989     // with a const or reference type.
   1990     (void)testing::StaticAssertTypeEq<RhsContainer,
   1991         GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
   1992   }
   1993 
   1994   template <typename LhsContainer>
   1995   operator Matcher<LhsContainer>() const {
   1996     return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
   1997   }
   1998 
   1999   template <typename LhsContainer>
   2000   class Impl : public MatcherInterface<LhsContainer> {
   2001    public:
   2002     typedef internal::StlContainerView<
   2003          GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
   2004     typedef typename LhsView::type LhsStlContainer;
   2005     typedef typename LhsView::const_reference LhsStlContainerReference;
   2006     typedef typename LhsStlContainer::value_type LhsValue;
   2007     // We pass the LHS value and the RHS value to the inner matcher by
   2008     // reference, as they may be expensive to copy.  We must use tuple
   2009     // instead of pair here, as a pair cannot hold references (C++ 98,
   2010     // 20.2.2 [lib.pairs]).
   2011     typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
   2012 
   2013     Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
   2014         // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
   2015         : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
   2016           rhs_(rhs) {}
   2017 
   2018     virtual void DescribeTo(::std::ostream* os) const {
   2019       *os << "contains " << rhs_.size()
   2020           << " values, where each value and its corresponding value in ";
   2021       UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
   2022       *os << " ";
   2023       mono_tuple_matcher_.DescribeTo(os);
   2024     }
   2025     virtual void DescribeNegationTo(::std::ostream* os) const {
   2026       *os << "doesn't contain exactly " << rhs_.size()
   2027           << " values, or contains a value x at some index i"
   2028           << " where x and the i-th value of ";
   2029       UniversalPrint(rhs_, os);
   2030       *os << " ";
   2031       mono_tuple_matcher_.DescribeNegationTo(os);
   2032     }
   2033 
   2034     virtual bool MatchAndExplain(LhsContainer lhs,
   2035                                  MatchResultListener* listener) const {
   2036       LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
   2037       const size_t actual_size = lhs_stl_container.size();
   2038       if (actual_size != rhs_.size()) {
   2039         *listener << "which contains " << actual_size << " values";
   2040         return false;
   2041       }
   2042 
   2043       typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
   2044       typename RhsStlContainer::const_iterator right = rhs_.begin();
   2045       for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
   2046         const InnerMatcherArg value_pair(*left, *right);
   2047 
   2048         if (listener->IsInterested()) {
   2049           StringMatchResultListener inner_listener;
   2050           if (!mono_tuple_matcher_.MatchAndExplain(
   2051                   value_pair, &inner_listener)) {
   2052             *listener << "where the value pair (";
   2053             UniversalPrint(*left, listener->stream());
   2054             *listener << ", ";
   2055             UniversalPrint(*right, listener->stream());
   2056             *listener << ") at index #" << i << " don't match";
   2057             PrintIfNotEmpty(inner_listener.str(), listener->stream());
   2058             return false;
   2059           }
   2060         } else {
   2061           if (!mono_tuple_matcher_.Matches(value_pair))
   2062             return false;
   2063         }
   2064       }
   2065 
   2066       return true;
   2067     }
   2068 
   2069    private:
   2070     const Matcher<InnerMatcherArg> mono_tuple_matcher_;
   2071     const RhsStlContainer rhs_;
   2072 
   2073     GTEST_DISALLOW_ASSIGN_(Impl);
   2074   };
   2075 
   2076  private:
   2077   const TupleMatcher tuple_matcher_;
   2078   const RhsStlContainer rhs_;
   2079 
   2080   GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
   2081 };
   2082 
   2083 // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
   2084 template <typename Container>
   2085 class QuantifierMatcherImpl : public MatcherInterface<Container> {
   2086  public:
   2087   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
   2088   typedef StlContainerView<RawContainer> View;
   2089   typedef typename View::type StlContainer;
   2090   typedef typename View::const_reference StlContainerReference;
   2091   typedef typename StlContainer::value_type Element;
   2092 
   2093   template <typename InnerMatcher>
   2094   explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
   2095       : inner_matcher_(
   2096            testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
   2097 
   2098   // Checks whether:
   2099   // * All elements in the container match, if all_elements_should_match.
   2100   // * Any element in the container matches, if !all_elements_should_match.
   2101   bool MatchAndExplainImpl(bool all_elements_should_match,
   2102                            Container container,
   2103                            MatchResultListener* listener) const {
   2104     StlContainerReference stl_container = View::ConstReference(container);
   2105     size_t i = 0;
   2106     for (typename StlContainer::const_iterator it = stl_container.begin();
   2107          it != stl_container.end(); ++it, ++i) {
   2108       StringMatchResultListener inner_listener;
   2109       const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
   2110 
   2111       if (matches != all_elements_should_match) {
   2112         *listener << "whose element #" << i
   2113                   << (matches ? " matches" : " doesn't match");
   2114         PrintIfNotEmpty(inner_listener.str(), listener->stream());
   2115         return !all_elements_should_match;
   2116       }
   2117     }
   2118     return all_elements_should_match;
   2119   }
   2120 
   2121  protected:
   2122   const Matcher<const Element&> inner_matcher_;
   2123 
   2124   GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
   2125 };
   2126 
   2127 // Implements Contains(element_matcher) for the given argument type Container.
   2128 // Symmetric to EachMatcherImpl.
   2129 template <typename Container>
   2130 class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
   2131  public:
   2132   template <typename InnerMatcher>
   2133   explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
   2134       : QuantifierMatcherImpl<Container>(inner_matcher) {}
   2135 
   2136   // Describes what this matcher does.
   2137   virtual void DescribeTo(::std::ostream* os) const {
   2138     *os << "contains at least one element that ";
   2139     this->inner_matcher_.DescribeTo(os);
   2140   }
   2141 
   2142   virtual void DescribeNegationTo(::std::ostream* os) const {
   2143     *os << "doesn't contain any element that ";
   2144     this->inner_matcher_.DescribeTo(os);
   2145   }
   2146 
   2147   virtual bool MatchAndExplain(Container container,
   2148                                MatchResultListener* listener) const {
   2149     return this->MatchAndExplainImpl(false, container, listener);
   2150   }
   2151 
   2152  private:
   2153   GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
   2154 };
   2155 
   2156 // Implements Each(element_matcher) for the given argument type Container.
   2157 // Symmetric to ContainsMatcherImpl.
   2158 template <typename Container>
   2159 class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
   2160  public:
   2161   template <typename InnerMatcher>
   2162   explicit EachMatcherImpl(InnerMatcher inner_matcher)
   2163       : QuantifierMatcherImpl<Container>(inner_matcher) {}
   2164 
   2165   // Describes what this matcher does.
   2166   virtual void DescribeTo(::std::ostream* os) const {
   2167     *os << "only contains elements that ";
   2168     this->inner_matcher_.DescribeTo(os);
   2169   }
   2170 
   2171   virtual void DescribeNegationTo(::std::ostream* os) const {
   2172     *os << "contains some element that ";
   2173     this->inner_matcher_.DescribeNegationTo(os);
   2174   }
   2175 
   2176   virtual bool MatchAndExplain(Container container,
   2177                                MatchResultListener* listener) const {
   2178     return this->MatchAndExplainImpl(true, container, listener);
   2179   }
   2180 
   2181  private:
   2182   GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
   2183 };
   2184 
   2185 // Implements polymorphic Contains(element_matcher).
   2186 template <typename M>
   2187 class ContainsMatcher {
   2188  public:
   2189   explicit ContainsMatcher(M m) : inner_matcher_(m) {}
   2190 
   2191   template <typename Container>
   2192   operator Matcher<Container>() const {
   2193     return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
   2194   }
   2195 
   2196  private:
   2197   const M inner_matcher_;
   2198 
   2199   GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
   2200 };
   2201 
   2202 // Implements polymorphic Each(element_matcher).
   2203 template <typename M>
   2204 class EachMatcher {
   2205  public:
   2206   explicit EachMatcher(M m) : inner_matcher_(m) {}
   2207 
   2208   template <typename Container>
   2209   operator Matcher<Container>() const {
   2210     return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
   2211   }
   2212 
   2213  private:
   2214   const M inner_matcher_;
   2215 
   2216   GTEST_DISALLOW_ASSIGN_(EachMatcher);
   2217 };
   2218 
   2219 // Implements Key(inner_matcher) for the given argument pair type.
   2220 // Key(inner_matcher) matches an std::pair whose 'first' field matches
   2221 // inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
   2222 // std::map that contains at least one element whose key is >= 5.
   2223 template <typename PairType>
   2224 class KeyMatcherImpl : public MatcherInterface<PairType> {
   2225  public:
   2226   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
   2227   typedef typename RawPairType::first_type KeyType;
   2228 
   2229   template <typename InnerMatcher>
   2230   explicit KeyMatcherImpl(InnerMatcher inner_matcher)
   2231       : inner_matcher_(
   2232           testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
   2233   }
   2234 
   2235   // Returns true iff 'key_value.first' (the key) matches the inner matcher.
   2236   virtual bool MatchAndExplain(PairType key_value,
   2237                                MatchResultListener* listener) const {
   2238     StringMatchResultListener inner_listener;
   2239     const bool match = inner_matcher_.MatchAndExplain(key_value.first,
   2240                                                       &inner_listener);
   2241     const internal::string explanation = inner_listener.str();
   2242     if (explanation != "") {
   2243       *listener << "whose first field is a value " << explanation;
   2244     }
   2245     return match;
   2246   }
   2247 
   2248   // Describes what this matcher does.
   2249   virtual void DescribeTo(::std::ostream* os) const {
   2250     *os << "has a key that ";
   2251     inner_matcher_.DescribeTo(os);
   2252   }
   2253 
   2254   // Describes what the negation of this matcher does.
   2255   virtual void DescribeNegationTo(::std::ostream* os) const {
   2256     *os << "doesn't have a key that ";
   2257     inner_matcher_.DescribeTo(os);
   2258   }
   2259 
   2260  private:
   2261   const Matcher<const KeyType&> inner_matcher_;
   2262 
   2263   GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
   2264 };
   2265 
   2266 // Implements polymorphic Key(matcher_for_key).
   2267 template <typename M>
   2268 class KeyMatcher {
   2269  public:
   2270   explicit KeyMatcher(M m) : matcher_for_key_(m) {}
   2271 
   2272   template <typename PairType>
   2273   operator Matcher<PairType>() const {
   2274     return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
   2275   }
   2276 
   2277  private:
   2278   const M matcher_for_key_;
   2279 
   2280   GTEST_DISALLOW_ASSIGN_(KeyMatcher);
   2281 };
   2282 
   2283 // Implements Pair(first_matcher, second_matcher) for the given argument pair
   2284 // type with its two matchers. See Pair() function below.
   2285 template <typename PairType>
   2286 class PairMatcherImpl : public MatcherInterface<PairType> {
   2287  public:
   2288   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
   2289   typedef typename RawPairType::first_type FirstType;
   2290   typedef typename RawPairType::second_type SecondType;
   2291 
   2292   template <typename FirstMatcher, typename SecondMatcher>
   2293   PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
   2294       : first_matcher_(
   2295             testing::SafeMatcherCast<const FirstType&>(first_matcher)),
   2296         second_matcher_(
   2297             testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
   2298   }
   2299 
   2300   // Describes what this matcher does.
   2301   virtual void DescribeTo(::std::ostream* os) const {
   2302     *os << "has a first field that ";
   2303     first_matcher_.DescribeTo(os);
   2304     *os << ", and has a second field that ";
   2305     second_matcher_.DescribeTo(os);
   2306   }
   2307 
   2308   // Describes what the negation of this matcher does.
   2309   virtual void DescribeNegationTo(::std::ostream* os) const {
   2310     *os << "has a first field that ";
   2311     first_matcher_.DescribeNegationTo(os);
   2312     *os << ", or has a second field that ";
   2313     second_matcher_.DescribeNegationTo(os);
   2314   }
   2315 
   2316   // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
   2317   // matches second_matcher.
   2318   virtual bool MatchAndExplain(PairType a_pair,
   2319                                MatchResultListener* listener) const {
   2320     if (!listener->IsInterested()) {
   2321       // If the listener is not interested, we don't need to construct the
   2322       // explanation.
   2323       return first_matcher_.Matches(a_pair.first) &&
   2324              second_matcher_.Matches(a_pair.second);
   2325     }
   2326     StringMatchResultListener first_inner_listener;
   2327     if (!first_matcher_.MatchAndExplain(a_pair.first,
   2328                                         &first_inner_listener)) {
   2329       *listener << "whose first field does not match";
   2330       PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
   2331       return false;
   2332     }
   2333     StringMatchResultListener second_inner_listener;
   2334     if (!second_matcher_.MatchAndExplain(a_pair.second,
   2335                                          &second_inner_listener)) {
   2336       *listener << "whose second field does not match";
   2337       PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
   2338       return false;
   2339     }
   2340     ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
   2341                    listener);
   2342     return true;
   2343   }
   2344 
   2345  private:
   2346   void ExplainSuccess(const internal::string& first_explanation,
   2347                       const internal::string& second_explanation,
   2348                       MatchResultListener* listener) const {
   2349     *listener << "whose both fields match";
   2350     if (first_explanation != "") {
   2351       *listener << ", where the first field is a value " << first_explanation;
   2352     }
   2353     if (second_explanation != "") {
   2354       *listener << ", ";
   2355       if (first_explanation != "") {
   2356         *listener << "and ";
   2357       } else {
   2358         *listener << "where ";
   2359       }
   2360       *listener << "the second field is a value " << second_explanation;
   2361     }
   2362   }
   2363 
   2364   const Matcher<const FirstType&> first_matcher_;
   2365   const Matcher<const SecondType&> second_matcher_;
   2366 
   2367   GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
   2368 };
   2369 
   2370 // Implements polymorphic Pair(first_matcher, second_matcher).
   2371 template <typename FirstMatcher, typename SecondMatcher>
   2372 class PairMatcher {
   2373  public:
   2374   PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
   2375       : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
   2376 
   2377   template <typename PairType>
   2378   operator Matcher<PairType> () const {
   2379     return MakeMatcher(
   2380         new PairMatcherImpl<PairType>(
   2381             first_matcher_, second_matcher_));
   2382   }
   2383 
   2384  private:
   2385   const FirstMatcher first_matcher_;
   2386   const SecondMatcher second_matcher_;
   2387 
   2388   GTEST_DISALLOW_ASSIGN_(PairMatcher);
   2389 };
   2390 
   2391 // Implements ElementsAre() and ElementsAreArray().
   2392 template <typename Container>
   2393 class ElementsAreMatcherImpl : public MatcherInterface<Container> {
   2394  public:
   2395   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
   2396   typedef internal::StlContainerView<RawContainer> View;
   2397   typedef typename View::type StlContainer;
   2398   typedef typename View::const_reference StlContainerReference;
   2399   typedef typename StlContainer::value_type Element;
   2400 
   2401   // Constructs the matcher from a sequence of element values or
   2402   // element matchers.
   2403   template <typename InputIter>
   2404   ElementsAreMatcherImpl(InputIter first, size_t a_count) {
   2405     matchers_.reserve(a_count);
   2406     InputIter it = first;
   2407     for (size_t i = 0; i != a_count; ++i, ++it) {
   2408       matchers_.push_back(MatcherCast<const Element&>(*it));
   2409     }
   2410   }
   2411 
   2412   // Describes what this matcher does.
   2413   virtual void DescribeTo(::std::ostream* os) const {
   2414     if (count() == 0) {
   2415       *os << "is empty";
   2416     } else if (count() == 1) {
   2417       *os << "has 1 element that ";
   2418       matchers_[0].DescribeTo(os);
   2419     } else {
   2420       *os << "has " << Elements(count()) << " where\n";
   2421       for (size_t i = 0; i != count(); ++i) {
   2422         *os << "element #" << i << " ";
   2423         matchers_[i].DescribeTo(os);
   2424         if (i + 1 < count()) {
   2425           *os << ",\n";
   2426         }
   2427       }
   2428     }
   2429   }
   2430 
   2431   // Describes what the negation of this matcher does.
   2432   virtual void DescribeNegationTo(::std::ostream* os) const {
   2433     if (count() == 0) {
   2434       *os << "isn't empty";
   2435       return;
   2436     }
   2437 
   2438     *os << "doesn't have " << Elements(count()) << ", or\n";
   2439     for (size_t i = 0; i != count(); ++i) {
   2440       *os << "element #" << i << " ";
   2441       matchers_[i].DescribeNegationTo(os);
   2442       if (i + 1 < count()) {
   2443         *os << ", or\n";
   2444       }
   2445     }
   2446   }
   2447 
   2448   virtual bool MatchAndExplain(Container container,
   2449                                MatchResultListener* listener) const {
   2450     StlContainerReference stl_container = View::ConstReference(container);
   2451     const size_t actual_count = stl_container.size();
   2452     if (actual_count != count()) {
   2453       // The element count doesn't match.  If the container is empty,
   2454       // there's no need to explain anything as Google Mock already
   2455       // prints the empty container.  Otherwise we just need to show
   2456       // how many elements there actually are.
   2457       if (actual_count != 0) {
   2458         *listener << "which has " << Elements(actual_count);
   2459       }
   2460       return false;
   2461     }
   2462 
   2463     typename StlContainer::const_iterator it = stl_container.begin();
   2464     // explanations[i] is the explanation of the element at index i.
   2465     std::vector<internal::string> explanations(count());
   2466     for (size_t i = 0; i != count();  ++it, ++i) {
   2467       StringMatchResultListener s;
   2468       if (matchers_[i].MatchAndExplain(*it, &s)) {
   2469         explanations[i] = s.str();
   2470       } else {
   2471         // The container has the right size but the i-th element
   2472         // doesn't match its expectation.
   2473         *listener << "whose element #" << i << " doesn't match";
   2474         PrintIfNotEmpty(s.str(), listener->stream());
   2475         return false;
   2476       }
   2477     }
   2478 
   2479     // Every element matches its expectation.  We need to explain why
   2480     // (the obvious ones can be skipped).
   2481     bool reason_printed = false;
   2482     for (size_t i = 0; i != count(); ++i) {
   2483       const internal::string& s = explanations[i];
   2484       if (!s.empty()) {
   2485         if (reason_printed) {
   2486           *listener << ",\nand ";
   2487         }
   2488         *listener << "whose element #" << i << " matches, " << s;
   2489         reason_printed = true;
   2490       }
   2491     }
   2492 
   2493     return true;
   2494   }
   2495 
   2496  private:
   2497   static Message Elements(size_t count) {
   2498     return Message() << count << (count == 1 ? " element" : " elements");
   2499   }
   2500 
   2501   size_t count() const { return matchers_.size(); }
   2502   std::vector<Matcher<const Element&> > matchers_;
   2503 
   2504   GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
   2505 };
   2506 
   2507 // Implements ElementsAre() of 0 arguments.
   2508 class ElementsAreMatcher0 {
   2509  public:
   2510   ElementsAreMatcher0() {}
   2511 
   2512   template <typename Container>
   2513   operator Matcher<Container>() const {
   2514     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
   2515     typedef typename internal::StlContainerView<RawContainer>::type::value_type
   2516         Element;
   2517 
   2518     const Matcher<const Element&>* const matchers = NULL;
   2519     return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
   2520   }
   2521 };
   2522 
   2523 // Implements ElementsAreArray().
   2524 template <typename T>
   2525 class ElementsAreArrayMatcher {
   2526  public:
   2527   ElementsAreArrayMatcher(const T* first, size_t count) :
   2528       first_(first), count_(count) {}
   2529 
   2530   template <typename Container>
   2531   operator Matcher<Container>() const {
   2532     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
   2533     typedef typename internal::StlContainerView<RawContainer>::type::value_type
   2534         Element;
   2535 
   2536     return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
   2537   }
   2538 
   2539  private:
   2540   const T* const first_;
   2541   const size_t count_;
   2542 
   2543   GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
   2544 };
   2545 
   2546 // Returns the description for a matcher defined using the MATCHER*()
   2547 // macro where the user-supplied description string is "", if
   2548 // 'negation' is false; otherwise returns the description of the
   2549 // negation of the matcher.  'param_values' contains a list of strings
   2550 // that are the print-out of the matcher's parameters.
   2551 string FormatMatcherDescription(bool negation, const char* matcher_name,
   2552                                 const Strings& param_values);
   2553 
   2554 }  // namespace internal
   2555 
   2556 // Implements MatcherCast().
   2557 template <typename T, typename M>
   2558 inline Matcher<T> MatcherCast(M matcher) {
   2559   return internal::MatcherCastImpl<T, M>::Cast(matcher);
   2560 }
   2561 
   2562 // _ is a matcher that matches anything of any type.
   2563 //
   2564 // This definition is fine as:
   2565 //
   2566 //   1. The C++ standard permits using the name _ in a namespace that
   2567 //      is not the global namespace or ::std.
   2568 //   2. The AnythingMatcher class has no data member or constructor,
   2569 //      so it's OK to create global variables of this type.
   2570 //   3. c-style has approved of using _ in this case.
   2571 const internal::AnythingMatcher _ = {};
   2572 // Creates a matcher that matches any value of the given type T.
   2573 template <typename T>
   2574 inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
   2575 
   2576 // Creates a matcher that matches any value of the given type T.
   2577 template <typename T>
   2578 inline Matcher<T> An() { return A<T>(); }
   2579 
   2580 // Creates a polymorphic matcher that matches anything equal to x.
   2581 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
   2582 // wouldn't compile.
   2583 template <typename T>
   2584 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
   2585 
   2586 // Constructs a Matcher<T> from a 'value' of type T.  The constructed
   2587 // matcher matches any value that's equal to 'value'.
   2588 template <typename T>
   2589 Matcher<T>::Matcher(T value) { *this = Eq(value); }
   2590 
   2591 // Creates a monomorphic matcher that matches anything with type Lhs
   2592 // and equal to rhs.  A user may need to use this instead of Eq(...)
   2593 // in order to resolve an overloading ambiguity.
   2594 //
   2595 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
   2596 // or Matcher<T>(x), but more readable than the latter.
   2597 //
   2598 // We could define similar monomorphic matchers for other comparison
   2599 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
   2600 // it yet as those are used much less than Eq() in practice.  A user
   2601 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
   2602 // for example.
   2603 template <typename Lhs, typename Rhs>
   2604 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
   2605 
   2606 // Creates a polymorphic matcher that matches anything >= x.
   2607 template <typename Rhs>
   2608 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
   2609   return internal::GeMatcher<Rhs>(x);
   2610 }
   2611 
   2612 // Creates a polymorphic matcher that matches anything > x.
   2613 template <typename Rhs>
   2614 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
   2615   return internal::GtMatcher<Rhs>(x);
   2616 }
   2617 
   2618 // Creates a polymorphic matcher that matches anything <= x.
   2619 template <typename Rhs>
   2620 inline internal::LeMatcher<Rhs> Le(Rhs x) {
   2621   return internal::LeMatcher<Rhs>(x);
   2622 }
   2623 
   2624 // Creates a polymorphic matcher that matches anything < x.
   2625 template <typename Rhs>
   2626 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
   2627   return internal::LtMatcher<Rhs>(x);
   2628 }
   2629 
   2630 // Creates a polymorphic matcher that matches anything != x.
   2631 template <typename Rhs>
   2632 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
   2633   return internal::NeMatcher<Rhs>(x);
   2634 }
   2635 
   2636 // Creates a polymorphic matcher that matches any NULL pointer.
   2637 inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
   2638   return MakePolymorphicMatcher(internal::IsNullMatcher());
   2639 }
   2640 
   2641 // Creates a polymorphic matcher that matches any non-NULL pointer.
   2642 // This is convenient as Not(NULL) doesn't compile (the compiler
   2643 // thinks that that expression is comparing a pointer with an integer).
   2644 inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
   2645   return MakePolymorphicMatcher(internal::NotNullMatcher());
   2646 }
   2647 
   2648 // Creates a polymorphic matcher that matches any argument that
   2649 // references variable x.
   2650 template <typename T>
   2651 inline internal::RefMatcher<T&> Ref(T& x) {  // NOLINT
   2652   return internal::RefMatcher<T&>(x);
   2653 }
   2654 
   2655 // Creates a matcher that matches any double argument approximately
   2656 // equal to rhs, where two NANs are considered unequal.
   2657 inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
   2658   return internal::FloatingEqMatcher<double>(rhs, false);
   2659 }
   2660 
   2661 // Creates a matcher that matches any double argument approximately
   2662 // equal to rhs, including NaN values when rhs is NaN.
   2663 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
   2664   return internal::FloatingEqMatcher<double>(rhs, true);
   2665 }
   2666 
   2667 // Creates a matcher that matches any float argument approximately
   2668 // equal to rhs, where two NANs are considered unequal.
   2669 inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
   2670   return internal::FloatingEqMatcher<float>(rhs, false);
   2671 }
   2672 
   2673 // Creates a matcher that matches any double argument approximately
   2674 // equal to rhs, including NaN values when rhs is NaN.
   2675 inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
   2676   return internal::FloatingEqMatcher<float>(rhs, true);
   2677 }
   2678 
   2679 // Creates a matcher that matches a pointer (raw or smart) that points
   2680 // to a value that matches inner_matcher.
   2681 template <typename InnerMatcher>
   2682 inline internal::PointeeMatcher<InnerMatcher> Pointee(
   2683     const InnerMatcher& inner_matcher) {
   2684   return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
   2685 }
   2686 
   2687 // Creates a matcher that matches an object whose given field matches
   2688 // 'matcher'.  For example,
   2689 //   Field(&Foo::number, Ge(5))
   2690 // matches a Foo object x iff x.number >= 5.
   2691 template <typename Class, typename FieldType, typename FieldMatcher>
   2692 inline PolymorphicMatcher<
   2693   internal::FieldMatcher<Class, FieldType> > Field(
   2694     FieldType Class::*field, const FieldMatcher& matcher) {
   2695   return MakePolymorphicMatcher(
   2696       internal::FieldMatcher<Class, FieldType>(
   2697           field, MatcherCast<const FieldType&>(matcher)));
   2698   // The call to MatcherCast() is required for supporting inner
   2699   // matchers of compatible types.  For example, it allows
   2700   //   Field(&Foo::bar, m)
   2701   // to compile where bar is an int32 and m is a matcher for int64.
   2702 }
   2703 
   2704 // Creates a matcher that matches an object whose given property
   2705 // matches 'matcher'.  For example,
   2706 //   Property(&Foo::str, StartsWith("hi"))
   2707 // matches a Foo object x iff x.str() starts with "hi".
   2708 template <typename Class, typename PropertyType, typename PropertyMatcher>
   2709 inline PolymorphicMatcher<
   2710   internal::PropertyMatcher<Class, PropertyType> > Property(
   2711     PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
   2712   return MakePolymorphicMatcher(
   2713       internal::PropertyMatcher<Class, PropertyType>(
   2714           property,
   2715           MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
   2716   // The call to MatcherCast() is required for supporting inner
   2717   // matchers of compatible types.  For example, it allows
   2718   //   Property(&Foo::bar, m)
   2719   // to compile where bar() returns an int32 and m is a matcher for int64.
   2720 }
   2721 
   2722 // Creates a matcher that matches an object iff the result of applying
   2723 // a callable to x matches 'matcher'.
   2724 // For example,
   2725 //   ResultOf(f, StartsWith("hi"))
   2726 // matches a Foo object x iff f(x) starts with "hi".
   2727 // callable parameter can be a function, function pointer, or a functor.
   2728 // Callable has to satisfy the following conditions:
   2729 //   * It is required to keep no state affecting the results of
   2730 //     the calls on it and make no assumptions about how many calls
   2731 //     will be made. Any state it keeps must be protected from the
   2732 //     concurrent access.
   2733 //   * If it is a function object, it has to define type result_type.
   2734 //     We recommend deriving your functor classes from std::unary_function.
   2735 template <typename Callable, typename ResultOfMatcher>
   2736 internal::ResultOfMatcher<Callable> ResultOf(
   2737     Callable callable, const ResultOfMatcher& matcher) {
   2738   return internal::ResultOfMatcher<Callable>(
   2739           callable,
   2740           MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
   2741               matcher));
   2742   // The call to MatcherCast() is required for supporting inner
   2743   // matchers of compatible types.  For example, it allows
   2744   //   ResultOf(Function, m)
   2745   // to compile where Function() returns an int32 and m is a matcher for int64.
   2746 }
   2747 
   2748 // String matchers.
   2749 
   2750 // Matches a string equal to str.
   2751 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
   2752     StrEq(const internal::string& str) {
   2753   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
   2754       str, true, true));
   2755 }
   2756 
   2757 // Matches a string not equal to str.
   2758 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
   2759     StrNe(const internal::string& str) {
   2760   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
   2761       str, false, true));
   2762 }
   2763 
   2764 // Matches a string equal to str, ignoring case.
   2765 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
   2766     StrCaseEq(const internal::string& str) {
   2767   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
   2768       str, true, false));
   2769 }
   2770 
   2771 // Matches a string not equal to str, ignoring case.
   2772 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
   2773     StrCaseNe(const internal::string& str) {
   2774   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
   2775       str, false, false));
   2776 }
   2777 
   2778 // Creates a matcher that matches any string, std::string, or C string
   2779 // that contains the given substring.
   2780 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
   2781     HasSubstr(const internal::string& substring) {
   2782   return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
   2783       substring));
   2784 }
   2785 
   2786 // Matches a string that starts with 'prefix' (case-sensitive).
   2787 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
   2788     StartsWith(const internal::string& prefix) {
   2789   return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
   2790       prefix));
   2791 }
   2792 
   2793 // Matches a string that ends with 'suffix' (case-sensitive).
   2794 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
   2795     EndsWith(const internal::string& suffix) {
   2796   return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
   2797       suffix));
   2798 }
   2799 
   2800 // Matches a string that fully matches regular expression 'regex'.
   2801 // The matcher takes ownership of 'regex'.
   2802 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
   2803     const internal::RE* regex) {
   2804   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
   2805 }
   2806 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
   2807     const internal::string& regex) {
   2808   return MatchesRegex(new internal::RE(regex));
   2809 }
   2810 
   2811 // Matches a string that contains regular expression 'regex'.
   2812 // The matcher takes ownership of 'regex'.
   2813 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
   2814     const internal::RE* regex) {
   2815   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
   2816 }
   2817 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
   2818     const internal::string& regex) {
   2819   return ContainsRegex(new internal::RE(regex));
   2820 }
   2821 
   2822 #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
   2823 // Wide string matchers.
   2824 
   2825 // Matches a string equal to str.
   2826 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
   2827     StrEq(const internal::wstring& str) {
   2828   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
   2829       str, true, true));
   2830 }
   2831 
   2832 // Matches a string not equal to str.
   2833 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
   2834     StrNe(const internal::wstring& str) {
   2835   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
   2836       str, false, true));
   2837 }
   2838 
   2839 // Matches a string equal to str, ignoring case.
   2840 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
   2841     StrCaseEq(const internal::wstring& str) {
   2842   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
   2843       str, true, false));
   2844 }
   2845 
   2846 // Matches a string not equal to str, ignoring case.
   2847 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
   2848     StrCaseNe(const internal::wstring& str) {
   2849   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
   2850       str, false, false));
   2851 }
   2852 
   2853 // Creates a matcher that matches any wstring, std::wstring, or C wide string
   2854 // that contains the given substring.
   2855 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
   2856     HasSubstr(const internal::wstring& substring) {
   2857   return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
   2858       substring));
   2859 }
   2860 
   2861 // Matches a string that starts with 'prefix' (case-sensitive).
   2862 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
   2863     StartsWith(const internal::wstring& prefix) {
   2864   return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
   2865       prefix));
   2866 }
   2867 
   2868 // Matches a string that ends with 'suffix' (case-sensitive).
   2869 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
   2870     EndsWith(const internal::wstring& suffix) {
   2871   return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
   2872       suffix));
   2873 }
   2874 
   2875 #endif  // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
   2876 
   2877 // Creates a polymorphic matcher that matches a 2-tuple where the
   2878 // first field == the second field.
   2879 inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
   2880 
   2881 // Creates a polymorphic matcher that matches a 2-tuple where the
   2882 // first field >= the second field.
   2883 inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
   2884 
   2885 // Creates a polymorphic matcher that matches a 2-tuple where the
   2886 // first field > the second field.
   2887 inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
   2888 
   2889 // Creates a polymorphic matcher that matches a 2-tuple where the
   2890 // first field <= the second field.
   2891 inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
   2892 
   2893 // Creates a polymorphic matcher that matches a 2-tuple where the
   2894 // first field < the second field.
   2895 inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
   2896 
   2897 // Creates a polymorphic matcher that matches a 2-tuple where the
   2898 // first field != the second field.
   2899 inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
   2900 
   2901 // Creates a matcher that matches any value of type T that m doesn't
   2902 // match.
   2903 template <typename InnerMatcher>
   2904 inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
   2905   return internal::NotMatcher<InnerMatcher>(m);
   2906 }
   2907 
   2908 // Returns a matcher that matches anything that satisfies the given
   2909 // predicate.  The predicate can be any unary function or functor
   2910 // whose return type can be implicitly converted to bool.
   2911 template <typename Predicate>
   2912 inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
   2913 Truly(Predicate pred) {
   2914   return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
   2915 }
   2916 
   2917 // Returns a matcher that matches an equal container.
   2918 // This matcher behaves like Eq(), but in the event of mismatch lists the
   2919 // values that are included in one container but not the other. (Duplicate
   2920 // values and order differences are not explained.)
   2921 template <typename Container>
   2922 inline PolymorphicMatcher<internal::ContainerEqMatcher<  // NOLINT
   2923                             GTEST_REMOVE_CONST_(Container)> >
   2924     ContainerEq(const Container& rhs) {
   2925   // This following line is for working around a bug in MSVC 8.0,
   2926   // which causes Container to be a const type sometimes.
   2927   typedef GTEST_REMOVE_CONST_(Container) RawContainer;
   2928   return MakePolymorphicMatcher(
   2929       internal::ContainerEqMatcher<RawContainer>(rhs));
   2930 }
   2931 
   2932 // Matches an STL-style container or a native array that contains the
   2933 // same number of elements as in rhs, where its i-th element and rhs's
   2934 // i-th element (as a pair) satisfy the given pair matcher, for all i.
   2935 // TupleMatcher must be able to be safely cast to Matcher<tuple<const
   2936 // T1&, const T2&> >, where T1 and T2 are the types of elements in the
   2937 // LHS container and the RHS container respectively.
   2938 template <typename TupleMatcher, typename Container>
   2939 inline internal::PointwiseMatcher<TupleMatcher,
   2940                                   GTEST_REMOVE_CONST_(Container)>
   2941 Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
   2942   // This following line is for working around a bug in MSVC 8.0,
   2943   // which causes Container to be a const type sometimes.
   2944   typedef GTEST_REMOVE_CONST_(Container) RawContainer;
   2945   return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
   2946       tuple_matcher, rhs);
   2947 }
   2948 
   2949 // Matches an STL-style container or a native array that contains at
   2950 // least one element matching the given value or matcher.
   2951 //
   2952 // Examples:
   2953 //   ::std::set<int> page_ids;
   2954 //   page_ids.insert(3);
   2955 //   page_ids.insert(1);
   2956 //   EXPECT_THAT(page_ids, Contains(1));
   2957 //   EXPECT_THAT(page_ids, Contains(Gt(2)));
   2958 //   EXPECT_THAT(page_ids, Not(Contains(4)));
   2959 //
   2960 //   ::std::map<int, size_t> page_lengths;
   2961 //   page_lengths[1] = 100;
   2962 //   EXPECT_THAT(page_lengths,
   2963 //               Contains(::std::pair<const int, size_t>(1, 100)));
   2964 //
   2965 //   const char* user_ids[] = { "joe", "mike", "tom" };
   2966 //   EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
   2967 template <typename M>
   2968 inline internal::ContainsMatcher<M> Contains(M matcher) {
   2969   return internal::ContainsMatcher<M>(matcher);
   2970 }
   2971 
   2972 // Matches an STL-style container or a native array that contains only
   2973 // elements matching the given value or matcher.
   2974 //
   2975 // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
   2976 // the messages are different.
   2977 //
   2978 // Examples:
   2979 //   ::std::set<int> page_ids;
   2980 //   // Each(m) matches an empty container, regardless of what m is.
   2981 //   EXPECT_THAT(page_ids, Each(Eq(1)));
   2982 //   EXPECT_THAT(page_ids, Each(Eq(77)));
   2983 //
   2984 //   page_ids.insert(3);
   2985 //   EXPECT_THAT(page_ids, Each(Gt(0)));
   2986 //   EXPECT_THAT(page_ids, Not(Each(Gt(4))));
   2987 //   page_ids.insert(1);
   2988 //   EXPECT_THAT(page_ids, Not(Each(Lt(2))));
   2989 //
   2990 //   ::std::map<int, size_t> page_lengths;
   2991 //   page_lengths[1] = 100;
   2992 //   page_lengths[2] = 200;
   2993 //   page_lengths[3] = 300;
   2994 //   EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
   2995 //   EXPECT_THAT(page_lengths, Each(Key(Le(3))));
   2996 //
   2997 //   const char* user_ids[] = { "joe", "mike", "tom" };
   2998 //   EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
   2999 template <typename M>
   3000 inline internal::EachMatcher<M> Each(M matcher) {
   3001   return internal::EachMatcher<M>(matcher);
   3002 }
   3003 
   3004 // Key(inner_matcher) matches an std::pair whose 'first' field matches
   3005 // inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
   3006 // std::map that contains at least one element whose key is >= 5.
   3007 template <typename M>
   3008 inline internal::KeyMatcher<M> Key(M inner_matcher) {
   3009   return internal::KeyMatcher<M>(inner_matcher);
   3010 }
   3011 
   3012 // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
   3013 // matches first_matcher and whose 'second' field matches second_matcher.  For
   3014 // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
   3015 // to match a std::map<int, string> that contains exactly one element whose key
   3016 // is >= 5 and whose value equals "foo".
   3017 template <typename FirstMatcher, typename SecondMatcher>
   3018 inline internal::PairMatcher<FirstMatcher, SecondMatcher>
   3019 Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
   3020   return internal::PairMatcher<FirstMatcher, SecondMatcher>(
   3021       first_matcher, second_matcher);
   3022 }
   3023 
   3024 // Returns a predicate that is satisfied by anything that matches the
   3025 // given matcher.
   3026 template <typename M>
   3027 inline internal::MatcherAsPredicate<M> Matches(M matcher) {
   3028   return internal::MatcherAsPredicate<M>(matcher);
   3029 }
   3030 
   3031 // Returns true iff the value matches the matcher.
   3032 template <typename T, typename M>
   3033 inline bool Value(const T& value, M matcher) {
   3034   return testing::Matches(matcher)(value);
   3035 }
   3036 
   3037 // Matches the value against the given matcher and explains the match
   3038 // result to listener.
   3039 template <typename T, typename M>
   3040 inline bool ExplainMatchResult(
   3041     M matcher, const T& value, MatchResultListener* listener) {
   3042   return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
   3043 }
   3044 
   3045 // AllArgs(m) is a synonym of m.  This is useful in
   3046 //
   3047 //   EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
   3048 //
   3049 // which is easier to read than
   3050 //
   3051 //   EXPECT_CALL(foo, Bar(_, _)).With(Eq());
   3052 template <typename InnerMatcher>
   3053 inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
   3054 
   3055 // These macros allow using matchers to check values in Google Test
   3056 // tests.  ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
   3057 // succeed iff the value matches the matcher.  If the assertion fails,
   3058 // the value and the description of the matcher will be printed.
   3059 #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
   3060     ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
   3061 #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
   3062     ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
   3063 
   3064 }  // namespace testing
   3065 
   3066 #endif  // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
   3067