Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-19 10:45:45

0001 // Copyright 2007, Google Inc.
0002 // All rights reserved.
0003 //
0004 // Redistribution and use in source and binary forms, with or without
0005 // modification, are permitted provided that the following conditions are
0006 // met:
0007 //
0008 //     * Redistributions of source code must retain the above copyright
0009 // notice, this list of conditions and the following disclaimer.
0010 //     * Redistributions in binary form must reproduce the above
0011 // copyright notice, this list of conditions and the following disclaimer
0012 // in the documentation and/or other materials provided with the
0013 // distribution.
0014 //     * Neither the name of Google Inc. nor the names of its
0015 // contributors may be used to endorse or promote products derived from
0016 // this software without specific prior written permission.
0017 //
0018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
0019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
0020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
0021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
0022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
0023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
0025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
0026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
0027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
0028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0029 
0030 // The Google C++ Testing and Mocking Framework (Google Test)
0031 //
0032 // This file implements just enough of the matcher interface to allow
0033 // EXPECT_DEATH and friends to accept a matcher argument.
0034 
0035 // IWYU pragma: private, include "gtest/gtest.h"
0036 // IWYU pragma: friend gtest/.*
0037 // IWYU pragma: friend gmock/.*
0038 
0039 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
0040 #define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
0041 
0042 #include <atomic>
0043 #include <cstddef>
0044 #include <functional>
0045 #include <memory>
0046 #include <ostream>
0047 #include <string>
0048 #include <string_view>
0049 #include <type_traits>
0050 
0051 #include "gtest/gtest-printers.h"
0052 #include "gtest/internal/gtest-internal.h"
0053 #include "gtest/internal/gtest-port.h"
0054 
0055 // MSVC warning C5046 is new as of VS2017 version 15.8.
0056 #if defined(_MSC_VER) && _MSC_VER >= 1915
0057 #define GTEST_MAYBE_5046_ 5046
0058 #else
0059 #define GTEST_MAYBE_5046_
0060 #endif
0061 
0062 GTEST_DISABLE_MSC_WARNINGS_PUSH_(
0063     4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
0064                               clients of class B */
0065     /* Symbol involving type with internal linkage not defined */)
0066 
0067 namespace testing {
0068 
0069 // To implement a matcher Foo for type T, define:
0070 //   1. a class FooMatcherMatcher that implements the matcher interface:
0071 //     using is_gtest_matcher = void;
0072 //     bool MatchAndExplain(const T&, std::ostream*) const;
0073 //       (MatchResultListener* can also be used instead of std::ostream*)
0074 //     void DescribeTo(std::ostream*) const;
0075 //     void DescribeNegationTo(std::ostream*) const;
0076 //
0077 //   2. a factory function that creates a Matcher<T> object from a
0078 //      FooMatcherMatcher.
0079 
0080 class [[nodiscard]] MatchResultListener {
0081  public:
0082   // Creates a listener object with the given underlying ostream.  The
0083   // listener does not own the ostream, and does not dereference it
0084   // in the constructor or destructor.
0085   explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
0086   virtual ~MatchResultListener() = 0;  // Makes this class abstract.
0087 
0088   // Streams x to the underlying ostream; does nothing if the ostream
0089   // is NULL.
0090   template <typename T>
0091   MatchResultListener& operator<<(const T& x) {
0092     if (stream_ != nullptr) *stream_ << x;
0093     return *this;
0094   }
0095 
0096   // Returns the underlying ostream.
0097   ::std::ostream* stream() { return stream_; }
0098 
0099   // Returns true if and only if the listener is interested in an explanation
0100   // of the match result.  A matcher's MatchAndExplain() method can use
0101   // this information to avoid generating the explanation when no one
0102   // intends to hear it.
0103   bool IsInterested() const { return stream_ != nullptr; }
0104 
0105  private:
0106   ::std::ostream* const stream_;
0107 
0108   MatchResultListener(const MatchResultListener&) = delete;
0109   MatchResultListener& operator=(const MatchResultListener&) = delete;
0110 };
0111 
0112 inline MatchResultListener::~MatchResultListener() = default;
0113 
0114 // An instance of a subclass of this knows how to describe itself as a
0115 // matcher.
0116 class GTEST_API_ [[nodiscard]] MatcherDescriberInterface {
0117  public:
0118   virtual ~MatcherDescriberInterface() = default;
0119 
0120   // Describes this matcher to an ostream.  The function should print
0121   // a verb phrase that describes the property a value matching this
0122   // matcher should have.  The subject of the verb phrase is the value
0123   // being matched.  For example, the DescribeTo() method of the Gt(7)
0124   // matcher prints "is greater than 7".
0125   virtual void DescribeTo(::std::ostream* os) const = 0;
0126 
0127   // Describes the negation of this matcher to an ostream.  For
0128   // example, if the description of this matcher is "is greater than
0129   // 7", the negated description could be "is not greater than 7".
0130   // You are not required to override this when implementing
0131   // MatcherInterface, but it is highly advised so that your matcher
0132   // can produce good error messages.
0133   virtual void DescribeNegationTo(::std::ostream* os) const {
0134     *os << "not (";
0135     DescribeTo(os);
0136     *os << ")";
0137   }
0138 };
0139 
0140 // The implementation of a matcher.
0141 template <typename T>
0142 class [[nodiscard]] MatcherInterface : public MatcherDescriberInterface {
0143  public:
0144   // Returns true if and only if the matcher matches x; also explains the
0145   // match result to 'listener' if necessary (see the next paragraph), in
0146   // the form of a non-restrictive relative clause ("which ...",
0147   // "whose ...", etc) that describes x.  For example, the
0148   // MatchAndExplain() method of the Pointee(...) matcher should
0149   // generate an explanation like "which points to ...".
0150   //
0151   // Implementations of MatchAndExplain() should add an explanation of
0152   // the match result *if and only if* they can provide additional
0153   // information that's not already present (or not obvious) in the
0154   // print-out of x and the matcher's description.  Whether the match
0155   // succeeds is not a factor in deciding whether an explanation is
0156   // needed, as sometimes the caller needs to print a failure message
0157   // when the match succeeds (e.g. when the matcher is used inside
0158   // Not()).
0159   //
0160   // For example, a "has at least 10 elements" matcher should explain
0161   // what the actual element count is, regardless of the match result,
0162   // as it is useful information to the reader; on the other hand, an
0163   // "is empty" matcher probably only needs to explain what the actual
0164   // size is when the match fails, as it's redundant to say that the
0165   // size is 0 when the value is already known to be empty.
0166   //
0167   // You should override this method when defining a new matcher.
0168   //
0169   // It's the responsibility of the caller (Google Test) to guarantee
0170   // that 'listener' is not NULL.  This helps to simplify a matcher's
0171   // implementation when it doesn't care about the performance, as it
0172   // can talk to 'listener' without checking its validity first.
0173   // However, in order to implement dummy listeners efficiently,
0174   // listener->stream() may be NULL.
0175   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
0176 
0177   // Inherits these methods from MatcherDescriberInterface:
0178   //   virtual void DescribeTo(::std::ostream* os) const = 0;
0179   //   virtual void DescribeNegationTo(::std::ostream* os) const;
0180 };
0181 
0182 namespace internal {
0183 
0184 // A match result listener that ignores the explanation.
0185 class [[nodiscard]] DummyMatchResultListener : public MatchResultListener {
0186  public:
0187   DummyMatchResultListener() : MatchResultListener(nullptr) {}
0188 
0189  private:
0190   DummyMatchResultListener(const DummyMatchResultListener&) = delete;
0191   DummyMatchResultListener& operator=(const DummyMatchResultListener&) = delete;
0192 };
0193 
0194 // A match result listener that forwards the explanation to a given
0195 // ostream.  The difference between this and MatchResultListener is
0196 // that the former is concrete.
0197 class [[nodiscard]] StreamMatchResultListener : public MatchResultListener {
0198  public:
0199   explicit StreamMatchResultListener(::std::ostream* os)
0200       : MatchResultListener(os) {}
0201 
0202  private:
0203   StreamMatchResultListener(const StreamMatchResultListener&) = delete;
0204   StreamMatchResultListener& operator=(const StreamMatchResultListener&) =
0205       delete;
0206 };
0207 
0208 struct SharedPayloadBase {
0209   std::atomic<int> ref{1};
0210   void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
0211   bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
0212 };
0213 
0214 template <typename T>
0215 struct SharedPayload : SharedPayloadBase {
0216   explicit SharedPayload(const T& v) : value(v) {}
0217   explicit SharedPayload(T&& v) : value(std::move(v)) {}
0218 
0219   static void Destroy(SharedPayloadBase* shared) {
0220     delete static_cast<SharedPayload*>(shared);
0221   }
0222 
0223   T value;
0224 };
0225 
0226 // An internal class for implementing Matcher<T>, which will derive
0227 // from it.  We put functionalities common to all Matcher<T>
0228 // specializations here to avoid code duplication.
0229 template <typename T>
0230 class [[nodiscard]] MatcherBase : private MatcherDescriberInterface {
0231  public:
0232   // Returns true if and only if the matcher matches x; also explains the
0233   // match result to 'listener'.
0234   bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
0235     GTEST_CHECK_(vtable_ != nullptr);
0236     return vtable_->match_and_explain(*this, x, listener);
0237   }
0238 
0239   // Returns true if and only if this matcher matches x.
0240   bool Matches(const T& x) const {
0241     DummyMatchResultListener dummy;
0242     return MatchAndExplain(x, &dummy);
0243   }
0244 
0245   // Describes this matcher to an ostream.
0246   void DescribeTo(::std::ostream* os) const final {
0247     GTEST_CHECK_(vtable_ != nullptr);
0248     vtable_->describe(*this, os, false);
0249   }
0250 
0251   // Describes the negation of this matcher to an ostream.
0252   void DescribeNegationTo(::std::ostream* os) const final {
0253     GTEST_CHECK_(vtable_ != nullptr);
0254     vtable_->describe(*this, os, true);
0255   }
0256 
0257   // Explains why x matches, or doesn't match, the matcher.
0258   void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
0259     StreamMatchResultListener listener(os);
0260     MatchAndExplain(x, &listener);
0261   }
0262 
0263   // Returns the describer for this matcher object; retains ownership
0264   // of the describer, which is only guaranteed to be alive when
0265   // this matcher object is alive.
0266   const MatcherDescriberInterface* GetDescriber() const {
0267     if (vtable_ == nullptr) return nullptr;
0268     return vtable_->get_describer(*this);
0269   }
0270 
0271  protected:
0272   MatcherBase() : vtable_(nullptr), buffer_() {}
0273 
0274   // Constructs a matcher from its implementation.
0275   template <typename U>
0276   explicit MatcherBase(const MatcherInterface<U>* impl)
0277       : vtable_(nullptr), buffer_() {
0278     Init(impl);
0279   }
0280 
0281   template <typename M,
0282             typename = typename std::remove_reference_t<M>::is_gtest_matcher>
0283   MatcherBase(M&& m) : vtable_(nullptr), buffer_() {  // NOLINT
0284     Init(std::forward<M>(m));
0285   }
0286 
0287   MatcherBase(const MatcherBase& other)
0288       : vtable_(other.vtable_), buffer_(other.buffer_) {
0289     if (IsShared()) buffer_.shared->Ref();
0290   }
0291 
0292   MatcherBase& operator=(const MatcherBase& other) {
0293     if (this == &other) return *this;
0294     Destroy();
0295     vtable_ = other.vtable_;
0296     buffer_ = other.buffer_;
0297     if (IsShared()) buffer_.shared->Ref();
0298     return *this;
0299   }
0300 
0301   MatcherBase(MatcherBase&& other) noexcept
0302       : vtable_(other.vtable_), buffer_(other.buffer_) {
0303     other.vtable_ = nullptr;
0304   }
0305 
0306   MatcherBase& operator=(MatcherBase&& other) noexcept {
0307     if (this == &other) return *this;
0308     Destroy();
0309     vtable_ = other.vtable_;
0310     buffer_ = other.buffer_;
0311     other.vtable_ = nullptr;
0312     return *this;
0313   }
0314 
0315   ~MatcherBase() override { Destroy(); }
0316 
0317  private:
0318   struct VTable {
0319     bool (*match_and_explain)(const MatcherBase&, const T&,
0320                               MatchResultListener*);
0321     void (*describe)(const MatcherBase&, std::ostream*, bool negation);
0322     // Returns the captured object if it implements the interface, otherwise
0323     // returns the MatcherBase itself.
0324     const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
0325     // Called on shared instances when the reference count reaches 0.
0326     void (*shared_destroy)(SharedPayloadBase*);
0327   };
0328 
0329   bool IsShared() const {
0330     return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
0331   }
0332 
0333   // If the implementation uses a listener, call that.
0334   template <typename P>
0335   static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
0336                                   MatchResultListener* listener)
0337       -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
0338     return P::Get(m).MatchAndExplain(value, listener->stream());
0339   }
0340 
0341   template <typename P>
0342   static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
0343                                   MatchResultListener* listener)
0344       -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
0345     return P::Get(m).MatchAndExplain(value, listener);
0346   }
0347 
0348   template <typename P>
0349   static void DescribeImpl(const MatcherBase& m, std::ostream* os,
0350                            bool negation) {
0351     if (negation) {
0352       P::Get(m).DescribeNegationTo(os);
0353     } else {
0354       P::Get(m).DescribeTo(os);
0355     }
0356   }
0357 
0358   template <typename P>
0359   static const MatcherDescriberInterface* GetDescriberImpl(
0360       const MatcherBase& m) {
0361     // If the impl is a MatcherDescriberInterface, then return it.
0362     // Otherwise use MatcherBase itself.
0363     // This allows us to implement the GetDescriber() function without support
0364     // from the impl, but some users really want to get their impl back when
0365     // they call GetDescriber().
0366     // We use std::get on a tuple as a workaround of not having `if constexpr`.
0367     return std::get<(std::is_convertible_v<decltype(&P::Get(m)),
0368                                            const MatcherDescriberInterface*>
0369                          ? 1
0370                          : 0)>(std::make_tuple(&m, &P::Get(m)));
0371   }
0372 
0373   template <typename P>
0374   const VTable* GetVTable() {
0375     static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
0376                                        &DescribeImpl<P>, &GetDescriberImpl<P>,
0377                                        P::shared_destroy};
0378     return &kVTable;
0379   }
0380 
0381   union Buffer {
0382     // Add some types to give Buffer some common alignment/size use cases.
0383     void* ptr;
0384     double d;
0385     int64_t i;
0386     // And add one for the out-of-line cases.
0387     SharedPayloadBase* shared;
0388   };
0389 
0390   void Destroy() {
0391     if (IsShared() && buffer_.shared->Unref()) {
0392       vtable_->shared_destroy(buffer_.shared);
0393     }
0394   }
0395 
0396   template <typename M>
0397   static constexpr bool IsInlined() {
0398     return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
0399            std::is_trivially_copy_constructible_v<M> &&
0400            std::is_trivially_destructible_v<M>;
0401   }
0402 
0403   template <typename M, bool = MatcherBase::IsInlined<M>()>
0404   struct ValuePolicy {
0405     static const M& Get(const MatcherBase& m) {
0406       // When inlined along with Init, need to be explicit to avoid violating
0407       // strict aliasing rules.
0408       const M* ptr =
0409           static_cast<const M*>(static_cast<const void*>(&m.buffer_));
0410       return *ptr;
0411     }
0412     static void Init(MatcherBase& m, M impl) {
0413       ::new (static_cast<void*>(&m.buffer_)) M(impl);
0414     }
0415     static constexpr auto shared_destroy = nullptr;
0416   };
0417 
0418   template <typename M>
0419   struct ValuePolicy<M, false> {
0420     using Shared = SharedPayload<M>;
0421     static const M& Get(const MatcherBase& m) {
0422       return static_cast<Shared*>(m.buffer_.shared)->value;
0423     }
0424     template <typename Arg>
0425     static void Init(MatcherBase& m, Arg&& arg) {
0426       m.buffer_.shared = new Shared(std::forward<Arg>(arg));
0427     }
0428     static constexpr auto shared_destroy = &Shared::Destroy;
0429   };
0430 
0431   template <typename U, bool B>
0432   struct ValuePolicy<const MatcherInterface<U>*, B> {
0433     using M = const MatcherInterface<U>;
0434     using Shared = SharedPayload<std::unique_ptr<M>>;
0435     static const M& Get(const MatcherBase& m) {
0436       return *static_cast<Shared*>(m.buffer_.shared)->value;
0437     }
0438     static void Init(MatcherBase& m, M* impl) {
0439       m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
0440     }
0441 
0442     static constexpr auto shared_destroy = &Shared::Destroy;
0443   };
0444 
0445   template <typename M>
0446   void Init(M&& m) {
0447     using MM = std::decay_t<M>;
0448     using Policy = ValuePolicy<MM>;
0449     vtable_ = GetVTable<Policy>();
0450     Policy::Init(*this, std::forward<M>(m));
0451   }
0452 
0453   const VTable* vtable_;
0454   Buffer buffer_;
0455 };
0456 
0457 }  // namespace internal
0458 
0459 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
0460 // object that can check whether a value of type T matches.  The
0461 // implementation of Matcher<T> is just a std::shared_ptr to const
0462 // MatcherInterface<T>.  Don't inherit from Matcher!
0463 template <typename T>
0464 class [[nodiscard]] Matcher : public internal::MatcherBase<T> {
0465  public:
0466   // Constructs a null matcher.  Needed for storing Matcher objects in STL
0467   // containers.  A default-constructed matcher is not yet initialized.  You
0468   // cannot use it until a valid value has been assigned to it.
0469   explicit Matcher() {}  // NOLINT
0470 
0471   // Constructs a matcher from its implementation.
0472   explicit Matcher(const MatcherInterface<const T&>* impl)
0473       : internal::MatcherBase<T>(impl) {}
0474 
0475   template <typename U>
0476   explicit Matcher(const MatcherInterface<U>* impl,
0477                    std::enable_if_t<!std::is_same_v<U, const U&>>* = nullptr)
0478       : internal::MatcherBase<T>(impl) {}
0479 
0480   template <typename M,
0481             typename = typename std::remove_reference_t<M>::is_gtest_matcher>
0482   Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {}  // NOLINT
0483 
0484   // Implicit constructor here allows people to write
0485   // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
0486   Matcher(T value);  // NOLINT
0487 
0488   // Implicit constructor here allows people to write
0489   // EXPECT_THAT(foo, nullptr) instead of EXPECT_THAT(foo, IsNull()) for smart
0490   // pointer types.
0491   //
0492   // The second argument is needed to avoid capturing literal '0'.
0493   template <typename U>
0494   Matcher(U,  // NOLINT
0495           std::enable_if_t<std::is_same_v<U, std::nullptr_t>>* = nullptr);
0496 };
0497 
0498 // The following two specializations allow the user to write str
0499 // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
0500 // matcher is expected.
0501 template <>
0502 class GTEST_API_ [[nodiscard]]
0503 Matcher<const std::string&> : public internal::MatcherBase<const std::string&> {
0504  public:
0505   Matcher() = default;
0506 
0507   explicit Matcher(const MatcherInterface<const std::string&>* impl)
0508       : internal::MatcherBase<const std::string&>(impl) {}
0509 
0510   template <typename M,
0511             typename = typename std::remove_reference_t<M>::is_gtest_matcher>
0512   Matcher(M&& m)  // NOLINT
0513       : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
0514 
0515   // Allows the user to write str instead of Eq(str) sometimes, where
0516   // str is a std::string object.
0517   Matcher(const std::string& s);  // NOLINT
0518 
0519   // Allows the user to write "foo" instead of Eq("foo") sometimes.
0520   Matcher(const char* s);  // NOLINT
0521 };
0522 
0523 template <>
0524 class GTEST_API_ [[nodiscard]]
0525 Matcher<std::string> : public internal::MatcherBase<std::string> {
0526  public:
0527   Matcher() = default;
0528 
0529   explicit Matcher(const MatcherInterface<const std::string&>* impl)
0530       : internal::MatcherBase<std::string>(impl) {}
0531   explicit Matcher(const MatcherInterface<std::string>* impl)
0532       : internal::MatcherBase<std::string>(impl) {}
0533 
0534   template <typename M,
0535             typename = typename std::remove_reference_t<M>::is_gtest_matcher>
0536   Matcher(M&& m)  // NOLINT
0537       : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
0538 
0539   // Allows the user to write str instead of Eq(str) sometimes, where
0540   // str is a string object.
0541   Matcher(const std::string& s);  // NOLINT
0542 
0543   // Allows the user to write "foo" instead of Eq("foo") sometimes.
0544   Matcher(const char* s);  // NOLINT
0545 };
0546 
0547 // The following two specializations allow the user to write str
0548 // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string_view
0549 // matcher is expected.
0550 template <>
0551 class GTEST_API_ [[nodiscard]] Matcher<const internal::StringView&>
0552     : public internal::MatcherBase<const internal::StringView&> {
0553  public:
0554   Matcher() = default;
0555 
0556   explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
0557       : internal::MatcherBase<const internal::StringView&>(impl) {}
0558 
0559   template <typename M,
0560             typename = typename std::remove_reference_t<M>::is_gtest_matcher>
0561   Matcher(M&& m)  // NOLINT
0562       : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
0563   }
0564 
0565   // Allows the user to write str instead of Eq(str) sometimes, where
0566   // str is a std::string object.
0567   Matcher(const std::string& s);  // NOLINT
0568 
0569   // Allows the user to write "foo" instead of Eq("foo") sometimes.
0570   Matcher(const char* s);  // NOLINT
0571 
0572   // Allows the user to pass std::string_views directly.
0573   Matcher(internal::StringView s);  // NOLINT
0574 };
0575 
0576 template <>
0577 class GTEST_API_ [[nodiscard]] Matcher<internal::StringView>
0578     : public internal::MatcherBase<internal::StringView> {
0579  public:
0580   Matcher() = default;
0581 
0582   explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
0583       : internal::MatcherBase<internal::StringView>(impl) {}
0584   explicit Matcher(const MatcherInterface<internal::StringView>* impl)
0585       : internal::MatcherBase<internal::StringView>(impl) {}
0586 
0587   template <typename M,
0588             typename = typename std::remove_reference_t<M>::is_gtest_matcher>
0589   Matcher(M&& m)  // NOLINT
0590       : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
0591 
0592   // Allows the user to write str instead of Eq(str) sometimes, where
0593   // str is a std::string object.
0594   Matcher(const std::string& s);  // NOLINT
0595 
0596   // Allows the user to write "foo" instead of Eq("foo") sometimes.
0597   Matcher(const char* s);  // NOLINT
0598 
0599   // Allows the user to pass std::string_views directly.
0600   Matcher(internal::StringView s);  // NOLINT
0601 };
0602 
0603 // Prints a matcher in a human-readable format.
0604 template <typename T>
0605 std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
0606   matcher.DescribeTo(&os);
0607   return os;
0608 }
0609 
0610 // The PolymorphicMatcher class template makes it easy to implement a
0611 // polymorphic matcher (i.e. a matcher that can match values of more
0612 // than one type, e.g. Eq(n) and NotNull()).
0613 //
0614 // To define a polymorphic matcher, a user should provide an Impl
0615 // class that has a DescribeTo() method and a DescribeNegationTo()
0616 // method, and define a member function (or member function template)
0617 //
0618 //   bool MatchAndExplain(const Value& value,
0619 //                        MatchResultListener* listener) const;
0620 //
0621 // See the definition of NotNull() for a complete example.
0622 template <class Impl>
0623 class [[nodiscard]] PolymorphicMatcher {
0624  public:
0625   explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
0626 
0627   // Returns a mutable reference to the underlying matcher
0628   // implementation object.
0629   Impl& mutable_impl() { return impl_; }
0630 
0631   // Returns an immutable reference to the underlying matcher
0632   // implementation object.
0633   const Impl& impl() const { return impl_; }
0634 
0635   template <typename T>
0636   operator Matcher<T>() const {
0637     return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
0638   }
0639 
0640  private:
0641   template <typename T>
0642   class MonomorphicImpl : public MatcherInterface<T> {
0643    public:
0644     explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
0645 
0646     void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
0647 
0648     void DescribeNegationTo(::std::ostream* os) const override {
0649       impl_.DescribeNegationTo(os);
0650     }
0651 
0652     bool MatchAndExplain(T x, MatchResultListener* listener) const override {
0653       return impl_.MatchAndExplain(x, listener);
0654     }
0655 
0656    private:
0657     const Impl impl_;
0658   };
0659 
0660   Impl impl_;
0661 };
0662 
0663 // Creates a matcher from its implementation.
0664 // DEPRECATED: Especially in the generic code, prefer:
0665 //   Matcher<T>(new MyMatcherImpl<const T&>(...));
0666 //
0667 // MakeMatcher may create a Matcher that accepts its argument by value, which
0668 // leads to unnecessary copies & lack of support for non-copyable types.
0669 template <typename T>
0670 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
0671   return Matcher<T>(impl);
0672 }
0673 
0674 // Creates a polymorphic matcher from its implementation.  This is
0675 // easier to use than the PolymorphicMatcher<Impl> constructor as it
0676 // doesn't require you to explicitly write the template argument, e.g.
0677 //
0678 //   MakePolymorphicMatcher(foo);
0679 // vs
0680 //   PolymorphicMatcher<TypeOfFoo>(foo);
0681 template <class Impl>
0682 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
0683   return PolymorphicMatcher<Impl>(impl);
0684 }
0685 
0686 namespace internal {
0687 // Implements a matcher that compares a given value with a
0688 // pre-supplied value using one of the ==, <=, <, etc, operators.  The
0689 // two values being compared don't have to have the same type.
0690 //
0691 // The matcher defined here is polymorphic (for example, Eq(5) can be
0692 // used to match an int, a short, a double, etc).  Therefore we use
0693 // a template type conversion operator in the implementation.
0694 //
0695 // The following template definition assumes that the Rhs parameter is
0696 // a "bare" type (i.e. neither 'const T' nor 'T&').
0697 template <typename D, typename Rhs, typename Op>
0698 class [[nodiscard]] ComparisonBase {
0699  public:
0700   explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
0701 
0702   using is_gtest_matcher = void;
0703 
0704   template <typename Lhs>
0705   bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
0706     return Op()(lhs, Unwrap(rhs_));
0707   }
0708   void DescribeTo(std::ostream* os) const {
0709     *os << D::Desc() << " ";
0710     UniversalPrint(Unwrap(rhs_), os);
0711   }
0712   void DescribeNegationTo(std::ostream* os) const {
0713     *os << D::NegatedDesc() << " ";
0714     UniversalPrint(Unwrap(rhs_), os);
0715   }
0716 
0717  private:
0718   template <typename T>
0719   static const T& Unwrap(const T& v) {
0720     return v;
0721   }
0722   template <typename T>
0723   static const T& Unwrap(std::reference_wrapper<T> v) {
0724     return v;
0725   }
0726 
0727   Rhs rhs_;
0728 };
0729 
0730 template <typename Rhs>
0731 class [[nodiscard]] EqMatcher
0732     : public ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>> {
0733  public:
0734   explicit EqMatcher(const Rhs& rhs)
0735       : ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>>(rhs) {}
0736   static const char* Desc() { return "is equal to"; }
0737   static const char* NegatedDesc() { return "isn't equal to"; }
0738 };
0739 template <typename Rhs>
0740 class [[nodiscard]] NeMatcher
0741     : public ComparisonBase<NeMatcher<Rhs>, Rhs, std::not_equal_to<>> {
0742  public:
0743   explicit NeMatcher(const Rhs& rhs)
0744       : ComparisonBase<NeMatcher<Rhs>, Rhs, std::not_equal_to<>>(rhs) {}
0745   static const char* Desc() { return "isn't equal to"; }
0746   static const char* NegatedDesc() { return "is equal to"; }
0747 };
0748 template <typename Rhs>
0749 class [[nodiscard]] LtMatcher
0750     : public ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>> {
0751  public:
0752   explicit LtMatcher(const Rhs& rhs)
0753       : ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>>(rhs) {}
0754   static const char* Desc() { return "is <"; }
0755   static const char* NegatedDesc() { return "isn't <"; }
0756 };
0757 template <typename Rhs>
0758 class [[nodiscard]] GtMatcher
0759     : public ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>> {
0760  public:
0761   explicit GtMatcher(const Rhs& rhs)
0762       : ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>>(rhs) {}
0763   static const char* Desc() { return "is >"; }
0764   static const char* NegatedDesc() { return "isn't >"; }
0765 };
0766 template <typename Rhs>
0767 class [[nodiscard]] LeMatcher
0768     : public ComparisonBase<LeMatcher<Rhs>, Rhs, std::less_equal<>> {
0769  public:
0770   explicit LeMatcher(const Rhs& rhs)
0771       : ComparisonBase<LeMatcher<Rhs>, Rhs, std::less_equal<>>(rhs) {}
0772   static const char* Desc() { return "is <="; }
0773   static const char* NegatedDesc() { return "isn't <="; }
0774 };
0775 template <typename Rhs>
0776 class [[nodiscard]] GeMatcher
0777     : public ComparisonBase<GeMatcher<Rhs>, Rhs, std::greater_equal<>> {
0778  public:
0779   explicit GeMatcher(const Rhs& rhs)
0780       : ComparisonBase<GeMatcher<Rhs>, Rhs, std::greater_equal<>>(rhs) {}
0781   static const char* Desc() { return "is >="; }
0782   static const char* NegatedDesc() { return "isn't >="; }
0783 };
0784 
0785 // Same as `EqMatcher<Rhs>`, except that the `rhs` is stored as `StoredRhs` and
0786 // must be implicitly convertible to `Rhs`.
0787 template <typename Rhs, typename StoredRhs>
0788 class [[nodiscard]] ImplicitCastEqMatcher {
0789  public:
0790   explicit ImplicitCastEqMatcher(const StoredRhs& rhs) : stored_rhs_(rhs) {}
0791 
0792   using is_gtest_matcher = void;
0793 
0794   template <typename Lhs>
0795   bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
0796     return lhs == rhs();
0797   }
0798 
0799   void DescribeTo(std::ostream* os) const {
0800     *os << "is equal to ";
0801     UniversalPrint(rhs(), os);
0802   }
0803   void DescribeNegationTo(std::ostream* os) const {
0804     *os << "isn't equal to ";
0805     UniversalPrint(rhs(), os);
0806   }
0807 
0808  private:
0809   Rhs rhs() const { return ImplicitCast_<Rhs>(stored_rhs_); }
0810 
0811   StoredRhs stored_rhs_;
0812 };
0813 
0814 // Dummy function (never defined) whose return type evaluates to std::string if
0815 // the given type is a string-like type that can be converted to std::string,
0816 // either directly or through an intermediate std::string_view.
0817 template <class T>
0818 extern std::enable_if_t<std::is_constructible_v<std::string, T>, std::string>
0819 ResolveAsString(const void* /* preferred */);
0820 
0821 #if GTEST_HAS_STD_WSTRING
0822 // Same as above, but for std::wstring. In cases where both conversions are
0823 // possible, this overload takes lower priority.
0824 template <class T>
0825 extern std::enable_if_t<std::is_constructible_v<std::wstring, T>, std::wstring>
0826 ResolveAsString(... /* fallback */);
0827 #endif
0828 
0829 // Evaluates to the std::basic_string type that the given string-like type can
0830 // be converted to. Prefers std::string over std::wstring if both are possible.
0831 // Fails in a SFINAE-friendly way if no conversion was viable.
0832 template <typename T>
0833 using StringType = decltype(ResolveAsString<T>(nullptr));
0834 
0835 // Implements polymorphic matchers MatchesRegex(regex) and
0836 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
0837 // T can be converted to a string.
0838 class [[nodiscard]] MatchesRegexMatcher {
0839  public:
0840   MatchesRegexMatcher(const RE* regex, bool full_match)
0841       : regex_(regex), full_match_(full_match) {}
0842 
0843   bool MatchAndExplain(const internal::StringView& s,
0844                        MatchResultListener* listener) const {
0845     return MatchAndExplain(std::string(s), listener);
0846   }
0847 
0848   // Accepts pointer types, particularly:
0849   //   const char*
0850   //   char*
0851   //   const wchar_t*
0852   //   wchar_t*
0853   template <typename CharType>
0854   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
0855     return s != nullptr && MatchAndExplain(std::string(s), listener);
0856   }
0857 
0858   // Matches anything that can convert to std::string.
0859   //
0860   // This is a template, not just a plain function with const std::string&,
0861   // because std::string_view has some interfering non-explicit constructors.
0862   template <class MatcheeStringType>
0863   bool MatchAndExplain(const MatcheeStringType& s,
0864                        MatchResultListener* /* listener */) const {
0865     const std::string s2(s);
0866     return full_match_ ? RE::FullMatch(s2, *regex_)
0867                        : RE::PartialMatch(s2, *regex_);
0868   }
0869 
0870   void DescribeTo(::std::ostream* os) const {
0871     *os << (full_match_ ? "matches" : "contains") << " regular expression ";
0872     UniversalPrinter<std::string>::Print(regex_->pattern(), os);
0873   }
0874 
0875   void DescribeNegationTo(::std::ostream* os) const {
0876     *os << "doesn't " << (full_match_ ? "match" : "contain")
0877         << " regular expression ";
0878     UniversalPrinter<std::string>::Print(regex_->pattern(), os);
0879   }
0880 
0881  private:
0882   const std::shared_ptr<const RE> regex_;
0883   const bool full_match_;
0884 };
0885 }  // namespace internal
0886 
0887 // Matches a string that fully matches regular expression 'regex'.
0888 // The matcher takes ownership of 'regex'.
0889 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
0890     const internal::RE* regex) {
0891   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
0892 }
0893 template <typename T = std::string>
0894 std::enable_if_t<std::is_constructible_v<internal::RE, internal::StringType<T>>,
0895                  PolymorphicMatcher<internal::MatchesRegexMatcher>>
0896 MatchesRegex(const T& regex) {
0897   return MatchesRegex(new internal::RE(internal::StringType<T>(regex)));
0898 }
0899 
0900 // Matches a string that contains regular expression 'regex'.
0901 // The matcher takes ownership of 'regex'.
0902 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
0903     const internal::RE* regex) {
0904   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
0905 }
0906 template <typename T = std::string>
0907 std::enable_if_t<std::is_constructible_v<internal::RE, internal::StringType<T>>,
0908                  PolymorphicMatcher<internal::MatchesRegexMatcher>>
0909 ContainsRegex(const T& regex) {
0910   return ContainsRegex(new internal::RE(internal::StringType<T>(regex)));
0911 }
0912 
0913 // Creates a polymorphic matcher that matches anything equal to x.
0914 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
0915 // wouldn't compile.
0916 template <typename T>
0917 inline internal::EqMatcher<T> Eq(T x) {
0918   return internal::EqMatcher<T>(x);
0919 }
0920 
0921 // Constructs a Matcher<T> from a 'value' of type T. The constructed
0922 // matcher matches any value that's equal to 'value'.
0923 template <typename T>
0924 Matcher<T>::Matcher(T value) {
0925   *this = Eq(value);
0926 }
0927 
0928 // Constructs a Matcher<T> from nullptr. The constructed matcher matches any
0929 // value that is equal to nullptr.
0930 template <typename T>
0931 template <typename U>
0932 Matcher<T>::Matcher(U, std::enable_if_t<std::is_same_v<U, std::nullptr_t>>*) {
0933   *this = Eq(nullptr);
0934 }
0935 
0936 // Creates a monomorphic matcher that matches anything with type Lhs
0937 // and equal to rhs.  A user may need to use this instead of Eq(...)
0938 // in order to resolve an overloading ambiguity.
0939 //
0940 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
0941 // or Matcher<T>(x), but more readable than the latter.
0942 //
0943 // We could define similar monomorphic matchers for other comparison
0944 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
0945 // it yet as those are used much less than Eq() in practice.  A user
0946 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
0947 // for example.
0948 template <typename Lhs, typename Rhs>
0949 inline Matcher<Lhs> TypedEq(const Rhs& rhs) {
0950   return Eq(rhs);
0951 }
0952 
0953 // Creates a polymorphic matcher that matches anything >= x.
0954 template <typename Rhs>
0955 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
0956   return internal::GeMatcher<Rhs>(x);
0957 }
0958 
0959 // Creates a polymorphic matcher that matches anything > x.
0960 template <typename Rhs>
0961 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
0962   return internal::GtMatcher<Rhs>(x);
0963 }
0964 
0965 // Creates a polymorphic matcher that matches anything <= x.
0966 template <typename Rhs>
0967 inline internal::LeMatcher<Rhs> Le(Rhs x) {
0968   return internal::LeMatcher<Rhs>(x);
0969 }
0970 
0971 // Creates a polymorphic matcher that matches anything < x.
0972 template <typename Rhs>
0973 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
0974   return internal::LtMatcher<Rhs>(x);
0975 }
0976 
0977 // Creates a polymorphic matcher that matches anything != x.
0978 template <typename Rhs>
0979 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
0980   return internal::NeMatcher<Rhs>(x);
0981 }
0982 }  // namespace testing
0983 
0984 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251 5046
0985 
0986 #endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_