gmock-matchers.h
Go to the documentation of this file.
00001 // Copyright 2007, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 //
00030 // Author: wan@google.com (Zhanyong Wan)
00031 
00032 // Google Mock - a framework for writing C++ mock classes.
00033 //
00034 // This file implements some commonly used argument matchers.  More
00035 // matchers can be defined by the user implementing the
00036 // MatcherInterface<T> interface if necessary.
00037 
00038 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
00039 #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
00040 
00041 #include <math.h>
00042 #include <algorithm>
00043 #include <iterator>
00044 #include <limits>
00045 #include <ostream>  // NOLINT
00046 #include <sstream>
00047 #include <string>
00048 #include <utility>
00049 #include <vector>
00050 
00051 #include "gmock/internal/gmock-internal-utils.h"
00052 #include "gmock/internal/gmock-port.h"
00053 #include "gtest/gtest.h"
00054 
00055 #if GTEST_LANG_CXX11
00056 #include <initializer_list>  // NOLINT -- must be after gtest.h
00057 #endif
00058 
00059 namespace testing {
00060 
00061 // To implement a matcher Foo for type T, define:
00062 //   1. a class FooMatcherImpl that implements the
00063 //      MatcherInterface<T> interface, and
00064 //   2. a factory function that creates a Matcher<T> object from a
00065 //      FooMatcherImpl*.
00066 //
00067 // The two-level delegation design makes it possible to allow a user
00068 // to write "v" instead of "Eq(v)" where a Matcher is expected, which
00069 // is impossible if we pass matchers by pointers.  It also eases
00070 // ownership management as Matcher objects can now be copied like
00071 // plain values.
00072 
00073 // MatchResultListener is an abstract class.  Its << operator can be
00074 // used by a matcher to explain why a value matches or doesn't match.
00075 //
00076 // TODO(wan@google.com): add method
00077 //   bool InterestedInWhy(bool result) const;
00078 // to indicate whether the listener is interested in why the match
00079 // result is 'result'.
00080 class MatchResultListener {
00081  public:
00082   // Creates a listener object with the given underlying ostream.  The
00083   // listener does not own the ostream, and does not dereference it
00084   // in the constructor or destructor.
00085   explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
00086   virtual ~MatchResultListener() = 0;  // Makes this class abstract.
00087 
00088   // Streams x to the underlying ostream; does nothing if the ostream
00089   // is NULL.
00090   template <typename T>
00091   MatchResultListener& operator<<(const T& x) {
00092     if (stream_ != NULL)
00093       *stream_ << x;
00094     return *this;
00095   }
00096 
00097   // Returns the underlying ostream.
00098   ::std::ostream* stream() { return stream_; }
00099 
00100   // Returns true iff the listener is interested in an explanation of
00101   // the match result.  A matcher's MatchAndExplain() method can use
00102   // this information to avoid generating the explanation when no one
00103   // intends to hear it.
00104   bool IsInterested() const { return stream_ != NULL; }
00105 
00106  private:
00107   ::std::ostream* const stream_;
00108 
00109   GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
00110 };
00111 
00112 inline MatchResultListener::~MatchResultListener() {
00113 }
00114 
00115 // An instance of a subclass of this knows how to describe itself as a
00116 // matcher.
00117 class MatcherDescriberInterface {
00118  public:
00119   virtual ~MatcherDescriberInterface() {}
00120 
00121   // Describes this matcher to an ostream.  The function should print
00122   // a verb phrase that describes the property a value matching this
00123   // matcher should have.  The subject of the verb phrase is the value
00124   // being matched.  For example, the DescribeTo() method of the Gt(7)
00125   // matcher prints "is greater than 7".
00126   virtual void DescribeTo(::std::ostream* os) const = 0;
00127 
00128   // Describes the negation of this matcher to an ostream.  For
00129   // example, if the description of this matcher is "is greater than
00130   // 7", the negated description could be "is not greater than 7".
00131   // You are not required to override this when implementing
00132   // MatcherInterface, but it is highly advised so that your matcher
00133   // can produce good error messages.
00134   virtual void DescribeNegationTo(::std::ostream* os) const {
00135     *os << "not (";
00136     DescribeTo(os);
00137     *os << ")";
00138   }
00139 };
00140 
00141 // The implementation of a matcher.
00142 template <typename T>
00143 class MatcherInterface : public MatcherDescriberInterface {
00144  public:
00145   // Returns true iff the matcher matches x; also explains the match
00146   // result to 'listener' if necessary (see the next paragraph), in
00147   // the form of a non-restrictive relative clause ("which ...",
00148   // "whose ...", etc) that describes x.  For example, the
00149   // MatchAndExplain() method of the Pointee(...) matcher should
00150   // generate an explanation like "which points to ...".
00151   //
00152   // Implementations of MatchAndExplain() should add an explanation of
00153   // the match result *if and only if* they can provide additional
00154   // information that's not already present (or not obvious) in the
00155   // print-out of x and the matcher's description.  Whether the match
00156   // succeeds is not a factor in deciding whether an explanation is
00157   // needed, as sometimes the caller needs to print a failure message
00158   // when the match succeeds (e.g. when the matcher is used inside
00159   // Not()).
00160   //
00161   // For example, a "has at least 10 elements" matcher should explain
00162   // what the actual element count is, regardless of the match result,
00163   // as it is useful information to the reader; on the other hand, an
00164   // "is empty" matcher probably only needs to explain what the actual
00165   // size is when the match fails, as it's redundant to say that the
00166   // size is 0 when the value is already known to be empty.
00167   //
00168   // You should override this method when defining a new matcher.
00169   //
00170   // It's the responsibility of the caller (Google Mock) to guarantee
00171   // that 'listener' is not NULL.  This helps to simplify a matcher's
00172   // implementation when it doesn't care about the performance, as it
00173   // can talk to 'listener' without checking its validity first.
00174   // However, in order to implement dummy listeners efficiently,
00175   // listener->stream() may be NULL.
00176   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
00177 
00178   // Inherits these methods from MatcherDescriberInterface:
00179   //   virtual void DescribeTo(::std::ostream* os) const = 0;
00180   //   virtual void DescribeNegationTo(::std::ostream* os) const;
00181 };
00182 
00183 // A match result listener that stores the explanation in a string.
00184 class StringMatchResultListener : public MatchResultListener {
00185  public:
00186   StringMatchResultListener() : MatchResultListener(&ss_) {}
00187 
00188   // Returns the explanation accumulated so far.
00189   internal::string str() const { return ss_.str(); }
00190 
00191   // Clears the explanation accumulated so far.
00192   void Clear() { ss_.str(""); }
00193 
00194  private:
00195   ::std::stringstream ss_;
00196 
00197   GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
00198 };
00199 
00200 namespace internal {
00201 
00202 // A match result listener that ignores the explanation.
00203 class DummyMatchResultListener : public MatchResultListener {
00204  public:
00205   DummyMatchResultListener() : MatchResultListener(NULL) {}
00206 
00207  private:
00208   GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
00209 };
00210 
00211 // A match result listener that forwards the explanation to a given
00212 // ostream.  The difference between this and MatchResultListener is
00213 // that the former is concrete.
00214 class StreamMatchResultListener : public MatchResultListener {
00215  public:
00216   explicit StreamMatchResultListener(::std::ostream* os)
00217       : MatchResultListener(os) {}
00218 
00219  private:
00220   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
00221 };
00222 
00223 // An internal class for implementing Matcher<T>, which will derive
00224 // from it.  We put functionalities common to all Matcher<T>
00225 // specializations here to avoid code duplication.
00226 template <typename T>
00227 class MatcherBase {
00228  public:
00229   // Returns true iff the matcher matches x; also explains the match
00230   // result to 'listener'.
00231   bool MatchAndExplain(T x, MatchResultListener* listener) const {
00232     return impl_->MatchAndExplain(x, listener);
00233   }
00234 
00235   // Returns true iff this matcher matches x.
00236   bool Matches(T x) const {
00237     DummyMatchResultListener dummy;
00238     return MatchAndExplain(x, &dummy);
00239   }
00240 
00241   // Describes this matcher to an ostream.
00242   void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
00243 
00244   // Describes the negation of this matcher to an ostream.
00245   void DescribeNegationTo(::std::ostream* os) const {
00246     impl_->DescribeNegationTo(os);
00247   }
00248 
00249   // Explains why x matches, or doesn't match, the matcher.
00250   void ExplainMatchResultTo(T x, ::std::ostream* os) const {
00251     StreamMatchResultListener listener(os);
00252     MatchAndExplain(x, &listener);
00253   }
00254 
00255   // Returns the describer for this matcher object; retains ownership
00256   // of the describer, which is only guaranteed to be alive when
00257   // this matcher object is alive.
00258   const MatcherDescriberInterface* GetDescriber() const {
00259     return impl_.get();
00260   }
00261 
00262  protected:
00263   MatcherBase() {}
00264 
00265   // Constructs a matcher from its implementation.
00266   explicit MatcherBase(const MatcherInterface<T>* impl)
00267       : impl_(impl) {}
00268 
00269   virtual ~MatcherBase() {}
00270 
00271  private:
00272   // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
00273   // interfaces.  The former dynamically allocates a chunk of memory
00274   // to hold the reference count, while the latter tracks all
00275   // references using a circular linked list without allocating
00276   // memory.  It has been observed that linked_ptr performs better in
00277   // typical scenarios.  However, shared_ptr can out-perform
00278   // linked_ptr when there are many more uses of the copy constructor
00279   // than the default constructor.
00280   //
00281   // If performance becomes a problem, we should see if using
00282   // shared_ptr helps.
00283   ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
00284 };
00285 
00286 }  // namespace internal
00287 
00288 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
00289 // object that can check whether a value of type T matches.  The
00290 // implementation of Matcher<T> is just a linked_ptr to const
00291 // MatcherInterface<T>, so copying is fairly cheap.  Don't inherit
00292 // from Matcher!
00293 template <typename T>
00294 class Matcher : public internal::MatcherBase<T> {
00295  public:
00296   // Constructs a null matcher.  Needed for storing Matcher objects in STL
00297   // containers.  A default-constructed matcher is not yet initialized.  You
00298   // cannot use it until a valid value has been assigned to it.
00299   Matcher() {}
00300 
00301   // Constructs a matcher from its implementation.
00302   explicit Matcher(const MatcherInterface<T>* impl)
00303       : internal::MatcherBase<T>(impl) {}
00304 
00305   // Implicit constructor here allows people to write
00306   // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
00307   Matcher(T value);  // NOLINT
00308 };
00309 
00310 // The following two specializations allow the user to write str
00311 // instead of Eq(str) and "foo" instead of Eq("foo") when a string
00312 // matcher is expected.
00313 template <>
00314 class GTEST_API_ Matcher<const internal::string&>
00315     : public internal::MatcherBase<const internal::string&> {
00316  public:
00317   Matcher() {}
00318 
00319   explicit Matcher(const MatcherInterface<const internal::string&>* impl)
00320       : internal::MatcherBase<const internal::string&>(impl) {}
00321 
00322   // Allows the user to write str instead of Eq(str) sometimes, where
00323   // str is a string object.
00324   Matcher(const internal::string& s);  // NOLINT
00325 
00326   // Allows the user to write "foo" instead of Eq("foo") sometimes.
00327   Matcher(const char* s);  // NOLINT
00328 };
00329 
00330 template <>
00331 class GTEST_API_ Matcher<internal::string>
00332     : public internal::MatcherBase<internal::string> {
00333  public:
00334   Matcher() {}
00335 
00336   explicit Matcher(const MatcherInterface<internal::string>* impl)
00337       : internal::MatcherBase<internal::string>(impl) {}
00338 
00339   // Allows the user to write str instead of Eq(str) sometimes, where
00340   // str is a string object.
00341   Matcher(const internal::string& s);  // NOLINT
00342 
00343   // Allows the user to write "foo" instead of Eq("foo") sometimes.
00344   Matcher(const char* s);  // NOLINT
00345 };
00346 
00347 #if GTEST_HAS_STRING_PIECE_
00348 // The following two specializations allow the user to write str
00349 // instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece
00350 // matcher is expected.
00351 template <>
00352 class GTEST_API_ Matcher<const StringPiece&>
00353     : public internal::MatcherBase<const StringPiece&> {
00354  public:
00355   Matcher() {}
00356 
00357   explicit Matcher(const MatcherInterface<const StringPiece&>* impl)
00358       : internal::MatcherBase<const StringPiece&>(impl) {}
00359 
00360   // Allows the user to write str instead of Eq(str) sometimes, where
00361   // str is a string object.
00362   Matcher(const internal::string& s);  // NOLINT
00363 
00364   // Allows the user to write "foo" instead of Eq("foo") sometimes.
00365   Matcher(const char* s);  // NOLINT
00366 
00367   // Allows the user to pass StringPieces directly.
00368   Matcher(StringPiece s);  // NOLINT
00369 };
00370 
00371 template <>
00372 class GTEST_API_ Matcher<StringPiece>
00373     : public internal::MatcherBase<StringPiece> {
00374  public:
00375   Matcher() {}
00376 
00377   explicit Matcher(const MatcherInterface<StringPiece>* impl)
00378       : internal::MatcherBase<StringPiece>(impl) {}
00379 
00380   // Allows the user to write str instead of Eq(str) sometimes, where
00381   // str is a string object.
00382   Matcher(const internal::string& s);  // NOLINT
00383 
00384   // Allows the user to write "foo" instead of Eq("foo") sometimes.
00385   Matcher(const char* s);  // NOLINT
00386 
00387   // Allows the user to pass StringPieces directly.
00388   Matcher(StringPiece s);  // NOLINT
00389 };
00390 #endif  // GTEST_HAS_STRING_PIECE_
00391 
00392 // The PolymorphicMatcher class template makes it easy to implement a
00393 // polymorphic matcher (i.e. a matcher that can match values of more
00394 // than one type, e.g. Eq(n) and NotNull()).
00395 //
00396 // To define a polymorphic matcher, a user should provide an Impl
00397 // class that has a DescribeTo() method and a DescribeNegationTo()
00398 // method, and define a member function (or member function template)
00399 //
00400 //   bool MatchAndExplain(const Value& value,
00401 //                        MatchResultListener* listener) const;
00402 //
00403 // See the definition of NotNull() for a complete example.
00404 template <class Impl>
00405 class PolymorphicMatcher {
00406  public:
00407   explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
00408 
00409   // Returns a mutable reference to the underlying matcher
00410   // implementation object.
00411   Impl& mutable_impl() { return impl_; }
00412 
00413   // Returns an immutable reference to the underlying matcher
00414   // implementation object.
00415   const Impl& impl() const { return impl_; }
00416 
00417   template <typename T>
00418   operator Matcher<T>() const {
00419     return Matcher<T>(new MonomorphicImpl<T>(impl_));
00420   }
00421 
00422  private:
00423   template <typename T>
00424   class MonomorphicImpl : public MatcherInterface<T> {
00425    public:
00426     explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
00427 
00428     virtual void DescribeTo(::std::ostream* os) const {
00429       impl_.DescribeTo(os);
00430     }
00431 
00432     virtual void DescribeNegationTo(::std::ostream* os) const {
00433       impl_.DescribeNegationTo(os);
00434     }
00435 
00436     virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
00437       return impl_.MatchAndExplain(x, listener);
00438     }
00439 
00440    private:
00441     const Impl impl_;
00442 
00443     GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
00444   };
00445 
00446   Impl impl_;
00447 
00448   GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
00449 };
00450 
00451 // Creates a matcher from its implementation.  This is easier to use
00452 // than the Matcher<T> constructor as it doesn't require you to
00453 // explicitly write the template argument, e.g.
00454 //
00455 //   MakeMatcher(foo);
00456 // vs
00457 //   Matcher<const string&>(foo);
00458 template <typename T>
00459 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
00460   return Matcher<T>(impl);
00461 }
00462 
00463 // Creates a polymorphic matcher from its implementation.  This is
00464 // easier to use than the PolymorphicMatcher<Impl> constructor as it
00465 // doesn't require you to explicitly write the template argument, e.g.
00466 //
00467 //   MakePolymorphicMatcher(foo);
00468 // vs
00469 //   PolymorphicMatcher<TypeOfFoo>(foo);
00470 template <class Impl>
00471 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
00472   return PolymorphicMatcher<Impl>(impl);
00473 }
00474 
00475 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
00476 // and MUST NOT BE USED IN USER CODE!!!
00477 namespace internal {
00478 
00479 // The MatcherCastImpl class template is a helper for implementing
00480 // MatcherCast().  We need this helper in order to partially
00481 // specialize the implementation of MatcherCast() (C++ allows
00482 // class/struct templates to be partially specialized, but not
00483 // function templates.).
00484 
00485 // This general version is used when MatcherCast()'s argument is a
00486 // polymorphic matcher (i.e. something that can be converted to a
00487 // Matcher but is not one yet; for example, Eq(value)) or a value (for
00488 // example, "hello").
00489 template <typename T, typename M>
00490 class MatcherCastImpl {
00491  public:
00492   static Matcher<T> Cast(M polymorphic_matcher_or_value) {
00493     // M can be a polymorhic matcher, in which case we want to use
00494     // its conversion operator to create Matcher<T>.  Or it can be a value
00495     // that should be passed to the Matcher<T>'s constructor.
00496     //
00497     // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
00498     // polymorphic matcher because it'll be ambiguous if T has an implicit
00499     // constructor from M (this usually happens when T has an implicit
00500     // constructor from any type).
00501     //
00502     // It won't work to unconditionally implict_cast
00503     // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
00504     // a user-defined conversion from M to T if one exists (assuming M is
00505     // a value).
00506     return CastImpl(
00507         polymorphic_matcher_or_value,
00508         BooleanConstant<
00509             internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
00510   }
00511 
00512  private:
00513   static Matcher<T> CastImpl(M value, BooleanConstant<false>) {
00514     // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
00515     // matcher.  It must be a value then.  Use direct initialization to create
00516     // a matcher.
00517     return Matcher<T>(ImplicitCast_<T>(value));
00518   }
00519 
00520   static Matcher<T> CastImpl(M polymorphic_matcher_or_value,
00521                              BooleanConstant<true>) {
00522     // M is implicitly convertible to Matcher<T>, which means that either
00523     // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
00524     // from M.  In both cases using the implicit conversion will produce a
00525     // matcher.
00526     //
00527     // Even if T has an implicit constructor from M, it won't be called because
00528     // creating Matcher<T> would require a chain of two user-defined conversions
00529     // (first to create T from M and then to create Matcher<T> from T).
00530     return polymorphic_matcher_or_value;
00531   }
00532 };
00533 
00534 // This more specialized version is used when MatcherCast()'s argument
00535 // is already a Matcher.  This only compiles when type T can be
00536 // statically converted to type U.
00537 template <typename T, typename U>
00538 class MatcherCastImpl<T, Matcher<U> > {
00539  public:
00540   static Matcher<T> Cast(const Matcher<U>& source_matcher) {
00541     return Matcher<T>(new Impl(source_matcher));
00542   }
00543 
00544  private:
00545   class Impl : public MatcherInterface<T> {
00546    public:
00547     explicit Impl(const Matcher<U>& source_matcher)
00548         : source_matcher_(source_matcher) {}
00549 
00550     // We delegate the matching logic to the source matcher.
00551     virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
00552       return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
00553     }
00554 
00555     virtual void DescribeTo(::std::ostream* os) const {
00556       source_matcher_.DescribeTo(os);
00557     }
00558 
00559     virtual void DescribeNegationTo(::std::ostream* os) const {
00560       source_matcher_.DescribeNegationTo(os);
00561     }
00562 
00563    private:
00564     const Matcher<U> source_matcher_;
00565 
00566     GTEST_DISALLOW_ASSIGN_(Impl);
00567   };
00568 };
00569 
00570 // This even more specialized version is used for efficiently casting
00571 // a matcher to its own type.
00572 template <typename T>
00573 class MatcherCastImpl<T, Matcher<T> > {
00574  public:
00575   static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
00576 };
00577 
00578 }  // namespace internal
00579 
00580 // In order to be safe and clear, casting between different matcher
00581 // types is done explicitly via MatcherCast<T>(m), which takes a
00582 // matcher m and returns a Matcher<T>.  It compiles only when T can be
00583 // statically converted to the argument type of m.
00584 template <typename T, typename M>
00585 inline Matcher<T> MatcherCast(M matcher) {
00586   return internal::MatcherCastImpl<T, M>::Cast(matcher);
00587 }
00588 
00589 // Implements SafeMatcherCast().
00590 //
00591 // We use an intermediate class to do the actual safe casting as Nokia's
00592 // Symbian compiler cannot decide between
00593 // template <T, M> ... (M) and
00594 // template <T, U> ... (const Matcher<U>&)
00595 // for function templates but can for member function templates.
00596 template <typename T>
00597 class SafeMatcherCastImpl {
00598  public:
00599   // This overload handles polymorphic matchers and values only since
00600   // monomorphic matchers are handled by the next one.
00601   template <typename M>
00602   static inline Matcher<T> Cast(M polymorphic_matcher_or_value) {
00603     return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
00604   }
00605 
00606   // This overload handles monomorphic matchers.
00607   //
00608   // In general, if type T can be implicitly converted to type U, we can
00609   // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
00610   // contravariant): just keep a copy of the original Matcher<U>, convert the
00611   // argument from type T to U, and then pass it to the underlying Matcher<U>.
00612   // The only exception is when U is a reference and T is not, as the
00613   // underlying Matcher<U> may be interested in the argument's address, which
00614   // is not preserved in the conversion from T to U.
00615   template <typename U>
00616   static inline Matcher<T> Cast(const Matcher<U>& matcher) {
00617     // Enforce that T can be implicitly converted to U.
00618     GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
00619                           T_must_be_implicitly_convertible_to_U);
00620     // Enforce that we are not converting a non-reference type T to a reference
00621     // type U.
00622     GTEST_COMPILE_ASSERT_(
00623         internal::is_reference<T>::value || !internal::is_reference<U>::value,
00624         cannot_convert_non_referentce_arg_to_reference);
00625     // In case both T and U are arithmetic types, enforce that the
00626     // conversion is not lossy.
00627     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
00628     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
00629     const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
00630     const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
00631     GTEST_COMPILE_ASSERT_(
00632         kTIsOther || kUIsOther ||
00633         (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
00634         conversion_of_arithmetic_types_must_be_lossless);
00635     return MatcherCast<T>(matcher);
00636   }
00637 };
00638 
00639 template <typename T, typename M>
00640 inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
00641   return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
00642 }
00643 
00644 // A<T>() returns a matcher that matches any value of type T.
00645 template <typename T>
00646 Matcher<T> A();
00647 
00648 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
00649 // and MUST NOT BE USED IN USER CODE!!!
00650 namespace internal {
00651 
00652 // If the explanation is not empty, prints it to the ostream.
00653 inline void PrintIfNotEmpty(const internal::string& explanation,
00654                             ::std::ostream* os) {
00655   if (explanation != "" && os != NULL) {
00656     *os << ", " << explanation;
00657   }
00658 }
00659 
00660 // Returns true if the given type name is easy to read by a human.
00661 // This is used to decide whether printing the type of a value might
00662 // be helpful.
00663 inline bool IsReadableTypeName(const string& type_name) {
00664   // We consider a type name readable if it's short or doesn't contain
00665   // a template or function type.
00666   return (type_name.length() <= 20 ||
00667           type_name.find_first_of("<(") == string::npos);
00668 }
00669 
00670 // Matches the value against the given matcher, prints the value and explains
00671 // the match result to the listener. Returns the match result.
00672 // 'listener' must not be NULL.
00673 // Value cannot be passed by const reference, because some matchers take a
00674 // non-const argument.
00675 template <typename Value, typename T>
00676 bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
00677                           MatchResultListener* listener) {
00678   if (!listener->IsInterested()) {
00679     // If the listener is not interested, we do not need to construct the
00680     // inner explanation.
00681     return matcher.Matches(value);
00682   }
00683 
00684   StringMatchResultListener inner_listener;
00685   const bool match = matcher.MatchAndExplain(value, &inner_listener);
00686 
00687   UniversalPrint(value, listener->stream());
00688 #if GTEST_HAS_RTTI
00689   const string& type_name = GetTypeName<Value>();
00690   if (IsReadableTypeName(type_name))
00691     *listener->stream() << " (of type " << type_name << ")";
00692 #endif
00693   PrintIfNotEmpty(inner_listener.str(), listener->stream());
00694 
00695   return match;
00696 }
00697 
00698 // An internal helper class for doing compile-time loop on a tuple's
00699 // fields.
00700 template <size_t N>
00701 class TuplePrefix {
00702  public:
00703   // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
00704   // iff the first N fields of matcher_tuple matches the first N
00705   // fields of value_tuple, respectively.
00706   template <typename MatcherTuple, typename ValueTuple>
00707   static bool Matches(const MatcherTuple& matcher_tuple,
00708                       const ValueTuple& value_tuple) {
00709     using ::std::tr1::get;
00710     return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
00711         && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
00712   }
00713 
00714   // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
00715   // describes failures in matching the first N fields of matchers
00716   // against the first N fields of values.  If there is no failure,
00717   // nothing will be streamed to os.
00718   template <typename MatcherTuple, typename ValueTuple>
00719   static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
00720                                      const ValueTuple& values,
00721                                      ::std::ostream* os) {
00722     using ::std::tr1::tuple_element;
00723     using ::std::tr1::get;
00724 
00725     // First, describes failures in the first N - 1 fields.
00726     TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
00727 
00728     // Then describes the failure (if any) in the (N - 1)-th (0-based)
00729     // field.
00730     typename tuple_element<N - 1, MatcherTuple>::type matcher =
00731         get<N - 1>(matchers);
00732     typedef typename tuple_element<N - 1, ValueTuple>::type Value;
00733     Value value = get<N - 1>(values);
00734     StringMatchResultListener listener;
00735     if (!matcher.MatchAndExplain(value, &listener)) {
00736       // TODO(wan): include in the message the name of the parameter
00737       // as used in MOCK_METHOD*() when possible.
00738       *os << "  Expected arg #" << N - 1 << ": ";
00739       get<N - 1>(matchers).DescribeTo(os);
00740       *os << "\n           Actual: ";
00741       // We remove the reference in type Value to prevent the
00742       // universal printer from printing the address of value, which
00743       // isn't interesting to the user most of the time.  The
00744       // matcher's MatchAndExplain() method handles the case when
00745       // the address is interesting.
00746       internal::UniversalPrint(value, os);
00747       PrintIfNotEmpty(listener.str(), os);
00748       *os << "\n";
00749     }
00750   }
00751 };
00752 
00753 // The base case.
00754 template <>
00755 class TuplePrefix<0> {
00756  public:
00757   template <typename MatcherTuple, typename ValueTuple>
00758   static bool Matches(const MatcherTuple& /* matcher_tuple */,
00759                       const ValueTuple& /* value_tuple */) {
00760     return true;
00761   }
00762 
00763   template <typename MatcherTuple, typename ValueTuple>
00764   static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
00765                                      const ValueTuple& /* values */,
00766                                      ::std::ostream* /* os */) {}
00767 };
00768 
00769 // TupleMatches(matcher_tuple, value_tuple) returns true iff all
00770 // matchers in matcher_tuple match the corresponding fields in
00771 // value_tuple.  It is a compiler error if matcher_tuple and
00772 // value_tuple have different number of fields or incompatible field
00773 // types.
00774 template <typename MatcherTuple, typename ValueTuple>
00775 bool TupleMatches(const MatcherTuple& matcher_tuple,
00776                   const ValueTuple& value_tuple) {
00777   using ::std::tr1::tuple_size;
00778   // Makes sure that matcher_tuple and value_tuple have the same
00779   // number of fields.
00780   GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
00781                         tuple_size<ValueTuple>::value,
00782                         matcher_and_value_have_different_numbers_of_fields);
00783   return TuplePrefix<tuple_size<ValueTuple>::value>::
00784       Matches(matcher_tuple, value_tuple);
00785 }
00786 
00787 // Describes failures in matching matchers against values.  If there
00788 // is no failure, nothing will be streamed to os.
00789 template <typename MatcherTuple, typename ValueTuple>
00790 void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
00791                                 const ValueTuple& values,
00792                                 ::std::ostream* os) {
00793   using ::std::tr1::tuple_size;
00794   TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
00795       matchers, values, os);
00796 }
00797 
00798 // TransformTupleValues and its helper.
00799 //
00800 // TransformTupleValuesHelper hides the internal machinery that
00801 // TransformTupleValues uses to implement a tuple traversal.
00802 template <typename Tuple, typename Func, typename OutIter>
00803 class TransformTupleValuesHelper {
00804  private:
00805   typedef typename ::std::tr1::tuple_size<Tuple> TupleSize;
00806 
00807  public:
00808   // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
00809   // Returns the final value of 'out' in case the caller needs it.
00810   static OutIter Run(Func f, const Tuple& t, OutIter out) {
00811     return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
00812   }
00813 
00814  private:
00815   template <typename Tup, size_t kRemainingSize>
00816   struct IterateOverTuple {
00817     OutIter operator() (Func f, const Tup& t, OutIter out) const {
00818       *out++ = f(::std::tr1::get<TupleSize::value - kRemainingSize>(t));
00819       return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
00820     }
00821   };
00822   template <typename Tup>
00823   struct IterateOverTuple<Tup, 0> {
00824     OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
00825       return out;
00826     }
00827   };
00828 };
00829 
00830 // Successively invokes 'f(element)' on each element of the tuple 't',
00831 // appending each result to the 'out' iterator. Returns the final value
00832 // of 'out'.
00833 template <typename Tuple, typename Func, typename OutIter>
00834 OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
00835   return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
00836 }
00837 
00838 // Implements A<T>().
00839 template <typename T>
00840 class AnyMatcherImpl : public MatcherInterface<T> {
00841  public:
00842   virtual bool MatchAndExplain(
00843       T /* x */, MatchResultListener* /* listener */) const { return true; }
00844   virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
00845   virtual void DescribeNegationTo(::std::ostream* os) const {
00846     // This is mostly for completeness' safe, as it's not very useful
00847     // to write Not(A<bool>()).  However we cannot completely rule out
00848     // such a possibility, and it doesn't hurt to be prepared.
00849     *os << "never matches";
00850   }
00851 };
00852 
00853 // Implements _, a matcher that matches any value of any
00854 // type.  This is a polymorphic matcher, so we need a template type
00855 // conversion operator to make it appearing as a Matcher<T> for any
00856 // type T.
00857 class AnythingMatcher {
00858  public:
00859   template <typename T>
00860   operator Matcher<T>() const { return A<T>(); }
00861 };
00862 
00863 // Implements a matcher that compares a given value with a
00864 // pre-supplied value using one of the ==, <=, <, etc, operators.  The
00865 // two values being compared don't have to have the same type.
00866 //
00867 // The matcher defined here is polymorphic (for example, Eq(5) can be
00868 // used to match an int, a short, a double, etc).  Therefore we use
00869 // a template type conversion operator in the implementation.
00870 //
00871 // We define this as a macro in order to eliminate duplicated source
00872 // code.
00873 //
00874 // The following template definition assumes that the Rhs parameter is
00875 // a "bare" type (i.e. neither 'const T' nor 'T&').
00876 #define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
00877     name, op, relation, negated_relation) \
00878   template <typename Rhs> class name##Matcher { \
00879    public: \
00880     explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
00881     template <typename Lhs> \
00882     operator Matcher<Lhs>() const { \
00883       return MakeMatcher(new Impl<Lhs>(rhs_)); \
00884     } \
00885    private: \
00886     template <typename Lhs> \
00887     class Impl : public MatcherInterface<Lhs> { \
00888      public: \
00889       explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
00890       virtual bool MatchAndExplain(\
00891           Lhs lhs, MatchResultListener* /* listener */) const { \
00892         return lhs op rhs_; \
00893       } \
00894       virtual void DescribeTo(::std::ostream* os) const { \
00895         *os << relation  " "; \
00896         UniversalPrint(rhs_, os); \
00897       } \
00898       virtual void DescribeNegationTo(::std::ostream* os) const { \
00899         *os << negated_relation  " "; \
00900         UniversalPrint(rhs_, os); \
00901       } \
00902      private: \
00903       Rhs rhs_; \
00904       GTEST_DISALLOW_ASSIGN_(Impl); \
00905     }; \
00906     Rhs rhs_; \
00907     GTEST_DISALLOW_ASSIGN_(name##Matcher); \
00908   }
00909 
00910 // Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
00911 // respectively.
00912 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
00913 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
00914 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
00915 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
00916 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
00917 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
00918 
00919 #undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
00920 
00921 // Implements the polymorphic IsNull() matcher, which matches any raw or smart
00922 // pointer that is NULL.
00923 class IsNullMatcher {
00924  public:
00925   template <typename Pointer>
00926   bool MatchAndExplain(const Pointer& p,
00927                        MatchResultListener* /* listener */) const {
00928     return GetRawPointer(p) == NULL;
00929   }
00930 
00931   void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
00932   void DescribeNegationTo(::std::ostream* os) const {
00933     *os << "isn't NULL";
00934   }
00935 };
00936 
00937 // Implements the polymorphic NotNull() matcher, which matches any raw or smart
00938 // pointer that is not NULL.
00939 class NotNullMatcher {
00940  public:
00941   template <typename Pointer>
00942   bool MatchAndExplain(const Pointer& p,
00943                        MatchResultListener* /* listener */) const {
00944     return GetRawPointer(p) != NULL;
00945   }
00946 
00947   void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
00948   void DescribeNegationTo(::std::ostream* os) const {
00949     *os << "is NULL";
00950   }
00951 };
00952 
00953 // Ref(variable) matches any argument that is a reference to
00954 // 'variable'.  This matcher is polymorphic as it can match any
00955 // super type of the type of 'variable'.
00956 //
00957 // The RefMatcher template class implements Ref(variable).  It can
00958 // only be instantiated with a reference type.  This prevents a user
00959 // from mistakenly using Ref(x) to match a non-reference function
00960 // argument.  For example, the following will righteously cause a
00961 // compiler error:
00962 //
00963 //   int n;
00964 //   Matcher<int> m1 = Ref(n);   // This won't compile.
00965 //   Matcher<int&> m2 = Ref(n);  // This will compile.
00966 template <typename T>
00967 class RefMatcher;
00968 
00969 template <typename T>
00970 class RefMatcher<T&> {
00971   // Google Mock is a generic framework and thus needs to support
00972   // mocking any function types, including those that take non-const
00973   // reference arguments.  Therefore the template parameter T (and
00974   // Super below) can be instantiated to either a const type or a
00975   // non-const type.
00976  public:
00977   // RefMatcher() takes a T& instead of const T&, as we want the
00978   // compiler to catch using Ref(const_value) as a matcher for a
00979   // non-const reference.
00980   explicit RefMatcher(T& x) : object_(x) {}  // NOLINT
00981 
00982   template <typename Super>
00983   operator Matcher<Super&>() const {
00984     // By passing object_ (type T&) to Impl(), which expects a Super&,
00985     // we make sure that Super is a super type of T.  In particular,
00986     // this catches using Ref(const_value) as a matcher for a
00987     // non-const reference, as you cannot implicitly convert a const
00988     // reference to a non-const reference.
00989     return MakeMatcher(new Impl<Super>(object_));
00990   }
00991 
00992  private:
00993   template <typename Super>
00994   class Impl : public MatcherInterface<Super&> {
00995    public:
00996     explicit Impl(Super& x) : object_(x) {}  // NOLINT
00997 
00998     // MatchAndExplain() takes a Super& (as opposed to const Super&)
00999     // in order to match the interface MatcherInterface<Super&>.
01000     virtual bool MatchAndExplain(
01001         Super& x, MatchResultListener* listener) const {
01002       *listener << "which is located @" << static_cast<const void*>(&x);
01003       return &x == &object_;
01004     }
01005 
01006     virtual void DescribeTo(::std::ostream* os) const {
01007       *os << "references the variable ";
01008       UniversalPrinter<Super&>::Print(object_, os);
01009     }
01010 
01011     virtual void DescribeNegationTo(::std::ostream* os) const {
01012       *os << "does not reference the variable ";
01013       UniversalPrinter<Super&>::Print(object_, os);
01014     }
01015 
01016    private:
01017     const Super& object_;
01018 
01019     GTEST_DISALLOW_ASSIGN_(Impl);
01020   };
01021 
01022   T& object_;
01023 
01024   GTEST_DISALLOW_ASSIGN_(RefMatcher);
01025 };
01026 
01027 // Polymorphic helper functions for narrow and wide string matchers.
01028 inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
01029   return String::CaseInsensitiveCStringEquals(lhs, rhs);
01030 }
01031 
01032 inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
01033                                          const wchar_t* rhs) {
01034   return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
01035 }
01036 
01037 // String comparison for narrow or wide strings that can have embedded NUL
01038 // characters.
01039 template <typename StringType>
01040 bool CaseInsensitiveStringEquals(const StringType& s1,
01041                                  const StringType& s2) {
01042   // Are the heads equal?
01043   if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
01044     return false;
01045   }
01046 
01047   // Skip the equal heads.
01048   const typename StringType::value_type nul = 0;
01049   const size_t i1 = s1.find(nul), i2 = s2.find(nul);
01050 
01051   // Are we at the end of either s1 or s2?
01052   if (i1 == StringType::npos || i2 == StringType::npos) {
01053     return i1 == i2;
01054   }
01055 
01056   // Are the tails equal?
01057   return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
01058 }
01059 
01060 // String matchers.
01061 
01062 // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
01063 template <typename StringType>
01064 class StrEqualityMatcher {
01065  public:
01066   StrEqualityMatcher(const StringType& str, bool expect_eq,
01067                      bool case_sensitive)
01068       : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
01069 
01070   // Accepts pointer types, particularly:
01071   //   const char*
01072   //   char*
01073   //   const wchar_t*
01074   //   wchar_t*
01075   template <typename CharType>
01076   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
01077     if (s == NULL) {
01078       return !expect_eq_;
01079     }
01080     return MatchAndExplain(StringType(s), listener);
01081   }
01082 
01083   // Matches anything that can convert to StringType.
01084   //
01085   // This is a template, not just a plain function with const StringType&,
01086   // because StringPiece has some interfering non-explicit constructors.
01087   template <typename MatcheeStringType>
01088   bool MatchAndExplain(const MatcheeStringType& s,
01089                        MatchResultListener* /* listener */) const {
01090     const StringType& s2(s);
01091     const bool eq = case_sensitive_ ? s2 == string_ :
01092         CaseInsensitiveStringEquals(s2, string_);
01093     return expect_eq_ == eq;
01094   }
01095 
01096   void DescribeTo(::std::ostream* os) const {
01097     DescribeToHelper(expect_eq_, os);
01098   }
01099 
01100   void DescribeNegationTo(::std::ostream* os) const {
01101     DescribeToHelper(!expect_eq_, os);
01102   }
01103 
01104  private:
01105   void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
01106     *os << (expect_eq ? "is " : "isn't ");
01107     *os << "equal to ";
01108     if (!case_sensitive_) {
01109       *os << "(ignoring case) ";
01110     }
01111     UniversalPrint(string_, os);
01112   }
01113 
01114   const StringType string_;
01115   const bool expect_eq_;
01116   const bool case_sensitive_;
01117 
01118   GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
01119 };
01120 
01121 // Implements the polymorphic HasSubstr(substring) matcher, which
01122 // can be used as a Matcher<T> as long as T can be converted to a
01123 // string.
01124 template <typename StringType>
01125 class HasSubstrMatcher {
01126  public:
01127   explicit HasSubstrMatcher(const StringType& substring)
01128       : substring_(substring) {}
01129 
01130   // Accepts pointer types, particularly:
01131   //   const char*
01132   //   char*
01133   //   const wchar_t*
01134   //   wchar_t*
01135   template <typename CharType>
01136   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
01137     return s != NULL && MatchAndExplain(StringType(s), listener);
01138   }
01139 
01140   // Matches anything that can convert to StringType.
01141   //
01142   // This is a template, not just a plain function with const StringType&,
01143   // because StringPiece has some interfering non-explicit constructors.
01144   template <typename MatcheeStringType>
01145   bool MatchAndExplain(const MatcheeStringType& s,
01146                        MatchResultListener* /* listener */) const {
01147     const StringType& s2(s);
01148     return s2.find(substring_) != StringType::npos;
01149   }
01150 
01151   // Describes what this matcher matches.
01152   void DescribeTo(::std::ostream* os) const {
01153     *os << "has substring ";
01154     UniversalPrint(substring_, os);
01155   }
01156 
01157   void DescribeNegationTo(::std::ostream* os) const {
01158     *os << "has no substring ";
01159     UniversalPrint(substring_, os);
01160   }
01161 
01162  private:
01163   const StringType substring_;
01164 
01165   GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
01166 };
01167 
01168 // Implements the polymorphic StartsWith(substring) matcher, which
01169 // can be used as a Matcher<T> as long as T can be converted to a
01170 // string.
01171 template <typename StringType>
01172 class StartsWithMatcher {
01173  public:
01174   explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
01175   }
01176 
01177   // Accepts pointer types, particularly:
01178   //   const char*
01179   //   char*
01180   //   const wchar_t*
01181   //   wchar_t*
01182   template <typename CharType>
01183   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
01184     return s != NULL && MatchAndExplain(StringType(s), listener);
01185   }
01186 
01187   // Matches anything that can convert to StringType.
01188   //
01189   // This is a template, not just a plain function with const StringType&,
01190   // because StringPiece has some interfering non-explicit constructors.
01191   template <typename MatcheeStringType>
01192   bool MatchAndExplain(const MatcheeStringType& s,
01193                        MatchResultListener* /* listener */) const {
01194     const StringType& s2(s);
01195     return s2.length() >= prefix_.length() &&
01196         s2.substr(0, prefix_.length()) == prefix_;
01197   }
01198 
01199   void DescribeTo(::std::ostream* os) const {
01200     *os << "starts with ";
01201     UniversalPrint(prefix_, os);
01202   }
01203 
01204   void DescribeNegationTo(::std::ostream* os) const {
01205     *os << "doesn't start with ";
01206     UniversalPrint(prefix_, os);
01207   }
01208 
01209  private:
01210   const StringType prefix_;
01211 
01212   GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
01213 };
01214 
01215 // Implements the polymorphic EndsWith(substring) matcher, which
01216 // can be used as a Matcher<T> as long as T can be converted to a
01217 // string.
01218 template <typename StringType>
01219 class EndsWithMatcher {
01220  public:
01221   explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
01222 
01223   // Accepts pointer types, particularly:
01224   //   const char*
01225   //   char*
01226   //   const wchar_t*
01227   //   wchar_t*
01228   template <typename CharType>
01229   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
01230     return s != NULL && MatchAndExplain(StringType(s), listener);
01231   }
01232 
01233   // Matches anything that can convert to StringType.
01234   //
01235   // This is a template, not just a plain function with const StringType&,
01236   // because StringPiece has some interfering non-explicit constructors.
01237   template <typename MatcheeStringType>
01238   bool MatchAndExplain(const MatcheeStringType& s,
01239                        MatchResultListener* /* listener */) const {
01240     const StringType& s2(s);
01241     return s2.length() >= suffix_.length() &&
01242         s2.substr(s2.length() - suffix_.length()) == suffix_;
01243   }
01244 
01245   void DescribeTo(::std::ostream* os) const {
01246     *os << "ends with ";
01247     UniversalPrint(suffix_, os);
01248   }
01249 
01250   void DescribeNegationTo(::std::ostream* os) const {
01251     *os << "doesn't end with ";
01252     UniversalPrint(suffix_, os);
01253   }
01254 
01255  private:
01256   const StringType suffix_;
01257 
01258   GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
01259 };
01260 
01261 // Implements polymorphic matchers MatchesRegex(regex) and
01262 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
01263 // T can be converted to a string.
01264 class MatchesRegexMatcher {
01265  public:
01266   MatchesRegexMatcher(const RE* regex, bool full_match)
01267       : regex_(regex), full_match_(full_match) {}
01268 
01269   // Accepts pointer types, particularly:
01270   //   const char*
01271   //   char*
01272   //   const wchar_t*
01273   //   wchar_t*
01274   template <typename CharType>
01275   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
01276     return s != NULL && MatchAndExplain(internal::string(s), listener);
01277   }
01278 
01279   // Matches anything that can convert to internal::string.
01280   //
01281   // This is a template, not just a plain function with const internal::string&,
01282   // because StringPiece has some interfering non-explicit constructors.
01283   template <class MatcheeStringType>
01284   bool MatchAndExplain(const MatcheeStringType& s,
01285                        MatchResultListener* /* listener */) const {
01286     const internal::string& s2(s);
01287     return full_match_ ? RE::FullMatch(s2, *regex_) :
01288         RE::PartialMatch(s2, *regex_);
01289   }
01290 
01291   void DescribeTo(::std::ostream* os) const {
01292     *os << (full_match_ ? "matches" : "contains")
01293         << " regular expression ";
01294     UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
01295   }
01296 
01297   void DescribeNegationTo(::std::ostream* os) const {
01298     *os << "doesn't " << (full_match_ ? "match" : "contain")
01299         << " regular expression ";
01300     UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
01301   }
01302 
01303  private:
01304   const internal::linked_ptr<const RE> regex_;
01305   const bool full_match_;
01306 
01307   GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
01308 };
01309 
01310 // Implements a matcher that compares the two fields of a 2-tuple
01311 // using one of the ==, <=, <, etc, operators.  The two fields being
01312 // compared don't have to have the same type.
01313 //
01314 // The matcher defined here is polymorphic (for example, Eq() can be
01315 // used to match a tuple<int, short>, a tuple<const long&, double>,
01316 // etc).  Therefore we use a template type conversion operator in the
01317 // implementation.
01318 //
01319 // We define this as a macro in order to eliminate duplicated source
01320 // code.
01321 #define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
01322   class name##2Matcher { \
01323    public: \
01324     template <typename T1, typename T2> \
01325     operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
01326       return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
01327     } \
01328     template <typename T1, typename T2> \
01329     operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
01330       return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
01331     } \
01332    private: \
01333     template <typename Tuple> \
01334     class Impl : public MatcherInterface<Tuple> { \
01335      public: \
01336       virtual bool MatchAndExplain( \
01337           Tuple args, \
01338           MatchResultListener* /* listener */) const { \
01339         return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
01340       } \
01341       virtual void DescribeTo(::std::ostream* os) const { \
01342         *os << "are " relation;                                 \
01343       } \
01344       virtual void DescribeNegationTo(::std::ostream* os) const { \
01345         *os << "aren't " relation; \
01346       } \
01347     }; \
01348   }
01349 
01350 // Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
01351 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
01352 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
01353     Ge, >=, "a pair where the first >= the second");
01354 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
01355     Gt, >, "a pair where the first > the second");
01356 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
01357     Le, <=, "a pair where the first <= the second");
01358 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
01359     Lt, <, "a pair where the first < the second");
01360 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
01361 
01362 #undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
01363 
01364 // Implements the Not(...) matcher for a particular argument type T.
01365 // We do not nest it inside the NotMatcher class template, as that
01366 // will prevent different instantiations of NotMatcher from sharing
01367 // the same NotMatcherImpl<T> class.
01368 template <typename T>
01369 class NotMatcherImpl : public MatcherInterface<T> {
01370  public:
01371   explicit NotMatcherImpl(const Matcher<T>& matcher)
01372       : matcher_(matcher) {}
01373 
01374   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
01375     return !matcher_.MatchAndExplain(x, listener);
01376   }
01377 
01378   virtual void DescribeTo(::std::ostream* os) const {
01379     matcher_.DescribeNegationTo(os);
01380   }
01381 
01382   virtual void DescribeNegationTo(::std::ostream* os) const {
01383     matcher_.DescribeTo(os);
01384   }
01385 
01386  private:
01387   const Matcher<T> matcher_;
01388 
01389   GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
01390 };
01391 
01392 // Implements the Not(m) matcher, which matches a value that doesn't
01393 // match matcher m.
01394 template <typename InnerMatcher>
01395 class NotMatcher {
01396  public:
01397   explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
01398 
01399   // This template type conversion operator allows Not(m) to be used
01400   // to match any type m can match.
01401   template <typename T>
01402   operator Matcher<T>() const {
01403     return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
01404   }
01405 
01406  private:
01407   InnerMatcher matcher_;
01408 
01409   GTEST_DISALLOW_ASSIGN_(NotMatcher);
01410 };
01411 
01412 // Implements the AllOf(m1, m2) matcher for a particular argument type
01413 // T. We do not nest it inside the BothOfMatcher class template, as
01414 // that will prevent different instantiations of BothOfMatcher from
01415 // sharing the same BothOfMatcherImpl<T> class.
01416 template <typename T>
01417 class BothOfMatcherImpl : public MatcherInterface<T> {
01418  public:
01419   BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
01420       : matcher1_(matcher1), matcher2_(matcher2) {}
01421 
01422   virtual void DescribeTo(::std::ostream* os) const {
01423     *os << "(";
01424     matcher1_.DescribeTo(os);
01425     *os << ") and (";
01426     matcher2_.DescribeTo(os);
01427     *os << ")";
01428   }
01429 
01430   virtual void DescribeNegationTo(::std::ostream* os) const {
01431     *os << "(";
01432     matcher1_.DescribeNegationTo(os);
01433     *os << ") or (";
01434     matcher2_.DescribeNegationTo(os);
01435     *os << ")";
01436   }
01437 
01438   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
01439     // If either matcher1_ or matcher2_ doesn't match x, we only need
01440     // to explain why one of them fails.
01441     StringMatchResultListener listener1;
01442     if (!matcher1_.MatchAndExplain(x, &listener1)) {
01443       *listener << listener1.str();
01444       return false;
01445     }
01446 
01447     StringMatchResultListener listener2;
01448     if (!matcher2_.MatchAndExplain(x, &listener2)) {
01449       *listener << listener2.str();
01450       return false;
01451     }
01452 
01453     // Otherwise we need to explain why *both* of them match.
01454     const internal::string s1 = listener1.str();
01455     const internal::string s2 = listener2.str();
01456 
01457     if (s1 == "") {
01458       *listener << s2;
01459     } else {
01460       *listener << s1;
01461       if (s2 != "") {
01462         *listener << ", and " << s2;
01463       }
01464     }
01465     return true;
01466   }
01467 
01468  private:
01469   const Matcher<T> matcher1_;
01470   const Matcher<T> matcher2_;
01471 
01472   GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
01473 };
01474 
01475 #if GTEST_LANG_CXX11
01476 // MatcherList provides mechanisms for storing a variable number of matchers in
01477 // a list structure (ListType) and creating a combining matcher from such a
01478 // list.
01479 // The template is defined recursively using the following template paramters:
01480 //   * kSize is the length of the MatcherList.
01481 //   * Head is the type of the first matcher of the list.
01482 //   * Tail denotes the types of the remaining matchers of the list.
01483 template <int kSize, typename Head, typename... Tail>
01484 struct MatcherList {
01485   typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
01486   typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
01487 
01488   // BuildList stores variadic type values in a nested pair structure.
01489   // Example:
01490   // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
01491   // the corresponding result of type pair<int, pair<string, float>>.
01492   static ListType BuildList(const Head& matcher, const Tail&... tail) {
01493     return ListType(matcher, MatcherListTail::BuildList(tail...));
01494   }
01495 
01496   // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
01497   // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
01498   // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
01499   // constructor taking two Matcher<T>s as input.
01500   template <typename T, template <typename /* T */> class CombiningMatcher>
01501   static Matcher<T> CreateMatcher(const ListType& matchers) {
01502     return Matcher<T>(new CombiningMatcher<T>(
01503         SafeMatcherCast<T>(matchers.first),
01504         MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
01505             matchers.second)));
01506   }
01507 };
01508 
01509 // The following defines the base case for the recursive definition of
01510 // MatcherList.
01511 template <typename Matcher1, typename Matcher2>
01512 struct MatcherList<2, Matcher1, Matcher2> {
01513   typedef ::std::pair<Matcher1, Matcher2> ListType;
01514 
01515   static ListType BuildList(const Matcher1& matcher1,
01516                             const Matcher2& matcher2) {
01517     return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
01518   }
01519 
01520   template <typename T, template <typename /* T */> class CombiningMatcher>
01521   static Matcher<T> CreateMatcher(const ListType& matchers) {
01522     return Matcher<T>(new CombiningMatcher<T>(
01523         SafeMatcherCast<T>(matchers.first),
01524         SafeMatcherCast<T>(matchers.second)));
01525   }
01526 };
01527 
01528 // VariadicMatcher is used for the variadic implementation of
01529 // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
01530 // CombiningMatcher<T> is used to recursively combine the provided matchers
01531 // (of type Args...).
01532 template <template <typename T> class CombiningMatcher, typename... Args>
01533 class VariadicMatcher {
01534  public:
01535   VariadicMatcher(const Args&... matchers)  // NOLINT
01536       : matchers_(MatcherListType::BuildList(matchers...)) {}
01537 
01538   // This template type conversion operator allows an
01539   // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
01540   // all of the provided matchers (Matcher1, Matcher2, ...) can match.
01541   template <typename T>
01542   operator Matcher<T>() const {
01543     return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
01544         matchers_);
01545   }
01546 
01547  private:
01548   typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
01549 
01550   const typename MatcherListType::ListType matchers_;
01551 
01552   GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
01553 };
01554 
01555 template <typename... Args>
01556 using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
01557 
01558 #endif  // GTEST_LANG_CXX11
01559 
01560 // Used for implementing the AllOf(m_1, ..., m_n) matcher, which
01561 // matches a value that matches all of the matchers m_1, ..., and m_n.
01562 template <typename Matcher1, typename Matcher2>
01563 class BothOfMatcher {
01564  public:
01565   BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
01566       : matcher1_(matcher1), matcher2_(matcher2) {}
01567 
01568   // This template type conversion operator allows a
01569   // BothOfMatcher<Matcher1, Matcher2> object to match any type that
01570   // both Matcher1 and Matcher2 can match.
01571   template <typename T>
01572   operator Matcher<T>() const {
01573     return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
01574                                                SafeMatcherCast<T>(matcher2_)));
01575   }
01576 
01577  private:
01578   Matcher1 matcher1_;
01579   Matcher2 matcher2_;
01580 
01581   GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
01582 };
01583 
01584 // Implements the AnyOf(m1, m2) matcher for a particular argument type
01585 // T.  We do not nest it inside the AnyOfMatcher class template, as
01586 // that will prevent different instantiations of AnyOfMatcher from
01587 // sharing the same EitherOfMatcherImpl<T> class.
01588 template <typename T>
01589 class EitherOfMatcherImpl : public MatcherInterface<T> {
01590  public:
01591   EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
01592       : matcher1_(matcher1), matcher2_(matcher2) {}
01593 
01594   virtual void DescribeTo(::std::ostream* os) const {
01595     *os << "(";
01596     matcher1_.DescribeTo(os);
01597     *os << ") or (";
01598     matcher2_.DescribeTo(os);
01599     *os << ")";
01600   }
01601 
01602   virtual void DescribeNegationTo(::std::ostream* os) const {
01603     *os << "(";
01604     matcher1_.DescribeNegationTo(os);
01605     *os << ") and (";
01606     matcher2_.DescribeNegationTo(os);
01607     *os << ")";
01608   }
01609 
01610   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
01611     // If either matcher1_ or matcher2_ matches x, we just need to
01612     // explain why *one* of them matches.
01613     StringMatchResultListener listener1;
01614     if (matcher1_.MatchAndExplain(x, &listener1)) {
01615       *listener << listener1.str();
01616       return true;
01617     }
01618 
01619     StringMatchResultListener listener2;
01620     if (matcher2_.MatchAndExplain(x, &listener2)) {
01621       *listener << listener2.str();
01622       return true;
01623     }
01624 
01625     // Otherwise we need to explain why *both* of them fail.
01626     const internal::string s1 = listener1.str();
01627     const internal::string s2 = listener2.str();
01628 
01629     if (s1 == "") {
01630       *listener << s2;
01631     } else {
01632       *listener << s1;
01633       if (s2 != "") {
01634         *listener << ", and " << s2;
01635       }
01636     }
01637     return false;
01638   }
01639 
01640  private:
01641   const Matcher<T> matcher1_;
01642   const Matcher<T> matcher2_;
01643 
01644   GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
01645 };
01646 
01647 #if GTEST_LANG_CXX11
01648 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
01649 template <typename... Args>
01650 using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
01651 
01652 #endif  // GTEST_LANG_CXX11
01653 
01654 // Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
01655 // matches a value that matches at least one of the matchers m_1, ...,
01656 // and m_n.
01657 template <typename Matcher1, typename Matcher2>
01658 class EitherOfMatcher {
01659  public:
01660   EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
01661       : matcher1_(matcher1), matcher2_(matcher2) {}
01662 
01663   // This template type conversion operator allows a
01664   // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
01665   // both Matcher1 and Matcher2 can match.
01666   template <typename T>
01667   operator Matcher<T>() const {
01668     return Matcher<T>(new EitherOfMatcherImpl<T>(
01669         SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
01670   }
01671 
01672  private:
01673   Matcher1 matcher1_;
01674   Matcher2 matcher2_;
01675 
01676   GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
01677 };
01678 
01679 // Used for implementing Truly(pred), which turns a predicate into a
01680 // matcher.
01681 template <typename Predicate>
01682 class TrulyMatcher {
01683  public:
01684   explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
01685 
01686   // This method template allows Truly(pred) to be used as a matcher
01687   // for type T where T is the argument type of predicate 'pred'.  The
01688   // argument is passed by reference as the predicate may be
01689   // interested in the address of the argument.
01690   template <typename T>
01691   bool MatchAndExplain(T& x,  // NOLINT
01692                        MatchResultListener* /* listener */) const {
01693     // Without the if-statement, MSVC sometimes warns about converting
01694     // a value to bool (warning 4800).
01695     //
01696     // We cannot write 'return !!predicate_(x);' as that doesn't work
01697     // when predicate_(x) returns a class convertible to bool but
01698     // having no operator!().
01699     if (predicate_(x))
01700       return true;
01701     return false;
01702   }
01703 
01704   void DescribeTo(::std::ostream* os) const {
01705     *os << "satisfies the given predicate";
01706   }
01707 
01708   void DescribeNegationTo(::std::ostream* os) const {
01709     *os << "doesn't satisfy the given predicate";
01710   }
01711 
01712  private:
01713   Predicate predicate_;
01714 
01715   GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
01716 };
01717 
01718 // Used for implementing Matches(matcher), which turns a matcher into
01719 // a predicate.
01720 template <typename M>
01721 class MatcherAsPredicate {
01722  public:
01723   explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
01724 
01725   // This template operator() allows Matches(m) to be used as a
01726   // predicate on type T where m is a matcher on type T.
01727   //
01728   // The argument x is passed by reference instead of by value, as
01729   // some matcher may be interested in its address (e.g. as in
01730   // Matches(Ref(n))(x)).
01731   template <typename T>
01732   bool operator()(const T& x) const {
01733     // We let matcher_ commit to a particular type here instead of
01734     // when the MatcherAsPredicate object was constructed.  This
01735     // allows us to write Matches(m) where m is a polymorphic matcher
01736     // (e.g. Eq(5)).
01737     //
01738     // If we write Matcher<T>(matcher_).Matches(x) here, it won't
01739     // compile when matcher_ has type Matcher<const T&>; if we write
01740     // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
01741     // when matcher_ has type Matcher<T>; if we just write
01742     // matcher_.Matches(x), it won't compile when matcher_ is
01743     // polymorphic, e.g. Eq(5).
01744     //
01745     // MatcherCast<const T&>() is necessary for making the code work
01746     // in all of the above situations.
01747     return MatcherCast<const T&>(matcher_).Matches(x);
01748   }
01749 
01750  private:
01751   M matcher_;
01752 
01753   GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
01754 };
01755 
01756 // For implementing ASSERT_THAT() and EXPECT_THAT().  The template
01757 // argument M must be a type that can be converted to a matcher.
01758 template <typename M>
01759 class PredicateFormatterFromMatcher {
01760  public:
01761   explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
01762 
01763   // This template () operator allows a PredicateFormatterFromMatcher
01764   // object to act as a predicate-formatter suitable for using with
01765   // Google Test's EXPECT_PRED_FORMAT1() macro.
01766   template <typename T>
01767   AssertionResult operator()(const char* value_text, const T& x) const {
01768     // We convert matcher_ to a Matcher<const T&> *now* instead of
01769     // when the PredicateFormatterFromMatcher object was constructed,
01770     // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
01771     // know which type to instantiate it to until we actually see the
01772     // type of x here.
01773     //
01774     // We write SafeMatcherCast<const T&>(matcher_) instead of
01775     // Matcher<const T&>(matcher_), as the latter won't compile when
01776     // matcher_ has type Matcher<T> (e.g. An<int>()).
01777     // We don't write MatcherCast<const T&> either, as that allows
01778     // potentially unsafe downcasting of the matcher argument.
01779     const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
01780     StringMatchResultListener listener;
01781     if (MatchPrintAndExplain(x, matcher, &listener))
01782       return AssertionSuccess();
01783 
01784     ::std::stringstream ss;
01785     ss << "Value of: " << value_text << "\n"
01786        << "Expected: ";
01787     matcher.DescribeTo(&ss);
01788     ss << "\n  Actual: " << listener.str();
01789     return AssertionFailure() << ss.str();
01790   }
01791 
01792  private:
01793   const M matcher_;
01794 
01795   GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
01796 };
01797 
01798 // A helper function for converting a matcher to a predicate-formatter
01799 // without the user needing to explicitly write the type.  This is
01800 // used for implementing ASSERT_THAT() and EXPECT_THAT().
01801 template <typename M>
01802 inline PredicateFormatterFromMatcher<M>
01803 MakePredicateFormatterFromMatcher(const M& matcher) {
01804   return PredicateFormatterFromMatcher<M>(matcher);
01805 }
01806 
01807 // Implements the polymorphic floating point equality matcher, which matches
01808 // two float values using ULP-based approximation or, optionally, a
01809 // user-specified epsilon.  The template is meant to be instantiated with
01810 // FloatType being either float or double.
01811 template <typename FloatType>
01812 class FloatingEqMatcher {
01813  public:
01814   // Constructor for FloatingEqMatcher.
01815   // The matcher's input will be compared with rhs.  The matcher treats two
01816   // NANs as equal if nan_eq_nan is true.  Otherwise, under IEEE standards,
01817   // equality comparisons between NANs will always return false.  We specify a
01818   // negative max_abs_error_ term to indicate that ULP-based approximation will
01819   // be used for comparison.
01820   FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
01821     rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
01822   }
01823 
01824   // Constructor that supports a user-specified max_abs_error that will be used
01825   // for comparison instead of ULP-based approximation.  The max absolute
01826   // should be non-negative.
01827   FloatingEqMatcher(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
01828     rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {
01829     GTEST_CHECK_(max_abs_error >= 0)
01830         << ", where max_abs_error is" << max_abs_error;
01831   }
01832 
01833   // Implements floating point equality matcher as a Matcher<T>.
01834   template <typename T>
01835   class Impl : public MatcherInterface<T> {
01836    public:
01837     Impl(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
01838       rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {}
01839 
01840     virtual bool MatchAndExplain(T value,
01841                                  MatchResultListener* /* listener */) const {
01842       const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
01843 
01844       // Compares NaNs first, if nan_eq_nan_ is true.
01845       if (lhs.is_nan() || rhs.is_nan()) {
01846         if (lhs.is_nan() && rhs.is_nan()) {
01847           return nan_eq_nan_;
01848         }
01849         // One is nan; the other is not nan.
01850         return false;
01851       }
01852       if (HasMaxAbsError()) {
01853         // We perform an equality check so that inf will match inf, regardless
01854         // of error bounds.  If the result of value - rhs_ would result in
01855         // overflow or if either value is inf, the default result is infinity,
01856         // which should only match if max_abs_error_ is also infinity.
01857         return value == rhs_ || fabs(value - rhs_) <= max_abs_error_;
01858       } else {
01859         return lhs.AlmostEquals(rhs);
01860       }
01861     }
01862 
01863     virtual void DescribeTo(::std::ostream* os) const {
01864       // os->precision() returns the previously set precision, which we
01865       // store to restore the ostream to its original configuration
01866       // after outputting.
01867       const ::std::streamsize old_precision = os->precision(
01868           ::std::numeric_limits<FloatType>::digits10 + 2);
01869       if (FloatingPoint<FloatType>(rhs_).is_nan()) {
01870         if (nan_eq_nan_) {
01871           *os << "is NaN";
01872         } else {
01873           *os << "never matches";
01874         }
01875       } else {
01876         *os << "is approximately " << rhs_;
01877         if (HasMaxAbsError()) {
01878           *os << " (absolute error <= " << max_abs_error_ << ")";
01879         }
01880       }
01881       os->precision(old_precision);
01882     }
01883 
01884     virtual void DescribeNegationTo(::std::ostream* os) const {
01885       // As before, get original precision.
01886       const ::std::streamsize old_precision = os->precision(
01887           ::std::numeric_limits<FloatType>::digits10 + 2);
01888       if (FloatingPoint<FloatType>(rhs_).is_nan()) {
01889         if (nan_eq_nan_) {
01890           *os << "isn't NaN";
01891         } else {
01892           *os << "is anything";
01893         }
01894       } else {
01895         *os << "isn't approximately " << rhs_;
01896         if (HasMaxAbsError()) {
01897           *os << " (absolute error > " << max_abs_error_ << ")";
01898         }
01899       }
01900       // Restore original precision.
01901       os->precision(old_precision);
01902     }
01903 
01904    private:
01905     bool HasMaxAbsError() const {
01906       return max_abs_error_ >= 0;
01907     }
01908 
01909     const FloatType rhs_;
01910     const bool nan_eq_nan_;
01911     // max_abs_error will be used for value comparison when >= 0.
01912     const FloatType max_abs_error_;
01913 
01914     GTEST_DISALLOW_ASSIGN_(Impl);
01915   };
01916 
01917   // The following 3 type conversion operators allow FloatEq(rhs) and
01918   // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
01919   // Matcher<const float&>, or a Matcher<float&>, but nothing else.
01920   // (While Google's C++ coding style doesn't allow arguments passed
01921   // by non-const reference, we may see them in code not conforming to
01922   // the style.  Therefore Google Mock needs to support them.)
01923   operator Matcher<FloatType>() const {
01924     return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_, max_abs_error_));
01925   }
01926 
01927   operator Matcher<const FloatType&>() const {
01928     return MakeMatcher(
01929         new Impl<const FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
01930   }
01931 
01932   operator Matcher<FloatType&>() const {
01933     return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
01934   }
01935 
01936  private:
01937   const FloatType rhs_;
01938   const bool nan_eq_nan_;
01939   // max_abs_error will be used for value comparison when >= 0.
01940   const FloatType max_abs_error_;
01941 
01942   GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
01943 };
01944 
01945 // Implements the Pointee(m) matcher for matching a pointer whose
01946 // pointee matches matcher m.  The pointer can be either raw or smart.
01947 template <typename InnerMatcher>
01948 class PointeeMatcher {
01949  public:
01950   explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
01951 
01952   // This type conversion operator template allows Pointee(m) to be
01953   // used as a matcher for any pointer type whose pointee type is
01954   // compatible with the inner matcher, where type Pointer can be
01955   // either a raw pointer or a smart pointer.
01956   //
01957   // The reason we do this instead of relying on
01958   // MakePolymorphicMatcher() is that the latter is not flexible
01959   // enough for implementing the DescribeTo() method of Pointee().
01960   template <typename Pointer>
01961   operator Matcher<Pointer>() const {
01962     return MakeMatcher(new Impl<Pointer>(matcher_));
01963   }
01964 
01965  private:
01966   // The monomorphic implementation that works for a particular pointer type.
01967   template <typename Pointer>
01968   class Impl : public MatcherInterface<Pointer> {
01969    public:
01970     typedef typename PointeeOf<GTEST_REMOVE_CONST_(  // NOLINT
01971         GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
01972 
01973     explicit Impl(const InnerMatcher& matcher)
01974         : matcher_(MatcherCast<const Pointee&>(matcher)) {}
01975 
01976     virtual void DescribeTo(::std::ostream* os) const {
01977       *os << "points to a value that ";
01978       matcher_.DescribeTo(os);
01979     }
01980 
01981     virtual void DescribeNegationTo(::std::ostream* os) const {
01982       *os << "does not point to a value that ";
01983       matcher_.DescribeTo(os);
01984     }
01985 
01986     virtual bool MatchAndExplain(Pointer pointer,
01987                                  MatchResultListener* listener) const {
01988       if (GetRawPointer(pointer) == NULL)
01989         return false;
01990 
01991       *listener << "which points to ";
01992       return MatchPrintAndExplain(*pointer, matcher_, listener);
01993     }
01994 
01995    private:
01996     const Matcher<const Pointee&> matcher_;
01997 
01998     GTEST_DISALLOW_ASSIGN_(Impl);
01999   };
02000 
02001   const InnerMatcher matcher_;
02002 
02003   GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
02004 };
02005 
02006 // Implements the Field() matcher for matching a field (i.e. member
02007 // variable) of an object.
02008 template <typename Class, typename FieldType>
02009 class FieldMatcher {
02010  public:
02011   FieldMatcher(FieldType Class::*field,
02012                const Matcher<const FieldType&>& matcher)
02013       : field_(field), matcher_(matcher) {}
02014 
02015   void DescribeTo(::std::ostream* os) const {
02016     *os << "is an object whose given field ";
02017     matcher_.DescribeTo(os);
02018   }
02019 
02020   void DescribeNegationTo(::std::ostream* os) const {
02021     *os << "is an object whose given field ";
02022     matcher_.DescribeNegationTo(os);
02023   }
02024 
02025   template <typename T>
02026   bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
02027     return MatchAndExplainImpl(
02028         typename ::testing::internal::
02029             is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
02030         value, listener);
02031   }
02032 
02033  private:
02034   // The first argument of MatchAndExplainImpl() is needed to help
02035   // Symbian's C++ compiler choose which overload to use.  Its type is
02036   // true_type iff the Field() matcher is used to match a pointer.
02037   bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
02038                            MatchResultListener* listener) const {
02039     *listener << "whose given field is ";
02040     return MatchPrintAndExplain(obj.*field_, matcher_, listener);
02041   }
02042 
02043   bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
02044                            MatchResultListener* listener) const {
02045     if (p == NULL)
02046       return false;
02047 
02048     *listener << "which points to an object ";
02049     // Since *p has a field, it must be a class/struct/union type and
02050     // thus cannot be a pointer.  Therefore we pass false_type() as
02051     // the first argument.
02052     return MatchAndExplainImpl(false_type(), *p, listener);
02053   }
02054 
02055   const FieldType Class::*field_;
02056   const Matcher<const FieldType&> matcher_;
02057 
02058   GTEST_DISALLOW_ASSIGN_(FieldMatcher);
02059 };
02060 
02061 // Implements the Property() matcher for matching a property
02062 // (i.e. return value of a getter method) of an object.
02063 template <typename Class, typename PropertyType>
02064 class PropertyMatcher {
02065  public:
02066   // The property may have a reference type, so 'const PropertyType&'
02067   // may cause double references and fail to compile.  That's why we
02068   // need GTEST_REFERENCE_TO_CONST, which works regardless of
02069   // PropertyType being a reference or not.
02070   typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
02071 
02072   PropertyMatcher(PropertyType (Class::*property)() const,
02073                   const Matcher<RefToConstProperty>& matcher)
02074       : property_(property), matcher_(matcher) {}
02075 
02076   void DescribeTo(::std::ostream* os) const {
02077     *os << "is an object whose given property ";
02078     matcher_.DescribeTo(os);
02079   }
02080 
02081   void DescribeNegationTo(::std::ostream* os) const {
02082     *os << "is an object whose given property ";
02083     matcher_.DescribeNegationTo(os);
02084   }
02085 
02086   template <typename T>
02087   bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
02088     return MatchAndExplainImpl(
02089         typename ::testing::internal::
02090             is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
02091         value, listener);
02092   }
02093 
02094  private:
02095   // The first argument of MatchAndExplainImpl() is needed to help
02096   // Symbian's C++ compiler choose which overload to use.  Its type is
02097   // true_type iff the Property() matcher is used to match a pointer.
02098   bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
02099                            MatchResultListener* listener) const {
02100     *listener << "whose given property is ";
02101     // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
02102     // which takes a non-const reference as argument.
02103     RefToConstProperty result = (obj.*property_)();
02104     return MatchPrintAndExplain(result, matcher_, listener);
02105   }
02106 
02107   bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
02108                            MatchResultListener* listener) const {
02109     if (p == NULL)
02110       return false;
02111 
02112     *listener << "which points to an object ";
02113     // Since *p has a property method, it must be a class/struct/union
02114     // type and thus cannot be a pointer.  Therefore we pass
02115     // false_type() as the first argument.
02116     return MatchAndExplainImpl(false_type(), *p, listener);
02117   }
02118 
02119   PropertyType (Class::*property_)() const;
02120   const Matcher<RefToConstProperty> matcher_;
02121 
02122   GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
02123 };
02124 
02125 // Type traits specifying various features of different functors for ResultOf.
02126 // The default template specifies features for functor objects.
02127 // Functor classes have to typedef argument_type and result_type
02128 // to be compatible with ResultOf.
02129 template <typename Functor>
02130 struct CallableTraits {
02131   typedef typename Functor::result_type ResultType;
02132   typedef Functor StorageType;
02133 
02134   static void CheckIsValid(Functor /* functor */) {}
02135   template <typename T>
02136   static ResultType Invoke(Functor f, T arg) { return f(arg); }
02137 };
02138 
02139 // Specialization for function pointers.
02140 template <typename ArgType, typename ResType>
02141 struct CallableTraits<ResType(*)(ArgType)> {
02142   typedef ResType ResultType;
02143   typedef ResType(*StorageType)(ArgType);
02144 
02145   static void CheckIsValid(ResType(*f)(ArgType)) {
02146     GTEST_CHECK_(f != NULL)
02147         << "NULL function pointer is passed into ResultOf().";
02148   }
02149   template <typename T>
02150   static ResType Invoke(ResType(*f)(ArgType), T arg) {
02151     return (*f)(arg);
02152   }
02153 };
02154 
02155 // Implements the ResultOf() matcher for matching a return value of a
02156 // unary function of an object.
02157 template <typename Callable>
02158 class ResultOfMatcher {
02159  public:
02160   typedef typename CallableTraits<Callable>::ResultType ResultType;
02161 
02162   ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
02163       : callable_(callable), matcher_(matcher) {
02164     CallableTraits<Callable>::CheckIsValid(callable_);
02165   }
02166 
02167   template <typename T>
02168   operator Matcher<T>() const {
02169     return Matcher<T>(new Impl<T>(callable_, matcher_));
02170   }
02171 
02172  private:
02173   typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
02174 
02175   template <typename T>
02176   class Impl : public MatcherInterface<T> {
02177    public:
02178     Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
02179         : callable_(callable), matcher_(matcher) {}
02180 
02181     virtual void DescribeTo(::std::ostream* os) const {
02182       *os << "is mapped by the given callable to a value that ";
02183       matcher_.DescribeTo(os);
02184     }
02185 
02186     virtual void DescribeNegationTo(::std::ostream* os) const {
02187       *os << "is mapped by the given callable to a value that ";
02188       matcher_.DescribeNegationTo(os);
02189     }
02190 
02191     virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
02192       *listener << "which is mapped by the given callable to ";
02193       // Cannot pass the return value (for example, int) to
02194       // MatchPrintAndExplain, which takes a non-const reference as argument.
02195       ResultType result =
02196           CallableTraits<Callable>::template Invoke<T>(callable_, obj);
02197       return MatchPrintAndExplain(result, matcher_, listener);
02198     }
02199 
02200    private:
02201     // Functors often define operator() as non-const method even though
02202     // they are actualy stateless. But we need to use them even when
02203     // 'this' is a const pointer. It's the user's responsibility not to
02204     // use stateful callables with ResultOf(), which does't guarantee
02205     // how many times the callable will be invoked.
02206     mutable CallableStorageType callable_;
02207     const Matcher<ResultType> matcher_;
02208 
02209     GTEST_DISALLOW_ASSIGN_(Impl);
02210   };  // class Impl
02211 
02212   const CallableStorageType callable_;
02213   const Matcher<ResultType> matcher_;
02214 
02215   GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
02216 };
02217 
02218 // Implements a matcher that checks the size of an STL-style container.
02219 template <typename SizeMatcher>
02220 class SizeIsMatcher {
02221  public:
02222   explicit SizeIsMatcher(const SizeMatcher& size_matcher)
02223        : size_matcher_(size_matcher) {
02224   }
02225 
02226   template <typename Container>
02227   operator Matcher<Container>() const {
02228     return MakeMatcher(new Impl<Container>(size_matcher_));
02229   }
02230 
02231   template <typename Container>
02232   class Impl : public MatcherInterface<Container> {
02233    public:
02234     typedef internal::StlContainerView<
02235          GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
02236     typedef typename ContainerView::type::size_type SizeType;
02237     explicit Impl(const SizeMatcher& size_matcher)
02238         : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
02239 
02240     virtual void DescribeTo(::std::ostream* os) const {
02241       *os << "size ";
02242       size_matcher_.DescribeTo(os);
02243     }
02244     virtual void DescribeNegationTo(::std::ostream* os) const {
02245       *os << "size ";
02246       size_matcher_.DescribeNegationTo(os);
02247     }
02248 
02249     virtual bool MatchAndExplain(Container container,
02250                                  MatchResultListener* listener) const {
02251       SizeType size = container.size();
02252       StringMatchResultListener size_listener;
02253       const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
02254       *listener
02255           << "whose size " << size << (result ? " matches" : " doesn't match");
02256       PrintIfNotEmpty(size_listener.str(), listener->stream());
02257       return result;
02258     }
02259 
02260    private:
02261     const Matcher<SizeType> size_matcher_;
02262     GTEST_DISALLOW_ASSIGN_(Impl);
02263   };
02264 
02265  private:
02266   const SizeMatcher size_matcher_;
02267   GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
02268 };
02269 
02270 // Implements an equality matcher for any STL-style container whose elements
02271 // support ==. This matcher is like Eq(), but its failure explanations provide
02272 // more detailed information that is useful when the container is used as a set.
02273 // The failure message reports elements that are in one of the operands but not
02274 // the other. The failure messages do not report duplicate or out-of-order
02275 // elements in the containers (which don't properly matter to sets, but can
02276 // occur if the containers are vectors or lists, for example).
02277 //
02278 // Uses the container's const_iterator, value_type, operator ==,
02279 // begin(), and end().
02280 template <typename Container>
02281 class ContainerEqMatcher {
02282  public:
02283   typedef internal::StlContainerView<Container> View;
02284   typedef typename View::type StlContainer;
02285   typedef typename View::const_reference StlContainerReference;
02286 
02287   // We make a copy of rhs in case the elements in it are modified
02288   // after this matcher is created.
02289   explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
02290     // Makes sure the user doesn't instantiate this class template
02291     // with a const or reference type.
02292     (void)testing::StaticAssertTypeEq<Container,
02293         GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
02294   }
02295 
02296   void DescribeTo(::std::ostream* os) const {
02297     *os << "equals ";
02298     UniversalPrint(rhs_, os);
02299   }
02300   void DescribeNegationTo(::std::ostream* os) const {
02301     *os << "does not equal ";
02302     UniversalPrint(rhs_, os);
02303   }
02304 
02305   template <typename LhsContainer>
02306   bool MatchAndExplain(const LhsContainer& lhs,
02307                        MatchResultListener* listener) const {
02308     // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
02309     // that causes LhsContainer to be a const type sometimes.
02310     typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
02311         LhsView;
02312     typedef typename LhsView::type LhsStlContainer;
02313     StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
02314     if (lhs_stl_container == rhs_)
02315       return true;
02316 
02317     ::std::ostream* const os = listener->stream();
02318     if (os != NULL) {
02319       // Something is different. Check for extra values first.
02320       bool printed_header = false;
02321       for (typename LhsStlContainer::const_iterator it =
02322                lhs_stl_container.begin();
02323            it != lhs_stl_container.end(); ++it) {
02324         if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
02325             rhs_.end()) {
02326           if (printed_header) {
02327             *os << ", ";
02328           } else {
02329             *os << "which has these unexpected elements: ";
02330             printed_header = true;
02331           }
02332           UniversalPrint(*it, os);
02333         }
02334       }
02335 
02336       // Now check for missing values.
02337       bool printed_header2 = false;
02338       for (typename StlContainer::const_iterator it = rhs_.begin();
02339            it != rhs_.end(); ++it) {
02340         if (internal::ArrayAwareFind(
02341                 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
02342             lhs_stl_container.end()) {
02343           if (printed_header2) {
02344             *os << ", ";
02345           } else {
02346             *os << (printed_header ? ",\nand" : "which")
02347                 << " doesn't have these expected elements: ";
02348             printed_header2 = true;
02349           }
02350           UniversalPrint(*it, os);
02351         }
02352       }
02353     }
02354 
02355     return false;
02356   }
02357 
02358  private:
02359   const StlContainer rhs_;
02360 
02361   GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
02362 };
02363 
02364 // A comparator functor that uses the < operator to compare two values.
02365 struct LessComparator {
02366   template <typename T, typename U>
02367   bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
02368 };
02369 
02370 // Implements WhenSortedBy(comparator, container_matcher).
02371 template <typename Comparator, typename ContainerMatcher>
02372 class WhenSortedByMatcher {
02373  public:
02374   WhenSortedByMatcher(const Comparator& comparator,
02375                       const ContainerMatcher& matcher)
02376       : comparator_(comparator), matcher_(matcher) {}
02377 
02378   template <typename LhsContainer>
02379   operator Matcher<LhsContainer>() const {
02380     return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
02381   }
02382 
02383   template <typename LhsContainer>
02384   class Impl : public MatcherInterface<LhsContainer> {
02385    public:
02386     typedef internal::StlContainerView<
02387          GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
02388     typedef typename LhsView::type LhsStlContainer;
02389     typedef typename LhsView::const_reference LhsStlContainerReference;
02390     // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
02391     // so that we can match associative containers.
02392     typedef typename RemoveConstFromKey<
02393         typename LhsStlContainer::value_type>::type LhsValue;
02394 
02395     Impl(const Comparator& comparator, const ContainerMatcher& matcher)
02396         : comparator_(comparator), matcher_(matcher) {}
02397 
02398     virtual void DescribeTo(::std::ostream* os) const {
02399       *os << "(when sorted) ";
02400       matcher_.DescribeTo(os);
02401     }
02402 
02403     virtual void DescribeNegationTo(::std::ostream* os) const {
02404       *os << "(when sorted) ";
02405       matcher_.DescribeNegationTo(os);
02406     }
02407 
02408     virtual bool MatchAndExplain(LhsContainer lhs,
02409                                  MatchResultListener* listener) const {
02410       LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
02411       ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
02412                                                lhs_stl_container.end());
02413       ::std::sort(
02414            sorted_container.begin(), sorted_container.end(), comparator_);
02415 
02416       if (!listener->IsInterested()) {
02417         // If the listener is not interested, we do not need to
02418         // construct the inner explanation.
02419         return matcher_.Matches(sorted_container);
02420       }
02421 
02422       *listener << "which is ";
02423       UniversalPrint(sorted_container, listener->stream());
02424       *listener << " when sorted";
02425 
02426       StringMatchResultListener inner_listener;
02427       const bool match = matcher_.MatchAndExplain(sorted_container,
02428                                                   &inner_listener);
02429       PrintIfNotEmpty(inner_listener.str(), listener->stream());
02430       return match;
02431     }
02432 
02433    private:
02434     const Comparator comparator_;
02435     const Matcher<const ::std::vector<LhsValue>&> matcher_;
02436 
02437     GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
02438   };
02439 
02440  private:
02441   const Comparator comparator_;
02442   const ContainerMatcher matcher_;
02443 
02444   GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
02445 };
02446 
02447 // Implements Pointwise(tuple_matcher, rhs_container).  tuple_matcher
02448 // must be able to be safely cast to Matcher<tuple<const T1&, const
02449 // T2&> >, where T1 and T2 are the types of elements in the LHS
02450 // container and the RHS container respectively.
02451 template <typename TupleMatcher, typename RhsContainer>
02452 class PointwiseMatcher {
02453  public:
02454   typedef internal::StlContainerView<RhsContainer> RhsView;
02455   typedef typename RhsView::type RhsStlContainer;
02456   typedef typename RhsStlContainer::value_type RhsValue;
02457 
02458   // Like ContainerEq, we make a copy of rhs in case the elements in
02459   // it are modified after this matcher is created.
02460   PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
02461       : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
02462     // Makes sure the user doesn't instantiate this class template
02463     // with a const or reference type.
02464     (void)testing::StaticAssertTypeEq<RhsContainer,
02465         GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
02466   }
02467 
02468   template <typename LhsContainer>
02469   operator Matcher<LhsContainer>() const {
02470     return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
02471   }
02472 
02473   template <typename LhsContainer>
02474   class Impl : public MatcherInterface<LhsContainer> {
02475    public:
02476     typedef internal::StlContainerView<
02477          GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
02478     typedef typename LhsView::type LhsStlContainer;
02479     typedef typename LhsView::const_reference LhsStlContainerReference;
02480     typedef typename LhsStlContainer::value_type LhsValue;
02481     // We pass the LHS value and the RHS value to the inner matcher by
02482     // reference, as they may be expensive to copy.  We must use tuple
02483     // instead of pair here, as a pair cannot hold references (C++ 98,
02484     // 20.2.2 [lib.pairs]).
02485     typedef ::std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
02486 
02487     Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
02488         // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
02489         : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
02490           rhs_(rhs) {}
02491 
02492     virtual void DescribeTo(::std::ostream* os) const {
02493       *os << "contains " << rhs_.size()
02494           << " values, where each value and its corresponding value in ";
02495       UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
02496       *os << " ";
02497       mono_tuple_matcher_.DescribeTo(os);
02498     }
02499     virtual void DescribeNegationTo(::std::ostream* os) const {
02500       *os << "doesn't contain exactly " << rhs_.size()
02501           << " values, or contains a value x at some index i"
02502           << " where x and the i-th value of ";
02503       UniversalPrint(rhs_, os);
02504       *os << " ";
02505       mono_tuple_matcher_.DescribeNegationTo(os);
02506     }
02507 
02508     virtual bool MatchAndExplain(LhsContainer lhs,
02509                                  MatchResultListener* listener) const {
02510       LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
02511       const size_t actual_size = lhs_stl_container.size();
02512       if (actual_size != rhs_.size()) {
02513         *listener << "which contains " << actual_size << " values";
02514         return false;
02515       }
02516 
02517       typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
02518       typename RhsStlContainer::const_iterator right = rhs_.begin();
02519       for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
02520         const InnerMatcherArg value_pair(*left, *right);
02521 
02522         if (listener->IsInterested()) {
02523           StringMatchResultListener inner_listener;
02524           if (!mono_tuple_matcher_.MatchAndExplain(
02525                   value_pair, &inner_listener)) {
02526             *listener << "where the value pair (";
02527             UniversalPrint(*left, listener->stream());
02528             *listener << ", ";
02529             UniversalPrint(*right, listener->stream());
02530             *listener << ") at index #" << i << " don't match";
02531             PrintIfNotEmpty(inner_listener.str(), listener->stream());
02532             return false;
02533           }
02534         } else {
02535           if (!mono_tuple_matcher_.Matches(value_pair))
02536             return false;
02537         }
02538       }
02539 
02540       return true;
02541     }
02542 
02543    private:
02544     const Matcher<InnerMatcherArg> mono_tuple_matcher_;
02545     const RhsStlContainer rhs_;
02546 
02547     GTEST_DISALLOW_ASSIGN_(Impl);
02548   };
02549 
02550  private:
02551   const TupleMatcher tuple_matcher_;
02552   const RhsStlContainer rhs_;
02553 
02554   GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
02555 };
02556 
02557 // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
02558 template <typename Container>
02559 class QuantifierMatcherImpl : public MatcherInterface<Container> {
02560  public:
02561   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
02562   typedef StlContainerView<RawContainer> View;
02563   typedef typename View::type StlContainer;
02564   typedef typename View::const_reference StlContainerReference;
02565   typedef typename StlContainer::value_type Element;
02566 
02567   template <typename InnerMatcher>
02568   explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
02569       : inner_matcher_(
02570            testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
02571 
02572   // Checks whether:
02573   // * All elements in the container match, if all_elements_should_match.
02574   // * Any element in the container matches, if !all_elements_should_match.
02575   bool MatchAndExplainImpl(bool all_elements_should_match,
02576                            Container container,
02577                            MatchResultListener* listener) const {
02578     StlContainerReference stl_container = View::ConstReference(container);
02579     size_t i = 0;
02580     for (typename StlContainer::const_iterator it = stl_container.begin();
02581          it != stl_container.end(); ++it, ++i) {
02582       StringMatchResultListener inner_listener;
02583       const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
02584 
02585       if (matches != all_elements_should_match) {
02586         *listener << "whose element #" << i
02587                   << (matches ? " matches" : " doesn't match");
02588         PrintIfNotEmpty(inner_listener.str(), listener->stream());
02589         return !all_elements_should_match;
02590       }
02591     }
02592     return all_elements_should_match;
02593   }
02594 
02595  protected:
02596   const Matcher<const Element&> inner_matcher_;
02597 
02598   GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
02599 };
02600 
02601 // Implements Contains(element_matcher) for the given argument type Container.
02602 // Symmetric to EachMatcherImpl.
02603 template <typename Container>
02604 class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
02605  public:
02606   template <typename InnerMatcher>
02607   explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
02608       : QuantifierMatcherImpl<Container>(inner_matcher) {}
02609 
02610   // Describes what this matcher does.
02611   virtual void DescribeTo(::std::ostream* os) const {
02612     *os << "contains at least one element that ";
02613     this->inner_matcher_.DescribeTo(os);
02614   }
02615 
02616   virtual void DescribeNegationTo(::std::ostream* os) const {
02617     *os << "doesn't contain any element that ";
02618     this->inner_matcher_.DescribeTo(os);
02619   }
02620 
02621   virtual bool MatchAndExplain(Container container,
02622                                MatchResultListener* listener) const {
02623     return this->MatchAndExplainImpl(false, container, listener);
02624   }
02625 
02626  private:
02627   GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
02628 };
02629 
02630 // Implements Each(element_matcher) for the given argument type Container.
02631 // Symmetric to ContainsMatcherImpl.
02632 template <typename Container>
02633 class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
02634  public:
02635   template <typename InnerMatcher>
02636   explicit EachMatcherImpl(InnerMatcher inner_matcher)
02637       : QuantifierMatcherImpl<Container>(inner_matcher) {}
02638 
02639   // Describes what this matcher does.
02640   virtual void DescribeTo(::std::ostream* os) const {
02641     *os << "only contains elements that ";
02642     this->inner_matcher_.DescribeTo(os);
02643   }
02644 
02645   virtual void DescribeNegationTo(::std::ostream* os) const {
02646     *os << "contains some element that ";
02647     this->inner_matcher_.DescribeNegationTo(os);
02648   }
02649 
02650   virtual bool MatchAndExplain(Container container,
02651                                MatchResultListener* listener) const {
02652     return this->MatchAndExplainImpl(true, container, listener);
02653   }
02654 
02655  private:
02656   GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
02657 };
02658 
02659 // Implements polymorphic Contains(element_matcher).
02660 template <typename M>
02661 class ContainsMatcher {
02662  public:
02663   explicit ContainsMatcher(M m) : inner_matcher_(m) {}
02664 
02665   template <typename Container>
02666   operator Matcher<Container>() const {
02667     return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
02668   }
02669 
02670  private:
02671   const M inner_matcher_;
02672 
02673   GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
02674 };
02675 
02676 // Implements polymorphic Each(element_matcher).
02677 template <typename M>
02678 class EachMatcher {
02679  public:
02680   explicit EachMatcher(M m) : inner_matcher_(m) {}
02681 
02682   template <typename Container>
02683   operator Matcher<Container>() const {
02684     return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
02685   }
02686 
02687  private:
02688   const M inner_matcher_;
02689 
02690   GTEST_DISALLOW_ASSIGN_(EachMatcher);
02691 };
02692 
02693 // Implements Key(inner_matcher) for the given argument pair type.
02694 // Key(inner_matcher) matches an std::pair whose 'first' field matches
02695 // inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
02696 // std::map that contains at least one element whose key is >= 5.
02697 template <typename PairType>
02698 class KeyMatcherImpl : public MatcherInterface<PairType> {
02699  public:
02700   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
02701   typedef typename RawPairType::first_type KeyType;
02702 
02703   template <typename InnerMatcher>
02704   explicit KeyMatcherImpl(InnerMatcher inner_matcher)
02705       : inner_matcher_(
02706           testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
02707   }
02708 
02709   // Returns true iff 'key_value.first' (the key) matches the inner matcher.
02710   virtual bool MatchAndExplain(PairType key_value,
02711                                MatchResultListener* listener) const {
02712     StringMatchResultListener inner_listener;
02713     const bool match = inner_matcher_.MatchAndExplain(key_value.first,
02714                                                       &inner_listener);
02715     const internal::string explanation = inner_listener.str();
02716     if (explanation != "") {
02717       *listener << "whose first field is a value " << explanation;
02718     }
02719     return match;
02720   }
02721 
02722   // Describes what this matcher does.
02723   virtual void DescribeTo(::std::ostream* os) const {
02724     *os << "has a key that ";
02725     inner_matcher_.DescribeTo(os);
02726   }
02727 
02728   // Describes what the negation of this matcher does.
02729   virtual void DescribeNegationTo(::std::ostream* os) const {
02730     *os << "doesn't have a key that ";
02731     inner_matcher_.DescribeTo(os);
02732   }
02733 
02734  private:
02735   const Matcher<const KeyType&> inner_matcher_;
02736 
02737   GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
02738 };
02739 
02740 // Implements polymorphic Key(matcher_for_key).
02741 template <typename M>
02742 class KeyMatcher {
02743  public:
02744   explicit KeyMatcher(M m) : matcher_for_key_(m) {}
02745 
02746   template <typename PairType>
02747   operator Matcher<PairType>() const {
02748     return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
02749   }
02750 
02751  private:
02752   const M matcher_for_key_;
02753 
02754   GTEST_DISALLOW_ASSIGN_(KeyMatcher);
02755 };
02756 
02757 // Implements Pair(first_matcher, second_matcher) for the given argument pair
02758 // type with its two matchers. See Pair() function below.
02759 template <typename PairType>
02760 class PairMatcherImpl : public MatcherInterface<PairType> {
02761  public:
02762   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
02763   typedef typename RawPairType::first_type FirstType;
02764   typedef typename RawPairType::second_type SecondType;
02765 
02766   template <typename FirstMatcher, typename SecondMatcher>
02767   PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
02768       : first_matcher_(
02769             testing::SafeMatcherCast<const FirstType&>(first_matcher)),
02770         second_matcher_(
02771             testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
02772   }
02773 
02774   // Describes what this matcher does.
02775   virtual void DescribeTo(::std::ostream* os) const {
02776     *os << "has a first field that ";
02777     first_matcher_.DescribeTo(os);
02778     *os << ", and has a second field that ";
02779     second_matcher_.DescribeTo(os);
02780   }
02781 
02782   // Describes what the negation of this matcher does.
02783   virtual void DescribeNegationTo(::std::ostream* os) const {
02784     *os << "has a first field that ";
02785     first_matcher_.DescribeNegationTo(os);
02786     *os << ", or has a second field that ";
02787     second_matcher_.DescribeNegationTo(os);
02788   }
02789 
02790   // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
02791   // matches second_matcher.
02792   virtual bool MatchAndExplain(PairType a_pair,
02793                                MatchResultListener* listener) const {
02794     if (!listener->IsInterested()) {
02795       // If the listener is not interested, we don't need to construct the
02796       // explanation.
02797       return first_matcher_.Matches(a_pair.first) &&
02798              second_matcher_.Matches(a_pair.second);
02799     }
02800     StringMatchResultListener first_inner_listener;
02801     if (!first_matcher_.MatchAndExplain(a_pair.first,
02802                                         &first_inner_listener)) {
02803       *listener << "whose first field does not match";
02804       PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
02805       return false;
02806     }
02807     StringMatchResultListener second_inner_listener;
02808     if (!second_matcher_.MatchAndExplain(a_pair.second,
02809                                          &second_inner_listener)) {
02810       *listener << "whose second field does not match";
02811       PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
02812       return false;
02813     }
02814     ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
02815                    listener);
02816     return true;
02817   }
02818 
02819  private:
02820   void ExplainSuccess(const internal::string& first_explanation,
02821                       const internal::string& second_explanation,
02822                       MatchResultListener* listener) const {
02823     *listener << "whose both fields match";
02824     if (first_explanation != "") {
02825       *listener << ", where the first field is a value " << first_explanation;
02826     }
02827     if (second_explanation != "") {
02828       *listener << ", ";
02829       if (first_explanation != "") {
02830         *listener << "and ";
02831       } else {
02832         *listener << "where ";
02833       }
02834       *listener << "the second field is a value " << second_explanation;
02835     }
02836   }
02837 
02838   const Matcher<const FirstType&> first_matcher_;
02839   const Matcher<const SecondType&> second_matcher_;
02840 
02841   GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
02842 };
02843 
02844 // Implements polymorphic Pair(first_matcher, second_matcher).
02845 template <typename FirstMatcher, typename SecondMatcher>
02846 class PairMatcher {
02847  public:
02848   PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
02849       : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
02850 
02851   template <typename PairType>
02852   operator Matcher<PairType> () const {
02853     return MakeMatcher(
02854         new PairMatcherImpl<PairType>(
02855             first_matcher_, second_matcher_));
02856   }
02857 
02858  private:
02859   const FirstMatcher first_matcher_;
02860   const SecondMatcher second_matcher_;
02861 
02862   GTEST_DISALLOW_ASSIGN_(PairMatcher);
02863 };
02864 
02865 // Implements ElementsAre() and ElementsAreArray().
02866 template <typename Container>
02867 class ElementsAreMatcherImpl : public MatcherInterface<Container> {
02868  public:
02869   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
02870   typedef internal::StlContainerView<RawContainer> View;
02871   typedef typename View::type StlContainer;
02872   typedef typename View::const_reference StlContainerReference;
02873   typedef typename StlContainer::value_type Element;
02874 
02875   // Constructs the matcher from a sequence of element values or
02876   // element matchers.
02877   template <typename InputIter>
02878   ElementsAreMatcherImpl(InputIter first, InputIter last) {
02879     while (first != last) {
02880       matchers_.push_back(MatcherCast<const Element&>(*first++));
02881     }
02882   }
02883 
02884   // Describes what this matcher does.
02885   virtual void DescribeTo(::std::ostream* os) const {
02886     if (count() == 0) {
02887       *os << "is empty";
02888     } else if (count() == 1) {
02889       *os << "has 1 element that ";
02890       matchers_[0].DescribeTo(os);
02891     } else {
02892       *os << "has " << Elements(count()) << " where\n";
02893       for (size_t i = 0; i != count(); ++i) {
02894         *os << "element #" << i << " ";
02895         matchers_[i].DescribeTo(os);
02896         if (i + 1 < count()) {
02897           *os << ",\n";
02898         }
02899       }
02900     }
02901   }
02902 
02903   // Describes what the negation of this matcher does.
02904   virtual void DescribeNegationTo(::std::ostream* os) const {
02905     if (count() == 0) {
02906       *os << "isn't empty";
02907       return;
02908     }
02909 
02910     *os << "doesn't have " << Elements(count()) << ", or\n";
02911     for (size_t i = 0; i != count(); ++i) {
02912       *os << "element #" << i << " ";
02913       matchers_[i].DescribeNegationTo(os);
02914       if (i + 1 < count()) {
02915         *os << ", or\n";
02916       }
02917     }
02918   }
02919 
02920   virtual bool MatchAndExplain(Container container,
02921                                MatchResultListener* listener) const {
02922     // To work with stream-like "containers", we must only walk
02923     // through the elements in one pass.
02924 
02925     const bool listener_interested = listener->IsInterested();
02926 
02927     // explanations[i] is the explanation of the element at index i.
02928     ::std::vector<internal::string> explanations(count());
02929     StlContainerReference stl_container = View::ConstReference(container);
02930     typename StlContainer::const_iterator it = stl_container.begin();
02931     size_t exam_pos = 0;
02932     bool mismatch_found = false;  // Have we found a mismatched element yet?
02933 
02934     // Go through the elements and matchers in pairs, until we reach
02935     // the end of either the elements or the matchers, or until we find a
02936     // mismatch.
02937     for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
02938       bool match;  // Does the current element match the current matcher?
02939       if (listener_interested) {
02940         StringMatchResultListener s;
02941         match = matchers_[exam_pos].MatchAndExplain(*it, &s);
02942         explanations[exam_pos] = s.str();
02943       } else {
02944         match = matchers_[exam_pos].Matches(*it);
02945       }
02946 
02947       if (!match) {
02948         mismatch_found = true;
02949         break;
02950       }
02951     }
02952     // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
02953 
02954     // Find how many elements the actual container has.  We avoid
02955     // calling size() s.t. this code works for stream-like "containers"
02956     // that don't define size().
02957     size_t actual_count = exam_pos;
02958     for (; it != stl_container.end(); ++it) {
02959       ++actual_count;
02960     }
02961 
02962     if (actual_count != count()) {
02963       // The element count doesn't match.  If the container is empty,
02964       // there's no need to explain anything as Google Mock already
02965       // prints the empty container.  Otherwise we just need to show
02966       // how many elements there actually are.
02967       if (listener_interested && (actual_count != 0)) {
02968         *listener << "which has " << Elements(actual_count);
02969       }
02970       return false;
02971     }
02972 
02973     if (mismatch_found) {
02974       // The element count matches, but the exam_pos-th element doesn't match.
02975       if (listener_interested) {
02976         *listener << "whose element #" << exam_pos << " doesn't match";
02977         PrintIfNotEmpty(explanations[exam_pos], listener->stream());
02978       }
02979       return false;
02980     }
02981 
02982     // Every element matches its expectation.  We need to explain why
02983     // (the obvious ones can be skipped).
02984     if (listener_interested) {
02985       bool reason_printed = false;
02986       for (size_t i = 0; i != count(); ++i) {
02987         const internal::string& s = explanations[i];
02988         if (!s.empty()) {
02989           if (reason_printed) {
02990             *listener << ",\nand ";
02991           }
02992           *listener << "whose element #" << i << " matches, " << s;
02993           reason_printed = true;
02994         }
02995       }
02996     }
02997     return true;
02998   }
02999 
03000  private:
03001   static Message Elements(size_t count) {
03002     return Message() << count << (count == 1 ? " element" : " elements");
03003   }
03004 
03005   size_t count() const { return matchers_.size(); }
03006 
03007   ::std::vector<Matcher<const Element&> > matchers_;
03008 
03009   GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
03010 };
03011 
03012 // Connectivity matrix of (elements X matchers), in element-major order.
03013 // Initially, there are no edges.
03014 // Use NextGraph() to iterate over all possible edge configurations.
03015 // Use Randomize() to generate a random edge configuration.
03016 class GTEST_API_ MatchMatrix {
03017  public:
03018   MatchMatrix(size_t num_elements, size_t num_matchers)
03019       : num_elements_(num_elements),
03020         num_matchers_(num_matchers),
03021         matched_(num_elements_* num_matchers_, 0) {
03022   }
03023 
03024   size_t LhsSize() const { return num_elements_; }
03025   size_t RhsSize() const { return num_matchers_; }
03026   bool HasEdge(size_t ilhs, size_t irhs) const {
03027     return matched_[SpaceIndex(ilhs, irhs)] == 1;
03028   }
03029   void SetEdge(size_t ilhs, size_t irhs, bool b) {
03030     matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
03031   }
03032 
03033   // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
03034   // adds 1 to that number; returns false if incrementing the graph left it
03035   // empty.
03036   bool NextGraph();
03037 
03038   void Randomize();
03039 
03040   string DebugString() const;
03041 
03042  private:
03043   size_t SpaceIndex(size_t ilhs, size_t irhs) const {
03044     return ilhs * num_matchers_ + irhs;
03045   }
03046 
03047   size_t num_elements_;
03048   size_t num_matchers_;
03049 
03050   // Each element is a char interpreted as bool. They are stored as a
03051   // flattened array in lhs-major order, use 'SpaceIndex()' to translate
03052   // a (ilhs, irhs) matrix coordinate into an offset.
03053   ::std::vector<char> matched_;
03054 };
03055 
03056 typedef ::std::pair<size_t, size_t> ElementMatcherPair;
03057 typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
03058 
03059 // Returns a maximum bipartite matching for the specified graph 'g'.
03060 // The matching is represented as a vector of {element, matcher} pairs.
03061 GTEST_API_ ElementMatcherPairs
03062 FindMaxBipartiteMatching(const MatchMatrix& g);
03063 
03064 GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
03065                             MatchResultListener* listener);
03066 
03067 // Untyped base class for implementing UnorderedElementsAre.  By
03068 // putting logic that's not specific to the element type here, we
03069 // reduce binary bloat and increase compilation speed.
03070 class GTEST_API_ UnorderedElementsAreMatcherImplBase {
03071  protected:
03072   // A vector of matcher describers, one for each element matcher.
03073   // Does not own the describers (and thus can be used only when the
03074   // element matchers are alive).
03075   typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
03076 
03077   // Describes this UnorderedElementsAre matcher.
03078   void DescribeToImpl(::std::ostream* os) const;
03079 
03080   // Describes the negation of this UnorderedElementsAre matcher.
03081   void DescribeNegationToImpl(::std::ostream* os) const;
03082 
03083   bool VerifyAllElementsAndMatchersAreMatched(
03084       const ::std::vector<string>& element_printouts,
03085       const MatchMatrix& matrix,
03086       MatchResultListener* listener) const;
03087 
03088   MatcherDescriberVec& matcher_describers() {
03089     return matcher_describers_;
03090   }
03091 
03092   static Message Elements(size_t n) {
03093     return Message() << n << " element" << (n == 1 ? "" : "s");
03094   }
03095 
03096  private:
03097   MatcherDescriberVec matcher_describers_;
03098 
03099   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
03100 };
03101 
03102 // Implements unordered ElementsAre and unordered ElementsAreArray.
03103 template <typename Container>
03104 class UnorderedElementsAreMatcherImpl
03105     : public MatcherInterface<Container>,
03106       public UnorderedElementsAreMatcherImplBase {
03107  public:
03108   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
03109   typedef internal::StlContainerView<RawContainer> View;
03110   typedef typename View::type StlContainer;
03111   typedef typename View::const_reference StlContainerReference;
03112   typedef typename StlContainer::const_iterator StlContainerConstIterator;
03113   typedef typename StlContainer::value_type Element;
03114 
03115   // Constructs the matcher from a sequence of element values or
03116   // element matchers.
03117   template <typename InputIter>
03118   UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
03119     for (; first != last; ++first) {
03120       matchers_.push_back(MatcherCast<const Element&>(*first));
03121       matcher_describers().push_back(matchers_.back().GetDescriber());
03122     }
03123   }
03124 
03125   // Describes what this matcher does.
03126   virtual void DescribeTo(::std::ostream* os) const {
03127     return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
03128   }
03129 
03130   // Describes what the negation of this matcher does.
03131   virtual void DescribeNegationTo(::std::ostream* os) const {
03132     return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
03133   }
03134 
03135   virtual bool MatchAndExplain(Container container,
03136                                MatchResultListener* listener) const {
03137     StlContainerReference stl_container = View::ConstReference(container);
03138     ::std::vector<string> element_printouts;
03139     MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
03140                                          stl_container.end(),
03141                                          &element_printouts,
03142                                          listener);
03143 
03144     const size_t actual_count = matrix.LhsSize();
03145     if (actual_count == 0 && matchers_.empty()) {
03146       return true;
03147     }
03148     if (actual_count != matchers_.size()) {
03149       // The element count doesn't match.  If the container is empty,
03150       // there's no need to explain anything as Google Mock already
03151       // prints the empty container. Otherwise we just need to show
03152       // how many elements there actually are.
03153       if (actual_count != 0 && listener->IsInterested()) {
03154         *listener << "which has " << Elements(actual_count);
03155       }
03156       return false;
03157     }
03158 
03159     return VerifyAllElementsAndMatchersAreMatched(element_printouts,
03160                                                   matrix, listener) &&
03161            FindPairing(matrix, listener);
03162   }
03163 
03164  private:
03165   typedef ::std::vector<Matcher<const Element&> > MatcherVec;
03166 
03167   template <typename ElementIter>
03168   MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
03169                               ::std::vector<string>* element_printouts,
03170                               MatchResultListener* listener) const {
03171     element_printouts->clear();
03172     ::std::vector<char> did_match;
03173     size_t num_elements = 0;
03174     for (; elem_first != elem_last; ++num_elements, ++elem_first) {
03175       if (listener->IsInterested()) {
03176         element_printouts->push_back(PrintToString(*elem_first));
03177       }
03178       for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
03179         did_match.push_back(Matches(matchers_[irhs])(*elem_first));
03180       }
03181     }
03182 
03183     MatchMatrix matrix(num_elements, matchers_.size());
03184     ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
03185     for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
03186       for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
03187         matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
03188       }
03189     }
03190     return matrix;
03191   }
03192 
03193   MatcherVec matchers_;
03194 
03195   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
03196 };
03197 
03198 // Functor for use in TransformTuple.
03199 // Performs MatcherCast<Target> on an input argument of any type.
03200 template <typename Target>
03201 struct CastAndAppendTransform {
03202   template <typename Arg>
03203   Matcher<Target> operator()(const Arg& a) const {
03204     return MatcherCast<Target>(a);
03205   }
03206 };
03207 
03208 // Implements UnorderedElementsAre.
03209 template <typename MatcherTuple>
03210 class UnorderedElementsAreMatcher {
03211  public:
03212   explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
03213       : matchers_(args) {}
03214 
03215   template <typename Container>
03216   operator Matcher<Container>() const {
03217     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
03218     typedef typename internal::StlContainerView<RawContainer>::type View;
03219     typedef typename View::value_type Element;
03220     typedef ::std::vector<Matcher<const Element&> > MatcherVec;
03221     MatcherVec matchers;
03222     matchers.reserve(::std::tr1::tuple_size<MatcherTuple>::value);
03223     TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
03224                          ::std::back_inserter(matchers));
03225     return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
03226                            matchers.begin(), matchers.end()));
03227   }
03228 
03229  private:
03230   const MatcherTuple matchers_;
03231   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
03232 };
03233 
03234 // Implements ElementsAre.
03235 template <typename MatcherTuple>
03236 class ElementsAreMatcher {
03237  public:
03238   explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
03239 
03240   template <typename Container>
03241   operator Matcher<Container>() const {
03242     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
03243     typedef typename internal::StlContainerView<RawContainer>::type View;
03244     typedef typename View::value_type Element;
03245     typedef ::std::vector<Matcher<const Element&> > MatcherVec;
03246     MatcherVec matchers;
03247     matchers.reserve(::std::tr1::tuple_size<MatcherTuple>::value);
03248     TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
03249                          ::std::back_inserter(matchers));
03250     return MakeMatcher(new ElementsAreMatcherImpl<Container>(
03251                            matchers.begin(), matchers.end()));
03252   }
03253 
03254  private:
03255   const MatcherTuple matchers_;
03256   GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
03257 };
03258 
03259 // Implements UnorderedElementsAreArray().
03260 template <typename T>
03261 class UnorderedElementsAreArrayMatcher {
03262  public:
03263   UnorderedElementsAreArrayMatcher() {}
03264 
03265   template <typename Iter>
03266   UnorderedElementsAreArrayMatcher(Iter first, Iter last)
03267       : matchers_(first, last) {}
03268 
03269   template <typename Container>
03270   operator Matcher<Container>() const {
03271     return MakeMatcher(
03272         new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
03273                                                        matchers_.end()));
03274   }
03275 
03276  private:
03277   ::std::vector<T> matchers_;
03278 
03279   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
03280 };
03281 
03282 // Implements ElementsAreArray().
03283 template <typename T>
03284 class ElementsAreArrayMatcher {
03285  public:
03286   template <typename Iter>
03287   ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
03288 
03289   template <typename Container>
03290   operator Matcher<Container>() const {
03291     return MakeMatcher(new ElementsAreMatcherImpl<Container>(
03292         matchers_.begin(), matchers_.end()));
03293   }
03294 
03295  private:
03296   const ::std::vector<T> matchers_;
03297 
03298   GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
03299 };
03300 
03301 // Returns the description for a matcher defined using the MATCHER*()
03302 // macro where the user-supplied description string is "", if
03303 // 'negation' is false; otherwise returns the description of the
03304 // negation of the matcher.  'param_values' contains a list of strings
03305 // that are the print-out of the matcher's parameters.
03306 GTEST_API_ string FormatMatcherDescription(bool negation,
03307                                            const char* matcher_name,
03308                                            const Strings& param_values);
03309 
03310 }  // namespace internal
03311 
03312 // ElementsAreArray(first, last)
03313 // ElementsAreArray(pointer, count)
03314 // ElementsAreArray(array)
03315 // ElementsAreArray(vector)
03316 // ElementsAreArray({ e1, e2, ..., en })
03317 //
03318 // The ElementsAreArray() functions are like ElementsAre(...), except
03319 // that they are given a homogeneous sequence rather than taking each
03320 // element as a function argument. The sequence can be specified as an
03321 // array, a pointer and count, a vector, an initializer list, or an
03322 // STL iterator range. In each of these cases, the underlying sequence
03323 // can be either a sequence of values or a sequence of matchers.
03324 //
03325 // All forms of ElementsAreArray() make a copy of the input matcher sequence.
03326 
03327 template <typename Iter>
03328 inline internal::ElementsAreArrayMatcher<
03329     typename ::std::iterator_traits<Iter>::value_type>
03330 ElementsAreArray(Iter first, Iter last) {
03331   typedef typename ::std::iterator_traits<Iter>::value_type T;
03332   return internal::ElementsAreArrayMatcher<T>(first, last);
03333 }
03334 
03335 template <typename T>
03336 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
03337     const T* pointer, size_t count) {
03338   return ElementsAreArray(pointer, pointer + count);
03339 }
03340 
03341 template <typename T, size_t N>
03342 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
03343     const T (&array)[N]) {
03344   return ElementsAreArray(array, N);
03345 }
03346 
03347 template <typename T, typename A>
03348 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
03349     const ::std::vector<T, A>& vec) {
03350   return ElementsAreArray(vec.begin(), vec.end());
03351 }
03352 
03353 #if GTEST_LANG_CXX11
03354 template <typename T>
03355 inline internal::ElementsAreArrayMatcher<T>
03356 ElementsAreArray(::std::initializer_list<T> xs) {
03357   return ElementsAreArray(xs.begin(), xs.end());
03358 }
03359 #endif
03360 
03361 // UnorderedElementsAreArray(first, last)
03362 // UnorderedElementsAreArray(pointer, count)
03363 // UnorderedElementsAreArray(array)
03364 // UnorderedElementsAreArray(vector)
03365 // UnorderedElementsAreArray({ e1, e2, ..., en })
03366 //
03367 // The UnorderedElementsAreArray() functions are like
03368 // ElementsAreArray(...), but allow matching the elements in any order.
03369 template <typename Iter>
03370 inline internal::UnorderedElementsAreArrayMatcher<
03371     typename ::std::iterator_traits<Iter>::value_type>
03372 UnorderedElementsAreArray(Iter first, Iter last) {
03373   typedef typename ::std::iterator_traits<Iter>::value_type T;
03374   return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
03375 }
03376 
03377 template <typename T>
03378 inline internal::UnorderedElementsAreArrayMatcher<T>
03379 UnorderedElementsAreArray(const T* pointer, size_t count) {
03380   return UnorderedElementsAreArray(pointer, pointer + count);
03381 }
03382 
03383 template <typename T, size_t N>
03384 inline internal::UnorderedElementsAreArrayMatcher<T>
03385 UnorderedElementsAreArray(const T (&array)[N]) {
03386   return UnorderedElementsAreArray(array, N);
03387 }
03388 
03389 template <typename T, typename A>
03390 inline internal::UnorderedElementsAreArrayMatcher<T>
03391 UnorderedElementsAreArray(const ::std::vector<T, A>& vec) {
03392   return UnorderedElementsAreArray(vec.begin(), vec.end());
03393 }
03394 
03395 #if GTEST_LANG_CXX11
03396 template <typename T>
03397 inline internal::UnorderedElementsAreArrayMatcher<T>
03398 UnorderedElementsAreArray(::std::initializer_list<T> xs) {
03399   return UnorderedElementsAreArray(xs.begin(), xs.end());
03400 }
03401 #endif
03402 
03403 // _ is a matcher that matches anything of any type.
03404 //
03405 // This definition is fine as:
03406 //
03407 //   1. The C++ standard permits using the name _ in a namespace that
03408 //      is not the global namespace or ::std.
03409 //   2. The AnythingMatcher class has no data member or constructor,
03410 //      so it's OK to create global variables of this type.
03411 //   3. c-style has approved of using _ in this case.
03412 const internal::AnythingMatcher _ = {};
03413 // Creates a matcher that matches any value of the given type T.
03414 template <typename T>
03415 inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
03416 
03417 // Creates a matcher that matches any value of the given type T.
03418 template <typename T>
03419 inline Matcher<T> An() { return A<T>(); }
03420 
03421 // Creates a polymorphic matcher that matches anything equal to x.
03422 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
03423 // wouldn't compile.
03424 template <typename T>
03425 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
03426 
03427 // Constructs a Matcher<T> from a 'value' of type T.  The constructed
03428 // matcher matches any value that's equal to 'value'.
03429 template <typename T>
03430 Matcher<T>::Matcher(T value) { *this = Eq(value); }
03431 
03432 // Creates a monomorphic matcher that matches anything with type Lhs
03433 // and equal to rhs.  A user may need to use this instead of Eq(...)
03434 // in order to resolve an overloading ambiguity.
03435 //
03436 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
03437 // or Matcher<T>(x), but more readable than the latter.
03438 //
03439 // We could define similar monomorphic matchers for other comparison
03440 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
03441 // it yet as those are used much less than Eq() in practice.  A user
03442 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
03443 // for example.
03444 template <typename Lhs, typename Rhs>
03445 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
03446 
03447 // Creates a polymorphic matcher that matches anything >= x.
03448 template <typename Rhs>
03449 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
03450   return internal::GeMatcher<Rhs>(x);
03451 }
03452 
03453 // Creates a polymorphic matcher that matches anything > x.
03454 template <typename Rhs>
03455 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
03456   return internal::GtMatcher<Rhs>(x);
03457 }
03458 
03459 // Creates a polymorphic matcher that matches anything <= x.
03460 template <typename Rhs>
03461 inline internal::LeMatcher<Rhs> Le(Rhs x) {
03462   return internal::LeMatcher<Rhs>(x);
03463 }
03464 
03465 // Creates a polymorphic matcher that matches anything < x.
03466 template <typename Rhs>
03467 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
03468   return internal::LtMatcher<Rhs>(x);
03469 }
03470 
03471 // Creates a polymorphic matcher that matches anything != x.
03472 template <typename Rhs>
03473 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
03474   return internal::NeMatcher<Rhs>(x);
03475 }
03476 
03477 // Creates a polymorphic matcher that matches any NULL pointer.
03478 inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
03479   return MakePolymorphicMatcher(internal::IsNullMatcher());
03480 }
03481 
03482 // Creates a polymorphic matcher that matches any non-NULL pointer.
03483 // This is convenient as Not(NULL) doesn't compile (the compiler
03484 // thinks that that expression is comparing a pointer with an integer).
03485 inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
03486   return MakePolymorphicMatcher(internal::NotNullMatcher());
03487 }
03488 
03489 // Creates a polymorphic matcher that matches any argument that
03490 // references variable x.
03491 template <typename T>
03492 inline internal::RefMatcher<T&> Ref(T& x) {  // NOLINT
03493   return internal::RefMatcher<T&>(x);
03494 }
03495 
03496 // Creates a matcher that matches any double argument approximately
03497 // equal to rhs, where two NANs are considered unequal.
03498 inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
03499   return internal::FloatingEqMatcher<double>(rhs, false);
03500 }
03501 
03502 // Creates a matcher that matches any double argument approximately
03503 // equal to rhs, including NaN values when rhs is NaN.
03504 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
03505   return internal::FloatingEqMatcher<double>(rhs, true);
03506 }
03507 
03508 // Creates a matcher that matches any double argument approximately equal to
03509 // rhs, up to the specified max absolute error bound, where two NANs are
03510 // considered unequal.  The max absolute error bound must be non-negative.
03511 inline internal::FloatingEqMatcher<double> DoubleNear(
03512     double rhs, double max_abs_error) {
03513   return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
03514 }
03515 
03516 // Creates a matcher that matches any double argument approximately equal to
03517 // rhs, up to the specified max absolute error bound, including NaN values when
03518 // rhs is NaN.  The max absolute error bound must be non-negative.
03519 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
03520     double rhs, double max_abs_error) {
03521   return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
03522 }
03523 
03524 // Creates a matcher that matches any float argument approximately
03525 // equal to rhs, where two NANs are considered unequal.
03526 inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
03527   return internal::FloatingEqMatcher<float>(rhs, false);
03528 }
03529 
03530 // Creates a matcher that matches any float argument approximately
03531 // equal to rhs, including NaN values when rhs is NaN.
03532 inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
03533   return internal::FloatingEqMatcher<float>(rhs, true);
03534 }
03535 
03536 // Creates a matcher that matches any float argument approximately equal to
03537 // rhs, up to the specified max absolute error bound, where two NANs are
03538 // considered unequal.  The max absolute error bound must be non-negative.
03539 inline internal::FloatingEqMatcher<float> FloatNear(
03540     float rhs, float max_abs_error) {
03541   return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
03542 }
03543 
03544 // Creates a matcher that matches any float argument approximately equal to
03545 // rhs, up to the specified max absolute error bound, including NaN values when
03546 // rhs is NaN.  The max absolute error bound must be non-negative.
03547 inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
03548     float rhs, float max_abs_error) {
03549   return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
03550 }
03551 
03552 // Creates a matcher that matches a pointer (raw or smart) that points
03553 // to a value that matches inner_matcher.
03554 template <typename InnerMatcher>
03555 inline internal::PointeeMatcher<InnerMatcher> Pointee(
03556     const InnerMatcher& inner_matcher) {
03557   return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
03558 }
03559 
03560 // Creates a matcher that matches an object whose given field matches
03561 // 'matcher'.  For example,
03562 //   Field(&Foo::number, Ge(5))
03563 // matches a Foo object x iff x.number >= 5.
03564 template <typename Class, typename FieldType, typename FieldMatcher>
03565 inline PolymorphicMatcher<
03566   internal::FieldMatcher<Class, FieldType> > Field(
03567     FieldType Class::*field, const FieldMatcher& matcher) {
03568   return MakePolymorphicMatcher(
03569       internal::FieldMatcher<Class, FieldType>(
03570           field, MatcherCast<const FieldType&>(matcher)));
03571   // The call to MatcherCast() is required for supporting inner
03572   // matchers of compatible types.  For example, it allows
03573   //   Field(&Foo::bar, m)
03574   // to compile where bar is an int32 and m is a matcher for int64.
03575 }
03576 
03577 // Creates a matcher that matches an object whose given property
03578 // matches 'matcher'.  For example,
03579 //   Property(&Foo::str, StartsWith("hi"))
03580 // matches a Foo object x iff x.str() starts with "hi".
03581 template <typename Class, typename PropertyType, typename PropertyMatcher>
03582 inline PolymorphicMatcher<
03583   internal::PropertyMatcher<Class, PropertyType> > Property(
03584     PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
03585   return MakePolymorphicMatcher(
03586       internal::PropertyMatcher<Class, PropertyType>(
03587           property,
03588           MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
03589   // The call to MatcherCast() is required for supporting inner
03590   // matchers of compatible types.  For example, it allows
03591   //   Property(&Foo::bar, m)
03592   // to compile where bar() returns an int32 and m is a matcher for int64.
03593 }
03594 
03595 // Creates a matcher that matches an object iff the result of applying
03596 // a callable to x matches 'matcher'.
03597 // For example,
03598 //   ResultOf(f, StartsWith("hi"))
03599 // matches a Foo object x iff f(x) starts with "hi".
03600 // callable parameter can be a function, function pointer, or a functor.
03601 // Callable has to satisfy the following conditions:
03602 //   * It is required to keep no state affecting the results of
03603 //     the calls on it and make no assumptions about how many calls
03604 //     will be made. Any state it keeps must be protected from the
03605 //     concurrent access.
03606 //   * If it is a function object, it has to define type result_type.
03607 //     We recommend deriving your functor classes from std::unary_function.
03608 template <typename Callable, typename ResultOfMatcher>
03609 internal::ResultOfMatcher<Callable> ResultOf(
03610     Callable callable, const ResultOfMatcher& matcher) {
03611   return internal::ResultOfMatcher<Callable>(
03612           callable,
03613           MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
03614               matcher));
03615   // The call to MatcherCast() is required for supporting inner
03616   // matchers of compatible types.  For example, it allows
03617   //   ResultOf(Function, m)
03618   // to compile where Function() returns an int32 and m is a matcher for int64.
03619 }
03620 
03621 // String matchers.
03622 
03623 // Matches a string equal to str.
03624 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
03625     StrEq(const internal::string& str) {
03626   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
03627       str, true, true));
03628 }
03629 
03630 // Matches a string not equal to str.
03631 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
03632     StrNe(const internal::string& str) {
03633   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
03634       str, false, true));
03635 }
03636 
03637 // Matches a string equal to str, ignoring case.
03638 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
03639     StrCaseEq(const internal::string& str) {
03640   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
03641       str, true, false));
03642 }
03643 
03644 // Matches a string not equal to str, ignoring case.
03645 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
03646     StrCaseNe(const internal::string& str) {
03647   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
03648       str, false, false));
03649 }
03650 
03651 // Creates a matcher that matches any string, std::string, or C string
03652 // that contains the given substring.
03653 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
03654     HasSubstr(const internal::string& substring) {
03655   return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
03656       substring));
03657 }
03658 
03659 // Matches a string that starts with 'prefix' (case-sensitive).
03660 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
03661     StartsWith(const internal::string& prefix) {
03662   return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
03663       prefix));
03664 }
03665 
03666 // Matches a string that ends with 'suffix' (case-sensitive).
03667 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
03668     EndsWith(const internal::string& suffix) {
03669   return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
03670       suffix));
03671 }
03672 
03673 // Matches a string that fully matches regular expression 'regex'.
03674 // The matcher takes ownership of 'regex'.
03675 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
03676     const internal::RE* regex) {
03677   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
03678 }
03679 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
03680     const internal::string& regex) {
03681   return MatchesRegex(new internal::RE(regex));
03682 }
03683 
03684 // Matches a string that contains regular expression 'regex'.
03685 // The matcher takes ownership of 'regex'.
03686 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
03687     const internal::RE* regex) {
03688   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
03689 }
03690 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
03691     const internal::string& regex) {
03692   return ContainsRegex(new internal::RE(regex));
03693 }
03694 
03695 #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
03696 // Wide string matchers.
03697 
03698 // Matches a string equal to str.
03699 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
03700     StrEq(const internal::wstring& str) {
03701   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
03702       str, true, true));
03703 }
03704 
03705 // Matches a string not equal to str.
03706 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
03707     StrNe(const internal::wstring& str) {
03708   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
03709       str, false, true));
03710 }
03711 
03712 // Matches a string equal to str, ignoring case.
03713 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
03714     StrCaseEq(const internal::wstring& str) {
03715   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
03716       str, true, false));
03717 }
03718 
03719 // Matches a string not equal to str, ignoring case.
03720 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
03721     StrCaseNe(const internal::wstring& str) {
03722   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
03723       str, false, false));
03724 }
03725 
03726 // Creates a matcher that matches any wstring, std::wstring, or C wide string
03727 // that contains the given substring.
03728 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
03729     HasSubstr(const internal::wstring& substring) {
03730   return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
03731       substring));
03732 }
03733 
03734 // Matches a string that starts with 'prefix' (case-sensitive).
03735 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
03736     StartsWith(const internal::wstring& prefix) {
03737   return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
03738       prefix));
03739 }
03740 
03741 // Matches a string that ends with 'suffix' (case-sensitive).
03742 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
03743     EndsWith(const internal::wstring& suffix) {
03744   return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
03745       suffix));
03746 }
03747 
03748 #endif  // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
03749 
03750 // Creates a polymorphic matcher that matches a 2-tuple where the
03751 // first field == the second field.
03752 inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
03753 
03754 // Creates a polymorphic matcher that matches a 2-tuple where the
03755 // first field >= the second field.
03756 inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
03757 
03758 // Creates a polymorphic matcher that matches a 2-tuple where the
03759 // first field > the second field.
03760 inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
03761 
03762 // Creates a polymorphic matcher that matches a 2-tuple where the
03763 // first field <= the second field.
03764 inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
03765 
03766 // Creates a polymorphic matcher that matches a 2-tuple where the
03767 // first field < the second field.
03768 inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
03769 
03770 // Creates a polymorphic matcher that matches a 2-tuple where the
03771 // first field != the second field.
03772 inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
03773 
03774 // Creates a matcher that matches any value of type T that m doesn't
03775 // match.
03776 template <typename InnerMatcher>
03777 inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
03778   return internal::NotMatcher<InnerMatcher>(m);
03779 }
03780 
03781 // Returns a matcher that matches anything that satisfies the given
03782 // predicate.  The predicate can be any unary function or functor
03783 // whose return type can be implicitly converted to bool.
03784 template <typename Predicate>
03785 inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
03786 Truly(Predicate pred) {
03787   return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
03788 }
03789 
03790 // Returns a matcher that matches the container size. The container must
03791 // support both size() and size_type which all STL-like containers provide.
03792 // Note that the parameter 'size' can be a value of type size_type as well as
03793 // matcher. For instance:
03794 //   EXPECT_THAT(container, SizeIs(2));     // Checks container has 2 elements.
03795 //   EXPECT_THAT(container, SizeIs(Le(2));  // Checks container has at most 2.
03796 template <typename SizeMatcher>
03797 inline internal::SizeIsMatcher<SizeMatcher>
03798 SizeIs(const SizeMatcher& size_matcher) {
03799   return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
03800 }
03801 
03802 // Returns a matcher that matches an equal container.
03803 // This matcher behaves like Eq(), but in the event of mismatch lists the
03804 // values that are included in one container but not the other. (Duplicate
03805 // values and order differences are not explained.)
03806 template <typename Container>
03807 inline PolymorphicMatcher<internal::ContainerEqMatcher<  // NOLINT
03808                             GTEST_REMOVE_CONST_(Container)> >
03809     ContainerEq(const Container& rhs) {
03810   // This following line is for working around a bug in MSVC 8.0,
03811   // which causes Container to be a const type sometimes.
03812   typedef GTEST_REMOVE_CONST_(Container) RawContainer;
03813   return MakePolymorphicMatcher(
03814       internal::ContainerEqMatcher<RawContainer>(rhs));
03815 }
03816 
03817 // Returns a matcher that matches a container that, when sorted using
03818 // the given comparator, matches container_matcher.
03819 template <typename Comparator, typename ContainerMatcher>
03820 inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
03821 WhenSortedBy(const Comparator& comparator,
03822              const ContainerMatcher& container_matcher) {
03823   return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
03824       comparator, container_matcher);
03825 }
03826 
03827 // Returns a matcher that matches a container that, when sorted using
03828 // the < operator, matches container_matcher.
03829 template <typename ContainerMatcher>
03830 inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
03831 WhenSorted(const ContainerMatcher& container_matcher) {
03832   return
03833       internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
03834           internal::LessComparator(), container_matcher);
03835 }
03836 
03837 // Matches an STL-style container or a native array that contains the
03838 // same number of elements as in rhs, where its i-th element and rhs's
03839 // i-th element (as a pair) satisfy the given pair matcher, for all i.
03840 // TupleMatcher must be able to be safely cast to Matcher<tuple<const
03841 // T1&, const T2&> >, where T1 and T2 are the types of elements in the
03842 // LHS container and the RHS container respectively.
03843 template <typename TupleMatcher, typename Container>
03844 inline internal::PointwiseMatcher<TupleMatcher,
03845                                   GTEST_REMOVE_CONST_(Container)>
03846 Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
03847   // This following line is for working around a bug in MSVC 8.0,
03848   // which causes Container to be a const type sometimes.
03849   typedef GTEST_REMOVE_CONST_(Container) RawContainer;
03850   return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
03851       tuple_matcher, rhs);
03852 }
03853 
03854 // Matches an STL-style container or a native array that contains at
03855 // least one element matching the given value or matcher.
03856 //
03857 // Examples:
03858 //   ::std::set<int> page_ids;
03859 //   page_ids.insert(3);
03860 //   page_ids.insert(1);
03861 //   EXPECT_THAT(page_ids, Contains(1));
03862 //   EXPECT_THAT(page_ids, Contains(Gt(2)));
03863 //   EXPECT_THAT(page_ids, Not(Contains(4)));
03864 //
03865 //   ::std::map<int, size_t> page_lengths;
03866 //   page_lengths[1] = 100;
03867 //   EXPECT_THAT(page_lengths,
03868 //               Contains(::std::pair<const int, size_t>(1, 100)));
03869 //
03870 //   const char* user_ids[] = { "joe", "mike", "tom" };
03871 //   EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
03872 template <typename M>
03873 inline internal::ContainsMatcher<M> Contains(M matcher) {
03874   return internal::ContainsMatcher<M>(matcher);
03875 }
03876 
03877 // Matches an STL-style container or a native array that contains only
03878 // elements matching the given value or matcher.
03879 //
03880 // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
03881 // the messages are different.
03882 //
03883 // Examples:
03884 //   ::std::set<int> page_ids;
03885 //   // Each(m) matches an empty container, regardless of what m is.
03886 //   EXPECT_THAT(page_ids, Each(Eq(1)));
03887 //   EXPECT_THAT(page_ids, Each(Eq(77)));
03888 //
03889 //   page_ids.insert(3);
03890 //   EXPECT_THAT(page_ids, Each(Gt(0)));
03891 //   EXPECT_THAT(page_ids, Not(Each(Gt(4))));
03892 //   page_ids.insert(1);
03893 //   EXPECT_THAT(page_ids, Not(Each(Lt(2))));
03894 //
03895 //   ::std::map<int, size_t> page_lengths;
03896 //   page_lengths[1] = 100;
03897 //   page_lengths[2] = 200;
03898 //   page_lengths[3] = 300;
03899 //   EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
03900 //   EXPECT_THAT(page_lengths, Each(Key(Le(3))));
03901 //
03902 //   const char* user_ids[] = { "joe", "mike", "tom" };
03903 //   EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
03904 template <typename M>
03905 inline internal::EachMatcher<M> Each(M matcher) {
03906   return internal::EachMatcher<M>(matcher);
03907 }
03908 
03909 // Key(inner_matcher) matches an std::pair whose 'first' field matches
03910 // inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
03911 // std::map that contains at least one element whose key is >= 5.
03912 template <typename M>
03913 inline internal::KeyMatcher<M> Key(M inner_matcher) {
03914   return internal::KeyMatcher<M>(inner_matcher);
03915 }
03916 
03917 // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
03918 // matches first_matcher and whose 'second' field matches second_matcher.  For
03919 // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
03920 // to match a std::map<int, string> that contains exactly one element whose key
03921 // is >= 5 and whose value equals "foo".
03922 template <typename FirstMatcher, typename SecondMatcher>
03923 inline internal::PairMatcher<FirstMatcher, SecondMatcher>
03924 Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
03925   return internal::PairMatcher<FirstMatcher, SecondMatcher>(
03926       first_matcher, second_matcher);
03927 }
03928 
03929 // Returns a predicate that is satisfied by anything that matches the
03930 // given matcher.
03931 template <typename M>
03932 inline internal::MatcherAsPredicate<M> Matches(M matcher) {
03933   return internal::MatcherAsPredicate<M>(matcher);
03934 }
03935 
03936 // Returns true iff the value matches the matcher.
03937 template <typename T, typename M>
03938 inline bool Value(const T& value, M matcher) {
03939   return testing::Matches(matcher)(value);
03940 }
03941 
03942 // Matches the value against the given matcher and explains the match
03943 // result to listener.
03944 template <typename T, typename M>
03945 inline bool ExplainMatchResult(
03946     M matcher, const T& value, MatchResultListener* listener) {
03947   return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
03948 }
03949 
03950 #if GTEST_LANG_CXX11
03951 // Define variadic matcher versions. They are overloaded in
03952 // gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
03953 template <typename... Args>
03954 inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
03955   return internal::AllOfMatcher<Args...>(matchers...);
03956 }
03957 
03958 template <typename... Args>
03959 inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
03960   return internal::AnyOfMatcher<Args...>(matchers...);
03961 }
03962 
03963 #endif  // GTEST_LANG_CXX11
03964 
03965 // AllArgs(m) is a synonym of m.  This is useful in
03966 //
03967 //   EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
03968 //
03969 // which is easier to read than
03970 //
03971 //   EXPECT_CALL(foo, Bar(_, _)).With(Eq());
03972 template <typename InnerMatcher>
03973 inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
03974 
03975 // These macros allow using matchers to check values in Google Test
03976 // tests.  ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
03977 // succeed iff the value matches the matcher.  If the assertion fails,
03978 // the value and the description of the matcher will be printed.
03979 #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
03980     ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
03981 #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
03982     ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
03983 
03984 }  // namespace testing
03985 
03986 #endif  // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_


ros_opcua_impl_freeopcua
Author(s): Denis Štogl
autogenerated on Sat Jun 8 2019 18:24:42