Update bundled GoogleTest to current HEAD
[alexxy/gromacs.git] / src / external / googletest / googletest / include / gtest / gtest-matchers.h
1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 // The Google C++ Testing and Mocking Framework (Google Test)
31 //
32 // This file implements just enough of the matcher interface to allow
33 // EXPECT_DEATH and friends to accept a matcher argument.
34
35 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
36 #define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
37
38 #include <atomic>
39 #include <memory>
40 #include <ostream>
41 #include <string>
42 #include <type_traits>
43
44 #include "gtest/gtest-printers.h"
45 #include "gtest/internal/gtest-internal.h"
46 #include "gtest/internal/gtest-port.h"
47
48 // MSVC warning C5046 is new as of VS2017 version 15.8.
49 #if defined(_MSC_VER) && _MSC_VER >= 1915
50 #define GTEST_MAYBE_5046_ 5046
51 #else
52 #define GTEST_MAYBE_5046_
53 #endif
54
55 GTEST_DISABLE_MSC_WARNINGS_PUSH_(
56     4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
57                               clients of class B */
58     /* Symbol involving type with internal linkage not defined */)
59
60 namespace testing {
61
62 // To implement a matcher Foo for type T, define:
63 //   1. a class FooMatcherMatcher that implements the matcher interface:
64 //     using is_gtest_matcher = void;
65 //     bool MatchAndExplain(const T&, std::ostream*);
66 //       (MatchResultListener* can also be used instead of std::ostream*)
67 //     void DescribeTo(std::ostream*);
68 //     void DescribeNegationTo(std::ostream*);
69 //
70 //   2. a factory function that creates a Matcher<T> object from a
71 //      FooMatcherMatcher.
72
73 class MatchResultListener {
74  public:
75   // Creates a listener object with the given underlying ostream.  The
76   // listener does not own the ostream, and does not dereference it
77   // in the constructor or destructor.
78   explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
79   virtual ~MatchResultListener() = 0;  // Makes this class abstract.
80
81   // Streams x to the underlying ostream; does nothing if the ostream
82   // is NULL.
83   template <typename T>
84   MatchResultListener& operator<<(const T& x) {
85     if (stream_ != nullptr) *stream_ << x;
86     return *this;
87   }
88
89   // Returns the underlying ostream.
90   ::std::ostream* stream() { return stream_; }
91
92   // Returns true if and only if the listener is interested in an explanation
93   // of the match result.  A matcher's MatchAndExplain() method can use
94   // this information to avoid generating the explanation when no one
95   // intends to hear it.
96   bool IsInterested() const { return stream_ != nullptr; }
97
98  private:
99   ::std::ostream* const stream_;
100
101   GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
102 };
103
104 inline MatchResultListener::~MatchResultListener() {
105 }
106
107 // An instance of a subclass of this knows how to describe itself as a
108 // matcher.
109 class GTEST_API_ MatcherDescriberInterface {
110  public:
111   virtual ~MatcherDescriberInterface() {}
112
113   // Describes this matcher to an ostream.  The function should print
114   // a verb phrase that describes the property a value matching this
115   // matcher should have.  The subject of the verb phrase is the value
116   // being matched.  For example, the DescribeTo() method of the Gt(7)
117   // matcher prints "is greater than 7".
118   virtual void DescribeTo(::std::ostream* os) const = 0;
119
120   // Describes the negation of this matcher to an ostream.  For
121   // example, if the description of this matcher is "is greater than
122   // 7", the negated description could be "is not greater than 7".
123   // You are not required to override this when implementing
124   // MatcherInterface, but it is highly advised so that your matcher
125   // can produce good error messages.
126   virtual void DescribeNegationTo(::std::ostream* os) const {
127     *os << "not (";
128     DescribeTo(os);
129     *os << ")";
130   }
131 };
132
133 // The implementation of a matcher.
134 template <typename T>
135 class MatcherInterface : public MatcherDescriberInterface {
136  public:
137   // Returns true if and only if the matcher matches x; also explains the
138   // match result to 'listener' if necessary (see the next paragraph), in
139   // the form of a non-restrictive relative clause ("which ...",
140   // "whose ...", etc) that describes x.  For example, the
141   // MatchAndExplain() method of the Pointee(...) matcher should
142   // generate an explanation like "which points to ...".
143   //
144   // Implementations of MatchAndExplain() should add an explanation of
145   // the match result *if and only if* they can provide additional
146   // information that's not already present (or not obvious) in the
147   // print-out of x and the matcher's description.  Whether the match
148   // succeeds is not a factor in deciding whether an explanation is
149   // needed, as sometimes the caller needs to print a failure message
150   // when the match succeeds (e.g. when the matcher is used inside
151   // Not()).
152   //
153   // For example, a "has at least 10 elements" matcher should explain
154   // what the actual element count is, regardless of the match result,
155   // as it is useful information to the reader; on the other hand, an
156   // "is empty" matcher probably only needs to explain what the actual
157   // size is when the match fails, as it's redundant to say that the
158   // size is 0 when the value is already known to be empty.
159   //
160   // You should override this method when defining a new matcher.
161   //
162   // It's the responsibility of the caller (Google Test) to guarantee
163   // that 'listener' is not NULL.  This helps to simplify a matcher's
164   // implementation when it doesn't care about the performance, as it
165   // can talk to 'listener' without checking its validity first.
166   // However, in order to implement dummy listeners efficiently,
167   // listener->stream() may be NULL.
168   virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
169
170   // Inherits these methods from MatcherDescriberInterface:
171   //   virtual void DescribeTo(::std::ostream* os) const = 0;
172   //   virtual void DescribeNegationTo(::std::ostream* os) const;
173 };
174
175 namespace internal {
176
177 struct AnyEq {
178   template <typename A, typename B>
179   bool operator()(const A& a, const B& b) const { return a == b; }
180 };
181 struct AnyNe {
182   template <typename A, typename B>
183   bool operator()(const A& a, const B& b) const { return a != b; }
184 };
185 struct AnyLt {
186   template <typename A, typename B>
187   bool operator()(const A& a, const B& b) const { return a < b; }
188 };
189 struct AnyGt {
190   template <typename A, typename B>
191   bool operator()(const A& a, const B& b) const { return a > b; }
192 };
193 struct AnyLe {
194   template <typename A, typename B>
195   bool operator()(const A& a, const B& b) const { return a <= b; }
196 };
197 struct AnyGe {
198   template <typename A, typename B>
199   bool operator()(const A& a, const B& b) const { return a >= b; }
200 };
201
202 // A match result listener that ignores the explanation.
203 class DummyMatchResultListener : public MatchResultListener {
204  public:
205   DummyMatchResultListener() : MatchResultListener(nullptr) {}
206
207  private:
208   GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
209 };
210
211 // A match result listener that forwards the explanation to a given
212 // ostream.  The difference between this and MatchResultListener is
213 // that the former is concrete.
214 class StreamMatchResultListener : public MatchResultListener {
215  public:
216   explicit StreamMatchResultListener(::std::ostream* os)
217       : MatchResultListener(os) {}
218
219  private:
220   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
221 };
222
223 struct SharedPayloadBase {
224   std::atomic<int> ref{1};
225   void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
226   bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
227 };
228
229 template <typename T>
230 struct SharedPayload : SharedPayloadBase {
231   explicit SharedPayload(const T& v) : value(v) {}
232   explicit SharedPayload(T&& v) : value(std::move(v)) {}
233
234   static void Destroy(SharedPayloadBase* shared) {
235     delete static_cast<SharedPayload*>(shared);
236   }
237
238   T value;
239 };
240
241 // An internal class for implementing Matcher<T>, which will derive
242 // from it.  We put functionalities common to all Matcher<T>
243 // specializations here to avoid code duplication.
244 template <typename T>
245 class MatcherBase : private MatcherDescriberInterface {
246  public:
247   // Returns true if and only if the matcher matches x; also explains the
248   // match result to 'listener'.
249   bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
250     GTEST_CHECK_(vtable_ != nullptr);
251     return vtable_->match_and_explain(*this, x, listener);
252   }
253
254   // Returns true if and only if this matcher matches x.
255   bool Matches(const T& x) const {
256     DummyMatchResultListener dummy;
257     return MatchAndExplain(x, &dummy);
258   }
259
260   // Describes this matcher to an ostream.
261   void DescribeTo(::std::ostream* os) const final {
262     GTEST_CHECK_(vtable_ != nullptr);
263     vtable_->describe(*this, os, false);
264   }
265
266   // Describes the negation of this matcher to an ostream.
267   void DescribeNegationTo(::std::ostream* os) const final {
268     GTEST_CHECK_(vtable_ != nullptr);
269     vtable_->describe(*this, os, true);
270   }
271
272   // Explains why x matches, or doesn't match, the matcher.
273   void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
274     StreamMatchResultListener listener(os);
275     MatchAndExplain(x, &listener);
276   }
277
278   // Returns the describer for this matcher object; retains ownership
279   // of the describer, which is only guaranteed to be alive when
280   // this matcher object is alive.
281   const MatcherDescriberInterface* GetDescriber() const {
282     if (vtable_ == nullptr) return nullptr;
283     return vtable_->get_describer(*this);
284   }
285
286  protected:
287   MatcherBase() : vtable_(nullptr) {}
288
289   // Constructs a matcher from its implementation.
290   template <typename U>
291   explicit MatcherBase(const MatcherInterface<U>* impl) {
292     Init(impl);
293   }
294
295   template <typename M, typename = typename std::remove_reference<
296                             M>::type::is_gtest_matcher>
297   MatcherBase(M&& m) {  // NOLINT
298     Init(std::forward<M>(m));
299   }
300
301   MatcherBase(const MatcherBase& other)
302       : vtable_(other.vtable_), buffer_(other.buffer_) {
303 #ifndef __clang_analyzer__
304     if (IsShared()) buffer_.shared->Ref();
305 #endif
306   }
307
308   MatcherBase& operator=(const MatcherBase& other) {
309     if (this == &other) return *this;
310     Destroy();
311     vtable_ = other.vtable_;
312     buffer_ = other.buffer_;
313     if (IsShared()) buffer_.shared->Ref();
314     return *this;
315   }
316
317   MatcherBase(MatcherBase&& other)
318       : vtable_(other.vtable_), buffer_(other.buffer_) {
319     other.vtable_ = nullptr;
320   }
321
322   MatcherBase& operator=(MatcherBase&& other) {
323     if (this == &other) return *this;
324     Destroy();
325     vtable_ = other.vtable_;
326     buffer_ = other.buffer_;
327     other.vtable_ = nullptr;
328     return *this;
329   }
330
331   ~MatcherBase() override { Destroy(); }
332
333  private:
334   struct VTable {
335     bool (*match_and_explain)(const MatcherBase&, const T&,
336                               MatchResultListener*);
337     void (*describe)(const MatcherBase&, std::ostream*, bool negation);
338     // Returns the captured object if it implements the interface, otherwise
339     // returns the MatcherBase itself.
340     const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
341     // Called on shared instances when the reference count reaches 0.
342     void (*shared_destroy)(SharedPayloadBase*);
343   };
344
345   bool IsShared() const {
346     return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
347   }
348
349   // If the implementation uses a listener, call that.
350   template <typename P>
351   static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
352                                   MatchResultListener* listener)
353       -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
354     return P::Get(m).MatchAndExplain(value, listener->stream());
355   }
356
357   template <typename P>
358   static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
359                                   MatchResultListener* listener)
360       -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
361     return P::Get(m).MatchAndExplain(value, listener);
362   }
363
364   template <typename P>
365   static void DescribeImpl(const MatcherBase& m, std::ostream* os,
366                            bool negation) {
367     if (negation) {
368       P::Get(m).DescribeNegationTo(os);
369     } else {
370       P::Get(m).DescribeTo(os);
371     }
372   }
373
374   template <typename P>
375   static const MatcherDescriberInterface* GetDescriberImpl(
376       const MatcherBase& m) {
377     // If the impl is a MatcherDescriberInterface, then return it.
378     // Otherwise use MatcherBase itself.
379     // This allows us to implement the GetDescriber() function without support
380     // from the impl, but some users really want to get their impl back when
381     // they call GetDescriber().
382     // We use std::get on a tuple as a workaround of not having `if constexpr`.
383     return std::get<(
384         std::is_convertible<decltype(&P::Get(m)),
385                             const MatcherDescriberInterface*>::value
386             ? 1
387             : 0)>(std::make_tuple(&m, &P::Get(m)));
388   }
389
390   template <typename P>
391   const VTable* GetVTable() {
392     static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
393                                        &DescribeImpl<P>, &GetDescriberImpl<P>,
394                                        P::shared_destroy};
395     return &kVTable;
396   }
397
398   union Buffer {
399     // Add some types to give Buffer some common alignment/size use cases.
400     void* ptr;
401     double d;
402     int64_t i;
403     // And add one for the out-of-line cases.
404     SharedPayloadBase* shared;
405   };
406
407   void Destroy() {
408 #ifndef __clang_analyzer__
409       if (IsShared() && buffer_.shared->Unref()) {
410       vtable_->shared_destroy(buffer_.shared);
411     }
412 #endif
413   }
414
415   template <typename M>
416   static constexpr bool IsInlined() {
417     return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
418            std::is_trivially_copy_constructible<M>::value &&
419            std::is_trivially_destructible<M>::value;
420   }
421
422   template <typename M, bool = MatcherBase::IsInlined<M>()>
423   struct ValuePolicy {
424     static const M& Get(const MatcherBase& m) {
425       // When inlined along with Init, need to be explicit to avoid violating
426       // strict aliasing rules.
427       const M *ptr = static_cast<const M*>(
428           static_cast<const void*>(&m.buffer_));
429       return *ptr;
430     }
431     static void Init(MatcherBase& m, M impl) {
432       ::new (static_cast<void*>(&m.buffer_)) M(impl);
433     }
434     static constexpr auto shared_destroy = nullptr;
435   };
436
437   template <typename M>
438   struct ValuePolicy<M, false> {
439     using Shared = SharedPayload<M>;
440     static const M& Get(const MatcherBase& m) {
441       return static_cast<Shared*>(m.buffer_.shared)->value;
442     }
443     template <typename Arg>
444     static void Init(MatcherBase& m, Arg&& arg) {
445       m.buffer_.shared = new Shared(std::forward<Arg>(arg));
446     }
447     static constexpr auto shared_destroy = &Shared::Destroy;
448   };
449
450   template <typename U, bool B>
451   struct ValuePolicy<const MatcherInterface<U>*, B> {
452     using M = const MatcherInterface<U>;
453     using Shared = SharedPayload<std::unique_ptr<M>>;
454     static const M& Get(const MatcherBase& m) {
455       return *static_cast<Shared*>(m.buffer_.shared)->value;
456     }
457     static void Init(MatcherBase& m, M* impl) {
458       m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
459     }
460
461     static constexpr auto shared_destroy = &Shared::Destroy;
462   };
463
464   template <typename M>
465   void Init(M&& m) {
466     using MM = typename std::decay<M>::type;
467     using Policy = ValuePolicy<MM>;
468     vtable_ = GetVTable<Policy>();
469     Policy::Init(*this, std::forward<M>(m));
470   }
471
472   const VTable* vtable_;
473   Buffer buffer_;
474 };
475
476 }  // namespace internal
477
478 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
479 // object that can check whether a value of type T matches.  The
480 // implementation of Matcher<T> is just a std::shared_ptr to const
481 // MatcherInterface<T>.  Don't inherit from Matcher!
482 template <typename T>
483 class Matcher : public internal::MatcherBase<T> {
484  public:
485   // Constructs a null matcher.  Needed for storing Matcher objects in STL
486   // containers.  A default-constructed matcher is not yet initialized.  You
487   // cannot use it until a valid value has been assigned to it.
488   explicit Matcher() {}  // NOLINT
489
490   // Constructs a matcher from its implementation.
491   explicit Matcher(const MatcherInterface<const T&>* impl)
492       : internal::MatcherBase<T>(impl) {}
493
494   template <typename U>
495   explicit Matcher(
496       const MatcherInterface<U>* impl,
497       typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
498           nullptr)
499       : internal::MatcherBase<T>(impl) {}
500
501   template <typename M, typename = typename std::remove_reference<
502                             M>::type::is_gtest_matcher>
503   Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {}  // NOLINT
504
505   // Implicit constructor here allows people to write
506   // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
507   Matcher(T value);  // NOLINT
508 };
509
510 // The following two specializations allow the user to write str
511 // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
512 // matcher is expected.
513 template <>
514 class GTEST_API_ Matcher<const std::string&>
515     : public internal::MatcherBase<const std::string&> {
516  public:
517   Matcher() {}
518
519   explicit Matcher(const MatcherInterface<const std::string&>* impl)
520       : internal::MatcherBase<const std::string&>(impl) {}
521
522   template <typename M, typename = typename std::remove_reference<
523                             M>::type::is_gtest_matcher>
524   Matcher(M&& m)  // NOLINT
525       : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
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   // Allows the user to write "foo" instead of Eq("foo") sometimes.
532   Matcher(const char* s);  // NOLINT
533 };
534
535 template <>
536 class GTEST_API_ Matcher<std::string>
537     : public internal::MatcherBase<std::string> {
538  public:
539   Matcher() {}
540
541   explicit Matcher(const MatcherInterface<const std::string&>* impl)
542       : internal::MatcherBase<std::string>(impl) {}
543   explicit Matcher(const MatcherInterface<std::string>* impl)
544       : internal::MatcherBase<std::string>(impl) {}
545
546   template <typename M, typename = typename std::remove_reference<
547                             M>::type::is_gtest_matcher>
548   Matcher(M&& m)  // NOLINT
549       : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
550
551   // Allows the user to write str instead of Eq(str) sometimes, where
552   // str is a string object.
553   Matcher(const std::string& s);  // NOLINT
554
555   // Allows the user to write "foo" instead of Eq("foo") sometimes.
556   Matcher(const char* s);  // NOLINT
557 };
558
559 #if GTEST_INTERNAL_HAS_STRING_VIEW
560 // The following two specializations allow the user to write str
561 // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
562 // matcher is expected.
563 template <>
564 class GTEST_API_ Matcher<const internal::StringView&>
565     : public internal::MatcherBase<const internal::StringView&> {
566  public:
567   Matcher() {}
568
569   explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
570       : internal::MatcherBase<const internal::StringView&>(impl) {}
571
572   template <typename M, typename = typename std::remove_reference<
573                             M>::type::is_gtest_matcher>
574   Matcher(M&& m)  // NOLINT
575       : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
576   }
577
578   // Allows the user to write str instead of Eq(str) sometimes, where
579   // str is a std::string object.
580   Matcher(const std::string& s);  // NOLINT
581
582   // Allows the user to write "foo" instead of Eq("foo") sometimes.
583   Matcher(const char* s);  // NOLINT
584
585   // Allows the user to pass absl::string_views or std::string_views directly.
586   Matcher(internal::StringView s);  // NOLINT
587 };
588
589 template <>
590 class GTEST_API_ Matcher<internal::StringView>
591     : public internal::MatcherBase<internal::StringView> {
592  public:
593   Matcher() {}
594
595   explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
596       : internal::MatcherBase<internal::StringView>(impl) {}
597   explicit Matcher(const MatcherInterface<internal::StringView>* impl)
598       : internal::MatcherBase<internal::StringView>(impl) {}
599
600   template <typename M, typename = typename std::remove_reference<
601                             M>::type::is_gtest_matcher>
602   Matcher(M&& m)  // NOLINT
603       : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
604
605   // Allows the user to write str instead of Eq(str) sometimes, where
606   // str is a std::string object.
607   Matcher(const std::string& s);  // NOLINT
608
609   // Allows the user to write "foo" instead of Eq("foo") sometimes.
610   Matcher(const char* s);  // NOLINT
611
612   // Allows the user to pass absl::string_views or std::string_views directly.
613   Matcher(internal::StringView s);  // NOLINT
614 };
615 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
616
617 // Prints a matcher in a human-readable format.
618 template <typename T>
619 std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
620   matcher.DescribeTo(&os);
621   return os;
622 }
623
624 // The PolymorphicMatcher class template makes it easy to implement a
625 // polymorphic matcher (i.e. a matcher that can match values of more
626 // than one type, e.g. Eq(n) and NotNull()).
627 //
628 // To define a polymorphic matcher, a user should provide an Impl
629 // class that has a DescribeTo() method and a DescribeNegationTo()
630 // method, and define a member function (or member function template)
631 //
632 //   bool MatchAndExplain(const Value& value,
633 //                        MatchResultListener* listener) const;
634 //
635 // See the definition of NotNull() for a complete example.
636 template <class Impl>
637 class PolymorphicMatcher {
638  public:
639   explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
640
641   // Returns a mutable reference to the underlying matcher
642   // implementation object.
643   Impl& mutable_impl() { return impl_; }
644
645   // Returns an immutable reference to the underlying matcher
646   // implementation object.
647   const Impl& impl() const { return impl_; }
648
649   template <typename T>
650   operator Matcher<T>() const {
651     return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
652   }
653
654  private:
655   template <typename T>
656   class MonomorphicImpl : public MatcherInterface<T> {
657    public:
658     explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
659
660     void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
661
662     void DescribeNegationTo(::std::ostream* os) const override {
663       impl_.DescribeNegationTo(os);
664     }
665
666     bool MatchAndExplain(T x, MatchResultListener* listener) const override {
667       return impl_.MatchAndExplain(x, listener);
668     }
669
670    private:
671     const Impl impl_;
672   };
673
674   Impl impl_;
675 };
676
677 // Creates a matcher from its implementation.
678 // DEPRECATED: Especially in the generic code, prefer:
679 //   Matcher<T>(new MyMatcherImpl<const T&>(...));
680 //
681 // MakeMatcher may create a Matcher that accepts its argument by value, which
682 // leads to unnecessary copies & lack of support for non-copyable types.
683 template <typename T>
684 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
685   return Matcher<T>(impl);
686 }
687
688 // Creates a polymorphic matcher from its implementation.  This is
689 // easier to use than the PolymorphicMatcher<Impl> constructor as it
690 // doesn't require you to explicitly write the template argument, e.g.
691 //
692 //   MakePolymorphicMatcher(foo);
693 // vs
694 //   PolymorphicMatcher<TypeOfFoo>(foo);
695 template <class Impl>
696 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
697   return PolymorphicMatcher<Impl>(impl);
698 }
699
700 namespace internal {
701 // Implements a matcher that compares a given value with a
702 // pre-supplied value using one of the ==, <=, <, etc, operators.  The
703 // two values being compared don't have to have the same type.
704 //
705 // The matcher defined here is polymorphic (for example, Eq(5) can be
706 // used to match an int, a short, a double, etc).  Therefore we use
707 // a template type conversion operator in the implementation.
708 //
709 // The following template definition assumes that the Rhs parameter is
710 // a "bare" type (i.e. neither 'const T' nor 'T&').
711 template <typename D, typename Rhs, typename Op>
712 class ComparisonBase {
713  public:
714   explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
715
716   using is_gtest_matcher = void;
717
718   template <typename Lhs>
719   bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
720     return Op()(lhs, Unwrap(rhs_));
721   }
722   void DescribeTo(std::ostream* os) const {
723     *os << D::Desc() << " ";
724     UniversalPrint(Unwrap(rhs_), os);
725   }
726   void DescribeNegationTo(std::ostream* os) const {
727     *os << D::NegatedDesc() << " ";
728     UniversalPrint(Unwrap(rhs_), os);
729   }
730
731  private:
732   template <typename T>
733   static const T& Unwrap(const T& v) {
734     return v;
735   }
736   template <typename T>
737   static const T& Unwrap(std::reference_wrapper<T> v) {
738     return v;
739   }
740
741   Rhs rhs_;
742 };
743
744 template <typename Rhs>
745 class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
746  public:
747   explicit EqMatcher(const Rhs& rhs)
748       : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
749   static const char* Desc() { return "is equal to"; }
750   static const char* NegatedDesc() { return "isn't equal to"; }
751 };
752 template <typename Rhs>
753 class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
754  public:
755   explicit NeMatcher(const Rhs& rhs)
756       : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
757   static const char* Desc() { return "isn't equal to"; }
758   static const char* NegatedDesc() { return "is equal to"; }
759 };
760 template <typename Rhs>
761 class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
762  public:
763   explicit LtMatcher(const Rhs& rhs)
764       : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
765   static const char* Desc() { return "is <"; }
766   static const char* NegatedDesc() { return "isn't <"; }
767 };
768 template <typename Rhs>
769 class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
770  public:
771   explicit GtMatcher(const Rhs& rhs)
772       : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
773   static const char* Desc() { return "is >"; }
774   static const char* NegatedDesc() { return "isn't >"; }
775 };
776 template <typename Rhs>
777 class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
778  public:
779   explicit LeMatcher(const Rhs& rhs)
780       : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
781   static const char* Desc() { return "is <="; }
782   static const char* NegatedDesc() { return "isn't <="; }
783 };
784 template <typename Rhs>
785 class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
786  public:
787   explicit GeMatcher(const Rhs& rhs)
788       : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
789   static const char* Desc() { return "is >="; }
790   static const char* NegatedDesc() { return "isn't >="; }
791 };
792
793 template <typename T, typename = typename std::enable_if<
794                           std::is_constructible<std::string, T>::value>::type>
795 using StringLike = T;
796
797 // Implements polymorphic matchers MatchesRegex(regex) and
798 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
799 // T can be converted to a string.
800 class MatchesRegexMatcher {
801  public:
802   MatchesRegexMatcher(const RE* regex, bool full_match)
803       : regex_(regex), full_match_(full_match) {}
804
805 #if GTEST_INTERNAL_HAS_STRING_VIEW
806   bool MatchAndExplain(const internal::StringView& s,
807                        MatchResultListener* listener) const {
808     return MatchAndExplain(std::string(s), listener);
809   }
810 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
811
812   // Accepts pointer types, particularly:
813   //   const char*
814   //   char*
815   //   const wchar_t*
816   //   wchar_t*
817   template <typename CharType>
818   bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
819     return s != nullptr && MatchAndExplain(std::string(s), listener);
820   }
821
822   // Matches anything that can convert to std::string.
823   //
824   // This is a template, not just a plain function with const std::string&,
825   // because absl::string_view has some interfering non-explicit constructors.
826   template <class MatcheeStringType>
827   bool MatchAndExplain(const MatcheeStringType& s,
828                        MatchResultListener* /* listener */) const {
829     const std::string& s2(s);
830     return full_match_ ? RE::FullMatch(s2, *regex_)
831                        : RE::PartialMatch(s2, *regex_);
832   }
833
834   void DescribeTo(::std::ostream* os) const {
835     *os << (full_match_ ? "matches" : "contains") << " regular expression ";
836     UniversalPrinter<std::string>::Print(regex_->pattern(), os);
837   }
838
839   void DescribeNegationTo(::std::ostream* os) const {
840     *os << "doesn't " << (full_match_ ? "match" : "contain")
841         << " regular expression ";
842     UniversalPrinter<std::string>::Print(regex_->pattern(), os);
843   }
844
845  private:
846   const std::shared_ptr<const RE> regex_;
847   const bool full_match_;
848 };
849 }  // namespace internal
850
851 // Matches a string that fully matches regular expression 'regex'.
852 // The matcher takes ownership of 'regex'.
853 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
854     const internal::RE* regex) {
855   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
856 }
857 template <typename T = std::string>
858 PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
859     const internal::StringLike<T>& regex) {
860   return MatchesRegex(new internal::RE(std::string(regex)));
861 }
862
863 // Matches a string that contains regular expression 'regex'.
864 // The matcher takes ownership of 'regex'.
865 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
866     const internal::RE* regex) {
867   return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
868 }
869 template <typename T = std::string>
870 PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
871     const internal::StringLike<T>& regex) {
872   return ContainsRegex(new internal::RE(std::string(regex)));
873 }
874
875 // Creates a polymorphic matcher that matches anything equal to x.
876 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
877 // wouldn't compile.
878 template <typename T>
879 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
880
881 // Constructs a Matcher<T> from a 'value' of type T.  The constructed
882 // matcher matches any value that's equal to 'value'.
883 template <typename T>
884 Matcher<T>::Matcher(T value) { *this = Eq(value); }
885
886 // Creates a monomorphic matcher that matches anything with type Lhs
887 // and equal to rhs.  A user may need to use this instead of Eq(...)
888 // in order to resolve an overloading ambiguity.
889 //
890 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
891 // or Matcher<T>(x), but more readable than the latter.
892 //
893 // We could define similar monomorphic matchers for other comparison
894 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
895 // it yet as those are used much less than Eq() in practice.  A user
896 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
897 // for example.
898 template <typename Lhs, typename Rhs>
899 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
900
901 // Creates a polymorphic matcher that matches anything >= x.
902 template <typename Rhs>
903 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
904   return internal::GeMatcher<Rhs>(x);
905 }
906
907 // Creates a polymorphic matcher that matches anything > x.
908 template <typename Rhs>
909 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
910   return internal::GtMatcher<Rhs>(x);
911 }
912
913 // Creates a polymorphic matcher that matches anything <= x.
914 template <typename Rhs>
915 inline internal::LeMatcher<Rhs> Le(Rhs x) {
916   return internal::LeMatcher<Rhs>(x);
917 }
918
919 // Creates a polymorphic matcher that matches anything < x.
920 template <typename Rhs>
921 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
922   return internal::LtMatcher<Rhs>(x);
923 }
924
925 // Creates a polymorphic matcher that matches anything != x.
926 template <typename Rhs>
927 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
928   return internal::NeMatcher<Rhs>(x);
929 }
930 }  // namespace testing
931
932 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251 5046
933
934 #endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_