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