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.
MatchResultListener(::std::ostream * os)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.
stream()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.
IsInterested()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 
~MatchResultListener()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:
~MatcherDescriberInterface()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.
DescribeNegationTo(::std::ostream * os)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:
StringMatchResultListener()186   StringMatchResultListener() : MatchResultListener(&ss_) {}
187 
188   // Returns the explanation accumulated so far.
str()189   internal::string str() const { return ss_.str(); }
190 
191   // Clears the explanation accumulated so far.
Clear()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>
operatorAnyEq204   bool operator()(const A& a, const B& b) const { return a == b; }
205 };
206 struct AnyNe {
207   template <typename A, typename B>
operatorAnyNe208   bool operator()(const A& a, const B& b) const { return a != b; }
209 };
210 struct AnyLt {
211   template <typename A, typename B>
operatorAnyLt212   bool operator()(const A& a, const B& b) const { return a < b; }
213 };
214 struct AnyGt {
215   template <typename A, typename B>
operatorAnyGt216   bool operator()(const A& a, const B& b) const { return a > b; }
217 };
218 struct AnyLe {
219   template <typename A, typename B>
operatorAnyLe220   bool operator()(const A& a, const B& b) const { return a <= b; }
221 };
222 struct AnyGe {
223   template <typename A, typename B>
operatorAnyGe224   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:
DummyMatchResultListener()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:
StreamMatchResultListener(::std::ostream * os)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'.
MatchAndExplain(T x,MatchResultListener * 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.
Matches(T x)261   bool Matches(T x) const {
262     DummyMatchResultListener dummy;
263     return MatchAndExplain(x, &dummy);
264   }
265 
266   // Describes this matcher to an ostream.
DescribeTo(::std::ostream * os)267   void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
268 
269   // Describes the negation of this matcher to an ostream.
DescribeNegationTo(::std::ostream * os)270   void DescribeNegationTo(::std::ostream* os) const {
271     impl_->DescribeNegationTo(os);
272   }
273 
274   // Explains why x matches, or doesn't match, the matcher.
ExplainMatchResultTo(T x,::std::ostream * os)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.
GetDescriber()283   const MatcherDescriberInterface* GetDescriber() const {
284     return impl_.get();
285   }
286 
287  protected:
MatcherBase()288   MatcherBase() {}
289 
290   // Constructs a matcher from its implementation.
MatcherBase(const MatcherInterface<T> * impl)291   explicit MatcherBase(const MatcherInterface<T>* impl)
292       : impl_(impl) {}
293 
~MatcherBase()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.
Matcher()324   explicit Matcher() {}  // NOLINT
325 
326   // Constructs a matcher from its implementation.
Matcher(const MatcherInterface<T> * impl)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:
Matcher()342   Matcher() {}
343 
Matcher(const MatcherInterface<const internal::string &> * impl)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:
Matcher()359   Matcher() {}
360 
Matcher(const MatcherInterface<internal::string> * impl)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:
Matcher()380   Matcher() {}
381 
Matcher(const MatcherInterface<const StringPiece &> * impl)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:
Matcher()400   Matcher() {}
401 
Matcher(const MatcherInterface<StringPiece> * impl)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:
PolymorphicMatcher(const Impl & an_impl)432   explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
433 
434   // Returns a mutable reference to the underlying matcher
435   // implementation object.
mutable_impl()436   Impl& mutable_impl() { return impl_; }
437 
438   // Returns an immutable reference to the underlying matcher
439   // implementation object.
impl()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:
MonomorphicImpl(const Impl & impl)451     explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
452 
DescribeTo(::std::ostream * os)453     virtual void DescribeTo(::std::ostream* os) const {
454       impl_.DescribeTo(os);
455     }
456 
DescribeNegationTo(::std::ostream * os)457     virtual void DescribeNegationTo(::std::ostream* os) const {
458       impl_.DescribeNegationTo(os);
459     }
460 
MatchAndExplain(T x,MatchResultListener * listener)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>
MakeMatcher(const MatcherInterface<T> * impl)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>
MakePolymorphicMatcher(const Impl & 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:
Cast(const M & polymorphic_matcher_or_value)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:
CastImpl(const M & value,BooleanConstant<false>)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 
CastImpl(const M & polymorphic_matcher_or_value,BooleanConstant<true>)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:
Cast(const Matcher<U> & source_matcher)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:
Impl(const Matcher<U> & source_matcher)572     explicit Impl(const Matcher<U>& source_matcher)
573         : source_matcher_(source_matcher) {}
574 
575     // We delegate the matching logic to the source matcher.
MatchAndExplain(T x,MatchResultListener * listener)576     virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
577       return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
578     }
579 
DescribeTo(::std::ostream * os)580     virtual void DescribeTo(::std::ostream* os) const {
581       source_matcher_.DescribeTo(os);
582     }
583 
DescribeNegationTo(::std::ostream * os)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:
Cast(const Matcher<T> & matcher)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>
MatcherCast(const M & matcher)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>
Cast(const M & polymorphic_matcher_or_value)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>
Cast(const Matcher<U> & matcher)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>
SafeMatcherCast(const M & polymorphic_matcher)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.
PrintIfNotEmpty(const internal::string & explanation,::std::ostream * os)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.
IsReadableTypeName(const string & type_name)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>
MatchPrintAndExplain(Value & value,const Matcher<T> & matcher,MatchResultListener * listener)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>
Matches(const MatcherTuple & matcher_tuple,const ValueTuple & value_tuple)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>
ExplainMatchFailuresTo(const MatcherTuple & matchers,const ValueTuple & values,::std::ostream * os)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>
Matches(const MatcherTuple &,const 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>
ExplainMatchFailuresTo(const MatcherTuple &,const ValueTuple &,::std::ostream *)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>
TupleMatches(const MatcherTuple & matcher_tuple,const ValueTuple & value_tuple)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>
ExplainMatchFailureTupleTo(const MatcherTuple & matchers,const ValueTuple & values,::std::ostream * os)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.
Run(Func f,const Tuple & t,OutIter out)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 {
operatorIterateOverTuple836     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 GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
2466     typedef internal::StlContainerView<RawContainer> View;
2467     typedef typename View::type StlContainer;
2468     typedef typename View::const_reference StlContainerReference;
2469     typedef decltype(std::begin(
2470         std::declval<StlContainerReference>())) StlContainerConstIterator;
2471     typedef typename std::iterator_traits<
2472         StlContainerConstIterator>::difference_type DistanceType;
2473     explicit Impl(const DistanceMatcher& distance_matcher)
2474         : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2475 
2476     virtual void DescribeTo(::std::ostream* os) const {
2477       *os << "distance between begin() and end() ";
2478       distance_matcher_.DescribeTo(os);
2479     }
2480     virtual void DescribeNegationTo(::std::ostream* os) const {
2481       *os << "distance between begin() and end() ";
2482       distance_matcher_.DescribeNegationTo(os);
2483     }
2484 
2485     virtual bool MatchAndExplain(Container container,
2486                                  MatchResultListener* listener) const {
2487 #if GTEST_HAS_STD_BEGIN_AND_END_
2488       using std::begin;
2489       using std::end;
2490       DistanceType distance = std::distance(begin(container), end(container));
2491 #else
2492       DistanceType distance = std::distance(container.begin(), container.end());
2493 #endif
2494       StringMatchResultListener distance_listener;
2495       const bool result =
2496           distance_matcher_.MatchAndExplain(distance, &distance_listener);
2497       *listener << "whose distance between begin() and end() " << distance
2498                 << (result ? " matches" : " doesn't match");
2499       PrintIfNotEmpty(distance_listener.str(), listener->stream());
2500       return result;
2501     }
2502 
2503    private:
2504     const Matcher<DistanceType> distance_matcher_;
2505     GTEST_DISALLOW_ASSIGN_(Impl);
2506   };
2507 
2508  private:
2509   const DistanceMatcher distance_matcher_;
2510   GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2511 };
2512 
2513 // Implements an equality matcher for any STL-style container whose elements
2514 // support ==. This matcher is like Eq(), but its failure explanations provide
2515 // more detailed information that is useful when the container is used as a set.
2516 // The failure message reports elements that are in one of the operands but not
2517 // the other. The failure messages do not report duplicate or out-of-order
2518 // elements in the containers (which don't properly matter to sets, but can
2519 // occur if the containers are vectors or lists, for example).
2520 //
2521 // Uses the container's const_iterator, value_type, operator ==,
2522 // begin(), and end().
2523 template <typename Container>
2524 class ContainerEqMatcher {
2525  public:
2526   typedef internal::StlContainerView<Container> View;
2527   typedef typename View::type StlContainer;
2528   typedef typename View::const_reference StlContainerReference;
2529 
2530   // We make a copy of expected in case the elements in it are modified
2531   // after this matcher is created.
2532   explicit ContainerEqMatcher(const Container& expected)
2533       : expected_(View::Copy(expected)) {
2534     // Makes sure the user doesn't instantiate this class template
2535     // with a const or reference type.
2536     (void)testing::StaticAssertTypeEq<Container,
2537         GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
2538   }
2539 
2540   void DescribeTo(::std::ostream* os) const {
2541     *os << "equals ";
2542     UniversalPrint(expected_, os);
2543   }
2544   void DescribeNegationTo(::std::ostream* os) const {
2545     *os << "does not equal ";
2546     UniversalPrint(expected_, os);
2547   }
2548 
2549   template <typename LhsContainer>
2550   bool MatchAndExplain(const LhsContainer& lhs,
2551                        MatchResultListener* listener) const {
2552     // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
2553     // that causes LhsContainer to be a const type sometimes.
2554     typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
2555         LhsView;
2556     typedef typename LhsView::type LhsStlContainer;
2557     StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2558     if (lhs_stl_container == expected_)
2559       return true;
2560 
2561     ::std::ostream* const os = listener->stream();
2562     if (os != NULL) {
2563       // Something is different. Check for extra values first.
2564       bool printed_header = false;
2565       for (typename LhsStlContainer::const_iterator it =
2566                lhs_stl_container.begin();
2567            it != lhs_stl_container.end(); ++it) {
2568         if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2569             expected_.end()) {
2570           if (printed_header) {
2571             *os << ", ";
2572           } else {
2573             *os << "which has these unexpected elements: ";
2574             printed_header = true;
2575           }
2576           UniversalPrint(*it, os);
2577         }
2578       }
2579 
2580       // Now check for missing values.
2581       bool printed_header2 = false;
2582       for (typename StlContainer::const_iterator it = expected_.begin();
2583            it != expected_.end(); ++it) {
2584         if (internal::ArrayAwareFind(
2585                 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2586             lhs_stl_container.end()) {
2587           if (printed_header2) {
2588             *os << ", ";
2589           } else {
2590             *os << (printed_header ? ",\nand" : "which")
2591                 << " doesn't have these expected elements: ";
2592             printed_header2 = true;
2593           }
2594           UniversalPrint(*it, os);
2595         }
2596       }
2597     }
2598 
2599     return false;
2600   }
2601 
2602  private:
2603   const StlContainer expected_;
2604 
2605   GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
2606 };
2607 
2608 // A comparator functor that uses the < operator to compare two values.
2609 struct LessComparator {
2610   template <typename T, typename U>
2611   bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2612 };
2613 
2614 // Implements WhenSortedBy(comparator, container_matcher).
2615 template <typename Comparator, typename ContainerMatcher>
2616 class WhenSortedByMatcher {
2617  public:
2618   WhenSortedByMatcher(const Comparator& comparator,
2619                       const ContainerMatcher& matcher)
2620       : comparator_(comparator), matcher_(matcher) {}
2621 
2622   template <typename LhsContainer>
2623   operator Matcher<LhsContainer>() const {
2624     return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2625   }
2626 
2627   template <typename LhsContainer>
2628   class Impl : public MatcherInterface<LhsContainer> {
2629    public:
2630     typedef internal::StlContainerView<
2631          GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2632     typedef typename LhsView::type LhsStlContainer;
2633     typedef typename LhsView::const_reference LhsStlContainerReference;
2634     // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2635     // so that we can match associative containers.
2636     typedef typename RemoveConstFromKey<
2637         typename LhsStlContainer::value_type>::type LhsValue;
2638 
2639     Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2640         : comparator_(comparator), matcher_(matcher) {}
2641 
2642     virtual void DescribeTo(::std::ostream* os) const {
2643       *os << "(when sorted) ";
2644       matcher_.DescribeTo(os);
2645     }
2646 
2647     virtual void DescribeNegationTo(::std::ostream* os) const {
2648       *os << "(when sorted) ";
2649       matcher_.DescribeNegationTo(os);
2650     }
2651 
2652     virtual bool MatchAndExplain(LhsContainer lhs,
2653                                  MatchResultListener* listener) const {
2654       LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2655       ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2656                                                lhs_stl_container.end());
2657       ::std::sort(
2658            sorted_container.begin(), sorted_container.end(), comparator_);
2659 
2660       if (!listener->IsInterested()) {
2661         // If the listener is not interested, we do not need to
2662         // construct the inner explanation.
2663         return matcher_.Matches(sorted_container);
2664       }
2665 
2666       *listener << "which is ";
2667       UniversalPrint(sorted_container, listener->stream());
2668       *listener << " when sorted";
2669 
2670       StringMatchResultListener inner_listener;
2671       const bool match = matcher_.MatchAndExplain(sorted_container,
2672                                                   &inner_listener);
2673       PrintIfNotEmpty(inner_listener.str(), listener->stream());
2674       return match;
2675     }
2676 
2677    private:
2678     const Comparator comparator_;
2679     const Matcher<const ::std::vector<LhsValue>&> matcher_;
2680 
2681     GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2682   };
2683 
2684  private:
2685   const Comparator comparator_;
2686   const ContainerMatcher matcher_;
2687 
2688   GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2689 };
2690 
2691 // Implements Pointwise(tuple_matcher, rhs_container).  tuple_matcher
2692 // must be able to be safely cast to Matcher<tuple<const T1&, const
2693 // T2&> >, where T1 and T2 are the types of elements in the LHS
2694 // container and the RHS container respectively.
2695 template <typename TupleMatcher, typename RhsContainer>
2696 class PointwiseMatcher {
2697  public:
2698   typedef internal::StlContainerView<RhsContainer> RhsView;
2699   typedef typename RhsView::type RhsStlContainer;
2700   typedef typename RhsStlContainer::value_type RhsValue;
2701 
2702   // Like ContainerEq, we make a copy of rhs in case the elements in
2703   // it are modified after this matcher is created.
2704   PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2705       : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2706     // Makes sure the user doesn't instantiate this class template
2707     // with a const or reference type.
2708     (void)testing::StaticAssertTypeEq<RhsContainer,
2709         GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2710   }
2711 
2712   template <typename LhsContainer>
2713   operator Matcher<LhsContainer>() const {
2714     return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2715   }
2716 
2717   template <typename LhsContainer>
2718   class Impl : public MatcherInterface<LhsContainer> {
2719    public:
2720     typedef internal::StlContainerView<
2721          GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2722     typedef typename LhsView::type LhsStlContainer;
2723     typedef typename LhsView::const_reference LhsStlContainerReference;
2724     typedef typename LhsStlContainer::value_type LhsValue;
2725     // We pass the LHS value and the RHS value to the inner matcher by
2726     // reference, as they may be expensive to copy.  We must use tuple
2727     // instead of pair here, as a pair cannot hold references (C++ 98,
2728     // 20.2.2 [lib.pairs]).
2729     typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2730 
2731     Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2732         // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2733         : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2734           rhs_(rhs) {}
2735 
2736     virtual void DescribeTo(::std::ostream* os) const {
2737       *os << "contains " << rhs_.size()
2738           << " values, where each value and its corresponding value in ";
2739       UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2740       *os << " ";
2741       mono_tuple_matcher_.DescribeTo(os);
2742     }
2743     virtual void DescribeNegationTo(::std::ostream* os) const {
2744       *os << "doesn't contain exactly " << rhs_.size()
2745           << " values, or contains a value x at some index i"
2746           << " where x and the i-th value of ";
2747       UniversalPrint(rhs_, os);
2748       *os << " ";
2749       mono_tuple_matcher_.DescribeNegationTo(os);
2750     }
2751 
2752     virtual bool MatchAndExplain(LhsContainer lhs,
2753                                  MatchResultListener* listener) const {
2754       LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2755       const size_t actual_size = lhs_stl_container.size();
2756       if (actual_size != rhs_.size()) {
2757         *listener << "which contains " << actual_size << " values";
2758         return false;
2759       }
2760 
2761       typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2762       typename RhsStlContainer::const_iterator right = rhs_.begin();
2763       for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2764         const InnerMatcherArg value_pair(*left, *right);
2765 
2766         if (listener->IsInterested()) {
2767           StringMatchResultListener inner_listener;
2768           if (!mono_tuple_matcher_.MatchAndExplain(
2769                   value_pair, &inner_listener)) {
2770             *listener << "where the value pair (";
2771             UniversalPrint(*left, listener->stream());
2772             *listener << ", ";
2773             UniversalPrint(*right, listener->stream());
2774             *listener << ") at index #" << i << " don't match";
2775             PrintIfNotEmpty(inner_listener.str(), listener->stream());
2776             return false;
2777           }
2778         } else {
2779           if (!mono_tuple_matcher_.Matches(value_pair))
2780             return false;
2781         }
2782       }
2783 
2784       return true;
2785     }
2786 
2787    private:
2788     const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2789     const RhsStlContainer rhs_;
2790 
2791     GTEST_DISALLOW_ASSIGN_(Impl);
2792   };
2793 
2794  private:
2795   const TupleMatcher tuple_matcher_;
2796   const RhsStlContainer rhs_;
2797 
2798   GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2799 };
2800 
2801 // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
2802 template <typename Container>
2803 class QuantifierMatcherImpl : public MatcherInterface<Container> {
2804  public:
2805   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
2806   typedef StlContainerView<RawContainer> View;
2807   typedef typename View::type StlContainer;
2808   typedef typename View::const_reference StlContainerReference;
2809   typedef typename StlContainer::value_type Element;
2810 
2811   template <typename InnerMatcher>
2812   explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
2813       : inner_matcher_(
2814            testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
2815 
2816   // Checks whether:
2817   // * All elements in the container match, if all_elements_should_match.
2818   // * Any element in the container matches, if !all_elements_should_match.
2819   bool MatchAndExplainImpl(bool all_elements_should_match,
2820                            Container container,
2821                            MatchResultListener* listener) const {
2822     StlContainerReference stl_container = View::ConstReference(container);
2823     size_t i = 0;
2824     for (typename StlContainer::const_iterator it = stl_container.begin();
2825          it != stl_container.end(); ++it, ++i) {
2826       StringMatchResultListener inner_listener;
2827       const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2828 
2829       if (matches != all_elements_should_match) {
2830         *listener << "whose element #" << i
2831                   << (matches ? " matches" : " doesn't match");
2832         PrintIfNotEmpty(inner_listener.str(), listener->stream());
2833         return !all_elements_should_match;
2834       }
2835     }
2836     return all_elements_should_match;
2837   }
2838 
2839  protected:
2840   const Matcher<const Element&> inner_matcher_;
2841 
2842   GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2843 };
2844 
2845 // Implements Contains(element_matcher) for the given argument type Container.
2846 // Symmetric to EachMatcherImpl.
2847 template <typename Container>
2848 class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2849  public:
2850   template <typename InnerMatcher>
2851   explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2852       : QuantifierMatcherImpl<Container>(inner_matcher) {}
2853 
2854   // Describes what this matcher does.
2855   virtual void DescribeTo(::std::ostream* os) const {
2856     *os << "contains at least one element that ";
2857     this->inner_matcher_.DescribeTo(os);
2858   }
2859 
2860   virtual void DescribeNegationTo(::std::ostream* os) const {
2861     *os << "doesn't contain any element that ";
2862     this->inner_matcher_.DescribeTo(os);
2863   }
2864 
2865   virtual bool MatchAndExplain(Container container,
2866                                MatchResultListener* listener) const {
2867     return this->MatchAndExplainImpl(false, container, listener);
2868   }
2869 
2870  private:
2871   GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
2872 };
2873 
2874 // Implements Each(element_matcher) for the given argument type Container.
2875 // Symmetric to ContainsMatcherImpl.
2876 template <typename Container>
2877 class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2878  public:
2879   template <typename InnerMatcher>
2880   explicit EachMatcherImpl(InnerMatcher inner_matcher)
2881       : QuantifierMatcherImpl<Container>(inner_matcher) {}
2882 
2883   // Describes what this matcher does.
2884   virtual void DescribeTo(::std::ostream* os) const {
2885     *os << "only contains elements that ";
2886     this->inner_matcher_.DescribeTo(os);
2887   }
2888 
2889   virtual void DescribeNegationTo(::std::ostream* os) const {
2890     *os << "contains some element that ";
2891     this->inner_matcher_.DescribeNegationTo(os);
2892   }
2893 
2894   virtual bool MatchAndExplain(Container container,
2895                                MatchResultListener* listener) const {
2896     return this->MatchAndExplainImpl(true, container, listener);
2897   }
2898 
2899  private:
2900   GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2901 };
2902 
2903 // Implements polymorphic Contains(element_matcher).
2904 template <typename M>
2905 class ContainsMatcher {
2906  public:
2907   explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2908 
2909   template <typename Container>
2910   operator Matcher<Container>() const {
2911     return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2912   }
2913 
2914  private:
2915   const M inner_matcher_;
2916 
2917   GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
2918 };
2919 
2920 // Implements polymorphic Each(element_matcher).
2921 template <typename M>
2922 class EachMatcher {
2923  public:
2924   explicit EachMatcher(M m) : inner_matcher_(m) {}
2925 
2926   template <typename Container>
2927   operator Matcher<Container>() const {
2928     return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2929   }
2930 
2931  private:
2932   const M inner_matcher_;
2933 
2934   GTEST_DISALLOW_ASSIGN_(EachMatcher);
2935 };
2936 
2937 // Implements Key(inner_matcher) for the given argument pair type.
2938 // Key(inner_matcher) matches an std::pair whose 'first' field matches
2939 // inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
2940 // std::map that contains at least one element whose key is >= 5.
2941 template <typename PairType>
2942 class KeyMatcherImpl : public MatcherInterface<PairType> {
2943  public:
2944   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
2945   typedef typename RawPairType::first_type KeyType;
2946 
2947   template <typename InnerMatcher>
2948   explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2949       : inner_matcher_(
2950           testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2951   }
2952 
2953   // Returns true iff 'key_value.first' (the key) matches the inner matcher.
2954   virtual bool MatchAndExplain(PairType key_value,
2955                                MatchResultListener* listener) const {
2956     StringMatchResultListener inner_listener;
2957     const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2958                                                       &inner_listener);
2959     const internal::string explanation = inner_listener.str();
2960     if (explanation != "") {
2961       *listener << "whose first field is a value " << explanation;
2962     }
2963     return match;
2964   }
2965 
2966   // Describes what this matcher does.
2967   virtual void DescribeTo(::std::ostream* os) const {
2968     *os << "has a key that ";
2969     inner_matcher_.DescribeTo(os);
2970   }
2971 
2972   // Describes what the negation of this matcher does.
2973   virtual void DescribeNegationTo(::std::ostream* os) const {
2974     *os << "doesn't have a key that ";
2975     inner_matcher_.DescribeTo(os);
2976   }
2977 
2978  private:
2979   const Matcher<const KeyType&> inner_matcher_;
2980 
2981   GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
2982 };
2983 
2984 // Implements polymorphic Key(matcher_for_key).
2985 template <typename M>
2986 class KeyMatcher {
2987  public:
2988   explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2989 
2990   template <typename PairType>
2991   operator Matcher<PairType>() const {
2992     return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2993   }
2994 
2995  private:
2996   const M matcher_for_key_;
2997 
2998   GTEST_DISALLOW_ASSIGN_(KeyMatcher);
2999 };
3000 
3001 // Implements Pair(first_matcher, second_matcher) for the given argument pair
3002 // type with its two matchers. See Pair() function below.
3003 template <typename PairType>
3004 class PairMatcherImpl : public MatcherInterface<PairType> {
3005  public:
3006   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
3007   typedef typename RawPairType::first_type FirstType;
3008   typedef typename RawPairType::second_type SecondType;
3009 
3010   template <typename FirstMatcher, typename SecondMatcher>
3011   PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3012       : first_matcher_(
3013             testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3014         second_matcher_(
3015             testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3016   }
3017 
3018   // Describes what this matcher does.
3019   virtual void DescribeTo(::std::ostream* os) const {
3020     *os << "has a first field that ";
3021     first_matcher_.DescribeTo(os);
3022     *os << ", and has a second field that ";
3023     second_matcher_.DescribeTo(os);
3024   }
3025 
3026   // Describes what the negation of this matcher does.
3027   virtual void DescribeNegationTo(::std::ostream* os) const {
3028     *os << "has a first field that ";
3029     first_matcher_.DescribeNegationTo(os);
3030     *os << ", or has a second field that ";
3031     second_matcher_.DescribeNegationTo(os);
3032   }
3033 
3034   // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3035   // matches second_matcher.
3036   virtual bool MatchAndExplain(PairType a_pair,
3037                                MatchResultListener* listener) const {
3038     if (!listener->IsInterested()) {
3039       // If the listener is not interested, we don't need to construct the
3040       // explanation.
3041       return first_matcher_.Matches(a_pair.first) &&
3042              second_matcher_.Matches(a_pair.second);
3043     }
3044     StringMatchResultListener first_inner_listener;
3045     if (!first_matcher_.MatchAndExplain(a_pair.first,
3046                                         &first_inner_listener)) {
3047       *listener << "whose first field does not match";
3048       PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
3049       return false;
3050     }
3051     StringMatchResultListener second_inner_listener;
3052     if (!second_matcher_.MatchAndExplain(a_pair.second,
3053                                          &second_inner_listener)) {
3054       *listener << "whose second field does not match";
3055       PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
3056       return false;
3057     }
3058     ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3059                    listener);
3060     return true;
3061   }
3062 
3063  private:
3064   void ExplainSuccess(const internal::string& first_explanation,
3065                       const internal::string& second_explanation,
3066                       MatchResultListener* listener) const {
3067     *listener << "whose both fields match";
3068     if (first_explanation != "") {
3069       *listener << ", where the first field is a value " << first_explanation;
3070     }
3071     if (second_explanation != "") {
3072       *listener << ", ";
3073       if (first_explanation != "") {
3074         *listener << "and ";
3075       } else {
3076         *listener << "where ";
3077       }
3078       *listener << "the second field is a value " << second_explanation;
3079     }
3080   }
3081 
3082   const Matcher<const FirstType&> first_matcher_;
3083   const Matcher<const SecondType&> second_matcher_;
3084 
3085   GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
3086 };
3087 
3088 // Implements polymorphic Pair(first_matcher, second_matcher).
3089 template <typename FirstMatcher, typename SecondMatcher>
3090 class PairMatcher {
3091  public:
3092   PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3093       : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3094 
3095   template <typename PairType>
3096   operator Matcher<PairType> () const {
3097     return MakeMatcher(
3098         new PairMatcherImpl<PairType>(
3099             first_matcher_, second_matcher_));
3100   }
3101 
3102  private:
3103   const FirstMatcher first_matcher_;
3104   const SecondMatcher second_matcher_;
3105 
3106   GTEST_DISALLOW_ASSIGN_(PairMatcher);
3107 };
3108 
3109 // Implements ElementsAre() and ElementsAreArray().
3110 template <typename Container>
3111 class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3112  public:
3113   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3114   typedef internal::StlContainerView<RawContainer> View;
3115   typedef typename View::type StlContainer;
3116   typedef typename View::const_reference StlContainerReference;
3117   typedef decltype(std::begin(
3118       std::declval<StlContainerReference>())) StlContainerConstIterator;
3119   typedef typename std::remove_reference<decltype(
3120       *std::declval<StlContainerConstIterator &>())>::type Element;
3121 
3122   // Constructs the matcher from a sequence of element values or
3123   // element matchers.
3124   template <typename InputIter>
3125   ElementsAreMatcherImpl(InputIter first, InputIter last) {
3126     while (first != last) {
3127       matchers_.push_back(MatcherCast<const Element&>(*first++));
3128     }
3129   }
3130 
3131   // Describes what this matcher does.
3132   virtual void DescribeTo(::std::ostream* os) const {
3133     if (count() == 0) {
3134       *os << "is empty";
3135     } else if (count() == 1) {
3136       *os << "has 1 element that ";
3137       matchers_[0].DescribeTo(os);
3138     } else {
3139       *os << "has " << Elements(count()) << " where\n";
3140       for (size_t i = 0; i != count(); ++i) {
3141         *os << "element #" << i << " ";
3142         matchers_[i].DescribeTo(os);
3143         if (i + 1 < count()) {
3144           *os << ",\n";
3145         }
3146       }
3147     }
3148   }
3149 
3150   // Describes what the negation of this matcher does.
3151   virtual void DescribeNegationTo(::std::ostream* os) const {
3152     if (count() == 0) {
3153       *os << "isn't empty";
3154       return;
3155     }
3156 
3157     *os << "doesn't have " << Elements(count()) << ", or\n";
3158     for (size_t i = 0; i != count(); ++i) {
3159       *os << "element #" << i << " ";
3160       matchers_[i].DescribeNegationTo(os);
3161       if (i + 1 < count()) {
3162         *os << ", or\n";
3163       }
3164     }
3165   }
3166 
3167   virtual bool MatchAndExplain(Container container,
3168                                MatchResultListener* listener) const {
3169     // To work with stream-like "containers", we must only walk
3170     // through the elements in one pass.
3171 
3172     const bool listener_interested = listener->IsInterested();
3173 
3174     // explanations[i] is the explanation of the element at index i.
3175     ::std::vector<internal::string> explanations(count());
3176     StlContainerReference stl_container = View::ConstReference(container);
3177     StlContainerConstIterator it = stl_container.begin();
3178     size_t exam_pos = 0;
3179     bool mismatch_found = false;  // Have we found a mismatched element yet?
3180 
3181     // Go through the elements and matchers in pairs, until we reach
3182     // the end of either the elements or the matchers, or until we find a
3183     // mismatch.
3184     for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3185       bool match;  // Does the current element match the current matcher?
3186       if (listener_interested) {
3187         StringMatchResultListener s;
3188         match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3189         explanations[exam_pos] = s.str();
3190       } else {
3191         match = matchers_[exam_pos].Matches(*it);
3192       }
3193 
3194       if (!match) {
3195         mismatch_found = true;
3196         break;
3197       }
3198     }
3199     // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3200 
3201     // Find how many elements the actual container has.  We avoid
3202     // calling size() s.t. this code works for stream-like "containers"
3203     // that don't define size().
3204     size_t actual_count = exam_pos;
3205     for (; it != stl_container.end(); ++it) {
3206       ++actual_count;
3207     }
3208 
3209     if (actual_count != count()) {
3210       // The element count doesn't match.  If the container is empty,
3211       // there's no need to explain anything as Google Mock already
3212       // prints the empty container.  Otherwise we just need to show
3213       // how many elements there actually are.
3214       if (listener_interested && (actual_count != 0)) {
3215         *listener << "which has " << Elements(actual_count);
3216       }
3217       return false;
3218     }
3219 
3220     if (mismatch_found) {
3221       // The element count matches, but the exam_pos-th element doesn't match.
3222       if (listener_interested) {
3223         *listener << "whose element #" << exam_pos << " doesn't match";
3224         PrintIfNotEmpty(explanations[exam_pos], listener->stream());
3225       }
3226       return false;
3227     }
3228 
3229     // Every element matches its expectation.  We need to explain why
3230     // (the obvious ones can be skipped).
3231     if (listener_interested) {
3232       bool reason_printed = false;
3233       for (size_t i = 0; i != count(); ++i) {
3234         const internal::string& s = explanations[i];
3235         if (!s.empty()) {
3236           if (reason_printed) {
3237             *listener << ",\nand ";
3238           }
3239           *listener << "whose element #" << i << " matches, " << s;
3240           reason_printed = true;
3241         }
3242       }
3243     }
3244     return true;
3245   }
3246 
3247  private:
3248   static Message Elements(size_t count) {
3249     return Message() << count << (count == 1 ? " element" : " elements");
3250   }
3251 
3252   size_t count() const { return matchers_.size(); }
3253 
3254   ::std::vector<Matcher<const Element&> > matchers_;
3255 
3256   GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
3257 };
3258 
3259 // Connectivity matrix of (elements X matchers), in element-major order.
3260 // Initially, there are no edges.
3261 // Use NextGraph() to iterate over all possible edge configurations.
3262 // Use Randomize() to generate a random edge configuration.
3263 class GTEST_API_ MatchMatrix {
3264  public:
3265   MatchMatrix(size_t num_elements, size_t num_matchers)
3266       : num_elements_(num_elements),
3267         num_matchers_(num_matchers),
3268         matched_(num_elements_* num_matchers_, 0) {
3269   }
3270 
3271   size_t LhsSize() const { return num_elements_; }
3272   size_t RhsSize() const { return num_matchers_; }
3273   bool HasEdge(size_t ilhs, size_t irhs) const {
3274     return matched_[SpaceIndex(ilhs, irhs)] == 1;
3275   }
3276   void SetEdge(size_t ilhs, size_t irhs, bool b) {
3277     matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3278   }
3279 
3280   // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3281   // adds 1 to that number; returns false if incrementing the graph left it
3282   // empty.
3283   bool NextGraph();
3284 
3285   void Randomize();
3286 
3287   string DebugString() const;
3288 
3289  private:
3290   size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3291     return ilhs * num_matchers_ + irhs;
3292   }
3293 
3294   size_t num_elements_;
3295   size_t num_matchers_;
3296 
3297   // Each element is a char interpreted as bool. They are stored as a
3298   // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3299   // a (ilhs, irhs) matrix coordinate into an offset.
3300   ::std::vector<char> matched_;
3301 };
3302 
3303 typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3304 typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3305 
3306 // Returns a maximum bipartite matching for the specified graph 'g'.
3307 // The matching is represented as a vector of {element, matcher} pairs.
3308 GTEST_API_ ElementMatcherPairs
3309 FindMaxBipartiteMatching(const MatchMatrix& g);
3310 
3311 GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3312                             MatchResultListener* listener);
3313 
3314 // Untyped base class for implementing UnorderedElementsAre.  By
3315 // putting logic that's not specific to the element type here, we
3316 // reduce binary bloat and increase compilation speed.
3317 class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3318  protected:
3319   // A vector of matcher describers, one for each element matcher.
3320   // Does not own the describers (and thus can be used only when the
3321   // element matchers are alive).
3322   typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3323 
3324   // Describes this UnorderedElementsAre matcher.
3325   void DescribeToImpl(::std::ostream* os) const;
3326 
3327   // Describes the negation of this UnorderedElementsAre matcher.
3328   void DescribeNegationToImpl(::std::ostream* os) const;
3329 
3330   bool VerifyAllElementsAndMatchersAreMatched(
3331       const ::std::vector<string>& element_printouts,
3332       const MatchMatrix& matrix,
3333       MatchResultListener* listener) const;
3334 
3335   MatcherDescriberVec& matcher_describers() {
3336     return matcher_describers_;
3337   }
3338 
3339   static Message Elements(size_t n) {
3340     return Message() << n << " element" << (n == 1 ? "" : "s");
3341   }
3342 
3343  private:
3344   MatcherDescriberVec matcher_describers_;
3345 
3346   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3347 };
3348 
3349 // Implements unordered ElementsAre and unordered ElementsAreArray.
3350 template <typename Container>
3351 class UnorderedElementsAreMatcherImpl
3352     : public MatcherInterface<Container>,
3353       public UnorderedElementsAreMatcherImplBase {
3354  public:
3355   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3356   typedef internal::StlContainerView<RawContainer> View;
3357   typedef typename View::type StlContainer;
3358   typedef typename View::const_reference StlContainerReference;
3359   typedef decltype(std::begin(
3360       std::declval<StlContainerReference>())) StlContainerConstIterator;
3361   typedef typename std::remove_reference<decltype(
3362       *std::declval<StlContainerConstIterator &>())>::type Element;
3363 
3364   // Constructs the matcher from a sequence of element values or
3365   // element matchers.
3366   template <typename InputIter>
3367   UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3368     for (; first != last; ++first) {
3369       matchers_.push_back(MatcherCast<const Element&>(*first));
3370       matcher_describers().push_back(matchers_.back().GetDescriber());
3371     }
3372   }
3373 
3374   // Describes what this matcher does.
3375   virtual void DescribeTo(::std::ostream* os) const {
3376     return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3377   }
3378 
3379   // Describes what the negation of this matcher does.
3380   virtual void DescribeNegationTo(::std::ostream* os) const {
3381     return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3382   }
3383 
3384   virtual bool MatchAndExplain(Container container,
3385                                MatchResultListener* listener) const {
3386     StlContainerReference stl_container = View::ConstReference(container);
3387     ::std::vector<string> element_printouts;
3388     MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3389                                          stl_container.end(),
3390                                          &element_printouts,
3391                                          listener);
3392 
3393     const size_t actual_count = matrix.LhsSize();
3394     if (actual_count == 0 && matchers_.empty()) {
3395       return true;
3396     }
3397     if (actual_count != matchers_.size()) {
3398       // The element count doesn't match.  If the container is empty,
3399       // there's no need to explain anything as Google Mock already
3400       // prints the empty container. Otherwise we just need to show
3401       // how many elements there actually are.
3402       if (actual_count != 0 && listener->IsInterested()) {
3403         *listener << "which has " << Elements(actual_count);
3404       }
3405       return false;
3406     }
3407 
3408     return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3409                                                   matrix, listener) &&
3410            FindPairing(matrix, listener);
3411   }
3412 
3413  private:
3414   typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3415 
3416   template <typename ElementIter>
3417   MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
3418                               ::std::vector<string>* element_printouts,
3419                               MatchResultListener* listener) const {
3420     element_printouts->clear();
3421     ::std::vector<char> did_match;
3422     size_t num_elements = 0;
3423     for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3424       if (listener->IsInterested()) {
3425         element_printouts->push_back(PrintToString(*elem_first));
3426       }
3427       for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3428         did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3429       }
3430     }
3431 
3432     MatchMatrix matrix(num_elements, matchers_.size());
3433     ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3434     for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3435       for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3436         matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3437       }
3438     }
3439     return matrix;
3440   }
3441 
3442   MatcherVec matchers_;
3443 
3444   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3445 };
3446 
3447 // Functor for use in TransformTuple.
3448 // Performs MatcherCast<Target> on an input argument of any type.
3449 template <typename Target>
3450 struct CastAndAppendTransform {
3451   template <typename Arg>
3452   Matcher<Target> operator()(const Arg& a) const {
3453     return MatcherCast<Target>(a);
3454   }
3455 };
3456 
3457 // Implements UnorderedElementsAre.
3458 template <typename MatcherTuple>
3459 class UnorderedElementsAreMatcher {
3460  public:
3461   explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3462       : matchers_(args) {}
3463 
3464   template <typename Container>
3465   operator Matcher<Container>() const {
3466     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3467     typedef internal::StlContainerView<RawContainer> View;
3468     typedef typename View::const_reference StlContainerReference;
3469     typedef decltype(std::begin(
3470         std::declval<StlContainerReference>())) StlContainerConstIterator;
3471     typedef typename std::remove_reference<decltype(
3472         *std::declval<StlContainerConstIterator &>())>::type Element;
3473     typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3474     MatcherVec matchers;
3475     matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3476     TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3477                          ::std::back_inserter(matchers));
3478     return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3479                            matchers.begin(), matchers.end()));
3480   }
3481 
3482  private:
3483   const MatcherTuple matchers_;
3484   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3485 };
3486 
3487 // Implements ElementsAre.
3488 template <typename MatcherTuple>
3489 class ElementsAreMatcher {
3490  public:
3491   explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3492 
3493   template <typename Container>
3494   operator Matcher<Container>() const {
3495     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3496     typedef internal::StlContainerView<RawContainer> View;
3497     typedef typename View::const_reference StlContainerReference;
3498     typedef decltype(std::begin(
3499         std::declval<StlContainerReference>())) StlContainerConstIterator;
3500     typedef typename std::remove_reference<decltype(
3501         *std::declval<StlContainerConstIterator &>())>::type Element;
3502     typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3503     MatcherVec matchers;
3504     matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3505     TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3506                          ::std::back_inserter(matchers));
3507     return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3508                            matchers.begin(), matchers.end()));
3509   }
3510 
3511  private:
3512   const MatcherTuple matchers_;
3513   GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3514 };
3515 
3516 // Implements UnorderedElementsAreArray().
3517 template <typename T>
3518 class UnorderedElementsAreArrayMatcher {
3519  public:
3520   UnorderedElementsAreArrayMatcher() {}
3521 
3522   template <typename Iter>
3523   UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3524       : matchers_(first, last) {}
3525 
3526   template <typename Container>
3527   operator Matcher<Container>() const {
3528     return MakeMatcher(
3529         new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3530                                                        matchers_.end()));
3531   }
3532 
3533  private:
3534   ::std::vector<T> matchers_;
3535 
3536   GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
3537 };
3538 
3539 // Implements ElementsAreArray().
3540 template <typename T>
3541 class ElementsAreArrayMatcher {
3542  public:
3543   template <typename Iter>
3544   ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
3545 
3546   template <typename Container>
3547   operator Matcher<Container>() const {
3548     return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3549         matchers_.begin(), matchers_.end()));
3550   }
3551 
3552  private:
3553   const ::std::vector<T> matchers_;
3554 
3555   GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
3556 };
3557 
3558 // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3559 // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3560 // second) is a polymorphic matcher that matches a value x iff tm
3561 // matches tuple (x, second).  Useful for implementing
3562 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
3563 //
3564 // BoundSecondMatcher is copyable and assignable, as we need to put
3565 // instances of this class in a vector when implementing
3566 // UnorderedPointwise().
3567 template <typename Tuple2Matcher, typename Second>
3568 class BoundSecondMatcher {
3569  public:
3570   BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3571       : tuple2_matcher_(tm), second_value_(second) {}
3572 
3573   template <typename T>
3574   operator Matcher<T>() const {
3575     return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3576   }
3577 
3578   // We have to define this for UnorderedPointwise() to compile in
3579   // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3580   // which requires the elements to be assignable in C++98.  The
3581   // compiler cannot generate the operator= for us, as Tuple2Matcher
3582   // and Second may not be assignable.
3583   //
3584   // However, this should never be called, so the implementation just
3585   // need to assert.
3586   void operator=(const BoundSecondMatcher& /*rhs*/) {
3587     GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3588   }
3589 
3590  private:
3591   template <typename T>
3592   class Impl : public MatcherInterface<T> {
3593    public:
3594     typedef ::testing::tuple<T, Second> ArgTuple;
3595 
3596     Impl(const Tuple2Matcher& tm, const Second& second)
3597         : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3598           second_value_(second) {}
3599 
3600     virtual void DescribeTo(::std::ostream* os) const {
3601       *os << "and ";
3602       UniversalPrint(second_value_, os);
3603       *os << " ";
3604       mono_tuple2_matcher_.DescribeTo(os);
3605     }
3606 
3607     virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3608       return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3609                                                   listener);
3610     }
3611 
3612    private:
3613     const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3614     const Second second_value_;
3615 
3616     GTEST_DISALLOW_ASSIGN_(Impl);
3617   };
3618 
3619   const Tuple2Matcher tuple2_matcher_;
3620   const Second second_value_;
3621 };
3622 
3623 // Given a 2-tuple matcher tm and a value second,
3624 // MatcherBindSecond(tm, second) returns a matcher that matches a
3625 // value x iff tm matches tuple (x, second).  Useful for implementing
3626 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
3627 template <typename Tuple2Matcher, typename Second>
3628 BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3629     const Tuple2Matcher& tm, const Second& second) {
3630   return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3631 }
3632 
3633 // Returns the description for a matcher defined using the MATCHER*()
3634 // macro where the user-supplied description string is "", if
3635 // 'negation' is false; otherwise returns the description of the
3636 // negation of the matcher.  'param_values' contains a list of strings
3637 // that are the print-out of the matcher's parameters.
3638 GTEST_API_ string FormatMatcherDescription(bool negation,
3639                                            const char* matcher_name,
3640                                            const Strings& param_values);
3641 
3642 }  // namespace internal
3643 
3644 // ElementsAreArray(first, last)
3645 // ElementsAreArray(pointer, count)
3646 // ElementsAreArray(array)
3647 // ElementsAreArray(container)
3648 // ElementsAreArray({ e1, e2, ..., en })
3649 //
3650 // The ElementsAreArray() functions are like ElementsAre(...), except
3651 // that they are given a homogeneous sequence rather than taking each
3652 // element as a function argument. The sequence can be specified as an
3653 // array, a pointer and count, a vector, an initializer list, or an
3654 // STL iterator range. In each of these cases, the underlying sequence
3655 // can be either a sequence of values or a sequence of matchers.
3656 //
3657 // All forms of ElementsAreArray() make a copy of the input matcher sequence.
3658 
3659 template <typename Iter>
3660 inline internal::ElementsAreArrayMatcher<
3661     typename ::std::iterator_traits<Iter>::value_type>
3662 ElementsAreArray(Iter first, Iter last) {
3663   typedef typename ::std::iterator_traits<Iter>::value_type T;
3664   return internal::ElementsAreArrayMatcher<T>(first, last);
3665 }
3666 
3667 template <typename T>
3668 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3669     const T* pointer, size_t count) {
3670   return ElementsAreArray(pointer, pointer + count);
3671 }
3672 
3673 template <typename T, size_t N>
3674 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3675     const T (&array)[N]) {
3676   return ElementsAreArray(array, N);
3677 }
3678 
3679 template <typename Container>
3680 inline internal::ElementsAreArrayMatcher<typename Container::value_type>
3681 ElementsAreArray(const Container& container) {
3682   return ElementsAreArray(container.begin(), container.end());
3683 }
3684 
3685 #if GTEST_HAS_STD_INITIALIZER_LIST_
3686 template <typename T>
3687 inline internal::ElementsAreArrayMatcher<T>
3688 ElementsAreArray(::std::initializer_list<T> xs) {
3689   return ElementsAreArray(xs.begin(), xs.end());
3690 }
3691 #endif
3692 
3693 // UnorderedElementsAreArray(first, last)
3694 // UnorderedElementsAreArray(pointer, count)
3695 // UnorderedElementsAreArray(array)
3696 // UnorderedElementsAreArray(container)
3697 // UnorderedElementsAreArray({ e1, e2, ..., en })
3698 //
3699 // The UnorderedElementsAreArray() functions are like
3700 // ElementsAreArray(...), but allow matching the elements in any order.
3701 template <typename Iter>
3702 inline internal::UnorderedElementsAreArrayMatcher<
3703     typename ::std::iterator_traits<Iter>::value_type>
3704 UnorderedElementsAreArray(Iter first, Iter last) {
3705   typedef typename ::std::iterator_traits<Iter>::value_type T;
3706   return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3707 }
3708 
3709 template <typename T>
3710 inline internal::UnorderedElementsAreArrayMatcher<T>
3711 UnorderedElementsAreArray(const T* pointer, size_t count) {
3712   return UnorderedElementsAreArray(pointer, pointer + count);
3713 }
3714 
3715 template <typename T, size_t N>
3716 inline internal::UnorderedElementsAreArrayMatcher<T>
3717 UnorderedElementsAreArray(const T (&array)[N]) {
3718   return UnorderedElementsAreArray(array, N);
3719 }
3720 
3721 template <typename Container>
3722 inline internal::UnorderedElementsAreArrayMatcher<
3723     typename Container::value_type>
3724 UnorderedElementsAreArray(const Container& container) {
3725   return UnorderedElementsAreArray(container.begin(), container.end());
3726 }
3727 
3728 #if GTEST_HAS_STD_INITIALIZER_LIST_
3729 template <typename T>
3730 inline internal::UnorderedElementsAreArrayMatcher<T>
3731 UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3732   return UnorderedElementsAreArray(xs.begin(), xs.end());
3733 }
3734 #endif
3735 
3736 // _ is a matcher that matches anything of any type.
3737 //
3738 // This definition is fine as:
3739 //
3740 //   1. The C++ standard permits using the name _ in a namespace that
3741 //      is not the global namespace or ::std.
3742 //   2. The AnythingMatcher class has no data member or constructor,
3743 //      so it's OK to create global variables of this type.
3744 //   3. c-style has approved of using _ in this case.
3745 const internal::AnythingMatcher _ = {};
3746 // Creates a matcher that matches any value of the given type T.
3747 template <typename T>
3748 inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3749 
3750 // Creates a matcher that matches any value of the given type T.
3751 template <typename T>
3752 inline Matcher<T> An() { return A<T>(); }
3753 
3754 // Creates a polymorphic matcher that matches anything equal to x.
3755 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3756 // wouldn't compile.
3757 template <typename T>
3758 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3759 
3760 // Constructs a Matcher<T> from a 'value' of type T.  The constructed
3761 // matcher matches any value that's equal to 'value'.
3762 template <typename T>
3763 Matcher<T>::Matcher(T value) { *this = Eq(value); }
3764 
3765 // Creates a monomorphic matcher that matches anything with type Lhs
3766 // and equal to rhs.  A user may need to use this instead of Eq(...)
3767 // in order to resolve an overloading ambiguity.
3768 //
3769 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3770 // or Matcher<T>(x), but more readable than the latter.
3771 //
3772 // We could define similar monomorphic matchers for other comparison
3773 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3774 // it yet as those are used much less than Eq() in practice.  A user
3775 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
3776 // for example.
3777 template <typename Lhs, typename Rhs>
3778 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3779 
3780 // Creates a polymorphic matcher that matches anything >= x.
3781 template <typename Rhs>
3782 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3783   return internal::GeMatcher<Rhs>(x);
3784 }
3785 
3786 // Creates a polymorphic matcher that matches anything > x.
3787 template <typename Rhs>
3788 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3789   return internal::GtMatcher<Rhs>(x);
3790 }
3791 
3792 // Creates a polymorphic matcher that matches anything <= x.
3793 template <typename Rhs>
3794 inline internal::LeMatcher<Rhs> Le(Rhs x) {
3795   return internal::LeMatcher<Rhs>(x);
3796 }
3797 
3798 // Creates a polymorphic matcher that matches anything < x.
3799 template <typename Rhs>
3800 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3801   return internal::LtMatcher<Rhs>(x);
3802 }
3803 
3804 // Creates a polymorphic matcher that matches anything != x.
3805 template <typename Rhs>
3806 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3807   return internal::NeMatcher<Rhs>(x);
3808 }
3809 
3810 // Creates a polymorphic matcher that matches any NULL pointer.
3811 inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3812   return MakePolymorphicMatcher(internal::IsNullMatcher());
3813 }
3814 
3815 // Creates a polymorphic matcher that matches any non-NULL pointer.
3816 // This is convenient as Not(NULL) doesn't compile (the compiler
3817 // thinks that that expression is comparing a pointer with an integer).
3818 inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3819   return MakePolymorphicMatcher(internal::NotNullMatcher());
3820 }
3821 
3822 // Creates a polymorphic matcher that matches any argument that
3823 // references variable x.
3824 template <typename T>
3825 inline internal::RefMatcher<T&> Ref(T& x) {  // NOLINT
3826   return internal::RefMatcher<T&>(x);
3827 }
3828 
3829 // Creates a matcher that matches any double argument approximately
3830 // equal to rhs, where two NANs are considered unequal.
3831 inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3832   return internal::FloatingEqMatcher<double>(rhs, false);
3833 }
3834 
3835 // Creates a matcher that matches any double argument approximately
3836 // equal to rhs, including NaN values when rhs is NaN.
3837 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3838   return internal::FloatingEqMatcher<double>(rhs, true);
3839 }
3840 
3841 // Creates a matcher that matches any double argument approximately equal to
3842 // rhs, up to the specified max absolute error bound, where two NANs are
3843 // considered unequal.  The max absolute error bound must be non-negative.
3844 inline internal::FloatingEqMatcher<double> DoubleNear(
3845     double rhs, double max_abs_error) {
3846   return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3847 }
3848 
3849 // Creates a matcher that matches any double argument approximately equal to
3850 // rhs, up to the specified max absolute error bound, including NaN values when
3851 // rhs is NaN.  The max absolute error bound must be non-negative.
3852 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3853     double rhs, double max_abs_error) {
3854   return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3855 }
3856 
3857 // Creates a matcher that matches any float argument approximately
3858 // equal to rhs, where two NANs are considered unequal.
3859 inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3860   return internal::FloatingEqMatcher<float>(rhs, false);
3861 }
3862 
3863 // Creates a matcher that matches any float argument approximately
3864 // equal to rhs, including NaN values when rhs is NaN.
3865 inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3866   return internal::FloatingEqMatcher<float>(rhs, true);
3867 }
3868 
3869 // Creates a matcher that matches any float argument approximately equal to
3870 // rhs, up to the specified max absolute error bound, where two NANs are
3871 // considered unequal.  The max absolute error bound must be non-negative.
3872 inline internal::FloatingEqMatcher<float> FloatNear(
3873     float rhs, float max_abs_error) {
3874   return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3875 }
3876 
3877 // Creates a matcher that matches any float argument approximately equal to
3878 // rhs, up to the specified max absolute error bound, including NaN values when
3879 // rhs is NaN.  The max absolute error bound must be non-negative.
3880 inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3881     float rhs, float max_abs_error) {
3882   return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3883 }
3884 
3885 // Creates a matcher that matches a pointer (raw or smart) that points
3886 // to a value that matches inner_matcher.
3887 template <typename InnerMatcher>
3888 inline internal::PointeeMatcher<InnerMatcher> Pointee(
3889     const InnerMatcher& inner_matcher) {
3890   return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3891 }
3892 
3893 // Creates a matcher that matches a pointer or reference that matches
3894 // inner_matcher when dynamic_cast<To> is applied.
3895 // The result of dynamic_cast<To> is forwarded to the inner matcher.
3896 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
3897 // If To is a reference and the cast fails, this matcher returns false
3898 // immediately.
3899 template <typename To>
3900 inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
3901 WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
3902   return MakePolymorphicMatcher(
3903       internal::WhenDynamicCastToMatcher<To>(inner_matcher));
3904 }
3905 
3906 // Creates a matcher that matches an object whose given field matches
3907 // 'matcher'.  For example,
3908 //   Field(&Foo::number, Ge(5))
3909 // matches a Foo object x iff x.number >= 5.
3910 template <typename Class, typename FieldType, typename FieldMatcher>
3911 inline PolymorphicMatcher<
3912   internal::FieldMatcher<Class, FieldType> > Field(
3913     FieldType Class::*field, const FieldMatcher& matcher) {
3914   return MakePolymorphicMatcher(
3915       internal::FieldMatcher<Class, FieldType>(
3916           field, MatcherCast<const FieldType&>(matcher)));
3917   // The call to MatcherCast() is required for supporting inner
3918   // matchers of compatible types.  For example, it allows
3919   //   Field(&Foo::bar, m)
3920   // to compile where bar is an int32 and m is a matcher for int64.
3921 }
3922 
3923 // Creates a matcher that matches an object whose given property
3924 // matches 'matcher'.  For example,
3925 //   Property(&Foo::str, StartsWith("hi"))
3926 // matches a Foo object x iff x.str() starts with "hi".
3927 template <typename Class, typename PropertyType, typename PropertyMatcher>
3928 inline PolymorphicMatcher<
3929   internal::PropertyMatcher<Class, PropertyType> > Property(
3930     PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
3931   return MakePolymorphicMatcher(
3932       internal::PropertyMatcher<Class, PropertyType>(
3933           property,
3934           MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
3935   // The call to MatcherCast() is required for supporting inner
3936   // matchers of compatible types.  For example, it allows
3937   //   Property(&Foo::bar, m)
3938   // to compile where bar() returns an int32 and m is a matcher for int64.
3939 }
3940 
3941 // Creates a matcher that matches an object iff the result of applying
3942 // a callable to x matches 'matcher'.
3943 // For example,
3944 //   ResultOf(f, StartsWith("hi"))
3945 // matches a Foo object x iff f(x) starts with "hi".
3946 // callable parameter can be a function, function pointer, or a functor.
3947 // Callable has to satisfy the following conditions:
3948 //   * It is required to keep no state affecting the results of
3949 //     the calls on it and make no assumptions about how many calls
3950 //     will be made. Any state it keeps must be protected from the
3951 //     concurrent access.
3952 //   * If it is a function object, it has to define type result_type.
3953 //     We recommend deriving your functor classes from std::unary_function.
3954 template <typename Callable, typename ResultOfMatcher>
3955 internal::ResultOfMatcher<Callable> ResultOf(
3956     Callable callable, const ResultOfMatcher& matcher) {
3957   return internal::ResultOfMatcher<Callable>(
3958           callable,
3959           MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3960               matcher));
3961   // The call to MatcherCast() is required for supporting inner
3962   // matchers of compatible types.  For example, it allows
3963   //   ResultOf(Function, m)
3964   // to compile where Function() returns an int32 and m is a matcher for int64.
3965 }
3966 
3967 // String matchers.
3968 
3969 // Matches a string equal to str.
3970 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3971     StrEq(const internal::string& str) {
3972   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3973       str, true, true));
3974 }
3975 
3976 // Matches a string not equal to str.
3977 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3978     StrNe(const internal::string& str) {
3979   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3980       str, false, true));
3981 }
3982 
3983 // Matches a string equal to str, ignoring case.
3984 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3985     StrCaseEq(const internal::string& str) {
3986   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3987       str, true, false));
3988 }
3989 
3990 // Matches a string not equal to str, ignoring case.
3991 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3992     StrCaseNe(const internal::string& str) {
3993   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3994       str, false, false));
3995 }
3996 
3997 // Creates a matcher that matches any string, std::string, or C string
3998 // that contains the given substring.
3999 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
4000     HasSubstr(const internal::string& substring) {
4001   return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
4002       substring));
4003 }
4004 
4005 // Matches a string that starts with 'prefix' (case-sensitive).
4006 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
4007     StartsWith(const internal::string& prefix) {
4008   return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
4009       prefix));
4010 }
4011 
4012 // Matches a string that ends with 'suffix' (case-sensitive).
4013 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
4014     EndsWith(const internal::string& suffix) {
4015   return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
4016       suffix));
4017 }
4018 
4019 // Matches a string that fully matches regular expression 'regex'.
4020 // The matcher takes ownership of 'regex'.
4021 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4022     const internal::RE* regex) {
4023   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4024 }
4025 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4026     const internal::string& regex) {
4027   return MatchesRegex(new internal::RE(regex));
4028 }
4029 
4030 // Matches a string that contains regular expression 'regex'.
4031 // The matcher takes ownership of 'regex'.
4032 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4033     const internal::RE* regex) {
4034   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4035 }
4036 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4037     const internal::string& regex) {
4038   return ContainsRegex(new internal::RE(regex));
4039 }
4040 
4041 #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4042 // Wide string matchers.
4043 
4044 // Matches a string equal to str.
4045 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4046     StrEq(const internal::wstring& str) {
4047   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4048       str, true, true));
4049 }
4050 
4051 // Matches a string not equal to str.
4052 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4053     StrNe(const internal::wstring& str) {
4054   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4055       str, false, true));
4056 }
4057 
4058 // Matches a string equal to str, ignoring case.
4059 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4060     StrCaseEq(const internal::wstring& str) {
4061   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4062       str, true, false));
4063 }
4064 
4065 // Matches a string not equal to str, ignoring case.
4066 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4067     StrCaseNe(const internal::wstring& str) {
4068   return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4069       str, false, false));
4070 }
4071 
4072 // Creates a matcher that matches any wstring, std::wstring, or C wide string
4073 // that contains the given substring.
4074 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
4075     HasSubstr(const internal::wstring& substring) {
4076   return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
4077       substring));
4078 }
4079 
4080 // Matches a string that starts with 'prefix' (case-sensitive).
4081 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
4082     StartsWith(const internal::wstring& prefix) {
4083   return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
4084       prefix));
4085 }
4086 
4087 // Matches a string that ends with 'suffix' (case-sensitive).
4088 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
4089     EndsWith(const internal::wstring& suffix) {
4090   return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
4091       suffix));
4092 }
4093 
4094 #endif  // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4095 
4096 // Creates a polymorphic matcher that matches a 2-tuple where the
4097 // first field == the second field.
4098 inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4099 
4100 // Creates a polymorphic matcher that matches a 2-tuple where the
4101 // first field >= the second field.
4102 inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4103 
4104 // Creates a polymorphic matcher that matches a 2-tuple where the
4105 // first field > the second field.
4106 inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4107 
4108 // Creates a polymorphic matcher that matches a 2-tuple where the
4109 // first field <= the second field.
4110 inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4111 
4112 // Creates a polymorphic matcher that matches a 2-tuple where the
4113 // first field < the second field.
4114 inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4115 
4116 // Creates a polymorphic matcher that matches a 2-tuple where the
4117 // first field != the second field.
4118 inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4119 
4120 // Creates a matcher that matches any value of type T that m doesn't
4121 // match.
4122 template <typename InnerMatcher>
4123 inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4124   return internal::NotMatcher<InnerMatcher>(m);
4125 }
4126 
4127 // Returns a matcher that matches anything that satisfies the given
4128 // predicate.  The predicate can be any unary function or functor
4129 // whose return type can be implicitly converted to bool.
4130 template <typename Predicate>
4131 inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4132 Truly(Predicate pred) {
4133   return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4134 }
4135 
4136 // Returns a matcher that matches the container size. The container must
4137 // support both size() and size_type which all STL-like containers provide.
4138 // Note that the parameter 'size' can be a value of type size_type as well as
4139 // matcher. For instance:
4140 //   EXPECT_THAT(container, SizeIs(2));     // Checks container has 2 elements.
4141 //   EXPECT_THAT(container, SizeIs(Le(2));  // Checks container has at most 2.
4142 template <typename SizeMatcher>
4143 inline internal::SizeIsMatcher<SizeMatcher>
4144 SizeIs(const SizeMatcher& size_matcher) {
4145   return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4146 }
4147 
4148 // Returns a matcher that matches the distance between the container's begin()
4149 // iterator and its end() iterator, i.e. the size of the container. This matcher
4150 // can be used instead of SizeIs with containers such as std::forward_list which
4151 // do not implement size(). The container must provide const_iterator (with
4152 // valid iterator_traits), begin() and end().
4153 template <typename DistanceMatcher>
4154 inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4155 BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4156   return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4157 }
4158 
4159 // Returns a matcher that matches an equal container.
4160 // This matcher behaves like Eq(), but in the event of mismatch lists the
4161 // values that are included in one container but not the other. (Duplicate
4162 // values and order differences are not explained.)
4163 template <typename Container>
4164 inline PolymorphicMatcher<internal::ContainerEqMatcher<  // NOLINT
4165                             GTEST_REMOVE_CONST_(Container)> >
4166     ContainerEq(const Container& rhs) {
4167   // This following line is for working around a bug in MSVC 8.0,
4168   // which causes Container to be a const type sometimes.
4169   typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4170   return MakePolymorphicMatcher(
4171       internal::ContainerEqMatcher<RawContainer>(rhs));
4172 }
4173 
4174 // Returns a matcher that matches a container that, when sorted using
4175 // the given comparator, matches container_matcher.
4176 template <typename Comparator, typename ContainerMatcher>
4177 inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4178 WhenSortedBy(const Comparator& comparator,
4179              const ContainerMatcher& container_matcher) {
4180   return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4181       comparator, container_matcher);
4182 }
4183 
4184 // Returns a matcher that matches a container that, when sorted using
4185 // the < operator, matches container_matcher.
4186 template <typename ContainerMatcher>
4187 inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4188 WhenSorted(const ContainerMatcher& container_matcher) {
4189   return
4190       internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4191           internal::LessComparator(), container_matcher);
4192 }
4193 
4194 // Matches an STL-style container or a native array that contains the
4195 // same number of elements as in rhs, where its i-th element and rhs's
4196 // i-th element (as a pair) satisfy the given pair matcher, for all i.
4197 // TupleMatcher must be able to be safely cast to Matcher<tuple<const
4198 // T1&, const T2&> >, where T1 and T2 are the types of elements in the
4199 // LHS container and the RHS container respectively.
4200 template <typename TupleMatcher, typename Container>
4201 inline internal::PointwiseMatcher<TupleMatcher,
4202                                   GTEST_REMOVE_CONST_(Container)>
4203 Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4204   // This following line is for working around a bug in MSVC 8.0,
4205   // which causes Container to be a const type sometimes (e.g. when
4206   // rhs is a const int[])..
4207   typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4208   return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4209       tuple_matcher, rhs);
4210 }
4211 
4212 #if GTEST_HAS_STD_INITIALIZER_LIST_
4213 
4214 // Supports the Pointwise(m, {a, b, c}) syntax.
4215 template <typename TupleMatcher, typename T>
4216 inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4217     const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4218   return Pointwise(tuple_matcher, std::vector<T>(rhs));
4219 }
4220 
4221 #endif  // GTEST_HAS_STD_INITIALIZER_LIST_
4222 
4223 // UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4224 // container or a native array that contains the same number of
4225 // elements as in rhs, where in some permutation of the container, its
4226 // i-th element and rhs's i-th element (as a pair) satisfy the given
4227 // pair matcher, for all i.  Tuple2Matcher must be able to be safely
4228 // cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4229 // the types of elements in the LHS container and the RHS container
4230 // respectively.
4231 //
4232 // This is like Pointwise(pair_matcher, rhs), except that the element
4233 // order doesn't matter.
4234 template <typename Tuple2Matcher, typename RhsContainer>
4235 inline internal::UnorderedElementsAreArrayMatcher<
4236     typename internal::BoundSecondMatcher<
4237         Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4238                            RhsContainer)>::type::value_type> >
4239 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4240                    const RhsContainer& rhs_container) {
4241   // This following line is for working around a bug in MSVC 8.0,
4242   // which causes RhsContainer to be a const type sometimes (e.g. when
4243   // rhs_container is a const int[]).
4244   typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4245 
4246   // RhsView allows the same code to handle RhsContainer being a
4247   // STL-style container and it being a native C-style array.
4248   typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4249   typedef typename RhsView::type RhsStlContainer;
4250   typedef typename RhsStlContainer::value_type Second;
4251   const RhsStlContainer& rhs_stl_container =
4252       RhsView::ConstReference(rhs_container);
4253 
4254   // Create a matcher for each element in rhs_container.
4255   ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4256   for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4257        it != rhs_stl_container.end(); ++it) {
4258     matchers.push_back(
4259         internal::MatcherBindSecond(tuple2_matcher, *it));
4260   }
4261 
4262   // Delegate the work to UnorderedElementsAreArray().
4263   return UnorderedElementsAreArray(matchers);
4264 }
4265 
4266 #if GTEST_HAS_STD_INITIALIZER_LIST_
4267 
4268 // Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4269 template <typename Tuple2Matcher, typename T>
4270 inline internal::UnorderedElementsAreArrayMatcher<
4271     typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4272 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4273                    std::initializer_list<T> rhs) {
4274   return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4275 }
4276 
4277 #endif  // GTEST_HAS_STD_INITIALIZER_LIST_
4278 
4279 // Matches an STL-style container or a native array that contains at
4280 // least one element matching the given value or matcher.
4281 //
4282 // Examples:
4283 //   ::std::set<int> page_ids;
4284 //   page_ids.insert(3);
4285 //   page_ids.insert(1);
4286 //   EXPECT_THAT(page_ids, Contains(1));
4287 //   EXPECT_THAT(page_ids, Contains(Gt(2)));
4288 //   EXPECT_THAT(page_ids, Not(Contains(4)));
4289 //
4290 //   ::std::map<int, size_t> page_lengths;
4291 //   page_lengths[1] = 100;
4292 //   EXPECT_THAT(page_lengths,
4293 //               Contains(::std::pair<const int, size_t>(1, 100)));
4294 //
4295 //   const char* user_ids[] = { "joe", "mike", "tom" };
4296 //   EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4297 template <typename M>
4298 inline internal::ContainsMatcher<M> Contains(M matcher) {
4299   return internal::ContainsMatcher<M>(matcher);
4300 }
4301 
4302 // Matches an STL-style container or a native array that contains only
4303 // elements matching the given value or matcher.
4304 //
4305 // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4306 // the messages are different.
4307 //
4308 // Examples:
4309 //   ::std::set<int> page_ids;
4310 //   // Each(m) matches an empty container, regardless of what m is.
4311 //   EXPECT_THAT(page_ids, Each(Eq(1)));
4312 //   EXPECT_THAT(page_ids, Each(Eq(77)));
4313 //
4314 //   page_ids.insert(3);
4315 //   EXPECT_THAT(page_ids, Each(Gt(0)));
4316 //   EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4317 //   page_ids.insert(1);
4318 //   EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4319 //
4320 //   ::std::map<int, size_t> page_lengths;
4321 //   page_lengths[1] = 100;
4322 //   page_lengths[2] = 200;
4323 //   page_lengths[3] = 300;
4324 //   EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4325 //   EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4326 //
4327 //   const char* user_ids[] = { "joe", "mike", "tom" };
4328 //   EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4329 template <typename M>
4330 inline internal::EachMatcher<M> Each(M matcher) {
4331   return internal::EachMatcher<M>(matcher);
4332 }
4333 
4334 // Key(inner_matcher) matches an std::pair whose 'first' field matches
4335 // inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
4336 // std::map that contains at least one element whose key is >= 5.
4337 template <typename M>
4338 inline internal::KeyMatcher<M> Key(M inner_matcher) {
4339   return internal::KeyMatcher<M>(inner_matcher);
4340 }
4341 
4342 // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4343 // matches first_matcher and whose 'second' field matches second_matcher.  For
4344 // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4345 // to match a std::map<int, string> that contains exactly one element whose key
4346 // is >= 5 and whose value equals "foo".
4347 template <typename FirstMatcher, typename SecondMatcher>
4348 inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4349 Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4350   return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4351       first_matcher, second_matcher);
4352 }
4353 
4354 // Returns a predicate that is satisfied by anything that matches the
4355 // given matcher.
4356 template <typename M>
4357 inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4358   return internal::MatcherAsPredicate<M>(matcher);
4359 }
4360 
4361 // Returns true iff the value matches the matcher.
4362 template <typename T, typename M>
4363 inline bool Value(const T& value, M matcher) {
4364   return testing::Matches(matcher)(value);
4365 }
4366 
4367 // Matches the value against the given matcher and explains the match
4368 // result to listener.
4369 template <typename T, typename M>
4370 inline bool ExplainMatchResult(
4371     M matcher, const T& value, MatchResultListener* listener) {
4372   return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4373 }
4374 
4375 #if GTEST_LANG_CXX11
4376 // Define variadic matcher versions. They are overloaded in
4377 // gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4378 template <typename... Args>
4379 inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4380   return internal::AllOfMatcher<Args...>(matchers...);
4381 }
4382 
4383 template <typename... Args>
4384 inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4385   return internal::AnyOfMatcher<Args...>(matchers...);
4386 }
4387 
4388 #endif  // GTEST_LANG_CXX11
4389 
4390 // AllArgs(m) is a synonym of m.  This is useful in
4391 //
4392 //   EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4393 //
4394 // which is easier to read than
4395 //
4396 //   EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4397 template <typename InnerMatcher>
4398 inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4399 
4400 // These macros allow using matchers to check values in Google Test
4401 // tests.  ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4402 // succeed iff the value matches the matcher.  If the assertion fails,
4403 // the value and the description of the matcher will be printed.
4404 #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4405     ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4406 #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4407     ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4408 
4409 }  // namespace testing
4410 
4411 // Include any custom callback matchers added by the local installation.
4412 // We must include this header at the end to make sure it can use the
4413 // declarations from this file.
4414 #include "gmock/internal/custom/gmock-matchers.h"
4415 #endif  // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
4416