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