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