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