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