PageRenderTime 91ms CodeModel.GetById 22ms app.highlight 54ms RepoModel.GetById 1ms app.codeStats 1ms

/testlibs/gmock/include/gmock/gmock-matchers.h

https://github.com/deltaforge/nebu-app-mongo
C Header | 3066 lines | 1846 code | 427 blank | 793 comment | 142 complexity | 0993f8cc8b4762f2903ce55c8ea73ade MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1// Copyright 2007, Google Inc.
   2// All rights reserved.
   3//
   4// Redistribution and use in source and binary forms, with or without
   5// modification, are permitted provided that the following conditions are
   6// met:
   7//
   8//     * Redistributions of source code must retain the above copyright
   9// notice, this list of conditions and the following disclaimer.
  10//     * Redistributions in binary form must reproduce the above
  11// copyright notice, this list of conditions and the following disclaimer
  12// in the documentation and/or other materials provided with the
  13// distribution.
  14//     * Neither the name of Google Inc. nor the names of its
  15// contributors may be used to endorse or promote products derived from
  16// this software without specific prior written permission.
  17//
  18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29//
  30// Author: wan@google.com (Zhanyong Wan)
  31
  32// Google Mock - a framework for writing C++ mock classes.
  33//
  34// This file implements some commonly used argument matchers.  More
  35// matchers can be defined by the user implementing the
  36// MatcherInterface<T> interface if necessary.
  37
  38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
  39#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
  40
  41#include <algorithm>
  42#include <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
  53namespace 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@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'.
  74class 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
 105inline MatchResultListener::~MatchResultListener() {
 106}
 107
 108// The implementation of a matcher.
 109template <typename T>
 110class 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
 150namespace internal {
 151
 152// A match result listener that ignores the explanation.
 153class 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.
 164class 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.
 174class 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.
 190template <typename T>
 191class 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!
 250template <typename T>
 251class 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.
 270template <>
 271class 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
 287template <>
 288class 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.
 316template <class Impl>
 317class 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);
 370template <typename T>
 371inline 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);
 382template <class Impl>
 383inline 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.
 391template <typename T, typename M>
 392Matcher<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.
 401template <typename T>
 402class 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
 444template <typename T, typename M>
 445inline 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.
 450template <typename T>
 451Matcher<T> A();
 452
 453// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
 454// and MUST NOT BE USED IN USER CODE!!!
 455namespace internal {
 456
 457// If the explanation is not empty, prints it to the ostream.
 458inline 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.
 468inline 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.
 480template <typename Value, typename T>
 481bool 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.
 505template <size_t N>
 506class 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.
 559template <>
 560class 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.
 579template <typename MatcherTuple, typename ValueTuple>
 580bool 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.
 594template <typename MatcherTuple, typename ValueTuple>
 595void 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)).
 612template <typename T, typename M>
 613class 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.
 623template <typename T, typename U>
 624class 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.
 658template <typename T>
 659class MatcherCastImpl<T, Matcher<T> > {
 660 public:
 661  static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
 662};
 663
 664// Implements A<T>().
 665template <typename T>
 666class 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.
 683class 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.
 738GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
 739GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
 740GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
 741GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
 742GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
 743GMOCK_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.
 749class 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.
 765class 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.
 792template <typename T>
 793class RefMatcher;
 794
 795template <typename T>
 796class 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.
 854inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
 855  return String::CaseInsensitiveCStringEquals(lhs, rhs);
 856}
 857
 858inline 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.
 865template <typename StringType>
 866bool 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.
 889template <typename StringType>
 890class 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.
 943template <typename StringType>
 944class 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.
 984template <typename StringType>
 985class 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.
1025template <typename StringType>
1026class 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.
1065class 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.
1145GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1146GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1147    Ge, >=, "a pair where the first >= the second");
1148GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1149    Gt, >, "a pair where the first > the second");
1150GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1151    Le, <=, "a pair where the first <= the second");
1152GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1153    Lt, <, "a pair where the first < the second");
1154GMOCK_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.
1162template <typename T>
1163class 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.
1188template <typename InnerMatcher>
1189class 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.
1210template <typename T>
1211class 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.
1271template <typename Matcher1, typename Matcher2>
1272class 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.
1297template <typename T>
1298class 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.
1359template <typename Matcher1, typename Matcher2>
1360class 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.
1383template <typename Predicate>
1384class 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    // Without the if-statement, MSVC sometimes warns about converting
1396    // a value to bool (warning 4800).
1397    //
1398    // We cannot write 'return !!predicate_(x);' as that doesn't work
1399    // when predicate_(x) returns a class convertible to bool but
1400    // having no operator!().
1401    if (predicate_(x))
1402      return true;
1403    return false;
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.
1422template <typename M>
1423class 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_ h

Large files files are truncated, but you can click here to view the full file