Generate gromacs.7 from the wrapper binary
[alexxy/gromacs.git] / src / external / gmock-1.7.0 / 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_LANG_CXX11
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(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(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(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(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(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     using ::std::tr1::get;
710     return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
711         && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
712   }
713
714   // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
715   // describes failures in matching the first N fields of matchers
716   // against the first N fields of values.  If there is no failure,
717   // nothing will be streamed to os.
718   template <typename MatcherTuple, typename ValueTuple>
719   static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
720                                      const ValueTuple& values,
721                                      ::std::ostream* os) {
722     using ::std::tr1::tuple_element;
723     using ::std::tr1::get;
724
725     // First, describes failures in the first N - 1 fields.
726     TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
727
728     // Then describes the failure (if any) in the (N - 1)-th (0-based)
729     // field.
730     typename tuple_element<N - 1, MatcherTuple>::type matcher =
731         get<N - 1>(matchers);
732     typedef typename tuple_element<N - 1, ValueTuple>::type Value;
733     Value value = get<N - 1>(values);
734     StringMatchResultListener listener;
735     if (!matcher.MatchAndExplain(value, &listener)) {
736       // TODO(wan): include in the message the name of the parameter
737       // as used in MOCK_METHOD*() when possible.
738       *os << "  Expected arg #" << N - 1 << ": ";
739       get<N - 1>(matchers).DescribeTo(os);
740       *os << "\n           Actual: ";
741       // We remove the reference in type Value to prevent the
742       // universal printer from printing the address of value, which
743       // isn't interesting to the user most of the time.  The
744       // matcher's MatchAndExplain() method handles the case when
745       // the address is interesting.
746       internal::UniversalPrint(value, os);
747       PrintIfNotEmpty(listener.str(), os);
748       *os << "\n";
749     }
750   }
751 };
752
753 // The base case.
754 template <>
755 class TuplePrefix<0> {
756  public:
757   template <typename MatcherTuple, typename ValueTuple>
758   static bool Matches(const MatcherTuple& /* matcher_tuple */,
759                       const ValueTuple& /* value_tuple */) {
760     return true;
761   }
762
763   template <typename MatcherTuple, typename ValueTuple>
764   static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
765                                      const ValueTuple& /* values */,
766                                      ::std::ostream* /* os */) {}
767 };
768
769 // TupleMatches(matcher_tuple, value_tuple) returns true iff all
770 // matchers in matcher_tuple match the corresponding fields in
771 // value_tuple.  It is a compiler error if matcher_tuple and
772 // value_tuple have different number of fields or incompatible field
773 // types.
774 template <typename MatcherTuple, typename ValueTuple>
775 bool TupleMatches(const MatcherTuple& matcher_tuple,
776                   const ValueTuple& value_tuple) {
777   using ::std::tr1::tuple_size;
778   // Makes sure that matcher_tuple and value_tuple have the same
779   // number of fields.
780   GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
781                         tuple_size<ValueTuple>::value,
782                         matcher_and_value_have_different_numbers_of_fields);
783   return TuplePrefix<tuple_size<ValueTuple>::value>::
784       Matches(matcher_tuple, value_tuple);
785 }
786
787 // Describes failures in matching matchers against values.  If there
788 // is no failure, nothing will be streamed to os.
789 template <typename MatcherTuple, typename ValueTuple>
790 void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
791                                 const ValueTuple& values,
792                                 ::std::ostream* os) {
793   using ::std::tr1::tuple_size;
794   TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
795       matchers, values, os);
796 }
797
798 // TransformTupleValues and its helper.
799 //
800 // TransformTupleValuesHelper hides the internal machinery that
801 // TransformTupleValues uses to implement a tuple traversal.
802 template <typename Tuple, typename Func, typename OutIter>
803 class TransformTupleValuesHelper {
804  private:
805   typedef typename ::std::tr1::tuple_size<Tuple> TupleSize;
806
807  public:
808   // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
809   // Returns the final value of 'out' in case the caller needs it.
810   static OutIter Run(Func f, const Tuple& t, OutIter out) {
811     return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
812   }
813
814  private:
815   template <typename Tup, size_t kRemainingSize>
816   struct IterateOverTuple {
817     OutIter operator() (Func f, const Tup& t, OutIter out) const {
818       *out++ = f(::std::tr1::get<TupleSize::value - kRemainingSize>(t));
819       return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
820     }
821   };
822   template <typename Tup>
823   struct IterateOverTuple<Tup, 0> {
824     OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
825       return out;
826     }
827   };
828 };
829
830 // Successively invokes 'f(element)' on each element of the tuple 't',
831 // appending each result to the 'out' iterator. Returns the final value
832 // of 'out'.
833 template <typename Tuple, typename Func, typename OutIter>
834 OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
835   return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
836 }
837
838 // Implements A<T>().
839 template <typename T>
840 class AnyMatcherImpl : public MatcherInterface<T> {
841  public:
842   virtual bool MatchAndExplain(
843       T /* x */, MatchResultListener* /* listener */) const { return true; }
844   virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
845   virtual void DescribeNegationTo(::std::ostream* os) const {
846     // This is mostly for completeness' safe, as it's not very useful
847     // to write Not(A<bool>()).  However we cannot completely rule out
848     // such a possibility, and it doesn't hurt to be prepared.
849     *os << "never matches";
850   }
851 };
852
853 // Implements _, a matcher that matches any value of any
854 // type.  This is a polymorphic matcher, so we need a template type
855 // conversion operator to make it appearing as a Matcher<T> for any
856 // type T.
857 class AnythingMatcher {
858  public:
859   template <typename T>
860   operator Matcher<T>() const { return A<T>(); }
861 };
862
863 // Implements a matcher that compares a given value with a
864 // pre-supplied value using one of the ==, <=, <, etc, operators.  The
865 // two values being compared don't have to have the same type.
866 //
867 // The matcher defined here is polymorphic (for example, Eq(5) can be
868 // used to match an int, a short, a double, etc).  Therefore we use
869 // a template type conversion operator in the implementation.
870 //
871 // We define this as a macro in order to eliminate duplicated source
872 // code.
873 //
874 // The following template definition assumes that the Rhs parameter is
875 // a "bare" type (i.e. neither 'const T' nor 'T&').
876 #define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
877     name, op, relation, negated_relation) \
878   template <typename Rhs> class name##Matcher { \
879    public: \
880     explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
881     template <typename Lhs> \
882     operator Matcher<Lhs>() const { \
883       return MakeMatcher(new Impl<Lhs>(rhs_)); \
884     } \
885    private: \
886     template <typename Lhs> \
887     class Impl : public MatcherInterface<Lhs> { \
888      public: \
889       explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
890       virtual bool MatchAndExplain(\
891           Lhs lhs, MatchResultListener* /* listener */) const { \
892         return lhs op rhs_; \
893       } \
894       virtual void DescribeTo(::std::ostream* os) const { \
895         *os << relation  " "; \
896         UniversalPrint(rhs_, os); \
897       } \
898       virtual void DescribeNegationTo(::std::ostream* os) const { \
899         *os << negated_relation  " "; \
900         UniversalPrint(rhs_, os); \
901       } \
902      private: \
903       Rhs rhs_; \
904       GTEST_DISALLOW_ASSIGN_(Impl); \
905     }; \
906     Rhs rhs_; \
907     GTEST_DISALLOW_ASSIGN_(name##Matcher); \
908   }
909
910 // Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
911 // respectively.
912 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
913 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
914 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
915 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
916 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
917 GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
918
919 #undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
920
921 // Implements the polymorphic IsNull() matcher, which matches any raw or smart
922 // pointer that is NULL.
923 class IsNullMatcher {
924  public:
925   template <typename Pointer>
926   bool MatchAndExplain(const Pointer& p,
927                        MatchResultListener* /* listener */) const {
928     return GetRawPointer(p) == NULL;
929   }
930
931   void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
932   void DescribeNegationTo(::std::ostream* os) const {
933     *os << "isn't NULL";
934   }
935 };
936
937 // Implements the polymorphic NotNull() matcher, which matches any raw or smart
938 // pointer that is not NULL.
939 class NotNullMatcher {
940  public:
941   template <typename Pointer>
942   bool MatchAndExplain(const Pointer& p,
943                        MatchResultListener* /* listener */) const {
944     return GetRawPointer(p) != NULL;
945   }
946
947   void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
948   void DescribeNegationTo(::std::ostream* os) const {
949     *os << "is NULL";
950   }
951 };
952
953 // Ref(variable) matches any argument that is a reference to
954 // 'variable'.  This matcher is polymorphic as it can match any
955 // super type of the type of 'variable'.
956 //
957 // The RefMatcher template class implements Ref(variable).  It can
958 // only be instantiated with a reference type.  This prevents a user
959 // from mistakenly using Ref(x) to match a non-reference function
960 // argument.  For example, the following will righteously cause a
961 // compiler error:
962 //
963 //   int n;
964 //   Matcher<int> m1 = Ref(n);   // This won't compile.
965 //   Matcher<int&> m2 = Ref(n);  // This will compile.
966 template <typename T>
967 class RefMatcher;
968
969 template <typename T>
970 class RefMatcher<T&> {
971   // Google Mock is a generic framework and thus needs to support
972   // mocking any function types, including those that take non-const
973   // reference arguments.  Therefore the template parameter T (and
974   // Super below) can be instantiated to either a const type or a
975   // non-const type.
976  public:
977   // RefMatcher() takes a T& instead of const T&, as we want the
978   // compiler to catch using Ref(const_value) as a matcher for a
979   // non-const reference.
980   explicit RefMatcher(T& x) : object_(x) {}  // NOLINT
981
982   template <typename Super>
983   operator Matcher<Super&>() const {
984     // By passing object_ (type T&) to Impl(), which expects a Super&,
985     // we make sure that Super is a super type of T.  In particular,
986     // this catches using Ref(const_value) as a matcher for a
987     // non-const reference, as you cannot implicitly convert a const
988     // reference to a non-const reference.
989     return MakeMatcher(new Impl<Super>(object_));
990   }
991
992  private:
993   template <typename Super>
994   class Impl : public MatcherInterface<Super&> {
995    public:
996     explicit Impl(Super& x) : object_(x) {}  // NOLINT
997
998     // MatchAndExplain() takes a Super& (as opposed to const Super&)
999     // in order to match the interface MatcherInterface<Super&>.
1000     virtual bool MatchAndExplain(
1001         Super& x, MatchResultListener* listener) const {
1002       *listener << "which is located @" << static_cast<const void*>(&x);
1003       return &x == &object_;
1004     }
1005
1006     virtual void DescribeTo(::std::ostream* os) const {
1007       *os << "references the variable ";
1008       UniversalPrinter<Super&>::Print(object_, os);
1009     }
1010
1011     virtual void DescribeNegationTo(::std::ostream* os) const {
1012       *os << "does not reference the variable ";
1013       UniversalPrinter<Super&>::Print(object_, os);
1014     }
1015
1016    private:
1017     const Super& object_;
1018
1019     GTEST_DISALLOW_ASSIGN_(Impl);
1020   };
1021
1022   T& object_;
1023
1024   GTEST_DISALLOW_ASSIGN_(RefMatcher);
1025 };
1026
1027 // Polymorphic helper functions for narrow and wide string matchers.
1028 inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1029   return String::CaseInsensitiveCStringEquals(lhs, rhs);
1030 }
1031
1032 inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1033                                          const wchar_t* rhs) {
1034   return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1035 }
1036
1037 // String comparison for narrow or wide strings that can have embedded NUL
1038 // characters.
1039 template <typename StringType>
1040 bool CaseInsensitiveStringEquals(const StringType& s1,
1041                                  const StringType& s2) {
1042   // Are the heads equal?
1043   if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1044     return false;
1045   }
1046
1047   // Skip the equal heads.
1048   const typename StringType::value_type nul = 0;
1049   const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1050
1051   // Are we at the end of either s1 or s2?
1052   if (i1 == StringType::npos || i2 == StringType::npos) {
1053     return i1 == i2;
1054   }
1055
1056   // Are the tails equal?
1057   return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1058 }
1059
1060 // String matchers.
1061
1062 // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1063 template <typename StringType>
1064 class StrEqualityMatcher {
1065  public:
1066   StrEqualityMatcher(const StringType& str, bool expect_eq,
1067                      bool case_sensitive)
1068       : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1069
1070   // Accepts pointer types, particularly:
1071   //   const char*
1072   //   char*
1073   //   const wchar_t*
1074   //   wchar_t*
1075   template <typename CharType>
1076   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1077     if (s == NULL) {
1078       return !expect_eq_;
1079     }
1080     return MatchAndExplain(StringType(s), listener);
1081   }
1082
1083   // Matches anything that can convert to StringType.
1084   //
1085   // This is a template, not just a plain function with const StringType&,
1086   // because StringPiece has some interfering non-explicit constructors.
1087   template <typename MatcheeStringType>
1088   bool MatchAndExplain(const MatcheeStringType& s,
1089                        MatchResultListener* /* listener */) const {
1090     const StringType& s2(s);
1091     const bool eq = case_sensitive_ ? s2 == string_ :
1092         CaseInsensitiveStringEquals(s2, string_);
1093     return expect_eq_ == eq;
1094   }
1095
1096   void DescribeTo(::std::ostream* os) const {
1097     DescribeToHelper(expect_eq_, os);
1098   }
1099
1100   void DescribeNegationTo(::std::ostream* os) const {
1101     DescribeToHelper(!expect_eq_, os);
1102   }
1103
1104  private:
1105   void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
1106     *os << (expect_eq ? "is " : "isn't ");
1107     *os << "equal to ";
1108     if (!case_sensitive_) {
1109       *os << "(ignoring case) ";
1110     }
1111     UniversalPrint(string_, os);
1112   }
1113
1114   const StringType string_;
1115   const bool expect_eq_;
1116   const bool case_sensitive_;
1117
1118   GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
1119 };
1120
1121 // Implements the polymorphic HasSubstr(substring) matcher, which
1122 // can be used as a Matcher<T> as long as T can be converted to a
1123 // string.
1124 template <typename StringType>
1125 class HasSubstrMatcher {
1126  public:
1127   explicit HasSubstrMatcher(const StringType& substring)
1128       : substring_(substring) {}
1129
1130   // Accepts pointer types, particularly:
1131   //   const char*
1132   //   char*
1133   //   const wchar_t*
1134   //   wchar_t*
1135   template <typename CharType>
1136   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1137     return s != NULL && MatchAndExplain(StringType(s), listener);
1138   }
1139
1140   // Matches anything that can convert to StringType.
1141   //
1142   // This is a template, not just a plain function with const StringType&,
1143   // because StringPiece has some interfering non-explicit constructors.
1144   template <typename MatcheeStringType>
1145   bool MatchAndExplain(const MatcheeStringType& s,
1146                        MatchResultListener* /* listener */) const {
1147     const StringType& s2(s);
1148     return s2.find(substring_) != StringType::npos;
1149   }
1150
1151   // Describes what this matcher matches.
1152   void DescribeTo(::std::ostream* os) const {
1153     *os << "has substring ";
1154     UniversalPrint(substring_, os);
1155   }
1156
1157   void DescribeNegationTo(::std::ostream* os) const {
1158     *os << "has no substring ";
1159     UniversalPrint(substring_, os);
1160   }
1161
1162  private:
1163   const StringType substring_;
1164
1165   GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
1166 };
1167
1168 // Implements the polymorphic StartsWith(substring) matcher, which
1169 // can be used as a Matcher<T> as long as T can be converted to a
1170 // string.
1171 template <typename StringType>
1172 class StartsWithMatcher {
1173  public:
1174   explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1175   }
1176
1177   // Accepts pointer types, particularly:
1178   //   const char*
1179   //   char*
1180   //   const wchar_t*
1181   //   wchar_t*
1182   template <typename CharType>
1183   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1184     return s != NULL && MatchAndExplain(StringType(s), listener);
1185   }
1186
1187   // Matches anything that can convert to StringType.
1188   //
1189   // This is a template, not just a plain function with const StringType&,
1190   // because StringPiece has some interfering non-explicit constructors.
1191   template <typename MatcheeStringType>
1192   bool MatchAndExplain(const MatcheeStringType& s,
1193                        MatchResultListener* /* listener */) const {
1194     const StringType& s2(s);
1195     return s2.length() >= prefix_.length() &&
1196         s2.substr(0, prefix_.length()) == prefix_;
1197   }
1198
1199   void DescribeTo(::std::ostream* os) const {
1200     *os << "starts with ";
1201     UniversalPrint(prefix_, os);
1202   }
1203
1204   void DescribeNegationTo(::std::ostream* os) const {
1205     *os << "doesn't start with ";
1206     UniversalPrint(prefix_, os);
1207   }
1208
1209  private:
1210   const StringType prefix_;
1211
1212   GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
1213 };
1214
1215 // Implements the polymorphic EndsWith(substring) matcher, which
1216 // can be used as a Matcher<T> as long as T can be converted to a
1217 // string.
1218 template <typename StringType>
1219 class EndsWithMatcher {
1220  public:
1221   explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1222
1223   // Accepts pointer types, particularly:
1224   //   const char*
1225   //   char*
1226   //   const wchar_t*
1227   //   wchar_t*
1228   template <typename CharType>
1229   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1230     return s != NULL && MatchAndExplain(StringType(s), listener);
1231   }
1232
1233   // Matches anything that can convert to StringType.
1234   //
1235   // This is a template, not just a plain function with const StringType&,
1236   // because StringPiece has some interfering non-explicit constructors.
1237   template <typename MatcheeStringType>
1238   bool MatchAndExplain(const MatcheeStringType& s,
1239                        MatchResultListener* /* listener */) const {
1240     const StringType& s2(s);
1241     return s2.length() >= suffix_.length() &&
1242         s2.substr(s2.length() - suffix_.length()) == suffix_;
1243   }
1244
1245   void DescribeTo(::std::ostream* os) const {
1246     *os << "ends with ";
1247     UniversalPrint(suffix_, os);
1248   }
1249
1250   void DescribeNegationTo(::std::ostream* os) const {
1251     *os << "doesn't end with ";
1252     UniversalPrint(suffix_, os);
1253   }
1254
1255  private:
1256   const StringType suffix_;
1257
1258   GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
1259 };
1260
1261 // Implements polymorphic matchers MatchesRegex(regex) and
1262 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
1263 // T can be converted to a string.
1264 class MatchesRegexMatcher {
1265  public:
1266   MatchesRegexMatcher(const RE* regex, bool full_match)
1267       : regex_(regex), full_match_(full_match) {}
1268
1269   // Accepts pointer types, particularly:
1270   //   const char*
1271   //   char*
1272   //   const wchar_t*
1273   //   wchar_t*
1274   template <typename CharType>
1275   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1276     return s != NULL && MatchAndExplain(internal::string(s), listener);
1277   }
1278
1279   // Matches anything that can convert to internal::string.
1280   //
1281   // This is a template, not just a plain function with const internal::string&,
1282   // because StringPiece has some interfering non-explicit constructors.
1283   template <class MatcheeStringType>
1284   bool MatchAndExplain(const MatcheeStringType& s,
1285                        MatchResultListener* /* listener */) const {
1286     const internal::string& s2(s);
1287     return full_match_ ? RE::FullMatch(s2, *regex_) :
1288         RE::PartialMatch(s2, *regex_);
1289   }
1290
1291   void DescribeTo(::std::ostream* os) const {
1292     *os << (full_match_ ? "matches" : "contains")
1293         << " regular expression ";
1294     UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1295   }
1296
1297   void DescribeNegationTo(::std::ostream* os) const {
1298     *os << "doesn't " << (full_match_ ? "match" : "contain")
1299         << " regular expression ";
1300     UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1301   }
1302
1303  private:
1304   const internal::linked_ptr<const RE> regex_;
1305   const bool full_match_;
1306
1307   GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
1308 };
1309
1310 // Implements a matcher that compares the two fields of a 2-tuple
1311 // using one of the ==, <=, <, etc, operators.  The two fields being
1312 // compared don't have to have the same type.
1313 //
1314 // The matcher defined here is polymorphic (for example, Eq() can be
1315 // used to match a tuple<int, short>, a tuple<const long&, double>,
1316 // etc).  Therefore we use a template type conversion operator in the
1317 // implementation.
1318 //
1319 // We define this as a macro in order to eliminate duplicated source
1320 // code.
1321 #define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
1322   class name##2Matcher { \
1323    public: \
1324     template <typename T1, typename T2> \
1325     operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
1326       return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
1327     } \
1328     template <typename T1, typename T2> \
1329     operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
1330       return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
1331     } \
1332    private: \
1333     template <typename Tuple> \
1334     class Impl : public MatcherInterface<Tuple> { \
1335      public: \
1336       virtual bool MatchAndExplain( \
1337           Tuple args, \
1338           MatchResultListener* /* listener */) const { \
1339         return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1340       } \
1341       virtual void DescribeTo(::std::ostream* os) const { \
1342         *os << "are " relation;                                 \
1343       } \
1344       virtual void DescribeNegationTo(::std::ostream* os) const { \
1345         *os << "aren't " relation; \
1346       } \
1347     }; \
1348   }
1349
1350 // Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
1351 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1352 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1353     Ge, >=, "a pair where the first >= the second");
1354 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1355     Gt, >, "a pair where the first > the second");
1356 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1357     Le, <=, "a pair where the first <= the second");
1358 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1359     Lt, <, "a pair where the first < the second");
1360 GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
1361
1362 #undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
1363
1364 // Implements the Not(...) matcher for a particular argument type T.
1365 // We do not nest it inside the NotMatcher class template, as that
1366 // will prevent different instantiations of NotMatcher from sharing
1367 // the same NotMatcherImpl<T> class.
1368 template <typename T>
1369 class NotMatcherImpl : public MatcherInterface<T> {
1370  public:
1371   explicit NotMatcherImpl(const Matcher<T>& matcher)
1372       : matcher_(matcher) {}
1373
1374   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1375     return !matcher_.MatchAndExplain(x, listener);
1376   }
1377
1378   virtual void DescribeTo(::std::ostream* os) const {
1379     matcher_.DescribeNegationTo(os);
1380   }
1381
1382   virtual void DescribeNegationTo(::std::ostream* os) const {
1383     matcher_.DescribeTo(os);
1384   }
1385
1386  private:
1387   const Matcher<T> matcher_;
1388
1389   GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
1390 };
1391
1392 // Implements the Not(m) matcher, which matches a value that doesn't
1393 // match matcher m.
1394 template <typename InnerMatcher>
1395 class NotMatcher {
1396  public:
1397   explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1398
1399   // This template type conversion operator allows Not(m) to be used
1400   // to match any type m can match.
1401   template <typename T>
1402   operator Matcher<T>() const {
1403     return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
1404   }
1405
1406  private:
1407   InnerMatcher matcher_;
1408
1409   GTEST_DISALLOW_ASSIGN_(NotMatcher);
1410 };
1411
1412 // Implements the AllOf(m1, m2) matcher for a particular argument type
1413 // T. We do not nest it inside the BothOfMatcher class template, as
1414 // that will prevent different instantiations of BothOfMatcher from
1415 // sharing the same BothOfMatcherImpl<T> class.
1416 template <typename T>
1417 class BothOfMatcherImpl : public MatcherInterface<T> {
1418  public:
1419   BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1420       : matcher1_(matcher1), matcher2_(matcher2) {}
1421
1422   virtual void DescribeTo(::std::ostream* os) const {
1423     *os << "(";
1424     matcher1_.DescribeTo(os);
1425     *os << ") and (";
1426     matcher2_.DescribeTo(os);
1427     *os << ")";
1428   }
1429
1430   virtual void DescribeNegationTo(::std::ostream* os) const {
1431     *os << "(";
1432     matcher1_.DescribeNegationTo(os);
1433     *os << ") or (";
1434     matcher2_.DescribeNegationTo(os);
1435     *os << ")";
1436   }
1437
1438   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1439     // If either matcher1_ or matcher2_ doesn't match x, we only need
1440     // to explain why one of them fails.
1441     StringMatchResultListener listener1;
1442     if (!matcher1_.MatchAndExplain(x, &listener1)) {
1443       *listener << listener1.str();
1444       return false;
1445     }
1446
1447     StringMatchResultListener listener2;
1448     if (!matcher2_.MatchAndExplain(x, &listener2)) {
1449       *listener << listener2.str();
1450       return false;
1451     }
1452
1453     // Otherwise we need to explain why *both* of them match.
1454     const internal::string s1 = listener1.str();
1455     const internal::string s2 = listener2.str();
1456
1457     if (s1 == "") {
1458       *listener << s2;
1459     } else {
1460       *listener << s1;
1461       if (s2 != "") {
1462         *listener << ", and " << s2;
1463       }
1464     }
1465     return true;
1466   }
1467
1468  private:
1469   const Matcher<T> matcher1_;
1470   const Matcher<T> matcher2_;
1471
1472   GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
1473 };
1474
1475 #if GTEST_LANG_CXX11
1476 // MatcherList provides mechanisms for storing a variable number of matchers in
1477 // a list structure (ListType) and creating a combining matcher from such a
1478 // list.
1479 // The template is defined recursively using the following template paramters:
1480 //   * kSize is the length of the MatcherList.
1481 //   * Head is the type of the first matcher of the list.
1482 //   * Tail denotes the types of the remaining matchers of the list.
1483 template <int kSize, typename Head, typename... Tail>
1484 struct MatcherList {
1485   typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
1486   typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
1487
1488   // BuildList stores variadic type values in a nested pair structure.
1489   // Example:
1490   // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1491   // the corresponding result of type pair<int, pair<string, float>>.
1492   static ListType BuildList(const Head& matcher, const Tail&... tail) {
1493     return ListType(matcher, MatcherListTail::BuildList(tail...));
1494   }
1495
1496   // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1497   // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1498   // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1499   // constructor taking two Matcher<T>s as input.
1500   template <typename T, template <typename /* T */> class CombiningMatcher>
1501   static Matcher<T> CreateMatcher(const ListType& matchers) {
1502     return Matcher<T>(new CombiningMatcher<T>(
1503         SafeMatcherCast<T>(matchers.first),
1504         MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1505             matchers.second)));
1506   }
1507 };
1508
1509 // The following defines the base case for the recursive definition of
1510 // MatcherList.
1511 template <typename Matcher1, typename Matcher2>
1512 struct MatcherList<2, Matcher1, Matcher2> {
1513   typedef ::std::pair<Matcher1, Matcher2> ListType;
1514
1515   static ListType BuildList(const Matcher1& matcher1,
1516                             const Matcher2& matcher2) {
1517     return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
1518   }
1519
1520   template <typename T, template <typename /* T */> class CombiningMatcher>
1521   static Matcher<T> CreateMatcher(const ListType& matchers) {
1522     return Matcher<T>(new CombiningMatcher<T>(
1523         SafeMatcherCast<T>(matchers.first),
1524         SafeMatcherCast<T>(matchers.second)));
1525   }
1526 };
1527
1528 // VariadicMatcher is used for the variadic implementation of
1529 // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1530 // CombiningMatcher<T> is used to recursively combine the provided matchers
1531 // (of type Args...).
1532 template <template <typename T> class CombiningMatcher, typename... Args>
1533 class VariadicMatcher {
1534  public:
1535   VariadicMatcher(const Args&... matchers)  // NOLINT
1536       : matchers_(MatcherListType::BuildList(matchers...)) {}
1537
1538   // This template type conversion operator allows an
1539   // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1540   // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1541   template <typename T>
1542   operator Matcher<T>() const {
1543     return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1544         matchers_);
1545   }
1546
1547  private:
1548   typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1549
1550   const typename MatcherListType::ListType matchers_;
1551
1552   GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1553 };
1554
1555 template <typename... Args>
1556 using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1557
1558 #endif  // GTEST_LANG_CXX11
1559
1560 // Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1561 // matches a value that matches all of the matchers m_1, ..., and m_n.
1562 template <typename Matcher1, typename Matcher2>
1563 class BothOfMatcher {
1564  public:
1565   BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1566       : matcher1_(matcher1), matcher2_(matcher2) {}
1567
1568   // This template type conversion operator allows a
1569   // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1570   // both Matcher1 and Matcher2 can match.
1571   template <typename T>
1572   operator Matcher<T>() const {
1573     return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1574                                                SafeMatcherCast<T>(matcher2_)));
1575   }
1576
1577  private:
1578   Matcher1 matcher1_;
1579   Matcher2 matcher2_;
1580
1581   GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
1582 };
1583
1584 // Implements the AnyOf(m1, m2) matcher for a particular argument type
1585 // T.  We do not nest it inside the AnyOfMatcher class template, as
1586 // that will prevent different instantiations of AnyOfMatcher from
1587 // sharing the same EitherOfMatcherImpl<T> class.
1588 template <typename T>
1589 class EitherOfMatcherImpl : public MatcherInterface<T> {
1590  public:
1591   EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1592       : matcher1_(matcher1), matcher2_(matcher2) {}
1593
1594   virtual void DescribeTo(::std::ostream* os) const {
1595     *os << "(";
1596     matcher1_.DescribeTo(os);
1597     *os << ") or (";
1598     matcher2_.DescribeTo(os);
1599     *os << ")";
1600   }
1601
1602   virtual void DescribeNegationTo(::std::ostream* os) const {
1603     *os << "(";
1604     matcher1_.DescribeNegationTo(os);
1605     *os << ") and (";
1606     matcher2_.DescribeNegationTo(os);
1607     *os << ")";
1608   }
1609
1610   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1611     // If either matcher1_ or matcher2_ matches x, we just need to
1612     // explain why *one* of them matches.
1613     StringMatchResultListener listener1;
1614     if (matcher1_.MatchAndExplain(x, &listener1)) {
1615       *listener << listener1.str();
1616       return true;
1617     }
1618
1619     StringMatchResultListener listener2;
1620     if (matcher2_.MatchAndExplain(x, &listener2)) {
1621       *listener << listener2.str();
1622       return true;
1623     }
1624
1625     // Otherwise we need to explain why *both* of them fail.
1626     const internal::string s1 = listener1.str();
1627     const internal::string s2 = listener2.str();
1628
1629     if (s1 == "") {
1630       *listener << s2;
1631     } else {
1632       *listener << s1;
1633       if (s2 != "") {
1634         *listener << ", and " << s2;
1635       }
1636     }
1637     return false;
1638   }
1639
1640  private:
1641   const Matcher<T> matcher1_;
1642   const Matcher<T> matcher2_;
1643
1644   GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
1645 };
1646
1647 #if GTEST_LANG_CXX11
1648 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1649 template <typename... Args>
1650 using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1651
1652 #endif  // GTEST_LANG_CXX11
1653
1654 // Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1655 // matches a value that matches at least one of the matchers m_1, ...,
1656 // and m_n.
1657 template <typename Matcher1, typename Matcher2>
1658 class EitherOfMatcher {
1659  public:
1660   EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1661       : matcher1_(matcher1), matcher2_(matcher2) {}
1662
1663   // This template type conversion operator allows a
1664   // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1665   // both Matcher1 and Matcher2 can match.
1666   template <typename T>
1667   operator Matcher<T>() const {
1668     return Matcher<T>(new EitherOfMatcherImpl<T>(
1669         SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
1670   }
1671
1672  private:
1673   Matcher1 matcher1_;
1674   Matcher2 matcher2_;
1675
1676   GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
1677 };
1678
1679 // Used for implementing Truly(pred), which turns a predicate into a
1680 // matcher.
1681 template <typename Predicate>
1682 class TrulyMatcher {
1683  public:
1684   explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1685
1686   // This method template allows Truly(pred) to be used as a matcher
1687   // for type T where T is the argument type of predicate 'pred'.  The
1688   // argument is passed by reference as the predicate may be
1689   // interested in the address of the argument.
1690   template <typename T>
1691   bool MatchAndExplain(T& x,  // NOLINT
1692                        MatchResultListener* /* listener */) const {
1693     // Without the if-statement, MSVC sometimes warns about converting
1694     // a value to bool (warning 4800).
1695     //
1696     // We cannot write 'return !!predicate_(x);' as that doesn't work
1697     // when predicate_(x) returns a class convertible to bool but
1698     // having no operator!().
1699     if (predicate_(x))
1700       return true;
1701     return false;
1702   }
1703
1704   void DescribeTo(::std::ostream* os) const {
1705     *os << "satisfies the given predicate";
1706   }
1707
1708   void DescribeNegationTo(::std::ostream* os) const {
1709     *os << "doesn't satisfy the given predicate";
1710   }
1711
1712  private:
1713   Predicate predicate_;
1714
1715   GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
1716 };
1717
1718 // Used for implementing Matches(matcher), which turns a matcher into
1719 // a predicate.
1720 template <typename M>
1721 class MatcherAsPredicate {
1722  public:
1723   explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1724
1725   // This template operator() allows Matches(m) to be used as a
1726   // predicate on type T where m is a matcher on type T.
1727   //
1728   // The argument x is passed by reference instead of by value, as
1729   // some matcher may be interested in its address (e.g. as in
1730   // Matches(Ref(n))(x)).
1731   template <typename T>
1732   bool operator()(const T& x) const {
1733     // We let matcher_ commit to a particular type here instead of
1734     // when the MatcherAsPredicate object was constructed.  This
1735     // allows us to write Matches(m) where m is a polymorphic matcher
1736     // (e.g. Eq(5)).
1737     //
1738     // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1739     // compile when matcher_ has type Matcher<const T&>; if we write
1740     // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1741     // when matcher_ has type Matcher<T>; if we just write
1742     // matcher_.Matches(x), it won't compile when matcher_ is
1743     // polymorphic, e.g. Eq(5).
1744     //
1745     // MatcherCast<const T&>() is necessary for making the code work
1746     // in all of the above situations.
1747     return MatcherCast<const T&>(matcher_).Matches(x);
1748   }
1749
1750  private:
1751   M matcher_;
1752
1753   GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
1754 };
1755
1756 // For implementing ASSERT_THAT() and EXPECT_THAT().  The template
1757 // argument M must be a type that can be converted to a matcher.
1758 template <typename M>
1759 class PredicateFormatterFromMatcher {
1760  public:
1761   explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1762
1763   // This template () operator allows a PredicateFormatterFromMatcher
1764   // object to act as a predicate-formatter suitable for using with
1765   // Google Test's EXPECT_PRED_FORMAT1() macro.
1766   template <typename T>
1767   AssertionResult operator()(const char* value_text, const T& x) const {
1768     // We convert matcher_ to a Matcher<const T&> *now* instead of
1769     // when the PredicateFormatterFromMatcher object was constructed,
1770     // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1771     // know which type to instantiate it to until we actually see the
1772     // type of x here.
1773     //
1774     // We write SafeMatcherCast<const T&>(matcher_) instead of
1775     // Matcher<const T&>(matcher_), as the latter won't compile when
1776     // matcher_ has type Matcher<T> (e.g. An<int>()).
1777     // We don't write MatcherCast<const T&> either, as that allows
1778     // potentially unsafe downcasting of the matcher argument.
1779     const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
1780     StringMatchResultListener listener;
1781     if (MatchPrintAndExplain(x, matcher, &listener))
1782       return AssertionSuccess();
1783
1784     ::std::stringstream ss;
1785     ss << "Value of: " << value_text << "\n"
1786        << "Expected: ";
1787     matcher.DescribeTo(&ss);
1788     ss << "\n  Actual: " << listener.str();
1789     return AssertionFailure() << ss.str();
1790   }
1791
1792  private:
1793   const M matcher_;
1794
1795   GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
1796 };
1797
1798 // A helper function for converting a matcher to a predicate-formatter
1799 // without the user needing to explicitly write the type.  This is
1800 // used for implementing ASSERT_THAT() and EXPECT_THAT().
1801 template <typename M>
1802 inline PredicateFormatterFromMatcher<M>
1803 MakePredicateFormatterFromMatcher(const M& matcher) {
1804   return PredicateFormatterFromMatcher<M>(matcher);
1805 }
1806
1807 // Implements the polymorphic floating point equality matcher, which matches
1808 // two float values using ULP-based approximation or, optionally, a
1809 // user-specified epsilon.  The template is meant to be instantiated with
1810 // FloatType being either float or double.
1811 template <typename FloatType>
1812 class FloatingEqMatcher {
1813  public:
1814   // Constructor for FloatingEqMatcher.
1815   // The matcher's input will be compared with rhs.  The matcher treats two
1816   // NANs as equal if nan_eq_nan is true.  Otherwise, under IEEE standards,
1817   // equality comparisons between NANs will always return false.  We specify a
1818   // negative max_abs_error_ term to indicate that ULP-based approximation will
1819   // be used for comparison.
1820   FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1821     rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
1822   }
1823
1824   // Constructor that supports a user-specified max_abs_error that will be used
1825   // for comparison instead of ULP-based approximation.  The max absolute
1826   // should be non-negative.
1827   FloatingEqMatcher(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
1828     rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {
1829     GTEST_CHECK_(max_abs_error >= 0)
1830         << ", where max_abs_error is" << max_abs_error;
1831   }
1832
1833   // Implements floating point equality matcher as a Matcher<T>.
1834   template <typename T>
1835   class Impl : public MatcherInterface<T> {
1836    public:
1837     Impl(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
1838       rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {}
1839
1840     virtual bool MatchAndExplain(T value,
1841                                  MatchResultListener* /* listener */) const {
1842       const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1843
1844       // Compares NaNs first, if nan_eq_nan_ is true.
1845       if (lhs.is_nan() || rhs.is_nan()) {
1846         if (lhs.is_nan() && rhs.is_nan()) {
1847           return nan_eq_nan_;
1848         }
1849         // One is nan; the other is not nan.
1850         return false;
1851       }
1852       if (HasMaxAbsError()) {
1853         // We perform an equality check so that inf will match inf, regardless
1854         // of error bounds.  If the result of value - rhs_ would result in
1855         // overflow or if either value is inf, the default result is infinity,
1856         // which should only match if max_abs_error_ is also infinity.
1857         return value == rhs_ || fabs(value - rhs_) <= max_abs_error_;
1858       } else {
1859         return lhs.AlmostEquals(rhs);
1860       }
1861     }
1862
1863     virtual void DescribeTo(::std::ostream* os) const {
1864       // os->precision() returns the previously set precision, which we
1865       // store to restore the ostream to its original configuration
1866       // after outputting.
1867       const ::std::streamsize old_precision = os->precision(
1868           ::std::numeric_limits<FloatType>::digits10 + 2);
1869       if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1870         if (nan_eq_nan_) {
1871           *os << "is NaN";
1872         } else {
1873           *os << "never matches";
1874         }
1875       } else {
1876         *os << "is approximately " << rhs_;
1877         if (HasMaxAbsError()) {
1878           *os << " (absolute error <= " << max_abs_error_ << ")";
1879         }
1880       }
1881       os->precision(old_precision);
1882     }
1883
1884     virtual void DescribeNegationTo(::std::ostream* os) const {
1885       // As before, get original precision.
1886       const ::std::streamsize old_precision = os->precision(
1887           ::std::numeric_limits<FloatType>::digits10 + 2);
1888       if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1889         if (nan_eq_nan_) {
1890           *os << "isn't NaN";
1891         } else {
1892           *os << "is anything";
1893         }
1894       } else {
1895         *os << "isn't approximately " << rhs_;
1896         if (HasMaxAbsError()) {
1897           *os << " (absolute error > " << max_abs_error_ << ")";
1898         }
1899       }
1900       // Restore original precision.
1901       os->precision(old_precision);
1902     }
1903
1904    private:
1905     bool HasMaxAbsError() const {
1906       return max_abs_error_ >= 0;
1907     }
1908
1909     const FloatType rhs_;
1910     const bool nan_eq_nan_;
1911     // max_abs_error will be used for value comparison when >= 0.
1912     const FloatType max_abs_error_;
1913
1914     GTEST_DISALLOW_ASSIGN_(Impl);
1915   };
1916
1917   // The following 3 type conversion operators allow FloatEq(rhs) and
1918   // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1919   // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1920   // (While Google's C++ coding style doesn't allow arguments passed
1921   // by non-const reference, we may see them in code not conforming to
1922   // the style.  Therefore Google Mock needs to support them.)
1923   operator Matcher<FloatType>() const {
1924     return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_, max_abs_error_));
1925   }
1926
1927   operator Matcher<const FloatType&>() const {
1928     return MakeMatcher(
1929         new Impl<const FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
1930   }
1931
1932   operator Matcher<FloatType&>() const {
1933     return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
1934   }
1935
1936  private:
1937   const FloatType rhs_;
1938   const bool nan_eq_nan_;
1939   // max_abs_error will be used for value comparison when >= 0.
1940   const FloatType max_abs_error_;
1941
1942   GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
1943 };
1944
1945 // Implements the Pointee(m) matcher for matching a pointer whose
1946 // pointee matches matcher m.  The pointer can be either raw or smart.
1947 template <typename InnerMatcher>
1948 class PointeeMatcher {
1949  public:
1950   explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1951
1952   // This type conversion operator template allows Pointee(m) to be
1953   // used as a matcher for any pointer type whose pointee type is
1954   // compatible with the inner matcher, where type Pointer can be
1955   // either a raw pointer or a smart pointer.
1956   //
1957   // The reason we do this instead of relying on
1958   // MakePolymorphicMatcher() is that the latter is not flexible
1959   // enough for implementing the DescribeTo() method of Pointee().
1960   template <typename Pointer>
1961   operator Matcher<Pointer>() const {
1962     return MakeMatcher(new Impl<Pointer>(matcher_));
1963   }
1964
1965  private:
1966   // The monomorphic implementation that works for a particular pointer type.
1967   template <typename Pointer>
1968   class Impl : public MatcherInterface<Pointer> {
1969    public:
1970     typedef typename PointeeOf<GTEST_REMOVE_CONST_(  // NOLINT
1971         GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
1972
1973     explicit Impl(const InnerMatcher& matcher)
1974         : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1975
1976     virtual void DescribeTo(::std::ostream* os) const {
1977       *os << "points to a value that ";
1978       matcher_.DescribeTo(os);
1979     }
1980
1981     virtual void DescribeNegationTo(::std::ostream* os) const {
1982       *os << "does not point to a value that ";
1983       matcher_.DescribeTo(os);
1984     }
1985
1986     virtual bool MatchAndExplain(Pointer pointer,
1987                                  MatchResultListener* listener) const {
1988       if (GetRawPointer(pointer) == NULL)
1989         return false;
1990
1991       *listener << "which points to ";
1992       return MatchPrintAndExplain(*pointer, matcher_, listener);
1993     }
1994
1995    private:
1996     const Matcher<const Pointee&> matcher_;
1997
1998     GTEST_DISALLOW_ASSIGN_(Impl);
1999   };
2000
2001   const InnerMatcher matcher_;
2002
2003   GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
2004 };
2005
2006 // Implements the Field() matcher for matching a field (i.e. member
2007 // variable) of an object.
2008 template <typename Class, typename FieldType>
2009 class FieldMatcher {
2010  public:
2011   FieldMatcher(FieldType Class::*field,
2012                const Matcher<const FieldType&>& matcher)
2013       : field_(field), matcher_(matcher) {}
2014
2015   void DescribeTo(::std::ostream* os) const {
2016     *os << "is an object whose given field ";
2017     matcher_.DescribeTo(os);
2018   }
2019
2020   void DescribeNegationTo(::std::ostream* os) const {
2021     *os << "is an object whose given field ";
2022     matcher_.DescribeNegationTo(os);
2023   }
2024
2025   template <typename T>
2026   bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2027     return MatchAndExplainImpl(
2028         typename ::testing::internal::
2029             is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2030         value, listener);
2031   }
2032
2033  private:
2034   // The first argument of MatchAndExplainImpl() is needed to help
2035   // Symbian's C++ compiler choose which overload to use.  Its type is
2036   // true_type iff the Field() matcher is used to match a pointer.
2037   bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2038                            MatchResultListener* listener) const {
2039     *listener << "whose given field is ";
2040     return MatchPrintAndExplain(obj.*field_, matcher_, listener);
2041   }
2042
2043   bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2044                            MatchResultListener* listener) const {
2045     if (p == NULL)
2046       return false;
2047
2048     *listener << "which points to an object ";
2049     // Since *p has a field, it must be a class/struct/union type and
2050     // thus cannot be a pointer.  Therefore we pass false_type() as
2051     // the first argument.
2052     return MatchAndExplainImpl(false_type(), *p, listener);
2053   }
2054
2055   const FieldType Class::*field_;
2056   const Matcher<const FieldType&> matcher_;
2057
2058   GTEST_DISALLOW_ASSIGN_(FieldMatcher);
2059 };
2060
2061 // Implements the Property() matcher for matching a property
2062 // (i.e. return value of a getter method) of an object.
2063 template <typename Class, typename PropertyType>
2064 class PropertyMatcher {
2065  public:
2066   // The property may have a reference type, so 'const PropertyType&'
2067   // may cause double references and fail to compile.  That's why we
2068   // need GTEST_REFERENCE_TO_CONST, which works regardless of
2069   // PropertyType being a reference or not.
2070   typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
2071
2072   PropertyMatcher(PropertyType (Class::*property)() const,
2073                   const Matcher<RefToConstProperty>& matcher)
2074       : property_(property), matcher_(matcher) {}
2075
2076   void DescribeTo(::std::ostream* os) const {
2077     *os << "is an object whose given property ";
2078     matcher_.DescribeTo(os);
2079   }
2080
2081   void DescribeNegationTo(::std::ostream* os) const {
2082     *os << "is an object whose given property ";
2083     matcher_.DescribeNegationTo(os);
2084   }
2085
2086   template <typename T>
2087   bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2088     return MatchAndExplainImpl(
2089         typename ::testing::internal::
2090             is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2091         value, listener);
2092   }
2093
2094  private:
2095   // The first argument of MatchAndExplainImpl() is needed to help
2096   // Symbian's C++ compiler choose which overload to use.  Its type is
2097   // true_type iff the Property() matcher is used to match a pointer.
2098   bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2099                            MatchResultListener* listener) const {
2100     *listener << "whose given property is ";
2101     // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2102     // which takes a non-const reference as argument.
2103     RefToConstProperty result = (obj.*property_)();
2104     return MatchPrintAndExplain(result, matcher_, listener);
2105   }
2106
2107   bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2108                            MatchResultListener* listener) const {
2109     if (p == NULL)
2110       return false;
2111
2112     *listener << "which points to an object ";
2113     // Since *p has a property method, it must be a class/struct/union
2114     // type and thus cannot be a pointer.  Therefore we pass
2115     // false_type() as the first argument.
2116     return MatchAndExplainImpl(false_type(), *p, listener);
2117   }
2118
2119   PropertyType (Class::*property_)() const;
2120   const Matcher<RefToConstProperty> matcher_;
2121
2122   GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
2123 };
2124
2125 // Type traits specifying various features of different functors for ResultOf.
2126 // The default template specifies features for functor objects.
2127 // Functor classes have to typedef argument_type and result_type
2128 // to be compatible with ResultOf.
2129 template <typename Functor>
2130 struct CallableTraits {
2131   typedef typename Functor::result_type ResultType;
2132   typedef Functor StorageType;
2133
2134   static void CheckIsValid(Functor /* functor */) {}
2135   template <typename T>
2136   static ResultType Invoke(Functor f, T arg) { return f(arg); }
2137 };
2138
2139 // Specialization for function pointers.
2140 template <typename ArgType, typename ResType>
2141 struct CallableTraits<ResType(*)(ArgType)> {
2142   typedef ResType ResultType;
2143   typedef ResType(*StorageType)(ArgType);
2144
2145   static void CheckIsValid(ResType(*f)(ArgType)) {
2146     GTEST_CHECK_(f != NULL)
2147         << "NULL function pointer is passed into ResultOf().";
2148   }
2149   template <typename T>
2150   static ResType Invoke(ResType(*f)(ArgType), T arg) {
2151     return (*f)(arg);
2152   }
2153 };
2154
2155 // Implements the ResultOf() matcher for matching a return value of a
2156 // unary function of an object.
2157 template <typename Callable>
2158 class ResultOfMatcher {
2159  public:
2160   typedef typename CallableTraits<Callable>::ResultType ResultType;
2161
2162   ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2163       : callable_(callable), matcher_(matcher) {
2164     CallableTraits<Callable>::CheckIsValid(callable_);
2165   }
2166
2167   template <typename T>
2168   operator Matcher<T>() const {
2169     return Matcher<T>(new Impl<T>(callable_, matcher_));
2170   }
2171
2172  private:
2173   typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2174
2175   template <typename T>
2176   class Impl : public MatcherInterface<T> {
2177    public:
2178     Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2179         : callable_(callable), matcher_(matcher) {}
2180
2181     virtual void DescribeTo(::std::ostream* os) const {
2182       *os << "is mapped by the given callable to a value that ";
2183       matcher_.DescribeTo(os);
2184     }
2185
2186     virtual void DescribeNegationTo(::std::ostream* os) const {
2187       *os << "is mapped by the given callable to a value that ";
2188       matcher_.DescribeNegationTo(os);
2189     }
2190
2191     virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
2192       *listener << "which is mapped by the given callable to ";
2193       // Cannot pass the return value (for example, int) to
2194       // MatchPrintAndExplain, which takes a non-const reference as argument.
2195       ResultType result =
2196           CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2197       return MatchPrintAndExplain(result, matcher_, listener);
2198     }
2199
2200    private:
2201     // Functors often define operator() as non-const method even though
2202     // they are actualy stateless. But we need to use them even when
2203     // 'this' is a const pointer. It's the user's responsibility not to
2204     // use stateful callables with ResultOf(), which does't guarantee
2205     // how many times the callable will be invoked.
2206     mutable CallableStorageType callable_;
2207     const Matcher<ResultType> matcher_;
2208
2209     GTEST_DISALLOW_ASSIGN_(Impl);
2210   };  // class Impl
2211
2212   const CallableStorageType callable_;
2213   const Matcher<ResultType> matcher_;
2214
2215   GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
2216 };
2217
2218 // Implements a matcher that checks the size of an STL-style container.
2219 template <typename SizeMatcher>
2220 class SizeIsMatcher {
2221  public:
2222   explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2223        : size_matcher_(size_matcher) {
2224   }
2225
2226   template <typename Container>
2227   operator Matcher<Container>() const {
2228     return MakeMatcher(new Impl<Container>(size_matcher_));
2229   }
2230
2231   template <typename Container>
2232   class Impl : public MatcherInterface<Container> {
2233    public:
2234     typedef internal::StlContainerView<
2235          GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2236     typedef typename ContainerView::type::size_type SizeType;
2237     explicit Impl(const SizeMatcher& size_matcher)
2238         : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2239
2240     virtual void DescribeTo(::std::ostream* os) const {
2241       *os << "size ";
2242       size_matcher_.DescribeTo(os);
2243     }
2244     virtual void DescribeNegationTo(::std::ostream* os) const {
2245       *os << "size ";
2246       size_matcher_.DescribeNegationTo(os);
2247     }
2248
2249     virtual bool MatchAndExplain(Container container,
2250                                  MatchResultListener* listener) const {
2251       SizeType size = container.size();
2252       StringMatchResultListener size_listener;
2253       const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2254       *listener
2255           << "whose size " << size << (result ? " matches" : " doesn't match");
2256       PrintIfNotEmpty(size_listener.str(), listener->stream());
2257       return result;
2258     }
2259
2260    private:
2261     const Matcher<SizeType> size_matcher_;
2262     GTEST_DISALLOW_ASSIGN_(Impl);
2263   };
2264
2265  private:
2266   const SizeMatcher size_matcher_;
2267   GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2268 };
2269
2270 // Implements an equality matcher for any STL-style container whose elements
2271 // support ==. This matcher is like Eq(), but its failure explanations provide
2272 // more detailed information that is useful when the container is used as a set.
2273 // The failure message reports elements that are in one of the operands but not
2274 // the other. The failure messages do not report duplicate or out-of-order
2275 // elements in the containers (which don't properly matter to sets, but can
2276 // occur if the containers are vectors or lists, for example).
2277 //
2278 // Uses the container's const_iterator, value_type, operator ==,
2279 // begin(), and end().
2280 template <typename Container>
2281 class ContainerEqMatcher {
2282  public:
2283   typedef internal::StlContainerView<Container> View;
2284   typedef typename View::type StlContainer;
2285   typedef typename View::const_reference StlContainerReference;
2286
2287   // We make a copy of rhs in case the elements in it are modified
2288   // after this matcher is created.
2289   explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
2290     // Makes sure the user doesn't instantiate this class template
2291     // with a const or reference type.
2292     (void)testing::StaticAssertTypeEq<Container,
2293         GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
2294   }
2295
2296   void DescribeTo(::std::ostream* os) const {
2297     *os << "equals ";
2298     UniversalPrint(rhs_, os);
2299   }
2300   void DescribeNegationTo(::std::ostream* os) const {
2301     *os << "does not equal ";
2302     UniversalPrint(rhs_, os);
2303   }
2304
2305   template <typename LhsContainer>
2306   bool MatchAndExplain(const LhsContainer& lhs,
2307                        MatchResultListener* listener) const {
2308     // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
2309     // that causes LhsContainer to be a const type sometimes.
2310     typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
2311         LhsView;
2312     typedef typename LhsView::type LhsStlContainer;
2313     StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2314     if (lhs_stl_container == rhs_)
2315       return true;
2316
2317     ::std::ostream* const os = listener->stream();
2318     if (os != NULL) {
2319       // Something is different. Check for extra values first.
2320       bool printed_header = false;
2321       for (typename LhsStlContainer::const_iterator it =
2322                lhs_stl_container.begin();
2323            it != lhs_stl_container.end(); ++it) {
2324         if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2325             rhs_.end()) {
2326           if (printed_header) {
2327             *os << ", ";
2328           } else {
2329             *os << "which has these unexpected elements: ";
2330             printed_header = true;
2331           }
2332           UniversalPrint(*it, os);
2333         }
2334       }
2335
2336       // Now check for missing values.
2337       bool printed_header2 = false;
2338       for (typename StlContainer::const_iterator it = rhs_.begin();
2339            it != rhs_.end(); ++it) {
2340         if (internal::ArrayAwareFind(
2341                 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2342             lhs_stl_container.end()) {
2343           if (printed_header2) {
2344             *os << ", ";
2345           } else {
2346             *os << (printed_header ? ",\nand" : "which")
2347                 << " doesn't have these expected elements: ";
2348             printed_header2 = true;
2349           }
2350           UniversalPrint(*it, os);
2351         }
2352       }
2353     }
2354
2355     return false;
2356   }
2357
2358  private:
2359   const StlContainer rhs_;
2360
2361   GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
2362 };
2363
2364 // A comparator functor that uses the < operator to compare two values.
2365 struct LessComparator {
2366   template <typename T, typename U>
2367   bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2368 };
2369
2370 // Implements WhenSortedBy(comparator, container_matcher).
2371 template <typename Comparator, typename ContainerMatcher>
2372 class WhenSortedByMatcher {
2373  public:
2374   WhenSortedByMatcher(const Comparator& comparator,
2375                       const ContainerMatcher& matcher)
2376       : comparator_(comparator), matcher_(matcher) {}
2377
2378   template <typename LhsContainer>
2379   operator Matcher<LhsContainer>() const {
2380     return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2381   }
2382
2383   template <typename LhsContainer>
2384   class Impl : public MatcherInterface<LhsContainer> {
2385    public:
2386     typedef internal::StlContainerView<
2387          GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2388     typedef typename LhsView::type LhsStlContainer;
2389     typedef typename LhsView::const_reference LhsStlContainerReference;
2390     // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2391     // so that we can match associative containers.
2392     typedef typename RemoveConstFromKey<
2393         typename LhsStlContainer::value_type>::type LhsValue;
2394
2395     Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2396         : comparator_(comparator), matcher_(matcher) {}
2397
2398     virtual void DescribeTo(::std::ostream* os) const {
2399       *os << "(when sorted) ";
2400       matcher_.DescribeTo(os);
2401     }
2402
2403     virtual void DescribeNegationTo(::std::ostream* os) const {
2404       *os << "(when sorted) ";
2405       matcher_.DescribeNegationTo(os);
2406     }
2407
2408     virtual bool MatchAndExplain(LhsContainer lhs,
2409                                  MatchResultListener* listener) const {
2410       LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2411       ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2412                                                lhs_stl_container.end());
2413       ::std::sort(
2414            sorted_container.begin(), sorted_container.end(), comparator_);
2415
2416       if (!listener->IsInterested()) {
2417         // If the listener is not interested, we do not need to
2418         // construct the inner explanation.
2419         return matcher_.Matches(sorted_container);
2420       }
2421
2422       *listener << "which is ";
2423       UniversalPrint(sorted_container, listener->stream());
2424       *listener << " when sorted";
2425
2426       StringMatchResultListener inner_listener;
2427       const bool match = matcher_.MatchAndExplain(sorted_container,
2428                                                   &inner_listener);
2429       PrintIfNotEmpty(inner_listener.str(), listener->stream());
2430       return match;
2431     }
2432
2433    private:
2434     const Comparator comparator_;
2435     const Matcher<const ::std::vector<LhsValue>&> matcher_;
2436
2437     GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2438   };
2439
2440  private:
2441   const Comparator comparator_;
2442   const ContainerMatcher matcher_;
2443
2444   GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2445 };
2446
2447 // Implements Pointwise(tuple_matcher, rhs_container).  tuple_matcher
2448 // must be able to be safely cast to Matcher<tuple<const T1&, const
2449 // T2&> >, where T1 and T2 are the types of elements in the LHS
2450 // container and the RHS container respectively.
2451 template <typename TupleMatcher, typename RhsContainer>
2452 class PointwiseMatcher {
2453  public:
2454   typedef internal::StlContainerView<RhsContainer> RhsView;
2455   typedef typename RhsView::type RhsStlContainer;
2456   typedef typename RhsStlContainer::value_type RhsValue;
2457
2458   // Like ContainerEq, we make a copy of rhs in case the elements in
2459   // it are modified after this matcher is created.
2460   PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2461       : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2462     // Makes sure the user doesn't instantiate this class template
2463     // with a const or reference type.
2464     (void)testing::StaticAssertTypeEq<RhsContainer,
2465         GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2466   }
2467
2468   template <typename LhsContainer>
2469   operator Matcher<LhsContainer>() const {
2470     return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2471   }
2472
2473   template <typename LhsContainer>
2474   class Impl : public MatcherInterface<LhsContainer> {
2475    public:
2476     typedef internal::StlContainerView<
2477          GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2478     typedef typename LhsView::type LhsStlContainer;
2479     typedef typename LhsView::const_reference LhsStlContainerReference;
2480     typedef typename LhsStlContainer::value_type LhsValue;
2481     // We pass the LHS value and the RHS value to the inner matcher by
2482     // reference, as they may be expensive to copy.  We must use tuple
2483     // instead of pair here, as a pair cannot hold references (C++ 98,
2484     // 20.2.2 [lib.pairs]).
2485     typedef ::std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2486
2487     Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2488         // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2489         : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2490           rhs_(rhs) {}
2491
2492     virtual void DescribeTo(::std::ostream* os) const {
2493       *os << "contains " << rhs_.size()
2494           << " values, where each value and its corresponding value in ";
2495       UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2496       *os << " ";
2497       mono_tuple_matcher_.DescribeTo(os);
2498     }
2499     virtual void DescribeNegationTo(::std::ostream* os) const {
2500       *os << "doesn't contain exactly " << rhs_.size()
2501           << " values, or contains a value x at some index i"
2502           << " where x and the i-th value of ";
2503       UniversalPrint(rhs_, os);
2504       *os << " ";
2505       mono_tuple_matcher_.DescribeNegationTo(os);
2506     }
2507
2508     virtual bool MatchAndExplain(LhsContainer lhs,
2509                                  MatchResultListener* listener) const {
2510       LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2511       const size_t actual_size = lhs_stl_container.size();
2512       if (actual_size != rhs_.size()) {
2513         *listener << "which contains " << actual_size << " values";
2514         return false;
2515       }
2516
2517       typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2518       typename RhsStlContainer::const_iterator right = rhs_.begin();
2519       for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2520         const InnerMatcherArg value_pair(*left, *right);
2521
2522         if (listener->IsInterested()) {
2523           StringMatchResultListener inner_listener;
2524           if (!mono_tuple_matcher_.MatchAndExplain(
2525                   value_pair, &inner_listener)) {
2526             *listener << "where the value pair (";
2527             UniversalPrint(*left, listener->stream());
2528             *listener << ", ";
2529             UniversalPrint(*right, listener->stream());
2530             *listener << ") at index #" << i << " don't match";
2531             PrintIfNotEmpty(inner_listener.str(), listener->stream());
2532             return false;
2533           }
2534         } else {
2535           if (!mono_tuple_matcher_.Matches(value_pair))
2536             return false;
2537         }
2538       }
2539
2540       return true;
2541     }
2542
2543    private:
2544     const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2545     const RhsStlContainer rhs_;
2546
2547     GTEST_DISALLOW_ASSIGN_(Impl);
2548   };
2549
2550  private:
2551   const TupleMatcher tuple_matcher_;
2552   const RhsStlContainer rhs_;
2553
2554   GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2555 };
2556
2557 // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
2558 template <typename Container>
2559 class QuantifierMatcherImpl : public MatcherInterface<Container> {
2560  public:
2561   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
2562   typedef StlContainerView<RawContainer> View;
2563   typedef typename View::type StlContainer;
2564   typedef typename View::const_reference StlContainerReference;
2565   typedef typename StlContainer::value_type Element;
2566
2567   template <typename InnerMatcher>
2568   explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
2569       : inner_matcher_(
2570            testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
2571
2572   // Checks whether:
2573   // * All elements in the container match, if all_elements_should_match.
2574   // * Any element in the container matches, if !all_elements_should_match.
2575   bool MatchAndExplainImpl(bool all_elements_should_match,
2576                            Container container,
2577                            MatchResultListener* listener) const {
2578     StlContainerReference stl_container = View::ConstReference(container);
2579     size_t i = 0;
2580     for (typename StlContainer::const_iterator it = stl_container.begin();
2581          it != stl_container.end(); ++it, ++i) {
2582       StringMatchResultListener inner_listener;
2583       const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2584
2585       if (matches != all_elements_should_match) {
2586         *listener << "whose element #" << i
2587                   << (matches ? " matches" : " doesn't match");
2588         PrintIfNotEmpty(inner_listener.str(), listener->stream());
2589         return !all_elements_should_match;
2590       }
2591     }
2592     return all_elements_should_match;
2593   }
2594
2595  protected:
2596   const Matcher<const Element&> inner_matcher_;
2597
2598   GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2599 };
2600
2601 // Implements Contains(element_matcher) for the given argument type Container.
2602 // Symmetric to EachMatcherImpl.
2603 template <typename Container>
2604 class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2605  public:
2606   template <typename InnerMatcher>
2607   explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2608       : QuantifierMatcherImpl<Container>(inner_matcher) {}
2609
2610   // Describes what this matcher does.
2611   virtual void DescribeTo(::std::ostream* os) const {
2612     *os << "contains at least one element that ";
2613     this->inner_matcher_.DescribeTo(os);
2614   }
2615
2616   virtual void DescribeNegationTo(::std::ostream* os) const {
2617     *os << "doesn't contain any element that ";
2618     this->inner_matcher_.DescribeTo(os);
2619   }
2620
2621   virtual bool MatchAndExplain(Container container,
2622                                MatchResultListener* listener) const {
2623     return this->MatchAndExplainImpl(false, container, listener);
2624   }
2625
2626  private:
2627   GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
2628 };
2629
2630 // Implements Each(element_matcher) for the given argument type Container.
2631 // Symmetric to ContainsMatcherImpl.
2632 template <typename Container>
2633 class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2634  public:
2635   template <typename InnerMatcher>
2636   explicit EachMatcherImpl(InnerMatcher inner_matcher)
2637       : QuantifierMatcherImpl<Container>(inner_matcher) {}
2638
2639   // Describes what this matcher does.
2640   virtual void DescribeTo(::std::ostream* os) const {
2641     *os << "only contains elements that ";
2642     this->inner_matcher_.DescribeTo(os);
2643   }
2644
2645   virtual void DescribeNegationTo(::std::ostream* os) const {
2646     *os << "contains some element that ";
2647     this->inner_matcher_.DescribeNegationTo(os);
2648   }
2649
2650   virtual bool MatchAndExplain(Container container,
2651                                MatchResultListener* listener) const {
2652     return this->MatchAndExplainImpl(true, container, listener);
2653   }
2654
2655  private:
2656   GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2657 };
2658
2659 // Implements polymorphic Contains(element_matcher).
2660 template <typename M>
2661 class ContainsMatcher {
2662  public:
2663   explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2664
2665   template <typename Container>
2666   operator Matcher<Container>() const {
2667     return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2668   }
2669
2670  private:
2671   const M inner_matcher_;
2672
2673   GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
2674 };
2675
2676 // Implements polymorphic Each(element_matcher).
2677 template <typename M>
2678 class EachMatcher {
2679  public:
2680   explicit EachMatcher(M m) : inner_matcher_(m) {}
2681
2682   template <typename Container>
2683   operator Matcher<Container>() const {
2684     return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2685   }
2686
2687  private:
2688   const M inner_matcher_;
2689
2690   GTEST_DISALLOW_ASSIGN_(EachMatcher);
2691 };
2692
2693 // Implements Key(inner_matcher) for the given argument pair type.
2694 // Key(inner_matcher) matches an std::pair whose 'first' field matches
2695 // inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
2696 // std::map that contains at least one element whose key is >= 5.
2697 template <typename PairType>
2698 class KeyMatcherImpl : public MatcherInterface<PairType> {
2699  public:
2700   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
2701   typedef typename RawPairType::first_type KeyType;
2702
2703   template <typename InnerMatcher>
2704   explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2705       : inner_matcher_(
2706           testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2707   }
2708
2709   // Returns true iff 'key_value.first' (the key) matches the inner matcher.
2710   virtual bool MatchAndExplain(PairType key_value,
2711                                MatchResultListener* listener) const {
2712     StringMatchResultListener inner_listener;
2713     const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2714                                                       &inner_listener);
2715     const internal::string explanation = inner_listener.str();
2716     if (explanation != "") {
2717       *listener << "whose first field is a value " << explanation;
2718     }
2719     return match;
2720   }
2721
2722   // Describes what this matcher does.
2723   virtual void DescribeTo(::std::ostream* os) const {
2724     *os << "has a key that ";
2725     inner_matcher_.DescribeTo(os);
2726   }
2727
2728   // Describes what the negation of this matcher does.
2729   virtual void DescribeNegationTo(::std::ostream* os) const {
2730     *os << "doesn't have a key that ";
2731     inner_matcher_.DescribeTo(os);
2732   }
2733
2734  private:
2735   const Matcher<const KeyType&> inner_matcher_;
2736
2737   GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
2738 };
2739
2740 // Implements polymorphic Key(matcher_for_key).
2741 template <typename M>
2742 class KeyMatcher {
2743  public:
2744   explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2745
2746   template <typename PairType>
2747   operator Matcher<PairType>() const {
2748     return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2749   }
2750
2751  private:
2752   const M matcher_for_key_;
2753
2754   GTEST_DISALLOW_ASSIGN_(KeyMatcher);
2755 };
2756
2757 // Implements Pair(first_matcher, second_matcher) for the given argument pair
2758 // type with its two matchers. See Pair() function below.
2759 template <typename PairType>
2760 class PairMatcherImpl : public MatcherInterface<PairType> {
2761  public:
2762   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
2763   typedef typename RawPairType::first_type FirstType;
2764   typedef typename RawPairType::second_type SecondType;
2765
2766   template <typename FirstMatcher, typename SecondMatcher>
2767   PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2768       : first_matcher_(
2769             testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2770         second_matcher_(
2771             testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2772   }
2773
2774   // Describes what this matcher does.
2775   virtual void DescribeTo(::std::ostream* os) const {
2776     *os << "has a first field that ";
2777     first_matcher_.DescribeTo(os);
2778     *os << ", and has a second field that ";
2779     second_matcher_.DescribeTo(os);
2780   }
2781
2782   // Describes what the negation of this matcher does.
2783   virtual void DescribeNegationTo(::std::ostream* os) const {
2784     *os << "has a first field that ";
2785     first_matcher_.DescribeNegationTo(os);
2786     *os << ", or has a second field that ";
2787     second_matcher_.DescribeNegationTo(os);
2788   }
2789
2790   // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2791   // matches second_matcher.
2792   virtual bool MatchAndExplain(PairType a_pair,
2793                                MatchResultListener* listener) const {
2794     if (!listener->IsInterested()) {
2795       // If the listener is not interested, we don't need to construct the
2796       // explanation.
2797       return first_matcher_.Matches(a_pair.first) &&
2798              second_matcher_.Matches(a_pair.second);
2799     }
2800     StringMatchResultListener first_inner_listener;
2801     if (!first_matcher_.MatchAndExplain(a_pair.first,
2802                                         &first_inner_listener)) {
2803       *listener << "whose first field does not match";
2804       PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
2805       return false;
2806     }
2807     StringMatchResultListener second_inner_listener;
2808     if (!second_matcher_.MatchAndExplain(a_pair.second,
2809                                          &second_inner_listener)) {
2810       *listener << "whose second field does not match";
2811       PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
2812       return false;
2813     }
2814     ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2815                    listener);
2816     return true;
2817   }
2818
2819  private:
2820   void ExplainSuccess(const internal::string& first_explanation,
2821                       const internal::string& second_explanation,
2822                       MatchResultListener* listener) const {
2823     *listener << "whose both fields match";
2824     if (first_explanation != "") {
2825       *listener << ", where the first field is a value " << first_explanation;
2826     }
2827     if (second_explanation != "") {
2828       *listener << ", ";
2829       if (first_explanation != "") {
2830         *listener << "and ";
2831       } else {
2832         *listener << "where ";
2833       }
2834       *listener << "the second field is a value " << second_explanation;
2835     }
2836   }
2837
2838   const Matcher<const FirstType&> first_matcher_;
2839   const Matcher<const SecondType&> second_matcher_;
2840
2841   GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
2842 };
2843
2844 // Implements polymorphic Pair(first_matcher, second_matcher).
2845 template <typename FirstMatcher, typename SecondMatcher>
2846 class PairMatcher {
2847  public:
2848   PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2849       : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2850
2851   template <typename PairType>
2852   operator Matcher<PairType> () const {
2853     return MakeMatcher(
2854         new PairMatcherImpl<PairType>(
2855             first_matcher_, second_matcher_));
2856   }
2857
2858  private:
2859   const FirstMatcher first_matcher_;
2860   const SecondMatcher second_matcher_;
2861
2862   GTEST_DISALLOW_ASSIGN_(PairMatcher);
2863 };
2864
2865 // Implements ElementsAre() and ElementsAreArray().
2866 template <typename Container>
2867 class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2868  public:
2869   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
2870   typedef internal::StlContainerView<RawContainer> View;
2871   typedef typename View::type StlContainer;
2872   typedef typename View::const_reference StlContainerReference;
2873   typedef typename StlContainer::value_type Element;
2874
2875   // Constructs the matcher from a sequence of element values or
2876   // element matchers.
2877   template <typename InputIter>
2878   ElementsAreMatcherImpl(InputIter first, InputIter last) {
2879     while (first != last) {
2880       matchers_.push_back(MatcherCast<const Element&>(*first++));
2881     }
2882   }
2883
2884   // Describes what this matcher does.
2885   virtual void DescribeTo(::std::ostream* os) const {
2886     if (count() == 0) {
2887       *os << "is empty";
2888     } else if (count() == 1) {
2889       *os << "has 1 element that ";
2890       matchers_[0].DescribeTo(os);
2891     } else {
2892       *os << "has " << Elements(count()) << " where\n";
2893       for (size_t i = 0; i != count(); ++i) {
2894         *os << "element #" << i << " ";
2895         matchers_[i].DescribeTo(os);
2896         if (i + 1 < count()) {
2897           *os << ",\n";
2898         }
2899       }
2900     }
2901   }
2902
2903   // Describes what the negation of this matcher does.
2904   virtual void DescribeNegationTo(::std::ostream* os) const {
2905     if (count() == 0) {
2906       *os << "isn't empty";
2907       return;
2908     }
2909
2910     *os << "doesn't have " << Elements(count()) << ", or\n";
2911     for (size_t i = 0; i != count(); ++i) {
2912       *os << "element #" << i << " ";
2913       matchers_[i].DescribeNegationTo(os);
2914       if (i + 1 < count()) {
2915         *os << ", or\n";
2916       }
2917     }
2918   }
2919
2920   virtual bool MatchAndExplain(Container container,
2921                                MatchResultListener* listener) const {
2922     // To work with stream-like "containers", we must only walk
2923     // through the elements in one pass.
2924
2925     const bool listener_interested = listener->IsInterested();
2926
2927     // explanations[i] is the explanation of the element at index i.
2928     ::std::vector<internal::string> explanations(count());
2929     StlContainerReference stl_container = View::ConstReference(container);
2930     typename StlContainer::const_iterator it = stl_container.begin();
2931     size_t exam_pos = 0;
2932     bool mismatch_found = false;  // Have we found a mismatched element yet?
2933
2934     // Go through the elements and matchers in pairs, until we reach
2935     // the end of either the elements or the matchers, or until we find a
2936     // mismatch.
2937     for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
2938       bool match;  // Does the current element match the current matcher?
2939       if (listener_interested) {
2940         StringMatchResultListener s;
2941         match = matchers_[exam_pos].MatchAndExplain(*it, &s);
2942         explanations[exam_pos] = s.str();
2943       } else {
2944         match = matchers_[exam_pos].Matches(*it);
2945       }
2946
2947       if (!match) {
2948         mismatch_found = true;
2949         break;
2950       }
2951     }
2952     // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
2953
2954     // Find how many elements the actual container has.  We avoid
2955     // calling size() s.t. this code works for stream-like "containers"
2956     // that don't define size().
2957     size_t actual_count = exam_pos;
2958     for (; it != stl_container.end(); ++it) {
2959       ++actual_count;
2960     }
2961
2962     if (actual_count != count()) {
2963       // The element count doesn't match.  If the container is empty,
2964       // there's no need to explain anything as Google Mock already
2965       // prints the empty container.  Otherwise we just need to show
2966       // how many elements there actually are.
2967       if (listener_interested && (actual_count != 0)) {
2968         *listener << "which has " << Elements(actual_count);
2969       }
2970       return false;
2971     }
2972
2973     if (mismatch_found) {
2974       // The element count matches, but the exam_pos-th element doesn't match.
2975       if (listener_interested) {
2976         *listener << "whose element #" << exam_pos << " doesn't match";
2977         PrintIfNotEmpty(explanations[exam_pos], listener->stream());
2978       }
2979       return false;
2980     }
2981
2982     // Every element matches its expectation.  We need to explain why
2983     // (the obvious ones can be skipped).
2984     if (listener_interested) {
2985       bool reason_printed = false;
2986       for (size_t i = 0; i != count(); ++i) {
2987         const internal::string& s = explanations[i];
2988         if (!s.empty()) {
2989           if (reason_printed) {
2990             *listener << ",\nand ";
2991           }
2992           *listener << "whose element #" << i << " matches, " << s;
2993           reason_printed = true;
2994         }
2995       }
2996     }
2997     return true;
2998   }
2999
3000  private:
3001   static Message Elements(size_t count) {
3002     return Message() << count << (count == 1 ? " element" : " elements");
3003   }
3004
3005   size_t count() const { return matchers_.size(); }
3006
3007   ::std::vector<Matcher<const Element&> > matchers_;
3008
3009   GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
3010 };
3011
3012 // Connectivity matrix of (elements X matchers), in element-major order.
3013 // Initially, there are no edges.
3014 // Use NextGraph() to iterate over all possible edge configurations.
3015 // Use Randomize() to generate a random edge configuration.
3016 class GTEST_API_ MatchMatrix {
3017  public:
3018   MatchMatrix(size_t num_elements, size_t num_matchers)
3019       : num_elements_(num_elements),
3020         num_matchers_(num_matchers),
3021         matched_(num_elements_* num_matchers_, 0) {
3022   }
3023
3024   size_t LhsSize() const { return num_elements_; }
3025   size_t RhsSize() const { return num_matchers_; }
3026   bool HasEdge(size_t ilhs, size_t irhs) const {
3027     return matched_[SpaceIndex(ilhs, irhs)] == 1;
3028   }
3029   void SetEdge(size_t ilhs, size_t irhs, bool b) {
3030     matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3031   }
3032
3033   // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3034   // adds 1 to that number; returns false if incrementing the graph left it
3035   // empty.
3036   bool NextGraph();
3037
3038   void Randomize();
3039
3040   string DebugString() const;
3041
3042  private:
3043   size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3044     return ilhs * num_matchers_ + irhs;
3045   }
3046
3047   size_t num_elements_;
3048   size_t num_matchers_;
3049
3050   // Each element is a char interpreted as bool. They are stored as a
3051   // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3052   // a (ilhs, irhs) matrix coordinate into an offset.
3053   ::std::vector<char> matched_;
3054 };
3055
3056 typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3057 typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3058
3059 // Returns a maximum bipartite matching for the specified graph 'g'.
3060 // The matching is represented as a vector of {element, matcher} pairs.
3061 GTEST_API_ ElementMatcherPairs
3062 FindMaxBipartiteMatching(const MatchMatrix& g);
3063
3064 GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3065                             MatchResultListener* listener);
3066
3067 // Untyped base class for implementing UnorderedElementsAre.  By
3068 // putting logic that's not specific to the element type here, we
3069 // reduce binary bloat and increase compilation speed.
3070 class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3071  protected:
3072   // A vector of matcher describers, one for each element matcher.
3073   // Does not own the describers (and thus can be used only when the
3074   // element matchers are alive).
3075   typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3076
3077   // Describes this UnorderedElementsAre matcher.
3078   void DescribeToImpl(::std::ostream* os) const;
3079
3080   // Describes the negation of this UnorderedElementsAre matcher.
3081   void DescribeNegationToImpl(::std::ostream* os) const;
3082
3083   bool VerifyAllElementsAndMatchersAreMatched(
3084       const ::std::vector<string>& element_printouts,
3085       const MatchMatrix& matrix,
3086       MatchResultListener* listener) const;
3087
3088   MatcherDescriberVec& matcher_describers() {
3089     return matcher_describers_;
3090   }
3091
3092   static Message Elements(size_t n) {
3093     return Message() << n << " element" << (n == 1 ? "" : "s");
3094   }
3095
3096  private:
3097   MatcherDescriberVec matcher_describers_;
3098
3099   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3100 };
3101
3102 // Implements unordered ElementsAre and unordered ElementsAreArray.
3103 template <typename Container>
3104 class UnorderedElementsAreMatcherImpl
3105     : public MatcherInterface<Container>,
3106       public UnorderedElementsAreMatcherImplBase {
3107  public:
3108   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3109   typedef internal::StlContainerView<RawContainer> View;
3110   typedef typename View::type StlContainer;
3111   typedef typename View::const_reference StlContainerReference;
3112   typedef typename StlContainer::const_iterator StlContainerConstIterator;
3113   typedef typename StlContainer::value_type Element;
3114
3115   // Constructs the matcher from a sequence of element values or
3116   // element matchers.
3117   template <typename InputIter>
3118   UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3119     for (; first != last; ++first) {
3120       matchers_.push_back(MatcherCast<const Element&>(*first));
3121       matcher_describers().push_back(matchers_.back().GetDescriber());
3122     }
3123   }
3124
3125   // Describes what this matcher does.
3126   virtual void DescribeTo(::std::ostream* os) const {
3127     return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3128   }
3129
3130   // Describes what the negation of this matcher does.
3131   virtual void DescribeNegationTo(::std::ostream* os) const {
3132     return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3133   }
3134
3135   virtual bool MatchAndExplain(Container container,
3136                                MatchResultListener* listener) const {
3137     StlContainerReference stl_container = View::ConstReference(container);
3138     ::std::vector<string> element_printouts;
3139     MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3140                                          stl_container.end(),
3141                                          &element_printouts,
3142                                          listener);
3143
3144     const size_t actual_count = matrix.LhsSize();
3145     if (actual_count == 0 && matchers_.empty()) {
3146       return true;
3147     }
3148     if (actual_count != matchers_.size()) {
3149       // The element count doesn't match.  If the container is empty,
3150       // there's no need to explain anything as Google Mock already
3151       // prints the empty container. Otherwise we just need to show
3152       // how many elements there actually are.
3153       if (actual_count != 0 && listener->IsInterested()) {
3154         *listener << "which has " << Elements(actual_count);
3155       }
3156       return false;
3157     }
3158
3159     return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3160                                                   matrix, listener) &&
3161            FindPairing(matrix, listener);
3162   }
3163
3164  private:
3165   typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3166
3167   template <typename ElementIter>
3168   MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
3169                               ::std::vector<string>* element_printouts,
3170                               MatchResultListener* listener) const {
3171     element_printouts->clear();
3172     ::std::vector<char> did_match;
3173     size_t num_elements = 0;
3174     for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3175       if (listener->IsInterested()) {
3176         element_printouts->push_back(PrintToString(*elem_first));
3177       }
3178       for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3179         did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3180       }
3181     }
3182
3183     MatchMatrix matrix(num_elements, matchers_.size());
3184     ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3185     for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3186       for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3187         matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3188       }
3189     }
3190     return matrix;
3191   }
3192
3193   MatcherVec matchers_;
3194
3195   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3196 };
3197
3198 // Functor for use in TransformTuple.
3199 // Performs MatcherCast<Target> on an input argument of any type.
3200 template <typename Target>
3201 struct CastAndAppendTransform {
3202   template <typename Arg>
3203   Matcher<Target> operator()(const Arg& a) const {
3204     return MatcherCast<Target>(a);
3205   }
3206 };
3207
3208 // Implements UnorderedElementsAre.
3209 template <typename MatcherTuple>
3210 class UnorderedElementsAreMatcher {
3211  public:
3212   explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3213       : matchers_(args) {}
3214
3215   template <typename Container>
3216   operator Matcher<Container>() const {
3217     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3218     typedef typename internal::StlContainerView<RawContainer>::type View;
3219     typedef typename View::value_type Element;
3220     typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3221     MatcherVec matchers;
3222     matchers.reserve(::std::tr1::tuple_size<MatcherTuple>::value);
3223     TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3224                          ::std::back_inserter(matchers));
3225     return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3226                            matchers.begin(), matchers.end()));
3227   }
3228
3229  private:
3230   const MatcherTuple matchers_;
3231   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3232 };
3233
3234 // Implements ElementsAre.
3235 template <typename MatcherTuple>
3236 class ElementsAreMatcher {
3237  public:
3238   explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3239
3240   template <typename Container>
3241   operator Matcher<Container>() const {
3242     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3243     typedef typename internal::StlContainerView<RawContainer>::type View;
3244     typedef typename View::value_type Element;
3245     typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3246     MatcherVec matchers;
3247     matchers.reserve(::std::tr1::tuple_size<MatcherTuple>::value);
3248     TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3249                          ::std::back_inserter(matchers));
3250     return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3251                            matchers.begin(), matchers.end()));
3252   }
3253
3254  private:
3255   const MatcherTuple matchers_;
3256   GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3257 };
3258
3259 // Implements UnorderedElementsAreArray().
3260 template <typename T>
3261 class UnorderedElementsAreArrayMatcher {
3262  public:
3263   UnorderedElementsAreArrayMatcher() {}
3264
3265   template <typename Iter>
3266   UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3267       : matchers_(first, last) {}
3268
3269   template <typename Container>
3270   operator Matcher<Container>() const {
3271     return MakeMatcher(
3272         new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3273                                                        matchers_.end()));
3274   }
3275
3276  private:
3277   ::std::vector<T> matchers_;
3278
3279   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
3280 };
3281
3282 // Implements ElementsAreArray().
3283 template <typename T>
3284 class ElementsAreArrayMatcher {
3285  public:
3286   template <typename Iter>
3287   ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
3288
3289   template <typename Container>
3290   operator Matcher<Container>() const {
3291     return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3292         matchers_.begin(), matchers_.end()));
3293   }
3294
3295  private:
3296   const ::std::vector<T> matchers_;
3297
3298   GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
3299 };
3300
3301 // Returns the description for a matcher defined using the MATCHER*()
3302 // macro where the user-supplied description string is "", if
3303 // 'negation' is false; otherwise returns the description of the
3304 // negation of the matcher.  'param_values' contains a list of strings
3305 // that are the print-out of the matcher's parameters.
3306 GTEST_API_ string FormatMatcherDescription(bool negation,
3307                                            const char* matcher_name,
3308                                            const Strings& param_values);
3309
3310 }  // namespace internal
3311
3312 // ElementsAreArray(first, last)
3313 // ElementsAreArray(pointer, count)
3314 // ElementsAreArray(array)
3315 // ElementsAreArray(vector)
3316 // ElementsAreArray({ e1, e2, ..., en })
3317 //
3318 // The ElementsAreArray() functions are like ElementsAre(...), except
3319 // that they are given a homogeneous sequence rather than taking each
3320 // element as a function argument. The sequence can be specified as an
3321 // array, a pointer and count, a vector, an initializer list, or an
3322 // STL iterator range. In each of these cases, the underlying sequence
3323 // can be either a sequence of values or a sequence of matchers.
3324 //
3325 // All forms of ElementsAreArray() make a copy of the input matcher sequence.
3326
3327 template <typename Iter>
3328 inline internal::ElementsAreArrayMatcher<
3329     typename ::std::iterator_traits<Iter>::value_type>
3330 ElementsAreArray(Iter first, Iter last) {
3331   typedef typename ::std::iterator_traits<Iter>::value_type T;
3332   return internal::ElementsAreArrayMatcher<T>(first, last);
3333 }
3334
3335 template <typename T>
3336 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3337     const T* pointer, size_t count) {
3338   return ElementsAreArray(pointer, pointer + count);
3339 }
3340
3341 template <typename T, size_t N>
3342 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3343     const T (&array)[N]) {
3344   return ElementsAreArray(array, N);
3345 }
3346
3347 template <typename T, typename A>
3348 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3349     const ::std::vector<T, A>& vec) {
3350   return ElementsAreArray(vec.begin(), vec.end());
3351 }
3352
3353 #if GTEST_LANG_CXX11
3354 template <typename T>
3355 inline internal::ElementsAreArrayMatcher<T>
3356 ElementsAreArray(::std::initializer_list<T> xs) {
3357   return ElementsAreArray(xs.begin(), xs.end());
3358 }
3359 #endif
3360
3361 // UnorderedElementsAreArray(first, last)
3362 // UnorderedElementsAreArray(pointer, count)
3363 // UnorderedElementsAreArray(array)
3364 // UnorderedElementsAreArray(vector)
3365 // UnorderedElementsAreArray({ e1, e2, ..., en })
3366 //
3367 // The UnorderedElementsAreArray() functions are like
3368 // ElementsAreArray(...), but allow matching the elements in any order.
3369 template <typename Iter>
3370 inline internal::UnorderedElementsAreArrayMatcher<
3371     typename ::std::iterator_traits<Iter>::value_type>
3372 UnorderedElementsAreArray(Iter first, Iter last) {
3373   typedef typename ::std::iterator_traits<Iter>::value_type T;
3374   return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3375 }
3376
3377 template <typename T>
3378 inline internal::UnorderedElementsAreArrayMatcher<T>
3379 UnorderedElementsAreArray(const T* pointer, size_t count) {
3380   return UnorderedElementsAreArray(pointer, pointer + count);
3381 }
3382
3383 template <typename T, size_t N>
3384 inline internal::UnorderedElementsAreArrayMatcher<T>
3385 UnorderedElementsAreArray(const T (&array)[N]) {
3386   return UnorderedElementsAreArray(array, N);
3387 }
3388
3389 template <typename T, typename A>
3390 inline internal::UnorderedElementsAreArrayMatcher<T>
3391 UnorderedElementsAreArray(const ::std::vector<T, A>& vec) {
3392   return UnorderedElementsAreArray(vec.begin(), vec.end());
3393 }
3394
3395 #if GTEST_LANG_CXX11
3396 template <typename T>
3397 inline internal::UnorderedElementsAreArrayMatcher<T>
3398 UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3399   return UnorderedElementsAreArray(xs.begin(), xs.end());
3400 }
3401 #endif
3402
3403 // _ is a matcher that matches anything of any type.
3404 //
3405 // This definition is fine as:
3406 //
3407 //   1. The C++ standard permits using the name _ in a namespace that
3408 //      is not the global namespace or ::std.
3409 //   2. The AnythingMatcher class has no data member or constructor,
3410 //      so it's OK to create global variables of this type.
3411 //   3. c-style has approved of using _ in this case.
3412 const internal::AnythingMatcher _ = {};
3413 // Creates a matcher that matches any value of the given type T.
3414 template <typename T>
3415 inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3416
3417 // Creates a matcher that matches any value of the given type T.
3418 template <typename T>
3419 inline Matcher<T> An() { return A<T>(); }
3420
3421 // Creates a polymorphic matcher that matches anything equal to x.
3422 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3423 // wouldn't compile.
3424 template <typename T>
3425 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3426
3427 // Constructs a Matcher<T> from a 'value' of type T.  The constructed
3428 // matcher matches any value that's equal to 'value'.
3429 template <typename T>
3430 Matcher<T>::Matcher(T value) { *this = Eq(value); }
3431
3432 // Creates a monomorphic matcher that matches anything with type Lhs
3433 // and equal to rhs.  A user may need to use this instead of Eq(...)
3434 // in order to resolve an overloading ambiguity.
3435 //
3436 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3437 // or Matcher<T>(x), but more readable than the latter.
3438 //
3439 // We could define similar monomorphic matchers for other comparison
3440 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3441 // it yet as those are used much less than Eq() in practice.  A user
3442 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
3443 // for example.
3444 template <typename Lhs, typename Rhs>
3445 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3446
3447 // Creates a polymorphic matcher that matches anything >= x.
3448 template <typename Rhs>
3449 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3450   return internal::GeMatcher<Rhs>(x);
3451 }
3452
3453 // Creates a polymorphic matcher that matches anything > x.
3454 template <typename Rhs>
3455 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3456   return internal::GtMatcher<Rhs>(x);
3457 }
3458
3459 // Creates a polymorphic matcher that matches anything <= x.
3460 template <typename Rhs>
3461 inline internal::LeMatcher<Rhs> Le(Rhs x) {
3462   return internal::LeMatcher<Rhs>(x);
3463 }
3464
3465 // Creates a polymorphic matcher that matches anything < x.
3466 template <typename Rhs>
3467 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3468   return internal::LtMatcher<Rhs>(x);
3469 }
3470
3471 // Creates a polymorphic matcher that matches anything != x.
3472 template <typename Rhs>
3473 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3474   return internal::NeMatcher<Rhs>(x);
3475 }
3476
3477 // Creates a polymorphic matcher that matches any NULL pointer.
3478 inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3479   return MakePolymorphicMatcher(internal::IsNullMatcher());
3480 }
3481
3482 // Creates a polymorphic matcher that matches any non-NULL pointer.
3483 // This is convenient as Not(NULL) doesn't compile (the compiler
3484 // thinks that that expression is comparing a pointer with an integer).
3485 inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3486   return MakePolymorphicMatcher(internal::NotNullMatcher());
3487 }
3488
3489 // Creates a polymorphic matcher that matches any argument that
3490 // references variable x.
3491 template <typename T>
3492 inline internal::RefMatcher<T&> Ref(T& x) {  // NOLINT
3493   return internal::RefMatcher<T&>(x);
3494 }
3495
3496 // Creates a matcher that matches any double argument approximately
3497 // equal to rhs, where two NANs are considered unequal.
3498 inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3499   return internal::FloatingEqMatcher<double>(rhs, false);
3500 }
3501
3502 // Creates a matcher that matches any double argument approximately
3503 // equal to rhs, including NaN values when rhs is NaN.
3504 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3505   return internal::FloatingEqMatcher<double>(rhs, true);
3506 }
3507
3508 // Creates a matcher that matches any double argument approximately equal to
3509 // rhs, up to the specified max absolute error bound, where two NANs are
3510 // considered unequal.  The max absolute error bound must be non-negative.
3511 inline internal::FloatingEqMatcher<double> DoubleNear(
3512     double rhs, double max_abs_error) {
3513   return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3514 }
3515
3516 // Creates a matcher that matches any double argument approximately equal to
3517 // rhs, up to the specified max absolute error bound, including NaN values when
3518 // rhs is NaN.  The max absolute error bound must be non-negative.
3519 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3520     double rhs, double max_abs_error) {
3521   return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3522 }
3523
3524 // Creates a matcher that matches any float argument approximately
3525 // equal to rhs, where two NANs are considered unequal.
3526 inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3527   return internal::FloatingEqMatcher<float>(rhs, false);
3528 }
3529
3530 // Creates a matcher that matches any float argument approximately
3531 // equal to rhs, including NaN values when rhs is NaN.
3532 inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3533   return internal::FloatingEqMatcher<float>(rhs, true);
3534 }
3535
3536 // Creates a matcher that matches any float argument approximately equal to
3537 // rhs, up to the specified max absolute error bound, where two NANs are
3538 // considered unequal.  The max absolute error bound must be non-negative.
3539 inline internal::FloatingEqMatcher<float> FloatNear(
3540     float rhs, float max_abs_error) {
3541   return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3542 }
3543
3544 // Creates a matcher that matches any float argument approximately equal to
3545 // rhs, up to the specified max absolute error bound, including NaN values when
3546 // rhs is NaN.  The max absolute error bound must be non-negative.
3547 inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3548     float rhs, float max_abs_error) {
3549   return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3550 }
3551
3552 // Creates a matcher that matches a pointer (raw or smart) that points
3553 // to a value that matches inner_matcher.
3554 template <typename InnerMatcher>
3555 inline internal::PointeeMatcher<InnerMatcher> Pointee(
3556     const InnerMatcher& inner_matcher) {
3557   return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3558 }
3559
3560 // Creates a matcher that matches an object whose given field matches
3561 // 'matcher'.  For example,
3562 //   Field(&Foo::number, Ge(5))
3563 // matches a Foo object x iff x.number >= 5.
3564 template <typename Class, typename FieldType, typename FieldMatcher>
3565 inline PolymorphicMatcher<
3566   internal::FieldMatcher<Class, FieldType> > Field(
3567     FieldType Class::*field, const FieldMatcher& matcher) {
3568   return MakePolymorphicMatcher(
3569       internal::FieldMatcher<Class, FieldType>(
3570           field, MatcherCast<const FieldType&>(matcher)));
3571   // The call to MatcherCast() is required for supporting inner
3572   // matchers of compatible types.  For example, it allows
3573   //   Field(&Foo::bar, m)
3574   // to compile where bar is an int32 and m is a matcher for int64.
3575 }
3576
3577 // Creates a matcher that matches an object whose given property
3578 // matches 'matcher'.  For example,
3579 //   Property(&Foo::str, StartsWith("hi"))
3580 // matches a Foo object x iff x.str() starts with "hi".
3581 template <typename Class, typename PropertyType, typename PropertyMatcher>
3582 inline PolymorphicMatcher<
3583   internal::PropertyMatcher<Class, PropertyType> > Property(
3584     PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
3585   return MakePolymorphicMatcher(
3586       internal::PropertyMatcher<Class, PropertyType>(
3587           property,
3588           MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
3589   // The call to MatcherCast() is required for supporting inner
3590   // matchers of compatible types.  For example, it allows
3591   //   Property(&Foo::bar, m)
3592   // to compile where bar() returns an int32 and m is a matcher for int64.
3593 }
3594
3595 // Creates a matcher that matches an object iff the result of applying
3596 // a callable to x matches 'matcher'.
3597 // For example,
3598 //   ResultOf(f, StartsWith("hi"))
3599 // matches a Foo object x iff f(x) starts with "hi".
3600 // callable parameter can be a function, function pointer, or a functor.
3601 // Callable has to satisfy the following conditions:
3602 //   * It is required to keep no state affecting the results of
3603 //     the calls on it and make no assumptions about how many calls
3604 //     will be made. Any state it keeps must be protected from the
3605 //     concurrent access.
3606 //   * If it is a function object, it has to define type result_type.
3607 //     We recommend deriving your functor classes from std::unary_function.
3608 template <typename Callable, typename ResultOfMatcher>
3609 internal::ResultOfMatcher<Callable> ResultOf(
3610     Callable callable, const ResultOfMatcher& matcher) {
3611   return internal::ResultOfMatcher<Callable>(
3612           callable,
3613           MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3614               matcher));
3615   // The call to MatcherCast() is required for supporting inner
3616   // matchers of compatible types.  For example, it allows
3617   //   ResultOf(Function, m)
3618   // to compile where Function() returns an int32 and m is a matcher for int64.
3619 }
3620
3621 // String matchers.
3622
3623 // Matches a string equal to str.
3624 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3625     StrEq(const internal::string& str) {
3626   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3627       str, true, true));
3628 }
3629
3630 // Matches a string not equal to str.
3631 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3632     StrNe(const internal::string& str) {
3633   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3634       str, false, true));
3635 }
3636
3637 // Matches a string equal to str, ignoring case.
3638 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3639     StrCaseEq(const internal::string& str) {
3640   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3641       str, true, false));
3642 }
3643
3644 // Matches a string not equal to str, ignoring case.
3645 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3646     StrCaseNe(const internal::string& str) {
3647   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3648       str, false, false));
3649 }
3650
3651 // Creates a matcher that matches any string, std::string, or C string
3652 // that contains the given substring.
3653 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
3654     HasSubstr(const internal::string& substring) {
3655   return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3656       substring));
3657 }
3658
3659 // Matches a string that starts with 'prefix' (case-sensitive).
3660 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3661     StartsWith(const internal::string& prefix) {
3662   return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3663       prefix));
3664 }
3665
3666 // Matches a string that ends with 'suffix' (case-sensitive).
3667 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3668     EndsWith(const internal::string& suffix) {
3669   return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
3670       suffix));
3671 }
3672
3673 // Matches a string that fully matches regular expression 'regex'.
3674 // The matcher takes ownership of 'regex'.
3675 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3676     const internal::RE* regex) {
3677   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
3678 }
3679 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3680     const internal::string& regex) {
3681   return MatchesRegex(new internal::RE(regex));
3682 }
3683
3684 // Matches a string that contains regular expression 'regex'.
3685 // The matcher takes ownership of 'regex'.
3686 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3687     const internal::RE* regex) {
3688   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
3689 }
3690 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3691     const internal::string& regex) {
3692   return ContainsRegex(new internal::RE(regex));
3693 }
3694
3695 #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3696 // Wide string matchers.
3697
3698 // Matches a string equal to str.
3699 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3700     StrEq(const internal::wstring& str) {
3701   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3702       str, true, true));
3703 }
3704
3705 // Matches a string not equal to str.
3706 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3707     StrNe(const internal::wstring& str) {
3708   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3709       str, false, true));
3710 }
3711
3712 // Matches a string equal to str, ignoring case.
3713 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3714     StrCaseEq(const internal::wstring& str) {
3715   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3716       str, true, false));
3717 }
3718
3719 // Matches a string not equal to str, ignoring case.
3720 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3721     StrCaseNe(const internal::wstring& str) {
3722   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3723       str, false, false));
3724 }
3725
3726 // Creates a matcher that matches any wstring, std::wstring, or C wide string
3727 // that contains the given substring.
3728 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
3729     HasSubstr(const internal::wstring& substring) {
3730   return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
3731       substring));
3732 }
3733
3734 // Matches a string that starts with 'prefix' (case-sensitive).
3735 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
3736     StartsWith(const internal::wstring& prefix) {
3737   return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
3738       prefix));
3739 }
3740
3741 // Matches a string that ends with 'suffix' (case-sensitive).
3742 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
3743     EndsWith(const internal::wstring& suffix) {
3744   return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
3745       suffix));
3746 }
3747
3748 #endif  // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3749
3750 // Creates a polymorphic matcher that matches a 2-tuple where the
3751 // first field == the second field.
3752 inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
3753
3754 // Creates a polymorphic matcher that matches a 2-tuple where the
3755 // first field >= the second field.
3756 inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
3757
3758 // Creates a polymorphic matcher that matches a 2-tuple where the
3759 // first field > the second field.
3760 inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
3761
3762 // Creates a polymorphic matcher that matches a 2-tuple where the
3763 // first field <= the second field.
3764 inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
3765
3766 // Creates a polymorphic matcher that matches a 2-tuple where the
3767 // first field < the second field.
3768 inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
3769
3770 // Creates a polymorphic matcher that matches a 2-tuple where the
3771 // first field != the second field.
3772 inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
3773
3774 // Creates a matcher that matches any value of type T that m doesn't
3775 // match.
3776 template <typename InnerMatcher>
3777 inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
3778   return internal::NotMatcher<InnerMatcher>(m);
3779 }
3780
3781 // Returns a matcher that matches anything that satisfies the given
3782 // predicate.  The predicate can be any unary function or functor
3783 // whose return type can be implicitly converted to bool.
3784 template <typename Predicate>
3785 inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
3786 Truly(Predicate pred) {
3787   return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
3788 }
3789
3790 // Returns a matcher that matches the container size. The container must
3791 // support both size() and size_type which all STL-like containers provide.
3792 // Note that the parameter 'size' can be a value of type size_type as well as
3793 // matcher. For instance:
3794 //   EXPECT_THAT(container, SizeIs(2));     // Checks container has 2 elements.
3795 //   EXPECT_THAT(container, SizeIs(Le(2));  // Checks container has at most 2.
3796 template <typename SizeMatcher>
3797 inline internal::SizeIsMatcher<SizeMatcher>
3798 SizeIs(const SizeMatcher& size_matcher) {
3799   return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
3800 }
3801
3802 // Returns a matcher that matches an equal container.
3803 // This matcher behaves like Eq(), but in the event of mismatch lists the
3804 // values that are included in one container but not the other. (Duplicate
3805 // values and order differences are not explained.)
3806 template <typename Container>
3807 inline PolymorphicMatcher<internal::ContainerEqMatcher<  // NOLINT
3808                             GTEST_REMOVE_CONST_(Container)> >
3809     ContainerEq(const Container& rhs) {
3810   // This following line is for working around a bug in MSVC 8.0,
3811   // which causes Container to be a const type sometimes.
3812   typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3813   return MakePolymorphicMatcher(
3814       internal::ContainerEqMatcher<RawContainer>(rhs));
3815 }
3816
3817 // Returns a matcher that matches a container that, when sorted using
3818 // the given comparator, matches container_matcher.
3819 template <typename Comparator, typename ContainerMatcher>
3820 inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
3821 WhenSortedBy(const Comparator& comparator,
3822              const ContainerMatcher& container_matcher) {
3823   return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
3824       comparator, container_matcher);
3825 }
3826
3827 // Returns a matcher that matches a container that, when sorted using
3828 // the < operator, matches container_matcher.
3829 template <typename ContainerMatcher>
3830 inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
3831 WhenSorted(const ContainerMatcher& container_matcher) {
3832   return
3833       internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
3834           internal::LessComparator(), container_matcher);
3835 }
3836
3837 // Matches an STL-style container or a native array that contains the
3838 // same number of elements as in rhs, where its i-th element and rhs's
3839 // i-th element (as a pair) satisfy the given pair matcher, for all i.
3840 // TupleMatcher must be able to be safely cast to Matcher<tuple<const
3841 // T1&, const T2&> >, where T1 and T2 are the types of elements in the
3842 // LHS container and the RHS container respectively.
3843 template <typename TupleMatcher, typename Container>
3844 inline internal::PointwiseMatcher<TupleMatcher,
3845                                   GTEST_REMOVE_CONST_(Container)>
3846 Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
3847   // This following line is for working around a bug in MSVC 8.0,
3848   // which causes Container to be a const type sometimes.
3849   typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3850   return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
3851       tuple_matcher, rhs);
3852 }
3853
3854 // Matches an STL-style container or a native array that contains at
3855 // least one element matching the given value or matcher.
3856 //
3857 // Examples:
3858 //   ::std::set<int> page_ids;
3859 //   page_ids.insert(3);
3860 //   page_ids.insert(1);
3861 //   EXPECT_THAT(page_ids, Contains(1));
3862 //   EXPECT_THAT(page_ids, Contains(Gt(2)));
3863 //   EXPECT_THAT(page_ids, Not(Contains(4)));
3864 //
3865 //   ::std::map<int, size_t> page_lengths;
3866 //   page_lengths[1] = 100;
3867 //   EXPECT_THAT(page_lengths,
3868 //               Contains(::std::pair<const int, size_t>(1, 100)));
3869 //
3870 //   const char* user_ids[] = { "joe", "mike", "tom" };
3871 //   EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
3872 template <typename M>
3873 inline internal::ContainsMatcher<M> Contains(M matcher) {
3874   return internal::ContainsMatcher<M>(matcher);
3875 }
3876
3877 // Matches an STL-style container or a native array that contains only
3878 // elements matching the given value or matcher.
3879 //
3880 // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
3881 // the messages are different.
3882 //
3883 // Examples:
3884 //   ::std::set<int> page_ids;
3885 //   // Each(m) matches an empty container, regardless of what m is.
3886 //   EXPECT_THAT(page_ids, Each(Eq(1)));
3887 //   EXPECT_THAT(page_ids, Each(Eq(77)));
3888 //
3889 //   page_ids.insert(3);
3890 //   EXPECT_THAT(page_ids, Each(Gt(0)));
3891 //   EXPECT_THAT(page_ids, Not(Each(Gt(4))));
3892 //   page_ids.insert(1);
3893 //   EXPECT_THAT(page_ids, Not(Each(Lt(2))));
3894 //
3895 //   ::std::map<int, size_t> page_lengths;
3896 //   page_lengths[1] = 100;
3897 //   page_lengths[2] = 200;
3898 //   page_lengths[3] = 300;
3899 //   EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
3900 //   EXPECT_THAT(page_lengths, Each(Key(Le(3))));
3901 //
3902 //   const char* user_ids[] = { "joe", "mike", "tom" };
3903 //   EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
3904 template <typename M>
3905 inline internal::EachMatcher<M> Each(M matcher) {
3906   return internal::EachMatcher<M>(matcher);
3907 }
3908
3909 // Key(inner_matcher) matches an std::pair whose 'first' field matches
3910 // inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
3911 // std::map that contains at least one element whose key is >= 5.
3912 template <typename M>
3913 inline internal::KeyMatcher<M> Key(M inner_matcher) {
3914   return internal::KeyMatcher<M>(inner_matcher);
3915 }
3916
3917 // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3918 // matches first_matcher and whose 'second' field matches second_matcher.  For
3919 // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3920 // to match a std::map<int, string> that contains exactly one element whose key
3921 // is >= 5 and whose value equals "foo".
3922 template <typename FirstMatcher, typename SecondMatcher>
3923 inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3924 Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3925   return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3926       first_matcher, second_matcher);
3927 }
3928
3929 // Returns a predicate that is satisfied by anything that matches the
3930 // given matcher.
3931 template <typename M>
3932 inline internal::MatcherAsPredicate<M> Matches(M matcher) {
3933   return internal::MatcherAsPredicate<M>(matcher);
3934 }
3935
3936 // Returns true iff the value matches the matcher.
3937 template <typename T, typename M>
3938 inline bool Value(const T& value, M matcher) {
3939   return testing::Matches(matcher)(value);
3940 }
3941
3942 // Matches the value against the given matcher and explains the match
3943 // result to listener.
3944 template <typename T, typename M>
3945 inline bool ExplainMatchResult(
3946     M matcher, const T& value, MatchResultListener* listener) {
3947   return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
3948 }
3949
3950 #if GTEST_LANG_CXX11
3951 // Define variadic matcher versions. They are overloaded in
3952 // gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
3953 template <typename... Args>
3954 inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
3955   return internal::AllOfMatcher<Args...>(matchers...);
3956 }
3957
3958 template <typename... Args>
3959 inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
3960   return internal::AnyOfMatcher<Args...>(matchers...);
3961 }
3962
3963 #endif  // GTEST_LANG_CXX11
3964
3965 // AllArgs(m) is a synonym of m.  This is useful in
3966 //
3967 //   EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3968 //
3969 // which is easier to read than
3970 //
3971 //   EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3972 template <typename InnerMatcher>
3973 inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3974
3975 // These macros allow using matchers to check values in Google Test
3976 // tests.  ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3977 // succeed iff the value matches the matcher.  If the assertion fails,
3978 // the value and the description of the matcher will be printed.
3979 #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3980     ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3981 #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3982     ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3983
3984 }  // namespace testing
3985
3986 #endif  // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_