Path: blob/main/contrib/googletest/googlemock/include/gmock/gmock-matchers.h
112651 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 <cstddef>260#include <exception>261#include <functional>262#include <initializer_list>263#include <ios>264#include <iterator>265#include <limits>266#include <memory>267#include <ostream> // NOLINT268#include <sstream>269#include <string>270#include <type_traits>271#include <utility>272#include <vector>273274#include "gmock/internal/gmock-internal-utils.h"275#include "gmock/internal/gmock-port.h"276#include "gmock/internal/gmock-pp.h"277#include "gtest/gtest.h"278279// MSVC warning C5046 is new as of VS2017 version 15.8.280#if defined(_MSC_VER) && _MSC_VER >= 1915281#define GMOCK_MAYBE_5046_ 5046282#else283#define GMOCK_MAYBE_5046_284#endif285286GTEST_DISABLE_MSC_WARNINGS_PUSH_(2874251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by288clients of class B */289/* Symbol involving type with internal linkage not defined */)290291namespace testing {292293// To implement a matcher Foo for type T, define:294// 1. a class FooMatcherImpl that implements the295// MatcherInterface<T> interface, and296// 2. a factory function that creates a Matcher<T> object from a297// FooMatcherImpl*.298//299// The two-level delegation design makes it possible to allow a user300// to write "v" instead of "Eq(v)" where a Matcher is expected, which301// is impossible if we pass matchers by pointers. It also eases302// ownership management as Matcher objects can now be copied like303// plain values.304305// A match result listener that stores the explanation in a string.306class StringMatchResultListener : public MatchResultListener {307public:308StringMatchResultListener() : MatchResultListener(&ss_) {}309310// Returns the explanation accumulated so far.311std::string str() const { return ss_.str(); }312313// Clears the explanation accumulated so far.314void Clear() { ss_.str(""); }315316private:317::std::stringstream ss_;318319StringMatchResultListener(const StringMatchResultListener&) = delete;320StringMatchResultListener& operator=(const StringMatchResultListener&) =321delete;322};323324// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION325// and MUST NOT BE USED IN USER CODE!!!326namespace internal {327328// The MatcherCastImpl class template is a helper for implementing329// MatcherCast(). We need this helper in order to partially330// specialize the implementation of MatcherCast() (C++ allows331// class/struct templates to be partially specialized, but not332// function templates.).333334// This general version is used when MatcherCast()'s argument is a335// polymorphic matcher (i.e. something that can be converted to a336// Matcher but is not one yet; for example, Eq(value)) or a value (for337// example, "hello").338template <typename T, typename M>339class MatcherCastImpl {340public:341static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {342// M can be a polymorphic matcher, in which case we want to use343// its conversion operator to create Matcher<T>. Or it can be a value344// that should be passed to the Matcher<T>'s constructor.345//346// We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a347// polymorphic matcher because it'll be ambiguous if T has an implicit348// constructor from M (this usually happens when T has an implicit349// constructor from any type).350//351// It won't work to unconditionally implicit_cast352// polymorphic_matcher_or_value to Matcher<T> because it won't trigger353// a user-defined conversion from M to T if one exists (assuming M is354// a value).355return CastImpl(polymorphic_matcher_or_value,356std::is_convertible<M, Matcher<T>>{},357std::is_convertible<M, T>{});358}359360private:361template <bool Ignore>362static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,363std::true_type /* convertible_to_matcher */,364std::integral_constant<bool, Ignore>) {365// M is implicitly convertible to Matcher<T>, which means that either366// M is a polymorphic matcher or Matcher<T> has an implicit constructor367// from M. In both cases using the implicit conversion will produce a368// matcher.369//370// Even if T has an implicit constructor from M, it won't be called because371// creating Matcher<T> would require a chain of two user-defined conversions372// (first to create T from M and then to create Matcher<T> from T).373return polymorphic_matcher_or_value;374}375376// M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic377// matcher. It's a value of a type implicitly convertible to T. Use direct378// initialization to create a matcher.379static Matcher<T> CastImpl(const M& value,380std::false_type /* convertible_to_matcher */,381std::true_type /* convertible_to_T */) {382return Matcher<T>(ImplicitCast_<T>(value));383}384385// M can't be implicitly converted to either Matcher<T> or T. Attempt to use386// polymorphic matcher Eq(value) in this case.387//388// Note that we first attempt to perform an implicit cast on the value and389// only fall back to the polymorphic Eq() matcher afterwards because the390// latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end391// which might be undefined even when Rhs is implicitly convertible to Lhs392// (e.g. std::pair<const int, int> vs. std::pair<int, int>).393//394// We don't define this method inline as we need the declaration of Eq().395static Matcher<T> CastImpl(const M& value,396std::false_type /* convertible_to_matcher */,397std::false_type /* convertible_to_T */);398};399400// This more specialized version is used when MatcherCast()'s argument401// is already a Matcher. This only compiles when type T can be402// statically converted to type U.403template <typename T, typename U>404class MatcherCastImpl<T, Matcher<U>> {405public:406static Matcher<T> Cast(const Matcher<U>& source_matcher) {407return Matcher<T>(new Impl(source_matcher));408}409410private:411// If it's possible to implicitly convert a `const T&` to U, then `Impl` can412// take that as input to avoid a copy. Otherwise, such as when `T` is a413// non-const reference type or a type explicitly constructible only from a414// non-const reference, then `Impl` must use `T` as-is (potentially copying).415using ImplArgT =416typename std::conditional<std::is_convertible<const T&, const U&>::value,417const T&, T>::type;418419class Impl : public MatcherInterface<ImplArgT> {420public:421explicit Impl(const Matcher<U>& source_matcher)422: source_matcher_(source_matcher) {}423424// We delegate the matching logic to the source matcher.425bool MatchAndExplain(ImplArgT x,426MatchResultListener* listener) const override {427using FromType = typename std::remove_cv<typename std::remove_pointer<428typename std::remove_reference<T>::type>::type>::type;429using ToType = typename std::remove_cv<typename std::remove_pointer<430typename std::remove_reference<U>::type>::type>::type;431// Do not allow implicitly converting base*/& to derived*/&.432static_assert(433// Do not trigger if only one of them is a pointer. That implies a434// regular conversion and not a down_cast.435(std::is_pointer<typename std::remove_reference<T>::type>::value !=436std::is_pointer<typename std::remove_reference<U>::type>::value) ||437std::is_same<FromType, ToType>::value ||438!std::is_base_of<FromType, ToType>::value,439"Can't implicitly convert from <base> to <derived>");440441// Do the cast to `U` explicitly if necessary.442// Otherwise, let implicit conversions do the trick.443using CastType = typename std::conditional<444std::is_convertible<ImplArgT&, const U&>::value, ImplArgT&, U>::type;445446return source_matcher_.MatchAndExplain(static_cast<CastType>(x),447listener);448}449450void DescribeTo(::std::ostream* os) const override {451source_matcher_.DescribeTo(os);452}453454void DescribeNegationTo(::std::ostream* os) const override {455source_matcher_.DescribeNegationTo(os);456}457458private:459const Matcher<U> source_matcher_;460};461};462463// This even more specialized version is used for efficiently casting464// a matcher to its own type.465template <typename T>466class MatcherCastImpl<T, Matcher<T>> {467public:468static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }469};470471// Template specialization for parameterless Matcher.472template <typename Derived>473class MatcherBaseImpl {474public:475MatcherBaseImpl() = default;476477template <typename T>478operator ::testing::Matcher<T>() const { // NOLINT(runtime/explicit)479return ::testing::Matcher<T>(new480typename Derived::template gmock_Impl<T>());481}482};483484// Template specialization for Matcher with parameters.485template <template <typename...> class Derived, typename... Ts>486class MatcherBaseImpl<Derived<Ts...>> {487public:488// Mark the constructor explicit for single argument T to avoid implicit489// conversions.490template <typename E = std::enable_if<sizeof...(Ts) == 1>,491typename E::type* = nullptr>492explicit MatcherBaseImpl(Ts... params)493: params_(std::forward<Ts>(params)...) {}494template <typename E = std::enable_if<sizeof...(Ts) != 1>,495typename = typename E::type>496MatcherBaseImpl(Ts... params) // NOLINT497: params_(std::forward<Ts>(params)...) {}498499template <typename F>500operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit)501return Apply<F>(std::make_index_sequence<sizeof...(Ts)>{});502}503504private:505template <typename F, std::size_t... tuple_ids>506::testing::Matcher<F> Apply(std::index_sequence<tuple_ids...>) const {507return ::testing::Matcher<F>(508new typename Derived<Ts...>::template gmock_Impl<F>(509std::get<tuple_ids>(params_)...));510}511512const std::tuple<Ts...> params_;513};514515} // namespace internal516517// In order to be safe and clear, casting between different matcher518// types is done explicitly via MatcherCast<T>(m), which takes a519// matcher m and returns a Matcher<T>. It compiles only when T can be520// statically converted to the argument type of m.521template <typename T, typename M>522inline Matcher<T> MatcherCast(const M& matcher) {523return internal::MatcherCastImpl<T, M>::Cast(matcher);524}525526// This overload handles polymorphic matchers and values only since527// monomorphic matchers are handled by the next one.528template <typename T, typename M>529inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) {530return MatcherCast<T>(polymorphic_matcher_or_value);531}532533// This overload handles monomorphic matchers.534//535// In general, if type T can be implicitly converted to type U, we can536// safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is537// contravariant): just keep a copy of the original Matcher<U>, convert the538// argument from type T to U, and then pass it to the underlying Matcher<U>.539// The only exception is when U is a non-const reference and T is not, as the540// underlying Matcher<U> may be interested in the argument's address, which541// cannot be preserved in the conversion from T to U (since a copy of the input542// T argument would be required to provide a non-const reference U).543template <typename T, typename U>544inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {545// Enforce that T can be implicitly converted to U.546static_assert(std::is_convertible<const T&, const U&>::value,547"T must be implicitly convertible to U (and T must be a "548"non-const reference if U is a non-const reference)");549// In case both T and U are arithmetic types, enforce that the550// conversion is not lossy.551typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;552typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;553constexpr bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;554constexpr bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;555static_assert(556kTIsOther || kUIsOther ||557(internal::LosslessArithmeticConvertible<RawT, RawU>::value),558"conversion of arithmetic types must be lossless");559return MatcherCast<T>(matcher);560}561562// A<T>() returns a matcher that matches any value of type T.563template <typename T>564Matcher<T> A();565566// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION567// and MUST NOT BE USED IN USER CODE!!!568namespace internal {569570// Used per go/ranked-overloads for dispatching.571struct Rank0 {};572struct Rank1 : Rank0 {};573using HighestRank = Rank1;574575// If the explanation is not empty, prints it to the ostream.576inline void PrintIfNotEmpty(const std::string& explanation,577::std::ostream* os) {578if (!explanation.empty() && os != nullptr) {579*os << ", " << explanation;580}581}582583// Returns true if the given type name is easy to read by a human.584// This is used to decide whether printing the type of a value might585// be helpful.586inline bool IsReadableTypeName(const std::string& type_name) {587// We consider a type name readable if it's short or doesn't contain588// a template or function type.589return (type_name.length() <= 20 ||590type_name.find_first_of("<(") == std::string::npos);591}592593// Matches the value against the given matcher, prints the value and explains594// the match result to the listener. Returns the match result.595// 'listener' must not be NULL.596// Value cannot be passed by const reference, because some matchers take a597// non-const argument.598template <typename Value, typename T>599bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,600MatchResultListener* listener) {601if (!listener->IsInterested()) {602// If the listener is not interested, we do not need to construct the603// inner explanation.604return matcher.Matches(value);605}606607StringMatchResultListener inner_listener;608const bool match = matcher.MatchAndExplain(value, &inner_listener);609610UniversalPrint(value, listener->stream());611#if GTEST_HAS_RTTI612const std::string& type_name = GetTypeName<Value>();613if (IsReadableTypeName(type_name))614*listener->stream() << " (of type " << type_name << ")";615#endif616PrintIfNotEmpty(inner_listener.str(), listener->stream());617618return match;619}620621// An internal helper class for doing compile-time loop on a tuple's622// fields.623template <size_t N>624class TuplePrefix {625public:626// TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true627// if and only if the first N fields of matcher_tuple matches628// the first N fields of value_tuple, respectively.629template <typename MatcherTuple, typename ValueTuple>630static bool Matches(const MatcherTuple& matcher_tuple,631const ValueTuple& value_tuple) {632return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) &&633std::get<N - 1>(matcher_tuple).Matches(std::get<N - 1>(value_tuple));634}635636// TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)637// describes failures in matching the first N fields of matchers638// against the first N fields of values. If there is no failure,639// nothing will be streamed to os.640template <typename MatcherTuple, typename ValueTuple>641static void ExplainMatchFailuresTo(const MatcherTuple& matchers,642const ValueTuple& values,643::std::ostream* os) {644// First, describes failures in the first N - 1 fields.645TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);646647// Then describes the failure (if any) in the (N - 1)-th (0-based)648// field.649typename std::tuple_element<N - 1, MatcherTuple>::type matcher =650std::get<N - 1>(matchers);651typedef typename std::tuple_element<N - 1, ValueTuple>::type Value;652const Value& value = std::get<N - 1>(values);653StringMatchResultListener listener;654if (!matcher.MatchAndExplain(value, &listener)) {655*os << " Expected arg #" << N - 1 << ": ";656std::get<N - 1>(matchers).DescribeTo(os);657*os << "\n Actual: ";658// We remove the reference in type Value to prevent the659// universal printer from printing the address of value, which660// isn't interesting to the user most of the time. The661// matcher's MatchAndExplain() method handles the case when662// the address is interesting.663internal::UniversalPrint(value, os);664PrintIfNotEmpty(listener.str(), os);665*os << "\n";666}667}668};669670// The base case.671template <>672class TuplePrefix<0> {673public:674template <typename MatcherTuple, typename ValueTuple>675static bool Matches(const MatcherTuple& /* matcher_tuple */,676const ValueTuple& /* value_tuple */) {677return true;678}679680template <typename MatcherTuple, typename ValueTuple>681static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,682const ValueTuple& /* values */,683::std::ostream* /* os */) {}684};685686// TupleMatches(matcher_tuple, value_tuple) returns true if and only if687// all matchers in matcher_tuple match the corresponding fields in688// value_tuple. It is a compiler error if matcher_tuple and689// value_tuple have different number of fields or incompatible field690// types.691template <typename MatcherTuple, typename ValueTuple>692bool TupleMatches(const MatcherTuple& matcher_tuple,693const ValueTuple& value_tuple) {694// Makes sure that matcher_tuple and value_tuple have the same695// number of fields.696static_assert(std::tuple_size<MatcherTuple>::value ==697std::tuple_size<ValueTuple>::value,698"matcher and value have different numbers of fields");699return TuplePrefix<std::tuple_size<ValueTuple>::value>::Matches(matcher_tuple,700value_tuple);701}702703// Describes failures in matching matchers against values. If there704// is no failure, nothing will be streamed to os.705template <typename MatcherTuple, typename ValueTuple>706void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,707const ValueTuple& values, ::std::ostream* os) {708TuplePrefix<std::tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(709matchers, values, os);710}711712// TransformTupleValues and its helper.713//714// TransformTupleValuesHelper hides the internal machinery that715// TransformTupleValues uses to implement a tuple traversal.716template <typename Tuple, typename Func, typename OutIter>717class TransformTupleValuesHelper {718private:719typedef ::std::tuple_size<Tuple> TupleSize;720721public:722// For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.723// Returns the final value of 'out' in case the caller needs it.724static OutIter Run(Func f, const Tuple& t, OutIter out) {725return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);726}727728private:729template <typename Tup, size_t kRemainingSize>730struct IterateOverTuple {731OutIter operator()(Func f, const Tup& t, OutIter out) const {732*out++ = f(::std::get<TupleSize::value - kRemainingSize>(t));733return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);734}735};736template <typename Tup>737struct IterateOverTuple<Tup, 0> {738OutIter operator()(Func /* f */, const Tup& /* t */, OutIter out) const {739return out;740}741};742};743744// Successively invokes 'f(element)' on each element of the tuple 't',745// appending each result to the 'out' iterator. Returns the final value746// of 'out'.747template <typename Tuple, typename Func, typename OutIter>748OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {749return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);750}751752// Implements _, a matcher that matches any value of any753// type. This is a polymorphic matcher, so we need a template type754// conversion operator to make it appearing as a Matcher<T> for any755// type T.756class AnythingMatcher {757public:758using is_gtest_matcher = void;759760template <typename T>761bool MatchAndExplain(const T& /* x */, std::ostream* /* listener */) const {762return true;763}764void DescribeTo(std::ostream* os) const { *os << "is anything"; }765void DescribeNegationTo(::std::ostream* os) const {766// This is mostly for completeness' sake, as it's not very useful767// to write Not(A<bool>()). However we cannot completely rule out768// such a possibility, and it doesn't hurt to be prepared.769*os << "never matches";770}771};772773// Implements the polymorphic IsNull() matcher, which matches any raw or smart774// pointer that is NULL.775class IsNullMatcher {776public:777template <typename Pointer>778bool MatchAndExplain(const Pointer& p,779MatchResultListener* /* listener */) const {780return p == nullptr;781}782783void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }784void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NULL"; }785};786787// Implements the polymorphic NotNull() matcher, which matches any raw or smart788// pointer that is not NULL.789class NotNullMatcher {790public:791template <typename Pointer>792bool MatchAndExplain(const Pointer& p,793MatchResultListener* /* listener */) const {794return p != nullptr;795}796797void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }798void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; }799};800801// Ref(variable) matches any argument that is a reference to802// 'variable'. This matcher is polymorphic as it can match any803// super type of the type of 'variable'.804//805// The RefMatcher template class implements Ref(variable). It can806// only be instantiated with a reference type. This prevents a user807// from mistakenly using Ref(x) to match a non-reference function808// argument. For example, the following will righteously cause a809// compiler error:810//811// int n;812// Matcher<int> m1 = Ref(n); // This won't compile.813// Matcher<int&> m2 = Ref(n); // This will compile.814template <typename T>815class RefMatcher;816817template <typename T>818class RefMatcher<T&> {819// Google Mock is a generic framework and thus needs to support820// mocking any function types, including those that take non-const821// reference arguments. Therefore the template parameter T (and822// Super below) can be instantiated to either a const type or a823// non-const type.824public:825// RefMatcher() takes a T& instead of const T&, as we want the826// compiler to catch using Ref(const_value) as a matcher for a827// non-const reference.828explicit RefMatcher(T& x) : object_(x) {} // NOLINT829830template <typename Super>831operator Matcher<Super&>() const {832// By passing object_ (type T&) to Impl(), which expects a Super&,833// we make sure that Super is a super type of T. In particular,834// this catches using Ref(const_value) as a matcher for a835// non-const reference, as you cannot implicitly convert a const836// reference to a non-const reference.837return MakeMatcher(new Impl<Super>(object_));838}839840private:841template <typename Super>842class Impl : public MatcherInterface<Super&> {843public:844explicit Impl(Super& x) : object_(x) {} // NOLINT845846// MatchAndExplain() takes a Super& (as opposed to const Super&)847// in order to match the interface MatcherInterface<Super&>.848bool MatchAndExplain(Super& x,849MatchResultListener* listener) const override {850*listener << "which is located @" << static_cast<const void*>(&x);851return &x == &object_;852}853854void DescribeTo(::std::ostream* os) const override {855*os << "references the variable ";856UniversalPrinter<Super&>::Print(object_, os);857}858859void DescribeNegationTo(::std::ostream* os) const override {860*os << "does not reference the variable ";861UniversalPrinter<Super&>::Print(object_, os);862}863864private:865const Super& object_;866};867868T& object_;869};870871// Polymorphic helper functions for narrow and wide string matchers.872inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {873return String::CaseInsensitiveCStringEquals(lhs, rhs);874}875876inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,877const wchar_t* rhs) {878return String::CaseInsensitiveWideCStringEquals(lhs, rhs);879}880881// String comparison for narrow or wide strings that can have embedded NUL882// characters.883template <typename StringType>884bool CaseInsensitiveStringEquals(const StringType& s1, const StringType& s2) {885// Are the heads equal?886if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {887return false;888}889890// Skip the equal heads.891const typename StringType::value_type nul = 0;892const size_t i1 = s1.find(nul), i2 = s2.find(nul);893894// Are we at the end of either s1 or s2?895if (i1 == StringType::npos || i2 == StringType::npos) {896return i1 == i2;897}898899// Are the tails equal?900return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));901}902903// String matchers.904905// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.906template <typename StringType>907class StrEqualityMatcher {908public:909StrEqualityMatcher(StringType str, bool expect_eq, bool case_sensitive)910: string_(std::move(str)),911expect_eq_(expect_eq),912case_sensitive_(case_sensitive) {}913914#if GTEST_INTERNAL_HAS_STRING_VIEW915bool MatchAndExplain(const internal::StringView& s,916MatchResultListener* listener) const {917// This should fail to compile if StringView is used with wide918// strings.919const StringType& str = std::string(s);920return MatchAndExplain(str, listener);921}922#endif // GTEST_INTERNAL_HAS_STRING_VIEW923924// Accepts pointer types, particularly:925// const char*926// char*927// const wchar_t*928// wchar_t*929template <typename CharType>930bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {931if (s == nullptr) {932return !expect_eq_;933}934return MatchAndExplain(StringType(s), listener);935}936937// Matches anything that can convert to StringType.938//939// This is a template, not just a plain function with const StringType&,940// because StringView has some interfering non-explicit constructors.941template <typename MatcheeStringType>942bool MatchAndExplain(const MatcheeStringType& s,943MatchResultListener* /* listener */) const {944const StringType s2(s);945const bool eq = case_sensitive_ ? s2 == string_946: CaseInsensitiveStringEquals(s2, string_);947return expect_eq_ == eq;948}949950void DescribeTo(::std::ostream* os) const {951DescribeToHelper(expect_eq_, os);952}953954void DescribeNegationTo(::std::ostream* os) const {955DescribeToHelper(!expect_eq_, os);956}957958private:959void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {960*os << (expect_eq ? "is " : "isn't ");961*os << "equal to ";962if (!case_sensitive_) {963*os << "(ignoring case) ";964}965UniversalPrint(string_, os);966}967968const StringType string_;969const bool expect_eq_;970const bool case_sensitive_;971};972973// Implements the polymorphic HasSubstr(substring) matcher, which974// can be used as a Matcher<T> as long as T can be converted to a975// string.976template <typename StringType>977class HasSubstrMatcher {978public:979explicit HasSubstrMatcher(const StringType& substring)980: substring_(substring) {}981982#if GTEST_INTERNAL_HAS_STRING_VIEW983bool MatchAndExplain(const internal::StringView& s,984MatchResultListener* listener) const {985// This should fail to compile if StringView is used with wide986// strings.987const StringType& str = std::string(s);988return MatchAndExplain(str, listener);989}990#endif // GTEST_INTERNAL_HAS_STRING_VIEW991992// Accepts pointer types, particularly:993// const char*994// char*995// const wchar_t*996// wchar_t*997template <typename CharType>998bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {999return s != nullptr && MatchAndExplain(StringType(s), listener);1000}10011002// Matches anything that can convert to StringType.1003//1004// This is a template, not just a plain function with const StringType&,1005// because StringView has some interfering non-explicit constructors.1006template <typename MatcheeStringType>1007bool MatchAndExplain(const MatcheeStringType& s,1008MatchResultListener* /* listener */) const {1009return StringType(s).find(substring_) != StringType::npos;1010}10111012// Describes what this matcher matches.1013void DescribeTo(::std::ostream* os) const {1014*os << "has substring ";1015UniversalPrint(substring_, os);1016}10171018void DescribeNegationTo(::std::ostream* os) const {1019*os << "has no substring ";1020UniversalPrint(substring_, os);1021}10221023private:1024const StringType substring_;1025};10261027// Implements the polymorphic StartsWith(substring) matcher, which1028// can be used as a Matcher<T> as long as T can be converted to a1029// string.1030template <typename StringType>1031class StartsWithMatcher {1032public:1033explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {}10341035#if GTEST_INTERNAL_HAS_STRING_VIEW1036bool MatchAndExplain(const internal::StringView& s,1037MatchResultListener* listener) const {1038// This should fail to compile if StringView is used with wide1039// strings.1040const StringType& str = std::string(s);1041return MatchAndExplain(str, listener);1042}1043#endif // GTEST_INTERNAL_HAS_STRING_VIEW10441045// Accepts pointer types, particularly:1046// const char*1047// char*1048// const wchar_t*1049// wchar_t*1050template <typename CharType>1051bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {1052return s != nullptr && MatchAndExplain(StringType(s), listener);1053}10541055// Matches anything that can convert to StringType.1056//1057// This is a template, not just a plain function with const StringType&,1058// because StringView has some interfering non-explicit constructors.1059template <typename MatcheeStringType>1060bool MatchAndExplain(const MatcheeStringType& s,1061MatchResultListener* /* listener */) const {1062const StringType s2(s);1063return s2.length() >= prefix_.length() &&1064s2.substr(0, prefix_.length()) == prefix_;1065}10661067void DescribeTo(::std::ostream* os) const {1068*os << "starts with ";1069UniversalPrint(prefix_, os);1070}10711072void DescribeNegationTo(::std::ostream* os) const {1073*os << "doesn't start with ";1074UniversalPrint(prefix_, os);1075}10761077private:1078const StringType prefix_;1079};10801081// Implements the polymorphic EndsWith(substring) matcher, which1082// can be used as a Matcher<T> as long as T can be converted to a1083// string.1084template <typename StringType>1085class EndsWithMatcher {1086public:1087explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}10881089#if GTEST_INTERNAL_HAS_STRING_VIEW1090bool MatchAndExplain(const internal::StringView& s,1091MatchResultListener* listener) const {1092// This should fail to compile if StringView is used with wide1093// strings.1094const StringType& str = std::string(s);1095return MatchAndExplain(str, listener);1096}1097#endif // GTEST_INTERNAL_HAS_STRING_VIEW10981099// Accepts pointer types, particularly:1100// const char*1101// char*1102// const wchar_t*1103// wchar_t*1104template <typename CharType>1105bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {1106return s != nullptr && MatchAndExplain(StringType(s), listener);1107}11081109// Matches anything that can convert to StringType.1110//1111// This is a template, not just a plain function with const StringType&,1112// because StringView has some interfering non-explicit constructors.1113template <typename MatcheeStringType>1114bool MatchAndExplain(const MatcheeStringType& s,1115MatchResultListener* /* listener */) const {1116const StringType s2(s);1117return s2.length() >= suffix_.length() &&1118s2.substr(s2.length() - suffix_.length()) == suffix_;1119}11201121void DescribeTo(::std::ostream* os) const {1122*os << "ends with ";1123UniversalPrint(suffix_, os);1124}11251126void DescribeNegationTo(::std::ostream* os) const {1127*os << "doesn't end with ";1128UniversalPrint(suffix_, os);1129}11301131private:1132const StringType suffix_;1133};11341135// Implements the polymorphic WhenBase64Unescaped(matcher) matcher, which can be1136// used as a Matcher<T> as long as T can be converted to a string.1137class WhenBase64UnescapedMatcher {1138public:1139using is_gtest_matcher = void;11401141explicit WhenBase64UnescapedMatcher(1142const Matcher<const std::string&>& internal_matcher)1143: internal_matcher_(internal_matcher) {}11441145// Matches anything that can convert to std::string.1146template <typename MatcheeStringType>1147bool MatchAndExplain(const MatcheeStringType& s,1148MatchResultListener* listener) const {1149const std::string s2(s); // NOLINT (needed for working with string_view).1150std::string unescaped;1151if (!internal::Base64Unescape(s2, &unescaped)) {1152if (listener != nullptr) {1153*listener << "is not a valid base64 escaped string";1154}1155return false;1156}1157return MatchPrintAndExplain(unescaped, internal_matcher_, listener);1158}11591160void DescribeTo(::std::ostream* os) const {1161*os << "matches after Base64Unescape ";1162internal_matcher_.DescribeTo(os);1163}11641165void DescribeNegationTo(::std::ostream* os) const {1166*os << "does not match after Base64Unescape ";1167internal_matcher_.DescribeTo(os);1168}11691170private:1171const Matcher<const std::string&> internal_matcher_;1172};11731174// Implements a matcher that compares the two fields of a 2-tuple1175// using one of the ==, <=, <, etc, operators. The two fields being1176// compared don't have to have the same type.1177//1178// The matcher defined here is polymorphic (for example, Eq() can be1179// used to match a std::tuple<int, short>, a std::tuple<const long&, double>,1180// etc). Therefore we use a template type conversion operator in the1181// implementation.1182template <typename D, typename Op>1183class PairMatchBase {1184public:1185template <typename T1, typename T2>1186operator Matcher<::std::tuple<T1, T2>>() const {1187return Matcher<::std::tuple<T1, T2>>(new Impl<const ::std::tuple<T1, T2>&>);1188}1189template <typename T1, typename T2>1190operator Matcher<const ::std::tuple<T1, T2>&>() const {1191return MakeMatcher(new Impl<const ::std::tuple<T1, T2>&>);1192}11931194private:1195static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT1196return os << D::Desc();1197}11981199template <typename Tuple>1200class Impl : public MatcherInterface<Tuple> {1201public:1202bool MatchAndExplain(Tuple args,1203MatchResultListener* /* listener */) const override {1204return Op()(::std::get<0>(args), ::std::get<1>(args));1205}1206void DescribeTo(::std::ostream* os) const override {1207*os << "are " << GetDesc;1208}1209void DescribeNegationTo(::std::ostream* os) const override {1210*os << "aren't " << GetDesc;1211}1212};1213};12141215class Eq2Matcher : public PairMatchBase<Eq2Matcher, std::equal_to<>> {1216public:1217static const char* Desc() { return "an equal pair"; }1218};1219class Ne2Matcher : public PairMatchBase<Ne2Matcher, std::not_equal_to<>> {1220public:1221static const char* Desc() { return "an unequal pair"; }1222};1223class Lt2Matcher : public PairMatchBase<Lt2Matcher, std::less<>> {1224public:1225static const char* Desc() { return "a pair where the first < the second"; }1226};1227class Gt2Matcher : public PairMatchBase<Gt2Matcher, std::greater<>> {1228public:1229static const char* Desc() { return "a pair where the first > the second"; }1230};1231class Le2Matcher : public PairMatchBase<Le2Matcher, std::less_equal<>> {1232public:1233static const char* Desc() { return "a pair where the first <= the second"; }1234};1235class Ge2Matcher : public PairMatchBase<Ge2Matcher, std::greater_equal<>> {1236public:1237static const char* Desc() { return "a pair where the first >= the second"; }1238};12391240// Implements the Not(...) matcher for a particular argument type T.1241// We do not nest it inside the NotMatcher class template, as that1242// will prevent different instantiations of NotMatcher from sharing1243// the same NotMatcherImpl<T> class.1244template <typename T>1245class NotMatcherImpl : public MatcherInterface<const T&> {1246public:1247explicit NotMatcherImpl(const Matcher<T>& matcher) : matcher_(matcher) {}12481249bool MatchAndExplain(const T& x,1250MatchResultListener* listener) const override {1251return !matcher_.MatchAndExplain(x, listener);1252}12531254void DescribeTo(::std::ostream* os) const override {1255matcher_.DescribeNegationTo(os);1256}12571258void DescribeNegationTo(::std::ostream* os) const override {1259matcher_.DescribeTo(os);1260}12611262private:1263const Matcher<T> matcher_;1264};12651266// Implements the Not(m) matcher, which matches a value that doesn't1267// match matcher m.1268template <typename InnerMatcher>1269class NotMatcher {1270public:1271explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}12721273// This template type conversion operator allows Not(m) to be used1274// to match any type m can match.1275template <typename T>1276operator Matcher<T>() const {1277return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));1278}12791280private:1281InnerMatcher matcher_;1282};12831284// Implements the AllOf(m1, m2) matcher for a particular argument type1285// T. We do not nest it inside the BothOfMatcher class template, as1286// that will prevent different instantiations of BothOfMatcher from1287// sharing the same BothOfMatcherImpl<T> class.1288template <typename T>1289class AllOfMatcherImpl : public MatcherInterface<const T&> {1290public:1291explicit AllOfMatcherImpl(std::vector<Matcher<T>> matchers)1292: matchers_(std::move(matchers)) {}12931294void DescribeTo(::std::ostream* os) const override {1295*os << "(";1296for (size_t i = 0; i < matchers_.size(); ++i) {1297if (i != 0) *os << ") and (";1298matchers_[i].DescribeTo(os);1299}1300*os << ")";1301}13021303void DescribeNegationTo(::std::ostream* os) const override {1304*os << "(";1305for (size_t i = 0; i < matchers_.size(); ++i) {1306if (i != 0) *os << ") or (";1307matchers_[i].DescribeNegationTo(os);1308}1309*os << ")";1310}13111312bool MatchAndExplain(const T& x,1313MatchResultListener* listener) const override {1314if (!listener->IsInterested()) {1315// Fast path to avoid unnecessary formatting.1316for (const Matcher<T>& matcher : matchers_) {1317if (!matcher.Matches(x)) {1318return false;1319}1320}1321return true;1322}1323// This method uses matcher's explanation when explaining the result.1324// However, if matcher doesn't provide one, this method uses matcher's1325// description.1326std::string all_match_result;1327for (const Matcher<T>& matcher : matchers_) {1328StringMatchResultListener slistener;1329// Return explanation for first failed matcher.1330if (!matcher.MatchAndExplain(x, &slistener)) {1331const std::string explanation = slistener.str();1332if (!explanation.empty()) {1333*listener << explanation;1334} else {1335*listener << "which doesn't match (" << Describe(matcher) << ")";1336}1337return false;1338}1339// Keep track of explanations in case all matchers succeed.1340std::string explanation = slistener.str();1341if (explanation.empty()) {1342explanation = Describe(matcher);1343}1344if (all_match_result.empty()) {1345all_match_result = explanation;1346} else {1347if (!explanation.empty()) {1348all_match_result += ", and ";1349all_match_result += explanation;1350}1351}1352}13531354*listener << all_match_result;1355return true;1356}13571358private:1359// Returns matcher description as a string.1360std::string Describe(const Matcher<T>& matcher) const {1361StringMatchResultListener listener;1362matcher.DescribeTo(listener.stream());1363return listener.str();1364}1365const std::vector<Matcher<T>> matchers_;1366};13671368// VariadicMatcher is used for the variadic implementation of1369// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).1370// CombiningMatcher<T> is used to recursively combine the provided matchers1371// (of type Args...).1372template <template <typename T> class CombiningMatcher, typename... Args>1373class VariadicMatcher {1374public:1375VariadicMatcher(const Args&... matchers) // NOLINT1376: matchers_(matchers...) {1377static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");1378}13791380VariadicMatcher(const VariadicMatcher&) = default;1381VariadicMatcher& operator=(const VariadicMatcher&) = delete;13821383// This template type conversion operator allows an1384// VariadicMatcher<Matcher1, Matcher2...> object to match any type that1385// all of the provided matchers (Matcher1, Matcher2, ...) can match.1386template <typename T>1387operator Matcher<T>() const {1388std::vector<Matcher<T>> values;1389CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());1390return Matcher<T>(new CombiningMatcher<T>(std::move(values)));1391}13921393private:1394template <typename T, size_t I>1395void CreateVariadicMatcher(std::vector<Matcher<T>>* values,1396std::integral_constant<size_t, I>) const {1397values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));1398CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());1399}14001401template <typename T>1402void CreateVariadicMatcher(1403std::vector<Matcher<T>>*,1404std::integral_constant<size_t, sizeof...(Args)>) const {}14051406std::tuple<Args...> matchers_;1407};14081409template <typename... Args>1410using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;14111412// Implements the AnyOf(m1, m2) matcher for a particular argument type1413// T. We do not nest it inside the AnyOfMatcher class template, as1414// that will prevent different instantiations of AnyOfMatcher from1415// sharing the same EitherOfMatcherImpl<T> class.1416template <typename T>1417class AnyOfMatcherImpl : public MatcherInterface<const T&> {1418public:1419explicit AnyOfMatcherImpl(std::vector<Matcher<T>> matchers)1420: matchers_(std::move(matchers)) {}14211422void DescribeTo(::std::ostream* os) const override {1423*os << "(";1424for (size_t i = 0; i < matchers_.size(); ++i) {1425if (i != 0) *os << ") or (";1426matchers_[i].DescribeTo(os);1427}1428*os << ")";1429}14301431void DescribeNegationTo(::std::ostream* os) const override {1432*os << "(";1433for (size_t i = 0; i < matchers_.size(); ++i) {1434if (i != 0) *os << ") and (";1435matchers_[i].DescribeNegationTo(os);1436}1437*os << ")";1438}14391440bool MatchAndExplain(const T& x,1441MatchResultListener* listener) const override {1442if (!listener->IsInterested()) {1443// Fast path to avoid unnecessary formatting of match explanations.1444for (const Matcher<T>& matcher : matchers_) {1445if (matcher.Matches(x)) {1446return true;1447}1448}1449return false;1450}1451// This method uses matcher's explanation when explaining the result.1452// However, if matcher doesn't provide one, this method uses matcher's1453// description.1454std::string no_match_result;1455for (const Matcher<T>& matcher : matchers_) {1456StringMatchResultListener slistener;1457// Return explanation for first match.1458if (matcher.MatchAndExplain(x, &slistener)) {1459const std::string explanation = slistener.str();1460if (!explanation.empty()) {1461*listener << explanation;1462} else {1463*listener << "which matches (" << Describe(matcher) << ")";1464}1465return true;1466}1467// Keep track of explanations in case there is no match.1468std::string explanation = slistener.str();1469if (explanation.empty()) {1470explanation = DescribeNegation(matcher);1471}1472if (no_match_result.empty()) {1473no_match_result = explanation;1474} else {1475if (!explanation.empty()) {1476no_match_result += ", and ";1477no_match_result += explanation;1478}1479}1480}14811482*listener << no_match_result;1483return false;1484}14851486private:1487// Returns matcher description as a string.1488std::string Describe(const Matcher<T>& matcher) const {1489StringMatchResultListener listener;1490matcher.DescribeTo(listener.stream());1491return listener.str();1492}14931494std::string DescribeNegation(const Matcher<T>& matcher) const {1495StringMatchResultListener listener;1496matcher.DescribeNegationTo(listener.stream());1497return listener.str();1498}14991500const std::vector<Matcher<T>> matchers_;1501};15021503// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).1504template <typename... Args>1505using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;15061507// ConditionalMatcher is the implementation of Conditional(cond, m1, m2)1508template <typename MatcherTrue, typename MatcherFalse>1509class ConditionalMatcher {1510public:1511ConditionalMatcher(bool condition, MatcherTrue matcher_true,1512MatcherFalse matcher_false)1513: condition_(condition),1514matcher_true_(std::move(matcher_true)),1515matcher_false_(std::move(matcher_false)) {}15161517template <typename T>1518operator Matcher<T>() const { // NOLINT(runtime/explicit)1519return condition_ ? SafeMatcherCast<T>(matcher_true_)1520: SafeMatcherCast<T>(matcher_false_);1521}15221523private:1524bool condition_;1525MatcherTrue matcher_true_;1526MatcherFalse matcher_false_;1527};15281529// Wrapper for implementation of Any/AllOfArray().1530template <template <class> class MatcherImpl, typename T>1531class SomeOfArrayMatcher {1532public:1533// Constructs the matcher from a sequence of element values or1534// element matchers.1535template <typename Iter>1536SomeOfArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}15371538template <typename U>1539operator Matcher<U>() const { // NOLINT1540using RawU = typename std::decay<U>::type;1541std::vector<Matcher<RawU>> matchers;1542matchers.reserve(matchers_.size());1543for (const auto& matcher : matchers_) {1544matchers.push_back(MatcherCast<RawU>(matcher));1545}1546return Matcher<U>(new MatcherImpl<RawU>(std::move(matchers)));1547}15481549private:1550const std::vector<std::remove_const_t<T>> matchers_;1551};15521553template <typename T>1554using AllOfArrayMatcher = SomeOfArrayMatcher<AllOfMatcherImpl, T>;15551556template <typename T>1557using AnyOfArrayMatcher = SomeOfArrayMatcher<AnyOfMatcherImpl, T>;15581559// Used for implementing Truly(pred), which turns a predicate into a1560// matcher.1561template <typename Predicate>1562class TrulyMatcher {1563public:1564explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}15651566// This method template allows Truly(pred) to be used as a matcher1567// for type T where T is the argument type of predicate 'pred'. The1568// argument is passed by reference as the predicate may be1569// interested in the address of the argument.1570template <typename T>1571bool MatchAndExplain(T& x, // NOLINT1572MatchResultListener* listener) const {1573// Without the if-statement, MSVC sometimes warns about converting1574// a value to bool (warning 4800).1575//1576// We cannot write 'return !!predicate_(x);' as that doesn't work1577// when predicate_(x) returns a class convertible to bool but1578// having no operator!().1579if (predicate_(x)) return true;1580*listener << "didn't satisfy the given predicate";1581return false;1582}15831584void DescribeTo(::std::ostream* os) const {1585*os << "satisfies the given predicate";1586}15871588void DescribeNegationTo(::std::ostream* os) const {1589*os << "doesn't satisfy the given predicate";1590}15911592private:1593Predicate predicate_;1594};15951596// Used for implementing Matches(matcher), which turns a matcher into1597// a predicate.1598template <typename M>1599class MatcherAsPredicate {1600public:1601explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}16021603// This template operator() allows Matches(m) to be used as a1604// predicate on type T where m is a matcher on type T.1605//1606// The argument x is passed by reference instead of by value, as1607// some matcher may be interested in its address (e.g. as in1608// Matches(Ref(n))(x)).1609template <typename T>1610bool operator()(const T& x) const {1611// We let matcher_ commit to a particular type here instead of1612// when the MatcherAsPredicate object was constructed. This1613// allows us to write Matches(m) where m is a polymorphic matcher1614// (e.g. Eq(5)).1615//1616// If we write Matcher<T>(matcher_).Matches(x) here, it won't1617// compile when matcher_ has type Matcher<const T&>; if we write1618// Matcher<const T&>(matcher_).Matches(x) here, it won't compile1619// when matcher_ has type Matcher<T>; if we just write1620// matcher_.Matches(x), it won't compile when matcher_ is1621// polymorphic, e.g. Eq(5).1622//1623// MatcherCast<const T&>() is necessary for making the code work1624// in all of the above situations.1625return MatcherCast<const T&>(matcher_).Matches(x);1626}16271628private:1629M matcher_;1630};16311632// For implementing ASSERT_THAT() and EXPECT_THAT(). The template1633// argument M must be a type that can be converted to a matcher.1634template <typename M>1635class PredicateFormatterFromMatcher {1636public:1637explicit PredicateFormatterFromMatcher(M m) : matcher_(std::move(m)) {}16381639// This template () operator allows a PredicateFormatterFromMatcher1640// object to act as a predicate-formatter suitable for using with1641// Google Test's EXPECT_PRED_FORMAT1() macro.1642template <typename T>1643AssertionResult operator()(const char* value_text, const T& x) const {1644// We convert matcher_ to a Matcher<const T&> *now* instead of1645// when the PredicateFormatterFromMatcher object was constructed,1646// as matcher_ may be polymorphic (e.g. NotNull()) and we won't1647// know which type to instantiate it to until we actually see the1648// type of x here.1649//1650// We write SafeMatcherCast<const T&>(matcher_) instead of1651// Matcher<const T&>(matcher_), as the latter won't compile when1652// matcher_ has type Matcher<T> (e.g. An<int>()).1653// We don't write MatcherCast<const T&> either, as that allows1654// potentially unsafe downcasting of the matcher argument.1655const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);16561657// The expected path here is that the matcher should match (i.e. that most1658// tests pass) so optimize for this case.1659if (matcher.Matches(x)) {1660return AssertionSuccess();1661}16621663::std::stringstream ss;1664ss << "Value of: " << value_text << "\n"1665<< "Expected: ";1666matcher.DescribeTo(&ss);16671668// Rerun the matcher to "PrintAndExplain" the failure.1669StringMatchResultListener listener;1670if (MatchPrintAndExplain(x, matcher, &listener)) {1671ss << "\n The matcher failed on the initial attempt; but passed when "1672"rerun to generate the explanation.";1673}1674ss << "\n Actual: " << listener.str();1675return AssertionFailure() << ss.str();1676}16771678private:1679const M matcher_;1680};16811682// A helper function for converting a matcher to a predicate-formatter1683// without the user needing to explicitly write the type. This is1684// used for implementing ASSERT_THAT() and EXPECT_THAT().1685// Implementation detail: 'matcher' is received by-value to force decaying.1686template <typename M>1687inline PredicateFormatterFromMatcher<M> MakePredicateFormatterFromMatcher(1688M matcher) {1689return PredicateFormatterFromMatcher<M>(std::move(matcher));1690}16911692// Implements the polymorphic IsNan() matcher, which matches any floating type1693// value that is Nan.1694class IsNanMatcher {1695public:1696template <typename FloatType>1697bool MatchAndExplain(const FloatType& f,1698MatchResultListener* /* listener */) const {1699return (::std::isnan)(f);1700}17011702void DescribeTo(::std::ostream* os) const { *os << "is NaN"; }1703void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NaN"; }1704};17051706// Implements the polymorphic floating point equality matcher, which matches1707// two float values using ULP-based approximation or, optionally, a1708// user-specified epsilon. The template is meant to be instantiated with1709// FloatType being either float or double.1710template <typename FloatType>1711class FloatingEqMatcher {1712public:1713// Constructor for FloatingEqMatcher.1714// The matcher's input will be compared with expected. The matcher treats two1715// NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,1716// equality comparisons between NANs will always return false. We specify a1717// negative max_abs_error_ term to indicate that ULP-based approximation will1718// be used for comparison.1719FloatingEqMatcher(FloatType expected, bool nan_eq_nan)1720: expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {}17211722// Constructor that supports a user-specified max_abs_error that will be used1723// for comparison instead of ULP-based approximation. The max absolute1724// should be non-negative.1725FloatingEqMatcher(FloatType expected, bool nan_eq_nan,1726FloatType max_abs_error)1727: expected_(expected),1728nan_eq_nan_(nan_eq_nan),1729max_abs_error_(max_abs_error) {1730GTEST_CHECK_(max_abs_error >= 0)1731<< ", where max_abs_error is" << max_abs_error;1732}17331734// Implements floating point equality matcher as a Matcher<T>.1735template <typename T>1736class Impl : public MatcherInterface<T> {1737public:1738Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)1739: expected_(expected),1740nan_eq_nan_(nan_eq_nan),1741max_abs_error_(max_abs_error) {}17421743bool MatchAndExplain(T value,1744MatchResultListener* listener) const override {1745const FloatingPoint<FloatType> actual(value), expected(expected_);17461747// Compares NaNs first, if nan_eq_nan_ is true.1748if (actual.is_nan() || expected.is_nan()) {1749if (actual.is_nan() && expected.is_nan()) {1750return nan_eq_nan_;1751}1752// One is nan; the other is not nan.1753return false;1754}1755if (HasMaxAbsError()) {1756// We perform an equality check so that inf will match inf, regardless1757// of error bounds. If the result of value - expected_ would result in1758// overflow or if either value is inf, the default result is infinity,1759// which should only match if max_abs_error_ is also infinity.1760if (value == expected_) {1761return true;1762}17631764const FloatType diff = value - expected_;1765if (::std::fabs(diff) <= max_abs_error_) {1766return true;1767}17681769if (listener->IsInterested()) {1770*listener << "which is " << diff << " from " << expected_;1771}1772return false;1773} else {1774return actual.AlmostEquals(expected);1775}1776}17771778void DescribeTo(::std::ostream* os) const override {1779// os->precision() returns the previously set precision, which we1780// store to restore the ostream to its original configuration1781// after outputting.1782const ::std::streamsize old_precision =1783os->precision(::std::numeric_limits<FloatType>::digits10 + 2);1784if (FloatingPoint<FloatType>(expected_).is_nan()) {1785if (nan_eq_nan_) {1786*os << "is NaN";1787} else {1788*os << "never matches";1789}1790} else {1791*os << "is approximately " << expected_;1792if (HasMaxAbsError()) {1793*os << " (absolute error <= " << max_abs_error_ << ")";1794}1795}1796os->precision(old_precision);1797}17981799void DescribeNegationTo(::std::ostream* os) const override {1800// As before, get original precision.1801const ::std::streamsize old_precision =1802os->precision(::std::numeric_limits<FloatType>::digits10 + 2);1803if (FloatingPoint<FloatType>(expected_).is_nan()) {1804if (nan_eq_nan_) {1805*os << "isn't NaN";1806} else {1807*os << "is anything";1808}1809} else {1810*os << "isn't approximately " << expected_;1811if (HasMaxAbsError()) {1812*os << " (absolute error > " << max_abs_error_ << ")";1813}1814}1815// Restore original precision.1816os->precision(old_precision);1817}18181819private:1820bool HasMaxAbsError() const { return max_abs_error_ >= 0; }18211822const FloatType expected_;1823const bool nan_eq_nan_;1824// max_abs_error will be used for value comparison when >= 0.1825const FloatType max_abs_error_;1826};18271828// The following 3 type conversion operators allow FloatEq(expected) and1829// NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a1830// Matcher<const float&>, or a Matcher<float&>, but nothing else.1831operator Matcher<FloatType>() const {1832return MakeMatcher(1833new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));1834}18351836operator Matcher<const FloatType&>() const {1837return MakeMatcher(1838new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));1839}18401841operator Matcher<FloatType&>() const {1842return MakeMatcher(1843new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));1844}18451846private:1847const FloatType expected_;1848const bool nan_eq_nan_;1849// max_abs_error will be used for value comparison when >= 0.1850const FloatType max_abs_error_;1851};18521853// A 2-tuple ("binary") wrapper around FloatingEqMatcher:1854// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)1855// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)1856// against y. The former implements "Eq", the latter "Near". At present, there1857// is no version that compares NaNs as equal.1858template <typename FloatType>1859class FloatingEq2Matcher {1860public:1861FloatingEq2Matcher() { Init(-1, false); }18621863explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }18641865explicit FloatingEq2Matcher(FloatType max_abs_error) {1866Init(max_abs_error, false);1867}18681869FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {1870Init(max_abs_error, nan_eq_nan);1871}18721873template <typename T1, typename T2>1874operator Matcher<::std::tuple<T1, T2>>() const {1875return MakeMatcher(1876new Impl<::std::tuple<T1, T2>>(max_abs_error_, nan_eq_nan_));1877}1878template <typename T1, typename T2>1879operator Matcher<const ::std::tuple<T1, T2>&>() const {1880return MakeMatcher(1881new Impl<const ::std::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));1882}18831884private:1885static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT1886return os << "an almost-equal pair";1887}18881889template <typename Tuple>1890class Impl : public MatcherInterface<Tuple> {1891public:1892Impl(FloatType max_abs_error, bool nan_eq_nan)1893: max_abs_error_(max_abs_error), nan_eq_nan_(nan_eq_nan) {}18941895bool MatchAndExplain(Tuple args,1896MatchResultListener* listener) const override {1897if (max_abs_error_ == -1) {1898FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_);1899return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(1900::std::get<1>(args), listener);1901} else {1902FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_,1903max_abs_error_);1904return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(1905::std::get<1>(args), listener);1906}1907}1908void DescribeTo(::std::ostream* os) const override {1909*os << "are " << GetDesc;1910}1911void DescribeNegationTo(::std::ostream* os) const override {1912*os << "aren't " << GetDesc;1913}19141915private:1916FloatType max_abs_error_;1917const bool nan_eq_nan_;1918};19191920void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {1921max_abs_error_ = max_abs_error_val;1922nan_eq_nan_ = nan_eq_nan_val;1923}1924FloatType max_abs_error_;1925bool nan_eq_nan_;1926};19271928// Implements the Pointee(m) matcher for matching a pointer whose1929// pointee matches matcher m. The pointer can be either raw or smart.1930template <typename InnerMatcher>1931class PointeeMatcher {1932public:1933explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}19341935// This type conversion operator template allows Pointee(m) to be1936// used as a matcher for any pointer type whose pointee type is1937// compatible with the inner matcher, where type Pointer can be1938// either a raw pointer or a smart pointer.1939//1940// The reason we do this instead of relying on1941// MakePolymorphicMatcher() is that the latter is not flexible1942// enough for implementing the DescribeTo() method of Pointee().1943template <typename Pointer>1944operator Matcher<Pointer>() const {1945return Matcher<Pointer>(new Impl<const Pointer&>(matcher_));1946}19471948private:1949// The monomorphic implementation that works for a particular pointer type.1950template <typename Pointer>1951class Impl : public MatcherInterface<Pointer> {1952public:1953using Pointee =1954typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(1955Pointer)>::element_type;19561957explicit Impl(const InnerMatcher& matcher)1958: matcher_(MatcherCast<const Pointee&>(matcher)) {}19591960void DescribeTo(::std::ostream* os) const override {1961*os << "points to a value that ";1962matcher_.DescribeTo(os);1963}19641965void DescribeNegationTo(::std::ostream* os) const override {1966*os << "does not point to a value that ";1967matcher_.DescribeTo(os);1968}19691970bool MatchAndExplain(Pointer pointer,1971MatchResultListener* listener) const override {1972if (GetRawPointer(pointer) == nullptr) return false;19731974*listener << "which points to ";1975return MatchPrintAndExplain(*pointer, matcher_, listener);1976}19771978private:1979const Matcher<const Pointee&> matcher_;1980};19811982const InnerMatcher matcher_;1983};19841985// Implements the Pointer(m) matcher1986// Implements the Pointer(m) matcher for matching a pointer that matches matcher1987// m. The pointer can be either raw or smart, and will match `m` against the1988// raw pointer.1989template <typename InnerMatcher>1990class PointerMatcher {1991public:1992explicit PointerMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}19931994// This type conversion operator template allows Pointer(m) to be1995// used as a matcher for any pointer type whose pointer type is1996// compatible with the inner matcher, where type PointerType can be1997// either a raw pointer or a smart pointer.1998//1999// The reason we do this instead of relying on2000// MakePolymorphicMatcher() is that the latter is not flexible2001// enough for implementing the DescribeTo() method of Pointer().2002template <typename PointerType>2003operator Matcher<PointerType>() const { // NOLINT2004return Matcher<PointerType>(new Impl<const PointerType&>(matcher_));2005}20062007private:2008// The monomorphic implementation that works for a particular pointer type.2009template <typename PointerType>2010class Impl : public MatcherInterface<PointerType> {2011public:2012using Pointer =2013const typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(2014PointerType)>::element_type*;20152016explicit Impl(const InnerMatcher& matcher)2017: matcher_(MatcherCast<Pointer>(matcher)) {}20182019void DescribeTo(::std::ostream* os) const override {2020*os << "is a pointer that ";2021matcher_.DescribeTo(os);2022}20232024void DescribeNegationTo(::std::ostream* os) const override {2025*os << "is not a pointer that ";2026matcher_.DescribeTo(os);2027}20282029bool MatchAndExplain(PointerType pointer,2030MatchResultListener* listener) const override {2031*listener << "which is a pointer that ";2032Pointer p = GetRawPointer(pointer);2033return MatchPrintAndExplain(p, matcher_, listener);2034}20352036private:2037Matcher<Pointer> matcher_;2038};20392040const InnerMatcher matcher_;2041};20422043#if GTEST_HAS_RTTI2044// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or2045// reference that matches inner_matcher when dynamic_cast<T> is applied.2046// The result of dynamic_cast<To> is forwarded to the inner matcher.2047// If To is a pointer and the cast fails, the inner matcher will receive NULL.2048// If To is a reference and the cast fails, this matcher returns false2049// immediately.2050template <typename To>2051class WhenDynamicCastToMatcherBase {2052public:2053explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)2054: matcher_(matcher) {}20552056void DescribeTo(::std::ostream* os) const {2057GetCastTypeDescription(os);2058matcher_.DescribeTo(os);2059}20602061void DescribeNegationTo(::std::ostream* os) const {2062GetCastTypeDescription(os);2063matcher_.DescribeNegationTo(os);2064}20652066protected:2067const Matcher<To> matcher_;20682069static std::string GetToName() { return GetTypeName<To>(); }20702071private:2072static void GetCastTypeDescription(::std::ostream* os) {2073*os << "when dynamic_cast to " << GetToName() << ", ";2074}2075};20762077// Primary template.2078// To is a pointer. Cast and forward the result.2079template <typename To>2080class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {2081public:2082explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)2083: WhenDynamicCastToMatcherBase<To>(matcher) {}20842085template <typename From>2086bool MatchAndExplain(From from, MatchResultListener* listener) const {2087To to = dynamic_cast<To>(from);2088return MatchPrintAndExplain(to, this->matcher_, listener);2089}2090};20912092// Specialize for references.2093// In this case we return false if the dynamic_cast fails.2094template <typename To>2095class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {2096public:2097explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)2098: WhenDynamicCastToMatcherBase<To&>(matcher) {}20992100template <typename From>2101bool MatchAndExplain(From& from, MatchResultListener* listener) const {2102// We don't want an std::bad_cast here, so do the cast with pointers.2103To* to = dynamic_cast<To*>(&from);2104if (to == nullptr) {2105*listener << "which cannot be dynamic_cast to " << this->GetToName();2106return false;2107}2108return MatchPrintAndExplain(*to, this->matcher_, listener);2109}2110};2111#endif // GTEST_HAS_RTTI21122113// Implements the Field() matcher for matching a field (i.e. member2114// variable) of an object.2115template <typename Class, typename FieldType>2116class FieldMatcher {2117public:2118FieldMatcher(FieldType Class::* field,2119const Matcher<const FieldType&>& matcher)2120: field_(field), matcher_(matcher), whose_field_("whose given field ") {}21212122FieldMatcher(const std::string& field_name, FieldType Class::* field,2123const Matcher<const FieldType&>& matcher)2124: field_(field),2125matcher_(matcher),2126whose_field_("whose field `" + field_name + "` ") {}21272128void DescribeTo(::std::ostream* os) const {2129*os << "is an object " << whose_field_;2130matcher_.DescribeTo(os);2131}21322133void DescribeNegationTo(::std::ostream* os) const {2134*os << "is an object " << whose_field_;2135matcher_.DescribeNegationTo(os);2136}21372138template <typename T>2139bool MatchAndExplain(const T& value, MatchResultListener* listener) const {2140// FIXME: The dispatch on std::is_pointer was introduced as a workaround for2141// a compiler bug, and can now be removed.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_field_ << "is ";2152return MatchPrintAndExplain(obj.*field_, matcher_, listener);2153}21542155bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,2156MatchResultListener* listener) const {2157if (p == nullptr) return false;21582159*listener << "which points to an object ";2160// Since *p has a field, it must be a class/struct/union type and2161// thus cannot be a pointer. Therefore we pass false_type() as2162// the first argument.2163return MatchAndExplainImpl(std::false_type(), *p, listener);2164}21652166const FieldType Class::* field_;2167const Matcher<const FieldType&> matcher_;21682169// Contains either "whose given field " if the name of the field is unknown2170// or "whose field `name_of_field` " if the name is known.2171const std::string whose_field_;2172};21732174// Implements the Property() matcher for matching a property2175// (i.e. return value of a getter method) of an object.2176//2177// Property is a const-qualified member function of Class returning2178// PropertyType.2179template <typename Class, typename PropertyType, typename Property>2180class PropertyMatcher {2181public:2182typedef const PropertyType& RefToConstProperty;21832184PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)2185: property_(property),2186matcher_(matcher),2187whose_property_("whose given property ") {}21882189PropertyMatcher(const std::string& property_name, Property property,2190const Matcher<RefToConstProperty>& matcher)2191: property_(property),2192matcher_(matcher),2193whose_property_("whose property `" + property_name + "` ") {}21942195void DescribeTo(::std::ostream* os) const {2196*os << "is an object " << whose_property_;2197matcher_.DescribeTo(os);2198}21992200void DescribeNegationTo(::std::ostream* os) const {2201*os << "is an object " << whose_property_;2202matcher_.DescribeNegationTo(os);2203}22042205template <typename T>2206bool MatchAndExplain(const T& value, MatchResultListener* listener) const {2207return MatchAndExplainImpl(2208typename std::is_pointer<typename std::remove_const<T>::type>::type(),2209value, listener);2210}22112212private:2213bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,2214const Class& obj,2215MatchResultListener* listener) const {2216*listener << whose_property_ << "is ";2217// Cannot pass the return value (for example, int) to MatchPrintAndExplain,2218// which takes a non-const reference as argument.2219RefToConstProperty result = (obj.*property_)();2220return MatchPrintAndExplain(result, matcher_, listener);2221}22222223bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,2224MatchResultListener* listener) const {2225if (p == nullptr) return false;22262227*listener << "which points to an object ";2228// Since *p has a property method, it must be a class/struct/union2229// type and thus cannot be a pointer. Therefore we pass2230// false_type() as the first argument.2231return MatchAndExplainImpl(std::false_type(), *p, listener);2232}22332234Property property_;2235const Matcher<RefToConstProperty> matcher_;22362237// Contains either "whose given property " if the name of the property is2238// unknown or "whose property `name_of_property` " if the name is known.2239const std::string whose_property_;2240};22412242// Type traits specifying various features of different functors for ResultOf.2243// The default template specifies features for functor objects.2244template <typename Functor>2245struct CallableTraits {2246typedef Functor StorageType;22472248static void CheckIsValid(Functor /* functor */) {}22492250template <typename T>2251static auto Invoke(Functor f, const T& arg) -> decltype(f(arg)) {2252return f(arg);2253}2254};22552256// Specialization for function pointers.2257template <typename ArgType, typename ResType>2258struct CallableTraits<ResType (*)(ArgType)> {2259typedef ResType ResultType;2260typedef ResType (*StorageType)(ArgType);22612262static void CheckIsValid(ResType (*f)(ArgType)) {2263GTEST_CHECK_(f != nullptr)2264<< "NULL function pointer is passed into ResultOf().";2265}2266template <typename T>2267static ResType Invoke(ResType (*f)(ArgType), T arg) {2268return (*f)(arg);2269}2270};22712272// Implements the ResultOf() matcher for matching a return value of a2273// unary function of an object.2274template <typename Callable, typename InnerMatcher>2275class ResultOfMatcher {2276public:2277ResultOfMatcher(Callable callable, InnerMatcher matcher)2278: ResultOfMatcher(/*result_description=*/"", std::move(callable),2279std::move(matcher)) {}22802281ResultOfMatcher(const std::string& result_description, Callable callable,2282InnerMatcher matcher)2283: result_description_(result_description),2284callable_(std::move(callable)),2285matcher_(std::move(matcher)) {2286CallableTraits<Callable>::CheckIsValid(callable_);2287}22882289template <typename T>2290operator Matcher<T>() const {2291return Matcher<T>(2292new Impl<const T&>(result_description_, callable_, matcher_));2293}22942295private:2296typedef typename CallableTraits<Callable>::StorageType CallableStorageType;22972298template <typename T>2299class Impl : public MatcherInterface<T> {2300using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(2301std::declval<CallableStorageType>(), std::declval<T>()));2302using InnerType = std::conditional_t<2303std::is_lvalue_reference<ResultType>::value,2304const typename std::remove_reference<ResultType>::type&, ResultType>;23052306public:2307template <typename M>2308Impl(const std::string& result_description,2309const CallableStorageType& callable, const M& matcher)2310: result_description_(result_description),2311callable_(callable),2312matcher_(MatcherCast<InnerType>(matcher)) {}23132314void DescribeTo(::std::ostream* os) const override {2315if (result_description_.empty()) {2316*os << "is mapped by the given callable to a value that ";2317} else {2318*os << "whose " << result_description_ << " ";2319}2320matcher_.DescribeTo(os);2321}23222323void DescribeNegationTo(::std::ostream* os) const override {2324if (result_description_.empty()) {2325*os << "is mapped by the given callable to a value that ";2326} else {2327*os << "whose " << result_description_ << " ";2328}2329matcher_.DescribeNegationTo(os);2330}23312332bool MatchAndExplain(T obj, MatchResultListener* listener) const override {2333if (result_description_.empty()) {2334*listener << "which is mapped by the given callable to ";2335} else {2336*listener << "whose " << result_description_ << " is ";2337}2338// Cannot pass the return value directly to MatchPrintAndExplain, which2339// takes a non-const reference as argument.2340// Also, specifying template argument explicitly is needed because T could2341// be a non-const reference (e.g. Matcher<Uncopyable&>).2342InnerType result =2343CallableTraits<Callable>::template Invoke<T>(callable_, obj);2344return MatchPrintAndExplain(result, matcher_, listener);2345}23462347private:2348const std::string result_description_;2349// Functors often define operator() as non-const method even though2350// they are actually stateless. But we need to use them even when2351// 'this' is a const pointer. It's the user's responsibility not to2352// use stateful callables with ResultOf(), which doesn't guarantee2353// how many times the callable will be invoked.2354mutable CallableStorageType callable_;2355const Matcher<InnerType> matcher_;2356}; // class Impl23572358const std::string result_description_;2359const CallableStorageType callable_;2360const InnerMatcher matcher_;2361};23622363// Implements a matcher that checks the size of an STL-style container.2364template <typename SizeMatcher>2365class SizeIsMatcher {2366public:2367explicit SizeIsMatcher(const SizeMatcher& size_matcher)2368: size_matcher_(size_matcher) {}23692370template <typename Container>2371operator Matcher<Container>() const {2372return Matcher<Container>(new Impl<const Container&>(size_matcher_));2373}23742375template <typename Container>2376class Impl : public MatcherInterface<Container> {2377public:2378using SizeType = decltype(std::declval<Container>().size());2379explicit Impl(const SizeMatcher& size_matcher)2380: size_matcher_(MatcherCast<SizeType>(size_matcher)) {}23812382void DescribeTo(::std::ostream* os) const override {2383*os << "has a size that ";2384size_matcher_.DescribeTo(os);2385}2386void DescribeNegationTo(::std::ostream* os) const override {2387*os << "has a size that ";2388size_matcher_.DescribeNegationTo(os);2389}23902391bool MatchAndExplain(Container container,2392MatchResultListener* listener) const override {2393SizeType size = container.size();2394StringMatchResultListener size_listener;2395const bool result = size_matcher_.MatchAndExplain(size, &size_listener);2396*listener << "whose size " << size2397<< (result ? " matches" : " doesn't match");2398PrintIfNotEmpty(size_listener.str(), listener->stream());2399return result;2400}24012402private:2403const Matcher<SizeType> size_matcher_;2404};24052406private:2407const SizeMatcher size_matcher_;2408};24092410// Implements a matcher that checks the begin()..end() distance of an STL-style2411// container.2412template <typename DistanceMatcher>2413class BeginEndDistanceIsMatcher {2414public:2415explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)2416: distance_matcher_(distance_matcher) {}24172418template <typename Container>2419operator Matcher<Container>() const {2420return Matcher<Container>(new Impl<const Container&>(distance_matcher_));2421}24222423template <typename Container>2424class Impl : public MatcherInterface<Container> {2425public:2426typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(2427Container)>2428ContainerView;2429typedef typename std::iterator_traits<2430typename ContainerView::type::const_iterator>::difference_type2431DistanceType;2432explicit Impl(const DistanceMatcher& distance_matcher)2433: distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}24342435void DescribeTo(::std::ostream* os) const override {2436*os << "distance between begin() and end() ";2437distance_matcher_.DescribeTo(os);2438}2439void DescribeNegationTo(::std::ostream* os) const override {2440*os << "distance between begin() and end() ";2441distance_matcher_.DescribeNegationTo(os);2442}24432444bool MatchAndExplain(Container container,2445MatchResultListener* listener) const override {2446using std::begin;2447using std::end;2448DistanceType distance = std::distance(begin(container), end(container));2449StringMatchResultListener distance_listener;2450const bool result =2451distance_matcher_.MatchAndExplain(distance, &distance_listener);2452*listener << "whose distance between begin() and end() " << distance2453<< (result ? " matches" : " doesn't match");2454PrintIfNotEmpty(distance_listener.str(), listener->stream());2455return result;2456}24572458private:2459const Matcher<DistanceType> distance_matcher_;2460};24612462private:2463const DistanceMatcher distance_matcher_;2464};24652466// Implements an equality matcher for any STL-style container whose elements2467// support ==. This matcher is like Eq(), but its failure explanations provide2468// more detailed information that is useful when the container is used as a set.2469// The failure message reports elements that are in one of the operands but not2470// the other. The failure messages do not report duplicate or out-of-order2471// elements in the containers (which don't properly matter to sets, but can2472// occur if the containers are vectors or lists, for example).2473//2474// Uses the container's const_iterator, value_type, operator ==,2475// begin(), and end().2476template <typename Container>2477class ContainerEqMatcher {2478public:2479typedef internal::StlContainerView<Container> View;2480typedef typename View::type StlContainer;2481typedef typename View::const_reference StlContainerReference;24822483static_assert(!std::is_const<Container>::value,2484"Container type must not be const");2485static_assert(!std::is_reference<Container>::value,2486"Container type must not be a reference");24872488// We make a copy of expected in case the elements in it are modified2489// after this matcher is created.2490explicit ContainerEqMatcher(const Container& expected)2491: expected_(View::Copy(expected)) {}24922493void DescribeTo(::std::ostream* os) const {2494*os << "equals ";2495UniversalPrint(expected_, os);2496}2497void DescribeNegationTo(::std::ostream* os) const {2498*os << "does not equal ";2499UniversalPrint(expected_, os);2500}25012502template <typename LhsContainer>2503bool MatchAndExplain(const LhsContainer& lhs,2504MatchResultListener* listener) const {2505typedef internal::StlContainerView<2506typename std::remove_const<LhsContainer>::type>2507LhsView;2508StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);2509if (lhs_stl_container == expected_) return true;25102511::std::ostream* const os = listener->stream();2512if (os != nullptr) {2513// Something is different. Check for extra values first.2514bool printed_header = false;2515for (auto it = lhs_stl_container.begin(); it != lhs_stl_container.end();2516++it) {2517if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==2518expected_.end()) {2519if (printed_header) {2520*os << ", ";2521} else {2522*os << "which has these unexpected elements: ";2523printed_header = true;2524}2525UniversalPrint(*it, os);2526}2527}25282529// Now check for missing values.2530bool printed_header2 = false;2531for (auto it = expected_.begin(); it != expected_.end(); ++it) {2532if (internal::ArrayAwareFind(lhs_stl_container.begin(),2533lhs_stl_container.end(),2534*it) == lhs_stl_container.end()) {2535if (printed_header2) {2536*os << ", ";2537} else {2538*os << (printed_header ? ",\nand" : "which")2539<< " doesn't have these expected elements: ";2540printed_header2 = true;2541}2542UniversalPrint(*it, os);2543}2544}2545}25462547return false;2548}25492550private:2551const StlContainer expected_;2552};25532554// A comparator functor that uses the < operator to compare two values.2555struct LessComparator {2556template <typename T, typename U>2557bool operator()(const T& lhs, const U& rhs) const {2558return lhs < rhs;2559}2560};25612562// Implements WhenSortedBy(comparator, container_matcher).2563template <typename Comparator, typename ContainerMatcher>2564class WhenSortedByMatcher {2565public:2566WhenSortedByMatcher(const Comparator& comparator,2567const ContainerMatcher& matcher)2568: comparator_(comparator), matcher_(matcher) {}25692570template <typename LhsContainer>2571operator Matcher<LhsContainer>() const {2572return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));2573}25742575template <typename LhsContainer>2576class Impl : public MatcherInterface<LhsContainer> {2577public:2578typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(2579LhsContainer)>2580LhsView;2581typedef typename LhsView::type LhsStlContainer;2582typedef typename LhsView::const_reference LhsStlContainerReference;2583// Transforms std::pair<const Key, Value> into std::pair<Key, Value>2584// so that we can match associative containers.2585typedef2586typename RemoveConstFromKey<typename LhsStlContainer::value_type>::type2587LhsValue;25882589Impl(const Comparator& comparator, const ContainerMatcher& matcher)2590: comparator_(comparator), matcher_(matcher) {}25912592void DescribeTo(::std::ostream* os) const override {2593*os << "(when sorted) ";2594matcher_.DescribeTo(os);2595}25962597void DescribeNegationTo(::std::ostream* os) const override {2598*os << "(when sorted) ";2599matcher_.DescribeNegationTo(os);2600}26012602bool MatchAndExplain(LhsContainer lhs,2603MatchResultListener* listener) const override {2604LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);2605::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),2606lhs_stl_container.end());2607::std::sort(sorted_container.begin(), sorted_container.end(),2608comparator_);26092610if (!listener->IsInterested()) {2611// If the listener is not interested, we do not need to2612// construct the inner explanation.2613return matcher_.Matches(sorted_container);2614}26152616*listener << "which is ";2617UniversalPrint(sorted_container, listener->stream());2618*listener << " when sorted";26192620StringMatchResultListener inner_listener;2621const bool match =2622matcher_.MatchAndExplain(sorted_container, &inner_listener);2623PrintIfNotEmpty(inner_listener.str(), listener->stream());2624return match;2625}26262627private:2628const Comparator comparator_;2629const Matcher<const ::std::vector<LhsValue>&> matcher_;26302631Impl(const Impl&) = delete;2632Impl& operator=(const Impl&) = delete;2633};26342635private:2636const Comparator comparator_;2637const ContainerMatcher matcher_;2638};26392640// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher2641// must be able to be safely cast to Matcher<std::tuple<const T1&, const2642// T2&> >, where T1 and T2 are the types of elements in the LHS2643// container and the RHS container respectively.2644template <typename TupleMatcher, typename RhsContainer>2645class PointwiseMatcher {2646static_assert(2647!IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,2648"use UnorderedPointwise with hash tables");26492650public:2651typedef internal::StlContainerView<RhsContainer> RhsView;2652typedef typename RhsView::type RhsStlContainer;2653typedef typename RhsStlContainer::value_type RhsValue;26542655static_assert(!std::is_const<RhsContainer>::value,2656"RhsContainer type must not be const");2657static_assert(!std::is_reference<RhsContainer>::value,2658"RhsContainer type must not be a reference");26592660// Like ContainerEq, we make a copy of rhs in case the elements in2661// it are modified after this matcher is created.2662PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)2663: tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {}26642665template <typename LhsContainer>2666operator Matcher<LhsContainer>() const {2667static_assert(2668!IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,2669"use UnorderedPointwise with hash tables");26702671return Matcher<LhsContainer>(2672new Impl<const LhsContainer&>(tuple_matcher_, rhs_));2673}26742675template <typename LhsContainer>2676class Impl : public MatcherInterface<LhsContainer> {2677public:2678typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(2679LhsContainer)>2680LhsView;2681typedef typename LhsView::type LhsStlContainer;2682typedef typename LhsView::const_reference LhsStlContainerReference;2683typedef typename LhsStlContainer::value_type LhsValue;2684// We pass the LHS value and the RHS value to the inner matcher by2685// reference, as they may be expensive to copy. We must use tuple2686// instead of pair here, as a pair cannot hold references (C++ 98,2687// 20.2.2 [lib.pairs]).2688typedef ::std::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;26892690Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)2691// mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.2692: mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),2693rhs_(rhs) {}26942695void DescribeTo(::std::ostream* os) const override {2696*os << "contains " << rhs_.size()2697<< " values, where each value and its corresponding value in ";2698UniversalPrinter<RhsStlContainer>::Print(rhs_, os);2699*os << " ";2700mono_tuple_matcher_.DescribeTo(os);2701}2702void DescribeNegationTo(::std::ostream* os) const override {2703*os << "doesn't contain exactly " << rhs_.size()2704<< " values, or contains a value x at some index i"2705<< " where x and the i-th value of ";2706UniversalPrint(rhs_, os);2707*os << " ";2708mono_tuple_matcher_.DescribeNegationTo(os);2709}27102711bool MatchAndExplain(LhsContainer lhs,2712MatchResultListener* listener) const override {2713LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);2714const size_t actual_size = lhs_stl_container.size();2715if (actual_size != rhs_.size()) {2716*listener << "which contains " << actual_size << " values";2717return false;2718}27192720auto left = lhs_stl_container.begin();2721auto right = rhs_.begin();2722for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {2723if (listener->IsInterested()) {2724StringMatchResultListener inner_listener;2725// Create InnerMatcherArg as a temporarily object to avoid it outlives2726// *left and *right. Dereference or the conversion to `const T&` may2727// return temp objects, e.g. for vector<bool>.2728if (!mono_tuple_matcher_.MatchAndExplain(2729InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),2730ImplicitCast_<const RhsValue&>(*right)),2731&inner_listener)) {2732*listener << "where the value pair (";2733UniversalPrint(*left, listener->stream());2734*listener << ", ";2735UniversalPrint(*right, listener->stream());2736*listener << ") at index #" << i << " don't match";2737PrintIfNotEmpty(inner_listener.str(), listener->stream());2738return false;2739}2740} else {2741if (!mono_tuple_matcher_.Matches(2742InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),2743ImplicitCast_<const RhsValue&>(*right))))2744return false;2745}2746}27472748return true;2749}27502751private:2752const Matcher<InnerMatcherArg> mono_tuple_matcher_;2753const RhsStlContainer rhs_;2754};27552756private:2757const TupleMatcher tuple_matcher_;2758const RhsStlContainer rhs_;2759};27602761// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.2762template <typename Container>2763class QuantifierMatcherImpl : public MatcherInterface<Container> {2764public:2765typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;2766typedef StlContainerView<RawContainer> View;2767typedef typename View::type StlContainer;2768typedef typename View::const_reference StlContainerReference;2769typedef typename StlContainer::value_type Element;27702771template <typename InnerMatcher>2772explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)2773: inner_matcher_(2774testing::SafeMatcherCast<const Element&>(inner_matcher)) {}27752776// Checks whether:2777// * All elements in the container match, if all_elements_should_match.2778// * Any element in the container matches, if !all_elements_should_match.2779bool MatchAndExplainImpl(bool all_elements_should_match, Container container,2780MatchResultListener* listener) const {2781StlContainerReference stl_container = View::ConstReference(container);2782size_t i = 0;2783for (auto it = stl_container.begin(); it != stl_container.end();2784++it, ++i) {2785StringMatchResultListener inner_listener;2786const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);27872788if (matches != all_elements_should_match) {2789*listener << "whose element #" << i2790<< (matches ? " matches" : " doesn't match");2791PrintIfNotEmpty(inner_listener.str(), listener->stream());2792return !all_elements_should_match;2793}2794}2795return all_elements_should_match;2796}27972798bool MatchAndExplainImpl(const Matcher<size_t>& count_matcher,2799Container container,2800MatchResultListener* listener) const {2801StlContainerReference stl_container = View::ConstReference(container);2802size_t i = 0;2803std::vector<size_t> match_elements;2804for (auto it = stl_container.begin(); it != stl_container.end();2805++it, ++i) {2806StringMatchResultListener inner_listener;2807const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);2808if (matches) {2809match_elements.push_back(i);2810}2811}2812if (listener->IsInterested()) {2813if (match_elements.empty()) {2814*listener << "has no element that matches";2815} else if (match_elements.size() == 1) {2816*listener << "whose element #" << match_elements[0] << " matches";2817} else {2818*listener << "whose elements (";2819std::string sep = "";2820for (size_t e : match_elements) {2821*listener << sep << e;2822sep = ", ";2823}2824*listener << ") match";2825}2826}2827StringMatchResultListener count_listener;2828if (count_matcher.MatchAndExplain(match_elements.size(), &count_listener)) {2829*listener << " and whose match quantity of " << match_elements.size()2830<< " matches";2831PrintIfNotEmpty(count_listener.str(), listener->stream());2832return true;2833} else {2834if (match_elements.empty()) {2835*listener << " and";2836} else {2837*listener << " but";2838}2839*listener << " whose match quantity of " << match_elements.size()2840<< " does not match";2841PrintIfNotEmpty(count_listener.str(), listener->stream());2842return false;2843}2844}28452846protected:2847const Matcher<const Element&> inner_matcher_;2848};28492850// Implements Contains(element_matcher) for the given argument type Container.2851// Symmetric to EachMatcherImpl.2852template <typename Container>2853class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {2854public:2855template <typename InnerMatcher>2856explicit ContainsMatcherImpl(InnerMatcher inner_matcher)2857: QuantifierMatcherImpl<Container>(inner_matcher) {}28582859// Describes what this matcher does.2860void DescribeTo(::std::ostream* os) const override {2861*os << "contains at least one element that ";2862this->inner_matcher_.DescribeTo(os);2863}28642865void DescribeNegationTo(::std::ostream* os) const override {2866*os << "doesn't contain any element that ";2867this->inner_matcher_.DescribeTo(os);2868}28692870bool MatchAndExplain(Container container,2871MatchResultListener* listener) const override {2872return this->MatchAndExplainImpl(false, container, listener);2873}2874};28752876// Implements DistanceFrom(target, get_distance, distance_matcher) for the given2877// argument types:2878// * V is the type of the value to be matched.2879// * T is the type of the target value.2880// * Distance is the type of the distance between V and T.2881// * GetDistance is the type of the functor for computing the distance between2882// V and T.2883template <typename V, typename T, typename Distance, typename GetDistance>2884class DistanceFromMatcherImpl : public MatcherInterface<V> {2885public:2886// Arguments:2887// * target: the target value.2888// * get_distance: the functor for computing the distance between the value2889// being matched and target.2890// * distance_matcher: the matcher for checking the distance.2891DistanceFromMatcherImpl(T target, GetDistance get_distance,2892Matcher<const Distance&> distance_matcher)2893: target_(std::move(target)),2894get_distance_(std::move(get_distance)),2895distance_matcher_(std::move(distance_matcher)) {}28962897// Describes what this matcher does.2898void DescribeTo(::std::ostream* os) const override {2899distance_matcher_.DescribeTo(os);2900*os << " away from " << PrintToString(target_);2901}29022903void DescribeNegationTo(::std::ostream* os) const override {2904distance_matcher_.DescribeNegationTo(os);2905*os << " away from " << PrintToString(target_);2906}29072908bool MatchAndExplain(V value, MatchResultListener* listener) const override {2909const auto distance = get_distance_(value, target_);2910const bool match = distance_matcher_.Matches(distance);2911if (!match && listener->IsInterested()) {2912*listener << "which is " << PrintToString(distance) << " away from "2913<< PrintToString(target_);2914}2915return match;2916}29172918private:2919const T target_;2920const GetDistance get_distance_;2921const Matcher<const Distance&> distance_matcher_;2922};29232924// Implements Each(element_matcher) for the given argument type Container.2925// Symmetric to ContainsMatcherImpl.2926template <typename Container>2927class EachMatcherImpl : public QuantifierMatcherImpl<Container> {2928public:2929template <typename InnerMatcher>2930explicit EachMatcherImpl(InnerMatcher inner_matcher)2931: QuantifierMatcherImpl<Container>(inner_matcher) {}29322933// Describes what this matcher does.2934void DescribeTo(::std::ostream* os) const override {2935*os << "only contains elements that ";2936this->inner_matcher_.DescribeTo(os);2937}29382939void DescribeNegationTo(::std::ostream* os) const override {2940*os << "contains some element that ";2941this->inner_matcher_.DescribeNegationTo(os);2942}29432944bool MatchAndExplain(Container container,2945MatchResultListener* listener) const override {2946return this->MatchAndExplainImpl(true, container, listener);2947}2948};29492950// Implements Contains(element_matcher).Times(n) for the given argument type2951// Container.2952template <typename Container>2953class ContainsTimesMatcherImpl : public QuantifierMatcherImpl<Container> {2954public:2955template <typename InnerMatcher>2956explicit ContainsTimesMatcherImpl(InnerMatcher inner_matcher,2957Matcher<size_t> count_matcher)2958: QuantifierMatcherImpl<Container>(inner_matcher),2959count_matcher_(std::move(count_matcher)) {}29602961void DescribeTo(::std::ostream* os) const override {2962*os << "quantity of elements that match ";2963this->inner_matcher_.DescribeTo(os);2964*os << " ";2965count_matcher_.DescribeTo(os);2966}29672968void DescribeNegationTo(::std::ostream* os) const override {2969*os << "quantity of elements that match ";2970this->inner_matcher_.DescribeTo(os);2971*os << " ";2972count_matcher_.DescribeNegationTo(os);2973}29742975bool MatchAndExplain(Container container,2976MatchResultListener* listener) const override {2977return this->MatchAndExplainImpl(count_matcher_, container, listener);2978}29792980private:2981const Matcher<size_t> count_matcher_;2982};29832984// Implements polymorphic Contains(element_matcher).Times(n).2985template <typename M>2986class ContainsTimesMatcher {2987public:2988explicit ContainsTimesMatcher(M m, Matcher<size_t> count_matcher)2989: inner_matcher_(m), count_matcher_(std::move(count_matcher)) {}29902991template <typename Container>2992operator Matcher<Container>() const { // NOLINT2993return Matcher<Container>(new ContainsTimesMatcherImpl<const Container&>(2994inner_matcher_, count_matcher_));2995}29962997private:2998const M inner_matcher_;2999const Matcher<size_t> count_matcher_;3000};30013002// Implements polymorphic Contains(element_matcher).3003template <typename M>3004class ContainsMatcher {3005public:3006explicit ContainsMatcher(M m) : inner_matcher_(m) {}30073008template <typename Container>3009operator Matcher<Container>() const { // NOLINT3010return Matcher<Container>(3011new ContainsMatcherImpl<const Container&>(inner_matcher_));3012}30133014ContainsTimesMatcher<M> Times(Matcher<size_t> count_matcher) const {3015return ContainsTimesMatcher<M>(inner_matcher_, std::move(count_matcher));3016}30173018private:3019const M inner_matcher_;3020};30213022// Implements polymorphic Each(element_matcher).3023template <typename M>3024class EachMatcher {3025public:3026explicit EachMatcher(M m) : inner_matcher_(m) {}30273028template <typename Container>3029operator Matcher<Container>() const { // NOLINT3030return Matcher<Container>(3031new EachMatcherImpl<const Container&>(inner_matcher_));3032}30333034private:3035const M inner_matcher_;3036};30373038namespace pair_getters {3039using std::get;3040template <typename T>3041auto First(T& x, Rank0) -> decltype(get<0>(x)) { // NOLINT3042return get<0>(x);3043}3044template <typename T>3045auto First(T& x, Rank1) -> decltype((x.first)) { // NOLINT3046return x.first;3047}30483049template <typename T>3050auto Second(T& x, Rank0) -> decltype(get<1>(x)) { // NOLINT3051return get<1>(x);3052}3053template <typename T>3054auto Second(T& x, Rank1) -> decltype((x.second)) { // NOLINT3055return x.second;3056}3057} // namespace pair_getters30583059// Default functor for computing the distance between two values.3060struct DefaultGetDistance {3061template <typename T, typename U>3062auto operator()(const T& lhs, const U& rhs) const {3063using std::abs;3064// Allow finding abs() in the type's namespace via ADL.3065return abs(lhs - rhs);3066}3067};30683069// Implements polymorphic DistanceFrom(target, get_distance, distance_matcher)3070// matcher. Template arguments:3071// * T is the type of the target value.3072// * GetDistance is the type of the functor for computing the distance between3073// the value being matched and the target.3074// * DistanceMatcher is the type of the matcher for checking the distance.3075template <typename T, typename GetDistance, typename DistanceMatcher>3076class DistanceFromMatcher {3077public:3078// Arguments:3079// * target: the target value.3080// * get_distance: the functor for computing the distance between the value3081// being matched and target.3082// * distance_matcher: the matcher for checking the distance.3083DistanceFromMatcher(T target, GetDistance get_distance,3084DistanceMatcher distance_matcher)3085: target_(std::move(target)),3086get_distance_(std::move(get_distance)),3087distance_matcher_(std::move(distance_matcher)) {}30883089DistanceFromMatcher(const DistanceFromMatcher& other) = default;30903091// Implicitly converts to a monomorphic matcher of the given type.3092template <typename V>3093operator Matcher<V>() const { // NOLINT3094using Distance = decltype(get_distance_(std::declval<V>(), target_));3095return Matcher<V>(new DistanceFromMatcherImpl<V, T, Distance, GetDistance>(3096target_, get_distance_, distance_matcher_));3097}30983099private:3100const T target_;3101const GetDistance get_distance_;3102const DistanceMatcher distance_matcher_;3103};31043105// Implements Key(inner_matcher) for the given argument pair type.3106// Key(inner_matcher) matches an std::pair whose 'first' field matches3107// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an3108// std::map that contains at least one element whose key is >= 5.3109template <typename PairType>3110class KeyMatcherImpl : public MatcherInterface<PairType> {3111public:3112typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;3113typedef typename RawPairType::first_type KeyType;31143115template <typename InnerMatcher>3116explicit KeyMatcherImpl(InnerMatcher inner_matcher)3117: inner_matcher_(3118testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {}31193120// Returns true if and only if 'key_value.first' (the key) matches the inner3121// matcher.3122bool MatchAndExplain(PairType key_value,3123MatchResultListener* listener) const override {3124StringMatchResultListener inner_listener;3125const bool match = inner_matcher_.MatchAndExplain(3126pair_getters::First(key_value, Rank1()), &inner_listener);3127const std::string explanation = inner_listener.str();3128if (!explanation.empty()) {3129*listener << "whose first field is a value " << explanation;3130}3131return match;3132}31333134// Describes what this matcher does.3135void DescribeTo(::std::ostream* os) const override {3136*os << "has a key that ";3137inner_matcher_.DescribeTo(os);3138}31393140// Describes what the negation of this matcher does.3141void DescribeNegationTo(::std::ostream* os) const override {3142*os << "doesn't have a key that ";3143inner_matcher_.DescribeTo(os);3144}31453146private:3147const Matcher<const KeyType&> inner_matcher_;3148};31493150// Implements polymorphic Key(matcher_for_key).3151template <typename M>3152class KeyMatcher {3153public:3154explicit KeyMatcher(M m) : matcher_for_key_(m) {}31553156template <typename PairType>3157operator Matcher<PairType>() const {3158return Matcher<PairType>(3159new KeyMatcherImpl<const PairType&>(matcher_for_key_));3160}31613162private:3163const M matcher_for_key_;3164};31653166// Implements polymorphic Address(matcher_for_address).3167template <typename InnerMatcher>3168class AddressMatcher {3169public:3170explicit AddressMatcher(InnerMatcher m) : matcher_(m) {}31713172template <typename Type>3173operator Matcher<Type>() const { // NOLINT3174return Matcher<Type>(new Impl<const Type&>(matcher_));3175}31763177private:3178// The monomorphic implementation that works for a particular object type.3179template <typename Type>3180class Impl : public MatcherInterface<Type> {3181public:3182using Address = const GTEST_REMOVE_REFERENCE_AND_CONST_(Type) *;3183explicit Impl(const InnerMatcher& matcher)3184: matcher_(MatcherCast<Address>(matcher)) {}31853186void DescribeTo(::std::ostream* os) const override {3187*os << "has address that ";3188matcher_.DescribeTo(os);3189}31903191void DescribeNegationTo(::std::ostream* os) const override {3192*os << "does not have address that ";3193matcher_.DescribeTo(os);3194}31953196bool MatchAndExplain(Type object,3197MatchResultListener* listener) const override {3198*listener << "which has address ";3199Address address = std::addressof(object);3200return MatchPrintAndExplain(address, matcher_, listener);3201}32023203private:3204const Matcher<Address> matcher_;3205};3206const InnerMatcher matcher_;3207};32083209// Implements Pair(first_matcher, second_matcher) for the given argument pair3210// type with its two matchers. See Pair() function below.3211template <typename PairType>3212class PairMatcherImpl : public MatcherInterface<PairType> {3213public:3214typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;3215typedef typename RawPairType::first_type FirstType;3216typedef typename RawPairType::second_type SecondType;32173218template <typename FirstMatcher, typename SecondMatcher>3219PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)3220: first_matcher_(3221testing::SafeMatcherCast<const FirstType&>(first_matcher)),3222second_matcher_(3223testing::SafeMatcherCast<const SecondType&>(second_matcher)) {}32243225// Describes what this matcher does.3226void DescribeTo(::std::ostream* os) const override {3227*os << "has a first field that ";3228first_matcher_.DescribeTo(os);3229*os << ", and has a second field that ";3230second_matcher_.DescribeTo(os);3231}32323233// Describes what the negation of this matcher does.3234void DescribeNegationTo(::std::ostream* os) const override {3235*os << "has a first field that ";3236first_matcher_.DescribeNegationTo(os);3237*os << ", or has a second field that ";3238second_matcher_.DescribeNegationTo(os);3239}32403241// Returns true if and only if 'a_pair.first' matches first_matcher and3242// 'a_pair.second' matches second_matcher.3243bool MatchAndExplain(PairType a_pair,3244MatchResultListener* listener) const override {3245if (!listener->IsInterested()) {3246// If the listener is not interested, we don't need to construct the3247// explanation.3248return first_matcher_.Matches(pair_getters::First(a_pair, Rank1())) &&3249second_matcher_.Matches(pair_getters::Second(a_pair, Rank1()));3250}3251StringMatchResultListener first_inner_listener;3252if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank1()),3253&first_inner_listener)) {3254*listener << "whose first field does not match";3255PrintIfNotEmpty(first_inner_listener.str(), listener->stream());3256return false;3257}3258StringMatchResultListener second_inner_listener;3259if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank1()),3260&second_inner_listener)) {3261*listener << "whose second field does not match";3262PrintIfNotEmpty(second_inner_listener.str(), listener->stream());3263return false;3264}3265ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),3266listener);3267return true;3268}32693270private:3271void ExplainSuccess(const std::string& first_explanation,3272const std::string& second_explanation,3273MatchResultListener* listener) const {3274*listener << "whose both fields match";3275if (!first_explanation.empty()) {3276*listener << ", where the first field is a value " << first_explanation;3277}3278if (!second_explanation.empty()) {3279*listener << ", ";3280if (!first_explanation.empty()) {3281*listener << "and ";3282} else {3283*listener << "where ";3284}3285*listener << "the second field is a value " << second_explanation;3286}3287}32883289const Matcher<const FirstType&> first_matcher_;3290const Matcher<const SecondType&> second_matcher_;3291};32923293// Implements polymorphic Pair(first_matcher, second_matcher).3294template <typename FirstMatcher, typename SecondMatcher>3295class PairMatcher {3296public:3297PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)3298: first_matcher_(first_matcher), second_matcher_(second_matcher) {}32993300template <typename PairType>3301operator Matcher<PairType>() const {3302return Matcher<PairType>(3303new PairMatcherImpl<const PairType&>(first_matcher_, second_matcher_));3304}33053306private:3307const FirstMatcher first_matcher_;3308const SecondMatcher second_matcher_;3309};33103311template <typename T, size_t... I>3312auto UnpackStructImpl(const T& t, std::index_sequence<I...>, int)3313-> decltype(std::tie(get<I>(t)...)) {3314static_assert(std::tuple_size<T>::value == sizeof...(I),3315"Number of arguments doesn't match the number of fields.");3316return std::tie(get<I>(t)...);3317}33183319#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 2016063320template <typename T>3321auto UnpackStructImpl(const T& t, std::make_index_sequence<1>, char) {3322const auto& [a] = t;3323return std::tie(a);3324}3325template <typename T>3326auto UnpackStructImpl(const T& t, std::make_index_sequence<2>, char) {3327const auto& [a, b] = t;3328return std::tie(a, b);3329}3330template <typename T>3331auto UnpackStructImpl(const T& t, std::make_index_sequence<3>, char) {3332const auto& [a, b, c] = t;3333return std::tie(a, b, c);3334}3335template <typename T>3336auto UnpackStructImpl(const T& t, std::make_index_sequence<4>, char) {3337const auto& [a, b, c, d] = t;3338return std::tie(a, b, c, d);3339}3340template <typename T>3341auto UnpackStructImpl(const T& t, std::make_index_sequence<5>, char) {3342const auto& [a, b, c, d, e] = t;3343return std::tie(a, b, c, d, e);3344}3345template <typename T>3346auto UnpackStructImpl(const T& t, std::make_index_sequence<6>, char) {3347const auto& [a, b, c, d, e, f] = t;3348return std::tie(a, b, c, d, e, f);3349}3350template <typename T>3351auto UnpackStructImpl(const T& t, std::make_index_sequence<7>, char) {3352const auto& [a, b, c, d, e, f, g] = t;3353return std::tie(a, b, c, d, e, f, g);3354}3355template <typename T>3356auto UnpackStructImpl(const T& t, std::make_index_sequence<8>, char) {3357const auto& [a, b, c, d, e, f, g, h] = t;3358return std::tie(a, b, c, d, e, f, g, h);3359}3360template <typename T>3361auto UnpackStructImpl(const T& t, std::make_index_sequence<9>, char) {3362const auto& [a, b, c, d, e, f, g, h, i] = t;3363return std::tie(a, b, c, d, e, f, g, h, i);3364}3365template <typename T>3366auto UnpackStructImpl(const T& t, std::make_index_sequence<10>, char) {3367const auto& [a, b, c, d, e, f, g, h, i, j] = t;3368return std::tie(a, b, c, d, e, f, g, h, i, j);3369}3370template <typename T>3371auto UnpackStructImpl(const T& t, std::make_index_sequence<11>, char) {3372const auto& [a, b, c, d, e, f, g, h, i, j, k] = t;3373return std::tie(a, b, c, d, e, f, g, h, i, j, k);3374}3375template <typename T>3376auto UnpackStructImpl(const T& t, std::make_index_sequence<12>, char) {3377const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t;3378return std::tie(a, b, c, d, e, f, g, h, i, j, k, l);3379}3380template <typename T>3381auto UnpackStructImpl(const T& t, std::make_index_sequence<13>, char) {3382const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t;3383return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m);3384}3385template <typename T>3386auto UnpackStructImpl(const T& t, std::make_index_sequence<14>, char) {3387const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t;3388return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n);3389}3390template <typename T>3391auto UnpackStructImpl(const T& t, std::make_index_sequence<15>, char) {3392const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t;3393return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);3394}3395template <typename T>3396auto UnpackStructImpl(const T& t, std::make_index_sequence<16>, char) {3397const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t;3398return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);3399}3400template <typename T>3401auto UnpackStructImpl(const T& t, std::make_index_sequence<17>, char) {3402const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q] = t;3403return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q);3404}3405template <typename T>3406auto UnpackStructImpl(const T& t, std::make_index_sequence<18>, char) {3407const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r] = t;3408return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r);3409}3410template <typename T>3411auto UnpackStructImpl(const T& t, std::make_index_sequence<19>, char) {3412const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s] = t;3413return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s);3414}3415template <typename T>3416auto UnpackStructImpl(const T& u, std::make_index_sequence<20>, char) {3417const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t] = u;3418return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t);3419}3420template <typename T>3421auto UnpackStructImpl(const T& in, std::make_index_sequence<21>, char) {3422const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u] =3423in;3424return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t,3425u);3426}34273428template <typename T>3429auto UnpackStructImpl(const T& in, std::make_index_sequence<22>, char) {3430const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u,3431v] = in;3432return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u,3433v);3434}3435#endif // defined(__cpp_structured_bindings)34363437template <size_t I, typename T>3438auto UnpackStruct(const T& t)3439-> decltype((UnpackStructImpl)(t, std::make_index_sequence<I>{}, 0)) {3440return (UnpackStructImpl)(t, std::make_index_sequence<I>{}, 0);3441}34423443// Helper function to do comma folding in C++11.3444// The array ensures left-to-right order of evaluation.3445// Usage: VariadicExpand({expr...});3446template <typename T, size_t N>3447void VariadicExpand(const T (&)[N]) {}34483449template <typename Struct, typename StructSize>3450class FieldsAreMatcherImpl;34513452template <typename Struct, size_t... I>3453class FieldsAreMatcherImpl<Struct, std::index_sequence<I...>>3454: public MatcherInterface<Struct> {3455using UnpackedType =3456decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>()));3457using MatchersType = std::tuple<3458Matcher<const typename std::tuple_element<I, UnpackedType>::type&>...>;34593460public:3461template <typename Inner>3462explicit FieldsAreMatcherImpl(const Inner& matchers)3463: matchers_(testing::SafeMatcherCast<3464const typename std::tuple_element<I, UnpackedType>::type&>(3465std::get<I>(matchers))...) {}34663467void DescribeTo(::std::ostream* os) const override {3468const char* separator = "";3469VariadicExpand(3470{(*os << separator << "has field #" << I << " that ",3471std::get<I>(matchers_).DescribeTo(os), separator = ", and ")...});3472}34733474void DescribeNegationTo(::std::ostream* os) const override {3475const char* separator = "";3476VariadicExpand({(*os << separator << "has field #" << I << " that ",3477std::get<I>(matchers_).DescribeNegationTo(os),3478separator = ", or ")...});3479}34803481bool MatchAndExplain(Struct t, MatchResultListener* listener) const override {3482return MatchInternal((UnpackStruct<sizeof...(I)>)(t), listener);3483}34843485private:3486bool MatchInternal(UnpackedType tuple, MatchResultListener* listener) const {3487if (!listener->IsInterested()) {3488// If the listener is not interested, we don't need to construct the3489// explanation.3490bool good = true;3491VariadicExpand({good = good && std::get<I>(matchers_).Matches(3492std::get<I>(tuple))...});3493return good;3494}34953496size_t failed_pos = ~size_t{};34973498std::vector<StringMatchResultListener> inner_listener(sizeof...(I));34993500VariadicExpand(3501{failed_pos == ~size_t{} && !std::get<I>(matchers_).MatchAndExplain(3502std::get<I>(tuple), &inner_listener[I])3503? failed_pos = I3504: 0 ...});3505if (failed_pos != ~size_t{}) {3506*listener << "whose field #" << failed_pos << " does not match";3507PrintIfNotEmpty(inner_listener[failed_pos].str(), listener->stream());3508return false;3509}35103511*listener << "whose all elements match";3512const char* separator = ", where";3513for (size_t index = 0; index < sizeof...(I); ++index) {3514const std::string str = inner_listener[index].str();3515if (!str.empty()) {3516*listener << separator << " field #" << index << " is a value " << str;3517separator = ", and";3518}3519}35203521return true;3522}35233524MatchersType matchers_;3525};35263527template <typename... Inner>3528class FieldsAreMatcher {3529public:3530explicit FieldsAreMatcher(Inner... inner) : matchers_(std::move(inner)...) {}35313532template <typename Struct>3533operator Matcher<Struct>() const { // NOLINT3534return Matcher<Struct>(3535new FieldsAreMatcherImpl<const Struct&,3536std::index_sequence_for<Inner...>>(matchers_));3537}35383539private:3540std::tuple<Inner...> matchers_;3541};35423543// Implements ElementsAre() and ElementsAreArray().3544template <typename Container>3545class ElementsAreMatcherImpl : public MatcherInterface<Container> {3546public:3547typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;3548typedef internal::StlContainerView<RawContainer> View;3549typedef typename View::type StlContainer;3550typedef typename View::const_reference StlContainerReference;3551typedef typename StlContainer::value_type Element;35523553// Constructs the matcher from a sequence of element values or3554// element matchers.3555template <typename InputIter>3556ElementsAreMatcherImpl(InputIter first, InputIter last) {3557while (first != last) {3558matchers_.push_back(MatcherCast<const Element&>(*first++));3559}3560}35613562// Describes what this matcher does.3563void DescribeTo(::std::ostream* os) const override {3564if (count() == 0) {3565*os << "is empty";3566} else if (count() == 1) {3567*os << "has 1 element that ";3568matchers_[0].DescribeTo(os);3569} else {3570*os << "has " << Elements(count()) << " where\n";3571for (size_t i = 0; i != count(); ++i) {3572*os << "element #" << i << " ";3573matchers_[i].DescribeTo(os);3574if (i + 1 < count()) {3575*os << ",\n";3576}3577}3578}3579}35803581// Describes what the negation of this matcher does.3582void DescribeNegationTo(::std::ostream* os) const override {3583if (count() == 0) {3584*os << "isn't empty";3585return;3586}35873588*os << "doesn't have " << Elements(count()) << ", or\n";3589for (size_t i = 0; i != count(); ++i) {3590*os << "element #" << i << " ";3591matchers_[i].DescribeNegationTo(os);3592if (i + 1 < count()) {3593*os << ", or\n";3594}3595}3596}35973598bool MatchAndExplain(Container container,3599MatchResultListener* listener) const override {3600// To work with stream-like "containers", we must only walk3601// through the elements in one pass.36023603const bool listener_interested = listener->IsInterested();36043605// explanations[i] is the explanation of the element at index i.3606::std::vector<std::string> explanations(count());3607StlContainerReference stl_container = View::ConstReference(container);3608auto it = stl_container.begin();3609size_t exam_pos = 0;3610bool unmatched_found = false;36113612// Go through the elements and matchers in pairs, until we reach3613// the end of either the elements or the matchers, or until we find a3614// mismatch.3615for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {3616bool match; // Does the current element match the current matcher?3617if (listener_interested) {3618StringMatchResultListener s;3619match = matchers_[exam_pos].MatchAndExplain(*it, &s);3620explanations[exam_pos] = s.str();3621} else {3622match = matchers_[exam_pos].Matches(*it);3623}36243625if (!match) {3626unmatched_found = true;3627// We cannot store the iterator for the unmatched element to be used3628// later, as some users use ElementsAre() with a "container" whose3629// iterator is not copy-constructible or copy-assignable.3630//3631// We cannot store a pointer to the element either, as some container's3632// iterators return a temporary.3633//3634// We cannot store the element itself either, as the element may not be3635// copyable.3636//3637// Therefore, we just remember the index of the unmatched element,3638// and use it later to print the unmatched element.3639break;3640}3641}3642// If unmatched_found is true, exam_pos is the index of the mismatch.36433644// Find how many elements the actual container has. We avoid3645// calling size() s.t. this code works for stream-like "containers"3646// that don't define size().3647size_t actual_count = exam_pos;3648for (; it != stl_container.end(); ++it) {3649++actual_count;3650}36513652if (actual_count != count()) {3653// The element count doesn't match. If the container is empty,3654// there's no need to explain anything as Google Mock already3655// prints the empty container. Otherwise we just need to show3656// how many elements there actually are.3657if (listener_interested && (actual_count != 0)) {3658*listener << "which has " << Elements(actual_count);3659}3660return false;3661}36623663if (unmatched_found) {3664// The element count matches, but the exam_pos-th element doesn't match.3665if (listener_interested) {3666// Find the unmatched element.3667auto unmatched_it = stl_container.begin();3668// We cannot call std::advance() on the iterator, as some users use3669// ElementsAre() with a "container" whose iterator is incompatible with3670// std::advance() (e.g. it may not have the difference_type member3671// type).3672for (size_t i = 0; i != exam_pos; ++i) {3673++unmatched_it;3674}36753676// If the array is long or the elements' print-out is large, it may be3677// hard for the user to find the mismatched element and its3678// corresponding matcher description. Therefore we print the index, the3679// value of the mismatched element, and the corresponding matcher3680// description to ease debugging.3681*listener << "whose element #" << exam_pos << " ("3682<< PrintToString(*unmatched_it) << ") ";3683matchers_[exam_pos].DescribeNegationTo(listener->stream());3684PrintIfNotEmpty(explanations[exam_pos], listener->stream());3685}3686return false;3687}36883689// Every element matches its expectation. We need to explain why3690// (the obvious ones can be skipped).3691if (listener_interested) {3692bool reason_printed = false;3693for (size_t i = 0; i != count(); ++i) {3694const std::string& s = explanations[i];3695if (!s.empty()) {3696if (reason_printed) {3697*listener << ",\nand ";3698}3699*listener << "whose element #" << i << " matches, " << s;3700reason_printed = true;3701}3702}3703}3704return true;3705}37063707private:3708static Message Elements(size_t count) {3709return Message() << count << (count == 1 ? " element" : " elements");3710}37113712size_t count() const { return matchers_.size(); }37133714::std::vector<Matcher<const Element&>> matchers_;3715};37163717// Connectivity matrix of (elements X matchers), in element-major order.3718// Initially, there are no edges.3719// Use NextGraph() to iterate over all possible edge configurations.3720// Use Randomize() to generate a random edge configuration.3721class GTEST_API_ MatchMatrix {3722public:3723MatchMatrix(size_t num_elements, size_t num_matchers)3724: num_elements_(num_elements),3725num_matchers_(num_matchers),3726matched_(num_elements_ * num_matchers_, 0) {}37273728size_t LhsSize() const { return num_elements_; }3729size_t RhsSize() const { return num_matchers_; }3730bool HasEdge(size_t ilhs, size_t irhs) const {3731return matched_[SpaceIndex(ilhs, irhs)] == 1;3732}3733void SetEdge(size_t ilhs, size_t irhs, bool b) {3734matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;3735}37363737// Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,3738// adds 1 to that number; returns false if incrementing the graph left it3739// empty.3740bool NextGraph();37413742void Randomize();37433744std::string DebugString() const;37453746private:3747size_t SpaceIndex(size_t ilhs, size_t irhs) const {3748return ilhs * num_matchers_ + irhs;3749}37503751size_t num_elements_;3752size_t num_matchers_;37533754// Each element is a char interpreted as bool. They are stored as a3755// flattened array in lhs-major order, use 'SpaceIndex()' to translate3756// a (ilhs, irhs) matrix coordinate into an offset.3757::std::vector<char> matched_;3758};37593760typedef ::std::pair<size_t, size_t> ElementMatcherPair;3761typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;37623763// Returns a maximum bipartite matching for the specified graph 'g'.3764// The matching is represented as a vector of {element, matcher} pairs.3765GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g);37663767struct UnorderedMatcherRequire {3768enum Flags {3769Superset = 1 << 0,3770Subset = 1 << 1,3771ExactMatch = Superset | Subset,3772};3773};37743775// Untyped base class for implementing UnorderedElementsAre. By3776// putting logic that's not specific to the element type here, we3777// reduce binary bloat and increase compilation speed.3778class GTEST_API_ UnorderedElementsAreMatcherImplBase {3779protected:3780explicit UnorderedElementsAreMatcherImplBase(3781UnorderedMatcherRequire::Flags matcher_flags)3782: match_flags_(matcher_flags) {}37833784// A vector of matcher describers, one for each element matcher.3785// Does not own the describers (and thus can be used only when the3786// element matchers are alive).3787typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;37883789// Describes this UnorderedElementsAre matcher.3790void DescribeToImpl(::std::ostream* os) const;37913792// Describes the negation of this UnorderedElementsAre matcher.3793void DescribeNegationToImpl(::std::ostream* os) const;37943795bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,3796const MatchMatrix& matrix,3797MatchResultListener* listener) const;37983799bool FindPairing(const MatchMatrix& matrix,3800MatchResultListener* listener) const;38013802MatcherDescriberVec& matcher_describers() { return matcher_describers_; }38033804static Message Elements(size_t n) {3805return Message() << n << " element" << (n == 1 ? "" : "s");3806}38073808UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }38093810private:3811UnorderedMatcherRequire::Flags match_flags_;3812MatcherDescriberVec matcher_describers_;3813};38143815// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and3816// IsSupersetOf.3817template <typename Container>3818class UnorderedElementsAreMatcherImpl3819: public MatcherInterface<Container>,3820public UnorderedElementsAreMatcherImplBase {3821public:3822typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;3823typedef internal::StlContainerView<RawContainer> View;3824typedef typename View::type StlContainer;3825typedef typename View::const_reference StlContainerReference;3826typedef typename StlContainer::value_type Element;38273828template <typename InputIter>3829UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,3830InputIter first, InputIter last)3831: UnorderedElementsAreMatcherImplBase(matcher_flags) {3832for (; first != last; ++first) {3833matchers_.push_back(MatcherCast<const Element&>(*first));3834}3835for (const auto& m : matchers_) {3836matcher_describers().push_back(m.GetDescriber());3837}3838}38393840// Describes what this matcher does.3841void DescribeTo(::std::ostream* os) const override {3842return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);3843}38443845// Describes what the negation of this matcher does.3846void DescribeNegationTo(::std::ostream* os) const override {3847return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);3848}38493850bool MatchAndExplain(Container container,3851MatchResultListener* listener) const override {3852StlContainerReference stl_container = View::ConstReference(container);3853::std::vector<std::string> element_printouts;3854MatchMatrix matrix =3855AnalyzeElements(stl_container.begin(), stl_container.end(),3856&element_printouts, listener);38573858return VerifyMatchMatrix(element_printouts, matrix, listener) &&3859FindPairing(matrix, listener);3860}38613862private:3863template <typename ElementIter>3864MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,3865::std::vector<std::string>* element_printouts,3866MatchResultListener* listener) const {3867element_printouts->clear();3868::std::vector<char> did_match;3869size_t num_elements = 0;3870DummyMatchResultListener dummy;3871for (; elem_first != elem_last; ++num_elements, ++elem_first) {3872if (listener->IsInterested()) {3873element_printouts->push_back(PrintToString(*elem_first));3874}3875for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {3876did_match.push_back(3877matchers_[irhs].MatchAndExplain(*elem_first, &dummy));3878}3879}38803881MatchMatrix matrix(num_elements, matchers_.size());3882::std::vector<char>::const_iterator did_match_iter = did_match.begin();3883for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {3884for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {3885matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);3886}3887}3888return matrix;3889}38903891::std::vector<Matcher<const Element&>> matchers_;3892};38933894// Functor for use in TransformTuple.3895// Performs MatcherCast<Target> on an input argument of any type.3896template <typename Target>3897struct CastAndAppendTransform {3898template <typename Arg>3899Matcher<Target> operator()(const Arg& a) const {3900return MatcherCast<Target>(a);3901}3902};39033904// Implements UnorderedElementsAre.3905template <typename MatcherTuple>3906class UnorderedElementsAreMatcher {3907public:3908explicit UnorderedElementsAreMatcher(const MatcherTuple& args)3909: matchers_(args) {}39103911template <typename Container>3912operator Matcher<Container>() const {3913typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;3914typedef typename internal::StlContainerView<RawContainer>::type View;3915typedef typename View::value_type Element;3916typedef ::std::vector<Matcher<const Element&>> MatcherVec;3917MatcherVec matchers;3918matchers.reserve(::std::tuple_size<MatcherTuple>::value);3919TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,3920::std::back_inserter(matchers));3921return Matcher<Container>(3922new UnorderedElementsAreMatcherImpl<const Container&>(3923UnorderedMatcherRequire::ExactMatch, matchers.begin(),3924matchers.end()));3925}39263927private:3928const MatcherTuple matchers_;3929};39303931// Implements ElementsAre.3932template <typename MatcherTuple>3933class ElementsAreMatcher {3934public:3935explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}39363937template <typename Container>3938operator Matcher<Container>() const {3939static_assert(3940!IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||3941::std::tuple_size<MatcherTuple>::value < 2,3942"use UnorderedElementsAre with hash tables");39433944typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;3945typedef typename internal::StlContainerView<RawContainer>::type View;3946typedef typename View::value_type Element;3947typedef ::std::vector<Matcher<const Element&>> MatcherVec;3948MatcherVec matchers;3949matchers.reserve(::std::tuple_size<MatcherTuple>::value);3950TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,3951::std::back_inserter(matchers));3952return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(3953matchers.begin(), matchers.end()));3954}39553956private:3957const MatcherTuple matchers_;3958};39593960// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().3961template <typename T>3962class UnorderedElementsAreArrayMatcher {3963public:3964template <typename Iter>3965UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,3966Iter first, Iter last)3967: match_flags_(match_flags), matchers_(first, last) {}39683969template <typename Container>3970operator Matcher<Container>() const {3971return Matcher<Container>(3972new UnorderedElementsAreMatcherImpl<const Container&>(3973match_flags_, matchers_.begin(), matchers_.end()));3974}39753976private:3977UnorderedMatcherRequire::Flags match_flags_;3978std::vector<std::remove_const_t<T>> matchers_;3979};39803981// Implements ElementsAreArray().3982template <typename T>3983class ElementsAreArrayMatcher {3984public:3985template <typename Iter>3986ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}39873988template <typename Container>3989operator Matcher<Container>() const {3990static_assert(3991!IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,3992"use UnorderedElementsAreArray with hash tables");39933994return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(3995matchers_.begin(), matchers_.end()));3996}39973998private:3999const std::vector<std::remove_const_t<T>> matchers_;4000};40014002// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second4003// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,4004// second) is a polymorphic matcher that matches a value x if and only if4005// tm matches tuple (x, second). Useful for implementing4006// UnorderedPointwise() in terms of UnorderedElementsAreArray().4007//4008// BoundSecondMatcher is copyable and assignable, as we need to put4009// instances of this class in a vector when implementing4010// UnorderedPointwise().4011template <typename Tuple2Matcher, typename Second>4012class BoundSecondMatcher {4013public:4014BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)4015: tuple2_matcher_(tm), second_value_(second) {}40164017BoundSecondMatcher(const BoundSecondMatcher& other) = default;40184019template <typename T>4020operator Matcher<T>() const {4021return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));4022}40234024// We have to define this for UnorderedPointwise() to compile in4025// C++98 mode, as it puts BoundSecondMatcher instances in a vector,4026// which requires the elements to be assignable in C++98. The4027// compiler cannot generate the operator= for us, as Tuple2Matcher4028// and Second may not be assignable.4029//4030// However, this should never be called, so the implementation just4031// need to assert.4032void operator=(const BoundSecondMatcher& /*rhs*/) {4033GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";4034}40354036private:4037template <typename T>4038class Impl : public MatcherInterface<T> {4039public:4040typedef ::std::tuple<T, Second> ArgTuple;40414042Impl(const Tuple2Matcher& tm, const Second& second)4043: mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),4044second_value_(second) {}40454046void DescribeTo(::std::ostream* os) const override {4047*os << "and ";4048UniversalPrint(second_value_, os);4049*os << " ";4050mono_tuple2_matcher_.DescribeTo(os);4051}40524053bool MatchAndExplain(T x, MatchResultListener* listener) const override {4054return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),4055listener);4056}40574058private:4059const Matcher<const ArgTuple&> mono_tuple2_matcher_;4060const Second second_value_;4061};40624063const Tuple2Matcher tuple2_matcher_;4064const Second second_value_;4065};40664067// Given a 2-tuple matcher tm and a value second,4068// MatcherBindSecond(tm, second) returns a matcher that matches a4069// value x if and only if tm matches tuple (x, second). Useful for4070// implementing UnorderedPointwise() in terms of UnorderedElementsAreArray().4071template <typename Tuple2Matcher, typename Second>4072BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(4073const Tuple2Matcher& tm, const Second& second) {4074return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);4075}40764077// Returns the description for a matcher defined using the MATCHER*()4078// macro where the user-supplied description string is "", if4079// 'negation' is false; otherwise returns the description of the4080// negation of the matcher. 'param_values' contains a list of strings4081// that are the print-out of the matcher's parameters.4082GTEST_API_ std::string FormatMatcherDescription(4083bool negation, const char* matcher_name,4084const std::vector<const char*>& param_names, const Strings& param_values);40854086// Overloads to support `OptionalMatcher` being used with a type that either4087// supports implicit conversion to bool or a `has_value()` method.4088template <typename Optional>4089auto IsOptionalEngaged(const Optional& optional, Rank1)4090-> decltype(!!optional) {4091// The use of double-negation here is to preserve historical behavior where4092// the matcher used `operator!` rather than directly using `operator bool`.4093return !static_cast<bool>(!optional);4094}4095template <typename Optional>4096auto IsOptionalEngaged(const Optional& optional, Rank0)4097-> decltype(!optional.has_value()) {4098return optional.has_value();4099}41004101// Implements a matcher that checks the value of a optional<> type variable.4102template <typename ValueMatcher>4103class OptionalMatcher {4104public:4105explicit OptionalMatcher(const ValueMatcher& value_matcher)4106: value_matcher_(value_matcher) {}41074108template <typename Optional>4109operator Matcher<Optional>() const {4110return Matcher<Optional>(new Impl<const Optional&>(value_matcher_));4111}41124113template <typename Optional>4114class Impl : public MatcherInterface<Optional> {4115public:4116typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;4117typedef typename OptionalView::value_type ValueType;4118explicit Impl(const ValueMatcher& value_matcher)4119: value_matcher_(MatcherCast<ValueType>(value_matcher)) {}41204121void DescribeTo(::std::ostream* os) const override {4122*os << "value ";4123value_matcher_.DescribeTo(os);4124}41254126void DescribeNegationTo(::std::ostream* os) const override {4127*os << "value ";4128value_matcher_.DescribeNegationTo(os);4129}41304131bool MatchAndExplain(Optional optional,4132MatchResultListener* listener) const override {4133if (!IsOptionalEngaged(optional, HighestRank())) {4134*listener << "which is not engaged";4135return false;4136}4137const ValueType& value = *optional;4138if (!listener->IsInterested()) {4139// Fast path to avoid unnecessary generation of match explanation.4140return value_matcher_.Matches(value);4141}4142StringMatchResultListener value_listener;4143const bool match = value_matcher_.MatchAndExplain(value, &value_listener);4144*listener << "whose value " << PrintToString(value)4145<< (match ? " matches" : " doesn't match");4146PrintIfNotEmpty(value_listener.str(), listener->stream());4147return match;4148}41494150private:4151const Matcher<ValueType> value_matcher_;4152};41534154private:4155const ValueMatcher value_matcher_;4156};41574158namespace variant_matcher {4159// Overloads to allow VariantMatcher to do proper ADL lookup.4160template <typename T>4161void holds_alternative() {}4162template <typename T>4163void get() {}41644165// Implements a matcher that checks the value of a variant<> type variable.4166template <typename T>4167class VariantMatcher {4168public:4169explicit VariantMatcher(::testing::Matcher<const T&> matcher)4170: matcher_(std::move(matcher)) {}41714172template <typename Variant>4173bool MatchAndExplain(const Variant& value,4174::testing::MatchResultListener* listener) const {4175using std::get;4176if (!listener->IsInterested()) {4177return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));4178}41794180if (!holds_alternative<T>(value)) {4181*listener << "whose value is not of type '" << GetTypeName() << "'";4182return false;4183}41844185const T& elem = get<T>(value);4186StringMatchResultListener elem_listener;4187const bool match = matcher_.MatchAndExplain(elem, &elem_listener);4188*listener << "whose value " << PrintToString(elem)4189<< (match ? " matches" : " doesn't match");4190PrintIfNotEmpty(elem_listener.str(), listener->stream());4191return match;4192}41934194void DescribeTo(std::ostream* os) const {4195*os << "is a variant<> with value of type '" << GetTypeName()4196<< "' and the value ";4197matcher_.DescribeTo(os);4198}41994200void DescribeNegationTo(std::ostream* os) const {4201*os << "is a variant<> with value of type other than '" << GetTypeName()4202<< "' or the value ";4203matcher_.DescribeNegationTo(os);4204}42054206private:4207static std::string GetTypeName() {4208#if GTEST_HAS_RTTI4209GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(4210return internal::GetTypeName<T>());4211#endif4212return "the element type";4213}42144215const ::testing::Matcher<const T&> matcher_;4216};42174218} // namespace variant_matcher42194220namespace any_cast_matcher {42214222// Overloads to allow AnyCastMatcher to do proper ADL lookup.4223template <typename T>4224void any_cast() {}42254226// Implements a matcher that any_casts the value.4227template <typename T>4228class AnyCastMatcher {4229public:4230explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)4231: matcher_(matcher) {}42324233template <typename AnyType>4234bool MatchAndExplain(const AnyType& value,4235::testing::MatchResultListener* listener) const {4236if (!listener->IsInterested()) {4237const T* ptr = any_cast<T>(&value);4238return ptr != nullptr && matcher_.Matches(*ptr);4239}42404241const T* elem = any_cast<T>(&value);4242if (elem == nullptr) {4243*listener << "whose value is not of type '" << GetTypeName() << "'";4244return false;4245}42464247StringMatchResultListener elem_listener;4248const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);4249*listener << "whose value " << PrintToString(*elem)4250<< (match ? " matches" : " doesn't match");4251PrintIfNotEmpty(elem_listener.str(), listener->stream());4252return match;4253}42544255void DescribeTo(std::ostream* os) const {4256*os << "is an 'any' type with value of type '" << GetTypeName()4257<< "' and the value ";4258matcher_.DescribeTo(os);4259}42604261void DescribeNegationTo(std::ostream* os) const {4262*os << "is an 'any' type with value of type other than '" << GetTypeName()4263<< "' or the value ";4264matcher_.DescribeNegationTo(os);4265}42664267private:4268static std::string GetTypeName() {4269#if GTEST_HAS_RTTI4270GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(4271return internal::GetTypeName<T>());4272#endif4273return "the element type";4274}42754276const ::testing::Matcher<const T&> matcher_;4277};42784279} // namespace any_cast_matcher42804281// Implements the Args() matcher.4282template <class ArgsTuple, size_t... k>4283class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {4284public:4285using RawArgsTuple = typename std::decay<ArgsTuple>::type;4286using SelectedArgs =4287std::tuple<typename std::tuple_element<k, RawArgsTuple>::type...>;4288using MonomorphicInnerMatcher = Matcher<const SelectedArgs&>;42894290template <typename InnerMatcher>4291explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)4292: inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}42934294bool MatchAndExplain(ArgsTuple args,4295MatchResultListener* listener) const override {4296// Workaround spurious C4100 on MSVC<=15.7 when k is empty.4297(void)args;4298const SelectedArgs& selected_args =4299std::forward_as_tuple(std::get<k>(args)...);4300if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args);43014302PrintIndices(listener->stream());4303*listener << "are " << PrintToString(selected_args);43044305StringMatchResultListener inner_listener;4306const bool match =4307inner_matcher_.MatchAndExplain(selected_args, &inner_listener);4308PrintIfNotEmpty(inner_listener.str(), listener->stream());4309return match;4310}43114312void DescribeTo(::std::ostream* os) const override {4313*os << "are a tuple ";4314PrintIndices(os);4315inner_matcher_.DescribeTo(os);4316}43174318void DescribeNegationTo(::std::ostream* os) const override {4319*os << "are a tuple ";4320PrintIndices(os);4321inner_matcher_.DescribeNegationTo(os);4322}43234324private:4325// Prints the indices of the selected fields.4326static void PrintIndices(::std::ostream* os) {4327*os << "whose fields (";4328const char* sep = "";4329// Workaround spurious C4189 on MSVC<=15.7 when k is empty.4330(void)sep;4331// The static_cast to void is needed to silence Clang's -Wcomma warning.4332// This pattern looks suspiciously like we may have mismatched parentheses4333// and may have been trying to use the first operation of the comma operator4334// as a member of the array, so Clang warns that we may have made a mistake.4335const char* dummy[] = {4336"", (static_cast<void>(*os << sep << "#" << k), sep = ", ")...};4337(void)dummy;4338*os << ") ";4339}43404341MonomorphicInnerMatcher inner_matcher_;4342};43434344template <class InnerMatcher, size_t... k>4345class ArgsMatcher {4346public:4347explicit ArgsMatcher(InnerMatcher inner_matcher)4348: inner_matcher_(std::move(inner_matcher)) {}43494350template <typename ArgsTuple>4351operator Matcher<ArgsTuple>() const { // NOLINT4352return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k...>(inner_matcher_));4353}43544355private:4356InnerMatcher inner_matcher_;4357};43584359} // namespace internal43604361// ElementsAreArray(iterator_first, iterator_last)4362// ElementsAreArray(pointer, count)4363// ElementsAreArray(array)4364// ElementsAreArray(container)4365// ElementsAreArray({ e1, e2, ..., en })4366//4367// The ElementsAreArray() functions are like ElementsAre(...), except4368// that they are given a homogeneous sequence rather than taking each4369// element as a function argument. The sequence can be specified as an4370// array, a pointer and count, a vector, an initializer list, or an4371// STL iterator range. In each of these cases, the underlying sequence4372// can be either a sequence of values or a sequence of matchers.4373//4374// All forms of ElementsAreArray() make a copy of the input matcher sequence.43754376template <typename Iter>4377inline internal::ElementsAreArrayMatcher<4378typename ::std::iterator_traits<Iter>::value_type>4379ElementsAreArray(Iter first, Iter last) {4380typedef typename ::std::iterator_traits<Iter>::value_type T;4381return internal::ElementsAreArrayMatcher<T>(first, last);4382}43834384template <typename T>4385inline auto ElementsAreArray(const T* pointer, size_t count)4386-> decltype(ElementsAreArray(pointer, pointer + count)) {4387return ElementsAreArray(pointer, pointer + count);4388}43894390template <typename T, size_t N>4391inline auto ElementsAreArray(const T (&array)[N])4392-> decltype(ElementsAreArray(array, N)) {4393return ElementsAreArray(array, N);4394}43954396template <typename Container>4397inline auto ElementsAreArray(const Container& container)4398-> decltype(ElementsAreArray(container.begin(), container.end())) {4399return ElementsAreArray(container.begin(), container.end());4400}44014402template <typename T>4403inline auto ElementsAreArray(::std::initializer_list<T> xs)4404-> decltype(ElementsAreArray(xs.begin(), xs.end())) {4405return ElementsAreArray(xs.begin(), xs.end());4406}44074408// UnorderedElementsAreArray(iterator_first, iterator_last)4409// UnorderedElementsAreArray(pointer, count)4410// UnorderedElementsAreArray(array)4411// UnorderedElementsAreArray(container)4412// UnorderedElementsAreArray({ e1, e2, ..., en })4413//4414// UnorderedElementsAreArray() verifies that a bijective mapping onto a4415// collection of matchers exists.4416//4417// The matchers can be specified as an array, a pointer and count, a container,4418// an initializer list, or an STL iterator range. In each of these cases, the4419// underlying matchers can be either values or matchers.44204421template <typename Iter>4422inline internal::UnorderedElementsAreArrayMatcher<4423typename ::std::iterator_traits<Iter>::value_type>4424UnorderedElementsAreArray(Iter first, Iter last) {4425typedef typename ::std::iterator_traits<Iter>::value_type T;4426return internal::UnorderedElementsAreArrayMatcher<T>(4427internal::UnorderedMatcherRequire::ExactMatch, first, last);4428}44294430template <typename T>4431inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(4432const T* pointer, size_t count) {4433return UnorderedElementsAreArray(pointer, pointer + count);4434}44354436template <typename T, size_t N>4437inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(4438const T (&array)[N]) {4439return UnorderedElementsAreArray(array, N);4440}44414442template <typename Container>4443inline internal::UnorderedElementsAreArrayMatcher<4444typename Container::value_type>4445UnorderedElementsAreArray(const Container& container) {4446return UnorderedElementsAreArray(container.begin(), container.end());4447}44484449template <typename T>4450inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(4451::std::initializer_list<T> xs) {4452return UnorderedElementsAreArray(xs.begin(), xs.end());4453}44544455// _ is a matcher that matches anything of any type.4456//4457// This definition is fine as:4458//4459// 1. The C++ standard permits using the name _ in a namespace that4460// is not the global namespace or ::std.4461// 2. The AnythingMatcher class has no data member or constructor,4462// so it's OK to create global variables of this type.4463// 3. c-style has approved of using _ in this case.4464const internal::AnythingMatcher _ = {};4465// Creates a matcher that matches any value of the given type T.4466template <typename T>4467inline Matcher<T> A() {4468return _;4469}44704471// Creates a matcher that matches any value of the given type T.4472template <typename T>4473inline Matcher<T> An() {4474return _;4475}44764477template <typename T, typename M>4478Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(4479const M& value, std::false_type /* convertible_to_matcher */,4480std::false_type /* convertible_to_T */) {4481return Eq(value);4482}44834484// Creates a polymorphic matcher that matches any NULL pointer.4485inline PolymorphicMatcher<internal::IsNullMatcher> IsNull() {4486return MakePolymorphicMatcher(internal::IsNullMatcher());4487}44884489// Creates a polymorphic matcher that matches any non-NULL pointer.4490// This is convenient as Not(NULL) doesn't compile (the compiler4491// thinks that that expression is comparing a pointer with an integer).4492inline PolymorphicMatcher<internal::NotNullMatcher> NotNull() {4493return MakePolymorphicMatcher(internal::NotNullMatcher());4494}44954496// Creates a polymorphic matcher that matches any argument that4497// references variable x.4498template <typename T>4499inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT4500return internal::RefMatcher<T&>(x);4501}45024503// Creates a polymorphic matcher that matches any NaN floating point.4504inline PolymorphicMatcher<internal::IsNanMatcher> IsNan() {4505return MakePolymorphicMatcher(internal::IsNanMatcher());4506}45074508// Creates a matcher that matches any double argument approximately4509// equal to rhs, where two NANs are considered unequal.4510inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {4511return internal::FloatingEqMatcher<double>(rhs, false);4512}45134514// Creates a matcher that matches any double argument approximately4515// equal to rhs, including NaN values when rhs is NaN.4516inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {4517return internal::FloatingEqMatcher<double>(rhs, true);4518}45194520// Creates a matcher that matches any double argument approximately equal to4521// rhs, up to the specified max absolute error bound, where two NANs are4522// considered unequal. The max absolute error bound must be non-negative.4523inline internal::FloatingEqMatcher<double> DoubleNear(double rhs,4524double max_abs_error) {4525return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);4526}45274528// The DistanceFrom(target, get_distance, m) and DistanceFrom(target, m)4529// matchers work on arbitrary types that have the "distance" concept. What they4530// do:4531//4532// 1. compute the distance between the value and the target using4533// get_distance(value, target) if get_distance is provided; otherwise compute4534// the distance as abs(value - target).4535// 2. match the distance against the user-provided matcher m; if the match4536// succeeds, the DistanceFrom() match succeeds.4537//4538// Examples:4539//4540// // 0.5's distance from 0.6 should be <= 0.2.4541// EXPECT_THAT(0.5, DistanceFrom(0.6, Le(0.2)));4542//4543// Vector2D v1(3.0, 4.0), v2(3.2, 6.0);4544// // v1's distance from v2, as computed by EuclideanDistance(v1, v2),4545// // should be >= 1.0.4546// EXPECT_THAT(v1, DistanceFrom(v2, EuclideanDistance, Ge(1.0)));45474548template <typename T, typename GetDistance, typename DistanceMatcher>4549inline internal::DistanceFromMatcher<T, GetDistance, DistanceMatcher>4550DistanceFrom(T target, GetDistance get_distance,4551DistanceMatcher distance_matcher) {4552return internal::DistanceFromMatcher<T, GetDistance, DistanceMatcher>(4553std::move(target), std::move(get_distance), std::move(distance_matcher));4554}45554556template <typename T, typename DistanceMatcher>4557inline internal::DistanceFromMatcher<T, internal::DefaultGetDistance,4558DistanceMatcher>4559DistanceFrom(T target, DistanceMatcher distance_matcher) {4560return DistanceFrom(std::move(target), internal::DefaultGetDistance(),4561std::move(distance_matcher));4562}45634564// Creates a matcher that matches any double argument approximately equal to4565// rhs, up to the specified max absolute error bound, including NaN values when4566// rhs is NaN. The max absolute error bound must be non-negative.4567inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(4568double rhs, double max_abs_error) {4569return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);4570}45714572// Creates a matcher that matches any float argument approximately4573// equal to rhs, where two NANs are considered unequal.4574inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {4575return internal::FloatingEqMatcher<float>(rhs, false);4576}45774578// Creates a matcher that matches any float argument approximately4579// equal to rhs, including NaN values when rhs is NaN.4580inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {4581return internal::FloatingEqMatcher<float>(rhs, true);4582}45834584// Creates a matcher that matches any float argument approximately equal to4585// rhs, up to the specified max absolute error bound, where two NANs are4586// considered unequal. The max absolute error bound must be non-negative.4587inline internal::FloatingEqMatcher<float> FloatNear(float rhs,4588float max_abs_error) {4589return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);4590}45914592// Creates a matcher that matches any float argument approximately equal to4593// rhs, up to the specified max absolute error bound, including NaN values when4594// rhs is NaN. The max absolute error bound must be non-negative.4595inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(4596float rhs, float max_abs_error) {4597return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);4598}45994600// Creates a matcher that matches a pointer (raw or smart) that points4601// to a value that matches inner_matcher.4602template <typename InnerMatcher>4603inline internal::PointeeMatcher<InnerMatcher> Pointee(4604const InnerMatcher& inner_matcher) {4605return internal::PointeeMatcher<InnerMatcher>(inner_matcher);4606}46074608#if GTEST_HAS_RTTI4609// Creates a matcher that matches a pointer or reference that matches4610// inner_matcher when dynamic_cast<To> is applied.4611// The result of dynamic_cast<To> is forwarded to the inner matcher.4612// If To is a pointer and the cast fails, the inner matcher will receive NULL.4613// If To is a reference and the cast fails, this matcher returns false4614// immediately.4615template <typename To>4616inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To>>4617WhenDynamicCastTo(const Matcher<To>& inner_matcher) {4618return MakePolymorphicMatcher(4619internal::WhenDynamicCastToMatcher<To>(inner_matcher));4620}4621#endif // GTEST_HAS_RTTI46224623// Creates a matcher that matches an object whose given field matches4624// 'matcher'. For example,4625// Field(&Foo::number, Ge(5))4626// matches a Foo object x if and only if x.number >= 5.4627template <typename Class, typename FieldType, typename FieldMatcher>4628inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType>> Field(4629FieldType Class::* field, const FieldMatcher& matcher) {4630return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(4631field, MatcherCast<const FieldType&>(matcher)));4632// The call to MatcherCast() is required for supporting inner4633// matchers of compatible types. For example, it allows4634// Field(&Foo::bar, m)4635// to compile where bar is an int32 and m is a matcher for int64.4636}46374638// Same as Field() but also takes the name of the field to provide better error4639// messages.4640template <typename Class, typename FieldType, typename FieldMatcher>4641inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType>> Field(4642const std::string& field_name, FieldType Class::* field,4643const FieldMatcher& matcher) {4644return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(4645field_name, field, MatcherCast<const FieldType&>(matcher)));4646}46474648// Creates a matcher that matches an object whose given property4649// matches 'matcher'. For example,4650// Property(&Foo::str, StartsWith("hi"))4651// matches a Foo object x if and only if x.str() starts with "hi".4652//4653// Warning: Don't use `Property()` against member functions that you do not4654// own, because taking addresses of functions is fragile and generally not part4655// of the contract of the function.4656template <typename Class, typename PropertyType, typename PropertyMatcher>4657inline PolymorphicMatcher<internal::PropertyMatcher<4658Class, PropertyType, PropertyType (Class::*)() const>>4659Property(PropertyType (Class::*property)() const,4660const PropertyMatcher& matcher) {4661return MakePolymorphicMatcher(4662internal::PropertyMatcher<Class, PropertyType,4663PropertyType (Class::*)() const>(4664property, MatcherCast<const PropertyType&>(matcher)));4665// The call to MatcherCast() is required for supporting inner4666// matchers of compatible types. For example, it allows4667// Property(&Foo::bar, m)4668// to compile where bar() returns an int32 and m is a matcher for int64.4669}46704671// Same as Property() above, but also takes the name of the property to provide4672// better error messages.4673template <typename Class, typename PropertyType, typename PropertyMatcher>4674inline PolymorphicMatcher<internal::PropertyMatcher<4675Class, PropertyType, PropertyType (Class::*)() const>>4676Property(const std::string& property_name,4677PropertyType (Class::*property)() const,4678const PropertyMatcher& matcher) {4679return MakePolymorphicMatcher(4680internal::PropertyMatcher<Class, PropertyType,4681PropertyType (Class::*)() const>(4682property_name, property, MatcherCast<const PropertyType&>(matcher)));4683}46844685// The same as above but for reference-qualified member functions.4686template <typename Class, typename PropertyType, typename PropertyMatcher>4687inline PolymorphicMatcher<internal::PropertyMatcher<4688Class, PropertyType, PropertyType (Class::*)() const&>>4689Property(PropertyType (Class::*property)() const&,4690const PropertyMatcher& matcher) {4691return MakePolymorphicMatcher(4692internal::PropertyMatcher<Class, PropertyType,4693PropertyType (Class::*)() const&>(4694property, MatcherCast<const PropertyType&>(matcher)));4695}46964697// Three-argument form for reference-qualified member functions.4698template <typename Class, typename PropertyType, typename PropertyMatcher>4699inline PolymorphicMatcher<internal::PropertyMatcher<4700Class, PropertyType, PropertyType (Class::*)() const&>>4701Property(const std::string& property_name,4702PropertyType (Class::*property)() const&,4703const PropertyMatcher& matcher) {4704return MakePolymorphicMatcher(4705internal::PropertyMatcher<Class, PropertyType,4706PropertyType (Class::*)() const&>(4707property_name, property, MatcherCast<const PropertyType&>(matcher)));4708}47094710// Creates a matcher that matches an object if and only if the result of4711// applying a callable to x matches 'matcher'. For example,4712// ResultOf(f, StartsWith("hi"))4713// matches a Foo object x if and only if f(x) starts with "hi".4714// `callable` parameter can be a function, function pointer, or a functor. It is4715// required to keep no state affecting the results of the calls on it and make4716// no assumptions about how many calls will be made. Any state it keeps must be4717// protected from the concurrent access.4718template <typename Callable, typename InnerMatcher>4719internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(4720Callable callable, InnerMatcher matcher) {4721return internal::ResultOfMatcher<Callable, InnerMatcher>(std::move(callable),4722std::move(matcher));4723}47244725// Same as ResultOf() above, but also takes a description of the `callable`4726// result to provide better error messages.4727template <typename Callable, typename InnerMatcher>4728internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(4729const std::string& result_description, Callable callable,4730InnerMatcher matcher) {4731return internal::ResultOfMatcher<Callable, InnerMatcher>(4732result_description, std::move(callable), std::move(matcher));4733}47344735// String matchers.47364737// Matches a string equal to str.4738template <typename T = std::string>4739PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrEq(4740const internal::StringLike<T>& str) {4741return MakePolymorphicMatcher(4742internal::StrEqualityMatcher<std::string>(std::string(str), true, true));4743}47444745// Matches a string not equal to str.4746template <typename T = std::string>4747PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrNe(4748const internal::StringLike<T>& str) {4749return MakePolymorphicMatcher(4750internal::StrEqualityMatcher<std::string>(std::string(str), false, true));4751}47524753// Matches a string equal to str, ignoring case.4754template <typename T = std::string>4755PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseEq(4756const internal::StringLike<T>& str) {4757return MakePolymorphicMatcher(4758internal::StrEqualityMatcher<std::string>(std::string(str), true, false));4759}47604761// Matches a string not equal to str, ignoring case.4762template <typename T = std::string>4763PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseNe(4764const internal::StringLike<T>& str) {4765return MakePolymorphicMatcher(internal::StrEqualityMatcher<std::string>(4766std::string(str), false, false));4767}47684769// Creates a matcher that matches any string, std::string, or C string4770// that contains the given substring.4771template <typename T = std::string>4772PolymorphicMatcher<internal::HasSubstrMatcher<std::string>> HasSubstr(4773const internal::StringLike<T>& substring) {4774return MakePolymorphicMatcher(4775internal::HasSubstrMatcher<std::string>(std::string(substring)));4776}47774778// Matches a string that starts with 'prefix' (case-sensitive).4779template <typename T = std::string>4780PolymorphicMatcher<internal::StartsWithMatcher<std::string>> StartsWith(4781const internal::StringLike<T>& prefix) {4782return MakePolymorphicMatcher(4783internal::StartsWithMatcher<std::string>(std::string(prefix)));4784}47854786// Matches a string that ends with 'suffix' (case-sensitive).4787template <typename T = std::string>4788PolymorphicMatcher<internal::EndsWithMatcher<std::string>> EndsWith(4789const internal::StringLike<T>& suffix) {4790return MakePolymorphicMatcher(4791internal::EndsWithMatcher<std::string>(std::string(suffix)));4792}47934794#if GTEST_HAS_STD_WSTRING4795// Wide string matchers.47964797// Matches a string equal to str.4798inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrEq(4799const std::wstring& str) {4800return MakePolymorphicMatcher(4801internal::StrEqualityMatcher<std::wstring>(str, true, true));4802}48034804// Matches a string not equal to str.4805inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrNe(4806const std::wstring& str) {4807return MakePolymorphicMatcher(4808internal::StrEqualityMatcher<std::wstring>(str, false, true));4809}48104811// Matches a string equal to str, ignoring case.4812inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrCaseEq(4813const std::wstring& str) {4814return MakePolymorphicMatcher(4815internal::StrEqualityMatcher<std::wstring>(str, true, false));4816}48174818// Matches a string not equal to str, ignoring case.4819inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrCaseNe(4820const std::wstring& str) {4821return MakePolymorphicMatcher(4822internal::StrEqualityMatcher<std::wstring>(str, false, false));4823}48244825// Creates a matcher that matches any ::wstring, std::wstring, or C wide string4826// that contains the given substring.4827inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring>> HasSubstr(4828const std::wstring& substring) {4829return MakePolymorphicMatcher(4830internal::HasSubstrMatcher<std::wstring>(substring));4831}48324833// Matches a string that starts with 'prefix' (case-sensitive).4834inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring>> StartsWith(4835const std::wstring& prefix) {4836return MakePolymorphicMatcher(4837internal::StartsWithMatcher<std::wstring>(prefix));4838}48394840// Matches a string that ends with 'suffix' (case-sensitive).4841inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring>> EndsWith(4842const std::wstring& suffix) {4843return MakePolymorphicMatcher(4844internal::EndsWithMatcher<std::wstring>(suffix));4845}48464847#endif // GTEST_HAS_STD_WSTRING48484849// Creates a polymorphic matcher that matches a 2-tuple where the4850// first field == the second field.4851inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }48524853// Creates a polymorphic matcher that matches a 2-tuple where the4854// first field >= the second field.4855inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }48564857// Creates a polymorphic matcher that matches a 2-tuple where the4858// first field > the second field.4859inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }48604861// Creates a polymorphic matcher that matches a 2-tuple where the4862// first field <= the second field.4863inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }48644865// Creates a polymorphic matcher that matches a 2-tuple where the4866// first field < the second field.4867inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }48684869// Creates a polymorphic matcher that matches a 2-tuple where the4870// first field != the second field.4871inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }48724873// Creates a polymorphic matcher that matches a 2-tuple where4874// FloatEq(first field) matches the second field.4875inline internal::FloatingEq2Matcher<float> FloatEq() {4876return internal::FloatingEq2Matcher<float>();4877}48784879// Creates a polymorphic matcher that matches a 2-tuple where4880// DoubleEq(first field) matches the second field.4881inline internal::FloatingEq2Matcher<double> DoubleEq() {4882return internal::FloatingEq2Matcher<double>();4883}48844885// Creates a polymorphic matcher that matches a 2-tuple where4886// FloatEq(first field) matches the second field with NaN equality.4887inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {4888return internal::FloatingEq2Matcher<float>(true);4889}48904891// Creates a polymorphic matcher that matches a 2-tuple where4892// DoubleEq(first field) matches the second field with NaN equality.4893inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {4894return internal::FloatingEq2Matcher<double>(true);4895}48964897// Creates a polymorphic matcher that matches a 2-tuple where4898// FloatNear(first field, max_abs_error) matches the second field.4899inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {4900return internal::FloatingEq2Matcher<float>(max_abs_error);4901}49024903// Creates a polymorphic matcher that matches a 2-tuple where4904// DoubleNear(first field, max_abs_error) matches the second field.4905inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {4906return internal::FloatingEq2Matcher<double>(max_abs_error);4907}49084909// Creates a polymorphic matcher that matches a 2-tuple where4910// FloatNear(first field, max_abs_error) matches the second field with NaN4911// equality.4912inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(4913float max_abs_error) {4914return internal::FloatingEq2Matcher<float>(max_abs_error, true);4915}49164917// Creates a polymorphic matcher that matches a 2-tuple where4918// DoubleNear(first field, max_abs_error) matches the second field with NaN4919// equality.4920inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(4921double max_abs_error) {4922return internal::FloatingEq2Matcher<double>(max_abs_error, true);4923}49244925// Creates a matcher that matches any value of type T that m doesn't4926// match.4927template <typename InnerMatcher>4928inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {4929return internal::NotMatcher<InnerMatcher>(m);4930}49314932// Returns a matcher that matches anything that satisfies the given4933// predicate. The predicate can be any unary function or functor4934// whose return type can be implicitly converted to bool.4935template <typename Predicate>4936inline PolymorphicMatcher<internal::TrulyMatcher<Predicate>> Truly(4937Predicate pred) {4938return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));4939}49404941// Returns a matcher that matches the container size. The container must4942// support both size() and size_type which all STL-like containers provide.4943// Note that the parameter 'size' can be a value of type size_type as well as4944// matcher. For instance:4945// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.4946// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.4947template <typename SizeMatcher>4948inline internal::SizeIsMatcher<SizeMatcher> SizeIs(4949const SizeMatcher& size_matcher) {4950return internal::SizeIsMatcher<SizeMatcher>(size_matcher);4951}49524953// Returns a matcher that matches the distance between the container's begin()4954// iterator and its end() iterator, i.e. the size of the container. This matcher4955// can be used instead of SizeIs with containers such as std::forward_list which4956// do not implement size(). The container must provide const_iterator (with4957// valid iterator_traits), begin() and end().4958template <typename DistanceMatcher>4959inline internal::BeginEndDistanceIsMatcher<DistanceMatcher> BeginEndDistanceIs(4960const DistanceMatcher& distance_matcher) {4961return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);4962}49634964// Returns a matcher that matches an equal container.4965// This matcher behaves like Eq(), but in the event of mismatch lists the4966// values that are included in one container but not the other. (Duplicate4967// values and order differences are not explained.)4968template <typename Container>4969inline PolymorphicMatcher<4970internal::ContainerEqMatcher<typename std::remove_const<Container>::type>>4971ContainerEq(const Container& rhs) {4972return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));4973}49744975// Returns a matcher that matches a container that, when sorted using4976// the given comparator, matches container_matcher.4977template <typename Comparator, typename ContainerMatcher>4978inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher> WhenSortedBy(4979const Comparator& comparator, const ContainerMatcher& container_matcher) {4980return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(4981comparator, container_matcher);4982}49834984// Returns a matcher that matches a container that, when sorted using4985// the < operator, matches container_matcher.4986template <typename ContainerMatcher>4987inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>4988WhenSorted(const ContainerMatcher& container_matcher) {4989return internal::WhenSortedByMatcher<internal::LessComparator,4990ContainerMatcher>(4991internal::LessComparator(), container_matcher);4992}49934994// Matches an STL-style container or a native array that contains the4995// same number of elements as in rhs, where its i-th element and rhs's4996// i-th element (as a pair) satisfy the given pair matcher, for all i.4997// TupleMatcher must be able to be safely cast to Matcher<std::tuple<const4998// T1&, const T2&> >, where T1 and T2 are the types of elements in the4999// LHS container and the RHS container respectively.5000template <typename TupleMatcher, typename Container>5001inline internal::PointwiseMatcher<TupleMatcher,5002typename std::remove_const<Container>::type>5003Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {5004return internal::PointwiseMatcher<TupleMatcher, Container>(tuple_matcher,5005rhs);5006}50075008// Supports the Pointwise(m, {a, b, c}) syntax.5009template <typename TupleMatcher, typename T>5010inline internal::PointwiseMatcher<TupleMatcher,5011std::vector<std::remove_const_t<T>>>5012Pointwise(const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {5013return Pointwise(tuple_matcher, std::vector<std::remove_const_t<T>>(rhs));5014}50155016// UnorderedPointwise(pair_matcher, rhs) matches an STL-style5017// container or a native array that contains the same number of5018// elements as in rhs, where in some permutation of the container, its5019// i-th element and rhs's i-th element (as a pair) satisfy the given5020// pair matcher, for all i. Tuple2Matcher must be able to be safely5021// cast to Matcher<std::tuple<const T1&, const T2&> >, where T1 and T2 are5022// the types of elements in the LHS container and the RHS container5023// respectively.5024//5025// This is like Pointwise(pair_matcher, rhs), except that the element5026// order doesn't matter.5027template <typename Tuple2Matcher, typename RhsContainer>5028inline internal::UnorderedElementsAreArrayMatcher<5029typename internal::BoundSecondMatcher<5030Tuple2Matcher,5031typename internal::StlContainerView<5032typename std::remove_const<RhsContainer>::type>::type::value_type>>5033UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,5034const RhsContainer& rhs_container) {5035// RhsView allows the same code to handle RhsContainer being a5036// STL-style container and it being a native C-style array.5037typedef typename internal::StlContainerView<RhsContainer> RhsView;5038typedef typename RhsView::type RhsStlContainer;5039typedef typename RhsStlContainer::value_type Second;5040const RhsStlContainer& rhs_stl_container =5041RhsView::ConstReference(rhs_container);50425043// Create a matcher for each element in rhs_container.5044::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second>> matchers;5045for (auto it = rhs_stl_container.begin(); it != rhs_stl_container.end();5046++it) {5047matchers.push_back(internal::MatcherBindSecond(tuple2_matcher, *it));5048}50495050// Delegate the work to UnorderedElementsAreArray().5051return UnorderedElementsAreArray(matchers);5052}50535054// Supports the UnorderedPointwise(m, {a, b, c}) syntax.5055template <typename Tuple2Matcher, typename T>5056inline internal::UnorderedElementsAreArrayMatcher<5057typename internal::BoundSecondMatcher<Tuple2Matcher, T>>5058UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,5059std::initializer_list<T> rhs) {5060return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));5061}50625063// Matches an STL-style container or a native array that contains at5064// least one element matching the given value or matcher.5065//5066// Examples:5067// ::std::set<int> page_ids;5068// page_ids.insert(3);5069// page_ids.insert(1);5070// EXPECT_THAT(page_ids, Contains(1));5071// EXPECT_THAT(page_ids, Contains(Gt(2)));5072// EXPECT_THAT(page_ids, Not(Contains(4))); // See below for Times(0)5073//5074// ::std::map<int, size_t> page_lengths;5075// page_lengths[1] = 100;5076// EXPECT_THAT(page_lengths,5077// Contains(::std::pair<const int, size_t>(1, 100)));5078//5079// const char* user_ids[] = { "joe", "mike", "tom" };5080// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));5081//5082// The matcher supports a modifier `Times` that allows to check for arbitrary5083// occurrences including testing for absence with Times(0).5084//5085// Examples:5086// ::std::vector<int> ids;5087// ids.insert(1);5088// ids.insert(1);5089// ids.insert(3);5090// EXPECT_THAT(ids, Contains(1).Times(2)); // 1 occurs 2 times5091// EXPECT_THAT(ids, Contains(2).Times(0)); // 2 is not present5092// EXPECT_THAT(ids, Contains(3).Times(Ge(1))); // 3 occurs at least once50935094template <typename M>5095inline internal::ContainsMatcher<M> Contains(M matcher) {5096return internal::ContainsMatcher<M>(matcher);5097}50985099// IsSupersetOf(iterator_first, iterator_last)5100// IsSupersetOf(pointer, count)5101// IsSupersetOf(array)5102// IsSupersetOf(container)5103// IsSupersetOf({e1, e2, ..., en})5104//5105// IsSupersetOf() verifies that a surjective partial mapping onto a collection5106// of matchers exists. In other words, a container matches5107// IsSupersetOf({e1, ..., en}) if and only if there is a permutation5108// {y1, ..., yn} of some of the container's elements where y1 matches e1,5109// ..., and yn matches en. Obviously, the size of the container must be >= n5110// in order to have a match. Examples:5111//5112// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and5113// 1 matches Ne(0).5114// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches5115// both Eq(1) and Lt(2). The reason is that different matchers must be used5116// for elements in different slots of the container.5117// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches5118// Eq(1) and (the second) 1 matches Lt(2).5119// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)5120// Gt(1) and 3 matches (the second) Gt(1).5121//5122// The matchers can be specified as an array, a pointer and count, a container,5123// an initializer list, or an STL iterator range. In each of these cases, the5124// underlying matchers can be either values or matchers.51255126template <typename Iter>5127inline internal::UnorderedElementsAreArrayMatcher<5128typename ::std::iterator_traits<Iter>::value_type>5129IsSupersetOf(Iter first, Iter last) {5130typedef typename ::std::iterator_traits<Iter>::value_type T;5131return internal::UnorderedElementsAreArrayMatcher<T>(5132internal::UnorderedMatcherRequire::Superset, first, last);5133}51345135template <typename T>5136inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(5137const T* pointer, size_t count) {5138return IsSupersetOf(pointer, pointer + count);5139}51405141template <typename T, size_t N>5142inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(5143const T (&array)[N]) {5144return IsSupersetOf(array, N);5145}51465147template <typename Container>5148inline internal::UnorderedElementsAreArrayMatcher<5149typename Container::value_type>5150IsSupersetOf(const Container& container) {5151return IsSupersetOf(container.begin(), container.end());5152}51535154template <typename T>5155inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(5156::std::initializer_list<T> xs) {5157return IsSupersetOf(xs.begin(), xs.end());5158}51595160// IsSubsetOf(iterator_first, iterator_last)5161// IsSubsetOf(pointer, count)5162// IsSubsetOf(array)5163// IsSubsetOf(container)5164// IsSubsetOf({e1, e2, ..., en})5165//5166// IsSubsetOf() verifies that an injective mapping onto a collection of matchers5167// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and5168// only if there is a subset of matchers {m1, ..., mk} which would match the5169// container using UnorderedElementsAre. Obviously, the size of the container5170// must be <= n in order to have a match. Examples:5171//5172// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).5173// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -15174// matches Lt(0).5175// - {1, 2} doesn't match IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both5176// match Gt(0). The reason is that different matchers must be used for5177// elements in different slots of the container.5178//5179// The matchers can be specified as an array, a pointer and count, a container,5180// an initializer list, or an STL iterator range. In each of these cases, the5181// underlying matchers can be either values or matchers.51825183template <typename Iter>5184inline internal::UnorderedElementsAreArrayMatcher<5185typename ::std::iterator_traits<Iter>::value_type>5186IsSubsetOf(Iter first, Iter last) {5187typedef typename ::std::iterator_traits<Iter>::value_type T;5188return internal::UnorderedElementsAreArrayMatcher<T>(5189internal::UnorderedMatcherRequire::Subset, first, last);5190}51915192template <typename T>5193inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(5194const T* pointer, size_t count) {5195return IsSubsetOf(pointer, pointer + count);5196}51975198template <typename T, size_t N>5199inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(5200const T (&array)[N]) {5201return IsSubsetOf(array, N);5202}52035204template <typename Container>5205inline internal::UnorderedElementsAreArrayMatcher<5206typename Container::value_type>5207IsSubsetOf(const Container& container) {5208return IsSubsetOf(container.begin(), container.end());5209}52105211template <typename T>5212inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(5213::std::initializer_list<T> xs) {5214return IsSubsetOf(xs.begin(), xs.end());5215}52165217// Matches an STL-style container or a native array that contains only5218// elements matching the given value or matcher.5219//5220// Each(m) is semantically equivalent to `Not(Contains(Not(m)))`. Only5221// the messages are different.5222//5223// Examples:5224// ::std::set<int> page_ids;5225// // Each(m) matches an empty container, regardless of what m is.5226// EXPECT_THAT(page_ids, Each(Eq(1)));5227// EXPECT_THAT(page_ids, Each(Eq(77)));5228//5229// page_ids.insert(3);5230// EXPECT_THAT(page_ids, Each(Gt(0)));5231// EXPECT_THAT(page_ids, Not(Each(Gt(4))));5232// page_ids.insert(1);5233// EXPECT_THAT(page_ids, Not(Each(Lt(2))));5234//5235// ::std::map<int, size_t> page_lengths;5236// page_lengths[1] = 100;5237// page_lengths[2] = 200;5238// page_lengths[3] = 300;5239// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));5240// EXPECT_THAT(page_lengths, Each(Key(Le(3))));5241//5242// const char* user_ids[] = { "joe", "mike", "tom" };5243// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));5244template <typename M>5245inline internal::EachMatcher<M> Each(M matcher) {5246return internal::EachMatcher<M>(matcher);5247}52485249// Key(inner_matcher) matches an std::pair whose 'first' field matches5250// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an5251// std::map that contains at least one element whose key is >= 5.5252template <typename M>5253inline internal::KeyMatcher<M> Key(M inner_matcher) {5254return internal::KeyMatcher<M>(inner_matcher);5255}52565257// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field5258// matches first_matcher and whose 'second' field matches second_matcher. For5259// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used5260// to match a std::map<int, string> that contains exactly one element whose key5261// is >= 5 and whose value equals "foo".5262template <typename FirstMatcher, typename SecondMatcher>5263inline internal::PairMatcher<FirstMatcher, SecondMatcher> Pair(5264FirstMatcher first_matcher, SecondMatcher second_matcher) {5265return internal::PairMatcher<FirstMatcher, SecondMatcher>(first_matcher,5266second_matcher);5267}52685269namespace no_adl {5270// Conditional() creates a matcher that conditionally uses either the first or5271// second matcher provided. For example, we could create an `equal if, and only5272// if' matcher using the Conditional wrapper as follows:5273//5274// EXPECT_THAT(result, Conditional(condition, Eq(expected), Ne(expected)));5275template <typename MatcherTrue, typename MatcherFalse>5276internal::ConditionalMatcher<MatcherTrue, MatcherFalse> Conditional(5277bool condition, MatcherTrue matcher_true, MatcherFalse matcher_false) {5278return internal::ConditionalMatcher<MatcherTrue, MatcherFalse>(5279condition, std::move(matcher_true), std::move(matcher_false));5280}52815282// FieldsAre(matchers...) matches piecewise the fields of compatible structs.5283// These include those that support `get<I>(obj)`, and when structured bindings5284// are enabled any class that supports them.5285// In particular, `std::tuple`, `std::pair`, `std::array` and aggregate types.5286template <typename... M>5287internal::FieldsAreMatcher<typename std::decay<M>::type...> FieldsAre(5288M&&... matchers) {5289return internal::FieldsAreMatcher<typename std::decay<M>::type...>(5290std::forward<M>(matchers)...);5291}52925293// Creates a matcher that matches a pointer (raw or smart) that matches5294// inner_matcher.5295template <typename InnerMatcher>5296inline internal::PointerMatcher<InnerMatcher> Pointer(5297const InnerMatcher& inner_matcher) {5298return internal::PointerMatcher<InnerMatcher>(inner_matcher);5299}53005301// Creates a matcher that matches an object that has an address that matches5302// inner_matcher.5303template <typename InnerMatcher>5304inline internal::AddressMatcher<InnerMatcher> Address(5305const InnerMatcher& inner_matcher) {5306return internal::AddressMatcher<InnerMatcher>(inner_matcher);5307}53085309// Matches a base64 escaped string, when the unescaped string matches the5310// internal matcher.5311template <typename MatcherType>5312internal::WhenBase64UnescapedMatcher WhenBase64Unescaped(5313const MatcherType& internal_matcher) {5314return internal::WhenBase64UnescapedMatcher(internal_matcher);5315}5316} // namespace no_adl53175318// Returns a predicate that is satisfied by anything that matches the5319// given matcher.5320template <typename M>5321inline internal::MatcherAsPredicate<M> Matches(M matcher) {5322return internal::MatcherAsPredicate<M>(matcher);5323}53245325// Returns true if and only if the value matches the matcher.5326template <typename T, typename M>5327inline bool Value(const T& value, M matcher) {5328return testing::Matches(matcher)(value);5329}53305331// Matches the value against the given matcher and explains the match5332// result to listener.5333template <typename T, typename M>5334inline bool ExplainMatchResult(M matcher, const T& value,5335MatchResultListener* listener) {5336return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);5337}53385339// Returns a string representation of the given matcher. Useful for description5340// strings of matchers defined using MATCHER_P* macros that accept matchers as5341// their arguments. For example:5342//5343// MATCHER_P(XAndYThat, matcher,5344// "X that " + DescribeMatcher<int>(matcher, negation) +5345// (negation ? " or" : " and") + " Y that " +5346// DescribeMatcher<double>(matcher, negation)) {5347// return ExplainMatchResult(matcher, arg.x(), result_listener) &&5348// ExplainMatchResult(matcher, arg.y(), result_listener);5349// }5350template <typename T, typename M>5351std::string DescribeMatcher(const M& matcher, bool negation = false) {5352::std::stringstream ss;5353Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);5354if (negation) {5355monomorphic_matcher.DescribeNegationTo(&ss);5356} else {5357monomorphic_matcher.DescribeTo(&ss);5358}5359return ss.str();5360}53615362template <typename... Args>5363internal::ElementsAreMatcher<5364std::tuple<typename std::decay<const Args&>::type...>>5365ElementsAre(const Args&... matchers) {5366return internal::ElementsAreMatcher<5367std::tuple<typename std::decay<const Args&>::type...>>(5368std::make_tuple(matchers...));5369}53705371template <typename... Args>5372internal::UnorderedElementsAreMatcher<5373std::tuple<typename std::decay<const Args&>::type...>>5374UnorderedElementsAre(const Args&... matchers) {5375return internal::UnorderedElementsAreMatcher<5376std::tuple<typename std::decay<const Args&>::type...>>(5377std::make_tuple(matchers...));5378}53795380// Define variadic matcher versions.5381template <typename... Args>5382internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(5383const Args&... matchers) {5384return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(5385matchers...);5386}53875388template <typename... Args>5389internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(5390const Args&... matchers) {5391return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(5392matchers...);5393}53945395// AnyOfArray(array)5396// AnyOfArray(pointer, count)5397// AnyOfArray(container)5398// AnyOfArray({ e1, e2, ..., en })5399// AnyOfArray(iterator_first, iterator_last)5400//5401// AnyOfArray() verifies whether a given value matches any member of a5402// collection of matchers.5403//5404// AllOfArray(array)5405// AllOfArray(pointer, count)5406// AllOfArray(container)5407// AllOfArray({ e1, e2, ..., en })5408// AllOfArray(iterator_first, iterator_last)5409//5410// AllOfArray() verifies whether a given value matches all members of a5411// collection of matchers.5412//5413// The matchers can be specified as an array, a pointer and count, a container,5414// an initializer list, or an STL iterator range. In each of these cases, the5415// underlying matchers can be either values or matchers.54165417template <typename Iter>5418inline internal::AnyOfArrayMatcher<5419typename ::std::iterator_traits<Iter>::value_type>5420AnyOfArray(Iter first, Iter last) {5421return internal::AnyOfArrayMatcher<5422typename ::std::iterator_traits<Iter>::value_type>(first, last);5423}54245425template <typename Iter>5426inline internal::AllOfArrayMatcher<5427typename ::std::iterator_traits<Iter>::value_type>5428AllOfArray(Iter first, Iter last) {5429return internal::AllOfArrayMatcher<5430typename ::std::iterator_traits<Iter>::value_type>(first, last);5431}54325433template <typename T>5434inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T* ptr, size_t count) {5435return AnyOfArray(ptr, ptr + count);5436}54375438template <typename T>5439inline internal::AllOfArrayMatcher<T> AllOfArray(const T* ptr, size_t count) {5440return AllOfArray(ptr, ptr + count);5441}54425443template <typename T, size_t N>5444inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T (&array)[N]) {5445return AnyOfArray(array, N);5446}54475448template <typename T, size_t N>5449inline internal::AllOfArrayMatcher<T> AllOfArray(const T (&array)[N]) {5450return AllOfArray(array, N);5451}54525453template <typename Container>5454inline internal::AnyOfArrayMatcher<typename Container::value_type> AnyOfArray(5455const Container& container) {5456return AnyOfArray(container.begin(), container.end());5457}54585459template <typename Container>5460inline internal::AllOfArrayMatcher<typename Container::value_type> AllOfArray(5461const Container& container) {5462return AllOfArray(container.begin(), container.end());5463}54645465template <typename T>5466inline internal::AnyOfArrayMatcher<T> AnyOfArray(5467::std::initializer_list<T> xs) {5468return AnyOfArray(xs.begin(), xs.end());5469}54705471template <typename T>5472inline internal::AllOfArrayMatcher<T> AllOfArray(5473::std::initializer_list<T> xs) {5474return AllOfArray(xs.begin(), xs.end());5475}54765477// Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected5478// fields of it matches a_matcher. C++ doesn't support default5479// arguments for function templates, so we have to overload it.5480template <size_t... k, typename InnerMatcher>5481internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...> Args(5482InnerMatcher&& matcher) {5483return internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...>(5484std::forward<InnerMatcher>(matcher));5485}54865487// AllArgs(m) is a synonym of m. This is useful in5488//5489// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));5490//5491// which is easier to read than5492//5493// EXPECT_CALL(foo, Bar(_, _)).With(Eq());5494template <typename InnerMatcher>5495inline InnerMatcher AllArgs(const InnerMatcher& matcher) {5496return matcher;5497}54985499// Returns a matcher that matches the value of an optional<> type variable.5500// The matcher implementation only uses '!arg' (or 'arg.has_value()' if '!arg`5501// isn't a valid expression) and requires that the optional<> type has a5502// 'value_type' member type and that '*arg' is of type 'value_type' and is5503// printable using 'PrintToString'. It is compatible with5504// std::optional/std::experimental::optional.5505// Note that to compare an optional type variable against nullopt you should5506// use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the5507// optional value contains an optional itself.5508template <typename ValueMatcher>5509inline internal::OptionalMatcher<ValueMatcher> Optional(5510const ValueMatcher& value_matcher) {5511return internal::OptionalMatcher<ValueMatcher>(value_matcher);5512}55135514// Returns a matcher that matches the value of a absl::any type variable.5515template <typename T>5516PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T>> AnyWith(5517const Matcher<const T&>& matcher) {5518return MakePolymorphicMatcher(5519internal::any_cast_matcher::AnyCastMatcher<T>(matcher));5520}55215522// Returns a matcher that matches the value of a variant<> type variable.5523// The matcher implementation uses ADL to find the holds_alternative and get5524// functions.5525// It is compatible with std::variant.5526template <typename T>5527PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T>> VariantWith(5528const Matcher<const T&>& matcher) {5529return MakePolymorphicMatcher(5530internal::variant_matcher::VariantMatcher<T>(matcher));5531}55325533#if GTEST_HAS_EXCEPTIONS55345535// Anything inside the `internal` namespace is internal to the implementation5536// and must not be used in user code!5537namespace internal {55385539class WithWhatMatcherImpl {5540public:5541WithWhatMatcherImpl(Matcher<std::string> matcher)5542: matcher_(std::move(matcher)) {}55435544void DescribeTo(std::ostream* os) const {5545*os << "contains .what() that ";5546matcher_.DescribeTo(os);5547}55485549void DescribeNegationTo(std::ostream* os) const {5550*os << "contains .what() that does not ";5551matcher_.DescribeTo(os);5552}55535554template <typename Err>5555bool MatchAndExplain(const Err& err, MatchResultListener* listener) const {5556*listener << "which contains .what() (of value = " << err.what()5557<< ") that ";5558return matcher_.MatchAndExplain(err.what(), listener);5559}55605561private:5562const Matcher<std::string> matcher_;5563};55645565inline PolymorphicMatcher<WithWhatMatcherImpl> WithWhat(5566Matcher<std::string> m) {5567return MakePolymorphicMatcher(WithWhatMatcherImpl(std::move(m)));5568}55695570template <typename Err>5571class ExceptionMatcherImpl {5572class NeverThrown {5573public:5574const char* what() const noexcept {5575return "this exception should never be thrown";5576}5577};55785579// If the matchee raises an exception of a wrong type, we'd like to5580// catch it and print its message and type. To do that, we add an additional5581// catch clause:5582//5583// try { ... }5584// catch (const Err&) { /* an expected exception */ }5585// catch (const std::exception&) { /* exception of a wrong type */ }5586//5587// However, if the `Err` itself is `std::exception`, we'd end up with two5588// identical `catch` clauses:5589//5590// try { ... }5591// catch (const std::exception&) { /* an expected exception */ }5592// catch (const std::exception&) { /* exception of a wrong type */ }5593//5594// This can cause a warning or an error in some compilers. To resolve5595// the issue, we use a fake error type whenever `Err` is `std::exception`:5596//5597// try { ... }5598// catch (const std::exception&) { /* an expected exception */ }5599// catch (const NeverThrown&) { /* exception of a wrong type */ }5600using DefaultExceptionType = typename std::conditional<5601std::is_same<typename std::remove_cv<5602typename std::remove_reference<Err>::type>::type,5603std::exception>::value,5604const NeverThrown&, const std::exception&>::type;56055606public:5607ExceptionMatcherImpl(Matcher<const Err&> matcher)5608: matcher_(std::move(matcher)) {}56095610void DescribeTo(std::ostream* os) const {5611*os << "throws an exception which is a " << GetTypeName<Err>();5612*os << " which ";5613matcher_.DescribeTo(os);5614}56155616void DescribeNegationTo(std::ostream* os) const {5617*os << "throws an exception which is not a " << GetTypeName<Err>();5618*os << " which ";5619matcher_.DescribeNegationTo(os);5620}56215622template <typename T>5623bool MatchAndExplain(T&& x, MatchResultListener* listener) const {5624try {5625(void)(std::forward<T>(x)());5626} catch (const Err& err) {5627*listener << "throws an exception which is a " << GetTypeName<Err>();5628*listener << " ";5629return matcher_.MatchAndExplain(err, listener);5630} catch (DefaultExceptionType err) {5631#if GTEST_HAS_RTTI5632*listener << "throws an exception of type " << GetTypeName(typeid(err));5633*listener << " ";5634#else5635*listener << "throws an std::exception-derived type ";5636#endif5637*listener << "with description \"" << err.what() << "\"";5638return false;5639} catch (...) {5640*listener << "throws an exception of an unknown type";5641return false;5642}56435644*listener << "does not throw any exception";5645return false;5646}56475648private:5649const Matcher<const Err&> matcher_;5650};56515652} // namespace internal56535654// Throws()5655// Throws(exceptionMatcher)5656// ThrowsMessage(messageMatcher)5657//5658// This matcher accepts a callable and verifies that when invoked, it throws5659// an exception with the given type and properties.5660//5661// Examples:5662//5663// EXPECT_THAT(5664// []() { throw std::runtime_error("message"); },5665// Throws<std::runtime_error>());5666//5667// EXPECT_THAT(5668// []() { throw std::runtime_error("message"); },5669// ThrowsMessage<std::runtime_error>(HasSubstr("message")));5670//5671// EXPECT_THAT(5672// []() { throw std::runtime_error("message"); },5673// Throws<std::runtime_error>(5674// Property(&std::runtime_error::what, HasSubstr("message"))));56755676template <typename Err>5677PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws() {5678return MakePolymorphicMatcher(5679internal::ExceptionMatcherImpl<Err>(A<const Err&>()));5680}56815682template <typename Err, typename ExceptionMatcher>5683PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws(5684const ExceptionMatcher& exception_matcher) {5685// Using matcher cast allows users to pass a matcher of a more broad type.5686// For example user may want to pass Matcher<std::exception>5687// to Throws<std::runtime_error>, or Matcher<int64> to Throws<int32>.5688return MakePolymorphicMatcher(internal::ExceptionMatcherImpl<Err>(5689SafeMatcherCast<const Err&>(exception_matcher)));5690}56915692template <typename Err, typename MessageMatcher>5693PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(5694MessageMatcher&& message_matcher) {5695static_assert(std::is_base_of<std::exception, Err>::value,5696"expected an std::exception-derived type");5697return Throws<Err>(internal::WithWhat(5698MatcherCast<std::string>(std::forward<MessageMatcher>(message_matcher))));5699}57005701#endif // GTEST_HAS_EXCEPTIONS57025703// These macros allow using matchers to check values in Google Test5704// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)5705// succeed if and only if the value matches the matcher. If the assertion5706// fails, the value and the description of the matcher will be printed.5707#define ASSERT_THAT(value, matcher) \5708ASSERT_PRED_FORMAT1( \5709::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)5710#define EXPECT_THAT(value, matcher) \5711EXPECT_PRED_FORMAT1( \5712::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)57135714// MATCHER* macros itself are listed below.5715#define MATCHER(name, description) \5716class name##Matcher \5717: public ::testing::internal::MatcherBaseImpl<name##Matcher> { \5718public: \5719template <typename arg_type> \5720class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \5721public: \5722gmock_Impl() {} \5723bool MatchAndExplain( \5724const arg_type& arg, \5725::testing::MatchResultListener* result_listener) const override; \5726void DescribeTo(::std::ostream* gmock_os) const override { \5727*gmock_os << FormatDescription(false); \5728} \5729void DescribeNegationTo(::std::ostream* gmock_os) const override { \5730*gmock_os << FormatDescription(true); \5731} \5732\5733private: \5734::std::string FormatDescription(bool negation) const { \5735/* NOLINTNEXTLINE readability-redundant-string-init */ \5736::std::string gmock_description = (description); \5737if (!gmock_description.empty()) { \5738return gmock_description; \5739} \5740return ::testing::internal::FormatMatcherDescription(negation, #name, \5741{}, {}); \5742} \5743}; \5744}; \5745inline name##Matcher GMOCK_INTERNAL_WARNING_PUSH() \5746GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-function") \5747GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \5748name GMOCK_INTERNAL_WARNING_POP()() { \5749return {}; \5750} \5751template <typename arg_type> \5752bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \5753const arg_type& arg, \5754[[maybe_unused]] ::testing::MatchResultListener* result_listener) const57555756#define MATCHER_P(name, p0, description) \5757GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (#p0), (p0))5758#define MATCHER_P2(name, p0, p1, description) \5759GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (#p0, #p1), \5760(p0, p1))5761#define MATCHER_P3(name, p0, p1, p2, description) \5762GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (#p0, #p1, #p2), \5763(p0, p1, p2))5764#define MATCHER_P4(name, p0, p1, p2, p3, description) \5765GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, \5766(#p0, #p1, #p2, #p3), (p0, p1, p2, p3))5767#define MATCHER_P5(name, p0, p1, p2, p3, p4, description) \5768GMOCK_INTERNAL_MATCHER(name, name##MatcherP5, description, \5769(#p0, #p1, #p2, #p3, #p4), (p0, p1, p2, p3, p4))5770#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \5771GMOCK_INTERNAL_MATCHER(name, name##MatcherP6, description, \5772(#p0, #p1, #p2, #p3, #p4, #p5), \5773(p0, p1, p2, p3, p4, p5))5774#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \5775GMOCK_INTERNAL_MATCHER(name, name##MatcherP7, description, \5776(#p0, #p1, #p2, #p3, #p4, #p5, #p6), \5777(p0, p1, p2, p3, p4, p5, p6))5778#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \5779GMOCK_INTERNAL_MATCHER(name, name##MatcherP8, description, \5780(#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7), \5781(p0, p1, p2, p3, p4, p5, p6, p7))5782#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \5783GMOCK_INTERNAL_MATCHER(name, name##MatcherP9, description, \5784(#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8), \5785(p0, p1, p2, p3, p4, p5, p6, p7, p8))5786#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \5787GMOCK_INTERNAL_MATCHER(name, name##MatcherP10, description, \5788(#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9), \5789(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9))57905791#define GMOCK_INTERNAL_MATCHER(name, full_name, description, arg_names, args) \5792template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \5793class full_name : public ::testing::internal::MatcherBaseImpl< \5794full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>> { \5795public: \5796using full_name::MatcherBaseImpl::MatcherBaseImpl; \5797template <typename arg_type> \5798class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \5799public: \5800explicit gmock_Impl(GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) \5801: GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) {} \5802bool MatchAndExplain( \5803const arg_type& arg, \5804::testing::MatchResultListener* result_listener) const override; \5805void DescribeTo(::std::ostream* gmock_os) const override { \5806*gmock_os << FormatDescription(false); \5807} \5808void DescribeNegationTo(::std::ostream* gmock_os) const override { \5809*gmock_os << FormatDescription(true); \5810} \5811GMOCK_INTERNAL_MATCHER_MEMBERS(args) \5812\5813private: \5814::std::string FormatDescription(bool negation) const { \5815::std::string gmock_description; \5816gmock_description = (description); \5817if (!gmock_description.empty()) { \5818return gmock_description; \5819} \5820return ::testing::internal::FormatMatcherDescription( \5821negation, #name, {GMOCK_PP_REMOVE_PARENS(arg_names)}, \5822::testing::internal::UniversalTersePrintTupleFieldsToStrings( \5823::std::tuple<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \5824GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args)))); \5825} \5826}; \5827}; \5828template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \5829inline full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)> name( \5830GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) { \5831return full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \5832GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args)); \5833} \5834template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \5835template <typename arg_type> \5836bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>:: \5837gmock_Impl<arg_type>::MatchAndExplain( \5838const arg_type& arg, \5839[[maybe_unused]] ::testing::MatchResultListener* result_listener) \5840const58415842#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \5843GMOCK_PP_TAIL( \5844GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM, , args))5845#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM(i_unused, data_unused, arg) \5846, typename arg##_type58475848#define GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args) \5849GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TYPE_PARAM, , args))5850#define GMOCK_INTERNAL_MATCHER_TYPE_PARAM(i_unused, data_unused, arg) \5851, arg##_type58525853#define GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args) \5854GMOCK_PP_TAIL(dummy_first GMOCK_PP_FOR_EACH( \5855GMOCK_INTERNAL_MATCHER_FUNCTION_ARG, , args))5856#define GMOCK_INTERNAL_MATCHER_FUNCTION_ARG(i, data_unused, arg) \5857, arg##_type gmock_p##i58585859#define GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) \5860GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_FORWARD_ARG, , args))5861#define GMOCK_INTERNAL_MATCHER_FORWARD_ARG(i, data_unused, arg) \5862, arg(::std::forward<arg##_type>(gmock_p##i))58635864#define GMOCK_INTERNAL_MATCHER_MEMBERS(args) \5865GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER, , args)5866#define GMOCK_INTERNAL_MATCHER_MEMBER(i_unused, data_unused, arg) \5867const arg##_type arg;58685869#define GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args) \5870GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER_USAGE, , args))5871#define GMOCK_INTERNAL_MATCHER_MEMBER_USAGE(i_unused, data_unused, arg) , arg58725873#define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \5874GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args))5875#define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg) \5876, ::std::forward<arg##_type>(gmock_p##i)58775878// To prevent ADL on certain functions we put them on a separate namespace.5879using namespace no_adl; // NOLINT58805881} // namespace testing58825883GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 504658845885// Include any custom callback matchers added by the local installation.5886// We must include this header at the end to make sure it can use the5887// declarations from this file.5888#include "gmock/internal/custom/gmock-matchers.h"58895890#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_589158925893