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