Path: blob/main/contrib/googletest/googlemock/include/gmock/gmock-matchers.h
48375 views
// Copyright 2007, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// Google Mock - a framework for writing C++ mock classes.30//31// The MATCHER* family of macros can be used in a namespace scope to32// define custom matchers easily.33//34// Basic Usage35// ===========36//37// The syntax38//39// MATCHER(name, description_string) { statements; }40//41// defines a matcher with the given name that executes the statements,42// which must return a bool to indicate if the match succeeds. Inside43// the statements, you can refer to the value being matched by 'arg',44// and refer to its type by 'arg_type'.45//46// The description string documents what the matcher does, and is used47// to generate the failure message when the match fails. Since a48// MATCHER() is usually defined in a header file shared by multiple49// C++ source files, we require the description to be a C-string50// literal to avoid possible side effects. It can be empty, in which51// case we'll use the sequence of words in the matcher name as the52// description.53//54// For example:55//56// MATCHER(IsEven, "") { return (arg % 2) == 0; }57//58// allows you to write59//60// // Expects mock_foo.Bar(n) to be called where n is even.61// EXPECT_CALL(mock_foo, Bar(IsEven()));62//63// or,64//65// // Verifies that the value of some_expression is even.66// EXPECT_THAT(some_expression, IsEven());67//68// If the above assertion fails, it will print something like:69//70// Value of: some_expression71// Expected: is even72// Actual: 773//74// where the description "is even" is automatically calculated from the75// matcher name IsEven.76//77// Argument Type78// =============79//80// Note that the type of the value being matched (arg_type) is81// determined by the context in which you use the matcher and is82// supplied to you by the compiler, so you don't need to worry about83// declaring it (nor can you). This allows the matcher to be84// polymorphic. For example, IsEven() can be used to match any type85// where the value of "(arg % 2) == 0" can be implicitly converted to86// a bool. In the "Bar(IsEven())" example above, if method Bar()87// takes an int, 'arg_type' will be int; if it takes an unsigned long,88// 'arg_type' will be unsigned long; and so on.89//90// Parameterizing Matchers91// =======================92//93// Sometimes you'll want to parameterize the matcher. For that you94// can use another macro:95//96// MATCHER_P(name, param_name, description_string) { statements; }97//98// For example:99//100// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }101//102// will allow you to write:103//104// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));105//106// which may lead to this message (assuming n is 10):107//108// Value of: Blah("a")109// Expected: has absolute value 10110// Actual: -9111//112// Note that both the matcher description and its parameter are113// printed, making the message human-friendly.114//115// In the matcher definition body, you can write 'foo_type' to116// reference the type of a parameter named 'foo'. For example, in the117// body of MATCHER_P(HasAbsoluteValue, value) above, you can write118// 'value_type' to refer to the type of 'value'.119//120// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to121// support multi-parameter matchers.122//123// Describing Parameterized Matchers124// =================================125//126// The last argument to MATCHER*() is a string-typed expression. The127// expression can reference all of the matcher's parameters and a128// special bool-typed variable named 'negation'. When 'negation' is129// false, the expression should evaluate to the matcher's description;130// otherwise it should evaluate to the description of the negation of131// the matcher. For example,132//133// using testing::PrintToString;134//135// MATCHER_P2(InClosedRange, low, hi,136// std::string(negation ? "is not" : "is") + " in range [" +137// PrintToString(low) + ", " + PrintToString(hi) + "]") {138// return low <= arg && arg <= hi;139// }140// ...141// EXPECT_THAT(3, InClosedRange(4, 6));142// EXPECT_THAT(3, Not(InClosedRange(2, 4)));143//144// would generate two failures that contain the text:145//146// Expected: is in range [4, 6]147// ...148// Expected: is not in range [2, 4]149//150// If you specify "" as the description, the failure message will151// contain the sequence of words in the matcher name followed by the152// parameter values printed as a tuple. For example,153//154// MATCHER_P2(InClosedRange, low, hi, "") { ... }155// ...156// EXPECT_THAT(3, InClosedRange(4, 6));157// EXPECT_THAT(3, Not(InClosedRange(2, 4)));158//159// would generate two failures that contain the text:160//161// Expected: in closed range (4, 6)162// ...163// Expected: not (in closed range (2, 4))164//165// Types of Matcher Parameters166// ===========================167//168// For the purpose of typing, you can view169//170// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }171//172// as shorthand for173//174// template <typename p1_type, ..., typename pk_type>175// FooMatcherPk<p1_type, ..., pk_type>176// Foo(p1_type p1, ..., pk_type pk) { ... }177//178// When you write Foo(v1, ..., vk), the compiler infers the types of179// the parameters v1, ..., and vk for you. If you are not happy with180// the result of the type inference, you can specify the types by181// explicitly instantiating the template, as in Foo<long, bool>(5,182// false). As said earlier, you don't get to (or need to) specify183// 'arg_type' as that's determined by the context in which the matcher184// is used. You can assign the result of expression Foo(p1, ..., pk)185// to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This186// can be useful when composing matchers.187//188// While you can instantiate a matcher template with reference types,189// passing the parameters by pointer usually makes your code more190// readable. If, however, you still want to pass a parameter by191// reference, be aware that in the failure message generated by the192// matcher you will see the value of the referenced object but not its193// address.194//195// Explaining Match Results196// ========================197//198// Sometimes the matcher description alone isn't enough to explain why199// the match has failed or succeeded. For example, when expecting a200// long string, it can be very helpful to also print the diff between201// the expected string and the actual one. To achieve that, you can202// optionally stream additional information to a special variable203// named result_listener, whose type is a pointer to class204// MatchResultListener:205//206// MATCHER_P(EqualsLongString, str, "") {207// if (arg == str) return true;208//209// *result_listener << "the difference: "210/// << DiffStrings(str, arg);211// return false;212// }213//214// Overloading Matchers215// ====================216//217// You can overload matchers with different numbers of parameters:218//219// MATCHER_P(Blah, a, description_string1) { ... }220// MATCHER_P2(Blah, a, b, description_string2) { ... }221//222// Caveats223// =======224//225// When defining a new matcher, you should also consider implementing226// MatcherInterface or using MakePolymorphicMatcher(). These227// approaches require more work than the MATCHER* macros, but also228// give you more control on the types of the value being matched and229// the matcher parameters, which may leads to better compiler error230// messages when the matcher is used wrong. They also allow231// overloading matchers based on parameter types (as opposed to just232// based on the number of parameters).233//234// MATCHER*() can only be used in a namespace scope as templates cannot be235// declared inside of a local class.236//237// More Information238// ================239//240// To learn more about using these macros, please search for 'MATCHER'241// on242// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md243//244// This file also implements some commonly used argument matchers. More245// matchers can be defined by the user implementing the246// MatcherInterface<T> interface if necessary.247//248// See googletest/include/gtest/gtest-matchers.h for the definition of class249// Matcher, class MatcherInterface, and others.250251// IWYU pragma: private, include "gmock/gmock.h"252// IWYU pragma: friend gmock/.*253254#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_255#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_256257#include <algorithm>258#include <cmath>259#include <exception>260#include <functional>261#include <initializer_list>262#include <ios>263#include <iterator>264#include <limits>265#include <memory>266#include <ostream> // NOLINT267#include <sstream>268#include <string>269#include <type_traits>270#include <utility>271#include <vector>272273#include "gmock/internal/gmock-internal-utils.h"274#include "gmock/internal/gmock-port.h"275#include "gmock/internal/gmock-pp.h"276#include "gtest/gtest.h"277278// MSVC warning C5046 is new as of VS2017 version 15.8.279#if defined(_MSC_VER) && _MSC_VER >= 1915280#define GMOCK_MAYBE_5046_ 5046281#else282#define GMOCK_MAYBE_5046_283#endif284285GTEST_DISABLE_MSC_WARNINGS_PUSH_(2864251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by287clients of class B */288/* Symbol involving type with internal linkage not defined */)289290namespace testing {291292// To implement a matcher Foo for type T, define:293// 1. a class FooMatcherImpl that implements the294// MatcherInterface<T> interface, and295// 2. a factory function that creates a Matcher<T> object from a296// FooMatcherImpl*.297//298// The two-level delegation design makes it possible to allow a user299// to write "v" instead of "Eq(v)" where a Matcher is expected, which300// is impossible if we pass matchers by pointers. It also eases301// ownership management as Matcher objects can now be copied like302// plain values.303304// A match result listener that stores the explanation in a string.305class StringMatchResultListener : public MatchResultListener {306public:307StringMatchResultListener() : MatchResultListener(&ss_) {}308309// Returns the explanation accumulated so far.310std::string str() const { return ss_.str(); }311312// Clears the explanation accumulated so far.313void Clear() { ss_.str(""); }314315private:316::std::stringstream ss_;317318StringMatchResultListener(const StringMatchResultListener&) = delete;319StringMatchResultListener& operator=(const StringMatchResultListener&) =320delete;321};322323// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION324// and MUST NOT BE USED IN USER CODE!!!325namespace internal {326327// The MatcherCastImpl class template is a helper for implementing328// MatcherCast(). We need this helper in order to partially329// specialize the implementation of MatcherCast() (C++ allows330// class/struct templates to be partially specialized, but not331// function templates.).332333// This general version is used when MatcherCast()'s argument is a334// polymorphic matcher (i.e. something that can be converted to a335// Matcher but is not one yet; for example, Eq(value)) or a value (for336// example, "hello").337template <typename T, typename M>338class MatcherCastImpl {339public:340static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {341// M can be a polymorphic matcher, in which case we want to use342// its conversion operator to create Matcher<T>. Or it can be a value343// that should be passed to the Matcher<T>'s constructor.344//345// We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a346// polymorphic matcher because it'll be ambiguous if T has an implicit347// constructor from M (this usually happens when T has an implicit348// constructor from any type).349//350// It won't work to unconditionally implicit_cast351// polymorphic_matcher_or_value to Matcher<T> because it won't trigger352// a user-defined conversion from M to T if one exists (assuming M is353// a value).354return CastImpl(polymorphic_matcher_or_value,355std::is_convertible<M, Matcher<T>>{},356std::is_convertible<M, T>{});357}358359private:360template <bool Ignore>361static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,362std::true_type /* convertible_to_matcher */,363std::integral_constant<bool, Ignore>) {364// M is implicitly convertible to Matcher<T>, which means that either365// M is a polymorphic matcher or Matcher<T> has an implicit constructor366// from M. In both cases using the implicit conversion will produce a367// matcher.368//369// Even if T has an implicit constructor from M, it won't be called because370// creating Matcher<T> would require a chain of two user-defined conversions371// (first to create T from M and then to create Matcher<T> from T).372return polymorphic_matcher_or_value;373}374375// M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic376// matcher. It's a value of a type implicitly convertible to T. Use direct377// initialization to create a matcher.378static Matcher<T> CastImpl(const M& value,379std::false_type /* convertible_to_matcher */,380std::true_type /* convertible_to_T */) {381return Matcher<T>(ImplicitCast_<T>(value));382}383384// M can't be implicitly converted to either Matcher<T> or T. Attempt to use385// polymorphic matcher Eq(value) in this case.386//387// Note that we first attempt to perform an implicit cast on the value and388// only fall back to the polymorphic Eq() matcher afterwards because the389// latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end390// which might be undefined even when Rhs is implicitly convertible to Lhs391// (e.g. std::pair<const int, int> vs. std::pair<int, int>).392//393// We don't define this method inline as we need the declaration of Eq().394static Matcher<T> CastImpl(const M& value,395std::false_type /* convertible_to_matcher */,396std::false_type /* convertible_to_T */);397};398399// This more specialized version is used when MatcherCast()'s argument400// is already a Matcher. This only compiles when type T can be401// statically converted to type U.402template <typename T, typename U>403class MatcherCastImpl<T, Matcher<U>> {404public:405static Matcher<T> Cast(const Matcher<U>& source_matcher) {406return Matcher<T>(new Impl(source_matcher));407}408409private:410class Impl : public MatcherInterface<T> {411public:412explicit Impl(const Matcher<U>& source_matcher)413: source_matcher_(source_matcher) {}414415// We delegate the matching logic to the source matcher.416bool MatchAndExplain(T x, MatchResultListener* listener) const override {417using FromType = typename std::remove_cv<typename std::remove_pointer<418typename std::remove_reference<T>::type>::type>::type;419using ToType = typename std::remove_cv<typename std::remove_pointer<420typename std::remove_reference<U>::type>::type>::type;421// Do not allow implicitly converting base*/& to derived*/&.422static_assert(423// Do not trigger if only one of them is a pointer. That implies a424// regular conversion and not a down_cast.425(std::is_pointer<typename std::remove_reference<T>::type>::value !=426std::is_pointer<typename std::remove_reference<U>::type>::value) ||427std::is_same<FromType, ToType>::value ||428!std::is_base_of<FromType, ToType>::value,429"Can't implicitly convert from <base> to <derived>");430431// Do the cast to `U` explicitly if necessary.432// Otherwise, let implicit conversions do the trick.433using CastType =434typename std::conditional<std::is_convertible<T&, const U&>::value,435T&, U>::type;436437return source_matcher_.MatchAndExplain(static_cast<CastType>(x),438listener);439}440441void DescribeTo(::std::ostream* os) const override {442source_matcher_.DescribeTo(os);443}444445void DescribeNegationTo(::std::ostream* os) const override {446source_matcher_.DescribeNegationTo(os);447}448449private:450const Matcher<U> source_matcher_;451};452};453454// This even more specialized version is used for efficiently casting455// a matcher to its own type.456template <typename T>457class MatcherCastImpl<T, Matcher<T>> {458public:459static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }460};461462// Template specialization for parameterless Matcher.463template <typename Derived>464class MatcherBaseImpl {465public:466MatcherBaseImpl() = default;467468template <typename T>469operator ::testing::Matcher<T>() const { // NOLINT(runtime/explicit)470return ::testing::Matcher<T>(new471typename Derived::template gmock_Impl<T>());472}473};474475// Template specialization for Matcher with parameters.476template <template <typename...> class Derived, typename... Ts>477class MatcherBaseImpl<Derived<Ts...>> {478public:479// Mark the constructor explicit for single argument T to avoid implicit480// conversions.481template <typename E = std::enable_if<sizeof...(Ts) == 1>,482typename E::type* = nullptr>483explicit MatcherBaseImpl(Ts... params)484: params_(std::forward<Ts>(params)...) {}485template <typename E = std::enable_if<sizeof...(Ts) != 1>,486typename = typename E::type>487MatcherBaseImpl(Ts... params) // NOLINT488: params_(std::forward<Ts>(params)...) {}489490template <typename F>491operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit)492return Apply<F>(std::make_index_sequence<sizeof...(Ts)>{});493}494495private:496template <typename F, std::size_t... tuple_ids>497::testing::Matcher<F> Apply(std::index_sequence<tuple_ids...>) const {498return ::testing::Matcher<F>(499new typename Derived<Ts...>::template gmock_Impl<F>(500std::get<tuple_ids>(params_)...));501}502503const std::tuple<Ts...> params_;504};505506} // namespace internal507508// In order to be safe and clear, casting between different matcher509// types is done explicitly via MatcherCast<T>(m), which takes a510// matcher m and returns a Matcher<T>. It compiles only when T can be511// statically converted to the argument type of m.512template <typename T, typename M>513inline Matcher<T> MatcherCast(const M& matcher) {514return internal::MatcherCastImpl<T, M>::Cast(matcher);515}516517// This overload handles polymorphic matchers and values only since518// monomorphic matchers are handled by the next one.519template <typename T, typename M>520inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) {521return MatcherCast<T>(polymorphic_matcher_or_value);522}523524// This overload handles monomorphic matchers.525//526// In general, if type T can be implicitly converted to type U, we can527// safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is528// contravariant): just keep a copy of the original Matcher<U>, convert the529// argument from type T to U, and then pass it to the underlying Matcher<U>.530// The only exception is when U is a reference and T is not, as the531// underlying Matcher<U> may be interested in the argument's address, which532// is not preserved in the conversion from T to U.533template <typename T, typename U>534inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {535// Enforce that T can be implicitly converted to U.536static_assert(std::is_convertible<const T&, const U&>::value,537"T must be implicitly convertible to U");538// Enforce that we are not converting a non-reference type T to a reference539// type U.540static_assert(std::is_reference<T>::value || !std::is_reference<U>::value,541"cannot convert non reference arg to reference");542// In case both T and U are arithmetic types, enforce that the543// conversion is not lossy.544typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;545typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;546constexpr bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;547constexpr bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;548static_assert(549kTIsOther || kUIsOther ||550(internal::LosslessArithmeticConvertible<RawT, RawU>::value),551"conversion of arithmetic types must be lossless");552return MatcherCast<T>(matcher);553}554555// A<T>() returns a matcher that matches any value of type T.556template <typename T>557Matcher<T> A();558559// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION560// and MUST NOT BE USED IN USER CODE!!!561namespace internal {562563// If the explanation is not empty, prints it to the ostream.564inline void PrintIfNotEmpty(const std::string& explanation,565::std::ostream* os) {566if (!explanation.empty() && os != nullptr) {567*os << ", " << explanation;568}569}570571// Returns true if the given type name is easy to read by a human.572// This is used to decide whether printing the type of a value might573// be helpful.574inline bool IsReadableTypeName(const std::string& type_name) {575// We consider a type name readable if it's short or doesn't contain576// a template or function type.577return (type_name.length() <= 20 ||578type_name.find_first_of("<(") == std::string::npos);579}580581// Matches the value against the given matcher, prints the value and explains582// the match result to the listener. Returns the match result.583// 'listener' must not be NULL.584// Value cannot be passed by const reference, because some matchers take a585// non-const argument.586template <typename Value, typename T>587bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,588MatchResultListener* listener) {589if (!listener->IsInterested()) {590// If the listener is not interested, we do not need to construct the591// inner explanation.592return matcher.Matches(value);593}594595StringMatchResultListener inner_listener;596const bool match = matcher.MatchAndExplain(value, &inner_listener);597598UniversalPrint(value, listener->stream());599#if GTEST_HAS_RTTI600const std::string& type_name = GetTypeName<Value>();601if (IsReadableTypeName(type_name))602*listener->stream() << " (of type " << type_name << ")";603#endif604PrintIfNotEmpty(inner_listener.str(), listener->stream());605606return match;607}608609// An internal helper class for doing compile-time loop on a tuple's610// fields.611template <size_t N>612class TuplePrefix {613public:614// TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true615// if and only if the first N fields of matcher_tuple matches616// the first N fields of value_tuple, respectively.617template <typename MatcherTuple, typename ValueTuple>618static bool Matches(const MatcherTuple& matcher_tuple,619const ValueTuple& value_tuple) {620return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) &&621std::get<N - 1>(matcher_tuple).Matches(std::get<N - 1>(value_tuple));622}623624// TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)625// describes failures in matching the first N fields of matchers626// against the first N fields of values. If there is no failure,627// nothing will be streamed to os.628template <typename MatcherTuple, typename ValueTuple>629static void ExplainMatchFailuresTo(const MatcherTuple& matchers,630const ValueTuple& values,631::std::ostream* os) {632// First, describes failures in the first N - 1 fields.633TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);634635// Then describes the failure (if any) in the (N - 1)-th (0-based)636// field.637typename std::tuple_element<N - 1, MatcherTuple>::type matcher =638std::get<N - 1>(matchers);639typedef typename std::tuple_element<N - 1, ValueTuple>::type Value;640const Value& value = std::get<N - 1>(values);641StringMatchResultListener listener;642if (!matcher.MatchAndExplain(value, &listener)) {643*os << " Expected arg #" << N - 1 << ": ";644std::get<N - 1>(matchers).DescribeTo(os);645*os << "\n Actual: ";646// We remove the reference in type Value to prevent the647// universal printer from printing the address of value, which648// isn't interesting to the user most of the time. The649// matcher's MatchAndExplain() method handles the case when650// the address is interesting.651internal::UniversalPrint(value, os);652PrintIfNotEmpty(listener.str(), os);653*os << "\n";654}655}656};657658// The base case.659template <>660class TuplePrefix<0> {661public:662template <typename MatcherTuple, typename ValueTuple>663static bool Matches(const MatcherTuple& /* matcher_tuple */,664const ValueTuple& /* value_tuple */) {665return true;666}667668template <typename MatcherTuple, typename ValueTuple>669static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,670const ValueTuple& /* values */,671::std::ostream* /* os */) {}672};673674// TupleMatches(matcher_tuple, value_tuple) returns true if and only if675// all matchers in matcher_tuple match the corresponding fields in676// value_tuple. It is a compiler error if matcher_tuple and677// value_tuple have different number of fields or incompatible field678// types.679template <typename MatcherTuple, typename ValueTuple>680bool TupleMatches(const MatcherTuple& matcher_tuple,681const ValueTuple& value_tuple) {682// Makes sure that matcher_tuple and value_tuple have the same683// number of fields.684static_assert(std::tuple_size<MatcherTuple>::value ==685std::tuple_size<ValueTuple>::value,686"matcher and value have different numbers of fields");687return TuplePrefix<std::tuple_size<ValueTuple>::value>::Matches(matcher_tuple,688value_tuple);689}690691// Describes failures in matching matchers against values. If there692// is no failure, nothing will be streamed to os.693template <typename MatcherTuple, typename ValueTuple>694void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,695const ValueTuple& values, ::std::ostream* os) {696TuplePrefix<std::tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(697matchers, values, os);698}699700// TransformTupleValues and its helper.701//702// TransformTupleValuesHelper hides the internal machinery that703// TransformTupleValues uses to implement a tuple traversal.704template <typename Tuple, typename Func, typename OutIter>705class TransformTupleValuesHelper {706private:707typedef ::std::tuple_size<Tuple> TupleSize;708709public:710// For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.711// Returns the final value of 'out' in case the caller needs it.712static OutIter Run(Func f, const Tuple& t, OutIter out) {713return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);714}715716private:717template <typename Tup, size_t kRemainingSize>718struct IterateOverTuple {719OutIter operator()(Func f, const Tup& t, OutIter out) const {720*out++ = f(::std::get<TupleSize::value - kRemainingSize>(t));721return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);722}723};724template <typename Tup>725struct IterateOverTuple<Tup, 0> {726OutIter operator()(Func /* f */, const Tup& /* t */, OutIter out) const {727return out;728}729};730};731732// Successively invokes 'f(element)' on each element of the tuple 't',733// appending each result to the 'out' iterator. Returns the final value734// of 'out'.735template <typename Tuple, typename Func, typename OutIter>736OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {737return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);738}739740// Implements _, a matcher that matches any value of any741// type. This is a polymorphic matcher, so we need a template type742// conversion operator to make it appearing as a Matcher<T> for any743// type T.744class AnythingMatcher {745public:746using is_gtest_matcher = void;747748template <typename T>749bool MatchAndExplain(const T& /* x */, std::ostream* /* listener */) const {750return true;751}752void DescribeTo(std::ostream* os) const { *os << "is anything"; }753void DescribeNegationTo(::std::ostream* os) const {754// This is mostly for completeness' sake, as it's not very useful755// to write Not(A<bool>()). However we cannot completely rule out756// such a possibility, and it doesn't hurt to be prepared.757*os << "never matches";758}759};760761// Implements the polymorphic IsNull() matcher, which matches any raw or smart762// pointer that is NULL.763class IsNullMatcher {764public:765template <typename Pointer>766bool MatchAndExplain(const Pointer& p,767MatchResultListener* /* listener */) const {768return p == nullptr;769}770771void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }772void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NULL"; }773};774775// Implements the polymorphic NotNull() matcher, which matches any raw or smart776// pointer that is not NULL.777class NotNullMatcher {778public:779template <typename Pointer>780bool MatchAndExplain(const Pointer& p,781MatchResultListener* /* listener */) const {782return p != nullptr;783}784785void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }786void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; }787};788789// Ref(variable) matches any argument that is a reference to790// 'variable'. This matcher is polymorphic as it can match any791// super type of the type of 'variable'.792//793// The RefMatcher template class implements Ref(variable). It can794// only be instantiated with a reference type. This prevents a user795// from mistakenly using Ref(x) to match a non-reference function796// argument. For example, the following will righteously cause a797// compiler error:798//799// int n;800// Matcher<int> m1 = Ref(n); // This won't compile.801// Matcher<int&> m2 = Ref(n); // This will compile.802template <typename T>803class RefMatcher;804805template <typename T>806class RefMatcher<T&> {807// Google Mock is a generic framework and thus needs to support808// mocking any function types, including those that take non-const809// reference arguments. Therefore the template parameter T (and810// Super below) can be instantiated to either a const type or a811// non-const type.812public:813// RefMatcher() takes a T& instead of const T&, as we want the814// compiler to catch using Ref(const_value) as a matcher for a815// non-const reference.816explicit RefMatcher(T& x) : object_(x) {} // NOLINT817818template <typename Super>819operator Matcher<Super&>() const {820// By passing object_ (type T&) to Impl(), which expects a Super&,821// we make sure that Super is a super type of T. In particular,822// this catches using Ref(const_value) as a matcher for a823// non-const reference, as you cannot implicitly convert a const824// reference to a non-const reference.825return MakeMatcher(new Impl<Super>(object_));826}827828private:829template <typename Super>830class Impl : public MatcherInterface<Super&> {831public:832explicit Impl(Super& x) : object_(x) {} // NOLINT833834// MatchAndExplain() takes a Super& (as opposed to const Super&)835// in order to match the interface MatcherInterface<Super&>.836bool MatchAndExplain(Super& x,837MatchResultListener* listener) const override {838*listener << "which is located @" << static_cast<const void*>(&x);839return &x == &object_;840}841842void DescribeTo(::std::ostream* os) const override {843*os << "references the variable ";844UniversalPrinter<Super&>::Print(object_, os);845}846847void DescribeNegationTo(::std::ostream* os) const override {848*os << "does not reference the variable ";849UniversalPrinter<Super&>::Print(object_, os);850}851852private:853const Super& object_;854};855856T& object_;857};858859// Polymorphic helper functions for narrow and wide string matchers.860inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {861return String::CaseInsensitiveCStringEquals(lhs, rhs);862}863864inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,865const wchar_t* rhs) {866return String::CaseInsensitiveWideCStringEquals(lhs, rhs);867}868869// String comparison for narrow or wide strings that can have embedded NUL870// characters.871template <typename StringType>872bool CaseInsensitiveStringEquals(const StringType& s1, const StringType& s2) {873// Are the heads equal?874if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {875return false;876}877878// Skip the equal heads.879const typename StringType::value_type nul = 0;880const size_t i1 = s1.find(nul), i2 = s2.find(nul);881882// Are we at the end of either s1 or s2?883if (i1 == StringType::npos || i2 == StringType::npos) {884return i1 == i2;885}886887// Are the tails equal?888return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));889}890891// String matchers.892893// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.894template <typename StringType>895class StrEqualityMatcher {896public:897StrEqualityMatcher(StringType str, bool expect_eq, bool case_sensitive)898: string_(std::move(str)),899expect_eq_(expect_eq),900case_sensitive_(case_sensitive) {}901902#if GTEST_INTERNAL_HAS_STRING_VIEW903bool MatchAndExplain(const internal::StringView& s,904MatchResultListener* listener) const {905// This should fail to compile if StringView is used with wide906// strings.907const StringType& str = std::string(s);908return MatchAndExplain(str, listener);909}910#endif // GTEST_INTERNAL_HAS_STRING_VIEW911912// Accepts pointer types, particularly:913// const char*914// char*915// const wchar_t*916// wchar_t*917template <typename CharType>918bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {919if (s == nullptr) {920return !expect_eq_;921}922return MatchAndExplain(StringType(s), listener);923}924925// Matches anything that can convert to StringType.926//927// This is a template, not just a plain function with const StringType&,928// because StringView has some interfering non-explicit constructors.929template <typename MatcheeStringType>930bool MatchAndExplain(const MatcheeStringType& s,931MatchResultListener* /* listener */) const {932const StringType s2(s);933const bool eq = case_sensitive_ ? s2 == string_934: CaseInsensitiveStringEquals(s2, string_);935return expect_eq_ == eq;936}937938void DescribeTo(::std::ostream* os) const {939DescribeToHelper(expect_eq_, os);940}941942void DescribeNegationTo(::std::ostream* os) const {943DescribeToHelper(!expect_eq_, os);944}945946private:947void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {948*os << (expect_eq ? "is " : "isn't ");949*os << "equal to ";950if (!case_sensitive_) {951*os << "(ignoring case) ";952}953UniversalPrint(string_, os);954}955956const StringType string_;957const bool expect_eq_;958const bool case_sensitive_;959};960961// Implements the polymorphic HasSubstr(substring) matcher, which962// can be used as a Matcher<T> as long as T can be converted to a963// string.964template <typename StringType>965class HasSubstrMatcher {966public:967explicit HasSubstrMatcher(const StringType& substring)968: substring_(substring) {}969970#if GTEST_INTERNAL_HAS_STRING_VIEW971bool MatchAndExplain(const internal::StringView& s,972MatchResultListener* listener) const {973// This should fail to compile if StringView is used with wide974// strings.975const StringType& str = std::string(s);976return MatchAndExplain(str, listener);977}978#endif // GTEST_INTERNAL_HAS_STRING_VIEW979980// Accepts pointer types, particularly:981// const char*982// char*983// const wchar_t*984// wchar_t*985template <typename CharType>986bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {987return s != nullptr && MatchAndExplain(StringType(s), listener);988}989990// Matches anything that can convert to StringType.991//992// This is a template, not just a plain function with const StringType&,993// because StringView has some interfering non-explicit constructors.994template <typename MatcheeStringType>995bool MatchAndExplain(const MatcheeStringType& s,996MatchResultListener* /* listener */) const {997return StringType(s).find(substring_) != StringType::npos;998}9991000// Describes what this matcher matches.1001void DescribeTo(::std::ostream* os) const {1002*os << "has substring ";1003UniversalPrint(substring_, os);1004}10051006void DescribeNegationTo(::std::ostream* os) const {1007*os << "has no substring ";1008UniversalPrint(substring_, os);1009}10101011private:1012const StringType substring_;1013};10141015// Implements the polymorphic StartsWith(substring) matcher, which1016// can be used as a Matcher<T> as long as T can be converted to a1017// string.1018template <typename StringType>1019class StartsWithMatcher {1020public:1021explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {}10221023#if GTEST_INTERNAL_HAS_STRING_VIEW1024bool MatchAndExplain(const internal::StringView& s,1025MatchResultListener* listener) const {1026// This should fail to compile if StringView is used with wide1027// strings.1028const StringType& str = std::string(s);1029return MatchAndExplain(str, listener);1030}1031#endif // GTEST_INTERNAL_HAS_STRING_VIEW10321033// Accepts pointer types, particularly:1034// const char*1035// char*1036// const wchar_t*1037// wchar_t*1038template <typename CharType>1039bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {1040return s != nullptr && MatchAndExplain(StringType(s), listener);1041}10421043// Matches anything that can convert to StringType.1044//1045// This is a template, not just a plain function with const StringType&,1046// because StringView has some interfering non-explicit constructors.1047template <typename MatcheeStringType>1048bool MatchAndExplain(const MatcheeStringType& s,1049MatchResultListener* /* listener */) const {1050const StringType s2(s);1051return s2.length() >= prefix_.length() &&1052s2.substr(0, prefix_.length()) == prefix_;1053}10541055void DescribeTo(::std::ostream* os) const {1056*os << "starts with ";1057UniversalPrint(prefix_, os);1058}10591060void DescribeNegationTo(::std::ostream* os) const {1061*os << "doesn't start with ";1062UniversalPrint(prefix_, os);1063}10641065private:1066const StringType prefix_;1067};10681069// Implements the polymorphic EndsWith(substring) matcher, which1070// can be used as a Matcher<T> as long as T can be converted to a1071// string.1072template <typename StringType>1073class EndsWithMatcher {1074public:1075explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}10761077#if GTEST_INTERNAL_HAS_STRING_VIEW1078bool MatchAndExplain(const internal::StringView& s,1079MatchResultListener* listener) const {1080// This should fail to compile if StringView is used with wide1081// strings.1082const StringType& str = std::string(s);1083return MatchAndExplain(str, listener);1084}1085#endif // GTEST_INTERNAL_HAS_STRING_VIEW10861087// Accepts pointer types, particularly:1088// const char*1089// char*1090// const wchar_t*1091// wchar_t*1092template <typename CharType>1093bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {1094return s != nullptr && MatchAndExplain(StringType(s), listener);1095}10961097// Matches anything that can convert to StringType.1098//1099// This is a template, not just a plain function with const StringType&,1100// because StringView has some interfering non-explicit constructors.1101template <typename MatcheeStringType>1102bool MatchAndExplain(const MatcheeStringType& s,1103MatchResultListener* /* listener */) const {1104const StringType s2(s);1105return s2.length() >= suffix_.length() &&1106s2.substr(s2.length() - suffix_.length()) == suffix_;1107}11081109void DescribeTo(::std::ostream* os) const {1110*os << "ends with ";1111UniversalPrint(suffix_, os);1112}11131114void DescribeNegationTo(::std::ostream* os) const {1115*os << "doesn't end with ";1116UniversalPrint(suffix_, os);1117}11181119private:1120const StringType suffix_;1121};11221123// Implements the polymorphic WhenBase64Unescaped(matcher) matcher, which can be1124// used as a Matcher<T> as long as T can be converted to a string.1125class WhenBase64UnescapedMatcher {1126public:1127using is_gtest_matcher = void;11281129explicit WhenBase64UnescapedMatcher(1130const Matcher<const std::string&>& internal_matcher)1131: internal_matcher_(internal_matcher) {}11321133// Matches anything that can convert to std::string.1134template <typename MatcheeStringType>1135bool MatchAndExplain(const MatcheeStringType& s,1136MatchResultListener* listener) const {1137const std::string s2(s); // NOLINT (needed for working with string_view).1138std::string unescaped;1139if (!internal::Base64Unescape(s2, &unescaped)) {1140if (listener != nullptr) {1141*listener << "is not a valid base64 escaped string";1142}1143return false;1144}1145return MatchPrintAndExplain(unescaped, internal_matcher_, listener);1146}11471148void DescribeTo(::std::ostream* os) const {1149*os << "matches after Base64Unescape ";1150internal_matcher_.DescribeTo(os);1151}11521153void DescribeNegationTo(::std::ostream* os) const {1154*os << "does not match after Base64Unescape ";1155internal_matcher_.DescribeTo(os);1156}11571158private:1159const Matcher<const std::string&> internal_matcher_;1160};11611162// Implements a matcher that compares the two fields of a 2-tuple1163// using one of the ==, <=, <, etc, operators. The two fields being1164// compared don't have to have the same type.1165//1166// The matcher defined here is polymorphic (for example, Eq() can be1167// used to match a std::tuple<int, short>, a std::tuple<const long&, double>,1168// etc). Therefore we use a template type conversion operator in the1169// implementation.1170template <typename D, typename Op>1171class PairMatchBase {1172public:1173template <typename T1, typename T2>1174operator Matcher<::std::tuple<T1, T2>>() const {1175return Matcher<::std::tuple<T1, T2>>(new Impl<const ::std::tuple<T1, T2>&>);1176}1177template <typename T1, typename T2>1178operator Matcher<const ::std::tuple<T1, T2>&>() const {1179return MakeMatcher(new Impl<const ::std::tuple<T1, T2>&>);1180}11811182private:1183static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT1184return os << D::Desc();1185}11861187template <typename Tuple>1188class Impl : public MatcherInterface<Tuple> {1189public:1190bool MatchAndExplain(Tuple args,1191MatchResultListener* /* listener */) const override {1192return Op()(::std::get<0>(args), ::std::get<1>(args));1193}1194void DescribeTo(::std::ostream* os) const override {1195*os << "are " << GetDesc;1196}1197void DescribeNegationTo(::std::ostream* os) const override {1198*os << "aren't " << GetDesc;1199}1200};1201};12021203class Eq2Matcher : public PairMatchBase<Eq2Matcher, std::equal_to<>> {1204public:1205static const char* Desc() { return "an equal pair"; }1206};1207class Ne2Matcher : public PairMatchBase<Ne2Matcher, std::not_equal_to<>> {1208public:1209static const char* Desc() { return "an unequal pair"; }1210};1211class Lt2Matcher : public PairMatchBase<Lt2Matcher, std::less<>> {1212public:1213static const char* Desc() { return "a pair where the first < the second"; }1214};1215class Gt2Matcher : public PairMatchBase<Gt2Matcher, std::greater<>> {1216public:1217static const char* Desc() { return "a pair where the first > the second"; }1218};1219class Le2Matcher : public PairMatchBase<Le2Matcher, std::less_equal<>> {1220public:1221static const char* Desc() { return "a pair where the first <= the second"; }1222};1223class Ge2Matcher : public PairMatchBase<Ge2Matcher, std::greater_equal<>> {1224public:1225static const char* Desc() { return "a pair where the first >= the second"; }1226};12271228// Implements the Not(...) matcher for a particular argument type T.1229// We do not nest it inside the NotMatcher class template, as that1230// will prevent different instantiations of NotMatcher from sharing1231// the same NotMatcherImpl<T> class.1232template <typename T>1233class NotMatcherImpl : public MatcherInterface<const T&> {1234public:1235explicit NotMatcherImpl(const Matcher<T>& matcher) : matcher_(matcher) {}12361237bool MatchAndExplain(const T& x,1238MatchResultListener* listener) const override {1239return !matcher_.MatchAndExplain(x, listener);1240}12411242void DescribeTo(::std::ostream* os) const override {1243matcher_.DescribeNegationTo(os);1244}12451246void DescribeNegationTo(::std::ostream* os) const override {1247matcher_.DescribeTo(os);1248}12491250private:1251const Matcher<T> matcher_;1252};12531254// Implements the Not(m) matcher, which matches a value that doesn't1255// match matcher m.1256template <typename InnerMatcher>1257class NotMatcher {1258public:1259explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}12601261// This template type conversion operator allows Not(m) to be used1262// to match any type m can match.1263template <typename T>1264operator Matcher<T>() const {1265return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));1266}12671268private:1269InnerMatcher matcher_;1270};12711272// Implements the AllOf(m1, m2) matcher for a particular argument type1273// T. We do not nest it inside the BothOfMatcher class template, as1274// that will prevent different instantiations of BothOfMatcher from1275// sharing the same BothOfMatcherImpl<T> class.1276template <typename T>1277class AllOfMatcherImpl : public MatcherInterface<const T&> {1278public:1279explicit AllOfMatcherImpl(std::vector<Matcher<T>> matchers)1280: matchers_(std::move(matchers)) {}12811282void DescribeTo(::std::ostream* os) const override {1283*os << "(";1284for (size_t i = 0; i < matchers_.size(); ++i) {1285if (i != 0) *os << ") and (";1286matchers_[i].DescribeTo(os);1287}1288*os << ")";1289}12901291void DescribeNegationTo(::std::ostream* os) const override {1292*os << "(";1293for (size_t i = 0; i < matchers_.size(); ++i) {1294if (i != 0) *os << ") or (";1295matchers_[i].DescribeNegationTo(os);1296}1297*os << ")";1298}12991300bool MatchAndExplain(const T& x,1301MatchResultListener* listener) const override {1302// If either matcher1_ or matcher2_ doesn't match x, we only need1303// to explain why one of them fails.1304std::string all_match_result;13051306for (size_t i = 0; i < matchers_.size(); ++i) {1307StringMatchResultListener slistener;1308if (matchers_[i].MatchAndExplain(x, &slistener)) {1309if (all_match_result.empty()) {1310all_match_result = slistener.str();1311} else {1312std::string result = slistener.str();1313if (!result.empty()) {1314all_match_result += ", and ";1315all_match_result += result;1316}1317}1318} else {1319*listener << slistener.str();1320return false;1321}1322}13231324// Otherwise we need to explain why *both* of them match.1325*listener << all_match_result;1326return true;1327}13281329private:1330const std::vector<Matcher<T>> matchers_;1331};13321333// VariadicMatcher is used for the variadic implementation of1334// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).1335// CombiningMatcher<T> is used to recursively combine the provided matchers1336// (of type Args...).1337template <template <typename T> class CombiningMatcher, typename... Args>1338class VariadicMatcher {1339public:1340VariadicMatcher(const Args&... matchers) // NOLINT1341: matchers_(matchers...) {1342static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");1343}13441345VariadicMatcher(const VariadicMatcher&) = default;1346VariadicMatcher& operator=(const VariadicMatcher&) = delete;13471348// This template type conversion operator allows an1349// VariadicMatcher<Matcher1, Matcher2...> object to match any type that1350// all of the provided matchers (Matcher1, Matcher2, ...) can match.1351template <typename T>1352operator Matcher<T>() const {1353std::vector<Matcher<T>> values;1354CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());1355return Matcher<T>(new CombiningMatcher<T>(std::move(values)));1356}13571358private:1359template <typename T, size_t I>1360void CreateVariadicMatcher(std::vector<Matcher<T>>* values,1361std::integral_constant<size_t, I>) const {1362values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));1363CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());1364}13651366template <typename T>1367void CreateVariadicMatcher(1368std::vector<Matcher<T>>*,1369std::integral_constant<size_t, sizeof...(Args)>) const {}13701371std::tuple<Args...> matchers_;1372};13731374template <typename... Args>1375using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;13761377// Implements the AnyOf(m1, m2) matcher for a particular argument type1378// T. We do not nest it inside the AnyOfMatcher class template, as1379// that will prevent different instantiations of AnyOfMatcher from1380// sharing the same EitherOfMatcherImpl<T> class.1381template <typename T>1382class AnyOfMatcherImpl : public MatcherInterface<const T&> {1383public:1384explicit AnyOfMatcherImpl(std::vector<Matcher<T>> matchers)1385: matchers_(std::move(matchers)) {}13861387void DescribeTo(::std::ostream* os) const override {1388*os << "(";1389for (size_t i = 0; i < matchers_.size(); ++i) {1390if (i != 0) *os << ") or (";1391matchers_[i].DescribeTo(os);1392}1393*os << ")";1394}13951396void DescribeNegationTo(::std::ostream* os) const override {1397*os << "(";1398for (size_t i = 0; i < matchers_.size(); ++i) {1399if (i != 0) *os << ") and (";1400matchers_[i].DescribeNegationTo(os);1401}1402*os << ")";1403}14041405bool MatchAndExplain(const T& x,1406MatchResultListener* listener) const override {1407std::string no_match_result;14081409// If either matcher1_ or matcher2_ matches x, we just need to1410// explain why *one* of them matches.1411for (size_t i = 0; i < matchers_.size(); ++i) {1412StringMatchResultListener slistener;1413if (matchers_[i].MatchAndExplain(x, &slistener)) {1414*listener << slistener.str();1415return true;1416} else {1417if (no_match_result.empty()) {1418no_match_result = slistener.str();1419} else {1420std::string result = slistener.str();1421if (!result.empty()) {1422no_match_result += ", and ";1423no_match_result += result;1424}1425}1426}1427}14281429// Otherwise we need to explain why *both* of them fail.1430*listener << no_match_result;1431return false;1432}14331434private:1435const std::vector<Matcher<T>> matchers_;1436};14371438// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).1439template <typename... Args>1440using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;14411442// ConditionalMatcher is the implementation of Conditional(cond, m1, m2)1443template <typename MatcherTrue, typename MatcherFalse>1444class ConditionalMatcher {1445public:1446ConditionalMatcher(bool condition, MatcherTrue matcher_true,1447MatcherFalse matcher_false)1448: condition_(condition),1449matcher_true_(std::move(matcher_true)),1450matcher_false_(std::move(matcher_false)) {}14511452template <typename T>1453operator Matcher<T>() const { // NOLINT(runtime/explicit)1454return condition_ ? SafeMatcherCast<T>(matcher_true_)1455: SafeMatcherCast<T>(matcher_false_);1456}14571458private:1459bool condition_;1460MatcherTrue matcher_true_;1461MatcherFalse matcher_false_;1462};14631464// Wrapper for implementation of Any/AllOfArray().1465template <template <class> class MatcherImpl, typename T>1466class SomeOfArrayMatcher {1467public:1468// Constructs the matcher from a sequence of element values or1469// element matchers.1470template <typename Iter>1471SomeOfArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}14721473template <typename U>1474operator Matcher<U>() const { // NOLINT1475using RawU = typename std::decay<U>::type;1476std::vector<Matcher<RawU>> matchers;1477matchers.reserve(matchers_.size());1478for (const auto& matcher : matchers_) {1479matchers.push_back(MatcherCast<RawU>(matcher));1480}1481return Matcher<U>(new MatcherImpl<RawU>(std::move(matchers)));1482}14831484private:1485const ::std::vector<T> matchers_;1486};14871488template <typename T>1489using AllOfArrayMatcher = SomeOfArrayMatcher<AllOfMatcherImpl, T>;14901491template <typename T>1492using AnyOfArrayMatcher = SomeOfArrayMatcher<AnyOfMatcherImpl, T>;14931494// Used for implementing Truly(pred), which turns a predicate into a1495// matcher.1496template <typename Predicate>1497class TrulyMatcher {1498public:1499explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}15001501// This method template allows Truly(pred) to be used as a matcher1502// for type T where T is the argument type of predicate 'pred'. The1503// argument is passed by reference as the predicate may be1504// interested in the address of the argument.1505template <typename T>1506bool MatchAndExplain(T& x, // NOLINT1507MatchResultListener* listener) const {1508// Without the if-statement, MSVC sometimes warns about converting1509// a value to bool (warning 4800).1510//1511// We cannot write 'return !!predicate_(x);' as that doesn't work1512// when predicate_(x) returns a class convertible to bool but1513// having no operator!().1514if (predicate_(x)) return true;1515*listener << "didn't satisfy the given predicate";1516return false;1517}15181519void DescribeTo(::std::ostream* os) const {1520*os << "satisfies the given predicate";1521}15221523void DescribeNegationTo(::std::ostream* os) const {1524*os << "doesn't satisfy the given predicate";1525}15261527private:1528Predicate predicate_;1529};15301531// Used for implementing Matches(matcher), which turns a matcher into1532// a predicate.1533template <typename M>1534class MatcherAsPredicate {1535public:1536explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}15371538// This template operator() allows Matches(m) to be used as a1539// predicate on type T where m is a matcher on type T.1540//1541// The argument x is passed by reference instead of by value, as1542// some matcher may be interested in its address (e.g. as in1543// Matches(Ref(n))(x)).1544template <typename T>1545bool operator()(const T& x) const {1546// We let matcher_ commit to a particular type here instead of1547// when the MatcherAsPredicate object was constructed. This1548// allows us to write Matches(m) where m is a polymorphic matcher1549// (e.g. Eq(5)).1550//1551// If we write Matcher<T>(matcher_).Matches(x) here, it won't1552// compile when matcher_ has type Matcher<const T&>; if we write1553// Matcher<const T&>(matcher_).Matches(x) here, it won't compile1554// when matcher_ has type Matcher<T>; if we just write1555// matcher_.Matches(x), it won't compile when matcher_ is1556// polymorphic, e.g. Eq(5).1557//1558// MatcherCast<const T&>() is necessary for making the code work1559// in all of the above situations.1560return MatcherCast<const T&>(matcher_).Matches(x);1561}15621563private:1564M matcher_;1565};15661567// For implementing ASSERT_THAT() and EXPECT_THAT(). The template1568// argument M must be a type that can be converted to a matcher.1569template <typename M>1570class PredicateFormatterFromMatcher {1571public:1572explicit PredicateFormatterFromMatcher(M m) : matcher_(std::move(m)) {}15731574// This template () operator allows a PredicateFormatterFromMatcher1575// object to act as a predicate-formatter suitable for using with1576// Google Test's EXPECT_PRED_FORMAT1() macro.1577template <typename T>1578AssertionResult operator()(const char* value_text, const T& x) const {1579// We convert matcher_ to a Matcher<const T&> *now* instead of1580// when the PredicateFormatterFromMatcher object was constructed,1581// as matcher_ may be polymorphic (e.g. NotNull()) and we won't1582// know which type to instantiate it to until we actually see the1583// type of x here.1584//1585// We write SafeMatcherCast<const T&>(matcher_) instead of1586// Matcher<const T&>(matcher_), as the latter won't compile when1587// matcher_ has type Matcher<T> (e.g. An<int>()).1588// We don't write MatcherCast<const T&> either, as that allows1589// potentially unsafe downcasting of the matcher argument.1590const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);15911592// The expected path here is that the matcher should match (i.e. that most1593// tests pass) so optimize for this case.1594if (matcher.Matches(x)) {1595return AssertionSuccess();1596}15971598::std::stringstream ss;1599ss << "Value of: " << value_text << "\n"1600<< "Expected: ";1601matcher.DescribeTo(&ss);16021603// Rerun the matcher to "PrintAndExplain" the failure.1604StringMatchResultListener listener;1605if (MatchPrintAndExplain(x, matcher, &listener)) {1606ss << "\n The matcher failed on the initial attempt; but passed when "1607"rerun to generate the explanation.";1608}1609ss << "\n Actual: " << listener.str();1610return AssertionFailure() << ss.str();1611}16121613private:1614const M matcher_;1615};16161617// A helper function for converting a matcher to a predicate-formatter1618// without the user needing to explicitly write the type. This is1619// used for implementing ASSERT_THAT() and EXPECT_THAT().1620// Implementation detail: 'matcher' is received by-value to force decaying.1621template <typename M>1622inline PredicateFormatterFromMatcher<M> MakePredicateFormatterFromMatcher(1623M matcher) {1624return PredicateFormatterFromMatcher<M>(std::move(matcher));1625}16261627// Implements the polymorphic IsNan() matcher, which matches any floating type1628// value that is Nan.1629class IsNanMatcher {1630public:1631template <typename FloatType>1632bool MatchAndExplain(const FloatType& f,1633MatchResultListener* /* listener */) const {1634return (::std::isnan)(f);1635}16361637void DescribeTo(::std::ostream* os) const { *os << "is NaN"; }1638void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NaN"; }1639};16401641// Implements the polymorphic floating point equality matcher, which matches1642// two float values using ULP-based approximation or, optionally, a1643// user-specified epsilon. The template is meant to be instantiated with1644// FloatType being either float or double.1645template <typename FloatType>1646class FloatingEqMatcher {1647public:1648// Constructor for FloatingEqMatcher.1649// The matcher's input will be compared with expected. The matcher treats two1650// NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,1651// equality comparisons between NANs will always return false. We specify a1652// negative max_abs_error_ term to indicate that ULP-based approximation will1653// be used for comparison.1654FloatingEqMatcher(FloatType expected, bool nan_eq_nan)1655: expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {}16561657// Constructor that supports a user-specified max_abs_error that will be used1658// for comparison instead of ULP-based approximation. The max absolute1659// should be non-negative.1660FloatingEqMatcher(FloatType expected, bool nan_eq_nan,1661FloatType max_abs_error)1662: expected_(expected),1663nan_eq_nan_(nan_eq_nan),1664max_abs_error_(max_abs_error) {1665GTEST_CHECK_(max_abs_error >= 0)1666<< ", where max_abs_error is" << max_abs_error;1667}16681669// Implements floating point equality matcher as a Matcher<T>.1670template <typename T>1671class Impl : public MatcherInterface<T> {1672public:1673Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)1674: expected_(expected),1675nan_eq_nan_(nan_eq_nan),1676max_abs_error_(max_abs_error) {}16771678bool MatchAndExplain(T value,1679MatchResultListener* listener) const override {1680const FloatingPoint<FloatType> actual(value), expected(expected_);16811682// Compares NaNs first, if nan_eq_nan_ is true.1683if (actual.is_nan() || expected.is_nan()) {1684if (actual.is_nan() && expected.is_nan()) {1685return nan_eq_nan_;1686}1687// One is nan; the other is not nan.1688return false;1689}1690if (HasMaxAbsError()) {1691// We perform an equality check so that inf will match inf, regardless1692// of error bounds. If the result of value - expected_ would result in1693// overflow or if either value is inf, the default result is infinity,1694// which should only match if max_abs_error_ is also infinity.1695if (value == expected_) {1696return true;1697}16981699const FloatType diff = value - expected_;1700if (::std::fabs(diff) <= max_abs_error_) {1701return true;1702}17031704if (listener->IsInterested()) {1705*listener << "which is " << diff << " from " << expected_;1706}1707return false;1708} else {1709return actual.AlmostEquals(expected);1710}1711}17121713void DescribeTo(::std::ostream* os) const override {1714// os->precision() returns the previously set precision, which we1715// store to restore the ostream to its original configuration1716// after outputting.1717const ::std::streamsize old_precision =1718os->precision(::std::numeric_limits<FloatType>::digits10 + 2);1719if (FloatingPoint<FloatType>(expected_).is_nan()) {1720if (nan_eq_nan_) {1721*os << "is NaN";1722} else {1723*os << "never matches";1724}1725} else {1726*os << "is approximately " << expected_;1727if (HasMaxAbsError()) {1728*os << " (absolute error <= " << max_abs_error_ << ")";1729}1730}1731os->precision(old_precision);1732}17331734void DescribeNegationTo(::std::ostream* os) const override {1735// As before, get original precision.1736const ::std::streamsize old_precision =1737os->precision(::std::numeric_limits<FloatType>::digits10 + 2);1738if (FloatingPoint<FloatType>(expected_).is_nan()) {1739if (nan_eq_nan_) {1740*os << "isn't NaN";1741} else {1742*os << "is anything";1743}1744} else {1745*os << "isn't approximately " << expected_;1746if (HasMaxAbsError()) {1747*os << " (absolute error > " << max_abs_error_ << ")";1748}1749}1750// Restore original precision.1751os->precision(old_precision);1752}17531754private:1755bool HasMaxAbsError() const { return max_abs_error_ >= 0; }17561757const FloatType expected_;1758const bool nan_eq_nan_;1759// max_abs_error will be used for value comparison when >= 0.1760const FloatType max_abs_error_;1761};17621763// The following 3 type conversion operators allow FloatEq(expected) and1764// NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a1765// Matcher<const float&>, or a Matcher<float&>, but nothing else.1766operator Matcher<FloatType>() const {1767return MakeMatcher(1768new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));1769}17701771operator Matcher<const FloatType&>() const {1772return MakeMatcher(1773new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));1774}17751776operator Matcher<FloatType&>() const {1777return MakeMatcher(1778new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));1779}17801781private:1782const FloatType expected_;1783const bool nan_eq_nan_;1784// max_abs_error will be used for value comparison when >= 0.1785const FloatType max_abs_error_;1786};17871788// A 2-tuple ("binary") wrapper around FloatingEqMatcher:1789// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)1790// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)1791// against y. The former implements "Eq", the latter "Near". At present, there1792// is no version that compares NaNs as equal.1793template <typename FloatType>1794class FloatingEq2Matcher {1795public:1796FloatingEq2Matcher() { Init(-1, false); }17971798explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }17991800explicit FloatingEq2Matcher(FloatType max_abs_error) {1801Init(max_abs_error, false);1802}18031804FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {1805Init(max_abs_error, nan_eq_nan);1806}18071808template <typename T1, typename T2>1809operator Matcher<::std::tuple<T1, T2>>() const {1810return MakeMatcher(1811new Impl<::std::tuple<T1, T2>>(max_abs_error_, nan_eq_nan_));1812}1813template <typename T1, typename T2>1814operator Matcher<const ::std::tuple<T1, T2>&>() const {1815return MakeMatcher(1816new Impl<const ::std::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));1817}18181819private:1820static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT1821return os << "an almost-equal pair";1822}18231824template <typename Tuple>1825class Impl : public MatcherInterface<Tuple> {1826public:1827Impl(FloatType max_abs_error, bool nan_eq_nan)1828: max_abs_error_(max_abs_error), nan_eq_nan_(nan_eq_nan) {}18291830bool MatchAndExplain(Tuple args,1831MatchResultListener* listener) const override {1832if (max_abs_error_ == -1) {1833FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_);1834return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(1835::std::get<1>(args), listener);1836} else {1837FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_,1838max_abs_error_);1839return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(1840::std::get<1>(args), listener);1841}1842}1843void DescribeTo(::std::ostream* os) const override {1844*os << "are " << GetDesc;1845}1846void DescribeNegationTo(::std::ostream* os) const override {1847*os << "aren't " << GetDesc;1848}18491850private:1851FloatType max_abs_error_;1852const bool nan_eq_nan_;1853};18541855void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {1856max_abs_error_ = max_abs_error_val;1857nan_eq_nan_ = nan_eq_nan_val;1858}1859FloatType max_abs_error_;1860bool nan_eq_nan_;1861};18621863// Implements the Pointee(m) matcher for matching a pointer whose1864// pointee matches matcher m. The pointer can be either raw or smart.1865template <typename InnerMatcher>1866class PointeeMatcher {1867public:1868explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}18691870// This type conversion operator template allows Pointee(m) to be1871// used as a matcher for any pointer type whose pointee type is1872// compatible with the inner matcher, where type Pointer can be1873// either a raw pointer or a smart pointer.1874//1875// The reason we do this instead of relying on1876// MakePolymorphicMatcher() is that the latter is not flexible1877// enough for implementing the DescribeTo() method of Pointee().1878template <typename Pointer>1879operator Matcher<Pointer>() const {1880return Matcher<Pointer>(new Impl<const Pointer&>(matcher_));1881}18821883private:1884// The monomorphic implementation that works for a particular pointer type.1885template <typename Pointer>1886class Impl : public MatcherInterface<Pointer> {1887public:1888using Pointee =1889typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(1890Pointer)>::element_type;18911892explicit Impl(const InnerMatcher& matcher)1893: matcher_(MatcherCast<const Pointee&>(matcher)) {}18941895void DescribeTo(::std::ostream* os) const override {1896*os << "points to a value that ";1897matcher_.DescribeTo(os);1898}18991900void DescribeNegationTo(::std::ostream* os) const override {1901*os << "does not point to a value that ";1902matcher_.DescribeTo(os);1903}19041905bool MatchAndExplain(Pointer pointer,1906MatchResultListener* listener) const override {1907if (GetRawPointer(pointer) == nullptr) return false;19081909*listener << "which points to ";1910return MatchPrintAndExplain(*pointer, matcher_, listener);1911}19121913private:1914const Matcher<const Pointee&> matcher_;1915};19161917const InnerMatcher matcher_;1918};19191920// Implements the Pointer(m) matcher1921// Implements the Pointer(m) matcher for matching a pointer that matches matcher1922// m. The pointer can be either raw or smart, and will match `m` against the1923// raw pointer.1924template <typename InnerMatcher>1925class PointerMatcher {1926public:1927explicit PointerMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}19281929// This type conversion operator template allows Pointer(m) to be1930// used as a matcher for any pointer type whose pointer type is1931// compatible with the inner matcher, where type PointerType can be1932// either a raw pointer or a smart pointer.1933//1934// The reason we do this instead of relying on1935// MakePolymorphicMatcher() is that the latter is not flexible1936// enough for implementing the DescribeTo() method of Pointer().1937template <typename PointerType>1938operator Matcher<PointerType>() const { // NOLINT1939return Matcher<PointerType>(new Impl<const PointerType&>(matcher_));1940}19411942private:1943// The monomorphic implementation that works for a particular pointer type.1944template <typename PointerType>1945class Impl : public MatcherInterface<PointerType> {1946public:1947using Pointer =1948const typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(1949PointerType)>::element_type*;19501951explicit Impl(const InnerMatcher& matcher)1952: matcher_(MatcherCast<Pointer>(matcher)) {}19531954void DescribeTo(::std::ostream* os) const override {1955*os << "is a pointer that ";1956matcher_.DescribeTo(os);1957}19581959void DescribeNegationTo(::std::ostream* os) const override {1960*os << "is not a pointer that ";1961matcher_.DescribeTo(os);1962}19631964bool MatchAndExplain(PointerType pointer,1965MatchResultListener* listener) const override {1966*listener << "which is a pointer that ";1967Pointer p = GetRawPointer(pointer);1968return MatchPrintAndExplain(p, matcher_, listener);1969}19701971private:1972Matcher<Pointer> matcher_;1973};19741975const InnerMatcher matcher_;1976};19771978#if GTEST_HAS_RTTI1979// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or1980// reference that matches inner_matcher when dynamic_cast<T> is applied.1981// The result of dynamic_cast<To> is forwarded to the inner matcher.1982// If To is a pointer and the cast fails, the inner matcher will receive NULL.1983// If To is a reference and the cast fails, this matcher returns false1984// immediately.1985template <typename To>1986class WhenDynamicCastToMatcherBase {1987public:1988explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)1989: matcher_(matcher) {}19901991void DescribeTo(::std::ostream* os) const {1992GetCastTypeDescription(os);1993matcher_.DescribeTo(os);1994}19951996void DescribeNegationTo(::std::ostream* os) const {1997GetCastTypeDescription(os);1998matcher_.DescribeNegationTo(os);1999}20002001protected:2002const Matcher<To> matcher_;20032004static std::string GetToName() { return GetTypeName<To>(); }20052006private:2007static void GetCastTypeDescription(::std::ostream* os) {2008*os << "when dynamic_cast to " << GetToName() << ", ";2009}2010};20112012// Primary template.2013// To is a pointer. Cast and forward the result.2014template <typename To>2015class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {2016public:2017explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)2018: WhenDynamicCastToMatcherBase<To>(matcher) {}20192020template <typename From>2021bool MatchAndExplain(From from, MatchResultListener* listener) const {2022To to = dynamic_cast<To>(from);2023return MatchPrintAndExplain(to, this->matcher_, listener);2024}2025};20262027// Specialize for references.2028// In this case we return false if the dynamic_cast fails.2029template <typename To>2030class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {2031public:2032explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)2033: WhenDynamicCastToMatcherBase<To&>(matcher) {}20342035template <typename From>2036bool MatchAndExplain(From& from, MatchResultListener* listener) const {2037// We don't want an std::bad_cast here, so do the cast with pointers.2038To* to = dynamic_cast<To*>(&from);2039if (to == nullptr) {2040*listener << "which cannot be dynamic_cast to " << this->GetToName();2041return false;2042}2043return MatchPrintAndExplain(*to, this->matcher_, listener);2044}2045};2046#endif // GTEST_HAS_RTTI20472048// Implements the Field() matcher for matching a field (i.e. member2049// variable) of an object.2050template <typename Class, typename FieldType>2051class FieldMatcher {2052public:2053FieldMatcher(FieldType Class::*field,2054const Matcher<const FieldType&>& matcher)2055: field_(field), matcher_(matcher), whose_field_("whose given field ") {}20562057FieldMatcher(const std::string& field_name, FieldType Class::*field,2058const Matcher<const FieldType&>& matcher)2059: field_(field),2060matcher_(matcher),2061whose_field_("whose field `" + field_name + "` ") {}20622063void DescribeTo(::std::ostream* os) const {2064*os << "is an object " << whose_field_;2065matcher_.DescribeTo(os);2066}20672068void DescribeNegationTo(::std::ostream* os) const {2069*os << "is an object " << whose_field_;2070matcher_.DescribeNegationTo(os);2071}20722073template <typename T>2074bool MatchAndExplain(const T& value, MatchResultListener* listener) const {2075// FIXME: The dispatch on std::is_pointer was introduced as a workaround for2076// a compiler bug, and can now be removed.2077return MatchAndExplainImpl(2078typename std::is_pointer<typename std::remove_const<T>::type>::type(),2079value, listener);2080}20812082private:2083bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,2084const Class& obj,2085MatchResultListener* listener) const {2086*listener << whose_field_ << "is ";2087return MatchPrintAndExplain(obj.*field_, matcher_, listener);2088}20892090bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,2091MatchResultListener* listener) const {2092if (p == nullptr) return false;20932094*listener << "which points to an object ";2095// Since *p has a field, it must be a class/struct/union type and2096// thus cannot be a pointer. Therefore we pass false_type() as2097// the first argument.2098return MatchAndExplainImpl(std::false_type(), *p, listener);2099}21002101const FieldType Class::*field_;2102const Matcher<const FieldType&> matcher_;21032104// Contains either "whose given field " if the name of the field is unknown2105// or "whose field `name_of_field` " if the name is known.2106const std::string whose_field_;2107};21082109// Implements the Property() matcher for matching a property2110// (i.e. return value of a getter method) of an object.2111//2112// Property is a const-qualified member function of Class returning2113// PropertyType.2114template <typename Class, typename PropertyType, typename Property>2115class PropertyMatcher {2116public:2117typedef const PropertyType& RefToConstProperty;21182119PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)2120: property_(property),2121matcher_(matcher),2122whose_property_("whose given property ") {}21232124PropertyMatcher(const std::string& property_name, Property property,2125const Matcher<RefToConstProperty>& matcher)2126: property_(property),2127matcher_(matcher),2128whose_property_("whose property `" + property_name + "` ") {}21292130void DescribeTo(::std::ostream* os) const {2131*os << "is an object " << whose_property_;2132matcher_.DescribeTo(os);2133}21342135void DescribeNegationTo(::std::ostream* os) const {2136*os << "is an object " << whose_property_;2137matcher_.DescribeNegationTo(os);2138}21392140template <typename T>2141bool MatchAndExplain(const T& value, MatchResultListener* listener) const {2142return MatchAndExplainImpl(2143typename std::is_pointer<typename std::remove_const<T>::type>::type(),2144value, listener);2145}21462147private:2148bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,2149const Class& obj,2150MatchResultListener* listener) const {2151*listener << whose_property_ << "is ";2152// Cannot pass the return value (for example, int) to MatchPrintAndExplain,2153// which takes a non-const reference as argument.2154RefToConstProperty result = (obj.*property_)();2155return MatchPrintAndExplain(result, matcher_, listener);2156}21572158bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,2159MatchResultListener* listener) const {2160if (p == nullptr) return false;21612162*listener << "which points to an object ";2163// Since *p has a property method, it must be a class/struct/union2164// type and thus cannot be a pointer. Therefore we pass2165// false_type() as the first argument.2166return MatchAndExplainImpl(std::false_type(), *p, listener);2167}21682169Property property_;2170const Matcher<RefToConstProperty> matcher_;21712172// Contains either "whose given property " if the name of the property is2173// unknown or "whose property `name_of_property` " if the name is known.2174const std::string whose_property_;2175};21762177// Type traits specifying various features of different functors for ResultOf.2178// The default template specifies features for functor objects.2179template <typename Functor>2180struct CallableTraits {2181typedef Functor StorageType;21822183static void CheckIsValid(Functor /* functor */) {}21842185template <typename T>2186static auto Invoke(Functor f, const T& arg) -> decltype(f(arg)) {2187return f(arg);2188}2189};21902191// Specialization for function pointers.2192template <typename ArgType, typename ResType>2193struct CallableTraits<ResType (*)(ArgType)> {2194typedef ResType ResultType;2195typedef ResType (*StorageType)(ArgType);21962197static void CheckIsValid(ResType (*f)(ArgType)) {2198GTEST_CHECK_(f != nullptr)2199<< "NULL function pointer is passed into ResultOf().";2200}2201template <typename T>2202static ResType Invoke(ResType (*f)(ArgType), T arg) {2203return (*f)(arg);2204}2205};22062207// Implements the ResultOf() matcher for matching a return value of a2208// unary function of an object.2209template <typename Callable, typename InnerMatcher>2210class ResultOfMatcher {2211public:2212ResultOfMatcher(Callable callable, InnerMatcher matcher)2213: ResultOfMatcher(/*result_description=*/"", std::move(callable),2214std::move(matcher)) {}22152216ResultOfMatcher(const std::string& result_description, Callable callable,2217InnerMatcher matcher)2218: result_description_(result_description),2219callable_(std::move(callable)),2220matcher_(std::move(matcher)) {2221CallableTraits<Callable>::CheckIsValid(callable_);2222}22232224template <typename T>2225operator Matcher<T>() const {2226return Matcher<T>(2227new Impl<const T&>(result_description_, callable_, matcher_));2228}22292230private:2231typedef typename CallableTraits<Callable>::StorageType CallableStorageType;22322233template <typename T>2234class Impl : public MatcherInterface<T> {2235using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(2236std::declval<CallableStorageType>(), std::declval<T>()));22372238public:2239template <typename M>2240Impl(const std::string& result_description,2241const CallableStorageType& callable, const M& matcher)2242: result_description_(result_description),2243callable_(callable),2244matcher_(MatcherCast<ResultType>(matcher)) {}22452246void DescribeTo(::std::ostream* os) const override {2247if (result_description_.empty()) {2248*os << "is mapped by the given callable to a value that ";2249} else {2250*os << "whose " << result_description_ << " ";2251}2252matcher_.DescribeTo(os);2253}22542255void DescribeNegationTo(::std::ostream* os) const override {2256if (result_description_.empty()) {2257*os << "is mapped by the given callable to a value that ";2258} else {2259*os << "whose " << result_description_ << " ";2260}2261matcher_.DescribeNegationTo(os);2262}22632264bool MatchAndExplain(T obj, MatchResultListener* listener) const override {2265if (result_description_.empty()) {2266*listener << "which is mapped by the given callable to ";2267} else {2268*listener << "whose " << result_description_ << " is ";2269}2270// Cannot pass the return value directly to MatchPrintAndExplain, which2271// takes a non-const reference as argument.2272// Also, specifying template argument explicitly is needed because T could2273// be a non-const reference (e.g. Matcher<Uncopyable&>).2274ResultType result =2275CallableTraits<Callable>::template Invoke<T>(callable_, obj);2276return MatchPrintAndExplain(result, matcher_, listener);2277}22782279private:2280const std::string result_description_;2281// Functors often define operator() as non-const method even though2282// they are actually stateless. But we need to use them even when2283// 'this' is a const pointer. It's the user's responsibility not to2284// use stateful callables with ResultOf(), which doesn't guarantee2285// how many times the callable will be invoked.2286mutable CallableStorageType callable_;2287const Matcher<ResultType> matcher_;2288}; // class Impl22892290const std::string result_description_;2291const CallableStorageType callable_;2292const InnerMatcher matcher_;2293};22942295// Implements a matcher that checks the size of an STL-style container.2296template <typename SizeMatcher>2297class SizeIsMatcher {2298public:2299explicit SizeIsMatcher(const SizeMatcher& size_matcher)2300: size_matcher_(size_matcher) {}23012302template <typename Container>2303operator Matcher<Container>() const {2304return Matcher<Container>(new Impl<const Container&>(size_matcher_));2305}23062307template <typename Container>2308class Impl : public MatcherInterface<Container> {2309public:2310using SizeType = decltype(std::declval<Container>().size());2311explicit Impl(const SizeMatcher& size_matcher)2312: size_matcher_(MatcherCast<SizeType>(size_matcher)) {}23132314void DescribeTo(::std::ostream* os) const override {2315*os << "has a size that ";2316size_matcher_.DescribeTo(os);2317}2318void DescribeNegationTo(::std::ostream* os) const override {2319*os << "has a size that ";2320size_matcher_.DescribeNegationTo(os);2321}23222323bool MatchAndExplain(Container container,2324MatchResultListener* listener) const override {2325SizeType size = container.size();2326StringMatchResultListener size_listener;2327const bool result = size_matcher_.MatchAndExplain(size, &size_listener);2328*listener << "whose size " << size2329<< (result ? " matches" : " doesn't match");2330PrintIfNotEmpty(size_listener.str(), listener->stream());2331return result;2332}23332334private:2335const Matcher<SizeType> size_matcher_;2336};23372338private:2339const SizeMatcher size_matcher_;2340};23412342// Implements a matcher that checks the begin()..end() distance of an STL-style2343// container.2344template <typename DistanceMatcher>2345class BeginEndDistanceIsMatcher {2346public:2347explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)2348: distance_matcher_(distance_matcher) {}23492350template <typename Container>2351operator Matcher<Container>() const {2352return Matcher<Container>(new Impl<const Container&>(distance_matcher_));2353}23542355template <typename Container>2356class Impl : public MatcherInterface<Container> {2357public:2358typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(2359Container)>2360ContainerView;2361typedef typename std::iterator_traits<2362typename ContainerView::type::const_iterator>::difference_type2363DistanceType;2364explicit Impl(const DistanceMatcher& distance_matcher)2365: distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}23662367void DescribeTo(::std::ostream* os) const override {2368*os << "distance between begin() and end() ";2369distance_matcher_.DescribeTo(os);2370}2371void DescribeNegationTo(::std::ostream* os) const override {2372*os << "distance between begin() and end() ";2373distance_matcher_.DescribeNegationTo(os);2374}23752376bool MatchAndExplain(Container container,2377MatchResultListener* listener) const override {2378using std::begin;2379using std::end;2380DistanceType distance = std::distance(begin(container), end(container));2381StringMatchResultListener distance_listener;2382const bool result =2383distance_matcher_.MatchAndExplain(distance, &distance_listener);2384*listener << "whose distance between begin() and end() " << distance2385<< (result ? " matches" : " doesn't match");2386PrintIfNotEmpty(distance_listener.str(), listener->stream());2387return result;2388}23892390private:2391const Matcher<DistanceType> distance_matcher_;2392};23932394private:2395const DistanceMatcher distance_matcher_;2396};23972398// Implements an equality matcher for any STL-style container whose elements2399// support ==. This matcher is like Eq(), but its failure explanations provide2400// more detailed information that is useful when the container is used as a set.2401// The failure message reports elements that are in one of the operands but not2402// the other. The failure messages do not report duplicate or out-of-order2403// elements in the containers (which don't properly matter to sets, but can2404// occur if the containers are vectors or lists, for example).2405//2406// Uses the container's const_iterator, value_type, operator ==,2407// begin(), and end().2408template <typename Container>2409class ContainerEqMatcher {2410public:2411typedef internal::StlContainerView<Container> View;2412typedef typename View::type StlContainer;2413typedef typename View::const_reference StlContainerReference;24142415static_assert(!std::is_const<Container>::value,2416"Container type must not be const");2417static_assert(!std::is_reference<Container>::value,2418"Container type must not be a reference");24192420// We make a copy of expected in case the elements in it are modified2421// after this matcher is created.2422explicit ContainerEqMatcher(const Container& expected)2423: expected_(View::Copy(expected)) {}24242425void DescribeTo(::std::ostream* os) const {2426*os << "equals ";2427UniversalPrint(expected_, os);2428}2429void DescribeNegationTo(::std::ostream* os) const {2430*os << "does not equal ";2431UniversalPrint(expected_, os);2432}24332434template <typename LhsContainer>2435bool MatchAndExplain(const LhsContainer& lhs,2436MatchResultListener* listener) const {2437typedef internal::StlContainerView<2438typename std::remove_const<LhsContainer>::type>2439LhsView;2440StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);2441if (lhs_stl_container == expected_) return true;24422443::std::ostream* const os = listener->stream();2444if (os != nullptr) {2445// Something is different. Check for extra values first.2446bool printed_header = false;2447for (auto it = lhs_stl_container.begin(); it != lhs_stl_container.end();2448++it) {2449if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==2450expected_.end()) {2451if (printed_header) {2452*os << ", ";2453} else {2454*os << "which has these unexpected elements: ";2455printed_header = true;2456}2457UniversalPrint(*it, os);2458}2459}24602461// Now check for missing values.2462bool printed_header2 = false;2463for (auto it = expected_.begin(); it != expected_.end(); ++it) {2464if (internal::ArrayAwareFind(lhs_stl_container.begin(),2465lhs_stl_container.end(),2466*it) == lhs_stl_container.end()) {2467if (printed_header2) {2468*os << ", ";2469} else {2470*os << (printed_header ? ",\nand" : "which")2471<< " doesn't have these expected elements: ";2472printed_header2 = true;2473}2474UniversalPrint(*it, os);2475}2476}2477}24782479return false;2480}24812482private:2483const StlContainer expected_;2484};24852486// A comparator functor that uses the < operator to compare two values.2487struct LessComparator {2488template <typename T, typename U>2489bool operator()(const T& lhs, const U& rhs) const {2490return lhs < rhs;2491}2492};24932494// Implements WhenSortedBy(comparator, container_matcher).2495template <typename Comparator, typename ContainerMatcher>2496class WhenSortedByMatcher {2497public:2498WhenSortedByMatcher(const Comparator& comparator,2499const ContainerMatcher& matcher)2500: comparator_(comparator), matcher_(matcher) {}25012502template <typename LhsContainer>2503operator Matcher<LhsContainer>() const {2504return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));2505}25062507template <typename LhsContainer>2508class Impl : public MatcherInterface<LhsContainer> {2509public:2510typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(2511LhsContainer)>2512LhsView;2513typedef typename LhsView::type LhsStlContainer;2514typedef typename LhsView::const_reference LhsStlContainerReference;2515// Transforms std::pair<const Key, Value> into std::pair<Key, Value>2516// so that we can match associative containers.2517typedef2518typename RemoveConstFromKey<typename LhsStlContainer::value_type>::type2519LhsValue;25202521Impl(const Comparator& comparator, const ContainerMatcher& matcher)2522: comparator_(comparator), matcher_(matcher) {}25232524void DescribeTo(::std::ostream* os) const override {2525*os << "(when sorted) ";2526matcher_.DescribeTo(os);2527}25282529void DescribeNegationTo(::std::ostream* os) const override {2530*os << "(when sorted) ";2531matcher_.DescribeNegationTo(os);2532}25332534bool MatchAndExplain(LhsContainer lhs,2535MatchResultListener* listener) const override {2536LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);2537::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),2538lhs_stl_container.end());2539::std::sort(sorted_container.begin(), sorted_container.end(),2540comparator_);25412542if (!listener->IsInterested()) {2543// If the listener is not interested, we do not need to2544// construct the inner explanation.2545return matcher_.Matches(sorted_container);2546}25472548*listener << "which is ";2549UniversalPrint(sorted_container, listener->stream());2550*listener << " when sorted";25512552StringMatchResultListener inner_listener;2553const bool match =2554matcher_.MatchAndExplain(sorted_container, &inner_listener);2555PrintIfNotEmpty(inner_listener.str(), listener->stream());2556return match;2557}25582559private:2560const Comparator comparator_;2561const Matcher<const ::std::vector<LhsValue>&> matcher_;25622563Impl(const Impl&) = delete;2564Impl& operator=(const Impl&) = delete;2565};25662567private:2568const Comparator comparator_;2569const ContainerMatcher matcher_;2570};25712572// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher2573// must be able to be safely cast to Matcher<std::tuple<const T1&, const2574// T2&> >, where T1 and T2 are the types of elements in the LHS2575// container and the RHS container respectively.2576template <typename TupleMatcher, typename RhsContainer>2577class PointwiseMatcher {2578static_assert(2579!IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,2580"use UnorderedPointwise with hash tables");25812582public:2583typedef internal::StlContainerView<RhsContainer> RhsView;2584typedef typename RhsView::type RhsStlContainer;2585typedef typename RhsStlContainer::value_type RhsValue;25862587static_assert(!std::is_const<RhsContainer>::value,2588"RhsContainer type must not be const");2589static_assert(!std::is_reference<RhsContainer>::value,2590"RhsContainer type must not be a reference");25912592// Like ContainerEq, we make a copy of rhs in case the elements in2593// it are modified after this matcher is created.2594PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)2595: tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {}25962597template <typename LhsContainer>2598operator Matcher<LhsContainer>() const {2599static_assert(2600!IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,2601"use UnorderedPointwise with hash tables");26022603return Matcher<LhsContainer>(2604new Impl<const LhsContainer&>(tuple_matcher_, rhs_));2605}26062607template <typename LhsContainer>2608class Impl : public MatcherInterface<LhsContainer> {2609public:2610typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(2611LhsContainer)>2612LhsView;2613typedef typename LhsView::type LhsStlContainer;2614typedef typename LhsView::const_reference LhsStlContainerReference;2615typedef typename LhsStlContainer::value_type LhsValue;2616// We pass the LHS value and the RHS value to the inner matcher by2617// reference, as they may be expensive to copy. We must use tuple2618// instead of pair here, as a pair cannot hold references (C++ 98,2619// 20.2.2 [lib.pairs]).2620typedef ::std::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;26212622Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)2623// mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.2624: mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),2625rhs_(rhs) {}26262627void DescribeTo(::std::ostream* os) const override {2628*os << "contains " << rhs_.size()2629<< " values, where each value and its corresponding value in ";2630UniversalPrinter<RhsStlContainer>::Print(rhs_, os);2631*os << " ";2632mono_tuple_matcher_.DescribeTo(os);2633}2634void DescribeNegationTo(::std::ostream* os) const override {2635*os << "doesn't contain exactly " << rhs_.size()2636<< " values, or contains a value x at some index i"2637<< " where x and the i-th value of ";2638UniversalPrint(rhs_, os);2639*os << " ";2640mono_tuple_matcher_.DescribeNegationTo(os);2641}26422643bool MatchAndExplain(LhsContainer lhs,2644MatchResultListener* listener) const override {2645LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);2646const size_t actual_size = lhs_stl_container.size();2647if (actual_size != rhs_.size()) {2648*listener << "which contains " << actual_size << " values";2649return false;2650}26512652auto left = lhs_stl_container.begin();2653auto right = rhs_.begin();2654for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {2655if (listener->IsInterested()) {2656StringMatchResultListener inner_listener;2657// Create InnerMatcherArg as a temporarily object to avoid it outlives2658// *left and *right. Dereference or the conversion to `const T&` may2659// return temp objects, e.g. for vector<bool>.2660if (!mono_tuple_matcher_.MatchAndExplain(2661InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),2662ImplicitCast_<const RhsValue&>(*right)),2663&inner_listener)) {2664*listener << "where the value pair (";2665UniversalPrint(*left, listener->stream());2666*listener << ", ";2667UniversalPrint(*right, listener->stream());2668*listener << ") at index #" << i << " don't match";2669PrintIfNotEmpty(inner_listener.str(), listener->stream());2670return false;2671}2672} else {2673if (!mono_tuple_matcher_.Matches(2674InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),2675ImplicitCast_<const RhsValue&>(*right))))2676return false;2677}2678}26792680return true;2681}26822683private:2684const Matcher<InnerMatcherArg> mono_tuple_matcher_;2685const RhsStlContainer rhs_;2686};26872688private:2689const TupleMatcher tuple_matcher_;2690const RhsStlContainer rhs_;2691};26922693// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.2694template <typename Container>2695class QuantifierMatcherImpl : public MatcherInterface<Container> {2696public:2697typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;2698typedef StlContainerView<RawContainer> View;2699typedef typename View::type StlContainer;2700typedef typename View::const_reference StlContainerReference;2701typedef typename StlContainer::value_type Element;27022703template <typename InnerMatcher>2704explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)2705: inner_matcher_(2706testing::SafeMatcherCast<const Element&>(inner_matcher)) {}27072708// Checks whether:2709// * All elements in the container match, if all_elements_should_match.2710// * Any element in the container matches, if !all_elements_should_match.2711bool MatchAndExplainImpl(bool all_elements_should_match, Container container,2712MatchResultListener* listener) const {2713StlContainerReference stl_container = View::ConstReference(container);2714size_t i = 0;2715for (auto it = stl_container.begin(); it != stl_container.end();2716++it, ++i) {2717StringMatchResultListener inner_listener;2718const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);27192720if (matches != all_elements_should_match) {2721*listener << "whose element #" << i2722<< (matches ? " matches" : " doesn't match");2723PrintIfNotEmpty(inner_listener.str(), listener->stream());2724return !all_elements_should_match;2725}2726}2727return all_elements_should_match;2728}27292730bool MatchAndExplainImpl(const Matcher<size_t>& count_matcher,2731Container container,2732MatchResultListener* listener) const {2733StlContainerReference stl_container = View::ConstReference(container);2734size_t i = 0;2735std::vector<size_t> match_elements;2736for (auto it = stl_container.begin(); it != stl_container.end();2737++it, ++i) {2738StringMatchResultListener inner_listener;2739const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);2740if (matches) {2741match_elements.push_back(i);2742}2743}2744if (listener->IsInterested()) {2745if (match_elements.empty()) {2746*listener << "has no element that matches";2747} else if (match_elements.size() == 1) {2748*listener << "whose element #" << match_elements[0] << " matches";2749} else {2750*listener << "whose elements (";2751std::string sep = "";2752for (size_t e : match_elements) {2753*listener << sep << e;2754sep = ", ";2755}2756*listener << ") match";2757}2758}2759StringMatchResultListener count_listener;2760if (count_matcher.MatchAndExplain(match_elements.size(), &count_listener)) {2761*listener << " and whose match quantity of " << match_elements.size()2762<< " matches";2763PrintIfNotEmpty(count_listener.str(), listener->stream());2764return true;2765} else {2766if (match_elements.empty()) {2767*listener << " and";2768} else {2769*listener << " but";2770}2771*listener << " whose match quantity of " << match_elements.size()2772<< " does not match";2773PrintIfNotEmpty(count_listener.str(), listener->stream());2774return false;2775}2776}27772778protected:2779const Matcher<const Element&> inner_matcher_;2780};27812782// Implements Contains(element_matcher) for the given argument type Container.2783// Symmetric to EachMatcherImpl.2784template <typename Container>2785class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {2786public:2787template <typename InnerMatcher>2788explicit ContainsMatcherImpl(InnerMatcher inner_matcher)2789: QuantifierMatcherImpl<Container>(inner_matcher) {}27902791// Describes what this matcher does.2792void DescribeTo(::std::ostream* os) const override {2793*os << "contains at least one element that ";2794this->inner_matcher_.DescribeTo(os);2795}27962797void DescribeNegationTo(::std::ostream* os) const override {2798*os << "doesn't contain any element that ";2799this->inner_matcher_.DescribeTo(os);2800}28012802bool MatchAndExplain(Container container,2803MatchResultListener* listener) const override {2804return this->MatchAndExplainImpl(false, container, listener);2805}2806};28072808// Implements Each(element_matcher) for the given argument type Container.2809// Symmetric to ContainsMatcherImpl.2810template <typename Container>2811class EachMatcherImpl : public QuantifierMatcherImpl<Container> {2812public:2813template <typename InnerMatcher>2814explicit EachMatcherImpl(InnerMatcher inner_matcher)2815: QuantifierMatcherImpl<Container>(inner_matcher) {}28162817// Describes what this matcher does.2818void DescribeTo(::std::ostream* os) const override {2819*os << "only contains elements that ";2820this->inner_matcher_.DescribeTo(os);2821}28222823void DescribeNegationTo(::std::ostream* os) const override {2824*os << "contains some element that ";2825this->inner_matcher_.DescribeNegationTo(os);2826}28272828bool MatchAndExplain(Container container,2829MatchResultListener* listener) const override {2830return this->MatchAndExplainImpl(true, container, listener);2831}2832};28332834// Implements Contains(element_matcher).Times(n) for the given argument type2835// Container.2836template <typename Container>2837class ContainsTimesMatcherImpl : public QuantifierMatcherImpl<Container> {2838public:2839template <typename InnerMatcher>2840explicit ContainsTimesMatcherImpl(InnerMatcher inner_matcher,2841Matcher<size_t> count_matcher)2842: QuantifierMatcherImpl<Container>(inner_matcher),2843count_matcher_(std::move(count_matcher)) {}28442845void DescribeTo(::std::ostream* os) const override {2846*os << "quantity of elements that match ";2847this->inner_matcher_.DescribeTo(os);2848*os << " ";2849count_matcher_.DescribeTo(os);2850}28512852void DescribeNegationTo(::std::ostream* os) const override {2853*os << "quantity of elements that match ";2854this->inner_matcher_.DescribeTo(os);2855*os << " ";2856count_matcher_.DescribeNegationTo(os);2857}28582859bool MatchAndExplain(Container container,2860MatchResultListener* listener) const override {2861return this->MatchAndExplainImpl(count_matcher_, container, listener);2862}28632864private:2865const Matcher<size_t> count_matcher_;2866};28672868// Implements polymorphic Contains(element_matcher).Times(n).2869template <typename M>2870class ContainsTimesMatcher {2871public:2872explicit ContainsTimesMatcher(M m, Matcher<size_t> count_matcher)2873: inner_matcher_(m), count_matcher_(std::move(count_matcher)) {}28742875template <typename Container>2876operator Matcher<Container>() const { // NOLINT2877return Matcher<Container>(new ContainsTimesMatcherImpl<const Container&>(2878inner_matcher_, count_matcher_));2879}28802881private:2882const M inner_matcher_;2883const Matcher<size_t> count_matcher_;2884};28852886// Implements polymorphic Contains(element_matcher).2887template <typename M>2888class ContainsMatcher {2889public:2890explicit ContainsMatcher(M m) : inner_matcher_(m) {}28912892template <typename Container>2893operator Matcher<Container>() const { // NOLINT2894return Matcher<Container>(2895new ContainsMatcherImpl<const Container&>(inner_matcher_));2896}28972898ContainsTimesMatcher<M> Times(Matcher<size_t> count_matcher) const {2899return ContainsTimesMatcher<M>(inner_matcher_, std::move(count_matcher));2900}29012902private:2903const M inner_matcher_;2904};29052906// Implements polymorphic Each(element_matcher).2907template <typename M>2908class EachMatcher {2909public:2910explicit EachMatcher(M m) : inner_matcher_(m) {}29112912template <typename Container>2913operator Matcher<Container>() const { // NOLINT2914return Matcher<Container>(2915new EachMatcherImpl<const Container&>(inner_matcher_));2916}29172918private:2919const M inner_matcher_;2920};29212922// Use go/ranked-overloads for dispatching.2923struct Rank0 {};2924struct Rank1 : Rank0 {};29252926namespace pair_getters {2927using std::get;2928template <typename T>2929auto First(T& x, Rank0) -> decltype(get<0>(x)) { // NOLINT2930return get<0>(x);2931}2932template <typename T>2933auto First(T& x, Rank1) -> decltype((x.first)) { // NOLINT2934return x.first;2935}29362937template <typename T>2938auto Second(T& x, Rank0) -> decltype(get<1>(x)) { // NOLINT2939return get<1>(x);2940}2941template <typename T>2942auto Second(T& x, Rank1) -> decltype((x.second)) { // NOLINT2943return x.second;2944}2945} // namespace pair_getters29462947// Implements Key(inner_matcher) for the given argument pair type.2948// Key(inner_matcher) matches an std::pair whose 'first' field matches2949// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an2950// std::map that contains at least one element whose key is >= 5.2951template <typename PairType>2952class KeyMatcherImpl : public MatcherInterface<PairType> {2953public:2954typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;2955typedef typename RawPairType::first_type KeyType;29562957template <typename InnerMatcher>2958explicit KeyMatcherImpl(InnerMatcher inner_matcher)2959: inner_matcher_(2960testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {}29612962// Returns true if and only if 'key_value.first' (the key) matches the inner2963// matcher.2964bool MatchAndExplain(PairType key_value,2965MatchResultListener* listener) const override {2966StringMatchResultListener inner_listener;2967const bool match = inner_matcher_.MatchAndExplain(2968pair_getters::First(key_value, Rank1()), &inner_listener);2969const std::string explanation = inner_listener.str();2970if (!explanation.empty()) {2971*listener << "whose first field is a value " << explanation;2972}2973return match;2974}29752976// Describes what this matcher does.2977void DescribeTo(::std::ostream* os) const override {2978*os << "has a key that ";2979inner_matcher_.DescribeTo(os);2980}29812982// Describes what the negation of this matcher does.2983void DescribeNegationTo(::std::ostream* os) const override {2984*os << "doesn't have a key that ";2985inner_matcher_.DescribeTo(os);2986}29872988private:2989const Matcher<const KeyType&> inner_matcher_;2990};29912992// Implements polymorphic Key(matcher_for_key).2993template <typename M>2994class KeyMatcher {2995public:2996explicit KeyMatcher(M m) : matcher_for_key_(m) {}29972998template <typename PairType>2999operator Matcher<PairType>() const {3000return Matcher<PairType>(3001new KeyMatcherImpl<const PairType&>(matcher_for_key_));3002}30033004private:3005const M matcher_for_key_;3006};30073008// Implements polymorphic Address(matcher_for_address).3009template <typename InnerMatcher>3010class AddressMatcher {3011public:3012explicit AddressMatcher(InnerMatcher m) : matcher_(m) {}30133014template <typename Type>3015operator Matcher<Type>() const { // NOLINT3016return Matcher<Type>(new Impl<const Type&>(matcher_));3017}30183019private:3020// The monomorphic implementation that works for a particular object type.3021template <typename Type>3022class Impl : public MatcherInterface<Type> {3023public:3024using Address = const GTEST_REMOVE_REFERENCE_AND_CONST_(Type) *;3025explicit Impl(const InnerMatcher& matcher)3026: matcher_(MatcherCast<Address>(matcher)) {}30273028void DescribeTo(::std::ostream* os) const override {3029*os << "has address that ";3030matcher_.DescribeTo(os);3031}30323033void DescribeNegationTo(::std::ostream* os) const override {3034*os << "does not have address that ";3035matcher_.DescribeTo(os);3036}30373038bool MatchAndExplain(Type object,3039MatchResultListener* listener) const override {3040*listener << "which has address ";3041Address address = std::addressof(object);3042return MatchPrintAndExplain(address, matcher_, listener);3043}30443045private:3046const Matcher<Address> matcher_;3047};3048const InnerMatcher matcher_;3049};30503051// Implements Pair(first_matcher, second_matcher) for the given argument pair3052// type with its two matchers. See Pair() function below.3053template <typename PairType>3054class PairMatcherImpl : public MatcherInterface<PairType> {3055public:3056typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;3057typedef typename RawPairType::first_type FirstType;3058typedef typename RawPairType::second_type SecondType;30593060template <typename FirstMatcher, typename SecondMatcher>3061PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)3062: first_matcher_(3063testing::SafeMatcherCast<const FirstType&>(first_matcher)),3064second_matcher_(3065testing::SafeMatcherCast<const SecondType&>(second_matcher)) {}30663067// Describes what this matcher does.3068void DescribeTo(::std::ostream* os) const override {3069*os << "has a first field that ";3070first_matcher_.DescribeTo(os);3071*os << ", and has a second field that ";3072second_matcher_.DescribeTo(os);3073}30743075// Describes what the negation of this matcher does.3076void DescribeNegationTo(::std::ostream* os) const override {3077*os << "has a first field that ";3078first_matcher_.DescribeNegationTo(os);3079*os << ", or has a second field that ";3080second_matcher_.DescribeNegationTo(os);3081}30823083// Returns true if and only if 'a_pair.first' matches first_matcher and3084// 'a_pair.second' matches second_matcher.3085bool MatchAndExplain(PairType a_pair,3086MatchResultListener* listener) const override {3087if (!listener->IsInterested()) {3088// If the listener is not interested, we don't need to construct the3089// explanation.3090return first_matcher_.Matches(pair_getters::First(a_pair, Rank1())) &&3091second_matcher_.Matches(pair_getters::Second(a_pair, Rank1()));3092}3093StringMatchResultListener first_inner_listener;3094if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank1()),3095&first_inner_listener)) {3096*listener << "whose first field does not match";3097PrintIfNotEmpty(first_inner_listener.str(), listener->stream());3098return false;3099}3100StringMatchResultListener second_inner_listener;3101if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank1()),3102&second_inner_listener)) {3103*listener << "whose second field does not match";3104PrintIfNotEmpty(second_inner_listener.str(), listener->stream());3105return false;3106}3107ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),3108listener);3109return true;3110}31113112private:3113void ExplainSuccess(const std::string& first_explanation,3114const std::string& second_explanation,3115MatchResultListener* listener) const {3116*listener << "whose both fields match";3117if (!first_explanation.empty()) {3118*listener << ", where the first field is a value " << first_explanation;3119}3120if (!second_explanation.empty()) {3121*listener << ", ";3122if (!first_explanation.empty()) {3123*listener << "and ";3124} else {3125*listener << "where ";3126}3127*listener << "the second field is a value " << second_explanation;3128}3129}31303131const Matcher<const FirstType&> first_matcher_;3132const Matcher<const SecondType&> second_matcher_;3133};31343135// Implements polymorphic Pair(first_matcher, second_matcher).3136template <typename FirstMatcher, typename SecondMatcher>3137class PairMatcher {3138public:3139PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)3140: first_matcher_(first_matcher), second_matcher_(second_matcher) {}31413142template <typename PairType>3143operator Matcher<PairType>() const {3144return Matcher<PairType>(3145new PairMatcherImpl<const PairType&>(first_matcher_, second_matcher_));3146}31473148private:3149const FirstMatcher first_matcher_;3150const SecondMatcher second_matcher_;3151};31523153template <typename T, size_t... I>3154auto UnpackStructImpl(const T& t, std::index_sequence<I...>,3155int) -> decltype(std::tie(get<I>(t)...)) {3156static_assert(std::tuple_size<T>::value == sizeof...(I),3157"Number of arguments doesn't match the number of fields.");3158return std::tie(get<I>(t)...);3159}31603161#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 2016063162template <typename T>3163auto UnpackStructImpl(const T& t, std::make_index_sequence<1>, char) {3164const auto& [a] = t;3165return std::tie(a);3166}3167template <typename T>3168auto UnpackStructImpl(const T& t, std::make_index_sequence<2>, char) {3169const auto& [a, b] = t;3170return std::tie(a, b);3171}3172template <typename T>3173auto UnpackStructImpl(const T& t, std::make_index_sequence<3>, char) {3174const auto& [a, b, c] = t;3175return std::tie(a, b, c);3176}3177template <typename T>3178auto UnpackStructImpl(const T& t, std::make_index_sequence<4>, char) {3179const auto& [a, b, c, d] = t;3180return std::tie(a, b, c, d);3181}3182template <typename T>3183auto UnpackStructImpl(const T& t, std::make_index_sequence<5>, char) {3184const auto& [a, b, c, d, e] = t;3185return std::tie(a, b, c, d, e);3186}3187template <typename T>3188auto UnpackStructImpl(const T& t, std::make_index_sequence<6>, char) {3189const auto& [a, b, c, d, e, f] = t;3190return std::tie(a, b, c, d, e, f);3191}3192template <typename T>3193auto UnpackStructImpl(const T& t, std::make_index_sequence<7>, char) {3194const auto& [a, b, c, d, e, f, g] = t;3195return std::tie(a, b, c, d, e, f, g);3196}3197template <typename T>3198auto UnpackStructImpl(const T& t, std::make_index_sequence<8>, char) {3199const auto& [a, b, c, d, e, f, g, h] = t;3200return std::tie(a, b, c, d, e, f, g, h);3201}3202template <typename T>3203auto UnpackStructImpl(const T& t, std::make_index_sequence<9>, char) {3204const auto& [a, b, c, d, e, f, g, h, i] = t;3205return std::tie(a, b, c, d, e, f, g, h, i);3206}3207template <typename T>3208auto UnpackStructImpl(const T& t, std::make_index_sequence<10>, char) {3209const auto& [a, b, c, d, e, f, g, h, i, j] = t;3210return std::tie(a, b, c, d, e, f, g, h, i, j);3211}3212template <typename T>3213auto UnpackStructImpl(const T& t, std::make_index_sequence<11>, char) {3214const auto& [a, b, c, d, e, f, g, h, i, j, k] = t;3215return std::tie(a, b, c, d, e, f, g, h, i, j, k);3216}3217template <typename T>3218auto UnpackStructImpl(const T& t, std::make_index_sequence<12>, char) {3219const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t;3220return std::tie(a, b, c, d, e, f, g, h, i, j, k, l);3221}3222template <typename T>3223auto UnpackStructImpl(const T& t, std::make_index_sequence<13>, char) {3224const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t;3225return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m);3226}3227template <typename T>3228auto UnpackStructImpl(const T& t, std::make_index_sequence<14>, char) {3229const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t;3230return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n);3231}3232template <typename T>3233auto UnpackStructImpl(const T& t, std::make_index_sequence<15>, char) {3234const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t;3235return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);3236}3237template <typename T>3238auto UnpackStructImpl(const T& t, std::make_index_sequence<16>, char) {3239const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t;3240return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);3241}3242template <typename T>3243auto UnpackStructImpl(const T& t, std::make_index_sequence<17>, char) {3244const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q] = t;3245return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q);3246}3247template <typename T>3248auto UnpackStructImpl(const T& t, std::make_index_sequence<18>, char) {3249const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r] = t;3250return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r);3251}3252template <typename T>3253auto UnpackStructImpl(const T& t, std::make_index_sequence<19>, char) {3254const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s] = t;3255return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s);3256}3257#endif // defined(__cpp_structured_bindings)32583259template <size_t I, typename T>3260auto UnpackStruct(const T& t)3261-> decltype((UnpackStructImpl)(t, std::make_index_sequence<I>{}, 0)) {3262return (UnpackStructImpl)(t, std::make_index_sequence<I>{}, 0);3263}32643265// Helper function to do comma folding in C++11.3266// The array ensures left-to-right order of evaluation.3267// Usage: VariadicExpand({expr...});3268template <typename T, size_t N>3269void VariadicExpand(const T (&)[N]) {}32703271template <typename Struct, typename StructSize>3272class FieldsAreMatcherImpl;32733274template <typename Struct, size_t... I>3275class FieldsAreMatcherImpl<Struct, std::index_sequence<I...>>3276: public MatcherInterface<Struct> {3277using UnpackedType =3278decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>()));3279using MatchersType = std::tuple<3280Matcher<const typename std::tuple_element<I, UnpackedType>::type&>...>;32813282public:3283template <typename Inner>3284explicit FieldsAreMatcherImpl(const Inner& matchers)3285: matchers_(testing::SafeMatcherCast<3286const typename std::tuple_element<I, UnpackedType>::type&>(3287std::get<I>(matchers))...) {}32883289void DescribeTo(::std::ostream* os) const override {3290const char* separator = "";3291VariadicExpand(3292{(*os << separator << "has field #" << I << " that ",3293std::get<I>(matchers_).DescribeTo(os), separator = ", and ")...});3294}32953296void DescribeNegationTo(::std::ostream* os) const override {3297const char* separator = "";3298VariadicExpand({(*os << separator << "has field #" << I << " that ",3299std::get<I>(matchers_).DescribeNegationTo(os),3300separator = ", or ")...});3301}33023303bool MatchAndExplain(Struct t, MatchResultListener* listener) const override {3304return MatchInternal((UnpackStruct<sizeof...(I)>)(t), listener);3305}33063307private:3308bool MatchInternal(UnpackedType tuple, MatchResultListener* listener) const {3309if (!listener->IsInterested()) {3310// If the listener is not interested, we don't need to construct the3311// explanation.3312bool good = true;3313VariadicExpand({good = good && std::get<I>(matchers_).Matches(3314std::get<I>(tuple))...});3315return good;3316}33173318size_t failed_pos = ~size_t{};33193320std::vector<StringMatchResultListener> inner_listener(sizeof...(I));33213322VariadicExpand(3323{failed_pos == ~size_t{} && !std::get<I>(matchers_).MatchAndExplain(3324std::get<I>(tuple), &inner_listener[I])3325? failed_pos = I3326: 0 ...});3327if (failed_pos != ~size_t{}) {3328*listener << "whose field #" << failed_pos << " does not match";3329PrintIfNotEmpty(inner_listener[failed_pos].str(), listener->stream());3330return false;3331}33323333*listener << "whose all elements match";3334const char* separator = ", where";3335for (size_t index = 0; index < sizeof...(I); ++index) {3336const std::string str = inner_listener[index].str();3337if (!str.empty()) {3338*listener << separator << " field #" << index << " is a value " << str;3339separator = ", and";3340}3341}33423343return true;3344}33453346MatchersType matchers_;3347};33483349template <typename... Inner>3350class FieldsAreMatcher {3351public:3352explicit FieldsAreMatcher(Inner... inner) : matchers_(std::move(inner)...) {}33533354template <typename Struct>3355operator Matcher<Struct>() const { // NOLINT3356return Matcher<Struct>(3357new FieldsAreMatcherImpl<const Struct&,3358std::index_sequence_for<Inner...>>(matchers_));3359}33603361private:3362std::tuple<Inner...> matchers_;3363};33643365// Implements ElementsAre() and ElementsAreArray().3366template <typename Container>3367class ElementsAreMatcherImpl : public MatcherInterface<Container> {3368public:3369typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;3370typedef internal::StlContainerView<RawContainer> View;3371typedef typename View::type StlContainer;3372typedef typename View::const_reference StlContainerReference;3373typedef typename StlContainer::value_type Element;33743375// Constructs the matcher from a sequence of element values or3376// element matchers.3377template <typename InputIter>3378ElementsAreMatcherImpl(InputIter first, InputIter last) {3379while (first != last) {3380matchers_.push_back(MatcherCast<const Element&>(*first++));3381}3382}33833384// Describes what this matcher does.3385void DescribeTo(::std::ostream* os) const override {3386if (count() == 0) {3387*os << "is empty";3388} else if (count() == 1) {3389*os << "has 1 element that ";3390matchers_[0].DescribeTo(os);3391} else {3392*os << "has " << Elements(count()) << " where\n";3393for (size_t i = 0; i != count(); ++i) {3394*os << "element #" << i << " ";3395matchers_[i].DescribeTo(os);3396if (i + 1 < count()) {3397*os << ",\n";3398}3399}3400}3401}34023403// Describes what the negation of this matcher does.3404void DescribeNegationTo(::std::ostream* os) const override {3405if (count() == 0) {3406*os << "isn't empty";3407return;3408}34093410*os << "doesn't have " << Elements(count()) << ", or\n";3411for (size_t i = 0; i != count(); ++i) {3412*os << "element #" << i << " ";3413matchers_[i].DescribeNegationTo(os);3414if (i + 1 < count()) {3415*os << ", or\n";3416}3417}3418}34193420bool MatchAndExplain(Container container,3421MatchResultListener* listener) const override {3422// To work with stream-like "containers", we must only walk3423// through the elements in one pass.34243425const bool listener_interested = listener->IsInterested();34263427// explanations[i] is the explanation of the element at index i.3428::std::vector<std::string> explanations(count());3429StlContainerReference stl_container = View::ConstReference(container);3430auto it = stl_container.begin();3431size_t exam_pos = 0;3432bool mismatch_found = false; // Have we found a mismatched element yet?34333434// Go through the elements and matchers in pairs, until we reach3435// the end of either the elements or the matchers, or until we find a3436// mismatch.3437for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {3438bool match; // Does the current element match the current matcher?3439if (listener_interested) {3440StringMatchResultListener s;3441match = matchers_[exam_pos].MatchAndExplain(*it, &s);3442explanations[exam_pos] = s.str();3443} else {3444match = matchers_[exam_pos].Matches(*it);3445}34463447if (!match) {3448mismatch_found = true;3449break;3450}3451}3452// If mismatch_found is true, 'exam_pos' is the index of the mismatch.34533454// Find how many elements the actual container has. We avoid3455// calling size() s.t. this code works for stream-like "containers"3456// that don't define size().3457size_t actual_count = exam_pos;3458for (; it != stl_container.end(); ++it) {3459++actual_count;3460}34613462if (actual_count != count()) {3463// The element count doesn't match. If the container is empty,3464// there's no need to explain anything as Google Mock already3465// prints the empty container. Otherwise we just need to show3466// how many elements there actually are.3467if (listener_interested && (actual_count != 0)) {3468*listener << "which has " << Elements(actual_count);3469}3470return false;3471}34723473if (mismatch_found) {3474// The element count matches, but the exam_pos-th element doesn't match.3475if (listener_interested) {3476*listener << "whose element #" << exam_pos << " doesn't match";3477PrintIfNotEmpty(explanations[exam_pos], listener->stream());3478}3479return false;3480}34813482// Every element matches its expectation. We need to explain why3483// (the obvious ones can be skipped).3484if (listener_interested) {3485bool reason_printed = false;3486for (size_t i = 0; i != count(); ++i) {3487const std::string& s = explanations[i];3488if (!s.empty()) {3489if (reason_printed) {3490*listener << ",\nand ";3491}3492*listener << "whose element #" << i << " matches, " << s;3493reason_printed = true;3494}3495}3496}3497return true;3498}34993500private:3501static Message Elements(size_t count) {3502return Message() << count << (count == 1 ? " element" : " elements");3503}35043505size_t count() const { return matchers_.size(); }35063507::std::vector<Matcher<const Element&>> matchers_;3508};35093510// Connectivity matrix of (elements X matchers), in element-major order.3511// Initially, there are no edges.3512// Use NextGraph() to iterate over all possible edge configurations.3513// Use Randomize() to generate a random edge configuration.3514class GTEST_API_ MatchMatrix {3515public:3516MatchMatrix(size_t num_elements, size_t num_matchers)3517: num_elements_(num_elements),3518num_matchers_(num_matchers),3519matched_(num_elements_ * num_matchers_, 0) {}35203521size_t LhsSize() const { return num_elements_; }3522size_t RhsSize() const { return num_matchers_; }3523bool HasEdge(size_t ilhs, size_t irhs) const {3524return matched_[SpaceIndex(ilhs, irhs)] == 1;3525}3526void SetEdge(size_t ilhs, size_t irhs, bool b) {3527matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;3528}35293530// Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,3531// adds 1 to that number; returns false if incrementing the graph left it3532// empty.3533bool NextGraph();35343535void Randomize();35363537std::string DebugString() const;35383539private:3540size_t SpaceIndex(size_t ilhs, size_t irhs) const {3541return ilhs * num_matchers_ + irhs;3542}35433544size_t num_elements_;3545size_t num_matchers_;35463547// Each element is a char interpreted as bool. They are stored as a3548// flattened array in lhs-major order, use 'SpaceIndex()' to translate3549// a (ilhs, irhs) matrix coordinate into an offset.3550::std::vector<char> matched_;3551};35523553typedef ::std::pair<size_t, size_t> ElementMatcherPair;3554typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;35553556// Returns a maximum bipartite matching for the specified graph 'g'.3557// The matching is represented as a vector of {element, matcher} pairs.3558GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g);35593560struct UnorderedMatcherRequire {3561enum Flags {3562Superset = 1 << 0,3563Subset = 1 << 1,3564ExactMatch = Superset | Subset,3565};3566};35673568// Untyped base class for implementing UnorderedElementsAre. By3569// putting logic that's not specific to the element type here, we3570// reduce binary bloat and increase compilation speed.3571class GTEST_API_ UnorderedElementsAreMatcherImplBase {3572protected:3573explicit UnorderedElementsAreMatcherImplBase(3574UnorderedMatcherRequire::Flags matcher_flags)3575: match_flags_(matcher_flags) {}35763577// A vector of matcher describers, one for each element matcher.3578// Does not own the describers (and thus can be used only when the3579// element matchers are alive).3580typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;35813582// Describes this UnorderedElementsAre matcher.3583void DescribeToImpl(::std::ostream* os) const;35843585// Describes the negation of this UnorderedElementsAre matcher.3586void DescribeNegationToImpl(::std::ostream* os) const;35873588bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,3589const MatchMatrix& matrix,3590MatchResultListener* listener) const;35913592bool FindPairing(const MatchMatrix& matrix,3593MatchResultListener* listener) const;35943595MatcherDescriberVec& matcher_describers() { return matcher_describers_; }35963597static Message Elements(size_t n) {3598return Message() << n << " element" << (n == 1 ? "" : "s");3599}36003601UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }36023603private:3604UnorderedMatcherRequire::Flags match_flags_;3605MatcherDescriberVec matcher_describers_;3606};36073608// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and3609// IsSupersetOf.3610template <typename Container>3611class UnorderedElementsAreMatcherImpl3612: public MatcherInterface<Container>,3613public UnorderedElementsAreMatcherImplBase {3614public:3615typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;3616typedef internal::StlContainerView<RawContainer> View;3617typedef typename View::type StlContainer;3618typedef typename View::const_reference StlContainerReference;3619typedef typename StlContainer::value_type Element;36203621template <typename InputIter>3622UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,3623InputIter first, InputIter last)3624: UnorderedElementsAreMatcherImplBase(matcher_flags) {3625for (; first != last; ++first) {3626matchers_.push_back(MatcherCast<const Element&>(*first));3627}3628for (const auto& m : matchers_) {3629matcher_describers().push_back(m.GetDescriber());3630}3631}36323633// Describes what this matcher does.3634void DescribeTo(::std::ostream* os) const override {3635return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);3636}36373638// Describes what the negation of this matcher does.3639void DescribeNegationTo(::std::ostream* os) const override {3640return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);3641}36423643bool MatchAndExplain(Container container,3644MatchResultListener* listener) const override {3645StlContainerReference stl_container = View::ConstReference(container);3646::std::vector<std::string> element_printouts;3647MatchMatrix matrix =3648AnalyzeElements(stl_container.begin(), stl_container.end(),3649&element_printouts, listener);36503651return VerifyMatchMatrix(element_printouts, matrix, listener) &&3652FindPairing(matrix, listener);3653}36543655private:3656template <typename ElementIter>3657MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,3658::std::vector<std::string>* element_printouts,3659MatchResultListener* listener) const {3660element_printouts->clear();3661::std::vector<char> did_match;3662size_t num_elements = 0;3663DummyMatchResultListener dummy;3664for (; elem_first != elem_last; ++num_elements, ++elem_first) {3665if (listener->IsInterested()) {3666element_printouts->push_back(PrintToString(*elem_first));3667}3668for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {3669did_match.push_back(3670matchers_[irhs].MatchAndExplain(*elem_first, &dummy));3671}3672}36733674MatchMatrix matrix(num_elements, matchers_.size());3675::std::vector<char>::const_iterator did_match_iter = did_match.begin();3676for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {3677for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {3678matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);3679}3680}3681return matrix;3682}36833684::std::vector<Matcher<const Element&>> matchers_;3685};36863687// Functor for use in TransformTuple.3688// Performs MatcherCast<Target> on an input argument of any type.3689template <typename Target>3690struct CastAndAppendTransform {3691template <typename Arg>3692Matcher<Target> operator()(const Arg& a) const {3693return MatcherCast<Target>(a);3694}3695};36963697// Implements UnorderedElementsAre.3698template <typename MatcherTuple>3699class UnorderedElementsAreMatcher {3700public:3701explicit UnorderedElementsAreMatcher(const MatcherTuple& args)3702: matchers_(args) {}37033704template <typename Container>3705operator Matcher<Container>() const {3706typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;3707typedef typename internal::StlContainerView<RawContainer>::type View;3708typedef typename View::value_type Element;3709typedef ::std::vector<Matcher<const Element&>> MatcherVec;3710MatcherVec matchers;3711matchers.reserve(::std::tuple_size<MatcherTuple>::value);3712TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,3713::std::back_inserter(matchers));3714return Matcher<Container>(3715new UnorderedElementsAreMatcherImpl<const Container&>(3716UnorderedMatcherRequire::ExactMatch, matchers.begin(),3717matchers.end()));3718}37193720private:3721const MatcherTuple matchers_;3722};37233724// Implements ElementsAre.3725template <typename MatcherTuple>3726class ElementsAreMatcher {3727public:3728explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}37293730template <typename Container>3731operator Matcher<Container>() const {3732static_assert(3733!IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||3734::std::tuple_size<MatcherTuple>::value < 2,3735"use UnorderedElementsAre with hash tables");37363737typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;3738typedef typename internal::StlContainerView<RawContainer>::type View;3739typedef typename View::value_type Element;3740typedef ::std::vector<Matcher<const Element&>> MatcherVec;3741MatcherVec matchers;3742matchers.reserve(::std::tuple_size<MatcherTuple>::value);3743TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,3744::std::back_inserter(matchers));3745return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(3746matchers.begin(), matchers.end()));3747}37483749private:3750const MatcherTuple matchers_;3751};37523753// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().3754template <typename T>3755class UnorderedElementsAreArrayMatcher {3756public:3757template <typename Iter>3758UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,3759Iter first, Iter last)3760: match_flags_(match_flags), matchers_(first, last) {}37613762template <typename Container>3763operator Matcher<Container>() const {3764return Matcher<Container>(3765new UnorderedElementsAreMatcherImpl<const Container&>(3766match_flags_, matchers_.begin(), matchers_.end()));3767}37683769private:3770UnorderedMatcherRequire::Flags match_flags_;3771::std::vector<T> matchers_;3772};37733774// Implements ElementsAreArray().3775template <typename T>3776class ElementsAreArrayMatcher {3777public:3778template <typename Iter>3779ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}37803781template <typename Container>3782operator Matcher<Container>() const {3783static_assert(3784!IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,3785"use UnorderedElementsAreArray with hash tables");37863787return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(3788matchers_.begin(), matchers_.end()));3789}37903791private:3792const ::std::vector<T> matchers_;3793};37943795// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second3796// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,3797// second) is a polymorphic matcher that matches a value x if and only if3798// tm matches tuple (x, second). Useful for implementing3799// UnorderedPointwise() in terms of UnorderedElementsAreArray().3800//3801// BoundSecondMatcher is copyable and assignable, as we need to put3802// instances of this class in a vector when implementing3803// UnorderedPointwise().3804template <typename Tuple2Matcher, typename Second>3805class BoundSecondMatcher {3806public:3807BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)3808: tuple2_matcher_(tm), second_value_(second) {}38093810BoundSecondMatcher(const BoundSecondMatcher& other) = default;38113812template <typename T>3813operator Matcher<T>() const {3814return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));3815}38163817// We have to define this for UnorderedPointwise() to compile in3818// C++98 mode, as it puts BoundSecondMatcher instances in a vector,3819// which requires the elements to be assignable in C++98. The3820// compiler cannot generate the operator= for us, as Tuple2Matcher3821// and Second may not be assignable.3822//3823// However, this should never be called, so the implementation just3824// need to assert.3825void operator=(const BoundSecondMatcher& /*rhs*/) {3826GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";3827}38283829private:3830template <typename T>3831class Impl : public MatcherInterface<T> {3832public:3833typedef ::std::tuple<T, Second> ArgTuple;38343835Impl(const Tuple2Matcher& tm, const Second& second)3836: mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),3837second_value_(second) {}38383839void DescribeTo(::std::ostream* os) const override {3840*os << "and ";3841UniversalPrint(second_value_, os);3842*os << " ";3843mono_tuple2_matcher_.DescribeTo(os);3844}38453846bool MatchAndExplain(T x, MatchResultListener* listener) const override {3847return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),3848listener);3849}38503851private:3852const Matcher<const ArgTuple&> mono_tuple2_matcher_;3853const Second second_value_;3854};38553856const Tuple2Matcher tuple2_matcher_;3857const Second second_value_;3858};38593860// Given a 2-tuple matcher tm and a value second,3861// MatcherBindSecond(tm, second) returns a matcher that matches a3862// value x if and only if tm matches tuple (x, second). Useful for3863// implementing UnorderedPointwise() in terms of UnorderedElementsAreArray().3864template <typename Tuple2Matcher, typename Second>3865BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(3866const Tuple2Matcher& tm, const Second& second) {3867return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);3868}38693870// Returns the description for a matcher defined using the MATCHER*()3871// macro where the user-supplied description string is "", if3872// 'negation' is false; otherwise returns the description of the3873// negation of the matcher. 'param_values' contains a list of strings3874// that are the print-out of the matcher's parameters.3875GTEST_API_ std::string FormatMatcherDescription(3876bool negation, const char* matcher_name,3877const std::vector<const char*>& param_names, const Strings& param_values);38783879// Implements a matcher that checks the value of a optional<> type variable.3880template <typename ValueMatcher>3881class OptionalMatcher {3882public:3883explicit OptionalMatcher(const ValueMatcher& value_matcher)3884: value_matcher_(value_matcher) {}38853886template <typename Optional>3887operator Matcher<Optional>() const {3888return Matcher<Optional>(new Impl<const Optional&>(value_matcher_));3889}38903891template <typename Optional>3892class Impl : public MatcherInterface<Optional> {3893public:3894typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;3895typedef typename OptionalView::value_type ValueType;3896explicit Impl(const ValueMatcher& value_matcher)3897: value_matcher_(MatcherCast<ValueType>(value_matcher)) {}38983899void DescribeTo(::std::ostream* os) const override {3900*os << "value ";3901value_matcher_.DescribeTo(os);3902}39033904void DescribeNegationTo(::std::ostream* os) const override {3905*os << "value ";3906value_matcher_.DescribeNegationTo(os);3907}39083909bool MatchAndExplain(Optional optional,3910MatchResultListener* listener) const override {3911if (!optional) {3912*listener << "which is not engaged";3913return false;3914}3915const ValueType& value = *optional;3916StringMatchResultListener value_listener;3917const bool match = value_matcher_.MatchAndExplain(value, &value_listener);3918*listener << "whose value " << PrintToString(value)3919<< (match ? " matches" : " doesn't match");3920PrintIfNotEmpty(value_listener.str(), listener->stream());3921return match;3922}39233924private:3925const Matcher<ValueType> value_matcher_;3926};39273928private:3929const ValueMatcher value_matcher_;3930};39313932namespace variant_matcher {3933// Overloads to allow VariantMatcher to do proper ADL lookup.3934template <typename T>3935void holds_alternative() {}3936template <typename T>3937void get() {}39383939// Implements a matcher that checks the value of a variant<> type variable.3940template <typename T>3941class VariantMatcher {3942public:3943explicit VariantMatcher(::testing::Matcher<const T&> matcher)3944: matcher_(std::move(matcher)) {}39453946template <typename Variant>3947bool MatchAndExplain(const Variant& value,3948::testing::MatchResultListener* listener) const {3949using std::get;3950if (!listener->IsInterested()) {3951return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));3952}39533954if (!holds_alternative<T>(value)) {3955*listener << "whose value is not of type '" << GetTypeName() << "'";3956return false;3957}39583959const T& elem = get<T>(value);3960StringMatchResultListener elem_listener;3961const bool match = matcher_.MatchAndExplain(elem, &elem_listener);3962*listener << "whose value " << PrintToString(elem)3963<< (match ? " matches" : " doesn't match");3964PrintIfNotEmpty(elem_listener.str(), listener->stream());3965return match;3966}39673968void DescribeTo(std::ostream* os) const {3969*os << "is a variant<> with value of type '" << GetTypeName()3970<< "' and the value ";3971matcher_.DescribeTo(os);3972}39733974void DescribeNegationTo(std::ostream* os) const {3975*os << "is a variant<> with value of type other than '" << GetTypeName()3976<< "' or the value ";3977matcher_.DescribeNegationTo(os);3978}39793980private:3981static std::string GetTypeName() {3982#if GTEST_HAS_RTTI3983GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(3984return internal::GetTypeName<T>());3985#endif3986return "the element type";3987}39883989const ::testing::Matcher<const T&> matcher_;3990};39913992} // namespace variant_matcher39933994namespace any_cast_matcher {39953996// Overloads to allow AnyCastMatcher to do proper ADL lookup.3997template <typename T>3998void any_cast() {}39994000// Implements a matcher that any_casts the value.4001template <typename T>4002class AnyCastMatcher {4003public:4004explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)4005: matcher_(matcher) {}40064007template <typename AnyType>4008bool MatchAndExplain(const AnyType& value,4009::testing::MatchResultListener* listener) const {4010if (!listener->IsInterested()) {4011const T* ptr = any_cast<T>(&value);4012return ptr != nullptr && matcher_.Matches(*ptr);4013}40144015const T* elem = any_cast<T>(&value);4016if (elem == nullptr) {4017*listener << "whose value is not of type '" << GetTypeName() << "'";4018return false;4019}40204021StringMatchResultListener elem_listener;4022const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);4023*listener << "whose value " << PrintToString(*elem)4024<< (match ? " matches" : " doesn't match");4025PrintIfNotEmpty(elem_listener.str(), listener->stream());4026return match;4027}40284029void DescribeTo(std::ostream* os) const {4030*os << "is an 'any' type with value of type '" << GetTypeName()4031<< "' and the value ";4032matcher_.DescribeTo(os);4033}40344035void DescribeNegationTo(std::ostream* os) const {4036*os << "is an 'any' type with value of type other than '" << GetTypeName()4037<< "' or the value ";4038matcher_.DescribeNegationTo(os);4039}40404041private:4042static std::string GetTypeName() {4043#if GTEST_HAS_RTTI4044GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(4045return internal::GetTypeName<T>());4046#endif4047return "the element type";4048}40494050const ::testing::Matcher<const T&> matcher_;4051};40524053} // namespace any_cast_matcher40544055// Implements the Args() matcher.4056template <class ArgsTuple, size_t... k>4057class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {4058public:4059using RawArgsTuple = typename std::decay<ArgsTuple>::type;4060using SelectedArgs =4061std::tuple<typename std::tuple_element<k, RawArgsTuple>::type...>;4062using MonomorphicInnerMatcher = Matcher<const SelectedArgs&>;40634064template <typename InnerMatcher>4065explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)4066: inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}40674068bool MatchAndExplain(ArgsTuple args,4069MatchResultListener* listener) const override {4070// Workaround spurious C4100 on MSVC<=15.7 when k is empty.4071(void)args;4072const SelectedArgs& selected_args =4073std::forward_as_tuple(std::get<k>(args)...);4074if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args);40754076PrintIndices(listener->stream());4077*listener << "are " << PrintToString(selected_args);40784079StringMatchResultListener inner_listener;4080const bool match =4081inner_matcher_.MatchAndExplain(selected_args, &inner_listener);4082PrintIfNotEmpty(inner_listener.str(), listener->stream());4083return match;4084}40854086void DescribeTo(::std::ostream* os) const override {4087*os << "are a tuple ";4088PrintIndices(os);4089inner_matcher_.DescribeTo(os);4090}40914092void DescribeNegationTo(::std::ostream* os) const override {4093*os << "are a tuple ";4094PrintIndices(os);4095inner_matcher_.DescribeNegationTo(os);4096}40974098private:4099// Prints the indices of the selected fields.4100static void PrintIndices(::std::ostream* os) {4101*os << "whose fields (";4102const char* sep = "";4103// Workaround spurious C4189 on MSVC<=15.7 when k is empty.4104(void)sep;4105// The static_cast to void is needed to silence Clang's -Wcomma warning.4106// This pattern looks suspiciously like we may have mismatched parentheses4107// and may have been trying to use the first operation of the comma operator4108// as a member of the array, so Clang warns that we may have made a mistake.4109const char* dummy[] = {4110"", (static_cast<void>(*os << sep << "#" << k), sep = ", ")...};4111(void)dummy;4112*os << ") ";4113}41144115MonomorphicInnerMatcher inner_matcher_;4116};41174118template <class InnerMatcher, size_t... k>4119class ArgsMatcher {4120public:4121explicit ArgsMatcher(InnerMatcher inner_matcher)4122: inner_matcher_(std::move(inner_matcher)) {}41234124template <typename ArgsTuple>4125operator Matcher<ArgsTuple>() const { // NOLINT4126return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k...>(inner_matcher_));4127}41284129private:4130InnerMatcher inner_matcher_;4131};41324133} // namespace internal41344135// ElementsAreArray(iterator_first, iterator_last)4136// ElementsAreArray(pointer, count)4137// ElementsAreArray(array)4138// ElementsAreArray(container)4139// ElementsAreArray({ e1, e2, ..., en })4140//4141// The ElementsAreArray() functions are like ElementsAre(...), except4142// that they are given a homogeneous sequence rather than taking each4143// element as a function argument. The sequence can be specified as an4144// array, a pointer and count, a vector, an initializer list, or an4145// STL iterator range. In each of these cases, the underlying sequence4146// can be either a sequence of values or a sequence of matchers.4147//4148// All forms of ElementsAreArray() make a copy of the input matcher sequence.41494150template <typename Iter>4151inline internal::ElementsAreArrayMatcher<4152typename ::std::iterator_traits<Iter>::value_type>4153ElementsAreArray(Iter first, Iter last) {4154typedef typename ::std::iterator_traits<Iter>::value_type T;4155return internal::ElementsAreArrayMatcher<T>(first, last);4156}41574158template <typename T>4159inline auto ElementsAreArray(const T* pointer, size_t count)4160-> decltype(ElementsAreArray(pointer, pointer + count)) {4161return ElementsAreArray(pointer, pointer + count);4162}41634164template <typename T, size_t N>4165inline auto ElementsAreArray(const T (&array)[N])4166-> decltype(ElementsAreArray(array, N)) {4167return ElementsAreArray(array, N);4168}41694170template <typename Container>4171inline auto ElementsAreArray(const Container& container)4172-> decltype(ElementsAreArray(container.begin(), container.end())) {4173return ElementsAreArray(container.begin(), container.end());4174}41754176template <typename T>4177inline auto ElementsAreArray(::std::initializer_list<T> xs)4178-> decltype(ElementsAreArray(xs.begin(), xs.end())) {4179return ElementsAreArray(xs.begin(), xs.end());4180}41814182// UnorderedElementsAreArray(iterator_first, iterator_last)4183// UnorderedElementsAreArray(pointer, count)4184// UnorderedElementsAreArray(array)4185// UnorderedElementsAreArray(container)4186// UnorderedElementsAreArray({ e1, e2, ..., en })4187//4188// UnorderedElementsAreArray() verifies that a bijective mapping onto a4189// collection of matchers exists.4190//4191// The matchers can be specified as an array, a pointer and count, a container,4192// an initializer list, or an STL iterator range. In each of these cases, the4193// underlying matchers can be either values or matchers.41944195template <typename Iter>4196inline internal::UnorderedElementsAreArrayMatcher<4197typename ::std::iterator_traits<Iter>::value_type>4198UnorderedElementsAreArray(Iter first, Iter last) {4199typedef typename ::std::iterator_traits<Iter>::value_type T;4200return internal::UnorderedElementsAreArrayMatcher<T>(4201internal::UnorderedMatcherRequire::ExactMatch, first, last);4202}42034204template <typename T>4205inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(4206const T* pointer, size_t count) {4207return UnorderedElementsAreArray(pointer, pointer + count);4208}42094210template <typename T, size_t N>4211inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(4212const T (&array)[N]) {4213return UnorderedElementsAreArray(array, N);4214}42154216template <typename Container>4217inline internal::UnorderedElementsAreArrayMatcher<4218typename Container::value_type>4219UnorderedElementsAreArray(const Container& container) {4220return UnorderedElementsAreArray(container.begin(), container.end());4221}42224223template <typename T>4224inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(4225::std::initializer_list<T> xs) {4226return UnorderedElementsAreArray(xs.begin(), xs.end());4227}42284229// _ is a matcher that matches anything of any type.4230//4231// This definition is fine as:4232//4233// 1. The C++ standard permits using the name _ in a namespace that4234// is not the global namespace or ::std.4235// 2. The AnythingMatcher class has no data member or constructor,4236// so it's OK to create global variables of this type.4237// 3. c-style has approved of using _ in this case.4238const internal::AnythingMatcher _ = {};4239// Creates a matcher that matches any value of the given type T.4240template <typename T>4241inline Matcher<T> A() {4242return _;4243}42444245// Creates a matcher that matches any value of the given type T.4246template <typename T>4247inline Matcher<T> An() {4248return _;4249}42504251template <typename T, typename M>4252Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(4253const M& value, std::false_type /* convertible_to_matcher */,4254std::false_type /* convertible_to_T */) {4255return Eq(value);4256}42574258// Creates a polymorphic matcher that matches any NULL pointer.4259inline PolymorphicMatcher<internal::IsNullMatcher> IsNull() {4260return MakePolymorphicMatcher(internal::IsNullMatcher());4261}42624263// Creates a polymorphic matcher that matches any non-NULL pointer.4264// This is convenient as Not(NULL) doesn't compile (the compiler4265// thinks that that expression is comparing a pointer with an integer).4266inline PolymorphicMatcher<internal::NotNullMatcher> NotNull() {4267return MakePolymorphicMatcher(internal::NotNullMatcher());4268}42694270// Creates a polymorphic matcher that matches any argument that4271// references variable x.4272template <typename T>4273inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT4274return internal::RefMatcher<T&>(x);4275}42764277// Creates a polymorphic matcher that matches any NaN floating point.4278inline PolymorphicMatcher<internal::IsNanMatcher> IsNan() {4279return MakePolymorphicMatcher(internal::IsNanMatcher());4280}42814282// Creates a matcher that matches any double argument approximately4283// equal to rhs, where two NANs are considered unequal.4284inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {4285return internal::FloatingEqMatcher<double>(rhs, false);4286}42874288// Creates a matcher that matches any double argument approximately4289// equal to rhs, including NaN values when rhs is NaN.4290inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {4291return internal::FloatingEqMatcher<double>(rhs, true);4292}42934294// Creates a matcher that matches any double argument approximately equal to4295// rhs, up to the specified max absolute error bound, where two NANs are4296// considered unequal. The max absolute error bound must be non-negative.4297inline internal::FloatingEqMatcher<double> DoubleNear(double rhs,4298double max_abs_error) {4299return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);4300}43014302// Creates a matcher that matches any double argument approximately equal to4303// rhs, up to the specified max absolute error bound, including NaN values when4304// rhs is NaN. The max absolute error bound must be non-negative.4305inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(4306double rhs, double max_abs_error) {4307return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);4308}43094310// Creates a matcher that matches any float argument approximately4311// equal to rhs, where two NANs are considered unequal.4312inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {4313return internal::FloatingEqMatcher<float>(rhs, false);4314}43154316// Creates a matcher that matches any float argument approximately4317// equal to rhs, including NaN values when rhs is NaN.4318inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {4319return internal::FloatingEqMatcher<float>(rhs, true);4320}43214322// Creates a matcher that matches any float argument approximately equal to4323// rhs, up to the specified max absolute error bound, where two NANs are4324// considered unequal. The max absolute error bound must be non-negative.4325inline internal::FloatingEqMatcher<float> FloatNear(float rhs,4326float max_abs_error) {4327return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);4328}43294330// Creates a matcher that matches any float argument approximately equal to4331// rhs, up to the specified max absolute error bound, including NaN values when4332// rhs is NaN. The max absolute error bound must be non-negative.4333inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(4334float rhs, float max_abs_error) {4335return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);4336}43374338// Creates a matcher that matches a pointer (raw or smart) that points4339// to a value that matches inner_matcher.4340template <typename InnerMatcher>4341inline internal::PointeeMatcher<InnerMatcher> Pointee(4342const InnerMatcher& inner_matcher) {4343return internal::PointeeMatcher<InnerMatcher>(inner_matcher);4344}43454346#if GTEST_HAS_RTTI4347// Creates a matcher that matches a pointer or reference that matches4348// inner_matcher when dynamic_cast<To> is applied.4349// The result of dynamic_cast<To> is forwarded to the inner matcher.4350// If To is a pointer and the cast fails, the inner matcher will receive NULL.4351// If To is a reference and the cast fails, this matcher returns false4352// immediately.4353template <typename To>4354inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To>>4355WhenDynamicCastTo(const Matcher<To>& inner_matcher) {4356return MakePolymorphicMatcher(4357internal::WhenDynamicCastToMatcher<To>(inner_matcher));4358}4359#endif // GTEST_HAS_RTTI43604361// Creates a matcher that matches an object whose given field matches4362// 'matcher'. For example,4363// Field(&Foo::number, Ge(5))4364// matches a Foo object x if and only if x.number >= 5.4365template <typename Class, typename FieldType, typename FieldMatcher>4366inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType>> Field(4367FieldType Class::*field, const FieldMatcher& matcher) {4368return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(4369field, MatcherCast<const FieldType&>(matcher)));4370// The call to MatcherCast() is required for supporting inner4371// matchers of compatible types. For example, it allows4372// Field(&Foo::bar, m)4373// to compile where bar is an int32 and m is a matcher for int64.4374}43754376// Same as Field() but also takes the name of the field to provide better error4377// messages.4378template <typename Class, typename FieldType, typename FieldMatcher>4379inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType>> Field(4380const std::string& field_name, FieldType Class::*field,4381const FieldMatcher& matcher) {4382return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(4383field_name, field, MatcherCast<const FieldType&>(matcher)));4384}43854386// Creates a matcher that matches an object whose given property4387// matches 'matcher'. For example,4388// Property(&Foo::str, StartsWith("hi"))4389// matches a Foo object x if and only if x.str() starts with "hi".4390template <typename Class, typename PropertyType, typename PropertyMatcher>4391inline PolymorphicMatcher<internal::PropertyMatcher<4392Class, PropertyType, PropertyType (Class::*)() const>>4393Property(PropertyType (Class::*property)() const,4394const PropertyMatcher& matcher) {4395return MakePolymorphicMatcher(4396internal::PropertyMatcher<Class, PropertyType,4397PropertyType (Class::*)() const>(4398property, MatcherCast<const PropertyType&>(matcher)));4399// The call to MatcherCast() is required for supporting inner4400// matchers of compatible types. For example, it allows4401// Property(&Foo::bar, m)4402// to compile where bar() returns an int32 and m is a matcher for int64.4403}44044405// Same as Property() above, but also takes the name of the property to provide4406// better error messages.4407template <typename Class, typename PropertyType, typename PropertyMatcher>4408inline PolymorphicMatcher<internal::PropertyMatcher<4409Class, PropertyType, PropertyType (Class::*)() const>>4410Property(const std::string& property_name,4411PropertyType (Class::*property)() const,4412const PropertyMatcher& matcher) {4413return MakePolymorphicMatcher(4414internal::PropertyMatcher<Class, PropertyType,4415PropertyType (Class::*)() const>(4416property_name, property, MatcherCast<const PropertyType&>(matcher)));4417}44184419// The same as above but for reference-qualified member functions.4420template <typename Class, typename PropertyType, typename PropertyMatcher>4421inline PolymorphicMatcher<internal::PropertyMatcher<4422Class, PropertyType, PropertyType (Class::*)() const&>>4423Property(PropertyType (Class::*property)() const&,4424const PropertyMatcher& matcher) {4425return MakePolymorphicMatcher(4426internal::PropertyMatcher<Class, PropertyType,4427PropertyType (Class::*)() const&>(4428property, MatcherCast<const PropertyType&>(matcher)));4429}44304431// Three-argument form for reference-qualified member functions.4432template <typename Class, typename PropertyType, typename PropertyMatcher>4433inline PolymorphicMatcher<internal::PropertyMatcher<4434Class, PropertyType, PropertyType (Class::*)() const&>>4435Property(const std::string& property_name,4436PropertyType (Class::*property)() const&,4437const PropertyMatcher& matcher) {4438return MakePolymorphicMatcher(4439internal::PropertyMatcher<Class, PropertyType,4440PropertyType (Class::*)() const&>(4441property_name, property, MatcherCast<const PropertyType&>(matcher)));4442}44434444// Creates a matcher that matches an object if and only if the result of4445// applying a callable to x matches 'matcher'. For example,4446// ResultOf(f, StartsWith("hi"))4447// matches a Foo object x if and only if f(x) starts with "hi".4448// `callable` parameter can be a function, function pointer, or a functor. It is4449// required to keep no state affecting the results of the calls on it and make4450// no assumptions about how many calls will be made. Any state it keeps must be4451// protected from the concurrent access.4452template <typename Callable, typename InnerMatcher>4453internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(4454Callable callable, InnerMatcher matcher) {4455return internal::ResultOfMatcher<Callable, InnerMatcher>(std::move(callable),4456std::move(matcher));4457}44584459// Same as ResultOf() above, but also takes a description of the `callable`4460// result to provide better error messages.4461template <typename Callable, typename InnerMatcher>4462internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(4463const std::string& result_description, Callable callable,4464InnerMatcher matcher) {4465return internal::ResultOfMatcher<Callable, InnerMatcher>(4466result_description, std::move(callable), std::move(matcher));4467}44684469// String matchers.44704471// Matches a string equal to str.4472template <typename T = std::string>4473PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrEq(4474const internal::StringLike<T>& str) {4475return MakePolymorphicMatcher(4476internal::StrEqualityMatcher<std::string>(std::string(str), true, true));4477}44784479// Matches a string not equal to str.4480template <typename T = std::string>4481PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrNe(4482const internal::StringLike<T>& str) {4483return MakePolymorphicMatcher(4484internal::StrEqualityMatcher<std::string>(std::string(str), false, true));4485}44864487// Matches a string equal to str, ignoring case.4488template <typename T = std::string>4489PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseEq(4490const internal::StringLike<T>& str) {4491return MakePolymorphicMatcher(4492internal::StrEqualityMatcher<std::string>(std::string(str), true, false));4493}44944495// Matches a string not equal to str, ignoring case.4496template <typename T = std::string>4497PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseNe(4498const internal::StringLike<T>& str) {4499return MakePolymorphicMatcher(internal::StrEqualityMatcher<std::string>(4500std::string(str), false, false));4501}45024503// Creates a matcher that matches any string, std::string, or C string4504// that contains the given substring.4505template <typename T = std::string>4506PolymorphicMatcher<internal::HasSubstrMatcher<std::string>> HasSubstr(4507const internal::StringLike<T>& substring) {4508return MakePolymorphicMatcher(4509internal::HasSubstrMatcher<std::string>(std::string(substring)));4510}45114512// Matches a string that starts with 'prefix' (case-sensitive).4513template <typename T = std::string>4514PolymorphicMatcher<internal::StartsWithMatcher<std::string>> StartsWith(4515const internal::StringLike<T>& prefix) {4516return MakePolymorphicMatcher(4517internal::StartsWithMatcher<std::string>(std::string(prefix)));4518}45194520// Matches a string that ends with 'suffix' (case-sensitive).4521template <typename T = std::string>4522PolymorphicMatcher<internal::EndsWithMatcher<std::string>> EndsWith(4523const internal::StringLike<T>& suffix) {4524return MakePolymorphicMatcher(4525internal::EndsWithMatcher<std::string>(std::string(suffix)));4526}45274528#if GTEST_HAS_STD_WSTRING4529// Wide string matchers.45304531// Matches a string equal to str.4532inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrEq(4533const std::wstring& str) {4534return MakePolymorphicMatcher(4535internal::StrEqualityMatcher<std::wstring>(str, true, true));4536}45374538// Matches a string not equal to str.4539inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrNe(4540const std::wstring& str) {4541return MakePolymorphicMatcher(4542internal::StrEqualityMatcher<std::wstring>(str, false, true));4543}45444545// Matches a string equal to str, ignoring case.4546inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrCaseEq(4547const std::wstring& str) {4548return MakePolymorphicMatcher(4549internal::StrEqualityMatcher<std::wstring>(str, true, false));4550}45514552// Matches a string not equal to str, ignoring case.4553inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrCaseNe(4554const std::wstring& str) {4555return MakePolymorphicMatcher(4556internal::StrEqualityMatcher<std::wstring>(str, false, false));4557}45584559// Creates a matcher that matches any ::wstring, std::wstring, or C wide string4560// that contains the given substring.4561inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring>> HasSubstr(4562const std::wstring& substring) {4563return MakePolymorphicMatcher(4564internal::HasSubstrMatcher<std::wstring>(substring));4565}45664567// Matches a string that starts with 'prefix' (case-sensitive).4568inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring>> StartsWith(4569const std::wstring& prefix) {4570return MakePolymorphicMatcher(4571internal::StartsWithMatcher<std::wstring>(prefix));4572}45734574// Matches a string that ends with 'suffix' (case-sensitive).4575inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring>> EndsWith(4576const std::wstring& suffix) {4577return MakePolymorphicMatcher(4578internal::EndsWithMatcher<std::wstring>(suffix));4579}45804581#endif // GTEST_HAS_STD_WSTRING45824583// Creates a polymorphic matcher that matches a 2-tuple where the4584// first field == the second field.4585inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }45864587// Creates a polymorphic matcher that matches a 2-tuple where the4588// first field >= the second field.4589inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }45904591// Creates a polymorphic matcher that matches a 2-tuple where the4592// first field > the second field.4593inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }45944595// Creates a polymorphic matcher that matches a 2-tuple where the4596// first field <= the second field.4597inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }45984599// Creates a polymorphic matcher that matches a 2-tuple where the4600// first field < the second field.4601inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }46024603// Creates a polymorphic matcher that matches a 2-tuple where the4604// first field != the second field.4605inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }46064607// Creates a polymorphic matcher that matches a 2-tuple where4608// FloatEq(first field) matches the second field.4609inline internal::FloatingEq2Matcher<float> FloatEq() {4610return internal::FloatingEq2Matcher<float>();4611}46124613// Creates a polymorphic matcher that matches a 2-tuple where4614// DoubleEq(first field) matches the second field.4615inline internal::FloatingEq2Matcher<double> DoubleEq() {4616return internal::FloatingEq2Matcher<double>();4617}46184619// Creates a polymorphic matcher that matches a 2-tuple where4620// FloatEq(first field) matches the second field with NaN equality.4621inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {4622return internal::FloatingEq2Matcher<float>(true);4623}46244625// Creates a polymorphic matcher that matches a 2-tuple where4626// DoubleEq(first field) matches the second field with NaN equality.4627inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {4628return internal::FloatingEq2Matcher<double>(true);4629}46304631// Creates a polymorphic matcher that matches a 2-tuple where4632// FloatNear(first field, max_abs_error) matches the second field.4633inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {4634return internal::FloatingEq2Matcher<float>(max_abs_error);4635}46364637// Creates a polymorphic matcher that matches a 2-tuple where4638// DoubleNear(first field, max_abs_error) matches the second field.4639inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {4640return internal::FloatingEq2Matcher<double>(max_abs_error);4641}46424643// Creates a polymorphic matcher that matches a 2-tuple where4644// FloatNear(first field, max_abs_error) matches the second field with NaN4645// equality.4646inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(4647float max_abs_error) {4648return internal::FloatingEq2Matcher<float>(max_abs_error, true);4649}46504651// Creates a polymorphic matcher that matches a 2-tuple where4652// DoubleNear(first field, max_abs_error) matches the second field with NaN4653// equality.4654inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(4655double max_abs_error) {4656return internal::FloatingEq2Matcher<double>(max_abs_error, true);4657}46584659// Creates a matcher that matches any value of type T that m doesn't4660// match.4661template <typename InnerMatcher>4662inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {4663return internal::NotMatcher<InnerMatcher>(m);4664}46654666// Returns a matcher that matches anything that satisfies the given4667// predicate. The predicate can be any unary function or functor4668// whose return type can be implicitly converted to bool.4669template <typename Predicate>4670inline PolymorphicMatcher<internal::TrulyMatcher<Predicate>> Truly(4671Predicate pred) {4672return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));4673}46744675// Returns a matcher that matches the container size. The container must4676// support both size() and size_type which all STL-like containers provide.4677// Note that the parameter 'size' can be a value of type size_type as well as4678// matcher. For instance:4679// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.4680// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.4681template <typename SizeMatcher>4682inline internal::SizeIsMatcher<SizeMatcher> SizeIs(4683const SizeMatcher& size_matcher) {4684return internal::SizeIsMatcher<SizeMatcher>(size_matcher);4685}46864687// Returns a matcher that matches the distance between the container's begin()4688// iterator and its end() iterator, i.e. the size of the container. This matcher4689// can be used instead of SizeIs with containers such as std::forward_list which4690// do not implement size(). The container must provide const_iterator (with4691// valid iterator_traits), begin() and end().4692template <typename DistanceMatcher>4693inline internal::BeginEndDistanceIsMatcher<DistanceMatcher> BeginEndDistanceIs(4694const DistanceMatcher& distance_matcher) {4695return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);4696}46974698// Returns a matcher that matches an equal container.4699// This matcher behaves like Eq(), but in the event of mismatch lists the4700// values that are included in one container but not the other. (Duplicate4701// values and order differences are not explained.)4702template <typename Container>4703inline PolymorphicMatcher<4704internal::ContainerEqMatcher<typename std::remove_const<Container>::type>>4705ContainerEq(const Container& rhs) {4706return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));4707}47084709// Returns a matcher that matches a container that, when sorted using4710// the given comparator, matches container_matcher.4711template <typename Comparator, typename ContainerMatcher>4712inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher> WhenSortedBy(4713const Comparator& comparator, const ContainerMatcher& container_matcher) {4714return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(4715comparator, container_matcher);4716}47174718// Returns a matcher that matches a container that, when sorted using4719// the < operator, matches container_matcher.4720template <typename ContainerMatcher>4721inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>4722WhenSorted(const ContainerMatcher& container_matcher) {4723return internal::WhenSortedByMatcher<internal::LessComparator,4724ContainerMatcher>(4725internal::LessComparator(), container_matcher);4726}47274728// Matches an STL-style container or a native array that contains the4729// same number of elements as in rhs, where its i-th element and rhs's4730// i-th element (as a pair) satisfy the given pair matcher, for all i.4731// TupleMatcher must be able to be safely cast to Matcher<std::tuple<const4732// T1&, const T2&> >, where T1 and T2 are the types of elements in the4733// LHS container and the RHS container respectively.4734template <typename TupleMatcher, typename Container>4735inline internal::PointwiseMatcher<TupleMatcher,4736typename std::remove_const<Container>::type>4737Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {4738return internal::PointwiseMatcher<TupleMatcher, Container>(tuple_matcher,4739rhs);4740}47414742// Supports the Pointwise(m, {a, b, c}) syntax.4743template <typename TupleMatcher, typename T>4744inline internal::PointwiseMatcher<TupleMatcher, std::vector<T>> Pointwise(4745const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {4746return Pointwise(tuple_matcher, std::vector<T>(rhs));4747}47484749// UnorderedPointwise(pair_matcher, rhs) matches an STL-style4750// container or a native array that contains the same number of4751// elements as in rhs, where in some permutation of the container, its4752// i-th element and rhs's i-th element (as a pair) satisfy the given4753// pair matcher, for all i. Tuple2Matcher must be able to be safely4754// cast to Matcher<std::tuple<const T1&, const T2&> >, where T1 and T2 are4755// the types of elements in the LHS container and the RHS container4756// respectively.4757//4758// This is like Pointwise(pair_matcher, rhs), except that the element4759// order doesn't matter.4760template <typename Tuple2Matcher, typename RhsContainer>4761inline internal::UnorderedElementsAreArrayMatcher<4762typename internal::BoundSecondMatcher<4763Tuple2Matcher,4764typename internal::StlContainerView<4765typename std::remove_const<RhsContainer>::type>::type::value_type>>4766UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,4767const RhsContainer& rhs_container) {4768// RhsView allows the same code to handle RhsContainer being a4769// STL-style container and it being a native C-style array.4770typedef typename internal::StlContainerView<RhsContainer> RhsView;4771typedef typename RhsView::type RhsStlContainer;4772typedef typename RhsStlContainer::value_type Second;4773const RhsStlContainer& rhs_stl_container =4774RhsView::ConstReference(rhs_container);47754776// Create a matcher for each element in rhs_container.4777::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second>> matchers;4778for (auto it = rhs_stl_container.begin(); it != rhs_stl_container.end();4779++it) {4780matchers.push_back(internal::MatcherBindSecond(tuple2_matcher, *it));4781}47824783// Delegate the work to UnorderedElementsAreArray().4784return UnorderedElementsAreArray(matchers);4785}47864787// Supports the UnorderedPointwise(m, {a, b, c}) syntax.4788template <typename Tuple2Matcher, typename T>4789inline internal::UnorderedElementsAreArrayMatcher<4790typename internal::BoundSecondMatcher<Tuple2Matcher, T>>4791UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,4792std::initializer_list<T> rhs) {4793return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));4794}47954796// Matches an STL-style container or a native array that contains at4797// least one element matching the given value or matcher.4798//4799// Examples:4800// ::std::set<int> page_ids;4801// page_ids.insert(3);4802// page_ids.insert(1);4803// EXPECT_THAT(page_ids, Contains(1));4804// EXPECT_THAT(page_ids, Contains(Gt(2)));4805// EXPECT_THAT(page_ids, Not(Contains(4))); // See below for Times(0)4806//4807// ::std::map<int, size_t> page_lengths;4808// page_lengths[1] = 100;4809// EXPECT_THAT(page_lengths,4810// Contains(::std::pair<const int, size_t>(1, 100)));4811//4812// const char* user_ids[] = { "joe", "mike", "tom" };4813// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));4814//4815// The matcher supports a modifier `Times` that allows to check for arbitrary4816// occurrences including testing for absence with Times(0).4817//4818// Examples:4819// ::std::vector<int> ids;4820// ids.insert(1);4821// ids.insert(1);4822// ids.insert(3);4823// EXPECT_THAT(ids, Contains(1).Times(2)); // 1 occurs 2 times4824// EXPECT_THAT(ids, Contains(2).Times(0)); // 2 is not present4825// EXPECT_THAT(ids, Contains(3).Times(Ge(1))); // 3 occurs at least once48264827template <typename M>4828inline internal::ContainsMatcher<M> Contains(M matcher) {4829return internal::ContainsMatcher<M>(matcher);4830}48314832// IsSupersetOf(iterator_first, iterator_last)4833// IsSupersetOf(pointer, count)4834// IsSupersetOf(array)4835// IsSupersetOf(container)4836// IsSupersetOf({e1, e2, ..., en})4837//4838// IsSupersetOf() verifies that a surjective partial mapping onto a collection4839// of matchers exists. In other words, a container matches4840// IsSupersetOf({e1, ..., en}) if and only if there is a permutation4841// {y1, ..., yn} of some of the container's elements where y1 matches e1,4842// ..., and yn matches en. Obviously, the size of the container must be >= n4843// in order to have a match. Examples:4844//4845// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and4846// 1 matches Ne(0).4847// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches4848// both Eq(1) and Lt(2). The reason is that different matchers must be used4849// for elements in different slots of the container.4850// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches4851// Eq(1) and (the second) 1 matches Lt(2).4852// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)4853// Gt(1) and 3 matches (the second) Gt(1).4854//4855// The matchers can be specified as an array, a pointer and count, a container,4856// an initializer list, or an STL iterator range. In each of these cases, the4857// underlying matchers can be either values or matchers.48584859template <typename Iter>4860inline internal::UnorderedElementsAreArrayMatcher<4861typename ::std::iterator_traits<Iter>::value_type>4862IsSupersetOf(Iter first, Iter last) {4863typedef typename ::std::iterator_traits<Iter>::value_type T;4864return internal::UnorderedElementsAreArrayMatcher<T>(4865internal::UnorderedMatcherRequire::Superset, first, last);4866}48674868template <typename T>4869inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(4870const T* pointer, size_t count) {4871return IsSupersetOf(pointer, pointer + count);4872}48734874template <typename T, size_t N>4875inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(4876const T (&array)[N]) {4877return IsSupersetOf(array, N);4878}48794880template <typename Container>4881inline internal::UnorderedElementsAreArrayMatcher<4882typename Container::value_type>4883IsSupersetOf(const Container& container) {4884return IsSupersetOf(container.begin(), container.end());4885}48864887template <typename T>4888inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(4889::std::initializer_list<T> xs) {4890return IsSupersetOf(xs.begin(), xs.end());4891}48924893// IsSubsetOf(iterator_first, iterator_last)4894// IsSubsetOf(pointer, count)4895// IsSubsetOf(array)4896// IsSubsetOf(container)4897// IsSubsetOf({e1, e2, ..., en})4898//4899// IsSubsetOf() verifies that an injective mapping onto a collection of matchers4900// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and4901// only if there is a subset of matchers {m1, ..., mk} which would match the4902// container using UnorderedElementsAre. Obviously, the size of the container4903// must be <= n in order to have a match. Examples:4904//4905// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).4906// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -14907// matches Lt(0).4908// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both4909// match Gt(0). The reason is that different matchers must be used for4910// elements in different slots of the container.4911//4912// The matchers can be specified as an array, a pointer and count, a container,4913// an initializer list, or an STL iterator range. In each of these cases, the4914// underlying matchers can be either values or matchers.49154916template <typename Iter>4917inline internal::UnorderedElementsAreArrayMatcher<4918typename ::std::iterator_traits<Iter>::value_type>4919IsSubsetOf(Iter first, Iter last) {4920typedef typename ::std::iterator_traits<Iter>::value_type T;4921return internal::UnorderedElementsAreArrayMatcher<T>(4922internal::UnorderedMatcherRequire::Subset, first, last);4923}49244925template <typename T>4926inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(4927const T* pointer, size_t count) {4928return IsSubsetOf(pointer, pointer + count);4929}49304931template <typename T, size_t N>4932inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(4933const T (&array)[N]) {4934return IsSubsetOf(array, N);4935}49364937template <typename Container>4938inline internal::UnorderedElementsAreArrayMatcher<4939typename Container::value_type>4940IsSubsetOf(const Container& container) {4941return IsSubsetOf(container.begin(), container.end());4942}49434944template <typename T>4945inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(4946::std::initializer_list<T> xs) {4947return IsSubsetOf(xs.begin(), xs.end());4948}49494950// Matches an STL-style container or a native array that contains only4951// elements matching the given value or matcher.4952//4953// Each(m) is semantically equivalent to `Not(Contains(Not(m)))`. Only4954// the messages are different.4955//4956// Examples:4957// ::std::set<int> page_ids;4958// // Each(m) matches an empty container, regardless of what m is.4959// EXPECT_THAT(page_ids, Each(Eq(1)));4960// EXPECT_THAT(page_ids, Each(Eq(77)));4961//4962// page_ids.insert(3);4963// EXPECT_THAT(page_ids, Each(Gt(0)));4964// EXPECT_THAT(page_ids, Not(Each(Gt(4))));4965// page_ids.insert(1);4966// EXPECT_THAT(page_ids, Not(Each(Lt(2))));4967//4968// ::std::map<int, size_t> page_lengths;4969// page_lengths[1] = 100;4970// page_lengths[2] = 200;4971// page_lengths[3] = 300;4972// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));4973// EXPECT_THAT(page_lengths, Each(Key(Le(3))));4974//4975// const char* user_ids[] = { "joe", "mike", "tom" };4976// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));4977template <typename M>4978inline internal::EachMatcher<M> Each(M matcher) {4979return internal::EachMatcher<M>(matcher);4980}49814982// Key(inner_matcher) matches an std::pair whose 'first' field matches4983// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an4984// std::map that contains at least one element whose key is >= 5.4985template <typename M>4986inline internal::KeyMatcher<M> Key(M inner_matcher) {4987return internal::KeyMatcher<M>(inner_matcher);4988}49894990// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field4991// matches first_matcher and whose 'second' field matches second_matcher. For4992// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used4993// to match a std::map<int, string> that contains exactly one element whose key4994// is >= 5 and whose value equals "foo".4995template <typename FirstMatcher, typename SecondMatcher>4996inline internal::PairMatcher<FirstMatcher, SecondMatcher> Pair(4997FirstMatcher first_matcher, SecondMatcher second_matcher) {4998return internal::PairMatcher<FirstMatcher, SecondMatcher>(first_matcher,4999second_matcher);5000}50015002namespace no_adl {5003// Conditional() creates a matcher that conditionally uses either the first or5004// second matcher provided. For example, we could create an `equal if, and only5005// if' matcher using the Conditional wrapper as follows:5006//5007// EXPECT_THAT(result, Conditional(condition, Eq(expected), Ne(expected)));5008template <typename MatcherTrue, typename MatcherFalse>5009internal::ConditionalMatcher<MatcherTrue, MatcherFalse> Conditional(5010bool condition, MatcherTrue matcher_true, MatcherFalse matcher_false) {5011return internal::ConditionalMatcher<MatcherTrue, MatcherFalse>(5012condition, std::move(matcher_true), std::move(matcher_false));5013}50145015// FieldsAre(matchers...) matches piecewise the fields of compatible structs.5016// These include those that support `get<I>(obj)`, and when structured bindings5017// are enabled any class that supports them.5018// In particular, `std::tuple`, `std::pair`, `std::array` and aggregate types.5019template <typename... M>5020internal::FieldsAreMatcher<typename std::decay<M>::type...> FieldsAre(5021M&&... matchers) {5022return internal::FieldsAreMatcher<typename std::decay<M>::type...>(5023std::forward<M>(matchers)...);5024}50255026// Creates a matcher that matches a pointer (raw or smart) that matches5027// inner_matcher.5028template <typename InnerMatcher>5029inline internal::PointerMatcher<InnerMatcher> Pointer(5030const InnerMatcher& inner_matcher) {5031return internal::PointerMatcher<InnerMatcher>(inner_matcher);5032}50335034// Creates a matcher that matches an object that has an address that matches5035// inner_matcher.5036template <typename InnerMatcher>5037inline internal::AddressMatcher<InnerMatcher> Address(5038const InnerMatcher& inner_matcher) {5039return internal::AddressMatcher<InnerMatcher>(inner_matcher);5040}50415042// Matches a base64 escaped string, when the unescaped string matches the5043// internal matcher.5044template <typename MatcherType>5045internal::WhenBase64UnescapedMatcher WhenBase64Unescaped(5046const MatcherType& internal_matcher) {5047return internal::WhenBase64UnescapedMatcher(internal_matcher);5048}5049} // namespace no_adl50505051// Returns a predicate that is satisfied by anything that matches the5052// given matcher.5053template <typename M>5054inline internal::MatcherAsPredicate<M> Matches(M matcher) {5055return internal::MatcherAsPredicate<M>(matcher);5056}50575058// Returns true if and only if the value matches the matcher.5059template <typename T, typename M>5060inline bool Value(const T& value, M matcher) {5061return testing::Matches(matcher)(value);5062}50635064// Matches the value against the given matcher and explains the match5065// result to listener.5066template <typename T, typename M>5067inline bool ExplainMatchResult(M matcher, const T& value,5068MatchResultListener* listener) {5069return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);5070}50715072// Returns a string representation of the given matcher. Useful for description5073// strings of matchers defined using MATCHER_P* macros that accept matchers as5074// their arguments. For example:5075//5076// MATCHER_P(XAndYThat, matcher,5077// "X that " + DescribeMatcher<int>(matcher, negation) +5078// (negation ? " or" : " and") + " Y that " +5079// DescribeMatcher<double>(matcher, negation)) {5080// return ExplainMatchResult(matcher, arg.x(), result_listener) &&5081// ExplainMatchResult(matcher, arg.y(), result_listener);5082// }5083template <typename T, typename M>5084std::string DescribeMatcher(const M& matcher, bool negation = false) {5085::std::stringstream ss;5086Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);5087if (negation) {5088monomorphic_matcher.DescribeNegationTo(&ss);5089} else {5090monomorphic_matcher.DescribeTo(&ss);5091}5092return ss.str();5093}50945095template <typename... Args>5096internal::ElementsAreMatcher<5097std::tuple<typename std::decay<const Args&>::type...>>5098ElementsAre(const Args&... matchers) {5099return internal::ElementsAreMatcher<5100std::tuple<typename std::decay<const Args&>::type...>>(5101std::make_tuple(matchers...));5102}51035104template <typename... Args>5105internal::UnorderedElementsAreMatcher<5106std::tuple<typename std::decay<const Args&>::type...>>5107UnorderedElementsAre(const Args&... matchers) {5108return internal::UnorderedElementsAreMatcher<5109std::tuple<typename std::decay<const Args&>::type...>>(5110std::make_tuple(matchers...));5111}51125113// Define variadic matcher versions.5114template <typename... Args>5115internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(5116const Args&... matchers) {5117return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(5118matchers...);5119}51205121template <typename... Args>5122internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(5123const Args&... matchers) {5124return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(5125matchers...);5126}51275128// AnyOfArray(array)5129// AnyOfArray(pointer, count)5130// AnyOfArray(container)5131// AnyOfArray({ e1, e2, ..., en })5132// AnyOfArray(iterator_first, iterator_last)5133//5134// AnyOfArray() verifies whether a given value matches any member of a5135// collection of matchers.5136//5137// AllOfArray(array)5138// AllOfArray(pointer, count)5139// AllOfArray(container)5140// AllOfArray({ e1, e2, ..., en })5141// AllOfArray(iterator_first, iterator_last)5142//5143// AllOfArray() verifies whether a given value matches all members of a5144// collection of matchers.5145//5146// The matchers can be specified as an array, a pointer and count, a container,5147// an initializer list, or an STL iterator range. In each of these cases, the5148// underlying matchers can be either values or matchers.51495150template <typename Iter>5151inline internal::AnyOfArrayMatcher<5152typename ::std::iterator_traits<Iter>::value_type>5153AnyOfArray(Iter first, Iter last) {5154return internal::AnyOfArrayMatcher<5155typename ::std::iterator_traits<Iter>::value_type>(first, last);5156}51575158template <typename Iter>5159inline internal::AllOfArrayMatcher<5160typename ::std::iterator_traits<Iter>::value_type>5161AllOfArray(Iter first, Iter last) {5162return internal::AllOfArrayMatcher<5163typename ::std::iterator_traits<Iter>::value_type>(first, last);5164}51655166template <typename T>5167inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T* ptr, size_t count) {5168return AnyOfArray(ptr, ptr + count);5169}51705171template <typename T>5172inline internal::AllOfArrayMatcher<T> AllOfArray(const T* ptr, size_t count) {5173return AllOfArray(ptr, ptr + count);5174}51755176template <typename T, size_t N>5177inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T (&array)[N]) {5178return AnyOfArray(array, N);5179}51805181template <typename T, size_t N>5182inline internal::AllOfArrayMatcher<T> AllOfArray(const T (&array)[N]) {5183return AllOfArray(array, N);5184}51855186template <typename Container>5187inline internal::AnyOfArrayMatcher<typename Container::value_type> AnyOfArray(5188const Container& container) {5189return AnyOfArray(container.begin(), container.end());5190}51915192template <typename Container>5193inline internal::AllOfArrayMatcher<typename Container::value_type> AllOfArray(5194const Container& container) {5195return AllOfArray(container.begin(), container.end());5196}51975198template <typename T>5199inline internal::AnyOfArrayMatcher<T> AnyOfArray(5200::std::initializer_list<T> xs) {5201return AnyOfArray(xs.begin(), xs.end());5202}52035204template <typename T>5205inline internal::AllOfArrayMatcher<T> AllOfArray(5206::std::initializer_list<T> xs) {5207return AllOfArray(xs.begin(), xs.end());5208}52095210// Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected5211// fields of it matches a_matcher. C++ doesn't support default5212// arguments for function templates, so we have to overload it.5213template <size_t... k, typename InnerMatcher>5214internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...> Args(5215InnerMatcher&& matcher) {5216return internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...>(5217std::forward<InnerMatcher>(matcher));5218}52195220// AllArgs(m) is a synonym of m. This is useful in5221//5222// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));5223//5224// which is easier to read than5225//5226// EXPECT_CALL(foo, Bar(_, _)).With(Eq());5227template <typename InnerMatcher>5228inline InnerMatcher AllArgs(const InnerMatcher& matcher) {5229return matcher;5230}52315232// Returns a matcher that matches the value of an optional<> type variable.5233// The matcher implementation only uses '!arg' and requires that the optional<>5234// type has a 'value_type' member type and that '*arg' is of type 'value_type'5235// and is printable using 'PrintToString'. It is compatible with5236// std::optional/std::experimental::optional.5237// Note that to compare an optional type variable against nullopt you should5238// use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the5239// optional value contains an optional itself.5240template <typename ValueMatcher>5241inline internal::OptionalMatcher<ValueMatcher> Optional(5242const ValueMatcher& value_matcher) {5243return internal::OptionalMatcher<ValueMatcher>(value_matcher);5244}52455246// Returns a matcher that matches the value of a absl::any type variable.5247template <typename T>5248PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T>> AnyWith(5249const Matcher<const T&>& matcher) {5250return MakePolymorphicMatcher(5251internal::any_cast_matcher::AnyCastMatcher<T>(matcher));5252}52535254// Returns a matcher that matches the value of a variant<> type variable.5255// The matcher implementation uses ADL to find the holds_alternative and get5256// functions.5257// It is compatible with std::variant.5258template <typename T>5259PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T>> VariantWith(5260const Matcher<const T&>& matcher) {5261return MakePolymorphicMatcher(5262internal::variant_matcher::VariantMatcher<T>(matcher));5263}52645265#if GTEST_HAS_EXCEPTIONS52665267// Anything inside the `internal` namespace is internal to the implementation5268// and must not be used in user code!5269namespace internal {52705271class WithWhatMatcherImpl {5272public:5273WithWhatMatcherImpl(Matcher<std::string> matcher)5274: matcher_(std::move(matcher)) {}52755276void DescribeTo(std::ostream* os) const {5277*os << "contains .what() that ";5278matcher_.DescribeTo(os);5279}52805281void DescribeNegationTo(std::ostream* os) const {5282*os << "contains .what() that does not ";5283matcher_.DescribeTo(os);5284}52855286template <typename Err>5287bool MatchAndExplain(const Err& err, MatchResultListener* listener) const {5288*listener << "which contains .what() (of value = " << err.what()5289<< ") that ";5290return matcher_.MatchAndExplain(err.what(), listener);5291}52925293private:5294const Matcher<std::string> matcher_;5295};52965297inline PolymorphicMatcher<WithWhatMatcherImpl> WithWhat(5298Matcher<std::string> m) {5299return MakePolymorphicMatcher(WithWhatMatcherImpl(std::move(m)));5300}53015302template <typename Err>5303class ExceptionMatcherImpl {5304class NeverThrown {5305public:5306const char* what() const noexcept {5307return "this exception should never be thrown";5308}5309};53105311// If the matchee raises an exception of a wrong type, we'd like to5312// catch it and print its message and type. To do that, we add an additional5313// catch clause:5314//5315// try { ... }5316// catch (const Err&) { /* an expected exception */ }5317// catch (const std::exception&) { /* exception of a wrong type */ }5318//5319// However, if the `Err` itself is `std::exception`, we'd end up with two5320// identical `catch` clauses:5321//5322// try { ... }5323// catch (const std::exception&) { /* an expected exception */ }5324// catch (const std::exception&) { /* exception of a wrong type */ }5325//5326// This can cause a warning or an error in some compilers. To resolve5327// the issue, we use a fake error type whenever `Err` is `std::exception`:5328//5329// try { ... }5330// catch (const std::exception&) { /* an expected exception */ }5331// catch (const NeverThrown&) { /* exception of a wrong type */ }5332using DefaultExceptionType = typename std::conditional<5333std::is_same<typename std::remove_cv<5334typename std::remove_reference<Err>::type>::type,5335std::exception>::value,5336const NeverThrown&, const std::exception&>::type;53375338public:5339ExceptionMatcherImpl(Matcher<const Err&> matcher)5340: matcher_(std::move(matcher)) {}53415342void DescribeTo(std::ostream* os) const {5343*os << "throws an exception which is a " << GetTypeName<Err>();5344*os << " which ";5345matcher_.DescribeTo(os);5346}53475348void DescribeNegationTo(std::ostream* os) const {5349*os << "throws an exception which is not a " << GetTypeName<Err>();5350*os << " which ";5351matcher_.DescribeNegationTo(os);5352}53535354template <typename T>5355bool MatchAndExplain(T&& x, MatchResultListener* listener) const {5356try {5357(void)(std::forward<T>(x)());5358} catch (const Err& err) {5359*listener << "throws an exception which is a " << GetTypeName<Err>();5360*listener << " ";5361return matcher_.MatchAndExplain(err, listener);5362} catch (DefaultExceptionType err) {5363#if GTEST_HAS_RTTI5364*listener << "throws an exception of type " << GetTypeName(typeid(err));5365*listener << " ";5366#else5367*listener << "throws an std::exception-derived type ";5368#endif5369*listener << "with description \"" << err.what() << "\"";5370return false;5371} catch (...) {5372*listener << "throws an exception of an unknown type";5373return false;5374}53755376*listener << "does not throw any exception";5377return false;5378}53795380private:5381const Matcher<const Err&> matcher_;5382};53835384} // namespace internal53855386// Throws()5387// Throws(exceptionMatcher)5388// ThrowsMessage(messageMatcher)5389//5390// This matcher accepts a callable and verifies that when invoked, it throws5391// an exception with the given type and properties.5392//5393// Examples:5394//5395// EXPECT_THAT(5396// []() { throw std::runtime_error("message"); },5397// Throws<std::runtime_error>());5398//5399// EXPECT_THAT(5400// []() { throw std::runtime_error("message"); },5401// ThrowsMessage<std::runtime_error>(HasSubstr("message")));5402//5403// EXPECT_THAT(5404// []() { throw std::runtime_error("message"); },5405// Throws<std::runtime_error>(5406// Property(&std::runtime_error::what, HasSubstr("message"))));54075408template <typename Err>5409PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws() {5410return MakePolymorphicMatcher(5411internal::ExceptionMatcherImpl<Err>(A<const Err&>()));5412}54135414template <typename Err, typename ExceptionMatcher>5415PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws(5416const ExceptionMatcher& exception_matcher) {5417// Using matcher cast allows users to pass a matcher of a more broad type.5418// For example user may want to pass Matcher<std::exception>5419// to Throws<std::runtime_error>, or Matcher<int64> to Throws<int32>.5420return MakePolymorphicMatcher(internal::ExceptionMatcherImpl<Err>(5421SafeMatcherCast<const Err&>(exception_matcher)));5422}54235424template <typename Err, typename MessageMatcher>5425PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(5426MessageMatcher&& message_matcher) {5427static_assert(std::is_base_of<std::exception, Err>::value,5428"expected an std::exception-derived type");5429return Throws<Err>(internal::WithWhat(5430MatcherCast<std::string>(std::forward<MessageMatcher>(message_matcher))));5431}54325433#endif // GTEST_HAS_EXCEPTIONS54345435// These macros allow using matchers to check values in Google Test5436// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)5437// succeed if and only if the value matches the matcher. If the assertion5438// fails, the value and the description of the matcher will be printed.5439#define ASSERT_THAT(value, matcher) \5440ASSERT_PRED_FORMAT1( \5441::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)5442#define EXPECT_THAT(value, matcher) \5443EXPECT_PRED_FORMAT1( \5444::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)54455446// MATCHER* macros itself are listed below.5447#define MATCHER(name, description) \5448class name##Matcher \5449: public ::testing::internal::MatcherBaseImpl<name##Matcher> { \5450public: \5451template <typename arg_type> \5452class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \5453public: \5454gmock_Impl() {} \5455bool MatchAndExplain( \5456const arg_type& arg, \5457::testing::MatchResultListener* result_listener) const override; \5458void DescribeTo(::std::ostream* gmock_os) const override { \5459*gmock_os << FormatDescription(false); \5460} \5461void DescribeNegationTo(::std::ostream* gmock_os) const override { \5462*gmock_os << FormatDescription(true); \5463} \5464\5465private: \5466::std::string FormatDescription(bool negation) const { \5467/* NOLINTNEXTLINE readability-redundant-string-init */ \5468::std::string gmock_description = (description); \5469if (!gmock_description.empty()) { \5470return gmock_description; \5471} \5472return ::testing::internal::FormatMatcherDescription(negation, #name, \5473{}, {}); \5474} \5475}; \5476}; \5477inline name##Matcher GMOCK_INTERNAL_WARNING_PUSH() \5478GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-function") \5479GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \5480name GMOCK_INTERNAL_WARNING_POP()() { \5481return {}; \5482} \5483template <typename arg_type> \5484bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \5485const arg_type& arg, \5486GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED ::testing::MatchResultListener* \5487result_listener) const54885489#define MATCHER_P(name, p0, description) \5490GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (#p0), (p0))5491#define MATCHER_P2(name, p0, p1, description) \5492GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (#p0, #p1), \5493(p0, p1))5494#define MATCHER_P3(name, p0, p1, p2, description) \5495GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (#p0, #p1, #p2), \5496(p0, p1, p2))5497#define MATCHER_P4(name, p0, p1, p2, p3, description) \5498GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, \5499(#p0, #p1, #p2, #p3), (p0, p1, p2, p3))5500#define MATCHER_P5(name, p0, p1, p2, p3, p4, description) \5501GMOCK_INTERNAL_MATCHER(name, name##MatcherP5, description, \5502(#p0, #p1, #p2, #p3, #p4), (p0, p1, p2, p3, p4))5503#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \5504GMOCK_INTERNAL_MATCHER(name, name##MatcherP6, description, \5505(#p0, #p1, #p2, #p3, #p4, #p5), \5506(p0, p1, p2, p3, p4, p5))5507#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \5508GMOCK_INTERNAL_MATCHER(name, name##MatcherP7, description, \5509(#p0, #p1, #p2, #p3, #p4, #p5, #p6), \5510(p0, p1, p2, p3, p4, p5, p6))5511#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \5512GMOCK_INTERNAL_MATCHER(name, name##MatcherP8, description, \5513(#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7), \5514(p0, p1, p2, p3, p4, p5, p6, p7))5515#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \5516GMOCK_INTERNAL_MATCHER(name, name##MatcherP9, description, \5517(#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8), \5518(p0, p1, p2, p3, p4, p5, p6, p7, p8))5519#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \5520GMOCK_INTERNAL_MATCHER(name, name##MatcherP10, description, \5521(#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9), \5522(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9))55235524#define GMOCK_INTERNAL_MATCHER(name, full_name, description, arg_names, args) \5525template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \5526class full_name : public ::testing::internal::MatcherBaseImpl< \5527full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>> { \5528public: \5529using full_name::MatcherBaseImpl::MatcherBaseImpl; \5530template <typename arg_type> \5531class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \5532public: \5533explicit gmock_Impl(GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) \5534: GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) {} \5535bool MatchAndExplain( \5536const arg_type& arg, \5537::testing::MatchResultListener* result_listener) const override; \5538void DescribeTo(::std::ostream* gmock_os) const override { \5539*gmock_os << FormatDescription(false); \5540} \5541void DescribeNegationTo(::std::ostream* gmock_os) const override { \5542*gmock_os << FormatDescription(true); \5543} \5544GMOCK_INTERNAL_MATCHER_MEMBERS(args) \5545\5546private: \5547::std::string FormatDescription(bool negation) const { \5548::std::string gmock_description; \5549gmock_description = (description); \5550if (!gmock_description.empty()) { \5551return gmock_description; \5552} \5553return ::testing::internal::FormatMatcherDescription( \5554negation, #name, {GMOCK_PP_REMOVE_PARENS(arg_names)}, \5555::testing::internal::UniversalTersePrintTupleFieldsToStrings( \5556::std::tuple<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \5557GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args)))); \5558} \5559}; \5560}; \5561template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \5562inline full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)> name( \5563GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) { \5564return full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \5565GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args)); \5566} \5567template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \5568template <typename arg_type> \5569bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>:: \5570gmock_Impl<arg_type>::MatchAndExplain( \5571const arg_type& arg, \5572GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED ::testing:: \5573MatchResultListener* result_listener) const55745575#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \5576GMOCK_PP_TAIL( \5577GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM, , args))5578#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM(i_unused, data_unused, arg) \5579, typename arg##_type55805581#define GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args) \5582GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TYPE_PARAM, , args))5583#define GMOCK_INTERNAL_MATCHER_TYPE_PARAM(i_unused, data_unused, arg) \5584, arg##_type55855586#define GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args) \5587GMOCK_PP_TAIL(dummy_first GMOCK_PP_FOR_EACH( \5588GMOCK_INTERNAL_MATCHER_FUNCTION_ARG, , args))5589#define GMOCK_INTERNAL_MATCHER_FUNCTION_ARG(i, data_unused, arg) \5590, arg##_type gmock_p##i55915592#define GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) \5593GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_FORWARD_ARG, , args))5594#define GMOCK_INTERNAL_MATCHER_FORWARD_ARG(i, data_unused, arg) \5595, arg(::std::forward<arg##_type>(gmock_p##i))55965597#define GMOCK_INTERNAL_MATCHER_MEMBERS(args) \5598GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER, , args)5599#define GMOCK_INTERNAL_MATCHER_MEMBER(i_unused, data_unused, arg) \5600const arg##_type arg;56015602#define GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args) \5603GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER_USAGE, , args))5604#define GMOCK_INTERNAL_MATCHER_MEMBER_USAGE(i_unused, data_unused, arg) , arg56055606#define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \5607GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args))5608#define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg) \5609, ::std::forward<arg##_type>(gmock_p##i)56105611// To prevent ADL on certain functions we put them on a separate namespace.5612using namespace no_adl; // NOLINT56135614} // namespace testing56155616GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 504656175618// Include any custom callback matchers added by the local installation.5619// We must include this header at the end to make sure it can use the5620// declarations from this file.5621#include "gmock/internal/custom/gmock-matchers.h"56225623#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_562456255626