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