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