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