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