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