[libc-commits] [libc] [libc][test] Align custom matchers with GoogleMock (PR #240616)

Roland McGrath via libc-commits libc-commits at lists.llvm.org
Mon Nov 9 21:09:35 PST 2026


https://github.com/frobtech updated https://github.com/llvm/llvm-project/pull/240616

>From d72f4e0397689ce7917e8695a9d313fa364239df Mon Sep 17 00:00:00 2001
From: Roland McGrath <mcgrathr at google.com>
Date: Sat, 7 Nov 2026 04:53:52 -0800
Subject: [PATCH 1/2] [libc] Add missing const in cpp::span and
 scanf_core::FormatSection

cpp::span provided a constructor from non-const cpp::array<U, N> & but
missed the corresponding const cpp::array<U, N> & overload from C++20
std::span, and scanf_core::FormatSection::operator== lacked a const
qualifier. Add both so const span-based and scanf format-section
comparisons work without const_cast or mutable copies.

Part of #91630

Assisted-by: Gemini
---
 libc/src/__support/CPP/span.h             | 5 +++++
 libc/src/stdio/scanf_core/core_structs.h  | 2 +-
 libc/test/src/__support/CPP/span_test.cpp | 9 +++++++++
 3 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/libc/src/__support/CPP/span.h b/libc/src/__support/CPP/span.h
index 859ba24d1442e7..cbf15d160feef1 100644
--- a/libc/src/__support/CPP/span.h
+++ b/libc/src/__support/CPP/span.h
@@ -77,6 +77,11 @@ template <typename T> class span {
   LIBC_INLINE constexpr span(array<U, N> &arr)
       : span_data(arr.data()), span_size(arr.size()) {}
 
+  template <typename U, size_t N,
+            cpp::enable_if_t<is_compatible_v<const U>, bool> = true>
+  LIBC_INLINE constexpr span(const array<U, N> &arr)
+      : span_data(arr.data()), span_size(arr.size()) {}
+
   template <typename U, cpp::enable_if_t<is_compatible_v<U>, bool> = true>
   LIBC_INLINE constexpr span(const span<U> &s)
       : span_data(s.data()), span_size(s.size()) {}
diff --git a/libc/src/stdio/scanf_core/core_structs.h b/libc/src/stdio/scanf_core/core_structs.h
index 87b2429ae550e6..7a80dc1166eb7f 100644
--- a/libc/src/stdio/scanf_core/core_structs.h
+++ b/libc/src/stdio/scanf_core/core_structs.h
@@ -46,7 +46,7 @@ struct FormatSection {
 
   cpp::bitset<256> scan_set;
 
-  LIBC_INLINE bool operator==(const FormatSection &other) {
+  LIBC_INLINE bool operator==(const FormatSection &other) const {
     if (has_conv != other.has_conv)
       return false;
 
diff --git a/libc/test/src/__support/CPP/span_test.cpp b/libc/test/src/__support/CPP/span_test.cpp
index 9d83e722c69c64..e8686749f85606 100644
--- a/libc/test/src/__support/CPP/span_test.cpp
+++ b/libc/test/src/__support/CPP/span_test.cpp
@@ -86,6 +86,15 @@ TEST(LlvmLibcSpanTest, InitializeViewFormMutableArray) {
   ASSERT_EQ(s[2], 3);
 }
 
+TEST(LlvmLibcSpanTest, InitializeViewFromConstArray) {
+  const array<int, 3> a = {1, 2, 3};
+  span<const int> s(a);
+  ASSERT_EQ(s.size(), size_t(3));
+  ASSERT_EQ(s[0], 1);
+  ASSERT_EQ(s[1], 2);
+  ASSERT_EQ(s[2], 3);
+}
+
 TEST(LlvmLibcSpanTest, InitializeFromMutable) {
   int a[] = {1, 2, 3};
   span<int> s(a);

>From 1ed5ef207c395137db768f7a027fe63f65f2d13c Mon Sep 17 00:00:00 2001
From: Roland McGrath <mcgrathr at google.com>
Date: Mon, 9 Nov 2026 15:30:20 -0800
Subject: [PATCH 2/2] [libc][test] Align custom matchers with GoogleMock

LibcTest custom matchers implemented stateful match(T) and explainError()
methods writing directly to tlog, whereas GoogleMock's polymorphic
is_gtest_matcher protocol expects const MatchAndExplain(T,
MatchResultListener *), DescribeTo, and DescribeNegationTo methods.

Add a hermetic MatchResultListener wrapper around TestLogger in
LibcTest.h and update custom matchers across libc/test and libc/utils to
implement MatchAndExplain(..., MatchResultListener *) const so they work
directly with GoogleMock's EXPECT_THAT and ASSERT_THAT without macro
redefinitions.

Depends on #240610
Part of #91630

Assisted-by: Gemini
---
 libc/test/UnitTest/ErrnoSetterMatcher.h       |  91 +++--
 libc/test/UnitTest/FPExceptMatcher.h          |  14 +-
 libc/test/UnitTest/FPMatcher.h                |  82 ++--
 libc/test/UnitTest/LibcTest.cpp               |  19 +-
 libc/test/UnitTest/LibcTest.h                 |  70 +++-
 libc/test/UnitTest/MemoryMatcher.cpp          |  55 ++-
 libc/test/UnitTest/MemoryMatcher.h            |   8 +-
 libc/test/UnitTest/PrintfMatcher.cpp          |  49 +--
 libc/test/UnitTest/PrintfMatcher.h            |  32 +-
 libc/test/UnitTest/ScanfMatcher.cpp           |  62 +--
 libc/test/UnitTest/ScanfMatcher.h             |   7 +-
 libc/test/include/sys/queue_test.cpp          |  21 +-
 .../sys/socket/linux/socket_test_support.h    |  67 ++--
 libc/test/src/time/TmMatcher.h                |  57 ++-
 libc/utils/MPCWrapper/MPCUtils.cpp            |  20 +-
 libc/utils/MPCWrapper/MPCUtils.h              |  38 +-
 libc/utils/MPFRWrapper/MPFRUtils.cpp          | 371 ++++++++++--------
 libc/utils/MPFRWrapper/MPFRUtils.h            |  72 ++--
 18 files changed, 606 insertions(+), 529 deletions(-)

diff --git a/libc/test/UnitTest/ErrnoSetterMatcher.h b/libc/test/UnitTest/ErrnoSetterMatcher.h
index a7f21843e602c2..0776541dd818ba 100644
--- a/libc/test/UnitTest/ErrnoSetterMatcher.h
+++ b/libc/test/UnitTest/ErrnoSetterMatcher.h
@@ -37,6 +37,7 @@
 #include "src/__support/FPUtil/FPBits.h"
 #include "src/__support/FPUtil/fpbits_str.h"
 #include "src/__support/StringUtil/error_to_string.h"
+#include "src/__support/integer_to_string.h"
 #include "src/__support/libc_errno.h"
 #include "src/__support/macros/config.h"
 #include "src/__support/macros/properties/architectures.h"
@@ -62,7 +63,7 @@ constexpr const char *CompareMessage[] = {
 template <typename T> struct Comparator {
   CompareAction cmp;
   T expected;
-  bool compare(T actual) {
+  bool compare(T actual) const {
     switch (cmp) {
     case CompareAction::EQ:
       return actual == expected;
@@ -83,9 +84,9 @@ template <typename T> struct Comparator {
   // The NVPTX backend cannot handle circular dependencies on global variables.
   // We provide a constant dummy implementation to prevent this from occurring.
 #ifdef LIBC_TARGET_ARCH_IS_NVPTX
-  constexpr const char *str() { return ""; }
+  constexpr const char *str() const { return ""; }
 #else
-  const char *str() { return CompareMessage[static_cast<int>(cmp)]; }
+  const char *str() const { return CompareMessage[static_cast<int>(cmp)]; }
 #endif
 };
 
@@ -128,25 +129,25 @@ class ErrnoCheck {
     return false;
   }
 
-  void print_expected() const {
+  template <typename Stream> void print_expected(Stream &os) const {
     if (type == Type::EQ) {
       auto expected_str = try_get_errno_name(expected);
-      tlog << "equal to " << (expected_str ? *expected_str : "<unknown>") << "("
-           << expected << ")";
+      os << "equal to " << (expected_str ? *expected_str : "<unknown>") << "("
+         << expected << ")";
     } else if (type == Type::NE) {
       auto expected_str = try_get_errno_name(expected);
-      tlog << "not equal to " << (expected_str ? *expected_str : "<unknown>")
-           << "(" << expected << ")";
+      os << "not equal to " << (expected_str ? *expected_str : "<unknown>")
+         << "(" << expected << ")";
     } else if (type == Type::ANY_OF) {
-      tlog << "one of [";
+      os << "one of [";
       for (size_t i = 0; i < list_count; ++i) {
         auto expected_str = try_get_errno_name(expected_list[i]);
-        tlog << (expected_str ? *expected_str : "<unknown>") << "("
-             << expected_list[i] << ")";
+        os << (expected_str ? *expected_str : "<unknown>") << "("
+           << expected_list[i] << ")";
         if (i + 1 < list_count)
-          tlog << ", ";
+          os << ", ";
       }
-      tlog << "]";
+      os << "]";
     }
   }
 };
@@ -154,8 +155,8 @@ class ErrnoCheck {
 template <typename T> class ErrnoSetterMatcher : public Matcher<T> {
   Comparator<T> return_cmp;
   ErrnoCheck errno_cmp;
-  T actual_return;
-  int actual_errno;
+  mutable int actual_errno = 0;
+  mutable bool has_errno = false;
 
   // Even though this is a errno matcher primarily, it has to cater to platforms
   // which do not have an errno. This predicate checks if errno matching is to
@@ -178,39 +179,51 @@ template <typename T> class ErrnoSetterMatcher : public Matcher<T> {
     return *this;
   }
 
-  void explainError() override {
-    if (!return_cmp.compare(actual_return)) {
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  bool MatchAndExplain(T got, MatchResultListener *listener) const {
+    if constexpr (!ignore_errno()) {
+      if (!has_errno) {
+        actual_errno = libc_errno;
+        libc_errno = 0;
+        has_errno = true;
+      }
+    }
+    bool ret_ok = return_cmp.compare(got);
+    bool errno_ok = ignore_errno() || errno_cmp.compare(actual_errno);
+    if (ret_ok && errno_ok)
+      return true;
+    if (!listener->IsInterested())
+      return false;
+
+    if (!ret_ok) {
       if constexpr (cpp::is_floating_point_v<T>) {
-        tlog << "Expected return value to be " << return_cmp.str() << ": "
-             << str(fputil::FPBits<T>(return_cmp.expected)) << '\n'
-             << "                    But got: "
-             << str(fputil::FPBits<T>(actual_return)) << '\n';
+        *listener << "Expected return value to be " << return_cmp.str() << ": "
+                  << str(fputil::FPBits<T>(return_cmp.expected)) << '\n'
+                  << "                    But got: "
+                  << str(fputil::FPBits<T>(got)) << '\n';
+      } else if constexpr (cpp::is_pointer_v<T>) {
+        const IntegerToString<uintptr_t, radix::Hex::WithPrefix> exp_hex(
+            reinterpret_cast<uintptr_t>(return_cmp.expected));
+        const IntegerToString<uintptr_t, radix::Hex::WithPrefix> got_hex(
+            reinterpret_cast<uintptr_t>(got));
+        *listener << "Expected return value to be " << return_cmp.str() << " "
+                  << exp_hex.view() << " but got " << got_hex.view() << ".\n";
       } else {
-        tlog << "Expected return value to be " << return_cmp.str() << " "
-             << return_cmp.expected << " but got " << actual_return << ".\n";
+        *listener << "Expected return value to be " << return_cmp.str() << " "
+                  << return_cmp.expected << " but got " << got << ".\n";
       }
     }
 
     if constexpr (!ignore_errno()) {
-      if (!errno_cmp.compare(actual_errno)) {
+      if (!errno_ok) {
         auto actual_str = try_get_errno_name(actual_errno);
-        tlog << "Expected errno to be ";
-        errno_cmp.print_expected();
-        tlog << " but got " << (actual_str ? *actual_str : "<unknown>") << "("
-             << actual_errno << ").\n";
+        *listener << "Expected errno to be ";
+        errno_cmp.print_expected(*listener);
+        *listener << " but got " << (actual_str ? *actual_str : "<unknown>")
+                  << "(" << actual_errno << ").\n";
       }
     }
-  }
-
-  bool match(T got) {
-    actual_return = got;
-    actual_errno = libc_errno;
-    libc_errno = 0;
-    if constexpr (ignore_errno())
-      return return_cmp.compare(actual_return);
-    else
-      return return_cmp.compare(actual_return) &&
-             errno_cmp.compare(actual_errno);
+    return false;
   }
 };
 
diff --git a/libc/test/UnitTest/FPExceptMatcher.h b/libc/test/UnitTest/FPExceptMatcher.h
index 732ac09557acbf..a3f9f7ec4537f0 100644
--- a/libc/test/UnitTest/FPExceptMatcher.h
+++ b/libc/test/UnitTest/FPExceptMatcher.h
@@ -12,7 +12,6 @@
 #include "src/__support/CPP/functional.h"
 #include "src/__support/macros/config.h"
 #include "test/UnitTest/Test.h"
-#include "test/UnitTest/TestLogger.h"
 
 #if LIBC_TEST_HAS_MATCHERS()
 
@@ -27,11 +26,14 @@ class FPExceptMatcher : public Matcher<bool> {
 public:
   explicit FPExceptMatcher(cpp::function_ref<void(void)> func);
 
-  bool match([[maybe_unused]] bool unused) { return exceptionRaised; }
-
-  void explainError() override {
-    tlog << "A floating point exception should have been raised but it "
-         << "wasn't\n";
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  bool MatchAndExplain([[maybe_unused]] bool unused,
+                       MatchResultListener *listener) const {
+    if (exceptionRaised)
+      return true;
+    *listener << "A floating point exception should have been raised but it "
+              << "wasn't\n";
+    return false;
   }
 };
 
diff --git a/libc/test/UnitTest/FPMatcher.h b/libc/test/UnitTest/FPMatcher.h
index 314d8f4f1ef1e8..09ef3e181a4aef 100644
--- a/libc/test/UnitTest/FPMatcher.h
+++ b/libc/test/UnitTest/FPMatcher.h
@@ -37,13 +37,11 @@ template <typename T, TestCond Condition> class FPMatcher : public Matcher<T> {
                 "Unsupported FPMatcher test condition.");
 
   T expected;
-  T actual;
 
 public:
   FPMatcher(T expectedValue) : expected(expectedValue) {}
 
-  bool match(T actualValue) {
-    actual = actualValue;
+  bool match(T actual) const {
     fputil::FPBits<T> actualBits(actual), expectedBits(expected);
     if (Condition == TestCond::EQ)
       return (actualBits.is_nan() && expectedBits.is_nan()) ||
@@ -56,11 +54,17 @@ template <typename T, TestCond Condition> class FPMatcher : public Matcher<T> {
            (actualBits.uintval() != expectedBits.uintval());
   }
 
-  void explainError() override {
-    tlog << "Expected floating point value: "
-         << str(fputil::FPBits<T>(expected)) << '\n';
-    tlog << "Actual floating point value: " << str(fputil::FPBits<T>(actual))
-         << '\n';
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  bool MatchAndExplain(T actual, MatchResultListener *listener) const {
+    if (match(actual))
+      return true;
+    if (listener->IsInterested()) {
+      *listener << "Expected floating point value: "
+                << str(fputil::FPBits<T>(expected)) << '\n'
+                << "Actual floating point value: "
+                << str(fputil::FPBits<T>(actual)) << '\n';
+    }
+    return false;
   }
 };
 
@@ -72,14 +76,13 @@ template <typename T, TestCond Condition> class CFPMatcher : public Matcher<T> {
                 "Unsupported CFPMatcher test condition.");
 
   T expected;
-  T actual;
 
 public:
   CFPMatcher(T expectedValue) : expected(expectedValue) {}
 
-  template <typename CFT> bool matchComplex() {
-    CFT *actualCmplxPtr = reinterpret_cast<CFT *>(&actual);
-    CFT *expectedCmplxPtr = reinterpret_cast<CFT *>(&expected);
+  template <typename CFT> bool matchComplex(T actual) const {
+    const CFT *actualCmplxPtr = reinterpret_cast<const CFT *>(&actual);
+    const CFT *expectedCmplxPtr = reinterpret_cast<const CFT *>(&expected);
     CFT actualReal = actualCmplxPtr[0];
     CFT actualImag = actualCmplxPtr[1];
     CFT expectedReal = expectedCmplxPtr[0];
@@ -107,62 +110,69 @@ template <typename T, TestCond Condition> class CFPMatcher : public Matcher<T> {
             actualImagBits.uintval() != expectedImagBits.uintval());
   }
 
-  template <typename CFT> void explainErrorComplex() {
-    CFT *actualCmplxPtr = reinterpret_cast<CFT *>(&actual);
-    CFT *expectedCmplxPtr = reinterpret_cast<CFT *>(&expected);
+  template <typename CFT>
+  void explainErrorComplex(T actual, MatchResultListener *listener) const {
+    const CFT *actualCmplxPtr = reinterpret_cast<const CFT *>(&actual);
+    const CFT *expectedCmplxPtr = reinterpret_cast<const CFT *>(&expected);
     CFT actualReal = actualCmplxPtr[0];
     CFT actualImag = actualCmplxPtr[1];
     CFT expectedReal = expectedCmplxPtr[0];
     CFT expectedImag = expectedCmplxPtr[1];
-    tlog << "Expected complex floating point value: "
-         << str(fputil::FPBits<CFT>(expectedReal)) + " + " +
-                str(fputil::FPBits<CFT>(expectedImag)) + "i"
-         << '\n';
-    tlog << "Actual complex floating point value: "
-         << str(fputil::FPBits<CFT>(actualReal)) + " + " +
-                str(fputil::FPBits<CFT>(actualImag)) + "i"
-         << '\n';
+    *listener << "Expected complex floating point value: "
+              << str(fputil::FPBits<CFT>(expectedReal)) + " + " +
+                     str(fputil::FPBits<CFT>(expectedImag)) + "i"
+              << '\n'
+              << "Actual complex floating point value: "
+              << str(fputil::FPBits<CFT>(actualReal)) + " + " +
+                     str(fputil::FPBits<CFT>(actualImag)) + "i"
+              << '\n';
   }
 
-  bool match(T actualValue) {
-    actual = actualValue;
+  bool match(T actual) const {
 #ifndef LIBC_COMPILER_IS_MSVC
     if constexpr (cpp::is_complex_type_same<T, _Complex float>())
-      return matchComplex<float>();
+      return matchComplex<float>(actual);
     else if constexpr (cpp::is_complex_type_same<T, _Complex double>())
-      return matchComplex<double>();
+      return matchComplex<double>(actual);
     else if constexpr (cpp::is_complex_type_same<T, _Complex long double>())
-      return matchComplex<long double>();
+      return matchComplex<long double>(actual);
 #ifdef LIBC_TYPES_HAS_CFLOAT16
     else if constexpr (cpp::is_complex_type_same<T, cfloat16>())
-      return matchComplex<float16>();
+      return matchComplex<float16>(actual);
 #endif // LIBC_TYPES_HAS_CFLOAT16
 #ifdef LIBC_TYPES_HAS_CFLOAT128
     else if constexpr (cpp::is_complex_type_same<T, cfloat128>())
-      return matchComplex<float128>();
+      return matchComplex<float128>(actual);
 #endif // LIBC_TYPES_HAS_CFLOAT128
 #else  // LIBC_COMPILER_IS_MSVC
+    (void)actual;
     return true;
 #endif // LIBC_COMPILER_IS_MSVC
   }
 
-  void explainError() override {
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  bool MatchAndExplain(T actual, MatchResultListener *listener) const {
+    if (match(actual))
+      return true;
+    if (!listener->IsInterested())
+      return false;
 #ifndef LIBC_COMPILER_IS_MSVC
     if constexpr (cpp::is_complex_type_same<T, _Complex float>())
-      return explainErrorComplex<float>();
+      explainErrorComplex<float>(actual, listener);
     else if constexpr (cpp::is_complex_type_same<T, _Complex double>())
-      return explainErrorComplex<double>();
+      explainErrorComplex<double>(actual, listener);
     else if constexpr (cpp::is_complex_type_same<T, _Complex long double>())
-      return explainErrorComplex<long double>();
+      explainErrorComplex<long double>(actual, listener);
 #ifdef LIBC_TYPES_HAS_CFLOAT16
     else if constexpr (cpp::is_complex_type_same<T, cfloat16>())
-      return explainErrorComplex<float16>();
+      explainErrorComplex<float16>(actual, listener);
 #endif // LIBC_TYPES_HAS_CFLOAT16
 #ifdef LIBC_TYPES_HAS_CFLOAT128
     else if constexpr (cpp::is_complex_type_same<T, cfloat128>())
-      return explainErrorComplex<float128>();
+      explainErrorComplex<float128>(actual, listener);
 #endif // LIBC_TYPES_HAS_CFLOAT128
 #endif // LIBC_COMPILER_IS_MSVC
+    return false;
   }
 };
 
diff --git a/libc/test/UnitTest/LibcTest.cpp b/libc/test/UnitTest/LibcTest.cpp
index a00d0ff32f1153..6b767a0103f107 100644
--- a/libc/test/UnitTest/LibcTest.cpp
+++ b/libc/test/UnitTest/LibcTest.cpp
@@ -313,21 +313,12 @@ bool test_str_ne(const wchar_t *LHS, const wchar_t *RHS, const char *LHSStr,
                    RHSStr, Loc);
 }
 
-} // namespace internal
-
-bool Test::testMatch(bool MatchResult, MatcherBase &Matcher, const char *LHSStr,
-                     const char *RHSStr, internal::Location Loc) {
-  if (MatchResult)
-    return true;
-
-  internal::current_context->markFail();
-  if (!Matcher.is_silent()) {
-    tlog << Loc;
-    tlog << "Failed to match " << LHSStr << " against " << RHSStr << ".\n";
-    Matcher.explainError();
-  }
-  return false;
+void mark_match_failure(const char *LHSStr, const char *RHSStr, Location Loc) {
+  current_context->markFail();
+  tlog << Loc;
+  tlog << "Failed to match " << LHSStr << " against " << RHSStr << ".\n";
 }
 
+} // namespace internal
 } // namespace testing
 } // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/test/UnitTest/LibcTest.h b/libc/test/UnitTest/LibcTest.h
index f0a951bd5777fd..fa4117fb21b736 100644
--- a/libc/test/UnitTest/LibcTest.h
+++ b/libc/test/UnitTest/LibcTest.h
@@ -44,17 +44,42 @@ namespace testing {
 // conditions for such cases.
 enum class TestCond { EQ, NE, LT, LE, GT, GE };
 
-struct MatcherBase {
-  virtual ~MatcherBase() {}
-  virtual void explainError() { tlog << "unknown error\n"; }
-  // Override and return true to skip `explainError` step.
-  virtual bool is_silent() const { return false; }
+// Source-compatible with GoogleMock's ::testing::MatchResultListener so custom
+// matchers work unchanged under both LibcTest and GoogleTest.
+class MatchResultListener {
+  TestLogger *logger;
+
+public:
+  LIBC_INLINE explicit MatchResultListener(TestLogger *logger)
+      : logger(logger) {}
+
+  LIBC_INLINE TestLogger *stream() { return logger; }
+  LIBC_INLINE bool IsInterested() const { return logger != nullptr; }
+
+  template <typename T>
+  LIBC_INLINE MatchResultListener &operator<<(const T &val) {
+    if (logger != nullptr)
+      *logger << val;
+    return *this;
+  }
 };
 
-template <typename T> struct Matcher : public MatcherBase {
-  bool match(const T &t);
+struct MatcherBase {
+  using is_gtest_matcher = void;
+
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  template <typename Stream> LIBC_INLINE void DescribeTo(Stream *os) const {
+    *os << "matches";
+  }
+
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  template <typename Stream>
+  LIBC_INLINE void DescribeNegationTo(Stream *os) const {
+    *os << "does not match";
+  }
 };
 
+template <typename T> struct Matcher : public MatcherBase {};
 namespace internal {
 
 // A simple location object to allow consistent passing of __FILE__ and
@@ -177,6 +202,20 @@ bool test_str_ne(const char *LHS, const char *RHS, const char *LHSStr,
 bool test_str_ne(const wchar_t *LHS, const wchar_t *RHS, const char *LHSStr,
                  const char *RHSStr, internal::Location Loc);
 
+void mark_match_failure(const char *LHSStr, const char *RHSStr, Location Loc);
+
+template <typename MatcherT, typename ValType>
+LIBC_INLINE bool match_and_explain(const MatcherT &Matcher,
+                                   const ValType &Value, const char *MatcherStr,
+                                   const char *ValueStr, Location Loc) {
+  MatchResultListener NullListener(nullptr);
+  if (Matcher.MatchAndExplain(Value, &NullListener))
+    return true;
+  mark_match_failure(ValueStr, MatcherStr, Loc);
+  MatchResultListener Listener(&tlog);
+  Matcher.MatchAndExplain(Value, &Listener);
+  return false;
+}
 } // namespace internal
 
 struct TestOptions {
@@ -205,16 +244,6 @@ class Test {
 protected:
   static void addTest(Test *T);
 
-  bool testMatch(bool MatchResult, MatcherBase &Matcher, const char *LHSStr,
-                 const char *RHSStr, internal::Location Loc);
-
-  template <typename MatcherT, typename ValType>
-  bool matchAndExplain(MatcherT &&Matcher, ValType Value,
-                       const char *MatcherStr, const char *ValueStr,
-                       internal::Location Loc) {
-    return testMatch(Matcher.match(Value), Matcher, ValueStr, MatcherStr, Loc);
-  }
-
   bool testProcessExits(cpp::function_ref<void(void)> Func, int ExitCode,
                         const char *LHSStr, const char *RHSStr,
                         internal::Location Loc);
@@ -539,9 +568,10 @@ CString libc_make_test_file_path_func(const char *file_name);
 // Custom matcher checks.
 
 #define LIBC_TEST_MATCH_(MATCHER, MATCH, MATCHER_STR, MATCH_STR, RET_OR_EMPTY) \
-  LIBC_TEST_SCAFFOLDING_(matchAndExplain(MATCHER, MATCH, MATCHER_STR,          \
-                                         MATCH_STR, LIBC_TEST_LOC_()),         \
-                         RET_OR_EMPTY)
+  LIBC_TEST_SCAFFOLDING_(                                                      \
+      LIBC_NAMESPACE::testing::internal::match_and_explain(                    \
+          MATCHER, MATCH, MATCHER_STR, MATCH_STR, LIBC_TEST_LOC_()),           \
+      RET_OR_EMPTY)
 
 #define EXPECT_THAT(MATCH, MATCHER)                                            \
   LIBC_TEST_MATCH_(MATCHER, MATCH, #MATCHER, #MATCH, )
diff --git a/libc/test/UnitTest/MemoryMatcher.cpp b/libc/test/UnitTest/MemoryMatcher.cpp
index 405f226798f7a5..f42dd99255f9ee 100644
--- a/libc/test/UnitTest/MemoryMatcher.cpp
+++ b/libc/test/UnitTest/MemoryMatcher.cpp
@@ -14,8 +14,6 @@
 
 #if LIBC_TEST_HAS_MATCHERS()
 
-using LIBC_NAMESPACE::testing::tlog;
-
 namespace LIBC_NAMESPACE_DECL {
 namespace testing {
 
@@ -34,49 +32,42 @@ bool equals(const cpp::span<T> &Span1, const cpp::span<T> &Span2,
   return true;
 }
 
-bool MemoryMatcher::match(MemoryView actualValue) {
-  actual = actualValue;
-  return equals(expected, actual, mismatch_size, mismatch_index);
-}
-
-static void display(char C) {
-  const auto print = [](unsigned char i) {
-    tlog << LIBC_NAMESPACE::internal::toupper(
+static void display(MatchResultListener &listener, char C) {
+  const auto print = [&listener](unsigned char i) {
+    listener << LIBC_NAMESPACE::internal::toupper(
         LIBC_NAMESPACE::internal::int_to_b36_char(i));
   };
   print(static_cast<unsigned char>(C) / 16);
   print(static_cast<unsigned char>(C) & 15);
 }
 
-static void display(MemoryView View) {
+static void display(MatchResultListener &listener, MemoryView View) {
   for (auto C : View) {
-    tlog << ' ';
-    display(C);
+    listener << ' ';
+    display(listener, C);
   }
 }
 
-void MemoryMatcher::explainError() {
+bool MemoryMatcher::MatchAndExplain(MemoryView actual,
+                                    MatchResultListener *listener) const {
+  bool mismatch_size = false;
+  size_t mismatch_index = cpp::numeric_limits<size_t>::max();
+  if (equals(expected, actual, mismatch_size, mismatch_index))
+    return true;
+  if (!listener->IsInterested())
+    return false;
   if (mismatch_size) {
-    tlog << "Size mismatch :";
-    tlog << "expected : ";
-    tlog << expected.size();
-    tlog << '\n';
-    tlog << "actual   : ";
-    tlog << actual.size();
-    tlog << '\n';
+    *listener << "Size mismatch :expected : " << expected.size() << '\n'
+              << "actual   : " << actual.size() << '\n';
   } else {
-    tlog << "Mismatch at position : ";
-    tlog << mismatch_index;
-    tlog << " / ";
-    tlog << expected.size();
-    tlog << "\n";
-    tlog << "expected :";
-    display(expected);
-    tlog << '\n';
-    tlog << "actual   :";
-    display(actual);
-    tlog << '\n';
+    *listener << "Mismatch at position : " << mismatch_index << " / "
+              << expected.size() << "\nexpected :";
+    display(*listener, expected);
+    *listener << "\nactual   :";
+    display(*listener, actual);
+    *listener << '\n';
   }
+  return false;
 }
 
 } // namespace testing
diff --git a/libc/test/UnitTest/MemoryMatcher.h b/libc/test/UnitTest/MemoryMatcher.h
index cbbf3286c02acc..662d751f6603ed 100644
--- a/libc/test/UnitTest/MemoryMatcher.h
+++ b/libc/test/UnitTest/MemoryMatcher.h
@@ -47,16 +47,12 @@ namespace testing {
 
 class MemoryMatcher : public Matcher<MemoryView> {
   MemoryView expected;
-  MemoryView actual;
-  bool mismatch_size = false;
-  size_t mismatch_index = cpp::numeric_limits<size_t>::max();
 
 public:
   MemoryMatcher(MemoryView expectedValue) : expected(expectedValue) {}
 
-  bool match(MemoryView actualValue);
-
-  void explainError() override;
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  bool MatchAndExplain(MemoryView actual, MatchResultListener *listener) const;
 };
 
 } // namespace testing
diff --git a/libc/test/UnitTest/PrintfMatcher.cpp b/libc/test/UnitTest/PrintfMatcher.cpp
index 2fe3482ea54383..563f2dfc896460 100644
--- a/libc/test/UnitTest/PrintfMatcher.cpp
+++ b/libc/test/UnitTest/PrintfMatcher.cpp
@@ -30,19 +30,20 @@ namespace {
 #define IF_FLAG_SHOW_FLAG(flag_name)                                           \
   do {                                                                         \
     if ((form.flags & FormatFlags::flag_name) == FormatFlags::flag_name)       \
-      tlog << "\n\t\t" << #flag_name;                                          \
+      listener << "\n\t\t" << #flag_name;                                      \
   } while (false)
 #define CASE_LM(lm)                                                            \
   case (LengthModifier::lm):                                                   \
-    tlog << #lm;                                                               \
+    listener << #lm;                                                           \
     break
 #define CASE_LM_BIT_WIDTH(lm, bw)                                              \
   case (LengthModifier::lm):                                                   \
-    tlog << #lm << "\n\tbit width: :" << bw;                                   \
+    listener << #lm << "\n\tbit width: :" << bw;                               \
     break
 
-template <typename CharT> void display_impl(FormatSection<CharT> form) {
-  tlog << "Raw String (len " << form.raw_string.size() << "): \"";
+template <typename CharT>
+void display_impl(MatchResultListener &listener, FormatSection<CharT> form) {
+  listener << "Raw String (len " << form.raw_string.size() << "): \"";
   cpp::string raw_string_utf8;
   if constexpr (cpp::is_same_v<CharT, char>) {
     raw_string_utf8 = form.raw_string;
@@ -50,20 +51,20 @@ template <typename CharT> void display_impl(FormatSection<CharT> form) {
     raw_string_utf8 = try_convert_to_utf8(form.raw_string);
   }
   for (size_t i = 0; i < raw_string_utf8.size(); ++i) {
-    tlog << raw_string_utf8[i];
+    listener << raw_string_utf8[i];
   }
-  tlog << "\"";
+  listener << "\"";
   if (form.has_conv) {
-    tlog << "\n\tHas Conv\n\tFlags:";
+    listener << "\n\tHas Conv\n\tFlags:";
     IF_FLAG_SHOW_FLAG(LEFT_JUSTIFIED);
     IF_FLAG_SHOW_FLAG(FORCE_SIGN);
     IF_FLAG_SHOW_FLAG(SPACE_PREFIX);
     IF_FLAG_SHOW_FLAG(ALTERNATE_FORM);
     IF_FLAG_SHOW_FLAG(LEADING_ZEROES);
-    tlog << "\n";
-    tlog << "\tmin width: " << form.min_width << "\n";
-    tlog << "\tprecision: " << form.precision << "\n";
-    tlog << "\tlength modifier: ";
+    listener << "\n";
+    listener << "\tmin width: " << form.min_width << "\n";
+    listener << "\tprecision: " << form.precision << "\n";
+    listener << "\tlength modifier: ";
     switch (form.length_modifier) {
       CASE_LM(none);
       CASE_LM(l);
@@ -90,26 +91,28 @@ template <typename CharT> void display_impl(FormatSection<CharT> form) {
       conv_name_utf8 =
           try_convert_to_utf8(cpp::wstring_view(&form.conv_name, 1));
     }
-    tlog << "\n";
-    tlog << "\tconversion name: " << conv_name_utf8 << "\n";
+    listener << "\n";
+    listener << "\tconversion name: " << conv_name_utf8 << "\n";
     if (conv_name_utf8 == "p" || conv_name_utf8 == "n" || conv_name_utf8 == "s")
-      tlog << "\tpointer value: "
-           << int_to_hex<uintptr_t>(
-                  reinterpret_cast<uintptr_t>(form.conv_val_ptr))
-           << "\n";
+      listener << "\tpointer value: "
+               << int_to_hex<uintptr_t>(
+                      reinterpret_cast<uintptr_t>(form.conv_val_ptr))
+               << "\n";
     else if (conv_name_utf8 != "%")
-      tlog << "\tvalue: " << int_to_hex(form.conv_val_raw) << "\n";
+      listener << "\tvalue: " << int_to_hex(form.conv_val_raw) << "\n";
   }
 }
 
 } // anonymous namespace
 
-void display(const FormatSection<char> &format_section) {
-  display_impl(format_section);
+void display(MatchResultListener &listener,
+             const FormatSection<char> &format_section) {
+  display_impl(listener, format_section);
 }
 
-void display(const FormatSection<wchar_t> &format_section) {
-  display_impl(format_section);
+void display(MatchResultListener &listener,
+             const FormatSection<wchar_t> &format_section) {
+  display_impl(listener, format_section);
 }
 
 } // namespace testing
diff --git a/libc/test/UnitTest/PrintfMatcher.h b/libc/test/UnitTest/PrintfMatcher.h
index 656856e25b708f..0e191ae67f69e2 100644
--- a/libc/test/UnitTest/PrintfMatcher.h
+++ b/libc/test/UnitTest/PrintfMatcher.h
@@ -16,30 +16,32 @@
 namespace LIBC_NAMESPACE_DECL {
 namespace testing {
 
-void display(const printf_core::FormatSection<char> &format_section);
-void display(const printf_core::FormatSection<wchar_t> &format_section);
+void display(MatchResultListener &listener,
+             const printf_core::FormatSection<char> &format_section);
+void display(MatchResultListener &listener,
+             const printf_core::FormatSection<wchar_t> &format_section);
 
 template <typename CharT>
 class FormatSectionMatcher : public Matcher<printf_core::FormatSection<CharT>> {
   printf_core::FormatSection<CharT> expected;
-  printf_core::FormatSection<CharT> actual;
 
 public:
   FormatSectionMatcher(printf_core::FormatSection<CharT> expectedValue)
       : expected(expectedValue) {}
 
-  bool match(printf_core::FormatSection<CharT> actualValue) {
-    actual = actualValue;
-    return expected == actual;
-  }
-
-  void explainError() override {
-    tlog << "expected format section: ";
-    display(expected);
-    tlog << '\n';
-    tlog << "actual format section  : ";
-    display(actual);
-    tlog << '\n';
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  bool MatchAndExplain(const printf_core::FormatSection<CharT> &actual,
+                       MatchResultListener *listener) const {
+    if (expected == actual)
+      return true;
+    if (!listener->IsInterested())
+      return false;
+    *listener << "expected format section: ";
+    display(*listener, expected);
+    *listener << "\nactual format section  : ";
+    display(*listener, actual);
+    *listener << '\n';
+    return false;
   }
 };
 
diff --git a/libc/test/UnitTest/ScanfMatcher.cpp b/libc/test/UnitTest/ScanfMatcher.cpp
index d47ad71a3b6f42..2853578352ecda 100644
--- a/libc/test/UnitTest/ScanfMatcher.cpp
+++ b/libc/test/UnitTest/ScanfMatcher.cpp
@@ -23,36 +23,31 @@ using scanf_core::FormatFlags;
 using scanf_core::FormatSection;
 using scanf_core::LengthModifier;
 
-bool FormatSectionMatcher::match(FormatSection actualValue) {
-  actual = actualValue;
-  return expected == actual;
-}
-
 namespace {
 
 #define IF_FLAG_SHOW_FLAG(flag_name)                                           \
   do {                                                                         \
     if ((form.flags & FormatFlags::flag_name) == FormatFlags::flag_name)       \
-      tlog << "\n\t\t" << #flag_name;                                          \
+      listener << "\n\t\t" << #flag_name;                                      \
   } while (false)
 #define CASE_LM(lm)                                                            \
   case (LengthModifier::lm):                                                   \
-    tlog << #lm;                                                               \
+    listener << #lm;                                                           \
     break
 
-void display(FormatSection form) {
-  tlog << "Raw String (len " << form.raw_string.size() << "): \"";
+void display(MatchResultListener &listener, const FormatSection &form) {
+  listener << "Raw String (len " << form.raw_string.size() << "): \"";
   for (size_t i = 0; i < form.raw_string.size(); ++i) {
-    tlog << form.raw_string[i];
+    listener << form.raw_string[i];
   }
-  tlog << "\"";
+  listener << "\"";
   if (form.has_conv) {
-    tlog << "\n\tHas Conv\n\tFlags:";
+    listener << "\n\tHas Conv\n\tFlags:";
     IF_FLAG_SHOW_FLAG(NO_WRITE);
     IF_FLAG_SHOW_FLAG(ALLOCATE);
-    tlog << "\n";
-    tlog << "\tmax width: " << form.max_width << "\n";
-    tlog << "\tlength modifier: ";
+    listener << "\n";
+    listener << "\tmax width: " << form.max_width << "\n";
+    listener << "\tlength modifier: ";
     switch (form.length_modifier) {
       CASE_LM(NONE);
       CASE_LM(l);
@@ -64,38 +59,43 @@ void display(FormatSection form) {
       CASE_LM(t);
       CASE_LM(L);
     }
-    tlog << "\n";
+    listener << "\n";
     // If the pointer is used (NO_WRITE is not set and the conversion isn't %).
     if (((form.flags & FormatFlags::NO_WRITE) == 0) &&
         (form.conv_name != '%')) {
-      tlog << "\tpointer value: "
-           << int_to_hex<uintptr_t>(
-                  reinterpret_cast<uintptr_t>(form.output_ptr))
-           << "\n";
+      listener << "\tpointer value: "
+               << int_to_hex<uintptr_t>(
+                      reinterpret_cast<uintptr_t>(form.output_ptr))
+               << "\n";
     }
 
-    tlog << "\tconversion name: " << form.conv_name << "\n";
+    listener << "\tconversion name: " << form.conv_name << "\n";
 
     if (form.conv_name == '[') {
-      tlog << "\t\t";
+      listener << "\t\t";
       for (size_t i = 0; i < 256 /* char max */; ++i) {
         if (form.scan_set.test(i)) {
-          tlog << static_cast<char>(i);
+          listener << static_cast<char>(i);
         }
       }
-      tlog << "\n\t]\n";
+      listener << "\n\t]\n";
     }
   }
 }
 } // anonymous namespace
 
-void FormatSectionMatcher::explainError() {
-  tlog << "expected format section: ";
-  display(expected);
-  tlog << '\n';
-  tlog << "actual format section  : ";
-  display(actual);
-  tlog << '\n';
+bool FormatSectionMatcher::MatchAndExplain(
+    const FormatSection &actual, MatchResultListener *listener) const {
+  if (expected == actual)
+    return true;
+  if (!listener->IsInterested())
+    return false;
+  *listener << "expected format section: ";
+  display(*listener, expected);
+  *listener << "\nactual format section  : ";
+  display(*listener, actual);
+  *listener << '\n';
+  return false;
 }
 
 } // namespace testing
diff --git a/libc/test/UnitTest/ScanfMatcher.h b/libc/test/UnitTest/ScanfMatcher.h
index cb9d13f7572b75..393a2e666b667b 100644
--- a/libc/test/UnitTest/ScanfMatcher.h
+++ b/libc/test/UnitTest/ScanfMatcher.h
@@ -18,15 +18,14 @@ namespace testing {
 
 class FormatSectionMatcher : public Matcher<scanf_core::FormatSection> {
   scanf_core::FormatSection expected;
-  scanf_core::FormatSection actual;
 
 public:
   FormatSectionMatcher(scanf_core::FormatSection expectedValue)
       : expected(expectedValue) {}
 
-  bool match(scanf_core::FormatSection actualValue);
-
-  void explainError() override;
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  bool MatchAndExplain(const scanf_core::FormatSection &actual,
+                       MatchResultListener *listener) const;
 };
 
 } // namespace testing
diff --git a/libc/test/include/sys/queue_test.cpp b/libc/test/include/sys/queue_test.cpp
index ce3ae8e8f9810f..7028110beda6c8 100644
--- a/libc/test/include/sys/queue_test.cpp
+++ b/libc/test/include/sys/queue_test.cpp
@@ -7,6 +7,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "src/__support/CPP/string.h"
+#include "src/__support/CPP/string_view.h"
 #include "src/__support/char_vector.h"
 #include "src/__support/macros/config.h"
 #include "test/UnitTest/Test.h"
@@ -31,11 +32,17 @@ TEST(LlvmLibcQueueTest, SList) {
   struct Contains : public testing::Matcher<Head> {
     string s;
     Contains(string s) : s(s) {}
-    bool match(Head head) {
+    // NOLINTNEXTLINE(readability-identifier-naming)
+    bool MatchAndExplain(Head head,
+                         testing::MatchResultListener *listener) const {
       Entry *e;
       CharVector v;
       SLIST_FOREACH(e, &head, entries) { v.append(e->c); }
-      return s == v.c_str();
+      if (s == v.c_str())
+        return true;
+      *listener << "actual elements: "
+                << cpp::string_view(v.c_str(), v.length());
+      return false;
     }
   };
 
@@ -98,11 +105,17 @@ TEST(LlvmLibcQueueTest, STailQ) {
   struct Contains : public testing::Matcher<Head> {
     string s;
     Contains(string s) : s(s) {}
-    bool match(Head head) {
+    // NOLINTNEXTLINE(readability-identifier-naming)
+    bool MatchAndExplain(Head head,
+                         testing::MatchResultListener *listener) const {
       Entry *e;
       CharVector v;
       STAILQ_FOREACH(e, &head, entries) { v.append(e->c); }
-      return s == v.c_str();
+      if (s == v.c_str())
+        return true;
+      *listener << "actual elements: "
+                << cpp::string_view(v.c_str(), v.length());
+      return false;
     }
   };
 
diff --git a/libc/test/src/sys/socket/linux/socket_test_support.h b/libc/test/src/sys/socket/linux/socket_test_support.h
index b930f8723f0877..a643a85ac9ea57 100644
--- a/libc/test/src/sys/socket/linux/socket_test_support.h
+++ b/libc/test/src/sys/socket/linux/socket_test_support.h
@@ -80,8 +80,6 @@ struct SocketAddress {
 
 class SocketAddressMatcher : public Matcher<SocketAddress> {
   cpp::string_view expected_path;
-  struct sockaddr_un actual_addr;
-  socklen_t actual_addrlen;
 
   static constexpr size_t SUN_PATH_OFFSET =
       offsetof(struct sockaddr_un, sun_path);
@@ -89,55 +87,40 @@ class SocketAddressMatcher : public Matcher<SocketAddress> {
 public:
   explicit SocketAddressMatcher(cpp::string_view path) : expected_path(path) {}
 
-  bool match(const SocketAddress &actual) {
-    actual_addr = actual.addr;
-    actual_addrlen = actual.addrlen;
-    if (actual_addr.sun_family != AF_UNIX)
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  bool MatchAndExplain(const SocketAddress &actual,
+                       MatchResultListener *listener) const {
+    if (actual.addr.sun_family != AF_UNIX) {
+      *listener << "Expected address family to be AF_UNIX but got "
+                << actual.addr.sun_family << "\n";
       return false;
-    if (actual_addrlen > sizeof(actual_addr))
-      return false;
-    size_t expected_path_len = expected_path.size();
-    if (expected_path_len + 1 + SUN_PATH_OFFSET > actual_addrlen)
-      return false;
-    if (actual_addrlen < SUN_PATH_OFFSET)
-      return false;
-    cpp::string_view actual_path(
-        actual_addr.sun_path,
-        strnlen(actual_addr.sun_path, actual_addrlen - SUN_PATH_OFFSET));
-    return actual_path == expected_path;
-  }
-
-  void explainError() override {
-    if (actual_addr.sun_family != AF_UNIX) {
-      tlog << "Expected address family to be AF_UNIX but got "
-           << actual_addr.sun_family << "\n";
-      return;
     }
-    if (actual_addrlen > sizeof(actual_addr)) {
-      tlog << "Expected address length to be less than or equal to "
-           << sizeof(actual_addr) << " but got " << actual_addrlen << "\n";
-      return;
+    if (actual.addrlen > sizeof(actual.addr)) {
+      *listener << "Expected address length to be less than or equal to "
+                << sizeof(actual.addr) << " but got " << actual.addrlen << "\n";
+      return false;
     }
     size_t expected_path_len = expected_path.size();
-    if (expected_path_len + 1 + SUN_PATH_OFFSET > actual_addrlen) {
-      tlog << "Expected address length to be less than or equal to "
-           << expected_path_len + 1 + SUN_PATH_OFFSET << " but got "
-           << actual_addrlen << "\n";
-      return;
+    if (expected_path_len + 1 + SUN_PATH_OFFSET > actual.addrlen) {
+      *listener << "Expected address length to be less than or equal to "
+                << expected_path_len + 1 + SUN_PATH_OFFSET << " but got "
+                << actual.addrlen << "\n";
+      return false;
     }
-    if (actual_addrlen < SUN_PATH_OFFSET) {
-      tlog << "Expected address length to be greater than or equal to "
-           << SUN_PATH_OFFSET << " but got " << actual_addrlen << "\n";
-      return;
+    if (actual.addrlen < SUN_PATH_OFFSET) {
+      *listener << "Expected address length to be greater than or equal to "
+                << SUN_PATH_OFFSET << " but got " << actual.addrlen << "\n";
+      return false;
     }
     cpp::string_view actual_path(
-        actual_addr.sun_path,
-        strnlen(actual_addr.sun_path, actual_addrlen - SUN_PATH_OFFSET));
+        actual.addr.sun_path,
+        strnlen(actual.addr.sun_path, actual.addrlen - SUN_PATH_OFFSET));
     if (actual_path != expected_path) {
-      tlog << "Expected address path to be " << expected_path << " but got "
-           << actual_path << "\n";
-      return;
+      *listener << "Expected address path to be " << expected_path
+                << " but got " << actual_path << "\n";
+      return false;
     }
+    return true;
   }
 };
 
diff --git a/libc/test/src/time/TmMatcher.h b/libc/test/src/time/TmMatcher.h
index 5715a3c1203acc..aa7d4392e3a304 100644
--- a/libc/test/src/time/TmMatcher.h
+++ b/libc/test/src/time/TmMatcher.h
@@ -18,41 +18,36 @@ namespace testing {
 
 class StructTmMatcher : public Matcher<::tm> {
   ::tm expected;
-  ::tm actual;
 
-public:
-  StructTmMatcher(::tm expectedValue) : expected(expectedValue) {}
-
-  bool match(::tm actualValue) {
-    actual = actualValue;
-    return (actual.tm_sec == expected.tm_sec &&
-            actual.tm_min == expected.tm_min &&
-            actual.tm_hour == expected.tm_hour &&
-            actual.tm_mday == expected.tm_mday &&
-            actual.tm_mon == expected.tm_mon &&
-            actual.tm_year == expected.tm_year &&
-            actual.tm_wday == expected.tm_wday &&
-            actual.tm_yday == expected.tm_yday &&
-            actual.tm_isdst == expected.tm_isdst);
+  static void describeValue(MatchResultListener &listener, const char *label,
+                            const ::tm &value) {
+    listener << label << " sec: " << value.tm_sec << " min: " << value.tm_min
+             << " hour: " << value.tm_hour << " mday: " << value.tm_mday
+             << " mon: " << value.tm_mon << " year: " << value.tm_year
+             << " wday: " << value.tm_wday << " yday: " << value.tm_yday
+             << " isdst: " << value.tm_isdst << '\n';
   }
 
-  void describeValue(const char *label, ::tm value) {
-    tlog << label;
-    tlog << " sec: " << value.tm_sec;
-    tlog << " min: " << value.tm_min;
-    tlog << " hour: " << value.tm_hour;
-    tlog << " mday: " << value.tm_mday;
-    tlog << " mon: " << value.tm_mon;
-    tlog << " year: " << value.tm_year;
-    tlog << " wday: " << value.tm_wday;
-    tlog << " yday: " << value.tm_yday;
-    tlog << " isdst: " << value.tm_isdst;
-    tlog << '\n';
-  }
+public:
+  StructTmMatcher(::tm expectedValue) : expected(expectedValue) {}
 
-  void explainError() override {
-    describeValue("Expected tm_struct value: ", expected);
-    describeValue("  Actual tm_struct value: ", actual);
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  bool MatchAndExplain(const ::tm &actual,
+                       MatchResultListener *listener) const {
+    if (actual.tm_sec == expected.tm_sec && actual.tm_min == expected.tm_min &&
+        actual.tm_hour == expected.tm_hour &&
+        actual.tm_mday == expected.tm_mday &&
+        actual.tm_mon == expected.tm_mon &&
+        actual.tm_year == expected.tm_year &&
+        actual.tm_wday == expected.tm_wday &&
+        actual.tm_yday == expected.tm_yday &&
+        actual.tm_isdst == expected.tm_isdst)
+      return true;
+    if (!listener->IsInterested())
+      return false;
+    describeValue(*listener, "Expected tm_struct value: ", expected);
+    describeValue(*listener, "  Actual tm_struct value: ", actual);
+    return false;
   }
 };
 
diff --git a/libc/utils/MPCWrapper/MPCUtils.cpp b/libc/utils/MPCWrapper/MPCUtils.cpp
index 20e2637912ee04..0e51f66f402e22 100644
--- a/libc/utils/MPCWrapper/MPCUtils.cpp
+++ b/libc/utils/MPCWrapper/MPCUtils.cpp
@@ -235,7 +235,7 @@ template bool compare_unary_operation_single_output_different_type(
 template <typename InputType, typename OutputType>
 void explain_unary_operation_single_output_different_type_error(
     Operation op, InputType input, OutputType libc_result, double ulp_tolerance,
-    RoundingMode rounding) {
+    RoundingMode rounding, MatchResultListener *listener) {
 
   unsigned int precision =
       mpfr::get_precision<make_real_t<InputType>>(ulp_tolerance);
@@ -271,20 +271,22 @@ void explain_unary_operation_single_output_different_type_error(
       << '\n'
       << "  ULP error: " << mpfr_result.ulp_as_mpfr_number(libc_result).str()
       << '\n';
-  tlog << msg.str();
+  *listener << msg.str();
   mpc_clear(mpc_result_val);
   mpfr_clear(real);
 }
 
 template void explain_unary_operation_single_output_different_type_error(
-    Operation, _Complex float, float, double, RoundingMode);
+    Operation, _Complex float, float, double, RoundingMode,
+    MatchResultListener *);
 template void explain_unary_operation_single_output_different_type_error(
-    Operation, _Complex double, double, double, RoundingMode);
+    Operation, _Complex double, double, double, RoundingMode,
+    MatchResultListener *);
 
 template <typename InputType, typename OutputType>
 void explain_unary_operation_single_output_same_type_error(
     Operation op, InputType input, OutputType libc_result, double ulp_tolerance,
-    RoundingMode rounding) {
+    RoundingMode rounding, MatchResultListener *listener) {
 
   unsigned int precision =
       mpfr::get_precision<make_real_t<InputType>>(ulp_tolerance);
@@ -340,16 +342,18 @@ void explain_unary_operation_single_output_same_type_error(
                      .imag)
              .str()
       << '\n';
-  tlog << msg.str();
+  *listener << msg.str();
   mpc_clear(mpc_result_val);
   mpfr_clear(real);
   mpfr_clear(imag);
 }
 
 template void explain_unary_operation_single_output_same_type_error(
-    Operation, _Complex float, _Complex float, double, RoundingMode);
+    Operation, _Complex float, _Complex float, double, RoundingMode,
+    MatchResultListener *);
 template void explain_unary_operation_single_output_same_type_error(
-    Operation, _Complex double, _Complex double, double, RoundingMode);
+    Operation, _Complex double, _Complex double, double, RoundingMode,
+    MatchResultListener *);
 
 } // namespace internal
 
diff --git a/libc/utils/MPCWrapper/MPCUtils.h b/libc/utils/MPCWrapper/MPCUtils.h
index d4ab672bcddbe8..f2d9ebd6c699b1 100644
--- a/libc/utils/MPCWrapper/MPCUtils.h
+++ b/libc/utils/MPCWrapper/MPCUtils.h
@@ -96,23 +96,22 @@ bool compare_binary_operation_one_output(Operation op,
 template <typename InputType, typename OutputType>
 void explain_unary_operation_single_output_same_type_error(
     Operation op, InputType input, OutputType match_value, double ulp_tolerance,
-    RoundingMode rounding);
+    RoundingMode rounding, MatchResultListener *listener);
 
 template <typename InputType, typename OutputType>
 void explain_unary_operation_single_output_different_type_error(
     Operation op, InputType input, OutputType match_value, double ulp_tolerance,
-    RoundingMode rounding);
+    RoundingMode rounding, MatchResultListener *listener);
 
 template <typename InputType, typename OutputType>
 void explain_binary_operation_one_output_error(
     Operation op, const BinaryInput<InputType> &input, OutputType match_value,
-    double ulp_tolerance, RoundingMode rounding);
+    double ulp_tolerance, RoundingMode rounding, MatchResultListener *listener);
 
 template <Operation op, typename InputType, typename OutputType>
 class MPCMatcher : public testing::Matcher<OutputType> {
 private:
   InputType input;
-  OutputType match_value;
   double ulp_tolerance;
   RoundingMode rounding;
 
@@ -120,18 +119,21 @@ class MPCMatcher : public testing::Matcher<OutputType> {
   MPCMatcher(InputType testInput, double ulp_tolerance, RoundingMode rounding)
       : input(testInput), ulp_tolerance(ulp_tolerance), rounding(rounding) {}
 
-  bool match(OutputType libcResult) {
-    match_value = libcResult;
-    return match(input, match_value);
-  }
+  bool match(OutputType libcResult) const { return match(input, libcResult); }
 
-  void explainError() override { // NOLINT
-    explain_error(input, match_value);
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  bool MatchAndExplain(OutputType libcResult,
+                       MatchResultListener *listener) const {
+    if (match(libcResult))
+      return true;
+    if (listener->IsInterested())
+      explain_error(input, libcResult, listener);
+    return false;
   }
 
 private:
   template <typename InType, typename OutType>
-  bool match(InType in, OutType out) {
+  bool match(InType in, OutType out) const {
     if (cpp::is_same_v<InType, OutType>) {
       return compare_unary_operation_single_output_same_type(
           op, in, out, ulp_tolerance, rounding);
@@ -142,26 +144,28 @@ class MPCMatcher : public testing::Matcher<OutputType> {
   }
 
   template <typename T, typename U>
-  bool match(const BinaryInput<T> &in, U out) {
+  bool match(const BinaryInput<T> &in, U out) const {
     return compare_binary_operation_one_output(op, in, out, ulp_tolerance,
                                                rounding);
   }
 
   template <typename InType, typename OutType>
-  void explain_error(InType in, OutType out) {
+  void explain_error(InType in, OutType out,
+                     MatchResultListener *listener) const {
     if (cpp::is_same_v<InType, OutType>) {
       explain_unary_operation_single_output_same_type_error(
-          op, in, out, ulp_tolerance, rounding);
+          op, in, out, ulp_tolerance, rounding, listener);
     } else {
       explain_unary_operation_single_output_different_type_error(
-          op, in, out, ulp_tolerance, rounding);
+          op, in, out, ulp_tolerance, rounding, listener);
     }
   }
 
   template <typename T, typename U>
-  void explain_error(const BinaryInput<T> &in, U out) {
+  void explain_error(const BinaryInput<T> &in, U out,
+                     MatchResultListener *listener) const {
     explain_binary_operation_one_output_error(op, in, out, ulp_tolerance,
-                                              rounding);
+                                              rounding, listener);
   }
 };
 
diff --git a/libc/utils/MPFRWrapper/MPFRUtils.cpp b/libc/utils/MPFRWrapper/MPFRUtils.cpp
index fea8c5512977dc..5432c6504b8d68 100644
--- a/libc/utils/MPFRWrapper/MPFRUtils.cpp
+++ b/libc/utils/MPFRWrapper/MPFRUtils.cpp
@@ -202,10 +202,9 @@ ternary_operation_one_output(Operation op, InputType x, InputType y,
 // once at the end.  This will stop the error messages from interleaving when
 // the tests are running concurrently.
 template <typename InputType, typename OutputType>
-void explain_unary_operation_single_output_error(Operation op, InputType input,
-                                                 OutputType matchValue,
-                                                 double ulp_tolerance,
-                                                 RoundingMode rounding) {
+void explain_unary_operation_single_output_error(
+    Operation op, InputType input, OutputType matchValue, double ulp_tolerance,
+    RoundingMode rounding, MatchResultListener *listener) {
   unsigned int precision = get_precision<InputType>(ulp_tolerance);
   MPFRNumber mpfrInput(input, precision);
   MPFRNumber mpfr_result;
@@ -226,72 +225,76 @@ void explain_unary_operation_single_output_error(Operation op, InputType input,
       << '\n';
   if (msg.overflow())
     __builtin_unreachable();
-  tlog << msg.str();
+  *listener << msg.str();
 }
 
-template void explain_unary_operation_single_output_error(Operation op, float,
-                                                          float, double,
-                                                          RoundingMode);
-template void explain_unary_operation_single_output_error(Operation op, double,
-                                                          double, double,
-                                                          RoundingMode);
-template void explain_unary_operation_single_output_error(Operation op,
-                                                          long double,
-                                                          long double, double,
-                                                          RoundingMode);
-template void explain_unary_operation_single_output_error(Operation op, double,
-                                                          float, double,
-                                                          RoundingMode);
-template void explain_unary_operation_single_output_error(Operation op,
-                                                          long double, float,
-                                                          double, RoundingMode);
-template void explain_unary_operation_single_output_error(Operation op,
-                                                          long double, double,
-                                                          double, RoundingMode);
+template void explain_unary_operation_single_output_error(
+    Operation op, float, float, double, RoundingMode, MatchResultListener *);
+template void explain_unary_operation_single_output_error(
+    Operation op, double, double, double, RoundingMode, MatchResultListener *);
+template void
+explain_unary_operation_single_output_error(Operation op, long double,
+                                            long double, double, RoundingMode,
+                                            MatchResultListener *);
+template void explain_unary_operation_single_output_error(
+    Operation op, double, float, double, RoundingMode, MatchResultListener *);
+template void
+explain_unary_operation_single_output_error(Operation op, long double, float,
+                                            double, RoundingMode,
+                                            MatchResultListener *);
+template void
+explain_unary_operation_single_output_error(Operation op, long double, double,
+                                            double, RoundingMode,
+                                            MatchResultListener *);
 
 #ifdef LIBC_TYPES_HAS_FLOAT16
-template void explain_unary_operation_single_output_error(Operation op, float16,
-                                                          float16, double,
-                                                          RoundingMode);
-template void explain_unary_operation_single_output_error(Operation op, float,
-                                                          float16, double,
-                                                          RoundingMode);
-template void explain_unary_operation_single_output_error(Operation op, double,
-                                                          float16, double,
-                                                          RoundingMode);
-template void explain_unary_operation_single_output_error(Operation op,
-                                                          long double, float16,
-                                                          double, RoundingMode);
+template void
+explain_unary_operation_single_output_error(Operation op, float16, float16,
+                                            double, RoundingMode,
+                                            MatchResultListener *);
+template void explain_unary_operation_single_output_error(
+    Operation op, float, float16, double, RoundingMode, MatchResultListener *);
+template void explain_unary_operation_single_output_error(
+    Operation op, double, float16, double, RoundingMode, MatchResultListener *);
+template void
+explain_unary_operation_single_output_error(Operation op, long double, float16,
+                                            double, RoundingMode,
+                                            MatchResultListener *);
 #ifdef LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE
-template void explain_unary_operation_single_output_error(Operation op,
-                                                          float128, float16,
-                                                          double, RoundingMode);
+template void
+explain_unary_operation_single_output_error(Operation op, float128, float16,
+                                            double, RoundingMode,
+                                            MatchResultListener *);
 #endif // LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE
 #endif // LIBC_TYPES_HAS_FLOAT16
 
 #ifdef LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE
-template void explain_unary_operation_single_output_error(Operation op,
-                                                          float128, float128,
-                                                          double, RoundingMode);
-template void explain_unary_operation_single_output_error(Operation op,
-                                                          float128, float,
-                                                          double, RoundingMode);
-template void explain_unary_operation_single_output_error(Operation op,
-                                                          float128, double,
-                                                          double, RoundingMode);
-template void explain_unary_operation_single_output_error(Operation op,
-                                                          float128, long double,
-                                                          double, RoundingMode);
+template void
+explain_unary_operation_single_output_error(Operation op, float128, float128,
+                                            double, RoundingMode,
+                                            MatchResultListener *);
+template void explain_unary_operation_single_output_error(
+    Operation op, float128, float, double, RoundingMode, MatchResultListener *);
+template void
+explain_unary_operation_single_output_error(Operation op, float128, double,
+                                            double, RoundingMode,
+                                            MatchResultListener *);
+template void
+explain_unary_operation_single_output_error(Operation op, float128, long double,
+                                            double, RoundingMode,
+                                            MatchResultListener *);
 #endif // LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE
 
-template void explain_unary_operation_single_output_error(Operation op,
-                                                          bfloat16, bfloat16,
-                                                          double, RoundingMode);
+template void
+explain_unary_operation_single_output_error(Operation op, bfloat16, bfloat16,
+                                            double, RoundingMode,
+                                            MatchResultListener *);
 
 template <typename T>
 void explain_unary_operation_two_outputs_error(
     Operation op, T input, const BinaryOutput<T> &libc_result,
-    double ulp_tolerance, RoundingMode rounding) {
+    double ulp_tolerance, RoundingMode rounding,
+    MatchResultListener *listener) {
   unsigned int precision = get_precision<T>(ulp_tolerance);
   MPFRNumber mpfrInput(input, precision);
   int mpfrIntResult;
@@ -299,55 +302,61 @@ void explain_unary_operation_two_outputs_error(
                                                        precision, rounding);
 
   if (mpfrIntResult != libc_result.i) {
-    tlog << "MPFR integral result: " << mpfrIntResult << '\n'
-         << "Libc integral result: " << libc_result.i << '\n';
+    *listener << "MPFR integral result: " << mpfrIntResult << '\n'
+              << "Libc integral result: " << libc_result.i << '\n';
   } else {
-    tlog << "Integral result from libc matches integral result from MPFR.\n";
+    *listener
+        << "Integral result from libc matches integral result from MPFR.\n";
   }
 
   MPFRNumber mpfrMatchValue(libc_result.f);
-  tlog
+  *listener
       << "Libc floating point result is not within tolerance value of the MPFR "
       << "result.\n\n";
 
-  tlog << "            Input decimal: " << mpfrInput.str() << "\n\n";
+  *listener << "            Input decimal: " << mpfrInput.str() << "\n\n";
 
-  tlog << "Libc floating point value: " << mpfrMatchValue.str() << '\n';
-  tlog << " Libc floating point bits: " << str(FPBits<T>(libc_result.f))
-       << '\n';
-  tlog << "\n\n";
+  *listener << "Libc floating point value: " << mpfrMatchValue.str() << '\n';
+  *listener << " Libc floating point bits: " << str(FPBits<T>(libc_result.f))
+            << '\n';
+  *listener << "\n\n";
 
-  tlog << "              MPFR result: " << mpfr_result.str() << '\n';
-  tlog << "             MPFR rounded: " << str(FPBits<T>(mpfr_result.as<T>()))
-       << '\n';
-  tlog << '\n'
-       << "                ULP error: "
-       << mpfr_result.ulp_as_mpfr_number(libc_result.f).str() << '\n';
+  *listener << "              MPFR result: " << mpfr_result.str() << '\n';
+  *listener << "             MPFR rounded: "
+            << str(FPBits<T>(mpfr_result.as<T>())) << '\n';
+  *listener << '\n'
+            << "                ULP error: "
+            << mpfr_result.ulp_as_mpfr_number(libc_result.f).str() << '\n';
 }
 
 template void explain_unary_operation_two_outputs_error<float>(
-    Operation, float, const BinaryOutput<float> &, double, RoundingMode);
+    Operation, float, const BinaryOutput<float> &, double, RoundingMode,
+    MatchResultListener *);
 template void explain_unary_operation_two_outputs_error<double>(
-    Operation, double, const BinaryOutput<double> &, double, RoundingMode);
+    Operation, double, const BinaryOutput<double> &, double, RoundingMode,
+    MatchResultListener *);
 template void explain_unary_operation_two_outputs_error<long double>(
     Operation, long double, const BinaryOutput<long double> &, double,
-    RoundingMode);
+    RoundingMode, MatchResultListener *);
 #ifdef LIBC_TYPES_HAS_FLOAT16
 template void explain_unary_operation_two_outputs_error<float16>(
-    Operation, float16, const BinaryOutput<float16> &, double, RoundingMode);
+    Operation, float16, const BinaryOutput<float16> &, double, RoundingMode,
+    MatchResultListener *);
 #endif
 template void explain_unary_operation_two_outputs_error<bfloat16>(
-    Operation, bfloat16, const BinaryOutput<bfloat16> &, double, RoundingMode);
+    Operation, bfloat16, const BinaryOutput<bfloat16> &, double, RoundingMode,
+    MatchResultListener *);
 #ifdef LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE
 template void explain_unary_operation_two_outputs_error<float128>(
-    Operation, float128, const BinaryOutput<float128> &, double, RoundingMode);
+    Operation, float128, const BinaryOutput<float128> &, double, RoundingMode,
+    MatchResultListener *);
 #endif // LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE
 
 template <typename T>
 void explain_binary_operation_two_outputs_error(
     Operation op, const BinaryInput<T> &input,
     const BinaryOutput<T> &libc_result, double ulp_tolerance,
-    RoundingMode rounding) {
+    RoundingMode rounding, MatchResultListener *listener) {
   unsigned int precision = get_precision<T>(ulp_tolerance);
   MPFRNumber mpfrX(input.x, precision);
   MPFRNumber mpfrY(input.y, precision);
@@ -356,46 +365,49 @@ void explain_binary_operation_two_outputs_error(
       op, input.x, input.y, mpfrIntResult, precision, rounding);
   MPFRNumber mpfrMatchValue(libc_result.f);
 
-  tlog << "Input decimal: x: " << mpfrX.str() << " y: " << mpfrY.str() << '\n'
-       << "MPFR integral result: " << mpfrIntResult << '\n'
-       << "Libc integral result: " << libc_result.i << '\n'
-       << "Libc floating point result: " << mpfrMatchValue.str() << '\n'
-       << "               MPFR result: " << mpfr_result.str() << '\n';
-  tlog << "Libc floating point result bits: " << str(FPBits<T>(libc_result.f))
-       << '\n';
-  tlog << "              MPFR rounded bits: "
-       << str(FPBits<T>(mpfr_result.as<T>())) << '\n';
-  tlog << "ULP error: " << mpfr_result.ulp_as_mpfr_number(libc_result.f).str()
-       << '\n';
+  *listener << "Input decimal: x: " << mpfrX.str() << " y: " << mpfrY.str()
+            << '\n'
+            << "MPFR integral result: " << mpfrIntResult << '\n'
+            << "Libc integral result: " << libc_result.i << '\n'
+            << "Libc floating point result: " << mpfrMatchValue.str() << '\n'
+            << "               MPFR result: " << mpfr_result.str() << '\n';
+  *listener << "Libc floating point result bits: "
+            << str(FPBits<T>(libc_result.f)) << '\n';
+  *listener << "              MPFR rounded bits: "
+            << str(FPBits<T>(mpfr_result.as<T>())) << '\n';
+  *listener << "ULP error: "
+            << mpfr_result.ulp_as_mpfr_number(libc_result.f).str() << '\n';
 }
 
 template void explain_binary_operation_two_outputs_error<float>(
     Operation, const BinaryInput<float> &, const BinaryOutput<float> &, double,
-    RoundingMode);
+    RoundingMode, MatchResultListener *);
 template void explain_binary_operation_two_outputs_error<double>(
     Operation, const BinaryInput<double> &, const BinaryOutput<double> &,
-    double, RoundingMode);
+    double, RoundingMode, MatchResultListener *);
 template void explain_binary_operation_two_outputs_error<long double>(
     Operation, const BinaryInput<long double> &,
-    const BinaryOutput<long double> &, double, RoundingMode);
+    const BinaryOutput<long double> &, double, RoundingMode,
+    MatchResultListener *);
 #ifdef LIBC_TYPES_HAS_FLOAT16
 template void explain_binary_operation_two_outputs_error<float16>(
     Operation, const BinaryInput<float16> &, const BinaryOutput<float16> &,
-    double, RoundingMode);
+    double, RoundingMode, MatchResultListener *);
 #endif
 template void explain_binary_operation_two_outputs_error<bfloat16>(
     Operation, const BinaryInput<bfloat16> &, const BinaryOutput<bfloat16> &,
-    double, RoundingMode);
+    double, RoundingMode, MatchResultListener *);
 #ifdef LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE
 template void explain_binary_operation_two_outputs_error<float128>(
     Operation, const BinaryInput<float128> &, const BinaryOutput<float128> &,
-    double, RoundingMode);
+    double, RoundingMode, MatchResultListener *);
 #endif // LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE
 
 template <typename InputType, typename OutputType>
 void explain_binary_operation_one_output_error(
     Operation op, const BinaryInput<InputType> &input, OutputType libc_result,
-    double ulp_tolerance, RoundingMode rounding) {
+    double ulp_tolerance, RoundingMode rounding,
+    MatchResultListener *listener) {
   unsigned int precision = get_precision<InputType>(ulp_tolerance);
   MPFRNumber mpfrX(input.x, precision);
   MPFRNumber mpfrY(input.y, precision);
@@ -405,73 +417,87 @@ void explain_binary_operation_one_output_error(
       binary_operation_one_output(op, input.x, input.y, precision, rounding);
   MPFRNumber mpfrMatchValue(libc_result);
 
-  tlog << "Input decimal: x: " << mpfrX.str() << " y: " << mpfrY.str() << '\n';
-  tlog << "First input bits: " << str(FPBits<InputType>(input.x)) << '\n';
-  tlog << "Second input bits: " << str(FPBits<InputType>(input.y)) << '\n';
-
-  tlog << "Libc result: " << mpfrMatchValue.str() << '\n'
-       << "MPFR result: " << mpfr_result.str() << '\n';
-  tlog << "Libc floating point result bits: "
-       << str(FPBits<OutputType>(libc_result)) << '\n';
-  tlog << "              MPFR rounded bits: "
-       << str(FPBits<OutputType>(mpfr_result.as<OutputType>())) << '\n';
-  tlog << "ULP error: " << mpfr_result.ulp_as_mpfr_number(libc_result).str()
-       << '\n';
+  *listener << "Input decimal: x: " << mpfrX.str() << " y: " << mpfrY.str()
+            << '\n';
+  *listener << "First input bits: " << str(FPBits<InputType>(input.x)) << '\n';
+  *listener << "Second input bits: " << str(FPBits<InputType>(input.y)) << '\n';
+
+  *listener << "Libc result: " << mpfrMatchValue.str() << '\n'
+            << "MPFR result: " << mpfr_result.str() << '\n';
+  *listener << "Libc floating point result bits: "
+            << str(FPBits<OutputType>(libc_result)) << '\n';
+  *listener << "              MPFR rounded bits: "
+            << str(FPBits<OutputType>(mpfr_result.as<OutputType>())) << '\n';
+  *listener << "ULP error: "
+            << mpfr_result.ulp_as_mpfr_number(libc_result).str() << '\n';
 }
 
 template void
 explain_binary_operation_one_output_error(Operation, const BinaryInput<float> &,
-                                          float, double, RoundingMode);
+                                          float, double, RoundingMode,
+                                          MatchResultListener *);
 template void explain_binary_operation_one_output_error(
-    Operation, const BinaryInput<double> &, float, double, RoundingMode);
+    Operation, const BinaryInput<double> &, float, double, RoundingMode,
+    MatchResultListener *);
 template void explain_binary_operation_one_output_error(
-    Operation, const BinaryInput<double> &, double, double, RoundingMode);
+    Operation, const BinaryInput<double> &, double, double, RoundingMode,
+    MatchResultListener *);
 template void explain_binary_operation_one_output_error(
-    Operation, const BinaryInput<long double> &, float, double, RoundingMode);
+    Operation, const BinaryInput<long double> &, float, double, RoundingMode,
+    MatchResultListener *);
 template void explain_binary_operation_one_output_error(
-    Operation, const BinaryInput<long double> &, double, double, RoundingMode);
-template void
-explain_binary_operation_one_output_error(Operation,
-                                          const BinaryInput<long double> &,
-                                          long double, double, RoundingMode);
+    Operation, const BinaryInput<long double> &, double, double, RoundingMode,
+    MatchResultListener *);
+template void explain_binary_operation_one_output_error(
+    Operation, const BinaryInput<long double> &, long double, double,
+    RoundingMode, MatchResultListener *);
 #ifdef LIBC_TYPES_HAS_FLOAT16
 template void explain_binary_operation_one_output_error(
-    Operation, const BinaryInput<float16> &, float16, double, RoundingMode);
+    Operation, const BinaryInput<float16> &, float16, double, RoundingMode,
+    MatchResultListener *);
 template void
 explain_binary_operation_one_output_error(Operation, const BinaryInput<float> &,
-                                          float16, double, RoundingMode);
+                                          float16, double, RoundingMode,
+                                          MatchResultListener *);
 template void explain_binary_operation_one_output_error(
-    Operation, const BinaryInput<double> &, float16, double, RoundingMode);
+    Operation, const BinaryInput<double> &, float16, double, RoundingMode,
+    MatchResultListener *);
 template void explain_binary_operation_one_output_error(
-    Operation, const BinaryInput<long double> &, float16, double, RoundingMode);
+    Operation, const BinaryInput<long double> &, float16, double, RoundingMode,
+    MatchResultListener *);
 #endif
 #if defined(LIBC_TYPES_HAS_NATIVE_FLOAT128) &&                                 \
     defined(LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE)
 template void explain_binary_operation_one_output_error(
-    Operation, const BinaryInput<float128> &, float128, double, RoundingMode);
+    Operation, const BinaryInput<float128> &, float128, double, RoundingMode,
+    MatchResultListener *);
 #endif
 template void explain_binary_operation_one_output_error(
-    Operation, const BinaryInput<bfloat16> &, bfloat16, double, RoundingMode);
+    Operation, const BinaryInput<bfloat16> &, bfloat16, double, RoundingMode,
+    MatchResultListener *);
 template void
 explain_binary_operation_one_output_error(Operation, const BinaryInput<float> &,
-                                          bfloat16, double, RoundingMode);
+                                          bfloat16, double, RoundingMode,
+                                          MatchResultListener *);
 template void explain_binary_operation_one_output_error(
-    Operation, const BinaryInput<double> &, bfloat16, double, RoundingMode);
-template void
-explain_binary_operation_one_output_error(Operation,
-                                          const BinaryInput<long double> &,
-                                          bfloat16, double, RoundingMode);
+    Operation, const BinaryInput<double> &, bfloat16, double, RoundingMode,
+    MatchResultListener *);
+template void explain_binary_operation_one_output_error(
+    Operation, const BinaryInput<long double> &, bfloat16, double, RoundingMode,
+    MatchResultListener *);
 #if defined(LIBC_TYPES_HAS_NATIVE_FLOAT128) &&                                 \
     defined(LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE)
 template void explain_binary_operation_one_output_error(
-    Operation, const BinaryInput<float128> &, bfloat16, double, RoundingMode);
+    Operation, const BinaryInput<float128> &, bfloat16, double, RoundingMode,
+    MatchResultListener *);
 #endif // defined(LIBC_TYPES_HAS_NATIVE_FLOAT128) &&
        // defined(LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE)
 
 template <typename InputType, typename OutputType>
 void explain_ternary_operation_one_output_error(
     Operation op, const TernaryInput<InputType> &input, OutputType libc_result,
-    double ulp_tolerance, RoundingMode rounding) {
+    double ulp_tolerance, RoundingMode rounding,
+    MatchResultListener *listener) {
   unsigned int precision = get_precision<InputType>(ulp_tolerance);
   MPFRNumber mpfrX(input.x, precision);
   MPFRNumber mpfrY(input.y, precision);
@@ -483,64 +509,73 @@ void explain_ternary_operation_one_output_error(
       op, input.x, input.y, input.z, precision, rounding);
   MPFRNumber mpfrMatchValue(libc_result);
 
-  tlog << "Input decimal: x: " << mpfrX.str() << " y: " << mpfrY.str()
-       << " z: " << mpfrZ.str() << '\n';
-  tlog << " First input bits: " << str(FPBits<InputType>(input.x)) << '\n';
-  tlog << "Second input bits: " << str(FPBits<InputType>(input.y)) << '\n';
-  tlog << " Third input bits: " << str(FPBits<InputType>(input.z)) << '\n';
-
-  tlog << "Libc result: " << mpfrMatchValue.str() << '\n'
-       << "MPFR result: " << mpfr_result.str() << '\n';
-  tlog << "Libc floating point result bits: "
-       << str(FPBits<OutputType>(libc_result)) << '\n';
-  tlog << "              MPFR rounded bits: "
-       << str(FPBits<OutputType>(mpfr_result.as<OutputType>())) << '\n';
-  tlog << "ULP error: " << mpfr_result.ulp_as_mpfr_number(libc_result).str()
-       << '\n';
+  *listener << "Input decimal: x: " << mpfrX.str() << " y: " << mpfrY.str()
+            << " z: " << mpfrZ.str() << '\n';
+  *listener << " First input bits: " << str(FPBits<InputType>(input.x)) << '\n';
+  *listener << "Second input bits: " << str(FPBits<InputType>(input.y)) << '\n';
+  *listener << " Third input bits: " << str(FPBits<InputType>(input.z)) << '\n';
+
+  *listener << "Libc result: " << mpfrMatchValue.str() << '\n'
+            << "MPFR result: " << mpfr_result.str() << '\n';
+  *listener << "Libc floating point result bits: "
+            << str(FPBits<OutputType>(libc_result)) << '\n';
+  *listener << "              MPFR rounded bits: "
+            << str(FPBits<OutputType>(mpfr_result.as<OutputType>())) << '\n';
+  *listener << "ULP error: "
+            << mpfr_result.ulp_as_mpfr_number(libc_result).str() << '\n';
 }
 
 template void explain_ternary_operation_one_output_error(
-    Operation, const TernaryInput<float> &, float, double, RoundingMode);
+    Operation, const TernaryInput<float> &, float, double, RoundingMode,
+    MatchResultListener *);
 template void explain_ternary_operation_one_output_error(
-    Operation, const TernaryInput<double> &, float, double, RoundingMode);
+    Operation, const TernaryInput<double> &, float, double, RoundingMode,
+    MatchResultListener *);
 template void explain_ternary_operation_one_output_error(
-    Operation, const TernaryInput<double> &, double, double, RoundingMode);
+    Operation, const TernaryInput<double> &, double, double, RoundingMode,
+    MatchResultListener *);
 template void explain_ternary_operation_one_output_error(
-    Operation, const TernaryInput<long double> &, float, double, RoundingMode);
+    Operation, const TernaryInput<long double> &, float, double, RoundingMode,
+    MatchResultListener *);
 template void explain_ternary_operation_one_output_error(
-    Operation, const TernaryInput<long double> &, double, double, RoundingMode);
-template void
-explain_ternary_operation_one_output_error(Operation,
-                                           const TernaryInput<long double> &,
-                                           long double, double, RoundingMode);
+    Operation, const TernaryInput<long double> &, double, double, RoundingMode,
+    MatchResultListener *);
+template void explain_ternary_operation_one_output_error(
+    Operation, const TernaryInput<long double> &, long double, double,
+    RoundingMode, MatchResultListener *);
 
 #ifdef LIBC_TYPES_HAS_FLOAT16
 template void explain_ternary_operation_one_output_error(
-    Operation, const TernaryInput<float16> &, float16, double, RoundingMode);
+    Operation, const TernaryInput<float16> &, float16, double, RoundingMode,
+    MatchResultListener *);
 template void explain_ternary_operation_one_output_error(
-    Operation, const TernaryInput<float> &, float16, double, RoundingMode);
+    Operation, const TernaryInput<float> &, float16, double, RoundingMode,
+    MatchResultListener *);
 template void explain_ternary_operation_one_output_error(
-    Operation, const TernaryInput<double> &, float16, double, RoundingMode);
-template void
-explain_ternary_operation_one_output_error(Operation,
-                                           const TernaryInput<long double> &,
-                                           float16, double, RoundingMode);
+    Operation, const TernaryInput<double> &, float16, double, RoundingMode,
+    MatchResultListener *);
+template void explain_ternary_operation_one_output_error(
+    Operation, const TernaryInput<long double> &, float16, double, RoundingMode,
+    MatchResultListener *);
 #endif
 
 template void explain_ternary_operation_one_output_error(
-    Operation, const TernaryInput<bfloat16> &, bfloat16, double, RoundingMode);
+    Operation, const TernaryInput<bfloat16> &, bfloat16, double, RoundingMode,
+    MatchResultListener *);
 template void explain_ternary_operation_one_output_error(
-    Operation, const TernaryInput<float> &, bfloat16, double, RoundingMode);
+    Operation, const TernaryInput<float> &, bfloat16, double, RoundingMode,
+    MatchResultListener *);
 template void explain_ternary_operation_one_output_error(
-    Operation, const TernaryInput<double> &, bfloat16, double, RoundingMode);
-template void
-explain_ternary_operation_one_output_error(Operation,
-                                           const TernaryInput<long double> &,
-                                           bfloat16, double, RoundingMode);
+    Operation, const TernaryInput<double> &, bfloat16, double, RoundingMode,
+    MatchResultListener *);
+template void explain_ternary_operation_one_output_error(
+    Operation, const TernaryInput<long double> &, bfloat16, double,
+    RoundingMode, MatchResultListener *);
 #if defined(LIBC_TYPES_HAS_NATIVE_FLOAT128) &&                                 \
     defined(LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE)
 template void explain_ternary_operation_one_output_error(
-    Operation, const TernaryInput<float128> &, bfloat16, double, RoundingMode);
+    Operation, const TernaryInput<float128> &, bfloat16, double, RoundingMode,
+    MatchResultListener *);
 #endif // defined(LIBC_TYPES_HAS_NATIVE_FLOAT128) &&
        // defined(LIBC_TYPES_FLOAT128_IS_NOT_LONG_DOUBLE)
 
diff --git a/libc/utils/MPFRWrapper/MPFRUtils.h b/libc/utils/MPFRWrapper/MPFRUtils.h
index 84e59674295f57..6add66c42f432d 100644
--- a/libc/utils/MPFRWrapper/MPFRUtils.h
+++ b/libc/utils/MPFRWrapper/MPFRUtils.h
@@ -205,31 +205,31 @@ template <typename InputType, typename OutputType>
 void explain_unary_operation_single_output_error(Operation op, InputType input,
                                                  OutputType match_value,
                                                  double ulp_tolerance,
-                                                 RoundingMode rounding);
+                                                 RoundingMode rounding,
+                                                 MatchResultListener *listener);
 template <typename T>
 void explain_unary_operation_two_outputs_error(
     Operation op, T input, const BinaryOutput<T> &match_value,
-    double ulp_tolerance, RoundingMode rounding);
+    double ulp_tolerance, RoundingMode rounding, MatchResultListener *listener);
 template <typename T>
 void explain_binary_operation_two_outputs_error(
     Operation op, const BinaryInput<T> &input,
     const BinaryOutput<T> &match_value, double ulp_tolerance,
-    RoundingMode rounding);
+    RoundingMode rounding, MatchResultListener *listener);
 
 template <typename InputType, typename OutputType>
 void explain_binary_operation_one_output_error(
     Operation op, const BinaryInput<InputType> &input, OutputType match_value,
-    double ulp_tolerance, RoundingMode rounding);
+    double ulp_tolerance, RoundingMode rounding, MatchResultListener *listener);
 
 template <typename InputType, typename OutputType>
 void explain_ternary_operation_one_output_error(
     Operation op, const TernaryInput<InputType> &input, OutputType match_value,
-    double ulp_tolerance, RoundingMode rounding);
+    double ulp_tolerance, RoundingMode rounding, MatchResultListener *listener);
 
 template <Operation op, bool silent, typename InputType, typename OutputType>
 class MPFRMatcher : public testing::Matcher<OutputType> {
   InputType input;
-  OutputType match_value;
   double ulp_tolerance;
   RoundingMode rounding;
 
@@ -237,77 +237,83 @@ class MPFRMatcher : public testing::Matcher<OutputType> {
   MPFRMatcher(InputType testInput, double ulp_tolerance, RoundingMode rounding)
       : input(testInput), ulp_tolerance(ulp_tolerance), rounding(rounding) {}
 
-  bool match(OutputType libcResult) {
-    match_value = libcResult;
-    return match(input, match_value);
+  bool match(OutputType libcResult) const { return match(input, libcResult); }
+
+  // NOLINTNEXTLINE(readability-identifier-naming)
+  bool MatchAndExplain(OutputType libcResult,
+                       MatchResultListener *listener) const {
+    if (match(libcResult))
+      return true;
+    if constexpr (!silent) {
+      if (listener->IsInterested())
+        explain_error(input, libcResult, listener);
+    }
+    return false;
   }
 
-  // This method is marked with NOLINT because the name `explainError` does not
-  // conform to the coding style.
-  void explainError() override { // NOLINT
-    explain_error(input, match_value);
-  }
-
-  // Whether the `explainError` step is skipped or not.
-  bool is_silent() const override { return silent; }
-
 private:
   template <typename InType, typename OutType>
-  bool match(InType in, OutType out) {
+  bool match(InType in, OutType out) const {
     return compare_unary_operation_single_output(op, in, out, ulp_tolerance,
                                                  rounding);
   }
 
-  template <typename T> bool match(T in, const BinaryOutput<T> &out) {
+  template <typename T> bool match(T in, const BinaryOutput<T> &out) const {
     return compare_unary_operation_two_outputs(op, in, out, ulp_tolerance,
                                                rounding);
   }
 
   template <typename T, typename U>
-  bool match(const BinaryInput<T> &in, U out) {
+  bool match(const BinaryInput<T> &in, U out) const {
     return compare_binary_operation_one_output(op, in, out, ulp_tolerance,
                                                rounding);
   }
 
   template <typename T>
-  bool match(BinaryInput<T> in, const BinaryOutput<T> &out) {
+  bool match(BinaryInput<T> in, const BinaryOutput<T> &out) const {
     return compare_binary_operation_two_outputs(op, in, out, ulp_tolerance,
                                                 rounding);
   }
 
   template <typename InType, typename OutType>
-  bool match(const TernaryInput<InType> &in, OutType out) {
+  bool match(const TernaryInput<InType> &in, OutType out) const {
     return compare_ternary_operation_one_output(op, in, out, ulp_tolerance,
                                                 rounding);
   }
 
   template <typename InType, typename OutType>
-  void explain_error(InType in, OutType out) {
+  void explain_error(InType in, OutType out,
+                     MatchResultListener *listener) const {
     explain_unary_operation_single_output_error(op, in, out, ulp_tolerance,
-                                                rounding);
+                                                rounding, listener);
   }
 
-  template <typename T> void explain_error(T in, const BinaryOutput<T> &out) {
+  template <typename T>
+  void explain_error(T in, const BinaryOutput<T> &out,
+                     MatchResultListener *listener) const {
     explain_unary_operation_two_outputs_error(op, in, out, ulp_tolerance,
-                                              rounding);
+                                              rounding, listener);
   }
 
   template <typename T>
-  void explain_error(const BinaryInput<T> &in, const BinaryOutput<T> &out) {
+  void explain_error(const BinaryInput<T> &in, const BinaryOutput<T> &out,
+                     MatchResultListener *listener) const {
     explain_binary_operation_two_outputs_error(op, in, out, ulp_tolerance,
-                                               rounding);
+                                               rounding, listener);
   }
 
   template <typename T, typename U>
-  void explain_error(const BinaryInput<T> &in, U out) {
+  void explain_error(const BinaryInput<T> &in, U out,
+                     MatchResultListener *listener) const {
     explain_binary_operation_one_output_error(op, in, out, ulp_tolerance,
-                                              rounding);
+                                              rounding, listener);
   }
 
   template <typename InType, typename OutType>
-  void explain_error(const TernaryInput<InType> &in, OutType out) {
+  void explain_error(const TernaryInput<InType> &in, OutType out,
+                     MatchResultListener *listener) const {
     explain_ternary_operation_one_output_error(op, in, out, ulp_tolerance,
-                                               rounding);
+                                               rounding, listener);
   }
 };
 



More information about the libc-commits mailing list