// Copyright Catch2 Authors // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // SPDX-License-Identifier: BSL-1.0 // Catch3 v0.4.0, on the Catch2 v3.16.1 engine // ---------------------------------------------------------- // This file is an amalgamation of multiple different files. // You probably shouldn't edit it directly. // // The parts that come from src/Progmasoft, the Catch3 runner, keep // their own copyright and license lines (LGPL-3.0-or-later). The // runner needs C++17. // ---------------------------------------------------------- #ifndef CATCH_AMALGAMATED_HPP_INCLUDED #define CATCH_AMALGAMATED_HPP_INCLUDED /** \file * This is a convenience header for Catch2. It includes **all** of Catch2 headers. * * Generally the Catch2 users should use specific includes they need, * but this header can be used instead for ease-of-experimentation, or * just plain convenience, at the cost of (significantly) increased * compilation times. * * When a new header is added to either the top level folder, or to the * corresponding internal subfolder, it should be added here. Headers * added to the various subparts (e.g. matchers, generators, etc...), * should go their respective catch-all headers. */ #include #include #include #include #include // Detect a number of compiler features - by compiler // The following features are defined: // // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled? // **************** // Note to maintainers: if new toggles are added please document them // in configuration.md, too // **************** // In general each macro has a _NO_ form // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature. // Many features, at point of detection, define an _INTERNAL_ macro, so they // can be combined, en-mass, with the _NO_ forms later. // See e.g.: // https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html #ifdef __APPLE__ # ifndef __has_extension # define __has_extension(x) 0 # endif # include # if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \ (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1) # define CATCH_PLATFORM_MAC # elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1) # define CATCH_PLATFORM_IPHONE # endif #elif defined(linux) || defined(__linux) || defined(__linux__) # define CATCH_PLATFORM_LINUX #elif defined(__QNX__) # define CATCH_PLATFORM_QNX #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) # define CATCH_PLATFORM_WINDOWS # if defined( WINAPI_FAMILY ) && ( WINAPI_FAMILY == WINAPI_FAMILY_APP ) # define CATCH_PLATFORM_WINDOWS_UWP # endif #elif defined(__ORBIS__) || defined(__PROSPERO__) # define CATCH_PLATFORM_PLAYSTATION #endif #if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) # define CATCH_CPP17_OR_GREATER #endif #if (__cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) # define CATCH_CPP20_OR_GREATER #endif // Matchers are only constexpr-able in C++20 #if defined( CATCH_CPP20_OR_GREATER ) && \ defined( __cpp_constexpr_dynamic_alloc ) && \ __cpp_constexpr_dynamic_alloc >= 201907L && \ /* GCC < 13 define the feature macro, but compiler bugs stop us from using it */ \ ( !defined( __GNUC__ ) || __GNUC__ >= 13 || defined(__clang__) ) # define CATCH_INTERNAL_CONSTEXPR_MATCHERS_ENABLED # define CATCH_DESTRUCTOR_CONSTEXPR constexpr #else # define CATCH_DESTRUCTOR_CONSTEXPR #endif // Only GCC compiler should be used in this block, so other compilers trying to // mask themselves as GCC should be ignored. #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__) && !defined(__NVCOMPILER) # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) // This only works on GCC 9+. so we have to also add a global suppression of Wparentheses // for older versions of GCC. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ _Pragma( "GCC diagnostic ignored \"-Wparentheses\"" ) # define CATCH_INTERNAL_SUPPRESS_UNUSED_RESULT \ _Pragma( "GCC diagnostic ignored \"-Wunused-result\"" ) # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \ _Pragma( "GCC diagnostic ignored \"-Wunused-variable\"" ) # define CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \ _Pragma( "GCC diagnostic ignored \"-Wuseless-cast\"" ) # define CATCH_INTERNAL_SUPPRESS_SHADOW_WARNINGS \ _Pragma( "GCC diagnostic ignored \"-Wshadow\"" ) # define CATCH_INTERNAL_CONFIG_USE_BUILTIN_CONSTANT_P #endif #if defined(__NVCOMPILER) # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "diag push" ) # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "diag pop" ) # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS _Pragma( "diag_suppress declared_but_not_referenced" ) #endif #if defined(__CUDACC__) && !defined(__clang__) # ifdef __NVCC_DIAG_PRAGMA_SUPPORT__ // New pragmas introduced in CUDA 11.5+ # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "nv_diagnostic push" ) # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "nv_diagnostic pop" ) # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS _Pragma( "nv_diag_suppress 177" ) # else # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS _Pragma( "diag_suppress 177" ) # endif #endif // clang-cl defines _MSC_VER as well as __clang__, which could cause the // start/stop internal suppression macros to be double defined. #if defined(__clang__) && !defined(_MSC_VER) # define CATCH_INTERNAL_CONFIG_USE_BUILTIN_CONSTANT_P # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) #endif // __clang__ && !_MSC_VER #if defined(__clang__) # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) # if (__clang_major__ >= 20) # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wvariadic-macro-arguments-omitted\"" ) # elif (__clang_major__ == 19) # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wc++20-extensions\"" ) # else # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) # endif # if ( __clang_major__ >= 22 ) # define CATCH_INTERNAL_SUPPRESS_COUNTER_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wc2y-extensions\"" ) # endif # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) # define CATCH_INTERNAL_SUPPRESS_COMMA_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wcomma\"" ) # define CATCH_INTERNAL_SUPPRESS_SHADOW_WARNINGS \ _Pragma( "clang diagnostic ignored \"-Wshadow\"" ) #endif // __clang__ // As of this writing, IBM XL's implementation of __builtin_constant_p has a bug // which results in calls to destructors being emitted for each temporary, // without a matching initialization. In practice, this can result in something // like `std::string::~string` being called on an uninitialized value. // // For example, this code will likely segfault under IBM XL: // ``` // REQUIRE(std::string("12") + "34" == "1234") // ``` // // Similarly, NVHPC's implementation of `__builtin_constant_p` has a bug which // results in calls to the immediately evaluated lambda expressions to be // reported as unevaluated lambdas. // https://developer.nvidia.com/nvidia_bug/3321845. // // Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented. #if defined( __ibmxl__ ) || defined( __CUDACC__ ) || defined( __NVCOMPILER ) # define CATCH_INTERNAL_CONFIG_NO_USE_BUILTIN_CONSTANT_P #endif //////////////////////////////////////////////////////////////////////////////// // We know some environments not to support full POSIX signals #if defined( CATCH_PLATFORM_WINDOWS ) || \ defined( CATCH_PLATFORM_PLAYSTATION ) || \ defined( __CYGWIN__ ) || \ defined( __QNX__ ) || \ defined( __EMSCRIPTEN__ ) || \ defined( __DJGPP__ ) || \ defined( __OS400__ ) # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS #else # define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS #endif //////////////////////////////////////////////////////////////////////////////// // Assume that some platforms do not support getenv. #if defined( CATCH_PLATFORM_WINDOWS_UWP ) || \ defined( CATCH_PLATFORM_PLAYSTATION ) || \ defined( _GAMING_XBOX ) # define CATCH_INTERNAL_CONFIG_NO_GETENV #else # define CATCH_INTERNAL_CONFIG_GETENV #endif //////////////////////////////////////////////////////////////////////////////// // Android somehow still does not support std::to_string #if defined(__ANDROID__) # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING #endif //////////////////////////////////////////////////////////////////////////////// // Not all Windows environments support SEH properly #if defined(__MINGW32__) # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH #endif //////////////////////////////////////////////////////////////////////////////// // PS4 #if defined(__ORBIS__) # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE #endif //////////////////////////////////////////////////////////////////////////////// // Cygwin #ifdef __CYGWIN__ // Required for some versions of Cygwin to declare gettimeofday // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin # define _BSD_SOURCE // some versions of cygwin (most) do not support std::to_string. Use the libstd check. // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING # endif #endif // __CYGWIN__ //////////////////////////////////////////////////////////////////////////////// // Visual C++ #if defined(_MSC_VER) && !defined(__clang__) // We want to defer to nvcc-specific warning suppression if we are compiled // with nvcc masquerading for MSVC. # if !defined( __CUDACC__ ) # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ __pragma( warning( push ) ) # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ __pragma( warning( pop ) ) # endif // Suppress MSVC C++ Core Guidelines checker warning 26426: // "Global initializer calls a non-constexpr function (i.22)" # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ __pragma( warning( disable : 26426 ) ) // Universal Windows platform does not support SEH # if !defined(CATCH_PLATFORM_WINDOWS_UWP) # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH # endif // Only some Windows platform families support the console # if defined(WINAPI_FAMILY_PARTITION) # if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_SYSTEM) # define CATCH_INTERNAL_CONFIG_NO_COLOUR_WIN32 # endif # endif // MSVC traditional preprocessor needs some workaround for __VA_ARGS__ // _MSVC_TRADITIONAL == 0 means new conformant preprocessor // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor # if !defined(__clang__) // Handle Clang masquerading for msvc # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR # endif // MSVC_TRADITIONAL # endif // __clang__ #endif // _MSC_VER #if defined(_REENTRANT) || defined(_MSC_VER) // Enable async processing, as -pthread is specified or no additional linking is required # define CATCH_INTERNAL_CONFIG_USE_ASYNC #endif // _MSC_VER //////////////////////////////////////////////////////////////////////////////// // Check if we are compiled with -fno-exceptions or equivalent #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED #endif //////////////////////////////////////////////////////////////////////////////// // Embarcadero C++Build #if defined(__BORLANDC__) #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN #endif //////////////////////////////////////////////////////////////////////////////// // RTX is a special version of Windows that is real time. // This means that it is detected as Windows, but does not provide // the same set of capabilities as real Windows does. #if defined(UNDER_RTSS) || defined(RTX64_BUILD) #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH #define CATCH_INTERNAL_CONFIG_NO_ASYNC #define CATCH_INTERNAL_CONFIG_NO_COLOUR_WIN32 #endif #if !defined(_GLIBCXX_USE_C99_MATH_TR1) #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER #endif // Various stdlib support checks that require __has_include #if defined(__has_include) // Check if string_view is available and usable #if __has_include() && defined(CATCH_CPP17_OR_GREATER) # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW #endif // Check if optional is available and usable # if __has_include() && defined(CATCH_CPP17_OR_GREATER) # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) // Check if byte is available and usable # if __has_include() && defined(CATCH_CPP17_OR_GREATER) # include # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0) # define CATCH_INTERNAL_CONFIG_CPP17_BYTE # endif # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) // Check if variant is available and usable # if __has_include() && defined(CATCH_CPP17_OR_GREATER) # if defined(__clang__) && (__clang_major__ < 8) // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 // fix should be in clang 8, workaround in libstdc++ 8.2 # include # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) # define CATCH_CONFIG_NO_CPP17_VARIANT # else # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) # else # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT # endif // defined(__clang__) && (__clang_major__ < 8) # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) #endif // defined(__has_include) #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) # define CATCH_CONFIG_WINDOWS_SEH #endif // This is set by default, because we assume that unix compilers are posix-signal-compatible by default. #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) # define CATCH_CONFIG_POSIX_SIGNALS #endif #if defined(CATCH_INTERNAL_CONFIG_GETENV) && !defined(CATCH_INTERNAL_CONFIG_NO_GETENV) && !defined(CATCH_CONFIG_NO_GETENV) && !defined(CATCH_CONFIG_GETENV) # define CATCH_CONFIG_GETENV #endif #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) # define CATCH_CONFIG_CPP11_TO_STRING #endif #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) # define CATCH_CONFIG_CPP17_OPTIONAL #endif #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) # define CATCH_CONFIG_CPP17_STRING_VIEW #endif #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) # define CATCH_CONFIG_CPP17_VARIANT #endif #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) # define CATCH_CONFIG_CPP17_BYTE #endif #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE #endif #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) # define CATCH_CONFIG_NEW_CAPTURE #endif #if !defined( CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED ) && \ !defined( CATCH_CONFIG_DISABLE_EXCEPTIONS ) && \ !defined( CATCH_CONFIG_NO_DISABLE_EXCEPTIONS ) # define CATCH_CONFIG_DISABLE_EXCEPTIONS #endif #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) # define CATCH_CONFIG_POLYFILL_ISNAN #endif #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) # define CATCH_CONFIG_USE_ASYNC #endif #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) # define CATCH_CONFIG_GLOBAL_NEXTAFTER #endif // The goal of this macro is to avoid evaluation of the arguments, but // still have the compiler warn on problems inside... #if defined( CATCH_INTERNAL_CONFIG_USE_BUILTIN_CONSTANT_P ) && \ !defined( CATCH_INTERNAL_CONFIG_NO_USE_BUILTIN_CONSTANT_P ) && !defined(CATCH_CONFIG_USE_BUILTIN_CONSTANT_P) #define CATCH_CONFIG_USE_BUILTIN_CONSTANT_P #endif #if defined( CATCH_CONFIG_USE_BUILTIN_CONSTANT_P ) && \ !defined( CATCH_CONFIG_NO_USE_BUILTIN_CONSTANT_P ) # define CATCH_INTERNAL_IGNORE_BUT_WARN( ... ) \ (void)__builtin_constant_p( __VA_ARGS__ ) /* NOLINT(cppcoreguidelines-pro-type-vararg, \ hicpp-vararg) */ #else # define CATCH_INTERNAL_IGNORE_BUT_WARN( ... ) #endif // Even if we do not think the compiler has that warning, we still have // to provide a macro that can be used by the code. #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION #endif #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION #endif #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_RESULT) # define CATCH_INTERNAL_SUPPRESS_UNUSED_RESULT #endif #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS #endif #if !defined( CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS ) # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS #endif #if !defined( CATCH_INTERNAL_SUPPRESS_COMMA_WARNINGS ) # define CATCH_INTERNAL_SUPPRESS_COMMA_WARNINGS #endif #if !defined( CATCH_INTERNAL_SUPPRESS_SHADOW_WARNINGS ) # define CATCH_INTERNAL_SUPPRESS_SHADOW_WARNINGS #endif #if !defined( CATCH_INTERNAL_SUPPRESS_COUNTER_WARNINGS ) # define CATCH_INTERNAL_SUPPRESS_COUNTER_WARNINGS #endif #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS #elif defined(__clang__) && (__clang_major__ < 5) # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS #endif #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) #define CATCH_TRY if ((true)) #define CATCH_CATCH_ALL if ((false)) #define CATCH_CATCH_ANON(type) if ((false)) #else #define CATCH_TRY try #define CATCH_CATCH_ALL catch (...) #define CATCH_CATCH_ANON(type) catch (type) #endif #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #endif #if defined( CATCH_PLATFORM_WINDOWS ) && \ !defined( CATCH_CONFIG_COLOUR_WIN32 ) && \ !defined( CATCH_CONFIG_NO_COLOUR_WIN32 ) && \ !defined( CATCH_INTERNAL_CONFIG_NO_COLOUR_WIN32 ) # define CATCH_CONFIG_COLOUR_WIN32 #endif #if defined( CATCH_CONFIG_SHARED_LIBRARY ) && defined( _MSC_VER ) && \ !defined( CATCH_CONFIG_STATIC ) # ifdef Catch2_EXPORTS # define CATCH_EXPORT //__declspec( dllexport ) // not needed # else # define CATCH_EXPORT __declspec( dllimport ) # endif #else # define CATCH_EXPORT #endif /** \file * Wrapper for the WCHAR configuration option * * We want to support platforms that do not provide `wchar_t`, so we * sometimes have to disable providing wchar_t overloads through Catch2, * e.g. the StringMaker specialization for `std::wstring`. */ // We assume that WCHAR should be enabled by default, and only disabled // for a shortlist (so far only DJGPP) of compilers. #if defined(__DJGPP__) # define CATCH_INTERNAL_CONFIG_NO_WCHAR #endif // __DJGPP__ #if !defined( CATCH_INTERNAL_CONFIG_NO_WCHAR ) && \ !defined( CATCH_CONFIG_NO_WCHAR ) && \ !defined( CATCH_CONFIG_WCHAR ) # define CATCH_CONFIG_WCHAR #endif namespace Catch { namespace Detail { //! Deriving classes become noncopyable and nonmovable class NonCopyable { public: NonCopyable( NonCopyable const& ) = delete; NonCopyable( NonCopyable&& ) = delete; NonCopyable& operator=( NonCopyable const& ) = delete; NonCopyable& operator=( NonCopyable&& ) = delete; protected: NonCopyable() noexcept = default; }; } // namespace Detail } // namespace Catch #include #include #include #include namespace Catch { class ReusableStringStream : Detail::NonCopyable { std::size_t m_index; std::ostream* m_oss; public: ReusableStringStream(); ~ReusableStringStream(); //! Returns the serialized state std::string str() const; //! Sets internal state to `str` void str(std::string const& str); #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic push // Old versions of GCC do not understand -Wnonnull-compare #pragma GCC diagnostic ignored "-Wpragmas" // Streaming a function pointer triggers Waddress and Wnonnull-compare // on GCC, because it implicitly converts it to bool and then decides // that the check it uses (a? true : false) is tautological and cannot // be null... #pragma GCC diagnostic ignored "-Waddress" #pragma GCC diagnostic ignored "-Wnonnull-compare" #elif defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpointer-bool-conversion" #pragma clang diagnostic ignored "-Wmicrosoft-cast" #endif template auto operator << ( T const& value ) -> ReusableStringStream& { *m_oss << value; return *this; } #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic pop #elif defined(__clang__) #pragma clang diagnostic pop #endif auto get() -> std::ostream& { return *m_oss; } }; } namespace Catch { namespace Detail { template struct make_void { using type = void; }; template using void_t = typename make_void::type; } // namespace Detail } // namespace Catch #if !defined( __has_cpp_attribute ) # define CATCH_ATTR_LIFETIMEBOUND #elif __has_cpp_attribute( msvc::lifetimebound ) # define CATCH_ATTR_LIFETIMEBOUND [[msvc::lifetimebound]] #elif __has_cpp_attribute( clang::lifetimebound ) # define CATCH_ATTR_LIFETIMEBOUND [[clang::lifetimebound]] #elif __has_cpp_attribute( lifetimebound ) # define CATCH_ATTR_LIFETIMEBOUND [[lifetimebound]] #else # define CATCH_ATTR_LIFETIMEBOUND #endif #include #include #include #include #include namespace Catch { /// A non-owning string class (similar to the forthcoming std::string_view) /// Note that, because a StringRef may be a substring of another string, /// it may not be null terminated. class StringRef { public: using size_type = std::size_t; using const_iterator = const char*; static constexpr size_type npos{ static_cast( -1 ) }; private: static constexpr char const* const s_empty = ""; char const* m_start = s_empty; size_type m_size = 0; public: // construction constexpr StringRef() noexcept = default; StringRef( char const* rawChars CATCH_ATTR_LIFETIMEBOUND ) noexcept; constexpr StringRef( char const* rawChars CATCH_ATTR_LIFETIMEBOUND, size_type size ) noexcept : m_start( rawChars ), m_size( size ) {} StringRef( std::string const& stdString CATCH_ATTR_LIFETIMEBOUND ) noexcept : m_start( stdString.c_str() ), m_size( stdString.size() ) {} explicit operator std::string() const { return std::string(m_start, m_size); } public: // operators auto operator == ( StringRef other ) const noexcept -> bool { return m_size == other.m_size && (std::memcmp( m_start, other.m_start, m_size ) == 0); } auto operator != (StringRef other) const noexcept -> bool { return !(*this == other); } constexpr auto operator[] ( size_type index ) const noexcept -> char { assert(index < m_size); return m_start[index]; } bool operator<(StringRef rhs) const noexcept; public: // named queries constexpr auto empty() const noexcept -> bool { return m_size == 0; } constexpr auto size() const noexcept -> size_type { return m_size; } // Returns a substring of [start, start + length). // If start + length > size(), then the substring is [start, size()). // If start > size(), then the substring is empty. constexpr StringRef substr(size_type start, size_type length) const noexcept { if (start < m_size) { const auto shortened_size = m_size - start; return StringRef(m_start + start, (shortened_size < length) ? shortened_size : length); } else { return StringRef(); } } // Returns the current start pointer. May not be null-terminated. constexpr char const* data() const noexcept CATCH_ATTR_LIFETIMEBOUND { return m_start; } constexpr const_iterator begin() const { return m_start; } constexpr const_iterator end() const { return m_start + m_size; } friend std::string& operator += (std::string& lhs, StringRef rhs); friend std::ostream& operator << (std::ostream& os, StringRef str); friend std::string operator+(StringRef lhs, StringRef rhs); /** * Provides a three-way comparison with rhs * * Returns negative number if lhs < rhs, 0 if lhs == rhs, and a positive * number if lhs > rhs */ int compare( StringRef rhs ) const; }; constexpr auto operator ""_sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { return StringRef( rawChars, size ); } } // namespace Catch constexpr auto operator ""_catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { return Catch::StringRef( rawChars, size ); } #include #include #include namespace Catch { namespace Detail { struct EnumInfo { StringRef m_name; std::vector> m_values; StringRef lookup( int64_t value ) const; }; EnumInfo makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector const& values ); template Detail::EnumInfo makeEnumInfo( StringRef enumName, StringRef allEnums, std::initializer_list values ) { static_assert( sizeof( int64_t ) >= sizeof( E ), "Cannot serialize enum to int64_t" ); std::vector intValues; intValues.reserve( values.size() ); for ( auto enumValue : values ) intValues.push_back( static_cast( enumValue ) ); return makeEnumInfo( enumName, allEnums, intValues ); } std::vector parseEnums( StringRef enums ); } // namespace Detail } // namespace Catch #ifdef CATCH_CONFIG_CPP17_STRING_VIEW #include #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless #endif // We need a dummy global operator<< so we can bring it into Catch namespace later struct Catch_global_namespace_dummy{}; std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy); namespace Catch { // Bring in global namespace operator<< for ADL lookup in // `IsStreamInsertable` below. using ::operator<<; namespace Detail { std::size_t catch_strnlen(const char *str, std::size_t n); std::string formatTimeT( std::time_t time ); constexpr StringRef unprintableString = "{?}"_sr; //! Encases `string in quotes, and optionally escapes invisibles std::string convertIntoString( StringRef string, bool escapeInvisibles ); //! Encases `string` in quotes, and escapes invisibles if user requested //! it via CLI std::string convertIntoString( StringRef string ); std::string rawMemoryToString( const void *object, std::size_t size ); template std::string rawMemoryToString( const T& object ) { return rawMemoryToString( &object, sizeof(object) ); } template static constexpr bool IsStreamInsertable_v = false; template static constexpr bool IsStreamInsertable_v< T, decltype( void( std::declval() << std::declval() ) )> = true; template std::string convertUnknownEnumToString( E e ); template std::enable_if_t< !std::is_enum::value && !std::is_base_of::value, std::string> convertUnstreamable( T const& ) { return std::string(Detail::unprintableString); } template std::enable_if_t< !std::is_enum::value && std::is_base_of::value, std::string> convertUnstreamable(T const& ex) { return ex.what(); } template std::enable_if_t< std::is_enum::value, std::string> convertUnstreamable( T const& value ) { return convertUnknownEnumToString( value ); } #if defined(_MANAGED) //! Convert a CLR string to a utf8 std::string template std::string clrReferenceToString( T^ ref ) { if (ref == nullptr) return std::string("null"); auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString()); cli::pin_ptr p = &bytes[0]; return std::string(reinterpret_cast(p), bytes->Length); } #endif } // namespace Detail template struct StringMaker { template static std::enable_if_t<::Catch::Detail::IsStreamInsertable_v, std::string> convert(const Fake& value) { ReusableStringStream rss; // NB: call using the function-like syntax to avoid ambiguity with // user-defined templated operator<< under clang. rss.operator<<(value); return rss.str(); } template static std::enable_if_t, std::string> convert( const Fake& value ) { #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER) return Detail::convertUnstreamable(value); #else return CATCH_CONFIG_FALLBACK_STRINGIFIER(value); #endif } }; namespace Detail { std::string makeExceptionHappenedString(); // This function dispatches all stringification requests inside of Catch. // Should be preferably called fully qualified, like ::Catch::Detail::stringify template std::string stringify( const T& e ) { CATCH_TRY { return ::Catch::StringMaker< std::remove_cv_t>>::convert( e ); } CATCH_CATCH_ALL { return makeExceptionHappenedString(); } } template std::string convertUnknownEnumToString( E e ) { return ::Catch::Detail::stringify(static_cast>(e)); } #if defined(_MANAGED) template std::string stringify( T^ e ) { return ::Catch::StringMaker::convert(e); } #endif } // namespace Detail // Some predefined specializations template<> struct StringMaker { static std::string convert(const std::string& str); }; #ifdef CATCH_CONFIG_CPP17_STRING_VIEW template<> struct StringMaker { static std::string convert(std::string_view str); }; #endif template<> struct StringMaker { static std::string convert(char const * str); }; template<> struct StringMaker { static std::string convert(char * str); }; #if defined(CATCH_CONFIG_WCHAR) template<> struct StringMaker { static std::string convert(const std::wstring& wstr); }; # ifdef CATCH_CONFIG_CPP17_STRING_VIEW template<> struct StringMaker { static std::string convert(std::wstring_view str); }; # endif template<> struct StringMaker { static std::string convert(wchar_t const * str); }; template<> struct StringMaker { static std::string convert(wchar_t * str); }; #endif // CATCH_CONFIG_WCHAR template struct StringMaker { static std::string convert(char const* str) { return Detail::convertIntoString( StringRef( str, Detail::catch_strnlen( str, SZ ) ) ); } }; template struct StringMaker { static std::string convert(signed char const* str) { auto reinterpreted = reinterpret_cast(str); return Detail::convertIntoString( StringRef(reinterpreted, Detail::catch_strnlen(reinterpreted, SZ))); } }; template struct StringMaker { static std::string convert(unsigned char const* str) { auto reinterpreted = reinterpret_cast(str); return Detail::convertIntoString( StringRef(reinterpreted, Detail::catch_strnlen(reinterpreted, SZ))); } }; #if defined(CATCH_CONFIG_CPP17_BYTE) template<> struct StringMaker { static std::string convert(std::byte value); }; #endif // defined(CATCH_CONFIG_CPP17_BYTE) template<> struct StringMaker { static std::string convert(int value); }; template<> struct StringMaker { static std::string convert(long value); }; template<> struct StringMaker { static std::string convert(long long value); }; template<> struct StringMaker { static std::string convert(unsigned int value); }; template<> struct StringMaker { static std::string convert(unsigned long value); }; template<> struct StringMaker { static std::string convert(unsigned long long value); }; template<> struct StringMaker { static std::string convert(bool b) { using namespace std::string_literals; return b ? "true"s : "false"s; } }; template<> struct StringMaker { static std::string convert(char c); }; template<> struct StringMaker { static std::string convert(signed char value); }; template<> struct StringMaker { static std::string convert(unsigned char value); }; template<> struct StringMaker { static std::string convert(std::nullptr_t) { using namespace std::string_literals; return "nullptr"s; } }; template<> struct StringMaker { static std::string convert(float value); CATCH_EXPORT static int precision; }; template<> struct StringMaker { static std::string convert(double value); CATCH_EXPORT static int precision; }; template struct StringMaker { template static std::string convert(U* p) { if (p) { return ::Catch::Detail::rawMemoryToString(p); } else { return "nullptr"; } } }; template struct StringMaker { static std::string convert(R C::* p) { if (p) { return ::Catch::Detail::rawMemoryToString(p); } else { return "nullptr"; } } }; #if defined(_MANAGED) template struct StringMaker { static std::string convert( T^ ref ) { return ::Catch::Detail::clrReferenceToString(ref); } }; #endif namespace Detail { template std::string rangeToString(InputIterator first, Sentinel last) { ReusableStringStream rss; rss << "{ "; if (first != last) { rss << ::Catch::Detail::stringify(*first); for (++first; first != last; ++first) rss << ", " << ::Catch::Detail::stringify(*first); } rss << " }"; return rss.str(); } } } // namespace Catch ////////////////////////////////////////////////////// // Separate std-lib types stringification, so it can be selectively enabled // This means that we do not bring in their headers #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS) # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER #endif // Separate std::pair specialization #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER) #include namespace Catch { template struct StringMaker > { static std::string convert(const std::pair& pair) { ReusableStringStream rss; rss << "{ " << ::Catch::Detail::stringify(pair.first) << ", " << ::Catch::Detail::stringify(pair.second) << " }"; return rss.str(); } }; } #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER #if defined( CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER ) && \ defined( CATCH_CONFIG_CPP17_OPTIONAL ) && \ /* P3168 turned optional into a range, making this ambiguous with the range support */ \ !defined( __cpp_lib_optional_range_support ) #include namespace Catch { template struct StringMaker > { static std::string convert(const std::optional& optional) { if (optional.has_value()) { return ::Catch::Detail::stringify(*optional); } else { return "{ }"; } } }; template <> struct StringMaker { static std::string convert(const std::nullopt_t&) { return "{ }"; } }; } #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER // Separate std::tuple specialization #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER) # include # include namespace Catch { namespace Detail { template void PrintTuple( const Tuple& tuple, std::ostream& os, std::index_sequence ) { // 1 + Account for when the tuple is empty char a[1 + sizeof...( Is )] = { ( ( os << ( Is ? ", " : " " ) << ::Catch::Detail::stringify( std::get( tuple ) ) ), '\0' )... }; (void)a; } } // namespace Detail template struct StringMaker> { static std::string convert( const std::tuple& tuple ) { ReusableStringStream rss; rss << '{'; Detail::PrintTuple( tuple, rss.get(), std::make_index_sequence{} ); rss << " }"; return rss.str(); } }; } // namespace Catch #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT) #include namespace Catch { template<> struct StringMaker { static std::string convert(const std::monostate&) { return "{ }"; } }; template struct StringMaker> { static std::string convert(const std::variant& variant) { if (variant.valueless_by_exception()) { return "{valueless variant}"; } else { return std::visit( [](const auto& value) { return ::Catch::Detail::stringify(value); }, variant ); } } }; } #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER namespace Catch { // Import begin/ end from std here using std::begin; using std::end; namespace Detail { template struct is_range_impl : std::false_type {}; template struct is_range_impl()))>> : std::true_type {}; } // namespace Detail template struct is_range : Detail::is_range_impl {}; #if defined(_MANAGED) // Managed types are never ranges template struct is_range { static const bool value = false; }; #endif template std::string rangeToString( Range const& range ) { return ::Catch::Detail::rangeToString( begin( range ), end( range ) ); } // Handle vector specially template std::string rangeToString( std::vector const& v ) { ReusableStringStream rss; rss << "{ "; bool first = true; for( bool b : v ) { if( first ) first = false; else rss << ", "; rss << ::Catch::Detail::stringify( b ); } rss << " }"; return rss.str(); } template struct StringMaker::value && !::Catch::Detail::IsStreamInsertable_v>> { static std::string convert( R const& range ) { return rangeToString( range ); } }; template struct StringMaker { static std::string convert(T const(&arr)[SZ]) { return rangeToString(arr); } }; } // namespace Catch // Separate std::chrono::duration specialization #include #include #include namespace Catch { template struct ratio_string { static std::string symbol() { Catch::ReusableStringStream rss; rss << '[' << Ratio::num << '/' << Ratio::den << ']'; return rss.str(); } }; template <> struct ratio_string { static char symbol() { return 'a'; } }; template <> struct ratio_string { static char symbol() { return 'f'; } }; template <> struct ratio_string { static char symbol() { return 'p'; } }; template <> struct ratio_string { static char symbol() { return 'n'; } }; template <> struct ratio_string { static char symbol() { return 'u'; } }; template <> struct ratio_string { static char symbol() { return 'm'; } }; //////////// // std::chrono::duration specializations template struct StringMaker> { static std::string convert(std::chrono::duration const& duration) { ReusableStringStream rss; rss << duration.count() << ' ' << ratio_string::symbol() << 's'; return rss.str(); } }; template struct StringMaker>> { static std::string convert(std::chrono::duration> const& duration) { ReusableStringStream rss; rss << duration.count() << " s"; return rss.str(); } }; template struct StringMaker>> { static std::string convert(std::chrono::duration> const& duration) { ReusableStringStream rss; rss << duration.count() << " m"; return rss.str(); } }; template struct StringMaker>> { static std::string convert(std::chrono::duration> const& duration) { ReusableStringStream rss; rss << duration.count() << " h"; return rss.str(); } }; //////////// // std::chrono::time_point specialization // Generic time_point cannot be specialized, only std::chrono::time_point template struct StringMaker> { static std::string convert(std::chrono::time_point const& time_point) { return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch"; } }; // std::chrono::time_point specialization template struct StringMaker> { static std::string convert(std::chrono::time_point const& time_point) { const auto systemish = std::chrono::time_point_cast< std::chrono::system_clock::duration>( time_point ); const auto as_time_t = std::chrono::system_clock::to_time_t( systemish ); return ::Catch::Detail::formatTimeT( as_time_t ); } }; } #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \ namespace Catch { \ template <> \ struct StringMaker { \ static std::string convert( enumName value ) { \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ static const auto enumInfo = ::Catch::Detail::makeEnumInfo( \ #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ return static_cast( \ enumInfo.lookup( static_cast( value ) ) ); \ } \ }; \ } #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ ) #ifdef _MSC_VER #pragma warning(pop) #endif #include namespace Catch { class Approx { private: bool equalityComparisonImpl(double other) const; // Sets and validates the new margin (margin >= 0) void setMargin(double margin); // Sets and validates the new epsilon (0 < epsilon < 1) void setEpsilon(double epsilon); public: explicit Approx ( double value ); static Approx custom(); Approx operator-() const; template ::value>> Approx operator()( T const& value ) const { Approx approx( static_cast(value) ); approx.m_epsilon = m_epsilon; approx.m_margin = m_margin; approx.m_scale = m_scale; return approx; } template ::value>> explicit Approx( T const& value ): Approx(static_cast(value)) {} template ::value>> friend bool operator == ( const T& lhs, Approx const& rhs ) { auto lhs_v = static_cast(lhs); return rhs.equalityComparisonImpl(lhs_v); } template ::value>> friend bool operator == ( Approx const& lhs, const T& rhs ) { return operator==( rhs, lhs ); } template ::value>> friend bool operator != ( T const& lhs, Approx const& rhs ) { return !operator==( lhs, rhs ); } template ::value>> friend bool operator != ( Approx const& lhs, T const& rhs ) { return !operator==( rhs, lhs ); } template ::value>> friend bool operator <= ( T const& lhs, Approx const& rhs ) { return static_cast(lhs) < rhs.m_value || lhs == rhs; } template ::value>> friend bool operator <= ( Approx const& lhs, T const& rhs ) { return lhs.m_value < static_cast(rhs) || lhs == rhs; } template ::value>> friend bool operator >= ( T const& lhs, Approx const& rhs ) { return static_cast(lhs) > rhs.m_value || lhs == rhs; } template ::value>> friend bool operator >= ( Approx const& lhs, T const& rhs ) { return lhs.m_value > static_cast(rhs) || lhs == rhs; } template ::value>> Approx& epsilon( T const& newEpsilon ) { const auto epsilonAsDouble = static_cast(newEpsilon); setEpsilon(epsilonAsDouble); return *this; } template ::value>> Approx& margin( T const& newMargin ) { const auto marginAsDouble = static_cast(newMargin); setMargin(marginAsDouble); return *this; } template ::value>> Approx& scale( T const& newScale ) { m_scale = static_cast(newScale); return *this; } std::string toString() const; private: double m_epsilon; double m_margin; double m_scale; double m_value; }; namespace literals { Approx operator ""_a(long double val); Approx operator ""_a(unsigned long long val); } // end namespace literals template<> struct StringMaker { static std::string convert(Catch::Approx const& value); }; } // end namespace Catch namespace Catch { // ResultWas::OfType enum struct ResultWas { enum OfType { Unknown = -1, Ok = 0, Info = 1, Warning = 2, // TODO: Should explicit skip be considered "not OK" (cf. isOk)? I.e., should it have the failure bit? ExplicitSkip = 4, FailureBit = 0x10, ExpressionFailed = FailureBit | 1, ExplicitFailure = FailureBit | 2, Exception = 0x100 | FailureBit, ThrewException = Exception | 1, DidntThrowException = Exception | 2, FatalErrorCondition = 0x200 | FailureBit }; }; constexpr bool isOk( ResultWas::OfType resultType ) { return ( resultType & ResultWas::FailureBit ) == 0; } constexpr bool isJustInfo( int flags ) { return flags == ResultWas::Info; } // ResultDisposition::Flags enum struct ResultDisposition { enum Flags { Normal = 0x01, ContinueOnFailure = 0x02, // Failures fail test, but execution continues FalseTest = 0x04, // Prefix expression with ! SuppressFail = 0x08 // Failures are reported but do not fail the test }; }; constexpr ResultDisposition::Flags operator|( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) { return static_cast( static_cast( lhs ) | static_cast( rhs ) ); } constexpr bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } constexpr bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; } } // end namespace Catch #include #include namespace Catch { struct SourceLineInfo { SourceLineInfo() = delete; constexpr SourceLineInfo( char const* _file, std::size_t _line ) noexcept: file( _file ), line( _line ) {} bool operator == ( SourceLineInfo const& other ) const noexcept; bool operator < ( SourceLineInfo const& other ) const noexcept; char const* file; std::size_t line; friend std::ostream& operator << (std::ostream& os, SourceLineInfo const& info); }; } #define CATCH_INTERNAL_LINEINFO \ ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) namespace Catch { struct AssertionInfo { // AssertionInfo() = delete; StringRef macroName; SourceLineInfo lineInfo; StringRef capturedExpression; ResultDisposition::Flags resultDisposition; }; } // end namespace Catch #include namespace Catch { class ITransientExpression; class LazyExpression { friend class AssertionHandler; friend struct AssertionStats; friend class RunContext; ITransientExpression const* m_transientExpression = nullptr; bool m_isNegated; public: constexpr LazyExpression( bool isNegated ): m_isNegated(isNegated) {} constexpr LazyExpression(LazyExpression const& other) = default; LazyExpression& operator = ( LazyExpression const& ) = delete; constexpr explicit operator bool() const { return m_transientExpression != nullptr; } friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&; }; } // namespace Catch #include namespace Catch { struct AssertionResultData { AssertionResultData() = delete; AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression ); std::string message; mutable std::string reconstructedExpression; LazyExpression lazyExpression; ResultWas::OfType resultType; std::string reconstructExpression() const; }; class AssertionResult { public: AssertionResult() = delete; AssertionResult( AssertionInfo const& info, AssertionResultData&& data ); bool isOk() const; bool succeeded() const; ResultWas::OfType getResultType() const; bool hasExpression() const; bool hasMessage() const; std::string getExpression() const; std::string getExpressionInMacro() const; bool hasExpandedExpression() const; std::string getExpandedExpression() const; StringRef getMessage() const; SourceLineInfo getSourceInfo() const; StringRef getTestMacroName() const; //protected: AssertionInfo m_info; AssertionResultData m_resultData; }; } // end namespace Catch /** \file * This is a convenience header for Catch2's benchmarking. It includes * **all** of Catch2 headers related to benchmarking. * * Generally the Catch2 users should use specific includes they need, * but this header can be used instead for ease-of-experimentation, or * just plain convenience, at the cost of (significantly) increased * compilation times. * * When a new header is added to either the `benchmark` folder, or to * the corresponding internal (detail) subfolder, it should be added here. */ // Adapted from donated nonius code. namespace Catch { class IResultCapture; class IConfig; class Context { IConfig const* m_config = nullptr; IResultCapture* m_resultCapture = nullptr; CATCH_EXPORT static Context currentContext; friend Context& getCurrentMutableContext(); friend Context const& getCurrentContext(); public: constexpr IResultCapture* getResultCapture() const { return m_resultCapture; } constexpr IConfig const* getConfig() const { return m_config; } constexpr void setResultCapture( IResultCapture* resultCapture ) { m_resultCapture = resultCapture; } constexpr void setConfig( IConfig const* config ) { m_config = config; } }; Context& getCurrentMutableContext(); inline Context const& getCurrentContext() { return Context::currentContext; } class SimplePcg32; SimplePcg32& sharedRng(); } #include //! Replacement for std::move with better compile time performance #define CATCH_MOVE(...) static_cast&&>(__VA_ARGS__) //! Replacement for std::forward with better compile time performance #define CATCH_FORWARD(...) static_cast(__VA_ARGS__) namespace Catch { //! Used to signal that an assertion macro failed struct TestFailureException{}; //! Used to signal that the remainder of a test should be skipped struct TestSkipException {}; /** * Outlines throwing of `TestFailureException` into a single TU * * Also handles `CATCH_CONFIG_DISABLE_EXCEPTIONS` for callers. */ [[noreturn]] void throw_test_failure_exception(); /** * Outlines throwing of `TestSkipException` into a single TU * * Also handles `CATCH_CONFIG_DISABLE_EXCEPTIONS` for callers. */ [[noreturn]] void throw_test_skip_exception(); } // namespace Catch /** \file * Wrapper for the CONFIG configuration option * * When generating internal unique names, there are two options. Either * we mix in the current line number, or mix in an incrementing number. * We prefer the latter, using `__COUNTER__`, but users might want to * use the former. */ #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) #define CATCH_INTERNAL_CONFIG_COUNTER #endif #if defined( CATCH_INTERNAL_CONFIG_COUNTER ) && \ !defined( CATCH_CONFIG_NO_COUNTER ) && \ !defined( CATCH_CONFIG_COUNTER ) # define CATCH_CONFIG_COUNTER #endif // Fixme: Clang 22 has an annoying bug where the localized suppression // below does not actually suppress the extension warning from // using __COUNTER__, so we have to leak the suppression for the // whole TU. Hopefully Clang 23 fixes this before full release. // As AppleClang does its own thing version-wise, we ignore it // completely. #if defined( __clang__ ) && ( __clang_major__ >= 22 ) && !defined( __APPLE__ ) CATCH_INTERNAL_SUPPRESS_COUNTER_WARNINGS #endif #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) #ifdef CATCH_CONFIG_COUNTER # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) #else # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) #endif #include #include #include namespace Catch { namespace Detail { /** * A reimplementation of `std::unique_ptr` for improved compilation performance * * Does not support arrays nor custom deleters. */ template class unique_ptr { T* m_ptr; public: constexpr unique_ptr(std::nullptr_t = nullptr): m_ptr{} {} explicit constexpr unique_ptr(T* ptr): m_ptr(ptr) {} template ::value>> unique_ptr(unique_ptr&& from): m_ptr(from.release()) {} template ::value>> unique_ptr& operator=(unique_ptr&& from) { reset(from.release()); return *this; } unique_ptr(unique_ptr const&) = delete; unique_ptr& operator=(unique_ptr const&) = delete; unique_ptr(unique_ptr&& rhs) noexcept: m_ptr(rhs.m_ptr) { rhs.m_ptr = nullptr; } unique_ptr& operator=(unique_ptr&& rhs) noexcept { reset(rhs.release()); return *this; } ~unique_ptr() { delete m_ptr; } T& operator*() { assert(m_ptr); return *m_ptr; } T const& operator*() const { assert(m_ptr); return *m_ptr; } T* operator->() noexcept { assert(m_ptr); return m_ptr; } T const* operator->() const noexcept { assert(m_ptr); return m_ptr; } T* get() { return m_ptr; } T const* get() const { return m_ptr; } void reset(T* ptr = nullptr) { delete m_ptr; m_ptr = ptr; } T* release() { auto temp = m_ptr; m_ptr = nullptr; return temp; } explicit operator bool() const { return m_ptr != nullptr; } friend void swap(unique_ptr& lhs, unique_ptr& rhs) { auto temp = lhs.m_ptr; lhs.m_ptr = rhs.m_ptr; rhs.m_ptr = temp; } }; //! Specialization to cause compile-time error for arrays template class unique_ptr; template unique_ptr make_unique(Args&&... args) { return unique_ptr(new T(CATCH_FORWARD(args)...)); } } // end namespace Detail } // end namespace Catch namespace Catch { namespace Detail { struct DummyTemplateArgPlaceholder; } // We cannot forward declare the type with default template argument // multiple times, so it is split out into a separate header so that // we can prevent multiple declarations in dependencies template struct BenchmarkStats; } // end namespace Catch namespace Catch { class AssertionResult; struct AssertionInfo; struct SectionInfo; struct SectionEndInfo; struct Counts; struct AssertionReaction; struct SourceLineInfo; class ITransientExpression; class IGeneratorTracker; struct BenchmarkInfo; namespace Generators { class GeneratorUntypedBase; using GeneratorBasePtr = Catch::Detail::unique_ptr; } class IResultCapture { public: virtual ~IResultCapture(); virtual void notifyAssertionStarted( AssertionInfo const& info ) = 0; virtual bool sectionStarted( StringRef sectionName, SourceLineInfo const& sectionLineInfo, Counts& assertions ) = 0; virtual void sectionEnded( SectionEndInfo&& endInfo ) = 0; virtual void sectionEndedEarly( SectionEndInfo&& endInfo ) = 0; virtual IGeneratorTracker* acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) = 0; virtual IGeneratorTracker* createGeneratorTracker( StringRef generatorName, SourceLineInfo lineInfo, Generators::GeneratorBasePtr&& generator ) = 0; virtual void benchmarkPreparing( StringRef name ) = 0; virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0; virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0; virtual void benchmarkFailed( StringRef error ) = 0; virtual void handleFatalErrorCondition( StringRef message ) = 0; virtual void handleExpr ( AssertionInfo const& info, ITransientExpression const& expr, AssertionReaction& reaction ) = 0; virtual void handleMessage ( AssertionInfo const& info, ResultWas::OfType resultType, std::string&& message, AssertionReaction& reaction ) = 0; virtual void handleUnexpectedExceptionNotThrown ( AssertionInfo const& info, AssertionReaction& reaction ) = 0; virtual void handleUnexpectedInflightException ( AssertionInfo const& info, std::string&& message, AssertionReaction& reaction ) = 0; virtual void handleIncomplete ( AssertionInfo const& info ) = 0; virtual void handleNonExpr ( AssertionInfo const &info, ResultWas::OfType resultType, AssertionReaction &reaction ) = 0; // Deprecated, do not use: virtual std::string getCurrentTestName() const = 0; virtual const AssertionResult* getLastResult() const = 0; virtual void exceptionEarlyReported() = 0; }; namespace Detail { [[noreturn]] void missingCaptureInstance(); } inline IResultCapture& getResultCapture() { if (auto* capture = getCurrentContext().getResultCapture()) { return *capture; } else { Detail::missingCaptureInstance(); } } } #include #include #include namespace Catch { enum class Verbosity { Quiet = 0, Normal, High }; struct WarnAbout { enum What { Nothing = 0x00, //! A test case or leaf section did not run any assertions NoAssertions = 0x01, //! A command line test spec matched no test cases UnmatchedTestSpec = 0x02, //! The resulting generator in GENERATE is infinite InfiniteGenerator = 0x04, }; }; enum class ShowDurations { DefaultForReporter, Always, Never }; enum class TestRunOrder { Declared, LexicographicallySorted, Randomized }; enum class ColourMode : std::uint8_t { //! Let Catch2 pick implementation based on platform detection PlatformDefault, //! Use ANSI colour code escapes ANSI, //! Use Win32 console colour API Win32, //! Don't use any colour None }; struct WaitForKeypress { enum When { Never, BeforeStart = 1, BeforeExit = 2, BeforeStartAndExit = BeforeStart | BeforeExit }; }; class TestSpec; class IStream; struct PathFilter; class IConfig : Detail::NonCopyable { public: virtual ~IConfig(); virtual bool allowThrows() const = 0; virtual StringRef name() const = 0; virtual bool includeSuccessfulResults() const = 0; virtual bool shouldDebugBreak() const = 0; virtual bool warnAboutMissingAssertions() const = 0; virtual bool warnAboutUnmatchedTestSpecs() const = 0; virtual bool warnAboutInfiniteGenerators() const = 0; virtual bool zeroTestsCountAsSuccess() const = 0; virtual int abortAfter() const = 0; virtual bool showInvisibles() const = 0; virtual ShowDurations showDurations() const = 0; virtual double minDuration() const = 0; virtual TestSpec const& testSpec() const = 0; virtual bool hasTestFilters() const = 0; virtual std::vector const& getTestsOrTags() const = 0; virtual TestRunOrder runOrder() const = 0; virtual uint32_t rngSeed() const = 0; virtual unsigned int shardCount() const = 0; virtual unsigned int shardIndex() const = 0; virtual ColourMode defaultColourMode() const = 0; virtual std::vector const& getPathFilters() const = 0; virtual bool useNewFilterBehaviour() const = 0; virtual Verbosity verbosity() const = 0; virtual bool skipBenchmarks() const = 0; virtual bool benchmarkNoAnalysis() const = 0; virtual unsigned int benchmarkSamples() const = 0; virtual double benchmarkConfidenceInterval() const = 0; virtual unsigned int benchmarkResamples() const = 0; virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0; }; } #include namespace Catch { class TestCaseHandle; struct TestCaseInfo; class ITestCaseRegistry; class IExceptionTranslatorRegistry; class IExceptionTranslator; class ReporterRegistry; class ITagAliasRegistry; class ITestInvoker; class IMutableEnumValuesRegistry; struct SourceLineInfo; class StartupExceptionRegistry; class EventListenerFactory; class IRegistryHub { public: virtual ~IRegistryHub(); // = default virtual ReporterRegistry const& getReporterRegistry() const = 0; virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0; virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0; virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0; }; class IMutableRegistryHub { public: virtual ~IMutableRegistryHub(); // = default virtual void registerListener( Detail::unique_ptr factory ) = 0; virtual void registerTest(Detail::unique_ptr&& testInfo, Detail::unique_ptr&& invoker) = 0; virtual void registerTranslator( Detail::unique_ptr&& translator ) = 0; virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0; virtual void registerStartupException() noexcept = 0; virtual ITestCaseRegistry& getMutableTestCaseRegistry() = 0; }; IRegistryHub const& getRegistryHub(); IMutableRegistryHub& getMutableRegistryHub(); void cleanUp(); std::string translateActiveException(); } // Adapted from donated nonius code. #include namespace Catch { namespace Benchmark { using IDuration = std::chrono::nanoseconds; using FDuration = std::chrono::duration; template using TimePoint = typename Clock::time_point; using default_clock = std::chrono::steady_clock; } // namespace Benchmark } // namespace Catch // Adapted from donated nonius code. namespace Catch { namespace Benchmark { template struct Estimate { Type point; Type lower_bound; Type upper_bound; double confidence_interval; }; } // namespace Benchmark } // namespace Catch // Adapted from donated nonius code. namespace Catch { namespace Benchmark { struct OutlierClassification { int samples_seen = 0; int low_severe = 0; // more than 3 times IQR below Q1 int low_mild = 0; // 1.5 to 3 times IQR below Q1 int high_mild = 0; // 1.5 to 3 times IQR above Q3 int high_severe = 0; // more than 3 times IQR above Q3 constexpr int total() const { return low_severe + low_mild + high_mild + high_severe; } }; } // namespace Benchmark } // namespace Catch // The fwd decl & default specialization needs to be seen by VS2017 before // BenchmarkStats itself, or VS2017 will report compilation error. #include #include namespace Catch { struct BenchmarkInfo { std::string name; double estimatedDuration; int iterations; unsigned int samples; unsigned int resamples; double clockResolution; double clockCost; }; // We need to keep template parameter for backwards compatibility, // but we also do not want to use the template paraneter. template struct BenchmarkStats { BenchmarkInfo info; std::vector samples; Benchmark::Estimate mean; Benchmark::Estimate standardDeviation; Benchmark::OutlierClassification outliers; double outlierVariance; }; } // end namespace Catch // Adapted from donated nonius code. namespace Catch { namespace Benchmark { struct EnvironmentEstimate { FDuration mean; OutlierClassification outliers; }; struct Environment { EnvironmentEstimate clock_resolution; EnvironmentEstimate clock_cost; }; } // namespace Benchmark } // namespace Catch // Adapted from donated nonius code. // Adapted from donated nonius code. // Adapted from donated nonius code. // Adapted from donated nonius code. #if defined(_MSC_VER) || defined(__IAR_SYSTEMS_ICC__) # include // atomic_thread_fence #endif #include namespace Catch { namespace Benchmark { #if defined(__GNUC__) || defined(__clang__) template inline void keep_memory(T* p) { asm volatile("" : : "g"(p) : "memory"); } inline void keep_memory() { asm volatile("" : : : "memory"); } namespace Detail { inline void optimizer_barrier() { keep_memory(); } } // namespace Detail #elif defined(_MSC_VER) || defined(__IAR_SYSTEMS_ICC__) #if defined(_MSC_VER) #pragma optimize("", off) #elif defined(__IAR_SYSTEMS_ICC__) // For IAR the pragma only affects the following function #pragma optimize=disable #endif template inline void keep_memory(T* p) { // thanks @milleniumbug *reinterpret_cast(p) = *reinterpret_cast(p); } // TODO equivalent keep_memory() #if defined(_MSC_VER) #pragma optimize("", on) #endif namespace Detail { inline void optimizer_barrier() { std::atomic_thread_fence(std::memory_order_seq_cst); } } // namespace Detail #endif template inline void deoptimize_value(T&& x) { keep_memory(&x); } template inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> std::enable_if_t::value> { deoptimize_value(CATCH_FORWARD(fn) (CATCH_FORWARD(args)...)); } template inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> std::enable_if_t::value> { CATCH_FORWARD((fn)) (CATCH_FORWARD(args)...); // In the non-void case, we pass the result through `deoptimize_value` // to force the compiler to keep it. We have no return value here, // but add an optimizer barrier (ideally a memory clobber) to force // the _side effects_ of the loop be visible (e.g. writes to globals). // Note that writes to benchmark-locals can be optimized away, as // we would expect in normal code. Detail::optimizer_barrier(); } } // namespace Benchmark } // namespace Catch #include namespace Catch { template struct true_given : std::true_type {}; struct is_callable_tester { template static true_given()(std::declval()...))> test(int); template static std::false_type test(...); }; template struct is_callable; template struct is_callable : decltype(is_callable_tester::test(0)) {}; #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703 // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is // replaced with std::invoke_result here. template using FunctionReturnType = std::remove_reference_t>>; #else template using FunctionReturnType = std::remove_reference_t>>; #endif } // namespace Catch namespace mpl_{ struct na; } namespace Catch { namespace Benchmark { namespace Detail { struct ChronometerConcept { virtual void start() = 0; virtual void finish() = 0; virtual ~ChronometerConcept(); // = default; ChronometerConcept() = default; ChronometerConcept(ChronometerConcept const&) = default; ChronometerConcept& operator=(ChronometerConcept const&) = default; }; template struct ChronometerModel final : public ChronometerConcept { void start() override { started = Clock::now(); } void finish() override { finished = Clock::now(); } IDuration elapsed() const { return std::chrono::duration_cast( finished - started ); } TimePoint started; TimePoint finished; }; } // namespace Detail struct Chronometer { public: template void measure(Fun&& fun) { measure(CATCH_FORWARD(fun), is_callable()); } int runs() const { return repeats; } Chronometer(Detail::ChronometerConcept& meter, int repeats_) : impl(&meter) , repeats(repeats_) {} private: template void measure(Fun&& fun, std::false_type) { measure([&fun](int) { return fun(); }, std::true_type()); } template void measure(Fun&& fun, std::true_type) { Detail::optimizer_barrier(); impl->start(); for (int i = 0; i < repeats; ++i) invoke_deoptimized(fun, i); impl->finish(); Detail::optimizer_barrier(); } Detail::ChronometerConcept* impl; int repeats; }; } // namespace Benchmark } // namespace Catch #include namespace Catch { namespace Benchmark { namespace Detail { template static constexpr bool is_related_v = std::is_same, std::decay_t>::value; /// We need to reinvent std::function because every piece of code that might add overhead /// in a measurement context needs to have consistent performance characteristics so that we /// can account for it in the measurement. /// Implementations of std::function with optimizations that aren't always applicable, like /// small buffer optimizations, are not uncommon. /// This is effectively an implementation of std::function without any such optimizations; /// it may be slow, but it is consistently slow. struct BenchmarkFunction { private: struct callable { virtual void call(Chronometer meter) const = 0; virtual ~callable(); // = default; callable() = default; callable(callable&&) = default; callable& operator=(callable&&) = default; }; template struct model final : public callable { model(Fun&& fun_) : fun(CATCH_MOVE(fun_)) {} model(Fun const& fun_) : fun(fun_) {} void call(Chronometer meter) const override { call(meter, is_callable()); } void call(Chronometer meter, std::true_type) const { fun(meter); } void call(Chronometer meter, std::false_type) const { meter.measure(fun); } Fun fun; }; public: BenchmarkFunction(); template , int> = 0> BenchmarkFunction(Fun&& fun) : f(new model>(CATCH_FORWARD(fun))) {} BenchmarkFunction( BenchmarkFunction&& that ) noexcept: f( CATCH_MOVE( that.f ) ) {} BenchmarkFunction& operator=( BenchmarkFunction&& that ) noexcept { f = CATCH_MOVE( that.f ); return *this; } void operator()(Chronometer meter) const { f->call(meter); } private: Catch::Detail::unique_ptr f; }; } // namespace Detail } // namespace Benchmark } // namespace Catch // Adapted from donated nonius code. #include namespace Catch { namespace Benchmark { namespace Detail { template struct repeater { void operator()(int k) const { for (int i = 0; i < k; ++i) { fun(); } } Fun fun; }; template repeater> repeat(Fun&& fun) { return { CATCH_FORWARD(fun) }; } } // namespace Detail } // namespace Benchmark } // namespace Catch // Adapted from donated nonius code. // Adapted from donated nonius code. // Adapted from donated nonius code. namespace Catch { namespace Benchmark { namespace Detail { template struct CompleteType { using type = T; }; template <> struct CompleteType { struct type {}; }; template using CompleteType_t = typename CompleteType::type; template struct CompleteInvoker { template static Result invoke(Fun&& fun, Args&&... args) { return CATCH_FORWARD(fun)(CATCH_FORWARD(args)...); } }; template <> struct CompleteInvoker { template static CompleteType_t invoke(Fun&& fun, Args&&... args) { CATCH_FORWARD(fun)(CATCH_FORWARD(args)...); return {}; } }; // invoke and not return void :( template CompleteType_t> complete_invoke(Fun&& fun, Args&&... args) { return CompleteInvoker>::invoke(CATCH_FORWARD(fun), CATCH_FORWARD(args)...); } } // namespace Detail template Detail::CompleteType_t> user_code(Fun&& fun) { return Detail::complete_invoke(CATCH_FORWARD(fun)); } } // namespace Benchmark } // namespace Catch // Adapted from donated nonius code. namespace Catch { namespace Benchmark { template struct Timing { IDuration elapsed; Result result; int iterations; }; template using TimingOf = Timing>>; } // namespace Benchmark } // namespace Catch namespace Catch { namespace Benchmark { namespace Detail { template TimingOf measure(Fun&& fun, Args&&... args) { auto start = Clock::now(); auto&& r = Detail::complete_invoke(CATCH_FORWARD(fun), CATCH_FORWARD(args)...); auto end = Clock::now(); auto delta = end - start; return { delta, CATCH_FORWARD(r), 1 }; } } // namespace Detail } // namespace Benchmark } // namespace Catch #include namespace Catch { namespace Benchmark { namespace Detail { template TimingOf measure_one(Fun&& fun, int iters, std::false_type) { return Detail::measure(fun, iters); } template TimingOf measure_one(Fun&& fun, int iters, std::true_type) { Detail::ChronometerModel meter; auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters)); return { meter.elapsed(), CATCH_MOVE(result), iters }; } template using run_for_at_least_argument_t = std::conditional_t::value, Chronometer, int>; [[noreturn]] void throw_optimized_away_error(); template TimingOf> run_for_at_least(IDuration how_long, const int initial_iterations, Fun&& fun) { auto iters = initial_iterations; while (iters < (1 << 30)) { auto&& Timing = measure_one(fun, iters, is_callable()); if (Timing.elapsed >= how_long) { return { Timing.elapsed, CATCH_MOVE(Timing.result), iters }; } iters *= 2; } throw_optimized_away_error(); } } // namespace Detail } // namespace Benchmark } // namespace Catch #include namespace Catch { namespace Benchmark { struct ExecutionPlan { int iterations_per_sample; FDuration estimated_duration; Detail::BenchmarkFunction benchmark; FDuration warmup_time; int warmup_iterations; template std::vector run(const IConfig &cfg, Environment env) const { // warmup a bit Detail::run_for_at_least( std::chrono::duration_cast( warmup_time ), warmup_iterations, Detail::repeat( []() { return Clock::now(); } ) ); std::vector times; const auto num_samples = cfg.benchmarkSamples(); times.reserve( num_samples ); for ( size_t i = 0; i < num_samples; ++i ) { Detail::ChronometerModel model; this->benchmark( Chronometer( model, iterations_per_sample ) ); auto sample_time = model.elapsed() - env.clock_cost.mean; if ( sample_time < FDuration::zero() ) { sample_time = FDuration::zero(); } times.push_back(sample_time / iterations_per_sample); } return times; } }; } // namespace Benchmark } // namespace Catch // Adapted from donated nonius code. // Adapted from donated nonius code. #include namespace Catch { namespace Benchmark { namespace Detail { using sample = std::vector; double weighted_average_quantile( int k, int q, double* first, double* last ); OutlierClassification classify_outliers( double const* first, double const* last ); double mean( double const* first, double const* last ); double normal_cdf( double x ); double erfc_inv(double x); double normal_quantile(double p); Estimate bootstrap( double confidence_level, double* first, double* last, sample const& resample, double ( *estimator )( double const*, double const* ) ); struct bootstrap_analysis { Estimate mean; Estimate standard_deviation; double outlier_variance; }; bootstrap_analysis analyse_samples(double confidence_level, unsigned int n_resamples, double* first, double* last); } // namespace Detail } // namespace Benchmark } // namespace Catch #include #include #include namespace Catch { namespace Benchmark { namespace Detail { template std::vector resolution(int k) { const size_t points = static_cast( k + 1 ); // To avoid overhead from the branch inside vector::push_back, // we allocate them all and then overwrite. std::vector> times(points); for ( auto& time : times ) { time = Clock::now(); } std::vector deltas; deltas.reserve(static_cast(k)); for ( size_t idx = 1; idx < points; ++idx ) { deltas.push_back( static_cast( ( times[idx] - times[idx - 1] ).count() ) ); } return deltas; } constexpr auto warmup_iterations = 10000; constexpr auto warmup_time = std::chrono::milliseconds(100); constexpr auto minimum_ticks = 1000; constexpr auto warmup_seed = 10000; constexpr auto clock_resolution_estimation_time = std::chrono::milliseconds(500); constexpr auto clock_cost_estimation_time_limit = std::chrono::seconds(1); constexpr auto clock_cost_estimation_tick_limit = 100000; constexpr auto clock_cost_estimation_time = std::chrono::milliseconds(10); constexpr auto clock_cost_estimation_iterations = 10000; template int warmup() { return run_for_at_least(warmup_time, warmup_seed, &resolution) .iterations; } template EnvironmentEstimate estimate_clock_resolution(int iterations) { auto r = run_for_at_least(clock_resolution_estimation_time, iterations, &resolution) .result; return { FDuration(mean(r.data(), r.data() + r.size())), classify_outliers(r.data(), r.data() + r.size()), }; } template EnvironmentEstimate estimate_clock_cost(FDuration resolution) { auto time_limit = (std::min)( resolution * clock_cost_estimation_tick_limit, FDuration(clock_cost_estimation_time_limit)); auto time_clock = [](int k) { return Detail::measure([k] { for (int i = 0; i < k; ++i) { volatile auto ignored = Clock::now(); (void)ignored; } }).elapsed; }; time_clock(1); int iters = clock_cost_estimation_iterations; auto&& r = run_for_at_least(clock_cost_estimation_time, iters, time_clock); std::vector times; int nsamples = static_cast(std::ceil(time_limit / r.elapsed)); times.reserve(static_cast(nsamples)); for ( int s = 0; s < nsamples; ++s ) { times.push_back( static_cast( ( time_clock( r.iterations ) / r.iterations ) .count() ) ); } return { FDuration(mean(times.data(), times.data() + times.size())), classify_outliers(times.data(), times.data() + times.size()), }; } template Environment measure_environment() { #if defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wexit-time-destructors" #endif static Catch::Detail::unique_ptr env; #if defined(__clang__) # pragma clang diagnostic pop #endif if (env) { return *env; } auto iters = Detail::warmup(); auto resolution = Detail::estimate_clock_resolution(iters); auto cost = Detail::estimate_clock_cost(resolution.mean); env = Catch::Detail::make_unique( Environment{resolution, cost} ); return *env; } } // namespace Detail } // namespace Benchmark } // namespace Catch // Adapted from donated nonius code. // Adapted from donated nonius code. #include namespace Catch { namespace Benchmark { struct SampleAnalysis { std::vector samples; Estimate mean; Estimate standard_deviation; OutlierClassification outliers; double outlier_variance; }; } // namespace Benchmark } // namespace Catch namespace Catch { class IConfig; namespace Benchmark { namespace Detail { SampleAnalysis analyse(const IConfig &cfg, FDuration* first, FDuration* last); } // namespace Detail } // namespace Benchmark } // namespace Catch #include #include #include #include #include #include namespace Catch { namespace Benchmark { namespace Detail { template ExecutionPlan prepare( const IConfig& cfg, Environment env, BenchmarkFunction&& fun ) { auto min_time = env.clock_resolution.mean * Detail::minimum_ticks; auto run_time = std::max( min_time, std::chrono::duration_cast( cfg.benchmarkWarmupTime() ) ); auto&& test = Detail::run_for_at_least( std::chrono::duration_cast( run_time ), 1, fun ); int new_iters = static_cast( std::ceil( min_time * test.iterations / test.elapsed ) ); return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), CATCH_MOVE( fun ), std::chrono::duration_cast( cfg.benchmarkWarmupTime() ), Detail::warmup_iterations }; } // These are wrappers for their respective function templated // over `default_clock`. This allows outlining the usual use // of the template into single TU and save on compilation costs. Environment measure_environment_default(); ExecutionPlan prepare_default( const IConfig& cfg, Environment env, BenchmarkFunction&& fun ); std::vector run_plan_default( ExecutionPlan const& plan, const IConfig& cfg, Environment env ); template std::enable_if_t::value, Environment> measureEnvironmentDispatch() { return measure_environment_default(); } template std::enable_if_t::value, Environment> measureEnvironmentDispatch() { return measure_environment(); } template std::enable_if_t::value, std::vector> runPlanDispatch( ExecutionPlan const& plan, const IConfig& cfg, Environment env ) { return run_plan_default( plan, cfg, env ); } template std::enable_if_t::value, std::vector> runPlanDispatch( ExecutionPlan const& plan, const IConfig& cfg, Environment env ) { return plan.template run( cfg, env ); } template std::enable_if_t::value, ExecutionPlan> prepareDispatch( const IConfig& cfg, Environment env, BenchmarkFunction&& fun ) { return prepare_default( cfg, env, CATCH_MOVE( fun ) ); } template std::enable_if_t::value, ExecutionPlan> prepareDispatch( const IConfig& cfg, Environment env, BenchmarkFunction&& fun ) { return prepare( cfg, env, CATCH_MOVE( fun ) ); } } // namespace Detail struct Benchmark { Benchmark(std::string&& benchmarkName) : name(CATCH_MOVE(benchmarkName)) {} template Benchmark(std::string&& benchmarkName , FUN &&func) : fun(CATCH_MOVE(func)), name(CATCH_MOVE(benchmarkName)) {} template void run() { static_assert( Clock::is_steady, "Benchmarking clock should be steady" ); auto const* cfg = getCurrentContext().getConfig(); auto env = Detail::measureEnvironmentDispatch(); getResultCapture().benchmarkPreparing(name); CATCH_TRY{ auto plan = user_code([&] { return Detail::prepareDispatch( *cfg, env, CATCH_MOVE(fun) ); }); BenchmarkInfo info { CATCH_MOVE(name), plan.estimated_duration.count(), plan.iterations_per_sample, cfg->benchmarkSamples(), cfg->benchmarkResamples(), env.clock_resolution.mean.count(), env.clock_cost.mean.count() }; getResultCapture().benchmarkStarting(info); auto samples = user_code([&] { return Detail::runPlanDispatch( plan, *cfg, env ); }); auto analysis = Detail::analyse(*cfg, samples.data(), samples.data() + samples.size()); BenchmarkStats<> stats{ CATCH_MOVE(info), CATCH_MOVE(analysis.samples), analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance }; getResultCapture().benchmarkEnded(stats); } CATCH_CATCH_ALL { getResultCapture().benchmarkFailed(translateActiveException()); // We let the exception go further up so that the // test case is marked as failed. std::rethrow_exception(std::current_exception()); } } // sets lambda to be used in fun *and* executes benchmark! template , int> = 0> Benchmark & operator=(Fun func) { auto const* cfg = getCurrentContext().getConfig(); if (!cfg->skipBenchmarks()) { fun = Detail::BenchmarkFunction(func); run(); } return *this; } explicit operator bool() { return true; } private: Detail::BenchmarkFunction fun; std::string name; }; } } // namespace Catch #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\ if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \ BenchmarkName = [&](int benchmarkIndex) #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\ if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \ BenchmarkName = [&] #if defined(CATCH_CONFIG_PREFIX_ALL) #define CATCH_BENCHMARK(...) \ INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(CATCH2_INTERNAL_BENCHMARK_), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,)) #define CATCH_BENCHMARK_ADVANCED(name) \ INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(CATCH2_INTERNAL_BENCHMARK_), name) #else #define BENCHMARK(...) \ INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(CATCH2_INTERNAL_BENCHMARK_), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,)) #define BENCHMARK_ADVANCED(name) \ INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(CATCH2_INTERNAL_BENCHMARK_), name) #endif // Adapted from donated nonius code. #include namespace Catch { namespace Benchmark { namespace Detail { template struct ObjectStorage { ObjectStorage() = default; ObjectStorage(const ObjectStorage& other) { new(&data) T(other.stored_object()); } ObjectStorage(ObjectStorage&& other) { new(data) T(CATCH_MOVE(other.stored_object())); } ~ObjectStorage() { destruct_on_exit(); } template void construct(Args&&... args) { new (data) T(CATCH_FORWARD(args)...); } template std::enable_if_t destruct() { stored_object().~T(); } private: // If this is a constructor benchmark, destruct the underlying object template void destruct_on_exit(std::enable_if_t* = nullptr) { destruct(); } // Otherwise, don't template void destruct_on_exit(std::enable_if_t* = nullptr) { } #if defined( __GNUC__ ) && __GNUC__ <= 6 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif T& stored_object() { return *reinterpret_cast( data ); } T const& stored_object() const { return *reinterpret_cast( data ); } #if defined( __GNUC__ ) && __GNUC__ <= 6 # pragma GCC diagnostic pop #endif alignas( T ) unsigned char data[sizeof( T )]{}; }; } // namespace Detail template using storage_for = Detail::ObjectStorage; template using destructable_object = Detail::ObjectStorage; } // namespace Benchmark } // namespace Catch namespace Catch { enum class CaseSensitive { Yes, No }; } // namespace Catch #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif #include namespace Catch { class WildcardPattern { enum WildcardPosition { NoWildcard = 0, WildcardAtStart = 1, WildcardAtEnd = 2, WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd }; public: WildcardPattern( std::string const& pattern, CaseSensitive caseSensitivity ); bool matches( StringRef str ) const; private: CaseSensitive m_caseSensitivity; WildcardPosition m_wildcard = NoWildcard; std::string m_pattern; }; } #include #include #include namespace Catch { class IConfig; struct TestCaseInfo; class TestCaseHandle; class TestSpec { class Pattern { public: explicit Pattern( std::string const& name ); virtual ~Pattern(); virtual bool matches( TestCaseInfo const& testCase ) const = 0; std::string const& name() const; private: virtual void serializeTo( std::ostream& out ) const = 0; // Writes string that would be reparsed into the pattern friend std::ostream& operator<<(std::ostream& out, Pattern const& pattern) { pattern.serializeTo( out ); return out; } std::string const m_name; }; class NamePattern : public Pattern { public: explicit NamePattern( std::string const& name, std::string const& filterString ); bool matches( TestCaseInfo const& testCase ) const override; private: void serializeTo( std::ostream& out ) const override; WildcardPattern m_wildcardPattern; }; class TagPattern : public Pattern { public: explicit TagPattern( std::string const& tag, std::string const& filterString ); bool matches( TestCaseInfo const& testCase ) const override; private: void serializeTo( std::ostream& out ) const override; std::string m_tag; }; struct Filter { std::vector> m_required; std::vector> m_forbidden; //! Serializes this filter into a string that would be parsed into //! an equivalent filter void serializeTo( std::ostream& out ) const; friend std::ostream& operator<<(std::ostream& out, Filter const& f) { f.serializeTo( out ); return out; } bool matches( TestCaseInfo const& testCase ) const; }; static std::string extractFilterName( Filter const& filter ); public: struct FilterMatch { std::string name; std::vector tests; }; using Matches = std::vector; using vectorStrings = std::vector; bool hasFilters() const; bool matches( TestCaseInfo const& testCase ) const; Matches matchesByFilter( std::vector const& testCases, IConfig const& config ) const; const vectorStrings & getInvalidSpecs() const; private: std::vector m_filters; std::vector m_invalidSpecs; friend class TestSpecParser; //! Serializes this test spec into a string that would be parsed into //! equivalent test spec void serializeTo( std::ostream& out ) const; friend std::ostream& operator<<(std::ostream& out, TestSpec const& spec) { spec.serializeTo( out ); return out; } }; } #ifdef __clang__ #pragma clang diagnostic pop #endif #include namespace Catch { // An optional type template class Optional { public: Optional(): nullableValue( nullptr ) {} ~Optional() { reset(); } Optional( T const& _value ): nullableValue( new ( storage ) T( _value ) ) {} Optional( T&& _value ): nullableValue( new ( storage ) T( CATCH_MOVE( _value ) ) ) {} Optional& operator=( T const& _value ) { reset(); nullableValue = new ( storage ) T( _value ); return *this; } Optional& operator=( T&& _value ) { reset(); nullableValue = new ( storage ) T( CATCH_MOVE( _value ) ); return *this; } Optional( Optional const& _other ): nullableValue( _other ? new ( storage ) T( *_other ) : nullptr ) {} Optional( Optional&& _other ): nullableValue( _other ? new ( storage ) T( CATCH_MOVE( *_other ) ) : nullptr ) {} Optional& operator=( Optional const& _other ) { if ( &_other != this ) { reset(); if ( _other ) { nullableValue = new ( storage ) T( *_other ); } } return *this; } Optional& operator=( Optional&& _other ) { if ( &_other != this ) { reset(); if ( _other ) { nullableValue = new ( storage ) T( CATCH_MOVE( *_other ) ); } } return *this; } void reset() { if ( nullableValue ) { nullableValue->~T(); } nullableValue = nullptr; } T& operator*() { assert(nullableValue); return *nullableValue; } T const& operator*() const { assert(nullableValue); return *nullableValue; } T* operator->() { assert(nullableValue); return nullableValue; } const T* operator->() const { assert(nullableValue); return nullableValue; } T valueOr( T const& defaultValue ) const { return nullableValue ? *nullableValue : defaultValue; } bool some() const { return nullableValue != nullptr; } bool none() const { return nullableValue == nullptr; } bool operator !() const { return nullableValue == nullptr; } explicit operator bool() const { return some(); } friend bool operator==(Optional const& a, Optional const& b) { if (a.none() && b.none()) { return true; } else if (a.some() && b.some()) { return *a == *b; } else { return false; } } friend bool operator!=(Optional const& a, Optional const& b) { return !( a == b ); } private: T* nullableValue; alignas(alignof(T)) char storage[sizeof(T)]; }; } // end namespace Catch #include namespace Catch { struct PathFilter { enum class For { Section, Generator, }; PathFilter( For type_, std::string filter_ ): type( type_ ), filter( CATCH_MOVE( filter_ ) ) {} For type; std::string filter; friend bool operator==( PathFilter const& lhs, PathFilter const& rhs ); }; } // end namespace Catch #include namespace Catch { enum class GenerateFrom { Time, RandomDevice, //! Currently equivalent to RandomDevice, but can change at any point Default }; std::uint32_t generateRandomSeed(GenerateFrom from); } // end namespace Catch #include #include #include namespace Catch { /** * How the tests of one process behave. * * The Catch3 runner fills this in from its own command line, in the * process that runs the tests: a worker, or the runner itself with * `--in-process`. What to run, in which order and where to report is * the runner's, not part of this configuration. */ struct ConfigData { bool showSuccessfulTests = false; bool shouldDebugBreak = false; bool noThrow = false; bool showInvisibles = false; bool filenamesAsTags = false; bool allowZeroTests = false; int abortAfter = -1; uint32_t rngSeed = generateRandomSeed(GenerateFrom::Default); bool rngSeedWasFixed = false; unsigned int shardCount = 1; unsigned int shardIndex = 0; bool skipBenchmarks = false; bool benchmarkNoAnalysis = false; unsigned int benchmarkSamples = 100; double benchmarkConfidenceInterval = 0.95; unsigned int benchmarkResamples = 100'000; std::chrono::milliseconds::rep benchmarkWarmupTime = 100; Verbosity verbosity = Verbosity::Normal; WarnAbout::What warnings = WarnAbout::Nothing; ShowDurations showDurations = ShowDurations::DefaultForReporter; double minDuration = -1; TestRunOrder runOrder = TestRunOrder::Declared; ColourMode defaultColourMode = ColourMode::PlatformDefault; std::string name; std::string processName; std::vector testsOrTags; std::vector pathFilters; bool useNewPathFilteringBehaviour = false; }; class Config : public IConfig { public: Config() = default; Config( ConfigData const& data ); ~Config() override; // = default in the cpp file std::vector const& getTestsOrTags() const override; std::vector const& getPathFilters() const override; bool useNewFilterBehaviour() const override; TestSpec const& testSpec() const override; bool hasTestFilters() const override; // IConfig interface bool allowThrows() const override; StringRef name() const override; bool includeSuccessfulResults() const override; bool warnAboutMissingAssertions() const override; bool warnAboutUnmatchedTestSpecs() const override; bool warnAboutInfiniteGenerators() const override; bool zeroTestsCountAsSuccess() const override; ShowDurations showDurations() const override; double minDuration() const override; TestRunOrder runOrder() const override; uint32_t rngSeed() const override; bool rngSeedWasFixed() const; unsigned int shardCount() const override; unsigned int shardIndex() const override; ColourMode defaultColourMode() const override; bool shouldDebugBreak() const override; int abortAfter() const override; bool showInvisibles() const override; Verbosity verbosity() const override; bool skipBenchmarks() const override; bool benchmarkNoAnalysis() const override; unsigned int benchmarkSamples() const override; double benchmarkConfidenceInterval() const override; unsigned int benchmarkResamples() const override; std::chrono::milliseconds benchmarkWarmupTime() const override; private: ConfigData m_data; TestSpec m_testSpec; bool m_hasTestFilters = false; }; } // end namespace Catch #include namespace Catch { // Versioning information struct Version { Version( Version const& ) = delete; Version& operator=( Version const& ) = delete; Version( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, char const * const _branchName, unsigned int _buildNumber ); unsigned int const majorVersion; unsigned int const minorVersion; unsigned int const patchNumber; // buildNumber is only used if branchName is not null char const * const branchName; unsigned int const buildNumber; friend std::ostream& operator << ( std::ostream& os, Version const& version ); }; Version const& libraryVersion(); } #define CATCH_VERSION_MAJOR 3 #define CATCH_VERSION_MINOR 16 #define CATCH_VERSION_PATCH 1 /** \file * This is a convenience header for Catch2's Generator support. It includes * **all** of Catch2 headers related to generators. * * Generally the Catch2 users should use specific includes they need, * but this header can be used instead for ease-of-experimentation, or * just plain convenience, at the cost of (significantly) increased * compilation times. * * When a new header is added to either the `generators` folder, * or to the corresponding internal subfolder, it should be added here. */ namespace Catch { namespace Generators { namespace Detail { //! Throws GeneratorException with the provided message [[noreturn]] void throw_generator_exception( char const* msg ); } // namespace Detail } // namespace Generators } // namespace Catch #include namespace Catch { namespace Generators { class GeneratorUntypedBase { // Caches result from `toStringImpl`, assume that when it is an // empty string, the cache is invalidated. mutable std::string m_stringReprCache; // Counts based on `next` returning true std::size_t m_currentElementIndex = 0; /** * Attempts to move the generator to the next element * * Returns true iff the move succeeded (and a valid element * can be retrieved). */ virtual bool next() = 0; //! Customization point for `currentElementAsString` virtual std::string stringifyImpl() const = 0; /** * Customization point for skipping to the n-th element * * Defaults to successively calling `countedNext`. If there * are not enough elements to reach the nth one, will throw * an error. */ virtual void skipToNthElementImpl( std::size_t n ); public: GeneratorUntypedBase() = default; // Generation of copy ops is deprecated (and Clang will complain) // if there is a user destructor defined GeneratorUntypedBase(GeneratorUntypedBase const&) = default; GeneratorUntypedBase& operator=(GeneratorUntypedBase const&) = default; virtual ~GeneratorUntypedBase(); // = default; /** * Attempts to move the generator to the next element * * Serves as a non-virtual interface to `next`, so that the * top level interface can provide sanity checking and shared * features. * * As with `next`, returns true iff the move succeeded and * the generator has new valid element to provide. */ bool countedNext(); std::size_t currentElementIndex() const { return m_currentElementIndex; } /** * Moves the generator forward **to** the n-th element * * Cannot move backwards. Can stay in place. */ void skipToNthElement( std::size_t n ); /** * Returns generator's current element as user-friendly string. * * By default returns string equivalent to calling * `Catch::Detail::stringify` on the current element, but generators * can customize their implementation as needed. * * Not thread-safe due to internal caching. * * The returned ref is valid only until the generator instance * is destructed, or it moves onto the next element, whichever * comes first. */ StringRef currentElementAsString() const; /** * Returns true if calls to `next` will eventually return false * * Note that for backwards compatibility this is currently defaulted * to return `true`, but in the future all generators will have to * provide their own implementation. */ virtual bool isFinite() const; }; using GeneratorBasePtr = Catch::Detail::unique_ptr; } // namespace Generators class IGeneratorTracker { public: virtual ~IGeneratorTracker(); // = default; virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0; }; } // namespace Catch #include #include namespace Catch { namespace Generators { template class IGenerator : public GeneratorUntypedBase { std::string stringifyImpl() const override { return ::Catch::Detail::stringify( get() ); } public: // Returns the current element of the generator // // \Precondition The generator is either freshly constructed, // or the last call to `next()` returned true virtual T const& get() const = 0; using type = T; }; template using GeneratorPtr = Catch::Detail::unique_ptr>; template class GeneratorWrapper final { GeneratorPtr m_generator; public: //! Takes ownership of the passed pointer. GeneratorWrapper(IGenerator* generator): m_generator(generator) {} GeneratorWrapper(GeneratorPtr generator): m_generator(CATCH_MOVE(generator)) {} T const& get() const { return m_generator->get(); } bool next() { return m_generator->countedNext(); } bool isFinite() const { return m_generator->isFinite(); } void skipToNthElement( size_t n ) { m_generator->skipToNthElement(n); } }; template class SingleValueGenerator final : public IGenerator { T m_value; public: SingleValueGenerator(T const& value) : m_value(value) {} SingleValueGenerator(T&& value): m_value(CATCH_MOVE(value)) {} T const& get() const override { return m_value; } bool next() override { return false; } bool isFinite() const override { return true; } }; template class FixedValuesGenerator final : public IGenerator { static_assert(!std::is_same::value, "FixedValuesGenerator does not support bools because of std::vector" "specialization, use SingleValue Generator instead."); std::vector m_values; size_t m_idx = 0; void skipToNthElementImpl( std::size_t n ) override { if ( n >= m_values.size() ) { Detail::throw_generator_exception( "Could not jump to Nth element: not enough elements" ); } m_idx = n; } public: FixedValuesGenerator( std::initializer_list values ) : m_values( values ) {} T const& get() const override { return m_values[m_idx]; } bool next() override { ++m_idx; return m_idx < m_values.size(); } bool isFinite() const override { return true; } }; template > GeneratorWrapper value( T&& value ) { return GeneratorWrapper( Catch::Detail::make_unique>( CATCH_FORWARD( value ) ) ); } template GeneratorWrapper values(std::initializer_list values) { return GeneratorWrapper(Catch::Detail::make_unique>(values)); } template class Generators : public IGenerator { std::vector> m_generators; size_t m_current = 0; void add_generator( GeneratorWrapper&& generator ) { m_generators.emplace_back( CATCH_MOVE( generator ) ); } void add_generator( T const& val ) { m_generators.emplace_back( value( val ) ); } void add_generator( T&& val ) { m_generators.emplace_back( value( CATCH_MOVE( val ) ) ); } template std::enable_if_t, T>::value> add_generator( U&& val ) { add_generator( T( CATCH_FORWARD( val ) ) ); } template void add_generators( U&& valueOrGenerator ) { add_generator( CATCH_FORWARD( valueOrGenerator ) ); } template void add_generators( U&& valueOrGenerator, Gs&&... moreGenerators ) { add_generator( CATCH_FORWARD( valueOrGenerator ) ); add_generators( CATCH_FORWARD( moreGenerators )... ); } public: template Generators(Gs &&... moreGenerators) { m_generators.reserve(sizeof...(Gs)); add_generators(CATCH_FORWARD(moreGenerators)...); } T const& get() const override { return m_generators[m_current].get(); } bool next() override { if (m_current >= m_generators.size()) { return false; } const bool current_status = m_generators[m_current].next(); if (!current_status) { ++m_current; } return m_current < m_generators.size(); } bool isFinite() const override { for (auto const& gen : m_generators) { if (!gen.isFinite()) { return false; } } return true; } }; template GeneratorWrapper...>> table( std::initializer_list...>> tuples ) { return values>( tuples ); } // Tag type to signal that a generator sequence should convert arguments to a specific type template struct as {}; template auto makeGenerators( GeneratorWrapper&& generator, Gs &&... moreGenerators ) -> Generators { return Generators(CATCH_MOVE(generator), CATCH_FORWARD(moreGenerators)...); } template auto makeGenerators( GeneratorWrapper&& generator ) -> Generators { return Generators(CATCH_MOVE(generator)); } template auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators> { return makeGenerators( value( CATCH_FORWARD( val ) ), CATCH_FORWARD( moreGenerators )... ); } template auto makeGenerators( as, U&& val, Gs &&... moreGenerators ) -> Generators { return makeGenerators( value( T( CATCH_FORWARD( val ) ) ), CATCH_FORWARD( moreGenerators )... ); } IGeneratorTracker* acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ); IGeneratorTracker* createGeneratorTracker( StringRef generatorName, SourceLineInfo lineInfo, GeneratorBasePtr&& generator ); template auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> typename decltype(generatorExpression())::type { using UnderlyingType = typename decltype(generatorExpression())::type; IGeneratorTracker* tracker = acquireGeneratorTracker( generatorName, lineInfo ); // Creation of tracker is delayed after generator creation, so // that constructing generator can fail without breaking everything. if (!tracker) { tracker = createGeneratorTracker( generatorName, lineInfo, Catch::Detail::make_unique>( generatorExpression() ) ); } auto const& generator = static_cast const&>( *tracker->getGenerator() ); return generator.get(); } } // namespace Generators } // namespace Catch #define CATCH_INTERNAL_GENERATOR_STRINGIZE_IMPL( ... ) #__VA_ARGS__##_catch_sr #define CATCH_INTERNAL_GENERATOR_STRINGIZE(...) CATCH_INTERNAL_GENERATOR_STRINGIZE_IMPL(__VA_ARGS__) #define GENERATE( ... ) \ Catch::Generators::generate( CATCH_INTERNAL_GENERATOR_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ CATCH_INTERNAL_LINEINFO, \ [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) #define GENERATE_COPY( ... ) \ Catch::Generators::generate( CATCH_INTERNAL_GENERATOR_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ CATCH_INTERNAL_LINEINFO, \ [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) #define GENERATE_REF( ... ) \ Catch::Generators::generate( CATCH_INTERNAL_GENERATOR_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ CATCH_INTERNAL_LINEINFO, \ [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) #include namespace Catch { namespace Generators { template class TakeGenerator final : public IGenerator { GeneratorWrapper m_generator; size_t m_returned = 0; size_t m_target; void skipToNthElementImpl( std::size_t n ) override { if ( n >= m_target ) { Detail::throw_generator_exception( "Could not jump to Nth element: not enough elements" ); } m_generator.skipToNthElement( n ); m_returned = n; } public: TakeGenerator(size_t target, GeneratorWrapper&& generator): m_generator(CATCH_MOVE(generator)), m_target(target) { assert(target != 0 && "Empty generators are not allowed"); } T const& get() const override { return m_generator.get(); } bool next() override { ++m_returned; if (m_returned >= m_target) { return false; } const auto success = m_generator.next(); // If the underlying generator does not contain enough values // then we cut short as well if (!success) { m_returned = m_target; } return success; } bool isFinite() const override { return true; } }; template GeneratorWrapper take(size_t target, GeneratorWrapper&& generator) { return GeneratorWrapper(Catch::Detail::make_unique>(target, CATCH_MOVE(generator))); } template class FilterGenerator final : public IGenerator { GeneratorWrapper m_generator; Predicate m_predicate; static_assert(!std::is_reference::value, "This would most likely result in a dangling reference"); public: template FilterGenerator(P&& pred, GeneratorWrapper&& generator): m_generator(CATCH_MOVE(generator)), m_predicate(CATCH_FORWARD(pred)) { if (!m_predicate(m_generator.get())) { // It might happen that there are no values that pass the // filter. In that case we throw an exception. auto has_initial_value = next(); if (!has_initial_value) { Detail::throw_generator_exception("No valid value found in filtered generator"); } } } T const& get() const override { return m_generator.get(); } bool next() override { bool success = m_generator.next(); if (!success) { return false; } while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true); return success; } bool isFinite() const override { return m_generator.isFinite(); } }; template GeneratorWrapper filter(Predicate&& pred, GeneratorWrapper&& generator) { return GeneratorWrapper(Catch::Detail::make_unique::type>>(CATCH_FORWARD(pred), CATCH_MOVE(generator))); } template class RepeatGenerator final : public IGenerator { static_assert(!std::is_same::value, "RepeatGenerator currently does not support bools" "because of std::vector specialization"); GeneratorWrapper m_generator; mutable std::vector m_returned; size_t m_target_repeats; size_t m_current_repeat = 0; size_t m_repeat_index = 0; public: RepeatGenerator(size_t repeats, GeneratorWrapper&& generator): m_generator(CATCH_MOVE(generator)), m_target_repeats(repeats) { assert(m_target_repeats > 0 && "Repeat generator must repeat at least once"); if (!m_generator.isFinite()) { Detail::throw_generator_exception( "Cannot repeat infinite generator" ); } } T const& get() const override { if (m_current_repeat == 0) { m_returned.push_back(m_generator.get()); return m_returned.back(); } return m_returned[m_repeat_index]; } bool next() override { // There are 2 basic cases: // 1) We are still reading the generator // 2) We are reading our own cache // In the first case, we need to poke the underlying generator. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache if (m_current_repeat == 0) { const auto success = m_generator.next(); if (!success) { ++m_current_repeat; } return m_current_repeat < m_target_repeats; } // In the second case, we need to move indices forward and check that we haven't run up against the end ++m_repeat_index; if (m_repeat_index == m_returned.size()) { m_repeat_index = 0; ++m_current_repeat; } return m_current_repeat < m_target_repeats; } bool isFinite() const override { return m_generator.isFinite(); } }; template GeneratorWrapper repeat(size_t repeats, GeneratorWrapper&& generator) { return GeneratorWrapper(Catch::Detail::make_unique>(repeats, CATCH_MOVE(generator))); } template class MapGenerator final : public IGenerator { // TBD: provide static assert for mapping function, for friendly error message GeneratorWrapper m_generator; Func m_function; // To avoid returning dangling reference, we have to save the values mutable Optional m_cache; void skipToNthElementImpl( std::size_t n ) override { m_generator.skipToNthElement( n ); m_cache.reset(); } public: template MapGenerator(F2&& function, GeneratorWrapper&& generator) : m_generator(CATCH_MOVE(generator)), m_function(CATCH_FORWARD(function)) {} T const& get() const override { if ( !m_cache ) { m_cache = m_function( m_generator.get() ); } return *m_cache; } bool next() override { m_cache.reset(); return m_generator.next(); } bool isFinite() const override { return m_generator.isFinite(); } }; template > GeneratorWrapper map(Func&& function, GeneratorWrapper&& generator) { return GeneratorWrapper( Catch::Detail::make_unique>(CATCH_FORWARD(function), CATCH_MOVE(generator)) ); } template GeneratorWrapper map(Func&& function, GeneratorWrapper&& generator) { return GeneratorWrapper( Catch::Detail::make_unique>(CATCH_FORWARD(function), CATCH_MOVE(generator)) ); } template class ChunkGenerator final : public IGenerator> { std::vector m_chunk; size_t m_chunk_size; GeneratorWrapper m_generator; public: ChunkGenerator(size_t size, GeneratorWrapper generator) : m_chunk_size(size), m_generator(CATCH_MOVE(generator)) { m_chunk.reserve(m_chunk_size); if (m_chunk_size != 0) { m_chunk.push_back(m_generator.get()); for (size_t i = 1; i < m_chunk_size; ++i) { if (!m_generator.next()) { Detail::throw_generator_exception("Not enough values to initialize the first chunk"); } m_chunk.push_back(m_generator.get()); } } } std::vector const& get() const override { return m_chunk; } bool next() override { m_chunk.clear(); for (size_t idx = 0; idx < m_chunk_size; ++idx) { if (!m_generator.next()) { return false; } m_chunk.push_back(m_generator.get()); } return true; } bool isFinite() const override { return m_generator.isFinite(); } }; template GeneratorWrapper> chunk(size_t size, GeneratorWrapper&& generator) { return GeneratorWrapper>( Catch::Detail::make_unique>(size, CATCH_MOVE(generator)) ); } template class ConcatGenerator final : public IGenerator { std::vector> m_generators; size_t m_current_generator = 0; void InsertGenerators( GeneratorWrapper&& gen ) { m_generators.push_back( CATCH_MOVE( gen ) ); } template void InsertGenerators( GeneratorWrapper&& gen, Generators&&... gens ) { m_generators.push_back( CATCH_MOVE( gen ) ); InsertGenerators( CATCH_MOVE( gens )... ); } public: template ConcatGenerator( Generators&&... generators ) { InsertGenerators( CATCH_MOVE( generators )... ); } T const& get() const override { return m_generators[m_current_generator].get(); } bool next() override { const bool success = m_generators[m_current_generator].next(); if ( success ) { return true; } // If current generator is used up, we have to move to the next one ++m_current_generator; return m_current_generator < m_generators.size(); } bool isFinite() const override { for ( auto const& gen : m_generators ) { if ( !gen.isFinite() ) { return false; } } return true; } }; template GeneratorWrapper cat( GeneratorWrapper&& generator, Generators&&... generators ) { return GeneratorWrapper( Catch::Detail::make_unique>( CATCH_MOVE( generator ), CATCH_MOVE( generators )... ) ); } } // namespace Generators } // namespace Catch #include namespace Catch { // Exception type to be thrown when a Generator runs into an error, // e.g. it cannot initialize the first return value based on // runtime information class GeneratorException : public std::exception { const char* const m_msg = ""; public: GeneratorException(const char* msg): m_msg(msg) {} const char* what() const noexcept final; }; } // end namespace Catch #include namespace Catch { // This is a simple implementation of C++11 Uniform Random Number // Generator. It does not provide all operators, because Catch2 // does not use it, but it should behave as expected inside stdlib's // distributions. // The implementation is based on the PCG family (http://pcg-random.org) class SimplePcg32 { using state_type = std::uint64_t; public: using result_type = std::uint32_t; static constexpr result_type (min)() { return 0; } static constexpr result_type (max)() { return static_cast(-1); } // Provide some default initial state for the default constructor SimplePcg32():SimplePcg32(0xed743cc4U) {} explicit SimplePcg32(result_type seed_); void seed(result_type seed_); void discard(uint64_t skip); result_type operator()(); private: friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs); friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs); // In theory we also need operator<< and operator>> // In practice we do not use them, so we will skip them for now std::uint64_t m_state; // This part of the state determines which "stream" of the numbers // is chosen -- we take it as a constant for Catch2, so we only // need to deal with seeding the main state. // Picked by reading 8 bytes from `/dev/random` :-) static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL; }; } // end namespace Catch #include #include #include #include // Note: We use the usual enable-disable-autodetect dance here even though // we do not support these in CMake configuration options (yet?). // It is highly unlikely that we will need to make these actually // user-configurable, but this will make it simpler if weend up needing // it, and it provides an escape hatch to the users who need it. #if defined( __SIZEOF_INT128__ ) # define CATCH_CONFIG_INTERNAL_UINT128 // Unlike GCC, MSVC does not polyfill umul as mulh + mul pair on ARM machines. // Currently we do not bother doing this ourselves, but we could if it became // important for perf. #elif defined( _MSC_VER ) && defined( _M_X64 ) # define CATCH_CONFIG_INTERNAL_MSVC_UMUL128 #endif #if defined( CATCH_CONFIG_INTERNAL_UINT128 ) && \ !defined( CATCH_CONFIG_NO_UINT128 ) && \ !defined( CATCH_CONFIG_UINT128 ) #define CATCH_CONFIG_UINT128 #endif #if defined( CATCH_CONFIG_INTERNAL_MSVC_UMUL128 ) && \ !defined( CATCH_CONFIG_NO_MSVC_UMUL128 ) && \ !defined( CATCH_CONFIG_MSVC_UMUL128 ) # define CATCH_CONFIG_MSVC_UMUL128 # include #endif namespace Catch { namespace Detail { template struct SizedUnsignedType; #define SizedUnsignedTypeHelper( TYPE ) \ template <> \ struct SizedUnsignedType { \ using type = TYPE; \ } SizedUnsignedTypeHelper( std::uint8_t ); SizedUnsignedTypeHelper( std::uint16_t ); SizedUnsignedTypeHelper( std::uint32_t ); SizedUnsignedTypeHelper( std::uint64_t ); #undef SizedUnsignedTypeHelper template using SizedUnsignedType_t = typename SizedUnsignedType::type; template using DoubleWidthUnsignedType_t = SizedUnsignedType_t<2 * sizeof( T )>; template struct ExtendedMultResult { T upper; T lower; constexpr bool operator==( ExtendedMultResult const& rhs ) const { return upper == rhs.upper && lower == rhs.lower; } }; /** * Returns 128 bit result of lhs * rhs using portable C++ code * * This implementation is almost twice as fast as naive long multiplication, * and unlike intrinsic-based approach, it supports constexpr evaluation. */ constexpr ExtendedMultResult extendedMultPortable(std::uint64_t lhs, std::uint64_t rhs) { #define CarryBits( x ) ( x >> 32 ) #define Digits( x ) ( x & 0xFF'FF'FF'FF ) std::uint64_t lhs_low = Digits( lhs ); std::uint64_t rhs_low = Digits( rhs ); std::uint64_t low_low = ( lhs_low * rhs_low ); std::uint64_t high_high = CarryBits( lhs ) * CarryBits( rhs ); // We add in carry bits from low-low already std::uint64_t high_low = ( CarryBits( lhs ) * rhs_low ) + CarryBits( low_low ); // Note that we can add only low bits from high_low, to avoid // overflow with large inputs std::uint64_t low_high = ( lhs_low * CarryBits( rhs ) ) + Digits( high_low ); return { high_high + CarryBits( high_low ) + CarryBits( low_high ), ( low_high << 32 ) | Digits( low_low ) }; #undef CarryBits #undef Digits } //! Returns 128 bit result of lhs * rhs inline ExtendedMultResult extendedMult( std::uint64_t lhs, std::uint64_t rhs ) { #if defined( CATCH_CONFIG_UINT128 ) auto result = __uint128_t( lhs ) * __uint128_t( rhs ); return { static_cast( result >> 64 ), static_cast( result ) }; #elif defined( CATCH_CONFIG_MSVC_UMUL128 ) std::uint64_t high; std::uint64_t low = _umul128( lhs, rhs, &high ); return { high, low }; #else return extendedMultPortable( lhs, rhs ); #endif } template constexpr ExtendedMultResult extendedMult( UInt lhs, UInt rhs ) { static_assert( std::is_unsigned::value, "extendedMult can only handle unsigned integers" ); static_assert( sizeof( UInt ) < sizeof( std::uint64_t ), "Generic extendedMult can only handle types smaller " "than uint64_t" ); using WideType = DoubleWidthUnsignedType_t; auto result = WideType( lhs ) * WideType( rhs ); return { static_cast( result >> ( CHAR_BIT * sizeof( UInt ) ) ), static_cast( result & UInt( -1 ) ) }; } template std::enable_if_t= sizeof(TargetType), TargetType> fillBitsFrom(Generator& gen) { using gresult_type = typename Generator::result_type; static_assert( std::is_unsigned::value, "Only unsigned integers are supported" ); static_assert( Generator::min() == 0 && Generator::max() == static_cast( -1 ), "Generator must be able to output all numbers in its result type (effectively it must be a random bit generator)" ); // We want to return the top bits from a generator, as they are // usually considered higher quality. constexpr auto generated_bits = sizeof( gresult_type ) * CHAR_BIT; constexpr auto return_bits = sizeof( TargetType ) * CHAR_BIT; return static_cast( gen() >> ( generated_bits - return_bits) ); } template std::enable_if_t fillBitsFrom(Generator& gen) { using gresult_type = typename Generator::result_type; static_assert( std::is_unsigned::value, "Only unsigned integers are supported" ); static_assert( Generator::min() == 0 && Generator::max() == static_cast( -1 ), "Generator must be able to output all numbers in its result type (effectively it must be a random bit generator)" ); constexpr auto generated_bits = sizeof( gresult_type ) * CHAR_BIT; constexpr auto return_bits = sizeof( TargetType ) * CHAR_BIT; std::size_t filled_bits = 0; TargetType ret = 0; do { ret <<= generated_bits; ret |= gen(); filled_bits += generated_bits; } while ( filled_bits < return_bits ); return ret; } /* * Transposes numbers into unsigned type while keeping their ordering * * This means that signed types are changed so that the ordering is * [INT_MIN, ..., -1, 0, ..., INT_MAX], rather than order we would * get by simple casting ([0, ..., INT_MAX, INT_MIN, ..., -1]) */ template constexpr std::enable_if_t::value, UnsignedType> transposeToNaturalOrder( UnsignedType in ) { static_assert( sizeof( OriginalType ) == sizeof( UnsignedType ), "reordering requires the same sized types on both sides" ); static_assert( std::is_unsigned::value, "Input type must be unsigned" ); // Assuming 2s complement (standardized in current C++), the // positive and negative numbers are already internally ordered, // and their difference is in the top bit. Swapping it orders // them the desired way. constexpr auto highest_bit = UnsignedType( 1 ) << ( sizeof( UnsignedType ) * CHAR_BIT - 1 ); return static_cast( in ^ highest_bit ); } template constexpr std::enable_if_t::value, UnsignedType> transposeToNaturalOrder(UnsignedType in) { static_assert( sizeof( OriginalType ) == sizeof( UnsignedType ), "reordering requires the same sized types on both sides" ); static_assert( std::is_unsigned::value, "Input type must be unsigned" ); // No reordering is needed for unsigned -> unsigned return in; } } // namespace Detail } // namespace Catch namespace Catch { /** * Implementation of uniform distribution on integers. * * Unlike `std::uniform_int_distribution`, this implementation supports * various 1 byte integral types, including bool (but you should not * actually use it for bools). * * The underlying algorithm is based on the one described in "Fast Random * Integer Generation in an Interval" by Daniel Lemire, but has been * optimized under the assumption of reuse of the same distribution object. */ template class uniform_integer_distribution { static_assert(std::is_integral::value, "..."); using UnsignedIntegerType = Detail::SizedUnsignedType_t; // Only the left bound is stored, and we store it converted to its // unsigned image. This avoids having to do the conversions inside // the operator(), at the cost of having to do the conversion in // the a() getter. The right bound is only needed in the b() getter, // so we recompute it there from other stored data. UnsignedIntegerType m_a; // How many different values are there in [a, b]. a == b => 1, can be 0 for distribution over all values in the type. UnsignedIntegerType m_ab_distance; // We hoisted this out of the main generation function. Technically, // this means that using this distribution will be slower than Lemire's // algorithm if this distribution instance will be used only few times, // but it will be faster if it is used many times. Since Catch2 uses // distributions only to implement random generators, we assume that each // distribution will be reused many times and this is an optimization. UnsignedIntegerType m_rejection_threshold = 0; static constexpr UnsignedIntegerType computeDistance(IntegerType a, IntegerType b) { // This overflows and returns 0 if a == 0 and b == TYPE_MAX. // We handle that later when generating the number. return transposeTo(b) - transposeTo(a) + 1; } static constexpr UnsignedIntegerType computeRejectionThreshold(UnsignedIntegerType ab_distance) { // distance == 0 means that we will return all possible values from // the type's range, and that we shouldn't reject anything. if ( ab_distance == 0 ) { return 0; } return ( ~ab_distance + 1 ) % ab_distance; } static constexpr UnsignedIntegerType transposeTo(IntegerType in) { return Detail::transposeToNaturalOrder( static_cast( in ) ); } static constexpr IntegerType transposeBack(UnsignedIntegerType in) { return static_cast( Detail::transposeToNaturalOrder(in) ); } public: using result_type = IntegerType; constexpr uniform_integer_distribution( IntegerType a, IntegerType b ): m_a( transposeTo(a) ), m_ab_distance( computeDistance(a, b) ), m_rejection_threshold( computeRejectionThreshold(m_ab_distance) ) { assert( a <= b ); } template constexpr result_type operator()( Generator& g ) { // All possible values of result_type are valid. if ( m_ab_distance == 0 ) { return transposeBack( Detail::fillBitsFrom( g ) ); } auto random_number = Detail::fillBitsFrom( g ); auto emul = Detail::extendedMult( random_number, m_ab_distance ); // Unlike Lemire's algorithm we skip the ab_distance check, since // we precomputed the rejection threshold, which is always tighter. while (emul.lower < m_rejection_threshold) { random_number = Detail::fillBitsFrom( g ); emul = Detail::extendedMult( random_number, m_ab_distance ); } return transposeBack(m_a + emul.upper); } constexpr result_type a() const { return transposeBack(m_a); } constexpr result_type b() const { return transposeBack(m_ab_distance + m_a - 1); } }; } // end namespace Catch namespace Catch { bool isnan(float f); bool isnan(double d); float nextafter(float x, float y); double nextafter(double x, double y); } #include #include #include #include #include namespace Catch { namespace Detail { /** * Returns the largest magnitude of 1-ULP distance inside the [a, b] range. * * Assumes `a < b`. */ template FloatType gamma(FloatType a, FloatType b) { static_assert( std::is_floating_point::value, "gamma returns the largest ULP magnitude within " "floating point range [a, b]. This only makes sense " "for floating point types" ); assert( a <= b ); const auto gamma_up = Catch::nextafter( a, std::numeric_limits::infinity() ) - a; const auto gamma_down = b - Catch::nextafter( b, -std::numeric_limits::infinity() ); return gamma_up < gamma_down ? gamma_down : gamma_up; } template struct DistanceTypePicker; template <> struct DistanceTypePicker { using type = std::uint32_t; }; template <> struct DistanceTypePicker { using type = std::uint64_t; }; template using DistanceType = typename DistanceTypePicker::type; #if defined( __GNUC__ ) || defined( __clang__ ) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wfloat-equal" #endif /** * Computes the number of equi-distant floats in [a, b] * * Since not every range can be split into equidistant floats * exactly, we actually compute ceil(b/distance - a/distance), * because in those cases we want to overcount. * * Uses modified Dekker's FastTwoSum algorithm to handle rounding. */ template DistanceType count_equidistant_floats( FloatType a, FloatType b, FloatType distance ) { assert( a <= b ); // We get distance as gamma for our uniform float distribution, // so this will round perfectly. const auto ag = a / distance; const auto bg = b / distance; const auto s = bg - ag; const auto err = ( std::fabs( a ) <= std::fabs( b ) ) ? -ag - ( s - bg ) : bg - ( s + ag ); const auto ceil_s = static_cast>( std::ceil( s ) ); return ( ceil_s != s ) ? ceil_s : ceil_s + ( err > 0 ); } #if defined( __GNUC__ ) || defined( __clang__ ) # pragma GCC diagnostic pop #endif } } // end namespace Catch #include #include namespace Catch { namespace Detail { #if defined( __GNUC__ ) || defined( __clang__ ) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wfloat-equal" #endif // The issue with overflow only happens with maximal ULP and HUGE // distance, e.g. when generating numbers in [-inf, inf] for given // type. So we only check for the largest possible ULP in the // type, and return something that does not overflow to inf in 1 mult. constexpr std::uint64_t calculate_max_steps_in_one_go(double gamma) { if ( gamma == 1.99584030953472e+292 ) { return 9007199254740991; } return static_cast( -1 ); } constexpr std::uint32_t calculate_max_steps_in_one_go(float gamma) { if ( gamma == 2.028241e+31f ) { return 16777215; } return static_cast( -1 ); } #if defined( __GNUC__ ) || defined( __clang__ ) # pragma GCC diagnostic pop #endif } /** * Implementation of uniform distribution on floating point numbers. * * Note that we support only `float` and `double` types, because these * usually mean the same thing across different platform. `long double` * varies wildly by platform and thus we cannot provide reproducible * implementation. Also note that we don't implement all parts of * distribution per standard: this distribution is not serializable, nor * can the range be arbitrarily reset. * * The implementation also uses different approach than the one taken by * `std::uniform_real_distribution`, where instead of generating a number * between [0, 1) and then multiplying the range bounds with it, we first * split the [a, b] range into a set of equidistributed floating point * numbers, and then use uniform int distribution to pick which one to * return. * * This has the advantage of guaranteeing uniformity (the multiplication * method loses uniformity due to rounding when multiplying floats), except * for small non-uniformity at one side of the interval, where we have * to deal with the fact that not every interval is splittable into * equidistributed floats. * * Based on "Drawing random floating-point numbers from an interval" by * Frederic Goualard. */ template class uniform_floating_point_distribution { static_assert(std::is_floating_point::value, "..."); static_assert(!std::is_same::value, "We do not support long double due to inconsistent behaviour between platforms"); using WidthType = Detail::DistanceType; FloatType m_a, m_b; FloatType m_ulp_magnitude; WidthType m_floats_in_range; uniform_integer_distribution m_int_dist; // In specific cases, we can overflow into `inf` when computing the // `steps * g` offset. To avoid this, we don't offset by more than this // in one multiply + addition. WidthType m_max_steps_in_one_go; // We don't want to do the magnitude check every call to `operator()` bool m_a_has_leq_magnitude; public: using result_type = FloatType; uniform_floating_point_distribution( FloatType a, FloatType b ): m_a( a ), m_b( b ), m_ulp_magnitude( Detail::gamma( m_a, m_b ) ), m_floats_in_range( Detail::count_equidistant_floats( m_a, m_b, m_ulp_magnitude ) ), m_int_dist(0, m_floats_in_range), m_max_steps_in_one_go( Detail::calculate_max_steps_in_one_go(m_ulp_magnitude)), m_a_has_leq_magnitude(std::fabs(m_a) <= std::fabs(m_b)) { assert( a <= b ); } template result_type operator()( Generator& g ) { WidthType steps = m_int_dist( g ); if ( m_a_has_leq_magnitude ) { if ( steps == m_floats_in_range ) { return m_a; } auto b = m_b; while (steps > m_max_steps_in_one_go) { b -= m_max_steps_in_one_go * m_ulp_magnitude; steps -= m_max_steps_in_one_go; } return b - steps * m_ulp_magnitude; } else { if ( steps == m_floats_in_range ) { return m_b; } auto a = m_a; while (steps > m_max_steps_in_one_go) { a += m_max_steps_in_one_go * m_ulp_magnitude; steps -= m_max_steps_in_one_go; } return a + steps * m_ulp_magnitude; } } result_type a() const { return m_a; } result_type b() const { return m_b; } }; } // end namespace Catch namespace Catch { namespace Generators { namespace Detail { // Returns a suitable seed for a random floating generator based off // the primary internal rng. It does so by taking current value from // the rng and returning it as the seed. std::uint32_t getSeed(); } template class RandomFloatingGenerator final : public IGenerator { Catch::SimplePcg32 m_rng; Catch::uniform_floating_point_distribution m_dist; Float m_current_number; public: RandomFloatingGenerator( Float a, Float b, std::uint32_t seed ): m_rng(seed), m_dist(a, b) { static_cast(next()); } Float const& get() const override { return m_current_number; } bool next() override { m_current_number = m_dist(m_rng); return true; } bool isFinite() const override { return false; } }; template <> class RandomFloatingGenerator final : public IGenerator { // We still rely on for this specialization, but we don't // want to drag it into the header. struct PImpl; Catch::Detail::unique_ptr m_pimpl; long double m_current_number; public: RandomFloatingGenerator( long double a, long double b, std::uint32_t seed ); long double const& get() const override { return m_current_number; } bool next() override; ~RandomFloatingGenerator() override; // = default bool isFinite() const override; }; template class RandomIntegerGenerator final : public IGenerator { Catch::SimplePcg32 m_rng; Catch::uniform_integer_distribution m_dist; Integer m_current_number; public: RandomIntegerGenerator( Integer a, Integer b, std::uint32_t seed ): m_rng(seed), m_dist(a, b) { static_cast(next()); } Integer const& get() const override { return m_current_number; } bool next() override { m_current_number = m_dist(m_rng); return true; } bool isFinite() const override { return false; } }; template std::enable_if_t::value, GeneratorWrapper> random(T a, T b) { return GeneratorWrapper( Catch::Detail::make_unique>(a, b, Detail::getSeed()) ); } template std::enable_if_t::value, GeneratorWrapper> random(T a, T b) { return GeneratorWrapper( Catch::Detail::make_unique>(a, b, Detail::getSeed()) ); } } // namespace Generators } // namespace Catch #include #include #include namespace Catch { namespace Generators { template class RangeGenerator final : public IGenerator { T m_current; T m_end; T m_step; bool m_positive; public: RangeGenerator(T const& start, T const& end, T const& step): m_current(start), m_end(end), m_step(step), m_positive(m_step > T(0)) { assert(m_current != m_end && "Range start and end cannot be equal"); assert(m_step != T(0) && "Step size cannot be zero"); assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end"); } RangeGenerator(T const& start, T const& end): RangeGenerator(start, end, (start < end) ? T(1) : T(-1)) {} T const& get() const override { return m_current; } bool next() override { m_current += m_step; return (m_positive) ? (m_current < m_end) : (m_current > m_end); } bool isFinite() const override { return true; } }; template GeneratorWrapper range(T const& start, T const& end, T const& step) { static_assert(std::is_arithmetic::value && !std::is_same::value, "Type must be numeric"); return GeneratorWrapper(Catch::Detail::make_unique>(start, end, step)); } template GeneratorWrapper range(T const& start, T const& end) { static_assert(std::is_integral::value && !std::is_same::value, "Type must be an integer"); return GeneratorWrapper(Catch::Detail::make_unique>(start, end)); } template class IteratorGenerator final : public IGenerator { static_assert(!std::is_same::value, "IteratorGenerator currently does not support bools" "because of std::vector specialization"); std::vector m_elems; size_t m_current = 0; public: template IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) { if (m_elems.empty()) { Detail::throw_generator_exception("IteratorGenerator received no valid values"); } } T const& get() const override { return m_elems[m_current]; } bool next() override { ++m_current; return m_current != m_elems.size(); } bool isFinite() const override { return true; } }; template ::value_type>> GeneratorWrapper from_range(InputIterator from, InputSentinel to) { return GeneratorWrapper(Catch::Detail::make_unique>(from, to)); } template auto from_range(Container const& cnt) { using std::begin; using std::end; return from_range( begin( cnt ), end( cnt ) ); } } // namespace Generators } // namespace Catch #include namespace Catch { //! Returns Catch2's current RNG seed. std::uint32_t getSeed(); } /** \file * This is a convenience header for Catch2's interfaces. It includes * **all** of Catch2 headers related to interfaces. * * Generally the Catch2 users should use specific includes they need, * but this header can be used instead for ease-of-experimentation, or * just plain convenience, at the cost of somewhat increased compilation * times. * * When a new header is added to either the `interfaces` folder, or to * the corresponding internal subfolder, it should be added here. */ #include namespace Catch { class IConfig; class IEventListener; using IEventListenerPtr = Detail::unique_ptr; class EventListenerFactory { public: virtual ~EventListenerFactory(); // = default virtual IEventListenerPtr create( IConfig const* config ) const = 0; //! Return a meaningful name for the listener, e.g. its type name virtual StringRef getName() const = 0; //! Return listener's description if available virtual std::string getDescription() const = 0; }; } // namespace Catch #include namespace Catch { struct Counts { Counts operator - ( Counts const& other ) const; Counts& operator += ( Counts const& other ); std::uint64_t total() const; bool allPassed() const; bool allOk() const; std::uint64_t passed = 0; std::uint64_t failed = 0; std::uint64_t failedButOk = 0; std::uint64_t skipped = 0; }; struct Totals { Totals operator - ( Totals const& other ) const; Totals& operator += ( Totals const& other ); Totals delta( Totals const& prevTotals ) const; Counts assertions; Counts testCases; }; } #include namespace Catch { struct SectionInfo { // The last argument is ignored, so that people can write // SECTION("ShortName", "Proper description that is long") and // still use the `-c` flag comfortably. SectionInfo( SourceLineInfo const& _lineInfo, std::string _name, const char* const = nullptr ): name(CATCH_MOVE(_name)), lineInfo(_lineInfo) {} std::string name; SourceLineInfo lineInfo; }; struct SectionEndInfo { SectionInfo sectionInfo; Counts prevAssertions; double durationInSeconds; }; } // end namespace Catch namespace Catch { struct TestRunInfo { constexpr TestRunInfo(StringRef _name) : name(_name) {} StringRef name; }; } // end namespace Catch #if !defined( CATCH_CONFIG_NO_DEPRECATION_ANNOTATIONS ) # define CATCH_DEPRECATED( msg ) [[deprecated( msg )]] #else # define CATCH_DEPRECATED( msg ) #endif #include namespace Catch { struct MessageInfo { MessageInfo( StringRef _macroName, SourceLineInfo const& _lineInfo, ResultWas::OfType _type ); StringRef macroName; std::string message; SourceLineInfo lineInfo; ResultWas::OfType type; // The "ID" of the message, used to know when to remove it from reporter context. unsigned int sequence; CATCH_DEPRECATED( "Explicitly use the 'sequence' member instead" ) bool operator == (MessageInfo const& other) const { return sequence == other.sequence; } CATCH_DEPRECATED( "Explicitly use the 'sequence' member instead" ) bool operator < (MessageInfo const& other) const { return sequence < other.sequence; } }; } // end namespace Catch #include #include #include namespace Catch { struct TestCaseInfo; class TestCaseHandle; class IConfig; enum class ColourMode : std::uint8_t; struct AssertionStats { AssertionStats( AssertionResult const& _assertionResult, std::vector const& _infoMessages, Totals const& _totals ); AssertionStats( AssertionStats const& ) = default; AssertionStats( AssertionStats && ) = default; AssertionStats& operator = ( AssertionStats const& ) = delete; AssertionStats& operator = ( AssertionStats && ) = delete; AssertionResult assertionResult; std::vector infoMessages; Totals totals; }; struct SectionStats { SectionStats( SectionInfo&& _sectionInfo, Counts const& _assertions, double _durationInSeconds, bool _missingAssertions ); SectionInfo sectionInfo; Counts assertions; double durationInSeconds; bool missingAssertions; }; struct TestCaseStats { TestCaseStats( TestCaseInfo const& _testInfo, Totals const& _totals, std::string&& _stdOut, std::string&& _stdErr, bool _aborting ); TestCaseInfo const * testInfo; Totals totals; std::string stdOut; std::string stdErr; bool aborting; }; struct TestRunStats { TestRunStats( TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting ); TestRunInfo runInfo; Totals totals; bool aborting; }; //! By setting up its preferences, a reporter can modify Catch2's behaviour //! in some regards, e.g. it can request Catch2 to capture writes to //! stdout/stderr during test execution, and pass them to the reporter. struct ReporterPreferences { //! Catch2 should redirect writes to stdout and pass them to the //! reporter bool shouldRedirectStdOut = false; //! Catch2 should call `Reporter::assertionEnded` even for passing //! assertions bool shouldReportAllAssertions = false; //! Catch2 should call `Reporter::assertionStarting` for all assertions // Defaults to true for backwards compatibility, but none of our current // reporters actually want this, and it enables a fast path in assertion // handling. bool shouldReportAllAssertionStarts = true; }; /** * The common base for all reporters and event listeners * * Implementing classes must also implement: * * //! User-friendly description of the reporter/listener type * static std::string getDescription() * * Generally shouldn't be derived from by users of Catch2 directly, * instead they should derive from one of the utility bases that * derive from this class. */ class IEventListener { protected: //! Derived classes can set up their preferences here ReporterPreferences m_preferences; //! The test run's config as filled in from CLI and defaults IConfig const* m_config; public: IEventListener( IConfig const* config ): m_config( config ) {} virtual ~IEventListener(); // = default; // Implementing class must also provide the following static methods: // static std::string getDescription(); ReporterPreferences const& getPreferences() const { return m_preferences; } //! Called when no test cases match provided test spec virtual void noMatchingTestCases( StringRef unmatchedSpec ) = 0; //! Called for all invalid test specs from the cli virtual void reportInvalidTestSpec( StringRef invalidArgument ) = 0; /** * Called once in a testing run before tests are started * * Not called if tests won't be run (e.g. only listing will happen) */ virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; //! Called _once_ for each TEST_CASE, no matter how many times it is entered virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; //! Called _every time_ a TEST_CASE is entered, including repeats (due to sections) virtual void testCasePartialStarting( TestCaseInfo const& testInfo, uint64_t partNumber ) = 0; //! Called when a `SECTION` is being entered. Not called for skipped sections virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; //! Called when user-code is being probed before the actual benchmark runs virtual void benchmarkPreparing( StringRef benchmarkName ) = 0; //! Called after probe but before the user-code is being benchmarked virtual void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) = 0; //! Called with the benchmark results if benchmark successfully finishes virtual void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) = 0; //! Called if running the benchmarks fails for any reason virtual void benchmarkFailed( StringRef benchmarkName ) = 0; //! Called before assertion success/failure is evaluated virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; //! Called after assertion was fully evaluated virtual void assertionEnded( AssertionStats const& assertionStats ) = 0; //! Called after a `SECTION` has finished running virtual void sectionEnded( SectionStats const& sectionStats ) = 0; //! Called _every time_ a TEST_CASE is entered, including repeats (due to sections) virtual void testCasePartialEnded(TestCaseStats const& testCaseStats, uint64_t partNumber ) = 0; //! Called _once_ for each TEST_CASE, no matter how many times it is entered virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; /** * Called once after all tests in a testing run are finished * * Not called if tests weren't run (e.g. only listings happened) */ virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; //! Called if a fatal error (signal/structured exception) occurred virtual void fatalErrorEncountered( StringRef error ) = 0; }; using IEventListenerPtr = Detail::unique_ptr; } // end namespace Catch #include #include namespace Catch { using exceptionTranslateFunction = std::string(*)(); class IExceptionTranslator; using ExceptionTranslators = std::vector>; class IExceptionTranslator { public: virtual ~IExceptionTranslator(); // = default virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0; }; class IExceptionTranslatorRegistry { public: virtual ~IExceptionTranslatorRegistry(); // = default virtual std::string translateActiveException() const = 0; }; } // namespace Catch #include namespace Catch { struct TagAlias; class ITagAliasRegistry { public: virtual ~ITagAliasRegistry(); // = default // Nullptr if not present virtual TagAlias const* find( std::string const& alias ) const = 0; virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; static ITagAliasRegistry const& get(); }; } // end namespace Catch #include namespace Catch { struct TestCaseInfo; class TestCaseHandle; class IConfig; class ITestCaseRegistry { public: virtual ~ITestCaseRegistry(); // = default virtual void enableFilenameTags() = 0; virtual std::vector const& getAllTests() const = 0; virtual std::vector const& getAllTestsSorted( IConfig const& config ) const = 0; }; } namespace Catch { class ITestInvoker { public: virtual void prepareTestCase(); virtual void tearDownTestCase(); virtual void invoke() const = 0; virtual ~ITestInvoker(); // = default }; } // namespace Catch #include namespace Catch { namespace Detail { #if defined( __GNUC__ ) && !defined( __clang__ ) # pragma GCC diagnostic push // GCC likes to complain about comparing bool with 0, in the decltype() // that defines the comparable traits below. # pragma GCC diagnostic ignored "-Wbool-compare" // "ordered comparison of pointer with integer zero" same as above, // but it does not have a separate warning flag to suppress # pragma GCC diagnostic ignored "-Wextra" // Did you know that comparing floats with `0` directly // is super-duper dangerous in unevaluated context? # pragma GCC diagnostic ignored "-Wfloat-equal" #endif #if defined( __clang__ ) # pragma clang diagnostic push // Did you know that comparing floats with `0` directly // is super-duper dangerous in unevaluated context? # pragma clang diagnostic ignored "-Wfloat-equal" #endif // To avoid instantiating all of `is_foo_comparable`, // `is_foo_comparable`, `is_foo_comparable`, ... // we force the type into simple T ref. This does not cause behaviour // change, because the decomposer already only uses lvalues. // // Note that we do not strip away constness, as that would make // the comparability of `const T` dependent on comparability of `T`, // which could lead to behavior change from the current implementation. template using IsComparableNormalized_t = std::remove_reference_t&; #define CATCH_DEFINE_COMPARABLE_TRAIT( id, op ) \ template \ struct is_##id##_comparable_impl : std::false_type {}; \ template \ struct is_##id##_comparable_impl< \ T, \ U, \ void_t() op std::declval() )>> \ : std::true_type {}; \ template \ using is_##id##_comparable = \ is_##id##_comparable_impl, \ IsComparableNormalized_t>; \ template \ struct is_##id##_0_comparable_impl : std::false_type {}; \ template \ struct is_##id##_0_comparable_impl< \ T, \ void_t() op 0 )>> \ : std::true_type {}; \ template \ using is_##id##_0_comparable = \ is_##id##_0_comparable_impl>; // We need all 6 pre-spaceship comparison ops: <, <=, >, >=, ==, != CATCH_DEFINE_COMPARABLE_TRAIT( lt, < ) CATCH_DEFINE_COMPARABLE_TRAIT( le, <= ) CATCH_DEFINE_COMPARABLE_TRAIT( gt, > ) CATCH_DEFINE_COMPARABLE_TRAIT( ge, >= ) CATCH_DEFINE_COMPARABLE_TRAIT( eq, == ) CATCH_DEFINE_COMPARABLE_TRAIT( ne, != ) #undef CATCH_DEFINE_COMPARABLE_TRAIT #if defined( __GNUC__ ) && !defined( __clang__ ) # pragma GCC diagnostic pop #endif #if defined( __clang__ ) # pragma clang diagnostic pop #endif } // namespace Detail } // namespace Catch #include namespace Catch { namespace Detail { #if defined( __cpp_lib_logical_traits ) && __cpp_lib_logical_traits >= 201510 using std::conjunction; using std::disjunction; using std::negation; #else template struct conjunction : std::true_type {}; template struct conjunction : B1 {}; template struct conjunction : std::conditional_t, B1> {}; template struct disjunction : std::false_type {}; template struct disjunction : B1 {}; template struct disjunction : std::conditional_t> {}; template struct negation : std::integral_constant {}; #endif } // namespace Detail } // namespace Catch #include #include /** \file * Why does decomposing look the way it does: * * Conceptually, decomposing is simple. We change `REQUIRE( a == b )` into * `Decomposer{} <= a == b`, so that `Decomposer{} <= a` is evaluated first, * and our custom operator is used for `a == b`, because `a` is transformed * into `ExprLhs` and then into `BinaryExpr`. * * In practice, decomposing ends up a mess, because we have to support * various fun things. * * 1) Types that are only comparable with literal 0, and they do this by * comparing against a magic type with pointer constructor and deleted * other constructors. Example: `REQUIRE((a <=> b) == 0)` in libstdc++ * * 2) Types that are only comparable with literal 0, and they do this by * comparing against a magic type with consteval integer constructor. * Example: `REQUIRE((a <=> b) == 0)` in current MSVC STL. * * 3) Types that have no linkage, and so we cannot form a reference to * them. Example: some implementations of traits. * * 4) Starting with C++20, when the compiler sees `a == b`, it also uses * `b == a` when constructing the overload set. For us this means that * when the compiler handles `ExprLhs == b`, it also tries to resolve * the overload set for `b == ExprLhs`. * * To accommodate these use cases, decomposer ended up rather complex. * * 1) These types are handled by adding SFINAE overloads to our comparison * operators, checking whether `T == U` are comparable with the given * operator, and if not, whether T (or U) are comparable with literal 0. * If yes, the overload compares T (or U) with 0 literal inline in the * definition. * * Note that for extra correctness, we check that the other type is * either an `int` (literal 0 is captured as `int` by templates), or * a `long` (some platforms use 0L for `NULL` and we want to support * that for pointer comparisons). * * 2) For these types, `is_foo_comparable` is true, but letting * them fall into the overload that actually does `T == int` causes * compilation error. Handling them requires that the decomposition * is `constexpr`, so that P2564R3 applies and the `consteval` from * their accompanying magic type is propagated through the `constexpr` * call stack. * * However this is not enough to handle these types automatically, * because our default is to capture types by reference, to avoid * runtime copies. While these references cannot become dangling, * they outlive the constexpr context and thus the default capture * path cannot be actually constexpr. * * The solution is to capture these types by value, by explicitly * specializing `Catch::capture_by_value` for them. Catch2 provides * specialization for `std::foo_ordering`s, but users can specialize * the trait for their own types as well. * * 3) If a type has no linkage, we also cannot capture it by reference. * The solution is once again to capture them by value. We handle * the common cases by using `std::is_arithmetic` and `std::is_enum` * as the default for `Catch::capture_by_value`, but that is only a * some-effort heuristic. These combine to capture all possible bitfield * bases, and also some trait-like types. As with 2), users can * specialize `capture_by_value` for their own types as needed. * * 4) To support C++20 and make the SFINAE on our decomposing operators * work, the SFINAE has to happen in return type, rather than in * a template type. This is due to our use of logical type traits * (`conjunction`/`disjunction`/`negation`), that we use to workaround * an issue in older (9-) versions of GCC. I still blame C++20 for * this, because without the comparison order switching, the logical * traits could still be used in template type. * * There are also other side concerns, e.g. supporting both `REQUIRE(a)` * and `REQUIRE(a == b)`, or making `REQUIRE_THAT(a, IsEqual(b))` slot * nicely into the same expression handling logic, but these are rather * straightforward and add only a bit of complexity (e.g. common base * class for decomposed expressions). */ #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4389) // '==' : signed/unsigned mismatch #pragma warning(disable:4018) // more "signed/unsigned mismatch" #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform) #pragma warning(disable:4180) // qualifier applied to function type has no meaning #pragma warning(disable:4800) // Forcing result to true or false #endif #ifdef __clang__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wsign-compare" # pragma clang diagnostic ignored "-Wnon-virtual-dtor" #elif defined __GNUC__ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wsign-compare" # pragma GCC diagnostic ignored "-Wnon-virtual-dtor" #endif #if defined(CATCH_CPP20_OR_GREATER) && __has_include() # include # if defined( __cpp_lib_three_way_comparison ) && \ __cpp_lib_three_way_comparison >= 201907L # define CATCH_CONFIG_CPP20_COMPARE_OVERLOADS # endif #endif namespace Catch { namespace Detail { // This was added in C++20, but we require only C++17. template using RemoveCVRef_t = std::remove_cv_t>; } // Note: This is about as much as we can currently reasonably support. // In an ideal world, we could capture by value small trivially // copyable types, but the actual `std::is_trivially_copyable` // trait is a huge mess with standard-violating results on // GCC and Clang, which are unlikely to be fixed soon due to ABI // concerns. // `std::is_scalar` also causes issues due to the `is_pointer` // component, which causes ambiguity issues with (references-to) // function pointer. If those are resolved, we still need to // disambiguate the overload set for arrays, through explicit // overload for references to sized arrays. template struct capture_by_value : std::integral_constant::value || std::is_enum::value> {}; #if defined( CATCH_CONFIG_CPP20_COMPARE_OVERLOADS ) template <> struct capture_by_value : std::true_type {}; template <> struct capture_by_value : std::true_type {}; template <> struct capture_by_value : std::true_type {}; #endif template struct always_false : std::false_type {}; class ITransientExpression { //! Type-erased streaming function for the derived expression using StreamFn = void ( * )( void const*, std::ostream& ); StreamFn m_streamFn; bool m_isBinaryExpression; bool m_result; public: constexpr auto isBinaryExpression() const -> bool { return m_isBinaryExpression; } constexpr auto getResult() const -> bool { return m_result; } constexpr ITransientExpression( StreamFn streamFn, bool isBinaryExpression, bool result ): m_streamFn( streamFn ), m_isBinaryExpression( isBinaryExpression ), m_result( result ) {} friend std::ostream& operator<<( std::ostream& out, ITransientExpression const& expr ) { expr.m_streamFn( &expr, out ); return out; } }; void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ); template class BinaryExpr final : public ITransientExpression { LhsT m_lhs; StringRef m_op; RhsT m_rhs; static void streamFn( void const* self, std::ostream& out ) { auto const& expr = *static_cast( static_cast( self ) ); formatReconstructedExpression( out, Catch::Detail::stringify( expr.m_lhs ), expr.m_op, Catch::Detail::stringify( expr.m_rhs ) ); } public: constexpr BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs ) : ITransientExpression{ &streamFn, true, comparisonResult }, m_lhs( lhs ), m_op( op ), m_rhs( rhs ) {} }; #define CATCH_INTERNAL_DEFINE_BINARY_EXPR_OPERATOR( op ) \ template \ auto operator op( BinaryExpr const&, T ) \ ->BinaryExpr const { \ static_assert( always_false::value, \ "chained comparisons are not supported inside " \ "assertions, wrap the expression inside " \ "parentheses, or decompose it" ); \ } /* * The operators are **intentionally** not hidden friends. * * If they were hidden friends, all of them would get stamped out when * a `BinaryExpr` is instantiated with a new type. In practice, only * few operators are used for each different `BinaryExpr`, * so this avoids bunch of wasted work. */ CATCH_INTERNAL_DEFINE_BINARY_EXPR_OPERATOR( && ) CATCH_INTERNAL_DEFINE_BINARY_EXPR_OPERATOR( || ) CATCH_INTERNAL_DEFINE_BINARY_EXPR_OPERATOR( == ) CATCH_INTERNAL_DEFINE_BINARY_EXPR_OPERATOR( != ) CATCH_INTERNAL_DEFINE_BINARY_EXPR_OPERATOR( > ) CATCH_INTERNAL_DEFINE_BINARY_EXPR_OPERATOR( < ) CATCH_INTERNAL_DEFINE_BINARY_EXPR_OPERATOR( >= ) CATCH_INTERNAL_DEFINE_BINARY_EXPR_OPERATOR( <= ) #undef CATCH_INTERNAL_DEFINE_BINARY_EXPR_OPERATOR template class UnaryExpr final : public ITransientExpression { LhsT m_lhs; static void streamFn( void const* self, std::ostream& os ) { auto const& expr = *static_cast( static_cast( self ) ); os << Catch::Detail::stringify( expr.m_lhs ); } public: explicit constexpr UnaryExpr( LhsT lhs ) : ITransientExpression{ &streamFn, false, static_cast(lhs) }, m_lhs( lhs ) {} }; template class ExprLhs { LhsT m_lhs; public: explicit constexpr ExprLhs( LhsT lhs ) : m_lhs( lhs ) {} // We rely on reference collapsing if LhsT is already a reference. // Used in the out-of-class decomposition operators constexpr LhsT& getLhs() { return m_lhs; } constexpr auto makeUnaryExpr() const -> UnaryExpr { return UnaryExpr{ m_lhs }; } }; /* * The comparison operators are **intentionally** not hidden friends. * * If they were hidden friends, all of them would get stamped out when * a `ExprLhs` is instantiated with a new type. In practice, only few * operators are used for each different `ExprLhs`, so this avoids * a lot of wasted work. */ #define CATCH_INTERNAL_DEFINE_EXPRESSION_EQUALITY_OPERATOR( id, op ) \ template \ constexpr auto operator op( ExprLhs&& lhs, RhsT&& rhs ) \ ->std::enable_if_t< \ Detail::conjunction, \ Detail::negation>>>::value, \ BinaryExpr> { \ return { static_cast( lhs.getLhs() op rhs ), \ lhs.getLhs(), \ #op##_sr, \ rhs }; \ } \ template \ constexpr auto operator op( ExprLhs&& lhs, RhsT rhs ) \ ->std::enable_if_t< \ Detail::conjunction, \ capture_by_value>::value, \ BinaryExpr> { \ return { static_cast( lhs.getLhs() op rhs ), \ lhs.getLhs(), \ #op##_sr, \ rhs }; \ } \ template \ constexpr auto operator op( ExprLhs&& lhs, RhsT rhs ) \ ->std::enable_if_t< \ Detail::conjunction< \ Detail::negation>, \ Detail::is_eq_0_comparable, /* We allow long because we \ want `ptr op NULL` to be \ accepted */ \ Detail::disjunction, \ std::is_same>>::value, \ BinaryExpr> { \ if ( rhs != 0 ) { throw_test_failure_exception(); } \ return { static_cast( lhs.getLhs() op 0 ), \ lhs.getLhs(), \ #op##_sr, \ rhs }; \ } \ template \ constexpr auto operator op( ExprLhs&& lhs, RhsT rhs ) \ ->std::enable_if_t< \ Detail::conjunction< \ Detail::negation>, \ Detail::is_eq_0_comparable, /* We allow long because we \ want `ptr op NULL` to be \ accepted */ \ Detail::disjunction, \ std::is_same>>::value, \ BinaryExpr> { \ if ( lhs.getLhs() != 0 ) { throw_test_failure_exception(); } \ return { static_cast( 0 op rhs ), lhs.getLhs(), #op##_sr, rhs }; \ } CATCH_INTERNAL_DEFINE_EXPRESSION_EQUALITY_OPERATOR( eq, == ) CATCH_INTERNAL_DEFINE_EXPRESSION_EQUALITY_OPERATOR( ne, != ) #undef CATCH_INTERNAL_DEFINE_EXPRESSION_EQUALITY_OPERATOR #define CATCH_INTERNAL_DEFINE_EXPRESSION_COMPARISON_OPERATOR( id, op ) \ template \ constexpr auto operator op( ExprLhs&& lhs, RhsT&& rhs ) \ ->std::enable_if_t< \ Detail::conjunction, \ Detail::negation>>>::value, \ BinaryExpr> { \ return { static_cast( lhs.getLhs() op rhs ), \ lhs.getLhs(), \ #op##_sr, \ rhs }; \ } \ template \ constexpr auto operator op( ExprLhs&& lhs, RhsT rhs ) \ ->std::enable_if_t< \ Detail::conjunction, \ capture_by_value>::value, \ BinaryExpr> { \ return { static_cast( lhs.getLhs() op rhs ), \ lhs.getLhs(), \ #op##_sr, \ rhs }; \ } \ template \ constexpr auto operator op( ExprLhs&& lhs, RhsT rhs ) \ ->std::enable_if_t< \ Detail::conjunction< \ Detail::negation>, \ Detail::is_##id##_0_comparable, \ std::is_same>::value, \ BinaryExpr> { \ if ( rhs != 0 ) { throw_test_failure_exception(); } \ return { static_cast( lhs.getLhs() op 0 ), \ lhs.getLhs(), \ #op##_sr, \ rhs }; \ } \ template \ constexpr auto operator op( ExprLhs&& lhs, RhsT rhs ) \ ->std::enable_if_t< \ Detail::conjunction< \ Detail::negation>, \ Detail::is_##id##_0_comparable, \ std::is_same>::value, \ BinaryExpr> { \ if ( lhs.getLhs() != 0 ) { throw_test_failure_exception(); } \ return { static_cast( 0 op rhs ), lhs.getLhs(), #op##_sr, rhs }; \ } CATCH_INTERNAL_DEFINE_EXPRESSION_COMPARISON_OPERATOR( lt, < ) CATCH_INTERNAL_DEFINE_EXPRESSION_COMPARISON_OPERATOR( le, <= ) CATCH_INTERNAL_DEFINE_EXPRESSION_COMPARISON_OPERATOR( gt, > ) CATCH_INTERNAL_DEFINE_EXPRESSION_COMPARISON_OPERATOR( ge, >= ) #undef CATCH_INTERNAL_DEFINE_EXPRESSION_COMPARISON_OPERATOR #define CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR( op ) \ template \ constexpr auto operator op( ExprLhs&& lhs, RhsT&& rhs ) \ ->std::enable_if_t< \ !capture_by_value>::value, \ BinaryExpr> { \ return { static_cast( lhs.getLhs() op rhs ), \ lhs.getLhs(), \ #op##_sr, \ rhs }; \ } \ template \ constexpr auto operator op( ExprLhs&& lhs, RhsT rhs ) \ ->std::enable_if_t::value, \ BinaryExpr> { \ return { static_cast( lhs.getLhs() op rhs ), \ lhs.getLhs(), \ #op##_sr, \ rhs }; \ } CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR( | ) CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR( & ) CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR( ^) #undef CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR template auto operator&&( ExprLhs&&, RhsT&& ) -> BinaryExpr { static_assert( always_false::value, "operator&& is not supported inside assertions, " "wrap the expression inside parentheses, or decompose it" ); } template auto operator||( ExprLhs&&, RhsT&& ) -> BinaryExpr { static_assert( always_false::value, "operator|| is not supported inside assertions, " "wrap the expression inside parentheses, or decompose it" ); } struct Decomposer { template >::value, int> = 0> constexpr friend auto operator <= ( Decomposer &&, T && lhs ) -> ExprLhs { return ExprLhs{ lhs }; } template ::value, int> = 0> constexpr friend auto operator <= ( Decomposer &&, T value ) -> ExprLhs { return ExprLhs{ value }; } }; } // end namespace Catch #ifdef _MSC_VER #pragma warning(pop) #endif #ifdef __clang__ # pragma clang diagnostic pop #elif defined __GNUC__ # pragma GCC diagnostic pop #endif #include namespace Catch { class RunContext; struct AssertionReaction { bool shouldDebugBreak = false; bool shouldThrow = false; bool shouldSkip = false; }; class AssertionHandler { AssertionInfo m_assertionInfo; AssertionReaction m_reaction; bool m_completed = false; // Since all uses are hidden in the .cpp file, we can directly use // the final type and avoid going through virtual dispatch, without // massive compilation time overhead. RunContext& m_resultCapture; void finishIncomplete(); public: AssertionHandler ( StringRef macroName, SourceLineInfo const& lineInfo, StringRef capturedExpression, ResultDisposition::Flags resultDisposition ); ~AssertionHandler() { // We want the common fast path inlinable, and the virtual // dispatch in a function in single TU. if ( !m_completed ) { finishIncomplete(); } } template constexpr void handleExpr( ExprLhs const& expr ) { handleExpr( expr.makeUnaryExpr() ); } void handleExpr( ITransientExpression const& expr ); void handleMessage(ResultWas::OfType resultType, std::string&& message); void handleExceptionThrownAsExpected(); void handleUnexpectedExceptionNotThrown(); void handleExceptionNotThrownAsExpected(); void handleThrowingCallSkipped(); // Marking this as `noexcept` gives us measurable improvement // in optimized compilation times. Making it `noexcept` changes // what happens if the underlying code throws, **but** the only // way this can throw is if the reporter itself throws from // `assertionEnded`. However, in such case the process is going // to abort anyway, because we will enter `assertionEnded` again // from the (noexcept) destructor of `AssertionHandler` above. // In the future, all reporter event handlers will be marked // `noexcept` to make this limitation explicit. void handleUnexpectedInflightException() noexcept; // Ideally we could extend the logic above to more of the handle* // function, but right now it would worsen the behaviour of // preexisting custom reporters that throw from event handlers. void complete(); // query auto allowThrows() const -> bool; }; void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str ); } // namespace Catch namespace Catch { namespace Detail { //! Provides case-insensitive `op<` semantics when called struct CaseInsensitiveLess { bool operator()( StringRef lhs, StringRef rhs ) const; }; //! Provides case-insensitive `op==` semantics when called struct CaseInsensitiveEqualTo { bool operator()( StringRef lhs, StringRef rhs ) const; }; } // namespace Detail } // namespace Catch /** \file * Wrapper for ANDROID_LOGWRITE configuration option * * We want to default to enabling it when compiled for android, but * users of the library should also be able to disable it if they want * to. */ #if defined(__ANDROID__) # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE #endif #if defined( CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE ) && \ !defined( CATCH_CONFIG_NO_ANDROID_LOGWRITE ) && \ !defined( CATCH_CONFIG_ANDROID_LOGWRITE ) # define CATCH_CONFIG_ANDROID_LOGWRITE #endif /** \file * Wrapper for the CATCH_CONFIG_PREFIX_MESSAGES configuration option * * CATCH_CONFIG_PREFIX_ALL can be used to avoid clashes with other macros * by prepending CATCH_. This may not be desirable if the only clashes are with * logger macros such as INFO and WARN. In this cases * CATCH_CONFIG_PREFIX_MESSAGES can be used to only prefix a small subset * of relevant macros. * */ #if defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_PREFIX_MESSAGES) #define CATCH_CONFIG_PREFIX_MESSAGES #endif /** \file * Wrapper for the STATIC_ANALYSIS_SUPPORT configuration option * * Some of Catch2's macros can be defined differently to work better with * static analysis tools, like clang-tidy or coverity. * Currently the main use case is to show that `SECTION`s are executed * exclusively, and not all in one run of a `TEST_CASE`. */ #if defined(__clang_analyzer__) || defined(__COVERITY__) #define CATCH_INTERNAL_CONFIG_STATIC_ANALYSIS_SUPPORT #endif #if defined( CATCH_INTERNAL_CONFIG_STATIC_ANALYSIS_SUPPORT ) && \ !defined( CATCH_CONFIG_NO_EXPERIMENTAL_STATIC_ANALYSIS_SUPPORT ) && \ !defined( CATCH_CONFIG_EXPERIMENTAL_STATIC_ANALYSIS_SUPPORT ) # define CATCH_CONFIG_EXPERIMENTAL_STATIC_ANALYSIS_SUPPORT #endif /** \file * Wrapper for UNCAUGHT_EXCEPTIONS configuration option * * For some functionality, Catch2 requires to know whether there is * an active exception. Because `std::uncaught_exception` is deprecated * in C++17, we want to use `std::uncaught_exceptions` if possible. */ #if defined(_MSC_VER) # if _MSC_VER >= 1900 // Visual Studio 2015 or newer # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS # endif #endif #include #if defined(__cpp_lib_uncaught_exceptions) \ && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS #endif // __cpp_lib_uncaught_exceptions #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \ && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \ && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS #endif #include #include // We want a simple polyfill over `std::empty`, `std::size` and so on // for C++14 or C++ libraries with incomplete support. // We also have to handle that MSVC std lib will happily provide these // under older standards. #if defined(CATCH_CPP17_OR_GREATER) || defined(_MSC_VER) // We are already using this header either way, so there shouldn't // be much additional overhead in including it to get the feature // test macros #include # if !defined(__cpp_lib_nonmember_container_access) # define CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS # endif #else #define CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS #endif namespace Catch { namespace Detail { #if defined(CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS) template constexpr auto empty(Container const& cont) -> decltype(cont.empty()) { return cont.empty(); } template constexpr bool empty(const T (&)[N]) noexcept { // GCC < 7 does not support the const T(&)[] parameter syntax // so we have to ignore the length explicitly (void)N; return false; } template constexpr bool empty(std::initializer_list list) noexcept { return list.size() > 0; } template constexpr auto size(Container const& cont) -> decltype(cont.size()) { return cont.size(); } template constexpr std::size_t size(const T(&)[N]) noexcept { return N; } #endif // CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS } // end namespace Detail } // end namespace Catch namespace Catch { bool isDebuggerActive(); } #if !defined( CATCH_TRAP ) && defined( __clang__ ) && defined( __has_builtin ) # if __has_builtin( __builtin_debugtrap ) # define CATCH_TRAP() __builtin_debugtrap() # endif #endif #if !defined( CATCH_TRAP ) && defined( _MSC_VER ) # define CATCH_TRAP() __debugbreak() #endif #if !defined(CATCH_TRAP) // If we couldn't use compiler-specific impl from above, we get into platform-specific options #ifdef CATCH_PLATFORM_MAC #if defined(__i386__) || defined(__x86_64__) #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */ #elif defined(__aarch64__) #define CATCH_TRAP() __asm__(".inst 0xd43e0000") #elif defined(__POWERPC__) #define CATCH_TRAP() __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \ : : : "memory","r0","r3","r4" ) /* NOLINT */ #endif #elif defined(CATCH_PLATFORM_IPHONE) // use inline assembler #if defined(__i386__) || defined(__x86_64__) #define CATCH_TRAP() __asm__("int $3") #elif defined(__aarch64__) #define CATCH_TRAP() __asm__(".inst 0xd4200000") #elif defined(__arm__) && !defined(__thumb__) #define CATCH_TRAP() __asm__(".inst 0xe7f001f0") #elif defined(__arm__) && defined(__thumb__) #define CATCH_TRAP() __asm__(".inst 0xde01") #endif #elif defined(CATCH_PLATFORM_LINUX) || defined(CATCH_PLATFORM_QNX) // If we can use inline assembler, do it because this allows us to break // directly at the location of the failing check instead of breaking inside // raise() called from it, i.e. one stack frame below. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */ #else // Fall back to the generic way. #include #define CATCH_TRAP() raise(SIGTRAP) #endif #elif defined(__MINGW32__) extern "C" __declspec(dllimport) void __stdcall DebugBreak(); #define CATCH_TRAP() DebugBreak() #endif #endif // ^^ CATCH_TRAP is not defined yet, so we define it #if !defined(CATCH_BREAK_INTO_DEBUGGER) #if defined(CATCH_TRAP) #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }() #else #define CATCH_BREAK_INTO_DEBUGGER() []{}() #endif #endif #include // for `std::exception` in no-exception configuration namespace Catch { #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) template [[noreturn]] void throw_exception(Ex const& e) { throw e; } #else // ^^ Exceptions are enabled // Exceptions are disabled vv [[noreturn]] void throw_exception(std::exception const& e); #endif [[noreturn]] void throw_logic_error(std::string const& msg); [[noreturn]] void throw_domain_error(std::string const& msg); [[noreturn]] void throw_runtime_error(std::string const& msg); } // namespace Catch; #define CATCH_MAKE_MSG(...) \ (Catch::ReusableStringStream() << __VA_ARGS__).str() #define CATCH_INTERNAL_ERROR(...) \ Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__)) #define CATCH_ERROR(...) \ Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ )) #define CATCH_RUNTIME_ERROR(...) \ Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ )) #define CATCH_ENFORCE( condition, ... ) \ do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false) namespace Catch { //! Simple RAII class that stores the value of `errno` //! at construction and restores it at destruction. class ErrnoGuard { public: // Keep these outlined to avoid dragging in macros from ErrnoGuard(); ~ErrnoGuard(); private: int m_oldErrno; }; } #include namespace Catch { class ExceptionTranslatorRegistry final : public IExceptionTranslatorRegistry { public: ~ExceptionTranslatorRegistry() override; void registerTranslator( Detail::unique_ptr&& translator ); std::string translateActiveException() const override; private: ExceptionTranslators m_translators; }; } #include namespace Catch { /** * Wrapper for platform-specific fatal error (signals/SEH) handlers * * Tries to be cooperative with other handlers, and not step over * other handlers. This means that unknown structured exceptions * are passed on, previous signal handlers are called, and so on. * * Can only be instantiated once, and assumes that once a signal * is caught, the binary will end up terminating. Thus, there */ class FatalConditionHandler { bool m_started = false; // Install/disengage implementation for specific platform. // Should be if-defed to work on current platform, can assume // engage-disengage 1:1 pairing. void engage_platform(); void disengage_platform() noexcept; public: // Should also have platform-specific implementations as needed FatalConditionHandler(); ~FatalConditionHandler(); void engage() { assert(!m_started && "Handler cannot be installed twice."); m_started = true; engage_platform(); } void disengage() noexcept { assert(m_started && "Handler cannot be uninstalled without being installed first"); m_started = false; disengage_platform(); } }; //! Simple RAII guard for (dis)engaging the FatalConditionHandler class FatalConditionHandlerGuard { FatalConditionHandler* m_handler; public: FatalConditionHandlerGuard(FatalConditionHandler* handler): m_handler(handler) { m_handler->engage(); } ~FatalConditionHandlerGuard() { m_handler->disengage(); } }; } // end namespace Catch #include #include #include #include #include namespace Catch { namespace Detail { uint32_t convertToBits(float f); uint64_t convertToBits(double d); // Used when we know we want == comparison of two doubles // to centralize warning suppression bool directCompare( float lhs, float rhs ); bool directCompare( double lhs, double rhs ); } // end namespace Detail #if defined( __GNUC__ ) || defined( __clang__ ) # pragma GCC diagnostic push // We do a bunch of direct compensations of floating point numbers, // because we know what we are doing and actually do want the direct // comparison behaviour. # pragma GCC diagnostic ignored "-Wfloat-equal" #endif /** * Calculates the ULP distance between two floating point numbers * * The ULP distance of two floating point numbers is the count of * valid floating point numbers representable between them. * * There are some exceptions between how this function counts the * distance, and the interpretation of the standard as implemented. * by e.g. `nextafter`. For this function it always holds that: * * `(x == y) => ulpDistance(x, y) == 0` (so `ulpDistance(-0, 0) == 0`) * * `ulpDistance(maxFinite, INF) == 1` * * `ulpDistance(x, -x) == 2 * ulpDistance(x, 0)` * * \pre `!isnan( lhs )` * \pre `!isnan( rhs )` * \pre floating point numbers are represented in IEEE-754 format */ template uint64_t ulpDistance( FP lhs, FP rhs ) { assert( std::numeric_limits::is_iec559 && "ulpDistance assumes IEEE-754 format for floating point types" ); assert( !Catch::isnan( lhs ) && "Distance between NaN and number is not meaningful" ); assert( !Catch::isnan( rhs ) && "Distance between NaN and number is not meaningful" ); // We want X == Y to imply 0 ULP distance even if X and Y aren't // bit-equal (-0 and 0), or X - Y != 0 (same sign infinities). if ( lhs == rhs ) { return 0; } // We need a properly typed positive zero for type inference. static constexpr FP positive_zero{}; // We want to ensure that +/- 0 is always represented as positive zero if ( lhs == positive_zero ) { lhs = positive_zero; } if ( rhs == positive_zero ) { rhs = positive_zero; } // If arguments have different signs, we can handle them by summing // how far are they from 0 each. if ( std::signbit( lhs ) != std::signbit( rhs ) ) { return ulpDistance( std::abs( lhs ), positive_zero ) + ulpDistance( std::abs( rhs ), positive_zero ); } // When both lhs and rhs are of the same sign, we can just // read the numbers bitwise as integers, and then subtract them // (assuming IEEE). uint64_t lc = Detail::convertToBits( lhs ); uint64_t rc = Detail::convertToBits( rhs ); // The ulp distance between two numbers is symmetric, so to avoid // dealing with overflows we want the bigger converted number on the lhs if ( lc < rc ) { std::swap( lc, rc ); } return lc - rc; } #if defined( __GNUC__ ) || defined( __clang__ ) # pragma GCC diagnostic pop #endif } // end namespace Catch namespace Catch { namespace Detail { //! Wrapper over `std::getenv` that compiles on UWP (and always returns nullptr there) char const* getEnv(char const* varName); } } #include #include namespace Catch { namespace Detail { template constexpr ForwardIter find_sentinel( ForwardIter start, Sentinel sentinel, T const& value, Comparator cmp ) { while ( start != sentinel ) { if ( cmp( *start, value ) ) { break; } ++start; } return start; } template constexpr std::ptrdiff_t count_sentinel( ForwardIter start, Sentinel sentinel, T const& value, Comparator cmp ) { std::ptrdiff_t count = 0; while ( start != sentinel ) { if ( cmp( *start, value ) ) { ++count; } ++start; } return count; } template constexpr std::enable_if_t::value, std::ptrdiff_t> sentinel_distance( ForwardIter iter, const Sentinel sentinel ) { std::ptrdiff_t dist = 0; while ( iter != sentinel ) { ++iter; ++dist; } return dist; } template constexpr std::ptrdiff_t sentinel_distance( ForwardIter first, ForwardIter last ) { return std::distance( first, last ); } template constexpr bool check_element_counts( ForwardIter1 first_1, const Sentinel1 end_1, ForwardIter2 first_2, const Sentinel2 end_2, Comparator cmp ) { auto cursor = first_1; while ( cursor != end_1 ) { if ( find_sentinel( first_1, cursor, *cursor, cmp ) == cursor ) { // we haven't checked this element yet const auto count_in_range_2 = count_sentinel( first_2, end_2, *cursor, cmp ); // Not a single instance in 2nd range, so it cannot be a // permutation of 1st range if ( count_in_range_2 == 0 ) { return false; } const auto count_in_range_1 = count_sentinel( cursor, end_1, *cursor, cmp ); if ( count_in_range_1 != count_in_range_2 ) { return false; } } ++cursor; } return true; } template constexpr bool is_permutation( ForwardIter1 first_1, const Sentinel1 end_1, ForwardIter2 first_2, const Sentinel2 end_2, Comparator cmp ) { // TODO: no optimization for stronger iterators, because we would also have to constrain on sentinel vs not sentinel types // TODO: Comparator has to be "both sides", e.g. a == b => b == a // This skips shared prefix of the two ranges while (first_1 != end_1 && first_2 != end_2 && cmp(*first_1, *first_2)) { ++first_1; ++first_2; } // We need to handle case where at least one of the ranges has no more elements if (first_1 == end_1 || first_2 == end_2) { return first_1 == end_1 && first_2 == end_2; } // pair counting is n**2, so we pay linear walk to compare the sizes first auto dist_1 = sentinel_distance( first_1, end_1 ); auto dist_2 = sentinel_distance( first_2, end_2 ); if (dist_1 != dist_2) { return false; } // Since we do not try to handle stronger iterators pair (e.g. // bidir) optimally, the only thing left to do is to check counts in // the remaining ranges. return check_element_counts( first_1, end_1, first_2, end_2, cmp ); } } // namespace Detail } // namespace Catch namespace Catch { struct LeakDetector { LeakDetector(); ~LeakDetector(); }; } #include #include namespace Catch { class OutputRedirect { bool m_redirectActive = false; virtual void activateImpl() = 0; virtual void deactivateImpl() = 0; public: enum Kind { //! No redirect (noop implementation) None, //! Redirect std::cout/std::cerr/std::clog streams internally Streams, //! Redirect the stdout/stderr file descriptors into files FileDescriptors, }; virtual ~OutputRedirect(); // = default; // TODO: Do we want to check that redirect is not active before retrieving the output? virtual std::string getStdout() = 0; virtual std::string getStderr() = 0; virtual void clearBuffers() = 0; bool isActive() const { return m_redirectActive; } void activate() { assert( !m_redirectActive && "redirect is already active" ); activateImpl(); m_redirectActive = true; } void deactivate() { assert( m_redirectActive && "redirect is not active" ); deactivateImpl(); m_redirectActive = false; } }; bool isRedirectAvailable( OutputRedirect::Kind kind); Detail::unique_ptr makeOutputRedirect( bool actual ); class RedirectGuard { OutputRedirect* m_redirect; bool m_activate; bool m_previouslyActive; bool m_moved = false; public: RedirectGuard( bool activate, OutputRedirect& redirectImpl ); ~RedirectGuard() noexcept( false ); RedirectGuard( RedirectGuard const& ) = delete; RedirectGuard& operator=( RedirectGuard const& ) = delete; // C++14 needs move-able guards to return them from functions RedirectGuard( RedirectGuard&& rhs ) noexcept; RedirectGuard& operator=( RedirectGuard&& rhs ) noexcept; }; RedirectGuard scopedActivate( OutputRedirect& redirectImpl ); RedirectGuard scopedDeactivate( OutputRedirect& redirectImpl ); } // end namespace Catch #include namespace Catch { /** * Parses unsigned int from the input, using provided base * * Effectively a wrapper around std::stoul but with better error checking * e.g. "-1" is rejected, instead of being parsed as UINT_MAX. */ Optional parseUInt(std::string const& input, int base = 10); } #define INTERNAL_CATCH_EXPAND1( param ) INTERNAL_CATCH_EXPAND2( param ) #define INTERNAL_CATCH_EXPAND2( ... ) INTERNAL_CATCH_NO##__VA_ARGS__ #define INTERNAL_CATCH_DEF( ... ) INTERNAL_CATCH_DEF __VA_ARGS__ #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF #define INTERNAL_CATCH_REMOVE_PARENS( ... ) \ INTERNAL_CATCH_EXPAND1( INTERNAL_CATCH_DEF __VA_ARGS__ ) #if defined(__GNUC__) // We need to silence "empty __VA_ARGS__ warning", and using just _Pragma does not work #pragma GCC system_header #endif namespace Catch { namespace Detail { template struct priority_tag : priority_tag {}; template <> struct priority_tag<0> {}; // This is a bunch of helpers for the templated test case handling. // They should live elsewhere in the long run, but as an in-between // step we toss them all here. template struct TypeList {}; template constexpr auto get_wrapper( priority_tag<1> ) noexcept -> TypeList { return {}; } template