Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / testing / gmock / include / gmock / gmock-matchers.h
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 <math.h>
42 #include <algorithm>
43 #include <iterator>
44 #include <limits>
45 #include <ostream>  // NOLINT
46 #include <sstream>
47 #include <string>
48 #include <utility>
49 #include <vector>
50
51 #include "gmock/internal/gmock-internal-utils.h"
52 #include "gmock/internal/gmock-port.h"
53 #include "gtest/gtest.h"
54
55 #if GTEST_HAS_STD_INITIALIZER_LIST_
56 # include <initializer_list>  // NOLINT -- must be after gtest.h
57 #endif
58
59 namespace testing {
60
61 // To implement a matcher Foo for type T, define:
62 //   1. a class FooMatcherImpl that implements the
63 //      MatcherInterface<T> interface, and
64 //   2. a factory function that creates a Matcher<T> object from a
65 //      FooMatcherImpl*.
66 //
67 // The two-level delegation design makes it possible to allow a user
68 // to write "v" instead of "Eq(v)" where a Matcher is expected, which
69 // is impossible if we pass matchers by pointers.  It also eases
70 // ownership management as Matcher objects can now be copied like
71 // plain values.
72
73 // MatchResultListener is an abstract class.  Its << operator can be
74 // used by a matcher to explain why a value matches or doesn't match.
75 //
76 // TODO(wan@google.com): add method
77 //   bool InterestedInWhy(bool result) const;
78 // to indicate whether the listener is interested in why the match
79 // result is 'result'.
80 class MatchResultListener {
81  public:
82   // Creates a listener object with the given underlying ostream.  The
83   // listener does not own the ostream, and does not dereference it
84   // in the constructor or destructor.
85   explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
86   virtual ~MatchResultListener() = 0;  // Makes this class abstract.
87
88   // Streams x to the underlying ostream; does nothing if the ostream
89   // is NULL.
90   template <typename T>
91   MatchResultListener& operator<<(const T& x) {
92     if (stream_ != NULL)
93       *stream_ << x;
94     return *this;
95   }
96
97   // Returns the underlying ostream.
98   ::std::ostream* stream() { return stream_; }
99
100   // Returns true iff the listener is interested in an explanation of
101   // the match result.  A matcher's MatchAndExplain() method can use
102   // this information to avoid generating the explanation when no one
103   // intends to hear it.
104   bool IsInterested() const { return stream_ != NULL; }
105
106  private:
107   ::std::ostream* const stream_;
108
109   GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
110 };
111
112 inline MatchResultListener::~MatchResultListener() {
113 }
114
115 // An instance of a subclass of this knows how to describe itself as a
116 // matcher.
117 class MatcherDescriberInterface {
118  public:
119   virtual ~MatcherDescriberInterface() {}
120
121   // Describes this matcher to an ostream.  The function should print
122   // a verb phrase that describes the property a value matching this
123   // matcher should have.  The subject of the verb phrase is the value
124   // being matched.  For example, the DescribeTo() method of the Gt(7)
125   // matcher prints "is greater than 7".
126   virtual void DescribeTo(::std::ostream* os) const = 0;
127
128   // Describes the negation of this matcher to an ostream.  For
129   // example, if the description of this matcher is "is greater than
130   // 7", the negated description could be "is not greater than 7".
131   // You are not required to override this when implementing
132   // MatcherInterface, but it is highly advised so that your matcher
133   // can produce good error messages.
134   virtual void DescribeNegationTo(::std::ostream* os) const {
135     *os << "not (";
136     DescribeTo(os);
137     *os << ")";
138   }
139 };
140
141 // The implementation of a matcher.
142 template <typename T>
143 class MatcherInterface : public MatcherDescriberInterface {
144  public:
145   // Returns true iff the matcher matches x; also explains the match
146   // result to 'listener' if necessary (see the next paragraph), in
147   // the form of a non-restrictive relative clause ("which ...",
148   // "whose ...", etc) that describes x.  For example, the
149   // MatchAndExplain() method of the Pointee(...) matcher should
150   // generate an explanation like "which points to ...".
151   //
152   // Implementations of MatchAndExplain() should add an explanation of
153   // the match result *if and only if* they can provide additional
154   // information that's not already present (or not obvious) in the
155   // print-out of x and the matcher's description.  Whether the match
156   // succeeds is not a factor in deciding whether an explanation is
157   // needed, as sometimes the caller needs to print a failure message
158   // when the match succeeds (e.g. when the matcher is used inside
159   // Not()).
160   //
161   // For example, a "has at least 10 elements" matcher should explain
162   // what the actual element count is, regardless of the match result,
163   // as it is useful information to the reader; on the other hand, an
164   // "is empty" matcher probably only needs to explain what the actual
165   // size is when the match fails, as it's redundant to say that the
166   // size is 0 when the value is already known to be empty.
167   //
168   // You should override this method when defining a new matcher.
169   //
170   // It's the responsibility of the caller (Google Mock) to guarantee
171   // that 'listener' is not NULL.  This helps to simplify a matcher's
172   // implementation when it doesn't care about the performance, as it
173   // can talk to 'listener' without checking its validity first.
174   // However, in order to implement dummy listeners efficiently,
175   // listener->stream() may be NULL.
176   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
177
178   // Inherits these methods from MatcherDescriberInterface:
179   //   virtual void DescribeTo(::std::ostream* os) const = 0;
180   //   virtual void DescribeNegationTo(::std::ostream* os) const;
181 };
182
183 // A match result listener that stores the explanation in a string.
184 class StringMatchResultListener : public MatchResultListener {
185  public:
186   StringMatchResultListener() : MatchResultListener(&ss_) {}
187
188   // Returns the explanation accumulated so far.
189   internal::string str() const { return ss_.str(); }
190
191   // Clears the explanation accumulated so far.
192   void Clear() { ss_.str(""); }
193
194  private:
195   ::std::stringstream ss_;
196
197   GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
198 };
199
200 namespace internal {
201
202 // A match result listener that ignores the explanation.
203 class DummyMatchResultListener : public MatchResultListener {
204  public:
205   DummyMatchResultListener() : MatchResultListener(NULL) {}
206
207  private:
208   GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
209 };
210
211 // A match result listener that forwards the explanation to a given
212 // ostream.  The difference between this and MatchResultListener is
213 // that the former is concrete.
214 class StreamMatchResultListener : public MatchResultListener {
215  public:
216   explicit StreamMatchResultListener(::std::ostream* os)
217       : MatchResultListener(os) {}
218
219  private:
220   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
221 };
222
223 // An internal class for implementing Matcher<T>, which will derive
224 // from it.  We put functionalities common to all Matcher<T>
225 // specializations here to avoid code duplication.
226 template <typename T>
227 class MatcherBase {
228  public:
229   // Returns true iff the matcher matches x; also explains the match
230   // result to 'listener'.
231   bool MatchAndExplain(T x, MatchResultListener* listener) const {
232     return impl_->MatchAndExplain(x, listener);
233   }
234
235   // Returns true iff this matcher matches x.
236   bool Matches(T x) const {
237     DummyMatchResultListener dummy;
238     return MatchAndExplain(x, &dummy);
239   }
240
241   // Describes this matcher to an ostream.
242   void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
243
244   // Describes the negation of this matcher to an ostream.
245   void DescribeNegationTo(::std::ostream* os) const {
246     impl_->DescribeNegationTo(os);
247   }
248
249   // Explains why x matches, or doesn't match, the matcher.
250   void ExplainMatchResultTo(T x, ::std::ostream* os) const {
251     StreamMatchResultListener listener(os);
252     MatchAndExplain(x, &listener);
253   }
254
255   // Returns the describer for this matcher object; retains ownership
256   // of the describer, which is only guaranteed to be alive when
257   // this matcher object is alive.
258   const MatcherDescriberInterface* GetDescriber() const {
259     return impl_.get();
260   }
261
262  protected:
263   MatcherBase() {}
264
265   // Constructs a matcher from its implementation.
266   explicit MatcherBase(const MatcherInterface<T>* impl)
267       : impl_(impl) {}
268
269   virtual ~MatcherBase() {}
270
271  private:
272   // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
273   // interfaces.  The former dynamically allocates a chunk of memory
274   // to hold the reference count, while the latter tracks all
275   // references using a circular linked list without allocating
276   // memory.  It has been observed that linked_ptr performs better in
277   // typical scenarios.  However, shared_ptr can out-perform
278   // linked_ptr when there are many more uses of the copy constructor
279   // than the default constructor.
280   //
281   // If performance becomes a problem, we should see if using
282   // shared_ptr helps.
283   ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
284 };
285
286 }  // namespace internal
287
288 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
289 // object that can check whether a value of type T matches.  The
290 // implementation of Matcher<T> is just a linked_ptr to const
291 // MatcherInterface<T>, so copying is fairly cheap.  Don't inherit
292 // from Matcher!
293 template <typename T>
294 class Matcher : public internal::MatcherBase<T> {
295  public:
296   // Constructs a null matcher.  Needed for storing Matcher objects in STL
297   // containers.  A default-constructed matcher is not yet initialized.  You
298   // cannot use it until a valid value has been assigned to it.
299   Matcher() {}
300
301   // Constructs a matcher from its implementation.
302   explicit Matcher(const MatcherInterface<T>* impl)
303       : internal::MatcherBase<T>(impl) {}
304
305   // Implicit constructor here allows people to write
306   // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
307   Matcher(T value);  // NOLINT
308 };
309
310 // The following two specializations allow the user to write str
311 // instead of Eq(str) and "foo" instead of Eq("foo") when a string
312 // matcher is expected.
313 template <>
314 class GTEST_API_ Matcher<const internal::string&>
315     : public internal::MatcherBase<const internal::string&> {
316  public:
317   Matcher() {}
318
319   explicit Matcher(const MatcherInterface<const internal::string&>* impl)
320       : internal::MatcherBase<const internal::string&>(impl) {}
321
322   // Allows the user to write str instead of Eq(str) sometimes, where
323   // str is a string object.
324   Matcher(const internal::string& s);  // NOLINT
325
326   // Allows the user to write "foo" instead of Eq("foo") sometimes.
327   Matcher(const char* s);  // NOLINT
328 };
329
330 template <>
331 class GTEST_API_ Matcher<internal::string>
332     : public internal::MatcherBase<internal::string> {
333  public:
334   Matcher() {}
335
336   explicit Matcher(const MatcherInterface<internal::string>* impl)
337       : internal::MatcherBase<internal::string>(impl) {}
338
339   // Allows the user to write str instead of Eq(str) sometimes, where
340   // str is a string object.
341   Matcher(const internal::string& s);  // NOLINT
342
343   // Allows the user to write "foo" instead of Eq("foo") sometimes.
344   Matcher(const char* s);  // NOLINT
345 };
346
347 #if GTEST_HAS_STRING_PIECE_
348 // The following two specializations allow the user to write str
349 // instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece
350 // matcher is expected.
351 template <>
352 class GTEST_API_ Matcher<const StringPiece&>
353     : public internal::MatcherBase<const StringPiece&> {
354  public:
355   Matcher() {}
356
357   explicit Matcher(const MatcherInterface<const StringPiece&>* impl)
358       : internal::MatcherBase<const StringPiece&>(impl) {}
359
360   // Allows the user to write str instead of Eq(str) sometimes, where
361   // str is a string object.
362   Matcher(const internal::string& s);  // NOLINT
363
364   // Allows the user to write "foo" instead of Eq("foo") sometimes.
365   Matcher(const char* s);  // NOLINT
366
367   // Allows the user to pass StringPieces directly.
368   Matcher(StringPiece s);  // NOLINT
369 };
370
371 template <>
372 class GTEST_API_ Matcher<StringPiece>
373     : public internal::MatcherBase<StringPiece> {
374  public:
375   Matcher() {}
376
377   explicit Matcher(const MatcherInterface<StringPiece>* impl)
378       : internal::MatcherBase<StringPiece>(impl) {}
379
380   // Allows the user to write str instead of Eq(str) sometimes, where
381   // str is a string object.
382   Matcher(const internal::string& s);  // NOLINT
383
384   // Allows the user to write "foo" instead of Eq("foo") sometimes.
385   Matcher(const char* s);  // NOLINT
386
387   // Allows the user to pass StringPieces directly.
388   Matcher(StringPiece s);  // NOLINT
389 };
390 #endif  // GTEST_HAS_STRING_PIECE_
391
392 // The PolymorphicMatcher class template makes it easy to implement a
393 // polymorphic matcher (i.e. a matcher that can match values of more
394 // than one type, e.g. Eq(n) and NotNull()).
395 //
396 // To define a polymorphic matcher, a user should provide an Impl
397 // class that has a DescribeTo() method and a DescribeNegationTo()
398 // method, and define a member function (or member function template)
399 //
400 //   bool MatchAndExplain(const Value& value,
401 //                        MatchResultListener* listener) const;
402 //
403 // See the definition of NotNull() for a complete example.
404 template <class Impl>
405 class PolymorphicMatcher {
406  public:
407   explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
408
409   // Returns a mutable reference to the underlying matcher
410   // implementation object.
411   Impl& mutable_impl() { return impl_; }
412
413   // Returns an immutable reference to the underlying matcher
414   // implementation object.
415   const Impl& impl() const { return impl_; }
416
417   template <typename T>
418   operator Matcher<T>() const {
419     return Matcher<T>(new MonomorphicImpl<T>(impl_));
420   }
421
422  private:
423   template <typename T>
424   class MonomorphicImpl : public MatcherInterface<T> {
425    public:
426     explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
427
428     virtual void DescribeTo(::std::ostream* os) const {
429       impl_.DescribeTo(os);
430     }
431
432     virtual void DescribeNegationTo(::std::ostream* os) const {
433       impl_.DescribeNegationTo(os);
434     }
435
436     virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
437       return impl_.MatchAndExplain(x, listener);
438     }
439
440    private:
441     const Impl impl_;
442
443     GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
444   };
445
446   Impl impl_;
447
448   GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
449 };
450
451 // Creates a matcher from its implementation.  This is easier to use
452 // than the Matcher<T> constructor as it doesn't require you to
453 // explicitly write the template argument, e.g.
454 //
455 //   MakeMatcher(foo);
456 // vs
457 //   Matcher<const string&>(foo);
458 template <typename T>
459 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
460   return Matcher<T>(impl);
461 }
462
463 // Creates a polymorphic matcher from its implementation.  This is
464 // easier to use than the PolymorphicMatcher<Impl> constructor as it
465 // doesn't require you to explicitly write the template argument, e.g.
466 //
467 //   MakePolymorphicMatcher(foo);
468 // vs
469 //   PolymorphicMatcher<TypeOfFoo>(foo);
470 template <class Impl>
471 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
472   return PolymorphicMatcher<Impl>(impl);
473 }
474
475 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
476 // and MUST NOT BE USED IN USER CODE!!!
477 namespace internal {
478
479 // The MatcherCastImpl class template is a helper for implementing
480 // MatcherCast().  We need this helper in order to partially
481 // specialize the implementation of MatcherCast() (C++ allows
482 // class/struct templates to be partially specialized, but not
483 // function templates.).
484
485 // This general version is used when MatcherCast()'s argument is a
486 // polymorphic matcher (i.e. something that can be converted to a
487 // Matcher but is not one yet; for example, Eq(value)) or a value (for
488 // example, "hello").
489 template <typename T, typename M>
490 class MatcherCastImpl {
491  public:
492   static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
493     // M can be a polymorhic matcher, in which case we want to use
494     // its conversion operator to create Matcher<T>.  Or it can be a value
495     // that should be passed to the Matcher<T>'s constructor.
496     //
497     // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
498     // polymorphic matcher because it'll be ambiguous if T has an implicit
499     // constructor from M (this usually happens when T has an implicit
500     // constructor from any type).
501     //
502     // It won't work to unconditionally implict_cast
503     // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
504     // a user-defined conversion from M to T if one exists (assuming M is
505     // a value).
506     return CastImpl(
507         polymorphic_matcher_or_value,
508         BooleanConstant<
509             internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
510   }
511
512  private:
513   static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) {
514     // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
515     // matcher.  It must be a value then.  Use direct initialization to create
516     // a matcher.
517     return Matcher<T>(ImplicitCast_<T>(value));
518   }
519
520   static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
521                              BooleanConstant<true>) {
522     // M is implicitly convertible to Matcher<T>, which means that either
523     // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
524     // from M.  In both cases using the implicit conversion will produce a
525     // matcher.
526     //
527     // Even if T has an implicit constructor from M, it won't be called because
528     // creating Matcher<T> would require a chain of two user-defined conversions
529     // (first to create T from M and then to create Matcher<T> from T).
530     return polymorphic_matcher_or_value;
531   }
532 };
533
534 // This more specialized version is used when MatcherCast()'s argument
535 // is already a Matcher.  This only compiles when type T can be
536 // statically converted to type U.
537 template <typename T, typename U>
538 class MatcherCastImpl<T, Matcher<U> > {
539  public:
540   static Matcher<T> Cast(const Matcher<U>& source_matcher) {
541     return Matcher<T>(new Impl(source_matcher));
542   }
543
544  private:
545   class Impl : public MatcherInterface<T> {
546    public:
547     explicit Impl(const Matcher<U>& source_matcher)
548         : source_matcher_(source_matcher) {}
549
550     // We delegate the matching logic to the source matcher.
551     virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
552       return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
553     }
554
555     virtual void DescribeTo(::std::ostream* os) const {
556       source_matcher_.DescribeTo(os);
557     }
558
559     virtual void DescribeNegationTo(::std::ostream* os) const {
560       source_matcher_.DescribeNegationTo(os);
561     }
562
563    private:
564     const Matcher<U> source_matcher_;
565
566     GTEST_DISALLOW_ASSIGN_(Impl);
567   };
568 };
569
570 // This even more specialized version is used for efficiently casting
571 // a matcher to its own type.
572 template <typename T>
573 class MatcherCastImpl<T, Matcher<T> > {
574  public:
575   static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
576 };
577
578 }  // namespace internal
579
580 // In order to be safe and clear, casting between different matcher
581 // types is done explicitly via MatcherCast<T>(m), which takes a
582 // matcher m and returns a Matcher<T>.  It compiles only when T can be
583 // statically converted to the argument type of m.
584 template <typename T, typename M>
585 inline Matcher<T> MatcherCast(const M& matcher) {
586   return internal::MatcherCastImpl<T, M>::Cast(matcher);
587 }
588
589 // Implements SafeMatcherCast().
590 //
591 // We use an intermediate class to do the actual safe casting as Nokia's
592 // Symbian compiler cannot decide between
593 // template <T, M> ... (M) and
594 // template <T, U> ... (const Matcher<U>&)
595 // for function templates but can for member function templates.
596 template <typename T>
597 class SafeMatcherCastImpl {
598  public:
599   // This overload handles polymorphic matchers and values only since
600   // monomorphic matchers are handled by the next one.
601   template <typename M>
602   static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
603     return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
604   }
605
606   // This overload handles monomorphic matchers.
607   //
608   // In general, if type T can be implicitly converted to type U, we can
609   // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
610   // contravariant): just keep a copy of the original Matcher<U>, convert the
611   // argument from type T to U, and then pass it to the underlying Matcher<U>.
612   // The only exception is when U is a reference and T is not, as the
613   // underlying Matcher<U> may be interested in the argument's address, which
614   // is not preserved in the conversion from T to U.
615   template <typename U>
616   static inline Matcher<T> Cast(const Matcher<U>& matcher) {
617     // Enforce that T can be implicitly converted to U.
618     GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
619                           T_must_be_implicitly_convertible_to_U);
620     // Enforce that we are not converting a non-reference type T to a reference
621     // type U.
622     GTEST_COMPILE_ASSERT_(
623         internal::is_reference<T>::value || !internal::is_reference<U>::value,
624         cannot_convert_non_referentce_arg_to_reference);
625     // In case both T and U are arithmetic types, enforce that the
626     // conversion is not lossy.
627     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
628     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
629     const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
630     const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
631     GTEST_COMPILE_ASSERT_(
632         kTIsOther || kUIsOther ||
633         (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
634         conversion_of_arithmetic_types_must_be_lossless);
635     return MatcherCast<T>(matcher);
636   }
637 };
638
639 template <typename T, typename M>
640 inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
641   return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
642 }
643
644 // A<T>() returns a matcher that matches any value of type T.
645 template <typename T>
646 Matcher<T> A();
647
648 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
649 // and MUST NOT BE USED IN USER CODE!!!
650 namespace internal {
651
652 // If the explanation is not empty, prints it to the ostream.
653 inline void PrintIfNotEmpty(const internal::string& explanation,
654                             ::std::ostream* os) {
655   if (explanation != "" && os != NULL) {
656     *os << ", " << explanation;
657   }
658 }
659
660 // Returns true if the given type name is easy to read by a human.
661 // This is used to decide whether printing the type of a value might
662 // be helpful.
663 inline bool IsReadableTypeName(const string& type_name) {
664   // We consider a type name readable if it's short or doesn't contain
665   // a template or function type.
666   return (type_name.length() <= 20 ||
667           type_name.find_first_of("<(") == string::npos);
668 }
669
670 // Matches the value against the given matcher, prints the value and explains
671 // the match result to the listener. Returns the match result.
672 // 'listener' must not be NULL.
673 // Value cannot be passed by const reference, because some matchers take a
674 // non-const argument.
675 template <typename Value, typename T>
676 bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
677                           MatchResultListener* listener) {
678   if (!listener->IsInterested()) {
679     // If the listener is not interested, we do not need to construct the
680     // inner explanation.
681     return matcher.Matches(value);
682   }
683
684   StringMatchResultListener inner_listener;
685   const bool match = matcher.MatchAndExplain(value, &inner_listener);
686
687   UniversalPrint(value, listener->stream());
688 #if GTEST_HAS_RTTI
689   const string& type_name = GetTypeName<Value>();
690   if (IsReadableTypeName(type_name))
691     *listener->stream() << " (of type " << type_name << ")";
692 #endif
693   PrintIfNotEmpty(inner_listener.str(), listener->stream());
694
695   return match;
696 }
697
698 // An internal helper class for doing compile-time loop on a tuple's
699 // fields.
700 template <size_t N>
701 class TuplePrefix {
702  public:
703   // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
704   // iff the first N fields of matcher_tuple matches the first N
705   // fields of value_tuple, respectively.
706   template <typename MatcherTuple, typename ValueTuple>
707   static bool Matches(const MatcherTuple& matcher_tuple,
708                       const ValueTuple& value_tuple) {
709     return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
710         && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
711   }
712
713   // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
714   // describes failures in matching the first N fields of matchers
715   // against the first N fields of values.  If there is no failure,
716   // nothing will be streamed to os.
717   template <typename MatcherTuple, typename ValueTuple>
718   static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
719                                      const ValueTuple& values,
720                                      ::std::ostream* os) {
721     // First, describes failures in the first N - 1 fields.
722     TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
723
724     // Then describes the failure (if any) in the (N - 1)-th (0-based)
725     // field.
726     typename tuple_element<N - 1, MatcherTuple>::type matcher =
727         get<N - 1>(matchers);
728     typedef typename tuple_element<N - 1, ValueTuple>::type Value;
729     Value value = get<N - 1>(values);
730     StringMatchResultListener listener;
731     if (!matcher.MatchAndExplain(value, &listener)) {
732       // TODO(wan): include in the message the name of the parameter
733       // as used in MOCK_METHOD*() when possible.
734       *os << "  Expected arg #" << N - 1 << ": ";
735       get<N - 1>(matchers).DescribeTo(os);
736       *os << "\n           Actual: ";
737       // We remove the reference in type Value to prevent the
738       // universal printer from printing the address of value, which
739       // isn't interesting to the user most of the time.  The
740       // matcher's MatchAndExplain() method handles the case when
741       // the address is interesting.
742       internal::UniversalPrint(value, os);
743       PrintIfNotEmpty(listener.str(), os);
744       *os << "\n";
745     }
746   }
747 };
748
749 // The base case.
750 template <>
751 class TuplePrefix<0> {
752  public:
753   template <typename MatcherTuple, typename ValueTuple>
754   static bool Matches(const MatcherTuple& /* matcher_tuple */,
755                       const ValueTuple& /* value_tuple */) {
756     return true;
757   }
758
759   template <typename MatcherTuple, typename ValueTuple>
760   static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
761                                      const ValueTuple& /* values */,
762                                      ::std::ostream* /* os */) {}
763 };
764
765 // TupleMatches(matcher_tuple, value_tuple) returns true iff all
766 // matchers in matcher_tuple match the corresponding fields in
767 // value_tuple.  It is a compiler error if matcher_tuple and
768 // value_tuple have different number of fields or incompatible field
769 // types.
770 template <typename MatcherTuple, typename ValueTuple>
771 bool TupleMatches(const MatcherTuple& matcher_tuple,
772                   const ValueTuple& value_tuple) {
773   // Makes sure that matcher_tuple and value_tuple have the same
774   // number of fields.
775   GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
776                         tuple_size<ValueTuple>::value,
777                         matcher_and_value_have_different_numbers_of_fields);
778   return TuplePrefix<tuple_size<ValueTuple>::value>::
779       Matches(matcher_tuple, value_tuple);
780 }
781
782 // Describes failures in matching matchers against values.  If there
783 // is no failure, nothing will be streamed to os.
784 template <typename MatcherTuple, typename ValueTuple>
785 void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
786                                 const ValueTuple& values,
787                                 ::std::ostream* os) {
788   TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
789       matchers, values, os);
790 }
791
792 // TransformTupleValues and its helper.
793 //
794 // TransformTupleValuesHelper hides the internal machinery that
795 // TransformTupleValues uses to implement a tuple traversal.
796 template <typename Tuple, typename Func, typename OutIter>
797 class TransformTupleValuesHelper {
798  private:
799   typedef ::testing::tuple_size<Tuple> TupleSize;
800
801  public:
802   // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
803   // Returns the final value of 'out' in case the caller needs it.
804   static OutIter Run(Func f, const Tuple& t, OutIter out) {
805     return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
806   }
807
808  private:
809   template <typename Tup, size_t kRemainingSize>
810   struct IterateOverTuple {
811     OutIter operator() (Func f, const Tup& t, OutIter out) const {
812       *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
813       return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
814     }
815   };
816   template <typename Tup>
817   struct IterateOverTuple<Tup, 0> {
818     OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
819       return out;
820     }
821   };
822 };
823
824 // Successively invokes 'f(element)' on each element of the tuple 't',
825 // appending each result to the 'out' iterator. Returns the final value
826 // of 'out'.
827 template <typename Tuple, typename Func, typename OutIter>
828 OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
829   return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
830 }
831
832 // Implements A<T>().
833 template <typename T>
834 class AnyMatcherImpl : public MatcherInterface<T> {
835  public:
836   virtual bool MatchAndExplain(
837       T /* x */, MatchResultListener* /* listener */) const { return true; }
838   virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
839   virtual void DescribeNegationTo(::std::ostream* os) const {
840     // This is mostly for completeness' safe, as it's not very useful
841     // to write Not(A<bool>()).  However we cannot completely rule out
842     // such a possibility, and it doesn't hurt to be prepared.
843     *os << "never matches";
844   }
845 };
846
847 // Implements _, a matcher that matches any value of any
848 // type.  This is a polymorphic matcher, so we need a template type
849 // conversion operator to make it appearing as a Matcher<T> for any
850 // type T.
851 class AnythingMatcher {
852  public:
853   template <typename T>
854   operator Matcher<T>() const { return A<T>(); }
855 };
856
857 // Implements a matcher that compares a given value with a
858 // pre-supplied value using one of the ==, <=, <, etc, operators.  The
859 // two values being compared don't have to have the same type.
860 //
861 // The matcher defined here is polymorphic (for example, Eq(5) can be
862 // used to match an int, a short, a double, etc).  Therefore we use
863 // a template type conversion operator in the implementation.
864 //
865 // We define this as a macro in order to eliminate duplicated source
866 // code.
867 //
868 // The following template definition assumes that the Rhs parameter is
869 // a "bare" type (i.e. neither 'const T' nor 'T&').
870 #define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
871     name, op, relation, negated_relation) \
872   template <typename Rhs> class name##Matcher { \
873    public: \
874     explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
875     template <typename Lhs> \
876     operator Matcher<Lhs>() const { \
877       return MakeMatcher(new Impl<Lhs>(rhs_)); \
878     } \
879    private: \
880     template <typename Lhs> \
881     class Impl : public MatcherInterface<Lhs> { \
882      public: \
883       explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
884       virtual bool MatchAndExplain(\
885           Lhs lhs, MatchResultListener* /* listener */) const { \
886         return lhs op rhs_; \
887       } \
888       virtual void DescribeTo(::std::ostream* os) const { \
889         *os << relation  " "; \
890         UniversalPrint(rhs_, os); \
891       } \
892       virtual void DescribeNegationTo(::std::ostream* os) const { \
893         *os << negated_relation  " "; \
894         UniversalPrint(rhs_, os); \
895       } \
896      private: \
897       Rhs rhs_; \
898       GTEST_DISALLOW_ASSIGN_(Impl); \
899     }; \
900     Rhs rhs_; \
901     GTEST_DISALLOW_ASSIGN_(name##Matcher); \
902   }
903
904 // Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
905 // respectively.
906 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
907 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
908 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
909 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
910 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
911 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
912
913 #undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
914
915 // Implements the polymorphic IsNull() matcher, which matches any raw or smart
916 // pointer that is NULL.
917 class IsNullMatcher {
918  public:
919   template <typename Pointer>
920   bool MatchAndExplain(const Pointer& p,
921                        MatchResultListener* /* listener */) const {
922     return GetRawPointer(p) == NULL;
923   }
924
925   void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
926   void DescribeNegationTo(::std::ostream* os) const {
927     *os << "isn't NULL";
928   }
929 };
930
931 // Implements the polymorphic NotNull() matcher, which matches any raw or smart
932 // pointer that is not NULL.
933 class NotNullMatcher {
934  public:
935   template <typename Pointer>
936   bool MatchAndExplain(const Pointer& p,
937                        MatchResultListener* /* listener */) const {
938     return GetRawPointer(p) != NULL;
939   }
940
941   void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
942   void DescribeNegationTo(::std::ostream* os) const {
943     *os << "is NULL";
944   }
945 };
946
947 // Ref(variable) matches any argument that is a reference to
948 // 'variable'.  This matcher is polymorphic as it can match any
949 // super type of the type of 'variable'.
950 //
951 // The RefMatcher template class implements Ref(variable).  It can
952 // only be instantiated with a reference type.  This prevents a user
953 // from mistakenly using Ref(x) to match a non-reference function
954 // argument.  For example, the following will righteously cause a
955 // compiler error:
956 //
957 //   int n;
958 //   Matcher<int> m1 = Ref(n);   // This won't compile.
959 //   Matcher<int&> m2 = Ref(n);  // This will compile.
960 template <typename T>
961 class RefMatcher;
962
963 template <typename T>
964 class RefMatcher<T&> {
965   // Google Mock is a generic framework and thus needs to support
966   // mocking any function types, including those that take non-const
967   // reference arguments.  Therefore the template parameter T (and
968   // Super below) can be instantiated to either a const type or a
969   // non-const type.
970  public:
971   // RefMatcher() takes a T& instead of const T&, as we want the
972   // compiler to catch using Ref(const_value) as a matcher for a
973   // non-const reference.
974   explicit RefMatcher(T& x) : object_(x) {}  // NOLINT
975
976   template <typename Super>
977   operator Matcher<Super&>() const {
978     // By passing object_ (type T&) to Impl(), which expects a Super&,
979     // we make sure that Super is a super type of T.  In particular,
980     // this catches using Ref(const_value) as a matcher for a
981     // non-const reference, as you cannot implicitly convert a const
982     // reference to a non-const reference.
983     return MakeMatcher(new Impl<Super>(object_));
984   }
985
986  private:
987   template <typename Super>
988   class Impl : public MatcherInterface<Super&> {
989    public:
990     explicit Impl(Super& x) : object_(x) {}  // NOLINT
991
992     // MatchAndExplain() takes a Super& (as opposed to const Super&)
993     // in order to match the interface MatcherInterface<Super&>.
994     virtual bool MatchAndExplain(
995         Super& x, MatchResultListener* listener) const {
996       *listener << "which is located @" << static_cast<const void*>(&x);
997       return &x == &object_;
998     }
999
1000     virtual void DescribeTo(::std::ostream* os) const {
1001       *os << "references the variable ";
1002       UniversalPrinter<Super&>::Print(object_, os);
1003     }
1004
1005     virtual void DescribeNegationTo(::std::ostream* os) const {
1006       *os << "does not reference the variable ";
1007       UniversalPrinter<Super&>::Print(object_, os);
1008     }
1009
1010    private:
1011     const Super& object_;
1012
1013     GTEST_DISALLOW_ASSIGN_(Impl);
1014   };
1015
1016   T& object_;
1017
1018   GTEST_DISALLOW_ASSIGN_(RefMatcher);
1019 };
1020
1021 // Polymorphic helper functions for narrow and wide string matchers.
1022 inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1023   return String::CaseInsensitiveCStringEquals(lhs, rhs);
1024 }
1025
1026 inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1027                                          const wchar_t* rhs) {
1028   return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1029 }
1030
1031 // String comparison for narrow or wide strings that can have embedded NUL
1032 // characters.
1033 template <typename StringType>
1034 bool CaseInsensitiveStringEquals(const StringType& s1,
1035                                  const StringType& s2) {
1036   // Are the heads equal?
1037   if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1038     return false;
1039   }
1040
1041   // Skip the equal heads.
1042   const typename StringType::value_type nul = 0;
1043   const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1044
1045   // Are we at the end of either s1 or s2?
1046   if (i1 == StringType::npos || i2 == StringType::npos) {
1047     return i1 == i2;
1048   }
1049
1050   // Are the tails equal?
1051   return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1052 }
1053
1054 // String matchers.
1055
1056 // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1057 template <typename StringType>
1058 class StrEqualityMatcher {
1059  public:
1060   StrEqualityMatcher(const StringType& str, bool expect_eq,
1061                      bool case_sensitive)
1062       : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1063
1064   // Accepts pointer types, particularly:
1065   //   const char*
1066   //   char*
1067   //   const wchar_t*
1068   //   wchar_t*
1069   template <typename CharType>
1070   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1071     if (s == NULL) {
1072       return !expect_eq_;
1073     }
1074     return MatchAndExplain(StringType(s), listener);
1075   }
1076
1077   // Matches anything that can convert to StringType.
1078   //
1079   // This is a template, not just a plain function with const StringType&,
1080   // because StringPiece has some interfering non-explicit constructors.
1081   template <typename MatcheeStringType>
1082   bool MatchAndExplain(const MatcheeStringType& s,
1083                        MatchResultListener* /* listener */) const {
1084     const StringType& s2(s);
1085     const bool eq = case_sensitive_ ? s2 == string_ :
1086         CaseInsensitiveStringEquals(s2, string_);
1087     return expect_eq_ == eq;
1088   }
1089
1090   void DescribeTo(::std::ostream* os) const {
1091     DescribeToHelper(expect_eq_, os);
1092   }
1093
1094   void DescribeNegationTo(::std::ostream* os) const {
1095     DescribeToHelper(!expect_eq_, os);
1096   }
1097
1098  private:
1099   void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
1100     *os << (expect_eq ? "is " : "isn't ");
1101     *os << "equal to ";
1102     if (!case_sensitive_) {
1103       *os << "(ignoring case) ";
1104     }
1105     UniversalPrint(string_, os);
1106   }
1107
1108   const StringType string_;
1109   const bool expect_eq_;
1110   const bool case_sensitive_;
1111
1112   GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
1113 };
1114
1115 // Implements the polymorphic HasSubstr(substring) matcher, which
1116 // can be used as a Matcher<T> as long as T can be converted to a
1117 // string.
1118 template <typename StringType>
1119 class HasSubstrMatcher {
1120  public:
1121   explicit HasSubstrMatcher(const StringType& substring)
1122       : substring_(substring) {}
1123
1124   // Accepts pointer types, particularly:
1125   //   const char*
1126   //   char*
1127   //   const wchar_t*
1128   //   wchar_t*
1129   template <typename CharType>
1130   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1131     return s != NULL && MatchAndExplain(StringType(s), listener);
1132   }
1133
1134   // Matches anything that can convert to StringType.
1135   //
1136   // This is a template, not just a plain function with const StringType&,
1137   // because StringPiece has some interfering non-explicit constructors.
1138   template <typename MatcheeStringType>
1139   bool MatchAndExplain(const MatcheeStringType& s,
1140                        MatchResultListener* /* listener */) const {
1141     const StringType& s2(s);
1142     return s2.find(substring_) != StringType::npos;
1143   }
1144
1145   // Describes what this matcher matches.
1146   void DescribeTo(::std::ostream* os) const {
1147     *os << "has substring ";
1148     UniversalPrint(substring_, os);
1149   }
1150
1151   void DescribeNegationTo(::std::ostream* os) const {
1152     *os << "has no substring ";
1153     UniversalPrint(substring_, os);
1154   }
1155
1156  private:
1157   const StringType substring_;
1158
1159   GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
1160 };
1161
1162 // Implements the polymorphic StartsWith(substring) matcher, which
1163 // can be used as a Matcher<T> as long as T can be converted to a
1164 // string.
1165 template <typename StringType>
1166 class StartsWithMatcher {
1167  public:
1168   explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1169   }
1170
1171   // Accepts pointer types, particularly:
1172   //   const char*
1173   //   char*
1174   //   const wchar_t*
1175   //   wchar_t*
1176   template <typename CharType>
1177   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1178     return s != NULL && MatchAndExplain(StringType(s), listener);
1179   }
1180
1181   // Matches anything that can convert to StringType.
1182   //
1183   // This is a template, not just a plain function with const StringType&,
1184   // because StringPiece has some interfering non-explicit constructors.
1185   template <typename MatcheeStringType>
1186   bool MatchAndExplain(const MatcheeStringType& s,
1187                        MatchResultListener* /* listener */) const {
1188     const StringType& s2(s);
1189     return s2.length() >= prefix_.length() &&
1190         s2.substr(0, prefix_.length()) == prefix_;
1191   }
1192
1193   void DescribeTo(::std::ostream* os) const {
1194     *os << "starts with ";
1195     UniversalPrint(prefix_, os);
1196   }
1197
1198   void DescribeNegationTo(::std::ostream* os) const {
1199     *os << "doesn't start with ";
1200     UniversalPrint(prefix_, os);
1201   }
1202
1203  private:
1204   const StringType prefix_;
1205
1206   GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
1207 };
1208
1209 // Implements the polymorphic EndsWith(substring) matcher, which
1210 // can be used as a Matcher<T> as long as T can be converted to a
1211 // string.
1212 template <typename StringType>
1213 class EndsWithMatcher {
1214  public:
1215   explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1216
1217   // Accepts pointer types, particularly:
1218   //   const char*
1219   //   char*
1220   //   const wchar_t*
1221   //   wchar_t*
1222   template <typename CharType>
1223   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1224     return s != NULL && MatchAndExplain(StringType(s), listener);
1225   }
1226
1227   // Matches anything that can convert to StringType.
1228   //
1229   // This is a template, not just a plain function with const StringType&,
1230   // because StringPiece has some interfering non-explicit constructors.
1231   template <typename MatcheeStringType>
1232   bool MatchAndExplain(const MatcheeStringType& s,
1233                        MatchResultListener* /* listener */) const {
1234     const StringType& s2(s);
1235     return s2.length() >= suffix_.length() &&
1236         s2.substr(s2.length() - suffix_.length()) == suffix_;
1237   }
1238
1239   void DescribeTo(::std::ostream* os) const {
1240     *os << "ends with ";
1241     UniversalPrint(suffix_, os);
1242   }
1243
1244   void DescribeNegationTo(::std::ostream* os) const {
1245     *os << "doesn't end with ";
1246     UniversalPrint(suffix_, os);
1247   }
1248
1249  private:
1250   const StringType suffix_;
1251
1252   GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
1253 };
1254
1255 // Implements polymorphic matchers MatchesRegex(regex) and
1256 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
1257 // T can be converted to a string.
1258 class MatchesRegexMatcher {
1259  public:
1260   MatchesRegexMatcher(const RE* regex, bool full_match)
1261       : regex_(regex), full_match_(full_match) {}
1262
1263   // Accepts pointer types, particularly:
1264   //   const char*
1265   //   char*
1266   //   const wchar_t*
1267   //   wchar_t*
1268   template <typename CharType>
1269   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1270     return s != NULL && MatchAndExplain(internal::string(s), listener);
1271   }
1272
1273   // Matches anything that can convert to internal::string.
1274   //
1275   // This is a template, not just a plain function with const internal::string&,
1276   // because StringPiece has some interfering non-explicit constructors.
1277   template <class MatcheeStringType>
1278   bool MatchAndExplain(const MatcheeStringType& s,
1279                        MatchResultListener* /* listener */) const {
1280     const internal::string& s2(s);
1281     return full_match_ ? RE::FullMatch(s2, *regex_) :
1282         RE::PartialMatch(s2, *regex_);
1283   }
1284
1285   void DescribeTo(::std::ostream* os) const {
1286     *os << (full_match_ ? "matches" : "contains")
1287         << " regular expression ";
1288     UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1289   }
1290
1291   void DescribeNegationTo(::std::ostream* os) const {
1292     *os << "doesn't " << (full_match_ ? "match" : "contain")
1293         << " regular expression ";
1294     UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1295   }
1296
1297  private:
1298   const internal::linked_ptr<const RE> regex_;
1299   const bool full_match_;
1300
1301   GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
1302 };
1303
1304 // Implements a matcher that compares the two fields of a 2-tuple
1305 // using one of the ==, <=, <, etc, operators.  The two fields being
1306 // compared don't have to have the same type.
1307 //
1308 // The matcher defined here is polymorphic (for example, Eq() can be
1309 // used to match a tuple<int, short>, a tuple<const long&, double>,
1310 // etc).  Therefore we use a template type conversion operator in the
1311 // implementation.
1312 //
1313 // We define this as a macro in order to eliminate duplicated source
1314 // code.
1315 #define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
1316   class name##2Matcher { \
1317    public: \
1318     template <typename T1, typename T2> \
1319     operator Matcher< ::testing::tuple<T1, T2> >() const { \
1320       return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >); \
1321     } \
1322     template <typename T1, typename T2> \
1323     operator Matcher<const ::testing::tuple<T1, T2>&>() const { \
1324       return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>); \
1325     } \
1326    private: \
1327     template <typename Tuple> \
1328     class Impl : public MatcherInterface<Tuple> { \
1329      public: \
1330       virtual bool MatchAndExplain( \
1331           Tuple args, \
1332           MatchResultListener* /* listener */) const { \
1333         return ::testing::get<0>(args) op ::testing::get<1>(args); \
1334       } \
1335       virtual void DescribeTo(::std::ostream* os) const { \
1336         *os << "are " relation; \
1337       } \
1338       virtual void DescribeNegationTo(::std::ostream* os) const { \
1339         *os << "aren't " relation; \
1340       } \
1341     }; \
1342   }
1343
1344 // Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
1345 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1346 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1347     Ge, >=, "a pair where the first >= the second");
1348 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1349     Gt, >, "a pair where the first > the second");
1350 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1351     Le, <=, "a pair where the first <= the second");
1352 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1353     Lt, <, "a pair where the first < the second");
1354 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
1355
1356 #undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
1357
1358 // Implements the Not(...) matcher for a particular argument type T.
1359 // We do not nest it inside the NotMatcher class template, as that
1360 // will prevent different instantiations of NotMatcher from sharing
1361 // the same NotMatcherImpl<T> class.
1362 template <typename T>
1363 class NotMatcherImpl : public MatcherInterface<T> {
1364  public:
1365   explicit NotMatcherImpl(const Matcher<T>& matcher)
1366       : matcher_(matcher) {}
1367
1368   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1369     return !matcher_.MatchAndExplain(x, listener);
1370   }
1371
1372   virtual void DescribeTo(::std::ostream* os) const {
1373     matcher_.DescribeNegationTo(os);
1374   }
1375
1376   virtual void DescribeNegationTo(::std::ostream* os) const {
1377     matcher_.DescribeTo(os);
1378   }
1379
1380  private:
1381   const Matcher<T> matcher_;
1382
1383   GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
1384 };
1385
1386 // Implements the Not(m) matcher, which matches a value that doesn't
1387 // match matcher m.
1388 template <typename InnerMatcher>
1389 class NotMatcher {
1390  public:
1391   explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1392
1393   // This template type conversion operator allows Not(m) to be used
1394   // to match any type m can match.
1395   template <typename T>
1396   operator Matcher<T>() const {
1397     return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
1398   }
1399
1400  private:
1401   InnerMatcher matcher_;
1402
1403   GTEST_DISALLOW_ASSIGN_(NotMatcher);
1404 };
1405
1406 // Implements the AllOf(m1, m2) matcher for a particular argument type
1407 // T. We do not nest it inside the BothOfMatcher class template, as
1408 // that will prevent different instantiations of BothOfMatcher from
1409 // sharing the same BothOfMatcherImpl<T> class.
1410 template <typename T>
1411 class BothOfMatcherImpl : public MatcherInterface<T> {
1412  public:
1413   BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1414       : matcher1_(matcher1), matcher2_(matcher2) {}
1415
1416   virtual void DescribeTo(::std::ostream* os) const {
1417     *os << "(";
1418     matcher1_.DescribeTo(os);
1419     *os << ") and (";
1420     matcher2_.DescribeTo(os);
1421     *os << ")";
1422   }
1423
1424   virtual void DescribeNegationTo(::std::ostream* os) const {
1425     *os << "(";
1426     matcher1_.DescribeNegationTo(os);
1427     *os << ") or (";
1428     matcher2_.DescribeNegationTo(os);
1429     *os << ")";
1430   }
1431
1432   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1433     // If either matcher1_ or matcher2_ doesn't match x, we only need
1434     // to explain why one of them fails.
1435     StringMatchResultListener listener1;
1436     if (!matcher1_.MatchAndExplain(x, &listener1)) {
1437       *listener << listener1.str();
1438       return false;
1439     }
1440
1441     StringMatchResultListener listener2;
1442     if (!matcher2_.MatchAndExplain(x, &listener2)) {
1443       *listener << listener2.str();
1444       return false;
1445     }
1446
1447     // Otherwise we need to explain why *both* of them match.
1448     const internal::string s1 = listener1.str();
1449     const internal::string s2 = listener2.str();
1450
1451     if (s1 == "") {
1452       *listener << s2;
1453     } else {
1454       *listener << s1;
1455       if (s2 != "") {
1456         *listener << ", and " << s2;
1457       }
1458     }
1459     return true;
1460   }
1461
1462  private:
1463   const Matcher<T> matcher1_;
1464   const Matcher<T> matcher2_;
1465
1466   GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
1467 };
1468
1469 #if GTEST_LANG_CXX11
1470 // MatcherList provides mechanisms for storing a variable number of matchers in
1471 // a list structure (ListType) and creating a combining matcher from such a
1472 // list.
1473 // The template is defined recursively using the following template paramters:
1474 //   * kSize is the length of the MatcherList.
1475 //   * Head is the type of the first matcher of the list.
1476 //   * Tail denotes the types of the remaining matchers of the list.
1477 template <int kSize, typename Head, typename... Tail>
1478 struct MatcherList {
1479   typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
1480   typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
1481
1482   // BuildList stores variadic type values in a nested pair structure.
1483   // Example:
1484   // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1485   // the corresponding result of type pair<int, pair<string, float>>.
1486   static ListType BuildList(const Head& matcher, const Tail&... tail) {
1487     return ListType(matcher, MatcherListTail::BuildList(tail...));
1488   }
1489
1490   // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1491   // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1492   // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1493   // constructor taking two Matcher<T>s as input.
1494   template <typename T, template <typename /* T */> class CombiningMatcher>
1495   static Matcher<T> CreateMatcher(const ListType& matchers) {
1496     return Matcher<T>(new CombiningMatcher<T>(
1497         SafeMatcherCast<T>(matchers.first),
1498         MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1499             matchers.second)));
1500   }
1501 };
1502
1503 // The following defines the base case for the recursive definition of
1504 // MatcherList.
1505 template <typename Matcher1, typename Matcher2>
1506 struct MatcherList<2, Matcher1, Matcher2> {
1507   typedef ::std::pair<Matcher1, Matcher2> ListType;
1508
1509   static ListType BuildList(const Matcher1& matcher1,
1510                             const Matcher2& matcher2) {
1511     return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
1512   }
1513
1514   template <typename T, template <typename /* T */> class CombiningMatcher>
1515   static Matcher<T> CreateMatcher(const ListType& matchers) {
1516     return Matcher<T>(new CombiningMatcher<T>(
1517         SafeMatcherCast<T>(matchers.first),
1518         SafeMatcherCast<T>(matchers.second)));
1519   }
1520 };
1521
1522 // VariadicMatcher is used for the variadic implementation of
1523 // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1524 // CombiningMatcher<T> is used to recursively combine the provided matchers
1525 // (of type Args...).
1526 template <template <typename T> class CombiningMatcher, typename... Args>
1527 class VariadicMatcher {
1528  public:
1529   VariadicMatcher(const Args&... matchers)  // NOLINT
1530       : matchers_(MatcherListType::BuildList(matchers...)) {}
1531
1532   // This template type conversion operator allows an
1533   // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1534   // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1535   template <typename T>
1536   operator Matcher<T>() const {
1537     return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1538         matchers_);
1539   }
1540
1541  private:
1542   typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1543
1544   const typename MatcherListType::ListType matchers_;
1545
1546   GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1547 };
1548
1549 template <typename... Args>
1550 using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1551
1552 #endif  // GTEST_LANG_CXX11
1553
1554 // Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1555 // matches a value that matches all of the matchers m_1, ..., and m_n.
1556 template <typename Matcher1, typename Matcher2>
1557 class BothOfMatcher {
1558  public:
1559   BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1560       : matcher1_(matcher1), matcher2_(matcher2) {}
1561
1562   // This template type conversion operator allows a
1563   // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1564   // both Matcher1 and Matcher2 can match.
1565   template <typename T>
1566   operator Matcher<T>() const {
1567     return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1568                                                SafeMatcherCast<T>(matcher2_)));
1569   }
1570
1571  private:
1572   Matcher1 matcher1_;
1573   Matcher2 matcher2_;
1574
1575   GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
1576 };
1577
1578 // Implements the AnyOf(m1, m2) matcher for a particular argument type
1579 // T.  We do not nest it inside the AnyOfMatcher class template, as
1580 // that will prevent different instantiations of AnyOfMatcher from
1581 // sharing the same EitherOfMatcherImpl<T> class.
1582 template <typename T>
1583 class EitherOfMatcherImpl : public MatcherInterface<T> {
1584  public:
1585   EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1586       : matcher1_(matcher1), matcher2_(matcher2) {}
1587
1588   virtual void DescribeTo(::std::ostream* os) const {
1589     *os << "(";
1590     matcher1_.DescribeTo(os);
1591     *os << ") or (";
1592     matcher2_.DescribeTo(os);
1593     *os << ")";
1594   }
1595
1596   virtual void DescribeNegationTo(::std::ostream* os) const {
1597     *os << "(";
1598     matcher1_.DescribeNegationTo(os);
1599     *os << ") and (";
1600     matcher2_.DescribeNegationTo(os);
1601     *os << ")";
1602   }
1603
1604   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1605     // If either matcher1_ or matcher2_ matches x, we just need to
1606     // explain why *one* of them matches.
1607     StringMatchResultListener listener1;
1608     if (matcher1_.MatchAndExplain(x, &listener1)) {
1609       *listener << listener1.str();
1610       return true;
1611     }
1612
1613     StringMatchResultListener listener2;
1614     if (matcher2_.MatchAndExplain(x, &listener2)) {
1615       *listener << listener2.str();
1616       return true;
1617     }
1618
1619     // Otherwise we need to explain why *both* of them fail.
1620     const internal::string s1 = listener1.str();
1621     const internal::string s2 = listener2.str();
1622
1623     if (s1 == "") {
1624       *listener << s2;
1625     } else {
1626       *listener << s1;
1627       if (s2 != "") {
1628         *listener << ", and " << s2;
1629       }
1630     }
1631     return false;
1632   }
1633
1634  private:
1635   const Matcher<T> matcher1_;
1636   const Matcher<T> matcher2_;
1637
1638   GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
1639 };
1640
1641 #if GTEST_LANG_CXX11
1642 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1643 template <typename... Args>
1644 using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1645
1646 #endif  // GTEST_LANG_CXX11
1647
1648 // Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1649 // matches a value that matches at least one of the matchers m_1, ...,
1650 // and m_n.
1651 template <typename Matcher1, typename Matcher2>
1652 class EitherOfMatcher {
1653  public:
1654   EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1655       : matcher1_(matcher1), matcher2_(matcher2) {}
1656
1657   // This template type conversion operator allows a
1658   // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1659   // both Matcher1 and Matcher2 can match.
1660   template <typename T>
1661   operator Matcher<T>() const {
1662     return Matcher<T>(new EitherOfMatcherImpl<T>(
1663         SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
1664   }
1665
1666  private:
1667   Matcher1 matcher1_;
1668   Matcher2 matcher2_;
1669
1670   GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
1671 };
1672
1673 // Used for implementing Truly(pred), which turns a predicate into a
1674 // matcher.
1675 template <typename Predicate>
1676 class TrulyMatcher {
1677  public:
1678   explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1679
1680   // This method template allows Truly(pred) to be used as a matcher
1681   // for type T where T is the argument type of predicate 'pred'.  The
1682   // argument is passed by reference as the predicate may be
1683   // interested in the address of the argument.
1684   template <typename T>
1685   bool MatchAndExplain(T& x,  // NOLINT
1686                        MatchResultListener* /* listener */) const {
1687     // Without the if-statement, MSVC sometimes warns about converting
1688     // a value to bool (warning 4800).
1689     //
1690     // We cannot write 'return !!predicate_(x);' as that doesn't work
1691     // when predicate_(x) returns a class convertible to bool but
1692     // having no operator!().
1693     if (predicate_(x))
1694       return true;
1695     return false;
1696   }
1697
1698   void DescribeTo(::std::ostream* os) const {
1699     *os << "satisfies the given predicate";
1700   }
1701
1702   void DescribeNegationTo(::std::ostream* os) const {
1703     *os << "doesn't satisfy the given predicate";
1704   }
1705
1706  private:
1707   Predicate predicate_;
1708
1709   GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
1710 };
1711
1712 // Used for implementing Matches(matcher), which turns a matcher into
1713 // a predicate.
1714 template <typename M>
1715 class MatcherAsPredicate {
1716  public:
1717   explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1718
1719   // This template operator() allows Matches(m) to be used as a
1720   // predicate on type T where m is a matcher on type T.
1721   //
1722   // The argument x is passed by reference instead of by value, as
1723   // some matcher may be interested in its address (e.g. as in
1724   // Matches(Ref(n))(x)).
1725   template <typename T>
1726   bool operator()(const T& x) const {
1727     // We let matcher_ commit to a particular type here instead of
1728     // when the MatcherAsPredicate object was constructed.  This
1729     // allows us to write Matches(m) where m is a polymorphic matcher
1730     // (e.g. Eq(5)).
1731     //
1732     // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1733     // compile when matcher_ has type Matcher<const T&>; if we write
1734     // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1735     // when matcher_ has type Matcher<T>; if we just write
1736     // matcher_.Matches(x), it won't compile when matcher_ is
1737     // polymorphic, e.g. Eq(5).
1738     //
1739     // MatcherCast<const T&>() is necessary for making the code work
1740     // in all of the above situations.
1741     return MatcherCast<const T&>(matcher_).Matches(x);
1742   }
1743
1744  private:
1745   M matcher_;
1746
1747   GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
1748 };
1749
1750 // For implementing ASSERT_THAT() and EXPECT_THAT().  The template
1751 // argument M must be a type that can be converted to a matcher.
1752 template <typename M>
1753 class PredicateFormatterFromMatcher {
1754  public:
1755   explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1756
1757   // This template () operator allows a PredicateFormatterFromMatcher
1758   // object to act as a predicate-formatter suitable for using with
1759   // Google Test's EXPECT_PRED_FORMAT1() macro.
1760   template <typename T>
1761   AssertionResult operator()(const char* value_text, const T& x) const {
1762     // We convert matcher_ to a Matcher<const T&> *now* instead of
1763     // when the PredicateFormatterFromMatcher object was constructed,
1764     // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1765     // know which type to instantiate it to until we actually see the
1766     // type of x here.
1767     //
1768     // We write SafeMatcherCast<const T&>(matcher_) instead of
1769     // Matcher<const T&>(matcher_), as the latter won't compile when
1770     // matcher_ has type Matcher<T> (e.g. An<int>()).
1771     // We don't write MatcherCast<const T&> either, as that allows
1772     // potentially unsafe downcasting of the matcher argument.
1773     const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
1774     StringMatchResultListener listener;
1775     if (MatchPrintAndExplain(x, matcher, &listener))
1776       return AssertionSuccess();
1777
1778     ::std::stringstream ss;
1779     ss << "Value of: " << value_text << "\n"
1780        << "Expected: ";
1781     matcher.DescribeTo(&ss);
1782     ss << "\n  Actual: " << listener.str();
1783     return AssertionFailure() << ss.str();
1784   }
1785
1786  private:
1787   const M matcher_;
1788
1789   GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
1790 };
1791
1792 // A helper function for converting a matcher to a predicate-formatter
1793 // without the user needing to explicitly write the type.  This is
1794 // used for implementing ASSERT_THAT() and EXPECT_THAT().
1795 template <typename M>
1796 inline PredicateFormatterFromMatcher<M>
1797 MakePredicateFormatterFromMatcher(const M& matcher) {
1798   return PredicateFormatterFromMatcher<M>(matcher);
1799 }
1800
1801 // Implements the polymorphic floating point equality matcher, which matches
1802 // two float values using ULP-based approximation or, optionally, a
1803 // user-specified epsilon.  The template is meant to be instantiated with
1804 // FloatType being either float or double.
1805 template <typename FloatType>
1806 class FloatingEqMatcher {
1807  public:
1808   // Constructor for FloatingEqMatcher.
1809   // The matcher's input will be compared with rhs.  The matcher treats two
1810   // NANs as equal if nan_eq_nan is true.  Otherwise, under IEEE standards,
1811   // equality comparisons between NANs will always return false.  We specify a
1812   // negative max_abs_error_ term to indicate that ULP-based approximation will
1813   // be used for comparison.
1814   FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1815     rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
1816   }
1817
1818   // Constructor that supports a user-specified max_abs_error that will be used
1819   // for comparison instead of ULP-based approximation.  The max absolute
1820   // should be non-negative.
1821   FloatingEqMatcher(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
1822     rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {
1823     GTEST_CHECK_(max_abs_error >= 0)
1824         << ", where max_abs_error is" << max_abs_error;
1825   }
1826
1827   // Implements floating point equality matcher as a Matcher<T>.
1828   template <typename T>
1829   class Impl : public MatcherInterface<T> {
1830    public:
1831     Impl(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
1832       rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {}
1833
1834     virtual bool MatchAndExplain(T value,
1835                                  MatchResultListener* /* listener */) const {
1836       const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1837
1838       // Compares NaNs first, if nan_eq_nan_ is true.
1839       if (lhs.is_nan() || rhs.is_nan()) {
1840         if (lhs.is_nan() && rhs.is_nan()) {
1841           return nan_eq_nan_;
1842         }
1843         // One is nan; the other is not nan.
1844         return false;
1845       }
1846       if (HasMaxAbsError()) {
1847         // We perform an equality check so that inf will match inf, regardless
1848         // of error bounds.  If the result of value - rhs_ would result in
1849         // overflow or if either value is inf, the default result is infinity,
1850         // which should only match if max_abs_error_ is also infinity.
1851         return value == rhs_ || fabs(value - rhs_) <= max_abs_error_;
1852       } else {
1853         return lhs.AlmostEquals(rhs);
1854       }
1855     }
1856
1857     virtual void DescribeTo(::std::ostream* os) const {
1858       // os->precision() returns the previously set precision, which we
1859       // store to restore the ostream to its original configuration
1860       // after outputting.
1861       const ::std::streamsize old_precision = os->precision(
1862           ::std::numeric_limits<FloatType>::digits10 + 2);
1863       if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1864         if (nan_eq_nan_) {
1865           *os << "is NaN";
1866         } else {
1867           *os << "never matches";
1868         }
1869       } else {
1870         *os << "is approximately " << rhs_;
1871         if (HasMaxAbsError()) {
1872           *os << " (absolute error <= " << max_abs_error_ << ")";
1873         }
1874       }
1875       os->precision(old_precision);
1876     }
1877
1878     virtual void DescribeNegationTo(::std::ostream* os) const {
1879       // As before, get original precision.
1880       const ::std::streamsize old_precision = os->precision(
1881           ::std::numeric_limits<FloatType>::digits10 + 2);
1882       if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1883         if (nan_eq_nan_) {
1884           *os << "isn't NaN";
1885         } else {
1886           *os << "is anything";
1887         }
1888       } else {
1889         *os << "isn't approximately " << rhs_;
1890         if (HasMaxAbsError()) {
1891           *os << " (absolute error > " << max_abs_error_ << ")";
1892         }
1893       }
1894       // Restore original precision.
1895       os->precision(old_precision);
1896     }
1897
1898    private:
1899     bool HasMaxAbsError() const {
1900       return max_abs_error_ >= 0;
1901     }
1902
1903     const FloatType rhs_;
1904     const bool nan_eq_nan_;
1905     // max_abs_error will be used for value comparison when >= 0.
1906     const FloatType max_abs_error_;
1907
1908     GTEST_DISALLOW_ASSIGN_(Impl);
1909   };
1910
1911   // The following 3 type conversion operators allow FloatEq(rhs) and
1912   // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1913   // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1914   // (While Google's C++ coding style doesn't allow arguments passed
1915   // by non-const reference, we may see them in code not conforming to
1916   // the style.  Therefore Google Mock needs to support them.)
1917   operator Matcher<FloatType>() const {
1918     return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_, max_abs_error_));
1919   }
1920
1921   operator Matcher<const FloatType&>() const {
1922     return MakeMatcher(
1923         new Impl<const FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
1924   }
1925
1926   operator Matcher<FloatType&>() const {
1927     return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
1928   }
1929
1930  private:
1931   const FloatType rhs_;
1932   const bool nan_eq_nan_;
1933   // max_abs_error will be used for value comparison when >= 0.
1934   const FloatType max_abs_error_;
1935
1936   GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
1937 };
1938
1939 // Implements the Pointee(m) matcher for matching a pointer whose
1940 // pointee matches matcher m.  The pointer can be either raw or smart.
1941 template <typename InnerMatcher>
1942 class PointeeMatcher {
1943  public:
1944   explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1945
1946   // This type conversion operator template allows Pointee(m) to be
1947   // used as a matcher for any pointer type whose pointee type is
1948   // compatible with the inner matcher, where type Pointer can be
1949   // either a raw pointer or a smart pointer.
1950   //
1951   // The reason we do this instead of relying on
1952   // MakePolymorphicMatcher() is that the latter is not flexible
1953   // enough for implementing the DescribeTo() method of Pointee().
1954   template <typename Pointer>
1955   operator Matcher<Pointer>() const {
1956     return MakeMatcher(new Impl<Pointer>(matcher_));
1957   }
1958
1959  private:
1960   // The monomorphic implementation that works for a particular pointer type.
1961   template <typename Pointer>
1962   class Impl : public MatcherInterface<Pointer> {
1963    public:
1964     typedef typename PointeeOf<GTEST_REMOVE_CONST_(  // NOLINT
1965         GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
1966
1967     explicit Impl(const InnerMatcher& matcher)
1968         : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1969
1970     virtual void DescribeTo(::std::ostream* os) const {
1971       *os << "points to a value that ";
1972       matcher_.DescribeTo(os);
1973     }
1974
1975     virtual void DescribeNegationTo(::std::ostream* os) const {
1976       *os << "does not point to a value that ";
1977       matcher_.DescribeTo(os);
1978     }
1979
1980     virtual bool MatchAndExplain(Pointer pointer,
1981                                  MatchResultListener* listener) const {
1982       if (GetRawPointer(pointer) == NULL)
1983         return false;
1984
1985       *listener << "which points to ";
1986       return MatchPrintAndExplain(*pointer, matcher_, listener);
1987     }
1988
1989    private:
1990     const Matcher<const Pointee&> matcher_;
1991
1992     GTEST_DISALLOW_ASSIGN_(Impl);
1993   };
1994
1995   const InnerMatcher matcher_;
1996
1997   GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
1998 };
1999
2000 // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2001 // reference that matches inner_matcher when dynamic_cast<T> is applied.
2002 // The result of dynamic_cast<To> is forwarded to the inner matcher.
2003 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
2004 // If To is a reference and the cast fails, this matcher returns false
2005 // immediately.
2006 template <typename To>
2007 class WhenDynamicCastToMatcherBase {
2008  public:
2009   explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2010       : matcher_(matcher) {}
2011
2012   void DescribeTo(::std::ostream* os) const {
2013     GetCastTypeDescription(os);
2014     matcher_.DescribeTo(os);
2015   }
2016
2017   void DescribeNegationTo(::std::ostream* os) const {
2018     GetCastTypeDescription(os);
2019     matcher_.DescribeNegationTo(os);
2020   }
2021
2022  protected:
2023   const Matcher<To> matcher_;
2024
2025   static string GetToName() {
2026 #if GTEST_HAS_RTTI
2027     return GetTypeName<To>();
2028 #else  // GTEST_HAS_RTTI
2029     return "the target type";
2030 #endif  // GTEST_HAS_RTTI
2031   }
2032
2033  private:
2034   static void GetCastTypeDescription(::std::ostream* os) {
2035     *os << "when dynamic_cast to " << GetToName() << ", ";
2036   }
2037
2038   GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2039 };
2040
2041 // Primary template.
2042 // To is a pointer. Cast and forward the result.
2043 template <typename To>
2044 class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2045  public:
2046   explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2047       : WhenDynamicCastToMatcherBase<To>(matcher) {}
2048
2049   template <typename From>
2050   bool MatchAndExplain(From from, MatchResultListener* listener) const {
2051     // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2052     To to = dynamic_cast<To>(from);
2053     return MatchPrintAndExplain(to, this->matcher_, listener);
2054   }
2055 };
2056
2057 // Specialize for references.
2058 // In this case we return false if the dynamic_cast fails.
2059 template <typename To>
2060 class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2061  public:
2062   explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2063       : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2064
2065   template <typename From>
2066   bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2067     // We don't want an std::bad_cast here, so do the cast with pointers.
2068     To* to = dynamic_cast<To*>(&from);
2069     if (to == NULL) {
2070       *listener << "which cannot be dynamic_cast to " << this->GetToName();
2071       return false;
2072     }
2073     return MatchPrintAndExplain(*to, this->matcher_, listener);
2074   }
2075 };
2076
2077 // Implements the Field() matcher for matching a field (i.e. member
2078 // variable) of an object.
2079 template <typename Class, typename FieldType>
2080 class FieldMatcher {
2081  public:
2082   FieldMatcher(FieldType Class::*field,
2083                const Matcher<const FieldType&>& matcher)
2084       : field_(field), matcher_(matcher) {}
2085
2086   void DescribeTo(::std::ostream* os) const {
2087     *os << "is an object whose given field ";
2088     matcher_.DescribeTo(os);
2089   }
2090
2091   void DescribeNegationTo(::std::ostream* os) const {
2092     *os << "is an object whose given field ";
2093     matcher_.DescribeNegationTo(os);
2094   }
2095
2096   template <typename T>
2097   bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2098     return MatchAndExplainImpl(
2099         typename ::testing::internal::
2100             is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2101         value, listener);
2102   }
2103
2104  private:
2105   // The first argument of MatchAndExplainImpl() is needed to help
2106   // Symbian's C++ compiler choose which overload to use.  Its type is
2107   // true_type iff the Field() matcher is used to match a pointer.
2108   bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2109                            MatchResultListener* listener) const {
2110     *listener << "whose given field is ";
2111     return MatchPrintAndExplain(obj.*field_, matcher_, listener);
2112   }
2113
2114   bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2115                            MatchResultListener* listener) const {
2116     if (p == NULL)
2117       return false;
2118
2119     *listener << "which points to an object ";
2120     // Since *p has a field, it must be a class/struct/union type and
2121     // thus cannot be a pointer.  Therefore we pass false_type() as
2122     // the first argument.
2123     return MatchAndExplainImpl(false_type(), *p, listener);
2124   }
2125
2126   const FieldType Class::*field_;
2127   const Matcher<const FieldType&> matcher_;
2128
2129   GTEST_DISALLOW_ASSIGN_(FieldMatcher);
2130 };
2131
2132 // Implements the Property() matcher for matching a property
2133 // (i.e. return value of a getter method) of an object.
2134 template <typename Class, typename PropertyType>
2135 class PropertyMatcher {
2136  public:
2137   // The property may have a reference type, so 'const PropertyType&'
2138   // may cause double references and fail to compile.  That's why we
2139   // need GTEST_REFERENCE_TO_CONST, which works regardless of
2140   // PropertyType being a reference or not.
2141   typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
2142
2143   PropertyMatcher(PropertyType (Class::*property)() const,
2144                   const Matcher<RefToConstProperty>& matcher)
2145       : property_(property), matcher_(matcher) {}
2146
2147   void DescribeTo(::std::ostream* os) const {
2148     *os << "is an object whose given property ";
2149     matcher_.DescribeTo(os);
2150   }
2151
2152   void DescribeNegationTo(::std::ostream* os) const {
2153     *os << "is an object whose given property ";
2154     matcher_.DescribeNegationTo(os);
2155   }
2156
2157   template <typename T>
2158   bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2159     return MatchAndExplainImpl(
2160         typename ::testing::internal::
2161             is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2162         value, listener);
2163   }
2164
2165  private:
2166   // The first argument of MatchAndExplainImpl() is needed to help
2167   // Symbian's C++ compiler choose which overload to use.  Its type is
2168   // true_type iff the Property() matcher is used to match a pointer.
2169   bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2170                            MatchResultListener* listener) const {
2171     *listener << "whose given property is ";
2172     // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2173     // which takes a non-const reference as argument.
2174     RefToConstProperty result = (obj.*property_)();
2175     return MatchPrintAndExplain(result, matcher_, listener);
2176   }
2177
2178   bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2179                            MatchResultListener* listener) const {
2180     if (p == NULL)
2181       return false;
2182
2183     *listener << "which points to an object ";
2184     // Since *p has a property method, it must be a class/struct/union
2185     // type and thus cannot be a pointer.  Therefore we pass
2186     // false_type() as the first argument.
2187     return MatchAndExplainImpl(false_type(), *p, listener);
2188   }
2189
2190   PropertyType (Class::*property_)() const;
2191   const Matcher<RefToConstProperty> matcher_;
2192
2193   GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
2194 };
2195
2196 // Type traits specifying various features of different functors for ResultOf.
2197 // The default template specifies features for functor objects.
2198 // Functor classes have to typedef argument_type and result_type
2199 // to be compatible with ResultOf.
2200 template <typename Functor>
2201 struct CallableTraits {
2202   typedef typename Functor::result_type ResultType;
2203   typedef Functor StorageType;
2204
2205   static void CheckIsValid(Functor /* functor */) {}
2206   template <typename T>
2207   static ResultType Invoke(Functor f, T arg) { return f(arg); }
2208 };
2209
2210 // Specialization for function pointers.
2211 template <typename ArgType, typename ResType>
2212 struct CallableTraits<ResType(*)(ArgType)> {
2213   typedef ResType ResultType;
2214   typedef ResType(*StorageType)(ArgType);
2215
2216   static void CheckIsValid(ResType(*f)(ArgType)) {
2217     GTEST_CHECK_(f != NULL)
2218         << "NULL function pointer is passed into ResultOf().";
2219   }
2220   template <typename T>
2221   static ResType Invoke(ResType(*f)(ArgType), T arg) {
2222     return (*f)(arg);
2223   }
2224 };
2225
2226 // Implements the ResultOf() matcher for matching a return value of a
2227 // unary function of an object.
2228 template <typename Callable>
2229 class ResultOfMatcher {
2230  public:
2231   typedef typename CallableTraits<Callable>::ResultType ResultType;
2232
2233   ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2234       : callable_(callable), matcher_(matcher) {
2235     CallableTraits<Callable>::CheckIsValid(callable_);
2236   }
2237
2238   template <typename T>
2239   operator Matcher<T>() const {
2240     return Matcher<T>(new Impl<T>(callable_, matcher_));
2241   }
2242
2243  private:
2244   typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2245
2246   template <typename T>
2247   class Impl : public MatcherInterface<T> {
2248    public:
2249     Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2250         : callable_(callable), matcher_(matcher) {}
2251
2252     virtual void DescribeTo(::std::ostream* os) const {
2253       *os << "is mapped by the given callable to a value that ";
2254       matcher_.DescribeTo(os);
2255     }
2256
2257     virtual void DescribeNegationTo(::std::ostream* os) const {
2258       *os << "is mapped by the given callable to a value that ";
2259       matcher_.DescribeNegationTo(os);
2260     }
2261
2262     virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
2263       *listener << "which is mapped by the given callable to ";
2264       // Cannot pass the return value (for example, int) to
2265       // MatchPrintAndExplain, which takes a non-const reference as argument.
2266       ResultType result =
2267           CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2268       return MatchPrintAndExplain(result, matcher_, listener);
2269     }
2270
2271    private:
2272     // Functors often define operator() as non-const method even though
2273     // they are actualy stateless. But we need to use them even when
2274     // 'this' is a const pointer. It's the user's responsibility not to
2275     // use stateful callables with ResultOf(), which does't guarantee
2276     // how many times the callable will be invoked.
2277     mutable CallableStorageType callable_;
2278     const Matcher<ResultType> matcher_;
2279
2280     GTEST_DISALLOW_ASSIGN_(Impl);
2281   };  // class Impl
2282
2283   const CallableStorageType callable_;
2284   const Matcher<ResultType> matcher_;
2285
2286   GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
2287 };
2288
2289 // Implements a matcher that checks the size of an STL-style container.
2290 template <typename SizeMatcher>
2291 class SizeIsMatcher {
2292  public:
2293   explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2294        : size_matcher_(size_matcher) {
2295   }
2296
2297   template <typename Container>
2298   operator Matcher<Container>() const {
2299     return MakeMatcher(new Impl<Container>(size_matcher_));
2300   }
2301
2302   template <typename Container>
2303   class Impl : public MatcherInterface<Container> {
2304    public:
2305     typedef internal::StlContainerView<
2306          GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2307     typedef typename ContainerView::type::size_type SizeType;
2308     explicit Impl(const SizeMatcher& size_matcher)
2309         : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2310
2311     virtual void DescribeTo(::std::ostream* os) const {
2312       *os << "size ";
2313       size_matcher_.DescribeTo(os);
2314     }
2315     virtual void DescribeNegationTo(::std::ostream* os) const {
2316       *os << "size ";
2317       size_matcher_.DescribeNegationTo(os);
2318     }
2319
2320     virtual bool MatchAndExplain(Container container,
2321                                  MatchResultListener* listener) const {
2322       SizeType size = container.size();
2323       StringMatchResultListener size_listener;
2324       const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2325       *listener
2326           << "whose size " << size << (result ? " matches" : " doesn't match");
2327       PrintIfNotEmpty(size_listener.str(), listener->stream());
2328       return result;
2329     }
2330
2331    private:
2332     const Matcher<SizeType> size_matcher_;
2333     GTEST_DISALLOW_ASSIGN_(Impl);
2334   };
2335
2336  private:
2337   const SizeMatcher size_matcher_;
2338   GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2339 };
2340
2341 // Implements a matcher that checks the begin()..end() distance of an STL-style
2342 // container.
2343 template <typename DistanceMatcher>
2344 class BeginEndDistanceIsMatcher {
2345  public:
2346   explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2347       : distance_matcher_(distance_matcher) {}
2348
2349   template <typename Container>
2350   operator Matcher<Container>() const {
2351     return MakeMatcher(new Impl<Container>(distance_matcher_));
2352   }
2353
2354   template <typename Container>
2355   class Impl : public MatcherInterface<Container> {
2356    public:
2357     typedef internal::StlContainerView<
2358         GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2359     typedef typename std::iterator_traits<
2360         typename ContainerView::type::const_iterator>::difference_type
2361         DistanceType;
2362     explicit Impl(const DistanceMatcher& distance_matcher)
2363         : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2364
2365     virtual void DescribeTo(::std::ostream* os) const {
2366       *os << "distance between begin() and end() ";
2367       distance_matcher_.DescribeTo(os);
2368     }
2369     virtual void DescribeNegationTo(::std::ostream* os) const {
2370       *os << "distance between begin() and end() ";
2371       distance_matcher_.DescribeNegationTo(os);
2372     }
2373
2374     virtual bool MatchAndExplain(Container container,
2375                                  MatchResultListener* listener) const {
2376 #if GTEST_LANG_CXX11
2377       using std::begin;
2378       using std::end;
2379       DistanceType distance = std::distance(begin(container), end(container));
2380 #else
2381       DistanceType distance = std::distance(container.begin(), container.end());
2382 #endif
2383       StringMatchResultListener distance_listener;
2384       const bool result =
2385           distance_matcher_.MatchAndExplain(distance, &distance_listener);
2386       *listener << "whose distance between begin() and end() " << distance
2387                 << (result ? " matches" : " doesn't match");
2388       PrintIfNotEmpty(distance_listener.str(), listener->stream());
2389       return result;
2390     }
2391
2392    private:
2393     const Matcher<DistanceType> distance_matcher_;
2394     GTEST_DISALLOW_ASSIGN_(Impl);
2395   };
2396
2397  private:
2398   const DistanceMatcher distance_matcher_;
2399   GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2400 };
2401
2402 // Implements an equality matcher for any STL-style container whose elements
2403 // support ==. This matcher is like Eq(), but its failure explanations provide
2404 // more detailed information that is useful when the container is used as a set.
2405 // The failure message reports elements that are in one of the operands but not
2406 // the other. The failure messages do not report duplicate or out-of-order
2407 // elements in the containers (which don't properly matter to sets, but can
2408 // occur if the containers are vectors or lists, for example).
2409 //
2410 // Uses the container's const_iterator, value_type, operator ==,
2411 // begin(), and end().
2412 template <typename Container>
2413 class ContainerEqMatcher {
2414  public:
2415   typedef internal::StlContainerView<Container> View;
2416   typedef typename View::type StlContainer;
2417   typedef typename View::const_reference StlContainerReference;
2418
2419   // We make a copy of rhs in case the elements in it are modified
2420   // after this matcher is created.
2421   explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
2422     // Makes sure the user doesn't instantiate this class template
2423     // with a const or reference type.
2424     (void)testing::StaticAssertTypeEq<Container,
2425         GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
2426   }
2427
2428   void DescribeTo(::std::ostream* os) const {
2429     *os << "equals ";
2430     UniversalPrint(rhs_, os);
2431   }
2432   void DescribeNegationTo(::std::ostream* os) const {
2433     *os << "does not equal ";
2434     UniversalPrint(rhs_, os);
2435   }
2436
2437   template <typename LhsContainer>
2438   bool MatchAndExplain(const LhsContainer& lhs,
2439                        MatchResultListener* listener) const {
2440     // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
2441     // that causes LhsContainer to be a const type sometimes.
2442     typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
2443         LhsView;
2444     typedef typename LhsView::type LhsStlContainer;
2445     StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2446     if (lhs_stl_container == rhs_)
2447       return true;
2448
2449     ::std::ostream* const os = listener->stream();
2450     if (os != NULL) {
2451       // Something is different. Check for extra values first.
2452       bool printed_header = false;
2453       for (typename LhsStlContainer::const_iterator it =
2454                lhs_stl_container.begin();
2455            it != lhs_stl_container.end(); ++it) {
2456         if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2457             rhs_.end()) {
2458           if (printed_header) {
2459             *os << ", ";
2460           } else {
2461             *os << "which has these unexpected elements: ";
2462             printed_header = true;
2463           }
2464           UniversalPrint(*it, os);
2465         }
2466       }
2467
2468       // Now check for missing values.
2469       bool printed_header2 = false;
2470       for (typename StlContainer::const_iterator it = rhs_.begin();
2471            it != rhs_.end(); ++it) {
2472         if (internal::ArrayAwareFind(
2473                 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2474             lhs_stl_container.end()) {
2475           if (printed_header2) {
2476             *os << ", ";
2477           } else {
2478             *os << (printed_header ? ",\nand" : "which")
2479                 << " doesn't have these expected elements: ";
2480             printed_header2 = true;
2481           }
2482           UniversalPrint(*it, os);
2483         }
2484       }
2485     }
2486
2487     return false;
2488   }
2489
2490  private:
2491   const StlContainer rhs_;
2492
2493   GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
2494 };
2495
2496 // A comparator functor that uses the < operator to compare two values.
2497 struct LessComparator {
2498   template <typename T, typename U>
2499   bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2500 };
2501
2502 // Implements WhenSortedBy(comparator, container_matcher).
2503 template <typename Comparator, typename ContainerMatcher>
2504 class WhenSortedByMatcher {
2505  public:
2506   WhenSortedByMatcher(const Comparator& comparator,
2507                       const ContainerMatcher& matcher)
2508       : comparator_(comparator), matcher_(matcher) {}
2509
2510   template <typename LhsContainer>
2511   operator Matcher<LhsContainer>() const {
2512     return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2513   }
2514
2515   template <typename LhsContainer>
2516   class Impl : public MatcherInterface<LhsContainer> {
2517    public:
2518     typedef internal::StlContainerView<
2519          GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2520     typedef typename LhsView::type LhsStlContainer;
2521     typedef typename LhsView::const_reference LhsStlContainerReference;
2522     // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2523     // so that we can match associative containers.
2524     typedef typename RemoveConstFromKey<
2525         typename LhsStlContainer::value_type>::type LhsValue;
2526
2527     Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2528         : comparator_(comparator), matcher_(matcher) {}
2529
2530     virtual void DescribeTo(::std::ostream* os) const {
2531       *os << "(when sorted) ";
2532       matcher_.DescribeTo(os);
2533     }
2534
2535     virtual void DescribeNegationTo(::std::ostream* os) const {
2536       *os << "(when sorted) ";
2537       matcher_.DescribeNegationTo(os);
2538     }
2539
2540     virtual bool MatchAndExplain(LhsContainer lhs,
2541                                  MatchResultListener* listener) const {
2542       LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2543       ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2544                                                lhs_stl_container.end());
2545       ::std::sort(
2546            sorted_container.begin(), sorted_container.end(), comparator_);
2547
2548       if (!listener->IsInterested()) {
2549         // If the listener is not interested, we do not need to
2550         // construct the inner explanation.
2551         return matcher_.Matches(sorted_container);
2552       }
2553
2554       *listener << "which is ";
2555       UniversalPrint(sorted_container, listener->stream());
2556       *listener << " when sorted";
2557
2558       StringMatchResultListener inner_listener;
2559       const bool match = matcher_.MatchAndExplain(sorted_container,
2560                                                   &inner_listener);
2561       PrintIfNotEmpty(inner_listener.str(), listener->stream());
2562       return match;
2563     }
2564
2565    private:
2566     const Comparator comparator_;
2567     const Matcher<const ::std::vector<LhsValue>&> matcher_;
2568
2569     GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2570   };
2571
2572  private:
2573   const Comparator comparator_;
2574   const ContainerMatcher matcher_;
2575
2576   GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2577 };
2578
2579 // Implements Pointwise(tuple_matcher, rhs_container).  tuple_matcher
2580 // must be able to be safely cast to Matcher<tuple<const T1&, const
2581 // T2&> >, where T1 and T2 are the types of elements in the LHS
2582 // container and the RHS container respectively.
2583 template <typename TupleMatcher, typename RhsContainer>
2584 class PointwiseMatcher {
2585  public:
2586   typedef internal::StlContainerView<RhsContainer> RhsView;
2587   typedef typename RhsView::type RhsStlContainer;
2588   typedef typename RhsStlContainer::value_type RhsValue;
2589
2590   // Like ContainerEq, we make a copy of rhs in case the elements in
2591   // it are modified after this matcher is created.
2592   PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2593       : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2594     // Makes sure the user doesn't instantiate this class template
2595     // with a const or reference type.
2596     (void)testing::StaticAssertTypeEq<RhsContainer,
2597         GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2598   }
2599
2600   template <typename LhsContainer>
2601   operator Matcher<LhsContainer>() const {
2602     return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2603   }
2604
2605   template <typename LhsContainer>
2606   class Impl : public MatcherInterface<LhsContainer> {
2607    public:
2608     typedef internal::StlContainerView<
2609          GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2610     typedef typename LhsView::type LhsStlContainer;
2611     typedef typename LhsView::const_reference LhsStlContainerReference;
2612     typedef typename LhsStlContainer::value_type LhsValue;
2613     // We pass the LHS value and the RHS value to the inner matcher by
2614     // reference, as they may be expensive to copy.  We must use tuple
2615     // instead of pair here, as a pair cannot hold references (C++ 98,
2616     // 20.2.2 [lib.pairs]).
2617     typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2618
2619     Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2620         // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2621         : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2622           rhs_(rhs) {}
2623
2624     virtual void DescribeTo(::std::ostream* os) const {
2625       *os << "contains " << rhs_.size()
2626           << " values, where each value and its corresponding value in ";
2627       UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2628       *os << " ";
2629       mono_tuple_matcher_.DescribeTo(os);
2630     }
2631     virtual void DescribeNegationTo(::std::ostream* os) const {
2632       *os << "doesn't contain exactly " << rhs_.size()
2633           << " values, or contains a value x at some index i"
2634           << " where x and the i-th value of ";
2635       UniversalPrint(rhs_, os);
2636       *os << " ";
2637       mono_tuple_matcher_.DescribeNegationTo(os);
2638     }
2639
2640     virtual bool MatchAndExplain(LhsContainer lhs,
2641                                  MatchResultListener* listener) const {
2642       LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2643       const size_t actual_size = lhs_stl_container.size();
2644       if (actual_size != rhs_.size()) {
2645         *listener << "which contains " << actual_size << " values";
2646         return false;
2647       }
2648
2649       typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2650       typename RhsStlContainer::const_iterator right = rhs_.begin();
2651       for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2652         const InnerMatcherArg value_pair(*left, *right);
2653
2654         if (listener->IsInterested()) {
2655           StringMatchResultListener inner_listener;
2656           if (!mono_tuple_matcher_.MatchAndExplain(
2657                   value_pair, &inner_listener)) {
2658             *listener << "where the value pair (";
2659             UniversalPrint(*left, listener->stream());
2660             *listener << ", ";
2661             UniversalPrint(*right, listener->stream());
2662             *listener << ") at index #" << i << " don't match";
2663             PrintIfNotEmpty(inner_listener.str(), listener->stream());
2664             return false;
2665           }
2666         } else {
2667           if (!mono_tuple_matcher_.Matches(value_pair))
2668             return false;
2669         }
2670       }
2671
2672       return true;
2673     }
2674
2675    private:
2676     const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2677     const RhsStlContainer rhs_;
2678
2679     GTEST_DISALLOW_ASSIGN_(Impl);
2680   };
2681
2682  private:
2683   const TupleMatcher tuple_matcher_;
2684   const RhsStlContainer rhs_;
2685
2686   GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2687 };
2688
2689 // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
2690 template <typename Container>
2691 class QuantifierMatcherImpl : public MatcherInterface<Container> {
2692  public:
2693   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
2694   typedef StlContainerView<RawContainer> View;
2695   typedef typename View::type StlContainer;
2696   typedef typename View::const_reference StlContainerReference;
2697   typedef typename StlContainer::value_type Element;
2698
2699   template <typename InnerMatcher>
2700   explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
2701       : inner_matcher_(
2702            testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
2703
2704   // Checks whether:
2705   // * All elements in the container match, if all_elements_should_match.
2706   // * Any element in the container matches, if !all_elements_should_match.
2707   bool MatchAndExplainImpl(bool all_elements_should_match,
2708                            Container container,
2709                            MatchResultListener* listener) const {
2710     StlContainerReference stl_container = View::ConstReference(container);
2711     size_t i = 0;
2712     for (typename StlContainer::const_iterator it = stl_container.begin();
2713          it != stl_container.end(); ++it, ++i) {
2714       StringMatchResultListener inner_listener;
2715       const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2716
2717       if (matches != all_elements_should_match) {
2718         *listener << "whose element #" << i
2719                   << (matches ? " matches" : " doesn't match");
2720         PrintIfNotEmpty(inner_listener.str(), listener->stream());
2721         return !all_elements_should_match;
2722       }
2723     }
2724     return all_elements_should_match;
2725   }
2726
2727  protected:
2728   const Matcher<const Element&> inner_matcher_;
2729
2730   GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2731 };
2732
2733 // Implements Contains(element_matcher) for the given argument type Container.
2734 // Symmetric to EachMatcherImpl.
2735 template <typename Container>
2736 class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2737  public:
2738   template <typename InnerMatcher>
2739   explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2740       : QuantifierMatcherImpl<Container>(inner_matcher) {}
2741
2742   // Describes what this matcher does.
2743   virtual void DescribeTo(::std::ostream* os) const {
2744     *os << "contains at least one element that ";
2745     this->inner_matcher_.DescribeTo(os);
2746   }
2747
2748   virtual void DescribeNegationTo(::std::ostream* os) const {
2749     *os << "doesn't contain any element that ";
2750     this->inner_matcher_.DescribeTo(os);
2751   }
2752
2753   virtual bool MatchAndExplain(Container container,
2754                                MatchResultListener* listener) const {
2755     return this->MatchAndExplainImpl(false, container, listener);
2756   }
2757
2758  private:
2759   GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
2760 };
2761
2762 // Implements Each(element_matcher) for the given argument type Container.
2763 // Symmetric to ContainsMatcherImpl.
2764 template <typename Container>
2765 class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2766  public:
2767   template <typename InnerMatcher>
2768   explicit EachMatcherImpl(InnerMatcher inner_matcher)
2769       : QuantifierMatcherImpl<Container>(inner_matcher) {}
2770
2771   // Describes what this matcher does.
2772   virtual void DescribeTo(::std::ostream* os) const {
2773     *os << "only contains elements that ";
2774     this->inner_matcher_.DescribeTo(os);
2775   }
2776
2777   virtual void DescribeNegationTo(::std::ostream* os) const {
2778     *os << "contains some element that ";
2779     this->inner_matcher_.DescribeNegationTo(os);
2780   }
2781
2782   virtual bool MatchAndExplain(Container container,
2783                                MatchResultListener* listener) const {
2784     return this->MatchAndExplainImpl(true, container, listener);
2785   }
2786
2787  private:
2788   GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2789 };
2790
2791 // Implements polymorphic Contains(element_matcher).
2792 template <typename M>
2793 class ContainsMatcher {
2794  public:
2795   explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2796
2797   template <typename Container>
2798   operator Matcher<Container>() const {
2799     return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2800   }
2801
2802  private:
2803   const M inner_matcher_;
2804
2805   GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
2806 };
2807
2808 // Implements polymorphic Each(element_matcher).
2809 template <typename M>
2810 class EachMatcher {
2811  public:
2812   explicit EachMatcher(M m) : inner_matcher_(m) {}
2813
2814   template <typename Container>
2815   operator Matcher<Container>() const {
2816     return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2817   }
2818
2819  private:
2820   const M inner_matcher_;
2821
2822   GTEST_DISALLOW_ASSIGN_(EachMatcher);
2823 };
2824
2825 // Implements Key(inner_matcher) for the given argument pair type.
2826 // Key(inner_matcher) matches an std::pair whose 'first' field matches
2827 // inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
2828 // std::map that contains at least one element whose key is >= 5.
2829 template <typename PairType>
2830 class KeyMatcherImpl : public MatcherInterface<PairType> {
2831  public:
2832   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
2833   typedef typename RawPairType::first_type KeyType;
2834
2835   template <typename InnerMatcher>
2836   explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2837       : inner_matcher_(
2838           testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2839   }
2840
2841   // Returns true iff 'key_value.first' (the key) matches the inner matcher.
2842   virtual bool MatchAndExplain(PairType key_value,
2843                                MatchResultListener* listener) const {
2844     StringMatchResultListener inner_listener;
2845     const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2846                                                       &inner_listener);
2847     const internal::string explanation = inner_listener.str();
2848     if (explanation != "") {
2849       *listener << "whose first field is a value " << explanation;
2850     }
2851     return match;
2852   }
2853
2854   // Describes what this matcher does.
2855   virtual void DescribeTo(::std::ostream* os) const {
2856     *os << "has a key that ";
2857     inner_matcher_.DescribeTo(os);
2858   }
2859
2860   // Describes what the negation of this matcher does.
2861   virtual void DescribeNegationTo(::std::ostream* os) const {
2862     *os << "doesn't have a key that ";
2863     inner_matcher_.DescribeTo(os);
2864   }
2865
2866  private:
2867   const Matcher<const KeyType&> inner_matcher_;
2868
2869   GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
2870 };
2871
2872 // Implements polymorphic Key(matcher_for_key).
2873 template <typename M>
2874 class KeyMatcher {
2875  public:
2876   explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2877
2878   template <typename PairType>
2879   operator Matcher<PairType>() const {
2880     return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2881   }
2882
2883  private:
2884   const M matcher_for_key_;
2885
2886   GTEST_DISALLOW_ASSIGN_(KeyMatcher);
2887 };
2888
2889 // Implements Pair(first_matcher, second_matcher) for the given argument pair
2890 // type with its two matchers. See Pair() function below.
2891 template <typename PairType>
2892 class PairMatcherImpl : public MatcherInterface<PairType> {
2893  public:
2894   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
2895   typedef typename RawPairType::first_type FirstType;
2896   typedef typename RawPairType::second_type SecondType;
2897
2898   template <typename FirstMatcher, typename SecondMatcher>
2899   PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2900       : first_matcher_(
2901             testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2902         second_matcher_(
2903             testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2904   }
2905
2906   // Describes what this matcher does.
2907   virtual void DescribeTo(::std::ostream* os) const {
2908     *os << "has a first field that ";
2909     first_matcher_.DescribeTo(os);
2910     *os << ", and has a second field that ";
2911     second_matcher_.DescribeTo(os);
2912   }
2913
2914   // Describes what the negation of this matcher does.
2915   virtual void DescribeNegationTo(::std::ostream* os) const {
2916     *os << "has a first field that ";
2917     first_matcher_.DescribeNegationTo(os);
2918     *os << ", or has a second field that ";
2919     second_matcher_.DescribeNegationTo(os);
2920   }
2921
2922   // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2923   // matches second_matcher.
2924   virtual bool MatchAndExplain(PairType a_pair,
2925                                MatchResultListener* listener) const {
2926     if (!listener->IsInterested()) {
2927       // If the listener is not interested, we don't need to construct the
2928       // explanation.
2929       return first_matcher_.Matches(a_pair.first) &&
2930              second_matcher_.Matches(a_pair.second);
2931     }
2932     StringMatchResultListener first_inner_listener;
2933     if (!first_matcher_.MatchAndExplain(a_pair.first,
2934                                         &first_inner_listener)) {
2935       *listener << "whose first field does not match";
2936       PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
2937       return false;
2938     }
2939     StringMatchResultListener second_inner_listener;
2940     if (!second_matcher_.MatchAndExplain(a_pair.second,
2941                                          &second_inner_listener)) {
2942       *listener << "whose second field does not match";
2943       PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
2944       return false;
2945     }
2946     ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2947                    listener);
2948     return true;
2949   }
2950
2951  private:
2952   void ExplainSuccess(const internal::string& first_explanation,
2953                       const internal::string& second_explanation,
2954                       MatchResultListener* listener) const {
2955     *listener << "whose both fields match";
2956     if (first_explanation != "") {
2957       *listener << ", where the first field is a value " << first_explanation;
2958     }
2959     if (second_explanation != "") {
2960       *listener << ", ";
2961       if (first_explanation != "") {
2962         *listener << "and ";
2963       } else {
2964         *listener << "where ";
2965       }
2966       *listener << "the second field is a value " << second_explanation;
2967     }
2968   }
2969
2970   const Matcher<const FirstType&> first_matcher_;
2971   const Matcher<const SecondType&> second_matcher_;
2972
2973   GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
2974 };
2975
2976 // Implements polymorphic Pair(first_matcher, second_matcher).
2977 template <typename FirstMatcher, typename SecondMatcher>
2978 class PairMatcher {
2979  public:
2980   PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2981       : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2982
2983   template <typename PairType>
2984   operator Matcher<PairType> () const {
2985     return MakeMatcher(
2986         new PairMatcherImpl<PairType>(
2987             first_matcher_, second_matcher_));
2988   }
2989
2990  private:
2991   const FirstMatcher first_matcher_;
2992   const SecondMatcher second_matcher_;
2993
2994   GTEST_DISALLOW_ASSIGN_(PairMatcher);
2995 };
2996
2997 // Implements ElementsAre() and ElementsAreArray().
2998 template <typename Container>
2999 class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3000  public:
3001   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3002   typedef internal::StlContainerView<RawContainer> View;
3003   typedef typename View::type StlContainer;
3004   typedef typename View::const_reference StlContainerReference;
3005   typedef typename StlContainer::value_type Element;
3006
3007   // Constructs the matcher from a sequence of element values or
3008   // element matchers.
3009   template <typename InputIter>
3010   ElementsAreMatcherImpl(InputIter first, InputIter last) {
3011     while (first != last) {
3012       matchers_.push_back(MatcherCast<const Element&>(*first++));
3013     }
3014   }
3015
3016   // Describes what this matcher does.
3017   virtual void DescribeTo(::std::ostream* os) const {
3018     if (count() == 0) {
3019       *os << "is empty";
3020     } else if (count() == 1) {
3021       *os << "has 1 element that ";
3022       matchers_[0].DescribeTo(os);
3023     } else {
3024       *os << "has " << Elements(count()) << " where\n";
3025       for (size_t i = 0; i != count(); ++i) {
3026         *os << "element #" << i << " ";
3027         matchers_[i].DescribeTo(os);
3028         if (i + 1 < count()) {
3029           *os << ",\n";
3030         }
3031       }
3032     }
3033   }
3034
3035   // Describes what the negation of this matcher does.
3036   virtual void DescribeNegationTo(::std::ostream* os) const {
3037     if (count() == 0) {
3038       *os << "isn't empty";
3039       return;
3040     }
3041
3042     *os << "doesn't have " << Elements(count()) << ", or\n";
3043     for (size_t i = 0; i != count(); ++i) {
3044       *os << "element #" << i << " ";
3045       matchers_[i].DescribeNegationTo(os);
3046       if (i + 1 < count()) {
3047         *os << ", or\n";
3048       }
3049     }
3050   }
3051
3052   virtual bool MatchAndExplain(Container container,
3053                                MatchResultListener* listener) const {
3054     // To work with stream-like "containers", we must only walk
3055     // through the elements in one pass.
3056
3057     const bool listener_interested = listener->IsInterested();
3058
3059     // explanations[i] is the explanation of the element at index i.
3060     ::std::vector<internal::string> explanations(count());
3061     StlContainerReference stl_container = View::ConstReference(container);
3062     typename StlContainer::const_iterator it = stl_container.begin();
3063     size_t exam_pos = 0;
3064     bool mismatch_found = false;  // Have we found a mismatched element yet?
3065
3066     // Go through the elements and matchers in pairs, until we reach
3067     // the end of either the elements or the matchers, or until we find a
3068     // mismatch.
3069     for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3070       bool match;  // Does the current element match the current matcher?
3071       if (listener_interested) {
3072         StringMatchResultListener s;
3073         match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3074         explanations[exam_pos] = s.str();
3075       } else {
3076         match = matchers_[exam_pos].Matches(*it);
3077       }
3078
3079       if (!match) {
3080         mismatch_found = true;
3081         break;
3082       }
3083     }
3084     // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3085
3086     // Find how many elements the actual container has.  We avoid
3087     // calling size() s.t. this code works for stream-like "containers"
3088     // that don't define size().
3089     size_t actual_count = exam_pos;
3090     for (; it != stl_container.end(); ++it) {
3091       ++actual_count;
3092     }
3093
3094     if (actual_count != count()) {
3095       // The element count doesn't match.  If the container is empty,
3096       // there's no need to explain anything as Google Mock already
3097       // prints the empty container.  Otherwise we just need to show
3098       // how many elements there actually are.
3099       if (listener_interested && (actual_count != 0)) {
3100         *listener << "which has " << Elements(actual_count);
3101       }
3102       return false;
3103     }
3104
3105     if (mismatch_found) {
3106       // The element count matches, but the exam_pos-th element doesn't match.
3107       if (listener_interested) {
3108         *listener << "whose element #" << exam_pos << " doesn't match";
3109         PrintIfNotEmpty(explanations[exam_pos], listener->stream());
3110       }
3111       return false;
3112     }
3113
3114     // Every element matches its expectation.  We need to explain why
3115     // (the obvious ones can be skipped).
3116     if (listener_interested) {
3117       bool reason_printed = false;
3118       for (size_t i = 0; i != count(); ++i) {
3119         const internal::string& s = explanations[i];
3120         if (!s.empty()) {
3121           if (reason_printed) {
3122             *listener << ",\nand ";
3123           }
3124           *listener << "whose element #" << i << " matches, " << s;
3125           reason_printed = true;
3126         }
3127       }
3128     }
3129     return true;
3130   }
3131
3132  private:
3133   static Message Elements(size_t count) {
3134     return Message() << count << (count == 1 ? " element" : " elements");
3135   }
3136
3137   size_t count() const { return matchers_.size(); }
3138
3139   ::std::vector<Matcher<const Element&> > matchers_;
3140
3141   GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
3142 };
3143
3144 // Connectivity matrix of (elements X matchers), in element-major order.
3145 // Initially, there are no edges.
3146 // Use NextGraph() to iterate over all possible edge configurations.
3147 // Use Randomize() to generate a random edge configuration.
3148 class GTEST_API_ MatchMatrix {
3149  public:
3150   MatchMatrix(size_t num_elements, size_t num_matchers)
3151       : num_elements_(num_elements),
3152         num_matchers_(num_matchers),
3153         matched_(num_elements_* num_matchers_, 0) {
3154   }
3155
3156   size_t LhsSize() const { return num_elements_; }
3157   size_t RhsSize() const { return num_matchers_; }
3158   bool HasEdge(size_t ilhs, size_t irhs) const {
3159     return matched_[SpaceIndex(ilhs, irhs)] == 1;
3160   }
3161   void SetEdge(size_t ilhs, size_t irhs, bool b) {
3162     matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3163   }
3164
3165   // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3166   // adds 1 to that number; returns false if incrementing the graph left it
3167   // empty.
3168   bool NextGraph();
3169
3170   void Randomize();
3171
3172   string DebugString() const;
3173
3174  private:
3175   size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3176     return ilhs * num_matchers_ + irhs;
3177   }
3178
3179   size_t num_elements_;
3180   size_t num_matchers_;
3181
3182   // Each element is a char interpreted as bool. They are stored as a
3183   // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3184   // a (ilhs, irhs) matrix coordinate into an offset.
3185   ::std::vector<char> matched_;
3186 };
3187
3188 typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3189 typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3190
3191 // Returns a maximum bipartite matching for the specified graph 'g'.
3192 // The matching is represented as a vector of {element, matcher} pairs.
3193 GTEST_API_ ElementMatcherPairs
3194 FindMaxBipartiteMatching(const MatchMatrix& g);
3195
3196 GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3197                             MatchResultListener* listener);
3198
3199 // Untyped base class for implementing UnorderedElementsAre.  By
3200 // putting logic that's not specific to the element type here, we
3201 // reduce binary bloat and increase compilation speed.
3202 class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3203  protected:
3204   // A vector of matcher describers, one for each element matcher.
3205   // Does not own the describers (and thus can be used only when the
3206   // element matchers are alive).
3207   typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3208
3209   // Describes this UnorderedElementsAre matcher.
3210   void DescribeToImpl(::std::ostream* os) const;
3211
3212   // Describes the negation of this UnorderedElementsAre matcher.
3213   void DescribeNegationToImpl(::std::ostream* os) const;
3214
3215   bool VerifyAllElementsAndMatchersAreMatched(
3216       const ::std::vector<string>& element_printouts,
3217       const MatchMatrix& matrix,
3218       MatchResultListener* listener) const;
3219
3220   MatcherDescriberVec& matcher_describers() {
3221     return matcher_describers_;
3222   }
3223
3224   static Message Elements(size_t n) {
3225     return Message() << n << " element" << (n == 1 ? "" : "s");
3226   }
3227
3228  private:
3229   MatcherDescriberVec matcher_describers_;
3230
3231   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3232 };
3233
3234 // Implements unordered ElementsAre and unordered ElementsAreArray.
3235 template <typename Container>
3236 class UnorderedElementsAreMatcherImpl
3237     : public MatcherInterface<Container>,
3238       public UnorderedElementsAreMatcherImplBase {
3239  public:
3240   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3241   typedef internal::StlContainerView<RawContainer> View;
3242   typedef typename View::type StlContainer;
3243   typedef typename View::const_reference StlContainerReference;
3244   typedef typename StlContainer::const_iterator StlContainerConstIterator;
3245   typedef typename StlContainer::value_type Element;
3246
3247   // Constructs the matcher from a sequence of element values or
3248   // element matchers.
3249   template <typename InputIter>
3250   UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3251     for (; first != last; ++first) {
3252       matchers_.push_back(MatcherCast<const Element&>(*first));
3253       matcher_describers().push_back(matchers_.back().GetDescriber());
3254     }
3255   }
3256
3257   // Describes what this matcher does.
3258   virtual void DescribeTo(::std::ostream* os) const {
3259     return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3260   }
3261
3262   // Describes what the negation of this matcher does.
3263   virtual void DescribeNegationTo(::std::ostream* os) const {
3264     return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3265   }
3266
3267   virtual bool MatchAndExplain(Container container,
3268                                MatchResultListener* listener) const {
3269     StlContainerReference stl_container = View::ConstReference(container);
3270     ::std::vector<string> element_printouts;
3271     MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3272                                          stl_container.end(),
3273                                          &element_printouts,
3274                                          listener);
3275
3276     const size_t actual_count = matrix.LhsSize();
3277     if (actual_count == 0 && matchers_.empty()) {
3278       return true;
3279     }
3280     if (actual_count != matchers_.size()) {
3281       // The element count doesn't match.  If the container is empty,
3282       // there's no need to explain anything as Google Mock already
3283       // prints the empty container. Otherwise we just need to show
3284       // how many elements there actually are.
3285       if (actual_count != 0 && listener->IsInterested()) {
3286         *listener << "which has " << Elements(actual_count);
3287       }
3288       return false;
3289     }
3290
3291     return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3292                                                   matrix, listener) &&
3293            FindPairing(matrix, listener);
3294   }
3295
3296  private:
3297   typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3298
3299   template <typename ElementIter>
3300   MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
3301                               ::std::vector<string>* element_printouts,
3302                               MatchResultListener* listener) const {
3303     element_printouts->clear();
3304     ::std::vector<char> did_match;
3305     size_t num_elements = 0;
3306     for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3307       if (listener->IsInterested()) {
3308         element_printouts->push_back(PrintToString(*elem_first));
3309       }
3310       for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3311         did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3312       }
3313     }
3314
3315     MatchMatrix matrix(num_elements, matchers_.size());
3316     ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3317     for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3318       for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3319         matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3320       }
3321     }
3322     return matrix;
3323   }
3324
3325   MatcherVec matchers_;
3326
3327   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3328 };
3329
3330 // Functor for use in TransformTuple.
3331 // Performs MatcherCast<Target> on an input argument of any type.
3332 template <typename Target>
3333 struct CastAndAppendTransform {
3334   template <typename Arg>
3335   Matcher<Target> operator()(const Arg& a) const {
3336     return MatcherCast<Target>(a);
3337   }
3338 };
3339
3340 // Implements UnorderedElementsAre.
3341 template <typename MatcherTuple>
3342 class UnorderedElementsAreMatcher {
3343  public:
3344   explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3345       : matchers_(args) {}
3346
3347   template <typename Container>
3348   operator Matcher<Container>() const {
3349     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3350     typedef typename internal::StlContainerView<RawContainer>::type View;
3351     typedef typename View::value_type Element;
3352     typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3353     MatcherVec matchers;
3354     matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3355     TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3356                          ::std::back_inserter(matchers));
3357     return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3358                            matchers.begin(), matchers.end()));
3359   }
3360
3361  private:
3362   const MatcherTuple matchers_;
3363   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3364 };
3365
3366 // Implements ElementsAre.
3367 template <typename MatcherTuple>
3368 class ElementsAreMatcher {
3369  public:
3370   explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3371
3372   template <typename Container>
3373   operator Matcher<Container>() const {
3374     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3375     typedef typename internal::StlContainerView<RawContainer>::type View;
3376     typedef typename View::value_type Element;
3377     typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3378     MatcherVec matchers;
3379     matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3380     TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3381                          ::std::back_inserter(matchers));
3382     return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3383                            matchers.begin(), matchers.end()));
3384   }
3385
3386  private:
3387   const MatcherTuple matchers_;
3388   GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3389 };
3390
3391 // Implements UnorderedElementsAreArray().
3392 template <typename T>
3393 class UnorderedElementsAreArrayMatcher {
3394  public:
3395   UnorderedElementsAreArrayMatcher() {}
3396
3397   template <typename Iter>
3398   UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3399       : matchers_(first, last) {}
3400
3401   template <typename Container>
3402   operator Matcher<Container>() const {
3403     return MakeMatcher(
3404         new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3405                                                        matchers_.end()));
3406   }
3407
3408  private:
3409   ::std::vector<T> matchers_;
3410
3411   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
3412 };
3413
3414 // Implements ElementsAreArray().
3415 template <typename T>
3416 class ElementsAreArrayMatcher {
3417  public:
3418   template <typename Iter>
3419   ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
3420
3421   template <typename Container>
3422   operator Matcher<Container>() const {
3423     return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3424         matchers_.begin(), matchers_.end()));
3425   }
3426
3427  private:
3428   const ::std::vector<T> matchers_;
3429
3430   GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
3431 };
3432
3433 // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3434 // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3435 // second) is a polymorphic matcher that matches a value x iff tm
3436 // matches tuple (x, second).  Useful for implementing
3437 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
3438 //
3439 // BoundSecondMatcher is copyable and assignable, as we need to put
3440 // instances of this class in a vector when implementing
3441 // UnorderedPointwise().
3442 template <typename Tuple2Matcher, typename Second>
3443 class BoundSecondMatcher {
3444  public:
3445   BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3446       : tuple2_matcher_(tm), second_value_(second) {}
3447
3448   template <typename T>
3449   operator Matcher<T>() const {
3450     return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3451   }
3452
3453   // We have to define this for UnorderedPointwise() to compile in
3454   // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3455   // which requires the elements to be assignable in C++98.  The
3456   // compiler cannot generate the operator= for us, as Tuple2Matcher
3457   // and Second may not be assignable.
3458   //
3459   // However, this should never be called, so the implementation just
3460   // need to assert.
3461   void operator=(const BoundSecondMatcher& /*rhs*/) {
3462     GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3463   }
3464
3465  private:
3466   template <typename T>
3467   class Impl : public MatcherInterface<T> {
3468    public:
3469     typedef ::testing::tuple<T, Second> ArgTuple;
3470
3471     Impl(const Tuple2Matcher& tm, const Second& second)
3472         : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3473           second_value_(second) {}
3474
3475     virtual void DescribeTo(::std::ostream* os) const {
3476       *os << "and ";
3477       UniversalPrint(second_value_, os);
3478       *os << " ";
3479       mono_tuple2_matcher_.DescribeTo(os);
3480     }
3481
3482     virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3483       return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3484                                                   listener);
3485     }
3486
3487    private:
3488     const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3489     const Second second_value_;
3490
3491     GTEST_DISALLOW_ASSIGN_(Impl);
3492   };
3493
3494   const Tuple2Matcher tuple2_matcher_;
3495   const Second second_value_;
3496 };
3497
3498 // Given a 2-tuple matcher tm and a value second,
3499 // MatcherBindSecond(tm, second) returns a matcher that matches a
3500 // value x iff tm matches tuple (x, second).  Useful for implementing
3501 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
3502 template <typename Tuple2Matcher, typename Second>
3503 BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3504     const Tuple2Matcher& tm, const Second& second) {
3505   return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3506 }
3507
3508 // Returns the description for a matcher defined using the MATCHER*()
3509 // macro where the user-supplied description string is "", if
3510 // 'negation' is false; otherwise returns the description of the
3511 // negation of the matcher.  'param_values' contains a list of strings
3512 // that are the print-out of the matcher's parameters.
3513 GTEST_API_ string FormatMatcherDescription(bool negation,
3514                                            const char* matcher_name,
3515                                            const Strings& param_values);
3516
3517 }  // namespace internal
3518
3519 // ElementsAreArray(first, last)
3520 // ElementsAreArray(pointer, count)
3521 // ElementsAreArray(array)
3522 // ElementsAreArray(container)
3523 // ElementsAreArray({ e1, e2, ..., en })
3524 //
3525 // The ElementsAreArray() functions are like ElementsAre(...), except
3526 // that they are given a homogeneous sequence rather than taking each
3527 // element as a function argument. The sequence can be specified as an
3528 // array, a pointer and count, a vector, an initializer list, or an
3529 // STL iterator range. In each of these cases, the underlying sequence
3530 // can be either a sequence of values or a sequence of matchers.
3531 //
3532 // All forms of ElementsAreArray() make a copy of the input matcher sequence.
3533
3534 template <typename Iter>
3535 inline internal::ElementsAreArrayMatcher<
3536     typename ::std::iterator_traits<Iter>::value_type>
3537 ElementsAreArray(Iter first, Iter last) {
3538   typedef typename ::std::iterator_traits<Iter>::value_type T;
3539   return internal::ElementsAreArrayMatcher<T>(first, last);
3540 }
3541
3542 template <typename T>
3543 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3544     const T* pointer, size_t count) {
3545   return ElementsAreArray(pointer, pointer + count);
3546 }
3547
3548 template <typename T, size_t N>
3549 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3550     const T (&array)[N]) {
3551   return ElementsAreArray(array, N);
3552 }
3553
3554 template <typename Container>
3555 inline internal::ElementsAreArrayMatcher<typename Container::value_type>
3556 ElementsAreArray(const Container& container) {
3557   return ElementsAreArray(container.begin(), container.end());
3558 }
3559
3560 #if GTEST_HAS_STD_INITIALIZER_LIST_
3561 template <typename T>
3562 inline internal::ElementsAreArrayMatcher<T>
3563 ElementsAreArray(::std::initializer_list<T> xs) {
3564   return ElementsAreArray(xs.begin(), xs.end());
3565 }
3566 #endif
3567
3568 // UnorderedElementsAreArray(first, last)
3569 // UnorderedElementsAreArray(pointer, count)
3570 // UnorderedElementsAreArray(array)
3571 // UnorderedElementsAreArray(container)
3572 // UnorderedElementsAreArray({ e1, e2, ..., en })
3573 //
3574 // The UnorderedElementsAreArray() functions are like
3575 // ElementsAreArray(...), but allow matching the elements in any order.
3576 template <typename Iter>
3577 inline internal::UnorderedElementsAreArrayMatcher<
3578     typename ::std::iterator_traits<Iter>::value_type>
3579 UnorderedElementsAreArray(Iter first, Iter last) {
3580   typedef typename ::std::iterator_traits<Iter>::value_type T;
3581   return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3582 }
3583
3584 template <typename T>
3585 inline internal::UnorderedElementsAreArrayMatcher<T>
3586 UnorderedElementsAreArray(const T* pointer, size_t count) {
3587   return UnorderedElementsAreArray(pointer, pointer + count);
3588 }
3589
3590 template <typename T, size_t N>
3591 inline internal::UnorderedElementsAreArrayMatcher<T>
3592 UnorderedElementsAreArray(const T (&array)[N]) {
3593   return UnorderedElementsAreArray(array, N);
3594 }
3595
3596 template <typename Container>
3597 inline internal::UnorderedElementsAreArrayMatcher<
3598     typename Container::value_type>
3599 UnorderedElementsAreArray(const Container& container) {
3600   return UnorderedElementsAreArray(container.begin(), container.end());
3601 }
3602
3603 #if GTEST_HAS_STD_INITIALIZER_LIST_
3604 template <typename T>
3605 inline internal::UnorderedElementsAreArrayMatcher<T>
3606 UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3607   return UnorderedElementsAreArray(xs.begin(), xs.end());
3608 }
3609 #endif
3610
3611 // _ is a matcher that matches anything of any type.
3612 //
3613 // This definition is fine as:
3614 //
3615 //   1. The C++ standard permits using the name _ in a namespace that
3616 //      is not the global namespace or ::std.
3617 //   2. The AnythingMatcher class has no data member or constructor,
3618 //      so it's OK to create global variables of this type.
3619 //   3. c-style has approved of using _ in this case.
3620 const internal::AnythingMatcher _ = {};
3621 // Creates a matcher that matches any value of the given type T.
3622 template <typename T>
3623 inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3624
3625 // Creates a matcher that matches any value of the given type T.
3626 template <typename T>
3627 inline Matcher<T> An() { return A<T>(); }
3628
3629 // Creates a polymorphic matcher that matches anything equal to x.
3630 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3631 // wouldn't compile.
3632 template <typename T>
3633 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3634
3635 // Constructs a Matcher<T> from a 'value' of type T.  The constructed
3636 // matcher matches any value that's equal to 'value'.
3637 template <typename T>
3638 Matcher<T>::Matcher(T value) { *this = Eq(value); }
3639
3640 // Creates a monomorphic matcher that matches anything with type Lhs
3641 // and equal to rhs.  A user may need to use this instead of Eq(...)
3642 // in order to resolve an overloading ambiguity.
3643 //
3644 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3645 // or Matcher<T>(x), but more readable than the latter.
3646 //
3647 // We could define similar monomorphic matchers for other comparison
3648 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3649 // it yet as those are used much less than Eq() in practice.  A user
3650 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
3651 // for example.
3652 template <typename Lhs, typename Rhs>
3653 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3654
3655 // Creates a polymorphic matcher that matches anything >= x.
3656 template <typename Rhs>
3657 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3658   return internal::GeMatcher<Rhs>(x);
3659 }
3660
3661 // Creates a polymorphic matcher that matches anything > x.
3662 template <typename Rhs>
3663 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3664   return internal::GtMatcher<Rhs>(x);
3665 }
3666
3667 // Creates a polymorphic matcher that matches anything <= x.
3668 template <typename Rhs>
3669 inline internal::LeMatcher<Rhs> Le(Rhs x) {
3670   return internal::LeMatcher<Rhs>(x);
3671 }
3672
3673 // Creates a polymorphic matcher that matches anything < x.
3674 template <typename Rhs>
3675 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3676   return internal::LtMatcher<Rhs>(x);
3677 }
3678
3679 // Creates a polymorphic matcher that matches anything != x.
3680 template <typename Rhs>
3681 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3682   return internal::NeMatcher<Rhs>(x);
3683 }
3684
3685 // Creates a polymorphic matcher that matches any NULL pointer.
3686 inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3687   return MakePolymorphicMatcher(internal::IsNullMatcher());
3688 }
3689
3690 // Creates a polymorphic matcher that matches any non-NULL pointer.
3691 // This is convenient as Not(NULL) doesn't compile (the compiler
3692 // thinks that that expression is comparing a pointer with an integer).
3693 inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3694   return MakePolymorphicMatcher(internal::NotNullMatcher());
3695 }
3696
3697 // Creates a polymorphic matcher that matches any argument that
3698 // references variable x.
3699 template <typename T>
3700 inline internal::RefMatcher<T&> Ref(T& x) {  // NOLINT
3701   return internal::RefMatcher<T&>(x);
3702 }
3703
3704 // Creates a matcher that matches any double argument approximately
3705 // equal to rhs, where two NANs are considered unequal.
3706 inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3707   return internal::FloatingEqMatcher<double>(rhs, false);
3708 }
3709
3710 // Creates a matcher that matches any double argument approximately
3711 // equal to rhs, including NaN values when rhs is NaN.
3712 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3713   return internal::FloatingEqMatcher<double>(rhs, true);
3714 }
3715
3716 // Creates a matcher that matches any double argument approximately equal to
3717 // rhs, up to the specified max absolute error bound, where two NANs are
3718 // considered unequal.  The max absolute error bound must be non-negative.
3719 inline internal::FloatingEqMatcher<double> DoubleNear(
3720     double rhs, double max_abs_error) {
3721   return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3722 }
3723
3724 // Creates a matcher that matches any double argument approximately equal to
3725 // rhs, up to the specified max absolute error bound, including NaN values when
3726 // rhs is NaN.  The max absolute error bound must be non-negative.
3727 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3728     double rhs, double max_abs_error) {
3729   return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3730 }
3731
3732 // Creates a matcher that matches any float argument approximately
3733 // equal to rhs, where two NANs are considered unequal.
3734 inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3735   return internal::FloatingEqMatcher<float>(rhs, false);
3736 }
3737
3738 // Creates a matcher that matches any float argument approximately
3739 // equal to rhs, including NaN values when rhs is NaN.
3740 inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3741   return internal::FloatingEqMatcher<float>(rhs, true);
3742 }
3743
3744 // Creates a matcher that matches any float argument approximately equal to
3745 // rhs, up to the specified max absolute error bound, where two NANs are
3746 // considered unequal.  The max absolute error bound must be non-negative.
3747 inline internal::FloatingEqMatcher<float> FloatNear(
3748     float rhs, float max_abs_error) {
3749   return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3750 }
3751
3752 // Creates a matcher that matches any float argument approximately equal to
3753 // rhs, up to the specified max absolute error bound, including NaN values when
3754 // rhs is NaN.  The max absolute error bound must be non-negative.
3755 inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3756     float rhs, float max_abs_error) {
3757   return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3758 }
3759
3760 // Creates a matcher that matches a pointer (raw or smart) that points
3761 // to a value that matches inner_matcher.
3762 template <typename InnerMatcher>
3763 inline internal::PointeeMatcher<InnerMatcher> Pointee(
3764     const InnerMatcher& inner_matcher) {
3765   return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3766 }
3767
3768 // Creates a matcher that matches a pointer or reference that matches
3769 // inner_matcher when dynamic_cast<To> is applied.
3770 // The result of dynamic_cast<To> is forwarded to the inner matcher.
3771 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
3772 // If To is a reference and the cast fails, this matcher returns false
3773 // immediately.
3774 template <typename To>
3775 inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
3776 WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
3777   return MakePolymorphicMatcher(
3778       internal::WhenDynamicCastToMatcher<To>(inner_matcher));
3779 }
3780
3781 // Creates a matcher that matches an object whose given field matches
3782 // 'matcher'.  For example,
3783 //   Field(&Foo::number, Ge(5))
3784 // matches a Foo object x iff x.number >= 5.
3785 template <typename Class, typename FieldType, typename FieldMatcher>
3786 inline PolymorphicMatcher<
3787   internal::FieldMatcher<Class, FieldType> > Field(
3788     FieldType Class::*field, const FieldMatcher& matcher) {
3789   return MakePolymorphicMatcher(
3790       internal::FieldMatcher<Class, FieldType>(
3791           field, MatcherCast<const FieldType&>(matcher)));
3792   // The call to MatcherCast() is required for supporting inner
3793   // matchers of compatible types.  For example, it allows
3794   //   Field(&Foo::bar, m)
3795   // to compile where bar is an int32 and m is a matcher for int64.
3796 }
3797
3798 // Creates a matcher that matches an object whose given property
3799 // matches 'matcher'.  For example,
3800 //   Property(&Foo::str, StartsWith("hi"))
3801 // matches a Foo object x iff x.str() starts with "hi".
3802 template <typename Class, typename PropertyType, typename PropertyMatcher>
3803 inline PolymorphicMatcher<
3804   internal::PropertyMatcher<Class, PropertyType> > Property(
3805     PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
3806   return MakePolymorphicMatcher(
3807       internal::PropertyMatcher<Class, PropertyType>(
3808           property,
3809           MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
3810   // The call to MatcherCast() is required for supporting inner
3811   // matchers of compatible types.  For example, it allows
3812   //   Property(&Foo::bar, m)
3813   // to compile where bar() returns an int32 and m is a matcher for int64.
3814 }
3815
3816 // Creates a matcher that matches an object iff the result of applying
3817 // a callable to x matches 'matcher'.
3818 // For example,
3819 //   ResultOf(f, StartsWith("hi"))
3820 // matches a Foo object x iff f(x) starts with "hi".
3821 // callable parameter can be a function, function pointer, or a functor.
3822 // Callable has to satisfy the following conditions:
3823 //   * It is required to keep no state affecting the results of
3824 //     the calls on it and make no assumptions about how many calls
3825 //     will be made. Any state it keeps must be protected from the
3826 //     concurrent access.
3827 //   * If it is a function object, it has to define type result_type.
3828 //     We recommend deriving your functor classes from std::unary_function.
3829 template <typename Callable, typename ResultOfMatcher>
3830 internal::ResultOfMatcher<Callable> ResultOf(
3831     Callable callable, const ResultOfMatcher& matcher) {
3832   return internal::ResultOfMatcher<Callable>(
3833           callable,
3834           MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3835               matcher));
3836   // The call to MatcherCast() is required for supporting inner
3837   // matchers of compatible types.  For example, it allows
3838   //   ResultOf(Function, m)
3839   // to compile where Function() returns an int32 and m is a matcher for int64.
3840 }
3841
3842 // String matchers.
3843
3844 // Matches a string equal to str.
3845 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3846     StrEq(const internal::string& str) {
3847   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3848       str, true, true));
3849 }
3850
3851 // Matches a string not equal to str.
3852 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3853     StrNe(const internal::string& str) {
3854   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3855       str, false, true));
3856 }
3857
3858 // Matches a string equal to str, ignoring case.
3859 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3860     StrCaseEq(const internal::string& str) {
3861   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3862       str, true, false));
3863 }
3864
3865 // Matches a string not equal to str, ignoring case.
3866 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3867     StrCaseNe(const internal::string& str) {
3868   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3869       str, false, false));
3870 }
3871
3872 // Creates a matcher that matches any string, std::string, or C string
3873 // that contains the given substring.
3874 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
3875     HasSubstr(const internal::string& substring) {
3876   return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3877       substring));
3878 }
3879
3880 // Matches a string that starts with 'prefix' (case-sensitive).
3881 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3882     StartsWith(const internal::string& prefix) {
3883   return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3884       prefix));
3885 }
3886
3887 // Matches a string that ends with 'suffix' (case-sensitive).
3888 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3889     EndsWith(const internal::string& suffix) {
3890   return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
3891       suffix));
3892 }
3893
3894 // Matches a string that fully matches regular expression 'regex'.
3895 // The matcher takes ownership of 'regex'.
3896 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3897     const internal::RE* regex) {
3898   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
3899 }
3900 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3901     const internal::string& regex) {
3902   return MatchesRegex(new internal::RE(regex));
3903 }
3904
3905 // Matches a string that contains regular expression 'regex'.
3906 // The matcher takes ownership of 'regex'.
3907 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3908     const internal::RE* regex) {
3909   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
3910 }
3911 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3912     const internal::string& regex) {
3913   return ContainsRegex(new internal::RE(regex));
3914 }
3915
3916 #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3917 // Wide string matchers.
3918
3919 // Matches a string equal to str.
3920 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3921     StrEq(const internal::wstring& str) {
3922   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3923       str, true, true));
3924 }
3925
3926 // Matches a string not equal to str.
3927 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3928     StrNe(const internal::wstring& str) {
3929   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3930       str, false, true));
3931 }
3932
3933 // Matches a string equal to str, ignoring case.
3934 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3935     StrCaseEq(const internal::wstring& str) {
3936   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3937       str, true, false));
3938 }
3939
3940 // Matches a string not equal to str, ignoring case.
3941 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3942     StrCaseNe(const internal::wstring& str) {
3943   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3944       str, false, false));
3945 }
3946
3947 // Creates a matcher that matches any wstring, std::wstring, or C wide string
3948 // that contains the given substring.
3949 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
3950     HasSubstr(const internal::wstring& substring) {
3951   return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
3952       substring));
3953 }
3954
3955 // Matches a string that starts with 'prefix' (case-sensitive).
3956 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
3957     StartsWith(const internal::wstring& prefix) {
3958   return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
3959       prefix));
3960 }
3961
3962 // Matches a string that ends with 'suffix' (case-sensitive).
3963 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
3964     EndsWith(const internal::wstring& suffix) {
3965   return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
3966       suffix));
3967 }
3968
3969 #endif  // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3970
3971 // Creates a polymorphic matcher that matches a 2-tuple where the
3972 // first field == the second field.
3973 inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
3974
3975 // Creates a polymorphic matcher that matches a 2-tuple where the
3976 // first field >= the second field.
3977 inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
3978
3979 // Creates a polymorphic matcher that matches a 2-tuple where the
3980 // first field > the second field.
3981 inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
3982
3983 // Creates a polymorphic matcher that matches a 2-tuple where the
3984 // first field <= the second field.
3985 inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
3986
3987 // Creates a polymorphic matcher that matches a 2-tuple where the
3988 // first field < the second field.
3989 inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
3990
3991 // Creates a polymorphic matcher that matches a 2-tuple where the
3992 // first field != the second field.
3993 inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
3994
3995 // Creates a matcher that matches any value of type T that m doesn't
3996 // match.
3997 template <typename InnerMatcher>
3998 inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
3999   return internal::NotMatcher<InnerMatcher>(m);
4000 }
4001
4002 // Returns a matcher that matches anything that satisfies the given
4003 // predicate.  The predicate can be any unary function or functor
4004 // whose return type can be implicitly converted to bool.
4005 template <typename Predicate>
4006 inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4007 Truly(Predicate pred) {
4008   return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4009 }
4010
4011 // Returns a matcher that matches the container size. The container must
4012 // support both size() and size_type which all STL-like containers provide.
4013 // Note that the parameter 'size' can be a value of type size_type as well as
4014 // matcher. For instance:
4015 //   EXPECT_THAT(container, SizeIs(2));     // Checks container has 2 elements.
4016 //   EXPECT_THAT(container, SizeIs(Le(2));  // Checks container has at most 2.
4017 template <typename SizeMatcher>
4018 inline internal::SizeIsMatcher<SizeMatcher>
4019 SizeIs(const SizeMatcher& size_matcher) {
4020   return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4021 }
4022
4023 // Returns a matcher that matches the distance between the container's begin()
4024 // iterator and its end() iterator, i.e. the size of the container. This matcher
4025 // can be used instead of SizeIs with containers such as std::forward_list which
4026 // do not implement size(). The container must provide const_iterator (with
4027 // valid iterator_traits), begin() and end().
4028 template <typename DistanceMatcher>
4029 inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4030 BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4031   return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4032 }
4033
4034 // Returns a matcher that matches an equal container.
4035 // This matcher behaves like Eq(), but in the event of mismatch lists the
4036 // values that are included in one container but not the other. (Duplicate
4037 // values and order differences are not explained.)
4038 template <typename Container>
4039 inline PolymorphicMatcher<internal::ContainerEqMatcher<  // NOLINT
4040                             GTEST_REMOVE_CONST_(Container)> >
4041     ContainerEq(const Container& rhs) {
4042   // This following line is for working around a bug in MSVC 8.0,
4043   // which causes Container to be a const type sometimes.
4044   typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4045   return MakePolymorphicMatcher(
4046       internal::ContainerEqMatcher<RawContainer>(rhs));
4047 }
4048
4049 // Returns a matcher that matches a container that, when sorted using
4050 // the given comparator, matches container_matcher.
4051 template <typename Comparator, typename ContainerMatcher>
4052 inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4053 WhenSortedBy(const Comparator& comparator,
4054              const ContainerMatcher& container_matcher) {
4055   return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4056       comparator, container_matcher);
4057 }
4058
4059 // Returns a matcher that matches a container that, when sorted using
4060 // the < operator, matches container_matcher.
4061 template <typename ContainerMatcher>
4062 inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4063 WhenSorted(const ContainerMatcher& container_matcher) {
4064   return
4065       internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4066           internal::LessComparator(), container_matcher);
4067 }
4068
4069 // Matches an STL-style container or a native array that contains the
4070 // same number of elements as in rhs, where its i-th element and rhs's
4071 // i-th element (as a pair) satisfy the given pair matcher, for all i.
4072 // TupleMatcher must be able to be safely cast to Matcher<tuple<const
4073 // T1&, const T2&> >, where T1 and T2 are the types of elements in the
4074 // LHS container and the RHS container respectively.
4075 template <typename TupleMatcher, typename Container>
4076 inline internal::PointwiseMatcher<TupleMatcher,
4077                                   GTEST_REMOVE_CONST_(Container)>
4078 Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4079   // This following line is for working around a bug in MSVC 8.0,
4080   // which causes Container to be a const type sometimes (e.g. when
4081   // rhs is a const int[])..
4082   typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4083   return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4084       tuple_matcher, rhs);
4085 }
4086
4087 #if GTEST_HAS_STD_INITIALIZER_LIST_
4088
4089 // Supports the Pointwise(m, {a, b, c}) syntax.
4090 template <typename TupleMatcher, typename T>
4091 inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4092     const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4093   return Pointwise(tuple_matcher, std::vector<T>(rhs));
4094 }
4095
4096 #endif  // GTEST_HAS_STD_INITIALIZER_LIST_
4097
4098 // UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4099 // container or a native array that contains the same number of
4100 // elements as in rhs, where in some permutation of the container, its
4101 // i-th element and rhs's i-th element (as a pair) satisfy the given
4102 // pair matcher, for all i.  Tuple2Matcher must be able to be safely
4103 // cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4104 // the types of elements in the LHS container and the RHS container
4105 // respectively.
4106 //
4107 // This is like Pointwise(pair_matcher, rhs), except that the element
4108 // order doesn't matter.
4109 template <typename Tuple2Matcher, typename RhsContainer>
4110 inline internal::UnorderedElementsAreArrayMatcher<
4111     typename internal::BoundSecondMatcher<
4112         Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4113                            RhsContainer)>::type::value_type> >
4114 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4115                    const RhsContainer& rhs_container) {
4116   // This following line is for working around a bug in MSVC 8.0,
4117   // which causes RhsContainer to be a const type sometimes (e.g. when
4118   // rhs_container is a const int[]).
4119   typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4120
4121   // RhsView allows the same code to handle RhsContainer being a
4122   // STL-style container and it being a native C-style array.
4123   typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4124   typedef typename RhsView::type RhsStlContainer;
4125   typedef typename RhsStlContainer::value_type Second;
4126   const RhsStlContainer& rhs_stl_container =
4127       RhsView::ConstReference(rhs_container);
4128
4129   // Create a matcher for each element in rhs_container.
4130   ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4131   for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4132        it != rhs_stl_container.end(); ++it) {
4133     matchers.push_back(
4134         internal::MatcherBindSecond(tuple2_matcher, *it));
4135   }
4136
4137   // Delegate the work to UnorderedElementsAreArray().
4138   return UnorderedElementsAreArray(matchers);
4139 }
4140
4141 #if GTEST_HAS_STD_INITIALIZER_LIST_
4142
4143 // Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4144 template <typename Tuple2Matcher, typename T>
4145 inline internal::UnorderedElementsAreArrayMatcher<
4146     typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4147 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4148                    std::initializer_list<T> rhs) {
4149   return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4150 }
4151
4152 #endif  // GTEST_HAS_STD_INITIALIZER_LIST_
4153
4154 // Matches an STL-style container or a native array that contains at
4155 // least one element matching the given value or matcher.
4156 //
4157 // Examples:
4158 //   ::std::set<int> page_ids;
4159 //   page_ids.insert(3);
4160 //   page_ids.insert(1);
4161 //   EXPECT_THAT(page_ids, Contains(1));
4162 //   EXPECT_THAT(page_ids, Contains(Gt(2)));
4163 //   EXPECT_THAT(page_ids, Not(Contains(4)));
4164 //
4165 //   ::std::map<int, size_t> page_lengths;
4166 //   page_lengths[1] = 100;
4167 //   EXPECT_THAT(page_lengths,
4168 //               Contains(::std::pair<const int, size_t>(1, 100)));
4169 //
4170 //   const char* user_ids[] = { "joe", "mike", "tom" };
4171 //   EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4172 template <typename M>
4173 inline internal::ContainsMatcher<M> Contains(M matcher) {
4174   return internal::ContainsMatcher<M>(matcher);
4175 }
4176
4177 // Matches an STL-style container or a native array that contains only
4178 // elements matching the given value or matcher.
4179 //
4180 // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4181 // the messages are different.
4182 //
4183 // Examples:
4184 //   ::std::set<int> page_ids;
4185 //   // Each(m) matches an empty container, regardless of what m is.
4186 //   EXPECT_THAT(page_ids, Each(Eq(1)));
4187 //   EXPECT_THAT(page_ids, Each(Eq(77)));
4188 //
4189 //   page_ids.insert(3);
4190 //   EXPECT_THAT(page_ids, Each(Gt(0)));
4191 //   EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4192 //   page_ids.insert(1);
4193 //   EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4194 //
4195 //   ::std::map<int, size_t> page_lengths;
4196 //   page_lengths[1] = 100;
4197 //   page_lengths[2] = 200;
4198 //   page_lengths[3] = 300;
4199 //   EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4200 //   EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4201 //
4202 //   const char* user_ids[] = { "joe", "mike", "tom" };
4203 //   EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4204 template <typename M>
4205 inline internal::EachMatcher<M> Each(M matcher) {
4206   return internal::EachMatcher<M>(matcher);
4207 }
4208
4209 // Key(inner_matcher) matches an std::pair whose 'first' field matches
4210 // inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
4211 // std::map that contains at least one element whose key is >= 5.
4212 template <typename M>
4213 inline internal::KeyMatcher<M> Key(M inner_matcher) {
4214   return internal::KeyMatcher<M>(inner_matcher);
4215 }
4216
4217 // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4218 // matches first_matcher and whose 'second' field matches second_matcher.  For
4219 // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4220 // to match a std::map<int, string> that contains exactly one element whose key
4221 // is >= 5 and whose value equals "foo".
4222 template <typename FirstMatcher, typename SecondMatcher>
4223 inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4224 Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4225   return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4226       first_matcher, second_matcher);
4227 }
4228
4229 // Returns a predicate that is satisfied by anything that matches the
4230 // given matcher.
4231 template <typename M>
4232 inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4233   return internal::MatcherAsPredicate<M>(matcher);
4234 }
4235
4236 // Returns true iff the value matches the matcher.
4237 template <typename T, typename M>
4238 inline bool Value(const T& value, M matcher) {
4239   return testing::Matches(matcher)(value);
4240 }
4241
4242 // Matches the value against the given matcher and explains the match
4243 // result to listener.
4244 template <typename T, typename M>
4245 inline bool ExplainMatchResult(
4246     M matcher, const T& value, MatchResultListener* listener) {
4247   return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4248 }
4249
4250 #if GTEST_LANG_CXX11
4251 // Define variadic matcher versions. They are overloaded in
4252 // gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4253 template <typename... Args>
4254 inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4255   return internal::AllOfMatcher<Args...>(matchers...);
4256 }
4257
4258 template <typename... Args>
4259 inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4260   return internal::AnyOfMatcher<Args...>(matchers...);
4261 }
4262
4263 #endif  // GTEST_LANG_CXX11
4264
4265 // AllArgs(m) is a synonym of m.  This is useful in
4266 //
4267 //   EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4268 //
4269 // which is easier to read than
4270 //
4271 //   EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4272 template <typename InnerMatcher>
4273 inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4274
4275 // These macros allow using matchers to check values in Google Test
4276 // tests.  ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4277 // succeed iff the value matches the matcher.  If the assertion fails,
4278 // the value and the description of the matcher will be printed.
4279 #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4280     ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4281 #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4282     ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4283
4284 }  // namespace testing
4285
4286 #endif  // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
4287