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