?login_element?

Subversion Repositories NedoOS

Rev

Blame | Last modification | View Log | Download

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