1 //===-- FPExceptMatcher.h ---------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_LIBC_UTILS_UNITTEST_FPEXCEPTMATCHER_H
10 #define LLVM_LIBC_UTILS_UNITTEST_FPEXCEPTMATCHER_H
11 
12 #ifndef LLVM_LIBC_TEST_USE_FUCHSIA
13 
14 #include "utils/UnitTest/Test.h"
15 
16 namespace __llvm_libc {
17 namespace fputil {
18 namespace testing {
19 
20 // TODO: Make the matcher match specific exceptions instead of just identifying
21 // that an exception was raised.
22 class FPExceptMatcher : public __llvm_libc::testing::Matcher<bool> {
23   bool exceptionRaised;
24 
25 public:
26   class FunctionCaller {
27   public:
~FunctionCaller()28     virtual ~FunctionCaller(){};
29     virtual void call() = 0;
30   };
31 
getFunctionCaller(Func func)32   template <typename Func> static FunctionCaller *getFunctionCaller(Func func) {
33     struct Callable : public FunctionCaller {
34       Func f;
35       explicit Callable(Func theFunc) : f(theFunc) {}
36       void call() override { f(); }
37     };
38 
39     return new Callable(func);
40   }
41 
42   // Takes ownership of func.
43   explicit FPExceptMatcher(FunctionCaller *func);
44 
match(bool unused)45   bool match(bool unused) { return exceptionRaised; }
46 
explainError(testutils::StreamWrapper & stream)47   void explainError(testutils::StreamWrapper &stream) override {
48     stream << "A floating point exception should have been raised but it "
49            << "wasn't\n";
50   }
51 };
52 
53 } // namespace testing
54 } // namespace fputil
55 } // namespace __llvm_libc
56 
57 #define ASSERT_RAISES_FP_EXCEPT(func)                                          \
58   ASSERT_THAT(                                                                 \
59       true,                                                                    \
60       __llvm_libc::fputil::testing::FPExceptMatcher(                           \
61           __llvm_libc::fputil::testing::FPExceptMatcher::getFunctionCaller(    \
62               func)))
63 #else
64 #define ASSERT_RAISES_FP_EXCEPT(func) ASSERT_DEATH(func, WITH_SIGNAL(SIGFPE))
65 #endif // LLVM_LIBC_TEST_USE_FUCHSIA
66 
67 #endif // LLVM_LIBC_UTILS_UNITTEST_FPEXCEPTMATCHER_H
68