tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

gmock-matchers.h (222841B)


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